mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-29 09:46:29 +01:00
Merge main into fix/kurbo-linear-cubic-zero-tangent
This commit is contained in:
commit
0fd83009e3
188 files changed
+30767
-1706
No files matched your search
Generated
+35
@@ -1823,6 +1823,7 @@ dependencies = [
|
||||
"craft-gpu-null",
|
||||
"craft-gpu-providers",
|
||||
"craft-gpu-wgpu",
|
||||
"craft-gpu-yuv",
|
||||
"craft-gridcraft-format",
|
||||
"craft-gzip",
|
||||
"craft-har",
|
||||
@@ -2960,6 +2961,17 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gpu-yuv"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-gpu",
|
||||
"craft-gpu-null",
|
||||
"pollster 0.4.0",
|
||||
"wgpu",
|
||||
"yuv",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gridcraft-format"
|
||||
version = "0.1.0"
|
||||
@@ -3595,6 +3607,9 @@ version = "0.1.0"
|
||||
name = "craft-pbr"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-materialx",
|
||||
"craft-mesh",
|
||||
"craft-pbr",
|
||||
"craft-texture",
|
||||
"glam 0.30.10",
|
||||
"naga",
|
||||
@@ -4319,8 +4334,11 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rustix 1.1.6",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"skrifa 0.47.0",
|
||||
"tempfile",
|
||||
"toml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4354,8 +4372,12 @@ name = "craft-texture"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"craft-exr",
|
||||
"craft-hdr",
|
||||
"craft-image-codecs",
|
||||
"dds",
|
||||
"half",
|
||||
"png 0.18.1",
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -4957,10 +4979,14 @@ name = "craft-xtask"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"flate2",
|
||||
"libc",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"toml_edit",
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -15061,6 +15087,15 @@ dependencies = [
|
||||
"synstructure 0.14.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yuv"
|
||||
version = "0.8.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d109d1eacc7b034329873d2d848039b365c65ab7d751b19ee84e4921c62c607"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zbus"
|
||||
version = "5.19.0"
|
||||
|
||||
@@ -39,6 +39,7 @@ log = "0.4"
|
||||
craft-plist = { path = "crates/plist" }
|
||||
craft-gpu-device = { path = "crates/gpu-device" }
|
||||
craft-wasm = { path = "crates/wasm" }
|
||||
craft-gpu-yuv = { path = "crates/gpu-yuv" }
|
||||
craft-platform = { path = "crates/platform" }
|
||||
craft-png = { path = "crates/png" }
|
||||
craft-aep = { path = "crates/aep" }
|
||||
|
||||
@@ -288,11 +288,10 @@ applications retain their own document-font selection and licensing policy.
|
||||
linesweeper
|
||||
|
||||
linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in
|
||||
vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_line.rs,
|
||||
src/segments.rs, src/curve/transverse.rs, src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its
|
||||
manifest names Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
|
||||
vendor/linesweeper with its upstream license files and local changes. Its manifest names Joe Neeman
|
||||
as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
|
||||
vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local
|
||||
patches and the files left out.
|
||||
changes and the files left out.
|
||||
|
||||
kurbo
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
|
||||
- [`craft-automation`](crates/automation/README.md): drive a running app from tests, agents and the CLI: control channel, screenshot queue, frame profiler and trace (native only); recorded actions, their playback and the Actions panel (every target).
|
||||
- [`craft-atomic`](crates/atomic/README.md): Crash-safe atomic file writing and replacement with same-directory staging, directory fsync, Apple `F_FULLFSYNC` fallback, transient lock backoff, and fault injection for the Craft suite.
|
||||
- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), an optional slot lock held across processes and an optional per-step JSON report. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft.
|
||||
- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), the asset attribution check, an optional slot lock held across processes, an optional per-step JSON report, and PNG images packed into `.ico` and `.icns` files. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft; icon packing for DeckCraft, CADCraft, craft-launcher and MaterialCraft.
|
||||
- [`craft-captions`](crates/captions/README.md): caption and subtitle files behind one neutral
|
||||
model (cues with exact tick times): SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and
|
||||
TTML / IMSC1 / DFXP readers and writers, and CEA-608 / CEA-708 byte-pair coding. Carved from
|
||||
@@ -211,6 +211,12 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
every frame's position, delay, disposal and transparent colour, the loop count and the first
|
||||
frame's colour table, without decompressing pixels. Tells an animation from a still and whether
|
||||
a file can hold the picture it declares before a decoder runs.
|
||||
- [`craft-gpu-yuv`](crates/gpu-yuv/README.md): the `craft.yuv` GPU provider. It converts RGBA to
|
||||
NV12, P010 and I420, scaled to the output size, in BT.601, BT.709 and BT.2020 at limited or full
|
||||
range, through the `craft-gpu` job registry on the null context or on a device. Each output texel
|
||||
averages the part of the source it covers. The crate also has the render passes for a caller's
|
||||
own encoder, read-back layouts with unpacking to a packed frame, and the same conversion on the
|
||||
CPU. Encoders and scopes stay in each app.
|
||||
- [`craft-gpu-device`](crates/gpu-device/README.md): choosing and opening a wgpu device: Auto,
|
||||
low power, a named adapter that survives a reordered list and a driver update, or software;
|
||||
corrections for drivers that crash; the next adapter and then a software one when a device fails
|
||||
@@ -417,15 +423,17 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
reference picking, selection statistics, error tags and filter buttons (`ui` feature).
|
||||
- [`craft-testkit`](crates/testkit/README.md): test support for the apps' own tests. Its `guards` module
|
||||
reports source patterns that broke platforms before: muda's predefined Quit item, WGSL float literals
|
||||
out of range, and `std::time::Instant` in code the web build runs. Its `deadline` module fails a test
|
||||
whose body runs past a limit, or whose condition does not hold in time; a variable the caller names
|
||||
replaces each limit. Its `hostile` module runs a parser on every truncation and on seeded damaged
|
||||
copies of a valid input, and fails the test with the case that panicked or did not finish. Its `rng`
|
||||
module holds two seeded generators for repeatable test input. Its `skip` module prints a `SKIPPED:`
|
||||
line when a test lacks a program, a corpus or the craft-fonts faces, or fails the test when the
|
||||
variable the caller names is `1`. Any other value of that variable except empty fails the test as a
|
||||
configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder against a
|
||||
pinned SHA-256 list. Not published.
|
||||
out of range, and `std::time::Instant` in code the web build runs. Its `fonts` module makes test fonts
|
||||
from font bytes the caller supplies: a face with a renamed family and a TrueType collection. Its
|
||||
`deadline` module fails a test whose body runs past a limit, or whose condition does not hold in time;
|
||||
a variable the caller names replaces each limit. Its `hostile` module runs a parser on every truncation
|
||||
and on seeded damaged copies of a valid input, and fails the test with the case that panicked or did
|
||||
not finish. Its `rng` module holds two seeded generators for repeatable test input. Its `skip` module
|
||||
prints a `SKIPPED:` line when a test lacks a program, a corpus or the craft-fonts faces, or fails the
|
||||
test when the variable the caller names is `1`. Any other value of that variable except empty fails
|
||||
the test as a configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder
|
||||
against a pinned SHA-256 list. Its `fixtures` module (native targets only) generates test fixtures
|
||||
under `target/fixtures` and publishes each one under a lock. Not published.
|
||||
- [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds
|
||||
hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns
|
||||
for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and
|
||||
@@ -433,8 +441,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
(ruler, Tabs, Paragraph, Columns and Hyperlink dialogs, notes editor, find); `spell` and `find`
|
||||
(regex) are features.
|
||||
- [`craft-texture`](crates/texture/README.md): linear float image planes, gray or RGBA, with
|
||||
nearest and bilinear sampling that repeats or clamps, resizing and display conversion. Sizes are
|
||||
bounded by `Limits`. From MaterialCraft.
|
||||
nearest and bilinear sampling that repeats or clamps, resizing and display conversion, and
|
||||
(optional features) PNG, TIFF, Radiance HDR and OpenEXR decoding that keeps 16-bit and float
|
||||
samples. Sizes are bounded by `Limits`. From MaterialCraft.
|
||||
- [`craft-timeline`](crates/timeline/README.md): timelines: exact media time, frame rates,
|
||||
timecode, the playback clock, a frame cache and frame server, and editorial interchange (ALE,
|
||||
CMX 3600 EDL, Final Cut Pro 7 XML, FCPXML, OpenTimelineIO), all egui-free; the timeline panel,
|
||||
|
||||
@@ -19,7 +19,12 @@ and contains no `unsafe` code.
|
||||
them in samples). The pitch shifter's Keep Formants switch adds the formant shifter's latency,
|
||||
and `latency()` reports it while the switch is on. A ring modulator for robotic and metallic
|
||||
voices (ring, frequency modulation, and positive or negative comb resonators, with the
|
||||
frequency moved by an LFO, the input's level or a sample-and-hold source) adds no latency.
|
||||
frequency moved by an LFO, the input's level or a sample-and-hold source) adds no latency, and
|
||||
neither does a bitcrusher that takes one sample in every 1 to 50 and rounds it to 1 to 16 bits,
|
||||
or a tremolo that lowers the gain once per cycle of a sine, triangle or square LFO. A vibrato
|
||||
that swings the pitch by up to 100 cents through a delay moved by a sine or triangle LFO adds
|
||||
no latency either: the delay is 0 at the start of each cycle, except while it glides to new
|
||||
settings.
|
||||
- `loudness`: an ITU-R BS.1770-4 / EBU R128 meter with momentary, short-term and integrated
|
||||
loudness, loudness range (EBU Tech 3342), sample peak and true peak.
|
||||
- `pan`: stereo pan laws, a surround panner over any layout of up to 16 speakers, and first-order
|
||||
|
||||
@@ -22,7 +22,7 @@ pub(crate) mod util;
|
||||
pub(crate) mod voice;
|
||||
|
||||
pub(crate) use channel::{Amplify, Balance, ChannelVolume, Invert, Route, Routing};
|
||||
pub use character::RingMod;
|
||||
pub use character::{Bitcrusher, RingMod, Tremolo, Vibrato};
|
||||
pub(crate) use declick::ClickRemover;
|
||||
pub use dither::Dither;
|
||||
pub use dynamics::{Compressor, Gate, Limiter, Maximizer};
|
||||
@@ -151,6 +151,8 @@ static REGISTRY: &[EffectInfo] = &[
|
||||
entry!("flanger", "Flanger", Modulation, Flanger),
|
||||
entry!("phaser", "Phaser", Modulation, Phaser),
|
||||
entry!("ring_mod", "Ring Modulator", Modulation, RingMod),
|
||||
entry!("tremolo", "Tremolo", Modulation, Tremolo),
|
||||
entry!("vibrato", "Vibrato", Modulation, Vibrato),
|
||||
entry!("analog_delay", "Analog Delay", Time, AnalogDelay),
|
||||
entry!("multitap_delay", "Multitap Delay", Time, MultitapDelay),
|
||||
entry!("convolution_reverb", "Convolution Reverb", Reverb, ConvolutionReverb),
|
||||
@@ -158,6 +160,7 @@ static REGISTRY: &[EffectInfo] = &[
|
||||
entry!("click_remover", "Automatic Click Remover", Restoration, ClickRemover),
|
||||
entry!("channel_mixer", "Channel Mixer", Channel, ChannelMixer),
|
||||
entry!("distortion", "Distortion", Special, Distortion),
|
||||
entry!("bitcrusher", "Bitcrusher", Special, Bitcrusher),
|
||||
entry!("guitar_suite", "GuitarSuite", Special, GuitarSuite),
|
||||
entry!("mastering", "Mastering", Special, Mastering),
|
||||
entry!("vocal_enhancer", "Vocal Enhancer", Special, VocalEnhancer),
|
||||
|
||||
@@ -991,6 +991,9 @@ fn direct_constructors_cap_the_channel_count() {
|
||||
voice::VoiceFormant,
|
||||
suppress::NoiseSuppression,
|
||||
character::RingMod,
|
||||
character::Bitcrusher,
|
||||
character::Tremolo,
|
||||
character::Vibrato,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -790,6 +790,44 @@ mod tests {
|
||||
assert!(fell < -20.0, "after a search window of quiet the estimate fell by only {:.1} dB", -fell);
|
||||
}
|
||||
|
||||
/// A mute of one hop, which leaves no frame of digital silence, ends the quiet run where it
|
||||
/// falls in the stream: the quiet frames waiting before it still count, and only the frames
|
||||
/// after the mute that may enter the estimate start the next run.
|
||||
#[test]
|
||||
fn a_short_mute_ends_the_quiet_run_in_queue_order() {
|
||||
let s = suppressor(24.0);
|
||||
let (n, hop, coefs) = (s.n, s.hop, s.coefs);
|
||||
let half = n / 2 + 1;
|
||||
let mut bins = Bins::new(half);
|
||||
let mut gains = vec![1.0f32; half];
|
||||
let im = vec![0.0f32; half];
|
||||
let (loud, quiet) = (vec![1.0f32; half], vec![0.001f32; half]);
|
||||
let mut step = |bins: &mut Bins, sample: f32, spectrum: &[f32]| {
|
||||
for _ in 0..hop {
|
||||
bins.sample(sample, hop);
|
||||
}
|
||||
bins.frame(spectrum, &im, &coefs, &mut gains);
|
||||
};
|
||||
for _ in 0..40 {
|
||||
step(&mut bins, 0.1, &loud);
|
||||
}
|
||||
for _ in 0..OVERLAP + 3 {
|
||||
step(&mut bins, 0.001, &quiet);
|
||||
}
|
||||
assert!(bins.quiet_run > 0, "the quiet frames before the mute did not count");
|
||||
step(&mut bins, 0.0, &quiet);
|
||||
let mut eligible = 0;
|
||||
for _ in 0..2 * n / hop {
|
||||
step(&mut bins, 0.001, &quiet);
|
||||
let newest = (bins.head + bins.queued - 1) % OVERLAP;
|
||||
eligible += usize::from(bins.queue_ok[newest]);
|
||||
}
|
||||
let waiting = (0..bins.queued).filter(|j| bins.queue_ok[(bins.head + j) % OVERLAP]).count();
|
||||
assert_eq!(waiting, bins.queued, "a frame waiting after the mute may not enter the estimate");
|
||||
assert!(eligible + 3 < coefs.window, "the test needs the run below its cap");
|
||||
assert_eq!(bins.quiet_run, eligible - waiting, "frames from before the mute counted in the new run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_mute_ends_the_queued_quiet_run() {
|
||||
for offset in [0, 17] {
|
||||
|
||||
@@ -459,8 +459,9 @@ impl AudioEffect for VoicePitch {
|
||||
let mut sum = 0.0f32;
|
||||
for (c, line) in self.lines.iter_mut().enumerate() {
|
||||
// A non-finite sample is stored as silence, so it never reaches the output. A
|
||||
// channel the block leaves out is stored as silence too, so its line holds none
|
||||
// of its earlier audio when it comes back.
|
||||
// channel the block leaves out is stored as silence too while its line advances,
|
||||
// so after a gap of at least `latency() + tail_samples()` samples it holds none of
|
||||
// its earlier audio; after a shorter gap, audio still in the line can sound.
|
||||
let x = channels.get(c).map_or(0.0, |io| flush32(io[i]));
|
||||
line[self.pos] = x;
|
||||
sum += x;
|
||||
@@ -759,8 +760,9 @@ impl AudioEffect for VoiceFormant {
|
||||
for i in 0..len {
|
||||
for c in 0..self.stage.stft.len() {
|
||||
// A non-finite sample is taken as silence, so it never reaches the output. A
|
||||
// channel the block leaves out is fed silence, so it holds none of its earlier
|
||||
// audio when it comes back.
|
||||
// channel the block leaves out is fed silence while its state advances, so after
|
||||
// a gap of at least `latency() + tail_samples()` samples it holds none of its
|
||||
// earlier audio; after a shorter gap, audio still pending can sound.
|
||||
match channels.get_mut(c) {
|
||||
Some(io) => io[i] = self.stage.tick(c, flush32(io[i]), self.ratio),
|
||||
None => {
|
||||
@@ -1197,8 +1199,9 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A block that leaves channels out feeds them silence, so when they come back without a
|
||||
/// reset none of their earlier audio sounds. Checked for the formant shifter and for the
|
||||
/// pitch shifter with and without Keep Formants.
|
||||
/// reset, after a gap at least as long as the latency and the tail, none of their earlier
|
||||
/// audio sounds. Checked for the formant shifter and for the pitch shifter with and without
|
||||
/// Keep Formants.
|
||||
#[test]
|
||||
fn channels_left_out_of_a_block_come_back_silent() {
|
||||
let mut rng = Rng::new(19);
|
||||
@@ -1213,6 +1216,7 @@ mod tests {
|
||||
keep.reset();
|
||||
let fxs: [&mut dyn AudioEffect; 3] = [&mut f, &mut plain, &mut keep];
|
||||
for fx in fxs {
|
||||
assert!(fx.latency() + fx.tail_samples() <= noise.len(), "{}: the gap is shorter than the latency and the tail", fx.id());
|
||||
let (mut a, mut b, mut c) = (noise.clone(), noise.clone(), noise.clone());
|
||||
fx.process(&mut [&mut a, &mut b, &mut c]);
|
||||
let mut a = noise.clone();
|
||||
@@ -1246,6 +1250,33 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A block that leaves a channel out gives the same output, once the channel is back, as a
|
||||
/// block that holds silence for it: with Keep Formants on, an impulse just before the block
|
||||
/// still sounds afterward.
|
||||
#[test]
|
||||
fn a_channel_left_out_of_a_block_runs_as_silence() {
|
||||
let mut out = Vec::new();
|
||||
for omit in [false, true] {
|
||||
let mut p = VoicePitch::new(SR, 2);
|
||||
assert!(p.set_param("formant_follow", 1.0));
|
||||
p.reset();
|
||||
let (mut l, mut r) = (vec![0.0f32; 480], vec![0.0f32; 480]);
|
||||
r[479] = 1.0;
|
||||
p.process(&mut [&mut l, &mut r]);
|
||||
let (mut l, mut r) = (vec![0.0f32; 480], vec![0.0f32; 480]);
|
||||
if omit {
|
||||
p.process(&mut [&mut l]);
|
||||
} else {
|
||||
p.process(&mut [&mut l, &mut r]);
|
||||
}
|
||||
let (mut l, mut r) = (vec![0.0f32; 4_000], vec![0.0f32; 4_000]);
|
||||
p.process(&mut [&mut l, &mut r]);
|
||||
assert!(r.iter().any(|v| *v != 0.0), "omit {omit}: the impulse did not sound");
|
||||
out.push((l, r));
|
||||
}
|
||||
assert!(out[0] == out[1], "leaving the channel out changed the output");
|
||||
}
|
||||
|
||||
/// Leaving a silent third channel out of a block does not change the pitch the tracker finds,
|
||||
/// so a shifted voice comes out the same on the channels that remain.
|
||||
#[test]
|
||||
|
||||
@@ -208,6 +208,8 @@ pub trait AudioEffect: Send {
|
||||
/// the end of its input. An effect whose output decays without reaching zero (a feedback
|
||||
/// delay, a resonator) reports where the decay falls below a cutoff, 60 dB under its start
|
||||
/// for the feedback delays and resonators, so quieter output can still follow that point.
|
||||
/// Those effects also cap the tail they report at 60 s, which is what a feedback of 1 or more
|
||||
/// reports.
|
||||
fn tail_samples(&self) -> usize {
|
||||
0
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou
|
||||
| `symphonia` | the fallback for formats with no native decoder; turning it on is the same as `decode` | `decode-native`, symphonia |
|
||||
| `encode` | every encoder, and every format of `encode` and `FileEncoder` | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-encode`, `vorbis-encode` |
|
||||
| `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` |
|
||||
| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`, `wav_float_header_with_bwf`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none |
|
||||
| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`, `wav_float_header_with_bwf`; `repair_wav` (size fields of a WAV left unfinished by a crash); `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none |
|
||||
| `flac-decode` | `flac::decode` (whole `.flac` files) and `flac::Decoder` (single frames, for callers that demux FLAC themselves); native, CRC-checked, 4 to 32 bits. `decode` still uses symphonia for FLAC files | none |
|
||||
| `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` |
|
||||
| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A and `PacketEncoder` for AAC | craft-media `bitstream`; `aac-encode` also `isobmff` |
|
||||
|
||||
@@ -19,9 +19,9 @@
|
||||
//! - [`TrackDecoder`] (any decoder feature): one track's packets from any demuxer to planar
|
||||
//! `f32` in WAV channel order.
|
||||
//! - [`encode`], [`FileEncoder`]: WAV/BWF/RF64 and AIFF/AIFF-C (feature `pcm-encode`, which also
|
||||
//! gives [`wav_float_header`] and [`wav_float_header_with_bwf`]), FLAC (feature `flac-encode`),
|
||||
//! AAC-LC and ALAC in M4A (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 streams
|
||||
//! (`mp3-encode`, `ac3-encode`, `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature
|
||||
//! gives [`wav_float_header`], [`wav_float_header_with_bwf`] and [`repair_wav`]), FLAC (feature
|
||||
//! `flac-encode`), AAC-LC and ALAC in M4A (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3
|
||||
//! streams (`mp3-encode`, `ac3-encode`, `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature
|
||||
//! `lossless-encode` turns on WAV, AIFF and FLAC; feature `encode` turns on every format and encoder.
|
||||
//! - [`PacketEncoder`] (any of `aac-encode`, `alac-encode`, `mp3-encode`, `ac3-encode`,
|
||||
//! `eac3-encode`, `opus-encode`): planar `f32` in WAV channel order to packets of AAC-LC, ALAC,
|
||||
@@ -221,9 +221,9 @@ pub use write::FileEncoder;
|
||||
))]
|
||||
pub use write::{ENCODE_EXTENSIONS, encode, encode_format_for};
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header};
|
||||
pub use write::{WavRepair, repair_wav, wav_float_header, wav_float_header_with_bwf};
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
pub use write::{wav_float_header, wav_float_header_with_bwf};
|
||||
pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header};
|
||||
|
||||
/// Errors from probing, decoding and encoding.
|
||||
#[non_exhaustive]
|
||||
|
||||
@@ -3,12 +3,9 @@
|
||||
|
||||
use super::source::Src;
|
||||
use crate::pcm::{PcmKind, le_u16, le_u32, le_u64, tag};
|
||||
use crate::wav::{GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM};
|
||||
use crate::wav::{AMBISONIC_TAIL, GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM};
|
||||
use crate::{AudioError, AudioInfo, BwfInfo, ChannelLayout, CodecId, Container, Result, SampleFormat};
|
||||
|
||||
/// Tail of the Ambisonic subtype GUIDs {0000000x-0721-11D3-8644-C8C1CA000000}: PCM (x = 1) and float (x = 3) as well.
|
||||
const AMBISONIC_TAIL: [u8; 14] = [0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00];
|
||||
|
||||
/// Parsed WAV layout (no sample data decoded yet).
|
||||
pub(crate) struct WavLayout {
|
||||
pub info: AudioInfo,
|
||||
@@ -359,7 +356,8 @@ pub(crate) fn parse(src: &Src<'_>) -> Result<WavParse> {
|
||||
ixml_time = ixml_time_reference(&small(IXML_MAX as u64));
|
||||
}
|
||||
}
|
||||
b"ds64" => ds64_data = le_u64(&small(64), 8),
|
||||
// The sizes come from the first `ds64` chunk that holds them.
|
||||
b"ds64" if ds64_data.is_none() => ds64_data = le_u64(&small(64), 8),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,3 +5,5 @@ pub(crate) const WAVE_FORMAT_IEEE_FLOAT: u16 = 3;
|
||||
pub(crate) const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE;
|
||||
/// Tail of the KSDATAFORMAT_SUBTYPE_* GUIDs (bytes 2..16); bytes 0..2 hold the format tag.
|
||||
pub(crate) const GUID_TAIL: [u8; 14] = [0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71];
|
||||
/// Tail of the Ambisonic subtype GUIDs {0000000x-0721-11D3-8644-C8C1CA000000}: PCM (x = 1) and float (x = 3) as well.
|
||||
pub(crate) const AMBISONIC_TAIL: [u8; 14] = [0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00];
|
||||
@@ -478,3 +478,70 @@ fn float_header(sample_rate: u32, channels: u16, bwf: Option<&crate::BwfInfo>, f
|
||||
}
|
||||
wav::header(usize::from(channels), sample_rate, (32, true), bwf, None, frames, false)
|
||||
}
|
||||
|
||||
/// What [`repair_wav`] wrote into a file.
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct WavRepair {
|
||||
/// The whole frames the data chunk holds.
|
||||
pub frames: u64,
|
||||
/// The length of the repaired file. Bytes past it are a partial last frame; truncate the
|
||||
/// file to this length (`File::set_len`) to drop them.
|
||||
pub len: u64,
|
||||
}
|
||||
|
||||
/// Rewrites the size fields of a PCM or float WAV whose writer stopped before finishing it, such
|
||||
/// as a recorder's file after a crash, for the whole frames the file holds. The file must end in
|
||||
/// its data chunk: everything after the data chunk's header counts as samples, whatever its size
|
||||
/// field says.
|
||||
///
|
||||
/// It writes these fields and leaves every other byte before the samples as it is, `fmt `, `bext`
|
||||
/// and unknown chunks included:
|
||||
///
|
||||
/// - the RIFF size and the data chunk's size (both `0xFFFF_FFFF` in an RF64 file);
|
||||
/// - the frame count, the first field of the first `fact` chunk (`0xFFFF_FFFF` past `u32::MAX` frames);
|
||||
/// - in an RF64 file, the RIFF size, data size and frame count at the start of the first `ds64` chunk;
|
||||
/// - the pad byte after an odd data length.
|
||||
///
|
||||
/// A RIFF file that grew past 4 GiB becomes RF64 when it starts with the 28-byte `JUNK` chunk that
|
||||
/// [`FileEncoder`] and [`wav_float_header`] write: `RIFF` becomes `RF64` and that `JUNK` chunk
|
||||
/// becomes a `ds64` chunk with an empty table. A RIFF file whose 28-byte chunk there already has the
|
||||
/// `ds64` id, left by an earlier repair that stopped before writing `RF64`, becomes RF64 the same way.
|
||||
///
|
||||
/// Errors:
|
||||
///
|
||||
/// - [`AudioError::Malformed`] when `file` is not a RIFF or RF64 WAVE file, has no data chunk within
|
||||
/// its first 100,000 chunks, has its data chunk before its `fmt ` chunk, has a `fmt ` chunk shorter
|
||||
/// than 16 bytes or cut short by the end of the file, has 0 channels or 0 bits, has a block size
|
||||
/// other than the channels times the bytes per sample, has an extensible `fmt ` chunk with a cbSize
|
||||
/// below 22 or more valid bits than bits per sample, or is RF64 without a `ds64` chunk or with a
|
||||
/// first `ds64` chunk of 16 to 27 bytes (the WAV reader takes the data size from that chunk).
|
||||
/// - [`AudioError::Unsupported`] for a format other than PCM and IEEE float, an extensible format
|
||||
/// whose subformat is neither, a sample width the WAV reader does not decode (PCM above 32 bits,
|
||||
/// float other than 32 or 64 bits), and unfinished 8-bit mono data of even length (its last byte
|
||||
/// may be a sample or a pad byte).
|
||||
/// - [`AudioError::TooLarge`] for a RIFF file past 4 GiB that does not start with that `JUNK` or
|
||||
/// `ds64` chunk.
|
||||
/// - [`AudioError::Io`] when reading, writing or seeking `file` fails.
|
||||
///
|
||||
/// ```
|
||||
/// use craft_audio::{repair_wav, wav_float_header};
|
||||
/// use std::io::Cursor;
|
||||
///
|
||||
/// // A recorder wrote the header for 0 frames, then 2 frames and part of a third, then stopped.
|
||||
/// let mut bytes = wav_float_header(48_000, 2, 0).unwrap();
|
||||
/// bytes.extend([0.25f32, -0.25, 0.5, -0.5, 0.75].iter().flat_map(|s| s.to_le_bytes()));
|
||||
/// let mut file = Cursor::new(bytes);
|
||||
/// let repaired = repair_wav(&mut file).unwrap();
|
||||
/// assert_eq!(repaired.frames, 2);
|
||||
/// let mut bytes = file.into_inner();
|
||||
/// bytes.truncate(repaired.len as usize);
|
||||
/// let header = wav_float_header(48_000, 2, 2).unwrap();
|
||||
/// assert_eq!(bytes[..header.len()], header[..]);
|
||||
/// ```
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
pub fn repair_wav<F: std::io::Read + Write + Seek>(file: &mut F) -> Result<WavRepair> {
|
||||
let (frames, len) = wav::repair(file)?;
|
||||
Ok(WavRepair { frames, len })
|
||||
}
|
||||
@@ -2,9 +2,9 @@
|
||||
//! specification, `bext` per EBU Tech 3285, `ds64` per EBU Tech 3306).
|
||||
|
||||
use super::pcm::{Quantizer, sample_format, validate_buffer, validate_layout, write_interleaved};
|
||||
use crate::wav::{GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM};
|
||||
use crate::wav::{AMBISONIC_TAIL, GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM};
|
||||
use crate::{AudioBuffer, AudioError, BitDepth, BwfInfo, Result};
|
||||
use std::io::{Cursor, Seek, SeekFrom, Write};
|
||||
use std::io::{Cursor, ErrorKind, Read, Seek, SeekFrom, Write};
|
||||
|
||||
const BEXT_MIN_LEN: usize = 602;
|
||||
|
||||
@@ -239,3 +239,175 @@ pub(crate) fn header(
|
||||
head.extend_from_slice(&(if rf64 { u32::MAX } else { data_len as u32 }).to_le_bytes());
|
||||
Ok(head)
|
||||
}
|
||||
|
||||
/// Where the size fields of a WAV sit, from a walk of its chunks up to `data`.
|
||||
struct Layout {
|
||||
rf64: bool,
|
||||
/// The body of the `ds64` chunk of an RF64 file, or in a RIFF file the body of the 28-byte
|
||||
/// `JUNK` or `ds64` chunk right after `WAVE` that can become one.
|
||||
ds64: Option<u64>,
|
||||
junk: bool,
|
||||
fact: Option<u64>,
|
||||
block_align: u64,
|
||||
data: u64,
|
||||
}
|
||||
|
||||
fn read_at<F: Read + Seek>(file: &mut F, pos: u64, buf: &mut [u8]) -> Result<bool> {
|
||||
file.seek(SeekFrom::Start(pos))?;
|
||||
match file.read_exact(buf) {
|
||||
Ok(()) => Ok(true),
|
||||
Err(e) if e.kind() == ErrorKind::UnexpectedEof => Ok(false),
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_at<F: Write + Seek>(file: &mut F, pos: u64, bytes: &[u8]) -> Result<()> {
|
||||
file.seek(SeekFrom::Start(pos))?;
|
||||
file.write_all(bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The block size of a PCM or float `fmt ` chunk body at `pos` of `size` bytes.
|
||||
fn pcm_block_align<F: Read + Seek>(file: &mut F, pos: u64, size: u32) -> Result<u64> {
|
||||
let mut fmt = [0u8; 40];
|
||||
let n = if size >= 40 { 40 } else { 16 };
|
||||
if size < 16 || !read_at(file, pos, &mut fmt[..n])? {
|
||||
return Err(AudioError::Malformed("WAV fmt chunk is cut short".into()));
|
||||
}
|
||||
let field = |at: usize| u16::from_le_bytes([fmt[at], fmt[at + 1]]);
|
||||
let mut tag = field(0);
|
||||
if tag == WAVE_FORMAT_EXTENSIBLE && n == 40 {
|
||||
// The extensible fields the reader checks.
|
||||
if field(16) < 22 || field(18) > field(14) {
|
||||
return Err(AudioError::Malformed("WAVE_FORMAT_EXTENSIBLE fmt chunk has a cbSize below 22 or too many valid bits".into()));
|
||||
}
|
||||
if fmt[26..] == GUID_TAIL || fmt[26..] == AMBISONIC_TAIL {
|
||||
tag = field(24);
|
||||
}
|
||||
}
|
||||
if tag != WAVE_FORMAT_PCM && tag != WAVE_FORMAT_IEEE_FLOAT {
|
||||
return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x}")));
|
||||
}
|
||||
let (channels, align, bits) = (field(2), field(12), field(14));
|
||||
if channels == 0 || bits == 0 || u32::from(align) != u32::from(channels) * u32::from(bits.div_ceil(8)) {
|
||||
return Err(AudioError::Malformed(format!("WAV block size {align} does not fit {channels} channels of {bits} bits")));
|
||||
}
|
||||
// The widths the WAV reader decodes.
|
||||
if !matches!((tag, bits), (WAVE_FORMAT_PCM, 1..=32) | (WAVE_FORMAT_IEEE_FLOAT, 32 | 64)) {
|
||||
return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x} with {bits} bits per sample")));
|
||||
}
|
||||
Ok(u64::from(align))
|
||||
}
|
||||
|
||||
fn layout<F: Read + Seek>(file: &mut F, len: u64) -> Result<Layout> {
|
||||
let mut riff = [0u8; 12];
|
||||
if !read_at(file, 0, &mut riff)? || !(riff.starts_with(b"RIFF") || riff.starts_with(b"RF64")) || &riff[8..] != b"WAVE" {
|
||||
return Err(AudioError::Malformed("not a WAV file".into()));
|
||||
}
|
||||
let rf64 = riff.starts_with(b"RF64");
|
||||
let (mut ds64, mut junk, mut fact, mut block_align) = (None, false, None, None);
|
||||
let mut pos = 12u64;
|
||||
let mut chunk = [0u8; 8];
|
||||
// The same bound as the reader's, so a file of tiny chunks can't spin forever.
|
||||
for _ in 0..100_000 {
|
||||
if pos >= len || !read_at(file, pos, &mut chunk)? {
|
||||
break;
|
||||
}
|
||||
let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]);
|
||||
let body = pos + 8;
|
||||
match &chunk[..4] {
|
||||
b"data" => {
|
||||
let block_align = block_align.ok_or_else(|| AudioError::Malformed("WAV data chunk before its fmt chunk".into()))?;
|
||||
return Ok(Layout { rf64, ds64, junk, fact, block_align, data: body });
|
||||
}
|
||||
// The first `ds64` and `fact` chunks take the sizes; later ones are left as they are.
|
||||
// The WAV reader takes the data size from the first `ds64` chunk of 16 bytes or more.
|
||||
b"ds64" if rf64 && size >= 16 && ds64.is_none() => {
|
||||
if size < 28 {
|
||||
return Err(AudioError::Malformed("RF64 ds64 chunk is shorter than 28 bytes".into()));
|
||||
}
|
||||
ds64 = Some(body);
|
||||
}
|
||||
// A `ds64` id here in a RIFF file is a promotion that stopped before the RF64 id.
|
||||
b"JUNK" | b"ds64" if !rf64 && pos == 12 && size == 28 => (ds64, junk) = (Some(body), true),
|
||||
b"fact" if size >= 4 && fact.is_none() => fact = Some(body),
|
||||
b"fmt " => block_align = Some(pcm_block_align(file, body, size)?),
|
||||
_ => {}
|
||||
}
|
||||
pos = body + u64::from(size) + u64::from(size & 1);
|
||||
}
|
||||
Err(AudioError::Malformed("WAV has no data chunk".into()))
|
||||
}
|
||||
|
||||
/// The data size the header records: the `ds64` field of an RF64 file, else the data chunk's.
|
||||
fn stored_data_len<F: Read + Seek>(file: &mut F, l: &Layout) -> Result<Option<u64>> {
|
||||
let mut size = [0u8; 8];
|
||||
Ok(match (l.rf64, l.ds64) {
|
||||
(true, Some(at)) => read_at(file, at + 8, &mut size)?.then(|| u64::from_le_bytes(size)),
|
||||
(true, None) => None,
|
||||
(false, _) => read_at(file, l.data - 4, &mut size[..4])?
|
||||
.then(|| u32::from_le_bytes([size[0], size[1], size[2], size[3]]))
|
||||
.filter(|&s| s != u32::MAX)
|
||||
.map(u64::from),
|
||||
})
|
||||
}
|
||||
|
||||
/// Rewrites the size fields of a WAV that ends in its data chunk for the whole frames it holds.
|
||||
/// Returns the frame count and the length the file should have; bytes past it are a partial frame.
|
||||
pub(crate) fn repair<F: Read + Write + Seek>(file: &mut F) -> Result<(u64, u64)> {
|
||||
let len = file.seek(SeekFrom::End(0))?;
|
||||
let l = layout(file, len)?;
|
||||
let held = len.saturating_sub(l.data);
|
||||
// A finished file's own size, which also tells its pad byte from a frame of one byte.
|
||||
let stored = stored_data_len(file, &l)?.filter(|&s| s % l.block_align == 0 && s.checked_add(s & 1) == Some(held));
|
||||
if stored.is_none() && l.block_align == 1 && held > 0 && held % 2 == 0 {
|
||||
// The last byte may be a sample or the pad byte after an odd count of them.
|
||||
return Err(AudioError::Unsupported("repairing 8-bit mono WAV data of even length: a pad byte reads as a sample".into()));
|
||||
}
|
||||
let frames = stored.unwrap_or(held) / l.block_align;
|
||||
let data_len = frames * l.block_align;
|
||||
let pad = data_len & 1;
|
||||
let new_len = l.data + data_len + pad;
|
||||
let riff_len = new_len - 8;
|
||||
let rf64 = l.rf64 || u32::try_from(riff_len).is_err();
|
||||
let ds64 = match (rf64, l.ds64) {
|
||||
(false, _) => None,
|
||||
(true, Some(at)) if l.rf64 || l.junk => Some(at),
|
||||
(true, _) if l.rf64 => return Err(AudioError::Malformed("RF64 file has no ds64 chunk".into())),
|
||||
(true, _) => return Err(AudioError::TooLarge("WAV past 4 GiB has no room for a ds64 chunk".into())),
|
||||
};
|
||||
if let Some(at) = l.fact {
|
||||
write_at(file, at, &u32::try_from(frames).unwrap_or(u32::MAX).to_le_bytes())?;
|
||||
}
|
||||
match ds64 {
|
||||
Some(at) => {
|
||||
let mut body = Vec::with_capacity(28);
|
||||
body.extend_from_slice(&riff_len.to_le_bytes());
|
||||
body.extend_from_slice(&data_len.to_le_bytes());
|
||||
body.extend_from_slice(&frames.to_le_bytes());
|
||||
if !l.rf64 {
|
||||
// The `JUNK` chunk's last 4 bytes become the table length: no table entries.
|
||||
body.extend_from_slice(&0u32.to_le_bytes());
|
||||
}
|
||||
write_at(file, at, &body)?;
|
||||
if !l.rf64 {
|
||||
write_at(file, at - 8, b"ds64")?;
|
||||
write_at(file, 0, b"RF64")?;
|
||||
}
|
||||
write_at(file, l.data - 4, &u32::MAX.to_le_bytes())?;
|
||||
write_at(file, 4, &u32::MAX.to_le_bytes())?;
|
||||
}
|
||||
None => {
|
||||
write_at(file, l.data - 4, &(data_len as u32).to_le_bytes())?;
|
||||
write_at(file, 4, &(riff_len as u32).to_le_bytes())?;
|
||||
}
|
||||
}
|
||||
// The pad byte goes last: until it is written, 8-bit mono data keeps an odd length that a
|
||||
// repeated repair can count.
|
||||
if pad == 1 {
|
||||
write_at(file, l.data + data_len, &[0])?;
|
||||
}
|
||||
file.seek(SeekFrom::Start(new_len))?;
|
||||
file.flush()?;
|
||||
Ok((frames, new_len))
|
||||
}
|
||||
@@ -68,6 +68,315 @@ fn wav_and_aiff_roundtrip_all_depths_and_layouts() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A file that stopped growing before its header was rewritten: the header for 0 frames, the
|
||||
/// samples of `buf`, then `extra` bytes of a frame that was never finished.
|
||||
fn unfinished_wav(buf: &AudioBuffer, opts: &EncodeOptions, extra: usize) -> (Vec<u8>, Vec<u8>) {
|
||||
let finished = encode(buf, opts).unwrap();
|
||||
let mut file = encode(&AudioBuffer::new(buf.sample_rate, buf.num_channels(), 0), opts).unwrap();
|
||||
let head = file.len();
|
||||
let sample_bytes = match opts.bit_depth {
|
||||
BitDepth::Int16 => 2,
|
||||
BitDepth::Int24 => 3,
|
||||
_ => 4,
|
||||
};
|
||||
let data_len = buf.frames() * usize::from(buf.num_channels()) * sample_bytes;
|
||||
file.extend_from_slice(&finished[head..head + data_len]);
|
||||
file.extend(std::iter::repeat_n(0x55, extra));
|
||||
(file, finished)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_wav_rewrites_the_sizes_of_an_unfinished_file() {
|
||||
let bwf = BwfInfo::default().with_description("take 3").with_time_reference(48_000 * 3600);
|
||||
let cases = [
|
||||
(sine(48_000, 2, 1_000), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Float32).with_bwf(bwf.clone()), 5),
|
||||
// 3 bytes a frame and an odd frame count: the data needs a pad byte.
|
||||
(sine(44_100, 1, 999), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24).with_bwf(bwf.clone()), 2),
|
||||
(sine(44_100, 1, 999), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24).with_bwf(bwf), 0),
|
||||
(sine(48_000, 6, 300), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16).with_force_rf64(true), 11),
|
||||
(sine(48_000, 2, 0), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16), 3),
|
||||
];
|
||||
for (buf, opts, extra) in cases {
|
||||
let (file, finished) = unfinished_wav(&buf, &opts, extra);
|
||||
assert_ne!(file, finished);
|
||||
let mut file = std::io::Cursor::new(file);
|
||||
let repaired = craft_audio::repair_wav(&mut file).unwrap();
|
||||
assert_eq!(repaired.frames, buf.frames() as u64);
|
||||
let mut file = file.into_inner();
|
||||
assert!(file.len() as u64 >= repaired.len);
|
||||
file.truncate(repaired.len as usize);
|
||||
assert_eq!(file, finished, "{opts:?}");
|
||||
// A finished file stays as it is.
|
||||
let mut again = std::io::Cursor::new(file.clone());
|
||||
assert_eq!(craft_audio::repair_wav(&mut again).unwrap(), repaired);
|
||||
assert_eq!(again.into_inner(), file);
|
||||
}
|
||||
}
|
||||
|
||||
/// A file whose data is all zeros past `head`, `len` bytes long, without holding them in memory.
|
||||
struct SparseWav {
|
||||
head: Vec<u8>,
|
||||
len: u64,
|
||||
pos: u64,
|
||||
}
|
||||
|
||||
impl std::io::Read for SparseWav {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
let n = (self.len.saturating_sub(self.pos)).min(buf.len() as u64) as usize;
|
||||
for (i, b) in buf[..n].iter_mut().enumerate() {
|
||||
*b = self.head.get(self.pos as usize + i).copied().unwrap_or(0);
|
||||
}
|
||||
self.pos += n as u64;
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Write for SparseWav {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
let end = self.pos as usize + buf.len();
|
||||
if end <= self.head.len() {
|
||||
self.head[self.pos as usize..end].copy_from_slice(buf);
|
||||
} else {
|
||||
assert!(buf.iter().all(|&b| b == 0), "only padding is written past the header");
|
||||
}
|
||||
self.pos += buf.len() as u64;
|
||||
self.len = self.len.max(self.pos);
|
||||
Ok(buf.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Seek for SparseWav {
|
||||
fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result<u64> {
|
||||
self.pos = match to {
|
||||
std::io::SeekFrom::Start(p) => p,
|
||||
std::io::SeekFrom::End(d) => self.len.checked_add_signed(d).unwrap(),
|
||||
std::io::SeekFrom::Current(d) => self.pos.checked_add_signed(d).unwrap(),
|
||||
};
|
||||
Ok(self.pos)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_wav_turns_a_file_past_4_gib_into_rf64() {
|
||||
let frames = 600_000_000u64; // 4.8 GB of stereo float
|
||||
let head = wav_float_header(48_000, 2, 0).unwrap();
|
||||
let len = head.len() as u64 + frames * 8 + 3;
|
||||
let mut file = SparseWav { head: head.clone(), len, pos: 0 };
|
||||
let repaired = craft_audio::repair_wav(&mut file).unwrap();
|
||||
assert_eq!((repaired.frames, repaired.len), (frames, len - 3));
|
||||
assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap());
|
||||
|
||||
// A JUNK chunk holding other bytes becomes a ds64 chunk with an empty table.
|
||||
let mut dirty = head.clone();
|
||||
assert_eq!(&dirty[12..16], b"JUNK");
|
||||
dirty[20..48].fill(0xAA);
|
||||
let mut file = SparseWav { head: dirty, len, pos: 0 };
|
||||
craft_audio::repair_wav(&mut file).unwrap();
|
||||
assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap());
|
||||
|
||||
// A repair that stopped after naming the ds64 chunk but before writing RF64 finishes next time.
|
||||
let mut half = head.clone();
|
||||
half[12..16].copy_from_slice(b"ds64");
|
||||
let mut file = SparseWav { head: half, len, pos: 0 };
|
||||
assert_eq!(craft_audio::repair_wav(&mut file).unwrap(), repaired);
|
||||
assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap());
|
||||
|
||||
// In a RIFF file only the chunk right after WAVE becomes ds64; a later ds64 chunk is left as it is.
|
||||
let at = head.windows(4).position(|w| w == b"data").unwrap();
|
||||
let later: Vec<u8> = [&b"ds64"[..], &28u32.to_le_bytes(), &[0xBB; 28]].concat();
|
||||
let mut two = head.clone();
|
||||
two.splice(at..at, later.iter().copied());
|
||||
let mut file = SparseWav { head: two, len: len + 36, pos: 0 };
|
||||
assert_eq!(craft_audio::repair_wav(&mut file).unwrap().frames, frames);
|
||||
assert_eq!((&file.head[..4], &file.head[12..16]), (&b"RF64"[..], &b"ds64"[..]));
|
||||
assert_eq!(file.head[at..at + 36], later[..]);
|
||||
|
||||
// In an RF64 file the ds64 chunk right after WAVE takes the sizes; a later ds64 chunk is left as it is.
|
||||
let finished = wav_float_header(48_000, 2, frames).unwrap();
|
||||
assert_eq!((&finished[..4], &finished[12..16]), (&b"RF64"[..], &b"ds64"[..]));
|
||||
let mut stale = finished.clone();
|
||||
stale[20..44].fill(0);
|
||||
stale.splice(at..at, later.iter().copied());
|
||||
let mut file = SparseWav { head: stale, len: len + 36, pos: 0 };
|
||||
let r = craft_audio::repair_wav(&mut file).unwrap();
|
||||
assert_eq!((r.frames, r.len), (frames, len + 33));
|
||||
let field = |at: usize| u64::from_le_bytes(file.head[at..at + 8].try_into().unwrap());
|
||||
assert_eq!((field(20), field(28), field(36)), (len + 25, frames * 8, frames));
|
||||
assert_eq!(file.head[at..at + 36], later[..]);
|
||||
|
||||
// A RIFF file with no JUNK chunk to turn into ds64 cannot grow past 4 GiB.
|
||||
let bare = craft_audio::pcm_wav_header(0, 2, 48_000, 16);
|
||||
assert_eq!(&bare[12..16], b"fmt ");
|
||||
let len = bare.len() as u64 + (1u64 << 32);
|
||||
let mut file = SparseWav { head: bare, len, pos: 0 };
|
||||
assert!(matches!(craft_audio::repair_wav(&mut file), Err(craft_audio::AudioError::TooLarge(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_wav_writes_the_frame_count_into_the_first_fact_chunk() {
|
||||
let mut file = wav_float_header(48_000, 2, 0).unwrap();
|
||||
let fact = file.windows(4).position(|w| w == b"fact").unwrap() + 8;
|
||||
let at = file.windows(4).position(|w| w == b"data").unwrap();
|
||||
let later: Vec<u8> = [&b"fact"[..], &4u32.to_le_bytes(), &[0xCC; 4]].concat();
|
||||
file.splice(at..at, later.iter().copied());
|
||||
file.extend(std::iter::repeat_n(0, 100 * 8));
|
||||
let mut file = std::io::Cursor::new(file);
|
||||
assert_eq!(craft_audio::repair_wav(&mut file).unwrap().frames, 100);
|
||||
let file = file.into_inner();
|
||||
assert_eq!(file[fact..fact + 4], 100u32.to_le_bytes());
|
||||
assert_eq!(file[at..at + 12], later[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rf64_data_size_comes_from_the_ds64_chunk_after_wave() {
|
||||
let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16).with_force_rf64(true);
|
||||
let wav = encode(&sine(48_000, 2, 300), &opts).unwrap();
|
||||
assert_eq!(&wav[12..16], b"ds64");
|
||||
// A later ds64 chunk that gives the data 4 bytes, one frame.
|
||||
let mut body = [0u8; 28];
|
||||
body[8..16].copy_from_slice(&4u64.to_le_bytes());
|
||||
let later = [&b"ds64"[..], &28u32.to_le_bytes(), &body].concat();
|
||||
let at = wav.windows(4).position(|w| w == b"data").unwrap();
|
||||
let mut two = wav.clone();
|
||||
two.splice(at..at, later);
|
||||
let (info, buf) = decode(&two, Some("wav")).unwrap();
|
||||
assert_eq!((info.frames, buf.frames()), (300, 300));
|
||||
|
||||
// A 16-byte first ds64 chunk gives the reader the data size, so repair does not use the later one.
|
||||
let mut short = two;
|
||||
short[16..20].copy_from_slice(&16u32.to_le_bytes());
|
||||
short[28..36].copy_from_slice(&4u64.to_le_bytes());
|
||||
short[36..44].copy_from_slice(&[&b"JUNK"[..], &4u32.to_le_bytes()].concat());
|
||||
assert_eq!(decode(&short, Some("wav")).unwrap().1.frames(), 1);
|
||||
let repaired = craft_audio::repair_wav(&mut std::io::Cursor::new(short));
|
||||
assert!(matches!(repaired, Err(craft_audio::AudioError::Malformed(_))), "{repaired:?}");
|
||||
}
|
||||
|
||||
/// A file whose writes fail once `writes` of them have gone through.
|
||||
struct FailingWrites {
|
||||
file: std::io::Cursor<Vec<u8>>,
|
||||
writes: usize,
|
||||
}
|
||||
|
||||
impl std::io::Read for FailingWrites {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
std::io::Read::read(&mut self.file, buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Write for FailingWrites {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
if self.writes == 0 {
|
||||
return Err(std::io::Error::other("disk full"));
|
||||
}
|
||||
self.writes -= 1;
|
||||
std::io::Write::write(&mut self.file, buf)
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Seek for FailingWrites {
|
||||
fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result<u64> {
|
||||
std::io::Seek::seek(&mut self.file, to)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_wav_runs_again_after_a_write_error() {
|
||||
let mut u8_mono = craft_audio::pcm_wav_header(0, 1, 8_000, 8);
|
||||
u8_mono.extend([0x80; 3]);
|
||||
let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24);
|
||||
let (int24, _) = unfinished_wav(&sine(44_100, 1, 999), &opts, 2);
|
||||
for (file, frames) in [(u8_mono, 3), (int24, 999)] {
|
||||
let mut whole = std::io::Cursor::new(file.clone());
|
||||
let repaired = craft_audio::repair_wav(&mut whole).unwrap();
|
||||
assert_eq!(repaired.frames, frames);
|
||||
for writes in 0.. {
|
||||
let mut failing = FailingWrites { file: std::io::Cursor::new(file.clone()), writes };
|
||||
if craft_audio::repair_wav(&mut failing).is_ok() {
|
||||
break;
|
||||
}
|
||||
let mut again = failing.file;
|
||||
assert_eq!(craft_audio::repair_wav(&mut again).unwrap(), repaired, "stopped after {writes} writes");
|
||||
assert_eq!(again.into_inner(), *whole.get_ref(), "stopped after {writes} writes");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_wav_refuses_what_it_cannot_repair() {
|
||||
use craft_audio::AudioError;
|
||||
let repair = |bytes: Vec<u8>| craft_audio::repair_wav(&mut std::io::Cursor::new(bytes));
|
||||
let wav = encode(&sine(48_000, 1, 100), &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16)).unwrap();
|
||||
assert!(matches!(repair(b"not a wave file at all".to_vec()), Err(AudioError::Malformed(_))));
|
||||
// Every cut inside the header is an error, not a panic.
|
||||
let data = wav.windows(4).position(|w| w == b"data").unwrap();
|
||||
for cut in 0..data + 8 {
|
||||
assert!(repair(wav[..cut].to_vec()).is_err(), "cut at {cut}");
|
||||
}
|
||||
// A compressed format (format tag 2, Microsoft ADPCM) has no fixed frame size to count by.
|
||||
let fmt = wav.windows(4).position(|w| w == b"fmt ").unwrap() + 8;
|
||||
let mut adpcm = wav.clone();
|
||||
adpcm[fmt..fmt + 2].copy_from_slice(&2u16.to_le_bytes());
|
||||
assert!(matches!(repair(adpcm), Err(AudioError::Unsupported(_))));
|
||||
// The chunk walk stops, as the reader's does, after 100,000 chunks.
|
||||
let mut many = wav[..12].to_vec();
|
||||
many.extend(b"JUNK\0\0\0\0".repeat(100_001));
|
||||
many.extend_from_slice(&wav[12..]);
|
||||
assert!(matches!(repair(many), Err(AudioError::Malformed(_))));
|
||||
// 8-bit mono: an even data length could end in a sample or in the pad after an odd count.
|
||||
let u8_mono = craft_audio::pcm_wav_header(0, 1, 8_000, 8);
|
||||
for (samples, ok) in [(3, true), (4, false)] {
|
||||
let mut file = u8_mono.clone();
|
||||
file.extend(std::iter::repeat_n(0x80, samples));
|
||||
assert_eq!(repair(file.clone()).map(|r| r.frames).ok(), ok.then_some(3), "{samples} bytes");
|
||||
if ok {
|
||||
// Once repaired, the size settles it.
|
||||
let mut file = std::io::Cursor::new(file);
|
||||
let r = craft_audio::repair_wav(&mut file).unwrap();
|
||||
assert_eq!(repair(file.into_inner()).unwrap(), r);
|
||||
}
|
||||
}
|
||||
// A block size that is not channels × sample bytes would count the wrong frames.
|
||||
let mut odd_align = wav.clone();
|
||||
odd_align[fmt + 12..fmt + 14].copy_from_slice(&4u16.to_le_bytes());
|
||||
assert!(matches!(repair(odd_align), Err(AudioError::Malformed(_))));
|
||||
// Widths the reader does not decode: 16-bit float and 40-bit PCM, each with a block size that fits.
|
||||
let mut float16 = wav.clone();
|
||||
float16[fmt..fmt + 2].copy_from_slice(&3u16.to_le_bytes());
|
||||
let mut pcm40 = wav.clone();
|
||||
pcm40[fmt + 12..fmt + 16].copy_from_slice(&[5, 0, 40, 0]);
|
||||
for bad in [float16, pcm40] {
|
||||
assert!(craft_audio::decode(&bad, Some("wav")).is_err());
|
||||
assert!(matches!(repair(bad), Err(AudioError::Unsupported(_))));
|
||||
}
|
||||
// An extensible file whose subformat is PCM's tag under another GUID is not PCM.
|
||||
let ext = encode(&sine(48_000, 2, 100), &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24)).unwrap();
|
||||
let fmt = ext.windows(4).position(|w| w == b"fmt ").unwrap() + 8;
|
||||
assert!(repair(ext.clone()).is_ok());
|
||||
let mut other_guid = ext.clone();
|
||||
other_guid[fmt + 39] ^= 0xFF;
|
||||
assert!(matches!(repair(other_guid), Err(AudioError::Unsupported(_))));
|
||||
// Extensible fields the reader refuses: a cbSize below 22 and more valid bits than the sample holds.
|
||||
let mut short_cb = ext.clone();
|
||||
short_cb[fmt + 16..fmt + 18].copy_from_slice(&21u16.to_le_bytes());
|
||||
let mut wide_valid = ext.clone();
|
||||
wide_valid[fmt + 18..fmt + 20].copy_from_slice(&25u16.to_le_bytes());
|
||||
for bad in [short_cb, wide_valid] {
|
||||
assert!(craft_audio::decode(&bad, Some("wav")).is_err());
|
||||
assert!(matches!(repair(bad), Err(AudioError::Malformed(_))));
|
||||
}
|
||||
// The Ambisonic PCM subformat {00000001-0721-11D3-8644-C8C1CA000000}, which the reader reads as PCM.
|
||||
let mut ambisonic = ext;
|
||||
ambisonic[fmt + 26..fmt + 40].copy_from_slice(&[0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]);
|
||||
assert_eq!(repair(ambisonic).unwrap().frames, 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_wav_header_with_bwf_keeps_its_bext_as_the_file_grows() {
|
||||
let take = sine(48_000, 2, 1_000);
|
||||
|
||||
@@ -103,10 +103,8 @@ fn an_unasked_line_makes_the_connection_unusable_before_sending() {
|
||||
let mut client = ControlClient::connect(addr, TOKEN).unwrap();
|
||||
assert!(client.is_usable(), "an idle connection with nothing pending is usable");
|
||||
said.send(()).unwrap();
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while client.is_usable() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
// A blocking peek (under the client's read timeout) returns once the line has arrived.
|
||||
assert!(client.stream.peek(&mut [0]).unwrap() > 0, "the unasked line arrived");
|
||||
assert!(!client.is_usable(), "the unasked line makes the connection unusable");
|
||||
assert_eq!(client.call("next", json!({})), Err("connection closed".to_string()));
|
||||
assert!(client.is_broken(), "the unusable connection is closed");
|
||||
|
||||
@@ -487,20 +487,40 @@ pub fn configure_stream(stream: &std::net::TcpStream) -> std::io::Result<()> {
|
||||
stream.set_write_timeout(Some(IO_TIMEOUT))
|
||||
}
|
||||
|
||||
/// The time an [`AuthDeadlineStream`] reads its deadline against: [`Instant::now`] in a server, or a time a test sets
|
||||
/// by hand.
|
||||
pub type DeadlineClock = std::sync::Arc<dyn Fn() -> Instant + Send + Sync>;
|
||||
|
||||
/// The real clock, [`Instant::now`].
|
||||
pub fn real_clock() -> DeadlineClock {
|
||||
std::sync::Arc::new(Instant::now)
|
||||
}
|
||||
|
||||
/// A read wrapper that fails once [`AUTH_DEADLINE`] passes without [`Self::authenticated`] being
|
||||
/// called, whatever the client sends meanwhile; after that only [`IO_TIMEOUT`] applies.
|
||||
#[derive(Debug)]
|
||||
pub struct AuthDeadlineStream {
|
||||
inner: std::net::TcpStream,
|
||||
deadline: Option<std::time::Instant>,
|
||||
clock: DeadlineClock,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AuthDeadlineStream {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("AuthDeadlineStream").field("inner", &self.inner).field("deadline", &self.deadline).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthDeadlineStream {
|
||||
/// Wraps `inner`; reads fail once `auth_deadline` has passed unauthenticated.
|
||||
pub fn new(inner: std::net::TcpStream, auth_deadline: Duration) -> Self {
|
||||
Self::with_clock(inner, auth_deadline, real_clock())
|
||||
}
|
||||
|
||||
/// [`Self::new`] with the deadline read against `clock` instead of the real clock.
|
||||
pub fn with_clock(inner: std::net::TcpStream, auth_deadline: Duration, clock: DeadlineClock) -> Self {
|
||||
// A limit too large to represent expires at once rather than never.
|
||||
let now = Instant::now();
|
||||
Self { inner, deadline: Some(now.checked_add(auth_deadline).unwrap_or(now)) }
|
||||
let now = clock();
|
||||
Self { inner, deadline: Some(now.checked_add(auth_deadline).unwrap_or(now)), clock }
|
||||
}
|
||||
|
||||
/// The handshake succeeded: lift the deadline and restore the idle timeout.
|
||||
@@ -513,7 +533,7 @@ impl AuthDeadlineStream {
|
||||
impl std::io::Read for AuthDeadlineStream {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
if let Some(deadline) = self.deadline {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
let left = deadline.saturating_duration_since((self.clock)());
|
||||
if left.is_zero() {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "not authenticated in time"));
|
||||
}
|
||||
|
||||
@@ -170,6 +170,37 @@ fn server_token_sources_and_validation() {
|
||||
);
|
||||
}
|
||||
|
||||
// An unauthenticated connection's reads succeed while its deadline is ahead, however much it sends, and fail once the
|
||||
// deadline has passed even with input waiting; after `authenticated` the deadline no longer applies.
|
||||
#[trial]
|
||||
fn the_authentication_deadline_holds_whatever_the_client_sends() {
|
||||
use std::io::{Read, Write};
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let mut client = std::net::TcpStream::connect(listener.local_addr().unwrap()).unwrap();
|
||||
let (server, _) = listener.accept().unwrap();
|
||||
server.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let start = Instant::now();
|
||||
let at = std::sync::Arc::new(std::sync::Mutex::new(start));
|
||||
let read_at = std::sync::Arc::clone(&at);
|
||||
let clock: DeadlineClock = std::sync::Arc::new(move || *read_at.lock().unwrap());
|
||||
let mut stream = AuthDeadlineStream::with_clock(server.try_clone().unwrap(), Duration::from_secs(10), clock);
|
||||
let mut byte = [0];
|
||||
// Blank lines and partial frames, each read while the deadline is ahead.
|
||||
for (step, sent) in [b"\n", b" ", b"{", b"\n"].into_iter().enumerate() {
|
||||
*at.lock().unwrap() = start + Duration::from_secs(3 * step as u64);
|
||||
client.write_all(sent).unwrap();
|
||||
assert_eq!(stream.read(&mut byte).unwrap(), 1, "read {step} is before the deadline");
|
||||
}
|
||||
*at.lock().unwrap() = start + Duration::from_secs(10);
|
||||
client.write_all(b"\n").unwrap();
|
||||
let late = stream.read(&mut byte).unwrap_err();
|
||||
assert_eq!(late.kind(), std::io::ErrorKind::TimedOut, "the input sent did not move the deadline: {late}");
|
||||
|
||||
stream.authenticated().unwrap();
|
||||
*at.lock().unwrap() = start + Duration::from_secs(60);
|
||||
assert_eq!(stream.read(&mut byte).unwrap(), 1, "an authenticated connection reads past the deadline");
|
||||
}
|
||||
|
||||
// A token file create that runs out of time fails with its own error, even when it left a file at
|
||||
// the path: that file is not read as another process's. A create that another process beat to the
|
||||
// path reads that process's token.
|
||||
|
||||
@@ -16,8 +16,8 @@ use serde_json::{Value, json};
|
||||
use crate::control::{ControlRequest, REPLY_DEADLINE};
|
||||
use crate::protocol::write_reply;
|
||||
use crate::security::{
|
||||
AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake, configure_stream,
|
||||
read_bounded_line, repeat_auth_reply,
|
||||
AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, DeadlineClock, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake,
|
||||
configure_stream, read_bounded_line, real_clock, repeat_auth_reply,
|
||||
};
|
||||
|
||||
/// A running control server. Dropping it stops accepting connections and returns once the port is
|
||||
@@ -72,6 +72,36 @@ pub fn serve_with_deadline(
|
||||
host: WindowHost,
|
||||
auth_deadline: Duration,
|
||||
) -> std::io::Result<(Receiver<ControlRequest>, Listening)> {
|
||||
serve_with(listener, token, host, ServeOptions { auth_deadline, ..ServeOptions::default() })
|
||||
}
|
||||
|
||||
/// What a test sets on a server [`serve_with`] starts.
|
||||
#[doc(hidden)]
|
||||
pub struct ServeOptions {
|
||||
/// How long a connection has to authenticate ([`AUTH_DEADLINE`] in [`serve`]).
|
||||
pub auth_deadline: Duration,
|
||||
/// The clock the authentication deadline is read against.
|
||||
pub clock: DeadlineClock,
|
||||
/// Sent `()` each time a connection has ended: its request sender is dropped and its place under
|
||||
/// [`MAX_CONNECTIONS`] is free again.
|
||||
pub ended: Option<Sender<()>>,
|
||||
}
|
||||
|
||||
impl Default for ServeOptions {
|
||||
fn default() -> Self {
|
||||
Self { auth_deadline: AUTH_DEADLINE, clock: real_clock(), ended: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// [`serve`] with the authentication deadline, its clock and a signal for each ended connection set by a test.
|
||||
#[doc(hidden)]
|
||||
pub fn serve_with(
|
||||
listener: TcpListener,
|
||||
token: String,
|
||||
host: WindowHost,
|
||||
options: ServeOptions,
|
||||
) -> std::io::Result<(Receiver<ControlRequest>, Listening)> {
|
||||
let ServeOptions { auth_deadline, clock, ended } = options;
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
let addr = listener.local_addr()?;
|
||||
// `ui.inspect`, `ui.click {label}` and `ui.focus` read the kept tree of the last presented frame; it is kept
|
||||
@@ -95,13 +125,19 @@ pub fn serve_with_deadline(
|
||||
let tx = tx.clone();
|
||||
let host = host.clone();
|
||||
let token = Arc::clone(&token);
|
||||
let clock = Arc::clone(&clock);
|
||||
let ended = ended.clone();
|
||||
std::thread::spawn(move || {
|
||||
serve_connection(stream, &token, &tx, &host, auth_deadline);
|
||||
serve_connection(stream, &token, &tx, &host, auth_deadline, clock);
|
||||
drop(tx);
|
||||
// What the last client held down would otherwise stay held with no one left to
|
||||
// release it; while another connection is live, its input is left alone.
|
||||
if permit.release() {
|
||||
host.end_injection();
|
||||
}
|
||||
if let Some(ended) = ended {
|
||||
let _ = ended.send(());
|
||||
}
|
||||
});
|
||||
}
|
||||
})?;
|
||||
@@ -110,12 +146,12 @@ pub fn serve_with_deadline(
|
||||
|
||||
/// Serve one connection: it must authenticate ([`ServerHandshake`]) within `auth_deadline` of
|
||||
/// connecting, however much it sends meanwhile; after that only the idle timeout applies.
|
||||
fn serve_connection(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, host: &WindowHost, auth_deadline: Duration) {
|
||||
fn serve_connection(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, host: &WindowHost, auth_deadline: Duration, clock: DeadlineClock) {
|
||||
if configure_stream(&stream).is_err() {
|
||||
return;
|
||||
}
|
||||
let Ok(read) = stream.try_clone() else { return };
|
||||
let mut reader = BufReader::new(AuthDeadlineStream::new(read, auth_deadline));
|
||||
let mut reader = BufReader::new(AuthDeadlineStream::with_clock(read, auth_deadline, clock));
|
||||
let mut out = stream;
|
||||
let mut line = String::new();
|
||||
let mut handshake = ServerHandshake::new();
|
||||
|
||||
@@ -2,14 +2,15 @@
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::{SocketAddr, TcpListener, TcpStream};
|
||||
use std::sync::mpsc::{Receiver, channel};
|
||||
use std::sync::mpsc::{Receiver, RecvTimeoutError, channel};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_automation::client::ControlClient;
|
||||
use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse, Reply, expired_error, result_reply, timeout_error};
|
||||
use craft_automation::protocol::MAX_RESPONSE_BYTES;
|
||||
use craft_automation::security::{CHALLENGE_METHOD, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches};
|
||||
use craft_automation::server;
|
||||
use craft_automation::server::{self, ServeOptions};
|
||||
use craft_ui::runtime::motion;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use craft_ui::testing::trial;
|
||||
@@ -101,39 +102,90 @@ fn host() -> WindowHost {
|
||||
/// sent is dispatched.
|
||||
#[trial]
|
||||
fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() {
|
||||
// A short deadline, so the test does not wait out the real one.
|
||||
let deadline = Duration::from_millis(400);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bound");
|
||||
let (rx, server) = server::serve_with_deadline(listener, TOKEN.into(), host(), deadline).expect("started");
|
||||
// Blank lines and partial frames, one byte every 20 ms: each read succeeds long before the idle timeout.
|
||||
let start = motion::now();
|
||||
let at = Arc::new(Mutex::new(start));
|
||||
let read_at = Arc::clone(&at);
|
||||
let (ended, connection_ended) = channel();
|
||||
// Each read of the clock is announced, so the test moves it only after the connection has set its deadline.
|
||||
let (read, clock_read) = channel();
|
||||
let clock = Arc::new(move || {
|
||||
let now = *read_at.lock().expect("the clock");
|
||||
let _ = read.send(());
|
||||
now
|
||||
});
|
||||
let options = ServeOptions { auth_deadline: Duration::from_secs(10), clock, ended: Some(ended) };
|
||||
let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started");
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
let started = motion::now();
|
||||
let mut closed = false;
|
||||
for i in 0..1000 {
|
||||
let byte: &[u8] = if i % 5 == 0 { b"\n" } else { b" " };
|
||||
if stream.write_all(byte).is_err() {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
let served = started.elapsed();
|
||||
assert!(closed, "the trickle did not keep the connection open");
|
||||
assert!(served < deadline + Duration::from_secs(3), "the trickle did not extend the deadline: {served:?}");
|
||||
assert!(rx.try_recv().is_err(), "nothing was dispatched");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
clock_read.recv_timeout(Duration::from_secs(5)).expect("the connection set its deadline");
|
||||
// Blank lines and the start of a line, sent while the deadline is ahead: none is a frame the handshake refuses.
|
||||
stream.write_all(b"\n \n ").expect("written");
|
||||
*at.lock().expect("the clock") = start + Duration::from_secs(10);
|
||||
// The server may already have closed when this is written; if not, it wakes the server's read.
|
||||
let _ = stream.write_all(b" ");
|
||||
assert!(is_closed(&mut reader), "the input sent did not keep the connection open past the deadline");
|
||||
assert!(nothing_more_dispatched(&rx, server, &connection_ended, 1), "nothing was dispatched");
|
||||
}
|
||||
|
||||
/// Whether the server closed the connection: the next read is the end of the stream, not a timeout or an error.
|
||||
/// Whether the server closed the connection: the next read is the end of the stream, or an error other than a timeout.
|
||||
/// A server that closes with input still unread makes the kernel send a reset, so the read fails with
|
||||
/// `ConnectionReset` or `ConnectionAborted` instead of returning the end of the stream (mostly on Windows).
|
||||
fn is_closed(reader: &mut impl BufRead) -> bool {
|
||||
let mut line = String::new();
|
||||
matches!(reader.read_line(&mut line), Ok(0))
|
||||
match reader.read_line(&mut line) {
|
||||
Ok(read) => read == 0,
|
||||
Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut),
|
||||
}
|
||||
}
|
||||
|
||||
/// A reader whose every read fails with the given error kind.
|
||||
struct Failing(std::io::ErrorKind);
|
||||
|
||||
impl std::io::Read for Failing {
|
||||
fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
|
||||
Err(self.0.into())
|
||||
}
|
||||
}
|
||||
|
||||
/// A reset or aborted connection counts as closed; a read timeout does not.
|
||||
#[trial]
|
||||
fn a_reset_connection_counts_as_closed() {
|
||||
use std::io::ErrorKind::{ConnectionAborted, ConnectionReset, TimedOut, WouldBlock};
|
||||
assert!(is_closed(&mut BufReader::new(Failing(ConnectionReset))), "a reset is a close");
|
||||
assert!(is_closed(&mut BufReader::new(Failing(ConnectionAborted))), "an abort is a close");
|
||||
assert!(!is_closed(&mut BufReader::new(Failing(TimedOut))), "a timeout is not a close");
|
||||
assert!(!is_closed(&mut BufReader::new(Failing(WouldBlock))), "a timeout is not a close");
|
||||
}
|
||||
|
||||
/// A server whose `ended` receiver gets `()` each time one of its connections has ended. Its clock stands still, so no
|
||||
/// connection reaches the authentication deadline: only the client or a refusal ends one. The frozen clock does not
|
||||
/// stop the socket's read timeout, which runs on real time and is the time left to the deadline capped at the idle
|
||||
/// timeout. The deadline is a minute, so a waiting connection's read times out after the 30-second idle timeout
|
||||
/// instead of after 10 seconds.
|
||||
fn serve_counting_ends() -> (Receiver<ControlRequest>, server::Listening, Receiver<()>) {
|
||||
let (ended, connection_ended) = channel();
|
||||
let start = motion::now();
|
||||
let options = ServeOptions { auth_deadline: Duration::from_secs(60), clock: Arc::new(move || start), ended: Some(ended) };
|
||||
let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started");
|
||||
(rx, server, connection_ended)
|
||||
}
|
||||
|
||||
/// Stops `server` and waits for its `connections` connections to end, so the request receiver `rx` is disconnected
|
||||
/// once every request that reached it has been taken: `rx` then answers whether anything more was dispatched.
|
||||
fn nothing_more_dispatched(rx: &Receiver<ControlRequest>, server: server::Listening, ended: &Receiver<()>, connections: usize) -> bool {
|
||||
drop(server);
|
||||
for _ in 0..connections {
|
||||
ended.recv_timeout(Duration::from_secs(5)).expect("a connection ended");
|
||||
}
|
||||
rx.recv_timeout(Duration::from_secs(5)).err() == Some(RecvTimeoutError::Disconnected)
|
||||
}
|
||||
|
||||
/// With `MAX_CONNECTIONS` connections open, the next one is told `connection limit reached` and closed; once one of
|
||||
/// the open ones ends, its place serves a new connection.
|
||||
#[trial]
|
||||
fn connections_past_the_limit_are_refused_with_the_reason() {
|
||||
let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started");
|
||||
let (rx, server, ended) = serve_counting_ends();
|
||||
let connect = || {
|
||||
let stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
@@ -150,20 +202,14 @@ fn connections_past_the_limit_are_refused_with_the_reason() {
|
||||
|
||||
drop(open.pop());
|
||||
// The server frees the place when it reads the close; a new connection is served once it has.
|
||||
let started = motion::now();
|
||||
let served = loop {
|
||||
let (mut stream, mut reader) = connect();
|
||||
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written");
|
||||
let reply = read_json(&mut reader).expect("a reply");
|
||||
if reply["ok"] == true || started.elapsed() > Duration::from_secs(5) {
|
||||
break reply;
|
||||
}
|
||||
assert_eq!(reply["error"], "connection limit reached", "{reply}");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
ended.recv_timeout(Duration::from_secs(5)).expect("the closed connection ended");
|
||||
let (mut stream, mut reader) = connect();
|
||||
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written");
|
||||
let served = read_json(&mut reader).expect("a reply");
|
||||
assert_eq!(served["result"]["authenticated"], true, "the freed place serves: {served}");
|
||||
assert!(rx.try_recv().is_err(), "nothing was dispatched");
|
||||
drop((stream, reader));
|
||||
drop(open);
|
||||
assert!(nothing_more_dispatched(&rx, server, &ended, MAX_CONNECTIONS), "nothing was dispatched");
|
||||
}
|
||||
|
||||
/// A first frame that is not JSON, and one with a wrong token, each get the `authentication required` refusal and the
|
||||
@@ -191,9 +237,8 @@ fn a_refused_first_frame_closes_the_connection() {
|
||||
/// and the connection closed, so neither the body's `auth` nor a request after it reaches the app.
|
||||
#[trial]
|
||||
fn a_browser_post_never_reaches_the_app() {
|
||||
// Far longer than the trial, so the close comes from the refusal, not the deadline.
|
||||
let (rx, server) = server::serve_with_deadline(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), Duration::from_secs(60))
|
||||
.expect("started");
|
||||
// The server's clock stands still, so the close comes from the refusal, not the deadline.
|
||||
let (rx, server, ended) = serve_counting_ends();
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
@@ -211,7 +256,8 @@ fn a_browser_post_never_reaches_the_app() {
|
||||
Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut),
|
||||
};
|
||||
assert!(closed, "the connection closes after the refusal, answering nothing more: {rest:?}");
|
||||
assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "nothing reached the app");
|
||||
drop((stream, reader));
|
||||
assert!(nothing_more_dispatched(&rx, server, &ended, 1), "nothing reached the app");
|
||||
}
|
||||
|
||||
/// A request line over `MAX_REQUEST_BYTES` without a newline gets an error reply and the connection is closed.
|
||||
@@ -325,19 +371,19 @@ fn the_documented_capture_client_sends_setup_steps_and_capture() {
|
||||
let mut client = ControlClient::connect(addr, TOKEN).expect("connected");
|
||||
capture_state(&mut client, &client_doc, &client_doc["states"][0], "new")
|
||||
});
|
||||
let mut channel = ControlChannel::new(requests);
|
||||
// Each request is waited for as it arrives and then taken through the channel, as the app's frame takes it.
|
||||
let (forward, forwarded) = channel();
|
||||
let mut channel = ControlChannel::new(forwarded);
|
||||
let mut seen: Vec<String> = Vec::new();
|
||||
let started = motion::now();
|
||||
while seen.len() < 4 && started.elapsed() < Duration::from_secs(10) {
|
||||
while let Some(req) = channel.next_request() {
|
||||
seen.push(format!("{} {}", req.method, req.params));
|
||||
let reply = match req.method.as_str() {
|
||||
"ui.screenshot" => Reply::from_result(Ok(json!({"path": req.params["path"], "width": 1280, "height": 800}))),
|
||||
_ => Reply::from_result(Ok(Value::Null)),
|
||||
};
|
||||
channel.settle(req, reply, None, 0.0);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
while seen.len() < 4 {
|
||||
forward.send(requests.recv_timeout(Duration::from_secs(10)).expect("a request")).expect("forwarded");
|
||||
let req = channel.next_request().expect("the forwarded request is dispatched");
|
||||
seen.push(format!("{} {}", req.method, req.params));
|
||||
let reply = match req.method.as_str() {
|
||||
"ui.screenshot" => Reply::from_result(Ok(json!({"path": req.params["path"], "width": 1280, "height": 800}))),
|
||||
_ => Reply::from_result(Ok(Value::Null)),
|
||||
};
|
||||
channel.settle(req, reply, None, 0.0);
|
||||
}
|
||||
let reply = client.join().expect("client ran").expect("the capture replied");
|
||||
assert_eq!(
|
||||
@@ -440,12 +486,12 @@ fn a_repeated_auth_is_answered_already_authenticated_without_dispatching() {
|
||||
/// and shut its end down) still reaches the app and is answered: a client cannot know it was dropped.
|
||||
#[trial]
|
||||
fn a_complete_json_request_at_eof_can_reach_the_app() {
|
||||
let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started");
|
||||
let (rx, server, ended) = serve_counting_ends();
|
||||
let handler = std::thread::spawn(move || {
|
||||
let req = rx.recv_timeout(Duration::from_secs(5)).expect("the request reached the app");
|
||||
assert_eq!(req.method, "test.once");
|
||||
req.reply.send(json!({"ok": true, "result": "once"})).expect("replied");
|
||||
assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "it ran exactly once");
|
||||
rx
|
||||
});
|
||||
let (mut stream, mut reader) = authenticated(server.addr);
|
||||
stream.write_all(json!({"id": 3, "method": "test.once"}).to_string().as_bytes()).expect("written");
|
||||
@@ -454,7 +500,8 @@ fn a_complete_json_request_at_eof_can_reach_the_app() {
|
||||
assert_eq!((&reply["id"], &reply["result"]), (&json!(3), &json!("once")));
|
||||
let mut rest = String::new();
|
||||
assert_eq!(reader.read_line(&mut rest).expect("closed, not timed out"), 0, "closed after the last request: {rest:?}");
|
||||
handler.join().expect("handler ran");
|
||||
let rx = handler.join().expect("handler ran");
|
||||
assert!(nothing_more_dispatched(&rx, server, &ended, 1), "it ran exactly once");
|
||||
}
|
||||
|
||||
/// Ported from WordCraft (#7317). Connections that never authenticate cannot fill the server: past the limit a new
|
||||
@@ -462,9 +509,8 @@ fn a_complete_json_request_at_eof_can_reach_the_app() {
|
||||
#[trial]
|
||||
fn idle_unauthenticated_connections_are_limited() {
|
||||
use craft_automation::security::MAX_CONNECTIONS;
|
||||
// Far longer than the trial, so only the limit refuses.
|
||||
let (rx, server) = server::serve_with_deadline(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), Duration::from_secs(60))
|
||||
.expect("started");
|
||||
// The server's clock stands still, so only the limit refuses.
|
||||
let (rx, server, ended) = serve_counting_ends();
|
||||
let idle: Vec<TcpStream> = (0..MAX_CONNECTIONS).map(|_| TcpStream::connect(server.addr).expect("connected")).collect();
|
||||
// Admission is counted by the accept thread: it is done once the next connection is answered.
|
||||
let refused = |addr| {
|
||||
@@ -477,18 +523,14 @@ fn idle_unauthenticated_connections_are_limited() {
|
||||
assert!(reply["error"].as_str().is_some_and(|e| e.contains("limit")), "{reply}");
|
||||
drop(idle);
|
||||
// The freed slots go back as the closed connections are noticed.
|
||||
let started = motion::now();
|
||||
loop {
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
// A refused connection may already be closed when the request is written (Windows resets it).
|
||||
let auth = json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}});
|
||||
if writeln!(stream, "{auth}").is_ok() && read_json(&mut reader).is_some_and(|r| r["ok"] == true) {
|
||||
break;
|
||||
}
|
||||
assert!(started.elapsed() < Duration::from_secs(10), "no slot came back");
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
for _ in 0..MAX_CONNECTIONS {
|
||||
ended.recv_timeout(Duration::from_secs(5)).expect("a closed connection ended");
|
||||
}
|
||||
assert!(rx.try_recv().is_err());
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
writeln!(stream, "{}", json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}})).expect("written");
|
||||
assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true, "a freed slot is admitted again");
|
||||
drop((stream, reader));
|
||||
assert!(nothing_more_dispatched(&rx, server, &ended, 1));
|
||||
}
|
||||
@@ -155,14 +155,13 @@ file is committed.
|
||||
| R72 | In the version 15 samples an `mcfg` chunk starts with the tag 1300 and the length of the rest of the chunk, then 4 bytes of 0 (the 12 bytes R10 names), and each `fild` chunk sits in a `LIST filc` of its own inside `LIST filt` | S: the 15 LT `testset/15` files without text (every `mcfg` starts with 1300 and its size less 8; each of their 31 `fild` chunks is the only chunk of a `LIST filc`) | sample (the reader skips the 12 bytes and finds `fild` chunks at any depth) |
|
||||
| R73 | The specification reads the id in a container's argument 8005 (R46) as the stored u32 plus 1, halved, and the `spnd` id as stored. Sample files hold the same stored u32 in both places, even ids included, which the halved reading would not match. The writer numbers containers 1, 2, 3 and so on, and writes the same number in the clipped group's `spnd` | KF L799-L807 (`powerclip_id`), L2305-L2312 (`spnd`); S: the container and `spnd` of LT `powerclipsquare_blackfill_whiterectangleinside.cdr` of `testset/12` (156091928) and `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (1), the eight UC files `corel_powerclip_*` of versions 7 to 13 (47834832) and TDF 114901 (515235504) | sample (the halved reading: not followed) |
|
||||
| R74 | `rscr`: a u16 count, then one field list per screen entry, which a `rotl` entry names (R58). The reader does not read it; the `.cmx` writer writes one entry whose field 1 holds the 13 bytes `00 00 3c 00 00 00 00 00 40 a5 ae 02 00` | S: each of the nine CX files with 32-bit coordinates has an `rscr` of one entry with a 13-byte field 1, these bytes in seven of them (`bars.cmx` and `thatch.cmx` differ in bytes 2 and 8 to 11) | sample |
|
||||
| R77 | The index of a file with 32-bit coordinates, which the reader does not read. `cont` bytes 84, 88 and 92 hold the u32 file offsets of the master index `ixmr`, of `LIST INFO` and of the picture of the drawing (`DISP`), 0xFFFFFFFF for one the file does not hold. Each offset here names where a chunk's id starts. `LIST indx` holds a layer table `ixlr`, then `ixtl`, `ixpg` and `ixmr`. `ixmr`: the u16 values 1 and 24, a u16 count, then a u16 id and a u32 offset for each entry: 1 `ixmr` itself, 2 `ixpg`, 3 `ixtl`, 15 `rotl`, 16 `rott`, 17 `rota`, 18 `rscr`, 19 `rpen`, 20 `rdot`, 21 `rclr`, 22 `ccmm`; a table the file does not hold has no entry. `ixpg`: a u16 count, then for each page a u16 record size of 16 and four u32: the page chunk, its layer table, its picture (0xFFFFFFFF for none) and its reference list `rlst`. `ixtl`: a u16 count, a u16 record size of 4, the u16 type 3 (layer tables), then the u32 offset of each layer table. `ixlr`: a u16 count of the page's layers and the u16 value 1, then for each layer in file order a u16 size (8 plus the name's length), the u32 offset of its begin-layer instruction, its name as a u16 count and 8-bit characters, and 0xFFFFFFFF after the size. `rlst`: a u16 count of the page's layers, then the u16 values 2 and 9 and the layer's number for each. Begin page's field 1 ends with the u32 offset of the end-page instruction, a u16 count of the page's layers and a u32 count of its instructions, begin and end page included; begin layer's field 1 holds a u32 count of the layer's instructions, begin and end layer included, at bytes 8 to 12; begin group's field 1 holds the left, top, right and bottom edges of its curves (i32), a u16 count of the groups directly inside it, a u32 count of its instructions, begin and end group included, and the u32 offset of the instruction after its end | LC `CMXParser.cpp` L260-L286 (the three offsets, 0xFFFFFFFF for none), L346-L413 (`ixmr`: two u16, the count, the id and offset pairs), L545-L590 (begin group: the edges, a u16, the command count and the end address), L1974-L2019 (`ixtl`: the count, the record size, the type), L2060-L2096 (`ixpg`: the count, the record size and four offsets for each page), `CMXParser.h` L24-L41 (the ids); S: every CX file with 32-bit coordinates holds these chunks in this order, its `ixmr` entries name these chunks with these ids, the values 1 and 24 and `ixtl` type 3, its `ixpg` names its one page, the one `ixlr` and the `rlst`, its `ixlr` names its layers' begin-layer instructions with their names and the value 1, its `rlst` holds 2, 9 and the number of each of its layers, and the counts and offsets in its 9 pages, 33 layers and 12 groups match the instructions; 8 of the 12 groups hold the edges of their curves' points | sample (the order, `ixlr`, `rlst`, the values 1 and 24, the counts and offsets in the records), public-reader (the header's offsets, the `ixmr` ids, `ixpg`, `ixtl` and the order of begin group's fields; the samples agree), unconfirmed (the group count counting only the groups directly inside, as no sample nests groups two deep; the value 1 in a layer table of a page after the first) |
|
||||
| R77 | The index of a file with 32-bit coordinates, which the reader does not read. `cont` bytes 84, 88 and 92 hold the u32 file offsets of the master index `ixmr`, of `LIST INFO` and of the picture of the drawing (`DISP`), 0xFFFFFFFF for one the file does not hold. Each offset here names where a chunk's id starts. `cont` bytes 96 to 112 hold four i32 edges, the same bytes as the edges in the page's begin-page record, and bytes 112 to 116 a u32, the page's instruction count as begin page holds it. `LIST indx` holds a layer table `ixlr`, then `ixtl`, `ixpg` and `ixmr`. `ixmr`: the u16 values 1 and 24, a u16 count, then a u16 id and a u32 offset for each entry: 1 `ixmr` itself, 2 `ixpg`, 3 `ixtl`, 15 `rotl`, 16 `rott`, 17 `rota`, 18 `rscr`, 19 `rpen`, 20 `rdot`, 21 `rclr`, 22 `ccmm`; a table the file does not hold has no entry. `ixpg`: a u16 count, then for each page a u16 record size of 16 and four u32: the page chunk, its layer table, its picture (0xFFFFFFFF for none) and its reference list `rlst`. `ixtl`: a u16 count, a u16 record size of 4, the u16 type 3 (layer tables), then the u32 offset of each layer table. `ixlr`: a u16 count of the page's layers and the u16 value 1, then for each layer in file order a u16 size (8 plus the name's length), the u32 offset of its begin-layer instruction, its name as a u16 count and 8-bit characters, and 0xFFFFFFFF after the size. `rlst`: a u16 count of the page's layers, then the u16 values 2 and 9 and the layer's number for each. Begin page's field 1 ends with the u32 offset of the end-page instruction, a u16 count of the page's layers and a u32 count of its instructions, begin and end page included; begin layer's field 1 holds a u32 count of the layer's instructions, begin and end layer included, at bytes 8 to 12; begin group's field 1 holds the left, top, right and bottom edges of its curves (i32), a u16 count of the groups directly inside it, a u32 count of its instructions, begin and end group included, and the u32 offset of the instruction after its end | LC `CMXParser.cpp` L260-L286 (the three offsets, 0xFFFFFFFF for none; four coordinates after them, read only for a debug message), L1011-L1019 (the four coordinates of a box), L346-L413 (`ixmr`: two u16, the count, the id and offset pairs), L545-L590 (begin group: the edges, a u16, the command count and the end address), L1974-L2019 (`ixtl`: the count, the record size, the type), L2060-L2096 (`ixpg`: the count, the record size and four offsets for each page), `CMXParser.h` L24-L41 (the ids); S: every CX file with 32-bit coordinates holds these chunks in this order, its `ixmr` entries name these chunks with these ids, the values 1 and 24 and `ixtl` type 3, its `ixpg` names its one page, the one `ixlr` and the `rlst`, its `ixlr` names its layers' begin-layer instructions with their names and the value 1, its `rlst` holds 2, 9 and the number of each of its layers, and the counts and offsets in its 9 pages, 33 layers and 12 groups match the instructions; in each of the 9 files, `cont` bytes 96 to 116 match its one page's edges and instruction count; 8 of the 12 groups hold the edges of their curves' points | sample (the order, `ixlr`, `rlst`, the values 1 and 24, the counts and offsets in the records, the header's edges and instruction count), public-reader (the header's offsets, the `ixmr` ids, `ixpg`, `ixtl` and the order of begin group's fields; the samples agree), unconfirmed (the group count counting only the groups directly inside, as no sample nests groups two deep; the value 1 in a layer table of a page after the first) |
|
||||
|
||||
## Written fields
|
||||
|
||||
`src/cmx_write.rs` writes `.cmx` files in the layouts of the rows above, nothing else. The table
|
||||
lists every field it sets. `own` marks a value the reader does not read, which the writer sets as
|
||||
the synthetic test files of `src/synth_cmx.rs` set it. The header's bounds and instruction count
|
||||
at bytes 96 to 116 are not written.
|
||||
the synthetic test files of `src/synth_cmx.rs` set it.
|
||||
|
||||
| Field written | Rows | Status |
|
||||
|---|---|---|
|
||||
@@ -170,6 +169,7 @@ at bytes 96 to 116 are not written.
|
||||
| Chunk order: `cont`, each `page` chunk followed by its `rlst`, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr`, then `LIST indx` | R53, R77 | sample (`page`, `rlst`, the tables, `LIST indx`), own (the order of the tables; the `rlst` of a page after the first) |
|
||||
| `cont`: `4` at byte 52, the unit 1e-7 m as an f64 at bytes 64 to 72 | R54 | sample |
|
||||
| `cont`: the offset of `ixmr` at bytes 84 to 88, 0xFFFFFFFF for the information list and the picture at bytes 88 to 96 | R77 | public-reader, sample (the picture), own (no information list) |
|
||||
| `cont`: the first page's edges at bytes 96 to 112 and its instruction count at bytes 112 to 116, as its begin-page record holds them; zeros for a file with no page | R77 | sample (one page), the writer's choice (the first page of several, and zeros) |
|
||||
| `cont`: `2` at bytes 48 and 54, zeros elsewhere, 180 bytes | R54 | own |
|
||||
| `LIST indx`: a layer table `ixlr` for each page, `ixtl` listing them, `ixpg` with each page, and `ixmr` with itself, `ixpg`, `ixtl` and the seven tables | R77 | sample (one page), own (a layer table for each page, `ixtl` listing each, and the page number after the count) |
|
||||
| `rlst` for each page: its layers' numbers | R77 | sample |
|
||||
|
||||
@@ -131,7 +131,7 @@ by their chunk ids, opens it: the header gives where the master index starts, th
|
||||
layer and group records give their instruction counts. A page's record also gives where its
|
||||
end-page instruction starts, and a group's record gives where the instruction after its end-group
|
||||
instruction starts and the edges of its curves. The record of a page with a size holds the edges of its curves, or
|
||||
of the page when it has none. The header's bounds and instruction count are not written.
|
||||
of the page when it has none. The header repeats the first page's edges and instruction count.
|
||||
`PROVENANCE.md`'s "Written fields" table lists every field the `.cmx` writer sets.
|
||||
|
||||
## Writing
|
||||
|
||||
+56
-32
@@ -131,20 +131,20 @@ pub fn write(drawing: &Drawing, limits: crate::Limits) -> Result<Written, Error>
|
||||
Ok(())
|
||||
};
|
||||
// The header's index offset is set once the index is placed.
|
||||
add(chunk(b"cont", &cont(0))?)?;
|
||||
add(chunk(b"cont", &cont(0, PageHead::default()))?)?;
|
||||
// Each page chunk and its reference list, with where they start in the file and the start and
|
||||
// name of each of the page's layers.
|
||||
let mut pages = Vec::new();
|
||||
let mut page = |w: &mut Writer, n: usize, size: Option<(f64, f64)>, layers: &[Layer]| -> Result<(), Error> {
|
||||
let at = w.file_bytes;
|
||||
let (c, written) = w.page(n, size, layers)?;
|
||||
let (c, written, head) = w.page(n, size, layers)?;
|
||||
add(c)?;
|
||||
let refs = w.file_bytes;
|
||||
let r = chunk(b"rlst", &reference_list(written.len()))?;
|
||||
w.check_bytes(r.len())?;
|
||||
w.file_bytes += r.len();
|
||||
add(r)?;
|
||||
pages.push(PageAt { at, refs, layers: written });
|
||||
pages.push(PageAt { at, refs, layers: written, head });
|
||||
Ok(())
|
||||
};
|
||||
for (n, p) in drawing.pages.iter().enumerate() {
|
||||
@@ -181,7 +181,7 @@ pub fn write(drawing: &Drawing, limits: crate::Limits) -> Result<Written, Error>
|
||||
if total > w.limits.input {
|
||||
return Err(Error::Limit("input size"));
|
||||
}
|
||||
children[0] = chunk(b"cont", &cont(ixmr))?;
|
||||
children[0] = chunk(b"cont", &cont(ixmr, pages.first().map(|p| p.head).unwrap_or_default()))?;
|
||||
let mut bytes = Vec::new();
|
||||
bytes.try_reserve_exact(total).map_err(|_| Error::Limit("file size"))?;
|
||||
bytes.extend(b"RIFF");
|
||||
@@ -222,8 +222,9 @@ fn chunk(id: &[u8; 4], body: &[u8]) -> Result<Vec<u8>, Error> {
|
||||
/// The header (R54): the coordinate size digit `4` at byte 52 and the unit in meters at bytes 64
|
||||
/// to 72. Bytes 48 and 54 hold the digit `2`, as in the sample files. Bytes 84 to 96 hold the file
|
||||
/// offset of the master index `ixmr`, then 0xFFFFFFFF for the information list and for the
|
||||
/// picture of the drawing, which the file does not hold (R77); the rest are zeros.
|
||||
fn cont(ixmr: u32) -> Vec<u8> {
|
||||
/// picture of the drawing, which the file does not hold (R77). Bytes 96 to 116 hold the edges and
|
||||
/// the instruction count of `first`, the first page's begin-page record (R77); the rest are zeros.
|
||||
fn cont(ixmr: u32, first: PageHead) -> Vec<u8> {
|
||||
let mut c = vec![0u8; 180];
|
||||
c[48] = b'2';
|
||||
c[52] = b'4';
|
||||
@@ -231,9 +232,21 @@ fn cont(ixmr: u32) -> Vec<u8> {
|
||||
c[64..72].copy_from_slice(&UNIT_METERS.to_le_bytes());
|
||||
c[84..88].copy_from_slice(&ixmr.to_le_bytes());
|
||||
c[88..96].fill(0xFF);
|
||||
for (i, v) in first.edges.iter().enumerate() {
|
||||
c[96 + 4 * i..100 + 4 * i].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
c[112..116].copy_from_slice(&first.instructions.to_le_bytes());
|
||||
c
|
||||
}
|
||||
|
||||
/// What a page's begin-page record holds that the header repeats: its left, top, right and bottom
|
||||
/// edges and its instruction count, begin and end page included.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct PageHead {
|
||||
edges: [i32; 4],
|
||||
instructions: u32,
|
||||
}
|
||||
|
||||
/// Where a layer's begin-layer instruction starts in the file, and the layer's 8-bit name.
|
||||
type LayerAt = (usize, Vec<u8>);
|
||||
|
||||
@@ -243,6 +256,8 @@ struct PageAt {
|
||||
/// The page's reference list `rlst`.
|
||||
refs: usize,
|
||||
layers: Vec<LayerAt>,
|
||||
/// What the header repeats of its begin-page record.
|
||||
head: PageHead,
|
||||
}
|
||||
|
||||
/// A page's reference list (R77): a u16 count of its layers, then for each layer from 1 the u16
|
||||
@@ -733,9 +748,10 @@ impl Writer {
|
||||
}
|
||||
|
||||
/// A `page` chunk: begin page `n` (from 0), its shown layers back to front, end the page (R60),
|
||||
/// with the file offset of each layer's begin-layer instruction and the layer's 8-bit name.
|
||||
/// The chunk starts at the file offset [`Writer::file_bytes`] gives.
|
||||
fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result<(Vec<u8>, Vec<LayerAt>), Error> {
|
||||
/// with the file offset of each layer's begin-layer instruction and the layer's 8-bit name, and
|
||||
/// what the header repeats of the begin-page record. The chunk starts at the file offset
|
||||
/// [`Writer::file_bytes`] gives.
|
||||
fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result<(Vec<u8>, Vec<LayerAt>, PageHead), Error> {
|
||||
let mut out = Vec::new();
|
||||
self.bounds = None;
|
||||
self.instructions = 1;
|
||||
@@ -803,7 +819,7 @@ impl Writer {
|
||||
self.check_bytes(c.len())?;
|
||||
let layers = starts.into_iter().map(|(at, name)| (base.saturating_add(at), name)).collect();
|
||||
self.file_bytes += c.len();
|
||||
Ok((c, layers))
|
||||
Ok((c, layers, PageHead { edges: page_edges(size, bounds)?, instructions: tail.instructions }))
|
||||
}
|
||||
|
||||
/// An [`Error::Limit`] when the file would be longer than the input size of the limits with
|
||||
@@ -1164,29 +1180,15 @@ fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>, tail
|
||||
let mut d = number.to_le_bytes().to_vec();
|
||||
d.extend(0u32.to_le_bytes());
|
||||
let mut list = Vec::new();
|
||||
let mut size_field = None;
|
||||
let mut edges = [0i32; 4];
|
||||
if let Some((w, h)) = size {
|
||||
// A negative or NaN side counts as 0.
|
||||
let (wu, hu) = (width_units(w)?, width_units(h)?);
|
||||
// A side that rounds to nothing would make the reader drop the page's whole size.
|
||||
if wu == 0 || hu == 0 {
|
||||
return Err(Error::Limit("page size"));
|
||||
let edges = page_edges(size, bounds)?;
|
||||
let size_field = match size {
|
||||
Some((w, h)) => {
|
||||
let mut s = width_units(w)?.to_le_bytes().to_vec();
|
||||
s.extend(width_units(h)?.to_le_bytes());
|
||||
Some(s)
|
||||
}
|
||||
edges = match bounds {
|
||||
Some([x0, y0, x1, y1]) => [x0, y1, x1, y0],
|
||||
None => {
|
||||
// The page around its center; an odd size keeps its extra unit on the left and
|
||||
// bottom, where the edge reaches -2^31.
|
||||
let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size"));
|
||||
let (w, h) = (i64::from(wu), i64::from(hu));
|
||||
[edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?]
|
||||
}
|
||||
};
|
||||
let mut s = wu.to_le_bytes().to_vec();
|
||||
s.extend(hu.to_le_bytes());
|
||||
size_field = Some(s);
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
for v in edges {
|
||||
d.extend(v.to_le_bytes());
|
||||
}
|
||||
@@ -1200,6 +1202,28 @@ fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>, tail
|
||||
Ok(instr(BEGIN_PAGE, &fields(&list)))
|
||||
}
|
||||
|
||||
/// The left, top, right and bottom edges begin page holds for a page of `size` whose art reaches
|
||||
/// `bounds`, as [`begin_page`] describes. A page side that rounds to 0 is an [`Error::Limit`].
|
||||
fn page_edges(size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> Result<[i32; 4], Error> {
|
||||
let Some((w, h)) = size else { return Ok([0; 4]) };
|
||||
// A negative or NaN side counts as 0.
|
||||
let (wu, hu) = (width_units(w)?, width_units(h)?);
|
||||
// A side that rounds to nothing would make the reader drop the page's whole size.
|
||||
if wu == 0 || hu == 0 {
|
||||
return Err(Error::Limit("page size"));
|
||||
}
|
||||
Ok(match bounds {
|
||||
Some([x0, y0, x1, y1]) => [x0, y1, x1, y0],
|
||||
None => {
|
||||
// The page around its center; an odd size keeps its extra unit on the left and
|
||||
// bottom, where the edge reaches -2^31.
|
||||
let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size"));
|
||||
let (w, h) = (i64::from(wu), i64::from(hu));
|
||||
[edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?]
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// `c` as a Windows-1252 byte, or `?` when the code page has no byte for it.
|
||||
fn windows_1252_byte(c: char) -> u8 {
|
||||
match u8::try_from(u32::from(c)) {
|
||||
|
||||
@@ -153,8 +153,8 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
|
||||
/// page, layer and group records give their instruction counts. A page's record also gives where
|
||||
/// its end-page instruction starts, and a group's record gives where the instruction after its
|
||||
/// end-group instruction starts and the edges of its curves. The record of a page with a size holds the edges of
|
||||
/// its curves, or of the page when it has none. The header's bounds and instruction count are not
|
||||
/// written.
|
||||
/// its curves, or of the page when it has none. The header repeats the first page's edges and
|
||||
/// instruction count.
|
||||
pub fn write_cmx(drawing: &Drawing, limits: Limits) -> Result<Written, Error> {
|
||||
cmx_write::write(drawing, limits)
|
||||
}
|
||||
@@ -1078,6 +1078,35 @@ fn the_index_and_the_records_give_where_everything_is() {
|
||||
assert_eq!(groups, [(0, 3), (1, 7)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_header_repeats_the_first_pages_edges_and_instruction_count() {
|
||||
let plain = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)));
|
||||
let pages = vec![
|
||||
Page { size: Some((200.0, 100.0)), layers: vec![layer("Front", vec![plain(0.0), plain(20.0)]), layer("Back", vec![plain(5.0)])] },
|
||||
Page { size: Some((300.0, 100.0)), layers: vec![layer("Only", vec![plain(1.0)])] },
|
||||
];
|
||||
let b = write_cmx(&drawing(pages)).unwrap().bytes;
|
||||
let cont = 12 + 8;
|
||||
let chunk = page_index(&b)[0][0];
|
||||
let page = chunk + 8;
|
||||
// Begin page's field 1: the page number, the flags, the edges, the end offset, the layer count
|
||||
// and the instruction count.
|
||||
let fields = field_starts(&b, page + 4, page + instruction_size(&b, page, page + u32_at(&b, chunk + 4)));
|
||||
assert_eq!(fields[0].0, 1);
|
||||
let f1 = fields[0].1;
|
||||
assert_eq!(&b[cont + 96..cont + 112], &b[f1 + 6..f1 + 22]);
|
||||
// The curves of the first page reach from 0 to 30 pt across and 0 to 10 pt down.
|
||||
let edges: Vec<i32> = (0..4).map(|i| i32::from_le_bytes(b[cont + 96 + 4 * i..cont + 100 + 4 * i].try_into().unwrap())).collect();
|
||||
let unit = |pt: f64| (pt * 0.0254 / 72.0 / 1e-7).round() as i32;
|
||||
assert_eq!(edges, [0, unit(10.0), unit(30.0), 0]);
|
||||
// Begin and end page, two begin and end layers and three curves.
|
||||
assert_eq!(u32_at(&b, cont + 112), 9);
|
||||
assert_eq!(u32_at(&b, f1 + 28), 9);
|
||||
// A drawing without pages leaves them 0.
|
||||
let b = write_cmx(&drawing(Vec::new())).unwrap().bytes;
|
||||
assert!(b[cont + 96..cont + 116].iter().all(|v| *v == 0));
|
||||
}
|
||||
|
||||
/// The page index of a written file of two pages, each entry's page chunk, layer table, picture
|
||||
/// and reference list, checked through the header and the master index.
|
||||
fn page_index(b: &[u8]) -> Vec<[usize; 4]> {
|
||||
|
||||
@@ -68,7 +68,7 @@ pub use paint_chip::{
|
||||
PaintListEvent, PaintListOptions, PaintListOutput, PaintRow, PaintWords,
|
||||
};
|
||||
pub use pair::{DropAccepts, PairWell, SwatchPair, SwatchPairOutput, Well};
|
||||
pub use palette::{SwatchPalette, SwatchPaletteOutput};
|
||||
pub use palette::{PaletteCell, SwatchPalette, SwatchPaletteOutput};
|
||||
pub use panel::{
|
||||
ColorPanel, ColorPanelAction, ColorPanelCommand, ColorPanelLayout, ColorPanelMenu, ColorPanelMode, ColorPanelOutput, ColorPanelRamp,
|
||||
ColorPanelShown, ColorPanelState, ColorPanelWords, PanelTarget, TintRow,
|
||||
|
||||
@@ -38,6 +38,18 @@ pub struct SwatchPaletteOutput {
|
||||
/// The picked entry's index in the palette, including a swatch with the bound colour or a duplicate colour.
|
||||
/// The recent row and the Other… cell do not report a swatch index.
|
||||
pub picked_swatch: Option<usize>,
|
||||
/// The cell `picked` came from, so a host can tell apart cells that show the same color.
|
||||
pub cell: Option<PaletteCell>,
|
||||
}
|
||||
|
||||
/// A cell of a [`SwatchPalette`] by its place in the host's lists.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum PaletteCell {
|
||||
/// The swatch at this index of the palette's swatches.
|
||||
Swatch(usize),
|
||||
/// The color at this index of the recent row's colors.
|
||||
Recent(usize),
|
||||
}
|
||||
|
||||
impl Outcome for SwatchPaletteOutput {
|
||||
@@ -112,8 +124,8 @@ impl PaletteColor<'_> {
|
||||
/// What the body picked in its pass.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Pick {
|
||||
/// A swatch or a recent colour.
|
||||
Color { color: Srgba, swatch: Option<usize> },
|
||||
/// A swatch or a recent color, and its cell.
|
||||
Color(Srgba, PaletteCell),
|
||||
/// The Other… cell.
|
||||
Other,
|
||||
}
|
||||
@@ -235,7 +247,7 @@ impl<'a> SwatchPalette<'a> {
|
||||
// The Other… cell is keyed `swatches.len()`, past the swatches. A click selects on its press and activates
|
||||
// on its release, so only the activation files the request: one request for one click.
|
||||
pick = picked_cell(&table, ui).and_then(|at| match swatches.get(at) {
|
||||
Some((_, picked)) => Some(Pick::Color { color: *picked, swatch: Some(at) }),
|
||||
Some((_, picked)) => Some(Pick::Color(*picked, PaletteCell::Swatch(at))),
|
||||
None => (other.is_some() && table.open == Some(at) && at == swatches.len()).then_some(Pick::Other),
|
||||
});
|
||||
}
|
||||
@@ -249,8 +261,8 @@ impl<'a> SwatchPalette<'a> {
|
||||
.space(SpaceAction::ActivateLead)
|
||||
.selection(Bind::bound(&mut current))
|
||||
.show_all(ui);
|
||||
if let Some((_, picked)) = picked_cell(&row, ui).and_then(|at| recent_cells.get(at)) {
|
||||
pick = Some(Pick::Color { color: *picked, swatch: None });
|
||||
if let Some((at, (_, picked))) = picked_cell(&row, ui).and_then(|at| recent_cells.get(at).map(|cell| (at, cell))) {
|
||||
pick = Some(Pick::Color(*picked, PaletteCell::Recent(at)));
|
||||
}
|
||||
}
|
||||
Some((before, pick))
|
||||
@@ -265,19 +277,23 @@ impl<'a> SwatchPalette<'a> {
|
||||
let key = other.as_ref().map(|(key, _)| key.clone())?;
|
||||
Some((None, None, Some(ColorRequest::new(key, bound).title(name.clone())), None))
|
||||
}
|
||||
Pick::Color { color: after, swatch } => {
|
||||
Pick::Color(after, cell) => {
|
||||
let unchanged = bound.is_some_and(|bound| bound.to_rgba() == after.to_rgba());
|
||||
let edit = (!unchanged).then(|| {
|
||||
color.write(cx, before, after, name.as_str());
|
||||
let reported = bound.map_or(Mixed::Mixed, Mixed::Same);
|
||||
EditEvent::set(reported, after, Arc::from(name.as_str()), None)
|
||||
});
|
||||
Some((Some(after), edit, None, swatch))
|
||||
Some((Some(after), edit, None, Some(cell)))
|
||||
}
|
||||
}
|
||||
})
|
||||
.flatten();
|
||||
let (picked, edit, pick_color, picked_swatch) = settled.unwrap_or((None, None, None, None));
|
||||
SwatchPaletteOutput { response: shown.output, edit, pick_color, picked, picked_swatch }
|
||||
let (picked, edit, pick_color, cell) = settled.unwrap_or((None, None, None, None));
|
||||
let picked_swatch = match cell {
|
||||
Some(PaletteCell::Swatch(at)) => Some(at),
|
||||
_ => None,
|
||||
};
|
||||
SwatchPaletteOutput { response: shown.output, edit, pick_color, picked, picked_swatch, cell }
|
||||
}
|
||||
}
|
||||
@@ -452,6 +452,7 @@ pub struct ColorPanel<'a> {
|
||||
edited: Option<Option<PickedColor>>,
|
||||
shown: Option<ColorPanelShown>,
|
||||
recent: Option<&'a [Srgba]>,
|
||||
recent_models: &'a [Option<ModelValues>],
|
||||
recent_setup: Option<RecentSetup>,
|
||||
gamut: Option<Gamut<'a>>,
|
||||
}
|
||||
@@ -476,6 +477,7 @@ struct Inputs<'a> {
|
||||
edited: Option<&'a Option<PickedColor>>,
|
||||
shown: &'a ColorPanelShown,
|
||||
recent: Option<&'a [Srgba]>,
|
||||
recent_models: &'a [Option<ModelValues>],
|
||||
recent_setup: Option<&'a RecentSetup>,
|
||||
}
|
||||
|
||||
@@ -494,6 +496,7 @@ impl<'a> ColorPanel<'a> {
|
||||
edited: None,
|
||||
shown: None,
|
||||
recent: None,
|
||||
recent_models: &[],
|
||||
recent_setup: None,
|
||||
gamut: None,
|
||||
}
|
||||
@@ -563,6 +566,15 @@ impl<'a> ColorPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The model values of each Recent Colors chip, in the order of [`recent`](Self::recent). A pick on a chip that has
|
||||
/// them reports them with its color (`PickedColor::in_model`), so a CMYK recent color stays CMYK, and a chip
|
||||
/// that shows the edited color's sRGB in another model still sets it. A chip with `None`, or past the end of
|
||||
/// `models`, works as without this call: a pick sets its sRGB, and a pick of the color already shown sets nothing.
|
||||
pub fn recent_models(mut self, models: &'a [Option<ModelValues>]) -> Self {
|
||||
self.recent_models = models;
|
||||
self
|
||||
}
|
||||
|
||||
/// The payload a Recent Colors chip drags.
|
||||
pub fn recent_payload<P: Send + Sync + 'static>(mut self, map: impl Fn(usize) -> Option<P> + Send + Sync + 'static) -> Self {
|
||||
self.recent_setup = Some(recent_setup(map));
|
||||
@@ -577,7 +589,8 @@ impl<'a> ColorPanel<'a> {
|
||||
|
||||
/// Shows the panel and returns this pass's edits and requests.
|
||||
pub fn show(self, ui: &mut Ui) -> ColorPanelOutput {
|
||||
let ColorPanel { state, colors, cmyk, rgb, dynamic, layout, wells, buttons, edited, shown: rows, recent, recent_setup, gamut } = self;
|
||||
let ColorPanel { state, colors, cmyk, rgb, dynamic, layout, wells, buttons, edited, shown: rows, recent, recent_models, recent_setup, gamut } =
|
||||
self;
|
||||
let env = Env::of(ui);
|
||||
let (words, dialog) = (env.words::<ColorPanelWords>(), env.words::<ColorPickerDialogWords>());
|
||||
let mut held = Held::new(state);
|
||||
@@ -617,6 +630,7 @@ impl<'a> ColorPanel<'a> {
|
||||
edited: edited.as_ref(),
|
||||
shown: rows.as_ref().unwrap_or(&default_rows),
|
||||
recent,
|
||||
recent_models,
|
||||
recent_setup: recent_setup.as_ref(),
|
||||
},
|
||||
now: before,
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! same `Body` as the Photoshop layout and shares its rows, wells, warnings and ramp helpers.
|
||||
|
||||
use craft_behavior::{EditEvent, Mixed};
|
||||
use craft_theme::Srgba;
|
||||
use craft_theme::{ModelValues, Srgba};
|
||||
use craft_ui::choice::{Swatch, SwatchSpacing};
|
||||
use craft_ui::contract::{Bind, Gap, LabelScheme, Props as _, Scroll, Show as _, ShowContainer as _, Sizing};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
@@ -15,7 +15,7 @@ use craft_ui::text::{HexField, TextField};
|
||||
use egui::Ui;
|
||||
|
||||
use super::{Body, ColorPanelMode, ColorPanelShown, PanelTarget, TintRow};
|
||||
use crate::ui::{ChannelRow, ChannelRule, ChannelUnit, ColorRamp, PickedColor, RampKind, SwatchPalette};
|
||||
use crate::ui::{ChannelRow, ChannelRule, ChannelUnit, ColorRamp, PaletteCell, PickedColor, RampKind, SwatchPalette};
|
||||
|
||||
impl Body<'_> {
|
||||
/// The layout. The options (rows, quick wells, recent colours) go when the state hides them; the proxy and the
|
||||
@@ -156,8 +156,8 @@ impl Body<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Recent Colors caption over a spaced palette; a pick sets the color. The caption shows while the host's list
|
||||
/// is empty, where the first applied color will go.
|
||||
/// The Recent Colors caption over a spaced palette; a pick sets the color, in the chip's model when the host gave it.
|
||||
/// The caption shows while the host's list is empty, where the first applied color will go.
|
||||
// PLAN: Alt on a recent colour or a warning chip should set the other colour; `SwatchPaletteOutput` and
|
||||
// `ColorWarningChipOutput` report no modifiers (color-w1 for the palette, the owner of warning.rs for the chip).
|
||||
fn recent(&mut self, ui: &mut Ui) {
|
||||
@@ -174,13 +174,34 @@ impl Body<'_> {
|
||||
if let Some(setup) = self.inputs.recent_setup {
|
||||
palette = setup(palette);
|
||||
}
|
||||
if let Some(event) = palette.show(ui).edit
|
||||
let out = palette.show(ui);
|
||||
let values = match out.cell {
|
||||
Some(PaletteCell::Swatch(at)) => self.inputs.recent_models.get(at).copied().flatten(),
|
||||
_ => None,
|
||||
};
|
||||
if let (Some(color), Some(values)) = (out.picked, values) {
|
||||
self.set_in_model(color, values);
|
||||
} else if let Some(event) = out.edit
|
||||
&& let Some(color) = event.value()
|
||||
{
|
||||
self.set_color(self.target, *color);
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the edited color to `color` in the model of `values`, keeping its alpha. It sets nothing when the host's
|
||||
/// color already has those values and shows that color.
|
||||
fn set_in_model(&mut self, color: Srgba, values: ModelValues) {
|
||||
let before = self.picked().copied().unwrap_or_else(|| PickedColor::rgb(self.colors[self.target.index()]));
|
||||
let after = PickedColor::in_model(color.with_alpha(before.color.a), values);
|
||||
if before.model == after.model && before.color.to_rgba() == after.color.to_rgba() {
|
||||
return;
|
||||
}
|
||||
// The rows' kept values in the chip's model would win over a host that keeps only sRGB (a grey's HSB hue).
|
||||
self.kept.values[self.target.index()].retain(|v| v.model != values.model);
|
||||
let name = self.words.title.as_str();
|
||||
self.push(self.target, EditEvent::set(Mixed::Same(before), after, name.into(), None));
|
||||
}
|
||||
|
||||
/// Sets `target`'s colour to `color`, keeping its alpha.
|
||||
fn set_color(&mut self, target: PanelTarget, color: Srgba) {
|
||||
let before = self.colors[target.index()];
|
||||
|
||||
@@ -8,11 +8,11 @@ use craft_behavior::{EditEvent, Mixed, Selection};
|
||||
use craft_color_ui::palette::{SwatchColor, SwatchGroup};
|
||||
use craft_color_ui::ui::{
|
||||
ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel,
|
||||
PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState,
|
||||
SwatchesWords, swatch_rows,
|
||||
PaletteCell, PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel,
|
||||
SwatchesState, SwatchesWords, swatch_rows,
|
||||
};
|
||||
use craft_host::target::Os;
|
||||
use craft_theme::{ColorModel as _, HsbModel, Srgba};
|
||||
use craft_theme::{ColorModel as _, HsbModel, ModelValues, Srgba};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::choice::SwatchTable;
|
||||
use craft_ui::contract::Role;
|
||||
@@ -367,6 +367,88 @@ fn the_fill_stroke_spectrums_tooltip_names_the_shown_mode_and_shift_click_cycles
|
||||
assert!(edits.borrow().is_empty(), "a Shift click picks nothing: {:?}", edits.borrow());
|
||||
}
|
||||
|
||||
/// A Recent Colors pick in the FillStroke layout reports the chip's model values with its color, also when the chip
|
||||
/// shows the edited color's sRGB in another model or without one; a chip whose values the edited color already has
|
||||
/// sets nothing.
|
||||
#[trial]
|
||||
fn a_fill_stroke_recent_pick_keeps_the_chips_model() {
|
||||
let chip = RECENT[0];
|
||||
let cmyk = ModelValues::new("cmyk", &[60.0, 90.0, 0.0, 0.0]);
|
||||
let pick = |edited: PickedColor| {
|
||||
let edits: Edits = Default::default();
|
||||
let seen = Rc::clone(&edits);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut state = ColorPanelState::default();
|
||||
let out = ColorPanel::new(Bind::bound(&mut state), [edited.color, BLUE])
|
||||
.layout(ColorPanelLayout::FillStroke)
|
||||
.edited(Some(edited))
|
||||
.recent(&RECENT)
|
||||
.recent_models(&[Some(cmyk)])
|
||||
.show(ui);
|
||||
seen.borrow_mut().extend(out.edits);
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
let recent = fixture.by_label(&chip.to_hex()).expect("the recent chip is named by its hex");
|
||||
fixture.click(&recent).settle();
|
||||
edits.take()
|
||||
};
|
||||
let rgb_of = |color: Srgba| ModelValues::new("rgb", &[color.r * 255.0, color.g * 255.0, color.b * 255.0]);
|
||||
for edited in [PickedColor::in_model(RED, rgb_of(RED)), PickedColor::in_model(chip, rgb_of(chip)), PickedColor::rgb(chip)] {
|
||||
let edits = pick(edited);
|
||||
assert!(
|
||||
matches!(edits.as_slice(), [(PanelTarget::Foreground, EditEvent::Set { after, .. })]
|
||||
if after.model == Some(cmyk) && after.color.to_rgba() == chip.to_rgba()),
|
||||
"one Set to the chip in CMYK from {edited:?}: {edits:?}"
|
||||
);
|
||||
}
|
||||
let edits = pick(PickedColor::in_model(chip, cmyk));
|
||||
assert!(edits.is_empty(), "the chip's own values set nothing: {edits:?}");
|
||||
}
|
||||
|
||||
/// A Recent Colors pick drops the HSB values the rows kept for a grey: after a host that keeps only sRGB applies a grey
|
||||
/// chip with HSB values, the Hue row reads the grey afresh instead of the hue of the earlier row edits.
|
||||
#[trial]
|
||||
fn a_fill_stroke_recent_pick_drops_the_rows_kept_hue() {
|
||||
let grey = Srgba::rgb(0.5, 0.5, 0.5);
|
||||
let chip = [grey];
|
||||
let chip_hsb = ModelValues::new("hsb", &[0.0, 0.0, 50.0]);
|
||||
let host = Rc::new(RefCell::new(grey));
|
||||
let color = Rc::clone(&host);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let current = *color.borrow();
|
||||
let mut state = ColorPanelState { mode: ColorPanelMode::HsbSliders, ..Default::default() };
|
||||
let shown = ColorPanel::new(Bind::bound(&mut state), [current, BLUE])
|
||||
.layout(ColorPanelLayout::FillStroke)
|
||||
.edited(Some(PickedColor::rgb(current)))
|
||||
.shown(ColorPanelShown::Mode(ColorPanelMode::HsbSliders))
|
||||
.recent(&chip)
|
||||
.recent_models(&[Some(chip_hsb)])
|
||||
.show(ui);
|
||||
for (_, event) in &shown.edits {
|
||||
if let Some(picked) = event.landed() {
|
||||
*color.borrow_mut() = picked.color;
|
||||
}
|
||||
}
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
let hue = fixture.by_role(Role::SLIDER).into_iter().next().expect("the hue slider");
|
||||
fixture.access(AccessActionKind::Focus, &hue).settle();
|
||||
for _ in 0..20 {
|
||||
fixture.key(Key::ArrowRight, Modifiers::NONE).settle();
|
||||
}
|
||||
let hue_value = |fixture: &mut Fixture| {
|
||||
let hue = fixture.by_role(Role::SLIDER).into_iter().next().expect("the hue slider");
|
||||
fixture.access(AccessActionKind::Focus, &hue).settle();
|
||||
let id = fixture.focused().expect("the hue slider takes the focus");
|
||||
fixture.tree().value(id).expect("the hue slider reports its value").to_owned()
|
||||
};
|
||||
let stepped = hue_value(&mut fixture);
|
||||
assert_ne!(stepped, "0", "the steps moved the kept hue of the grey");
|
||||
let recent = fixture.by_label(&grey.to_hex()).expect("the recent chip is named by its hex");
|
||||
fixture.click(&recent).settle();
|
||||
assert_eq!(hue_value(&mut fixture), "0", "the pick drops the kept hue {stepped}");
|
||||
}
|
||||
|
||||
/// In a host sized by its content (a floating Color panel) the FillStroke spectrum is as tall as its end boxes stacked,
|
||||
/// each at least as tall as it is wide, not a thin band; in a short group it keeps that height and the body scrolls.
|
||||
#[trial]
|
||||
@@ -471,6 +553,7 @@ struct PaletteReports {
|
||||
edits: Vec<EditEvent<Srgba>>,
|
||||
requests: Vec<ColorRequest>,
|
||||
picked: Vec<Srgba>,
|
||||
cells: Vec<PaletteCell>,
|
||||
swatches: Vec<usize>,
|
||||
}
|
||||
|
||||
@@ -482,6 +565,7 @@ fn collect(reports: &Reports, shown: craft_color_ui::ui::SwatchPaletteOutput) {
|
||||
reports.edits.extend(shown.edit);
|
||||
reports.requests.extend(shown.pick_color);
|
||||
reports.picked.extend(shown.picked);
|
||||
reports.cells.extend(shown.cell);
|
||||
reports.swatches.extend(shown.picked_swatch);
|
||||
}
|
||||
|
||||
@@ -539,11 +623,13 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() {
|
||||
taken.edits[0]
|
||||
);
|
||||
assert_eq!(bound.get().to_rgba(), RECENT[0].to_rgba(), "the recent pick is written");
|
||||
assert_eq!(taken.cells, [PaletteCell::Recent(0)], "the pick names its cell in the recent row");
|
||||
|
||||
let violet = fixture.by_label("Violet").expect("violet");
|
||||
fixture.click(&violet).settle();
|
||||
let _ = std::mem::take(&mut *reports.borrow_mut());
|
||||
let taken = std::mem::take(&mut *reports.borrow_mut());
|
||||
assert_eq!(bound.get().to_rgba(), swatch("Violet").to_rgba());
|
||||
assert_eq!(taken.cells, [PaletteCell::Swatch(5)], "the pick names its swatch");
|
||||
// Past the double-click time, so the repeat is a single click of its own.
|
||||
fixture.advance(1.0);
|
||||
let violet = fixture.by_label("Violet").expect("violet");
|
||||
|
||||
@@ -226,6 +226,7 @@ craft-gpu-device = { workspace = true, optional = true }
|
||||
craft-gpu-null = { workspace = true, optional = true }
|
||||
craft-gpu-providers = { workspace = true, optional = true }
|
||||
craft-gpu-wgpu = { workspace = true, optional = true }
|
||||
craft-gpu-yuv = { workspace = true, optional = true }
|
||||
craft-ipp = { workspace = true, optional = true }
|
||||
craft-ppt-binary = { workspace = true, optional = true }
|
||||
craft-sqlite = { workspace = true, optional = true }
|
||||
@@ -552,6 +553,8 @@ gpu-wgpu-native-gles = ["gpu-wgpu", "craft-gpu-wgpu/native-gles"]
|
||||
gpu-wgpu-native-metal = ["gpu-wgpu", "craft-gpu-wgpu/native-metal"]
|
||||
gpu-wgpu-native-vulkan = ["gpu-wgpu", "craft-gpu-wgpu/native-vulkan"]
|
||||
|
||||
gpu-yuv = ["dep:craft-gpu-yuv"]
|
||||
|
||||
gridcraft-format = ["dep:craft-gridcraft-format"]
|
||||
|
||||
gzip = ["dep:craft-gzip"]
|
||||
@@ -703,6 +706,8 @@ pages = ["dep:craft-pages", "keymap", "text"]
|
||||
palette = ["dep:craft-palette"]
|
||||
|
||||
pbr = ["dep:craft-pbr"]
|
||||
pbr-materialx = ["pbr", "craft-pbr/materialx"]
|
||||
pbr-mesh = ["pbr", "craft-pbr/mesh"]
|
||||
pbr-parallel = ["pbr", "craft-pbr/parallel"]
|
||||
|
||||
pcap = ["dep:craft-pcap"]
|
||||
@@ -942,7 +947,12 @@ text-ukrainian = ["text", "craft-text/ukrainian"]
|
||||
|
||||
texture = ["dep:craft-texture"]
|
||||
texture-dds = ["texture", "craft-texture/dds"]
|
||||
texture-decode = ["texture", "craft-texture/decode"]
|
||||
texture-exr = ["texture", "craft-texture/exr"]
|
||||
texture-hdr = ["texture", "craft-texture/hdr"]
|
||||
texture-parallel = ["texture", "craft-texture/parallel"]
|
||||
texture-png = ["texture", "craft-texture/png"]
|
||||
texture-tiff = ["texture", "craft-texture/tiff"]
|
||||
|
||||
tga = ["dep:craft-tga"]
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ craft = { workspace = true, features = ["ui", "color-ui", "draw", "imaging", "ke
|
||||
## Features
|
||||
|
||||
- One feature per crate, named after the crate without `craft-`: `color-ui` turns on `craft-color-ui` and re-exports it as `craft::color_ui`.
|
||||
- `gpu-yuv` enables the GPU YUV provider through `craft::gpu_yuv`.
|
||||
- `ui` turns on `craft-ui` (`craft::ui`), re-exports `egui` (`craft::egui`, the egui the library is built with) and forwards `ui` to every enabled crate.
|
||||
- `screen-testing` implies `ui` and forwards to every enabled crate.
|
||||
- Each crate feature is forwarded as `<crate>-<feature>` (`platform-appearance`, `text-hyphen`, `ui-window-frame`).
|
||||
|
||||
@@ -169,6 +169,8 @@ pub use craft_gpu_null as gpu_null;
|
||||
pub use craft_gpu_providers as gpu_providers;
|
||||
#[cfg(feature = "gpu-wgpu")]
|
||||
pub use craft_gpu_wgpu as gpu_wgpu;
|
||||
#[cfg(feature = "gpu-yuv")]
|
||||
pub use craft_gpu_yuv as gpu_yuv;
|
||||
#[cfg(feature = "gridcraft-format")]
|
||||
pub use craft_gridcraft_format as gridcraft_format;
|
||||
#[cfg(feature = "gzip")]
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "craft-gpu-yuv"
|
||||
description = "RGBA to NV12, P010 and I420 on the GPU with scaling, in BT.601, BT.709 and BT.2020 at limited or full range, as a craft-gpu provider, with a CPU reference of the same conversion"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-gpu = { workspace = true }
|
||||
wgpu = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
pollster = { workspace = true }
|
||||
|
||||
# The device tests (src/tests.rs) open a native adapter. The backends are on for this crate's own
|
||||
# tests only; crates that depend on craft-gpu-yuv get the workspace wgpu with `std` and `wgsl`.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
|
||||
wgpu = { workspace = true, features = ["dx12", "metal", "vulkan", "gles"] }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-gpu-null = { workspace = true }
|
||||
pollster = { workspace = true }
|
||||
# The independent reference the oracle tests compare with (BSD-3-Clause OR Apache-2.0).
|
||||
yuv = { version = "0.8.20", default-features = false, features = ["professional_mode"] }
|
||||
@@ -0,0 +1,148 @@
|
||||
# craft-gpu-yuv
|
||||
|
||||
RGBA to 4:2:0 Y'CbCr for the Craft apps' encoders and scopes: NV12, P010 and I420, scaled to the
|
||||
output size, in the BT.601, BT.709 and BT.2020 matrices at limited or full range. `YuvProvider` is
|
||||
the `craft.yuv` provider of the `craft-gpu` job layer. `Converter` records the same conversion as
|
||||
render passes into a caller's own encoder, and `cpu::convert` is the same conversion on the CPU.
|
||||
|
||||
Licensed under MIT OR Apache-2.0.
|
||||
|
||||
## Contents
|
||||
|
||||
| Item | What |
|
||||
|---|---|
|
||||
| `YuvProvider` | the `craft.yuv` `GpuProvider`; `new()` converts on the CPU on any `GpuContext`, `with_device(device, queue)` converts with the render passes on that device (not on `wasm32`) |
|
||||
| `YuvJob` | one job's conversion, source size and output size; `params()` writes them, `parse` reads them, `job(input)` makes the `GpuJob` |
|
||||
| `PROVIDER_ID` | `"craft.yuv"` |
|
||||
| `Format` | `Nv12` (8-bit luma, then interleaved Cb and Cr), `P010` (10-bit values in the high bits of little-endian 16-bit words, same planes as NV12) and `I420` (8-bit luma, Cb, then Cr) |
|
||||
| `Matrix`, `Range` | BT.601, BT.709 and BT.2020 non-constant luminance; limited range (luma 16 to 235, chroma 16 to 240, times 4 at 10 bits) or full range (every code, chroma centered on 128 or 512) |
|
||||
| `Conversion` | one format, matrix and range |
|
||||
| `Converter::new(device, conversion)` | the two render pipelines of one conversion; no per-frame state |
|
||||
| `Converter::bind(device, view)` | a source texture view bound once, as a `Source` |
|
||||
| `Converter::planes(device, width, height)` | the plane textures of one output size, as `Planes` |
|
||||
| `Converter::draw(encoder, source, planes)` | records a luma pass and a chroma pass |
|
||||
| `Planes::copy_to_buffer(encoder, buffer, offset)` | records the copies of every plane into a read-back buffer |
|
||||
| `FrameLayout` | each plane's size, its offset and row pitch in a read-back buffer (`buffer_size`), and the size of a packed frame (`frame_bytes`); `unpack` copies a mapped buffer into a packed frame |
|
||||
| `cpu::convert(rgba, src_width, src_height, conversion, width, height)` | the conversion of an RGBA8 picture on the CPU, as one packed frame |
|
||||
|
||||
## Jobs
|
||||
|
||||
A host registers `YuvProvider` in a `ProviderRegistry` and dispatches jobs made by `YuvJob::job`:
|
||||
|
||||
```rust
|
||||
let mut registry = craft_gpu::ProviderRegistry::new();
|
||||
registry.register(Box::new(craft_gpu_yuv::YuvProvider::new()));
|
||||
let input = ctx.upload_buffer("rgba", &rgba)?;
|
||||
let job = craft_gpu_yuv::YuvJob::new(conversion, 1920, 1080, 1280, 720).job(input);
|
||||
let outcome = registry.dispatch(&mut ctx, &job)?;
|
||||
let frame = ctx.read_buffer(outcome.outputs[0])?;
|
||||
```
|
||||
|
||||
A job has one input, an RGBA8 buffer of exactly `src_width × src_height × 4` bytes, and no
|
||||
outputs; its outcome has one output, a new buffer that holds the packed frame. The parameters are
|
||||
ASCII `key:value` fields separated by `;`:
|
||||
`fmt:nv12;matrix:bt709;range:limited;sw:1920;sh:1080;w:1280;h:720`. `fmt` is `nv12`, `p010` or
|
||||
`i420`, `matrix` is `bt601`, `bt709` or `bt2020`, `range` is `limited` or `full`, and the four sides
|
||||
are decimal digits.
|
||||
|
||||
The provider checks the job against the context's `DeviceCaps` on every context, the null one
|
||||
included: each source and output side must be at most `max_texture_dimension_2d`, and the
|
||||
read-back layout with its padded rows (`FrameLayout::buffer_size`) and the RGBA8 input at most
|
||||
`max_buffer_size` bytes. Each output side must also be at most `cpu::MAX_SIDE` (16384), with or
|
||||
without a device. It checks the input's length before reading it. A
|
||||
malformed, missing, repeated or unknown parameter, a wrong input count or length, and a size the
|
||||
caps or the conversion do not allow are `GpuFault::InvalidJob`. With a device, the provider also
|
||||
checks the device's own limits, and an error the device reports during the job is
|
||||
`GpuFault::Operation`. Each conversion's pipelines are made once per provider.
|
||||
|
||||
`YuvProvider::new()` runs `cpu::convert`, so a consumer's tests and CI run on `craft-gpu-null`
|
||||
without a graphics adapter. `YuvProvider::with_device` runs the render passes on the given device
|
||||
and waits for each job to finish; the input and the output still move through the context's
|
||||
buffers.
|
||||
|
||||
## Plane layout
|
||||
|
||||
A packed frame of `w × h` (both even) holds its planes one after another, each row without
|
||||
padding:
|
||||
|
||||
| Format | Plane | Offset | Row bytes | Rows |
|
||||
|---|---|---|---|---|
|
||||
| NV12 | Y' | 0 | `w` | `h` |
|
||||
| NV12 | Cb, Cr interleaved | `w·h` | `w` | `h/2` |
|
||||
| P010 | Y' | 0 | `2w` | `h` |
|
||||
| P010 | Cb, Cr interleaved | `2w·h` | `2w` | `h/2` |
|
||||
| I420 | Y' | 0 | `w` | `h` |
|
||||
| I420 | Cb | `w·h` | `w/2` | `h/2` |
|
||||
| I420 | Cr | `w·h + w·h/4` | `w/2` | `h/2` |
|
||||
|
||||
A frame is `1.5·w·h` bytes in NV12 and I420 and `3·w·h` bytes in P010. Each P010 word holds the
|
||||
10-bit value in its high bits, with the 6 low bits zero. NV12 and I420 follow the W3C WebCodecs
|
||||
definitions (<https://www.w3.org/TR/webcodecs/#enumdef-videopixelformat>), and NV12 and P010 follow
|
||||
the Linux media API's sample images
|
||||
(<https://docs.kernel.org/userspace-api/media/v4l/pixfmt-yuv-planar.html>).
|
||||
|
||||
In a read-back buffer, `FrameLayout` pads each row to a multiple of
|
||||
`wgpu::COPY_BYTES_PER_ROW_ALIGNMENT` (256) bytes, as a texture-to-buffer copy needs, and puts each
|
||||
plane right after the previous plane's padded rows. `FrameLayout::unpack` removes the padding.
|
||||
|
||||
## Code values
|
||||
|
||||
Luma and chroma follow BT.601-7 section 2.5, BT.709-6 items 3.2 to 3.5 and BT.2020-2 tables 4 and
|
||||
5 at limited range, and BT.2100-3 table 9 at full range. A half rounds away from zero, as `INT` in
|
||||
BT.709 and BT.2020 and `Round` in BT.2100 do, so a full-range Cb or Cr that computes to 0.5 is
|
||||
code 1.
|
||||
|
||||
## Sampling
|
||||
|
||||
The source is scaled to the output size; the caller keeps the aspect ratio. Each output texel
|
||||
(luma at the output size, chroma at half the output size in both directions) takes the average
|
||||
of up to 4 × 4 bilinear taps spread over the part of the source it covers: 1 tap per axis while
|
||||
the source is at most twice the plane's size, and one more for each further 2:1 of reduction.
|
||||
At the same size, each chroma sample is the average of the 2 × 2 pixels it covers, and its
|
||||
position is the center of those pixels. A reduction of more than 8:1 along an axis skips part of
|
||||
the source between taps.
|
||||
|
||||
`cpu::convert` scales with these same taps rather than with a resampling crate such as
|
||||
`fast_image_resize`, because it is the reference the shader is tested against, and a different
|
||||
kernel would differ from the shader at every edge. A caller that wants another filter on the CPU
|
||||
can resize first with such a crate and convert at the same size.
|
||||
|
||||
The passes write unsigned-integer textures (`R8Uint`, `Rg8Uint`, `R16Uint`, `Rg16Uint`), so P010
|
||||
does not need wgpu's 16-bit norm feature.
|
||||
|
||||
## Limits
|
||||
|
||||
- The matrix applies to the stored values: the source must already be in the output's primaries
|
||||
and transfer function. An sRGB view of the source gives linear values, which the matrix does
|
||||
not expect; bind a non-sRGB view. Alpha is ignored, so premultiplied pixels convert as if they
|
||||
were over black.
|
||||
- Output sides must be even and not zero (`Error::OutputSize`), and no larger than the device's
|
||||
largest 2D texture (`Error::TooLarge`). A layout whose byte sizes do not fit in `u32` rows, `u64`
|
||||
offsets or a `usize` frame is `Error::Overflow`. `Converter::planes` refuses a read-back layout
|
||||
larger than the device's largest buffer (`Error::BufferLimit`), and `cpu::convert` refuses an
|
||||
output side over `cpu::MAX_SIDE` (16384).
|
||||
- The source view must be a 2D view of a filterable float format, such as `Rgba8Unorm`,
|
||||
`Bgra8Unorm` or `Rgba16Float`.
|
||||
- `copy_to_buffer` needs an offset that is a multiple of `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`
|
||||
(`Error::Offset`) and a buffer of at least `buffer_size` bytes from it (`Error::BufferSize`).
|
||||
`draw` refuses planes made for another format (`Error::Mismatch`).
|
||||
|
||||
## Tests
|
||||
|
||||
- `oracle_tests.rs` checks the conversion against sources outside the crate. It computes the
|
||||
code values of 729 colors in `f64` from each recommendation's Kr, Kb and quantization, and
|
||||
checks the nominal levels the recommendations state (white, black, neutral chroma and the
|
||||
chroma extremes). It compares every format, matrix and range with the `yuv` crate's conversion
|
||||
of the same pictures (`yuv` 0.8, a dev-dependency), within 1 code value at 8 bits and 2 at
|
||||
10 bits. It checks the packed plane sizes against the planes `yuv` allocates, and a 4 × 4 frame
|
||||
against the byte offsets of the public format definitions. The GPU passes are checked against
|
||||
the same equations, within 1 code value.
|
||||
- `job_tests.rs` runs `craft.yuv` through a `ProviderRegistry` on `craft-gpu-null`, and with a
|
||||
device. It checks the parameters, the inputs and outputs, the caps limits, and a device whose
|
||||
limits are smaller than the context's.
|
||||
- `tests.rs` checks standard code values, each format's plane order, the area average of a
|
||||
reduction and the read-back layout. It also compares the GPU passes with `cpu::convert` on
|
||||
pictures with hard edges at the same size and on smooth pictures at five scales, within 2 code
|
||||
values at 8 bits and 6 at 10 bits.
|
||||
|
||||
A machine without a graphics adapter skips the GPU tests and prints that it did so.
|
||||
@@ -0,0 +1,142 @@
|
||||
//! The conversion on the CPU, sample for sample the rule the GPU passes follow. Tests compare the
|
||||
//! two, and a caller without a GPU can use it directly.
|
||||
//!
|
||||
//! Each output texel (luma at the output size, chroma at half of it) takes the area of the source
|
||||
//! under it: up to 4 × 4 bilinear taps spread over the texel's footprint, 1 per axis while the
|
||||
//! source is at most twice the plane's size, one more for each further 2:1 of reduction. The
|
||||
//! average of the taps goes through the matrix. At the same size the chroma tap lands between
|
||||
//! four source pixels, so each chroma sample is the average of the 2 × 2 pixels it covers.
|
||||
//!
|
||||
//! The scaler here takes the shader's taps at the shader's positions instead of using a
|
||||
//! resampling crate such as `fast_image_resize`: this function is the reference the shader is
|
||||
//! tested against, and another kernel would differ from the shader at every edge. For another
|
||||
//! filter, resize with such a crate first and convert at the same size.
|
||||
|
||||
use crate::layout::FrameLayout;
|
||||
use crate::spec::{Coefficients, Conversion, Error};
|
||||
|
||||
/// The largest output side [`convert`] takes.
|
||||
pub const MAX_SIDE: u32 = 16384;
|
||||
|
||||
/// The taps along one axis for a reduction of `r` (source size over plane size).
|
||||
pub(crate) fn taps(r: f32) -> u32 {
|
||||
((r * 0.5 - 0.001).ceil() as i32).clamp(1, 4) as u32
|
||||
}
|
||||
|
||||
struct Image<'a> {
|
||||
rgba: &'a [u8],
|
||||
width: usize,
|
||||
height: usize,
|
||||
}
|
||||
|
||||
impl Image<'_> {
|
||||
fn pixel(&self, x: i64, y: i64) -> [f32; 3] {
|
||||
let x = x.clamp(0, self.width as i64 - 1) as usize;
|
||||
let y = y.clamp(0, self.height as i64 - 1) as usize;
|
||||
let i = (y * self.width + x) * 4;
|
||||
match self.rgba.get(i..i + 3) {
|
||||
Some(p) => [f32::from(p[0]) / 255.0, f32::from(p[1]) / 255.0, f32::from(p[2]) / 255.0],
|
||||
None => [0.0; 3],
|
||||
}
|
||||
}
|
||||
|
||||
/// The linear filter at `(x, y)` in pixels (pixel centers at .5), clamped to the edges.
|
||||
fn bilinear(&self, x: f32, y: f32) -> [f32; 3] {
|
||||
let (x, y) = (x - 0.5, y - 0.5);
|
||||
let (x0, y0) = (x.floor(), y.floor());
|
||||
let (fx, fy) = (x - x0, y - y0);
|
||||
let (xi, yi) = (x0 as i64, y0 as i64);
|
||||
let [a, b, c, d] = [self.pixel(xi, yi), self.pixel(xi + 1, yi), self.pixel(xi, yi + 1), self.pixel(xi + 1, yi + 1)];
|
||||
let mut out = [0.0; 3];
|
||||
for k in 0..3 {
|
||||
let top = a[k] + (b[k] - a[k]) * fx;
|
||||
let bottom = c[k] + (d[k] - c[k]) * fx;
|
||||
out[k] = top + (bottom - top) * fy;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The average color under the texel centered at `pos` of a plane of `size` texels.
|
||||
fn area(&self, pos: [f32; 2], size: [f32; 2]) -> [f32; 3] {
|
||||
let s = [self.width as f32, self.height as f32];
|
||||
let r = [s[0] / size[0], s[1] / size[1]];
|
||||
let n = [taps(r[0]), taps(r[1])];
|
||||
let nf = [n[0] as f32, n[1] as f32];
|
||||
let step = [r[0] / nf[0], r[1] / nf[1]];
|
||||
let center = [pos[0] / size[0] * s[0], pos[1] / size[1] * s[1]];
|
||||
let mut sum = [0.0f32; 3];
|
||||
for j in 0..n[1] {
|
||||
for i in 0..n[0] {
|
||||
let px = center[0] + (i as f32 + 0.5 - nf[0] * 0.5) * step[0];
|
||||
let py = center[1] + (j as f32 + 0.5 - nf[1] * 0.5) * step[1];
|
||||
let c = self.bilinear(px, py);
|
||||
for k in 0..3 {
|
||||
sum[k] += c[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
let count = nf[0] * nf[1];
|
||||
[sum[0] / count, sum[1] / count, sum[2] / count]
|
||||
}
|
||||
}
|
||||
|
||||
/// An empty vector with room for `len` values, or [`Error::Memory`] when the room cannot be
|
||||
/// allocated.
|
||||
pub(crate) fn reserve<T>(len: usize) -> Result<Vec<T>, Error> {
|
||||
let mut v = Vec::new();
|
||||
v.try_reserve_exact(len).map_err(|_| Error::Memory { bytes: len.saturating_mul(size_of::<T>()) })?;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// `rgba` (`src_width × src_height`, 4 bytes per pixel; alpha is ignored, so premultiplied
|
||||
/// pixels convert as if over black) scaled to `width × height` and converted, as one tightly
|
||||
/// packed frame in [`FrameLayout`] order.
|
||||
pub fn convert(rgba: &[u8], src_width: u32, src_height: u32, conversion: Conversion, width: u32, height: u32) -> Result<Vec<u8>, Error> {
|
||||
let bytes = (src_width as usize).checked_mul(src_height as usize).and_then(|n| n.checked_mul(4));
|
||||
if src_width == 0 || src_height == 0 || bytes != Some(rgba.len()) {
|
||||
return Err(Error::Source { width: src_width, height: src_height, bytes: rgba.len() });
|
||||
}
|
||||
if width > MAX_SIDE || height > MAX_SIDE {
|
||||
return Err(Error::TooLarge { width, height, limit: MAX_SIDE });
|
||||
}
|
||||
let layout = FrameLayout::new(conversion.format, width, height)?;
|
||||
let image = Image { rgba, width: src_width as usize, height: src_height as usize };
|
||||
let c = Coefficients::of(conversion);
|
||||
let (shift, wide) = (conversion.format.shift(), conversion.format.sample_bytes() == 2);
|
||||
let (cw, ch) = (width / 2, height / 2);
|
||||
let mut out = reserve(layout.frame_bytes())?;
|
||||
let mut cr: Vec<u16> = if conversion.format == crate::Format::I420 { reserve(cw as usize * ch as usize)? } else { Vec::new() };
|
||||
let mut put = |v: u16| {
|
||||
let v = v << shift;
|
||||
if wide {
|
||||
out.extend_from_slice(&v.to_le_bytes());
|
||||
} else {
|
||||
out.push(v as u8);
|
||||
}
|
||||
};
|
||||
let plane = |pw: u32, ph: u32, pick: &mut dyn FnMut([u16; 3])| {
|
||||
let size = [pw as f32, ph as f32];
|
||||
for j in 0..ph {
|
||||
for i in 0..pw {
|
||||
pick(c.codes(image.area([i as f32 + 0.5, j as f32 + 0.5], size)));
|
||||
}
|
||||
}
|
||||
};
|
||||
plane(width, height, &mut |v| put(v[0]));
|
||||
match conversion.format {
|
||||
crate::Format::Nv12 | crate::Format::P010 => plane(cw, ch, &mut |v| {
|
||||
put(v[1]);
|
||||
put(v[2]);
|
||||
}),
|
||||
crate::Format::I420 => {
|
||||
plane(cw, ch, &mut |v| {
|
||||
put(v[1]);
|
||||
cr.push(v[2]);
|
||||
});
|
||||
for v in cr {
|
||||
put(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
//! The conversion as render passes: one pass draws the luma plane, one draws the chroma plane or
|
||||
//! planes, each into unsigned-integer textures that hold the exact stored words.
|
||||
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::layout::FrameLayout;
|
||||
use crate::spec::{Coefficients, Conversion, Error, Format};
|
||||
|
||||
/// The render pipelines of one [`Conversion`]. Make it once per device and conversion; it holds
|
||||
/// no per-frame state.
|
||||
pub struct Converter {
|
||||
conversion: Conversion,
|
||||
plane_layout: wgpu::BindGroupLayout,
|
||||
source_layout: wgpu::BindGroupLayout,
|
||||
luma: wgpu::RenderPipeline,
|
||||
chroma: wgpu::RenderPipeline,
|
||||
sampler: wgpu::Sampler,
|
||||
}
|
||||
|
||||
/// A source texture view bound for a [`Converter`]. Keep one per texture that is converted more
|
||||
/// than once.
|
||||
pub struct Source {
|
||||
bind: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
/// The plane textures of one output size, and their read-back layout.
|
||||
pub struct Planes {
|
||||
layout: FrameLayout,
|
||||
textures: Vec<wgpu::Texture>,
|
||||
views: Vec<wgpu::TextureView>,
|
||||
luma_bind: wgpu::BindGroup,
|
||||
chroma_bind: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
fn plane_formats(format: Format) -> &'static [wgpu::TextureFormat] {
|
||||
use wgpu::TextureFormat as T;
|
||||
match format {
|
||||
Format::Nv12 => &[T::R8Uint, T::Rg8Uint],
|
||||
Format::P010 => &[T::R16Uint, T::Rg16Uint],
|
||||
Format::I420 => &[T::R8Uint, T::R8Uint, T::R8Uint],
|
||||
}
|
||||
}
|
||||
|
||||
fn attachment(view: &wgpu::TextureView) -> Option<wgpu::RenderPassColorAttachment<'_>> {
|
||||
Some(wgpu::RenderPassColorAttachment {
|
||||
view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store },
|
||||
})
|
||||
}
|
||||
|
||||
fn vec3(w: [f32; 3]) -> String {
|
||||
format!("vec3<f32>({:?}, {:?}, {:?})", w[0], w[1], w[2])
|
||||
}
|
||||
|
||||
/// The WGSL of `conversion`, with its weights and scale written in as constants.
|
||||
pub(crate) fn shader(conversion: Conversion) -> String {
|
||||
let k = Coefficients::of(conversion);
|
||||
let chroma = match conversion.format {
|
||||
Format::Nv12 | Format::P010 => {
|
||||
"@fragment fn fs_chroma(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<u32> {
|
||||
let c = area(pos.xy);
|
||||
return vec4<u32>(code(dot(c, CB) * CS + CO), code(dot(c, CR) * CS + CO), 0u, 0u);
|
||||
}"
|
||||
}
|
||||
Format::I420 => {
|
||||
"struct Chroma { @location(0) cb: vec4<u32>, @location(1) cr: vec4<u32> }
|
||||
@fragment fn fs_chroma(@builtin(position) pos: vec4<f32>) -> Chroma {
|
||||
let c = area(pos.xy);
|
||||
var o: Chroma;
|
||||
o.cb = vec4<u32>(code(dot(c, CB) * CS + CO), 0u, 0u, 0u);
|
||||
o.cr = vec4<u32>(code(dot(c, CR) * CS + CO), 0u, 0u, 0u);
|
||||
return o;
|
||||
}"
|
||||
}
|
||||
};
|
||||
format!(
|
||||
"const KY = {ky};
|
||||
const CB = {cb};
|
||||
const CR = {cr};
|
||||
const YS = {ys:?};
|
||||
const YO = {yo:?};
|
||||
const CS = {cs:?};
|
||||
const CO = {co:?};
|
||||
const MAX = {max:?};
|
||||
const SHIFT = {shift}u;
|
||||
|
||||
struct Plane {{ size: vec2<f32>, pad: vec2<f32> }}
|
||||
@group(0) @binding(0) var<uniform> plane: Plane;
|
||||
@group(1) @binding(0) var tex: texture_2d<f32>;
|
||||
@group(1) @binding(1) var samp: sampler;
|
||||
|
||||
@vertex fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {{
|
||||
let x = f32((vi << 1u) & 2u);
|
||||
let y = f32(vi & 2u);
|
||||
return vec4<f32>(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);
|
||||
}}
|
||||
|
||||
fn taps(r: f32) -> i32 {{
|
||||
return clamp(i32(ceil(r * 0.5 - 0.001)), 1, 4);
|
||||
}}
|
||||
|
||||
// The average color under the texel centered at `pos`: up to 4 x 4 bilinear taps over its
|
||||
// footprint in the source.
|
||||
fn area(pos: vec2<f32>) -> vec3<f32> {{
|
||||
let src = vec2<f32>(textureDimensions(tex));
|
||||
let r = src / plane.size;
|
||||
let n = vec2<i32>(taps(r.x), taps(r.y));
|
||||
let nf = vec2<f32>(n);
|
||||
let step = r / nf;
|
||||
let center = pos / plane.size * src;
|
||||
var sum = vec3<f32>(0.0);
|
||||
for (var j = 0; j < n.y; j++) {{
|
||||
for (var i = 0; i < n.x; i++) {{
|
||||
let p = center + (vec2<f32>(f32(i), f32(j)) + 0.5 - nf * 0.5) * step;
|
||||
sum += textureSampleLevel(tex, samp, p / src, 0.0).rgb;
|
||||
}}
|
||||
}}
|
||||
return sum / (nf.x * nf.y);
|
||||
}}
|
||||
|
||||
// A half rounds up, as INT and Round do in the recommendations; WGSL's round() takes it to the
|
||||
// even neighbor. The fraction v - floor(v) is exact in f32, while floor(v + 0.5) takes a value
|
||||
// just below a half up, because v + 0.5 rounds to the next integer. Values below 0 clamp to 0.
|
||||
fn code(v: f32) -> u32 {{
|
||||
let f = floor(v);
|
||||
return u32(clamp(select(f, f + 1.0, v - f >= 0.5), 0.0, MAX)) << SHIFT;
|
||||
}}
|
||||
|
||||
@fragment fn fs_luma(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<u32> {{
|
||||
return vec4<u32>(code(dot(area(pos.xy), KY) * YS + YO), 0u, 0u, 0u);
|
||||
}}
|
||||
|
||||
{chroma}
|
||||
",
|
||||
ky = vec3(k.y),
|
||||
cb = vec3(k.cb),
|
||||
cr = vec3(k.cr),
|
||||
ys = k.y_scale,
|
||||
yo = k.y_offset,
|
||||
cs = k.c_scale,
|
||||
co = k.c_offset,
|
||||
max = k.max,
|
||||
shift = conversion.format.shift(),
|
||||
)
|
||||
}
|
||||
|
||||
impl Converter {
|
||||
/// The pipelines of `conversion` on `device`.
|
||||
pub fn new(device: &wgpu::Device, conversion: Conversion) -> Converter {
|
||||
let plane_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("yuv plane"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: wgpu::BufferSize::new(16),
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
});
|
||||
let source_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("yuv source"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
multisampled: false,
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("yuv"),
|
||||
bind_group_layouts: &[Some(&plane_layout), Some(&source_layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some(conversion.format.name()),
|
||||
source: wgpu::ShaderSource::Wgsl(shader(conversion).into()),
|
||||
});
|
||||
let target = |format| Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL });
|
||||
let formats = plane_formats(conversion.format);
|
||||
let pipeline = |label: &str, fs: &str, targets: &[Option<wgpu::ColorTargetState>]| {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some(label),
|
||||
layout: Some(&layout),
|
||||
vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() },
|
||||
primitive: wgpu::PrimitiveState::default(),
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
fragment: Some(wgpu::FragmentState { module: &module, entry_point: Some(fs), targets, compilation_options: Default::default() }),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
let luma = pipeline("yuv luma", "fs_luma", &[target(formats[0])]);
|
||||
let chroma_targets: Vec<_> = formats[1..].iter().map(|f| target(*f)).collect();
|
||||
let chroma = pipeline("yuv chroma", "fs_chroma", &chroma_targets);
|
||||
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("yuv linear"),
|
||||
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
||||
address_mode_v: wgpu::AddressMode::ClampToEdge,
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
..Default::default()
|
||||
});
|
||||
Converter { conversion, plane_layout, source_layout, luma, chroma, sampler }
|
||||
}
|
||||
|
||||
pub fn conversion(&self) -> Conversion {
|
||||
self.conversion
|
||||
}
|
||||
|
||||
/// Bind `view` as a source. The view must be a 2D view of a filterable float format, such as
|
||||
/// `Rgba8Unorm` or `Bgra8Unorm`; an sRGB view gives linear values, which the matrix does not
|
||||
/// expect.
|
||||
pub fn bind(&self, device: &wgpu::Device, view: &wgpu::TextureView) -> Source {
|
||||
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("yuv source"),
|
||||
layout: &self.source_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(view) },
|
||||
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) },
|
||||
],
|
||||
});
|
||||
Source { bind }
|
||||
}
|
||||
|
||||
/// Plane textures for frames of `width × height`. Both sides must be even, not zero, and no
|
||||
/// larger than the device's largest 2D texture.
|
||||
pub fn planes(&self, device: &wgpu::Device, width: u32, height: u32) -> Result<Planes, Error> {
|
||||
let limit = device.limits().max_texture_dimension_2d;
|
||||
if width > limit || height > limit {
|
||||
return Err(Error::TooLarge { width, height, limit });
|
||||
}
|
||||
let layout = FrameLayout::new(self.conversion.format, width, height)?;
|
||||
let max = device.limits().max_buffer_size;
|
||||
if layout.buffer_size > max {
|
||||
return Err(Error::BufferLimit { needed: layout.buffer_size, limit: max });
|
||||
}
|
||||
let formats = plane_formats(self.conversion.format);
|
||||
let textures: Vec<wgpu::Texture> = layout
|
||||
.planes
|
||||
.iter()
|
||||
.zip(formats)
|
||||
.map(|(p, format)| {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("yuv plane"),
|
||||
size: wgpu::Extent3d { width: p.width, height: p.height, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: *format,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
||||
view_formats: &[],
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let views = textures.iter().map(|t| t.create_view(&wgpu::TextureViewDescriptor::default())).collect();
|
||||
let uniform = |w: u32, h: u32| {
|
||||
let mut bytes = [0u8; 16];
|
||||
bytes[..4].copy_from_slice(&(w as f32).to_le_bytes());
|
||||
bytes[4..8].copy_from_slice(&(h as f32).to_le_bytes());
|
||||
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("yuv plane size"),
|
||||
contents: &bytes,
|
||||
usage: wgpu::BufferUsages::UNIFORM,
|
||||
});
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("yuv plane"),
|
||||
layout: &self.plane_layout,
|
||||
entries: &[wgpu::BindGroupEntry { binding: 0, resource: buffer.as_entire_binding() }],
|
||||
})
|
||||
};
|
||||
let luma_bind = uniform(width, height);
|
||||
let chroma_bind = uniform(width / 2, height / 2);
|
||||
Ok(Planes { layout, textures, views, luma_bind, chroma_bind })
|
||||
}
|
||||
|
||||
/// Record the passes that convert `source` into `planes`.
|
||||
pub fn draw(&self, encoder: &mut wgpu::CommandEncoder, source: &Source, planes: &Planes) -> Result<(), Error> {
|
||||
if planes.layout.format != self.conversion.format {
|
||||
return Err(Error::Mismatch { converter: self.conversion.format, planes: planes.layout.format });
|
||||
}
|
||||
// No allocation per frame: one luma view, then one or two chroma views.
|
||||
let chroma_count = planes.views.len().saturating_sub(1).min(2);
|
||||
let luma = [planes.views.first().and_then(attachment)];
|
||||
let chroma = [planes.views.get(1).and_then(attachment), planes.views.get(2).and_then(attachment)];
|
||||
let passes: [(&wgpu::RenderPipeline, &wgpu::BindGroup, &[Option<wgpu::RenderPassColorAttachment<'_>>]); 2] =
|
||||
[(&self.luma, &planes.luma_bind, &luma), (&self.chroma, &planes.chroma_bind, &chroma[..chroma_count])];
|
||||
for (pipeline, plane, attachments) in passes {
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("yuv"),
|
||||
color_attachments: attachments,
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.set_bind_group(0, plane, &[]);
|
||||
pass.set_bind_group(1, &source.bind, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Planes {
|
||||
pub fn layout(&self) -> &FrameLayout {
|
||||
&self.layout
|
||||
}
|
||||
|
||||
/// The plane textures, luma first.
|
||||
pub fn textures(&self) -> &[wgpu::Texture] {
|
||||
&self.textures
|
||||
}
|
||||
|
||||
/// Record copies of every plane into `buffer` from `offset`, in the [`FrameLayout`]'s
|
||||
/// places. `offset` must be a multiple of `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`, and the
|
||||
/// buffer must hold `layout().buffer_size` bytes from it.
|
||||
pub fn copy_to_buffer(&self, encoder: &mut wgpu::CommandEncoder, buffer: &wgpu::Buffer, offset: u64) -> Result<(), Error> {
|
||||
if !offset.is_multiple_of(u64::from(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)) {
|
||||
return Err(Error::Offset(offset));
|
||||
}
|
||||
let needed = offset.saturating_add(self.layout.buffer_size);
|
||||
if buffer.size() < needed {
|
||||
return Err(Error::BufferSize { needed, actual: buffer.size() });
|
||||
}
|
||||
for (texture, p) in self.textures.iter().zip(&self.layout.planes) {
|
||||
encoder.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer,
|
||||
layout: wgpu::TexelCopyBufferLayout {
|
||||
offset: offset + p.offset,
|
||||
bytes_per_row: Some(p.bytes_per_row),
|
||||
rows_per_image: Some(p.height),
|
||||
},
|
||||
},
|
||||
wgpu::Extent3d { width: p.width, height: p.height, depth_or_array_layers: 1 },
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
//! The conversion as a `craft-gpu` job: [`YuvProvider`] answers [`GpuJob`]s whose provider id is
|
||||
//! [`PROVIDER_ID`], dispatched through a [`craft_gpu::ProviderRegistry`].
|
||||
//!
|
||||
//! A job has one input, an RGBA8 buffer of `src_width × src_height × 4` bytes in the context, and
|
||||
//! [`YuvJob::params`] as its parameters. Its outcome has one output: a new buffer that holds the
|
||||
//! packed frame in [`FrameLayout`] order. Every side must be no larger than the context's
|
||||
//! [`DeviceCaps::max_texture_dimension_2d`](craft_gpu::DeviceCaps), and the input and the frame no
|
||||
//! larger than its `max_buffer_size`, on every context, so that a job that runs on the null context
|
||||
//! also runs on a device with the same caps.
|
||||
|
||||
use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuJobParams, GpuProvider, HandleId};
|
||||
|
||||
use crate::cpu;
|
||||
use crate::layout::FrameLayout;
|
||||
use crate::spec::{Conversion, Error, Format, Matrix, Range};
|
||||
|
||||
/// The provider id of [`YuvProvider`].
|
||||
pub const PROVIDER_ID: &str = "craft.yuv";
|
||||
|
||||
/// The parameter keys, in the order [`YuvJob::params`] writes them.
|
||||
const KEYS: [&str; 7] = ["fmt", "matrix", "range", "sw", "sh", "w", "h"];
|
||||
|
||||
/// The parameters of one `craft.yuv` job: the conversion, the source size and the output size.
|
||||
///
|
||||
/// They are written as ASCII `key:value` fields separated by `;`, for example
|
||||
/// `fmt:nv12;matrix:bt709;range:limited;sw:1920;sh:1080;w:1280;h:720`. `fmt` is `nv12`, `p010` or
|
||||
/// `i420`; `matrix` is `bt601`, `bt709` or `bt2020`; `range` is `limited` or `full`; the sides are
|
||||
/// decimal digits. A missing, repeated or unknown key, or a value outside these, is
|
||||
/// [`GpuFault::InvalidJob`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct YuvJob {
|
||||
pub conversion: Conversion,
|
||||
pub src_width: u32,
|
||||
pub src_height: u32,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
fn invalid(message: impl std::fmt::Display) -> GpuFault {
|
||||
GpuFault::InvalidJob(format!("{PROVIDER_ID}: {message}"))
|
||||
}
|
||||
|
||||
/// A conversion error as a fault: device errors and allocation failures are
|
||||
/// [`GpuFault::Operation`], the rest describe a job that cannot run and are
|
||||
/// [`GpuFault::InvalidJob`].
|
||||
fn fault(e: Error) -> GpuFault {
|
||||
match e {
|
||||
Error::Device(_) | Error::Memory { .. } => GpuFault::Operation(format!("{PROVIDER_ID}: {e}")),
|
||||
_ => invalid(e),
|
||||
}
|
||||
}
|
||||
|
||||
fn format_token(f: Format) -> &'static str {
|
||||
match f {
|
||||
Format::Nv12 => "nv12",
|
||||
Format::P010 => "p010",
|
||||
Format::I420 => "i420",
|
||||
}
|
||||
}
|
||||
|
||||
fn matrix_token(m: Matrix) -> &'static str {
|
||||
match m {
|
||||
Matrix::Bt601 => "bt601",
|
||||
Matrix::Bt709 => "bt709",
|
||||
Matrix::Bt2020 => "bt2020",
|
||||
}
|
||||
}
|
||||
|
||||
fn range_token(r: Range) -> &'static str {
|
||||
match r {
|
||||
Range::Limited => "limited",
|
||||
Range::Full => "full",
|
||||
}
|
||||
}
|
||||
|
||||
impl YuvJob {
|
||||
pub fn new(conversion: Conversion, src_width: u32, src_height: u32, width: u32, height: u32) -> YuvJob {
|
||||
YuvJob { conversion, src_width, src_height, width, height }
|
||||
}
|
||||
|
||||
/// The job's parameters.
|
||||
pub fn params(&self) -> GpuJobParams {
|
||||
let c = self.conversion;
|
||||
let text = format!(
|
||||
"fmt:{};matrix:{};range:{};sw:{};sh:{};w:{};h:{}",
|
||||
format_token(c.format),
|
||||
matrix_token(c.matrix),
|
||||
range_token(c.range),
|
||||
self.src_width,
|
||||
self.src_height,
|
||||
self.width,
|
||||
self.height
|
||||
);
|
||||
GpuJobParams(text.into_bytes())
|
||||
}
|
||||
|
||||
/// A `craft.yuv` job that converts the RGBA8 buffer `input`.
|
||||
pub fn job(&self, input: HandleId) -> GpuJob {
|
||||
GpuJob { provider_id: PROVIDER_ID.into(), params: self.params(), inputs: vec![input], outputs: Vec::new() }
|
||||
}
|
||||
|
||||
/// Read parameters written by [`YuvJob::params`].
|
||||
pub fn parse(params: &GpuJobParams) -> Result<YuvJob, GpuFault> {
|
||||
let text = std::str::from_utf8(¶ms.0).map_err(|_| invalid("the parameters are not UTF-8"))?;
|
||||
let mut values: [Option<&str>; KEYS.len()] = [None; KEYS.len()];
|
||||
for field in text.split(';') {
|
||||
let (key, value) = field.split_once(':').ok_or_else(|| invalid(format!("`{field}` is not a key:value field")))?;
|
||||
let i = KEYS.iter().position(|k| *k == key).ok_or_else(|| invalid(format!("unknown key `{key}`")))?;
|
||||
if values[i].replace(value).is_some() {
|
||||
return Err(invalid(format!("`{key}` is given twice")));
|
||||
}
|
||||
}
|
||||
let get = |i: usize| values[i].ok_or_else(|| invalid(format!("`{}` is missing", KEYS[i])));
|
||||
let token = |i: usize, value: &str| invalid(format!("`{value}` is not a value of `{}`", KEYS[i]));
|
||||
let format = match get(0)? {
|
||||
"nv12" => Format::Nv12,
|
||||
"p010" => Format::P010,
|
||||
"i420" => Format::I420,
|
||||
v => return Err(token(0, v)),
|
||||
};
|
||||
let matrix = match get(1)? {
|
||||
"bt601" => Matrix::Bt601,
|
||||
"bt709" => Matrix::Bt709,
|
||||
"bt2020" => Matrix::Bt2020,
|
||||
v => return Err(token(1, v)),
|
||||
};
|
||||
let range = match get(2)? {
|
||||
"limited" => Range::Limited,
|
||||
"full" => Range::Full,
|
||||
v => return Err(token(2, v)),
|
||||
};
|
||||
let side = |i: usize| -> Result<u32, GpuFault> {
|
||||
let v = get(i)?;
|
||||
if v.is_empty() || !v.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return Err(token(i, v));
|
||||
}
|
||||
v.parse().map_err(|_| token(i, v))
|
||||
};
|
||||
Ok(YuvJob {
|
||||
conversion: Conversion::new(format, matrix, range),
|
||||
src_width: side(3)?,
|
||||
src_height: side(4)?,
|
||||
width: side(5)?,
|
||||
height: side(6)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The `craft.yuv` provider.
|
||||
///
|
||||
/// [`YuvProvider::new`] converts with [`cpu::convert`], on any context: the null context in tests
|
||||
/// and CI, or a context whose device a provider cannot reach. [`YuvProvider::with_device`]
|
||||
/// converts with the render passes on a device the caller holds, such as the one it already draws
|
||||
/// with; the RGBA8 input and the output frame still move through the context's buffers. Both give
|
||||
/// the same frame within the tolerance the crate's tests state.
|
||||
pub struct YuvProvider {
|
||||
device: Option<device::DeviceRunner>,
|
||||
}
|
||||
|
||||
impl Default for YuvProvider {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl YuvProvider {
|
||||
/// A provider that converts on the CPU.
|
||||
pub fn new() -> YuvProvider {
|
||||
YuvProvider { device: None }
|
||||
}
|
||||
|
||||
/// A provider that converts with the render passes on `device`. Each job waits for the device
|
||||
/// to finish, so this is not available on `wasm32`, where a buffer map completes only from the
|
||||
/// browser's event loop.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn with_device(device: wgpu::Device, queue: wgpu::Queue) -> YuvProvider {
|
||||
YuvProvider { device: Some(device::DeviceRunner::new(device, queue)) }
|
||||
}
|
||||
|
||||
/// Whether jobs run on a device.
|
||||
pub fn has_device(&self) -> bool {
|
||||
self.device.is_some()
|
||||
}
|
||||
|
||||
fn convert(&self, rgba: &[u8], job: &YuvJob) -> Result<Vec<u8>, Error> {
|
||||
match &self.device {
|
||||
Some(d) => d.convert(rgba, job),
|
||||
None => cpu::convert(rgba, job.src_width, job.src_height, job.conversion, job.width, job.height),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuProvider for YuvProvider {
|
||||
fn id(&self) -> &'static str {
|
||||
PROVIDER_ID
|
||||
}
|
||||
|
||||
fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result<GpuJobOutcome, GpuFault> {
|
||||
let spec = YuvJob::parse(&job.params)?;
|
||||
let [input] = job.inputs.as_slice() else {
|
||||
return Err(invalid(format!("expects one RGBA8 input, not {}", job.inputs.len())));
|
||||
};
|
||||
if !job.outputs.is_empty() {
|
||||
return Err(invalid("makes its own output buffer, so the job names no outputs"));
|
||||
}
|
||||
let YuvJob { conversion, src_width, src_height, width, height } = spec;
|
||||
let layout = FrameLayout::new(conversion.format, width, height).map_err(fault)?;
|
||||
let caps = ctx.caps();
|
||||
// An output side is also held to `cpu::MAX_SIDE`, so that both provider modes take the
|
||||
// same jobs.
|
||||
let limit = caps.max_texture_dimension_2d;
|
||||
for (w, h, limit) in [(src_width, src_height, limit), (width, height, limit.min(cpu::MAX_SIDE))] {
|
||||
if w > limit || h > limit {
|
||||
return Err(fault(Error::TooLarge { width: w, height: h, limit }));
|
||||
}
|
||||
}
|
||||
// The read-back buffer with its padded rows is the largest buffer a device run makes, so
|
||||
// the null context refuses the same jobs a device with these caps does.
|
||||
let needed = layout.buffer_size.max(layout.frame_bytes() as u64);
|
||||
if needed > caps.max_buffer_size {
|
||||
return Err(fault(Error::BufferLimit { needed, limit: caps.max_buffer_size }));
|
||||
}
|
||||
// The input's size is checked before its bytes are read.
|
||||
let bytes = ctx.buffer_len(*input)?;
|
||||
let expected = (src_width as usize).checked_mul(src_height as usize).and_then(|n| n.checked_mul(4));
|
||||
if src_width == 0 || src_height == 0 || expected != Some(bytes) {
|
||||
return Err(fault(Error::Source { width: src_width, height: src_height, bytes }));
|
||||
}
|
||||
let input_bytes = bytes as u64;
|
||||
if input_bytes > caps.max_buffer_size {
|
||||
return Err(fault(Error::BufferLimit { needed: input_bytes, limit: caps.max_buffer_size }));
|
||||
}
|
||||
let rgba = ctx.read_buffer(*input)?;
|
||||
let frame = self.convert(&rgba, &spec).map_err(fault)?;
|
||||
let output = ctx.upload_buffer("craft.yuv.frame", &frame)?;
|
||||
Ok(GpuJobOutcome { outputs: vec![output], data: None })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod device {
|
||||
use std::sync::Mutex;
|
||||
|
||||
use crate::gpu::{Converter, Planes};
|
||||
use crate::spec::{Conversion, Error};
|
||||
|
||||
use super::YuvJob;
|
||||
|
||||
/// A device, its queue, and the converters made on it so far, one per conversion.
|
||||
pub(super) struct DeviceRunner {
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
converters: Mutex<Vec<Converter>>,
|
||||
}
|
||||
|
||||
fn device_error(e: impl std::fmt::Display) -> Error {
|
||||
Error::Device(e.to_string())
|
||||
}
|
||||
|
||||
impl DeviceRunner {
|
||||
pub(super) fn new(device: wgpu::Device, queue: wgpu::Queue) -> DeviceRunner {
|
||||
DeviceRunner { device, queue, converters: Mutex::new(Vec::new()) }
|
||||
}
|
||||
|
||||
/// `rgba` converted on the device, as one packed frame. Errors the device reports go to
|
||||
/// error scopes and come back as [`Error::Device`]; a frame that cannot be allocated is
|
||||
/// [`Error::Memory`].
|
||||
pub(super) fn convert(&self, rgba: &[u8], job: &YuvJob) -> Result<Vec<u8>, Error> {
|
||||
let (sw, sh) = (job.src_width, job.src_height);
|
||||
let limit = self.device.limits().max_texture_dimension_2d;
|
||||
if sw > limit || sh > limit {
|
||||
return Err(Error::TooLarge { width: sw, height: sh, limit });
|
||||
}
|
||||
// A converter leaves the cache while a job uses it, and goes back only when the device
|
||||
// reported no error, so a converter whose pipelines failed is not used again.
|
||||
let mut converters = self.converters.lock().map_err(|_| device_error("the converter cache lock is poisoned"))?;
|
||||
let cached = take(&mut converters, job.conversion);
|
||||
drop(converters);
|
||||
let oom = self.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||
let validation = self.device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
let internal = self.device.push_error_scope(wgpu::ErrorFilter::Internal);
|
||||
let converter = cached.unwrap_or_else(|| Converter::new(&self.device, job.conversion));
|
||||
let recorded = self.record(&converter, rgba, job);
|
||||
// The scopes are popped on every path, in the reverse of the order they were pushed,
|
||||
// so that none stays open on the device.
|
||||
let errors = [pollster::block_on(internal.pop()), pollster::block_on(validation.pop()), pollster::block_on(oom.pop())];
|
||||
if let Some(e) = errors.into_iter().flatten().next() {
|
||||
return Err(device_error(e));
|
||||
}
|
||||
if let Ok(mut converters) = self.converters.lock() {
|
||||
converters.push(converter);
|
||||
}
|
||||
let (planes, buffer) = recorded?;
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
buffer.map_async(wgpu::MapMode::Read, .., move |result| {
|
||||
let _ = tx.send(result);
|
||||
});
|
||||
self.device.poll(wgpu::PollType::wait_indefinitely()).map_err(device_error)?;
|
||||
rx.try_recv().map_err(|_| device_error("the read-back map did not complete"))?.map_err(device_error)?;
|
||||
let mapped = buffer.get_mapped_range(..).map_err(device_error)?;
|
||||
let bytes = planes.layout().frame_bytes();
|
||||
let mut frame = crate::cpu::reserve(bytes)?;
|
||||
frame.resize(bytes, 0u8);
|
||||
let unpacked = planes.layout().unpack(&mapped, &mut frame);
|
||||
drop(mapped);
|
||||
buffer.unmap();
|
||||
unpacked.map(|()| frame)
|
||||
}
|
||||
|
||||
/// Upload `rgba` and record and submit the passes and the copy into a read-back buffer.
|
||||
fn record(&self, converter: &Converter, rgba: &[u8], job: &YuvJob) -> Result<(Planes, wgpu::Buffer), Error> {
|
||||
// The output size is checked against the device before the source is uploaded, so a
|
||||
// rejected job queues no upload.
|
||||
let planes = converter.planes(&self.device, job.width, job.height)?;
|
||||
let (sw, sh) = (job.src_width, job.src_height);
|
||||
let size = wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 };
|
||||
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("craft.yuv source"),
|
||||
size,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
let layout = wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(sw * 4), rows_per_image: Some(sh) };
|
||||
self.queue.write_texture(texture.as_image_copy(), rgba, layout, size);
|
||||
let source = converter.bind(&self.device, &texture.create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("craft.yuv read-back"),
|
||||
size: planes.layout().buffer_size,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft.yuv") });
|
||||
converter.draw(&mut encoder, &source, &planes)?;
|
||||
planes.copy_to_buffer(&mut encoder, &buffer, 0)?;
|
||||
self.queue.submit([encoder.finish()]);
|
||||
Ok((planes, buffer))
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove and return the converter of `conversion` from `converters`, if there is one.
|
||||
fn take(converters: &mut Vec<Converter>, conversion: Conversion) -> Option<Converter> {
|
||||
let i = converters.iter().position(|c| c.conversion() == conversion)?;
|
||||
Some(converters.swap_remove(i))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod device {
|
||||
use crate::spec::Error;
|
||||
|
||||
use super::YuvJob;
|
||||
|
||||
/// No device runs jobs on `wasm32`: [`super::YuvProvider::with_device`] is native only.
|
||||
pub(super) enum DeviceRunner {}
|
||||
|
||||
impl DeviceRunner {
|
||||
pub(super) fn convert(&self, _rgba: &[u8], _job: &YuvJob) -> Result<Vec<u8>, Error> {
|
||||
match *self {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
//! `craft.yuv` through the job contract: on `craft-gpu-null`, which needs no hardware, and with a
|
||||
//! device when the machine has a graphics adapter.
|
||||
|
||||
use craft_gpu::{DeviceCaps, GpuContext, GpuFault, GpuJob, GpuJobParams, HandleId, ProviderRegistry, ReadOutcome, ReadRequest, WorkerKind};
|
||||
use craft_gpu_null::NullContext;
|
||||
|
||||
use super::*;
|
||||
|
||||
const ALL: [Format; 3] = [Format::Nv12, Format::P010, Format::I420];
|
||||
const MATRICES: [Matrix; 3] = [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020];
|
||||
const RANGES: [Range; 2] = [Range::Limited, Range::Full];
|
||||
|
||||
/// A null context with caps of the test's choosing, which counts the buffers read.
|
||||
struct Capped {
|
||||
inner: NullContext,
|
||||
caps: DeviceCaps,
|
||||
reads: usize,
|
||||
}
|
||||
|
||||
impl Capped {
|
||||
fn new(caps: DeviceCaps) -> Capped {
|
||||
Capped { inner: NullContext::new(WorkerKind::Main), caps, reads: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuContext for Capped {
|
||||
fn caps(&self) -> DeviceCaps {
|
||||
self.caps.clone()
|
||||
}
|
||||
fn worker_kind(&self) -> WorkerKind {
|
||||
self.inner.worker_kind()
|
||||
}
|
||||
fn upload_buffer(&mut self, label: &str, bytes: &[u8]) -> Result<HandleId, GpuFault> {
|
||||
self.inner.upload_buffer(label, bytes)
|
||||
}
|
||||
fn buffer_len(&self, handle: HandleId) -> Result<usize, GpuFault> {
|
||||
self.inner.buffer_len(handle)
|
||||
}
|
||||
fn request_read(&mut self, handle: HandleId) -> Result<ReadRequest, GpuFault> {
|
||||
self.reads += 1;
|
||||
self.inner.request_read(handle)
|
||||
}
|
||||
fn poll_reads(&mut self) -> Vec<ReadOutcome> {
|
||||
self.inner.poll_reads()
|
||||
}
|
||||
fn free_buffer(&mut self, handle: HandleId) {
|
||||
self.inner.free_buffer(handle);
|
||||
}
|
||||
fn read_buffer(&mut self, handle: HandleId) -> Result<Vec<u8>, GpuFault> {
|
||||
self.reads += 1;
|
||||
self.inner.read_buffer(handle)
|
||||
}
|
||||
}
|
||||
|
||||
fn registry(provider: YuvProvider) -> ProviderRegistry {
|
||||
let mut r = ProviderRegistry::new();
|
||||
r.register(Box::new(provider));
|
||||
r
|
||||
}
|
||||
|
||||
/// Run `job` on `ctx` and read its one output back.
|
||||
fn dispatch(r: &ProviderRegistry, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result<Vec<u8>, GpuFault> {
|
||||
let outcome = r.dispatch(ctx, job)?;
|
||||
assert_eq!(outcome.outputs.len(), 1);
|
||||
assert_eq!(outcome.data, None);
|
||||
ctx.read_buffer(outcome.outputs[0])
|
||||
}
|
||||
|
||||
fn invalid(result: Result<impl std::fmt::Debug, GpuFault>) -> String {
|
||||
match result {
|
||||
Err(GpuFault::InvalidJob(message)) => message,
|
||||
other => panic!("expected an invalid job, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_registry_runs_craft_yuv_on_the_null_context() {
|
||||
let r = registry(YuvProvider::new());
|
||||
let mut ctx = NullContext::new(WorkerKind::Main);
|
||||
let px = tests::noise(64, 36);
|
||||
let input = ctx.upload_buffer("rgba", &px).unwrap();
|
||||
for format in ALL {
|
||||
for matrix in MATRICES {
|
||||
for range in RANGES {
|
||||
let c = Conversion::new(format, matrix, range);
|
||||
for (w, h) in [(64, 36), (32, 18), (100, 50)] {
|
||||
let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 36, w, h).job(input)).unwrap();
|
||||
assert_eq!(frame, cpu::convert(&px, 64, 36, c, w, h).unwrap(), "{c:?} {w}×{h}");
|
||||
assert_eq!(frame.len(), FrameLayout::new(format, w, h).unwrap().frame_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parameters_read_back_as_written() {
|
||||
let job = YuvJob::new(Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited), 1920, 1080, 1280, 720);
|
||||
assert_eq!(job.params().0, b"fmt:nv12;matrix:bt709;range:limited;sw:1920;sh:1080;w:1280;h:720");
|
||||
for format in ALL {
|
||||
for matrix in MATRICES {
|
||||
for range in RANGES {
|
||||
let job = YuvJob::new(Conversion::new(format, matrix, range), 7, u32::MAX, 0, 4);
|
||||
assert_eq!(YuvJob::parse(&job.params()), Ok(job));
|
||||
}
|
||||
}
|
||||
}
|
||||
let job = YuvJob::new(Conversion::new(Format::P010, Matrix::Bt2020, Range::Full), 3, 5, 8, 6).job(HandleId(9));
|
||||
assert_eq!((job.provider_id.as_str(), job.inputs.as_slice(), job.outputs.len()), (PROVIDER_ID, [HandleId(9)].as_slice(), 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_parameters_are_invalid_jobs() {
|
||||
let good = "fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4";
|
||||
let cases: [(&[u8], &str); 14] = [
|
||||
(b"", "is not a key:value field"),
|
||||
(b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4", "`h` is missing"),
|
||||
(b"fmt:nv12;fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4", "`fmt` is given twice"),
|
||||
(b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4;alpha:1", "unknown key `alpha`"),
|
||||
(b"fmt:NV12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4", "`NV12` is not a value of `fmt`"),
|
||||
(b"fmt:nv12;matrix:bt2100;range:limited;sw:4;sh:4;w:4;h:4", "`bt2100` is not a value of `matrix`"),
|
||||
(b"fmt:nv12;matrix:bt709;range:studio;sw:4;sh:4;w:4;h:4", "`studio` is not a value of `range`"),
|
||||
(b"fmt:nv12;matrix:bt709;range:limited;sw:+4;sh:4;w:4;h:4", "`+4` is not a value of `sw`"),
|
||||
(b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:-4;w:4;h:4", "`-4` is not a value of `sh`"),
|
||||
(b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:;h:4", "`` is not a value of `w`"),
|
||||
(b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4294967296", "`4294967296` is not a value of `h`"),
|
||||
(b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4;", "`` is not a key:value field"),
|
||||
(b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4.0", "`4.0` is not a value of `h`"),
|
||||
(b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:\xff", "not UTF-8"),
|
||||
];
|
||||
assert!(YuvJob::parse(&GpuJobParams(good.as_bytes().to_vec())).is_ok());
|
||||
for (params, want) in cases {
|
||||
let message = invalid(YuvJob::parse(&GpuJobParams(params.to_vec())));
|
||||
assert!(message.starts_with("craft.yuv: ") && message.contains(want), "{message:?} for {:?}", String::from_utf8_lossy(params));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inputs_outputs_and_sizes_are_checked_before_any_read() {
|
||||
let r = registry(YuvProvider::new());
|
||||
let mut ctx = Capped::new(DeviceCaps::default());
|
||||
let c = Conversion::new(Format::I420, Matrix::Bt601, Range::Limited);
|
||||
let input = ctx.upload_buffer("rgba", &tests::noise(8, 4)).unwrap();
|
||||
let mut job = YuvJob::new(c, 8, 4, 8, 4).job(input);
|
||||
job.inputs.clear();
|
||||
assert!(invalid(r.dispatch(&mut ctx, &job)).contains("expects one RGBA8 input, not 0"));
|
||||
job.inputs = vec![input, input];
|
||||
assert!(invalid(r.dispatch(&mut ctx, &job)).contains("not 2"));
|
||||
job.inputs = vec![input];
|
||||
job.outputs = vec![input];
|
||||
assert!(invalid(r.dispatch(&mut ctx, &job)).contains("names no outputs"));
|
||||
// A buffer whose size is not the source's, an odd or zero side, and a missing buffer.
|
||||
let wrong = [
|
||||
YuvJob::new(c, 8, 8, 8, 4).job(input),
|
||||
YuvJob::new(c, 0, 4, 8, 4).job(input),
|
||||
YuvJob::new(c, 8, 4, 7, 4).job(input),
|
||||
YuvJob::new(c, 8, 4, 8, 0).job(input),
|
||||
YuvJob::new(c, u32::MAX, u32::MAX, 8, 4).job(input),
|
||||
];
|
||||
for job in &wrong {
|
||||
invalid(r.dispatch(&mut ctx, job));
|
||||
}
|
||||
assert!(matches!(r.dispatch(&mut ctx, &YuvJob::new(c, 8, 4, 8, 4).job(HandleId(99))), Err(GpuFault::InvalidJob(_))));
|
||||
assert_eq!(ctx.reads, 0, "no job above reads its input");
|
||||
assert!(r.dispatch(&mut ctx, &YuvJob::new(c, 8, 4, 8, 4).job(input)).is_ok());
|
||||
assert_eq!(ctx.reads, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jobs_past_the_context_caps_are_refused() {
|
||||
let r = registry(YuvProvider::new());
|
||||
let caps = DeviceCaps { max_texture_dimension_2d: 64, max_buffer_size: 16128, ..DeviceCaps::default() };
|
||||
let mut ctx = Capped::new(caps);
|
||||
let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited);
|
||||
let small = ctx.upload_buffer("small", &tests::noise(64, 4)).unwrap();
|
||||
let wide = ctx.upload_buffer("wide", &tests::noise(66, 2)).unwrap();
|
||||
// The source and the output sides against the largest texture side.
|
||||
assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 66, 2, 64, 2).job(wide))).contains("66×2 is larger than the largest texture side, 64"));
|
||||
assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 64, 4, 66, 4).job(small))).contains("66×4"));
|
||||
// NV12 read-back rows at width 64 are padded to 256 bytes: 64 × 44 packs into 4224 bytes
|
||||
// but reads back through 256 × (44 + 22) = 16896, more than the 16128-byte limit; 64 × 42
|
||||
// reads back through exactly 16128.
|
||||
assert_eq!(FrameLayout::new(Format::Nv12, 64, 44).unwrap().frame_bytes(), 4224);
|
||||
let refused = invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 64, 4, 64, 44).job(small)));
|
||||
assert!(refused.contains("16896 bytes is larger than the largest buffer, 16128"), "{refused}");
|
||||
assert!(dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 4, 64, 42).job(small)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_output_side_past_the_cpu_limit_is_refused_before_the_input_is_read() {
|
||||
let r = registry(YuvProvider::new());
|
||||
let side = cpu::MAX_SIDE + 2;
|
||||
let caps = DeviceCaps { max_texture_dimension_2d: side, ..DeviceCaps::default() };
|
||||
let mut ctx = Capped::new(caps);
|
||||
let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited);
|
||||
let input = ctx.upload_buffer("input", &tests::noise(2, 2)).unwrap();
|
||||
let refused = invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 2, 2, side, 2).job(input)));
|
||||
assert!(refused.contains(&format!("{side}×2 is larger than the largest texture side, {}", cpu::MAX_SIDE)), "{refused}");
|
||||
assert_eq!(ctx.reads, 0, "the refused input is not read");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_input_past_the_buffer_limit_is_refused_before_it_is_read() {
|
||||
let r = registry(YuvProvider::new());
|
||||
let caps = DeviceCaps { max_texture_dimension_2d: 64, max_buffer_size: 16128, ..DeviceCaps::default() };
|
||||
let mut ctx = Capped::new(caps);
|
||||
let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited);
|
||||
// 64 × 64 × 4 = 16384 bytes, more than the 16128-byte limit; 64 × 63 × 4 is exactly 16128.
|
||||
let large = ctx.upload_buffer("large", &tests::noise(64, 64)).unwrap();
|
||||
let at_limit = ctx.upload_buffer("at limit", &tests::noise(64, 63)).unwrap();
|
||||
let refused = invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 64, 64, 64, 4).job(large)));
|
||||
assert!(refused.contains("16384 bytes is larger than the largest buffer, 16128"), "{refused}");
|
||||
assert_eq!(ctx.reads, 0, "the refused input is not read");
|
||||
assert!(dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 63, 64, 4).job(at_limit)).is_ok());
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_provider_with_a_device_matches_the_cpu_through_the_registry() {
|
||||
let Some((device, queue)) = tests::device() else { return };
|
||||
let provider = YuvProvider::with_device(device, queue);
|
||||
assert!(provider.has_device() && !YuvProvider::new().has_device());
|
||||
let r = registry(provider);
|
||||
let mut ctx = NullContext::new(WorkerKind::Main);
|
||||
let (noise, ramps) = (tests::noise(64, 36), tests::ramps(160, 90));
|
||||
let (n, s) = (ctx.upload_buffer("noise", &noise).unwrap(), ctx.upload_buffer("ramps", &ramps).unwrap());
|
||||
for format in ALL {
|
||||
for matrix in MATRICES {
|
||||
for range in RANGES {
|
||||
let c = Conversion::new(format, matrix, range);
|
||||
let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 36, 64, 36).job(n)).unwrap();
|
||||
tests::assert_close(&frame, &cpu::convert(&noise, 64, 36, c, 64, 36).unwrap(), c, "64×36 through the registry");
|
||||
}
|
||||
}
|
||||
// Each conversion's converter is made once and used again: the second run of a
|
||||
// conversion gives the same frame.
|
||||
let c = Conversion::new(format, Matrix::Bt709, Range::Limited);
|
||||
for (w, h) in [(80, 46), (240, 136)] {
|
||||
let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 160, 90, w, h).job(s)).unwrap();
|
||||
tests::assert_close(&frame, &cpu::convert(&ramps, 160, 90, c, w, h).unwrap(), c, &format!("160×90 to {w}×{h} through the registry"));
|
||||
assert_eq!(frame, dispatch(&r, &mut ctx, &YuvJob::new(c, 160, 90, w, h).job(s)).unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_device_smaller_than_the_context_caps_refuses_the_job_without_a_device_error() {
|
||||
let Some((device, queue)) = tests::device_with(|l| wgpu::Limits { max_texture_dimension_2d: 64, ..l }) else { return };
|
||||
let r = registry(YuvProvider::with_device(device, queue));
|
||||
// The null context's caps allow 8192, so only the device's own limit stops these.
|
||||
let mut ctx = NullContext::new(WorkerKind::Main);
|
||||
let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited);
|
||||
let big = ctx.upload_buffer("big", &tests::noise(128, 2)).unwrap();
|
||||
let small = ctx.upload_buffer("small", &tests::noise(8, 2)).unwrap();
|
||||
assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 128, 2, 8, 2).job(big))).contains("128×2 is larger than the largest texture side, 64"));
|
||||
assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 8, 2, 128, 2).job(small))).contains("128×2"));
|
||||
// The device still runs a job that fits after refusing two.
|
||||
let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 8, 2, 8, 2).job(small)).unwrap();
|
||||
tests::assert_close(&frame, &cpu::convert(&tests::noise(8, 2), 8, 2, c, 8, 2).unwrap(), c, "8×2 after two refusals");
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Where each plane sits in a read-back buffer and in a tightly packed frame.
|
||||
|
||||
use crate::spec::{Error, Format};
|
||||
|
||||
/// One plane: its size in texels, the bytes of one texel, and where its rows start in a
|
||||
/// read-back buffer.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PlaneLayout {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Bytes per texel: 1 or 2 for one sample, 2 or 4 for an interleaved Cb and Cr pair.
|
||||
pub texel_bytes: u32,
|
||||
/// The plane's first byte in the read-back buffer.
|
||||
pub offset: u64,
|
||||
/// Bytes from one row to the next in the read-back buffer, a multiple of
|
||||
/// `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`.
|
||||
pub bytes_per_row: u32,
|
||||
}
|
||||
|
||||
impl PlaneLayout {
|
||||
/// Bytes of one row in a packed frame, or `u32::MAX` when the fields give more.
|
||||
pub fn row_bytes(&self) -> u32 {
|
||||
self.width.saturating_mul(self.texel_bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// The planes of one frame of `format` at `width × height`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FrameLayout {
|
||||
pub format: Format,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub planes: Vec<PlaneLayout>,
|
||||
/// Bytes a read-back buffer needs from its offset.
|
||||
pub buffer_size: u64,
|
||||
}
|
||||
|
||||
fn aligned(n: u32) -> Option<u32> {
|
||||
let a = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
|
||||
n.div_ceil(a).checked_mul(a)
|
||||
}
|
||||
|
||||
/// The planes of `format` at `width × height` (the first `count` of the array) and the read-back
|
||||
/// buffer size.
|
||||
fn planes_of(format: Format, width: u32, height: u32) -> Result<([PlaneLayout; 3], usize, u64), Error> {
|
||||
if width == 0 || height == 0 || width % 2 == 1 || height % 2 == 1 {
|
||||
return Err(Error::OutputSize { width, height });
|
||||
}
|
||||
let s = format.sample_bytes();
|
||||
let (cw, ch) = (width / 2, height / 2);
|
||||
let (sizes, count) = match format {
|
||||
Format::Nv12 | Format::P010 => ([(width, height, s), (cw, ch, 2 * s), (0, 0, 0)], 2),
|
||||
Format::I420 => ([(width, height, s), (cw, ch, s), (cw, ch, s)], 3),
|
||||
};
|
||||
let overflow = Error::Overflow { width, height };
|
||||
let mut offset = 0u64;
|
||||
let mut tight = 0u64;
|
||||
let mut planes = [PlaneLayout { width: 0, height: 0, texel_bytes: 0, offset: 0, bytes_per_row: 0 }; 3];
|
||||
for (plane, (w, h, texel_bytes)) in planes.iter_mut().zip(sizes).take(count) {
|
||||
let row = w.checked_mul(texel_bytes).ok_or(overflow.clone())?;
|
||||
let bytes_per_row = aligned(row).ok_or(overflow.clone())?;
|
||||
*plane = PlaneLayout { width: w, height: h, texel_bytes, offset, bytes_per_row };
|
||||
offset = offset.checked_add(u64::from(bytes_per_row) * u64::from(h)).ok_or(overflow.clone())?;
|
||||
tight = tight.checked_add(u64::from(row) * u64::from(h)).ok_or(overflow.clone())?;
|
||||
}
|
||||
// A packed frame must also fit in memory on this target.
|
||||
usize::try_from(tight).map_err(|_| overflow)?;
|
||||
Ok((planes, count, offset))
|
||||
}
|
||||
|
||||
impl FrameLayout {
|
||||
/// The layout of `format` at `width × height`; both sides must be even and not zero.
|
||||
pub fn new(format: Format, width: u32, height: u32) -> Result<FrameLayout, Error> {
|
||||
let (planes, count, buffer_size) = planes_of(format, width, height)?;
|
||||
Ok(FrameLayout { format, width, height, planes: planes[..count].to_vec(), buffer_size })
|
||||
}
|
||||
|
||||
/// Whether the fields are what [`FrameLayout::new`] gives for the format and size. It does not
|
||||
/// allocate, so a frame loop can call it.
|
||||
fn is_valid(&self) -> bool {
|
||||
matches!(planes_of(self.format, self.width, self.height),
|
||||
Ok((planes, count, size)) if planes[..count] == self.planes[..] && size == self.buffer_size)
|
||||
}
|
||||
|
||||
/// Bytes of one tightly packed frame: the planes one after another, each row without padding.
|
||||
/// Fields changed after [`FrameLayout::new`] that give more than `usize::MAX` give
|
||||
/// `usize::MAX`.
|
||||
pub fn frame_bytes(&self) -> usize {
|
||||
self.planes
|
||||
.iter()
|
||||
.fold(0usize, |n, p| n.saturating_add((p.width as usize).saturating_mul(p.texel_bytes as usize).saturating_mul(p.height as usize)))
|
||||
}
|
||||
|
||||
/// Copy the planes from `padded` (a mapped read-back buffer, from the offset it was copied to)
|
||||
/// into `frame` without the row padding. `frame` must be [`FrameLayout::frame_bytes`] long.
|
||||
/// A layout whose fields differ from what [`FrameLayout::new`] gives is [`Error::Layout`].
|
||||
pub fn unpack(&self, padded: &[u8], frame: &mut [u8]) -> Result<(), Error> {
|
||||
if !self.is_valid() {
|
||||
return Err(Error::Layout);
|
||||
}
|
||||
if (padded.len() as u64) < self.buffer_size {
|
||||
return Err(Error::BufferSize { needed: self.buffer_size, actual: padded.len() as u64 });
|
||||
}
|
||||
let tight = self.frame_bytes();
|
||||
if frame.len() != tight {
|
||||
return Err(Error::BufferSize { needed: tight as u64, actual: frame.len() as u64 });
|
||||
}
|
||||
let mut out = frame;
|
||||
for p in &self.planes {
|
||||
let (row, padded_row) = (p.row_bytes() as usize, p.bytes_per_row as usize);
|
||||
let (dst, rest) = out.split_at_mut(row * p.height as usize);
|
||||
let src = padded.get(p.offset as usize..).unwrap_or_default();
|
||||
for (d, s) in dst.chunks_exact_mut(row).zip(src.chunks(padded_row)) {
|
||||
// The layout and size checks above leave every row whole.
|
||||
if let Some(s) = s.get(..row) {
|
||||
d.copy_from_slice(s);
|
||||
}
|
||||
}
|
||||
out = rest;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! RGBA to 4:2:0 Y'CbCr on the GPU, for encoders and scopes.
|
||||
//!
|
||||
//! - [`YuvProvider`] is the `craft.yuv` [`craft_gpu::GpuProvider`]: a host registers it in a
|
||||
//! [`craft_gpu::ProviderRegistry`] and dispatches [`YuvJob`]s, on the null context or on a device.
|
||||
//! - [`Converter`] holds the render pipelines of one [`Conversion`]: a [`Format`] (NV12, P010 or
|
||||
//! I420), a [`Matrix`] (BT.601, BT.709 or BT.2020) and a [`Range`] (limited or full), for a
|
||||
//! caller that records the passes into its own command encoder.
|
||||
//! - [`Converter::bind`] binds a source texture view once; [`Converter::planes`] makes the plane
|
||||
//! textures of one output size; [`Converter::draw`] records the two passes. The source is scaled
|
||||
//! to the output size.
|
||||
//! - [`Planes::copy_to_buffer`] records the copies into a read-back buffer, and
|
||||
//! [`FrameLayout::unpack`] turns the mapped buffer into one tightly packed frame.
|
||||
//! - [`cpu::convert`] is the same conversion on the CPU.
|
||||
//!
|
||||
//! The matrix applies to the stored values as they are: the input must already be in the
|
||||
//! output's primaries and transfer, and alpha is ignored.
|
||||
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod cpu;
|
||||
mod gpu;
|
||||
mod job;
|
||||
mod layout;
|
||||
mod spec;
|
||||
|
||||
pub use gpu::{Converter, Planes, Source};
|
||||
pub use job::{PROVIDER_ID, YuvJob, YuvProvider};
|
||||
pub use layout::{FrameLayout, PlaneLayout};
|
||||
pub use spec::{Conversion, Error, Format, Matrix, Range};
|
||||
|
||||
#[cfg(test)]
|
||||
mod job_tests;
|
||||
#[cfg(test)]
|
||||
mod oracle_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,350 @@
|
||||
//! Checks against sources outside this crate: code values computed here in `f64` from the Kr and
|
||||
//! Kb values and the quantization each ITU-R recommendation states, the `yuv` crate's conversion
|
||||
//! of the same pictures, and the plane layouts the formats' public definitions give. None of these
|
||||
//! checks reads `spec::Coefficients`.
|
||||
//!
|
||||
//! - BT.601-7 section 2.5, <https://www.itu.int/rec/R-REC-BT.601>: Kr 0.299, Kb 0.114.
|
||||
//! - BT.709-6 items 3.2 to 3.5, <https://www.itu.int/rec/R-REC-BT.709>: Kr 0.2126, Kb 0.0722;
|
||||
//! limited range `INT[(219 E'Y + 16) 2^(n-8)]` and `INT[(224 E'C + 128) 2^(n-8)]`, where INT
|
||||
//! rounds a fraction of 0.5 up.
|
||||
//! - BT.2020-2 tables 4 and 5, <https://www.itu.int/rec/R-REC-BT.2020>: Kr 0.2627, Kb 0.0593,
|
||||
//! quantized as in BT.709.
|
||||
//! - BT.2100-3 table 9, <https://www.itu.int/rec/R-REC-BT.2100>: full range
|
||||
//! `Round[(2^n - 1) E'Y]` and `Round[(2^n - 1) E'C + 2^(n-1)]`, with
|
||||
//! `Round(x) = Sign(x) Floor(|x| + 0.5)`.
|
||||
//! - NV12 and I420: the W3C WebCodecs `VideoPixelFormat` definitions,
|
||||
//! <https://www.w3.org/TR/webcodecs/#enumdef-videopixelformat>.
|
||||
//! - NV12 and P010: the Linux media API's semi-planar YUV formats and their sample 4×4 images,
|
||||
//! <https://docs.kernel.org/userspace-api/media/v4l/pixfmt-yuv-planar.html>.
|
||||
|
||||
use super::*;
|
||||
|
||||
const ALL: [Format; 3] = [Format::Nv12, Format::P010, Format::I420];
|
||||
const MATRICES: [Matrix; 3] = [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020];
|
||||
const RANGES: [Range; 2] = [Range::Limited, Range::Full];
|
||||
|
||||
/// Kr and Kb as each recommendation states them.
|
||||
fn kr_kb(m: Matrix) -> (f64, f64) {
|
||||
match m {
|
||||
Matrix::Bt601 => (0.299, 0.114),
|
||||
Matrix::Bt709 => (0.2126, 0.0722),
|
||||
Matrix::Bt2020 => (0.2627, 0.0593),
|
||||
}
|
||||
}
|
||||
|
||||
/// The unrounded luma, Cb and Cr code values of an 8-bit RGB color.
|
||||
fn exact(rgb: [f64; 3], c: Conversion) -> [f64; 3] {
|
||||
let (kr, kb) = kr_kb(c.matrix);
|
||||
let [r, g, b] = rgb.map(|v| v / 255.0);
|
||||
let y = kr * r + (1.0 - kr - kb) * g + kb * b;
|
||||
let pb = (b - y) / (2.0 * (1.0 - kb));
|
||||
let pr = (r - y) / (2.0 * (1.0 - kr));
|
||||
let n = c.format.bits() as i32;
|
||||
match c.range {
|
||||
Range::Limited => {
|
||||
let s = 2f64.powi(n - 8);
|
||||
[(219.0 * y + 16.0) * s, (224.0 * pb + 128.0) * s, (224.0 * pr + 128.0) * s]
|
||||
}
|
||||
Range::Full => {
|
||||
let m = 2f64.powi(n) - 1.0;
|
||||
let half = 2f64.powi(n - 1);
|
||||
[m * y, m * pb + half, m * pr + half]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Round(x) = Sign(x) Floor(|x| + 0.5)`, clamped to the codes of `bits`. `f64::round` is that
|
||||
/// function; adding 0.5 in `f64` would take the largest value below a half up to 1.
|
||||
fn round(x: f64, bits: u32) -> u16 {
|
||||
x.round().clamp(0.0, f64::from((1u32 << bits) - 1)) as u16
|
||||
}
|
||||
|
||||
/// Whether `got` is the rounded `exact` value. A value within 0.001 of a half may round either
|
||||
/// way in `f32`, so there the floor and the ceiling of `exact`, clamped to the codes, both pass.
|
||||
fn rounds_to(got: u16, exact: f64, bits: u32) -> bool {
|
||||
let near_half = ((exact - exact.floor()) - 0.5).abs() < 1e-3;
|
||||
let code = |v: f64| v.clamp(0.0, f64::from((1u32 << bits) - 1)) as u16;
|
||||
got == round(exact, bits) || near_half && (got == code(exact.floor()) || got == code(exact.ceil()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_near_a_half_passes_only_as_its_floor_or_ceiling() {
|
||||
assert!(rounds_to(128, 128.5, 8));
|
||||
assert!(rounds_to(129, 128.5, 8));
|
||||
assert!(!rounds_to(130, 128.5, 8));
|
||||
assert!(!rounds_to(127, 128.5, 8));
|
||||
assert!(rounds_to(255, 254.9995, 8));
|
||||
assert!(!rounds_to(254, 254.9, 8));
|
||||
assert!(rounds_to(0, -0.5, 8));
|
||||
assert!(!rounds_to(1, -0.5, 8));
|
||||
assert_eq!(round(0.5 - f64::EPSILON / 4.0, 8), 0);
|
||||
assert_eq!(round(2.5, 8), 3);
|
||||
}
|
||||
|
||||
/// Every sample of a frame as its value (P010 words shifted down by 6).
|
||||
fn samples(frame: &[u8], format: Format) -> Vec<u16> {
|
||||
match format {
|
||||
Format::P010 => frame.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b) >> 6).collect(),
|
||||
Format::Nv12 | Format::I420 => frame.iter().map(|&b| u16::from(b)).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The luma sample of pixel `(x, y)` and the Cb and Cr samples of the chroma texel over it, in
|
||||
/// a packed frame of `w × h`.
|
||||
fn at(s: &[u16], format: Format, w: usize, h: usize, x: usize, y: usize) -> [u16; 3] {
|
||||
let luma = w * h;
|
||||
let (cw, ch) = (w / 2, h / 2);
|
||||
let c = (y / 2) * cw + x / 2;
|
||||
match format {
|
||||
Format::Nv12 | Format::P010 => [s[y * w + x], s[luma + 2 * c], s[luma + 2 * c + 1]],
|
||||
Format::I420 => [s[y * w + x], s[luma + c], s[luma + cw * ch + c]],
|
||||
}
|
||||
}
|
||||
|
||||
/// Channel values that include black, white, the 75% level (191), the limited-range nominal
|
||||
/// levels and values one step from the ends.
|
||||
const LEVELS: [u8; 9] = [0, 1, 16, 64, 128, 191, 235, 254, 255];
|
||||
|
||||
/// A picture of every color whose channels are in [`LEVELS`], each as a 2 × 2 block, so that no
|
||||
/// sample depends on how chroma is subsampled. Returns the pixels, the side and the colors.
|
||||
fn blocks() -> (Vec<u8>, u32, Vec<[u8; 3]>) {
|
||||
let colors: Vec<[u8; 3]> = LEVELS.iter().flat_map(|&r| LEVELS.iter().flat_map(move |&g| LEVELS.iter().map(move |&b| [r, g, b]))).collect();
|
||||
let per_row = 27usize;
|
||||
let side = per_row * 2;
|
||||
let mut px = vec![0u8; side * side * 4];
|
||||
for (k, rgb) in colors.iter().enumerate() {
|
||||
let (bx, by) = (k % per_row, k / per_row);
|
||||
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
|
||||
let i = ((by * 2 + dy) * side + bx * 2 + dx) * 4;
|
||||
px[i..i + 4].copy_from_slice(&[rgb[0], rgb[1], rgb[2], 255]);
|
||||
}
|
||||
}
|
||||
(px, side as u32, colors)
|
||||
}
|
||||
|
||||
/// Every block of `frame` against the equations. `slack` is 0 for the CPU and 1 for the GPU.
|
||||
fn check_blocks(frame: &[u8], c: Conversion, side: u32, colors: &[[u8; 3]], slack: u16, what: &str) {
|
||||
let s = samples(frame, c.format);
|
||||
let side = side as usize;
|
||||
for (k, rgb) in colors.iter().enumerate() {
|
||||
let (x, y) = ((k % 27) * 2, (k / 27) * 2);
|
||||
let got = at(&s, c.format, side, side, x, y);
|
||||
let want = exact(rgb.map(f64::from), c);
|
||||
for i in 0..3 {
|
||||
let ok = rounds_to(got[i], want[i], c.format.bits()) || got[i].abs_diff(round(want[i], c.format.bits())) <= slack;
|
||||
assert!(ok, "{what} {c:?} {rgb:?}: component {i} is {} where the equations give {:.4}", got[i], want[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cpu_gives_the_codes_of_the_published_equations() {
|
||||
let (px, side, colors) = blocks();
|
||||
for format in ALL {
|
||||
for matrix in MATRICES {
|
||||
for range in RANGES {
|
||||
let c = Conversion::new(format, matrix, range);
|
||||
let frame = cpu::convert(&px, side, side, c, side, side).unwrap();
|
||||
check_blocks(&frame, c, side, &colors, 0, "CPU");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nominal_levels_have_the_codes_the_recommendations_state() {
|
||||
// White, black and neutral chroma are 235, 16 and 128 at limited range, 255, 0 and 128 at
|
||||
// full range, times 4 (and 1023 for full white) at 10 bits. Chroma reaches 240 (960) for blue's
|
||||
// Cb and red's Cr, and 16 (64) for yellow's Cb and cyan's Cr. At full range those are
|
||||
// Round(255.5) and Round(0.5), clamped to 255 (1023) and 1.
|
||||
for format in ALL {
|
||||
let ten = format.bits() == 10;
|
||||
for matrix in MATRICES {
|
||||
for range in RANGES {
|
||||
let c = Conversion::new(format, matrix, range);
|
||||
let (white, black, mid, high, low) = match (range, ten) {
|
||||
(Range::Limited, false) => (235, 16, 128, 240, 16),
|
||||
(Range::Limited, true) => (940, 64, 512, 960, 64),
|
||||
(Range::Full, false) => (255, 0, 128, 255, 1),
|
||||
(Range::Full, true) => (1023, 0, 512, 1023, 1),
|
||||
};
|
||||
let code = |rgb: [u8; 3]| {
|
||||
let frame = cpu::convert(&(0..4).flat_map(|_| [rgb[0], rgb[1], rgb[2], 255]).collect::<Vec<_>>(), 2, 2, c, 2, 2).unwrap();
|
||||
at(&samples(&frame, format), format, 2, 2, 0, 0)
|
||||
};
|
||||
assert_eq!(code([255, 255, 255]), [white, mid, mid], "{c:?} white");
|
||||
assert_eq!(code([0, 0, 0]), [black, mid, mid], "{c:?} black");
|
||||
assert_eq!(code([0, 0, 255])[1], high, "{c:?} blue Cb");
|
||||
assert_eq!(code([255, 0, 0])[2], high, "{c:?} red Cr");
|
||||
assert_eq!(code([255, 255, 0])[1], low, "{c:?} yellow Cb");
|
||||
assert_eq!(code([0, 255, 255])[2], low, "{c:?} cyan Cr");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn yuv_range(r: Range) -> yuv::YuvRange {
|
||||
match r {
|
||||
Range::Limited => yuv::YuvRange::Limited,
|
||||
Range::Full => yuv::YuvRange::Full,
|
||||
}
|
||||
}
|
||||
|
||||
fn yuv_matrix(m: Matrix) -> yuv::YuvStandardMatrix {
|
||||
match m {
|
||||
Matrix::Bt601 => yuv::YuvStandardMatrix::Bt601,
|
||||
Matrix::Bt709 => yuv::YuvStandardMatrix::Bt709,
|
||||
Matrix::Bt2020 => yuv::YuvStandardMatrix::Bt2020,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `yuv` crate's conversion of `px` (`w × h`) as one packed frame in this crate's order.
|
||||
/// P010 takes 10-bit RGB there, so each channel is scaled to 0..=1023 and rounded first.
|
||||
fn yuv_convert(px: &[u8], w: u32, h: u32, c: Conversion) -> Vec<u8> {
|
||||
use yuv::{YuvBiPlanarImageMut, YuvChromaSubsampling, YuvConversionMode, YuvPlanarImageMut};
|
||||
let (range, matrix, mode) = (yuv_range(c.range), yuv_matrix(c.matrix), YuvConversionMode::Professional);
|
||||
match c.format {
|
||||
Format::Nv12 => {
|
||||
let mut img = YuvBiPlanarImageMut::<u8>::alloc(w, h, YuvChromaSubsampling::Yuv420);
|
||||
yuv::rgba_to_yuv_nv12(&mut img, px, w * 4, range, matrix, mode).unwrap();
|
||||
[img.y_plane.borrow(), img.uv_plane.borrow()].concat()
|
||||
}
|
||||
Format::I420 => {
|
||||
let mut img = YuvPlanarImageMut::<u8>::alloc(w, h, YuvChromaSubsampling::Yuv420);
|
||||
yuv::rgba_to_yuv420(&mut img, px, w * 4, range, matrix, mode).unwrap();
|
||||
[img.y_plane.borrow(), img.u_plane.borrow(), img.v_plane.borrow()].concat()
|
||||
}
|
||||
Format::P010 => {
|
||||
let wide: Vec<u16> = px.iter().map(|&v| (f64::from(v) * 1023.0 / 255.0).round() as u16).collect();
|
||||
let mut img = YuvBiPlanarImageMut::<u16>::alloc(w, h, YuvChromaSubsampling::Yuv420);
|
||||
yuv::rgba10_to_p010(&mut img, &wide, w * 4, range, matrix).unwrap();
|
||||
[img.y_plane.borrow(), img.uv_plane.borrow()].concat().iter().flat_map(|v| v.to_le_bytes()).collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest difference allowed from the `yuv` crate: 1 code value at 8 bits, and 2 at 10 bits,
|
||||
/// where its input was rounded to 10 bits first.
|
||||
fn yuv_tolerance(format: Format) -> u16 {
|
||||
if format.bits() == 10 { 2 } else { 1 }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cpu_matches_the_yuv_crate() {
|
||||
let (px, side, _) = blocks();
|
||||
for format in ALL {
|
||||
for matrix in MATRICES {
|
||||
for range in RANGES {
|
||||
let c = Conversion::new(format, matrix, range);
|
||||
let ours = samples(&cpu::convert(&px, side, side, c, side, side).unwrap(), format);
|
||||
let theirs = samples(&yuv_convert(&px, side, side, c), format);
|
||||
assert_eq!(ours.len(), theirs.len(), "{c:?}");
|
||||
for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
|
||||
assert!(a.abs_diff(*b) <= yuv_tolerance(format), "{c:?}: sample {i} is {a} here and {b} in the yuv crate");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packed_planes_have_the_sizes_the_yuv_crate_allocates() {
|
||||
use yuv::{YuvBiPlanarImageMut, YuvChromaSubsampling, YuvPlanarImageMut};
|
||||
for (w, h) in [(2, 2), (4, 4), (16, 10), (1920, 1080), (3840, 2160)] {
|
||||
for format in ALL {
|
||||
let l = FrameLayout::new(format, w, h).unwrap();
|
||||
let s = format.sample_bytes() as usize;
|
||||
let packed: Vec<(usize, usize)> = l.planes.iter().map(|p| (p.row_bytes() as usize, p.row_bytes() as usize * p.height as usize)).collect();
|
||||
let theirs: Vec<(usize, usize)> = match format {
|
||||
Format::Nv12 | Format::P010 => {
|
||||
let img = YuvBiPlanarImageMut::<u16>::alloc(w, h, YuvChromaSubsampling::Yuv420);
|
||||
vec![(img.y_stride as usize * s, img.y_plane.borrow().len() * s), (img.uv_stride as usize * s, img.uv_plane.borrow().len() * s)]
|
||||
}
|
||||
Format::I420 => {
|
||||
let img = YuvPlanarImageMut::<u8>::alloc(w, h, YuvChromaSubsampling::Yuv420);
|
||||
vec![
|
||||
(img.y_stride as usize, img.y_plane.borrow().len()),
|
||||
(img.u_stride as usize, img.u_plane.borrow().len()),
|
||||
(img.v_stride as usize, img.v_plane.borrow().len()),
|
||||
]
|
||||
}
|
||||
};
|
||||
assert_eq!(packed, theirs, "{format} {w}×{h}: row bytes and plane bytes");
|
||||
assert_eq!(l.frame_bytes(), theirs.iter().map(|p| p.1).sum::<usize>(), "{format} {w}×{h}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sixteen different colors for a 4 × 4 picture.
|
||||
fn sixteen() -> Vec<[u8; 3]> {
|
||||
(0..16u32).map(|k| [(k * 17) as u8, ((k * 53 + 30) % 256) as u8, ((k * 91 + 60) % 256) as u8]).collect()
|
||||
}
|
||||
|
||||
/// The byte offset of luma sample `(x, y)`.
|
||||
type LumaAt = fn(usize, usize) -> usize;
|
||||
/// The byte offsets of the Cb and Cr samples of chroma texel `(x, y)`.
|
||||
type ChromaAt = fn(usize, usize) -> (usize, usize);
|
||||
|
||||
/// Where the public definitions put each sample of a 4 × 4 frame.
|
||||
fn documented_offsets(format: Format) -> (LumaAt, ChromaAt) {
|
||||
match format {
|
||||
// "start + 0: Y'00 Y'01 Y'02 Y'03 ... start + 16: Cb00 Cr00 Cb01 Cr01, start + 20: Cb10 Cr10 Cb11 Cr11"
|
||||
Format::Nv12 => (|x, y| y * 4 + x, |x, y| (16 + y * 4 + x * 2, 17 + y * 4 + x * 2)),
|
||||
// Rows of 8 bytes: "start + 8: Y'10 ... start + 32: Cb00 Cr00 Cb01 Cr01, start + 40: Cb10 ..."
|
||||
Format::P010 => (|x, y| y * 8 + x * 2, |x, y| (32 + y * 8 + x * 4, 34 + y * 8 + x * 4)),
|
||||
// Y, then U, then V; each chroma plane has 2 rows of 2 samples.
|
||||
Format::I420 => (|x, y| y * 4 + x, |x, y| (16 + y * 2 + x, 20 + y * 2 + x)),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_4x4_frame_puts_each_sample_where_the_format_definitions_do() {
|
||||
let colors = sixteen();
|
||||
let px: Vec<u8> = colors.iter().flat_map(|c| [c[0], c[1], c[2], 255]).collect();
|
||||
for format in ALL {
|
||||
let c = Conversion::new(format, Matrix::Bt709, Range::Limited);
|
||||
let frame = cpu::convert(&px, 4, 4, c, 4, 4).unwrap();
|
||||
assert_eq!(frame.len(), 4 * 4 * 3 / 2 * format.sample_bytes() as usize, "{format}");
|
||||
let read = |offset: usize| match format {
|
||||
Format::P010 => {
|
||||
let word = u16::from_le_bytes([frame[offset], frame[offset + 1]]);
|
||||
assert_eq!(word & 0x3f, 0, "{format}: the 6 low bits are zero");
|
||||
word >> 6
|
||||
}
|
||||
Format::Nv12 | Format::I420 => u16::from(frame[offset]),
|
||||
};
|
||||
let (luma, chroma) = documented_offsets(format);
|
||||
for y in 0..4 {
|
||||
for x in 0..4 {
|
||||
let want = exact(colors[y * 4 + x].map(f64::from), c)[0];
|
||||
assert!(rounds_to(read(luma(x, y)), want, format.bits()), "{format}: luma {x},{y}");
|
||||
}
|
||||
}
|
||||
for y in 0..2 {
|
||||
for x in 0..2 {
|
||||
// Each chroma sample is the code of the average of the 2 × 2 pixels under it.
|
||||
let quad = [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(dx, dy)| colors[(y * 2 + dy) * 4 + x * 2 + dx]);
|
||||
let mean = [0, 1, 2].map(|i| quad.iter().map(|p| f64::from(p[i])).sum::<f64>() / 4.0);
|
||||
let want = exact(mean, c);
|
||||
let (cb, cr) = chroma(x, y);
|
||||
assert!(rounds_to(read(cb), want[1], format.bits()), "{format}: Cb {x},{y}");
|
||||
assert!(rounds_to(read(cr), want[2], format.bits()), "{format}: Cr {x},{y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gpu_gives_the_codes_of_the_published_equations() {
|
||||
let Some((device, queue)) = tests::device() else { return };
|
||||
let (px, side, colors) = blocks();
|
||||
for format in ALL {
|
||||
for matrix in MATRICES {
|
||||
for range in RANGES {
|
||||
let c = Conversion::new(format, matrix, range);
|
||||
let frame = tests::gpu_convert(&device, &queue, (&px, side, side), c, (side, side));
|
||||
check_blocks(&frame, c, side, &colors, 1, "GPU");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
//! What a conversion produces: the plane format, the matrix and the range, and the code values
|
||||
//! they give.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// The 4:2:0 layout a conversion writes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Format {
|
||||
/// 8 bits: the luma plane, then one plane of interleaved Cb and Cr samples.
|
||||
Nv12,
|
||||
/// 10 bits in the high bits of little-endian 16-bit words: the luma plane, then one plane of
|
||||
/// interleaved Cb and Cr samples.
|
||||
P010,
|
||||
/// 8 bits: the luma plane, then the Cb plane, then the Cr plane.
|
||||
I420,
|
||||
}
|
||||
|
||||
impl Format {
|
||||
/// Bits per sample value.
|
||||
pub fn bits(self) -> u32 {
|
||||
match self {
|
||||
Format::P010 => 10,
|
||||
Format::Nv12 | Format::I420 => 8,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes each sample takes in memory.
|
||||
pub fn sample_bytes(self) -> u32 {
|
||||
match self {
|
||||
Format::P010 => 2,
|
||||
Format::Nv12 | Format::I420 => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// The left shift from a sample value to the stored word: 6 for P010, else 0.
|
||||
pub fn shift(self) -> u32 {
|
||||
match self {
|
||||
Format::P010 => 6,
|
||||
Format::Nv12 | Format::I420 => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The format's usual name: `NV12`, `P010` or `I420`.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Format::Nv12 => "NV12",
|
||||
Format::P010 => "P010",
|
||||
Format::I420 => "I420",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Format {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(self.name())
|
||||
}
|
||||
}
|
||||
|
||||
/// The RGB to Y'CbCr matrix (ITU-R BT.601, BT.709 and BT.2020 non-constant luminance).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Matrix {
|
||||
Bt601,
|
||||
Bt709,
|
||||
Bt2020,
|
||||
}
|
||||
|
||||
impl Matrix {
|
||||
/// The red and blue luma weights, Kr and Kb.
|
||||
pub fn kr_kb(self) -> (f32, f32) {
|
||||
match self {
|
||||
Matrix::Bt601 => (0.299, 0.114),
|
||||
Matrix::Bt709 => (0.2126, 0.0722),
|
||||
Matrix::Bt2020 => (0.2627, 0.0593),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The code values the signal spans.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Range {
|
||||
/// Luma from 16 to 235 and chroma from 16 to 240, scaled by 4 at 10 bits.
|
||||
Limited,
|
||||
/// Every code value, from 0 to 255 (1023 at 10 bits); chroma is centered on 128 (512).
|
||||
Full,
|
||||
}
|
||||
|
||||
/// One conversion: the plane format, the matrix and the range.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Conversion {
|
||||
pub format: Format,
|
||||
pub matrix: Matrix,
|
||||
pub range: Range,
|
||||
}
|
||||
|
||||
impl Conversion {
|
||||
pub fn new(format: Format, matrix: Matrix, range: Range) -> Conversion {
|
||||
Conversion { format, matrix, range }
|
||||
}
|
||||
}
|
||||
|
||||
/// The weights and the scale of one conversion. The code value of luma is
|
||||
/// `dot(y, rgb) * y_scale + y_offset`, of Cb `dot(cb, rgb) * c_scale + c_offset`, and of Cr
|
||||
/// `dot(cr, rgb) * c_scale + c_offset`, rounded with halves away from zero and clamped to
|
||||
/// `0..=max`, for `rgb` from 0 to 1. That rounding is `INT` in BT.709 and BT.2020 and `Round` in
|
||||
/// BT.2100.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct Coefficients {
|
||||
pub y: [f32; 3],
|
||||
pub cb: [f32; 3],
|
||||
pub cr: [f32; 3],
|
||||
pub y_scale: f32,
|
||||
pub y_offset: f32,
|
||||
pub c_scale: f32,
|
||||
pub c_offset: f32,
|
||||
pub max: f32,
|
||||
}
|
||||
|
||||
impl Coefficients {
|
||||
pub fn of(c: Conversion) -> Coefficients {
|
||||
let (kr, kb) = c.matrix.kr_kb();
|
||||
let kg = 1.0 - kr - kb;
|
||||
let (db, dr) = (2.0 * (1.0 - kb), 2.0 * (1.0 - kr));
|
||||
let bits = c.format.bits();
|
||||
let max = ((1u32 << bits) - 1) as f32;
|
||||
let step = (1u32 << (bits - 8)) as f32;
|
||||
let (y_scale, y_offset, c_scale, c_offset) = match c.range {
|
||||
Range::Limited => (219.0 * step, 16.0 * step, 224.0 * step, 128.0 * step),
|
||||
Range::Full => (max, 0.0, max, (1u32 << (bits - 1)) as f32),
|
||||
};
|
||||
Coefficients { y: [kr, kg, kb], cb: [-kr / db, -kg / db, 0.5], cr: [0.5, -kg / dr, -kb / dr], y_scale, y_offset, c_scale, c_offset, max }
|
||||
}
|
||||
|
||||
/// The code values of luma, Cb and Cr for `rgb`.
|
||||
pub fn codes(&self, rgb: [f32; 3]) -> [u16; 3] {
|
||||
let dot = |w: [f32; 3]| w[0] * rgb[0] + w[1] * rgb[1] + w[2] * rgb[2];
|
||||
let code = |v: f32| v.round().clamp(0.0, self.max) as u16;
|
||||
[
|
||||
code(dot(self.y) * self.y_scale + self.y_offset),
|
||||
code(dot(self.cb) * self.c_scale + self.c_offset),
|
||||
code(dot(self.cr) * self.c_scale + self.c_offset),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// What a conversion cannot do.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
/// An output side is zero or odd; 4:2:0 needs both sides even.
|
||||
OutputSize { width: u32, height: u32 },
|
||||
/// A side is larger than the device's largest 2D texture.
|
||||
TooLarge { width: u32, height: u32, limit: u32 },
|
||||
/// The frame's byte sizes do not fit in the integer types that hold them.
|
||||
Overflow { width: u32, height: u32 },
|
||||
/// A buffer the job uses (the RGBA8 input, or the read-back buffer for the frame) would be
|
||||
/// larger than the device's largest buffer.
|
||||
BufferLimit { needed: u64, limit: u64 },
|
||||
/// A source side is zero, or the pixels are not `width × height × 4` bytes.
|
||||
Source { width: u32, height: u32, bytes: usize },
|
||||
/// A buffer or a frame does not have the size the layout needs.
|
||||
BufferSize { needed: u64, actual: u64 },
|
||||
/// A buffer offset is not a multiple of `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`.
|
||||
Offset(u64),
|
||||
/// The planes were made for another format than the converter's.
|
||||
Mismatch { converter: Format, planes: Format },
|
||||
/// A frame layout's fields are not what [`crate::FrameLayout::new`] gives for its format and
|
||||
/// size.
|
||||
Layout,
|
||||
/// A buffer of `bytes` bytes for the frame could not be allocated.
|
||||
Memory { bytes: usize },
|
||||
/// The device reported an error (validation, out of memory, a failed map or poll) while
|
||||
/// [`crate::YuvProvider`] ran a job on it.
|
||||
Device(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Error::OutputSize { width, height } => write!(f, "a 4:2:0 picture of {width}×{height} needs both sides even and not zero"),
|
||||
Error::TooLarge { width, height, limit } => write!(f, "{width}×{height} is larger than the largest texture side, {limit}"),
|
||||
Error::Overflow { width, height } => write!(f, "a frame of {width}×{height} is too large to hold"),
|
||||
Error::BufferLimit { needed, limit } => write!(f, "a buffer of {needed} bytes is larger than the largest buffer, {limit}"),
|
||||
Error::Source { width, height, bytes } => write!(f, "{bytes} bytes are not an RGBA picture of {width}×{height}"),
|
||||
Error::BufferSize { needed, actual } => write!(f, "{actual} bytes where {needed} are needed"),
|
||||
Error::Offset(offset) => write!(f, "buffer offset {offset} is not a multiple of {}", wgpu::COPY_BYTES_PER_ROW_ALIGNMENT),
|
||||
Error::Mismatch { converter, planes } => write!(f, "{planes} planes given to a {converter} converter"),
|
||||
Error::Layout => f.write_str("the frame layout does not match its format and size"),
|
||||
Error::Memory { bytes } => write!(f, "a buffer of {bytes} bytes could not be allocated"),
|
||||
Error::Device(message) => write!(f, "the device reported an error: {message}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
@@ -0,0 +1,468 @@
|
||||
use super::*;
|
||||
|
||||
const ALL: [Format; 3] = [Format::Nv12, Format::P010, Format::I420];
|
||||
const MATRICES: [Matrix; 3] = [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020];
|
||||
const RANGES: [Range; 2] = [Range::Limited, Range::Full];
|
||||
|
||||
fn solid(w: u32, h: u32, rgb: [u8; 3]) -> Vec<u8> {
|
||||
(0..w * h).flat_map(|_| [rgb[0], rgb[1], rgb[2], 255]).collect()
|
||||
}
|
||||
|
||||
/// The first luma sample and the first Cb and Cr samples of a converted frame, as values.
|
||||
fn first(frame: &[u8], format: Format, w: u32, h: u32) -> [u16; 3] {
|
||||
let s = samples(frame, format);
|
||||
let luma = (w * h) as usize;
|
||||
let quarter = luma / 4;
|
||||
match format {
|
||||
Format::Nv12 | Format::P010 => [s[0], s[luma], s[luma + 1]],
|
||||
Format::I420 => [s[0], s[luma], s[luma + quarter]],
|
||||
}
|
||||
}
|
||||
|
||||
/// Every sample of a frame as its value (P010 words shifted down by 6).
|
||||
fn samples(frame: &[u8], format: Format) -> Vec<u16> {
|
||||
match format {
|
||||
Format::P010 => frame.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b) >> 6).collect(),
|
||||
Format::Nv12 | Format::I420 => frame.iter().map(|&b| u16::from(b)).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn cpu(rgb: [u8; 3], c: Conversion) -> [u16; 3] {
|
||||
let frame = cpu::convert(&solid(2, 2, rgb), 2, 2, c, 2, 2).unwrap();
|
||||
first(&frame, c.format, 2, 2)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bt709_limited_colors_have_their_standard_codes() {
|
||||
let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited);
|
||||
assert_eq!(cpu([255, 255, 255], c), [235, 128, 128]);
|
||||
assert_eq!(cpu([0, 0, 0], c), [16, 128, 128]);
|
||||
assert_eq!(cpu([255, 0, 0], c), [63, 102, 240]);
|
||||
assert_eq!(cpu([0, 0, 255], c), [32, 240, 118]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_matrix_weights_red_by_its_kr() {
|
||||
let red = |m| cpu([255, 0, 0], Conversion::new(Format::Nv12, m, Range::Limited));
|
||||
assert_eq!(red(Matrix::Bt601), [81, 90, 240]);
|
||||
assert_eq!(red(Matrix::Bt2020), [74, 97, 240]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_range_spans_every_code() {
|
||||
let c = Conversion::new(Format::I420, Matrix::Bt709, Range::Full);
|
||||
assert_eq!(cpu([255, 255, 255], c), [255, 128, 128]);
|
||||
assert_eq!(cpu([0, 0, 0], c), [0, 128, 128]);
|
||||
assert_eq!(cpu([255, 0, 0], c), [54, 99, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn p010_holds_ten_bit_codes_in_the_high_bits() {
|
||||
let limited = Conversion::new(Format::P010, Matrix::Bt2020, Range::Limited);
|
||||
assert_eq!(cpu([255, 255, 255], limited), [940, 512, 512]);
|
||||
assert_eq!(cpu([0, 0, 0], limited), [64, 512, 512]);
|
||||
let full = Conversion::new(Format::P010, Matrix::Bt2020, Range::Full);
|
||||
assert_eq!(cpu([255, 255, 255], full), [1023, 512, 512]);
|
||||
let frame = cpu::convert(&solid(2, 2, [255, 255, 255]), 2, 2, limited, 2, 2).unwrap();
|
||||
assert_eq!(&frame[..2], &(940u16 << 6).to_le_bytes());
|
||||
assert_eq!(frame.len(), 12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn planes_follow_each_format_s_order() {
|
||||
let red = solid(4, 2, [255, 0, 0]);
|
||||
let nv12 = cpu::convert(&red, 4, 2, Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited), 4, 2).unwrap();
|
||||
assert_eq!(nv12, [63, 63, 63, 63, 63, 63, 63, 63, 102, 240, 102, 240]);
|
||||
let i420 = cpu::convert(&red, 4, 2, Conversion::new(Format::I420, Matrix::Bt709, Range::Limited), 4, 2).unwrap();
|
||||
assert_eq!(i420, [63, 63, 63, 63, 63, 63, 63, 63, 102, 102, 240, 240]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chroma_at_the_same_size_averages_the_four_pixels_it_covers() {
|
||||
// Red over blue: chroma is the code of their average, magenta at half strength.
|
||||
let mut px = solid(2, 1, [255, 0, 0]);
|
||||
px.extend(solid(2, 1, [0, 0, 255]));
|
||||
let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Full);
|
||||
let frame = cpu::convert(&px, 2, 2, c, 2, 2).unwrap();
|
||||
let half = cpu([128, 0, 128], c);
|
||||
assert!(frame[4].abs_diff(half[1] as u8) <= 1 && frame[5].abs_diff(half[2] as u8) <= 1, "{frame:?} {half:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reduction_averages_the_area_under_each_texel() {
|
||||
// One white column in four: a 4:1 reduction gives a quarter of white, where one bilinear tap
|
||||
// at the texel's center would land between two black columns.
|
||||
let px: Vec<u8> = (0..16).flat_map(|i| if i % 4 == 0 { [255, 255, 255, 255] } else { [0, 0, 0, 255] }).collect();
|
||||
let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Full);
|
||||
let frame = cpu::convert(&px, 8, 2, c, 2, 2).unwrap();
|
||||
assert_eq!(&frame[..4], &[64, 64, 64, 64]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tap_count_grows_with_the_reduction_up_to_four() {
|
||||
assert_eq!([0.5, 1.0, 2.0, 2.01, 4.0, 4.5, 8.0, 100.0].map(cpu::taps), [1, 1, 1, 2, 2, 3, 4, 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_sizes_are_errors() {
|
||||
let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited);
|
||||
let px = solid(2, 2, [0, 0, 0]);
|
||||
assert_eq!(cpu::convert(&px, 2, 2, c, 3, 2).unwrap_err(), Error::OutputSize { width: 3, height: 2 });
|
||||
assert_eq!(cpu::convert(&px, 2, 2, c, 0, 0).unwrap_err(), Error::OutputSize { width: 0, height: 0 });
|
||||
assert_eq!(cpu::convert(&px, 2, 3, c, 2, 2).unwrap_err(), Error::Source { width: 2, height: 3, bytes: 16 });
|
||||
assert_eq!(cpu::convert(&[], 0, 0, c, 2, 2).unwrap_err(), Error::Source { width: 0, height: 0, bytes: 0 });
|
||||
assert_eq!(FrameLayout::new(Format::P010, 4, 5).unwrap_err(), Error::OutputSize { width: 4, height: 5 });
|
||||
let big = cpu::MAX_SIDE + 2;
|
||||
assert_eq!(cpu::convert(&px, 2, 2, c, big, 2).unwrap_err(), Error::TooLarge { width: big, height: 2, limit: cpu::MAX_SIDE });
|
||||
// Byte sizes past the integer types are an error, not an overflow.
|
||||
let huge = u32::MAX - 1;
|
||||
assert_eq!(FrameLayout::new(Format::P010, huge, 2).unwrap_err(), Error::Overflow { width: huge, height: 2 });
|
||||
assert_eq!(FrameLayout::new(Format::Nv12, huge, 2).unwrap_err(), Error::Overflow { width: huge, height: 2 });
|
||||
assert_eq!(Error::OutputSize { width: 3, height: 2 }.to_string(), "a 4:2:0 picture of 3×2 needs both sides even and not zero");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_buffer_that_cannot_be_allocated_is_an_error() {
|
||||
// A request past `isize::MAX` bytes fails on every allocator, so the failure path runs
|
||||
// without exhausting memory.
|
||||
assert_eq!(cpu::reserve::<u8>(usize::MAX).unwrap_err(), Error::Memory { bytes: usize::MAX });
|
||||
assert_eq!(cpu::reserve::<u16>(usize::MAX / 2).unwrap_err(), Error::Memory { bytes: usize::MAX - 1 });
|
||||
let room = cpu::reserve::<u8>(4096).unwrap();
|
||||
assert!(room.is_empty() && room.capacity() >= 4096);
|
||||
assert_eq!(Error::Memory { bytes: 16 }.to_string(), "a buffer of 16 bytes could not be allocated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layouts_pad_rows_for_copies_and_unpack_without_the_padding() {
|
||||
let l = FrameLayout::new(Format::Nv12, 1920, 1080).unwrap();
|
||||
assert_eq!(
|
||||
l.planes.iter().map(|p| (p.width, p.height, p.offset, p.bytes_per_row)).collect::<Vec<_>>(),
|
||||
[(1920, 1080, 0, 2048), (960, 540, 2048 * 1080, 2048)]
|
||||
);
|
||||
assert_eq!((l.buffer_size, l.frame_bytes()), (2048 * 1620, 1920 * 1620));
|
||||
let p = FrameLayout::new(Format::P010, 640, 360).unwrap();
|
||||
assert_eq!((p.planes[0].bytes_per_row, p.planes[1].texel_bytes, p.frame_bytes()), (1280, 4, 640 * 360 * 3));
|
||||
let i = FrameLayout::new(Format::I420, 4, 2).unwrap();
|
||||
assert_eq!(i.planes.iter().map(|p| p.offset).collect::<Vec<_>>(), [0, 512, 768]);
|
||||
let mut padded = vec![0u8; i.buffer_size as usize];
|
||||
padded[..4].copy_from_slice(&[1, 2, 3, 4]);
|
||||
padded[256..260].copy_from_slice(&[5, 6, 7, 8]);
|
||||
padded[512..514].copy_from_slice(&[9, 10]);
|
||||
padded[768..770].copy_from_slice(&[11, 12]);
|
||||
let mut frame = vec![0u8; i.frame_bytes()];
|
||||
i.unpack(&padded, &mut frame).unwrap();
|
||||
assert_eq!(frame, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
|
||||
assert_eq!(i.unpack(&padded[..100], &mut frame).unwrap_err(), Error::BufferSize { needed: 1024, actual: 100 });
|
||||
assert_eq!(i.unpack(&padded, &mut [0; 3]).unwrap_err(), Error::BufferSize { needed: 12, actual: 3 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unpack_refuses_a_layout_that_was_changed_after_it_was_made() {
|
||||
let l = FrameLayout::new(Format::I420, 4, 2).unwrap();
|
||||
let padded = vec![0u8; l.buffer_size as usize];
|
||||
let changes: [fn(&mut FrameLayout); 6] = [
|
||||
|l| l.planes[0].bytes_per_row = 0,
|
||||
|l| l.planes[0].width = 0,
|
||||
|l| l.planes[0].texel_bytes = 0,
|
||||
|l| l.planes[0].offset = 768,
|
||||
|l| l.planes[0].bytes_per_row = 2,
|
||||
|l| l.planes.truncate(1),
|
||||
];
|
||||
for (n, change) in changes.iter().enumerate() {
|
||||
let mut bad = l.clone();
|
||||
change(&mut bad);
|
||||
let mut frame = vec![0u8; bad.frame_bytes()];
|
||||
assert_eq!(bad.unpack(&padded, &mut frame), Err(Error::Layout), "change {n}");
|
||||
}
|
||||
assert_eq!(Error::Layout.to_string(), "the frame layout does not match its format and size");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes_of_a_changed_layout_saturate_instead_of_overflowing() {
|
||||
let mut l = FrameLayout::new(Format::I420, 4, 2).unwrap();
|
||||
let huge = PlaneLayout { width: u32::MAX, height: u32::MAX, texel_bytes: 4, offset: 0, bytes_per_row: 0 };
|
||||
assert_eq!(huge.row_bytes(), u32::MAX);
|
||||
l.planes = vec![PlaneLayout { height: 1, ..huge }];
|
||||
let full = usize::try_from(u64::from(u32::MAX) * 4).unwrap_or(usize::MAX);
|
||||
assert_eq!(l.frame_bytes(), full, "a row past u32::MAX bytes counts in full");
|
||||
l.planes = vec![huge; 3];
|
||||
assert_eq!(l.frame_bytes(), usize::MAX);
|
||||
assert_eq!(l.unpack(&[], &mut []), Err(Error::Layout));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_enlarged_solid_color_keeps_its_codes() {
|
||||
for format in ALL {
|
||||
let c = Conversion::new(format, Matrix::Bt709, Range::Limited);
|
||||
let frame = cpu::convert(&solid(3, 1, [10, 200, 90]), 3, 1, c, 8, 6).unwrap();
|
||||
let expect = cpu([10, 200, 90], c);
|
||||
let s = samples(&frame, format);
|
||||
assert_eq!(s.len(), 8 * 6 * 3 / 2);
|
||||
assert!(s[..48].iter().all(|&v| v == expect[0]), "{format}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaders_write_no_value_wgsl_cannot_read() {
|
||||
for format in ALL {
|
||||
for matrix in MATRICES {
|
||||
for range in RANGES {
|
||||
let s = gpu::shader(Conversion::new(format, matrix, range));
|
||||
assert!(!s.contains("NaN") && !s.contains("inf"), "{s}");
|
||||
assert!(s.contains("fn fs_chroma") && s.contains("fn fs_luma"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The GPU half: the passes against the CPU reference. A machine without a graphics adapter skips
|
||||
// these comparisons and says so on stderr.
|
||||
|
||||
pub(crate) fn device() -> Option<(wgpu::Device, wgpu::Queue)> {
|
||||
device_with(|l| l)
|
||||
}
|
||||
|
||||
/// A device with the adapter's limits as `limits` changes them.
|
||||
pub(crate) fn device_with(limits: impl FnOnce(wgpu::Limits) -> wgpu::Limits) -> Option<(wgpu::Device, wgpu::Queue)> {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
|
||||
let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else {
|
||||
eprintln!("no graphics adapter: the GPU half of this test is skipped");
|
||||
return None;
|
||||
};
|
||||
let desc = wgpu::DeviceDescriptor { required_limits: limits(adapter.limits()), ..Default::default() };
|
||||
match pollster::block_on(adapter.request_device(&desc)) {
|
||||
Ok(d) => Some(d),
|
||||
Err(e) => {
|
||||
eprintln!("the graphics adapter did not open ({e}): the GPU half of this test is skipped");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `src` (its pixels, width and height) converted on the GPU to `out` (width and height).
|
||||
pub(crate) fn gpu_convert(device: &wgpu::Device, queue: &wgpu::Queue, src: (&[u8], u32, u32), c: Conversion, out: (u32, u32)) -> Vec<u8> {
|
||||
let ((rgba, sw, sh), (w, h)) = (src, out);
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: None,
|
||||
size: wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
queue.write_texture(
|
||||
texture.as_image_copy(),
|
||||
rgba,
|
||||
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(sw * 4), rows_per_image: Some(sh) },
|
||||
wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 },
|
||||
);
|
||||
let converter = Converter::new(device, c);
|
||||
let source = converter.bind(device, &texture.create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
let planes = converter.planes(device, w, h).unwrap();
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: 256 + planes.layout().buffer_size,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
|
||||
converter.draw(&mut enc, &source, &planes).unwrap();
|
||||
planes.copy_to_buffer(&mut enc, &buffer, 256).unwrap();
|
||||
queue.submit([enc.finish()]);
|
||||
buffer.map_async(wgpu::MapMode::Read, 256.., |r| r.unwrap());
|
||||
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
|
||||
let view = buffer.get_mapped_range(256..).unwrap();
|
||||
let mut frame = vec![0; planes.layout().frame_bytes()];
|
||||
planes.layout().unpack(&view, &mut frame).unwrap();
|
||||
frame
|
||||
}
|
||||
|
||||
/// The tolerance in code values: 2 at 8 bits and 6 at 10 bits. GPUs filter with fewer bits of
|
||||
/// weight than `f32` and may round a half the other way.
|
||||
fn tolerance(format: Format) -> u16 {
|
||||
if format.bits() == 10 { 6 } else { 2 }
|
||||
}
|
||||
|
||||
pub(crate) fn assert_close(gpu: &[u8], cpu: &[u8], c: Conversion, what: &str) {
|
||||
assert_eq!(gpu.len(), cpu.len(), "{what}");
|
||||
let (g, k) = (samples(gpu, c.format), samples(cpu, c.format));
|
||||
let worst = g.iter().zip(&k).enumerate().max_by_key(|(_, (a, b))| a.abs_diff(**b));
|
||||
if let Some((i, (a, b))) = worst {
|
||||
assert!(a.abs_diff(*b) <= tolerance(c.format), "{what} {c:?}: sample {i} is {a} on the GPU and {b} on the CPU");
|
||||
}
|
||||
}
|
||||
|
||||
/// A picture with hard edges: each pixel's channels from a fixed pseudo-random sequence.
|
||||
pub(crate) fn noise(w: u32, h: u32) -> Vec<u8> {
|
||||
let mut x = 0x2545_f491_u32;
|
||||
(0..w * h * 4)
|
||||
.map(|i| {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
if i % 4 == 3 { 255 } else { (x >> 24) as u8 }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A smooth picture: three ramps at different angles.
|
||||
pub(crate) fn ramps(w: u32, h: u32) -> Vec<u8> {
|
||||
(0..h)
|
||||
.flat_map(|y| {
|
||||
(0..w).flat_map(move |x| {
|
||||
let (u, v) = (x as f32 / w as f32, y as f32 / h as f32);
|
||||
[(u * 255.0) as u8, (v * 255.0) as u8, ((1.0 - (u + v) * 0.5) * 255.0) as u8, 255]
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gpu_matches_the_cpu_at_the_same_size() {
|
||||
let Some((device, queue)) = device() else { return };
|
||||
let px = noise(64, 36);
|
||||
for format in ALL {
|
||||
for matrix in MATRICES {
|
||||
for range in RANGES {
|
||||
let c = Conversion::new(format, matrix, range);
|
||||
let g = gpu_convert(&device, &queue, (&px, 64, 36), c, (64, 36));
|
||||
assert_close(&g, &cpu::convert(&px, 64, 36, c, 64, 36).unwrap(), c, "64×36 at the same size");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gpu_matches_the_cpu_when_scaling() {
|
||||
let Some((device, queue)) = device() else { return };
|
||||
let px = ramps(160, 90);
|
||||
for format in ALL {
|
||||
let c = Conversion::new(format, Matrix::Bt709, Range::Limited);
|
||||
for (w, h) in [(80, 46), (32, 18), (16, 10), (240, 136)] {
|
||||
let g = gpu_convert(&device, &queue, (&px, 160, 90), c, (w, h));
|
||||
assert_close(&g, &cpu::convert(&px, 160, 90, c, w, h).unwrap(), c, &format!("160×90 to {w}×{h}"));
|
||||
}
|
||||
let odd = ramps(37, 23);
|
||||
let g = gpu_convert(&device, &queue, (&odd, 37, 23), c, (20, 12));
|
||||
assert_close(&g, &cpu::convert(&odd, 37, 23, c, 20, 12).unwrap(), c, "37×23 to 20×12");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gpu_rounds_a_value_just_below_a_half_down() {
|
||||
let Some((device, queue)) = device() else { return };
|
||||
// The shader's own code(), driven by one extra entry point. The values are built from the
|
||||
// texel position so that no compiler folds them: k is 0 at the only texel's center.
|
||||
// 0x3effffff is 0.49999997, the largest f32 below 0.5, and 0x3f7fffff is 0.99999994.
|
||||
let probe = "@fragment fn fs_probe(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<u32> {
|
||||
let k = u32(pos.x);
|
||||
let z = f32(k);
|
||||
return vec4<u32>(code(bitcast<f32>(0x3effffffu + k)), code(0.5 + z), code(2.5 + z), code(bitcast<f32>(0x3f7fffffu + k)));
|
||||
}";
|
||||
let wgsl = gpu::shader(Conversion::new(Format::Nv12, Matrix::Bt709, Range::Full)) + probe;
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(wgsl.into()) });
|
||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: None,
|
||||
layout: None,
|
||||
vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() },
|
||||
primitive: wgpu::PrimitiveState::default(),
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &module,
|
||||
entry_point: Some("fs_probe"),
|
||||
targets: &[Some(wgpu::ColorTargetState { format: wgpu::TextureFormat::Rgba8Uint, blend: None, write_mask: wgpu::ColorWrites::ALL })],
|
||||
compilation_options: Default::default(),
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: None,
|
||||
size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Uint,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
||||
view_formats: &[],
|
||||
});
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: 256,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
|
||||
{
|
||||
let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: None,
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store },
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
pass.set_pipeline(&pipeline);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
enc.copy_texture_to_buffer(
|
||||
texture.as_image_copy(),
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &buffer,
|
||||
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256), rows_per_image: Some(1) },
|
||||
},
|
||||
wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
|
||||
);
|
||||
queue.submit([enc.finish()]);
|
||||
buffer.map_async(wgpu::MapMode::Read, .., |r| r.unwrap());
|
||||
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
|
||||
let got = buffer.get_mapped_range(..4).unwrap().to_vec();
|
||||
assert_eq!(got, [0, 1, 3, 1], "code() of 0.49999997, 0.5, 2.5 and 0.99999994");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn planes_larger_than_the_device_allows_are_errors() {
|
||||
// The queue stays alive: a device whose queue was dropped cannot make an encoder.
|
||||
let Some((device, _queue)) = device() else { return };
|
||||
let converter = Converter::new(&device, Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited));
|
||||
let limit = device.limits().max_texture_dimension_2d;
|
||||
let too_big = (limit + 2) & !1;
|
||||
assert_eq!(converter.planes(&device, too_big, 2).err(), Some(Error::TooLarge { width: too_big, height: 2, limit }));
|
||||
let planes = converter.planes(&device, 4, 2).unwrap();
|
||||
let other = Converter::new(&device, Conversion::new(Format::P010, Matrix::Bt709, Range::Limited));
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: None,
|
||||
size: wgpu::Extent3d { width: 4, height: 2, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
});
|
||||
let source = other.bind(&device, &texture.create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
|
||||
assert_eq!(other.draw(&mut enc, &source, &planes).unwrap_err(), Error::Mismatch { converter: Format::P010, planes: Format::Nv12 });
|
||||
let small =
|
||||
device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 256, usage: wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
|
||||
assert_eq!(planes.copy_to_buffer(&mut enc, &small, 0).unwrap_err(), Error::BufferSize { needed: 768, actual: 256 });
|
||||
assert_eq!(planes.copy_to_buffer(&mut enc, &small, 4).unwrap_err(), Error::Offset(4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn planes_whose_read_back_is_larger_than_the_largest_buffer_are_errors() {
|
||||
let Some((device, _queue)) = device_with(|l| wgpu::Limits { max_buffer_size: 1 << 20, ..l }) else { return };
|
||||
let converter = Converter::new(&device, Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited));
|
||||
// 1024 × 1024 NV12 reads back 1.5 MiB.
|
||||
assert_eq!(converter.planes(&device, 1024, 1024).err(), Some(Error::BufferLimit { needed: 1024 * 1536, limit: 1 << 20 }));
|
||||
assert!(converter.planes(&device, 512, 512).is_ok());
|
||||
}
|
||||
@@ -747,8 +747,8 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
|
||||
let tl = {
|
||||
let mut l = tiff::decoder::Limits::default();
|
||||
l.decoding_buffer_size = limits.alloc_usize();
|
||||
// No compressed chunk can be larger than the file.
|
||||
l.intermediate_buffer_size = f.b.len().max(1);
|
||||
// Each compressed chunk must fit both the file and the allocation budget.
|
||||
l.intermediate_buffer_size = f.b.len().max(1).min(limits.alloc_usize());
|
||||
l
|
||||
};
|
||||
let mut dec = Decoder::new(Patched { b: f.b, patches: &patches, pos: 0 }).map(|d| d.with_limits(tl.clone())).map_err(map_err)?;
|
||||
|
||||
+1094
-44
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,8 @@
|
||||
# craft-mcp
|
||||
|
||||
Transport-independent MCP server initialization and tool result helpers.
|
||||
Transport-independent MCP 2025-03-26 server initialization and result helpers for tools,
|
||||
resources, prompts and completion.
|
||||
Use one `Session` per client connection with `craft-jsonrpc` for message parsing and
|
||||
batch dispatch. The caller owns transport, tool definitions and execution, response
|
||||
size limits, and shutdown. Pass the outer envelope's batch status to `Session::request`.
|
||||
@@ -50,3 +52,25 @@ outside the roots.
|
||||
|
||||
See the [MCP lifecycle specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle)
|
||||
and the [2025-06-18 changes](https://modelcontextprotocol.io/specification/2025-06-18/changelog).
|
||||
|
||||
The crate also checks the parameters of the resource, prompt and completion methods and
|
||||
builds their results, for a server that routes those methods itself:
|
||||
|
||||
- `page` takes one page of a list from the request's `cursor`, and `resource_list`,
|
||||
`resource_template_list` and `prompt_list` wrap the page with its `nextCursor`. A
|
||||
cursor must be a canonical positive decimal offset divisible by the page size;
|
||||
malformed cursors are rejected with -32602. The helper returns an empty last page
|
||||
for a cursor past the list's end, including after the list shrinks.
|
||||
- `resource_read` returns the requested URI. `text_contents`, `blob_contents` and
|
||||
`read_result` build the `resources/read` result, and `resource_not_found` is the
|
||||
-32002 error with the URI in its data.
|
||||
- `prompt_get` returns the prompt name and its string arguments. `prompt_result` and
|
||||
`text_message` build the `prompts/get` result.
|
||||
- `completion_request` returns the prompt or resource reference and the argument being
|
||||
completed. `completion_result` keeps the first 100 values and sets `total` and `hasMore`.
|
||||
|
||||
See the [pagination](https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/pagination),
|
||||
[resources](https://modelcontextprotocol.io/specification/2025-03-26/server/resources),
|
||||
[prompts](https://modelcontextprotocol.io/specification/2025-03-26/server/prompts) and
|
||||
[completion](https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/completion)
|
||||
specifications.
|
||||
+280
-2
@@ -1,11 +1,14 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
//! MCP server initialization and tool envelopes, independent of transport and tools. Sessions
|
||||
//! answer 2025-03-26 by default and can negotiate any of `SUPPORTED_PROTOCOL_VERSIONS`.
|
||||
//! MCP server initialization and the envelopes of tools, resources, prompts and completion,
|
||||
//! independent of transport and of what the server serves. Sessions answer 2025-03-26 by default
|
||||
//! and can negotiate any of `SUPPORTED_PROTOCOL_VERSIONS`.
|
||||
//! The caller owns routing, transport and JSON-RPC batching. Compatibility mode preserves servers
|
||||
//! that accepted calls before initialization and initialize in a batch; strict mode enforces the
|
||||
//! initialization ordering and batch prohibition. Create one session per connection.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use craft_jsonrpc::{Limits, Request, RpcError};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -238,6 +241,196 @@ pub fn text_tool_result(text: &str, is_error: bool) -> Value {
|
||||
json!({"content": [{"type": "text", "text": text}], "isError": is_error})
|
||||
}
|
||||
|
||||
/// Most values one `completion/complete` result may carry.
|
||||
pub const MAX_COMPLETIONS: usize = 100;
|
||||
|
||||
/// One page of a `resources/list`, `resources/templates/list` or `prompts/list` result.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Page {
|
||||
pub items: Vec<Value>,
|
||||
/// The cursor a client sends to get the next page; `None` on the last page.
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
|
||||
impl Page {
|
||||
/// Every item in one page, for a server that does not paginate.
|
||||
pub fn all(items: Vec<Value>) -> Self {
|
||||
Self { items, next_cursor: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the page of `items` that starts at the `cursor` in a list request's parameters, with at most
|
||||
/// `page_size` items (0 puts every item in one page). The helper accepts canonical positive
|
||||
/// decimal offsets divisible by `page_size`. Parameters that are not an object, and malformed
|
||||
/// cursors, are rejected with -32602. The helper returns an empty last page for a cursor past
|
||||
/// the list's end, including after the list shrinks.
|
||||
pub fn page(params: Option<&Value>, mut items: Vec<Value>, page_size: usize) -> Result<Page, RpcError> {
|
||||
if params.is_some_and(|p| !p.is_object()) {
|
||||
return Err(RpcError::new(-32602, "List parameters must be an object"));
|
||||
}
|
||||
let start = match params.and_then(|p| p.get("cursor")) {
|
||||
None => 0,
|
||||
Some(Value::String(cursor)) => match cursor.parse::<usize>() {
|
||||
Ok(offset) if page_size > 0 && offset > 0 && offset % page_size == 0 && offset.to_string() == *cursor => offset,
|
||||
_ => return Err(invalid_cursor()),
|
||||
},
|
||||
Some(_) => return Err(invalid_cursor()),
|
||||
};
|
||||
let start = start.min(items.len());
|
||||
items.drain(..start);
|
||||
let mut next_cursor = None;
|
||||
if page_size > 0 && items.len() > page_size {
|
||||
items.truncate(page_size);
|
||||
next_cursor = Some((start + page_size).to_string());
|
||||
}
|
||||
Ok(Page { items, next_cursor })
|
||||
}
|
||||
|
||||
fn invalid_cursor() -> RpcError {
|
||||
RpcError::new(-32602, "Invalid cursor")
|
||||
}
|
||||
|
||||
/// Wrap a page of MCP `Resource` objects in the `resources/list` result.
|
||||
pub fn resource_list(page: Page) -> Value {
|
||||
list_result("resources", page)
|
||||
}
|
||||
|
||||
/// Wrap a page of MCP `ResourceTemplate` objects in the `resources/templates/list` result.
|
||||
pub fn resource_template_list(page: Page) -> Value {
|
||||
list_result("resourceTemplates", page)
|
||||
}
|
||||
|
||||
/// Wrap a page of MCP `Prompt` objects in the `prompts/list` result.
|
||||
pub fn prompt_list(page: Page) -> Value {
|
||||
list_result("prompts", page)
|
||||
}
|
||||
|
||||
fn list_result(key: &str, page: Page) -> Value {
|
||||
let mut result = serde_json::Map::new();
|
||||
result.insert(key.to_owned(), Value::Array(page.items));
|
||||
if let Some(cursor) = page.next_cursor {
|
||||
result.insert("nextCursor".to_owned(), Value::String(cursor));
|
||||
}
|
||||
Value::Object(result)
|
||||
}
|
||||
|
||||
/// Validate `resources/read` parameters and return the requested URI.
|
||||
pub fn resource_read(params: &Value) -> Result<&str, RpcError> {
|
||||
params.get("uri").and_then(Value::as_str).ok_or_else(|| RpcError::new(-32602, "Missing resource URI"))
|
||||
}
|
||||
|
||||
/// The error MCP specifies for a `resources/read` of a URI the server does not have.
|
||||
pub fn resource_not_found(uri: &str) -> RpcError {
|
||||
RpcError { code: -32002, message: "Resource not found".into(), data: Some(json!({"uri": uri})) }
|
||||
}
|
||||
|
||||
/// Text contents of a resource, for [`read_result`].
|
||||
pub fn text_contents(uri: &str, mime_type: Option<&str>, text: &str) -> Value {
|
||||
contents(uri, mime_type, "text", text)
|
||||
}
|
||||
|
||||
/// Binary contents of a resource, for [`read_result`]. `base64` is the data in standard base64.
|
||||
pub fn blob_contents(uri: &str, mime_type: Option<&str>, base64: &str) -> Value {
|
||||
contents(uri, mime_type, "blob", base64)
|
||||
}
|
||||
|
||||
fn contents(uri: &str, mime_type: Option<&str>, key: &str, value: &str) -> Value {
|
||||
let mut result = serde_json::Map::new();
|
||||
result.insert("uri".to_owned(), json!(uri));
|
||||
if let Some(mime_type) = mime_type {
|
||||
result.insert("mimeType".to_owned(), json!(mime_type));
|
||||
}
|
||||
result.insert(key.to_owned(), json!(value));
|
||||
Value::Object(result)
|
||||
}
|
||||
|
||||
/// Wrap resource contents in the `resources/read` result.
|
||||
pub fn read_result(contents: Vec<Value>) -> Value {
|
||||
json!({"contents": contents})
|
||||
}
|
||||
|
||||
/// Validate `prompts/get` parameters and return the prompt name and its arguments. MCP prompt
|
||||
/// arguments are strings, so an argument of any other type is rejected with -32602.
|
||||
pub fn prompt_get(params: &Value) -> Result<(&str, BTreeMap<&str, &str>), RpcError> {
|
||||
let name = params.get("name").and_then(Value::as_str).ok_or_else(|| RpcError::new(-32602, "Missing prompt name"))?;
|
||||
let arguments = match params.get("arguments") {
|
||||
None => BTreeMap::new(),
|
||||
Some(Value::Object(map)) => map
|
||||
.iter()
|
||||
.map(|(key, value)| value.as_str().map(|v| (key.as_str(), v)))
|
||||
.collect::<Option<BTreeMap<_, _>>>()
|
||||
.ok_or_else(|| RpcError::new(-32602, "Prompt arguments must be strings"))?,
|
||||
Some(_) => return Err(RpcError::new(-32602, "Prompt arguments must be an object")),
|
||||
};
|
||||
Ok((name, arguments))
|
||||
}
|
||||
|
||||
/// Wrap prompt messages (MCP `PromptMessage` objects) in the `prompts/get` result.
|
||||
pub fn prompt_result(description: Option<&str>, messages: Vec<Value>) -> Value {
|
||||
let mut result = json!({"messages": messages});
|
||||
if let Some(description) = description {
|
||||
result["description"] = json!(description);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// A prompt message with one text block, from `"user"` or `"assistant"`.
|
||||
pub fn text_message(role: &str, text: &str) -> Value {
|
||||
json!({"role": role, "content": {"type": "text", "text": text}})
|
||||
}
|
||||
|
||||
/// What a `completion/complete` request refers to.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CompletionRef<'a> {
|
||||
/// A prompt, by name (`ref/prompt`).
|
||||
Prompt(&'a str),
|
||||
/// A resource or resource template, by URI or URI template (`ref/resource`).
|
||||
Resource(&'a str),
|
||||
}
|
||||
|
||||
/// The parameters of a `completion/complete` request.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Completion<'a> {
|
||||
pub reference: CompletionRef<'a>,
|
||||
/// The name of the argument being completed.
|
||||
pub argument: &'a str,
|
||||
/// What the user has typed for it so far.
|
||||
pub value: &'a str,
|
||||
}
|
||||
|
||||
/// Validate `completion/complete` parameters.
|
||||
pub fn completion_request(params: &Value) -> Result<Completion<'_>, RpcError> {
|
||||
let invalid = |message: &str| RpcError::new(-32602, message);
|
||||
let reference = params.get("ref").ok_or_else(|| invalid("Missing completion reference"))?;
|
||||
let field = |key: &str| reference.get(key).and_then(Value::as_str);
|
||||
let reference = match reference.get("type").and_then(Value::as_str) {
|
||||
Some("ref/prompt") => CompletionRef::Prompt(field("name").ok_or_else(|| invalid("Missing prompt name"))?),
|
||||
Some("ref/resource") => CompletionRef::Resource(field("uri").ok_or_else(|| invalid("Missing resource URI"))?),
|
||||
_ => return Err(invalid("Unknown completion reference type")),
|
||||
};
|
||||
let argument = params.get("argument");
|
||||
let text = |key: &str| argument.and_then(|a| a.get(key)).and_then(Value::as_str);
|
||||
let (Some(name), Some(value)) = (text("name"), text("value")) else {
|
||||
return Err(invalid("Completion argument needs a name and a value"));
|
||||
};
|
||||
Ok(Completion { reference, argument: name, value })
|
||||
}
|
||||
|
||||
/// Build the `completion/complete` result from every matching value. The result carries the first
|
||||
/// [`MAX_COMPLETIONS`] values, the number of matches in `total`, and whether any were left out in
|
||||
/// `hasMore`.
|
||||
pub fn completion_result(values: impl IntoIterator<Item = String>) -> Value {
|
||||
let mut kept = Vec::new();
|
||||
let mut total = 0usize;
|
||||
for value in values {
|
||||
if kept.len() < MAX_COMPLETIONS {
|
||||
kept.push(value);
|
||||
}
|
||||
total += 1;
|
||||
}
|
||||
json!({"completion": {"values": kept, "total": total, "hasMore": total > MAX_COMPLETIONS}})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -423,4 +616,89 @@ mod tests {
|
||||
assert_eq!(reply[1]["result"]["tools"], json!([]));
|
||||
assert_eq!(session.borrow().state(), State::Ready);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_pages_follow_their_cursors_to_the_end() {
|
||||
let items: Vec<Value> = (0..5).map(|i| json!({"name": i})).collect();
|
||||
let mut params = None;
|
||||
let mut names = Vec::new();
|
||||
let mut pages = 0;
|
||||
loop {
|
||||
let page = page(params.as_ref(), items.clone(), 2).unwrap();
|
||||
let result = prompt_list(page);
|
||||
pages += 1;
|
||||
names.extend(result["prompts"].as_array().unwrap().iter().map(|p| p["name"].clone()));
|
||||
match result.get("nextCursor") {
|
||||
Some(cursor) => params = Some(json!({"cursor": cursor})),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
assert_eq!((pages, names), (3, (0..5).map(|i| json!(i)).collect::<Vec<_>>()));
|
||||
assert_eq!(resource_list(page(None, items.clone(), 0).unwrap()), json!({"resources": items}));
|
||||
let past_the_end = page(Some(&json!({"cursor": "8"})), items, 2).unwrap();
|
||||
assert_eq!(resource_template_list(past_the_end), json!({"resourceTemplates": []}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_cursors_that_were_not_handed_out_are_invalid_params() {
|
||||
for cursor in [json!(""), json!("-1"), json!("+1"), json!("1.0"), json!("abc"), json!(2), json!(null), json!("99999999999999999999999")] {
|
||||
let error = page(Some(&json!({"cursor": cursor})), vec![json!(1)], 1).unwrap_err();
|
||||
assert_eq!(error.code, -32602, "{cursor}");
|
||||
}
|
||||
for cursor in ["1", "02", "0"] {
|
||||
assert_eq!(page(Some(&json!({"cursor": cursor})), vec![json!(1); 5], 2).unwrap_err().code, -32602, "{cursor}");
|
||||
}
|
||||
assert_eq!(page(Some(&json!({"cursor": "2"})), vec![json!(1); 5], 0).unwrap_err().code, -32602);
|
||||
for params in [json!(null), json!([]), json!("0")] {
|
||||
assert_eq!(page(Some(¶ms), vec![json!(1)], 1).unwrap_err().code, -32602, "{params}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_reads_validate_the_uri_and_build_contents() {
|
||||
assert_eq!(resource_read(&json!({"uri": "x://a"})).unwrap(), "x://a");
|
||||
assert_eq!(resource_read(&json!({"uri": 1})).unwrap_err().code, -32602);
|
||||
let missing = resource_not_found("x://b");
|
||||
assert_eq!((missing.code, missing.data), (-32002, Some(json!({"uri": "x://b"}))));
|
||||
let result = read_result(vec![text_contents("x://a", Some("text/markdown"), "# A"), blob_contents("x://c", None, "AAE=")]);
|
||||
assert_eq!(result, json!({"contents": [{"uri": "x://a", "mimeType": "text/markdown", "text": "# A"}, {"uri": "x://c", "blob": "AAE="}]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_arguments_must_be_strings() {
|
||||
let params = json!({"name": "describe", "arguments": {"part": "bracket"}});
|
||||
let (name, args) = prompt_get(¶ms).unwrap();
|
||||
assert_eq!((name, args.get("part").copied()), ("describe", Some("bracket")));
|
||||
assert!(prompt_get(&json!({"name": "describe"})).unwrap().1.is_empty());
|
||||
for params in [json!({}), json!({"name": "d", "arguments": {"n": 1}}), json!({"name": "d", "arguments": ["x"]})] {
|
||||
assert_eq!(prompt_get(¶ms).unwrap_err().code, -32602, "{params}");
|
||||
}
|
||||
let result = prompt_result(Some("Describe a part"), vec![text_message("user", "Describe bracket")]);
|
||||
assert_eq!(result["messages"][0]["content"], json!({"type": "text", "text": "Describe bracket"}));
|
||||
assert_eq!(result["description"], "Describe a part");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_requests_name_a_prompt_or_a_resource() {
|
||||
let prompt = json!({"ref": {"type": "ref/prompt", "name": "describe"}, "argument": {"name": "part", "value": "br"}});
|
||||
assert_eq!(completion_request(&prompt).unwrap(), Completion { reference: CompletionRef::Prompt("describe"), argument: "part", value: "br" });
|
||||
let resource = json!({"ref": {"type": "ref/resource", "uri": "lib://parts/{part}"}, "argument": {"name": "part", "value": ""}});
|
||||
assert_eq!(completion_request(&resource).unwrap().reference, CompletionRef::Resource("lib://parts/{part}"));
|
||||
for params in [
|
||||
json!({"ref": {"type": "ref/tool", "name": "x"}, "argument": {"name": "a", "value": ""}}),
|
||||
json!({"ref": {"type": "ref/prompt"}, "argument": {"name": "a", "value": ""}}),
|
||||
json!({"ref": {"type": "ref/prompt", "name": "x"}, "argument": {"name": "a"}}),
|
||||
json!({"argument": {"name": "a", "value": ""}}),
|
||||
] {
|
||||
assert_eq!(completion_request(¶ms).unwrap_err().code, -32602, "{params}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_results_carry_at_most_a_hundred_values() {
|
||||
let result = completion_result((0..150).map(|i| i.to_string()));
|
||||
assert_eq!(result["completion"]["values"].as_array().map(Vec::len), Some(MAX_COMPLETIONS));
|
||||
assert_eq!((&result["completion"]["total"], &result["completion"]["hasMore"]), (&json!(150), &json!(true)));
|
||||
assert_eq!(completion_result(["a".to_owned()]), json!({"completion": {"values": ["a"], "total": 1, "hasMore": false}}));
|
||||
}
|
||||
}
|
||||
@@ -10,16 +10,25 @@ repository.workspace = true
|
||||
[features]
|
||||
default = []
|
||||
parallel = ["dep:rayon"]
|
||||
# The conversion from craft-mesh's glTF metallic-roughness material.
|
||||
mesh = ["dep:craft-mesh"]
|
||||
# The conversion from craft-materialx's resolved shader inputs.
|
||||
materialx = ["dep:craft-materialx"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-materialx = { workspace = true, optional = true }
|
||||
craft-mesh = { path = "../mesh", default-features = false, optional = true }
|
||||
craft-texture = { workspace = true }
|
||||
rayon = { workspace = true, optional = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-materialx = { workspace = true }
|
||||
craft-mesh = { path = "../mesh", default-features = false }
|
||||
craft-pbr = { path = ".", features = ["parallel", "mesh", "materialx"] }
|
||||
# The differential tests run verbatim copies of the apps' previous code, which uses glam and rayon.
|
||||
glam = "0.30"
|
||||
# Parses and validates the WGSL text of `SHADE_WGSL`.
|
||||
|
||||
+41
-2
@@ -109,8 +109,47 @@ It has no UI, does no file or network I/O and has no `unsafe` code.
|
||||
`PbrError::BadDirection`.
|
||||
After size and byte checks pass, a filtering work count above `u64::MAX` returns
|
||||
`PbrError::BadOption`, including when `max_work` is `u64::MAX`. `hammersley` returns coordinates in `0..1`.
|
||||
- **Features.** `parallel` computes rows on several threads with rayon. The default build is
|
||||
serial and builds for `wasm32-unknown-unknown`. Results are the same either way.
|
||||
- **Surfaces.** A `Surface` holds a `Material` and the state a renderer applies around it: alpha
|
||||
and `AlphaMode`, linear emission, the double-sided and unlit flags, optional `Clearcoat` and
|
||||
`Sheen` layers, `TextureBinding`s (the image or file, UV set, wrap modes, UV transform, encoding
|
||||
and a scale) and `other_inputs`. Textures are not loaded. `try_direct` shades only the
|
||||
`Material`; the layers, textures and other inputs are kept for a renderer that shades them, and
|
||||
an unlit surface shows its base color without lighting.
|
||||
- **Conversions.** `try_from_mesh` (feature `mesh`) converts a `craft_mesh::Material` and
|
||||
`try_from_materialx` (feature `materialx`) converts the `craft_materialx::StrictMaterial` that
|
||||
`Document::read_material_strict` reads. Each returns
|
||||
a `Conversion`: the `Surface` and a `ConversionReport` that lists what was kept without being
|
||||
shaded, what was approximated and how, what was dropped and why, and the MaterialX reader's
|
||||
warnings. No value is clamped: one that is not finite, is out of its range or has the wrong
|
||||
number of components gives a `ConvertError` naming the source field.
|
||||
- From craft-mesh, the glTF 2.0 metallic-roughness material
|
||||
(<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#materials>): base color, alpha,
|
||||
metallic, roughness, emissive, alpha mode and cutoff, double-sided and unlit map as they are.
|
||||
Every texture is kept with its UV state; base color, emissive and sheen color textures are
|
||||
sRGB and the others linear. Clearcoat (`KHR_materials_clearcoat`) and sheen
|
||||
(`KHR_materials_sheen`) are kept when on; a clearcoat factor of 0 or a black sheen color turns
|
||||
the layer off, and its textures are dropped.
|
||||
- From MaterialX, OpenPBR Surface, Standard Surface and glTF PBR inputs take the defaults of
|
||||
their node definitions when absent
|
||||
(<https://github.com/AcademySoftwareFoundation/MaterialX/tree/main/libraries/bxdf>). The base
|
||||
color is multiplied by the base weight, the specular weight becomes the weight times
|
||||
`((ior − 1) / (ior + 1))² / 0.04` (at most `MAX_SPECULAR`), emission is the color times its
|
||||
strength, and the coat, fuzz or sheen become the layers. Color constants are decoded to linear
|
||||
Rec.709 from the color space in effect (`srgb_texture`, `srgb_rec709_scene`, the Rec.709
|
||||
gamma spaces, `lin_rec709`, `lin_rec709_scene`, `data`); another color space is an error. An
|
||||
image becomes a texture binding and the core holds 1 times any weight in its place. A coat or
|
||||
sheen roughness image binds as `ClearcoatRoughnessFirst` or `SheenRoughnessFirst`, which read
|
||||
the first channel; the glTF bindings `ClearcoatRoughness` and `SheenRoughness` read G and A.
|
||||
Tangent-space normal textures require an image connected through a `normalmap` node.
|
||||
Direct world-space normal images are dropped with a report entry. Literal normal-map
|
||||
inputs and authored normal-map frames are unsupported and reported. Authored `constant`,
|
||||
`clamp`, and `mirror` image addressing modes are also reported. Other inputs of the shader's
|
||||
table are kept in `other_inputs`.
|
||||
- **Features.** `parallel` computes rows on several threads with rayon. `mesh` and `materialx`
|
||||
add the conversions and depend on craft-mesh and craft-materialx. The default build has none of
|
||||
them, is serial and builds for `wasm32-unknown-unknown`, as do `mesh` and `materialx`. Results
|
||||
are the same either way.
|
||||
The `craft` facade forwards the conversion features as `pbr-mesh` and `pbr-materialx`.
|
||||
|
||||
On a 256 × 128 source, the default `try_prefilter` evaluates 1,396,736 samples (10,912 output
|
||||
pixels in levels 1 to 5, 128 samples each).
|
||||
|
||||
@@ -0,0 +1,600 @@
|
||||
//! The conversion from a `craft_materialx::StrictMaterial`: an OpenPBR Surface, Standard Surface
|
||||
//! or glTF PBR shader with its resolved inputs.
|
||||
|
||||
use craft_materialx::{Resolved, Shader, StrictMaterial};
|
||||
use craft_texture::srgb_to_linear;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::surface::{
|
||||
AlphaMode, Clearcoat, Conversion, ConversionReport, ConvertError, FINITE, NON_NEGATIVE, ReportItem, Sheen, Surface, TextureBinding,
|
||||
TextureEncoding, TextureInput, TextureSource, UNIT, UvTransform, Wrap,
|
||||
};
|
||||
use crate::{MAX_SPECULAR, Material};
|
||||
|
||||
/// What a shader input holds and the range its values must be in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Kind {
|
||||
/// One number from `lo` to `hi`.
|
||||
Scalar(f32, f32),
|
||||
/// Three color components from 0 to the bound, in the color space in effect.
|
||||
Color(f32),
|
||||
/// Three finite numbers, such as a normal.
|
||||
Vector,
|
||||
/// glTF PBR's alpha mode: 0, 1 or 2.
|
||||
Mode,
|
||||
}
|
||||
|
||||
const UNIT_KIND: Kind = Kind::Scalar(0.0, 1.0);
|
||||
const NON_NEGATIVE_KIND: Kind = Kind::Scalar(0.0, f32::MAX);
|
||||
const COLOR: Kind = Kind::Color(1.0);
|
||||
|
||||
const COAT_OFF: &str = "the coat weight is 0, which turns the layer off";
|
||||
const SHEEN_OFF: &str = "the sheen color is black or its weight is 0, which turns the layer off";
|
||||
|
||||
/// What an input maps to on the [`Surface`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Role {
|
||||
BaseColor,
|
||||
BaseWeight,
|
||||
Metallic,
|
||||
Roughness,
|
||||
SpecularWeight,
|
||||
Ior,
|
||||
CoatWeight,
|
||||
CoatRoughness,
|
||||
SheenWeight,
|
||||
SheenColor,
|
||||
SheenRoughness,
|
||||
EmissionStrength,
|
||||
EmissionColor,
|
||||
Opacity,
|
||||
AlphaMode,
|
||||
AlphaCutoff,
|
||||
Normal,
|
||||
Occlusion,
|
||||
/// Kept as an other input or a texture, and not shaded.
|
||||
Kept,
|
||||
/// Kept like [`Role::Kept`] while the coat is on, and dropped when it is off.
|
||||
CoatKept,
|
||||
}
|
||||
|
||||
/// A shader input the conversion reads, with its default from the shader's node definition.
|
||||
struct Field {
|
||||
name: &'static str,
|
||||
kind: Kind,
|
||||
role: Role,
|
||||
default: [f32; 3],
|
||||
}
|
||||
|
||||
const fn field(name: &'static str, kind: Kind, role: Role, default: f32) -> Field {
|
||||
Field { name, kind, role, default: [default; 3] }
|
||||
}
|
||||
|
||||
/// OpenPBR Surface inputs and defaults, from its node definition
|
||||
/// (<https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/bxdf/open_pbr_surface.mtlx>).
|
||||
const OPEN_PBR: &[Field] = &[
|
||||
field("base_color", COLOR, Role::BaseColor, 0.8),
|
||||
field("base_weight", UNIT_KIND, Role::BaseWeight, 1.0),
|
||||
field("base_metalness", UNIT_KIND, Role::Metallic, 0.0),
|
||||
field("specular_roughness", UNIT_KIND, Role::Roughness, 0.3),
|
||||
field("specular_weight", NON_NEGATIVE_KIND, Role::SpecularWeight, 1.0),
|
||||
field("specular_ior", NON_NEGATIVE_KIND, Role::Ior, 1.5),
|
||||
field("coat_weight", UNIT_KIND, Role::CoatWeight, 0.0),
|
||||
field("coat_roughness", UNIT_KIND, Role::CoatRoughness, 0.0),
|
||||
field("fuzz_weight", UNIT_KIND, Role::SheenWeight, 0.0),
|
||||
field("fuzz_color", COLOR, Role::SheenColor, 1.0),
|
||||
field("fuzz_roughness", UNIT_KIND, Role::SheenRoughness, 0.5),
|
||||
field("emission_luminance", NON_NEGATIVE_KIND, Role::EmissionStrength, 0.0),
|
||||
field("emission_color", COLOR, Role::EmissionColor, 1.0),
|
||||
field("geometry_opacity", UNIT_KIND, Role::Opacity, 1.0),
|
||||
field("geometry_normal", Kind::Vector, Role::Normal, 0.0),
|
||||
field("geometry_coat_normal", Kind::Vector, Role::CoatKept, 0.0),
|
||||
field("specular_color", COLOR, Role::Kept, 1.0),
|
||||
field("specular_roughness_anisotropy", UNIT_KIND, Role::Kept, 0.0),
|
||||
field("transmission_weight", UNIT_KIND, Role::Kept, 0.0),
|
||||
field("subsurface_weight", UNIT_KIND, Role::Kept, 0.0),
|
||||
field("coat_color", COLOR, Role::CoatKept, 1.0),
|
||||
field("coat_ior", NON_NEGATIVE_KIND, Role::CoatKept, 1.6),
|
||||
];
|
||||
|
||||
/// Standard Surface 1.0.1 inputs and defaults, from its node definition
|
||||
/// (<https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/bxdf/standard_surface.mtlx>).
|
||||
const STANDARD_SURFACE: &[Field] = &[
|
||||
field("base_color", COLOR, Role::BaseColor, 0.8),
|
||||
field("base", UNIT_KIND, Role::BaseWeight, 1.0),
|
||||
field("metalness", UNIT_KIND, Role::Metallic, 0.0),
|
||||
field("specular_roughness", UNIT_KIND, Role::Roughness, 0.2),
|
||||
field("specular", UNIT_KIND, Role::SpecularWeight, 1.0),
|
||||
field("specular_IOR", NON_NEGATIVE_KIND, Role::Ior, 1.5),
|
||||
field("coat", UNIT_KIND, Role::CoatWeight, 0.0),
|
||||
field("coat_roughness", UNIT_KIND, Role::CoatRoughness, 0.1),
|
||||
field("sheen", UNIT_KIND, Role::SheenWeight, 0.0),
|
||||
field("sheen_color", COLOR, Role::SheenColor, 1.0),
|
||||
field("sheen_roughness", UNIT_KIND, Role::SheenRoughness, 0.3),
|
||||
field("emission", NON_NEGATIVE_KIND, Role::EmissionStrength, 0.0),
|
||||
field("emission_color", COLOR, Role::EmissionColor, 1.0),
|
||||
field("opacity", COLOR, Role::Opacity, 1.0),
|
||||
field("normal", Kind::Vector, Role::Normal, 0.0),
|
||||
field("coat_normal", Kind::Vector, Role::CoatKept, 0.0),
|
||||
field("specular_color", COLOR, Role::Kept, 1.0),
|
||||
field("specular_anisotropy", UNIT_KIND, Role::Kept, 0.0),
|
||||
field("transmission", UNIT_KIND, Role::Kept, 0.0),
|
||||
field("subsurface", UNIT_KIND, Role::Kept, 0.0),
|
||||
field("coat_color", COLOR, Role::CoatKept, 1.0),
|
||||
field("coat_IOR", NON_NEGATIVE_KIND, Role::CoatKept, 1.5),
|
||||
];
|
||||
|
||||
/// glTF PBR inputs and defaults, from its node definition
|
||||
/// (<https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/bxdf/gltf_pbr.mtlx>).
|
||||
const GLTF_PBR: &[Field] = &[
|
||||
field("base_color", COLOR, Role::BaseColor, 1.0),
|
||||
field("metallic", UNIT_KIND, Role::Metallic, 1.0),
|
||||
field("roughness", UNIT_KIND, Role::Roughness, 1.0),
|
||||
field("specular", UNIT_KIND, Role::SpecularWeight, 1.0),
|
||||
field("ior", Kind::Scalar(1.0, f32::MAX), Role::Ior, 1.5),
|
||||
field("clearcoat", UNIT_KIND, Role::CoatWeight, 0.0),
|
||||
field("clearcoat_roughness", UNIT_KIND, Role::CoatRoughness, 0.0),
|
||||
field("sheen_color", COLOR, Role::SheenColor, 0.0),
|
||||
field("sheen_roughness", UNIT_KIND, Role::SheenRoughness, 0.0),
|
||||
field("emissive_strength", NON_NEGATIVE_KIND, Role::EmissionStrength, 1.0),
|
||||
field("emissive", COLOR, Role::EmissionColor, 0.0),
|
||||
field("alpha", UNIT_KIND, Role::Opacity, 1.0),
|
||||
field("alpha_mode", Kind::Mode, Role::AlphaMode, 0.0),
|
||||
field("alpha_cutoff", UNIT_KIND, Role::AlphaCutoff, 0.5),
|
||||
field("normal", Kind::Vector, Role::Normal, 0.0),
|
||||
field("occlusion", UNIT_KIND, Role::Occlusion, 1.0),
|
||||
field("clearcoat_normal", Kind::Vector, Role::CoatKept, 0.0),
|
||||
field("transmission", UNIT_KIND, Role::Kept, 0.0),
|
||||
field("specular_color", Kind::Color(f32::MAX), Role::Kept, 1.0),
|
||||
];
|
||||
|
||||
/// What a conversion found for one field of the table.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Got {
|
||||
Missing,
|
||||
/// Checked values, linear for a color.
|
||||
Constant(Vec<f32>),
|
||||
Texture,
|
||||
}
|
||||
|
||||
/// The table of the material's shader and what each field holds.
|
||||
struct Inputs {
|
||||
table: &'static [Field],
|
||||
got: Vec<Got>,
|
||||
}
|
||||
|
||||
impl Inputs {
|
||||
fn find(&self, role: Role) -> Option<(&Field, &Got)> {
|
||||
self.table.iter().zip(&self.got).find(|(f, _)| f.role == role)
|
||||
}
|
||||
|
||||
/// The field's value: the authored one, 1 for a texture (the factor its samples multiply),
|
||||
/// or the default when the input is absent. `None` when the shader has no such field.
|
||||
fn value(&self, role: Role) -> Option<[f32; 3]> {
|
||||
let (f, got) = self.find(role)?;
|
||||
Some(match got {
|
||||
Got::Missing => f.default,
|
||||
Got::Texture => [1.0; 3],
|
||||
Got::Constant(v) if v.len() == 1 => [v[0]; 3],
|
||||
Got::Constant(v) => [v.first().copied().unwrap_or(0.0), v.get(1).copied().unwrap_or(0.0), v.get(2).copied().unwrap_or(0.0)],
|
||||
})
|
||||
}
|
||||
|
||||
fn scalar(&self, role: Role, absent: f32) -> f32 {
|
||||
self.value(role).map_or(absent, |v| v[0])
|
||||
}
|
||||
|
||||
fn textured(&self, role: Role) -> bool {
|
||||
self.find(role).is_some_and(|(_, g)| *g == Got::Texture)
|
||||
}
|
||||
|
||||
fn name(&self, role: Role) -> &'static str {
|
||||
self.table.iter().find(|f| f.role == role).map_or("", |f| f.name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a `craft_materialx::StrictMaterial`, as `Document::read_material_strict` reads it, by
|
||||
/// the input tables of its shader's node definition
|
||||
/// (<https://github.com/AcademySoftwareFoundation/MaterialX/tree/main/libraries/bxdf>). An input
|
||||
/// that is absent takes the definition's default, so an empty input list gives the shader's
|
||||
/// default material.
|
||||
///
|
||||
/// - The core's base color is the base color times the base weight (`base_weight`, or `base` in
|
||||
/// Standard Surface), which both shaders apply to the diffuse and the metal color. Metallic
|
||||
/// and roughness map as they are. The core's specular weight is the specular weight times
|
||||
/// Schlick's reflectance at normal incidence for the index of refraction,
|
||||
/// `((ior − 1) / (ior + 1))²`, divided by 0.04; it is reported as approximated when it is not 1,
|
||||
/// and a value over [`MAX_SPECULAR`] is an error.
|
||||
/// - The coat (`coat_*`, or `clearcoat*` in glTF PBR) becomes [`Surface::clearcoat`] when its
|
||||
/// weight is above 0 or a texture sets it. The fuzz of OpenPBR and the sheen of Standard
|
||||
/// Surface become [`Surface::sheen`] with the weight times the color as its color, reported as
|
||||
/// approximated; glTF PBR's sheen maps as it is. A layer is kept only when it is on.
|
||||
/// - Emission is the emission color times its strength: `emission_luminance` (reported as
|
||||
/// approximated, since it is in nits), `emission`, or `emissive_strength`. A color whose
|
||||
/// strength is 0 gives no emission.
|
||||
/// An authored color at strength 0 is validated and reported as dropped.
|
||||
/// - Alpha is the opacity. Standard Surface's opacity is a color: equal channels give that value,
|
||||
/// and different channels give their luminance by the Rec.709 luma coefficients, reported as
|
||||
/// approximated, as the shader's own node graph reduces it with a `luminance` node. OpenPBR's
|
||||
/// `geometry_opacity` and glTF PBR's `alpha` are floats in their node definitions, so a color
|
||||
/// there is [`ConvertError::Components`]. glTF PBR's `alpha_mode` 0, 1 and 2 give opaque,
|
||||
/// masked at `alpha_cutoff`, and blended; the other shaders blend when the opacity is below 1
|
||||
/// or a texture sets it.
|
||||
/// - Every other input of the table (normals, specular color, anisotropy, transmission,
|
||||
/// subsurface, coat color and IOR, occlusion) is kept in [`Surface::other_inputs`], or as a
|
||||
/// texture, and reported as unshaded. The displacement is kept the same way.
|
||||
/// - An image becomes a [`TextureBinding`] with the file path, the UV tiling as its transform's
|
||||
/// scale, and an encoding from its color space for a color input (linear for data); the core
|
||||
/// holds 1 times any weight in its place; Standard Surface's color `opacity` binds as
|
||||
/// [`TextureInput::OpacityRgb`] and the float opacities as [`TextureInput::Opacity`]; an IOR
|
||||
/// texture leaves the default IOR, reported
|
||||
/// as approximated. The inputs and textures of a layer that is off (the coat's roughness,
|
||||
/// color, IOR and normal among them) are dropped and reported.
|
||||
/// - Color constants are decoded to linear Rec.709 from the color space in effect, as the
|
||||
/// MaterialX specification asks
|
||||
/// (<https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/documents/Specification/MaterialX.Specification.md#color-spaces-and-color-management-systems>):
|
||||
/// `srgb_texture` and `srgb_rec709_scene` by the sRGB transfer function, the Rec.709 gamma
|
||||
/// spaces by their power, and `lin_rec709`, `lin_rec709_scene`, `data`, `none` or no color
|
||||
/// space as they are. Another color space is [`ConvertError::ColorSpace`].
|
||||
/// - The reader's warnings are carried into the report. Inputs outside the table are dropped and
|
||||
/// reported.
|
||||
///
|
||||
/// Every value is checked and none is clamped: a value that is not finite (a color also after it
|
||||
/// is decoded to linear), is outside the definition's range (`0..=1` for weights, colors and
|
||||
/// roughness, at least 0 for strengths and IOR, at least 1 for glTF PBR's `ior`), has the wrong
|
||||
/// number of components, or is an
|
||||
/// `alpha_mode` other than 0, 1 or 2 is an error, and so is a texture on `alpha_mode` or
|
||||
/// `alpha_cutoff`, a UV tiling that is not two positive numbers, or an input named twice.
|
||||
pub fn try_from_materialx(m: &StrictMaterial) -> Result<Conversion, ConvertError> {
|
||||
let table = match m.shader {
|
||||
Shader::OpenPbr => OPEN_PBR,
|
||||
Shader::StandardSurface => STANDARD_SURFACE,
|
||||
Shader::GltfPbr => GLTF_PBR,
|
||||
};
|
||||
let mut report = ConversionReport::default();
|
||||
let mut inputs = Inputs { table, got: table.iter().map(|_| Got::Missing).collect() };
|
||||
let mut textures: Vec<(Role, TextureBinding)> = Vec::new();
|
||||
let mut others: Vec<(Role, String, Vec<f32>)> = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
for (name, value) in &m.inputs {
|
||||
if !seen.insert(name.as_str()) {
|
||||
return Err(ConvertError::Duplicate(name.clone()));
|
||||
}
|
||||
let Some(idx) = table.iter().position(|f| f.name == name) else {
|
||||
report.items.push(ReportItem::Dropped { input: name.clone(), why: "is not an input of the shader that the conversion reads" });
|
||||
continue;
|
||||
};
|
||||
let f = &table[idx];
|
||||
match value {
|
||||
Resolved::Constant { values, colorspace } => {
|
||||
let v = checked_values(f, values, colorspace.as_deref())?;
|
||||
if matches!(f.role, Role::Kept | Role::CoatKept | Role::Normal | Role::Occlusion) {
|
||||
others.push((f.role, name.clone(), v));
|
||||
} else {
|
||||
inputs.got[idx] = Got::Constant(v);
|
||||
}
|
||||
}
|
||||
Resolved::Image { file, colorspace, uv_tiling } | Resolved::NormalMap { file, colorspace, uv_tiling } => {
|
||||
if matches!(f.role, Role::AlphaMode | Role::AlphaCutoff) {
|
||||
return Err(ConvertError::BadValue { input: name.clone(), reason: "cannot be a texture" });
|
||||
}
|
||||
let binding = image_binding(f, file, colorspace.as_deref(), *uv_tiling)?;
|
||||
let tangent = matches!(value, Resolved::NormalMap { .. });
|
||||
let normal = matches!(f.role, Role::Normal) || (matches!(f.role, Role::CoatKept) && matches!(f.kind, Kind::Vector));
|
||||
if normal && !tangent {
|
||||
report.items.push(ReportItem::Dropped { input: name.clone(), why: "world-space normal images are not supported" });
|
||||
continue;
|
||||
}
|
||||
if tangent && !normal {
|
||||
report.items.push(ReportItem::Dropped { input: name.clone(), why: "a normalmap image is not supported on this input" });
|
||||
continue;
|
||||
}
|
||||
textures.push((f.role, binding));
|
||||
inputs.got[idx] = Got::Texture;
|
||||
}
|
||||
}
|
||||
}
|
||||
let material = core(&inputs, &mut report)?;
|
||||
let clearcoat = clearcoat(&inputs);
|
||||
let sheen = sheen(&inputs, m.shader, &mut report);
|
||||
let emissive = emission(&inputs, m.shader, &mut report);
|
||||
let (alpha, alpha_mode) = alpha(&inputs, m.shader, &mut report)?;
|
||||
let off = |role: Role| match role {
|
||||
Role::CoatWeight | Role::CoatRoughness | Role::CoatKept if clearcoat.is_none() => Some(COAT_OFF),
|
||||
Role::SheenWeight | Role::SheenColor | Role::SheenRoughness if sheen.is_none() => Some(SHEEN_OFF),
|
||||
Role::EmissionColor if inputs.scalar(Role::EmissionStrength, 1.0) == 0.0 => Some("the emission strength is 0"),
|
||||
_ => None,
|
||||
};
|
||||
// Authored constants of a layer that is off, except the weight or color that turns it off.
|
||||
for (f, got) in table.iter().zip(&inputs.got) {
|
||||
let Got::Constant(v) = got else { continue };
|
||||
let turns_it_off = match f.role {
|
||||
Role::CoatWeight => true,
|
||||
Role::SheenWeight | Role::SheenColor => v.iter().all(|c| *c == 0.0),
|
||||
_ => false,
|
||||
};
|
||||
if let Some(why) = off(f.role).filter(|_| !turns_it_off) {
|
||||
report.items.push(ReportItem::Dropped { input: f.name.to_owned(), why });
|
||||
}
|
||||
}
|
||||
let mut other_inputs = Vec::new();
|
||||
for (role, input, values) in others {
|
||||
match off(role) {
|
||||
Some(why) => report.items.push(ReportItem::Dropped { input, why }),
|
||||
None => {
|
||||
report.items.push(ReportItem::Unshaded { input: input.clone() });
|
||||
other_inputs.push((input, values));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut kept = Vec::new();
|
||||
for (role, binding) in textures {
|
||||
let off = off(role);
|
||||
let input = texture_name(&inputs, role, &binding);
|
||||
match off {
|
||||
Some(why) => report.items.push(ReportItem::Dropped { input, why }),
|
||||
None => {
|
||||
report.items.push(ReportItem::Unshaded { input });
|
||||
kept.push(binding);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (layer, on) in [("clearcoat", clearcoat.is_some()), ("sheen", sheen.is_some())] {
|
||||
if on {
|
||||
report.items.push(ReportItem::Unshaded { input: layer.into() });
|
||||
}
|
||||
}
|
||||
displacement(m.displacement.as_ref(), &mut kept, &mut other_inputs, &mut report)?;
|
||||
report.items.extend(m.warnings.iter().cloned().map(ReportItem::Warning));
|
||||
let surface = Surface {
|
||||
name: m.name.clone(),
|
||||
material,
|
||||
alpha,
|
||||
alpha_mode,
|
||||
emissive,
|
||||
double_sided: false,
|
||||
unlit: false,
|
||||
clearcoat,
|
||||
sheen,
|
||||
textures: kept,
|
||||
other_inputs,
|
||||
};
|
||||
Ok(Conversion { surface, report })
|
||||
}
|
||||
|
||||
/// The source name of a texture for the report.
|
||||
fn texture_name(inputs: &Inputs, role: Role, binding: &TextureBinding) -> String {
|
||||
match &binding.input {
|
||||
TextureInput::Other(name) => name.clone(),
|
||||
_ => inputs.name(role).to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The reason text for a value outside `lo..=hi`.
|
||||
fn reason(lo: f32, hi: f32) -> &'static str {
|
||||
match (lo, hi) {
|
||||
(0.0, 1.0) => UNIT,
|
||||
(0.0, _) => NON_NEGATIVE,
|
||||
(1.0, _) => "is not a finite number of at least 1",
|
||||
_ => FINITE,
|
||||
}
|
||||
}
|
||||
|
||||
/// The values of a constant for field `f`, checked against its kind and, for a color, decoded
|
||||
/// to linear from `space`.
|
||||
fn checked_values(f: &Field, values: &[f32], space: Option<&str>) -> Result<Vec<f32>, ConvertError> {
|
||||
let expected = match f.kind {
|
||||
Kind::Scalar(..) | Kind::Mode => 1,
|
||||
Kind::Color(_) | Kind::Vector => 3,
|
||||
};
|
||||
if values.len() != expected {
|
||||
return Err(ConvertError::Components { input: f.name.to_owned(), expected, found: values.len() });
|
||||
}
|
||||
let bad = |reason| ConvertError::BadValue { input: f.name.to_owned(), reason };
|
||||
let (lo, hi) = match f.kind {
|
||||
Kind::Scalar(lo, hi) => (lo, hi),
|
||||
Kind::Color(hi) => (0.0, hi),
|
||||
Kind::Vector => (f32::MIN, f32::MAX),
|
||||
Kind::Mode => (0.0, 2.0),
|
||||
};
|
||||
let in_range = |v: f32| v.is_finite() && (lo..=hi).contains(&v);
|
||||
for &v in values {
|
||||
if !in_range(v) {
|
||||
return Err(bad(reason(lo, hi)));
|
||||
}
|
||||
if f.kind == Kind::Mode && v.fract() != 0.0 {
|
||||
return Err(bad("is not 0, 1 or 2"));
|
||||
}
|
||||
}
|
||||
match f.kind {
|
||||
Kind::Color(_) => {
|
||||
let linear = decode(values, space, f.name)?;
|
||||
if linear.iter().all(|&v| in_range(v)) { Ok(linear) } else { Err(bad("is not a finite color once decoded to linear")) }
|
||||
}
|
||||
_ => Ok(values.to_vec()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `values` decoded to linear Rec.709 from the color space `space`.
|
||||
fn decode(values: &[f32], space: Option<&str>, input: &str) -> Result<Vec<f32>, ConvertError> {
|
||||
let power = |p: f32| values.iter().map(|v| v.powf(p)).collect();
|
||||
Ok(match space {
|
||||
None | Some("data" | "none" | "lin_rec709" | "lin_rec709_scene") => values.to_vec(),
|
||||
Some("srgb_texture" | "srgb_rec709_scene") => values.iter().map(|v| srgb_to_linear(*v)).collect(),
|
||||
Some("g22_rec709" | "g22_rec709_scene") => power(2.2),
|
||||
Some("g18_rec709" | "g18_rec709_scene") => power(1.8),
|
||||
Some("g24_rec709_scene") => power(2.4),
|
||||
Some(other) => return Err(ConvertError::ColorSpace { input: input.to_owned(), colorspace: other.to_owned() }),
|
||||
})
|
||||
}
|
||||
|
||||
/// The binding of an image on field `f`.
|
||||
fn image_binding(f: &Field, file: &str, space: Option<&str>, tiling: Option<[f32; 2]>) -> Result<TextureBinding, ConvertError> {
|
||||
let input = match f.role {
|
||||
Role::BaseColor => TextureInput::BaseColor,
|
||||
Role::Metallic => TextureInput::Metallic,
|
||||
Role::Roughness => TextureInput::Roughness,
|
||||
Role::Normal => TextureInput::Normal,
|
||||
Role::Occlusion => TextureInput::Occlusion,
|
||||
Role::EmissionColor => TextureInput::Emissive,
|
||||
Role::Opacity if matches!(f.kind, Kind::Color(_)) => TextureInput::OpacityRgb,
|
||||
Role::Opacity => TextureInput::Opacity,
|
||||
Role::CoatWeight => TextureInput::Clearcoat,
|
||||
Role::CoatRoughness => TextureInput::ClearcoatRoughnessFirst,
|
||||
Role::SheenColor => TextureInput::SheenColor,
|
||||
Role::SheenRoughness => TextureInput::SheenRoughnessFirst,
|
||||
_ => TextureInput::Other(f.name.to_owned()),
|
||||
};
|
||||
let encoding = if matches!(f.kind, Kind::Color(_)) { encoding(space) } else { TextureEncoding::Linear };
|
||||
let transform = match tiling {
|
||||
Some(scale) if scale.iter().all(|v| v.is_finite() && *v > 0.0) => Some(UvTransform { offset: [0.0; 2], rotation: 0.0, scale }),
|
||||
Some(_) => return Err(ConvertError::BadValue { input: f.name.to_owned(), reason: "has a UV tiling that is not two positive numbers" }),
|
||||
None => None,
|
||||
};
|
||||
Ok(TextureBinding { input, source: TextureSource::File(file.to_owned()), encoding, uv_set: 0, wrap: [Wrap::Repeat; 2], transform, scale: 1.0 })
|
||||
}
|
||||
|
||||
/// The encoding of a color image in the color space `space`.
|
||||
fn encoding(space: Option<&str>) -> TextureEncoding {
|
||||
match space {
|
||||
None | Some("data" | "none" | "lin_rec709" | "lin_rec709_scene") => TextureEncoding::Linear,
|
||||
Some("srgb_texture" | "srgb_rec709_scene") => TextureEncoding::Srgb,
|
||||
Some(other) => TextureEncoding::Named(other.to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The BRDF core.
|
||||
fn core(inputs: &Inputs, report: &mut ConversionReport) -> Result<Material, ConvertError> {
|
||||
let color = inputs.value(Role::BaseColor).unwrap_or([1.0; 3]);
|
||||
let weight = inputs.scalar(Role::BaseWeight, 1.0);
|
||||
let base = color.map(|c| c * weight);
|
||||
let metallic = inputs.scalar(Role::Metallic, 0.0);
|
||||
let roughness = inputs.scalar(Role::Roughness, 0.0);
|
||||
if inputs.textured(Role::Ior) {
|
||||
report
|
||||
.items
|
||||
.push(ReportItem::Approximated { input: inputs.name(Role::Ior).into(), how: "is a texture; the default index of refraction was used" });
|
||||
}
|
||||
let ior = match inputs.find(Role::Ior) {
|
||||
Some((f, Got::Texture)) => f64::from(f.default[0]),
|
||||
_ => f64::from(inputs.scalar(Role::Ior, 1.5)),
|
||||
};
|
||||
// The reflectance relative to 0.04, which is 1 within rounding at the default IOR of 1.5.
|
||||
let mut ratio = ((ior - 1.0) / (ior + 1.0)).powi(2) / 0.04;
|
||||
if (ratio - 1.0).abs() < 1e-9 {
|
||||
ratio = 1.0;
|
||||
}
|
||||
let specular = f64::from(inputs.scalar(Role::SpecularWeight, 1.0)) * ratio;
|
||||
let name = inputs.name(Role::SpecularWeight);
|
||||
if specular > f64::from(MAX_SPECULAR) {
|
||||
return Err(ConvertError::BadValue {
|
||||
input: name.into(),
|
||||
reason: "times the reflectance of the index of refraction is over the 25 the BRDF supports",
|
||||
});
|
||||
}
|
||||
if specular != 1.0 {
|
||||
report.items.push(ReportItem::Approximated {
|
||||
input: name.into(),
|
||||
how: "times Schlick's reflectance at normal incidence for the index of refraction, over 0.04, is the core's specular weight",
|
||||
});
|
||||
}
|
||||
Ok(Material::try_new(base, metallic, roughness)?.try_with_weights(specular as f32, 1.0)?)
|
||||
}
|
||||
|
||||
/// The coat, when its weight is above 0 or a texture sets it.
|
||||
fn clearcoat(inputs: &Inputs) -> Option<Clearcoat> {
|
||||
let weight = inputs.scalar(Role::CoatWeight, 0.0);
|
||||
(weight > 0.0).then(|| Clearcoat { weight, roughness: inputs.scalar(Role::CoatRoughness, 0.0) })
|
||||
}
|
||||
|
||||
/// The sheen, when its color times its weight is not black.
|
||||
fn sheen(inputs: &Inputs, shader: Shader, report: &mut ConversionReport) -> Option<Sheen> {
|
||||
let weight = inputs.scalar(Role::SheenWeight, 1.0);
|
||||
let color = inputs.value(Role::SheenColor)?.map(|c| c * weight);
|
||||
if color == [0.0; 3] {
|
||||
return None;
|
||||
}
|
||||
if shader != Shader::GltfPbr {
|
||||
report.items.push(ReportItem::Approximated { input: inputs.name(Role::SheenWeight).into(), how: "times the color is the sheen color" });
|
||||
}
|
||||
Some(Sheen { color, roughness: inputs.scalar(Role::SheenRoughness, 0.0) })
|
||||
}
|
||||
|
||||
/// The emission color times its strength.
|
||||
fn emission(inputs: &Inputs, shader: Shader, report: &mut ConversionReport) -> [f32; 3] {
|
||||
let strength = inputs.scalar(Role::EmissionStrength, 1.0);
|
||||
let color = inputs.value(Role::EmissionColor).unwrap_or([0.0; 3]);
|
||||
let emissive = color.map(|c| c * strength);
|
||||
if shader == Shader::OpenPbr && emissive != [0.0; 3] {
|
||||
report.items.push(ReportItem::Approximated {
|
||||
input: inputs.name(Role::EmissionStrength).into(),
|
||||
how: "is in nits and multiplies the emission color",
|
||||
});
|
||||
}
|
||||
emissive
|
||||
}
|
||||
|
||||
/// Alpha and its mode.
|
||||
fn alpha(inputs: &Inputs, shader: Shader, report: &mut ConversionReport) -> Result<(f32, AlphaMode), ConvertError> {
|
||||
let opacity = inputs.value(Role::Opacity).unwrap_or([1.0; 3]);
|
||||
let alpha = if shader == Shader::StandardSurface && (opacity[0] != opacity[1] || opacity[1] != opacity[2]) {
|
||||
report
|
||||
.items
|
||||
.push(ReportItem::Approximated { input: inputs.name(Role::Opacity).into(), how: "is a color; its Rec.709 luminance is the alpha" });
|
||||
luminance(opacity)
|
||||
} else {
|
||||
opacity[0]
|
||||
};
|
||||
let mode = if shader == Shader::GltfPbr {
|
||||
match inputs.scalar(Role::AlphaMode, 0.0) {
|
||||
0.0 => AlphaMode::Opaque,
|
||||
1.0 => AlphaMode::Mask(inputs.scalar(Role::AlphaCutoff, 0.5)),
|
||||
2.0 => AlphaMode::Blend,
|
||||
_ => return Err(ConvertError::BadValue { input: "alpha_mode".into(), reason: "is not 0, 1 or 2" }),
|
||||
}
|
||||
} else if alpha < 1.0 || inputs.textured(Role::Opacity) {
|
||||
AlphaMode::Blend
|
||||
} else {
|
||||
AlphaMode::Opaque
|
||||
};
|
||||
if shader == Shader::GltfPbr
|
||||
&& !matches!(mode, AlphaMode::Mask(_))
|
||||
&& inputs.find(Role::AlphaCutoff).is_some_and(|(_, value)| matches!(value, Got::Constant(_)))
|
||||
{
|
||||
report.items.push(ReportItem::Dropped { input: inputs.name(Role::AlphaCutoff).into(), why: "the alpha mode does not use a cutoff" });
|
||||
}
|
||||
Ok((alpha, mode))
|
||||
}
|
||||
|
||||
/// The luminance of a linear Rec.709 color, by the `rec709` luma coefficients of the MaterialX
|
||||
/// `luminance` node
|
||||
/// (<https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/stdlib_defs.mtlx>),
|
||||
/// kept between the smallest and largest channel so that rounding cannot leave `0..=1`.
|
||||
fn luminance(c: [f32; 3]) -> f32 {
|
||||
let y = 0.2126 * f64::from(c[0]) + 0.7152 * f64::from(c[1]) + 0.0722 * f64::from(c[2]);
|
||||
(y as f32).clamp(c[0].min(c[1]).min(c[2]), c[0].max(c[1]).max(c[2]))
|
||||
}
|
||||
|
||||
/// Keeps the displacement as a texture or an other input.
|
||||
fn displacement(
|
||||
value: Option<&Resolved>,
|
||||
textures: &mut Vec<TextureBinding>,
|
||||
other_inputs: &mut Vec<(String, Vec<f32>)>,
|
||||
report: &mut ConversionReport,
|
||||
) -> Result<(), ConvertError> {
|
||||
const DISPLACEMENT: Field = field("displacement", Kind::Scalar(f32::MIN, f32::MAX), Role::Kept, 0.0);
|
||||
match value {
|
||||
None => return Ok(()),
|
||||
Some(Resolved::Constant { values, .. }) => other_inputs.push(("displacement".into(), checked_values(&DISPLACEMENT, values, None)?)),
|
||||
Some(Resolved::Image { file, colorspace, uv_tiling }) => {
|
||||
let mut binding = image_binding(&DISPLACEMENT, file, colorspace.as_deref(), *uv_tiling)?;
|
||||
binding.input = TextureInput::Displacement;
|
||||
textures.push(binding);
|
||||
}
|
||||
Some(Resolved::NormalMap { .. }) => {
|
||||
return Err(ConvertError::BadValue { input: "displacement".into(), reason: "cannot be a normalmap image" });
|
||||
}
|
||||
}
|
||||
report.items.push(ReportItem::Unshaded { input: "displacement".into() });
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
//! The conversion from a `craft_mesh::Material`, which holds a glTF 2.0 metallic-roughness
|
||||
//! material.
|
||||
|
||||
use craft_mesh::{AlphaMode as MeshAlpha, Material as MeshMaterial, TextureRef, Wrap as MeshWrap};
|
||||
|
||||
use crate::Material;
|
||||
use crate::surface::{
|
||||
AlphaMode, Clearcoat, Conversion, ConversionReport, ConvertError, FINITE, NON_NEGATIVE, ReportItem, Sheen, Surface, TextureBinding,
|
||||
TextureEncoding, TextureInput, TextureSource, UNIT, UvTransform, Wrap, checked,
|
||||
};
|
||||
|
||||
/// The material extensions whose values `craft_mesh` reads into `craft_mesh::Material`'s fields.
|
||||
/// It reads only part of `KHR_materials_pbrSpecularGlossiness` and of `KHR_materials_clearcoat`.
|
||||
const CONVERTED_EXTENSIONS: &[&str] = &[
|
||||
"KHR_materials_unlit",
|
||||
"KHR_materials_emissive_strength",
|
||||
"KHR_materials_pbrSpecularGlossiness",
|
||||
"KHR_materials_clearcoat",
|
||||
"KHR_materials_sheen",
|
||||
];
|
||||
const SPECULAR_GLOSSINESS: &str = "KHR_materials_pbrSpecularGlossiness";
|
||||
|
||||
/// Converts a `craft_mesh::Material` as glTF 2.0 defines its metallic-roughness material
|
||||
/// (<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#materials>).
|
||||
///
|
||||
/// - Mapped as they are: the linear base color RGB, metallic and roughness into the core with
|
||||
/// specular and diffuse weights of 1, base color alpha into [`Surface::alpha`], the alpha mode
|
||||
/// and cutoff, the linear emissive color, the double-sided flag, the unlit flag of
|
||||
/// `KHR_materials_unlit` and the name. Nothing is converted between color spaces: the source
|
||||
/// values are linear.
|
||||
/// - Kept and reported as [`ReportItem::Unshaded`]: every texture, with its image index, UV set,
|
||||
/// wrap modes and `KHR_texture_transform`, and the normal scale and occlusion strength as the
|
||||
/// binding's scale; the clearcoat layer of `KHR_materials_clearcoat`; the sheen layer of
|
||||
/// `KHR_materials_sheen`; and the unlit flag. Base color, emissive and sheen color textures
|
||||
/// are sRGB-encoded and the others are linear, as glTF and its extensions define them.
|
||||
/// - Dropped and reported: the clearcoat textures when the clearcoat factor is 0, and the sheen
|
||||
/// textures when the sheen color factor is black. Each extension turns its layer off then.
|
||||
/// Every other material extension in `craft_mesh::Material::extensions`, such as
|
||||
/// `KHR_materials_transmission`, is dropped and reported by its name, and so is the
|
||||
/// `clearcoatNormalTexture` of `KHR_materials_clearcoat`, which `craft_mesh` does not read.
|
||||
/// - Reported as [`ReportItem::Approximated`]: `KHR_materials_pbrSpecularGlossiness`, which
|
||||
/// `craft_mesh` reads as its diffuse color and texture with roughness from the glossiness,
|
||||
/// without its specular color or specular-glossiness texture.
|
||||
///
|
||||
/// Every value is checked and none is clamped. Base color channels, alpha, metallic,
|
||||
/// roughness, occlusion strength and the clearcoat and sheen values must be numbers from 0 to 1;
|
||||
/// emissive channels and the alpha cutoff must be finite and at least 0; the normal scale and
|
||||
/// every UV transform value must be finite. Otherwise the result is
|
||||
/// [`ConvertError::BadValue`] naming the `craft_mesh::Material` field.
|
||||
pub fn try_from_mesh(m: &MeshMaterial) -> Result<Conversion, ConvertError> {
|
||||
let [r, g, b, a] = m.base_color;
|
||||
let base = [checked(r, 0.0, 1.0, "base_color", UNIT)?, checked(g, 0.0, 1.0, "base_color", UNIT)?, checked(b, 0.0, 1.0, "base_color", UNIT)?];
|
||||
let alpha = checked(a, 0.0, 1.0, "base_color alpha", UNIT)?;
|
||||
let metallic = checked(m.metallic, 0.0, 1.0, "metallic", UNIT)?;
|
||||
let roughness = checked(m.roughness, 0.0, 1.0, "roughness", UNIT)?;
|
||||
let material = Material::try_new(base, metallic, roughness)?;
|
||||
let mut emissive = [0.0; 3];
|
||||
for (out, v) in emissive.iter_mut().zip(m.emissive) {
|
||||
*out = checked(v, 0.0, f32::MAX, "emissive", NON_NEGATIVE)?;
|
||||
}
|
||||
let alpha_mode = match m.alpha_mode {
|
||||
MeshAlpha::Opaque => AlphaMode::Opaque,
|
||||
MeshAlpha::Mask(cutoff) => AlphaMode::Mask(checked(cutoff, 0.0, f32::MAX, "alpha cutoff", NON_NEGATIVE)?),
|
||||
MeshAlpha::Blend => AlphaMode::Blend,
|
||||
};
|
||||
let normal_scale = checked(m.normal_scale, f32::MIN, f32::MAX, "normal_scale", FINITE)?;
|
||||
let occlusion_strength = checked(m.occlusion_strength, 0.0, 1.0, "occlusion_strength", UNIT)?;
|
||||
let clearcoat_weight = checked(m.clearcoat, 0.0, 1.0, "clearcoat", UNIT)?;
|
||||
let clearcoat_roughness = checked(m.clearcoat_roughness, 0.0, 1.0, "clearcoat_roughness", UNIT)?;
|
||||
let mut sheen_color = [0.0; 3];
|
||||
for (out, v) in sheen_color.iter_mut().zip(m.sheen_color) {
|
||||
*out = checked(v, 0.0, 1.0, "sheen_color", UNIT)?;
|
||||
}
|
||||
let sheen_roughness = checked(m.sheen_roughness, 0.0, 1.0, "sheen_roughness", UNIT)?;
|
||||
|
||||
let mut report = ConversionReport::default();
|
||||
let mut textures = Vec::new();
|
||||
let mut bind =
|
||||
|name: &str, slot: &Option<TextureRef>, input: TextureInput, encoding: TextureEncoding, scale: f32, dropped: Option<&'static str>| {
|
||||
let Some(t) = slot else {
|
||||
if scale != 1.0 {
|
||||
let factor = match input {
|
||||
TextureInput::Normal => "normal_scale",
|
||||
TextureInput::Occlusion => "occlusion_strength",
|
||||
_ => name,
|
||||
};
|
||||
report.items.push(ReportItem::Dropped { input: factor.to_owned(), why: "the corresponding texture is absent" });
|
||||
}
|
||||
return Ok(());
|
||||
};
|
||||
// The texture is checked before a layer that is off drops it.
|
||||
let b = binding(name, t, input, encoding, scale)?;
|
||||
if let Some(why) = dropped {
|
||||
report.items.push(ReportItem::Dropped { input: name.to_owned(), why });
|
||||
return Ok(());
|
||||
}
|
||||
textures.push(b);
|
||||
report.items.push(ReportItem::Unshaded { input: name.to_owned() });
|
||||
Ok::<(), ConvertError>(())
|
||||
};
|
||||
use TextureEncoding::{Linear, Srgb};
|
||||
bind("base_color_texture", &m.base_color_texture, TextureInput::BaseColor, Srgb, 1.0, None)?;
|
||||
bind("metallic_roughness_texture", &m.metallic_roughness_texture, TextureInput::MetallicRoughness, Linear, 1.0, None)?;
|
||||
bind("normal_texture", &m.normal_texture, TextureInput::Normal, Linear, normal_scale, None)?;
|
||||
bind("occlusion_texture", &m.occlusion_texture, TextureInput::Occlusion, Linear, occlusion_strength, None)?;
|
||||
bind("emissive_texture", &m.emissive_texture, TextureInput::Emissive, Srgb, 1.0, None)?;
|
||||
let coat_off = (clearcoat_weight == 0.0).then_some("the clearcoat factor is 0, which turns the layer off");
|
||||
bind("clearcoat_texture", &m.clearcoat_texture, TextureInput::Clearcoat, Linear, 1.0, coat_off)?;
|
||||
bind("clearcoat_roughness_texture", &m.clearcoat_roughness_texture, TextureInput::ClearcoatRoughness, Linear, 1.0, coat_off)?;
|
||||
let sheen_off = (sheen_color == [0.0; 3]).then_some("the sheen color factor is black, which turns the layer off");
|
||||
bind("sheen_color_texture", &m.sheen_color_texture, TextureInput::SheenColor, Srgb, 1.0, sheen_off)?;
|
||||
bind("sheen_roughness_texture", &m.sheen_roughness_texture, TextureInput::SheenRoughness, Linear, 1.0, sheen_off)?;
|
||||
|
||||
let clearcoat = coat_off.is_none().then_some(Clearcoat { weight: clearcoat_weight, roughness: clearcoat_roughness });
|
||||
if clearcoat.is_some() {
|
||||
report.items.push(ReportItem::Unshaded { input: "clearcoat".into() });
|
||||
}
|
||||
let sheen = sheen_off.is_none().then_some(Sheen { color: sheen_color, roughness: sheen_roughness });
|
||||
if sheen.is_some() {
|
||||
report.items.push(ReportItem::Unshaded { input: "sheen".into() });
|
||||
}
|
||||
for (inactive, roughness, input) in
|
||||
[(clearcoat.is_none(), clearcoat_roughness, "clearcoat_roughness"), (sheen.is_none(), sheen_roughness, "sheen_roughness")]
|
||||
{
|
||||
if inactive && roughness != 0.0 {
|
||||
report.items.push(ReportItem::Dropped { input: input.into(), why: "the layer is off" });
|
||||
}
|
||||
}
|
||||
if m.unlit {
|
||||
report.items.push(ReportItem::Unshaded { input: "unlit".into() });
|
||||
}
|
||||
for name in m.extensions.keys().filter(|k| !CONVERTED_EXTENSIONS.contains(&k.as_str())) {
|
||||
report.items.push(ReportItem::Dropped { input: name.clone(), why: "the extension is not converted" });
|
||||
}
|
||||
if m.extensions.get("KHR_materials_clearcoat").is_some_and(|c| c.get("clearcoatNormalTexture").is_some()) {
|
||||
report.items.push(ReportItem::Dropped { input: "clearcoatNormalTexture".into(), why: "craft-mesh does not read it" });
|
||||
}
|
||||
if m.extensions.contains_key(SPECULAR_GLOSSINESS) {
|
||||
report.items.push(ReportItem::Approximated {
|
||||
input: SPECULAR_GLOSSINESS.into(),
|
||||
how: "read as its diffuse color and texture with roughness from the glossiness; its specular color and texture are not converted",
|
||||
});
|
||||
}
|
||||
let surface = Surface {
|
||||
name: m.name.clone(),
|
||||
material,
|
||||
alpha,
|
||||
alpha_mode,
|
||||
emissive,
|
||||
double_sided: m.double_sided,
|
||||
unlit: m.unlit,
|
||||
clearcoat,
|
||||
sheen,
|
||||
textures,
|
||||
other_inputs: Vec::new(),
|
||||
};
|
||||
Ok(Conversion { surface, report })
|
||||
}
|
||||
|
||||
/// The binding of the texture `t` in the field `name`.
|
||||
fn binding(name: &str, t: &TextureRef, input: TextureInput, encoding: TextureEncoding, scale: f32) -> Result<TextureBinding, ConvertError> {
|
||||
let transform = match t.transform {
|
||||
Some(x) => {
|
||||
for v in [x.offset[0], x.offset[1], x.rotation, x.scale[0], x.scale[1]] {
|
||||
checked(v, f32::MIN, f32::MAX, &format!("{name} transform"), FINITE)?;
|
||||
}
|
||||
Some(UvTransform { offset: x.offset, rotation: x.rotation, scale: x.scale })
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let wrap = t.wrap.map(|w| match w {
|
||||
MeshWrap::Repeat => Wrap::Repeat,
|
||||
MeshWrap::Clamp => Wrap::Clamp,
|
||||
MeshWrap::Mirror => Wrap::Mirror,
|
||||
});
|
||||
Ok(TextureBinding { input, source: TextureSource::Image(t.image), encoding, uv_set: t.uv_set, wrap, transform, scale })
|
||||
}
|
||||
@@ -36,6 +36,14 @@
|
||||
//! [`SHADE_WGSL`] is the WGSL text of the same shading functions for an app's own shaders, and
|
||||
//! [`GpuMaterial`] and [`GpuSh9`] lay out the values it reads.
|
||||
//!
|
||||
//! A [`Surface`] is a [`Material`] with the state a renderer applies around it: alpha and its
|
||||
//! mode, emission, sidedness, the unlit flag, clearcoat and sheen layers, and texture bindings
|
||||
//! that are kept but not loaded. With the `mesh` feature, `try_from_mesh` converts a
|
||||
//! `craft_mesh::Material`, and with the `materialx` feature, `try_from_materialx` converts a
|
||||
//! `craft_materialx::StrictMaterial`. Each returns the surface and a [`ConversionReport`] of what it
|
||||
//! kept without shading, approximated or dropped, and a [`ConvertError`] for a value that is not
|
||||
//! finite or is out of its range. Neither feature is on by default.
|
||||
//!
|
||||
//! The diffuse coefficients are the nine real SH coefficients of the radiance, convolved with the
|
||||
//! clamped cosine lobe (band factors `π`, `2π/3` and `π/4`, Ramamoorthi and Hanrahan 2001,
|
||||
//! <https://graphics.stanford.edu/papers/envmap/envmap.pdf>) and divided by `π`. [`irradiance`]
|
||||
@@ -51,9 +59,14 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod brdf;
|
||||
#[cfg(feature = "materialx")]
|
||||
mod convert_materialx;
|
||||
#[cfg(feature = "mesh")]
|
||||
mod convert_mesh;
|
||||
mod environment;
|
||||
mod prefilter;
|
||||
mod sh;
|
||||
mod surface;
|
||||
mod vec3;
|
||||
mod wgsl;
|
||||
|
||||
@@ -61,9 +74,17 @@ mod wgsl;
|
||||
use rayon::prelude::*;
|
||||
|
||||
pub use brdf::{MAX_SPECULAR, MIN_DIRECT_ROUGHNESS, Material, Visibility, try_environment_brdf};
|
||||
#[cfg(feature = "materialx")]
|
||||
pub use convert_materialx::try_from_materialx;
|
||||
#[cfg(feature = "mesh")]
|
||||
pub use convert_mesh::try_from_mesh;
|
||||
pub use environment::{ColorEncoding, ENVIRONMENTS, EnvImage, Environment, MAX_RADIANCE, default_environment, dir_of, uv_of};
|
||||
pub use prefilter::{PrefilterOptions, ggx_distribution, ggx_distribution_between, hammersley, try_prefilter};
|
||||
pub use sh::{irradiance, sh_basis, try_sh9};
|
||||
pub use surface::{
|
||||
AlphaMode, Clearcoat, Conversion, ConversionReport, ConvertError, ReportItem, Sheen, Surface, TextureBinding, TextureEncoding, TextureInput,
|
||||
TextureSource, UvTransform, Wrap,
|
||||
};
|
||||
pub use wgsl::{GpuMaterial, GpuSh9, SHADE_WGSL};
|
||||
|
||||
/// Why an environment could not be made, filtered or read, or a material could not be shaded.
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
//! A surface material: the BRDF core with the surface state around it, and the report and errors
|
||||
//! of the conversions into it.
|
||||
|
||||
use crate::{Material, PbrError};
|
||||
|
||||
/// A material as a renderer needs it: the metallic-roughness [`Material`] that
|
||||
/// [`Material::try_direct`] shades, and the state a renderer applies around it. Alpha, emission
|
||||
/// and sidedness are applied by the renderer, not by the BRDF. The clearcoat and sheen layers,
|
||||
/// the textures and [`Surface::other_inputs`] are kept but not shaded by
|
||||
/// [`Material::try_direct`]. When [`Surface::unlit`] is set, the surface shows its base color
|
||||
/// without lighting, and [`Material::try_direct`] does not give its appearance.
|
||||
///
|
||||
/// Made by `try_from_mesh` (the `mesh` feature) and `try_from_materialx` (the `materialx`
|
||||
/// feature), which check every value.
|
||||
/// `#[non_exhaustive]`: read and change the fields, but get a value from a conversion.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct Surface {
|
||||
/// The source material's name.
|
||||
pub name: String,
|
||||
/// The BRDF core. Where a texture is bound to one of its values, the core holds the factor the
|
||||
/// texture's samples are multiplied by.
|
||||
pub material: Material,
|
||||
/// Coverage from 0 (transparent) to 1 (opaque).
|
||||
pub alpha: f32,
|
||||
/// How [`Surface::alpha`] is used.
|
||||
pub alpha_mode: AlphaMode,
|
||||
/// Linear RGB emission, each channel at least 0.
|
||||
pub emissive: [f32; 3],
|
||||
/// Both faces are drawn and lit.
|
||||
pub double_sided: bool,
|
||||
/// The surface is shown as its base color and alpha, without lighting.
|
||||
pub unlit: bool,
|
||||
/// A clear layer over the base, when its weight is above 0 or a texture sets it.
|
||||
pub clearcoat: Option<Clearcoat>,
|
||||
/// A sheen layer, when its color is not black or a texture sets it.
|
||||
pub sheen: Option<Sheen>,
|
||||
/// Textures bound to the material's values, not loaded or sampled.
|
||||
pub textures: Vec<TextureBinding>,
|
||||
/// Source inputs with no field here, by their source name, as authored. Color values are
|
||||
/// linear.
|
||||
pub other_inputs: Vec<(String, Vec<f32>)>,
|
||||
}
|
||||
|
||||
/// How a surface's alpha is used.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub enum AlphaMode {
|
||||
/// Alpha is ignored and the surface is opaque.
|
||||
#[default]
|
||||
Opaque,
|
||||
/// The surface is drawn where alpha is at least the cutoff, which is at least 0.
|
||||
Mask(f32),
|
||||
/// The surface is blended by alpha.
|
||||
Blend,
|
||||
}
|
||||
|
||||
/// A clear layer over the base: weight and perceptual roughness, each from 0 to 1.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Clearcoat {
|
||||
pub weight: f32,
|
||||
pub roughness: f32,
|
||||
}
|
||||
|
||||
/// A sheen layer: linear RGB color and perceptual roughness, each from 0 to 1.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Sheen {
|
||||
pub color: [f32; 3],
|
||||
pub roughness: f32,
|
||||
}
|
||||
|
||||
/// The value a texture sets, and which of its channels it reads.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum TextureInput {
|
||||
/// Base color in RGB; from glTF, alpha in A.
|
||||
BaseColor,
|
||||
/// glTF's packed texture: roughness in G and metallic in B.
|
||||
MetallicRoughness,
|
||||
/// Metallic in the first channel.
|
||||
Metallic,
|
||||
/// Roughness in the first channel.
|
||||
Roughness,
|
||||
/// A tangent-space normal map; [`TextureBinding::scale`] scales its X and Y.
|
||||
Normal,
|
||||
/// Ambient occlusion in R; [`TextureBinding::scale`] is its strength.
|
||||
Occlusion,
|
||||
/// Emission color in RGB.
|
||||
Emissive,
|
||||
/// Opacity: alpha in the first channel.
|
||||
Opacity,
|
||||
/// A colored opacity in RGB, such as Standard Surface's `opacity`; the alpha is its Rec.709
|
||||
/// luminance.
|
||||
OpacityRgb,
|
||||
/// Clearcoat weight in R.
|
||||
Clearcoat,
|
||||
/// glTF's clearcoat roughness texture: roughness in G.
|
||||
ClearcoatRoughness,
|
||||
/// Clearcoat roughness in the first channel.
|
||||
ClearcoatRoughnessFirst,
|
||||
/// Sheen color in RGB.
|
||||
SheenColor,
|
||||
/// glTF's sheen roughness texture: roughness in A.
|
||||
SheenRoughness,
|
||||
/// Sheen roughness in the first channel.
|
||||
SheenRoughnessFirst,
|
||||
/// Displacement height in the first channel.
|
||||
Displacement,
|
||||
/// A source input with no slot above, by its source name.
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// Where a texture's image is.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum TextureSource {
|
||||
/// An index into the source scene's images (`craft_mesh::Scene::images`).
|
||||
Image(usize),
|
||||
/// A file path, as the source document wrote it with any file prefix applied.
|
||||
File(String),
|
||||
}
|
||||
|
||||
/// How a texture's samples are encoded.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum TextureEncoding {
|
||||
/// Linear values, or data that is not a color.
|
||||
Linear,
|
||||
/// sRGB-encoded color.
|
||||
Srgb,
|
||||
/// A color space by the name the source gives it, which the caller converts.
|
||||
Named(String),
|
||||
}
|
||||
|
||||
/// How a texture continues outside 0..1.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum Wrap {
|
||||
#[default]
|
||||
Repeat,
|
||||
Clamp,
|
||||
Mirror,
|
||||
}
|
||||
|
||||
/// A UV transform: scale, then rotate by `rotation` radians, then add `offset`, in the order and
|
||||
/// with the signs of glTF's `KHR_texture_transform`. Every value is finite.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct UvTransform {
|
||||
pub offset: [f32; 2],
|
||||
pub rotation: f32,
|
||||
pub scale: [f32; 2],
|
||||
}
|
||||
|
||||
/// A texture bound to a value of a [`Surface`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TextureBinding {
|
||||
pub input: TextureInput,
|
||||
pub source: TextureSource,
|
||||
pub encoding: TextureEncoding,
|
||||
/// The UV set the texture reads.
|
||||
pub uv_set: u32,
|
||||
/// How the texture continues outside 0..1 along u and v.
|
||||
pub wrap: [Wrap; 2],
|
||||
pub transform: Option<UvTransform>,
|
||||
/// A finite scale on the samples: the normal scale of a normal map, the strength of an
|
||||
/// occlusion map, and 1 otherwise.
|
||||
pub scale: f32,
|
||||
}
|
||||
|
||||
/// A converted surface and what the conversion did not carry over exactly.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Conversion {
|
||||
pub surface: Surface,
|
||||
pub report: ConversionReport,
|
||||
}
|
||||
|
||||
/// What a conversion kept without shading, approximated or dropped, in the order it found them.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ConversionReport {
|
||||
pub items: Vec<ReportItem>,
|
||||
}
|
||||
|
||||
impl ConversionReport {
|
||||
/// Whether every source value went into a field that [`Material::try_direct`] shades or that
|
||||
/// a renderer applies (alpha, emission, sidedness), with nothing approximated or dropped.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.items.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry of a [`ConversionReport`]. `input` is the source's name for the value.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ReportItem {
|
||||
/// Kept on the [`Surface`] (a layer, a texture, an unlit flag or an other input), and not
|
||||
/// shaded by [`Material::try_direct`].
|
||||
Unshaded { input: String },
|
||||
/// Mapped with a change of meaning; `how` says what was done.
|
||||
Approximated { input: String, how: &'static str },
|
||||
/// Not kept; `why` says why.
|
||||
Dropped { input: String, why: &'static str },
|
||||
/// A warning the source reader gave.
|
||||
Warning(String),
|
||||
}
|
||||
|
||||
/// Why a material could not be converted. Nothing is clamped or replaced: a value out of its
|
||||
/// range is an error.
|
||||
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum ConvertError {
|
||||
/// A value is not a finite number, or is out of its range; `reason` says which.
|
||||
#[error("{input} {reason}")]
|
||||
BadValue { input: String, reason: &'static str },
|
||||
/// A value has the wrong number of components.
|
||||
#[error("{input} has {found} values where {expected} are needed")]
|
||||
Components { input: String, expected: usize, found: usize },
|
||||
/// A color value is in a color space the conversion does not decode.
|
||||
#[error("{input} is in the color space {colorspace}, which is not converted")]
|
||||
ColorSpace { input: String, colorspace: String },
|
||||
/// The source names an input more than once.
|
||||
#[error("the material has more than one {0} input")]
|
||||
Duplicate(String),
|
||||
/// The BRDF core rejected the converted values.
|
||||
#[error(transparent)]
|
||||
Material(#[from] PbrError),
|
||||
}
|
||||
|
||||
/// `v` when it is finite and in `lo..=hi`, else [`ConvertError::BadValue`] naming `input`.
|
||||
#[cfg(feature = "mesh")]
|
||||
pub(crate) fn checked(v: f32, lo: f32, hi: f32, input: &str, reason: &'static str) -> Result<f32, ConvertError> {
|
||||
if v.is_finite() && (lo..=hi).contains(&v) { Ok(v) } else { Err(ConvertError::BadValue { input: input.to_owned(), reason }) }
|
||||
}
|
||||
|
||||
/// The reason text for a value that must be from 0 to 1.
|
||||
#[cfg(any(feature = "mesh", feature = "materialx"))]
|
||||
pub(crate) const UNIT: &str = "is not a number from 0 to 1";
|
||||
/// The reason text for a value that must be finite and at least 0.
|
||||
#[cfg(any(feature = "mesh", feature = "materialx"))]
|
||||
pub(crate) const NON_NEGATIVE: &str = "is not a finite number of at least 0";
|
||||
/// The reason text for a value that must be finite.
|
||||
#[cfg(any(feature = "mesh", feature = "materialx"))]
|
||||
pub(crate) const FINITE: &str = "is not a finite number";
|
||||
@@ -0,0 +1,252 @@
|
||||
use craft_materialx::{Document, Resolved};
|
||||
use craft_mesh::Material as Mesh;
|
||||
use craft_pbr::{ConvertError, ReportItem, TextureInput, TextureSource, try_from_materialx, try_from_mesh};
|
||||
|
||||
fn document(shader: &str, inputs: &str, nodes: &str, material_inputs: &str) -> Document {
|
||||
let text = format!(
|
||||
r#"<materialx><{shader} name="S">{inputs}</{shader}>{nodes}<surfacematerial name="M"><input name="surfaceshader" nodename="S"/>{material_inputs}</surfacematerial></materialx>"#
|
||||
);
|
||||
Document::parse(text.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inactive_emission_still_validates_the_color_field() {
|
||||
let doc = document("standard_surface", r#"<input name="emission" value="0"/><input name="emission_color" value="2,0,0"/>"#, "", "");
|
||||
let material = doc.read_material_strict(None).unwrap();
|
||||
assert!(matches!(try_from_materialx(&material), Err(ConvertError::BadValue { input, .. }) if input == "emission_color"));
|
||||
let legacy = doc.read_material(None).unwrap();
|
||||
assert!(!legacy.inputs.iter().any(|(name, _)| name == "emission_color"));
|
||||
let valid = document("standard_surface", r#"<input name="emission" value="0"/><input name="emission_color" value="0.2,0.3,0.4"/>"#, "", "");
|
||||
let converted = try_from_materialx(&valid.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_eq!(converted.surface.emissive, [0.0; 3]);
|
||||
assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == "emission_color")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn displacement_scale_is_reported_when_it_is_not_applied() {
|
||||
for scale in ["", r#"<input name="scale" value="1"/>"#, r#"<input name="scale" value="2"/>"#] {
|
||||
let node = format!(r#"<displacement name="D"><input name="displacement" type="float" value="0.25"/>{scale}</displacement>"#);
|
||||
let doc = document("standard_surface", "", &node, r#"<input name="displacementshader" nodename="D"/>"#);
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_eq!(converted.surface.other_inputs, vec![("displacement".into(), vec![0.25])]);
|
||||
assert_eq!(
|
||||
converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains("scale"))),
|
||||
scale.contains('2')
|
||||
);
|
||||
}
|
||||
for scale in ["1,2", "NaN", ""] {
|
||||
let node = format!(r#"<displacement name="D"><input name="displacement" value="0.25"/><input name="scale" value="{scale}"/></displacement>"#);
|
||||
assert!(document("standard_surface", "", &node, r#"<input name="displacementshader" nodename="D"/>"#).read_material_strict(None).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graph_surface_connections_preserve_the_shader_scope() {
|
||||
let doc = Document::parse(
|
||||
br#"<materialx><image name="T" type="color3"><input name="file" value="root.png"/></image>
|
||||
<nodegraph name="g"><image name="T" type="color3"><input name="file" value="graph.png"/></image>
|
||||
<standard_surface name="S"><input name="base_color" nodename="T"/></standard_surface>
|
||||
<output name="out" nodename="S"/></nodegraph>
|
||||
<surfacematerial name="M"><input name="surfaceshader" nodegraph="g" output="out"/></surfacematerial></materialx>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_eq!(converted.surface.textures[0].source, TextureSource::File("graph.png".into()));
|
||||
assert!(doc.read_material(None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_authored_connections_do_not_become_shader_defaults() {
|
||||
for reference in [r#"nodename="missing""#, r#"nodegraph="missing" output="out""#] {
|
||||
let doc = document("open_pbr_surface", &format!(r#"<input name="base_color" {reference}/>"#), "", "");
|
||||
assert!(doc.read_material_strict(None).is_err(), "{reference}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nonzero_tiled_image_offset_is_reported() {
|
||||
for offset in ["0,0", "0.25,0"] {
|
||||
let nodes = format!(
|
||||
r#"<tiledimage name="T" type="color3"><input name="file" value="tile.png"/><input name="uvtiling" value="2,2"/><input name="uvoffset" value="{offset}"/></tiledimage>"#
|
||||
);
|
||||
let doc = document("open_pbr_surface", r#"<input name="base_color" nodename="T"/>"#, &nodes, "");
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_eq!(converted.surface.textures[0].transform.unwrap().scale, [2.0, 2.0]);
|
||||
assert_eq!(
|
||||
converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains("uvoffset"))),
|
||||
offset != "0,0"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_omitted_color_constant_value_is_black() {
|
||||
let doc = document("open_pbr_surface", r#"<input name="base_color" nodename="K"/>"#, r#"<constant name="K" type="color3"/>"#, "");
|
||||
let material = doc.read_material_strict(None).unwrap();
|
||||
assert!(
|
||||
matches!(material.inputs.iter().find(|(name, _)| name == "base_color"), Some((_, Resolved::Constant { values, .. })) if values == &[0.0; 3])
|
||||
);
|
||||
assert_eq!(try_from_materialx(&material).unwrap().surface.material.base_color(), [0.0; 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_authored_cutoff_is_reported_when_the_alpha_mode_does_not_use_it() {
|
||||
for mode in [0, 1, 2] {
|
||||
let doc = document("gltf_pbr", &format!(r#"<input name="alpha_mode" value="{mode}"/><input name="alpha_cutoff" value="0.25"/>"#), "", "");
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_eq!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == "alpha_cutoff")), mode != 1);
|
||||
if mode == 1 {
|
||||
assert_eq!(converted.surface.alpha_mode, craft_pbr::AlphaMode::Mask(0.25));
|
||||
}
|
||||
let absent = document("gltf_pbr", &format!(r#"<input name="alpha_mode" value="{mode}"/>"#), "", "");
|
||||
let converted = try_from_materialx(&absent.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(!converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == "alpha_cutoff")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_displacement_is_reported_without_a_scalar_height_binding() {
|
||||
for source in [r#"type="vector3" value="0.1,0.2,0.3""#, r#"type="vector3" nodename="T""#, r#"value="0.1,0.2,0.3""#] {
|
||||
let nodes = format!(
|
||||
r#"<image name="T" type="vector3"><input name="file" value="vector.png"/></image><displacement name="D"><input name="displacement" {source}/></displacement>"#
|
||||
);
|
||||
let doc = document("standard_surface", "", &nodes, r#"<input name="displacementshader" nodename="D"/>"#);
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(!converted.surface.textures.iter().any(|texture| texture.input == TextureInput::Displacement));
|
||||
assert!(!converted.surface.other_inputs.iter().any(|(name, _)| name == "displacement"));
|
||||
assert!(
|
||||
converted
|
||||
.report
|
||||
.items
|
||||
.iter()
|
||||
.any(|item| matches!(item, ReportItem::Warning(message) if message.contains("vector") && message.contains("displacement")))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inactive_mesh_layers_report_nondefault_roughness() {
|
||||
assert!(try_from_mesh(&Mesh::default()).unwrap().report.is_empty());
|
||||
let converted = try_from_mesh(&Mesh { clearcoat_roughness: 0.5, sheen_roughness: 0.5, ..Mesh::default() }).unwrap();
|
||||
for field in ["clearcoat_roughness", "sheen_roughness"] {
|
||||
assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == field)), "{field}");
|
||||
}
|
||||
let active =
|
||||
try_from_mesh(&Mesh { clearcoat: 1.0, clearcoat_roughness: 0.5, sheen_color: [0.2; 3], sheen_roughness: 0.5, ..Mesh::default() }).unwrap();
|
||||
assert_eq!(active.surface.clearcoat.unwrap().roughness, 0.5);
|
||||
assert_eq!(active.surface.sheen.unwrap().roughness, 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn omitted_numeric_constants_use_their_typed_zero_values() {
|
||||
for (kind, count) in [("float", 1), ("integer", 1), ("boolean", 1), ("vector2", 2), ("vector3", 3), ("vector4", 4), ("color3", 3), ("color4", 4)]
|
||||
{
|
||||
let doc = document("open_pbr_surface", r#"<input name="base_color" nodename="K"/>"#, &format!(r#"<constant name="K" type="{kind}"/>"#), "");
|
||||
let material = doc.read_material_strict(None).unwrap();
|
||||
assert!(
|
||||
matches!(material.inputs.iter().find(|(name, _)| name == "base_color"), Some((_, Resolved::Constant { values, .. })) if values == &vec![0.0; count]),
|
||||
"{kind}"
|
||||
);
|
||||
}
|
||||
let unsupported = document("open_pbr_surface", r#"<input name="base_color" nodename="K"/>"#, r#"<constant name="K" type="matrix33"/>"#, "");
|
||||
let material = unsupported.read_material_strict(None).unwrap();
|
||||
assert!(material.inputs.is_empty() && !material.warnings.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_graph_output_selection_rejects_ambiguity() {
|
||||
let read = |outputs: &str, selection: &str| {
|
||||
Document::parse(
|
||||
format!(
|
||||
r#"<materialx><nodegraph name="g">
|
||||
<standard_surface name="A"><input name="base_color" value="0.2,0.2,0.2"/></standard_surface>
|
||||
<standard_surface name="B"><input name="base_color" value="0.8,0.8,0.8"/></standard_surface>{outputs}</nodegraph>
|
||||
<surfacematerial name="M"><input name="surfaceshader" nodegraph="g" {selection}/></surfacematerial></materialx>"#
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.unwrap()
|
||||
.read_material_strict(None)
|
||||
};
|
||||
let both = r#"<output name="a" nodename="A"/><output name="b" nodename="B"/>"#;
|
||||
assert!(read(both, "").is_err());
|
||||
assert!(read(both, r#"output="missing""#).is_err());
|
||||
assert_eq!(try_from_materialx(&read(both, r#"output="b""#).unwrap()).unwrap().surface.material.base_color(), [0.8; 3]);
|
||||
let sole = read(r#"<output name="a" nodename="A"/>"#, r#"output="unused""#).unwrap();
|
||||
assert_eq!(try_from_materialx(&sole).unwrap().surface.material.base_color(), [0.2; 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn omitted_node_parameters_keep_their_identity_defaults() {
|
||||
let displaced = document(
|
||||
"standard_surface",
|
||||
"",
|
||||
r#"<displacement name="D"><input name="displacement" value="0.25"/><input name="scale" type="float"/></displacement>"#,
|
||||
r#"<input name="displacementshader" nodename="D"/>"#,
|
||||
);
|
||||
assert!(displaced.read_material_strict(None).unwrap().warnings.is_empty());
|
||||
let image = document(
|
||||
"open_pbr_surface",
|
||||
r#"<input name="base_color" nodename="T"/>"#,
|
||||
r#"<tiledimage name="T" type="color3"><input name="file" value="tile.png"/><input name="uvoffset" type="vector2"/></tiledimage>"#,
|
||||
"",
|
||||
);
|
||||
assert!(image.read_material_strict(None).unwrap().warnings.is_empty());
|
||||
let normal = document(
|
||||
"open_pbr_surface",
|
||||
r#"<input name="geometry_normal" nodename="N"/>"#,
|
||||
r#"<normalmap name="N"><input name="in" nodename="T"/><input name="scale" type="float"/></normalmap><image name="T" type="vector3"><input name="file" value="n.png"/></image>"#,
|
||||
"",
|
||||
);
|
||||
assert!(normal.read_material_strict(None).unwrap().warnings.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_connections_report_the_unsupported_value() {
|
||||
let doc = Document::parse(
|
||||
br#"<materialx><nodegraph name="g"><input name="tint" type="color3" value="0.2,0.3,0.4"/>
|
||||
<standard_surface name="S"><input name="base_color" interfacename="tint" value="0.8,0.8,0.8"/></standard_surface>
|
||||
<output name="out" nodename="S"/></nodegraph><surfacematerial name="M">
|
||||
<input name="surfaceshader" nodegraph="g"/></surfacematerial></materialx>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(
|
||||
converted
|
||||
.report
|
||||
.items
|
||||
.iter()
|
||||
.any(|item| matches!(item, ReportItem::Warning(message) if message.contains("interface") && message.contains("tint")))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connected_image_tiling_keeps_the_resolved_scale() {
|
||||
for connection in [r#"nodename="K""#, r#"nodegraph="g""#] {
|
||||
let nodes = format!(
|
||||
r#"<tiledimage name="T" type="color3"><input name="file" value="tile.png"/><input name="uvtiling" {connection}/></tiledimage>
|
||||
<constant name="K" type="vector2"><input name="value" value="2,3"/></constant>
|
||||
<nodegraph name="g"><constant name="K" type="vector2"><input name="value" value="2,3"/></constant><output name="out" nodename="K"/></nodegraph>"#
|
||||
);
|
||||
let doc = document("standard_surface", r#"<input name="base_color" nodename="T"/>"#, &nodes, "");
|
||||
let material = doc.read_material_strict(None).unwrap();
|
||||
assert!(material.warnings.is_empty(), "{:?}", material.warnings);
|
||||
assert_eq!(material.uv_tiling, [2.0, 3.0]);
|
||||
let converted = try_from_materialx(&material).unwrap();
|
||||
let binding = converted.surface.textures.iter().find(|binding| binding.input == TextureInput::BaseColor).unwrap();
|
||||
assert_eq!(binding.transform.as_ref().map(|transform| transform.scale), Some([2.0, 3.0]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn images_without_literal_file_values_report_the_skipped_texture() {
|
||||
for kind in ["image", "tiledimage"] {
|
||||
for file in ["", r#"<input name="file"/>"#, r#"<input name="file" value=""/>"#, r#"<input name="file" interfacename="filename"/>"#] {
|
||||
let nodes = format!(r#"<{kind} name="T" type="color3">{file}</{kind}>"#);
|
||||
let doc = document("standard_surface", r#"<input name="base_color" nodename="T"/>"#, &nodes, "");
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(converted.surface.textures.is_empty());
|
||||
assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains("file"))));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
use craft_materialx::Document;
|
||||
use craft_mesh::Material;
|
||||
use craft_pbr::{ReportItem, TextureInput, try_from_materialx, try_from_mesh};
|
||||
|
||||
fn document(input: &str, nodes: &str) -> Document {
|
||||
Document::parse(
|
||||
format!(
|
||||
r#"<materialx><open_pbr_surface name="S">{input}</open_pbr_surface>{nodes}<surfacematerial name="M"><input name="surfaceshader" nodename="S"/></surfacematerial></materialx>"#
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_output_without_a_target_does_not_select_another_output() {
|
||||
let doc = Document::parse(
|
||||
br#"<materialx><nodegraph name="g"><open_pbr_surface name="S"/>
|
||||
<output name="a" nodename="S"/><output name="b"/></nodegraph>
|
||||
<surfacematerial name="M"><input name="surfaceshader" nodegraph="g" output="b"/></surfacematerial></materialx>"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(doc.read_material_strict(None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nondefault_image_addressing_modes_are_reported() {
|
||||
for name in ["uaddressmode", "vaddressmode"] {
|
||||
for mode in ["constant", "clamp", "mirror"] {
|
||||
let node =
|
||||
format!(r#"<image name="T" type="color3"><input name="file" value="color.png"/><input name="{name}" value="{mode}"/></image>"#);
|
||||
let doc = document(r#"<input name="base_color" nodename="T"/>"#, &node);
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains(name))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_identified_convert_node_uses_its_omitted_input_default() {
|
||||
let doc = document(r#"<input name="base_color" nodename="C"/>"#, r#"<convert name="C" type="color3" nodedef="ND_convert_float_color3"/>"#);
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_eq!(converted.surface.material.base_color(), [0.0; 3]);
|
||||
assert!(converted.report.is_empty(), "{:?}", converted.report);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_literals_use_the_nodes_type_when_the_input_omits_it() {
|
||||
for (ty, value) in [("integer", "0.5"), ("float", "1,2"), ("color3", "1,2")] {
|
||||
let node = format!(r#"<constant name="C" type="{ty}"><input name="value" value="{value}"/></constant>"#);
|
||||
let doc = document(r#"<input name="base_color" nodename="C"/>"#, &node);
|
||||
assert!(doc.read_material_strict(None).is_err(), "{ty} {value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_graph_local_node_does_not_bind_a_root_node() {
|
||||
let doc = Document::parse(
|
||||
br#"<materialx><image name="T" type="color3"><input name="file" value="root.png"/></image>
|
||||
<nodegraph name="g"><open_pbr_surface name="S"><input name="base_color" nodename="T"/></open_pbr_surface>
|
||||
<output name="out" nodename="S"/></nodegraph><surfacematerial name="M">
|
||||
<input name="surfaceshader" nodegraph="g"/></surfacematerial></materialx>"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(doc.read_material_strict(None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_normal_vectors_are_not_bound_as_tangent_space_maps() {
|
||||
let image = r#"<image name="T" type="vector3"><input name="file" value="normal.png"/></image>"#;
|
||||
let direct = document(r#"<input name="geometry_normal" nodename="T"/>"#, image);
|
||||
let converted = try_from_materialx(&direct.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(!converted.surface.textures.iter().any(|binding| binding.input == TextureInput::Normal));
|
||||
assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == "geometry_normal")));
|
||||
let nodes = format!(r#"{image}<normalmap name="N" type="vector3"><input name="in" nodename="T"/></normalmap>"#);
|
||||
let wrapped = document(r#"<input name="geometry_normal" nodename="N"/>"#, &nodes);
|
||||
let converted = try_from_materialx(&wrapped.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(converted.surface.textures.iter().any(|binding| binding.input == TextureInput::Normal));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nondefault_factors_without_textures_are_reported() {
|
||||
let material = Material { normal_scale: 0.5, occlusion_strength: 0.25, ..Material::default() };
|
||||
let converted = try_from_mesh(&material).unwrap();
|
||||
for name in ["normal_scale", "occlusion_strength"] {
|
||||
assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == name)));
|
||||
}
|
||||
assert!(try_from_mesh(&Material::default()).unwrap().report.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_normalmaps_are_reported_and_skipped() {
|
||||
let nodes = r#"<image name="T" type="vector3"><input name="file" value="normal.png"/></image>
|
||||
<normalmap name="Inner" type="vector3"><input name="in" nodename="T"/></normalmap>
|
||||
<normalmap name="Outer" type="vector3"><input name="in" nodename="Inner"/></normalmap>"#;
|
||||
let doc = document(r#"<input name="geometry_normal" nodename="Outer"/>"#, nodes);
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(!converted.surface.textures.iter().any(|binding| binding.input == TextureInput::Normal));
|
||||
assert!(
|
||||
converted
|
||||
.report
|
||||
.items
|
||||
.iter()
|
||||
.any(|item| matches!(item, ReportItem::Warning(message) if message.contains("nested") && message.contains("Outer")))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalmap_literals_do_not_become_untransformed_world_normals() {
|
||||
for value in ["1,0.5,1", "0.5,0.5,1"] {
|
||||
let doc = document(
|
||||
r#"<input name="geometry_normal" nodename="N"/>"#,
|
||||
&format!(r#"<normalmap name="N" type="vector3"><input name="in" value="{value}"/></normalmap>"#),
|
||||
);
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(!converted.surface.other_inputs.iter().any(|(name, _)| name == "geometry_normal"));
|
||||
assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains("normalmap"))));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authored_normalmap_frames_are_reported() {
|
||||
for name in ["normal", "tangent", "bitangent"] {
|
||||
let nodes = format!(
|
||||
r#"<image name="T" type="vector3"><input name="file" value="normal.png"/></image>
|
||||
<normalmap name="N" type="vector3"><input name="in" nodename="T"/><input name="{name}" type="vector3" value="1,0,0"/></normalmap>"#
|
||||
);
|
||||
let doc = document(r#"<input name="geometry_normal" nodename="N"/>"#, &nodes);
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains(name))));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coat_normals_keep_tangent_maps_and_report_direct_world_images() {
|
||||
for (shader, weight, normal) in [
|
||||
("open_pbr_surface", "coat_weight", "geometry_coat_normal"),
|
||||
("standard_surface", "coat", "coat_normal"),
|
||||
("gltf_pbr", "clearcoat", "clearcoat_normal"),
|
||||
] {
|
||||
for (node, wrapped) in [("T", false), ("N", true)] {
|
||||
let xml = format!(
|
||||
r#"<materialx><{shader} name="S"><input name="{weight}" value="1"/><input name="{normal}" nodename="{node}"/></{shader}>
|
||||
<image name="T" type="vector3"><input name="file" value="normal.png"/></image>
|
||||
<normalmap name="N" type="vector3"><input name="in" nodename="T"/></normalmap>
|
||||
<surfacematerial name="M"><input name="surfaceshader" nodename="S"/></surfacematerial></materialx>"#
|
||||
);
|
||||
let doc = Document::parse(xml.as_bytes()).unwrap();
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
converted.surface.textures.iter().any(|binding| matches!(&binding.input, TextureInput::Other(name) if name == normal)),
|
||||
wrapped,
|
||||
"{shader} {node}"
|
||||
);
|
||||
assert_eq!(
|
||||
converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == normal)),
|
||||
!wrapped,
|
||||
"{shader} {node}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,724 @@
|
||||
//! Conversions into a `Surface`: glTF 2.0 materials from craft-mesh and MaterialX shaders from
|
||||
//! craft-materialx, checked against the defaults and ranges the public definitions give.
|
||||
|
||||
use craft_materialx::{Document, Resolved as Value, Shader, StrictMaterial as Mx, Texture, write_open_pbr};
|
||||
use craft_mesh::{AlphaMode as MeshAlpha, Material as Mesh, TextureRef, UvTransform as MeshUv, Wrap as MeshWrap};
|
||||
use craft_pbr::{
|
||||
AlphaMode, Clearcoat, Conversion, ConvertError, ReportItem, Sheen, TextureEncoding, TextureInput, TextureSource, UvTransform, Wrap,
|
||||
try_from_materialx, try_from_mesh,
|
||||
};
|
||||
|
||||
fn close(a: f32, b: f32) -> bool {
|
||||
a.is_finite() && b.is_finite() && (a - b).abs() <= 1e-6 * a.abs().max(b.abs()).max(1.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_is_false_for_values_that_are_not_finite() {
|
||||
assert!(close(1.0, 1.0 + 1e-7));
|
||||
assert!(!close(f32::INFINITY, 1.0) && !close(f32::INFINITY, f32::INFINITY) && !close(f32::NAN, 1.0));
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn assert_close3(a: [f32; 3], b: [f32; 3]) {
|
||||
assert!(a.iter().zip(b).all(|(x, y)| close(*x, y)), "{a:?} against {b:?}");
|
||||
}
|
||||
|
||||
fn unshaded(c: &Conversion, input: &str) -> bool {
|
||||
c.report.items.iter().any(|i| matches!(i, ReportItem::Unshaded { input: n } if n == input))
|
||||
}
|
||||
|
||||
fn approximated(c: &Conversion, input: &str) -> bool {
|
||||
c.report.items.iter().any(|i| matches!(i, ReportItem::Approximated { input: n, .. } if n == input))
|
||||
}
|
||||
|
||||
fn dropped(c: &Conversion, input: &str) -> bool {
|
||||
c.report.items.iter().any(|i| matches!(i, ReportItem::Dropped { input: n, .. } if n == input))
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn bad_value(r: Result<Conversion, ConvertError>, input: &str) {
|
||||
match r {
|
||||
Err(ConvertError::BadValue { input: n, .. }) => assert!(n.contains(input), "{n} is not {input}"),
|
||||
other => panic!("{input}: expected a bad value, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn tex(image: usize) -> Option<TextureRef> {
|
||||
Some(TextureRef { image, ..TextureRef::default() })
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ craft-mesh (glTF 2.0)
|
||||
|
||||
#[test]
|
||||
fn mesh_factors_map_as_they_are() {
|
||||
let m = Mesh {
|
||||
name: "Paint".into(),
|
||||
base_color: [0.25, 0.5, 0.75, 0.6],
|
||||
metallic: 0.3,
|
||||
roughness: 0.7,
|
||||
emissive: [2.0, 0.5, 0.0],
|
||||
alpha_mode: MeshAlpha::Mask(0.4),
|
||||
double_sided: true,
|
||||
..Mesh::default()
|
||||
};
|
||||
let c = try_from_mesh(&m).unwrap();
|
||||
let s = &c.surface;
|
||||
assert_eq!(s.name, "Paint");
|
||||
assert_eq!(s.material.base_color(), [0.25, 0.5, 0.75]);
|
||||
assert_eq!((s.material.metallic(), s.material.roughness()), (0.3, 0.7));
|
||||
assert_eq!((s.material.specular(), s.material.diffuse()), (1.0, 1.0));
|
||||
assert_eq!(s.alpha, 0.6);
|
||||
assert_eq!(s.alpha_mode, AlphaMode::Mask(0.4));
|
||||
assert_eq!(s.emissive, [2.0, 0.5, 0.0]);
|
||||
assert!(s.double_sided && !s.unlit);
|
||||
assert_eq!((s.clearcoat, s.sheen), (None, None));
|
||||
assert!(s.textures.is_empty() && s.other_inputs.is_empty());
|
||||
assert!(c.report.is_empty(), "{:?}", c.report);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_defaults_are_the_gltf_defaults() {
|
||||
// glTF 2.0 gives baseColorFactor [1, 1, 1, 1], metallicFactor 1, roughnessFactor 1,
|
||||
// emissiveFactor [0, 0, 0] and alphaMode OPAQUE
|
||||
// (https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-material).
|
||||
let c = try_from_mesh(&Mesh::default()).unwrap();
|
||||
let s = &c.surface;
|
||||
assert_eq!(s.material.base_color(), [1.0; 3]);
|
||||
assert_eq!((s.material.metallic(), s.material.roughness(), s.alpha), (1.0, 1.0, 1.0));
|
||||
assert_eq!((s.emissive, s.alpha_mode), ([0.0; 3], AlphaMode::Opaque));
|
||||
assert!(!s.double_sided);
|
||||
assert!(c.report.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_extensions_that_are_not_converted_are_reported_as_dropped() {
|
||||
let mut m = Mesh::default();
|
||||
for name in ["KHR_materials_transmission", "KHR_materials_clearcoat", "KHR_materials_unlit", "KHR_materials_emissive_strength"] {
|
||||
m.extensions.insert(name.into(), craft_mesh::serde_json::json!({}));
|
||||
}
|
||||
let c = try_from_mesh(&m).unwrap();
|
||||
assert!(dropped(&c, "KHR_materials_transmission"), "{:?}", c.report);
|
||||
assert_eq!(c.report.items.len(), 1, "{:?}", c.report);
|
||||
// craft-mesh reads part of these two.
|
||||
m.extensions.insert("KHR_materials_clearcoat".into(), craft_mesh::serde_json::json!({ "clearcoatNormalTexture": { "index": 0 } }));
|
||||
m.extensions.insert("KHR_materials_pbrSpecularGlossiness".into(), craft_mesh::serde_json::json!({ "specularFactor": [1, 0, 0] }));
|
||||
let c = try_from_mesh(&m).unwrap();
|
||||
assert!(dropped(&c, "clearcoatNormalTexture"), "{:?}", c.report);
|
||||
assert!(approximated(&c, "KHR_materials_pbrSpecularGlossiness"), "{:?}", c.report);
|
||||
assert_eq!(c.report.items.len(), 3, "{:?}", c.report);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_textures_keep_their_uv_state_scale_and_encoding() {
|
||||
let mr = TextureRef {
|
||||
image: 2,
|
||||
uv_set: 1,
|
||||
wrap: [MeshWrap::Clamp, MeshWrap::Mirror],
|
||||
transform: Some(MeshUv { offset: [0.25, 0.5], rotation: 0.5, scale: [2.0, 3.0] }),
|
||||
};
|
||||
let m = Mesh {
|
||||
base_color_texture: tex(1),
|
||||
metallic_roughness_texture: Some(mr),
|
||||
normal_texture: tex(3),
|
||||
normal_scale: 0.5,
|
||||
occlusion_texture: tex(4),
|
||||
occlusion_strength: 0.25,
|
||||
emissive_texture: tex(5),
|
||||
clearcoat: 0.5,
|
||||
clearcoat_texture: tex(6),
|
||||
clearcoat_roughness_texture: tex(7),
|
||||
sheen_color: [0.1, 0.0, 0.0],
|
||||
sheen_color_texture: tex(8),
|
||||
sheen_roughness_texture: tex(9),
|
||||
..Mesh::default()
|
||||
};
|
||||
let c = try_from_mesh(&m).unwrap();
|
||||
// Base color, emissive and sheen color textures are sRGB, the rest linear (glTF 2.0 and
|
||||
// KHR_materials_sheen); the packed texture holds roughness in G and metallic in B.
|
||||
let expected = [
|
||||
("base_color_texture", TextureInput::BaseColor, TextureEncoding::Srgb),
|
||||
("metallic_roughness_texture", TextureInput::MetallicRoughness, TextureEncoding::Linear),
|
||||
("normal_texture", TextureInput::Normal, TextureEncoding::Linear),
|
||||
("occlusion_texture", TextureInput::Occlusion, TextureEncoding::Linear),
|
||||
("emissive_texture", TextureInput::Emissive, TextureEncoding::Srgb),
|
||||
("clearcoat_texture", TextureInput::Clearcoat, TextureEncoding::Linear),
|
||||
("clearcoat_roughness_texture", TextureInput::ClearcoatRoughness, TextureEncoding::Linear),
|
||||
("sheen_color_texture", TextureInput::SheenColor, TextureEncoding::Srgb),
|
||||
("sheen_roughness_texture", TextureInput::SheenRoughness, TextureEncoding::Linear),
|
||||
];
|
||||
assert_eq!(c.surface.textures.len(), expected.len());
|
||||
for (i, ((name, input, encoding), b)) in expected.into_iter().zip(&c.surface.textures).enumerate() {
|
||||
assert_eq!((&b.input, &b.encoding, &b.source), (&input, &encoding, &TextureSource::Image(i + 1)), "{name}");
|
||||
assert!(unshaded(&c, name), "{name}");
|
||||
}
|
||||
let mr = &c.surface.textures[1];
|
||||
assert_eq!((mr.uv_set, mr.wrap), (1, [Wrap::Clamp, Wrap::Mirror]));
|
||||
assert_eq!(mr.transform, Some(UvTransform { offset: [0.25, 0.5], rotation: 0.5, scale: [2.0, 3.0] }));
|
||||
assert_eq!((c.surface.textures[2].scale, c.surface.textures[3].scale, c.surface.textures[0].scale), (0.5, 0.25, 1.0));
|
||||
assert_eq!(c.surface.textures[0].transform, None);
|
||||
// The core holds the factors the textures multiply: glTF's defaults here.
|
||||
assert_eq!((c.surface.material.metallic(), c.surface.material.roughness()), (1.0, 1.0));
|
||||
assert!(unshaded(&c, "clearcoat") && unshaded(&c, "sheen"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_clearcoat_and_sheen_are_kept_and_layers_that_are_off_drop_their_textures() {
|
||||
let on = Mesh { clearcoat: 0.75, clearcoat_roughness: 0.25, sheen_color: [0.5, 0.25, 0.0], sheen_roughness: 0.6, ..Mesh::default() };
|
||||
let c = try_from_mesh(&on).unwrap();
|
||||
assert_eq!(c.surface.clearcoat, Some(Clearcoat { weight: 0.75, roughness: 0.25 }));
|
||||
assert_eq!(c.surface.sheen, Some(Sheen { color: [0.5, 0.25, 0.0], roughness: 0.6 }));
|
||||
// A clearcoat factor of 0 and a black sheen color each turn their layer off
|
||||
// (KHR_materials_clearcoat, KHR_materials_sheen).
|
||||
let off = Mesh {
|
||||
clearcoat_roughness: 0.5,
|
||||
clearcoat_texture: tex(1),
|
||||
clearcoat_roughness_texture: tex(2),
|
||||
sheen_roughness: 0.5,
|
||||
sheen_color_texture: tex(3),
|
||||
sheen_roughness_texture: tex(4),
|
||||
..Mesh::default()
|
||||
};
|
||||
let c = try_from_mesh(&off).unwrap();
|
||||
assert_eq!((c.surface.clearcoat, c.surface.sheen), (None, None));
|
||||
assert!(c.surface.textures.is_empty());
|
||||
for name in ["clearcoat_texture", "clearcoat_roughness_texture", "sheen_color_texture", "sheen_roughness_texture"] {
|
||||
assert!(dropped(&c, name), "{name}");
|
||||
}
|
||||
assert!(!unshaded(&c, "clearcoat") && !unshaded(&c, "sheen"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_textures_of_a_layer_that_is_off_are_checked_before_they_are_dropped() {
|
||||
let t = TextureRef { transform: Some(MeshUv { rotation: f32::NAN, ..MeshUv::default() }), ..TextureRef::default() };
|
||||
bad_value(try_from_mesh(&Mesh { clearcoat_roughness_texture: Some(t), ..Mesh::default() }), "clearcoat_roughness_texture transform");
|
||||
bad_value(try_from_mesh(&Mesh { sheen_color_texture: Some(t), ..Mesh::default() }), "sheen_color_texture transform");
|
||||
let fine = TextureRef { transform: Some(MeshUv { rotation: 0.5, ..MeshUv::default() }), ..TextureRef::default() };
|
||||
let c = try_from_mesh(&Mesh { clearcoat_texture: Some(fine), ..Mesh::default() }).unwrap();
|
||||
assert!(c.surface.textures.is_empty() && dropped(&c, "clearcoat_texture"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_unlit_is_kept_and_reported() {
|
||||
let c = try_from_mesh(&Mesh { unlit: true, base_color: [0.2, 0.4, 0.6, 1.0], ..Mesh::default() }).unwrap();
|
||||
assert!(c.surface.unlit);
|
||||
assert_eq!(c.surface.material.base_color(), [0.2, 0.4, 0.6]);
|
||||
assert!(unshaded(&c, "unlit"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_values_that_are_not_finite_or_out_of_range_are_errors() {
|
||||
type Set = fn(&mut Mesh, f32);
|
||||
let unit: [(&str, Set); 8] = [
|
||||
("base_color", |m, v| m.base_color[1] = v),
|
||||
("base_color alpha", |m, v| m.base_color[3] = v),
|
||||
("metallic", |m, v| m.metallic = v),
|
||||
("roughness", |m, v| m.roughness = v),
|
||||
("occlusion_strength", |m, v| m.occlusion_strength = v),
|
||||
("clearcoat", |m, v| m.clearcoat = v),
|
||||
("clearcoat_roughness", |m, v| m.clearcoat_roughness = v),
|
||||
("sheen_color", |m, v| m.sheen_color[2] = v),
|
||||
];
|
||||
for (name, set) in unit.iter().chain([("sheen_roughness", (|m: &mut Mesh, v| m.sheen_roughness = v) as Set)].iter()) {
|
||||
for v in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.01, 1.01] {
|
||||
let mut m = Mesh::default();
|
||||
set(&mut m, v);
|
||||
bad_value(try_from_mesh(&m), name);
|
||||
}
|
||||
for v in [0.0, 1.0] {
|
||||
let mut m = Mesh::default();
|
||||
set(&mut m, v);
|
||||
assert!(try_from_mesh(&m).is_ok(), "{name} {v}");
|
||||
}
|
||||
}
|
||||
for v in [f32::NAN, f32::INFINITY, -1.0] {
|
||||
bad_value(try_from_mesh(&Mesh { emissive: [0.0, v, 0.0], ..Mesh::default() }), "emissive");
|
||||
bad_value(try_from_mesh(&Mesh { alpha_mode: MeshAlpha::Mask(v), ..Mesh::default() }), "alpha cutoff");
|
||||
}
|
||||
for v in [f32::NAN, f32::INFINITY] {
|
||||
bad_value(try_from_mesh(&Mesh { normal_scale: v, ..Mesh::default() }), "normal_scale");
|
||||
let t = TextureRef { transform: Some(MeshUv { rotation: v, ..MeshUv::default() }), ..TextureRef::default() };
|
||||
bad_value(try_from_mesh(&Mesh { emissive_texture: Some(t), ..Mesh::default() }), "emissive_texture transform");
|
||||
}
|
||||
// Emission above 1, a cutoff above 1 and a negative normal scale are in range.
|
||||
let wide = Mesh { emissive: [40.0; 3], alpha_mode: MeshAlpha::Mask(2.0), normal_scale: -1.0, ..Mesh::default() };
|
||||
let c = try_from_mesh(&wide).unwrap();
|
||||
assert_eq!((c.surface.emissive, c.surface.alpha_mode), ([40.0; 3], AlphaMode::Mask(2.0)));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ craft-materialx
|
||||
|
||||
fn mx(shader: Shader, inputs: &[(&str, Value)]) -> Mx {
|
||||
Mx {
|
||||
name: "M".into(),
|
||||
shader,
|
||||
inputs: inputs.iter().map(|(n, v)| ((*n).to_owned(), v.clone())).collect(),
|
||||
displacement: None,
|
||||
uv_tiling: [1.0, 1.0],
|
||||
warnings: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn k(values: &[f32]) -> Value {
|
||||
Value::Constant { values: values.to_vec(), colorspace: None }
|
||||
}
|
||||
|
||||
fn ks(values: &[f32], space: &str) -> Value {
|
||||
Value::Constant { values: values.to_vec(), colorspace: Some(space.into()) }
|
||||
}
|
||||
|
||||
fn img(file: &str, space: Option<&str>, tiling: Option<[f32; 2]>) -> Value {
|
||||
Value::Image { file: file.into(), colorspace: space.map(str::to_owned), uv_tiling: tiling }
|
||||
}
|
||||
|
||||
/// Schlick's reflectance at normal incidence for an index of refraction, as the specular weight
|
||||
/// of the core: `((n − 1) / (n + 1))² / 0.04`.
|
||||
fn specular_for_ior(n: f64) -> f32 {
|
||||
(((n - 1.0) / (n + 1.0)).powi(2) / 0.04) as f32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_empty_inputs_give_each_shaders_defaults() {
|
||||
// The defaults of the node definitions in MaterialX's libraries/bxdf: open_pbr_surface.mtlx,
|
||||
// standard_surface.mtlx (version 1.0.1) and gltf_pbr.mtlx
|
||||
// (https://github.com/AcademySoftwareFoundation/MaterialX/tree/main/libraries/bxdf).
|
||||
let open = try_from_materialx(&mx(Shader::OpenPbr, &[])).unwrap();
|
||||
let s = &open.surface;
|
||||
assert_close3(s.material.base_color(), [0.8; 3]);
|
||||
assert_eq!((s.material.metallic(), s.material.roughness(), s.material.specular()), (0.0, 0.3, 1.0));
|
||||
assert_eq!((s.alpha, s.alpha_mode, s.emissive), (1.0, AlphaMode::Opaque, [0.0; 3]));
|
||||
assert_eq!((s.clearcoat, s.sheen), (None, None));
|
||||
assert!(open.report.is_empty(), "{:?}", open.report);
|
||||
|
||||
let standard = try_from_materialx(&mx(Shader::StandardSurface, &[])).unwrap();
|
||||
let s = &standard.surface;
|
||||
assert_close3(s.material.base_color(), [0.8; 3]);
|
||||
assert_eq!((s.material.metallic(), s.material.roughness(), s.material.specular()), (0.0, 0.2, 1.0));
|
||||
assert_eq!((s.alpha, s.alpha_mode, s.emissive), (1.0, AlphaMode::Opaque, [0.0; 3]));
|
||||
assert_eq!((s.clearcoat, s.sheen), (None, None));
|
||||
assert!(standard.report.is_empty(), "{:?}", standard.report);
|
||||
|
||||
let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[])).unwrap();
|
||||
let s = &gltf.surface;
|
||||
assert_eq!(s.material.base_color(), [1.0; 3]);
|
||||
assert_eq!((s.material.metallic(), s.material.roughness(), s.material.specular()), (1.0, 1.0, 1.0));
|
||||
assert_eq!((s.alpha, s.alpha_mode, s.emissive), (1.0, AlphaMode::Opaque, [0.0; 3]));
|
||||
assert_eq!((s.clearcoat, s.sheen), (None, None));
|
||||
assert!(gltf.report.is_empty(), "{:?}", gltf.report);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_base_weight_scales_the_base_color_and_specular_follows_weight_and_ior() {
|
||||
let c =
|
||||
try_from_materialx(&mx(Shader::OpenPbr, &[("base_color", k(&[0.5, 0.4, 0.2])), ("base_weight", k(&[0.5])), ("base_metalness", k(&[0.25]))]))
|
||||
.unwrap();
|
||||
assert_close3(c.surface.material.base_color(), [0.25, 0.2, 0.1]);
|
||||
assert_eq!(c.surface.material.metallic(), 0.25);
|
||||
assert!(c.report.is_empty(), "{:?}", c.report);
|
||||
let standard = try_from_materialx(&mx(Shader::StandardSurface, &[("base", k(&[0.5])), ("specular", k(&[0.5]))])).unwrap();
|
||||
assert_close3(standard.surface.material.base_color(), [0.4; 3]);
|
||||
assert!(close(standard.surface.material.specular(), 0.5));
|
||||
assert!(approximated(&standard, "specular"));
|
||||
|
||||
let weight = try_from_materialx(&mx(Shader::OpenPbr, &[("specular_weight", k(&[2.0]))])).unwrap();
|
||||
assert!(close(weight.surface.material.specular(), 2.0));
|
||||
assert!(approximated(&weight, "specular_weight"));
|
||||
let water = try_from_materialx(&mx(Shader::OpenPbr, &[("specular_ior", k(&[1.33]))])).unwrap();
|
||||
assert!(close(water.surface.material.specular(), specular_for_ior(1.33)), "{}", water.surface.material.specular());
|
||||
let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[("ior", k(&[2.0])), ("specular", k(&[0.5]))])).unwrap();
|
||||
assert!(close(gltf.surface.material.specular(), 0.5 * specular_for_ior(2.0)));
|
||||
// 25 is the largest weight the core takes: at IOR 1.5 a weight of 25 fits, 25.5 does not.
|
||||
let max = try_from_materialx(&mx(Shader::OpenPbr, &[("specular_weight", k(&[25.0]))])).unwrap();
|
||||
assert!(close(max.surface.material.specular(), 25.0));
|
||||
bad_value(try_from_materialx(&mx(Shader::OpenPbr, &[("specular_weight", k(&[25.5]))])), "specular_weight");
|
||||
bad_value(try_from_materialx(&mx(Shader::OpenPbr, &[("specular_weight", k(&[2.0])), ("specular_ior", k(&[30.0]))])), "specular_weight");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_color_constants_are_decoded_from_the_color_space_in_effect() {
|
||||
let base = |v: Value| try_from_materialx(&mx(Shader::GltfPbr, &[("base_color", v)])).map(|c| c.surface.material.base_color());
|
||||
let c = [0.5, 0.2, 0.02];
|
||||
// The sRGB transfer function of IEC 61966-2-1, written out here independently.
|
||||
let srgb = |v: f32| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) };
|
||||
for space in ["srgb_texture", "srgb_rec709_scene"] {
|
||||
let got = base(ks(&c, space)).unwrap();
|
||||
assert_close3(got, c.map(srgb));
|
||||
assert_close3(got, c.map(craft_texture::srgb_to_linear));
|
||||
}
|
||||
for space in ["lin_rec709", "lin_rec709_scene", "data", "none"] {
|
||||
assert_eq!(base(ks(&c, space)).unwrap(), c, "{space}");
|
||||
}
|
||||
assert_eq!(base(k(&c)).unwrap(), c);
|
||||
assert_close3(base(ks(&c, "g22_rec709")).unwrap(), c.map(|v| v.powf(2.2)));
|
||||
assert_close3(base(ks(&c, "g18_rec709_scene")).unwrap(), c.map(|v| v.powf(1.8)));
|
||||
assert_close3(base(ks(&c, "g24_rec709_scene")).unwrap(), c.map(|v| v.powf(2.4)));
|
||||
for space in ["acescg", "lin_ap1_scene", "srgb_p3d65_scene", "bogus"] {
|
||||
match base(ks(&c, space)) {
|
||||
Err(ConvertError::ColorSpace { input, colorspace }) => assert_eq!((input.as_str(), colorspace.as_str()), ("base_color", space)),
|
||||
other => panic!("{space}: {other:?}"),
|
||||
}
|
||||
}
|
||||
// Scalars are never decoded, whatever the color space.
|
||||
let rough = try_from_materialx(&mx(Shader::GltfPbr, &[("roughness", ks(&[0.5], "srgb_texture"))])).unwrap();
|
||||
assert_eq!(rough.surface.material.roughness(), 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_images_become_bindings_and_the_core_holds_the_factor() {
|
||||
let m = mx(
|
||||
Shader::OpenPbr,
|
||||
&[
|
||||
("base_color", img("tex/albedo.png", Some("srgb_texture"), Some([2.0, 3.0]))),
|
||||
("base_weight", k(&[0.5])),
|
||||
("base_metalness", img("metal.png", Some("srgb_texture"), None)),
|
||||
("specular_roughness", img("rough.png", None, None)),
|
||||
("geometry_opacity", img("cut.png", None, None)),
|
||||
("geometry_normal", Value::NormalMap { file: "n.png".into(), colorspace: Some("lin_rec709".into()), uv_tiling: None }),
|
||||
("emission_color", img("glow.png", Some("acescg"), None)),
|
||||
("emission_luminance", k(&[4.0])),
|
||||
("specular_ior", img("ior.png", None, None)),
|
||||
],
|
||||
);
|
||||
let c = try_from_materialx(&m).unwrap();
|
||||
let s = &c.surface;
|
||||
assert_close3(s.material.base_color(), [0.5; 3]);
|
||||
assert_eq!((s.material.metallic(), s.material.roughness(), s.material.specular()), (1.0, 1.0, 1.0));
|
||||
assert_eq!((s.alpha, s.alpha_mode), (1.0, AlphaMode::Blend));
|
||||
assert_eq!(s.emissive, [4.0; 3]);
|
||||
let find = |input: TextureInput| s.textures.iter().find(|b| b.input == input).unwrap();
|
||||
let albedo = find(TextureInput::BaseColor);
|
||||
assert_eq!((&albedo.source, &albedo.encoding), (&TextureSource::File("tex/albedo.png".into()), &TextureEncoding::Srgb));
|
||||
assert_eq!(albedo.transform, Some(UvTransform { offset: [0.0; 2], rotation: 0.0, scale: [2.0, 3.0] }));
|
||||
assert_eq!((albedo.uv_set, albedo.wrap, albedo.scale), (0, [Wrap::Repeat; 2], 1.0));
|
||||
// Data inputs are linear whatever color space the file carries; color inputs keep theirs.
|
||||
assert_eq!(find(TextureInput::Metallic).encoding, TextureEncoding::Linear);
|
||||
assert_eq!(find(TextureInput::Roughness).encoding, TextureEncoding::Linear);
|
||||
assert_eq!(find(TextureInput::Normal).encoding, TextureEncoding::Linear);
|
||||
assert_eq!(find(TextureInput::Opacity).source, TextureSource::File("cut.png".into()));
|
||||
assert_eq!(find(TextureInput::Emissive).encoding, TextureEncoding::Named("acescg".into()));
|
||||
assert_eq!(find(TextureInput::Other("specular_ior".into())).source, TextureSource::File("ior.png".into()));
|
||||
for name in ["base_color", "base_metalness", "specular_roughness", "geometry_opacity", "geometry_normal", "emission_color", "specular_ior"] {
|
||||
assert!(unshaded(&c, name), "{name}");
|
||||
}
|
||||
assert!(approximated(&c, "specular_ior"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_coat_and_sheen_are_kept_only_when_they_are_on() {
|
||||
let c = try_from_materialx(&mx(
|
||||
Shader::OpenPbr,
|
||||
&[("coat_weight", k(&[0.5])), ("coat_roughness", k(&[0.2])), ("fuzz_weight", k(&[0.5])), ("fuzz_color", k(&[1.0, 0.5, 0.0]))],
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(c.surface.clearcoat, Some(Clearcoat { weight: 0.5, roughness: 0.2 }));
|
||||
// fuzz_roughness defaults to 0.5.
|
||||
assert_eq!(c.surface.sheen, Some(Sheen { color: [0.5, 0.25, 0.0], roughness: 0.5 }));
|
||||
assert!(approximated(&c, "fuzz_weight") && unshaded(&c, "clearcoat") && unshaded(&c, "sheen"));
|
||||
|
||||
let standard = try_from_materialx(&mx(Shader::StandardSurface, &[("coat", k(&[1.0])), ("sheen", k(&[0.5]))])).unwrap();
|
||||
// coat_roughness 0.1, sheen_color white and sheen_roughness 0.3 by default.
|
||||
assert_eq!(standard.surface.clearcoat, Some(Clearcoat { weight: 1.0, roughness: 0.1 }));
|
||||
assert_eq!(standard.surface.sheen, Some(Sheen { color: [0.5; 3], roughness: 0.3 }));
|
||||
|
||||
let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[("sheen_color", k(&[0.2, 0.1, 0.0])), ("sheen_roughness", k(&[0.4]))])).unwrap();
|
||||
assert_eq!(gltf.surface.sheen, Some(Sheen { color: [0.2, 0.1, 0.0], roughness: 0.4 }));
|
||||
assert!(!approximated(&gltf, "sheen_color"));
|
||||
|
||||
let off = try_from_materialx(&mx(
|
||||
Shader::OpenPbr,
|
||||
&[("coat_roughness", img("coat_r.png", None, None)), ("fuzz_color", img("fuzz.png", None, None)), ("coat_weight", k(&[0.0]))],
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!((off.surface.clearcoat, off.surface.sheen), (None, None));
|
||||
assert!(off.surface.textures.is_empty());
|
||||
assert!(dropped(&off, "coat_roughness") && dropped(&off, "fuzz_color"));
|
||||
let textured = try_from_materialx(&mx(Shader::OpenPbr, &[("coat_weight", img("coat.png", None, None))])).unwrap();
|
||||
assert_eq!(textured.surface.clearcoat, Some(Clearcoat { weight: 1.0, roughness: 0.0 }));
|
||||
assert_eq!(textured.surface.textures[0].input, TextureInput::Clearcoat);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_coat_and_sheen_roughness_images_read_their_first_channel() {
|
||||
let cases = [
|
||||
(Shader::OpenPbr, [("coat_weight", k(&[1.0])), ("fuzz_weight", k(&[1.0]))], ["coat_roughness", "fuzz_roughness"]),
|
||||
(Shader::StandardSurface, [("coat", k(&[1.0])), ("sheen", k(&[1.0]))], ["coat_roughness", "sheen_roughness"]),
|
||||
(Shader::GltfPbr, [("clearcoat", k(&[1.0])), ("sheen_color", k(&[1.0, 1.0, 1.0]))], ["clearcoat_roughness", "sheen_roughness"]),
|
||||
];
|
||||
for (shader, [coat, sheen], [coat_roughness, sheen_roughness]) in cases {
|
||||
let c = try_from_materialx(&mx(
|
||||
shader,
|
||||
&[coat, sheen, (coat_roughness, img("coat_r.png", None, None)), (sheen_roughness, img("sheen_r.png", None, None))],
|
||||
))
|
||||
.unwrap();
|
||||
let inputs: Vec<_> = c.surface.textures.iter().map(|t| (t.input.clone(), t.source.clone())).collect();
|
||||
assert_eq!(
|
||||
inputs,
|
||||
[
|
||||
(TextureInput::ClearcoatRoughnessFirst, TextureSource::File("coat_r.png".into())),
|
||||
(TextureInput::SheenRoughnessFirst, TextureSource::File("sheen_r.png".into())),
|
||||
],
|
||||
"{shader:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_coat_only_inputs_are_dropped_while_the_coat_is_off() {
|
||||
let coat_only = [
|
||||
(Shader::OpenPbr, "coat_weight", ["geometry_coat_normal", "coat_color", "coat_ior"]),
|
||||
(Shader::StandardSurface, "coat", ["coat_normal", "coat_color", "coat_IOR"]),
|
||||
];
|
||||
for (shader, weight, [normal, color, ior]) in coat_only {
|
||||
let inputs = [
|
||||
(normal, Value::NormalMap { file: "coat_n.png".into(), colorspace: None, uv_tiling: None }),
|
||||
(color, img("coat_c.png", None, None)),
|
||||
(ior, k(&[1.4])),
|
||||
];
|
||||
// The coat weight is left at its default of 0.
|
||||
let off = try_from_materialx(&mx(shader, &inputs)).unwrap();
|
||||
assert_eq!(off.surface.clearcoat, None);
|
||||
assert!(off.surface.textures.is_empty(), "{:?}", off.surface.textures);
|
||||
assert!(off.surface.other_inputs.is_empty(), "{:?}", off.surface.other_inputs);
|
||||
for name in [normal, color, ior] {
|
||||
assert!(dropped(&off, name) && !unshaded(&off, name), "{name}: {:?}", off.report);
|
||||
}
|
||||
// With the coat on, the same inputs are kept and reported as unshaded.
|
||||
let mut with_coat = inputs.to_vec();
|
||||
with_coat.push((weight, k(&[0.5])));
|
||||
let on = try_from_materialx(&mx(shader, &with_coat)).unwrap();
|
||||
assert!(on.surface.clearcoat.is_some());
|
||||
assert_eq!(on.surface.textures.len(), 2);
|
||||
assert_eq!(on.surface.other_inputs, vec![(ior.to_owned(), vec![1.4])]);
|
||||
for name in [normal, color, ior] {
|
||||
assert!(unshaded(&on, name) && !dropped(&on, name), "{name}");
|
||||
}
|
||||
}
|
||||
let gltf = try_from_materialx(&mx(
|
||||
Shader::GltfPbr,
|
||||
&[("clearcoat_normal", Value::NormalMap { file: "cc_n.png".into(), colorspace: None, uv_tiling: None })],
|
||||
))
|
||||
.unwrap();
|
||||
assert!(gltf.surface.textures.is_empty() && dropped(&gltf, "clearcoat_normal"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_constants_of_a_layer_that_is_off_are_dropped() {
|
||||
// The coat weight defaults to 0, so the coat is off and its roughness is dropped.
|
||||
let coat = try_from_materialx(&mx(Shader::OpenPbr, &[("coat_roughness", k(&[0.4]))])).unwrap();
|
||||
assert_eq!(coat.surface.clearcoat, None);
|
||||
assert!(dropped(&coat, "coat_roughness"), "{:?}", coat.report);
|
||||
// The weight that turns the layer off is not reported as dropped.
|
||||
let zero = try_from_materialx(&mx(Shader::OpenPbr, &[("coat_weight", k(&[0.0])), ("coat_roughness", k(&[0.4]))])).unwrap();
|
||||
assert!(dropped(&zero, "coat_roughness") && !dropped(&zero, "coat_weight"), "{:?}", zero.report);
|
||||
let on = try_from_materialx(&mx(Shader::OpenPbr, &[("coat_weight", k(&[0.5])), ("coat_roughness", k(&[0.4]))])).unwrap();
|
||||
assert!(!dropped(&on, "coat_roughness"));
|
||||
// fuzz_weight defaults to 0: the fuzz color and roughness are dropped.
|
||||
let fuzz = try_from_materialx(&mx(Shader::OpenPbr, &[("fuzz_color", k(&[1.0, 0.5, 0.0])), ("fuzz_roughness", k(&[0.2]))])).unwrap();
|
||||
assert!(dropped(&fuzz, "fuzz_color") && dropped(&fuzz, "fuzz_roughness"), "{:?}", fuzz.report);
|
||||
// A black color turns the sheen off, so its weight is dropped and the color is not.
|
||||
let black = try_from_materialx(&mx(Shader::StandardSurface, &[("sheen", k(&[0.5])), ("sheen_color", k(&[0.0; 3]))])).unwrap();
|
||||
assert!(dropped(&black, "sheen") && !dropped(&black, "sheen_color"), "{:?}", black.report);
|
||||
let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[("sheen_roughness", k(&[0.3]))])).unwrap();
|
||||
assert!(dropped(&gltf, "sheen_roughness"), "{:?}", gltf.report);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_emission_is_the_color_times_its_strength() {
|
||||
let dark = try_from_materialx(&mx(Shader::OpenPbr, &[("emission_color", k(&[1.0, 0.5, 0.0]))])).unwrap();
|
||||
assert_eq!(dark.surface.emissive, [0.0; 3]);
|
||||
assert!(dropped(&dark, "emission_color"), "{:?}", dark.report);
|
||||
let lit = try_from_materialx(&mx(Shader::OpenPbr, &[("emission_color", k(&[1.0, 0.5, 0.0])), ("emission_luminance", k(&[10.0]))])).unwrap();
|
||||
assert_eq!(lit.surface.emissive, [10.0, 5.0, 0.0]);
|
||||
assert!(approximated(&lit, "emission_luminance"));
|
||||
let standard = try_from_materialx(&mx(Shader::StandardSurface, &[("emission", k(&[2.0])), ("emission_color", k(&[0.5, 0.25, 1.0]))])).unwrap();
|
||||
assert_eq!(standard.surface.emissive, [1.0, 0.5, 2.0]);
|
||||
assert!(standard.report.is_empty());
|
||||
let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[("emissive", k(&[0.5, 0.25, 0.0])), ("emissive_strength", k(&[2.0]))])).unwrap();
|
||||
assert_eq!(gltf.surface.emissive, [1.0, 0.5, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_standard_surface_opacity_color_gives_its_luminance() {
|
||||
let standard = |opacity: &[f32]| try_from_materialx(&mx(Shader::StandardSurface, &[("opacity", k(opacity))]));
|
||||
let gray = standard(&[0.5; 3]).unwrap();
|
||||
assert_eq!(gray.surface.alpha, 0.5);
|
||||
assert!(gray.report.is_empty(), "{:?}", gray.report);
|
||||
// 0.2126 * 0.2 + 0.7152 * 0.4 + 0.0722 * 0.6, the Rec.709 luminance; the mean would be 0.4.
|
||||
let colored = standard(&[0.2, 0.4, 0.6]).unwrap();
|
||||
assert!(close(colored.surface.alpha, 0.37192), "{}", colored.surface.alpha);
|
||||
assert_eq!(colored.surface.alpha_mode, AlphaMode::Blend);
|
||||
assert!(approximated(&colored, "opacity"));
|
||||
let green = standard(&[0.0, 1.0, 0.0]).unwrap();
|
||||
assert!(close(green.surface.alpha, 0.7152), "{}", green.surface.alpha);
|
||||
let near_white = standard(&[1.0, 1.0, 0.999_999_9]).unwrap();
|
||||
assert!(near_white.surface.alpha <= 1.0 && near_white.surface.alpha >= 0.999_999_9);
|
||||
for v in [f32::NAN, f32::INFINITY, -0.01, 1.01] {
|
||||
bad_value(standard(&[0.5, v, 0.5]), "opacity");
|
||||
}
|
||||
// An image on the color opacity binds as RGB; the float opacities bind their first channel.
|
||||
let textured = try_from_materialx(&mx(Shader::StandardSurface, &[("opacity", img("o.png", None, None))])).unwrap();
|
||||
assert_eq!(textured.surface.textures[0].input, TextureInput::OpacityRgb);
|
||||
for (shader, name) in [(Shader::OpenPbr, "geometry_opacity"), (Shader::GltfPbr, "alpha")] {
|
||||
let c = try_from_materialx(&mx(shader, &[(name, img("o.png", None, None))])).unwrap();
|
||||
assert_eq!(c.surface.textures[0].input, TextureInput::Opacity, "{name}");
|
||||
}
|
||||
// OpenPBR's geometry_opacity is a float in its node definition.
|
||||
assert_eq!(
|
||||
try_from_materialx(&mx(Shader::OpenPbr, &[("geometry_opacity", k(&[0.5; 3]))])).unwrap_err(),
|
||||
ConvertError::Components { input: "geometry_opacity".into(), expected: 1, found: 3 }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_alpha_and_its_mode() {
|
||||
let open = try_from_materialx(&mx(Shader::OpenPbr, &[("geometry_opacity", k(&[0.5]))])).unwrap();
|
||||
assert_eq!((open.surface.alpha, open.surface.alpha_mode), (0.5, AlphaMode::Blend));
|
||||
|
||||
let gltf = |inputs: &[(&str, Value)]| try_from_materialx(&mx(Shader::GltfPbr, inputs));
|
||||
assert_eq!(gltf(&[("alpha_mode", k(&[1.0])), ("alpha_cutoff", k(&[0.25]))]).unwrap().surface.alpha_mode, AlphaMode::Mask(0.25));
|
||||
assert_eq!(gltf(&[("alpha_mode", k(&[1.0]))]).unwrap().surface.alpha_mode, AlphaMode::Mask(0.5));
|
||||
assert_eq!(gltf(&[("alpha_mode", k(&[2.0]))]).unwrap().surface.alpha_mode, AlphaMode::Blend);
|
||||
let opaque = gltf(&[("alpha", k(&[0.5]))]).unwrap();
|
||||
assert_eq!((opaque.surface.alpha, opaque.surface.alpha_mode), (0.5, AlphaMode::Opaque));
|
||||
for bad in [3.0, 1.5, -1.0] {
|
||||
bad_value(gltf(&[("alpha_mode", k(&[bad]))]), "alpha_mode");
|
||||
}
|
||||
bad_value(gltf(&[("alpha_mode", img("m.png", None, None))]), "alpha_mode");
|
||||
bad_value(gltf(&[("alpha_cutoff", img("c.png", None, None))]), "alpha_cutoff");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_bad_inputs_are_errors_and_unknown_ones_are_dropped() {
|
||||
let open = |inputs: &[(&str, Value)]| try_from_materialx(&mx(Shader::OpenPbr, inputs));
|
||||
assert_eq!(open(&[("base_metalness", k(&[0.0])), ("base_metalness", k(&[1.0]))]).unwrap_err(), ConvertError::Duplicate("base_metalness".into()));
|
||||
assert_eq!(open(&[("base_color", k(&[0.5]))]).unwrap_err(), ConvertError::Components { input: "base_color".into(), expected: 3, found: 1 });
|
||||
assert_eq!(
|
||||
open(&[("base_metalness", k(&[0.5; 3]))]).unwrap_err(),
|
||||
ConvertError::Components { input: "base_metalness".into(), expected: 1, found: 3 }
|
||||
);
|
||||
for v in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.01, 1.01] {
|
||||
for name in
|
||||
["base_weight", "base_metalness", "specular_roughness", "coat_weight", "fuzz_roughness", "geometry_opacity", "transmission_weight"]
|
||||
{
|
||||
bad_value(open(&[(name, k(&[v]))]), name);
|
||||
}
|
||||
bad_value(open(&[("base_color", k(&[0.5, v, 0.5]))]), "base_color");
|
||||
}
|
||||
for v in [f32::NAN, f32::INFINITY, -1.0] {
|
||||
bad_value(open(&[("emission_luminance", k(&[v]))]), "emission_luminance");
|
||||
bad_value(open(&[("specular_ior", k(&[v]))]), "specular_ior");
|
||||
bad_value(open(&[("geometry_normal", k(&[0.0, 0.0, if v < 0.0 { f32::NAN } else { v }]))]), "geometry_normal");
|
||||
}
|
||||
bad_value(try_from_materialx(&mx(Shader::GltfPbr, &[("ior", k(&[0.9]))])), "ior");
|
||||
// glTF PBR's specular_color has no upper bound, so a large encoded value overflows to
|
||||
// infinity when it is decoded to linear; that is an error, not an infinite input.
|
||||
for space in ["g22_rec709", "srgb_texture", "srgb_rec709_scene", "g24_rec709_scene"] {
|
||||
bad_value(try_from_materialx(&mx(Shader::GltfPbr, &[("specular_color", ks(&[1e20, 1.0, 1.0], space))])), "specular_color");
|
||||
}
|
||||
let wide = try_from_materialx(&mx(Shader::GltfPbr, &[("specular_color", ks(&[4.0, 1.0, 1.0], "g22_rec709"))])).unwrap();
|
||||
assert_eq!(wide.surface.other_inputs.len(), 1);
|
||||
assert!(close(wide.surface.other_inputs[0].1[0], 4f32.powf(2.2)));
|
||||
bad_value(open(&[("base_color", img("a.png", None, Some([0.0, 1.0])))]), "base_color");
|
||||
bad_value(open(&[("base_color", img("a.png", None, Some([f32::NAN, 1.0])))]), "base_color");
|
||||
let unknown = open(&[("thin_film_weight", k(&[0.5])), ("not_an_input", img("x.png", None, None))]).unwrap();
|
||||
assert!(dropped(&unknown, "thin_film_weight") && dropped(&unknown, "not_an_input"));
|
||||
assert!(unknown.surface.textures.is_empty() && unknown.surface.other_inputs.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_other_inputs_and_the_displacement_are_kept() {
|
||||
let mut m = mx(
|
||||
Shader::OpenPbr,
|
||||
&[
|
||||
("specular_color", ks(&[1.0, 0.5, 0.5], "srgb_texture")),
|
||||
("transmission_weight", k(&[0.5])),
|
||||
("subsurface_weight", img("sss.png", None, None)),
|
||||
],
|
||||
);
|
||||
m.displacement = Some(k(&[0.25]));
|
||||
let c = try_from_materialx(&m).unwrap();
|
||||
let srgb_half = craft_texture::srgb_to_linear(0.5);
|
||||
assert_eq!(
|
||||
c.surface.other_inputs,
|
||||
vec![
|
||||
("specular_color".into(), vec![1.0, srgb_half, srgb_half]),
|
||||
("transmission_weight".into(), vec![0.5]),
|
||||
("displacement".into(), vec![0.25])
|
||||
]
|
||||
);
|
||||
assert_eq!(c.surface.textures[0].input, TextureInput::Other("subsurface_weight".into()));
|
||||
for name in ["specular_color", "transmission_weight", "subsurface_weight", "displacement"] {
|
||||
assert!(unshaded(&c, name), "{name}");
|
||||
}
|
||||
m.displacement = Some(img("h.png", Some("srgb_texture"), Some([4.0, 4.0])));
|
||||
let c = try_from_materialx(&m).unwrap();
|
||||
let h = c.surface.textures.iter().find(|b| b.input == TextureInput::Displacement).unwrap();
|
||||
assert_eq!((&h.source, &h.encoding), (&TextureSource::File("h.png".into()), &TextureEncoding::Linear));
|
||||
assert_eq!(h.transform.map(|t| t.scale), Some([4.0, 4.0]));
|
||||
m.displacement = Some(k(&[f32::NAN]));
|
||||
bad_value(try_from_materialx(&m), "displacement");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_reader_warnings_reach_the_report() {
|
||||
let mut m = mx(Shader::OpenPbr, &[]);
|
||||
m.warnings = vec!["input thin_film_weight is not read".into()];
|
||||
let c = try_from_materialx(&m).unwrap();
|
||||
assert_eq!(c.report.items, vec![ReportItem::Warning("input thin_film_weight is not read".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_float_converted_to_a_color_is_not_decoded_from_the_nodes_color_space() {
|
||||
// The float is not a color value, so the node's srgb_texture does not apply to it.
|
||||
let doc = Document::parse(
|
||||
br#"<materialx colorspace="lin_rec709">
|
||||
<open_pbr_surface name="S"><input name="base_color" nodename="C"/></open_pbr_surface>
|
||||
<convert name="C" type="color3" colorspace="srgb_texture"><input name="in" type="float" value="0.5"/></convert>
|
||||
<surfacematerial name="M"><input name="surfaceshader" nodename="S"/></surfacematerial>
|
||||
</materialx>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let c = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_close3(c.surface.material.base_color(), [0.5; 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_documents_convert_from_xml() {
|
||||
let doc = Document::parse(
|
||||
br#"<materialx colorspace="srgb_texture">
|
||||
<gltf_pbr name="S">
|
||||
<input name="base_color" type="color3" value="0.5, 0.5, 0.5"/>
|
||||
<input name="emissive" type="color3" value="1, 0, 0" colorspace="lin_rec709"/>
|
||||
<input name="emissive_strength" type="float" value="3"/>
|
||||
<input name="iridescence" type="float" value="0.5"/>
|
||||
</gltf_pbr>
|
||||
<surfacematerial name="Red"><input name="surfaceshader" nodename="S"/></surfacematerial>
|
||||
</materialx>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let c = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_eq!(c.surface.name, "Red");
|
||||
assert_close3(c.surface.material.base_color(), [craft_texture::srgb_to_linear(0.5); 3]);
|
||||
assert_eq!(c.surface.emissive, [3.0, 0.0, 0.0]);
|
||||
assert_eq!(c.report.items, vec![ReportItem::Warning("input iridescence is not read".into())]);
|
||||
|
||||
// craft-materialx's OpenPBR writer and this conversion agree on every texture it writes.
|
||||
let textures = [
|
||||
Texture { input: "base_color".into(), file: "albedo.png".into(), colorspace: "srgb_texture".into() },
|
||||
Texture { input: "specular_roughness".into(), file: "rough.png".into(), colorspace: "srgb_texture".into() },
|
||||
Texture { input: "geometry_normal".into(), file: "normal.png".into(), colorspace: "lin_rec709".into() },
|
||||
Texture { input: "emission_color".into(), file: "glow.png".into(), colorspace: "lin_rec709".into() },
|
||||
Texture { input: "height".into(), file: "height.png".into(), colorspace: "lin_rec709".into() },
|
||||
];
|
||||
let written = Document::parse(write_open_pbr("Stone", &textures, None).as_bytes()).unwrap();
|
||||
let c = try_from_materialx(&written.read_material_strict(None).unwrap()).unwrap();
|
||||
let s = &c.surface;
|
||||
let by = |input: TextureInput| s.textures.iter().find(|b| b.input == input).map(|b| (b.source.clone(), b.encoding.clone()));
|
||||
assert_eq!(by(TextureInput::BaseColor), Some((TextureSource::File("albedo.png".into()), TextureEncoding::Srgb)));
|
||||
assert_eq!(by(TextureInput::Roughness), Some((TextureSource::File("rough.png".into()), TextureEncoding::Linear)));
|
||||
assert_eq!(by(TextureInput::Normal), Some((TextureSource::File("normal.png".into()), TextureEncoding::Linear)));
|
||||
assert_eq!(by(TextureInput::Emissive), Some((TextureSource::File("glow.png".into()), TextureEncoding::Linear)));
|
||||
assert_eq!(by(TextureInput::Displacement), Some((TextureSource::File("height.png".into()), TextureEncoding::Linear)));
|
||||
// The writer sets emission_luminance to 1 with an emission texture, so the texture shows.
|
||||
assert_eq!(s.emissive, [1.0; 3]);
|
||||
assert_eq!(s.name, "Stone");
|
||||
}
|
||||
@@ -5,6 +5,9 @@
|
||||
mod bench;
|
||||
mod bounds;
|
||||
mod brdf;
|
||||
mod conversion_edges;
|
||||
mod conversion_followups;
|
||||
mod convert;
|
||||
mod differential;
|
||||
mod moved;
|
||||
mod numeric;
|
||||
|
||||
Generated
-2
@@ -103,8 +103,6 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69374b3668dd45aeb3d3145cda68f2c7b4f223aaa2511e67d076f1c7d741388d"
|
||||
dependencies = [
|
||||
"hayro-ccitt",
|
||||
]
|
||||
|
||||
@@ -611,7 +611,8 @@ fn renderer_operators(data: &[u8]) -> Vec<Vec<u8>> {
|
||||
let mut iter = hayro_syntax::content::UntypedIter::new(data);
|
||||
let mut out = Vec::new();
|
||||
while let Some(instruction) = iter.next() {
|
||||
out.push(instruction.operator.as_ref().to_vec());
|
||||
let operator: &[u8] = instruction.operator.as_ref();
|
||||
out.push(operator.to_vec());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -30,6 +30,13 @@ use super::{BlendMode, DisplayList, FillItem, FillRule, GroupItem, Item, Paint};
|
||||
use crate::ink::{InkColor, InkId, InkSet, Overprint, Process};
|
||||
|
||||
/// How [`flatten`] cuts transparent art.
|
||||
///
|
||||
/// `FlattenOptions` can be initialized with its three fields:
|
||||
///
|
||||
/// ```
|
||||
/// use craft_prepress::flatten::FlattenOptions;
|
||||
/// let options = FlattenOptions { sliver: 0.01, max_regions: 5000, raster_dpi: 300.0 };
|
||||
/// ```
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct FlattenOptions {
|
||||
/// Regions narrower than this (in points) are dropped ([`geom::regions_with`]).
|
||||
@@ -48,6 +55,27 @@ impl Default for FlattenOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// These limits bound each region sweep used by [`flatten_with_limits`]. The PDF entry points
|
||||
/// with explicit limits also apply them to each even-odd path rebuild during page reading.
|
||||
/// A stopped rebuild retains the original path and fill rule.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct FlattenSweepLimits {
|
||||
/// The region sweep of one group stops after this many work units. The group then goes to
|
||||
/// [`Flattened::complex`] whole as [`ComplexReason::Degenerate`]. The default is
|
||||
/// [`geom::DEFAULT_MAX_SWEEP_WORK`].
|
||||
pub max_sweep_work: u64,
|
||||
/// The region sweep of one group stops before holding more than this many output units.
|
||||
/// The group then goes to [`Flattened::complex`] whole as [`ComplexReason::Degenerate`].
|
||||
/// The default is [`geom::DEFAULT_MAX_TOPOLOGY_UNITS`].
|
||||
pub max_sweep_units: usize,
|
||||
}
|
||||
|
||||
impl Default for FlattenSweepLimits {
|
||||
fn default() -> Self {
|
||||
Self { max_sweep_work: geom::DEFAULT_MAX_SWEEP_WORK, max_sweep_units: geom::DEFAULT_MAX_TOPOLOGY_UNITS }
|
||||
}
|
||||
}
|
||||
|
||||
/// A page with no transparency left.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Flattened {
|
||||
@@ -132,6 +160,11 @@ pub enum FlattenError {
|
||||
/// an item that does come back unchanged, and so do opaque items with no transparency painted
|
||||
/// above them where they paint.
|
||||
pub fn flatten(list: &DisplayList, opts: &FlattenOptions) -> Result<Flattened, FlattenError> {
|
||||
flatten_with_limits(list, opts, &FlattenSweepLimits::default())
|
||||
}
|
||||
|
||||
/// `flatten_with_limits` flattens `list` using `opts` and the region sweep `limits`.
|
||||
pub fn flatten_with_limits(list: &DisplayList, opts: &FlattenOptions, limits: &FlattenSweepLimits) -> Result<Flattened, FlattenError> {
|
||||
let nan = Rect::new(f64::NAN, f64::NAN, f64::NAN, f64::NAN);
|
||||
let bounds: Vec<Rect> = list.items.iter().map(|i| bounds(i).unwrap_or(nan)).collect();
|
||||
let transparent: Vec<bool> = list.items.iter().map(is_transparent).collect();
|
||||
@@ -165,7 +198,7 @@ pub fn flatten(list: &DisplayList, opts: &FlattenOptions) -> Result<Flattened, F
|
||||
out.report.kept += 1;
|
||||
}
|
||||
Plan::Drop => {}
|
||||
Plan::Emit(g) => flatten_group(list, &members[g], &bounds, &transparent, opts, &mut out)?,
|
||||
Plan::Emit(g) => flatten_group(list, &members[g], &bounds, &transparent, opts, limits, &mut out)?,
|
||||
}
|
||||
}
|
||||
out.report.complex_regions = out.complex.len();
|
||||
@@ -178,6 +211,7 @@ fn flatten_group(
|
||||
bounds: &[Rect],
|
||||
transparent: &[bool],
|
||||
opts: &FlattenOptions,
|
||||
limits: &FlattenSweepLimits,
|
||||
out: &mut Flattened,
|
||||
) -> Result<(), FlattenError> {
|
||||
let mut b = Builder::new(&list.inks);
|
||||
@@ -206,7 +240,7 @@ fn flatten_group(
|
||||
out.report.flattened += members.len();
|
||||
return Ok(());
|
||||
}
|
||||
let regions = match geom::regions_with(&b.shapes, &b.clips, opts.sliver) {
|
||||
let regions = match geom::regions_with_limits(&b.shapes, &b.clips, opts.sliver, limits.max_sweep_work, limits.max_sweep_units) {
|
||||
Ok(r) => r,
|
||||
Err(GeomError::Degenerate) => {
|
||||
// Each member's box is clear of every other group's items.
|
||||
@@ -1046,4 +1080,24 @@ mod tests {
|
||||
let l = list(InkSet::new(), vec![Item::Group(group(0.5, BlendMode::Normal, vec![crowded]))]);
|
||||
assert!(flatten(&l, &FlattenOptions::default()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sweep_limits_send_the_group_to_complex() {
|
||||
let l = list(
|
||||
InkSet::new(),
|
||||
vec![
|
||||
solid(Rect::new(0.0, 0.0, 100.0, 100.0), &[(M, 1.0)]),
|
||||
Item::Group(group(0.5, BlendMode::Normal, vec![solid(Rect::new(50.0, 0.0, 150.0, 100.0), &[(C, 1.0)])])),
|
||||
],
|
||||
);
|
||||
assert!(flat(&l).report.complex_groups.is_empty());
|
||||
|
||||
for limits in [
|
||||
FlattenSweepLimits { max_sweep_work: 1, ..FlattenSweepLimits::default() },
|
||||
FlattenSweepLimits { max_sweep_units: 1, ..FlattenSweepLimits::default() },
|
||||
] {
|
||||
let f = flatten_with_limits(&l, &FlattenOptions::default(), &limits).unwrap();
|
||||
assert_eq!(f.report.complex_groups, [ComplexGroup { items: vec![0, 1], reason: ComplexReason::Degenerate }], "{limits:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,7 @@ use kurbo::Rect;
|
||||
use super::pdf::{ReadColor, ReadError, ReadOptions, read_color, read_page_in};
|
||||
use super::raster::{FlattenPageReport, Rasterizer};
|
||||
use super::write::{FontMap, WriteError, write_flattened_with_fonts};
|
||||
use super::{DisplayList, FlattenError, FlattenOptions, flatten};
|
||||
use super::{DisplayList, FlattenError, FlattenOptions, FlattenSweepLimits, flatten_with_limits};
|
||||
use crate::cms::CmsConversion;
|
||||
use crate::plates::{self, Fallback, pdf_text};
|
||||
|
||||
@@ -175,7 +175,16 @@ pub enum FlattenDocumentError {
|
||||
/// `pdf` with the transparency of every page in [`FlattenDocumentOptions::pages`] flattened, as
|
||||
/// one PDF. See the module docs for what carries over.
|
||||
pub fn flatten_document(pdf: &[u8], opts: &FlattenDocumentOptions) -> Result<(Vec<u8>, FlattenDocumentReport), FlattenDocumentError> {
|
||||
flatten_document_with_progress(pdf, opts, &mut |_, _| {})
|
||||
flatten_document_with_limits(pdf, opts, &FlattenSweepLimits::default())
|
||||
}
|
||||
|
||||
/// [`flatten_document`] with explicit sweep work and output limits.
|
||||
pub fn flatten_document_with_limits(
|
||||
pdf: &[u8],
|
||||
opts: &FlattenDocumentOptions,
|
||||
limits: &FlattenSweepLimits,
|
||||
) -> Result<(Vec<u8>, FlattenDocumentReport), FlattenDocumentError> {
|
||||
flatten_document_with_limits_and_progress(pdf, opts, limits, &mut |_, _| {})
|
||||
}
|
||||
|
||||
/// [`flatten_document`], calling `progress(done, total)` after each page.
|
||||
@@ -183,6 +192,16 @@ pub fn flatten_document_with_progress(
|
||||
pdf: &[u8],
|
||||
opts: &FlattenDocumentOptions,
|
||||
progress: &mut dyn FnMut(usize, usize),
|
||||
) -> Result<(Vec<u8>, FlattenDocumentReport), FlattenDocumentError> {
|
||||
flatten_document_with_limits_and_progress(pdf, opts, &FlattenSweepLimits::default(), progress)
|
||||
}
|
||||
|
||||
/// [`flatten_document_with_limits`], calling `progress(done, total)` after each page.
|
||||
pub fn flatten_document_with_limits_and_progress(
|
||||
pdf: &[u8],
|
||||
opts: &FlattenDocumentOptions,
|
||||
limits: &FlattenSweepLimits,
|
||||
progress: &mut dyn FnMut(usize, usize),
|
||||
) -> Result<(Vec<u8>, FlattenDocumentReport), FlattenDocumentError> {
|
||||
let doc = Arc::new(open_slice(pdf, None)?);
|
||||
let count = doc.pages().len();
|
||||
@@ -213,9 +232,9 @@ pub fn flatten_document_with_progress(
|
||||
report.other_intents.push(page);
|
||||
}
|
||||
let p = doc.pages().get(page).ok_or(FlattenDocumentError::Read { page, source: ReadError::NoPage(page) })?;
|
||||
match read_page_in(&doc, page, &opts.read, color.read.clone()) {
|
||||
match read_page_in(&doc, page, &opts.read, color.read.clone(), limits) {
|
||||
Ok((list, read)) => {
|
||||
let flat = flatten(&list, &opts.flatten).map_err(|source| FlattenDocumentError::Flatten { page, source })?;
|
||||
let flat = flatten_with_limits(&list, &opts.flatten, limits).map_err(|source| FlattenDocumentError::Flatten { page, source })?;
|
||||
let mut raster = Rasterizer::new(&list, color.settings.clone(), color.condition.clone(), &color.cms, opts.flatten.raster_dpi);
|
||||
let at = |source| FlattenDocumentError::Write { page, source };
|
||||
let settings = page_settings(p, list.page).ok_or(at(WriteError::Page))?;
|
||||
|
||||
@@ -21,6 +21,19 @@ use linesweeper::topology::{ContourIdx, Contours, Topology, WindingNumber};
|
||||
/// numerical debris, such as the lens between two nearly coincident curves.
|
||||
pub const DEFAULT_SLIVER: f64 = 0.01;
|
||||
|
||||
/// The default for the most work the sweep may do, counted as segment comparisons plus segment
|
||||
/// position checks plus one unit for every 16 segments a search of the sweep line passes or probes
|
||||
/// plus the horizontal segments each step of a sweep line visits,
|
||||
/// before the shapes count as too degenerate to sweep. Stacked copies of a shape can need billions
|
||||
/// of comparisons; a release build makes about 17 million a second.
|
||||
pub const DEFAULT_MAX_SWEEP_WORK: u64 = 100_000_000;
|
||||
|
||||
/// The default for the most output the sweep's topology may hold before the shapes count as too
|
||||
/// degenerate to sweep, in units: each output segment takes one unit plus one for each entry of its
|
||||
/// two winding numbers (at least one each), so 2,000,000 segments with single-entry windings fill
|
||||
/// it. Each segment's windings can hold an entry for every shape that covers it.
|
||||
pub const DEFAULT_MAX_TOPOLOGY_UNITS: usize = 6_000_000;
|
||||
|
||||
/// How a path's winding number decides what is inside it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum FillRule {
|
||||
@@ -125,10 +138,17 @@ pub fn regions(shapes: &[Shape], clips: &[ClipPath]) -> Result<Vec<Region>, Geom
|
||||
|
||||
/// [`regions`] with contours narrower than `sliver` dropped.
|
||||
pub fn regions_with(shapes: &[Shape], clips: &[ClipPath], sliver: f64) -> Result<Vec<Region>, GeomError> {
|
||||
regions_with_limits(shapes, clips, sliver, DEFAULT_MAX_SWEEP_WORK, DEFAULT_MAX_TOPOLOGY_UNITS)
|
||||
}
|
||||
|
||||
/// [`regions_with`] with the sweep stopped, as [`GeomError::Degenerate`], once it passes
|
||||
/// `max_work` units of work or its topology passes `max_units` units of output (see
|
||||
/// [`DEFAULT_MAX_SWEEP_WORK`] and [`DEFAULT_MAX_TOPOLOGY_UNITS`] for the units).
|
||||
pub fn regions_with_limits(shapes: &[Shape], clips: &[ClipPath], sliver: f64, max_work: u64, max_units: usize) -> Result<Vec<Region>, GeomError> {
|
||||
if shapes.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
Ok(Arrangement::new(shapes, clips, sliver)?.regions())
|
||||
Arrangement::new(shapes, clips, sliver, max_work, max_units)?.regions()
|
||||
}
|
||||
|
||||
/// The finiteness check [`regions_with`] makes: every point of every shape path and of every clip
|
||||
@@ -268,6 +288,9 @@ impl WindingNumber for Multi {
|
||||
let w = self.get(tag);
|
||||
Multi(Arc::new(if w == 0 { vec![] } else { vec![(tag, w)] }))
|
||||
}
|
||||
fn storage_units(&self) -> usize {
|
||||
self.0.len().max(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// The sweep of shapes and clips. Tags `0..n` are shapes, `n + c` is clip `c`.
|
||||
@@ -281,7 +304,7 @@ struct Arrangement {
|
||||
}
|
||||
|
||||
impl Arrangement {
|
||||
fn new(shapes: &[Shape], clips: &[ClipPath], sliver: f64) -> Result<Self, GeomError> {
|
||||
fn new(shapes: &[Shape], clips: &[ClipPath], sliver: f64, work_limit: u64, output_limit: usize) -> Result<Self, GeomError> {
|
||||
let n = shapes.len();
|
||||
let mut used = vec![false; clips.len()];
|
||||
let mut shape_clips = Vec::with_capacity(n);
|
||||
@@ -304,8 +327,11 @@ impl Arrangement {
|
||||
let eps = eps_for(paths.iter().map(|p| &p.0))?;
|
||||
snap_horizontals(&mut paths.iter_mut().map(|p| &mut p.0).collect::<Vec<_>>(), eps);
|
||||
// The sweep can panic on rare near-degenerate input; the flattener then rasterizes.
|
||||
let sweep = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Topology::<Multi>::from_paths(paths.iter().map(|(p, t)| (p, *t)), eps)));
|
||||
// Every subpath is closed, so a path error is a degenerate input too.
|
||||
let sweep = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
Topology::<Multi>::from_paths_with_limits(paths.iter().map(|(p, t)| (p, *t)), eps, work_limit, output_limit)
|
||||
}));
|
||||
// Every subpath is closed, so a path error or a sweep past its work or output limit is a
|
||||
// degenerate input too.
|
||||
let top = sweep.map_err(|_| GeomError::Degenerate)?.map_err(|_| GeomError::Degenerate)?;
|
||||
let rules = shapes.iter().map(|s| s.rule).chain(clips.iter().map(|c| c.rule)).collect();
|
||||
let tidy = Tidy::keeping(sliver, paths.iter().map(|p| &p.0));
|
||||
@@ -324,7 +350,7 @@ impl Arrangement {
|
||||
/// sets × edges. Instead the sets go into batches whose faces share no vertex (so no edge
|
||||
/// either): one pass per batch walks each face's contours as its own set's pass would, and the
|
||||
/// set a contour bounds is the one of its batch at its first point.
|
||||
fn regions(&self) -> Vec<Region> {
|
||||
fn regions(&self) -> Result<Vec<Region>, GeomError> {
|
||||
let top = &self.top;
|
||||
// The distinct non-empty coverage sets, numbered in the order met, and the set of each
|
||||
// side of each segment. Faces have many sides, so a set is worked out once per winding.
|
||||
@@ -391,7 +417,7 @@ impl Arrangement {
|
||||
}
|
||||
let mut faces: Vec<Vec<BezPath>> = vec![Vec::new(); sets.len()];
|
||||
for b in 0..batches {
|
||||
let c = top.contours(|w| id(w).is_some_and(|m| batch[m] == b));
|
||||
let c = contours(top, |w| id(w).is_some_and(|m| batch[m] == b))?;
|
||||
let owner: Option<Vec<usize>> = c
|
||||
.contours()
|
||||
.map(|ct| {
|
||||
@@ -403,7 +429,7 @@ impl Arrangement {
|
||||
// Not expected: every contour starts at a vertex of the arrangement. Fall back to
|
||||
// a pass per set for this batch.
|
||||
for m in (0..sets.len()).filter(|&m| batch[m] == b) {
|
||||
let c = top.contours(|w| id(w) == Some(m));
|
||||
let c = contours(top, |w| id(w) == Some(m))?;
|
||||
faces[m].extend(c.grouped().into_iter().map(|g| self.outline(&c, g)));
|
||||
}
|
||||
continue;
|
||||
@@ -439,7 +465,7 @@ impl Arrangement {
|
||||
out.push(Region { path, area, sources: sources.clone() });
|
||||
}
|
||||
}
|
||||
out
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The contours `idx` of `c` as one path, repaired, without slivers, and with the pieces the
|
||||
@@ -467,6 +493,18 @@ impl Arrangement {
|
||||
}
|
||||
}
|
||||
|
||||
/// The contours of `top`'s faces for which `inside` holds. The contour walk returns an error when the
|
||||
/// sweep left winding numbers that disagree around a point, and can still panic on other degenerate
|
||||
/// input; either way that input is degenerate.
|
||||
fn contours(top: &Topology<Multi>, inside: impl Fn(&Multi) -> bool) -> Result<Contours, GeomError> {
|
||||
walk_result(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| top.try_contours(inside))))
|
||||
}
|
||||
|
||||
/// Maps a contour walk that panicked or returned an error to [`GeomError::Degenerate`].
|
||||
fn walk_result<T>(walk: std::thread::Result<Result<T, linesweeper::Error>>) -> Result<T, GeomError> {
|
||||
walk.map_err(|_| GeomError::Degenerate)?.map_err(|_| GeomError::Degenerate)
|
||||
}
|
||||
|
||||
/// A point as a map key (the arrangement's vertices are exact).
|
||||
fn vertex_key(p: Point) -> (u64, u64) {
|
||||
(p.x.to_bits(), p.y.to_bits())
|
||||
@@ -963,6 +1001,20 @@ mod tests {
|
||||
Shape::new(path, FillRule::NonZero)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inconsistent_windings_are_degenerate() {
|
||||
// A walk that returns an error or panics gives `Degenerate`; one that finishes gives its contours.
|
||||
assert_eq!(walk_result::<u8>(Ok(Err(linesweeper::Error::InconsistentWindingNumbers))), Err(GeomError::Degenerate));
|
||||
assert_eq!(walk_result::<u8>(Err(Box::new("walk panicked"))), Err(GeomError::Degenerate));
|
||||
assert_eq!(walk_result(Ok(Ok(7_u8))), Ok(7));
|
||||
let shapes = [fill(rect(0.0, 0.0, 10.0, 10.0))];
|
||||
let arrangement = Arrangement::new(&shapes, &[], DEFAULT_SLIVER, DEFAULT_MAX_SWEEP_WORK, DEFAULT_MAX_TOPOLOGY_UNITS).unwrap();
|
||||
assert_eq!(contours(&arrangement.top, |w: &Multi| w.get(0) != 0).map(|c| c.contours().count()), Ok(1));
|
||||
// A walk that panics, in debug and release builds alike, gives `Degenerate`.
|
||||
let panicking = |_: &Multi| -> bool { panic!("degenerate walk") };
|
||||
assert_eq!(contours(&arrangement.top, panicking).err(), Some(GeomError::Degenerate));
|
||||
}
|
||||
|
||||
/// The regions with their sources and areas rounded to 1e-6, sorted.
|
||||
fn summary(regions: &[Region]) -> Vec<(Vec<usize>, f64)> {
|
||||
let mut v: Vec<(Vec<usize>, f64)> = regions.iter().map(|r| (r.sources.clone(), (r.area * 1e6).round() / 1e6)).collect();
|
||||
@@ -1035,6 +1087,58 @@ mod tests {
|
||||
top.contours(|w| *w != 0).contours().map(|c| c.path.area()).sum::<f64>().abs()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sweep_past_its_work_limit_is_degenerate() {
|
||||
let shapes = vec![fill(Circle::new((50.0, 50.0), 40.0).to_path(0.01)); 20];
|
||||
assert_eq!(Arrangement::new(&shapes, &[], DEFAULT_SLIVER, 1_000, DEFAULT_MAX_TOPOLOGY_UNITS).err(), Some(GeomError::Degenerate));
|
||||
assert_eq!(regions(&shapes, &[]).unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regions_with_limits_takes_the_callers_limits() {
|
||||
let shapes = vec![fill(Circle::new((50.0, 50.0), 40.0).to_path(0.01)); 20];
|
||||
let limited = |work, units| regions_with_limits(&shapes, &[], DEFAULT_SLIVER, work, units);
|
||||
assert_eq!(limited(1_000, DEFAULT_MAX_TOPOLOGY_UNITS).err(), Some(GeomError::Degenerate));
|
||||
assert_eq!(limited(DEFAULT_MAX_SWEEP_WORK, 10).err(), Some(GeomError::Degenerate));
|
||||
assert_eq!(limited(DEFAULT_MAX_SWEEP_WORK, DEFAULT_MAX_TOPOLOGY_UNITS).unwrap().len(), 1);
|
||||
}
|
||||
|
||||
// 1,100 overlapping shapes made only of horizontal edges at one height. The sweep makes one
|
||||
// output segment for each run of coincident horizontal pieces and none for a run whose winding
|
||||
// numbers cancel, as every run does here, so the topology stays under
|
||||
// DEFAULT_MAX_TOPOLOGY_UNITS.
|
||||
#[test]
|
||||
fn coincident_horizontal_edges_stay_under_the_output_limit() {
|
||||
let n = 1_100;
|
||||
let shapes: Vec<Shape> = (0..n)
|
||||
.map(|i| {
|
||||
let i = f64::from(i);
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((i, 0.0));
|
||||
path.line_to((2.0 * f64::from(n) + i, 0.0));
|
||||
path.close_path();
|
||||
fill(path)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(regions(&shapes, &[]), Ok(vec![]));
|
||||
}
|
||||
|
||||
// 200 squares, each one unit down and right of the one before, cross each other's edges and
|
||||
// make fewer than 2,000,000 output segments, but the winding numbers of those segments hold an
|
||||
// entry for each square that covers them, which passes DEFAULT_MAX_TOPOLOGY_UNITS. The sweep
|
||||
// has no work limit here, so the output limit stops it.
|
||||
#[test]
|
||||
fn winding_entries_count_toward_the_output_limit() {
|
||||
let k = 200;
|
||||
let shapes: Vec<Shape> = (0..k)
|
||||
.map(|i| {
|
||||
let i = f64::from(i);
|
||||
fill(rect(i, i, f64::from(k) + i, f64::from(k) + i))
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(Arrangement::new(&shapes, &[], DEFAULT_SLIVER, u64::MAX, DEFAULT_MAX_TOPOLOGY_UNITS).err(), Some(GeomError::Degenerate));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stacked_boxes_fold_into_one_group_past_the_comparison_budget() {
|
||||
// Boxes one above the other, all sharing x 0–10: each stays open for every later one.
|
||||
@@ -1054,7 +1158,7 @@ mod tests {
|
||||
fill(rect(i, i + 0.25, i + 8.0, i + 8.25))
|
||||
})
|
||||
.collect();
|
||||
let a = Arrangement::new(&shapes, &[], DEFAULT_SLIVER).unwrap();
|
||||
let a = Arrangement::new(&shapes, &[], DEFAULT_SLIVER, DEFAULT_MAX_SWEEP_WORK, DEFAULT_MAX_TOPOLOGY_UNITS).unwrap();
|
||||
let mut sides = 0;
|
||||
let mut lists = std::collections::HashSet::new();
|
||||
for s in a.top.segment_indices() {
|
||||
|
||||
@@ -14,12 +14,16 @@ use kurbo::{Affine, BezPath, Point, Rect};
|
||||
|
||||
use crate::ink::{InkColor, InkId, InkSet, Overprint};
|
||||
|
||||
pub use compose::{ComplexGroup, ComplexReason, ComplexRegion, FlattenError, FlattenOptions, FlattenReport, Flattened, flatten};
|
||||
pub use compose::{
|
||||
ComplexGroup, ComplexReason, ComplexRegion, FlattenError, FlattenOptions, FlattenReport, FlattenSweepLimits, Flattened, flatten,
|
||||
flatten_with_limits,
|
||||
};
|
||||
pub use document::{
|
||||
FlattenDocumentError, FlattenDocumentOptions, FlattenDocumentReport, FlattenTotals, Unreadable, flatten_document, flatten_document_with_progress,
|
||||
FlattenDocumentError, FlattenDocumentOptions, FlattenDocumentReport, FlattenTotals, Unreadable, flatten_document, flatten_document_with_limits,
|
||||
flatten_document_with_limits_and_progress, flatten_document_with_progress,
|
||||
};
|
||||
pub use geom::FillRule;
|
||||
pub use raster::{FlattenPageError, FlattenPageOptions, FlattenPageReport, flatten_page};
|
||||
pub use raster::{FlattenPageError, FlattenPageOptions, FlattenPageReport, flatten_page, flatten_page_with_limits};
|
||||
|
||||
mod compose;
|
||||
mod document;
|
||||
|
||||
@@ -43,6 +43,8 @@ use craft_pdf::{OpenError, open_slice};
|
||||
use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke, StrokeOpts};
|
||||
|
||||
use super::font::FontCache;
|
||||
#[cfg(test)]
|
||||
use super::geom;
|
||||
use super::shade::{self, Canvas, StopInks};
|
||||
use super::{
|
||||
BlendMode, DisplayList, FillItem, FillRule, GradientGeometry, GroupItem, ImageItem, ImageSpace, Item, Mask, MaskKind, Paint, PlacedGlyph,
|
||||
@@ -170,7 +172,7 @@ pub enum ReadError {
|
||||
pub fn read_page(pdf: &[u8], page: usize, opts: &ReadOptions) -> Result<(DisplayList, ReadReport), ReadError> {
|
||||
let doc = open_slice(pdf, None)?;
|
||||
let color = read_color(&doc, page, &opts.fallback)?;
|
||||
read_page_in(&doc, page, opts, color)
|
||||
read_page_in(&doc, page, opts, color, &super::FlattenSweepLimits::default())
|
||||
}
|
||||
|
||||
/// How a page's process color converts: its output intent's simulation, else `fallback`'s.
|
||||
@@ -189,7 +191,13 @@ pub(crate) fn read_color(doc: &Pdf, page: usize, fallback: &Fallback) -> Result<
|
||||
}
|
||||
|
||||
/// [`read_page`] of an open document, with the page's color already read.
|
||||
pub(crate) fn read_page_in(doc: &Pdf, page: usize, opts: &ReadOptions, color: ReadColor) -> Result<(DisplayList, ReadReport), ReadError> {
|
||||
pub(crate) fn read_page_in(
|
||||
doc: &Pdf,
|
||||
page: usize,
|
||||
opts: &ReadOptions,
|
||||
color: ReadColor,
|
||||
limits: &super::FlattenSweepLimits,
|
||||
) -> Result<(DisplayList, ReadReport), ReadError> {
|
||||
let (simulation, conversion) = color;
|
||||
let pages = doc.pages();
|
||||
let p = pages.get(page).ok_or(ReadError::NoPage(page))?;
|
||||
@@ -220,6 +228,7 @@ pub(crate) fn read_page_in(doc: &Pdf, page: usize, opts: &ReadOptions, color: Re
|
||||
masks: HashMap::new(),
|
||||
fonts: FontCache::new(),
|
||||
scale: f64::from(dpi) / 72.0,
|
||||
sweep_limits: *limits,
|
||||
};
|
||||
|
||||
let items = catch_unwind(AssertUnwindSafe(|| {
|
||||
@@ -260,6 +269,7 @@ struct Shared {
|
||||
fonts: FontCache,
|
||||
/// Raster pixels per point.
|
||||
scale: f64,
|
||||
sweep_limits: super::FlattenSweepLimits,
|
||||
}
|
||||
|
||||
/// How a paint composites: what wraps it in a group of its own.
|
||||
@@ -344,6 +354,11 @@ fn clip_group((clip, rule): (BezPath, FillRule)) -> GroupItem {
|
||||
}
|
||||
|
||||
impl<'s, 'a> Reader<'s, 'a> {
|
||||
fn nonzero(&self, path: &BezPath, rule: FillRule) -> (BezPath, FillRule) {
|
||||
let limits = self.shared.sweep_limits;
|
||||
nonzero_within(path, rule, limits.max_sweep_work, limits.max_sweep_units)
|
||||
}
|
||||
|
||||
fn new(shared: &'s mut Shared, glyph: bool, bounds: Rect) -> Self {
|
||||
Self {
|
||||
shared,
|
||||
@@ -621,7 +636,7 @@ impl<'s, 'a> Reader<'s, 'a> {
|
||||
fn area_fill(&mut self, path: BezPath, rule: FillRule, paint: &PdfPaint<'a>, stroke: bool) {
|
||||
let PdfPaint::Pattern(pattern) = paint else { return };
|
||||
self.flush();
|
||||
let (clip, rule) = nonzero(&path, rule);
|
||||
let (clip, rule) = self.nonzero(&path, rule);
|
||||
let (op, big_op, _) = self.overprint;
|
||||
let flag = if stroke { big_op } else { op };
|
||||
match pattern.as_ref() {
|
||||
@@ -975,7 +990,7 @@ impl<'s, 'a> Reader<'s, 'a> {
|
||||
let mut outline = BezPath::new();
|
||||
for item in &items {
|
||||
if let Item::Fill(f) = item {
|
||||
let (path, rule) = nonzero(&f.path, f.rule);
|
||||
let (path, rule) = self.nonzero(&f.path, f.rule);
|
||||
if rule != FillRule::NonZero {
|
||||
return None;
|
||||
}
|
||||
@@ -1016,7 +1031,7 @@ impl<'a> Device<'a> for Reader<'_, 'a> {
|
||||
|
||||
fn push_clip_path(&mut self, clip_path: &ClipPath) {
|
||||
self.flush();
|
||||
let clip = nonzero(&clip_path.path, fill_rule(clip_path.fill));
|
||||
let clip = self.nonzero(&clip_path.path, fill_rule(clip_path.fill));
|
||||
self.frames.push(Frame { kind: FrameKind::Clip, group: clip_group(clip) });
|
||||
}
|
||||
|
||||
@@ -1317,22 +1332,35 @@ fn dash_pattern(path: &BezPath, dashes: &[f32]) -> Option<Vec<f64>> {
|
||||
}
|
||||
|
||||
/// `path` filled by `rule`, as a path and the rule it is filled by. An even-odd path is
|
||||
/// rebuilt from its boundary as a path filled nonzero; if that fails it is kept closed and
|
||||
/// filled even-odd.
|
||||
/// rebuilt from its boundary as a path filled nonzero; if that fails, panics, or passes the
|
||||
/// flattener's default sweep work or output limit ([`geom::DEFAULT_MAX_SWEEP_WORK`],
|
||||
/// [`geom::DEFAULT_MAX_TOPOLOGY_UNITS`]), it is kept closed and filled even-odd. The same fallback
|
||||
/// applies when an input subpath fails [`linesweeper::binary_op`]'s automatic-accuracy check.
|
||||
#[cfg(test)]
|
||||
fn nonzero(path: &BezPath, rule: FillRule) -> (BezPath, FillRule) {
|
||||
nonzero_within(path, rule, geom::DEFAULT_MAX_SWEEP_WORK, geom::DEFAULT_MAX_TOPOLOGY_UNITS)
|
||||
}
|
||||
|
||||
/// Rebuilds an even-odd path with the sweep stopped after `work_limit` units of work or before
|
||||
/// its topology holds more than `output_limit` units. A stopped rebuild keeps the original rule.
|
||||
fn nonzero_within(path: &BezPath, rule: FillRule, work_limit: u64, output_limit: usize) -> (BezPath, FillRule) {
|
||||
if rule == FillRule::NonZero {
|
||||
return (path.clone(), FillRule::NonZero);
|
||||
}
|
||||
let closed = closed(path);
|
||||
match linesweeper::binary_op(&closed, &BezPath::new(), linesweeper::FillRule::EvenOdd, linesweeper::BinaryOp::Union) {
|
||||
Ok(contours) => {
|
||||
let op = catch_unwind(AssertUnwindSafe(|| {
|
||||
let top = linesweeper::topology::Topology::<i32>::from_paths_with_automatic_limits([(&closed, ())], work_limit, output_limit)?;
|
||||
top.try_contours(|winding| winding % 2 != 0)
|
||||
}));
|
||||
match op {
|
||||
Ok(Ok(contours)) => {
|
||||
let mut out = BezPath::new();
|
||||
for contour in contours.contours() {
|
||||
out.extend(contour.path.iter());
|
||||
}
|
||||
(out, FillRule::NonZero)
|
||||
}
|
||||
Err(_) => (closed, FillRule::EvenOdd),
|
||||
Ok(Err(_)) | Err(_) => (closed, FillRule::EvenOdd),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1363,6 +1391,119 @@ fn closed(path: &BezPath) -> BezPath {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn page_reader_uses_explicit_sweep_limits_for_even_odd_clips() {
|
||||
use craft_pdf::write::backend::geom::{PathBuilder, Rect as KRect};
|
||||
use craft_pdf::write::backend::page::PageSettings;
|
||||
use craft_pdf::write::backend::paint::{Fill, FillRule as KFillRule};
|
||||
use craft_pdf::write::{Metadata, Writer};
|
||||
let mut writer = Writer::new(Default::default(), Metadata::default());
|
||||
let mut page = writer.document_mut().start_page_with(PageSettings::from_wh(100.0, 100.0).unwrap());
|
||||
let mut surface = page.surface();
|
||||
let mut clip = PathBuilder::new();
|
||||
clip.push_rect(KRect::from_ltrb(0.0, 0.0, 90.0, 90.0).unwrap());
|
||||
clip.push_rect(KRect::from_ltrb(20.0, 20.0, 70.0, 70.0).unwrap());
|
||||
surface.push_clip_path(&clip.finish().unwrap(), &KFillRule::EvenOdd);
|
||||
let mut paint = PathBuilder::new();
|
||||
paint.push_rect(KRect::from_ltrb(0.0, 0.0, 100.0, 100.0).unwrap());
|
||||
surface.set_fill(Some(Fill::default()));
|
||||
surface.draw_path(&paint.finish().unwrap());
|
||||
surface.pop();
|
||||
surface.finish();
|
||||
page.finish();
|
||||
let bytes = writer.finish().unwrap();
|
||||
let doc = open_slice(&bytes, None).unwrap();
|
||||
let opts = ReadOptions::default();
|
||||
for limits in [
|
||||
super::super::FlattenSweepLimits::default(),
|
||||
super::super::FlattenSweepLimits { max_sweep_work: 1, ..Default::default() },
|
||||
super::super::FlattenSweepLimits { max_sweep_units: 1, ..Default::default() },
|
||||
] {
|
||||
let color = read_color(&doc, 0, &opts.fallback).unwrap();
|
||||
let (list, _) = read_page_in(&doc, 0, &opts, color, &limits).unwrap();
|
||||
let group = list
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|item| match item {
|
||||
Item::Group(group) if group.clip.is_some() => Some(group),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let expected = if limits == super::super::FlattenSweepLimits::default() { FillRule::NonZero } else { FillRule::EvenOdd };
|
||||
assert_eq!(group.clip_rule, expected, "{limits:?}");
|
||||
let path = group.clip.as_ref().unwrap();
|
||||
let filled = |point| match group.clip_rule {
|
||||
FillRule::NonZero => path.winding(point) != 0,
|
||||
FillRule::EvenOdd => path.winding(point) % 2 != 0,
|
||||
};
|
||||
assert!(filled((10.0, 10.0).into()));
|
||||
assert!(!filled((50.0, 50.0).into()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_odd_path_with_inconsistent_windings_is_kept() {
|
||||
// `nonzero` returns a path for this input whether the sweep succeeds or reports
|
||||
// winding numbers that disagree around a point.
|
||||
let path = BezPath::from_svg("M4,-1 C8,1 -7,-2 5,8 L-4,-8 L2,1 L1,1 Z").unwrap();
|
||||
assert!(!nonzero(&path, FillRule::EvenOdd).0.elements().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_odd_holes_stay_open_beside_a_far_point() {
|
||||
// A square with a hole drawn in the same direction, a 0.3 wide sliver and a triangle at
|
||||
// 3e13, which makes the sweep tolerance about 0.43.
|
||||
let mut path = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.0);
|
||||
path.extend(Rect::new(25.0, 25.0, 75.0, 75.0).to_path(0.0).iter());
|
||||
path.extend(Rect::new(200.0, 0.0, 200.3, 10.0).to_path(0.0).iter());
|
||||
path.move_to((3.0e13, 3.0e13));
|
||||
path.line_to((3.0e13 + 1.0e3, 3.0e13));
|
||||
path.line_to((3.0e13, 3.0e13 + 1.0e3));
|
||||
path.close_path();
|
||||
// The automatic-accuracy check rejects rebuilding the narrow subpath.
|
||||
let swept = linesweeper::binary_op(&path, &BezPath::new(), linesweeper::FillRule::EvenOdd, linesweeper::BinaryOp::Union);
|
||||
assert!(matches!(swept, Err(linesweeper::Error::FeatureBelowTolerance { .. })));
|
||||
let (out, rule) = nonzero(&path, FillRule::EvenOdd);
|
||||
let contains = |point| {
|
||||
let winding = out.winding(point);
|
||||
match rule {
|
||||
FillRule::EvenOdd => winding % 2 != 0,
|
||||
FillRule::NonZero => winding != 0,
|
||||
}
|
||||
};
|
||||
assert!(contains((200.15, 5.0).into()), "the narrow subpath remains filled");
|
||||
assert!(contains((10.0, 10.0).into()));
|
||||
assert!(!contains((50.0, 50.0).into()));
|
||||
assert_eq!(rule, FillRule::EvenOdd);
|
||||
assert_eq!(out, path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_odd_path_past_the_sweep_work_limit_is_kept() {
|
||||
// 21 stacked copies of one circle: the sweep compares their segments many times over.
|
||||
let circle = kurbo::Circle::new((50.0, 50.0), 40.0).to_path(0.01);
|
||||
let mut path = BezPath::new();
|
||||
for _ in 0..21 {
|
||||
path.extend(circle.iter());
|
||||
}
|
||||
let (kept, rule) = nonzero_within(&path, FillRule::EvenOdd, 1_000, geom::DEFAULT_MAX_TOPOLOGY_UNITS);
|
||||
assert_eq!(kept.elements(), closed(&path).elements());
|
||||
assert_eq!(rule, FillRule::EvenOdd);
|
||||
assert_ne!(nonzero(&path, FillRule::EvenOdd).0.elements(), closed(&path).elements());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_odd_path_past_the_sweep_output_limit_is_kept() {
|
||||
// A square with a hole drawn in the same direction makes 8 output segments.
|
||||
let mut path = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.0);
|
||||
path.extend(Rect::new(25.0, 25.0, 75.0, 75.0).to_path(0.0).iter());
|
||||
let (kept, rule) = nonzero_within(&path, FillRule::EvenOdd, geom::DEFAULT_MAX_SWEEP_WORK, 4);
|
||||
assert_eq!(kept.elements(), closed(&path).elements());
|
||||
assert_eq!(rule, FillRule::EvenOdd);
|
||||
assert_ne!(kept.winding((50.0, 50.0).into()), 0);
|
||||
assert_eq!(nonzero(&path, FillRule::EvenOdd).0.winding((50.0, 50.0).into()), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_odd_paths_keep_their_rule_when_the_rebuild_fails() {
|
||||
// Two nested squares drawn in the same direction: even-odd leaves a hole, nonzero fills it.
|
||||
|
||||
@@ -41,7 +41,7 @@ use craft_pdf::interpret::color::CmykConversion;
|
||||
use craft_pdf::write::backend::SerializeSettings;
|
||||
use kurbo::{Affine, Rect, Shape as _};
|
||||
|
||||
use super::document::{FlattenDocumentError, FlattenDocumentOptions, flatten_document};
|
||||
use super::document::{FlattenDocumentError, FlattenDocumentOptions, flatten_document_with_limits};
|
||||
use super::pdf::{ReadError, ReadOptions, ReadReport};
|
||||
use super::write::{WriteError, page_pdf};
|
||||
use super::{
|
||||
@@ -409,11 +409,21 @@ pub enum FlattenPageError {
|
||||
}
|
||||
|
||||
/// Page `page` (from 0) of `pdf` with its transparency flattened, as a one-page PDF: the
|
||||
/// one-page case of [`flatten_document`].
|
||||
/// one-page case of [`super::flatten_document`].
|
||||
pub fn flatten_page(pdf: &[u8], page: usize, opts: &FlattenPageOptions) -> Result<(Vec<u8>, FlattenPageReport), FlattenPageError> {
|
||||
flatten_page_with_limits(pdf, page, opts, &super::FlattenSweepLimits::default())
|
||||
}
|
||||
|
||||
/// [`flatten_page`] with explicit sweep work and output limits.
|
||||
pub fn flatten_page_with_limits(
|
||||
pdf: &[u8],
|
||||
page: usize,
|
||||
opts: &FlattenPageOptions,
|
||||
limits: &super::FlattenSweepLimits,
|
||||
) -> Result<(Vec<u8>, FlattenPageReport), FlattenPageError> {
|
||||
let doc =
|
||||
FlattenDocumentOptions { read: opts.read.clone(), flatten: opts.flatten, pages: Some(page..page.saturating_add(1)), ..Default::default() };
|
||||
let (bytes, mut report) = flatten_document(pdf, &doc).map_err(|e| match e {
|
||||
let (bytes, mut report) = flatten_document_with_limits(pdf, &doc, limits).map_err(|e| match e {
|
||||
FlattenDocumentError::Open(e) => FlattenPageError::Open(e),
|
||||
FlattenDocumentError::PageRange { .. } => FlattenPageError::Read(ReadError::NoPage(page)),
|
||||
FlattenDocumentError::Read { source, .. } => FlattenPageError::Read(source),
|
||||
|
||||
@@ -117,6 +117,41 @@ fn opts() -> FlattenDocumentOptions {
|
||||
FlattenDocumentOptions { flatten: FlattenOptions { raster_dpi: 72.0, ..FlattenOptions::default() }, ..FlattenDocumentOptions::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_entry_points_keep_explicit_sweep_limits() {
|
||||
use craft_prepress::flatten::{
|
||||
FlattenSweepLimits, flatten_document_with_limits, flatten_document_with_limits_and_progress, flatten_page_with_limits,
|
||||
};
|
||||
let settings = SerializeSettings { no_device_cs: false, group_color_space: GroupColorSpace::Cmyk, ..Default::default() };
|
||||
let mut writer = Writer::new(settings, Metadata::default());
|
||||
let mut page = writer.document_mut().start_page_with(PageSettings::from_wh(200.0, 160.0).unwrap());
|
||||
let mut surface = page.surface();
|
||||
rect(&mut surface, 20.0, 20.0, 120.0, 100.0, fill(255, 0, 0, 0));
|
||||
surface.push_opacity(NormalizedF32::new(0.5).unwrap());
|
||||
rect(&mut surface, 70.0, 60.0, 170.0, 130.0, fill(0, 255, 0, 0));
|
||||
surface.pop();
|
||||
surface.finish();
|
||||
page.finish();
|
||||
let source = writer.finish().unwrap();
|
||||
let options = opts();
|
||||
let (_, ordinary) = flatten_document(&source, &options).unwrap();
|
||||
assert_eq!(ordinary.totals.complex_groups, 0);
|
||||
for limits in [FlattenSweepLimits { max_sweep_work: 1, ..Default::default() }, FlattenSweepLimits { max_sweep_units: 1, ..Default::default() }] {
|
||||
let (_, document) = flatten_document_with_limits(&source, &options, &limits).unwrap();
|
||||
assert_eq!(document.totals.complex_groups, 1);
|
||||
let mut progress = Vec::new();
|
||||
let (_, observed) = flatten_document_with_limits_and_progress(&source, &options, &limits, &mut |done, total| {
|
||||
progress.push((done, total));
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(observed, document);
|
||||
assert_eq!(progress, [(1, 1)]);
|
||||
let page_options = FlattenPageOptions { flatten: options.flatten, ..Default::default() };
|
||||
let (_, page) = flatten_page_with_limits(&source, 0, &page_options, &limits).unwrap();
|
||||
assert_eq!(page.flatten.complex_groups.len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
fn separate(pdf: &[u8], page: usize) -> Plates {
|
||||
plates(pdf, page, DPI, &Options::default()).unwrap()
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "<commit>
|
||||
| German | — | — | TeX patterns (embedded, or a Language pack) |
|
||||
| Bulgarian | — | — | syllable rules |
|
||||
| Gujarati, Hindi | the installed Hunspell dictionary (Hindi: nukta letters spelled either way) | generic checks | akshara rules (or a Language pack) |
|
||||
| Marathi (mr) | its Language pack or Hunspell dictionary, as any pack language | — | akshara rules (or a Language pack) |
|
||||
|
||||
Grammar rules, suggestion tuning and the rule-based hyphenation are code: they work in every
|
||||
build.
|
||||
|
||||
@@ -130,6 +130,34 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A zero-width joiner or non-joiner in a conjunct (`પુસ્` U+200D `તક`) keeps the word whole,
|
||||
/// and the word is found under the dictionary's spelling, which has no joiner.
|
||||
#[test]
|
||||
fn words_with_joiners_are_one_word_and_spelled() {
|
||||
test_dict::install();
|
||||
for word in ["પુસ્\u{200D}તક", "પુસ્\u{200C}તકોમાં"] {
|
||||
let text = format!("ઘર {word} ગામ");
|
||||
let at = text.find(word).unwrap();
|
||||
assert!(crate::words(&text).contains(&(at, at + word.len())), "{word:?}");
|
||||
assert!(is_correct(word), "{word:?}");
|
||||
let issues = crate::check_text(&text, &[(0..text.len(), crate::ProofLang::Gu)]);
|
||||
assert!(issues.is_empty(), "{word:?}: {issues:?}");
|
||||
}
|
||||
// Still a misspelling with a joiner, and a joiner at a word's edge is not in the word.
|
||||
assert!(!is_correct("પુસ્\u{200D}તકક"));
|
||||
let text = "ઘર\u{200D} ગામ";
|
||||
assert!(crate::words(text).contains(&(0, "ઘર".len())));
|
||||
// A word with a joiner written twice is a repeated word.
|
||||
let text = "પુસ્\u{200D}તક પુસ્\u{200D}તક";
|
||||
let issues = crate::check_grammar_in(text, crate::ProofLang::Gu);
|
||||
assert!(issues.iter().any(|i| i.start == 0 && i.end == text.len()), "{issues:?}");
|
||||
// A word Gujarati repeats on purpose (`જલ્દી જલ્દી`) still is one when typed with a joiner.
|
||||
for text in ["જલ્\u{200D}દી જલ્\u{200D}દી", "જલ્\u{200C}દી જલ્\u{200C}દી"] {
|
||||
let issues = crate::check_grammar_in(text, crate::ProofLang::Gu);
|
||||
assert!(issues.is_empty(), "{text:?}: {issues:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forbidden_words_are_rejected() {
|
||||
test_dict::install();
|
||||
|
||||
@@ -143,6 +143,22 @@ mod tests {
|
||||
test_dict::install();
|
||||
}
|
||||
|
||||
/// A zero-width joiner or non-joiner after a virama (`क्` U+200D `ष`) keeps the word whole, and
|
||||
/// the word is found under the dictionary's spelling, which has no joiner.
|
||||
#[test]
|
||||
fn words_with_joiners_are_one_word_and_spelled() {
|
||||
test_dict::install();
|
||||
for word in ["परीक्\u{200D}षण", "परीक्\u{200C}षण", "मित्\u{200D}रों"] {
|
||||
let text = format!("घर {word} पानी।");
|
||||
let at = text.find(word).unwrap();
|
||||
assert!(crate::words(&text).contains(&(at, at + word.len())), "{word:?}");
|
||||
assert!(is_correct(word), "{word:?}");
|
||||
let issues = crate::check_text(&text, &[(0..text.len(), crate::ProofLang::Hi)]);
|
||||
assert!(issues.is_empty(), "{word:?}: {issues:?}");
|
||||
}
|
||||
assert!(!is_correct("परीक्\u{200D}षणण"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_dictionary_applies() {
|
||||
test_dict::install();
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
//!
|
||||
//! **Bulgarian**: the Bulgarian syllable rules ([`crate::bg`]); no pattern file or word list.
|
||||
//!
|
||||
//! **Gujarati and Hindi**: breaks between aksharas, never inside a conjunct or between a
|
||||
//! **Gujarati, Hindi and Marathi**: breaks between aksharas, never inside a conjunct or between a
|
||||
//! consonant and its vowel sign ([`crate::indic`], rules from the script's Unicode encoding); no
|
||||
//! pattern file.
|
||||
//!
|
||||
@@ -120,7 +120,7 @@ pub enum Source {
|
||||
Patterns,
|
||||
/// A heuristic for a language without a dictionary or patterns.
|
||||
Heuristic,
|
||||
/// A language's syllable rules (Bulgarian [`crate::bg`], Turkish, Gujarati and Hindi [`crate::indic`]).
|
||||
/// A language's syllable rules (Bulgarian [`crate::bg`], Turkish, Gujarati, Hindi and Marathi [`crate::indic`]).
|
||||
Rules,
|
||||
/// No break points: the word is too short or no source applies.
|
||||
None,
|
||||
@@ -167,7 +167,7 @@ fn core_breaks(core: &[char], lang: ProofLang) -> (Vec<usize>, Source) {
|
||||
if lang == ProofLang::Bg && core.iter().all(|&c| crate::bg::is_letter(c)) {
|
||||
return (crate::bg::points(core), Source::Rules);
|
||||
}
|
||||
// Gujarati and Hindi words break between aksharas ([`crate::indic`]); other words in their runs
|
||||
// Gujarati, Hindi and Marathi words break between aksharas ([`crate::indic`]); other words in their runs
|
||||
// (`WordCraft`) are hyphenated as English.
|
||||
if let Some(script) = crate::indic::Script::of(lang)
|
||||
&& core.iter().all(|&c| script.is_letter(c))
|
||||
@@ -242,8 +242,8 @@ fn composed_chars(core: &[char]) -> (Vec<char>, Vec<Option<usize>>) {
|
||||
(nfc, starts)
|
||||
}
|
||||
|
||||
/// Does a pack's `pats` hyphenate `core` in `lang`? Russian, Bulgarian, Turkish, Gujarati and
|
||||
/// Hindi: a word in their script (the guard their rules use; for Gujarati and Hindi, the script's
|
||||
/// Does a pack's `pats` hyphenate `core` in `lang`? Russian, Bulgarian, Turkish, Gujarati, Hindi
|
||||
/// and Marathi: a word in their script (the guard their rules use; for the Indic ones, the script's
|
||||
/// letters and marks and the joiners inside a conjunct, [`crate::indic`]) whose letters the
|
||||
/// patterns know, so a word with a letter the pack never mentions goes on to the fallback rules. Polish, Portuguese, Italian
|
||||
/// and German: every word, as their embedded patterns do. Any other language: a word whose letters
|
||||
@@ -254,7 +254,7 @@ fn pack_patterns_fit(lang: ProofLang, pats: &Patterns, core: &[char]) -> bool {
|
||||
ProofLang::Bg => core.iter().all(|&c| crate::bg::is_letter(c)) && pack_knows(pats, core),
|
||||
ProofLang::Tr => core.iter().all(|&c| crate::tr::hyphen::is_letter(c)) && pack_knows(pats, core),
|
||||
ProofLang::Pl | ProofLang::Pt | ProofLang::It | ProofLang::De => true,
|
||||
ProofLang::Gu | ProofLang::Hi => {
|
||||
_ if crate::indic::Script::of(lang).is_some() => {
|
||||
crate::indic::Script::of(lang).is_some_and(|s| core.iter().all(|&c| s.is_letter(c))) && pack_knows(pats, core)
|
||||
}
|
||||
_ => pats.values(core).is_some(),
|
||||
|
||||
@@ -235,3 +235,12 @@ fn hindi_breaks_between_aksharas_within_the_limits() {
|
||||
assert_eq!(hi("«विद्यार्थी»"), "«वि-द्या-र्थी»", "punctuation around the word");
|
||||
assert_eq!(hi("Typography"), hyphenate_word_in("Typography", &lim, ProofLang::En));
|
||||
}
|
||||
|
||||
/// storytold/vectorcraft#4947: Marathi, a pack language (`mr`), breaks between aksharas as Hindi
|
||||
/// does, within the paragraph's limits.
|
||||
#[test]
|
||||
fn marathi_breaks_between_aksharas() {
|
||||
let mr = ProofLang::from_tag(Some("mr-IN"));
|
||||
assert_eq!(hyphenate_word_in("महाराष्ट्र", &Limits::default(), mr), "महा-रा-ष्ट्र");
|
||||
assert_eq!(word_breaks_in("महाराष्ट्र", mr).1, Source::Rules);
|
||||
}
|
||||
@@ -14,7 +14,8 @@
|
||||
//! The rules come from the scripts' Unicode encoding alone; no pattern file or word list is
|
||||
//! read (and none is borrowed). The Brahmic blocks share one layout (the ISCII order), so a
|
||||
//! script is its block's start and a few script-specific code points (`Script::kind`).
|
||||
//! Gujarati ([`ProofLang::Gu`]) and Hindi ([`ProofLang::Hi`], [`Script::Devanagari`]) use them;
|
||||
//! Gujarati ([`ProofLang::Gu`]), Hindi ([`ProofLang::Hi`]) and Marathi (the pack language `mr`)
|
||||
//! use them, Hindi and Marathi with [`Script::Devanagari`];
|
||||
//! another language written in one of these scripts is one more line in [`Script::of`].
|
||||
//!
|
||||
//! A single akshara left at the end or start of a line is ruled out by the paragraph's
|
||||
@@ -61,6 +62,9 @@ impl Script {
|
||||
match lang {
|
||||
ProofLang::Gu => Some(Script::Gujarati),
|
||||
ProofLang::Hi => Some(Script::Devanagari),
|
||||
// Marathi has no proofing language of its own: `mr`, `mr-IN` and `mar` are pack
|
||||
// languages, spelled from their pack or Hunspell dictionary.
|
||||
ProofLang::Pack(l) if matches!(l.primary(), "mr" | "mar") => Some(Script::Devanagari),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -243,11 +247,16 @@ mod tests {
|
||||
assert_eq!(hi("क्\u{200D}षमा"), "क्\u{200D}ष-मा");
|
||||
}
|
||||
|
||||
/// Gujarati and Hindi are mapped to their scripts, other languages to none.
|
||||
/// Gujarati, Hindi and Marathi (a pack language, by any of its tags) are mapped to their
|
||||
/// scripts, other languages (another pack language among them) to none.
|
||||
#[test]
|
||||
fn languages_map_to_their_script() {
|
||||
assert_eq!(Script::of(ProofLang::Gu), Some(Script::Gujarati));
|
||||
assert_eq!(Script::of(ProofLang::Hi), Some(Script::Devanagari));
|
||||
for tag in ["mr", "mr-IN", "mar"] {
|
||||
assert_eq!(Script::of(ProofLang::from_tag(Some(tag))), Some(Script::Devanagari), "{tag}");
|
||||
}
|
||||
assert_eq!(Script::of(ProofLang::from_tag(Some("ne"))), None);
|
||||
assert_eq!(Script::of(ProofLang::En), None);
|
||||
assert_eq!(Script::of(ProofLang::Bg), None);
|
||||
}
|
||||
|
||||
+22
-3
@@ -489,13 +489,32 @@ fn in_dialect(s: &str, word: &str, lang: ProofLang) -> String {
|
||||
}
|
||||
|
||||
/// Words in `text`: (byte start, byte end). Combining marks belong to the word they follow, so a
|
||||
/// word typed decomposed (`tambie\u{301}n`, NFD) is one word, as its precomposed form is.
|
||||
/// word typed decomposed (`tambie\u{301}n`, NFD) is one word, as its precomposed form is. A
|
||||
/// zero-width joiner or non-joiner between two letters, digits or marks is inside the word, as in
|
||||
/// Unicode's word boundaries (UAX #29): Indic text uses one to choose how a conjunct is drawn
|
||||
/// (`क्` U+200D `ष`, `પુસ્` U+200D `તક`). A joiner at a word's edge is not part of it.
|
||||
pub fn words(text: &str) -> Vec<(usize, usize)> {
|
||||
use indic::is_joiner;
|
||||
let mut out = Vec::new();
|
||||
let mut start: Option<usize> = None;
|
||||
let is_w = |c: char| c.is_alphanumeric() || c == '\'' || c == '’' || c == '-' || unicode_normalization::char::is_combining_mark(c);
|
||||
let is_core = |c: char| c.is_alphanumeric() || unicode_normalization::char::is_combining_mark(c);
|
||||
let is_w = |c: char| is_core(c) || c == '\'' || c == '’' || c == '-';
|
||||
// The char before was a letter, digit or mark, or a joiner kept after one.
|
||||
let mut after_core = false;
|
||||
// Is the first char after the current run of joiners a letter, digit or mark? Looked up once
|
||||
// per run, so a long run of joiners costs linear time, not quadratic.
|
||||
let mut run_ends_core: Option<bool> = None;
|
||||
for (i, c) in text.char_indices() {
|
||||
match (start, is_w(c)) {
|
||||
let w = if is_joiner(c) {
|
||||
after_core
|
||||
&& *run_ends_core
|
||||
.get_or_insert_with(|| text.get(i + c.len_utf8()..).and_then(|rest| rest.chars().find(|&n| !is_joiner(n))).is_some_and(is_core))
|
||||
} else {
|
||||
run_ends_core = None;
|
||||
is_w(c)
|
||||
};
|
||||
after_core = if is_joiner(c) { w } else { is_core(c) };
|
||||
match (start, w) {
|
||||
(None, true) => start = Some(i),
|
||||
(Some(s), false) => {
|
||||
out.push((s, i));
|
||||
|
||||
@@ -46,10 +46,13 @@ pub(crate) fn is_correct(script: &Script, d: &AffixDict, word: &str, opts: &crat
|
||||
}
|
||||
|
||||
/// Is one word (no hyphens) in the dictionary or the user dictionary, spelled as it is or as the
|
||||
/// script's [`Script::variant`]?
|
||||
/// script's [`Script::variant`]? A word with a zero-width joiner or non-joiner (`પુસ્` U+200D
|
||||
/// `તક`) is tried as typed, then without its joiners, as a dictionary that ignores them
|
||||
/// (Hunspell's `IGNORE`) would: they choose how a conjunct is drawn, not how the word is spelled.
|
||||
fn known(script: &Script, d: &AffixDict, w: &str) -> bool {
|
||||
let listed = |w: &str| d.check(w) || crate::in_user_dictionary(&w.to_lowercase());
|
||||
listed(w) || script.variant.and_then(|v| v(w)).is_some_and(|v| listed(&v))
|
||||
let spelled = |w: &str| listed(w) || script.variant.and_then(|v| v(w)).is_some_and(|v| listed(&v));
|
||||
spelled(w) || (w.contains(crate::indic::is_joiner) && spelled(&w.replace(crate::indic::is_joiner, "")))
|
||||
}
|
||||
|
||||
/// A language's script, messages and choices for [`check`].
|
||||
@@ -91,9 +94,11 @@ fn repeated_words(text: &str, ws: &[(usize, usize)], rules: &Rules, v: &mut Vec<
|
||||
let (Some(w0), Some(w1), Some(gap)) = (text.get(*a0..*b0), text.get(*a1..*b1), text.get(*b0..*a1)) else { continue };
|
||||
if !gap.is_empty()
|
||||
&& gap.chars().all(char::is_whitespace)
|
||||
&& w0.chars().all(|c| c.is_alphabetic() || (rules.script.is_letter)(c))
|
||||
&& w0.chars().all(|c| c.is_alphabetic() || (rules.script.is_letter)(c) || crate::indic::is_joiner(c))
|
||||
&& w0 == w1
|
||||
&& (rules.flag_repeat)(w0)
|
||||
// The words a language repeats on purpose are listed without joiners (`જલ્દી`), so
|
||||
// `જલ્` U+200D `દી` twice is the same intentional repeat.
|
||||
&& (rules.flag_repeat)(&w0.replace(crate::indic::is_joiner, ""))
|
||||
{
|
||||
v.push(issue(rules, *a0, *b1, format!("{}: “{w1}”", rules.repeated_word), vec![w0.to_string()]));
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ description = "Source-level platform regression guards, test deadlines, hostile-
|
||||
publish = false
|
||||
|
||||
[features]
|
||||
# `mcp::McpChild`: an MCP stdio test client.
|
||||
mcp = ["dep:serde_json"]
|
||||
# Pinned-corpus manifests and the `corpus::pinned` test gate (native only).
|
||||
corpus = ["dep:sha2", "dep:libc"]
|
||||
# `font-coverage`: `skip::craft_fonts_cover`, which parses font data with skrifa.
|
||||
@@ -19,10 +21,24 @@ sha2 = { version = "0.10", default-features = false, features = ["std"], optiona
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
skrifa = { workspace = true, optional = true }
|
||||
toml = { version = "1", default-features = false, features = ["parse", "serde", "std"] }
|
||||
serde_json = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = { version = "0.2", optional = true }
|
||||
rustix = { version = "1.1", default-features = false, features = ["std", "fs"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
[[test]]
|
||||
name = "mcp"
|
||||
required-features = ["mcp"]
|
||||
|
||||
[[test]]
|
||||
name = "mcp_child"
|
||||
harness = false
|
||||
required-features = ["mcp"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+164
-20
@@ -99,25 +99,40 @@ fn no_std_instant_in_code_the_web_build_runs() {
|
||||
}
|
||||
```
|
||||
|
||||
## Test fonts
|
||||
|
||||
The `fonts` module makes test fonts from font bytes the caller supplies. It reads no file and no environment variable, prints nothing, and builds for `wasm32-unknown-unknown`.
|
||||
|
||||
- **`fonts::rename_family(bytes, from, to)`** returns a copy of one standalone face with the family name `from` replaced by `to`, which must have the same length in UTF-16 code units. It changes the family name records (name IDs 1, 16 and 21) whose value is `from`, and full names (ID 4) that are `from` or start with `from` and a space. At least one family record must hold `from`. It reads UTF-16BE and Macintosh Roman records, writes only ASCII names into Macintosh Roman records, leaves the PostScript name (ID 6), other names and other tables as they are, and writes the `name` table checksum and the `head` table's `checkSumAdjustment`.
|
||||
- **`fonts::collection(faces)`** returns a TrueType collection (TTC 1.0) holding standalone faces. Each face gets its own copy of every table, tables start on four-byte boundaries, offsets count from the start of the collection, `checkSumAdjustment` is zero, and every table checksum matches the bytes in the collection.
|
||||
|
||||
Both return a `fonts::FontError` instead of panicking: names of different lengths, a name that no family record holds, a face shorter than its table directory, a table or name string out of range, a collection given as a face, or output past the 4 GiB a collection's offsets reach. The layouts come from the OpenType font file and `name` table chapters: <https://learn.microsoft.com/en-us/typography/opentype/spec/otff> and <https://learn.microsoft.com/en-us/typography/opentype/spec/name>.
|
||||
|
||||
The tests that call the copies in VectorCraft, DesignCraft and WordCraft need each app's font database and its bundled fonts, so they stay in the apps. `tests/it/fonts.rs` tests the module on faces it assembles from bytes.
|
||||
|
||||
## deadline
|
||||
|
||||
The `deadline` module is not built for `wasm32`.
|
||||
|
||||
`with_deadline(limit, label, f)` runs `f` on its own thread and returns its value. When `f` does not
|
||||
finish within the limit, the test fails with a message that names `label`, the limit and the variable
|
||||
that sets it. A panic in `f` is raised again in the test with its original payload. The limit counts
|
||||
from the call, including the time spent starting the thread. When `f` returns or panics after the
|
||||
limit has passed, the test fails with the label and the limit, and with the panic's message if it has
|
||||
one.
|
||||
The limits in this module guard against a hang. Elapsed time does not decide a result: a test fails on
|
||||
a limit only when nothing has arrived by then.
|
||||
|
||||
`wait_until(limit, what, cond)` calls `cond` on the test's thread until it returns `true`. It calls
|
||||
`cond` at once, then after pauses that start at 1 ms and double up to 50 ms, and does not call it
|
||||
again once the limit has passed. When the limit passes first, or `cond` returns `true` only after the
|
||||
limit has passed, the test fails with a message that names `what`.
|
||||
`with_deadline(limit, label, f)` runs `f` on its own thread and returns its value. A panic in `f` is
|
||||
raised again in the test with its original payload. A value or panic that arrives after the limit is
|
||||
still the result. When `f` has neither returned nor panicked within the limit, the test fails with a
|
||||
message that names `label`, the limit and the variable that sets it. The limit counts from the start
|
||||
of the thread.
|
||||
|
||||
`wait_until(limit, what, &signal, cond)` calls `cond` on the test's thread at once, and again each
|
||||
time another thread calls `signal.raise()`, until `cond` returns `true`. The thread that changes the
|
||||
state `cond` reads raises the `Signal` after each change. A raise that comes while `cond` runs makes
|
||||
`wait_until` call `cond` again straight after. The limit counts from the start of the call. When the
|
||||
limit has passed and the latest call of `cond` returned `false`, the test fails with a message that
|
||||
names `what`, even if the signal is still being raised.
|
||||
|
||||
```rust
|
||||
use std::time::Duration;
|
||||
use craft_testkit::deadline::{DeadlineLimit, wait_until, with_deadline};
|
||||
use craft_testkit::deadline::{DeadlineLimit, Signal, wait_until, with_deadline};
|
||||
|
||||
// The default of 30 s; CRAFT_TEST_TIMEOUT_SECS replaces it.
|
||||
let pixels = with_deadline(Duration::from_secs(30), "decode seed 7", move || decode(&bytes));
|
||||
@@ -126,7 +141,9 @@ let pixels = with_deadline(Duration::from_secs(30), "decode seed 7", move || dec
|
||||
let limit = DeadlineLimit::new(Duration::from_secs(30)).with_variable("FILMCRAFT_HOSTILE_TIMEOUT_SECS");
|
||||
with_deadline(limit, "hostile input 12", move || parse(&input));
|
||||
|
||||
wait_until(Duration::from_secs(10), "the export to finish", || job.is_done());
|
||||
// The export job calls `done.raise()` after it changes its state.
|
||||
let done = Signal::new();
|
||||
wait_until(Duration::from_secs(10), "the export to finish", &done, || job.is_done());
|
||||
```
|
||||
|
||||
### The limit variable
|
||||
@@ -150,12 +167,14 @@ calls this module's.
|
||||
|
||||
### Limits
|
||||
|
||||
- A body that runs past its limit fails the test, but its thread is left running until the test
|
||||
process exits. A body that never returns can keep the test binary alive after its tests finish.
|
||||
- `wait_until` checks its limit only between calls of `cond`. A `cond` that blocks is not interrupted,
|
||||
so it must return promptly.
|
||||
- Neither function returns elapsed time. Tests of this crate use channel handshakes, and the only time
|
||||
bounds in them are the limits under test.
|
||||
- When a body has no result within its limit, the test fails, but the body's thread is left running
|
||||
until the test process exits. A body that never returns can keep the test binary alive after its
|
||||
tests finish.
|
||||
- A `cond` that blocks is not interrupted, so it must return promptly.
|
||||
- A state change that nobody signals is not seen: when the signal is not raised, `wait_until` fails
|
||||
at the limit even if `cond` would now return `true`.
|
||||
- Neither function returns elapsed time. Tests of this crate use channel handshakes and an injected
|
||||
wait in place of the limits.
|
||||
|
||||
## hostile
|
||||
|
||||
@@ -169,8 +188,10 @@ yields no copies. `mutations` and `Rng` build for `wasm32`.
|
||||
|
||||
`hammer(&config, seed, parse)` runs `parse` on the unmodified seed, on every truncation of it
|
||||
(lengths 0 to one less than its length), and on `mutations(seed, rounds)`. The cases run one after
|
||||
another on one worker thread, and the test's thread fails the test when a case runs past its limit.
|
||||
A case that finishes after its limit also fails the test. The test fails on the first case that
|
||||
another on one worker thread, and the test's thread fails the test when a case is still running once
|
||||
its limit has passed since it started. The limit guards against a hang: a case that finishes passes
|
||||
or fails on what `parse` did, however long it took, and the number of cases depends only on the seed,
|
||||
the rounds and the divisor. The test fails on the first case that
|
||||
panics or does not finish, with a message that names the config's label, the case
|
||||
(`the unmodified seed`, `truncation to N` or the edits), the input's length and the panic's message.
|
||||
`parse` must be `Fn(&[u8]) + Send + Sync + 'static`, since a case that does not finish keeps running
|
||||
@@ -237,6 +258,77 @@ Changes from `craft-media-testkit`'s `hammer`:
|
||||
- `parse` is owned and runs on a worker thread. A closure that borrows from the test needs its data
|
||||
moved or shared with an `Arc`.
|
||||
|
||||
## fixtures
|
||||
|
||||
The `fixtures` module (native targets only) generates missing test fixtures and shares them between test runs and processes:
|
||||
|
||||
- `fixtures_root(var)` is the nonempty value of `var` (default `CRAFT_FIXTURES_DIR`) or `<workspace>/target/fixtures`. The workspace is the one that holds the package under test, found from the `CARGO_MANIFEST_DIR` that Cargo and nextest set when they run tests: the folder named by the package's `package.workspace` key, or else the nearest folder whose `Cargo.toml` has a `[workspace]` table. A test binary run without `CARGO_MANIFEST_DIR` needs the root variable. `CARGO_TARGET_DIR` does not move the root. `fixtures_dir(sub, var)` creates a folder below the root and rejects an absolute `sub`, one containing `..`, and on Windows one with a drive inside it (`group\C:outside`). It creates the folder one level at a time and returns an error, without creating the rest, when a level resolves outside the root or is not a folder, for example a symbolic link or junction under the root that points elsewhere. The check uses paths, so it does not detect a folder that another process replaces with a link while the call runs or after it returns.
|
||||
- `temp_path(out)` creates a new, empty sibling of `out` with `create_new`, keeping the extension. A name that already exists is never reused.
|
||||
- `publish(tmp, out)` moves a nonempty regular file into place while holding a lock on `<out>.fixture-lock`. When `out` is already a nonempty regular file, it is kept and `tmp` is removed; the check reads only the type and length of `out`, so a nonempty `out` that cannot be read is kept too. A directory at `out` is an error, and so are an `out` whose name ends with `.fixture-lock` and a file system that does not support the lock.
|
||||
- `generate(out, required_var, make)` and `generate_with(out, required, make)` return a cached fixture without calling `make`, or run `make` on a claimed temporary file and publish it. The temporary file is removed when `make` fails, panics, writes nothing or makes `out` name the temporary file, and such an `out` is not returned. When `make` fails after another process published `out`, the published file is returned. A fixture that cannot be made follows the [skip](#skip) rule with the required variable `generate` is given (default `CRAFT_TEST_REQUIRED`): unset or empty prints `SKIPPED: <reason>` on standard error and returns `None`, `1` fails the test, and any other value, `0` included, fails the test as a configuration error. Only `generate` reads the required variable. `generate_with` uses the caller's `required` value instead: `true` fails the test, and `false` prints the skip line and returns `None`.
|
||||
- `run_generator(cmd, env, max_output)` runs a generator with `env` added to the child's environment only, and keeps at most `max_output` bytes of each output stream (`DEFAULT_MAX_OUTPUT` is 64 KiB). The variables and stream settings stay on `cmd`, so use a new `Command` for each call that needs a clean environment.
|
||||
- `report(name, status)` and `generate_and_report(name, outputs, generate)` print one of these lines on standard output, which FilmCraft's `cargo xtask fixtures` counts:
|
||||
|
||||
```text
|
||||
FIXTURE made <name>
|
||||
FIXTURE cached <name>
|
||||
FIXTURE skipped <name>
|
||||
```
|
||||
|
||||
A complete fixture is a nonempty regular file. A consumer that needs a valid media file checks its format after generation.
|
||||
|
||||
## mcp
|
||||
|
||||
The `mcp` feature adds `craft_testkit::mcp` and the `serde_json` dependency. The module is built on every target except `wasm32`, and it opens no network connection.
|
||||
|
||||
`McpChild::spawn(path, args, env)` starts an MCP server program with its stdin and stdout piped. The variables in `env` are set for the child only; the test process's environment is not changed. `McpChild::connect(reader, writer, limits)` talks to a server that runs in the test process; its reading thread stops when the server drops its end of `reader`, or at the next line the server writes after `close()`. Each message is one line of JSON-RPC 2.0, as the [MCP stdio transport](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports) describes.
|
||||
|
||||
| Call | What it does |
|
||||
|---|---|
|
||||
| `initialize(version)` | Sends `initialize` with `version` (`mcp::PROTOCOL_VERSION` is `2025-06-18`), validates the reply, then sends `notifications/initialized`. The result must contain `capabilities` and `serverInfo` objects, with string `serverInfo.name` and `serverInfo.version` fields. Invalid fields return `Protocol` and close the connection. A reply with another version returns `UnsupportedVersion` and closes the connection. |
|
||||
| `request(method, params)`, `request_within(.., timeout)` | Sends a request with a new numeric id and returns the `result` of the reply with that id. Well-formed replies with other ids are skipped. An error reply returns `Rpc` with its code, message and data, and the connection stays usable. |
|
||||
| `call_tool(name, args)`, `call_tool_within(.., timeout)` | Sends `tools/call` and returns the tool result unchanged, `content` and `isError` included. |
|
||||
| `list_tools()` | Reads `tools/list` pages through `nextCursor` and returns the tools as sent. More than `max_pages` pages returns `TooManyPages`, and tools that add up to more than `max_line_bytes` of JSON return `ToolListTooLarge`. |
|
||||
| `notify(method, params)` | Sends a notification, which has no id and gets no reply. |
|
||||
| `take_notifications()` | Returns the notifications kept so far without waiting. |
|
||||
| `close()` | Closes the child's stdin, waits for it to exit, stops it after the grace period, and returns its exit status, whether it was stopped, and the stderr kept. After the child exits, it waits up to 5 s for the rest of stderr to be read. |
|
||||
|
||||
Tool results require a `content` array. Optional `isError` must be a boolean, and optional
|
||||
`structuredContent` and `_meta` must be objects. Both tool helpers reject a malformed envelope
|
||||
with `Protocol` and close the connection. Requests and notifications from the server require
|
||||
object-valued `params` when that field is present. `close()` drains and discards stdout while
|
||||
waiting for the child; incoming output does not extend the grace period.
|
||||
|
||||
While a call waits, the client answers the child's `ping` with an empty result and its other requests with error -32601. Server requests require string or integer IDs. A line on stdout that is not a JSON-RPC 2.0 message, a reply with neither or both of `result` and `error`, a line over the length limit, a missed deadline and the end of stdout each return an error and close the connection; later calls return `Closed`. A terminal failure discards queued writes and unread messages. A write already in progress may finish. After the end of stdout or an I/O error, `close()` or dropping the connection reaps the child. Other terminal failures stop and reap it immediately. Dropping an `McpChild` stops and reaps a child that is still running. Setup returns a `Result` and nothing in the module panics.
|
||||
|
||||
`McpLimits` holds the limits. These defaults are the crate's own values:
|
||||
|
||||
| Field | Default | Range |
|
||||
|---|---|---|
|
||||
| `max_line_bytes` | 64 MiB, for one stdout line, for the whole `list_tools` result, and for the total compact JSON bytes of retained notifications | at least 1 |
|
||||
| `request_timeout` | 30 s | more than zero, at most 1 hour |
|
||||
| `initialize_timeout` | 60 s | more than zero, at most 1 hour |
|
||||
| `close_grace` | 2 s | at most 1 hour |
|
||||
| `max_pages` | 64 | at least 1 |
|
||||
| `max_notifications` | 0 (notifications are not kept); oldest entries are dropped to satisfy both this count and the `max_line_bytes` byte budget | at most 4096 |
|
||||
| `stderr_tail_bytes` | 0 (stderr goes to the null device); otherwise the last bytes written are kept | at most 16 MiB |
|
||||
|
||||
A notification whose compact JSON encoding exceeds `max_line_bytes` is discarded without removing previously retained notifications.
|
||||
|
||||
`McpLimits::timeouts_from_var(name)` sets both deadlines from a variable that holds a whole number of seconds from 1 to 3600; `mcp::TIMEOUT_VAR` (`CRAFT_TEST_MCP_TIMEOUT_SECS`) is the default name. Any other value returns an error.
|
||||
|
||||
```rust
|
||||
use craft_testkit::mcp::{McpChild, PROTOCOL_VERSION};
|
||||
|
||||
let mut mcp = McpChild::spawn(env!("CARGO_BIN_EXE_my-cli"), ["mcp"], [("MYCRAFT_CONFIG_DIR", dir.path())])?;
|
||||
mcp.initialize(PROTOCOL_VERSION)?;
|
||||
let result = mcp.call_tool("doc.new", serde_json::json!({}))?;
|
||||
assert!(!result["isError"].as_bool().unwrap_or(false));
|
||||
assert!(mcp.close()?.status.is_some_and(|s| s.success()));
|
||||
```
|
||||
|
||||
The tests that start a real child are in `tests/mcp_child.rs`, a target with `harness = false`: the child is that test program, and the standard harness writes its own lines on stdout. Both test targets build to nothing on `wasm32`.
|
||||
|
||||
## corpus
|
||||
|
||||
`craft_testkit::corpus` is behind the `corpus` feature and is native only. It parses a corpus manifest and checks a folder of files against it.
|
||||
@@ -349,6 +441,16 @@ PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copie
|
||||
|---|---|---|---|
|
||||
| `guards` | storytold/craft-libs#163 (zachshallbetter), with the rules of PhotoCraft's shader float test and FilmCraft's web clock test | `crates/testkit/src/guards.rs` | `e92825e427` |
|
||||
|
||||
### fonts
|
||||
|
||||
| Module | Source | Path | Commit |
|
||||
|---|---|---|---|
|
||||
| `fonts` | storytold/vectorcraft, `rename` and `collection` | `crates/text/src/tests/sysfonts.rs` | `bada8e1710` |
|
||||
| `fonts` | storytold/vectorcraft, `renamed` | `crates/testkit/src/fonts.rs` | `bada8e1710` |
|
||||
| `fonts` | storytold/designcraft, the family renaming and `collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` | `8b169f8ee7` |
|
||||
| `fonts` | storytold/wordcraft, `renamed_to` and `collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` | `f8c66d0692` |
|
||||
| `fonts` | storytold/wordcraft, `renamed` | `crates/fonts/src/fontdb/user/tests.rs` | `f8c66d0692` |
|
||||
|
||||
### deadline
|
||||
|
||||
| Code | Repository | Path | SHA |
|
||||
@@ -368,6 +470,21 @@ PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copie
|
||||
|---|---|---|---|
|
||||
| `Rng`, the edits of `mutations` and `hammer` | storytold/craft-libs | `crates/media-testkit/src/hostile.rs` | `75a654f4` |
|
||||
|
||||
### fixtures
|
||||
|
||||
| Part | Repository | Path | Commit |
|
||||
|---|---|---|---|
|
||||
| Locations, publication with winner reuse, reporting, and the moved tests | storytold/filmcraft | `crates/testkit/src/fixtures.rs` | `e4ab3c6a99` |
|
||||
| `generate_with` and the required rule, with `failed_generator_skips_when_optional` and `failed_generator_fails_when_required` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` | `75a654f4f8` |
|
||||
|
||||
### mcp
|
||||
|
||||
| Code | Repository | Path | SHA |
|
||||
|---|---|---|---|
|
||||
| `Conn`, `request`, `call_tool`, `MAX_LINE`, deadlines, and the 14 tests of `child_tests.rs`, written again here | storytold/craft-ai-integrations | `crates/ai-mcp/src/apps/child.rs` | `e8b31cb0` |
|
||||
| The MCP end-to-end helpers | storytold/vectorcraft | `apps/vectorcraft-cli/tests/it/mcp_e2e.rs` | `460d2119` |
|
||||
| `mcp_recv` | storytold/photocraft | `apps/photocraft-cli/tests/it/cli.rs` | `58d11d91` |
|
||||
|
||||
### corpus
|
||||
|
||||
| Code | Repository | Path | SHA |
|
||||
@@ -401,6 +518,14 @@ PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copie
|
||||
| PhotoCraft | `wgsl_float_literals` | `crates/gpu/src/tests.rs` scanner | Not started |
|
||||
| FilmCraft | `std_instant` | `crates/engine/src/wasm_clock_tests.rs` search | Not started |
|
||||
|
||||
### fonts
|
||||
|
||||
| Consumer | Guard | Replaces | State |
|
||||
|---|---|---|---|
|
||||
| VectorCraft | `fonts::rename_family`, `fonts::collection` | `crates/text/src/tests/sysfonts.rs` and `crates/testkit/src/fonts.rs` helpers | Not started |
|
||||
| DesignCraft | `fonts::rename_family`, `fonts::collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` helpers | Not started |
|
||||
| WordCraft | `fonts::rename_family`, `fonts::collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` and `crates/fonts/src/fontdb/user/tests.rs` helpers | Not started |
|
||||
|
||||
### rng
|
||||
|
||||
| Consumer | Code it replaces | State |
|
||||
@@ -434,6 +559,25 @@ An adoption keeps the variable name the app uses today.
|
||||
CADCraft's and TextureCraft's loops make other edits than `mutations`. Their adoptions say which
|
||||
cases change, and keep the test names.
|
||||
|
||||
### fixtures
|
||||
|
||||
| Consumer | Copy it replaces | State |
|
||||
|---|---|---|
|
||||
| FilmCraft | `crates/testkit/src/fixtures.rs` (passes `FILMCRAFT_FIXTURES_DIR` and `FILMCRAFT_REQUIRE_ORACLES`) | Not switched |
|
||||
| EffectCraft | `crates/media/tests/it/footage.rs` | Not switched |
|
||||
| craft-libs `audio` and `video` tests | `crates/audio/tests/codecs/testkit.rs`, `crates/video/tests/vp8/common/mod.rs` | Not switched |
|
||||
| `craft-media-testkit` | its `fixtures` module and `temp_path` (keeps its public names) | Not switched |
|
||||
|
||||
### mcp
|
||||
|
||||
| Consumer | Code it replaces | State |
|
||||
|---|---|---|
|
||||
| VectorCraft | `apps/vectorcraft-cli/tests/it/mcp_e2e.rs` | Pending |
|
||||
| PhotoCraft | `apps/photocraft-cli/tests/it/cli.rs` | Pending |
|
||||
| CADCraft, DeckCraft, DesignCraft, EffectCraft | the MCP helpers in their CLI tests | Pending |
|
||||
| FigCraft, FilmCraft, GridCraft, LightCraft, PdfCraft, SoundCraft | the MCP helpers in their CLI tests | Pending |
|
||||
| craft-ai-integrations | `crates/ai-mcp/src/apps/child.rs`, production code | Kept as it is |
|
||||
|
||||
### corpus
|
||||
|
||||
| Consumer | Code it replaces | State |
|
||||
|
||||
+254
-245
@@ -1,11 +1,18 @@
|
||||
//! Limits on how long a test waits.
|
||||
//!
|
||||
//! [`with_deadline`] runs a test body on its own thread and returns its value. When the body does not
|
||||
//! finish within the limit, the test fails with the call's label, the limit and the variable that sets
|
||||
//! it. A panic in the body is raised again in the test with its original payload.
|
||||
//! A limit here guards against a hang and does not decide a result. A value or panic that a body
|
||||
//! produces is the call's result whenever it arrives, and a test fails on the limit only when nothing
|
||||
//! has arrived by then.
|
||||
//!
|
||||
//! [`wait_until`] calls a condition on the test's thread until it returns `true`, pausing between
|
||||
//! calls, and fails the test with its description when the limit passes first.
|
||||
//! [`with_deadline`] runs a test body on its own thread and returns its value. A panic in the body is
|
||||
//! raised again in the test with its original payload. When the body has neither returned nor
|
||||
//! panicked within the limit, the test fails with the call's label, the limit and the variable that
|
||||
//! sets it.
|
||||
//!
|
||||
//! [`wait_until`] calls a condition on the test's thread, and calls it again each time another
|
||||
//! thread raises the [`Signal`] the call waits on. It returns when the condition returns `true`, and
|
||||
//! fails the test with its description when the limit has passed since the call began and the latest
|
||||
//! call of the condition returned `false`.
|
||||
//!
|
||||
//! A limit is a default [`Duration`] and the name of a variable that replaces it. A plain `Duration`
|
||||
//! reads [`DEFAULT_VARIABLE`]; [`DeadlineLimit::with_variable`] names another one. The variable holds
|
||||
@@ -13,30 +20,23 @@
|
||||
//! fractional, not Unicode, zero, or larger than a `u64` fails the test that reads it, as does a zero
|
||||
//! default and a limit past the latest time the platform's clock can represent.
|
||||
//!
|
||||
//! Neither function can stop code that does not return. A body that runs past its limit fails the
|
||||
//! test, and its thread is left running until the test process exits. A condition that blocks is
|
||||
//! not interrupted: [`wait_until`] checks its limit only between calls, so a condition must return
|
||||
//! promptly.
|
||||
//! Neither function can stop code that does not return. When a body does not finish within its
|
||||
//! limit, the test fails and the body's thread is left running until the test process exits. A
|
||||
//! condition that blocks is not interrupted, so a condition must return promptly.
|
||||
|
||||
use std::any::Any;
|
||||
use std::ffi::OsString;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
|
||||
use std::sync::mpsc::{self, RecvTimeoutError, Sender};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The variable a limit reads unless [`DeadlineLimit::with_variable`] names another.
|
||||
pub const DEFAULT_VARIABLE: &str = "CRAFT_TEST_TIMEOUT_SECS";
|
||||
|
||||
/// The first pause of [`wait_until`] between two calls of its condition.
|
||||
const FIRST_PAUSE: Duration = Duration::from_millis(1);
|
||||
|
||||
/// The longest pause of [`wait_until`]: each pause doubles up to this.
|
||||
const MAX_PAUSE: Duration = Duration::from_millis(50);
|
||||
|
||||
/// The name of the thread [`with_deadline`] runs a body on.
|
||||
const WORKER_NAME: &str = "craft-testkit deadline";
|
||||
|
||||
@@ -91,15 +91,50 @@ impl From<Duration> for DeadlineLimit<'static> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f` on its own thread and returns its value, failing the calling test when `f` does not
|
||||
/// finish within `limit`.
|
||||
/// A signal that [`wait_until`] waits on: the thread that changes the state a condition reads raises
|
||||
/// it after each change, and every call waiting on it then calls its condition again.
|
||||
///
|
||||
/// The failure names `label`, the limit and the variable that sets it. A panic in `f` is raised
|
||||
/// again here with its original payload. The limit is read and checked before `f` starts, and a
|
||||
/// limit that is not valid fails the test without running `f`. The limit counts from the call, so
|
||||
/// the time spent starting the thread counts against it. When `f` returns or panics after the limit
|
||||
/// has passed, the test fails with the label and the limit, and with the panic's message if it has
|
||||
/// one. When the limit passes, the thread running `f` is left running.
|
||||
/// ```
|
||||
/// use craft_testkit::deadline::Signal;
|
||||
///
|
||||
/// let signal = Signal::new();
|
||||
/// // A raise with no call waiting is kept: the next wait sees it and calls its condition again.
|
||||
/// signal.raise();
|
||||
/// ```
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Signal {
|
||||
/// How many times the signal has been raised, wrapping.
|
||||
raised: Mutex<u64>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
impl Signal {
|
||||
/// A signal that has not been raised.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Wakes every [`wait_until`] call waiting on this signal, so that each calls its condition again.
|
||||
pub fn raise(&self) {
|
||||
let mut raised = self.lock();
|
||||
*raised = raised.wrapping_add(1);
|
||||
self.changed.notify_all();
|
||||
}
|
||||
|
||||
fn lock(&self) -> MutexGuard<'_, u64> {
|
||||
self.raised.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f` on its own thread and returns its value, failing the calling test when `f` has neither
|
||||
/// returned nor panicked within `limit`.
|
||||
///
|
||||
/// A panic in `f` is raised again here with its original payload. The limit guards against a hang:
|
||||
/// a value or panic that `f` produces is the result whenever it arrives, and the test fails on the
|
||||
/// limit only when `f` has produced neither by then. That failure names `label`, the limit and the
|
||||
/// variable that sets it, and the thread running `f` is left running. The limit is read and checked
|
||||
/// before `f` starts, and a limit that is not valid fails the test without running `f`. The limit
|
||||
/// counts from the start of the thread running `f`.
|
||||
///
|
||||
/// ```
|
||||
/// use std::time::Duration;
|
||||
@@ -112,46 +147,51 @@ impl From<Duration> for DeadlineLimit<'static> {
|
||||
#[allow(clippy::panic)]
|
||||
#[track_caller]
|
||||
pub fn with_deadline<'a, T: Send + 'static>(limit: impl Into<DeadlineLimit<'a>>, label: &str, f: impl FnOnce() -> T + Send + 'static) -> T {
|
||||
let start = Instant::now();
|
||||
match run_with_deadline(limit.into(), label, f, read_variable, spawn_worker, Arc::new(move || start.elapsed())) {
|
||||
match run_with_deadline(limit.into(), label, f, read_variable, spawn_worker, |rx, limit| rx.recv_timeout(limit)) {
|
||||
Ok(value) => value,
|
||||
Err(Failure::Panic(payload)) => resume_unwind(payload),
|
||||
Err(Failure::Message(message)) => panic!("{message}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls `cond` on the calling thread until it returns `true`, failing the calling test when the
|
||||
/// limit passes first.
|
||||
/// Calls `cond` on the calling thread, and again each time `signal` is raised, until it returns
|
||||
/// `true`, failing the calling test when the limit has passed since the call began and the latest
|
||||
/// call of `cond` returned `false`.
|
||||
///
|
||||
/// `cond` is called at once, and then after pauses that grow from 1 ms to 50 ms, but not again once
|
||||
/// the limit has passed. The failure names `what`, the limit and the variable that sets it. A `true`
|
||||
/// that `cond` returns after the limit has passed also fails the test. A panic in `cond` reaches the
|
||||
/// caller unchanged. `cond` runs on the calling thread and is not interrupted, so it must return
|
||||
/// promptly.
|
||||
/// `cond` is called at once. A raise that comes while `cond` runs is not lost: `cond` is called
|
||||
/// again straight after. The limit guards against a hang and counts from the start of the call, so
|
||||
/// a signal that keeps being raised while `cond` stays `false` still fails the test. `cond` is
|
||||
/// called before the limit is checked, so a condition that holds is never failed by it. The failure
|
||||
/// names `what`, the limit and the
|
||||
/// variable that sets it. A panic in `cond` reaches the caller unchanged. `cond` runs on the calling
|
||||
/// thread and is not interrupted, so it must return promptly. The threads that change what `cond`
|
||||
/// reads raise `signal` after each change.
|
||||
///
|
||||
/// ```
|
||||
/// use std::sync::atomic::{AtomicBool, Ordering};
|
||||
/// use std::time::Duration;
|
||||
/// use craft_testkit::deadline::wait_until;
|
||||
/// use craft_testkit::deadline::{Signal, wait_until};
|
||||
///
|
||||
/// let ready = AtomicBool::new(false);
|
||||
/// let signal = Signal::new();
|
||||
/// std::thread::scope(|s| {
|
||||
/// s.spawn(|| ready.store(true, Ordering::SeqCst));
|
||||
/// wait_until(Duration::from_secs(30), "the worker to start", || ready.load(Ordering::SeqCst));
|
||||
/// s.spawn(|| {
|
||||
/// ready.store(true, Ordering::SeqCst);
|
||||
/// signal.raise();
|
||||
/// });
|
||||
/// wait_until(Duration::from_secs(30), "the worker to start", &signal, || ready.load(Ordering::SeqCst));
|
||||
/// });
|
||||
/// ```
|
||||
// Failing the calling test is what this function is for.
|
||||
#[allow(clippy::panic)]
|
||||
#[track_caller]
|
||||
pub fn wait_until<'a>(limit: impl Into<DeadlineLimit<'a>>, what: &str, mut cond: impl FnMut() -> bool) {
|
||||
pub fn wait_until<'a>(limit: impl Into<DeadlineLimit<'a>>, what: &str, signal: &Signal, mut cond: impl FnMut() -> bool) {
|
||||
let limit = limit.into();
|
||||
let start = Instant::now();
|
||||
let resolved = match resolve(&limit, read_variable, start) {
|
||||
let resolved = match resolve(&limit, read_variable, Instant::now()) {
|
||||
Ok(resolved) => resolved,
|
||||
Err(error) => panic!("waiting for {what}: {error}"),
|
||||
};
|
||||
let mut elapsed = || start.elapsed();
|
||||
if let Err(message) = poll_until(&resolved, what, &mut cond, &mut elapsed, &mut thread::sleep) {
|
||||
if let Err(message) = wait_for_signal(&resolved, what, signal, &mut cond, Instant::now, wait_for_raise) {
|
||||
panic!("{message}");
|
||||
}
|
||||
}
|
||||
@@ -265,8 +305,8 @@ fn spawn_worker(job: Job, done: Sender<()>) -> io::Result<()> {
|
||||
.map(drop)
|
||||
}
|
||||
|
||||
/// The body's result and the clock reading when it finished, filled in by the worker.
|
||||
type Slot<T> = Arc<Mutex<Option<(thread::Result<T>, Duration)>>>;
|
||||
/// The body's result, filled in by the worker.
|
||||
type Slot<T> = Arc<Mutex<Option<thread::Result<T>>>>;
|
||||
|
||||
/// How a [`with_deadline`] call failed.
|
||||
enum Failure {
|
||||
@@ -276,52 +316,32 @@ enum Failure {
|
||||
Message(String),
|
||||
}
|
||||
|
||||
/// A clock that returns the time since a [`with_deadline`] call started.
|
||||
type Clock = Arc<dyn Fn() -> Duration + Send + Sync>;
|
||||
|
||||
/// The text of a panic payload that holds a message.
|
||||
fn panic_text(payload: &(dyn Any + Send)) -> Option<&str> {
|
||||
payload.downcast_ref::<String>().map(String::as_str).or_else(|| payload.downcast_ref::<&str>().copied())
|
||||
}
|
||||
|
||||
/// [`with_deadline`] with the variable lookup, the thread start and the clock passed in. Starting
|
||||
/// the worker counts against the limit. The worker stores the body's result with the clock reading
|
||||
/// when it finished, under a lock, and then sends on the channel `spawn` receives. When the wait
|
||||
/// times out, the stored result is still used if it is there, so a body that finished in time passes
|
||||
/// even when its thread sends late.
|
||||
/// [`with_deadline`] with the variable lookup, the thread start and the wait for the worker passed
|
||||
/// in. The worker stores the body's result under a lock and then sends on the channel `spawn`
|
||||
/// receives. `wait` waits on that channel for at most the limit. Whatever `wait` returns, a stored
|
||||
/// result is the call's result, so the limit fails the call only when the body has produced nothing.
|
||||
fn run_with_deadline<T: Send + 'static>(
|
||||
limit: DeadlineLimit<'_>,
|
||||
label: &str,
|
||||
f: impl FnOnce() -> T + Send + 'static,
|
||||
lookup: impl FnOnce(&str) -> Option<OsString>,
|
||||
spawn: impl FnOnce(Job, Sender<()>) -> io::Result<()>,
|
||||
clock: Clock,
|
||||
wait: impl FnOnce(&Receiver<()>, Duration) -> Result<(), RecvTimeoutError>,
|
||||
) -> Result<T, Failure> {
|
||||
let resolved = resolve(&limit, lookup, Instant::now()).map_err(|error| Failure::Message(format!("{label}: {error}")))?;
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let slot: Slot<T> = Arc::new(Mutex::new(None));
|
||||
let worker_slot = Arc::clone(&slot);
|
||||
let worker_clock = Arc::clone(&clock);
|
||||
let job: Job = Box::new(move || {
|
||||
let result = catch_unwind(AssertUnwindSafe(f));
|
||||
// The clock is read under the lock: once the caller finds the slot empty after its limit,
|
||||
// any later reading is past the limit too.
|
||||
let mut stored = worker_slot.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
*stored = Some((result, worker_clock()));
|
||||
*worker_slot.lock().unwrap_or_else(PoisonError::into_inner) = Some(result);
|
||||
});
|
||||
spawn(job, tx).map_err(|error| Failure::Message(format!("{label}: could not start the worker thread: {error}")))?;
|
||||
let waited = rx.recv_timeout(resolved.limit.saturating_sub(clock()));
|
||||
let waited = wait(&rx, resolved.limit);
|
||||
let stored = slot.lock().unwrap_or_else(PoisonError::into_inner).take();
|
||||
match (stored, waited) {
|
||||
(Some((result, finished)), _) if finished > resolved.limit => {
|
||||
let panicked = match &result {
|
||||
Ok(_) => String::new(),
|
||||
Err(payload) => format!(" (it panicked: {})", panic_text(payload.as_ref()).unwrap_or("a payload that is not a message")),
|
||||
};
|
||||
Err(Failure::Message(format!("{label} finished only after its limit of {resolved}{panicked}")))
|
||||
}
|
||||
(Some((Ok(value), _)), _) => Ok(value),
|
||||
(Some((Err(payload), _)), _) => Err(Failure::Panic(payload)),
|
||||
(Some(Ok(value)), _) => Ok(value),
|
||||
(Some(Err(payload)), _) => Err(Failure::Panic(payload)),
|
||||
(None, Err(RecvTimeoutError::Timeout)) => {
|
||||
Err(Failure::Message(format!("{label} did not finish within {resolved}; its thread is left running")))
|
||||
}
|
||||
@@ -329,44 +349,49 @@ fn run_with_deadline<T: Send + 'static>(
|
||||
}
|
||||
}
|
||||
|
||||
/// The loop of [`wait_until`], with the clock and the pause passed in. `elapsed` returns the time
|
||||
/// since the wait started.
|
||||
fn poll_until(
|
||||
/// Waits on `changed` while `raised` still reads `seen`, for at most `limit`. Returns the guard and
|
||||
/// whether the limit passed with no raise.
|
||||
fn wait_for_raise<'g>(changed: &Condvar, raised: MutexGuard<'g, u64>, seen: u64, limit: Duration) -> (MutexGuard<'g, u64>, bool) {
|
||||
let (raised, result) = changed.wait_timeout_while(raised, limit, |count| *count == seen).unwrap_or_else(PoisonError::into_inner);
|
||||
(raised, result.timed_out())
|
||||
}
|
||||
|
||||
/// The loop of [`wait_until`], with the clock and the wait for a raise passed in. The raise count is
|
||||
/// read before each call of `cond`, so a raise during the call ends the next wait at once. The limit
|
||||
/// counts from the start of the loop, and each wait lasts at most the time left.
|
||||
fn wait_for_signal(
|
||||
resolved: &Resolved<'_>,
|
||||
what: &str,
|
||||
signal: &Signal,
|
||||
cond: &mut dyn FnMut() -> bool,
|
||||
elapsed: &mut dyn FnMut() -> Duration,
|
||||
pause: &mut dyn FnMut(Duration),
|
||||
now: impl Fn() -> Instant,
|
||||
wait: impl for<'g> Fn(&Condvar, MutexGuard<'g, u64>, u64, Duration) -> (MutexGuard<'g, u64>, bool),
|
||||
) -> Result<(), String> {
|
||||
let mut next_pause = FIRST_PAUSE;
|
||||
let mut first = true;
|
||||
let start = now();
|
||||
let mut seen = *signal.lock();
|
||||
loop {
|
||||
// After the first call, the condition is called only while the limit has not passed.
|
||||
if !first && elapsed() >= resolved.limit {
|
||||
return Err(format!("timed out waiting for {what} within {resolved}"));
|
||||
}
|
||||
first = false;
|
||||
let held = cond();
|
||||
let spent = elapsed();
|
||||
if held && spent <= resolved.limit {
|
||||
if cond() {
|
||||
return Ok(());
|
||||
}
|
||||
if held {
|
||||
return Err(format!("timed out waiting for {what} within {resolved} (it held only after the limit had passed)"));
|
||||
let remaining = resolved.limit.saturating_sub(now().saturating_duration_since(start));
|
||||
if remaining.is_zero() {
|
||||
return Err(format!("timed out waiting for {what} within {resolved}: the condition still returned false at the limit"));
|
||||
}
|
||||
if spent < resolved.limit {
|
||||
pause(next_pause.min(resolved.limit - spent));
|
||||
let (raised, timed_out) = wait(&signal.changed, signal.lock(), seen, remaining);
|
||||
if timed_out {
|
||||
return Err(format!("timed out waiting for {what} within {resolved}: the signal was not raised after the last check"));
|
||||
}
|
||||
next_pause = next_pause.saturating_mul(2).min(MAX_PAUSE);
|
||||
seen = *raised;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::RefCell;
|
||||
use std::ffi::OsStr;
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
/// A variable no test sets, so the environment cannot lengthen a test's short limit.
|
||||
const UNSET: &str = "CRAFT_TESTKIT_DEADLINE_UNSET_IN_TESTS";
|
||||
@@ -400,6 +425,27 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A wait for the worker that returns at once, as when the limit passes with nothing received.
|
||||
fn limit_passes(_: &Receiver<()>, _: Duration) -> Result<(), RecvTimeoutError> {
|
||||
Err(RecvTimeoutError::Timeout)
|
||||
}
|
||||
|
||||
/// Runs `run_with_deadline` with its limit passing before the body has a result, and returns the
|
||||
/// failure's message. The body runs on its own thread and blocks until the call has returned.
|
||||
fn hung<T: Send + 'static>(limit: DeadlineLimit<'_>, label: &str, value: T) -> String {
|
||||
let (gate, gate_rx) = mpsc::channel::<()>();
|
||||
let (done_tx, done) = mpsc::channel();
|
||||
let body = move || {
|
||||
let _ = gate_rx.recv();
|
||||
done_tx.send(()).unwrap();
|
||||
value
|
||||
};
|
||||
let result = run_with_deadline(limit, label, body, |_| None, spawn_worker, limit_passes);
|
||||
drop(gate);
|
||||
done.recv().unwrap();
|
||||
failure_message(result)
|
||||
}
|
||||
|
||||
/// Runs `child_reads_its_variable` in a child process with `CHILD_VARIABLE` set to `value`, and
|
||||
/// returns what the child printed. The child must fail.
|
||||
fn run_child(value: &OsStr) -> String {
|
||||
@@ -442,21 +488,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "seed 7 byte 3 did not finish within 50ms")]
|
||||
fn a_hang_fails_and_names_the_input() {
|
||||
let (gate, gate_rx) = mpsc::channel::<()>();
|
||||
let (done_tx, done) = mpsc::channel();
|
||||
let result = catch_unwind(AssertUnwindSafe(|| {
|
||||
with_deadline(short(), "seed 7 byte 3", move || {
|
||||
let _ = gate_rx.recv();
|
||||
done_tx.send(()).unwrap();
|
||||
})
|
||||
}));
|
||||
drop(gate);
|
||||
done.recv().unwrap();
|
||||
if let Err(payload) = result {
|
||||
resume_unwind(payload);
|
||||
}
|
||||
let text = hung(short(), "seed 7 byte 3", ());
|
||||
assert!(text.contains("seed 7 byte 3 did not finish within 50ms"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -467,14 +501,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "did not finish within")]
|
||||
fn with_deadline_times_out() {
|
||||
let (gate, gate_rx) = mpsc::channel::<()>();
|
||||
let result = catch_unwind(AssertUnwindSafe(|| with_deadline(short(), "blocked body", move || gate_rx.recv().unwrap_or_default())));
|
||||
drop(gate);
|
||||
if let Err(payload) = result {
|
||||
resume_unwind(payload);
|
||||
}
|
||||
let text = hung(short(), "blocked body", 7u8);
|
||||
assert!(text.contains("did not finish within") && text.contains("its thread is left running"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -492,14 +521,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn timeout_names_this_call_only() {
|
||||
let call = |label: &'static str| {
|
||||
thread::spawn(move || {
|
||||
let (gate, gate_rx) = mpsc::channel::<()>();
|
||||
let result = catch_unwind(AssertUnwindSafe(|| with_deadline(short(), label, move || gate_rx.recv().unwrap_or_default())));
|
||||
drop(gate);
|
||||
message(result.unwrap_err())
|
||||
})
|
||||
};
|
||||
let call = |label: &'static str| thread::spawn(move || hung(short(), label, ()));
|
||||
let first = call("first call");
|
||||
let second = call("second call");
|
||||
let first = first.join().unwrap();
|
||||
@@ -517,13 +539,10 @@ mod tests {
|
||||
7
|
||||
})
|
||||
});
|
||||
let (gate, gate_rx) = mpsc::channel::<()>();
|
||||
let short_call = catch_unwind(AssertUnwindSafe(|| with_deadline(short(), "short call", move || gate_rx.recv().unwrap_or_default())));
|
||||
let text = message(short_call.unwrap_err());
|
||||
let text = hung(short(), "short call", ());
|
||||
assert!(text.contains("short call") && text.contains("50ms") && !text.contains("long call"), "{text}");
|
||||
release.send(()).unwrap();
|
||||
assert_eq!(long_call.join().unwrap(), 7);
|
||||
drop(gate);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -533,7 +552,7 @@ mod tests {
|
||||
ran.store(true, Ordering::SeqCst);
|
||||
Err(io::Error::other("no threads left"))
|
||||
};
|
||||
let result = run_with_deadline(long(), "no thread", || (), |_| None, spawn, Arc::new(|| Duration::ZERO));
|
||||
let result = run_with_deadline(long(), "no thread", || (), |_| None, spawn, limit_passes);
|
||||
let text = failure_message(result);
|
||||
assert!(ran.load(Ordering::SeqCst));
|
||||
assert!(text.contains("no thread: could not start the worker thread: no threads left"), "{text}");
|
||||
@@ -579,10 +598,10 @@ mod tests {
|
||||
ran.store(true, Ordering::SeqCst);
|
||||
Ok(())
|
||||
};
|
||||
let text = failure_message(run_with_deadline(huge, "huge", || (), |_| None, spawn, Arc::new(|| Duration::ZERO)));
|
||||
let text = failure_message(run_with_deadline(huge, "huge", || (), |_| None, spawn, limit_passes));
|
||||
assert!(text.contains("ends past the latest time"), "{text}");
|
||||
assert!(!ran.load(Ordering::SeqCst), "the body started");
|
||||
let text = message(catch_unwind(|| wait_until(huge, "a huge limit", || true)).unwrap_err());
|
||||
let text = message(catch_unwind(|| wait_until(huge, "a huge limit", &Signal::new(), || true)).unwrap_err());
|
||||
assert!(text.contains("waiting for a huge limit: the limit of") && text.contains("ends past the latest time"), "{text}");
|
||||
}
|
||||
|
||||
@@ -619,22 +638,20 @@ mod tests {
|
||||
#[test]
|
||||
fn wait_until_returns_on_condition() {
|
||||
let ready = &AtomicBool::new(false);
|
||||
let signal = &Signal::new();
|
||||
let (asked, asked_rx) = mpsc::channel();
|
||||
let (stored, stored_rx) = mpsc::channel();
|
||||
thread::scope(|s| {
|
||||
s.spawn(move || {
|
||||
asked_rx.recv().unwrap();
|
||||
ready.store(true, Ordering::SeqCst);
|
||||
stored.send(()).unwrap();
|
||||
signal.raise();
|
||||
});
|
||||
let mut calls = 0;
|
||||
wait_until(long(), "the flag", || {
|
||||
wait_until(long(), "the flag", signal, || {
|
||||
calls += 1;
|
||||
if calls == 1 {
|
||||
// The flag is set before this call returns, and it still answers false, so the
|
||||
// condition is called a second time whatever order the threads run in.
|
||||
// The other thread sets the flag only after this call has started.
|
||||
asked.send(()).unwrap();
|
||||
stored_rx.recv().unwrap();
|
||||
return false;
|
||||
}
|
||||
ready.load(Ordering::SeqCst)
|
||||
@@ -644,145 +661,137 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "timed out waiting for the export to finish within 50ms")]
|
||||
fn wait_until_times_out_with_label() {
|
||||
wait_until(short(), "the export to finish", || false);
|
||||
fn a_raise_during_the_condition_ends_the_next_wait_at_once() {
|
||||
let signal = Signal::new();
|
||||
let mut calls = 0;
|
||||
let mut cond = || {
|
||||
calls += 1;
|
||||
if calls == 1 {
|
||||
signal.raise();
|
||||
}
|
||||
calls == 2
|
||||
};
|
||||
let result = wait_for_signal(&fake_resolved(Duration::from_secs(600)), "a raise", &signal, &mut cond, Instant::now, |_, raised, seen, _| {
|
||||
assert_ne!(*raised, seen, "the raise made during the condition was lost");
|
||||
(raised, false)
|
||||
});
|
||||
assert_eq!(result, Ok(()));
|
||||
assert_eq!(calls, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wait_until_times_out_with_label() {
|
||||
let mut calls = 0;
|
||||
let mut cond = || {
|
||||
calls += 1;
|
||||
false
|
||||
};
|
||||
let resolved = fake_resolved(Duration::from_millis(50));
|
||||
let text = wait_for_signal(&resolved, "the export to finish", &Signal::new(), &mut cond, Instant::now, |_, raised, _, _| (raised, true))
|
||||
.unwrap_err();
|
||||
assert!(text.starts_with("timed out waiting for the export to finish within 50ms"), "{text}");
|
||||
assert!(text.ends_with("the signal was not raised after the last check"), "{text}");
|
||||
assert_eq!(calls, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raises_that_never_satisfy_the_condition_fail_at_the_limit() {
|
||||
// A clock that moves 20 s on each reading, and a wait that always reports a raise.
|
||||
let start = Instant::now();
|
||||
let readings = std::cell::Cell::new(0u32);
|
||||
let now = || {
|
||||
let n = readings.get();
|
||||
readings.set(n + 1);
|
||||
start + Duration::from_secs(20) * n
|
||||
};
|
||||
let mut calls = 0;
|
||||
let mut cond = || {
|
||||
calls += 1;
|
||||
false
|
||||
};
|
||||
let resolved = fake_resolved(Duration::from_secs(60));
|
||||
let text = wait_for_signal(&resolved, "a progress tick", &Signal::new(), &mut cond, now, |_, mut raised, _, _| {
|
||||
*raised = raised.wrapping_add(1);
|
||||
(raised, false)
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(text.starts_with("timed out waiting for a progress tick within 60s"), "{text}");
|
||||
assert!(text.ends_with("the condition still returned false at the limit"), "{text}");
|
||||
assert_eq!(calls, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thread_raising_in_a_loop_cannot_hold_wait_until_past_the_limit() {
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let signal = Arc::new(Signal::new());
|
||||
let raiser = {
|
||||
let (stop, signal) = (Arc::clone(&stop), Arc::clone(&signal));
|
||||
thread::spawn(move || {
|
||||
while !stop.load(Ordering::SeqCst) {
|
||||
signal.raise();
|
||||
thread::yield_now();
|
||||
}
|
||||
})
|
||||
};
|
||||
let waiter_signal = Arc::clone(&signal);
|
||||
let guard = DeadlineLimit::new(Duration::from_secs(30)).with_variable(UNSET);
|
||||
let outcome = with_deadline(guard, "wait_until under constant raises", move || {
|
||||
catch_unwind(AssertUnwindSafe(|| wait_until(short(), "a condition that never holds", &waiter_signal, || false))).map_err(message)
|
||||
});
|
||||
stop.store(true, Ordering::SeqCst);
|
||||
raiser.join().unwrap();
|
||||
let text = outcome.unwrap_err();
|
||||
assert!(text.contains("timed out waiting for a condition that never holds within 50ms"), "{text}");
|
||||
}
|
||||
#[test]
|
||||
#[should_panic(expected = "condition boom")]
|
||||
fn wait_until_propagates_condition_panic() {
|
||||
wait_until(long(), "a panicking condition", || panic!("condition boom"));
|
||||
wait_until(long(), "a panicking condition", &Signal::new(), || panic!("condition boom"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wait_until_keeps_a_typed_condition_payload() {
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Marker(u32);
|
||||
let payload = catch_unwind(|| wait_until(long(), "a typed panic", || std::panic::panic_any(Marker(9)))).unwrap_err();
|
||||
let payload = catch_unwind(|| wait_until(long(), "a typed panic", &Signal::new(), || std::panic::panic_any(Marker(9)))).unwrap_err();
|
||||
assert_eq!(payload.downcast_ref::<Marker>(), Some(&Marker(9)));
|
||||
}
|
||||
|
||||
/// A default limit for the loop tests, which pass their own clock.
|
||||
/// A limit for the loop tests, which pass their own wait.
|
||||
fn fake_resolved(limit: Duration) -> Resolved<'static> {
|
||||
Resolved { limit, variable: UNSET, from_variable: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wait_until_rejects_a_true_after_the_limit() {
|
||||
let resolved = fake_resolved(Duration::from_millis(10));
|
||||
let mut now = Duration::ZERO;
|
||||
let mut cond = || true;
|
||||
// The condition took 11 ms to return.
|
||||
let mut elapsed = || {
|
||||
now += Duration::from_millis(11);
|
||||
now
|
||||
};
|
||||
let result = poll_until(&resolved, "a late flag", &mut cond, &mut elapsed, &mut |_| panic!("paused"));
|
||||
let text = result.unwrap_err();
|
||||
assert!(text.contains("timed out waiting for a late flag") && text.contains("held only after the limit"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wait_until_pauses_grow_and_stop_at_the_limit() {
|
||||
let resolved = fake_resolved(Duration::from_millis(100));
|
||||
let now = std::cell::Cell::new(Duration::ZERO);
|
||||
let mut pauses = Vec::new();
|
||||
let mut calls = 0;
|
||||
let mut cond = || {
|
||||
calls += 1;
|
||||
false
|
||||
};
|
||||
let mut elapsed = || now.get();
|
||||
let mut pause = |d: Duration| {
|
||||
pauses.push(d);
|
||||
now.set(now.get() + d);
|
||||
};
|
||||
let result = poll_until(&resolved, "never", &mut cond, &mut elapsed, &mut pause);
|
||||
assert!(result.is_err());
|
||||
let ms: Vec<u128> = pauses.iter().map(Duration::as_millis).collect();
|
||||
// 1 + 2 + 4 + 8 + 16 + 32 = 63, then the 37 ms left, after which the limit is reached.
|
||||
assert_eq!(ms, [1, 2, 4, 8, 16, 32, 37]);
|
||||
// One call before each pause, and none after the last one.
|
||||
assert_eq!(calls, 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wait_until_stops_calling_after_an_overshooting_pause() {
|
||||
let resolved = fake_resolved(Duration::from_millis(100));
|
||||
let now = std::cell::Cell::new(Duration::from_millis(99));
|
||||
let mut calls = 0;
|
||||
let mut cond = || {
|
||||
calls += 1;
|
||||
false
|
||||
};
|
||||
let mut elapsed = || now.get();
|
||||
// The thread wakes 50 ms late from the 1 ms pause.
|
||||
let mut pause = |d: Duration| now.set(now.get() + d + Duration::from_millis(50));
|
||||
let result = poll_until(&resolved, "late wake", &mut cond, &mut elapsed, &mut pause);
|
||||
assert!(result.unwrap_err().contains("timed out waiting for late wake"));
|
||||
assert_eq!(calls, 1);
|
||||
}
|
||||
|
||||
/// Runs `run_with_deadline` with a 5 s limit on a fake clock. The worker runs on the calling
|
||||
/// thread: the clock reads `start_secs` while the body runs and `received_secs` when the result
|
||||
/// is received. When `sends` is false, the worker stores its result but does not send, as if its
|
||||
/// thread stopped running between the two.
|
||||
fn on_fake_clock<T: Send + 'static>(
|
||||
f: impl FnOnce() -> T + Send + 'static,
|
||||
start_secs: u64,
|
||||
received_secs: u64,
|
||||
sends: bool,
|
||||
) -> Result<T, Failure> {
|
||||
let now = Arc::new(AtomicU64::new(0));
|
||||
let clock_now = Arc::clone(&now);
|
||||
let clock: Clock = Arc::new(move || Duration::from_secs(clock_now.load(Ordering::SeqCst)));
|
||||
let unsent = std::cell::RefCell::new(None);
|
||||
/// Runs `run_with_deadline` on `f` with the body's result arriving only after the limit has
|
||||
/// passed: the body does not start until the wait for it, which runs it on the calling thread
|
||||
/// and then reports that the limit passed. The worker never sends.
|
||||
fn finishing_after_the_limit<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Result<T, Failure> {
|
||||
let held = RefCell::new(None);
|
||||
let spawn = |job: Job, done: Sender<()>| {
|
||||
now.store(start_secs, Ordering::SeqCst);
|
||||
job();
|
||||
now.store(received_secs, Ordering::SeqCst);
|
||||
if sends {
|
||||
let _ = done.send(());
|
||||
} else {
|
||||
// Kept alive so that the wait times out instead of seeing a closed channel.
|
||||
*unsent.borrow_mut() = Some(done);
|
||||
}
|
||||
*held.borrow_mut() = Some((job, done));
|
||||
Ok(())
|
||||
};
|
||||
let limit = DeadlineLimit::new(Duration::from_secs(5)).with_variable(UNSET);
|
||||
run_with_deadline(limit, "fake clock", f, |_| None, spawn, clock)
|
||||
let wait = |_: &Receiver<()>, _: Duration| {
|
||||
if let Some((job, _done)) = held.borrow_mut().take() {
|
||||
job();
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout)
|
||||
};
|
||||
run_with_deadline(short(), "late body", f, |_| None, spawn, wait)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_returned_after_the_limit_fails() {
|
||||
let text = failure_message(on_fake_clock(|| 1, 6, 6, true));
|
||||
assert!(text.contains("fake clock finished only after its limit of 5s"), "{text}");
|
||||
fn a_value_that_arrives_after_the_limit_is_returned() {
|
||||
assert!(matches!(finishing_after_the_limit(|| 1), Ok(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_finished_in_time_but_received_late_passes() {
|
||||
assert!(matches!(on_fake_clock(|| 1, 1, 6, true), Ok(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_finished_in_time_but_sent_late_passes() {
|
||||
assert!(matches!(on_fake_clock(|| 1, 1, 6, false), Ok(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panic_finished_in_time_but_sent_late_keeps_its_payload() {
|
||||
let payload = match on_fake_clock(|| -> u8 { panic!("early boom") }, 1, 6, false) {
|
||||
fn a_panic_that_arrives_after_the_limit_keeps_its_payload() {
|
||||
let payload = match finishing_after_the_limit(|| -> u8 { panic!("late boom") }) {
|
||||
Err(Failure::Panic(payload)) => payload,
|
||||
Ok(_) => panic!("the call did not fail"),
|
||||
Err(Failure::Message(text)) => panic!("the payload was replaced: {text}"),
|
||||
};
|
||||
assert_eq!(message(payload), "early boom");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panic_after_the_limit_names_the_limit_and_the_panic() {
|
||||
let text = failure_message(on_fake_clock(|| -> u8 { panic!("late boom") }, 6, 6, true));
|
||||
assert!(text.contains("fake clock finished only after its limit of 5s") && text.ends_with("(it panicked: late boom)"), "{text}");
|
||||
assert_eq!(message(payload), "late boom");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,563 @@
|
||||
//! Test fonts made from font bytes the caller supplies.
|
||||
//!
|
||||
//! [`rename_family`] gives one standalone face a family name of the same length, and [`collection`]
|
||||
//! builds a TrueType collection (TTC) from standalone faces. Both read the structures they change as
|
||||
//! the OpenType specification lays them out
|
||||
//! (<https://learn.microsoft.com/en-us/typography/opentype/spec/otff> and
|
||||
//! <https://learn.microsoft.com/en-us/typography/opentype/spec/name>), and return a [`FontError`]
|
||||
//! for input that does not fit them. Other tables are copied as they are and are not checked.
|
||||
//!
|
||||
//! The module reads no file and no environment variable, prints nothing, and builds for
|
||||
//! `wasm32-unknown-unknown`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::ops::Range;
|
||||
|
||||
/// Length of the sfnt header: version, `numTables`, `searchRange`, `entrySelector`, `rangeShift`.
|
||||
const SFNT_HEADER: usize = 12;
|
||||
/// Length of one table record: tag, checksum, offset, length.
|
||||
const TABLE_RECORD: usize = 16;
|
||||
/// Length of the `name` table header: version, count, `storageOffset`.
|
||||
const NAME_HEADER: usize = 6;
|
||||
/// Length of one name record.
|
||||
const NAME_RECORD: usize = 12;
|
||||
/// Length of one language-tag record of a version 1 `name` table.
|
||||
const LANG_TAG_RECORD: usize = 4;
|
||||
/// Offset of `checkSumAdjustment` in the `head` table.
|
||||
const HEAD_ADJUSTMENT: usize = 8;
|
||||
/// The value a standalone font's checksum and its `checkSumAdjustment` add up to.
|
||||
const CHECKSUM_TARGET: u32 = 0xB1B0_AFBA;
|
||||
/// Name IDs that hold a family name: legacy (1), typographic (16) and WWS (21).
|
||||
const FAMILY_IDS: [u16; 3] = [1, 16, 21];
|
||||
/// Name ID of the full font name, which starts with the family name.
|
||||
const FULL_NAME_ID: u16 = 4;
|
||||
|
||||
/// Why a face could not be renamed or collected.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum FontError {
|
||||
/// `from` and `to` have different lengths in UTF-16 code units.
|
||||
UnequalLength,
|
||||
/// `from` or `to` is empty.
|
||||
InvalidName,
|
||||
/// No family record of the face holds `from`.
|
||||
NameNotFound,
|
||||
/// The face has no `name` table.
|
||||
MissingNameTable,
|
||||
/// A structure the function reads is truncated, out of range or of an unknown version.
|
||||
MalformedFont,
|
||||
/// A matching Macintosh Roman record would need a name that is not ASCII.
|
||||
UnsupportedEncoding,
|
||||
/// Bytes the rename changes are shared with a string it keeps, or with a different replacement.
|
||||
ConflictingNameStorage,
|
||||
/// [`collection`] was given no faces.
|
||||
EmptyCollection,
|
||||
/// The input is a collection, or an sfnt version other than TrueType or CFF outlines.
|
||||
UnsupportedFace,
|
||||
/// The output would not fit in memory or in the 32-bit offsets of a collection.
|
||||
OutputTooLarge,
|
||||
}
|
||||
|
||||
impl fmt::Display for FontError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::UnequalLength => "the old and new family names have different lengths",
|
||||
Self::InvalidName => "a family name is empty",
|
||||
Self::NameNotFound => "no family name record holds the old name",
|
||||
Self::MissingNameTable => "the font has no name table",
|
||||
Self::MalformedFont => "the font's table directory or name table is truncated or out of range",
|
||||
Self::UnsupportedEncoding => "a Macintosh Roman name record can only take an ASCII name",
|
||||
Self::ConflictingNameStorage => "the bytes of a renamed family name are shared with a string that must not change",
|
||||
Self::EmptyCollection => "a collection needs at least one face",
|
||||
Self::UnsupportedFace => "the input is not a standalone TrueType or CFF face",
|
||||
Self::OutputTooLarge => "the output is too large",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for FontError {}
|
||||
|
||||
/// Returns a copy of `bytes`, one standalone face, with the family name `from` replaced by `to`.
|
||||
///
|
||||
/// The records changed are the legacy, typographic and WWS family names (name IDs 1, 16 and 21)
|
||||
/// whose whole value is `from`, and full names (name ID 4) that are `from` or start with `from` and a
|
||||
/// space; at least one family record must hold `from`. Copyright, style, PostScript (ID 6) and every
|
||||
/// other name keep their bytes. Records in UTF-16BE (platform 0, and platform 3 encodings 0, 1 and
|
||||
/// 10) and Macintosh Roman (platform 1 encoding 0) are read, and only ASCII names are written into
|
||||
/// Macintosh Roman records; records in other encodings are left as they are. The function then writes the
|
||||
/// `name` table's checksum and the `head` table's `checkSumAdjustment`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`FontError::InvalidName`] when a name is empty, [`FontError::UnequalLength`] when the names have
|
||||
/// different UTF-16 lengths, [`FontError::NameNotFound`] when no family record holds `from`,
|
||||
/// [`FontError::UnsupportedEncoding`] when a matching Macintosh Roman record would need non-ASCII
|
||||
/// bytes, [`FontError::ConflictingNameStorage`] when changed bytes are shared with a kept string,
|
||||
/// [`FontError::MissingNameTable`], [`FontError::UnsupportedFace`] for a collection, and
|
||||
/// [`FontError::MalformedFont`] when the directory, the `name` table or the `head` table is out of
|
||||
/// range or of an unknown version, or when the `name` or `head` table shares bytes with the directory
|
||||
/// or another table.
|
||||
pub fn rename_family(bytes: &[u8], from: &str, to: &str) -> Result<Vec<u8>, FontError> {
|
||||
if from.is_empty() || to.is_empty() {
|
||||
return Err(FontError::InvalidName);
|
||||
}
|
||||
if from.encode_utf16().count() != to.encode_utf16().count() {
|
||||
return Err(FontError::UnequalLength);
|
||||
}
|
||||
let tables = directory(bytes)?;
|
||||
let name = tables.iter().find(|t| &t.tag == b"name").ok_or(FontError::MissingNameTable)?;
|
||||
let head = tables.iter().find(|t| &t.tag == b"head");
|
||||
if shares_bytes(&tables, name) || head.is_some_and(|head| shares_bytes(&tables, head)) {
|
||||
return Err(FontError::MalformedFont);
|
||||
}
|
||||
if head.is_some_and(|head| head.length < HEAD_ADJUSTMENT + 4) {
|
||||
return Err(FontError::MalformedFont);
|
||||
}
|
||||
let strings = name_strings(bytes, name)?;
|
||||
let (edits, kept) = plan_edits(bytes, &strings, from, to)?;
|
||||
check_kept(&edits, kept)?;
|
||||
|
||||
let mut out = copy_of(bytes)?;
|
||||
apply_edits(&mut out, name, &edits)?;
|
||||
let name_sum = checksum(bytes_at(&out, name.offset, name.length)?);
|
||||
put_u32(&mut out, name.record + 4, name_sum)?;
|
||||
if let Some(head) = head {
|
||||
let at = head.offset + HEAD_ADJUSTMENT;
|
||||
put_u32(&mut out, at, 0)?;
|
||||
let sum = checksum(&out);
|
||||
put_u32(&mut out, at, CHECKSUM_TARGET.wrapping_sub(sum))?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Returns a TrueType collection (TTC version 1.0) holding `faces`, each a standalone face, in order.
|
||||
///
|
||||
/// Every face keeps its sfnt header and table order and gets its own copy of each table. Tables
|
||||
/// start on four-byte boundaries with zero padding between them, offsets count from the start of the
|
||||
/// collection, and each record keeps the table's unpadded length. Each `head` table's
|
||||
/// `checkSumAdjustment` is set to zero, as a collection does not use it, and every table checksum is
|
||||
/// computed from the bytes in the collection.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`FontError::EmptyCollection`] for no faces, [`FontError::UnsupportedFace`] for a face that is
|
||||
/// itself a collection, [`FontError::MalformedFont`] for a face shorter than its table directory or
|
||||
/// with a table out of range, and [`FontError::OutputTooLarge`] when the collection would pass the
|
||||
/// 4 GiB that its 32-bit offsets reach or cannot be allocated. The headers and table directories are
|
||||
/// counted from each face's `numTables` before any table record is read, so faces whose directories
|
||||
/// alone pass 4 GiB return [`FontError::OutputTooLarge`] even when a table record is out of range.
|
||||
pub fn collection(faces: &[&[u8]]) -> Result<Vec<u8>, FontError> {
|
||||
if faces.is_empty() {
|
||||
return Err(FontError::EmptyCollection);
|
||||
}
|
||||
let count = u32::try_from(faces.len()).map_err(|_| FontError::OutputTooLarge)?;
|
||||
let size = collection_size(faces)?;
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(size).map_err(|_| FontError::OutputTooLarge)?;
|
||||
out.extend_from_slice(b"ttcf");
|
||||
out.extend_from_slice(&0x0001_0000u32.to_be_bytes());
|
||||
out.extend_from_slice(&count.to_be_bytes());
|
||||
out.resize(SFNT_HEADER + faces.len() * 4, 0);
|
||||
for (index, face) in faces.iter().enumerate() {
|
||||
let tables = directory(face)?;
|
||||
let directory = offset32(out.len())?;
|
||||
put_u32(&mut out, SFNT_HEADER + index * 4, directory)?;
|
||||
write_face(&mut out, face, &tables)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// One table record of a face: where the record is and where its table is.
|
||||
struct Table {
|
||||
tag: [u8; 4],
|
||||
/// Offset of the table record in the face.
|
||||
record: usize,
|
||||
offset: usize,
|
||||
length: usize,
|
||||
}
|
||||
|
||||
/// Reads a standalone face's table directory, checking that every record and table lies in `face`.
|
||||
fn directory(face: &[u8]) -> Result<Vec<Table>, FontError> {
|
||||
let count = table_count(face)?;
|
||||
bytes_at(face, 0, SFNT_HEADER + count * TABLE_RECORD)?;
|
||||
let mut tables = Vec::with_capacity(count);
|
||||
for index in 0..count {
|
||||
let record = SFNT_HEADER + index * TABLE_RECORD;
|
||||
let tag = <[u8; 4]>::try_from(bytes_at(face, record, 4)?).map_err(|_| FontError::MalformedFont)?;
|
||||
let offset = usize_from(u32_at(face, record + 8)?)?;
|
||||
let length = usize_from(u32_at(face, record + 12)?)?;
|
||||
bytes_at(face, offset, length)?;
|
||||
tables.push(Table { tag, record, offset, length });
|
||||
}
|
||||
Ok(tables)
|
||||
}
|
||||
|
||||
/// Reads a standalone face's sfnt version and `numTables`, without reading the table records.
|
||||
fn table_count(face: &[u8]) -> Result<usize, FontError> {
|
||||
let version = bytes_at(face, 0, 4)?;
|
||||
if !matches!(version, [0, 1, 0, 0] | [b'O', b'T', b'T', b'O'] | [b't', b'r', b'u', b'e']) {
|
||||
return Err(FontError::UnsupportedFace);
|
||||
}
|
||||
Ok(usize::from(u16_at(face, 4)?))
|
||||
}
|
||||
|
||||
/// Whether `table` shares bytes with the table directory or with another table of the face. Another
|
||||
/// table of length 0 shares no bytes, wherever its offset points.
|
||||
fn shares_bytes(tables: &[Table], table: &Table) -> bool {
|
||||
let end = table.offset + table.length;
|
||||
let overlaps = |start: usize, other_end: usize| start < other_end && start < end && table.offset < other_end;
|
||||
overlaps(0, SFNT_HEADER + tables.len() * TABLE_RECORD)
|
||||
|| tables.iter().any(|other| other.record != table.record && overlaps(other.offset, other.offset + other.length))
|
||||
}
|
||||
|
||||
/// Bytes a collection of these faces takes, refused past what a 32-bit offset reaches.
|
||||
///
|
||||
/// The headers and table directories are added up first, from each face's `numTables` alone, so that
|
||||
/// input whose directories already pass the limit is refused before any table record is read. The
|
||||
/// tables are then added one face at a time, and no face's directory is kept.
|
||||
fn collection_size(faces: &[&[u8]]) -> Result<usize, FontError> {
|
||||
let add = |size: u64, bytes: usize| -> Result<u64, FontError> {
|
||||
let size = size.checked_add(u64::try_from(bytes).map_err(|_| FontError::OutputTooLarge)?).ok_or(FontError::OutputTooLarge)?;
|
||||
if size > u64::from(u32::MAX) { Err(FontError::OutputTooLarge) } else { Ok(size) }
|
||||
};
|
||||
let mut size = add(0, SFNT_HEADER)?;
|
||||
size = add(size, faces.len().checked_mul(4).ok_or(FontError::OutputTooLarge)?)?;
|
||||
for face in faces {
|
||||
size = add(size, SFNT_HEADER + table_count(face)? * TABLE_RECORD)?;
|
||||
}
|
||||
for face in faces {
|
||||
for table in directory(face)? {
|
||||
size = add(size, table.length.div_ceil(4).checked_mul(4).ok_or(FontError::OutputTooLarge)?)?;
|
||||
}
|
||||
}
|
||||
usize::try_from(size).map_err(|_| FontError::OutputTooLarge)
|
||||
}
|
||||
|
||||
/// Appends one face's directory and tables to a collection being built.
|
||||
fn write_face(out: &mut Vec<u8>, face: &[u8], tables: &[Table]) -> Result<(), FontError> {
|
||||
let directory = out.len();
|
||||
out.extend_from_slice(bytes_at(face, 0, SFNT_HEADER)?);
|
||||
out.resize(directory + SFNT_HEADER + tables.len() * TABLE_RECORD, 0);
|
||||
for (index, table) in tables.iter().enumerate() {
|
||||
let start = out.len();
|
||||
out.extend_from_slice(bytes_at(face, table.offset, table.length)?);
|
||||
if &table.tag == b"head" {
|
||||
if table.length < HEAD_ADJUSTMENT + 4 {
|
||||
return Err(FontError::MalformedFont);
|
||||
}
|
||||
put_u32(out, start + HEAD_ADJUSTMENT, 0)?;
|
||||
}
|
||||
let sum = checksum(bytes_at(out, start, table.length)?);
|
||||
out.resize(out.len().div_ceil(4) * 4, 0);
|
||||
let record = directory + SFNT_HEADER + index * TABLE_RECORD;
|
||||
put_bytes(out, record, &table.tag)?;
|
||||
put_u32(out, record + 4, sum)?;
|
||||
put_u32(out, record + 8, offset32(start)?)?;
|
||||
put_u32(out, record + 12, offset32(table.length)?)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How the bytes of a name record are encoded, as far as renaming reads them.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
enum Encoding {
|
||||
Utf16,
|
||||
MacRoman,
|
||||
Other,
|
||||
}
|
||||
|
||||
impl Encoding {
|
||||
fn of(platform: u16, encoding: u16) -> Self {
|
||||
match (platform, encoding) {
|
||||
(0, _) | (3, 0 | 1 | 10) => Self::Utf16,
|
||||
(1, 0) => Self::MacRoman,
|
||||
_ => Self::Other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One string of the `name` table, with its range in the face.
|
||||
struct NameString {
|
||||
encoding: Encoding,
|
||||
name_id: u16,
|
||||
range: Range<usize>,
|
||||
}
|
||||
|
||||
/// The strings of a face's `name` table: the name records, then the language tags of version 1.
|
||||
struct NameStrings {
|
||||
names: Vec<NameString>,
|
||||
lang_tags: Vec<Range<usize>>,
|
||||
}
|
||||
|
||||
/// Reads the name and language-tag records of `table`, checking every string lies in the table.
|
||||
fn name_strings(face: &[u8], table: &Table) -> Result<NameStrings, FontError> {
|
||||
let data = bytes_at(face, table.offset, table.length)?;
|
||||
let version = u16_at(data, 0)?;
|
||||
if version > 1 {
|
||||
return Err(FontError::MalformedFont);
|
||||
}
|
||||
let count = usize::from(u16_at(data, 2)?);
|
||||
let storage = usize::from(u16_at(data, 4)?);
|
||||
let records_end = NAME_HEADER + count * NAME_RECORD;
|
||||
bytes_at(data, 0, records_end)?;
|
||||
let mut header_end = records_end;
|
||||
let mut lang_tag_records = 0;
|
||||
if version == 1 {
|
||||
lang_tag_records = usize::from(u16_at(data, records_end)?);
|
||||
header_end = records_end + 2 + lang_tag_records * LANG_TAG_RECORD;
|
||||
}
|
||||
if storage < header_end || storage > data.len() {
|
||||
return Err(FontError::MalformedFont);
|
||||
}
|
||||
let string = |at: usize| -> Result<Range<usize>, FontError> {
|
||||
let length = usize::from(u16_at(data, at)?);
|
||||
let start = storage + usize::from(u16_at(data, at + 2)?);
|
||||
bytes_at(data, start, length)?;
|
||||
Ok(table.offset + start..table.offset + start + length)
|
||||
};
|
||||
let mut names = Vec::with_capacity(count);
|
||||
for index in 0..count {
|
||||
let record = NAME_HEADER + index * NAME_RECORD;
|
||||
let encoding = Encoding::of(u16_at(data, record)?, u16_at(data, record + 2)?);
|
||||
let name_id = u16_at(data, record + 6)?;
|
||||
names.push(NameString { encoding, name_id, range: string(record + 8)? });
|
||||
}
|
||||
let mut lang_tags = Vec::with_capacity(lang_tag_records);
|
||||
for index in 0..lang_tag_records {
|
||||
lang_tags.push(string(records_end + 2 + index * LANG_TAG_RECORD)?);
|
||||
}
|
||||
Ok(NameStrings { names, lang_tags })
|
||||
}
|
||||
|
||||
/// Bytes the rename writes: the range of the family name at the start of a string, and the new name.
|
||||
/// The rest of the string keeps its bytes.
|
||||
struct Edit {
|
||||
range: Range<usize>,
|
||||
bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Works out the family names to rewrite and the ranges of the strings that must keep their bytes.
|
||||
/// Refuses with [`FontError::NameNotFound`] when no family record (IDs 1, 16 and 21) holds `from`.
|
||||
/// Records that point at the same string are read once.
|
||||
fn plan_edits(face: &[u8], strings: &NameStrings, from: &str, to: &str) -> Result<(Vec<Edit>, Vec<Range<usize>>), FontError> {
|
||||
let mut edits = Vec::new();
|
||||
let mut kept = strings.lang_tags.clone();
|
||||
let mut family_found = false;
|
||||
let mut read: HashMap<(usize, usize, Encoding, bool), bool> = HashMap::new();
|
||||
for string in &strings.names {
|
||||
let family = FAMILY_IDS.contains(&string.name_id);
|
||||
if !family && string.name_id != FULL_NAME_ID {
|
||||
kept.push(string.range.clone());
|
||||
continue;
|
||||
}
|
||||
let key = (string.range.start, string.range.end, string.encoding, family);
|
||||
let edited = match read.get(&key) {
|
||||
Some(&edited) => edited,
|
||||
None => {
|
||||
let edit = renamed(string, face, from, to)?;
|
||||
let edited = edit.is_some();
|
||||
if let Some(edit) = &edit {
|
||||
// The rest of a full name, after the family name, must keep its bytes.
|
||||
kept.push(edit.range.end..string.range.end);
|
||||
}
|
||||
edits.extend(edit);
|
||||
read.insert(key, edited);
|
||||
edited
|
||||
}
|
||||
};
|
||||
if edited {
|
||||
family_found |= family;
|
||||
} else {
|
||||
kept.push(string.range.clone());
|
||||
}
|
||||
}
|
||||
if !family_found {
|
||||
return Err(FontError::NameNotFound);
|
||||
}
|
||||
Ok((edits, kept))
|
||||
}
|
||||
|
||||
/// The edit of a family or full-name string, or `None` when it does not hold `from`.
|
||||
fn renamed(string: &NameString, face: &[u8], from: &str, to: &str) -> Result<Option<Edit>, FontError> {
|
||||
let family = FAMILY_IDS.contains(&string.name_id);
|
||||
let bytes = face.get(string.range.clone()).ok_or(FontError::MalformedFont)?;
|
||||
let renamed = match string.encoding {
|
||||
Encoding::Utf16 => renamed_utf16(family, bytes, from, to)?,
|
||||
Encoding::MacRoman => renamed_mac_roman(family, bytes, from, to)?,
|
||||
Encoding::Other => None,
|
||||
};
|
||||
let Some((old_length, new)) = renamed else {
|
||||
return Ok(None);
|
||||
};
|
||||
if new.len() != old_length {
|
||||
return Err(FontError::UnequalLength);
|
||||
}
|
||||
let start = string.range.start;
|
||||
Ok(Some(Edit { range: start..start + old_length, bytes: new }))
|
||||
}
|
||||
|
||||
/// Renames a UTF-16BE family string whose value is `from`, or a full name that starts with `from` and
|
||||
/// a space. Returns the byte length of `from` in the string and the bytes of `to`.
|
||||
fn renamed_utf16(family: bool, bytes: &[u8], from: &str, to: &str) -> Result<Option<(usize, Vec<u8>)>, FontError> {
|
||||
let (pairs, rest) = bytes.as_chunks::<2>();
|
||||
if !rest.is_empty() {
|
||||
return Err(FontError::MalformedFont);
|
||||
}
|
||||
let units = pairs.iter().map(|&pair| u16::from_be_bytes(pair));
|
||||
if char::decode_utf16(units.clone()).any(|c| c.is_err()) {
|
||||
return Err(FontError::MalformedFont);
|
||||
}
|
||||
let count = from.encode_utf16().count();
|
||||
if !units.clone().take(count).eq(from.encode_utf16()) {
|
||||
return Ok(None);
|
||||
}
|
||||
match units.clone().nth(count) {
|
||||
None => {}
|
||||
Some(unit) if !family && unit == u16::from(b' ') => {}
|
||||
Some(_) => return Ok(None),
|
||||
}
|
||||
Ok(Some((count * 2, to.encode_utf16().flat_map(u16::to_be_bytes).collect())))
|
||||
}
|
||||
|
||||
/// Renames a Macintosh Roman string the way [`renamed_utf16`] does, comparing its decoded characters
|
||||
/// with `from`. Only ASCII names are written.
|
||||
fn renamed_mac_roman(family: bool, bytes: &[u8], from: &str, to: &str) -> Result<Option<(usize, Vec<u8>)>, FontError> {
|
||||
let count = from.chars().count();
|
||||
let Some(name) = bytes.get(..count) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !name.iter().map(|&byte| mac_roman_char(byte)).eq(from.chars()) {
|
||||
return Ok(None);
|
||||
}
|
||||
match bytes.get(count) {
|
||||
None => {}
|
||||
Some(b' ') if !family => {}
|
||||
Some(_) => return Ok(None),
|
||||
}
|
||||
if !from.is_ascii() || !to.is_ascii() {
|
||||
return Err(FontError::UnsupportedEncoding);
|
||||
}
|
||||
Ok(Some((count, to.as_bytes().to_vec())))
|
||||
}
|
||||
|
||||
/// The character a Macintosh Roman byte stands for. Bytes below 0x80 are ASCII; the others follow
|
||||
/// the mapping at <https://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/ROMAN.TXT>.
|
||||
fn mac_roman_char(byte: u8) -> char {
|
||||
match byte.checked_sub(0x80) {
|
||||
None => char::from(byte),
|
||||
Some(high) => MAC_ROMAN_HIGH.get(usize::from(high)).copied().unwrap_or(char::REPLACEMENT_CHARACTER),
|
||||
}
|
||||
}
|
||||
|
||||
/// The characters of Macintosh Roman bytes 0x80 to 0xFF.
|
||||
#[rustfmt::skip]
|
||||
const MAC_ROMAN_HIGH: [char; 128] = [
|
||||
'\u{00C4}', '\u{00C5}', '\u{00C7}', '\u{00C9}', '\u{00D1}', '\u{00D6}', '\u{00DC}', '\u{00E1}',
|
||||
'\u{00E0}', '\u{00E2}', '\u{00E4}', '\u{00E3}', '\u{00E5}', '\u{00E7}', '\u{00E9}', '\u{00E8}',
|
||||
'\u{00EA}', '\u{00EB}', '\u{00ED}', '\u{00EC}', '\u{00EE}', '\u{00EF}', '\u{00F1}', '\u{00F3}',
|
||||
'\u{00F2}', '\u{00F4}', '\u{00F6}', '\u{00F5}', '\u{00FA}', '\u{00F9}', '\u{00FB}', '\u{00FC}',
|
||||
'\u{2020}', '\u{00B0}', '\u{00A2}', '\u{00A3}', '\u{00A7}', '\u{2022}', '\u{00B6}', '\u{00DF}',
|
||||
'\u{00AE}', '\u{00A9}', '\u{2122}', '\u{00B4}', '\u{00A8}', '\u{2260}', '\u{00C6}', '\u{00D8}',
|
||||
'\u{221E}', '\u{00B1}', '\u{2264}', '\u{2265}', '\u{00A5}', '\u{00B5}', '\u{2202}', '\u{2211}',
|
||||
'\u{220F}', '\u{03C0}', '\u{222B}', '\u{00AA}', '\u{00BA}', '\u{03A9}', '\u{00E6}', '\u{00F8}',
|
||||
'\u{00BF}', '\u{00A1}', '\u{00AC}', '\u{221A}', '\u{0192}', '\u{2248}', '\u{2206}', '\u{00AB}',
|
||||
'\u{00BB}', '\u{2026}', '\u{00A0}', '\u{00C0}', '\u{00C3}', '\u{00D5}', '\u{0152}', '\u{0153}',
|
||||
'\u{2013}', '\u{2014}', '\u{201C}', '\u{201D}', '\u{2018}', '\u{2019}', '\u{00F7}', '\u{25CA}',
|
||||
'\u{00FF}', '\u{0178}', '\u{2044}', '\u{20AC}', '\u{2039}', '\u{203A}', '\u{FB01}', '\u{FB02}',
|
||||
'\u{2021}', '\u{00B7}', '\u{201A}', '\u{201E}', '\u{2030}', '\u{00C2}', '\u{00CA}', '\u{00C1}',
|
||||
'\u{00CB}', '\u{00C8}', '\u{00CD}', '\u{00CE}', '\u{00CF}', '\u{00CC}', '\u{00D3}', '\u{00D4}',
|
||||
'\u{F8FF}', '\u{00D2}', '\u{00DA}', '\u{00DB}', '\u{00D9}', '\u{0131}', '\u{02C6}', '\u{02DC}',
|
||||
'\u{00AF}', '\u{02D8}', '\u{02D9}', '\u{02DA}', '\u{00B8}', '\u{02DD}', '\u{02DB}', '\u{02C7}',
|
||||
];
|
||||
|
||||
/// Refuses a rename whose strings overlap a string that keeps its bytes.
|
||||
fn check_kept(edits: &[Edit], mut kept: Vec<Range<usize>>) -> Result<(), FontError> {
|
||||
kept.retain(|range| !range.is_empty());
|
||||
kept.sort_by_key(|range| range.start);
|
||||
let mut merged: Vec<Range<usize>> = Vec::with_capacity(kept.len());
|
||||
for range in kept {
|
||||
match merged.last_mut() {
|
||||
Some(last) if range.start <= last.end => last.end = last.end.max(range.end),
|
||||
_ => merged.push(range),
|
||||
}
|
||||
}
|
||||
for edit in edits {
|
||||
let next = merged.partition_point(|range| range.end <= edit.range.start);
|
||||
if merged.get(next).is_some_and(|range| range.start < edit.range.end) {
|
||||
return Err(FontError::ConflictingNameStorage);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes the edits into `out`, refusing two edits that write different bytes to the same place.
|
||||
fn apply_edits(out: &mut [u8], name: &Table, edits: &[Edit]) -> Result<(), FontError> {
|
||||
let mut ranges: Vec<&Edit> = edits.iter().collect();
|
||||
ranges.sort_by_key(|edit| (edit.range.start, edit.range.end));
|
||||
ranges.dedup_by(|a, b| a.range == b.range && a.bytes == b.bytes);
|
||||
let mut written = vec![false; name.length];
|
||||
for edit in ranges {
|
||||
let target = out.get_mut(edit.range.clone()).ok_or(FontError::MalformedFont)?;
|
||||
let start = edit.range.start.checked_sub(name.offset).ok_or(FontError::MalformedFont)?;
|
||||
let marks = written.get_mut(start..start + edit.bytes.len()).ok_or(FontError::MalformedFont)?;
|
||||
for ((byte, mark), &new) in target.iter_mut().zip(marks.iter_mut()).zip(&edit.bytes) {
|
||||
if *mark && *byte != new {
|
||||
return Err(FontError::ConflictingNameStorage);
|
||||
}
|
||||
*byte = new;
|
||||
*mark = true;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The OpenType table checksum: the sum of big-endian 32-bit words, the last one padded with zeros.
|
||||
fn checksum(data: &[u8]) -> u32 {
|
||||
data.chunks(4).fold(0u32, |sum, chunk| {
|
||||
let mut word = [0u8; 4];
|
||||
for (to, &from) in word.iter_mut().zip(chunk) {
|
||||
*to = from;
|
||||
}
|
||||
sum.wrapping_add(u32::from_be_bytes(word))
|
||||
})
|
||||
}
|
||||
|
||||
fn copy_of(bytes: &[u8]) -> Result<Vec<u8>, FontError> {
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(bytes.len()).map_err(|_| FontError::OutputTooLarge)?;
|
||||
out.extend_from_slice(bytes);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn bytes_at(data: &[u8], at: usize, length: usize) -> Result<&[u8], FontError> {
|
||||
let end = at.checked_add(length).ok_or(FontError::MalformedFont)?;
|
||||
data.get(at..end).ok_or(FontError::MalformedFont)
|
||||
}
|
||||
|
||||
fn u16_at(data: &[u8], at: usize) -> Result<u16, FontError> {
|
||||
let bytes = <[u8; 2]>::try_from(bytes_at(data, at, 2)?).map_err(|_| FontError::MalformedFont)?;
|
||||
Ok(u16::from_be_bytes(bytes))
|
||||
}
|
||||
|
||||
fn u32_at(data: &[u8], at: usize) -> Result<u32, FontError> {
|
||||
let bytes = <[u8; 4]>::try_from(bytes_at(data, at, 4)?).map_err(|_| FontError::MalformedFont)?;
|
||||
Ok(u32::from_be_bytes(bytes))
|
||||
}
|
||||
|
||||
fn put_bytes(data: &mut [u8], at: usize, bytes: &[u8]) -> Result<(), FontError> {
|
||||
let end = at.checked_add(bytes.len()).ok_or(FontError::MalformedFont)?;
|
||||
data.get_mut(at..end).ok_or(FontError::MalformedFont)?.copy_from_slice(bytes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn put_u32(data: &mut [u8], at: usize, value: u32) -> Result<(), FontError> {
|
||||
put_bytes(data, at, &value.to_be_bytes())
|
||||
}
|
||||
|
||||
fn usize_from(value: u32) -> Result<usize, FontError> {
|
||||
usize::try_from(value).map_err(|_| FontError::MalformedFont)
|
||||
}
|
||||
|
||||
fn offset32(value: usize) -> Result<u32, FontError> {
|
||||
u32::try_from(value).map_err(|_| FontError::OutputTooLarge)
|
||||
}
|
||||
@@ -389,7 +389,9 @@ fn read_variable(name: &str) -> Option<OsString> {
|
||||
/// that panics or does not finish within the config's limit.
|
||||
///
|
||||
/// The cases run one after another on one worker thread, while the calling thread fails the test
|
||||
/// when a case runs past the config's limit. A case that finishes after the limit also fails it. A
|
||||
/// when a case is still running once the config's limit has passed since it started. The limit
|
||||
/// guards against a hang: a case that has finished, however long it took, passes or fails on what
|
||||
/// `parse` did, and the number of cases depends only on the seed, the rounds and the divisor. A
|
||||
/// failure starts with the config's label and names the case (`the unmodified seed`,
|
||||
/// `truncation to N` or the mutation's edits), the input's length and the panic's message. A case
|
||||
/// that does not finish fails the test while the worker thread is left running, so `parse` must be
|
||||
@@ -436,7 +438,13 @@ where
|
||||
let start = Instant::now();
|
||||
let limit = resolve(&config.timeout, &lookup, start).map(Limit::from).map_err(|error| format!("{label}: {error}"))?;
|
||||
let clock: Clock = Arc::new(move || start.elapsed());
|
||||
run_cases(label.to_owned(), limit, Arc::from(seed), rounds, divisor, parse, clock)
|
||||
run_cases(label.to_owned(), limit, Arc::from(seed), rounds, divisor, parse, clock, wait_for_worker)
|
||||
}
|
||||
|
||||
/// Waits on `signal` for at most `wait`, or less when the wait wakes early.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn wait_for_worker<'g>(signal: &Condvar, state: MutexGuard<'g, Progress>, wait: Duration) -> MutexGuard<'g, Progress> {
|
||||
signal.wait_timeout(state, wait).unwrap_or_else(PoisonError::into_inner).0
|
||||
}
|
||||
|
||||
/// A clock that returns the time since a [`hammer`] call started.
|
||||
@@ -473,11 +481,11 @@ struct Progress {
|
||||
outcome: Option<Result<(), String>>,
|
||||
}
|
||||
|
||||
/// [`Progress`] under a lock, with a signal for when the worker stops.
|
||||
/// [`Progress`] under a lock, with a signal for when a case starts and when the worker stops.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
struct Watch {
|
||||
state: Mutex<Progress>,
|
||||
stopped: Condvar,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -500,27 +508,30 @@ impl Drop for Report {
|
||||
fn drop(&mut self) {
|
||||
let mut state = self.watch.lock();
|
||||
state.outcome = Some(std::mem::replace(&mut self.outcome, Ok(())));
|
||||
self.watch.stopped.notify_all();
|
||||
self.watch.changed.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the worker that runs every case, then waits for it, failing when a case runs past the
|
||||
/// limit.
|
||||
/// Starts the worker that runs every case, then waits for it, failing when a case is still running
|
||||
/// once the limit has passed since it started. `wait` waits on the watch's signal for at most the
|
||||
/// given time.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn run_cases<F>(label: String, limit: Limit, seed: Arc<[u8]>, rounds: usize, divisor: usize, parse: F, clock: Clock) -> Result<(), String>
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn run_cases<F, W>(label: String, limit: Limit, seed: Arc<[u8]>, rounds: usize, divisor: usize, parse: F, clock: Clock, wait: W) -> Result<(), String>
|
||||
where
|
||||
F: Fn(&[u8]) + Send + Sync + 'static,
|
||||
W: for<'g> Fn(&Condvar, MutexGuard<'g, Progress>, Duration) -> MutexGuard<'g, Progress>,
|
||||
{
|
||||
// No case counts as running until the worker starts it, so a worker that starts late is not
|
||||
// reported as a case past its limit.
|
||||
let first = Progress { case: "the unmodified seed".to_owned(), len: seed.len(), started: clock(), running: false, outcome: None };
|
||||
let watch = Arc::new(Watch { state: Mutex::new(first), stopped: Condvar::new() });
|
||||
let (worker_watch, worker_clock, worker_label, worker_limit) = (Arc::clone(&watch), Arc::clone(&clock), label.clone(), limit.clone());
|
||||
let watch = Arc::new(Watch { state: Mutex::new(first), changed: Condvar::new() });
|
||||
let (worker_watch, worker_clock, worker_label) = (Arc::clone(&watch), Arc::clone(&clock), label.clone());
|
||||
thread::Builder::new()
|
||||
.name(WORKER_NAME.to_owned())
|
||||
.spawn(move || {
|
||||
let mut report = Report { watch: worker_watch, outcome: Err(format!("{worker_label}: the worker thread stopped without a result")) };
|
||||
report.outcome = run_all(&report.watch, &worker_clock, &worker_label, &worker_limit, &seed, rounds, divisor, &parse);
|
||||
report.outcome = run_all(&report.watch, &worker_clock, &worker_label, &seed, rounds, divisor, &parse);
|
||||
})
|
||||
.map_err(|error| format!("{label}: could not start the worker thread: {error}"))?;
|
||||
let mut state = watch.lock();
|
||||
@@ -533,57 +544,43 @@ where
|
||||
if state.running && now >= deadline {
|
||||
return Err(format!("{label}: {} (len {}) did not finish within {}; its thread is left running", state.case, state.len, limit.text));
|
||||
}
|
||||
let wait = if state.running { deadline.saturating_sub(now) } else { limit.limit };
|
||||
state = watch.stopped.wait_timeout(state, wait).unwrap_or_else(PoisonError::into_inner).0;
|
||||
let wait_for = if state.running { deadline.saturating_sub(now) } else { limit.limit };
|
||||
state = wait(&watch.changed, state, wait_for);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the unmodified seed, every `divisor`-th truncation and its mutations in order, stopping at
|
||||
/// the first failure.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn run_all<F: Fn(&[u8])>(
|
||||
watch: &Watch,
|
||||
clock: &Clock,
|
||||
label: &str,
|
||||
limit: &Limit,
|
||||
seed: &[u8],
|
||||
rounds: usize,
|
||||
divisor: usize,
|
||||
parse: &F,
|
||||
) -> Result<(), String> {
|
||||
fn run_all<F: Fn(&[u8])>(watch: &Watch, clock: &Clock, label: &str, seed: &[u8], rounds: usize, divisor: usize, parse: &F) -> Result<(), String> {
|
||||
for n in std::iter::once(seed.len()).chain((0..seed.len()).step_by(divisor)) {
|
||||
let case = if n == seed.len() { "the unmodified seed".to_owned() } else { format!("truncation to {n}") };
|
||||
run_one(watch, clock, label, limit, case, seed.get(..n).unwrap_or_default(), parse)?;
|
||||
run_one(watch, clock, label, case, seed.get(..n).unwrap_or_default(), parse)?;
|
||||
}
|
||||
for mutation in mutations(seed, rounds) {
|
||||
run_one(watch, clock, label, limit, mutation.label, &mutation.bytes, parse)?;
|
||||
run_one(watch, clock, label, mutation.label, &mutation.bytes, parse)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs one case, recording it in `watch` while it runs, and returns the failure's message when it
|
||||
/// panics or finishes after the limit.
|
||||
/// panics. How long the case took does not change its result.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn run_one<F: Fn(&[u8])>(watch: &Watch, clock: &Clock, label: &str, limit: &Limit, case: String, data: &[u8], parse: &F) -> Result<(), String> {
|
||||
fn run_one<F: Fn(&[u8])>(watch: &Watch, clock: &Clock, label: &str, case: String, data: &[u8], parse: &F) -> Result<(), String> {
|
||||
let started = clock();
|
||||
{
|
||||
let mut state = watch.lock();
|
||||
(state.case, state.len, state.started, state.running) = (case, data.len(), started, true);
|
||||
// Wakes the calling thread so that it waits on this case's limit.
|
||||
watch.changed.notify_all();
|
||||
}
|
||||
let outcome = catch_unwind(AssertUnwindSafe(|| parse(data)));
|
||||
let spent = clock().saturating_sub(started);
|
||||
// The payload is dropped before the lock is taken and while the case still counts as running, so
|
||||
// the watchdog still reports a payload whose drop does not return.
|
||||
let panicked = outcome.err().map(|payload| panic_text(payload.as_ref()));
|
||||
let mut state = watch.lock();
|
||||
state.running = false;
|
||||
let name = || format!("{label}: {} (len {})", state.case, state.len);
|
||||
if spent > limit.limit {
|
||||
let panicked = panicked.map_or_else(String::new, |text| format!(" (it panicked: {text})"));
|
||||
return Err(format!("{} finished only after its limit of {}{panicked}", name(), limit.text));
|
||||
}
|
||||
panicked.map_or(Ok(()), |text| Err(format!("{}: the parser panicked: {text}", name())))
|
||||
panicked.map_or(Ok(()), |text| Err(format!("{label}: {} (len {}): the parser panicked: {text}", state.case, state.len)))
|
||||
}
|
||||
|
||||
/// The text of a panic payload.
|
||||
@@ -602,6 +599,7 @@ mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::mpsc;
|
||||
|
||||
/// A variable no test sets, so the environment cannot change a test's rounds or limits.
|
||||
@@ -641,36 +639,44 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn deadline_names_stuck_case() {
|
||||
let (release, wait) = mpsc::channel::<()>();
|
||||
let wait = Mutex::new(wait);
|
||||
let short = config("stuck demo", 0).with_timeout(DeadlineLimit::new(Duration::from_millis(50)).with_variable(UNSET));
|
||||
let result = hammer_with(
|
||||
&short,
|
||||
&[1, 2, 3],
|
||||
move |d| {
|
||||
if d.len() == 3 {
|
||||
let _ = wait.lock().unwrap().recv();
|
||||
}
|
||||
},
|
||||
unset,
|
||||
);
|
||||
// The clock jumps an hour ahead the first time the calling thread waits while a case runs.
|
||||
let now = Arc::new(AtomicU64::new(0));
|
||||
let clock_now = Arc::clone(&now);
|
||||
let clock: Clock = Arc::new(move || Duration::from_secs(clock_now.load(Ordering::SeqCst)));
|
||||
let (release, blocked) = mpsc::channel::<()>();
|
||||
let blocked = Mutex::new(blocked);
|
||||
let parse = move |d: &[u8]| {
|
||||
if d.len() == 3 {
|
||||
let _ = blocked.lock().unwrap().recv();
|
||||
}
|
||||
};
|
||||
let limit = Limit { limit: Duration::from_millis(50), text: "50ms".to_owned() };
|
||||
let result = run_cases("stuck demo".to_owned(), limit, Arc::from(&[1u8, 2, 3][..]), 0, 1, parse, clock, |signal, state, _| {
|
||||
if state.running {
|
||||
now.store(3600, Ordering::SeqCst);
|
||||
state
|
||||
} else {
|
||||
signal.wait(state).unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
});
|
||||
release.send(()).unwrap();
|
||||
let message = result.unwrap_err();
|
||||
assert!(message.contains("stuck demo: the unmodified seed (len 3) did not finish within 50ms"), "{message}");
|
||||
assert_eq!(result, Err("stuck demo: the unmodified seed (len 3) did not finish within 50ms; its thread is left running".to_owned()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_case_that_finishes_after_the_limit_fails() {
|
||||
let readings = Arc::new(Mutex::new(vec![Duration::from_secs(6), Duration::ZERO]));
|
||||
let clock: Clock = Arc::new(move || readings.lock().unwrap().pop().unwrap_or(Duration::MAX));
|
||||
let watch = Watch {
|
||||
state: Mutex::new(Progress { case: String::new(), len: 0, started: Duration::ZERO, running: true, outcome: None }),
|
||||
stopped: Condvar::new(),
|
||||
};
|
||||
fn a_case_that_finishes_after_the_limit_passes() {
|
||||
// By the worker's clock the first case takes six seconds against a limit of five; the calling
|
||||
// thread's clock stays at zero, so the watchdog does not fire.
|
||||
let worker_readings = Mutex::new(vec![Duration::from_secs(6), Duration::ZERO]);
|
||||
let clock: Clock = Arc::new(move || {
|
||||
if thread::current().name() == Some(WORKER_NAME) {
|
||||
worker_readings.lock().unwrap().pop().unwrap_or(Duration::from_secs(6))
|
||||
} else {
|
||||
Duration::ZERO
|
||||
}
|
||||
});
|
||||
let limit = Limit { limit: Duration::from_secs(5), text: "5s".to_owned() };
|
||||
let message = run_one(&watch, &clock, "late", &limit, "the unmodified seed".to_owned(), &[1], &|_: &[u8]| {}).unwrap_err();
|
||||
assert_eq!(message, "late: the unmodified seed (len 1) finished only after its limit of 5s");
|
||||
assert!(!watch.lock().running);
|
||||
assert_eq!(run_cases("slow".to_owned(), limit, Arc::from(&[1u8][..]), 0, 1, |_: &[u8]| {}, clock, wait_for_worker), Ok(()));
|
||||
}
|
||||
|
||||
/// A panic payload that records, when it is dropped, whether the progress lock was free and
|
||||
@@ -691,14 +697,13 @@ mod tests {
|
||||
fn a_panic_payload_is_dropped_outside_the_lock_while_the_case_runs() {
|
||||
let watch = Arc::new(Watch {
|
||||
state: Mutex::new(Progress { case: String::new(), len: 0, started: Duration::ZERO, running: false, outcome: None }),
|
||||
stopped: Condvar::new(),
|
||||
changed: Condvar::new(),
|
||||
});
|
||||
let seen = Arc::new(Mutex::new(None));
|
||||
let clock: Clock = Arc::new(|| Duration::ZERO);
|
||||
let limit = Limit { limit: Duration::from_secs(5), text: "5s".to_owned() };
|
||||
let probe = (Arc::clone(&watch), Arc::clone(&seen));
|
||||
let parse = move |_: &[u8]| std::panic::panic_any(DropProbe { watch: Arc::clone(&probe.0), seen: Arc::clone(&probe.1) });
|
||||
let message = run_one(&watch, &clock, "probe", &limit, "the unmodified seed".to_owned(), &[1], &parse).unwrap_err();
|
||||
let message = run_one(&watch, &clock, "probe", "the unmodified seed".to_owned(), &[1], &parse).unwrap_err();
|
||||
assert_eq!(message, "probe: the unmodified seed (len 1): the parser panicked: a payload that is not a message");
|
||||
assert_eq!(*seen.lock().unwrap(), Some(Some(true)), "the payload was dropped with the lock held or the case stopped");
|
||||
assert!(!watch.lock().running);
|
||||
@@ -725,7 +730,7 @@ mod tests {
|
||||
Duration::ZERO
|
||||
});
|
||||
let limit = Limit { limit: Duration::from_secs(5), text: "5s".to_owned() };
|
||||
assert_eq!(run_cases("late start".to_owned(), limit, Arc::from(&[1u8][..]), 0, 1, |_: &[u8]| {}, clock), Ok(()));
|
||||
assert_eq!(run_cases("late start".to_owned(), limit, Arc::from(&[1u8][..]), 0, 1, |_: &[u8]| {}, clock, wait_for_worker), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -14,13 +14,21 @@
|
||||
//! * `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`.
|
||||
//!
|
||||
//! On native targets, the `fixtures` module locates generated test fixtures under `<workspace>/target/fixtures`,
|
||||
//! generates a missing one into a claimed temporary sibling, publishes it under a per-output lock that
|
||||
//! keeps a complete file another process published first, and prints the `FIXTURE made`, `cached` and
|
||||
//! `skipped` lines that FilmCraft's `cargo xtask fixtures` counts.
|
||||
//!
|
||||
//! [`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`
|
||||
//! 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.
|
||||
//! and fails the test when the body still has no result once the limit has passed; a result that
|
||||
//! arrives before that check is returned. `deadline::wait_until` calls a condition, and when a
|
||||
//! `deadline::Signal` raise wakes it, checks the condition again until it holds; raises that come
|
||||
//! during one call of the condition share one recheck. It fails the test when the condition still
|
||||
//! does not hold at the limit. 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
|
||||
@@ -42,6 +50,10 @@
|
||||
//! corpus folder against them: `corpus::Manifest`, `corpus::verify` and the test gate
|
||||
//! `corpus::pinned`, which skips or fails under the rule of `skip`.
|
||||
//!
|
||||
//! With the `mcp` feature, on targets other than `wasm32`, `mcp::McpChild` runs an MCP server as a
|
||||
//! child process and talks to it over stdin and stdout, with a deadline on every wait and a length
|
||||
//! limit on every line it reads.
|
||||
//!
|
||||
//! ### Epistemic Scope: What Source Guards Establish vs What They Cannot
|
||||
//!
|
||||
//! Source-level guards provide deterministic syntactic evidence about codebase structure.
|
||||
@@ -51,13 +63,24 @@
|
||||
//! They do **not** establish runtime correctness, protocol concurrency safety, or platform behavior
|
||||
//! under foreign host environments. They are lightweight syntactic regression gates designed to complement,
|
||||
//! rather than replace, platform integration tests and CI execution.
|
||||
//!
|
||||
//! ### Test fonts
|
||||
//!
|
||||
//! The [`fonts`] module makes test fonts from font bytes the caller supplies:
|
||||
//! [`fonts::rename_family`] gives a face a family name of the same length, and
|
||||
//! [`fonts::collection`] builds a TrueType collection from standalone faces.
|
||||
|
||||
#[cfg(all(feature = "corpus", not(target_arch = "wasm32")))]
|
||||
pub mod corpus;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod deadline;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod fixtures;
|
||||
pub mod fonts;
|
||||
pub mod guards;
|
||||
pub mod hostile;
|
||||
#[cfg(all(feature = "mcp", not(target_arch = "wasm32")))]
|
||||
pub mod mcp;
|
||||
pub mod rng;
|
||||
pub mod sample_damage;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -66,7 +89,7 @@ pub mod serial;
|
||||
pub mod skip;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use deadline::{DeadlineLimit, wait_until, with_deadline};
|
||||
pub use deadline::{DeadlineLimit, Signal, wait_until, with_deadline};
|
||||
pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -111,7 +111,7 @@ pub fn skip(reason: &str, required_var: &str) -> bool {
|
||||
/// 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 {
|
||||
pub(crate) fn skip_with(required: bool, reason: &str, required_var: &str) -> bool {
|
||||
if required {
|
||||
panic!("{reason}, and {required_var}=1 forbids skipping this test");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,630 @@
|
||||
//! Tests of `craft_testkit::fonts` on faces assembled here from bytes.
|
||||
//!
|
||||
//! The helpers below read the output by the offsets the OpenType specification gives, without the
|
||||
//! crate's own parser, so a test fails when a field is wrong even if the crate could read it back.
|
||||
|
||||
use craft_testkit::fonts::{FontError, collection, rename_family};
|
||||
|
||||
const FROM: &str = "Source Sans 3";
|
||||
const TO: &str = "Sysfont Sans3";
|
||||
const CHECKSUM_TARGET: u32 = 0xB1B0_AFBA;
|
||||
|
||||
fn be16(data: &[u8], at: usize) -> u16 {
|
||||
u16::from_be_bytes([data[at], data[at + 1]])
|
||||
}
|
||||
|
||||
fn be32(data: &[u8], at: usize) -> u32 {
|
||||
u32::from_be_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]])
|
||||
}
|
||||
|
||||
fn set16(data: &mut [u8], at: usize, value: u16) {
|
||||
data[at..at + 2].copy_from_slice(&value.to_be_bytes());
|
||||
}
|
||||
|
||||
fn set32(data: &mut [u8], at: usize, value: u32) {
|
||||
data[at..at + 4].copy_from_slice(&value.to_be_bytes());
|
||||
}
|
||||
|
||||
/// The table checksum: big-endian 32-bit words added with wrapping, the last padded with zeros.
|
||||
fn sum(data: &[u8]) -> u32 {
|
||||
let mut total = 0u32;
|
||||
let mut at = 0;
|
||||
while at < data.len() {
|
||||
let mut word = [0u8; 4];
|
||||
for (k, byte) in word.iter_mut().enumerate() {
|
||||
if let Some(&b) = data.get(at + k) {
|
||||
*byte = b;
|
||||
}
|
||||
}
|
||||
total = total.wrapping_add(u32::from_be_bytes(word));
|
||||
at += 4;
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
fn utf16(text: &str) -> Vec<u8> {
|
||||
text.encode_utf16().flat_map(u16::to_be_bytes).collect()
|
||||
}
|
||||
|
||||
/// A name record: platform, encoding, name ID, and where its string is in storage.
|
||||
struct Rec {
|
||||
platform: u16,
|
||||
encoding: u16,
|
||||
name_id: u16,
|
||||
offset: u16,
|
||||
length: u16,
|
||||
}
|
||||
|
||||
/// A `name` table of `version` with the records as given, language tags as (length, offset), then storage.
|
||||
fn name_table(version: u16, records: &[Rec], lang_tags: &[(u16, u16)], storage: &[u8]) -> Vec<u8> {
|
||||
let mut header = 6 + 12 * records.len();
|
||||
if version == 1 {
|
||||
header += 2 + 4 * lang_tags.len();
|
||||
}
|
||||
let mut table = Vec::new();
|
||||
table.extend_from_slice(&version.to_be_bytes());
|
||||
table.extend_from_slice(&(records.len() as u16).to_be_bytes());
|
||||
table.extend_from_slice(&(header as u16).to_be_bytes());
|
||||
for rec in records {
|
||||
for value in [rec.platform, rec.encoding, 0, rec.name_id, rec.length, rec.offset] {
|
||||
table.extend_from_slice(&value.to_be_bytes());
|
||||
}
|
||||
}
|
||||
if version == 1 {
|
||||
table.extend_from_slice(&(lang_tags.len() as u16).to_be_bytes());
|
||||
for &(length, offset) in lang_tags {
|
||||
table.extend_from_slice(&length.to_be_bytes());
|
||||
table.extend_from_slice(&offset.to_be_bytes());
|
||||
}
|
||||
}
|
||||
table.extend_from_slice(storage);
|
||||
table
|
||||
}
|
||||
|
||||
/// Name records with their strings stored one after another: (platform, encoding, name ID, bytes).
|
||||
fn names(list: &[(u16, u16, u16, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut storage = Vec::new();
|
||||
let mut records = Vec::new();
|
||||
for (platform, encoding, name_id, bytes) in list {
|
||||
records.push(Rec { platform: *platform, encoding: *encoding, name_id: *name_id, offset: storage.len() as u16, length: bytes.len() as u16 });
|
||||
storage.extend_from_slice(bytes);
|
||||
}
|
||||
name_table(0, &records, &[], &storage)
|
||||
}
|
||||
|
||||
/// A 54-byte `head` table whose `checkSumAdjustment` holds a stale value.
|
||||
fn head() -> Vec<u8> {
|
||||
let mut table = vec![0u8; 54];
|
||||
set32(&mut table, 0, 0x0001_0000);
|
||||
set32(&mut table, 8, 0x1234_5678);
|
||||
set32(&mut table, 12, 0x5F0F_3CF5);
|
||||
set16(&mut table, 18, 1000);
|
||||
table
|
||||
}
|
||||
|
||||
/// A standalone TrueType face holding `tables` in the order given, each on a four-byte boundary.
|
||||
fn face(tables: &[(&[u8; 4], Vec<u8>)]) -> Vec<u8> {
|
||||
let mut font = Vec::new();
|
||||
font.extend_from_slice(&0x0001_0000u32.to_be_bytes());
|
||||
font.extend_from_slice(&(tables.len() as u16).to_be_bytes());
|
||||
font.extend_from_slice(&[0; 6]);
|
||||
font.resize(12 + 16 * tables.len(), 0);
|
||||
for (index, (tag, data)) in tables.iter().enumerate() {
|
||||
let offset = font.len();
|
||||
font.extend_from_slice(data);
|
||||
font.resize(font.len().div_ceil(4) * 4, 0);
|
||||
let record = 12 + 16 * index;
|
||||
font[record..record + 4].copy_from_slice(&tag[..]);
|
||||
set32(&mut font, record + 4, sum(data));
|
||||
set32(&mut font, record + 8, offset as u32);
|
||||
set32(&mut font, record + 12, data.len() as u32);
|
||||
}
|
||||
font
|
||||
}
|
||||
|
||||
fn family_face(list: &[(u16, u16, u16, Vec<u8>)]) -> Vec<u8> {
|
||||
face(&[(b"head", head()), (b"name", names(list))])
|
||||
}
|
||||
|
||||
/// A table of the face whose directory starts at `directory`: (record offset, table offset, length).
|
||||
fn table_at(font: &[u8], directory: usize, tag: &[u8; 4]) -> (usize, usize, usize) {
|
||||
let count = usize::from(be16(font, directory + 4));
|
||||
(0..count)
|
||||
.map(|i| directory + 12 + 16 * i)
|
||||
.find(|&record| &font[record..record + 4] == tag)
|
||||
.map(|record| (record, be32(font, record + 8) as usize, be32(font, record + 12) as usize))
|
||||
.unwrap_or_else(|| panic!("no {} table", String::from_utf8_lossy(tag)))
|
||||
}
|
||||
|
||||
fn table(font: &[u8], tag: &[u8; 4]) -> (usize, usize, usize) {
|
||||
table_at(font, 0, tag)
|
||||
}
|
||||
|
||||
/// Every name record of a standalone face: (platform, encoding, name ID, bytes).
|
||||
fn strings(font: &[u8]) -> Vec<(u16, u16, u16, Vec<u8>)> {
|
||||
let (_, at, _) = table(font, b"name");
|
||||
let count = usize::from(be16(font, at + 2));
|
||||
let storage = at + usize::from(be16(font, at + 4));
|
||||
(0..count)
|
||||
.map(|i| {
|
||||
let rec = at + 6 + 12 * i;
|
||||
let start = storage + usize::from(be16(font, rec + 10));
|
||||
let end = start + usize::from(be16(font, rec + 8));
|
||||
(be16(font, rec), be16(font, rec + 2), be16(font, rec + 6), font[start..end].to_vec())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn win(name_id: u16, text: &str) -> (u16, u16, u16, Vec<u8>) {
|
||||
(3, 1, name_id, utf16(text))
|
||||
}
|
||||
|
||||
fn mac(name_id: u16, bytes: &[u8]) -> (u16, u16, u16, Vec<u8>) {
|
||||
(1, 0, name_id, bytes.to_vec())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_handles_utf16_and_ascii() {
|
||||
let font = family_face(&[win(1, FROM), (0, 3, 1, utf16(FROM)), mac(1, FROM.as_bytes()), win(16, FROM), win(21, FROM)]);
|
||||
let out = rename_family(&font, FROM, TO).unwrap();
|
||||
assert_eq!(out.len(), font.len());
|
||||
assert_eq!(strings(&out), vec![win(1, TO), (0, 3, 1, utf16(TO)), mac(1, TO.as_bytes()), win(16, TO), win(21, TO)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_only_family_records() {
|
||||
let list = [
|
||||
win(0, "Copyright 2026 the Source Sans 3 authors"),
|
||||
win(1, FROM),
|
||||
win(2, "Regular"),
|
||||
win(6, "SourceSans3-Regular"),
|
||||
win(13, "Source Sans 3 is licensed under the OFL"),
|
||||
win(16, "Source Sans 3 Extra"),
|
||||
];
|
||||
let other = utf16(FROM);
|
||||
let font = face(&[(b"head", head()), (b"name", names(&list)), (b"zzzz", other.clone())]);
|
||||
let out = rename_family(&font, FROM, TO).unwrap();
|
||||
let mut want = list.to_vec();
|
||||
want[1] = win(1, TO);
|
||||
assert_eq!(strings(&out), want);
|
||||
let (_, at, length) = table(&out, b"zzzz");
|
||||
assert_eq!(&out[at..at + length], &other[..], "a table other than name keeps its bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_full_name_prefix_only() {
|
||||
let list =
|
||||
[win(1, FROM), win(4, "Source Sans 3 Bold"), (0, 3, 4, utf16("Source Sans 3Bold")), mac(4, b"My Source Sans 3"), mac(4, FROM.as_bytes())];
|
||||
let out = rename_family(&family_face(&list), FROM, TO).unwrap();
|
||||
assert_eq!(strings(&out), vec![win(1, TO), win(4, "Sysfont Sans3 Bold"), list[2].clone(), list[3].clone(), mac(4, TO.as_bytes())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_non_ascii_mac_roman() {
|
||||
let font = family_face(&[win(1, FROM), mac(1, FROM.as_bytes())]);
|
||||
assert_eq!(rename_family(&font, FROM, "Sourcé Sans 3"), Err(FontError::UnsupportedEncoding));
|
||||
// "Café Sans 3" in Mac Roman, where é is 0x8E.
|
||||
let font = family_face(&[win(1, "Café Sans 3"), mac(1, b"Caf\x8E Sans 3")]);
|
||||
assert_eq!(rename_family(&font, "Café Sans 3", "Cafe Sans 3"), Err(FontError::UnsupportedEncoding));
|
||||
let font = family_face(&[win(1, "Café Sans 3"), mac(4, b"Caf\x8E Sans 3 Bold")]);
|
||||
assert_eq!(rename_family(&font, "Café Sans 3", "Cafe Sans 3"), Err(FontError::UnsupportedEncoding));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_keeps_mac_roman_names_with_other_letters() {
|
||||
// Mac Roman 0x80 is "Ä" and 0x8F is "è", so neither Mac record holds "Café Sans 3".
|
||||
let list = [win(1, "Café Sans 3"), mac(1, b"Caf\x80 Sans 3"), mac(4, b"Caf\x8F Sans 3 Bold")];
|
||||
let out = rename_family(&family_face(&list), "Café Sans 3", "Cafe Sans 3").unwrap();
|
||||
assert_eq!(strings(&out), vec![win(1, "Cafe Sans 3"), list[1].clone(), list[2].clone()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_keeps_unrelated_mac_roman_names() {
|
||||
// Mac Roman 0x8E is "é". Neither Mac record can hold "Café Sans 3": one is shorter, and the other
|
||||
// differs from it in an ASCII position.
|
||||
let list = [win(1, "Café Sans 3"), mac(4, b"Autre \x8E"), mac(16, b"Caf\x8E Sans 4")];
|
||||
let out = rename_family(&family_face(&list), "Café Sans 3", "Cafe Sans 3").unwrap();
|
||||
assert_eq!(strings(&out), vec![win(1, "Cafe Sans 3"), list[1].clone(), list[2].clone()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_keeps_mac_roman_full_name_suffix() {
|
||||
let list = [win(1, FROM), mac(4, b"Source Sans 3 Cr\x8Ame")];
|
||||
let out = rename_family(&family_face(&list), FROM, TO).unwrap();
|
||||
assert_eq!(strings(&out), vec![win(1, TO), mac(4, b"Sysfont Sans3 Cr\x8Ame")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_requires_a_family_record() {
|
||||
let font = family_face(&[win(1, "Other Family"), win(4, "Source Sans 3 Bold")]);
|
||||
assert_eq!(rename_family(&font, FROM, TO), Err(FontError::NameNotFound));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_preserves_other_encodings() {
|
||||
let list = [win(1, FROM), (3, 3, 1, utf16(FROM)), (1, 1, 1, FROM.as_bytes().to_vec()), (2, 1, 1, utf16(FROM))];
|
||||
let out = rename_family(&family_face(&list), FROM, TO).unwrap();
|
||||
let mut want = list.to_vec();
|
||||
want[0] = win(1, TO);
|
||||
assert_eq!(strings(&out), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_odd_utf16() {
|
||||
let mut odd = utf16(FROM);
|
||||
odd.push(0);
|
||||
let font = family_face(&[(3, 1, 1, odd)]);
|
||||
assert_eq!(rename_family(&font, FROM, TO), Err(FontError::MalformedFont));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_bad_surrogate() {
|
||||
let font = family_face(&[(3, 1, 1, vec![0xD8, 0x00, 0x00, b'A']), win(16, FROM)]);
|
||||
assert_eq!(rename_family(&font, FROM, TO), Err(FontError::MalformedFont));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_handles_shared_family_storage() {
|
||||
let storage = utf16("Source Sans 3 Bold");
|
||||
let records = [
|
||||
Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 },
|
||||
Rec { platform: 3, encoding: 1, name_id: 16, offset: 0, length: 26 },
|
||||
Rec { platform: 3, encoding: 1, name_id: 4, offset: 0, length: 36 },
|
||||
];
|
||||
let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &storage))]);
|
||||
let out = rename_family(&font, FROM, TO).unwrap();
|
||||
assert_eq!(strings(&out), vec![win(1, TO), win(16, TO), win(4, "Sysfont Sans3 Bold")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_shared_nonfamily_storage() {
|
||||
let records =
|
||||
[Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }, Rec { platform: 3, encoding: 1, name_id: 6, offset: 2, length: 10 }];
|
||||
let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &utf16(FROM)))]);
|
||||
assert_eq!(rename_family(&font, FROM, TO), Err(FontError::ConflictingNameStorage));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_keeps_a_style_sharing_the_full_name_suffix() {
|
||||
// The style name (ID 2) "Bold" is the last 8 bytes of the full name, which the rename does not change.
|
||||
let storage = [utf16(FROM), utf16("Source Sans 3 Bold")].concat();
|
||||
let records = [
|
||||
Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 },
|
||||
Rec { platform: 3, encoding: 1, name_id: 2, offset: 54, length: 8 },
|
||||
Rec { platform: 3, encoding: 1, name_id: 4, offset: 26, length: 36 },
|
||||
];
|
||||
let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &storage))]);
|
||||
let out = rename_family(&font, FROM, TO).unwrap();
|
||||
assert_eq!(strings(&out), vec![win(1, TO), win(2, "Bold"), win(4, "Sysfont Sans3 Bold")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_a_family_name_in_the_full_name_suffix() {
|
||||
// The full name "A A" is stored once, and the family name (ID 1) is its last "A". Renaming the
|
||||
// family would change the full name's suffix " A".
|
||||
let records =
|
||||
[Rec { platform: 3, encoding: 1, name_id: 4, offset: 0, length: 6 }, Rec { platform: 3, encoding: 1, name_id: 1, offset: 4, length: 2 }];
|
||||
let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &utf16("A A")))]);
|
||||
assert_eq!(rename_family(&font, "A", "B"), Err(FontError::ConflictingNameStorage));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_updates_name_checksum() {
|
||||
let font = family_face(&[win(1, FROM), win(2, "Regular")]);
|
||||
let out = rename_family(&font, FROM, TO).unwrap();
|
||||
let (record, at, length) = table(&out, b"name");
|
||||
assert_eq!(be32(&out, record + 4), sum(&out[at..at + length]));
|
||||
assert_ne!(be32(&out, record + 4), be32(&font, record + 4), "the renamed table has a new checksum");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_updates_head_adjustment() {
|
||||
let font = family_face(&[win(1, FROM)]);
|
||||
let out = rename_family(&font, FROM, TO).unwrap();
|
||||
let (_, at, _) = table(&out, b"head");
|
||||
let mut zeroed = out.clone();
|
||||
set32(&mut zeroed, at + 8, 0);
|
||||
assert_eq!(be32(&out, at + 8), CHECKSUM_TARGET.wrapping_sub(sum(&zeroed)));
|
||||
assert_eq!(sum(&out), CHECKSUM_TARGET);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_format_one_preserves_language_tags() {
|
||||
let mut storage = utf16(FROM);
|
||||
storage.extend(utf16("en-US"));
|
||||
let records = [Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }];
|
||||
let font = face(&[(b"head", head()), (b"name", name_table(1, &records, &[(10, 26)], &storage))]);
|
||||
let out = rename_family(&font, FROM, TO).unwrap();
|
||||
assert_eq!(strings(&out), vec![win(1, TO)]);
|
||||
let (_, at, length) = table(&out, b"name");
|
||||
assert_eq!(&out[at + length - 10..at + length], &utf16("en-US")[..]);
|
||||
assert_eq!(be16(&out, at + 18), 1, "the language-tag count stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_keeps_language_tag_storage() {
|
||||
let records = [Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }];
|
||||
let font = face(&[(b"head", head()), (b"name", name_table(1, &records, &[(26, 0)], &utf16(FROM)))]);
|
||||
assert_eq!(rename_family(&font, FROM, TO), Err(FontError::ConflictingNameStorage));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_short_sfnt() {
|
||||
assert_eq!(rename_family(&[], FROM, TO), Err(FontError::MalformedFont));
|
||||
assert_eq!(rename_family(&[0, 1, 0, 0, 0], FROM, TO), Err(FontError::MalformedFont));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_truncated_directory() {
|
||||
let font = family_face(&[win(1, FROM)]);
|
||||
assert_eq!(rename_family(&font[..12 + 16 + 8], FROM, TO), Err(FontError::MalformedFont));
|
||||
let mut many = font.clone();
|
||||
set16(&mut many, 4, 4000);
|
||||
assert_eq!(rename_family(&many, FROM, TO), Err(FontError::MalformedFont));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_collection() {
|
||||
let font = family_face(&[win(1, FROM)]);
|
||||
let ttc = collection(&[&font]).unwrap();
|
||||
assert_eq!(rename_family(&ttc, FROM, TO), Err(FontError::UnsupportedFace));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_missing_name_table() {
|
||||
let font = face(&[(b"head", head())]);
|
||||
assert_eq!(rename_family(&font, FROM, TO), Err(FontError::MissingNameTable));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_short_head() {
|
||||
let font = face(&[(b"head", head()[..8].to_vec()), (b"name", names(&[win(1, FROM)]))]);
|
||||
assert_eq!(rename_family(&font, FROM, TO), Err(FontError::MalformedFont));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_bad_name_storage() {
|
||||
let font = family_face(&[win(1, FROM)]);
|
||||
let (_, at, length) = table(&font, b"name");
|
||||
let mut beyond = font.clone();
|
||||
set16(&mut beyond, at + 4, length as u16 + 1);
|
||||
assert_eq!(rename_family(&beyond, FROM, TO), Err(FontError::MalformedFont));
|
||||
let mut inside_header = font.clone();
|
||||
set16(&mut inside_header, at + 4, 6);
|
||||
assert_eq!(rename_family(&inside_header, FROM, TO), Err(FontError::MalformedFont));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_bad_name_record_range() {
|
||||
let font = family_face(&[win(1, FROM)]);
|
||||
let (_, at, _) = table(&font, b"name");
|
||||
let mut long = font.clone();
|
||||
set16(&mut long, at + 6 + 8, 28);
|
||||
assert_eq!(rename_family(&long, FROM, TO), Err(FontError::MalformedFont));
|
||||
let mut late = font;
|
||||
set16(&mut late, at + 6 + 10, 2);
|
||||
assert_eq!(rename_family(&late, FROM, TO), Err(FontError::MalformedFont));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_name_table_sharing_bytes() {
|
||||
let font = face(&[(b"head", head()), (b"name", names(&[win(1, FROM)])), (b"zzzz", vec![7; 8])]);
|
||||
let (_, at, _) = table(&font, b"name");
|
||||
let (record, _, _) = table(&font, b"zzzz");
|
||||
let mut shared = font.clone();
|
||||
set32(&mut shared, record + 8, (at + 18) as u32);
|
||||
assert_eq!(rename_family(&shared, FROM, TO), Err(FontError::MalformedFont));
|
||||
let (_, head_at, _) = table(&font, b"head");
|
||||
let mut under_head = font;
|
||||
set32(&mut under_head, record + 8, (head_at + 8) as u32);
|
||||
assert_eq!(rename_family(&under_head, FROM, TO), Err(FontError::MalformedFont), "checkSumAdjustment would land in zzzz");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_accepts_an_empty_table_inside_name_or_head() {
|
||||
let font = face(&[(b"head", head()), (b"name", names(&[win(1, FROM)])), (b"zzzz", vec![7; 8])]);
|
||||
let (record, _, _) = table(&font, b"zzzz");
|
||||
let (_, name_at, _) = table(&font, b"name");
|
||||
let (_, head_at, _) = table(&font, b"head");
|
||||
for inside in [name_at + 18, head_at + 8] {
|
||||
let mut empty = font.clone();
|
||||
set32(&mut empty, record + 8, inside as u32);
|
||||
set32(&mut empty, record + 12, 0);
|
||||
assert!(rename_family(&empty, FROM, TO).is_ok(), "an empty table at {inside} shares no bytes");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_unknown_name_format() {
|
||||
let font = family_face(&[win(1, FROM)]);
|
||||
let (_, at, _) = table(&font, b"name");
|
||||
let mut two = font;
|
||||
set16(&mut two, at, 2);
|
||||
assert_eq!(rename_family(&two, FROM, TO), Err(FontError::MalformedFont));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_unequal_lengths() {
|
||||
let font = family_face(&[win(1, FROM)]);
|
||||
assert_eq!(rename_family(&font, FROM, "Other"), Err(FontError::UnequalLength));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_unequal_utf16_lengths() {
|
||||
// Both names are four bytes of UTF-8, but "𝐀" is two UTF-16 code units and "abcd" is four.
|
||||
let font = family_face(&[win(1, "𝐀")]);
|
||||
assert_eq!(rename_family(&font, "𝐀", "abcd"), Err(FontError::UnequalLength));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_missing_family() {
|
||||
let font = family_face(&[win(1, FROM), win(2, "Regular")]);
|
||||
assert_eq!(rename_family(&font, "Source Sans 4", TO), Err(FontError::NameNotFound));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_empty_names() {
|
||||
let font = family_face(&[win(1, FROM)]);
|
||||
assert_eq!(rename_family(&font, "", ""), Err(FontError::InvalidName));
|
||||
assert_eq!(rename_family(&font, FROM, ""), Err(FontError::InvalidName));
|
||||
}
|
||||
|
||||
/// Two faces that differ in every table, with table lengths that are not multiples of four.
|
||||
fn two_faces() -> (Vec<u8>, Vec<u8>) {
|
||||
let a = face(&[(b"head", head()), (b"name", names(&[mac(1, b"Alpha")])), (b"zzzz", vec![1, 2, 3, 4, 5])]);
|
||||
let mut other_head = head();
|
||||
set32(&mut other_head, 4, 0x0002_0000);
|
||||
let b = face(&[(b"head", other_head), (b"name", names(&[mac(1, b"Beta")])), (b"zzzz", vec![9; 7])]);
|
||||
(a, b)
|
||||
}
|
||||
|
||||
/// Each face's directory offset, read from the TTC header.
|
||||
fn ttc_faces(ttc: &[u8]) -> Vec<usize> {
|
||||
assert_eq!(&ttc[..4], b"ttcf");
|
||||
assert_eq!(be32(ttc, 4), 0x0001_0000);
|
||||
(0..be32(ttc, 8) as usize).map(|i| be32(ttc, 12 + 4 * i) as usize).collect()
|
||||
}
|
||||
|
||||
/// Every table of a face in a collection: (tag, checksum, offset, length).
|
||||
fn ttc_tables(ttc: &[u8], directory: usize) -> Vec<([u8; 4], u32, usize, usize)> {
|
||||
(0..usize::from(be16(ttc, directory + 4)))
|
||||
.map(|i| {
|
||||
let r = directory + 12 + 16 * i;
|
||||
(ttc[r..r + 4].try_into().unwrap(), be32(ttc, r + 4), be32(ttc, r + 8) as usize, be32(ttc, r + 12) as usize)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_offsets_are_file_relative() {
|
||||
let (a, b) = two_faces();
|
||||
let ttc = collection(&[&a, &b]).unwrap();
|
||||
let faces = ttc_faces(&ttc);
|
||||
assert_eq!(faces.len(), 2);
|
||||
for (directory, input) in faces.into_iter().zip([&a, &b]) {
|
||||
assert_eq!(&ttc[directory..directory + 12], &input[..12], "the sfnt header is copied");
|
||||
for (tag, _, offset, length) in ttc_tables(&ttc, directory) {
|
||||
let (_, from, from_length) = table(input, &tag);
|
||||
assert_eq!(length, from_length);
|
||||
let mut want = input[from..from + from_length].to_vec();
|
||||
if &tag == b"head" {
|
||||
set32(&mut want, 8, 0);
|
||||
}
|
||||
assert_eq!(&ttc[offset..offset + length], &want[..], "{} sits at its file offset", String::from_utf8_lossy(&tag));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_pads_odd_faces() {
|
||||
let (a, b) = two_faces();
|
||||
let ttc = collection(&[&a, &b]).unwrap();
|
||||
assert_eq!(ttc.len() % 4, 0);
|
||||
for directory in ttc_faces(&ttc) {
|
||||
assert_eq!(directory % 4, 0);
|
||||
for (_, _, offset, length) in ttc_tables(&ttc, directory) {
|
||||
assert_eq!(offset % 4, 0, "tables start on four-byte boundaries");
|
||||
let padded = length.div_ceil(4) * 4;
|
||||
assert!(ttc[offset + length..offset + padded].iter().all(|&b| b == 0), "padding is zero");
|
||||
}
|
||||
}
|
||||
let lengths: Vec<usize> = ttc_faces(&ttc).into_iter().flat_map(|d| ttc_tables(&ttc, d)).map(|t| t.3).collect();
|
||||
assert!(lengths.iter().any(|length| length % 4 != 0), "the fixture has unpadded lengths");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_checksums_match_tables() {
|
||||
let (a, b) = two_faces();
|
||||
let ttc = collection(&[&a, &b]).unwrap();
|
||||
for directory in ttc_faces(&ttc) {
|
||||
for (tag, checksum, offset, length) in ttc_tables(&ttc, directory) {
|
||||
assert_eq!(checksum, sum(&ttc[offset..offset + length]));
|
||||
if &tag == b"head" {
|
||||
assert_eq!(be32(&ttc, offset + 8), 0, "checkSumAdjustment is zero in a collection");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_copies_tables() {
|
||||
let (a, _) = two_faces();
|
||||
let ttc = collection(&[&a, &a]).unwrap();
|
||||
let mut ranges: Vec<(usize, usize)> = ttc_faces(&ttc).into_iter().flat_map(|d| ttc_tables(&ttc, d)).map(|t| (t.2, t.2 + t.3)).collect();
|
||||
assert_eq!(ranges.len(), 6);
|
||||
ranges.sort();
|
||||
assert!(ranges.windows(2).all(|pair| pair[0].1 <= pair[1].0), "each face has its own tables");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_rejects_empty() {
|
||||
assert_eq!(collection(&[]), Err(FontError::EmptyCollection));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_rejects_nested_ttc() {
|
||||
let (a, _) = two_faces();
|
||||
let ttc = collection(&[&a]).unwrap();
|
||||
assert_eq!(collection(&[&a, &ttc]), Err(FontError::UnsupportedFace));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_rejects_short_directory() {
|
||||
let (a, _) = two_faces();
|
||||
assert_eq!(collection(&[&a[..3]]), Err(FontError::MalformedFont));
|
||||
assert_eq!(collection(&[&a[..12 + 16 * 2]]), Err(FontError::MalformedFont));
|
||||
let mut many = a.clone();
|
||||
set16(&mut many, 4, 400);
|
||||
assert_eq!(collection(&[&a, &many]), Err(FontError::MalformedFont));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_rejects_out_of_range_table() {
|
||||
let (a, _) = two_faces();
|
||||
let (record, _, _) = table(&a, b"zzzz");
|
||||
let mut late = a.clone();
|
||||
set32(&mut late, record + 8, a.len() as u32);
|
||||
assert_eq!(collection(&[&late]), Err(FontError::MalformedFont));
|
||||
let mut long = a.clone();
|
||||
set32(&mut long, record + 12, u32::MAX);
|
||||
assert_eq!(collection(&[&long]), Err(FontError::MalformedFont));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_rejects_short_head() {
|
||||
let font = face(&[(b"head", head()[..8].to_vec())]);
|
||||
assert_eq!(collection(&[&font]), Err(FontError::MalformedFont));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_rejects_offset_overflow() {
|
||||
// 4,096 references to one face with a 1 MiB table add up to more than 4 GiB of output, which
|
||||
// 32-bit offsets cannot address. The function refuses before allocating any of it.
|
||||
let big = face(&[(b"zzzz", vec![0; 1 << 20])]);
|
||||
let faces = vec![&big[..]; 4096];
|
||||
assert_eq!(collection(&faces), Err(FontError::OutputTooLarge));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_rejects_directories_past_the_offset_limit() {
|
||||
// 65,536 references to one face with 4,096 empty tables: the table directories alone take more
|
||||
// than 4 GiB. The function refuses without keeping a directory for every face.
|
||||
let tables: Vec<(&[u8; 4], Vec<u8>)> = (0..4096).map(|_| (b"zzzz", Vec::new())).collect();
|
||||
let many = face(&tables);
|
||||
let faces = vec![&many[..]; 65536];
|
||||
assert_eq!(collection(&faces), Err(FontError::OutputTooLarge));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_counts_directories_before_reading_records() {
|
||||
// The same number of directories, each with every table record out of range. The size limit is
|
||||
// found from the faces' table counts before any table record is read.
|
||||
let mut directory = vec![0u8; 12 + 16 * 4096];
|
||||
set32(&mut directory, 0, 0x0001_0000);
|
||||
set16(&mut directory, 4, 4096);
|
||||
for index in 0..4096 {
|
||||
set32(&mut directory, 12 + 16 * index + 8, u32::MAX);
|
||||
}
|
||||
let faces = vec![&directory[..]; 65536];
|
||||
assert_eq!(collection(&faces), Err(FontError::OutputTooLarge));
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! The crate's integration tests, linked into one test binary.
|
||||
|
||||
mod fonts;
|
||||
mod guards;
|
||||
mod source_limits;
|
||||
@@ -0,0 +1,605 @@
|
||||
#![cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_testkit::mcp::{McpChild, McpError, McpLimits, PROTOCOL_VERSION};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// An in-process MCP server: answers each line it reads with `reply(method, message)`; `None`
|
||||
/// sends nothing. A reply from the client has the method `""`. Returns the client side.
|
||||
fn fake_with<F>(limits: McpLimits, reply: F) -> McpChild
|
||||
where
|
||||
F: Fn(&str, &Value) -> Option<Vec<String>> + Send + 'static,
|
||||
{
|
||||
let (client_r, mut server_w) = std::io::pipe().unwrap();
|
||||
let (server_r, client_w) = std::io::pipe().unwrap();
|
||||
std::thread::spawn(move || {
|
||||
for line in BufReader::new(server_r).lines() {
|
||||
let Ok(line) = line else { return };
|
||||
let Ok(req) = serde_json::from_str::<Value>(&line) else {
|
||||
continue;
|
||||
};
|
||||
let method = req["method"].as_str().unwrap_or("").to_string();
|
||||
let Some(out) = reply(&method, &req) else {
|
||||
continue;
|
||||
};
|
||||
for l in out {
|
||||
if server_w.write_all(format!("{l}\n").as_bytes()).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
McpChild::connect(client_r, client_w, limits).unwrap()
|
||||
}
|
||||
|
||||
fn fake<F>(reply: F) -> McpChild
|
||||
where
|
||||
F: Fn(&str, &Value) -> Option<Vec<String>> + Send + 'static,
|
||||
{
|
||||
fake_with(McpLimits::default(), reply)
|
||||
}
|
||||
|
||||
fn result(req: &Value, result: Value) -> String {
|
||||
json!({"jsonrpc": "2.0", "id": req["id"], "result": result}).to_string()
|
||||
}
|
||||
|
||||
/// A deadline for replies that never come.
|
||||
const SHORT: Duration = Duration::from_millis(200);
|
||||
/// A deadline that a passing test does not reach.
|
||||
const LONG: Duration = Duration::from_secs(30);
|
||||
|
||||
#[test]
|
||||
fn handshake_list_and_call() {
|
||||
let initialized = Arc::new(AtomicBool::new(false));
|
||||
let seen = initialized.clone();
|
||||
let mut c = fake(move |m, req| match m {
|
||||
"initialize" => Some(vec![result(
|
||||
req,
|
||||
json!({"protocolVersion": req["params"]["protocolVersion"], "capabilities": {}, "serverInfo": {"name": "fake", "version": "0"}}),
|
||||
)]),
|
||||
"notifications/initialized" => {
|
||||
assert!(req.get("id").is_none(), "a notification has no id");
|
||||
seen.store(true, Ordering::SeqCst);
|
||||
None
|
||||
}
|
||||
// The list is sent only after `notifications/initialized`, which the client sends first.
|
||||
"tools/list" if seen.load(Ordering::SeqCst) => Some(vec![result(req, json!({"tools": [{"name": "doc.new"}, {"no": "name"}]}))]),
|
||||
"tools/call" => Some(vec![result(req, json!({"content": [{"type": "text", "text": req["params"]["name"]}]}))]),
|
||||
_ => None,
|
||||
});
|
||||
let init = c.initialize(PROTOCOL_VERSION).unwrap();
|
||||
assert_eq!(init["protocolVersion"], PROTOCOL_VERSION);
|
||||
let tools = c.list_tools().unwrap();
|
||||
assert_eq!(tools.len(), 2, "the list is returned as the server sent it");
|
||||
assert!(initialized.load(Ordering::SeqCst));
|
||||
let r = c.call_tool_within("doc.new", json!({}), Duration::from_secs(5)).unwrap();
|
||||
assert_eq!(r["content"][0]["text"], "doc.new");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initialize_requires_capabilities_and_server_info() {
|
||||
for fields in [
|
||||
json!({}),
|
||||
json!({"capabilities": []}),
|
||||
json!({"capabilities": {}}),
|
||||
json!({"capabilities": {}, "serverInfo": []}),
|
||||
json!({"capabilities": {}, "serverInfo": {}}),
|
||||
json!({"capabilities": {}, "serverInfo": {"name": "fake"}}),
|
||||
json!({"capabilities": {}, "serverInfo": {"name": 1, "version": "0"}}),
|
||||
json!({"capabilities": {}, "serverInfo": {"name": "fake", "version": 1}}),
|
||||
] {
|
||||
let mut c = fake(move |_, req| {
|
||||
let mut reply = fields.clone();
|
||||
reply["protocolVersion"] = json!(PROTOCOL_VERSION);
|
||||
Some(vec![result(req, reply)])
|
||||
});
|
||||
assert!(matches!(c.initialize(PROTOCOL_VERSION), Err(McpError::Protocol(_))));
|
||||
assert!(c.closed().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_requests_require_string_or_integer_ids() {
|
||||
for id in [Value::Null, json!(1.5), json!(1.0), json!(1e2)] {
|
||||
let mut c = fake(move |method, req| match method {
|
||||
"x" => Some(vec![json!({"jsonrpc": "2.0", "id": id, "method": "ping"}).to_string(), result(req, json!(true))]),
|
||||
_ => None,
|
||||
});
|
||||
assert!(matches!(c.request("x", Value::Null), Err(McpError::Protocol(_))));
|
||||
assert!(c.closed().is_some());
|
||||
}
|
||||
for id in [json!("server"), json!(-1), json!(u64::MAX)] {
|
||||
let expected = id.clone();
|
||||
let mut c = fake(move |method, req| match method {
|
||||
"x" => Some(vec![json!({"jsonrpc": "2.0", "id": id, "method": "ping"}).to_string()]),
|
||||
"" => {
|
||||
assert_eq!(req["id"], expected);
|
||||
Some(vec![json!({"jsonrpc": "2.0", "id": 1, "result": true}).to_string()])
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(c.request("x", Value::Null).unwrap(), json!(true));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pages_are_followed() {
|
||||
let mut c = fake(|m, req| match m {
|
||||
"tools/list" if req["params"]["cursor"].is_null() => Some(vec![result(req, json!({"tools": [{"name": "a"}], "nextCursor": "p2"}))]),
|
||||
"tools/list" if req["params"]["cursor"] == "p2" => Some(vec![result(req, json!({"tools": [{"name": "b"}]}))]),
|
||||
"tools/list" => panic!("unexpected cursor: {}", req["params"]["cursor"]),
|
||||
_ => None,
|
||||
});
|
||||
let names: Vec<String> = c.list_tools().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect();
|
||||
assert_eq!(names, vec!["a", "b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_result_envelopes_are_required() {
|
||||
for within in [false, true] {
|
||||
for malformed in [
|
||||
json!(null),
|
||||
json!({}),
|
||||
json!({"content": true}),
|
||||
json!({"content": [], "isError": 1}),
|
||||
json!({"content": [], "structuredContent": []}),
|
||||
json!({"content": [], "_meta": null}),
|
||||
] {
|
||||
let mut client = fake(move |_, req| Some(vec![result(req, malformed.clone())]));
|
||||
let reply = if within { client.call_tool_within("probe", json!({}), LONG) } else { client.call_tool("probe", json!({})) };
|
||||
assert!(matches!(reply, Err(McpError::Protocol(_))), "{reply:?}");
|
||||
assert!(client.closed().is_some());
|
||||
}
|
||||
for valid in [
|
||||
json!({"content": []}),
|
||||
json!({"content": [], "isError": true}),
|
||||
json!({"content": [], "structuredContent": {"value": 1}, "_meta": {}, "extra": "kept"}),
|
||||
] {
|
||||
let sent = valid.clone();
|
||||
let mut client = fake(move |_, req| Some(vec![result(req, sent.clone())]));
|
||||
let reply = if within { client.call_tool_within("probe", json!({}), LONG) } else { client.call_tool("probe", json!({})) };
|
||||
assert_eq!(reply.unwrap(), valid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_request_params_are_objects() {
|
||||
for params in [json!(true), json!(1), json!("bad"), json!(null), json!([])] {
|
||||
let mut client = fake(move |method, req| {
|
||||
(method == "probe")
|
||||
.then(|| vec![json!({"jsonrpc": "2.0", "id": "server", "method": "ping", "params": params}).to_string(), result(req, json!("done"))])
|
||||
});
|
||||
assert!(matches!(client.request("probe", json!({})), Err(McpError::Protocol(_))));
|
||||
}
|
||||
let mut client = fake(|method, req| {
|
||||
(method == "probe")
|
||||
.then(|| vec![json!({"jsonrpc": "2.0", "id": "server", "method": "ping", "params": {}}).to_string(), result(req, json!("done"))])
|
||||
});
|
||||
assert_eq!(client.request("probe", json!({})).unwrap(), "done");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notifications_are_bounded_by_total_json_bytes() {
|
||||
let notes: Vec<Value> = (0..3)
|
||||
.map(|index| json!({"jsonrpc": "2.0", "method": "notifications/message", "params": {"index": index, "data": "x".repeat(96)}}))
|
||||
.collect();
|
||||
let limits = McpLimits { max_notifications: 4, max_line_bytes: notes[0].to_string().len() * 3 / 2, ..McpLimits::default() };
|
||||
let sent = notes.clone();
|
||||
let mut c = fake_with(limits, move |_, req| {
|
||||
let mut lines: Vec<String> = sent.iter().map(Value::to_string).collect();
|
||||
lines.push(result(req, json!(true)));
|
||||
Some(lines)
|
||||
});
|
||||
assert_eq!(c.request("x", Value::Null).unwrap(), json!(true));
|
||||
assert_eq!(c.take_notifications(), vec![notes[2].clone()]);
|
||||
assert!(c.take_notifications().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_notification_larger_than_the_capture_budget_keeps_earlier_messages() {
|
||||
let oversized = r#"{"jsonrpc":"2.0","method":"n","params":{"n":1e1}}"#;
|
||||
let kept = json!({"jsonrpc": "2.0", "method": "n", "params": {}});
|
||||
let limits = McpLimits { max_notifications: 4, max_line_bytes: oversized.len(), ..McpLimits::default() };
|
||||
let first = kept.to_string();
|
||||
let mut c = fake_with(limits, move |_, req| Some(vec![first.clone(), oversized.to_string(), result(req, json!(true))]));
|
||||
assert_eq!(c.request("x", Value::Null).unwrap(), json!(true));
|
||||
assert_eq!(c.take_notifications(), vec![kept]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notifications_log_lines_and_stale_replies_are_skipped() {
|
||||
// A log line on stdout is a protocol error (`non_json_stdout_is_protocol_error`); a
|
||||
// notification and a stale reply are skipped.
|
||||
let mut c = fake(|_, req| {
|
||||
Some(vec![
|
||||
json!({"jsonrpc": "2.0", "method": "notifications/message", "params": {"level": "info", "data": "starting up"}}).to_string(),
|
||||
json!({"jsonrpc": "2.0", "method": "notifications/progress", "params": {}}).to_string(),
|
||||
json!({"jsonrpc": "2.0", "id": 999, "result": "stale"}).to_string(),
|
||||
result(req, json!("mine")),
|
||||
])
|
||||
});
|
||||
assert_eq!(c.request_within("x", json!({}), Duration::from_secs(5)).unwrap(), json!("mine"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_from_the_app_is_refused_and_the_reply_still_arrives() {
|
||||
let refusal: Arc<Mutex<Option<Value>>> = Arc::default();
|
||||
let log = refusal.clone();
|
||||
let mut c = fake(move |m, req| match m {
|
||||
"x" => Some(vec![json!({"jsonrpc": "2.0", "id": "srv-1", "method": "sampling/createMessage"}).to_string()]),
|
||||
// The reply to `x` follows the client's answer to the server's request.
|
||||
"" => {
|
||||
*log.lock().unwrap() = Some(req.clone());
|
||||
Some(vec![json!({"jsonrpc": "2.0", "id": 1, "result": 1}).to_string()])
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(c.request_within("x", json!({}), Duration::from_secs(5)).unwrap(), json!(1));
|
||||
let refusal = refusal.lock().unwrap().clone().unwrap();
|
||||
assert_eq!(refusal["id"], "srv-1");
|
||||
assert_eq!(refusal["error"]["code"], -32601);
|
||||
assert!(refusal.get("result").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_reply_is_an_err_and_the_connection_stays_usable() {
|
||||
let mut c = fake(|m, req| match m {
|
||||
"bad" => {
|
||||
Some(vec![json!({"jsonrpc": "2.0", "id": req["id"], "error": {"code": -1, "message": "nope", "data": {"why": "test"}}}).to_string()])
|
||||
}
|
||||
_ => Some(vec![result(req, json!(true))]),
|
||||
});
|
||||
match c.request_within("bad", json!({}), Duration::from_secs(5)) {
|
||||
Err(McpError::Rpc { method, code, message, data }) => {
|
||||
assert_eq!((method.as_str(), code, message.as_str()), ("bad", -1, "nope"));
|
||||
assert_eq!(data, Some(json!({"why": "test"})));
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert!(c.closed().is_none());
|
||||
assert_eq!(c.request_within("ok", json!({}), Duration::from_secs(5)).unwrap(), json!(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_silent_app_times_out_and_the_connection_is_closed() {
|
||||
let mut c = fake(|_, _| None);
|
||||
let err = c.request_within("x", json!({}), Duration::from_millis(100)).unwrap_err();
|
||||
assert!(matches!(&err, McpError::Deadline { method, .. } if method == "x"), "{err}");
|
||||
assert!(c.closed().is_some());
|
||||
assert!(matches!(c.request_within("y", json!({}), Duration::from_secs(5)), Err(McpError::Closed(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_app_that_exits_is_reported() {
|
||||
let (client_r, server_w) = std::io::pipe().unwrap();
|
||||
let (_server_r, client_w) = std::io::pipe().unwrap();
|
||||
drop(server_w);
|
||||
let mut c = McpChild::connect(client_r, client_w, McpLimits::default()).unwrap();
|
||||
let err = c.request_within("x", json!({}), Duration::from_secs(5)).unwrap_err();
|
||||
assert!(matches!(err, McpError::Ended), "{err}");
|
||||
assert!(c.closed().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_cli_is_an_error_not_a_panic() {
|
||||
let program = std::env::temp_dir().join("no-such-craft-cli-for-tests");
|
||||
let err = McpChild::spawn(&program, ["mcp"], [("CRAFT_TESTKIT_UNUSED", "1")]).unwrap_err();
|
||||
assert!(matches!(&err, McpError::Spawn { program: p, .. } if p.as_os_str() == program.as_os_str()), "{err}");
|
||||
assert!(err.to_string().contains("could not start"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tool_list_that_never_ends_is_an_error_not_a_partial_list() {
|
||||
let mut c = fake(|m, req| match m {
|
||||
"tools/list" => Some(vec![result(req, json!({"tools": [{"name": "a"}], "nextCursor": "more"}))]),
|
||||
_ => None,
|
||||
});
|
||||
let err = c.list_tools().unwrap_err();
|
||||
assert!(matches!(err, McpError::TooManyPages { limit: 64 }), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tool_list_larger_than_the_limit_is_an_error() {
|
||||
// Each page fits in a line; the pages together do not.
|
||||
let limits = McpLimits { max_line_bytes: 256, ..McpLimits::default() };
|
||||
let mut c = fake_with(limits, |m, req| match m {
|
||||
"tools/list" => Some(vec![result(req, json!({"tools": [{"name": "x".repeat(100)}], "nextCursor": "more"}))]),
|
||||
_ => None,
|
||||
});
|
||||
let err = c.list_tools().unwrap_err();
|
||||
assert!(matches!(err, McpError::ToolListTooLarge { limit: 256 }), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_app_that_stops_reading_times_out_instead_of_blocking_the_write() {
|
||||
// The server side never reads, so the pipe fills and the write blocks the writer thread, not
|
||||
// the request.
|
||||
let (client_r, _server_w) = std::io::pipe().unwrap();
|
||||
let (server_r, client_w) = std::io::pipe().unwrap();
|
||||
let mut c = McpChild::connect(client_r, client_w, McpLimits::default()).unwrap();
|
||||
let big = "x".repeat(4 << 20);
|
||||
let err = c.call_tool_within("t", json!({"data": big}), Duration::from_millis(300)).unwrap_err();
|
||||
assert!(matches!(err, McpError::Deadline { .. }), "{err}");
|
||||
drop(server_r);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tools_changed_notification_is_remembered_once() {
|
||||
let limits = McpLimits { max_notifications: 8, ..McpLimits::default() };
|
||||
let mut c = fake_with(limits, |m, req| match m {
|
||||
"x" => Some(vec![json!({"jsonrpc": "2.0", "method": "notifications/tools/list_changed"}).to_string(), result(req, json!(1))]),
|
||||
_ => None,
|
||||
});
|
||||
assert!(c.take_notifications().is_empty());
|
||||
c.request_within("x", json!({}), Duration::from_secs(5)).unwrap();
|
||||
let kept = c.take_notifications();
|
||||
assert_eq!(kept.len(), 1, "{kept:?}");
|
||||
assert_eq!(kept[0]["method"], "notifications/tools/list_changed");
|
||||
assert!(c.take_notifications().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notifications_are_kept_up_to_the_limit_newest_last() {
|
||||
let limits = McpLimits { max_notifications: 2, ..McpLimits::default() };
|
||||
let mut c = fake_with(limits, |m, req| match m {
|
||||
"x" => {
|
||||
let mut out: Vec<String> =
|
||||
(0..5).map(|n| json!({"jsonrpc": "2.0", "method": "notifications/progress", "params": {"n": n}}).to_string()).collect();
|
||||
out.push(result(req, json!(1)));
|
||||
Some(out)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
c.request_within("x", json!({}), Duration::from_secs(5)).unwrap();
|
||||
let kept: Vec<Value> = c.take_notifications().iter().map(|n| n["params"]["n"].clone()).collect();
|
||||
assert_eq!(kept, vec![json!(3), json!(4)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn take_notifications_returns_while_the_server_keeps_writing() {
|
||||
let (client_r, mut server_w) = std::io::pipe().unwrap();
|
||||
let (_server_r, client_w) = std::io::pipe().unwrap();
|
||||
std::thread::spawn(move || {
|
||||
let note = format!("{}\n", json!({"jsonrpc": "2.0", "method": "notifications/progress", "params": {}}));
|
||||
while server_w.write_all(note.as_bytes()).is_ok() {}
|
||||
});
|
||||
let limits = McpLimits { max_notifications: 8, ..McpLimits::default() };
|
||||
let mut c = McpChild::connect(client_r, client_w, limits).unwrap();
|
||||
for _ in 0..3 {
|
||||
assert!(c.take_notifications().len() <= 8);
|
||||
}
|
||||
assert!(c.closed().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_write_ends_the_waiting_request_at_once() {
|
||||
struct Broken;
|
||||
impl std::io::Write for Broken {
|
||||
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
|
||||
Err(std::io::Error::other("stdin closed"))
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
// The app keeps stdout open but takes nothing on stdin. The deadline is an hour, so a write
|
||||
// failure that did not end the request would show as a hung test.
|
||||
let (client_r, _server_w) = std::io::pipe().unwrap();
|
||||
let mut c = McpChild::connect(client_r, Broken, McpLimits::default()).unwrap();
|
||||
let err = c.request_within("x", json!({}), Duration::from_secs(3600)).unwrap_err();
|
||||
assert!(matches!(&err, McpError::Io { what: "writing to the child", .. }), "{err}");
|
||||
assert!(err.to_string().contains("stdin closed"), "{err}");
|
||||
assert!(c.closed().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_app_ping_gets_an_empty_result_during_a_request_and_between_them() {
|
||||
// `x` brings a ping before its reply and one after it. The second is read while `y` waits;
|
||||
// the server answers `y` once both pings have their answers, with those answers.
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
answers: Vec<Value>,
|
||||
y: Option<Value>,
|
||||
}
|
||||
let state: Arc<Mutex<State>> = Arc::default();
|
||||
let mut c = fake(move |m, req| {
|
||||
let mut s = state.lock().unwrap();
|
||||
match m {
|
||||
"x" => Some(vec![
|
||||
json!({"jsonrpc": "2.0", "id": "p1", "method": "ping"}).to_string(),
|
||||
result(req, json!(1)),
|
||||
json!({"jsonrpc": "2.0", "id": "p2", "method": "ping"}).to_string(),
|
||||
]),
|
||||
"y" => {
|
||||
s.y = Some(req.clone());
|
||||
None
|
||||
}
|
||||
"" => {
|
||||
s.answers.push(req.clone());
|
||||
None
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
.or_else(|| {
|
||||
let ready = s.answers.len() == 2;
|
||||
let y = if ready { s.y.take() } else { None }?;
|
||||
Some(vec![result(&y, json!(s.answers))])
|
||||
})
|
||||
});
|
||||
assert_eq!(c.request_within("x", json!({}), Duration::from_secs(5)).unwrap(), json!(1));
|
||||
let answers = c.request_within("y", json!({}), Duration::from_secs(5)).unwrap();
|
||||
for id in ["p1", "p2"] {
|
||||
let reply = answers.as_array().unwrap().iter().find(|v| v["id"] == id).unwrap_or_else(|| panic!("no reply to {id}: {answers}"));
|
||||
assert_eq!(reply["result"], json!({}), "{reply}");
|
||||
assert!(reply.get("error").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn over_long_line_returns_error() {
|
||||
let limits = McpLimits { max_line_bytes: 16, ..McpLimits::default() };
|
||||
// The line has no newline yet, and the server keeps its end open.
|
||||
let (client_r, mut server_w) = std::io::pipe().unwrap();
|
||||
let (_server_r, client_w) = std::io::pipe().unwrap();
|
||||
server_w.write_all(&[b'x'; 64]).unwrap();
|
||||
let mut c = McpChild::connect(client_r, client_w, limits).unwrap();
|
||||
let err = c.request_within("x", json!({}), LONG).unwrap_err();
|
||||
assert!(matches!(err, McpError::LineTooLong { limit: 16 }), "{err}");
|
||||
assert!(c.closed().is_some());
|
||||
drop(server_w);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_id_does_not_satisfy_request() {
|
||||
let mut c = fake(|_, req| {
|
||||
let id = req["id"].as_u64().unwrap();
|
||||
Some(vec![
|
||||
json!({"jsonrpc": "2.0", "id": id + 1, "result": "other"}).to_string(),
|
||||
json!({"jsonrpc": "2.0", "id": id.to_string(), "result": "string id"}).to_string(),
|
||||
json!({"jsonrpc": "2.0", "id": null, "result": "null id"}).to_string(),
|
||||
])
|
||||
});
|
||||
let err = c.request_within("x", json!({}), SHORT).unwrap_err();
|
||||
assert!(matches!(err, McpError::Deadline { .. }), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flood_of_stale_replies_does_not_extend_the_deadline() {
|
||||
let (client_r, mut server_w) = std::io::pipe().unwrap();
|
||||
let (_server_r, client_w) = std::io::pipe().unwrap();
|
||||
std::thread::spawn(move || {
|
||||
let stale = format!("{}\n", json!({"jsonrpc": "2.0", "id": 999, "result": "stale"}));
|
||||
while server_w.write_all(stale.as_bytes()).is_ok() {}
|
||||
});
|
||||
let mut c = McpChild::connect(client_r, client_w, McpLimits::default()).unwrap();
|
||||
let err = c.request_within("x", json!({}), SHORT).unwrap_err();
|
||||
assert!(matches!(err, McpError::Deadline { .. }), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_json_stdout_is_protocol_error() {
|
||||
for line in ["starting up...", r#"{"id": 1, "result": 1}"#, "[]", "\u{fffd}\u{0}"] {
|
||||
let line = line.to_string();
|
||||
let mut c = fake(move |_, _| Some(vec![line.clone()]));
|
||||
let err = c.request_within("x", json!({}), LONG).unwrap_err();
|
||||
assert!(matches!(err, McpError::Protocol(_)), "{err}");
|
||||
assert!(c.closed().is_some());
|
||||
}
|
||||
// Bytes that are not UTF-8.
|
||||
let (client_r, mut server_w) = std::io::pipe().unwrap();
|
||||
let (_server_r, client_w) = std::io::pipe().unwrap();
|
||||
server_w.write_all(b"{\"jsonrpc\": \"2.0\", \"method\": \"\xff\"}\n").unwrap();
|
||||
let mut c = McpChild::connect(client_r, client_w, McpLimits::default()).unwrap();
|
||||
let err = c.request_within("x", json!({}), LONG).unwrap_err();
|
||||
assert!(matches!(err, McpError::Protocol(_)), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blank_stdout_line_is_protocol_error() {
|
||||
// The fake ends each line with a newline, so these send "\n" and " \r\n".
|
||||
for blank in ["", " \r"] {
|
||||
let mut c = fake(move |_, req| Some(vec![blank.to_string(), result(req, json!(1))]));
|
||||
let err = c.request_within("x", json!({}), LONG).unwrap_err();
|
||||
assert!(matches!(err, McpError::Protocol(_)), "{blank:?}: {err}");
|
||||
assert!(c.closed().is_some());
|
||||
// Without a reply after it, the blank line still ends the request before its deadline.
|
||||
let mut c = fake(move |_, _| Some(vec![blank.to_string()]));
|
||||
let err = c.request_within("x", json!({}), LONG).unwrap_err();
|
||||
assert!(matches!(err, McpError::Protocol(_)), "{blank:?}: {err}");
|
||||
assert!(c.closed().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_reply_is_a_protocol_error() {
|
||||
for reply in [json!({"result": 1, "error": {"code": 1, "message": "both"}}), json!({}), json!({"error": {"code": "x", "message": "m"}})] {
|
||||
let mut c = fake(move |_, req| {
|
||||
let mut msg = reply.clone();
|
||||
msg["jsonrpc"] = json!("2.0");
|
||||
msg["id"] = req["id"].clone();
|
||||
Some(vec![msg.to_string()])
|
||||
});
|
||||
let err = c.request_within("x", json!({}), LONG).unwrap_err();
|
||||
assert!(matches!(err, McpError::Protocol(_)), "{err}");
|
||||
assert!(c.closed().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_message_with_an_invalid_id_is_a_protocol_error() {
|
||||
let replies = [
|
||||
json!({"jsonrpc": "2.0", "id": true, "result": 1}),
|
||||
json!({"jsonrpc": "2.0", "id": [1], "result": 1}),
|
||||
json!({"jsonrpc": "2.0", "id": {"n": 1}, "error": {"code": 1, "message": "m"}}),
|
||||
json!({"jsonrpc": "2.0", "id": false, "method": "ping"}),
|
||||
];
|
||||
for msg in replies {
|
||||
let mut c = fake(move |_, _| Some(vec![msg.to_string()]));
|
||||
let err = c.request_within("x", json!({}), LONG).unwrap_err();
|
||||
assert!(matches!(err, McpError::Protocol(_)), "{err}");
|
||||
assert!(c.closed().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_reply_to_another_id_is_a_protocol_error() {
|
||||
let replies = [
|
||||
json!({"jsonrpc": "2.0", "id": 9999, "result": 1, "error": {"code": 1, "message": "both"}}),
|
||||
json!({"jsonrpc": "2.0", "id": "other"}),
|
||||
json!({"jsonrpc": "2.0", "id": null, "error": {"code": "x", "message": "m"}}),
|
||||
];
|
||||
for msg in replies {
|
||||
let mut c = fake(move |_, _| Some(vec![msg.to_string()]));
|
||||
let err = c.request_within("x", json!({}), LONG).unwrap_err();
|
||||
assert!(matches!(err, McpError::Protocol(_)), "{err}");
|
||||
assert!(c.closed().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tool_error_result_is_returned_unchanged() {
|
||||
let mut c = fake(|_, req| Some(vec![result(req, json!({"content": [{"type": "text", "text": "no document"}], "isError": true}))]));
|
||||
let r = c.call_tool("doc.save", json!({})).unwrap();
|
||||
assert_eq!(r["isError"], true);
|
||||
assert!(c.closed().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_different_protocol_version_is_an_error_and_closes() {
|
||||
let mut c = fake(|m, req| match m {
|
||||
"initialize" => Some(vec![result(req, json!({"protocolVersion": "2024-11-05"}))]),
|
||||
_ => None,
|
||||
});
|
||||
let err = c.initialize(PROTOCOL_VERSION).unwrap_err();
|
||||
assert!(
|
||||
matches!(&err, McpError::UnsupportedVersion { requested, returned } if requested == PROTOCOL_VERSION && returned == "2024-11-05"),
|
||||
"{err}"
|
||||
);
|
||||
assert!(c.closed().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_limits_and_environment_are_setup_errors() {
|
||||
let zero_line = McpLimits { max_line_bytes: 0, ..McpLimits::default() };
|
||||
let zero_deadline = McpLimits { request_timeout: Duration::ZERO, ..McpLimits::default() };
|
||||
let long_deadline = McpLimits { initialize_timeout: Duration::from_secs(3601), ..McpLimits::default() };
|
||||
let many_notes = McpLimits { max_notifications: 4097, ..McpLimits::default() };
|
||||
for limits in [zero_line, zero_deadline, long_deadline, many_notes] {
|
||||
let (client_r, _server_w) = std::io::pipe().unwrap();
|
||||
let (_server_r, client_w) = std::io::pipe().unwrap();
|
||||
assert!(matches!(McpChild::connect(client_r, client_w, limits.clone()), Err(McpError::Setup(_))), "{limits:?}");
|
||||
}
|
||||
let program = std::env::temp_dir().join("no-such-craft-cli-for-tests");
|
||||
for (key, value) in [("", "1"), ("A=B", "1"), ("A\0B", "1"), ("A", "1\0")] {
|
||||
let err = McpChild::spawn(&program, ["mcp"], [(key, value)]).unwrap_err();
|
||||
assert!(matches!(err, McpError::Setup(_)), "{key:?}={value:?}: {err}");
|
||||
}
|
||||
let mut c = fake(|_, _| None);
|
||||
assert!(matches!(c.request_within("x", json!({}), Duration::ZERO), Err(McpError::Setup(_))));
|
||||
assert!(c.closed().is_none(), "a bad deadline does not close the connection");
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//! `McpChild` against a real child process. The child is this test program, started again with
|
||||
//! `CRAFT_TESTKIT_MCP_CHILD` naming the server it acts as. The target has `harness = false`
|
||||
//! because the standard test harness writes its own lines on stdout, which an MCP child must not
|
||||
//! do. `main` runs each test whose name contains every argument that does not start with `-`, and
|
||||
//! `--list` lists them. On `wasm32`, where the `mcp` module is not built, `main` does nothing.
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[path = "mcp_child/child.rs"]
|
||||
mod child;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn main() -> std::process::ExitCode {
|
||||
child::run()
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn main() {}
|
||||
@@ -0,0 +1,265 @@
|
||||
use std::io::{BufRead, Write};
|
||||
use std::process::ExitCode;
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_testkit::mcp::{McpChild, McpError, McpLimits, PROTOCOL_VERSION};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The server the child acts as.
|
||||
const CHILD_VAR: &str = "CRAFT_TESTKIT_MCP_CHILD";
|
||||
/// Text the `server` child returns from every tool call.
|
||||
const ECHO_VAR: &str = "CRAFT_TESTKIT_MCP_ECHO";
|
||||
/// Bytes the `flood` child writes on stderr before each reply, more than a pipe holds.
|
||||
const FLOOD: usize = 1 << 20;
|
||||
|
||||
type Test = fn() -> Result<(), String>;
|
||||
|
||||
const TESTS: &[(&str, Test)] = &[
|
||||
("a_spawned_server_answers_and_closes_cleanly", a_spawned_server_answers_and_closes_cleanly),
|
||||
("silent_spawned_child_hits_deadline", silent_spawned_child_hits_deadline),
|
||||
("child_exits_before_initialize", child_exits_before_initialize),
|
||||
("stderr_flood_does_not_block", stderr_flood_does_not_block),
|
||||
("close_forces_and_reaps_unresponsive_child", close_forces_and_reaps_unresponsive_child),
|
||||
("close_keeps_stderr_written_before_exit", close_keeps_stderr_written_before_exit),
|
||||
("skip_filters_exclude_tests_from_the_child_runner", skip_filters_exclude_tests_from_the_child_runner),
|
||||
("thread_count_options_preserve_child_test_selection", thread_count_options_preserve_child_test_selection),
|
||||
("close_drains_stdout_before_child_exit", close_drains_stdout_before_child_exit),
|
||||
];
|
||||
|
||||
pub fn run() -> ExitCode {
|
||||
if let Some(mode) = std::env::var_os(CHILD_VAR) {
|
||||
return serve(&mode.to_string_lossy());
|
||||
}
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let mut filters = Vec::new();
|
||||
let mut skipped = Vec::new();
|
||||
let mut options = args.iter();
|
||||
while let Some(arg) = options.next() {
|
||||
if arg == "--test-threads" {
|
||||
if !options.next().is_some_and(|value| value.parse::<usize>().is_ok_and(|count| count > 0)) {
|
||||
eprintln!("--test-threads requires a positive integer");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
} else if let Some(value) = arg.strip_prefix("--test-threads=") {
|
||||
if !value.parse::<usize>().is_ok_and(|count| count > 0) {
|
||||
eprintln!("--test-threads requires a positive integer");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
} else if arg == "--skip" {
|
||||
let Some(filter) = options.next().filter(|value| !value.is_empty() && !value.starts_with('-')) else {
|
||||
eprintln!("--skip requires a test name");
|
||||
return ExitCode::FAILURE;
|
||||
};
|
||||
skipped.push(filter.as_str());
|
||||
} else if let Some(filter) = arg.strip_prefix("--skip=") {
|
||||
if filter.is_empty() || filter.starts_with('-') {
|
||||
eprintln!("--skip requires a test name");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
skipped.push(filter);
|
||||
} else if !arg.starts_with('-') {
|
||||
filters.push(arg.as_str());
|
||||
}
|
||||
}
|
||||
let chosen: Vec<&(&str, Test)> =
|
||||
TESTS.iter().filter(|(name, _)| filters.iter().all(|f| name.contains(*f)) && !skipped.iter().any(|f| name.contains(*f))).collect();
|
||||
if args.iter().any(|a| a == "--list") {
|
||||
for (name, _) in chosen {
|
||||
println!("{name}: test");
|
||||
}
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
println!("\nrunning {} tests", chosen.len());
|
||||
let mut failed = 0;
|
||||
for (name, test) in &chosen {
|
||||
match test() {
|
||||
Ok(()) => println!("test {name} ... ok"),
|
||||
Err(why) => {
|
||||
failed += 1;
|
||||
println!("test {name} ... FAILED\n {why}");
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("\ntest result: {}. {} passed; {failed} failed", if failed == 0 { "ok" } else { "FAILED" }, chosen.len() - failed);
|
||||
if failed == 0 { ExitCode::SUCCESS } else { ExitCode::FAILURE }
|
||||
}
|
||||
|
||||
/// Runs as the child: `server` answers `initialize` with the version asked for and every tool call
|
||||
/// with `ECHO_VAR`, and exits when its stdin closes; `flood` also writes `FLOOD` bytes and `END` on
|
||||
/// stderr before each reply; `silent` reads and never answers; `stubborn` answers but does not
|
||||
/// exit when its stdin closes; `exit` exits at once with code 3; `goodbye` writes `FLOOD` bytes and
|
||||
/// `BYE` on stderr and exits without reading.
|
||||
fn serve(mode: &str) -> ExitCode {
|
||||
if mode == "exit" {
|
||||
return ExitCode::from(3);
|
||||
}
|
||||
if mode == "goodbye" {
|
||||
let mut err = std::io::stderr();
|
||||
let written = err.write_all(&vec![b'e'; FLOOD]).and_then(|()| err.write_all(b"BYE"));
|
||||
return if written.is_ok() { ExitCode::SUCCESS } else { ExitCode::FAILURE };
|
||||
}
|
||||
let stdin = std::io::stdin();
|
||||
let mut out = std::io::stdout();
|
||||
for line in stdin.lock().lines() {
|
||||
let Ok(line) = line else { break };
|
||||
let Ok(req) = serde_json::from_str::<Value>(&line) else { continue };
|
||||
if mode == "silent" || req.get("id").is_none() {
|
||||
continue;
|
||||
}
|
||||
let result = match req["method"].as_str() {
|
||||
Some("initialize") => {
|
||||
json!({"protocolVersion": req["params"]["protocolVersion"], "capabilities": {}, "serverInfo": {"name": "child", "version": "0"}})
|
||||
}
|
||||
Some("tools/call") => {
|
||||
let text = std::env::var(ECHO_VAR).unwrap_or_default();
|
||||
json!({"content": [{"type": "text", "text": text}], "isError": false})
|
||||
}
|
||||
_ => json!(null),
|
||||
};
|
||||
if mode == "flood" {
|
||||
let mut err = std::io::stderr();
|
||||
if err.write_all(&vec![b'e'; FLOOD]).and_then(|()| err.write_all(b"END")).is_err() {
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
}
|
||||
let reply = json!({"jsonrpc": "2.0", "id": req["id"], "result": result});
|
||||
if writeln!(out, "{reply}").and_then(|()| out.flush()).is_err() {
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
}
|
||||
if mode == "stdout-after-eof" {
|
||||
let line = json!({"jsonrpc": "2.0", "method": "notifications/message", "params": {"data": "x".repeat(FLOOD)}}).to_string();
|
||||
for _ in 0..8 {
|
||||
if writeln!(out, "{line}").is_err() {
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
if mode == "stubborn" {
|
||||
// Waits without a stdin to read until the parent stops it; ends on its own after ten
|
||||
// minutes so a parent that fails to stop it leaves nothing running.
|
||||
let (_keep, wait) = std::sync::mpsc::channel::<()>();
|
||||
let _ = wait.recv_timeout(Duration::from_secs(600));
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn start(mode: &str, limits: McpLimits) -> Result<McpChild, String> {
|
||||
let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
|
||||
McpChild::spawn_with_limits(exe, std::iter::empty::<&str>(), [(CHILD_VAR, mode), (ECHO_VAR, "hello from the child")], limits)
|
||||
.map_err(|e| format!("spawn {mode}: {e}"))
|
||||
}
|
||||
|
||||
fn skip_filters_exclude_tests_from_the_child_runner() -> Result<(), String> {
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
for args in [vec!["--list", "--skip", "stderr_flood_does_not_block"], vec!["--list", "--skip=stderr_flood_does_not_block"]] {
|
||||
let output = std::process::Command::new(&exe).args(args).output().map_err(|e| e.to_string())?;
|
||||
check(output.status.success(), || String::from_utf8_lossy(&output.stderr).into_owned())?;
|
||||
let listed = String::from_utf8_lossy(&output.stdout);
|
||||
check(!listed.contains("stderr_flood_does_not_block"), || format!("the skipped test was selected: {listed}"))?;
|
||||
check(listed.lines().count() == TESTS.len() - 1, || format!("other tests were filtered out: {listed}"))?;
|
||||
}
|
||||
for args in
|
||||
[vec!["--list", "--skip"], vec!["--skip", "--list"], vec!["--list", "--skip", ""], vec!["--list", "--skip="], vec!["--list", "--skip=--list"]]
|
||||
{
|
||||
let output = std::process::Command::new(&exe).args(&args).output().map_err(|e| e.to_string())?;
|
||||
check(!output.status.success(), || format!("an invalid skip filter was accepted: {args:?}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn thread_count_options_preserve_child_test_selection() -> Result<(), String> {
|
||||
let exe = std::env::current_exe().map_err(|error| error.to_string())?;
|
||||
for args in [vec!["--list", "--test-threads", "1"], vec!["--list", "--test-threads=2"]] {
|
||||
let output = std::process::Command::new(&exe).args(args).output().map_err(|error| error.to_string())?;
|
||||
check(output.status.success(), || String::from_utf8_lossy(&output.stderr).into_owned())?;
|
||||
let listed = String::from_utf8_lossy(&output.stdout);
|
||||
check(listed.lines().count() == TESTS.len(), || format!("thread count changed test selection: {listed}"))?;
|
||||
}
|
||||
for args in [
|
||||
vec!["--list", "--test-threads"],
|
||||
vec!["--list", "--test-threads", "0"],
|
||||
vec!["--list", "--test-threads="],
|
||||
vec!["--list", "--test-threads=bad"],
|
||||
vec!["--test-threads", "--list"],
|
||||
] {
|
||||
let output = std::process::Command::new(&exe).args(&args).output().map_err(|error| error.to_string())?;
|
||||
check(!output.status.success(), || format!("an invalid thread count was accepted: {args:?}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn close_drains_stdout_before_child_exit() -> Result<(), String> {
|
||||
let mut client = start("stdout-after-eof", McpLimits::default())?;
|
||||
client.initialize(PROTOCOL_VERSION).map_err(|error| error.to_string())?;
|
||||
let outcome = client.close().map_err(|error| error.to_string())?;
|
||||
check(!outcome.forced && outcome.status.is_some_and(|status| status.success()), || format!("close: {outcome:?}"))
|
||||
}
|
||||
|
||||
fn check(ok: bool, what: impl FnOnce() -> String) -> Result<(), String> {
|
||||
if ok { Ok(()) } else { Err(what()) }
|
||||
}
|
||||
|
||||
fn a_spawned_server_answers_and_closes_cleanly() -> Result<(), String> {
|
||||
let before = std::env::var_os(ECHO_VAR);
|
||||
let mut c = start("server", McpLimits::default())?;
|
||||
let init = c.initialize(PROTOCOL_VERSION).map_err(|e| e.to_string())?;
|
||||
check(init["serverInfo"]["name"] == "child", || format!("initialize: {init}"))?;
|
||||
let r = c.call_tool("echo", json!({})).map_err(|e| e.to_string())?;
|
||||
check(r["content"][0]["text"] == "hello from the child", || format!("the child did not get its variable: {r}"))?;
|
||||
check(std::env::var_os(ECHO_VAR) == before, || "the test process's environment changed".into())?;
|
||||
let out = c.close().map_err(|e| e.to_string())?;
|
||||
check(!out.forced && out.status.is_some_and(|s| s.success()), || format!("close: {out:?}"))
|
||||
}
|
||||
|
||||
fn silent_spawned_child_hits_deadline() -> Result<(), String> {
|
||||
let limits = McpLimits { initialize_timeout: Duration::from_millis(200), ..McpLimits::default() };
|
||||
let mut c = start("silent", limits)?;
|
||||
let err = c.initialize(PROTOCOL_VERSION).err();
|
||||
check(matches!(err, Some(McpError::Deadline { .. })), || format!("initialize: {err:?}"))?;
|
||||
check(c.closed().is_some(), || "the connection is still open".into())?;
|
||||
let out = c.close().map_err(|e| e.to_string())?;
|
||||
check(out.forced && out.status.is_some(), || format!("the silent child was not stopped: {out:?}"))
|
||||
}
|
||||
|
||||
fn child_exits_before_initialize() -> Result<(), String> {
|
||||
let mut c = start("exit", McpLimits::default())?;
|
||||
// The write of `initialize` and the end of stdout race; either one is reported.
|
||||
let err = c.initialize(PROTOCOL_VERSION).err();
|
||||
check(matches!(err, Some(McpError::Ended | McpError::Io { .. })), || format!("initialize: {err:?}"))?;
|
||||
let out = c.close().map_err(|e| e.to_string())?;
|
||||
check(!out.forced && out.status.and_then(|s| s.code()) == Some(3), || format!("close: {out:?}"))
|
||||
}
|
||||
|
||||
fn stderr_flood_does_not_block() -> Result<(), String> {
|
||||
let limits = McpLimits {
|
||||
stderr_tail_bytes: 4096,
|
||||
initialize_timeout: Duration::from_secs(20),
|
||||
request_timeout: Duration::from_secs(20),
|
||||
..McpLimits::default()
|
||||
};
|
||||
let mut c = start("flood", limits)?;
|
||||
c.initialize(PROTOCOL_VERSION).map_err(|e| e.to_string())?;
|
||||
c.call_tool("echo", json!({})).map_err(|e| e.to_string())?;
|
||||
let out = c.close().map_err(|e| e.to_string())?;
|
||||
check(!out.forced, || format!("close: {out:?}"))?;
|
||||
check(out.stderr.len() == 4096 && out.stderr.ends_with(b"eeeEND"), || format!("kept {} bytes of stderr", out.stderr.len()))
|
||||
}
|
||||
|
||||
fn close_forces_and_reaps_unresponsive_child() -> Result<(), String> {
|
||||
let limits = McpLimits { close_grace: Duration::from_millis(200), ..McpLimits::default() };
|
||||
let mut c = start("stubborn", limits)?;
|
||||
c.initialize(PROTOCOL_VERSION).map_err(|e| e.to_string())?;
|
||||
let out = c.close().map_err(|e| e.to_string())?;
|
||||
check(out.forced && out.status.is_some_and(|s| !s.success()), || format!("close: {out:?}"))
|
||||
}
|
||||
|
||||
fn close_keeps_stderr_written_before_exit() -> Result<(), String> {
|
||||
let limits = McpLimits { stderr_tail_bytes: 4096, close_grace: Duration::ZERO, ..McpLimits::default() };
|
||||
let mut c = start("goodbye", limits)?;
|
||||
// The child's stdout ends when it exits, after its stderr is written.
|
||||
let err = c.initialize(PROTOCOL_VERSION).err();
|
||||
check(matches!(err, Some(McpError::Ended | McpError::Io { .. })), || format!("initialize: {err:?}"))?;
|
||||
let out = c.close().map_err(|e| e.to_string())?;
|
||||
check(out.stderr.len() == 4096 && out.stderr.ends_with(b"eeeBYE"), || format!("kept {} bytes of stderr", out.stderr.len()))
|
||||
}
|
||||
@@ -11,11 +11,19 @@ repository.workspace = true
|
||||
default = []
|
||||
dds = ["dep:dds", "dep:bytemuck"]
|
||||
parallel = ["dep:rayon"]
|
||||
png = ["dep:craft-image-codecs"]
|
||||
tiff = ["dep:craft-image-codecs"]
|
||||
hdr = ["dep:craft-hdr"]
|
||||
exr = ["dep:craft-exr", "craft-exr/decode"]
|
||||
decode = ["png", "tiff", "hdr", "exr"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-exr = { workspace = true, optional = true }
|
||||
craft-hdr = { workspace = true, optional = true }
|
||||
craft-image-codecs = { workspace = true, optional = true }
|
||||
rayon = { workspace = true, optional = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
@@ -24,6 +32,7 @@ dds = { version = "0.2.0", default-features = false, optional = true }
|
||||
bytemuck = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
png-encoder = { package = "png", version = "0.18" }
|
||||
half = "2"
|
||||
dds = { version = "0.2.0", default-features = false }
|
||||
bytemuck = { workspace = true }
|
||||
@@ -58,6 +58,22 @@ network I/O and has no `unsafe` code.
|
||||
`to_rgba8_display` encodes 8-bit sRGB RGBA. `linear_to_srgb`, `srgb_to_linear` and `luminance`
|
||||
(Rec. 709) are scalar helpers. `resource_key` and `split_resource_key` tag a bitmap name with
|
||||
its color space.
|
||||
- **Decoding.** With the `png`, `tiff`, `hdr` and `exr` features, `decode::png`, `decode::tiff`,
|
||||
`decode::hdr` and `decode::exr` turn a file's bytes into a plane. Integer samples are divided
|
||||
by their maximum (255 or 65535), so a 16-bit file keeps all 65536 levels. Float samples are
|
||||
kept as stored, values above 1 and negative values included, and OpenEXR NaN and infinities
|
||||
too, except that 64-bit TIFF floats are narrowed to 32 bits and lose any precision beyond
|
||||
`f32`. Gray without alpha gives a gray plane, as does an OpenEXR file of exactly one channel
|
||||
whatever its name; every other layout gives RGBA, with alpha 1 when the file has none. The
|
||||
result's `transfer` is `Encoded` for integer code values whose transfer
|
||||
the file does not state, `Linear` for Radiance HDR, OpenEXR and PNG with a linear `cICP`, and
|
||||
`Unknown` otherwise (an ICC profile, another `cICP` transfer, a float TIFF). No transfer
|
||||
function is applied: the caller decodes sRGB color data, such as glTF base color, and leaves
|
||||
linear data, such as normals, as it is. `alpha` is `Premultiplied` for OpenEXR and `Straight`
|
||||
otherwise; TIFF associated alpha is converted to straight. The plane's size is checked against
|
||||
`Limits` before it is reserved, the format decoder's own buffer is limited to `max_bytes` (for
|
||||
OpenEXR, every channel the file declares counts at 4 bytes a sample), and CMYK and Lab TIFF, OpenEXR files with a deep part and files that end early return a
|
||||
`DecodeError`. A Radiance HDR side over `max_side` is refused from the header.
|
||||
- **Height to normal and ORM packing.** Both read a `ScalarSource`: a plane of linear scalar
|
||||
samples that gives its size and one row at a time, so an adapter can decode a tiled or encoded
|
||||
surface in place. Besides the output, each worker keeps at most three rows for the normal map
|
||||
@@ -88,8 +104,8 @@ network I/O and has no `unsafe` code.
|
||||
and two names of one set with the same role and tile are both kept and reported. See
|
||||
[Texture-set names](#texture-set-names).
|
||||
|
||||
DDS first-surface decoding is available with the `dds` feature. Other image decoding and
|
||||
mirrored repeat are not supported.
|
||||
DDS first-surface decoding is available with the `dds` feature. Mirrored repeat is not in the
|
||||
crate yet.
|
||||
|
||||
## Cargo features
|
||||
|
||||
@@ -99,8 +115,13 @@ No default features.
|
||||
|---|---|---|
|
||||
| `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` |
|
||||
| `png` | `decode::png` | `craft-image-codecs` |
|
||||
| `tiff` | `decode::tiff` | `craft-image-codecs` |
|
||||
| `hdr` | `decode::hdr` | `craft-hdr` |
|
||||
| `exr` | `decode::exr` | `craft-exr` with its `decode` feature |
|
||||
| `decode` | all four decoders | the above |
|
||||
|
||||
Without `parallel` the crate builds for `wasm32-unknown-unknown`.
|
||||
Without `parallel` the crate builds for `wasm32-unknown-unknown`, the decoding features included.
|
||||
|
||||
## Limits
|
||||
|
||||
@@ -179,6 +200,7 @@ inverted.
|
||||
| `Image`, `Kind`, sampling, resizing, conversions, sRGB helpers, resource keys and the six tests `sample_survives_huge_coordinates`, `resource_keys_round_trip`, `sample_wraps_and_clamps`, `resize_box_and_bilinear`, `hostile_sizes_are_clamped`, `conversions` | MaterialCraft `crates/image/src/lib.rs` at [3133062](https://github.com/storytold/materialcraft/commit/3133062968b8a1566eda12a357cb06062db16687) |
|
||||
| `get_axes`, `sample_axes`, `sample_nearest_axes`, `sample_stored` and the integer-sampling flag | MaterialCraft `crates/image/src/lib.rs` at [6c3b35c](https://github.com/storytold/materialcraft/commit/6c3b35c39632feafcda3d7a90ff18242f3ad910f), on this crate's coordinate reduction and `f64` bilinear sum |
|
||||
| `Limits`, the `try_` constructors, `from_data`, private fields with getters, the `parallel` feature, `with_integer_sampling` and `integer_sampling` | written here |
|
||||
| the `decode` module and its features | written here, on `craft-image-codecs`, `craft-hdr` and `craft-exr` |
|
||||
| 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 |
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
//! Decoding PNG, TIFF, Radiance HDR and OpenEXR bytes into float [`Image`] planes, each format
|
||||
//! behind its own Cargo feature. Integer samples are scaled by their own maximum (255 for 8 bits,
|
||||
//! 65535 for 16 bits), so a 16-bit file keeps all 65536 levels. Float samples are kept as stored:
|
||||
//! values above 1, negative values and, in OpenEXR, NaN and infinities. The one exception is a
|
||||
//! 64-bit TIFF float, which is narrowed to `f32` and loses any precision beyond it.
|
||||
//!
|
||||
//! Every function takes the file's bytes and does no I/O. The size of the result is checked
|
||||
//! against [`Limits`] before its plane is reserved, and the reservation is fallible. The format
|
||||
//! decoders are bounded by the same limits: their own buffer is at most `max_bytes`, so a decode
|
||||
//! holds at most two buffers of that size at once. Damaged, cut-short and unsupported files are
|
||||
//! errors; nothing is filled in.
|
||||
//!
|
||||
//! A gray file without alpha gives a [`Kind::Gray`] plane. Every other file gives a
|
||||
//! [`Kind::Color`] RGBA plane: gray with alpha repeats the gray value in R, G and B, and a file
|
||||
//! without alpha gets alpha 1. No transfer function is applied: [`Decoded::transfer`] says what
|
||||
//! the values are, and the caller converts color data (glTF base color and emissive RGB are sRGB)
|
||||
//! and leaves linear data (normals, metallic-roughness, occlusion) as it is.
|
||||
|
||||
#[cfg(any(feature = "png", feature = "tiff"))]
|
||||
use craft_image_codecs::{ChannelLayout, Cicp, Format, SampleType, f16};
|
||||
|
||||
use crate::{Image, ImageError, Kind, Limits};
|
||||
|
||||
/// What the RGB values of a decoded plane are.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Transfer {
|
||||
/// Integer code values scaled to `0..=1`, in the file's own encoding. The file states no
|
||||
/// transfer function through a PNG `cICP` chunk or an ICC profile; PNG `sRGB` and `gAMA`
|
||||
/// chunks are not read. The caller decides by the use of the texture whether to apply the
|
||||
/// sRGB decoding.
|
||||
Encoded,
|
||||
/// Linear values: Radiance HDR, OpenEXR, and PNG with a `cICP` chunk naming linear transfer.
|
||||
Linear,
|
||||
/// The file describes its color in a way these tags do not cover (an ICC profile, a `cICP`
|
||||
/// transfer other than sRGB or linear), or it is a float TIFF, whose transfer the format does
|
||||
/// not define.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// How the color of a decoded plane relates to its alpha.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Alpha {
|
||||
/// Color is independent of alpha. TIFF associated alpha is converted to this form.
|
||||
Straight,
|
||||
/// Color is already multiplied by alpha, as OpenEXR stores it. A pixel with alpha 0 can still
|
||||
/// carry color (an emitting pixel), and is kept as stored.
|
||||
Premultiplied,
|
||||
}
|
||||
|
||||
/// A decoded texture: the plane and what its values mean.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct Decoded {
|
||||
/// The pixels, top row first.
|
||||
pub image: Image,
|
||||
pub transfer: Transfer,
|
||||
pub alpha: Alpha,
|
||||
}
|
||||
|
||||
/// Why bytes could not be decoded.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum DecodeError {
|
||||
/// The bytes do not start like a file of the format asked for (empty bytes included).
|
||||
#[error("the bytes are not a {0} file")]
|
||||
WrongFormat(&'static str),
|
||||
/// A valid file this decoder does not cover, such as a CMYK or Lab TIFF, or deep OpenEXR.
|
||||
#[error("unsupported {format} file: {reason}")]
|
||||
Unsupported { format: &'static str, reason: String },
|
||||
/// The file is damaged or cut short.
|
||||
#[error("damaged {format} file: {reason}")]
|
||||
Malformed { format: &'static str, reason: String },
|
||||
/// The format decoder refused a size over the limits it was given.
|
||||
#[error("{format} file exceeds a limit: {reason}")]
|
||||
LimitExceeded { format: &'static str, reason: String },
|
||||
/// The plane is over [`Limits`], or its memory could not be reserved.
|
||||
#[error(transparent)]
|
||||
Image(#[from] ImageError),
|
||||
}
|
||||
|
||||
/// Reserves exactly `len` floats for a `w × h` plane.
|
||||
fn reserve(len: usize, w: u32, h: u32) -> Result<Vec<f32>, DecodeError> {
|
||||
let mut data = Vec::new();
|
||||
data.try_reserve_exact(len).map_err(|_| ImageError::OutOfMemory(w, h))?;
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "png", feature = "tiff"))]
|
||||
fn codec_error(format: &'static str, e: craft_image_codecs::CodecError) -> DecodeError {
|
||||
use craft_image_codecs::CodecError;
|
||||
match e {
|
||||
CodecError::UnknownFormat => DecodeError::WrongFormat(format),
|
||||
CodecError::Unsupported { reason, .. } => DecodeError::Unsupported { format, reason },
|
||||
CodecError::LimitExceeded(reason) => DecodeError::LimitExceeded { format, reason },
|
||||
CodecError::Malformed { message, .. } => DecodeError::Malformed { format, reason: message },
|
||||
e => DecodeError::Malformed { format, reason: e.to_string() },
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes `bytes` as `format` through `craft-image-codecs`, keeping the stored sample depth.
|
||||
#[cfg(any(feature = "png", feature = "tiff"))]
|
||||
fn decode_codec(bytes: &[u8], format: Format, name: &'static str, limits: &Limits) -> Result<Decoded, DecodeError> {
|
||||
if craft_image_codecs::detect(bytes) != Some(format) {
|
||||
return Err(DecodeError::WrongFormat(name));
|
||||
}
|
||||
let codec_limits = craft_image_codecs::Limits {
|
||||
max_width: limits.max_side,
|
||||
max_height: limits.max_side,
|
||||
max_pixels: limits.max_pixels,
|
||||
max_alloc: limits.max_bytes,
|
||||
};
|
||||
let opts = craft_image_codecs::DecodeOptions { limits: codec_limits, ..Default::default() };
|
||||
let img = craft_image_codecs::decode_as_with(format, bytes, &opts).map_err(|e| codec_error(name, e))?;
|
||||
if img.warnings.iter().any(|w| matches!(w, craft_image_codecs::DecodeWarning::Truncated { .. })) {
|
||||
return Err(DecodeError::Malformed { format: name, reason: "the image data ends early".into() });
|
||||
}
|
||||
let image = codec_plane(&img, name, limits)?;
|
||||
Ok(Decoded { image, transfer: codec_transfer(&img), alpha: Alpha::Straight })
|
||||
}
|
||||
|
||||
/// The transfer a `craft-image-codecs` image states. An ICC profile makes it unknown, since
|
||||
/// `craft-image-codecs` relies on the `cICP` only when there is no profile.
|
||||
#[cfg(any(feature = "png", feature = "tiff"))]
|
||||
fn codec_transfer(img: &craft_image_codecs::Image) -> Transfer {
|
||||
/// The `cICP` transfer code of the sRGB transfer function (ITU-T H.273, IEC 61966-2-1).
|
||||
const TRANSFER_SRGB: u16 = 13;
|
||||
if img.icc.is_some() {
|
||||
return Transfer::Unknown;
|
||||
}
|
||||
match img.cicp {
|
||||
Some(c) if c.transfer == Cicp::TRANSFER_LINEAR => Transfer::Linear,
|
||||
Some(c) if c.transfer == TRANSFER_SRGB => Transfer::Encoded,
|
||||
Some(_) => Transfer::Unknown,
|
||||
None if img.sample_type().is_float() => Transfer::Unknown,
|
||||
None => Transfer::Encoded,
|
||||
}
|
||||
}
|
||||
|
||||
/// One stored sample as `f32`: integers scaled by their maximum, floats as stored.
|
||||
#[cfg(any(feature = "png", feature = "tiff"))]
|
||||
fn sample_f32(sample: SampleType, s: &[u8]) -> f32 {
|
||||
match (sample, s) {
|
||||
(SampleType::U8, &[a]) => f32::from(a) / 255.0,
|
||||
(SampleType::U16, &[a, b]) => f32::from(u16::from_ne_bytes([a, b])) / 65535.0,
|
||||
(SampleType::F16, &[a, b]) => f16::from_bits(u16::from_ne_bytes([a, b])).to_f32(),
|
||||
(SampleType::F32, &[a, b, c, d]) => f32::from_ne_bytes([a, b, c, d]),
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a decoded image into one plane, reserved after the limit check of its final kind.
|
||||
#[cfg(any(feature = "png", feature = "tiff"))]
|
||||
fn codec_plane(img: &craft_image_codecs::Image, name: &'static str, limits: &Limits) -> Result<Image, DecodeError> {
|
||||
let layout = img.layout();
|
||||
let kind = match layout {
|
||||
ChannelLayout::Gray => Kind::Gray,
|
||||
ChannelLayout::GrayA | ChannelLayout::Rgb | ChannelLayout::Rgba => Kind::Color,
|
||||
other => return Err(DecodeError::Unsupported { format: name, reason: format!("{other:?} color is not converted to RGB") }),
|
||||
};
|
||||
let (w, h) = img.dimensions();
|
||||
let len = limits.check(w, h, kind)?;
|
||||
let sample = img.sample_type();
|
||||
let bytes = sample.bytes();
|
||||
let pixel_bytes = layout.channels() * bytes;
|
||||
if img.data().len() != img.pixel_count().saturating_mul(pixel_bytes) {
|
||||
return Err(DecodeError::Malformed { format: name, reason: "the decoded buffer does not match the image size".into() });
|
||||
}
|
||||
let mut data = reserve(len, w, h)?;
|
||||
for px in img.data().chunks_exact(pixel_bytes) {
|
||||
let at = |c: usize| sample_f32(sample, px.get(c * bytes..(c + 1) * bytes).unwrap_or_default());
|
||||
match layout {
|
||||
ChannelLayout::Gray => data.push(at(0)),
|
||||
ChannelLayout::GrayA => {
|
||||
let g = at(0);
|
||||
data.extend([g, g, g, at(1)]);
|
||||
}
|
||||
ChannelLayout::Rgb => data.extend([at(0), at(1), at(2), 1.0]),
|
||||
_ => data.extend([at(0), at(1), at(2), at(3)]),
|
||||
}
|
||||
}
|
||||
Ok(Image::from_data(w, h, kind, data, limits)?)
|
||||
}
|
||||
|
||||
/// Decodes a PNG: 1- to 16-bit gray, gray with alpha, RGB, RGBA and palette images. A 16-bit
|
||||
/// sample `v` becomes `v / 65535`. The EXIF orientation, when the file has one, is applied.
|
||||
#[cfg(feature = "png")]
|
||||
pub fn png(bytes: &[u8], limits: &Limits) -> Result<Decoded, DecodeError> {
|
||||
decode_codec(bytes, Format::Png, "PNG", limits)
|
||||
}
|
||||
|
||||
/// Decodes the first page of a TIFF: gray, gray with alpha, RGB, RGBA, palette and YCbCr images,
|
||||
/// 8- and 16-bit integer samples (wider integers keep their top 16 bits) and 16- and 32-bit float
|
||||
/// samples (64-bit floats become 32-bit). Associated alpha is converted to straight alpha. CMYK
|
||||
/// and Lab files are [`DecodeError::Unsupported`], and a file whose image data ends early is
|
||||
/// [`DecodeError::Malformed`].
|
||||
#[cfg(feature = "tiff")]
|
||||
pub fn tiff(bytes: &[u8], limits: &Limits) -> Result<Decoded, DecodeError> {
|
||||
decode_codec(bytes, Format::Tiff, "TIFF", limits)
|
||||
}
|
||||
|
||||
/// Decodes a Radiance HDR (RGBE) picture into linear RGB with alpha 1. The `EXPOSURE` and
|
||||
/// `PRIMARIES` header lines are not applied.
|
||||
#[cfg(feature = "hdr")]
|
||||
pub fn hdr(bytes: &[u8], limits: &Limits) -> Result<Decoded, DecodeError> {
|
||||
const NAME: &str = "Radiance HDR";
|
||||
if !craft_hdr::sniff(bytes) {
|
||||
return Err(DecodeError::WrongFormat(NAME));
|
||||
}
|
||||
let mut hdr_limits = craft_hdr::Limits::default();
|
||||
// The picture holds 12 bytes a pixel, less than the 16 of the RGBA plane made from it.
|
||||
hdr_limits.max_pixels = limits.max_pixels.min(limits.max_bytes / 16);
|
||||
hdr_limits.max_axis = limits.max_side;
|
||||
let pic = craft_hdr::decode(bytes, &hdr_limits).map_err(|e| match e {
|
||||
craft_hdr::Error::NotHdr => DecodeError::WrongFormat(NAME),
|
||||
craft_hdr::Error::Malformed(m) => DecodeError::Malformed { format: NAME, reason: m.into() },
|
||||
craft_hdr::Error::Unsupported(m) => DecodeError::Unsupported { format: NAME, reason: m },
|
||||
craft_hdr::Error::LimitExceeded(m) => DecodeError::LimitExceeded { format: NAME, reason: m.into() },
|
||||
})?;
|
||||
let (w, h) = (pic.width, pic.height);
|
||||
let len = limits.check(w, h, Kind::Color)?;
|
||||
let mut data = reserve(len, w, h)?;
|
||||
for &[r, g, b] in pic.rgb.as_chunks::<3>().0 {
|
||||
data.extend([r, g, b, 1.0]);
|
||||
}
|
||||
let image = Image::from_data(w, h, Kind::Color, data, limits)?;
|
||||
Ok(Decoded { image, transfer: Transfer::Linear, alpha: Alpha::Straight })
|
||||
}
|
||||
|
||||
/// Decodes the color channels of an OpenEXR file: the part and the channel group that
|
||||
/// `craft_exr::decode::pick_part` and `craft_exr::channels::color_channels` choose (R, G, B and A,
|
||||
/// or Y and A, sharing one layer prefix), over the part's data window. A file of exactly one
|
||||
/// channel, whatever its name (a height or depth map), gives a gray plane. Half and float samples
|
||||
/// are kept as stored. The result is [`Alpha::Premultiplied`], as OpenEXR stores color. Files
|
||||
/// with a deep part (even when the color part is flat), subsampled channels, 32-bit unsigned
|
||||
/// integer color channels and files of several channels without a color group are
|
||||
/// [`DecodeError::Unsupported`]. The plane's size is checked before any pixel is decoded, and the
|
||||
/// samples the file declares, every channel of every part at 4 bytes each, must also fit in
|
||||
/// [`Limits::max_bytes`].
|
||||
#[cfg(feature = "exr")]
|
||||
pub fn exr(bytes: &[u8], limits: &Limits) -> Result<Decoded, DecodeError> {
|
||||
use craft_exr::channels::{ColorLayout, color_channels};
|
||||
use craft_exr::decode::{self as exr_decode, Error, SampleType};
|
||||
|
||||
const NAME: &str = "OpenEXR";
|
||||
if bytes.get(..4) != Some(&[0x76, 0x2f, 0x31, 0x01][..]) {
|
||||
return Err(DecodeError::WrongFormat(NAME));
|
||||
}
|
||||
let map = |e: Error| match e {
|
||||
Error::Unsupported(m) => DecodeError::Unsupported { format: NAME, reason: m },
|
||||
Error::LimitExceeded(m) => DecodeError::LimitExceeded { format: NAME, reason: m },
|
||||
Error::Malformed(m) | Error::Encode(m) => DecodeError::Malformed { format: NAME, reason: m },
|
||||
};
|
||||
let mut exr_limits = exr_decode::Limits::default();
|
||||
exr_limits.max_width = limits.max_side;
|
||||
exr_limits.max_height = limits.max_side;
|
||||
exr_limits.max_pixels = limits.max_pixels;
|
||||
// The decoder counts every channel of every part at 4 bytes a sample, which also covers the
|
||||
// all-channel blocks it decompresses before the unused channels are dropped.
|
||||
exr_limits.max_bytes = limits.max_bytes;
|
||||
let parts = exr_decode::parts(bytes, &exr_limits).map_err(map)?;
|
||||
let unsupported = |reason: &str| DecodeError::Unsupported { format: NAME, reason: reason.into() };
|
||||
let info = exr_decode::pick_part(&parts).and_then(|i| parts.get(i)).ok_or_else(|| unsupported("no part has color channels"))?;
|
||||
if parts.iter().any(|p| p.deep) {
|
||||
return Err(unsupported("deep data"));
|
||||
}
|
||||
let (layout, picked) = color_channels(info.channels.iter().map(|c| c.name.as_str())).ok_or_else(|| unsupported("no color channels"))?;
|
||||
let mut names = Vec::with_capacity(picked.len());
|
||||
for i in picked {
|
||||
let c = info.channels.get(i).ok_or_else(|| unsupported("no color channels"))?;
|
||||
if c.sample == SampleType::U32 {
|
||||
return Err(unsupported("a color channel holds 32-bit unsigned integers"));
|
||||
}
|
||||
names.push(c.name.as_str());
|
||||
}
|
||||
let kind = if layout == ColorLayout::Y { Kind::Gray } else { Kind::Color };
|
||||
let (w, h) = (info.data_window.width, info.data_window.height);
|
||||
let len = limits.check(w, h, kind)?;
|
||||
let part = exr_decode::decode_part(bytes, info.index, &|n| names.contains(&n), &exr_limits).map_err(map)?;
|
||||
let mut planes = Vec::with_capacity(names.len());
|
||||
for n in &names {
|
||||
let c = part.channel(n).ok_or_else(|| DecodeError::Malformed { format: NAME, reason: format!("channel {n} was not read") })?;
|
||||
planes.push(&c.samples);
|
||||
}
|
||||
let pixels = len / kind.channels();
|
||||
if planes.iter().any(|p| p.len() != pixels) {
|
||||
return Err(DecodeError::Malformed { format: NAME, reason: "a channel does not cover the data window".into() });
|
||||
}
|
||||
let mut data = reserve(len, w, h)?;
|
||||
let at = |c: usize, i: usize| planes.get(c).map_or(0.0, |p| p.get_f32(i));
|
||||
for i in 0..pixels {
|
||||
match layout {
|
||||
ColorLayout::Y => data.push(at(0, i)),
|
||||
ColorLayout::YA => {
|
||||
let y = at(0, i);
|
||||
data.extend([y, y, y, at(1, i)]);
|
||||
}
|
||||
ColorLayout::Rgb => data.extend([at(0, i), at(1, i), at(2, i), 1.0]),
|
||||
ColorLayout::Rgba => data.extend([at(0, i), at(1, i), at(2, i), at(3, i)]),
|
||||
}
|
||||
}
|
||||
let image = Image::from_data(w, h, kind, data, limits)?;
|
||||
Ok(Decoded { image, transfer: Transfer::Linear, alpha: Alpha::Premultiplied })
|
||||
}
|
||||
|
||||
#[cfg(all(test, any(feature = "png", feature = "tiff")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_icc_profile_makes_the_transfer_unknown_whatever_the_cicp() {
|
||||
let Ok(mut img) = craft_image_codecs::Image::from_u16(1, 1, ChannelLayout::Gray, &[7]) else { panic!("valid 1 x 1 image") };
|
||||
assert_eq!(codec_transfer(&img), Transfer::Encoded);
|
||||
img.cicp = Some(Cicp { primaries: 1, transfer: Cicp::TRANSFER_LINEAR, matrix: 0, full_range: true });
|
||||
assert_eq!(codec_transfer(&img), Transfer::Linear);
|
||||
img.icc = Some(vec![0; 128]);
|
||||
assert_eq!(codec_transfer(&img), Transfer::Unknown);
|
||||
img.cicp = Some(Cicp { primaries: 1, transfer: 13, matrix: 0, full_range: true });
|
||||
assert_eq!(codec_transfer(&img), Transfer::Unknown);
|
||||
img.icc = None;
|
||||
assert_eq!(codec_transfer(&img), Transfer::Encoded);
|
||||
img.cicp = Some(Cicp { primaries: 9, transfer: Cicp::TRANSFER_PQ, matrix: 0, full_range: true });
|
||||
assert_eq!(codec_transfer(&img), Transfer::Unknown);
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,9 @@
|
||||
//! infallible allocation ends the process. Rows are generated on several threads only with the
|
||||
//! `parallel` feature.
|
||||
//!
|
||||
//! The `png`, `tiff`, `hdr` and `exr` features add the `decode` module, which turns those files'
|
||||
//! bytes into planes without reducing 16-bit or float samples to 8 bits.
|
||||
//!
|
||||
//! [`normal`] makes tangent-space normal maps from a height plane, and [`packing`] packs
|
||||
//! occlusion, roughness and metallic into one RGBA image. Both read a [`ScalarSource`] one row at
|
||||
//! a time, so a tiled surface is read in place instead of copied into a float plane.
|
||||
@@ -49,6 +52,8 @@ use std::sync::Arc;
|
||||
#[cfg(feature = "parallel")]
|
||||
use rayon::prelude::*;
|
||||
|
||||
#[cfg(any(feature = "png", feature = "tiff", feature = "hdr", feature = "exr"))]
|
||||
pub mod decode;
|
||||
pub mod normal;
|
||||
pub mod packing;
|
||||
mod source;
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
//! Decoding files built in the tests: PNG with the `png` crate, TIFF and Radiance HDR byte by byte
|
||||
//! from their published layouts, and OpenEXR with `craft-exr`'s writer.
|
||||
#![cfg(any(feature = "png", feature = "tiff", feature = "hdr", feature = "exr"))]
|
||||
#![allow(clippy::unwrap_used, clippy::panic)]
|
||||
|
||||
#[cfg(any(feature = "png", feature = "tiff"))]
|
||||
use std::collections::HashSet;
|
||||
|
||||
use craft_texture::decode::{Alpha, DecodeError, Transfer};
|
||||
use craft_texture::{Kind, Limits};
|
||||
|
||||
/// How many different values the floats of `d` hold.
|
||||
#[cfg(any(feature = "png", feature = "tiff"))]
|
||||
fn distinct(d: &craft_texture::decode::Decoded) -> usize {
|
||||
d.image.data().iter().map(|v| v.to_bits()).collect::<HashSet<_>>().len()
|
||||
}
|
||||
|
||||
/// 512 16-bit codes from 0 to 65535, all different.
|
||||
#[cfg(any(feature = "png", feature = "tiff"))]
|
||||
fn ramp16() -> Vec<u16> {
|
||||
(0..512u32).map(|x| (x * 65535 / 511) as u16).collect()
|
||||
}
|
||||
|
||||
#[cfg(feature = "png")]
|
||||
mod png {
|
||||
use super::*;
|
||||
use craft_texture::ImageError;
|
||||
use png_encoder::{BitDepth, ColorType, Encoder};
|
||||
|
||||
pub(super) fn encode(w: u32, h: u32, color: ColorType, depth: BitDepth, data: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let mut enc = Encoder::new(&mut out, w, h);
|
||||
enc.set_color(color);
|
||||
enc.set_depth(depth);
|
||||
let mut writer = enc.write_header().unwrap();
|
||||
writer.write_image_data(data).unwrap();
|
||||
writer.finish().unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixteen_bit_gray_ramp_keeps_every_level() {
|
||||
let codes = ramp16();
|
||||
let bytes: Vec<u8> = codes.iter().flat_map(|v| v.to_be_bytes()).collect();
|
||||
let file = encode(512, 1, ColorType::Grayscale, BitDepth::Sixteen, &bytes);
|
||||
let d = craft_texture::decode::png(&file, &Limits::default()).unwrap();
|
||||
assert_eq!((d.image.width(), d.image.height(), d.image.kind()), (512, 1, Kind::Gray));
|
||||
assert!(distinct(&d) > 256, "{} levels", distinct(&d));
|
||||
for (v, &c) in d.image.data().iter().zip(&codes) {
|
||||
assert_eq!(*v, f32::from(c) / 65535.0);
|
||||
}
|
||||
assert_eq!((d.image.data()[0], d.image.data()[511]), (0.0, 1.0));
|
||||
assert_eq!((d.transfer, d.alpha), (Transfer::Encoded, Alpha::Straight));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixteen_bit_rgba_keeps_every_level_in_every_channel() {
|
||||
let codes = ramp16();
|
||||
let bytes: Vec<u8> = codes.iter().flat_map(|&v| [v, 65535 - v, v, v].into_iter().flat_map(u16::to_be_bytes)).collect();
|
||||
let file = encode(512, 1, ColorType::Rgba, BitDepth::Sixteen, &bytes);
|
||||
let d = craft_texture::decode::png(&file, &Limits::default()).unwrap();
|
||||
assert_eq!(d.image.kind(), Kind::Color);
|
||||
for c in 0..4 {
|
||||
let levels: HashSet<u32> = d.image.data().as_chunks::<4>().0.iter().map(|p| p[c].to_bits()).collect();
|
||||
assert_eq!(levels.len(), 512, "channel {c}");
|
||||
}
|
||||
assert_eq!(d.image.get(1, 0, false), [128.0 / 65535.0, 65407.0 / 65535.0, 128.0 / 65535.0, 128.0 / 65535.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eight_bit_layouts_map_to_gray_or_rgba() {
|
||||
let ga = encode(2, 1, ColorType::GrayscaleAlpha, BitDepth::Eight, &[51, 0, 255, 102]);
|
||||
let d = craft_texture::decode::png(&ga, &Limits::default()).unwrap();
|
||||
assert_eq!(d.image.kind(), Kind::Color);
|
||||
assert_eq!(d.image.get(0, 0, false), [0.2, 0.2, 0.2, 0.0]);
|
||||
assert_eq!(d.image.get(1, 0, false), [1.0, 1.0, 1.0, 0.4]);
|
||||
let rgb = encode(1, 1, ColorType::Rgb, BitDepth::Eight, &[255, 0, 51]);
|
||||
let d = craft_texture::decode::png(&rgb, &Limits::default()).unwrap();
|
||||
assert_eq!(d.image.get(0, 0, false), [1.0, 0.0, 0.2, 1.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_limit_counts_the_rgba_plane_made_from_rgb() {
|
||||
// 4 × 4 RGB is 48 bytes in the file's own depth and 256 bytes as an RGBA float plane.
|
||||
let file = encode(4, 4, ColorType::Rgb, BitDepth::Eight, &[7; 48]);
|
||||
let mut limits = Limits::default();
|
||||
limits.max_bytes = 255;
|
||||
assert_eq!(craft_texture::decode::png(&file, &limits), Err(DecodeError::Image(ImageError::TooLarge(4, 4))));
|
||||
limits.max_bytes = 256;
|
||||
assert!(craft_texture::decode::png(&file, &limits).is_ok());
|
||||
limits.max_side = 3;
|
||||
assert!(craft_texture::decode::png(&file, &limits).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_wrong_and_cut_short_bytes_are_errors() {
|
||||
let l = Limits::default();
|
||||
assert_eq!(craft_texture::decode::png(&[], &l), Err(DecodeError::WrongFormat("PNG")));
|
||||
assert_eq!(craft_texture::decode::png(b"#?RADIANCE\n", &l), Err(DecodeError::WrongFormat("PNG")));
|
||||
let codes = ramp16();
|
||||
let bytes: Vec<u8> = codes.iter().flat_map(|v| v.to_be_bytes()).collect();
|
||||
let file = encode(512, 1, ColorType::Grayscale, BitDepth::Sixteen, &bytes);
|
||||
for cut in [9, 40, file.len() / 2, file.len() - 13] {
|
||||
assert!(craft_texture::decode::png(&file[..cut], &l).is_err(), "cut at {cut}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "tiff")]
|
||||
mod tiff {
|
||||
use super::*;
|
||||
|
||||
/// A little-endian, uncompressed, single-strip TIFF (TIFF 6.0, section 2 and the baseline
|
||||
/// fields of sections 3 to 8) of one row.
|
||||
fn build(w: u32, photometric: u16, bits: &[u16], sample_format: u16, extra: Option<u16>, pixels: &[u8]) -> Vec<u8> {
|
||||
build_strips(w, 1, photometric, bits, sample_format, extra, pixels)
|
||||
}
|
||||
|
||||
/// [`build`] with `rows` rows, one strip a row. `pixels` holds the first rows; the strips of
|
||||
/// the rows it does not hold point past the end of the file.
|
||||
fn build_strips(w: u32, rows: u32, photometric: u16, bits: &[u16], sample_format: u16, extra: Option<u16>, pixels: &[u8]) -> Vec<u8> {
|
||||
let spp = bits.len() as u16;
|
||||
let row_bytes = w * bits.iter().map(|&b| u32::from(b)).sum::<u32>() / 8;
|
||||
let shorts = |v: &[u16]| v.iter().flat_map(|s| s.to_le_bytes()).collect::<Vec<u8>>();
|
||||
let longs = |v: &[u32]| v.iter().flat_map(|s| s.to_le_bytes()).collect::<Vec<u8>>();
|
||||
let offsets: Vec<u32> = (0..rows).map(|r| if (r + 1) * row_bytes <= pixels.len() as u32 { 8 + r * row_bytes } else { 0x7fff_0000 }).collect();
|
||||
let mut out = b"II*\0".to_vec();
|
||||
let ifd_at = (8 + pixels.len() as u32).next_multiple_of(2);
|
||||
out.extend(ifd_at.to_le_bytes());
|
||||
out.extend(pixels);
|
||||
out.resize(ifd_at as usize, 0);
|
||||
let mut entries: Vec<(u16, u16, u32, Vec<u8>)> = vec![
|
||||
(256, 4, 1, w.to_le_bytes().to_vec()),
|
||||
(257, 4, 1, rows.to_le_bytes().to_vec()),
|
||||
(258, 3, u32::from(spp), shorts(bits)),
|
||||
(259, 3, 1, shorts(&[1])),
|
||||
(262, 3, 1, shorts(&[photometric])),
|
||||
(273, 4, rows, longs(&offsets)),
|
||||
(277, 3, 1, shorts(&[spp])),
|
||||
(278, 4, 1, 1u32.to_le_bytes().to_vec()),
|
||||
(279, 4, rows, longs(&vec![row_bytes; rows as usize])),
|
||||
];
|
||||
if let Some(e) = extra {
|
||||
entries.push((338, 3, 1, shorts(&[e])));
|
||||
}
|
||||
entries.push((339, 3, u32::from(spp), shorts(&vec![sample_format; usize::from(spp)])));
|
||||
let mut spill_at = ifd_at + 2 + entries.len() as u32 * 12 + 4;
|
||||
let mut spill = Vec::new();
|
||||
out.extend((entries.len() as u16).to_le_bytes());
|
||||
for (tag, kind, count, mut value) in entries {
|
||||
out.extend(tag.to_le_bytes());
|
||||
out.extend(kind.to_le_bytes());
|
||||
out.extend(count.to_le_bytes());
|
||||
if value.len() <= 4 {
|
||||
value.resize(4, 0);
|
||||
out.extend(value);
|
||||
} else {
|
||||
out.extend(spill_at.to_le_bytes());
|
||||
spill_at += value.len() as u32;
|
||||
spill.extend(value);
|
||||
}
|
||||
}
|
||||
out.extend(0u32.to_le_bytes());
|
||||
out.extend(spill);
|
||||
out
|
||||
}
|
||||
|
||||
fn le16(v: &[u16]) -> Vec<u8> {
|
||||
v.iter().flat_map(|s| s.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixteen_bit_gray_ramp_keeps_every_level() {
|
||||
let codes = ramp16();
|
||||
let file = build(512, 1, &[16], 1, None, &le16(&codes));
|
||||
let d = craft_texture::decode::tiff(&file, &Limits::default()).unwrap();
|
||||
assert_eq!(d.image.kind(), Kind::Gray);
|
||||
assert!(distinct(&d) > 256, "{} levels", distinct(&d));
|
||||
for (v, &c) in d.image.data().iter().zip(&codes) {
|
||||
assert_eq!(*v, f32::from(c) / 65535.0);
|
||||
}
|
||||
assert_eq!((d.transfer, d.alpha), (Transfer::Encoded, Alpha::Straight));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixteen_bit_rgba_with_unassociated_alpha_keeps_every_level() {
|
||||
let codes = ramp16();
|
||||
let px: Vec<u16> = codes.iter().flat_map(|&v| [v, v, 65535 - v, v]).collect();
|
||||
let file = build(512, 2, &[16; 4], 1, Some(2), &le16(&px));
|
||||
let d = craft_texture::decode::tiff(&file, &Limits::default()).unwrap();
|
||||
assert_eq!(d.image.kind(), Kind::Color);
|
||||
let alpha: HashSet<u32> = d.image.data().as_chunks::<4>().0.iter().map(|p| p[3].to_bits()).collect();
|
||||
assert_eq!(alpha.len(), 512);
|
||||
assert_eq!(d.image.get(511, 0, false), [1.0, 1.0, 0.0, 1.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn associated_alpha_becomes_straight() {
|
||||
// Color 0.25 premultiplied by alpha 0.5 is straight color 0.5.
|
||||
let file = build(1, 2, &[16; 4], 1, Some(1), &le16(&[16384, 16384, 16384, 32768]));
|
||||
let d = craft_texture::decode::tiff(&file, &Limits::default()).unwrap();
|
||||
let p = d.image.get(0, 0, false);
|
||||
assert!(p[..3].iter().all(|c| (c - 0.5).abs() < 1e-3), "{p:?}");
|
||||
assert_eq!(p[3], 32768.0 / 65535.0);
|
||||
assert_eq!(d.alpha, Alpha::Straight);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_samples_keep_values_outside_zero_to_one() {
|
||||
let px: Vec<u8> = [3.5f32, -0.25].iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||
let file = build(2, 1, &[32], 3, None, &px);
|
||||
let d = craft_texture::decode::tiff(&file, &Limits::default()).unwrap();
|
||||
assert_eq!(d.image.data(), &[3.5, -0.25]);
|
||||
assert_eq!(d.transfer, Transfer::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_is_unsupported() {
|
||||
let file = build(1, 5, &[8; 4], 1, None, &[0, 64, 128, 255]);
|
||||
assert!(matches!(craft_texture::decode::tiff(&file, &Limits::default()), Err(DecodeError::Unsupported { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compressed_strip_must_fit_the_byte_limit() {
|
||||
let mut packed = vec![0u8; (34usize * 9).div_ceil(8)];
|
||||
for (i, code) in std::iter::repeat_n(256u16, 32).chain([7, 257]).enumerate() {
|
||||
for bit in 0..9 {
|
||||
let at = i * 9 + bit;
|
||||
packed[at / 8] |= (((code >> (8 - bit)) & 1) as u8) << (7 - at % 8);
|
||||
}
|
||||
}
|
||||
let mut file = build(1, 1, &[8], 1, None, &packed);
|
||||
let ifd = u32::from_le_bytes(file[4..8].try_into().unwrap()) as usize;
|
||||
let count = usize::from(u16::from_le_bytes(file[ifd..ifd + 2].try_into().unwrap()));
|
||||
for entry in file[ifd + 2..ifd + 2 + count * 12].as_chunks_mut::<12>().0 {
|
||||
match u16::from_le_bytes(entry[..2].try_into().unwrap()) {
|
||||
259 => entry[8..12].copy_from_slice(&5u32.to_le_bytes()),
|
||||
279 => entry[8..12].copy_from_slice(&(packed.len() as u32).to_le_bytes()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut limits = Limits::default();
|
||||
limits.max_bytes = packed.len() as u64;
|
||||
let decoded = craft_texture::decode::tiff(&file, &limits).unwrap();
|
||||
assert_eq!(decoded.image.data(), &[7.0 / 255.0]);
|
||||
limits.max_bytes = 4;
|
||||
assert!(matches!(craft_texture::decode::tiff(&file, &limits), Err(DecodeError::LimitExceeded { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_strip_missing_rows_is_an_error() {
|
||||
let codes = ramp16();
|
||||
// Two rows, one strip each; the second strip points past the end of the file.
|
||||
let file = build_strips(512, 2, 1, &[16], 1, None, &le16(&codes));
|
||||
assert!(matches!(craft_texture::decode::tiff(&file, &Limits::default()), Err(DecodeError::Malformed { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_and_wrong_bytes_are_errors() {
|
||||
let l = Limits::default();
|
||||
assert_eq!(craft_texture::decode::tiff(&[], &l), Err(DecodeError::WrongFormat("TIFF")));
|
||||
assert_eq!(craft_texture::decode::tiff(b"II*", &l), Err(DecodeError::WrongFormat("TIFF")));
|
||||
let file = build(512, 1, &[16], 1, None, &le16(&ramp16()));
|
||||
assert!(craft_texture::decode::tiff(&file[..12], &l).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "hdr")]
|
||||
mod hdr {
|
||||
use super::*;
|
||||
|
||||
/// A flat Radiance picture of `pixels` RGBE quadruples in one row (`-Y 1 +X n`).
|
||||
fn build(pixels: &[[u8; 4]]) -> Vec<u8> {
|
||||
let mut out = format!("#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y 1 +X {}\n", pixels.len()).into_bytes();
|
||||
out.extend(pixels.iter().flatten());
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_above_one_are_kept() {
|
||||
// Mantissa × 2^(exponent − 136): 128 × 2^−6 is 2, and 128 × 2^4 is 2048.
|
||||
let file = build(&[[128, 128, 128, 130], [128, 64, 32, 129], [128, 0, 0, 140]]);
|
||||
let d = craft_texture::decode::hdr(&file, &Limits::default()).unwrap();
|
||||
assert_eq!(d.image.kind(), Kind::Color);
|
||||
assert_eq!(d.image.data(), &[2.0, 2.0, 2.0, 1.0, 1.0, 0.5, 0.25, 1.0, 2048.0, 0.0, 0.0, 1.0]);
|
||||
assert_eq!((d.transfer, d.alpha), (Transfer::Linear, Alpha::Straight));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_wrong_and_oversized_pictures_are_errors() {
|
||||
let l = Limits::default();
|
||||
assert_eq!(craft_texture::decode::hdr(&[], &l), Err(DecodeError::WrongFormat("Radiance HDR")));
|
||||
let file = build(&[[128, 128, 128, 130]; 4]);
|
||||
assert!(matches!(craft_texture::decode::hdr(&file[..file.len() - 2], &l), Err(DecodeError::Malformed { .. })));
|
||||
let mut narrow = Limits::default();
|
||||
narrow.max_side = 3;
|
||||
assert_eq!(
|
||||
craft_texture::decode::hdr(&file, &narrow),
|
||||
Err(DecodeError::LimitExceeded { format: "Radiance HDR", reason: "axis length".into() })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_side_over_the_limit_is_refused_from_the_header() {
|
||||
// No pixel data follows, so only the header can give the size error.
|
||||
let mut narrow = Limits::default();
|
||||
narrow.max_side = 50;
|
||||
let axis = Err(DecodeError::LimitExceeded { format: "Radiance HDR", reason: "axis length".into() });
|
||||
let wide = b"#?RADIANCE\r\nFORMAT=32-bit_rle_rgbe\r\n\r\n-Y 2 +X 100\n";
|
||||
assert_eq!(craft_texture::decode::hdr(wide, &narrow), axis);
|
||||
let tall = b"#?RADIANCE\n\n+X 3 -Y 60\n";
|
||||
assert_eq!(craft_texture::decode::hdr(tall, &narrow), axis);
|
||||
// The decoder treats a line of carriage returns alone as the empty line that ends the header.
|
||||
let crs = b"#?RADIANCE\r\r\n\r\r\n-Y 2 +X 100\n";
|
||||
assert_eq!(craft_texture::decode::hdr(crs, &narrow), axis);
|
||||
// A byte that is not UTF-8 after the four tokens does not hide the sizes.
|
||||
let trailing = b"#?RADIANCE\n\n-Y 2 +X 100 \xff\n";
|
||||
assert_eq!(craft_texture::decode::hdr(trailing, &narrow), axis);
|
||||
// A resolution line longer than the 64 KiB header limit is not read for sizes; the
|
||||
// decoder refuses it as a damaged header.
|
||||
let mut long = b"#?RADIANCE\n\n-Y 2 +X 100 ".to_vec();
|
||||
long.extend(std::iter::repeat_n(0xff, 70_000));
|
||||
long.push(b'\n');
|
||||
assert!(matches!(craft_texture::decode::hdr(&long, &narrow), Err(DecodeError::Malformed { .. })));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "exr")]
|
||||
mod exr {
|
||||
use super::*;
|
||||
use craft_exr::decode::{Channel, Compression, Samples, f16, write};
|
||||
use craft_texture::ImageError;
|
||||
|
||||
fn half(v: &[f32]) -> Samples {
|
||||
Samples::F16(v.iter().map(|&x| f16::from_f32(x)).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_and_float_values_are_kept_as_stored() {
|
||||
let channels = [
|
||||
Channel { name: "R".into(), samples: half(&[4.0, -0.5, 1.0]) },
|
||||
Channel { name: "G".into(), samples: Samples::F32(vec![f32::NAN, 1.0e6, 0.0]) },
|
||||
Channel { name: "B".into(), samples: Samples::F32(vec![f32::INFINITY, 0.125, 0.0]) },
|
||||
Channel { name: "A".into(), samples: half(&[1.0, 0.5, 0.0]) },
|
||||
];
|
||||
let file = write(3, 1, &channels, Compression::Zip16).unwrap();
|
||||
let d = craft_texture::decode::exr(&file, &Limits::default()).unwrap();
|
||||
assert_eq!((d.image.width(), d.image.height(), d.image.kind()), (3, 1, Kind::Color));
|
||||
let p = d.image.data();
|
||||
assert_eq!(p[0], 4.0);
|
||||
assert!(p[1].is_nan());
|
||||
assert_eq!((p[2], p[3]), (f32::INFINITY, 1.0));
|
||||
assert_eq!(&p[4..], &[-0.5, 1.0e6, 0.125, 0.5, 1.0, 0.0, 0.0, 0.0]);
|
||||
assert_eq!((d.transfer, d.alpha), (Transfer::Linear, Alpha::Premultiplied));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn luminance_gives_a_gray_plane_and_a_lone_alpha_is_unsupported() {
|
||||
let y = write(2, 1, &[Channel { name: "Y".into(), samples: half(&[3.0, 0.25]) }], Compression::None).unwrap();
|
||||
let d = craft_texture::decode::exr(&y, &Limits::default()).unwrap();
|
||||
assert_eq!((d.image.kind(), d.image.data()), (Kind::Gray, &[3.0f32, 0.25][..]));
|
||||
// A file of one channel is gray whatever the channel's name, such as a height map in Z.
|
||||
let z = write(2, 1, &[Channel { name: "Z".into(), samples: Samples::F32(vec![-2.0, 7.5]) }], Compression::None).unwrap();
|
||||
let d = craft_texture::decode::exr(&z, &Limits::default()).unwrap();
|
||||
assert_eq!((d.image.kind(), d.image.data()), (Kind::Gray, &[-2.0f32, 7.5][..]));
|
||||
let za = [Channel { name: "Z".into(), samples: half(&[1.0]) }, Channel { name: "A".into(), samples: half(&[1.0]) }];
|
||||
let za = write(1, 1, &za, Compression::None).unwrap();
|
||||
assert!(matches!(craft_texture::decode::exr(&za, &Limits::default()), Err(DecodeError::Unsupported { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channels_outside_the_color_group_count_toward_max_bytes() {
|
||||
// 11 channels of 4 × 4 declare 704 bytes; the RGBA plane made from R, G and B is 256.
|
||||
let names = ["R", "G", "B", "N.X", "N.Y", "N.Z", "P.X", "P.Y", "P.Z", "Z", "id"];
|
||||
let channels: Vec<Channel> = names.iter().map(|n| Channel { name: (*n).into(), samples: Samples::F32(vec![1.5; 16]) }).collect();
|
||||
let file = write(4, 4, &channels, Compression::Zip16).unwrap();
|
||||
let mut limits = Limits::default();
|
||||
limits.max_bytes = 703;
|
||||
assert!(matches!(craft_texture::decode::exr(&file, &limits), Err(DecodeError::LimitExceeded { .. })));
|
||||
limits.max_bytes = 704;
|
||||
let d = craft_texture::decode::exr(&file, &limits).unwrap();
|
||||
assert_eq!(d.image.get(3, 3, false), [1.5, 1.5, 1.5, 1.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_plane_is_checked_before_decoding_and_damage_is_an_error() {
|
||||
let rgb: Vec<Channel> = ["R", "G", "B"].iter().map(|n| Channel { name: (*n).into(), samples: half(&[2.0; 16]) }).collect();
|
||||
let file = write(4, 4, &rgb, Compression::Zip16).unwrap();
|
||||
let mut limits = Limits::default();
|
||||
// 4 × 4 RGB as an RGBA float plane is 256 bytes.
|
||||
limits.max_bytes = 255;
|
||||
assert_eq!(craft_texture::decode::exr(&file, &limits), Err(DecodeError::Image(ImageError::TooLarge(4, 4))));
|
||||
limits.max_bytes = 256;
|
||||
assert!(craft_texture::decode::exr(&file, &limits).is_ok());
|
||||
let l = Limits::default();
|
||||
assert_eq!(craft_texture::decode::exr(&[], &l), Err(DecodeError::WrongFormat("OpenEXR")));
|
||||
assert!(craft_texture::decode::exr(&file[..file.len() - 8], &l).is_err());
|
||||
}
|
||||
|
||||
/// Appends a header attribute: its name, its type, the payload's size and the payload.
|
||||
fn attr(out: &mut Vec<u8>, name: &str, ty: &str, payload: &[u8]) {
|
||||
for s in [name, ty] {
|
||||
out.extend_from_slice(s.as_bytes());
|
||||
out.push(0);
|
||||
}
|
||||
out.extend_from_slice(&i32::try_from(payload.len()).unwrap().to_le_bytes());
|
||||
out.extend_from_slice(payload);
|
||||
}
|
||||
|
||||
/// A multi-part file of one pixel: a flat scan-line part with float B, G and R channels of
|
||||
/// 0.25, then a deep scan-line part with one float A sample of 0.5.
|
||||
fn flat_and_deep() -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
out.extend_from_slice(&0x0131_2f76u32.to_le_bytes());
|
||||
out.extend_from_slice(&(2u32 | 0x800 | 0x1000).to_le_bytes());
|
||||
for deep in [false, true] {
|
||||
let names: &[&str] = if deep { &["A"] } else { &["B", "G", "R"] };
|
||||
let mut chlist = Vec::new();
|
||||
for n in names {
|
||||
chlist.extend_from_slice(n.as_bytes());
|
||||
chlist.push(0);
|
||||
chlist.extend_from_slice(&2i32.to_le_bytes()); // float
|
||||
chlist.extend_from_slice(&[0; 4]); // pLinear and reserved
|
||||
chlist.extend_from_slice(&1i32.to_le_bytes());
|
||||
chlist.extend_from_slice(&1i32.to_le_bytes());
|
||||
}
|
||||
chlist.push(0);
|
||||
let window: Vec<u8> = [0i32; 4].iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||
attr(&mut out, "channels", "chlist", &chlist);
|
||||
attr(&mut out, "chunkCount", "int", &1i32.to_le_bytes());
|
||||
attr(&mut out, "compression", "compression", &[0]);
|
||||
attr(&mut out, "dataWindow", "box2i", &window);
|
||||
attr(&mut out, "displayWindow", "box2i", &window);
|
||||
attr(&mut out, "lineOrder", "lineOrder", &[0]);
|
||||
if deep {
|
||||
attr(&mut out, "maxSamplesPerPixel", "int", &1i32.to_le_bytes());
|
||||
}
|
||||
attr(&mut out, "name", "string", if deep { b"deep" } else { b"flat" });
|
||||
attr(&mut out, "pixelAspectRatio", "float", &1f32.to_le_bytes());
|
||||
attr(&mut out, "screenWindowCenter", "v2f", &[0; 8]);
|
||||
attr(&mut out, "screenWindowWidth", "float", &1f32.to_le_bytes());
|
||||
attr(&mut out, "type", "string", if deep { b"deepscanline" } else { b"scanlineimage" });
|
||||
if deep {
|
||||
attr(&mut out, "version", "int", &1i32.to_le_bytes());
|
||||
}
|
||||
out.push(0); // end of this header
|
||||
}
|
||||
out.push(0); // end of the header list
|
||||
// Each chunk starts with its part number and its scan line.
|
||||
let mut flat = [0i32.to_le_bytes(), 0i32.to_le_bytes(), 12i32.to_le_bytes()].concat();
|
||||
(0..3).for_each(|_| flat.extend_from_slice(&0.25f32.to_le_bytes()));
|
||||
// The deep chunk holds the sizes of the count table and of the packed and unpacked
|
||||
// samples, then the table (the running sample count) and the one sample.
|
||||
let mut deep = [1i32.to_le_bytes(), 0i32.to_le_bytes()].concat();
|
||||
(0..3).for_each(|_| deep.extend_from_slice(&4u64.to_le_bytes()));
|
||||
deep.extend_from_slice(&1u32.to_le_bytes());
|
||||
deep.extend_from_slice(&0.5f32.to_le_bytes());
|
||||
let first = out.len() + 16;
|
||||
out.extend_from_slice(&(first as u64).to_le_bytes());
|
||||
out.extend_from_slice(&((first + flat.len()) as u64).to_le_bytes());
|
||||
out.extend_from_slice(&flat);
|
||||
out.extend_from_slice(&deep);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deep_part_beside_a_flat_color_part_is_unsupported() {
|
||||
let file = flat_and_deep();
|
||||
let parts = craft_exr::decode::parts(&file, &craft_exr::decode::Limits::default()).unwrap();
|
||||
assert_eq!(parts.iter().map(|p| p.deep).collect::<Vec<_>>(), [false, true]);
|
||||
// The flat part alone decodes, so only the deep part can refuse the file.
|
||||
let flat = craft_exr::decode::decode_part(&file, 0, &|_| true, &craft_exr::decode::Limits::default()).unwrap();
|
||||
assert_eq!(flat.channel("R").unwrap().samples, Samples::F32(vec![0.25]));
|
||||
let refused = craft_texture::decode::exr(&file, &Limits::default());
|
||||
assert_eq!(refused, Err(DecodeError::Unsupported { format: "OpenEXR", reason: "deep data".into() }));
|
||||
}
|
||||
}
|
||||
@@ -153,149 +153,16 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
}
|
||||
|
||||
fn read(&mut self, comp: &mut C, stage: &mut MemoryStage, id: Id, env: &Env) {
|
||||
let ctx = stage.ctx().clone();
|
||||
let props = Arc::clone(&self.props);
|
||||
let props = &*props;
|
||||
let scroll = scroll_of(props);
|
||||
let collapse = props.collapse;
|
||||
let save = props.save.clone();
|
||||
self.save = save.clone();
|
||||
// The overlay host decides a layer's Escape; so does a full-window mount's.
|
||||
self.layer = matches!(props.mount, Mount::Layer(_) | Mount::Viewport { .. } | Mount::FullWindow);
|
||||
self.region_gap = gap_of(&env.tokens, Gap::Tight);
|
||||
self.end_gap = gap_of(&env.tokens, props.end.map_or(Gap::Tight, |end| end.gap));
|
||||
self.header_gap = header_gap_of(props, &env.tokens);
|
||||
let start = layout::flow_start(&ctx, env);
|
||||
self.after_rule = start == Some(true);
|
||||
self.rules = RuleBands::of(props, env, crate::runtime::egui::scale::pixels_per_point(&ctx), start);
|
||||
self.least_width = least_of(&env.tokens, props.least_width);
|
||||
let quiet = stage.is_peek() || crate::runtime::measure::active(&ctx);
|
||||
if !matches!(props.mount, Mount::Inline | Mount::Pane(_))
|
||||
&& let Some(why) = if quiet { crate::runtime::overlay::peek_close(&ctx, id) } else { crate::runtime::overlay::take_close(&ctx, id) }
|
||||
{
|
||||
self.close = true;
|
||||
self.reason = Some(why);
|
||||
}
|
||||
let quiet = self.read_before_open(stage, id, env);
|
||||
self.open_bound = comp.open().is_some();
|
||||
self.open = open_now(comp, stage, id, props);
|
||||
self.open_at_read = self.open;
|
||||
self.presence = match collapse {
|
||||
Some(collapse) if collapse.animated => {
|
||||
Driver { stage: &*stage, base: id, policy: env.motion }.presence("collapse", self.open, spec::OPEN_RISE)
|
||||
}
|
||||
_ => Presence { t: f32::from(u8::from(self.open)), visible: self.open, exiting: false },
|
||||
};
|
||||
self.mode = stage.session::<WindowMode>(sub(id, "window_mode")).clone();
|
||||
self.fixed = match &props.mount {
|
||||
Mount::FullWindow => true,
|
||||
// A viewport whose fallback covers the window is fixed in both modes, as a full-window mount is: its body
|
||||
// never sizes as a layer's content.
|
||||
Mount::Viewport { fallback, .. } if fallback.is_full_window() => true,
|
||||
Mount::Viewport { .. } if windows::mount_window(&ctx, id) => true,
|
||||
Mount::Layer(_) | Mount::Viewport { .. } => {
|
||||
let placement = overlay_of(props).map_or_else(Placement::default, |overlay| {
|
||||
let screen = crate::contract::overlay::screen_for(&ctx, env, overlay);
|
||||
shown_placement(&ctx, id, save.as_ref(), overlay, None, screen, env.tokens.space.inset.screen)
|
||||
});
|
||||
// A layer the user sized takes that size, at its saved position or where its anchor places it.
|
||||
placement.size.is_some()
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
self.last = stage.recall::<BodyView>(sub(id, "view"));
|
||||
self.strip = scroll_strip_height(&env.tokens);
|
||||
self.row = env.tokens.size.control.md;
|
||||
let Some(scroll) = scroll else { return };
|
||||
// A scrolled body of a layer, or in one, starts at the top at every opening of the layer, as at its first.
|
||||
let opening = match props.mount {
|
||||
Mount::Layer(_) => crate::runtime::overlay::appears(&ctx, id, false),
|
||||
_ => crate::runtime::overlay::drawing_parent(&ctx).is_some_and(|layer| crate::runtime::overlay::opening(&ctx, layer)),
|
||||
};
|
||||
if opening && comp.scroll().is_none() {
|
||||
*stage.session::<ScrollState>(sub(id, "scroll")) = ScrollState::default();
|
||||
}
|
||||
self.last_extent = stage.session::<ScrollState>(sub(id, "scroll")).extent;
|
||||
self.scroll_bound = comp.scroll().is_some();
|
||||
let held = match comp.scroll() {
|
||||
Some(bind) => match bind.get() {
|
||||
Some(Mixed::Same(pos)) => pos,
|
||||
_ => ScrollPos::default(),
|
||||
},
|
||||
None => {
|
||||
let state = stage.session::<ScrollState>(sub(id, "scroll"));
|
||||
self.anchor = state.anchor;
|
||||
ScrollPos { x: state.offset.0, y: state.offset.1 }
|
||||
}
|
||||
};
|
||||
self.anchor_at_read = self.anchor;
|
||||
self.offset = held;
|
||||
self.offset_at_read = held;
|
||||
let rtl = env.direction.is_rtl();
|
||||
let view = self.last.view.map_or(Vec2::ZERO, |view| self.shown_view(scroll, rect_of(view)).size());
|
||||
// Step 4 applies, in order, the scroll bar, AccessKit and reveal moves the update step of the last pass queued
|
||||
// (`Jumps`), this pass's wheel share and the scroll moves queued for the body.
|
||||
let frame = jump_frame(&ctx);
|
||||
let jump = pass_state::with::<Jumps, _>(&ctx, |jumps| {
|
||||
jumps.0.retain(|(.., queued)| queued + 1 >= frame);
|
||||
let at = jumps.0.iter().position(|(owner, ..)| *owner == id)?;
|
||||
Some(if quiet { jumps.0[at].1 } else { jumps.0.remove(at).1 })
|
||||
let props = Arc::clone(&self.props);
|
||||
self.open = open_now(comp, stage, id, &props);
|
||||
// The caller's scroll offset: the position it holds, the default when it is mixed or unset.
|
||||
let bound_scroll = comp.scroll().map(|bind| match bind.get() {
|
||||
Some(Mixed::Same(pos)) => pos,
|
||||
_ => ScrollPos::default(),
|
||||
});
|
||||
if let Some(jump) = jump {
|
||||
self.offset = jump;
|
||||
self.moved = true;
|
||||
}
|
||||
if let Some(share) = if quiet { wheel::peek(&ctx, id) } else { wheel::take(&ctx, id) } {
|
||||
let sign = if rtl { 1.0 } else { -1.0 };
|
||||
self.offset.x += f64::from(sign * share.scroll.x);
|
||||
self.offset.y -= f64::from(share.scroll.y);
|
||||
self.moved = true;
|
||||
}
|
||||
for (mv, _) in crate::contract::steps::scroll_moves(&ctx, id, quiet) {
|
||||
let (visible, extent, offset, vertical) = if scroll.vertical_on() {
|
||||
(view.y, self.last_extent.1, self.offset.y, true)
|
||||
} else {
|
||||
(view.x, self.last_extent.0, self.offset.x, false)
|
||||
};
|
||||
let span = ScrollSpan::new(0.0..f64::from(extent).max(f64::from(visible)), offset..offset + f64::from(visible));
|
||||
if let Some(range) = craft_behavior::scroll::jump(&span, mv) {
|
||||
if vertical {
|
||||
self.offset.y = range.start;
|
||||
} else {
|
||||
self.offset.x = range.start;
|
||||
}
|
||||
self.moved = true;
|
||||
}
|
||||
}
|
||||
// A move of the area's own ends a glide; a child reveal starts one. A running glide moves the offset toward
|
||||
// its aim.
|
||||
self.glide = if self.moved { None } else { stage.session::<ScrollState>(sub(id, "scroll")).glide };
|
||||
if let Some(child) = crate::contract::child_reveal(&ctx, id, quiet) {
|
||||
self.glide = Some(Glide { child, to: None, running: false });
|
||||
}
|
||||
self.glide_at_read = self.glide;
|
||||
if let Some(glide) = self.glide.as_mut()
|
||||
&& let Some(to) = glide.to
|
||||
&& (glide.running || !quiet)
|
||||
{
|
||||
let driver = Driver { stage: &*stage, base: id, policy: env.motion };
|
||||
if !glide.running {
|
||||
driver.jump("glide", Vec2::new(self.offset.x as f32, self.offset.y as f32));
|
||||
glide.running = true;
|
||||
}
|
||||
let at = driver.anim("glide", to, spec::FOLLOW);
|
||||
self.offset = ScrollPos { x: f64::from(at.x), y: f64::from(at.y) };
|
||||
self.moved = true;
|
||||
if at == to {
|
||||
self.glide = None;
|
||||
}
|
||||
}
|
||||
let follows = stage.session::<ScrollState>(sub(id, "scroll")).follow_end.unwrap_or(true);
|
||||
self.follows_end = scroll.anchor == crate::contract::ScrollAnchor::End && follows;
|
||||
if self.follows_end && !self.moved {
|
||||
self.offset.y = f64::from((self.last_extent.1 - view.y).max(0.0));
|
||||
}
|
||||
self.clamp_offset(scroll, view);
|
||||
self.view_offset = self.offset;
|
||||
self.read_after_open(stage, id, env, quiet, bound_scroll);
|
||||
}
|
||||
|
||||
fn overflow(&self) -> f32 {
|
||||
@@ -548,60 +415,9 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
}
|
||||
|
||||
fn updated(&mut self, comp: &mut C, cx: &mut Cx<'_, C>) {
|
||||
use crate::contract::Pointer as _;
|
||||
let props = comp.props(Internal::new());
|
||||
let (scroll, layer) = (scroll_of(props), matches!(props.mount, Mount::Layer(_) | Mount::Viewport { .. }));
|
||||
// The OS asked a viewport mount's window to close: the container closes at step 15.
|
||||
if matches!(props.mount, Mount::Viewport { .. }) && windows::take_close_request(cx.core.memory.ctx(), cx.core.id) {
|
||||
self.close = true;
|
||||
self.reason = self.reason.or(Some(CloseReason::Requested));
|
||||
}
|
||||
if scroll.is_some() {
|
||||
self.scroll_input(props, cx);
|
||||
}
|
||||
// A reveal queued for the body moves its offset against the view this pass shows, on top of a move
|
||||
// `scroll_input` queued, within the offsets the content allows; the next pass takes the offset at step 4, as it
|
||||
// takes the scroll bar's, and places by it. A reveal that moves nothing queues no jump, so it costs no pass. The
|
||||
// part of the rect the moved view shows goes on to the scroll owner around.
|
||||
if let Some((scroll, view)) = scroll.zip(self.view)
|
||||
&& let Some(rect) = crate::contract::take_reveal(&cx.core.ctx, cx.core.id)
|
||||
{
|
||||
let view = self.shown_view(scroll, view);
|
||||
let (by, _) = crate::contract::steps::reveal_move(rect, view);
|
||||
let rtl = cx.core.env.direction().is_rtl();
|
||||
let id = cx.core.id;
|
||||
let from = super::scroll::queued_jump(&cx.core.ctx, id).unwrap_or(self.offset);
|
||||
let mut offset = from;
|
||||
offset.y += f64::from(by.y);
|
||||
offset.x += f64::from(if rtl { -by.x } else { by.x });
|
||||
let offset = self.clamped(scroll, view.size(), offset);
|
||||
// A reveal of what the view shows moves nothing: no jump, so no repeated pass.
|
||||
if offset != from {
|
||||
super::scroll::queue_jump(&cx.core.ctx, id, offset);
|
||||
}
|
||||
let moved = Vec2::new((offset.x - from.x) as f32, (offset.y - from.y) as f32);
|
||||
let moved = Vec2::new(if rtl { -moved.x } else { moved.x }, moved.y);
|
||||
crate::contract::Focus::reveal(cx, rect.translate(-moved).intersect(view));
|
||||
}
|
||||
// AccessKit Expand, Collapse and Click reach a collapsible container as an activation: it folds or unfolds.
|
||||
if props.collapse.is_some() && cx.activation().is_some_and(|activation| activation.by_key) {
|
||||
self.open = !self.open;
|
||||
}
|
||||
self.band_double(cx.core);
|
||||
self.surface_press(comp.sense().contains(craft_behavior::Sense::SURFACE), cx.core);
|
||||
let band = props.header.is_some_and(|header| header.band == DragBand::Move);
|
||||
if (band || matches!(props.mount, Mount::Viewport { .. } | Mount::Window { .. }))
|
||||
&& let Some(viewport) = os_window(props, cx.core.memory.ctx(), cx.core.id, &cx.core.env)
|
||||
{
|
||||
self.window_os(viewport, props, cx);
|
||||
self.window_movable(viewport, cx.core);
|
||||
}
|
||||
self.pane_drag(props, cx.core);
|
||||
if layer && !(matches!(props.mount, Mount::Viewport { .. }) && windows::mount_window(cx.core.memory.ctx(), cx.core.id)) {
|
||||
self.window_keys(props, cx);
|
||||
self.window_drag(props, cx);
|
||||
}
|
||||
self.window_placed(props, cx.core);
|
||||
let style_min = cx.style.metrics().min_size;
|
||||
let surface = comp.sense().contains(craft_behavior::Sense::SURFACE);
|
||||
self.updated_core(comp.props(Internal::new()), surface, style_min, cx.core);
|
||||
// The body moves and resizes the layer in screen space; the caller places it in its parent's layer space.
|
||||
let from_screen = crate::runtime::overlay::parent_space(&cx.core.ctx, cx.core.id).inverse();
|
||||
for mut change in std::mem::take(&mut self.reports) {
|
||||
@@ -790,6 +606,215 @@ fn first_line_found(ctx: &Context, (header, body): (Id, Id), top: f32, moved: f3
|
||||
}
|
||||
|
||||
impl BodyHooks<'_> {
|
||||
/// The read step up to the container's open state, which needs the component: the same for every container type.
|
||||
/// Whether the stage only peeks (a peek or a measuring pass), which the rest of the step needs too.
|
||||
fn read_before_open(&mut self, stage: &mut MemoryStage, id: Id, env: &Env) -> bool {
|
||||
let ctx = stage.ctx().clone();
|
||||
let props = Arc::clone(&self.props);
|
||||
let props = &*props;
|
||||
self.save = props.save.clone();
|
||||
// The overlay host decides a layer's Escape; so does a full-window mount's.
|
||||
self.layer = matches!(props.mount, Mount::Layer(_) | Mount::Viewport { .. } | Mount::FullWindow);
|
||||
self.region_gap = gap_of(&env.tokens, Gap::Tight);
|
||||
self.end_gap = gap_of(&env.tokens, props.end.map_or(Gap::Tight, |end| end.gap));
|
||||
self.header_gap = header_gap_of(props, &env.tokens);
|
||||
let start = layout::flow_start(&ctx, env);
|
||||
self.after_rule = start == Some(true);
|
||||
self.rules = RuleBands::of(props, env, crate::runtime::egui::scale::pixels_per_point(&ctx), start);
|
||||
self.least_width = least_of(&env.tokens, props.least_width);
|
||||
let quiet = stage.is_peek() || crate::runtime::measure::active(&ctx);
|
||||
if !matches!(props.mount, Mount::Inline | Mount::Pane(_))
|
||||
&& let Some(why) = if quiet { crate::runtime::overlay::peek_close(&ctx, id) } else { crate::runtime::overlay::take_close(&ctx, id) }
|
||||
{
|
||||
self.close = true;
|
||||
self.reason = Some(why);
|
||||
}
|
||||
quiet
|
||||
}
|
||||
|
||||
/// The read step from the open state on, given the caller's bound scroll offset: the same for every container type.
|
||||
fn read_after_open(&mut self, stage: &mut MemoryStage, id: Id, env: &Env, quiet: bool, bound_scroll: Option<ScrollPos>) {
|
||||
let ctx = stage.ctx().clone();
|
||||
let props = Arc::clone(&self.props);
|
||||
let props = &*props;
|
||||
let scroll = scroll_of(props);
|
||||
let collapse = props.collapse;
|
||||
let save = props.save.clone();
|
||||
self.open_at_read = self.open;
|
||||
self.presence = match collapse {
|
||||
Some(collapse) if collapse.animated => {
|
||||
Driver { stage: &*stage, base: id, policy: env.motion }.presence("collapse", self.open, spec::OPEN_RISE)
|
||||
}
|
||||
_ => Presence { t: f32::from(u8::from(self.open)), visible: self.open, exiting: false },
|
||||
};
|
||||
self.mode = stage.session::<WindowMode>(sub(id, "window_mode")).clone();
|
||||
self.fixed = match &props.mount {
|
||||
Mount::FullWindow => true,
|
||||
// A viewport whose fallback covers the window is fixed in both modes, as a full-window mount is: its body
|
||||
// never sizes as a layer's content.
|
||||
Mount::Viewport { fallback, .. } if fallback.is_full_window() => true,
|
||||
Mount::Viewport { .. } if windows::mount_window(&ctx, id) => true,
|
||||
Mount::Layer(_) | Mount::Viewport { .. } => {
|
||||
let placement = overlay_of(props).map_or_else(Placement::default, |overlay| {
|
||||
let screen = crate::contract::overlay::screen_for(&ctx, env, overlay);
|
||||
shown_placement(&ctx, id, save.as_ref(), overlay, None, screen, env.tokens.space.inset.screen)
|
||||
});
|
||||
// A layer the user sized takes that size, at its saved position or where its anchor places it.
|
||||
placement.size.is_some()
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
self.last = stage.recall::<BodyView>(sub(id, "view"));
|
||||
self.strip = scroll_strip_height(&env.tokens);
|
||||
self.row = env.tokens.size.control.md;
|
||||
let Some(scroll) = scroll else { return };
|
||||
// A scrolled body of a layer, or in one, starts at the top at every opening of the layer, as at its first.
|
||||
let opening = match props.mount {
|
||||
Mount::Layer(_) => crate::runtime::overlay::appears(&ctx, id, false),
|
||||
_ => crate::runtime::overlay::drawing_parent(&ctx).is_some_and(|layer| crate::runtime::overlay::opening(&ctx, layer)),
|
||||
};
|
||||
if opening && bound_scroll.is_none() {
|
||||
*stage.session::<ScrollState>(sub(id, "scroll")) = ScrollState::default();
|
||||
}
|
||||
self.last_extent = stage.session::<ScrollState>(sub(id, "scroll")).extent;
|
||||
self.scroll_bound = bound_scroll.is_some();
|
||||
let held = match bound_scroll {
|
||||
Some(pos) => pos,
|
||||
None => {
|
||||
let state = stage.session::<ScrollState>(sub(id, "scroll"));
|
||||
self.anchor = state.anchor;
|
||||
ScrollPos { x: state.offset.0, y: state.offset.1 }
|
||||
}
|
||||
};
|
||||
self.anchor_at_read = self.anchor;
|
||||
self.offset = held;
|
||||
self.offset_at_read = held;
|
||||
let rtl = env.direction.is_rtl();
|
||||
let view = self.last.view.map_or(Vec2::ZERO, |view| self.shown_view(scroll, rect_of(view)).size());
|
||||
// Step 4 applies, in order, the scroll bar, AccessKit and reveal moves the update step of the last pass queued
|
||||
// (`Jumps`), this pass's wheel share and the scroll moves queued for the body.
|
||||
let frame = jump_frame(&ctx);
|
||||
let jump = pass_state::with::<Jumps, _>(&ctx, |jumps| {
|
||||
jumps.0.retain(|(.., queued)| queued + 1 >= frame);
|
||||
let at = jumps.0.iter().position(|(owner, ..)| *owner == id)?;
|
||||
Some(if quiet { jumps.0[at].1 } else { jumps.0.remove(at).1 })
|
||||
});
|
||||
if let Some(jump) = jump {
|
||||
self.offset = jump;
|
||||
self.moved = true;
|
||||
}
|
||||
if let Some(share) = if quiet { wheel::peek(&ctx, id) } else { wheel::take(&ctx, id) } {
|
||||
let sign = if rtl { 1.0 } else { -1.0 };
|
||||
self.offset.x += f64::from(sign * share.scroll.x);
|
||||
self.offset.y -= f64::from(share.scroll.y);
|
||||
self.moved = true;
|
||||
}
|
||||
for (mv, _) in crate::contract::steps::scroll_moves(&ctx, id, quiet) {
|
||||
let (visible, extent, offset, vertical) = if scroll.vertical_on() {
|
||||
(view.y, self.last_extent.1, self.offset.y, true)
|
||||
} else {
|
||||
(view.x, self.last_extent.0, self.offset.x, false)
|
||||
};
|
||||
let span = ScrollSpan::new(0.0..f64::from(extent).max(f64::from(visible)), offset..offset + f64::from(visible));
|
||||
if let Some(range) = craft_behavior::scroll::jump(&span, mv) {
|
||||
if vertical {
|
||||
self.offset.y = range.start;
|
||||
} else {
|
||||
self.offset.x = range.start;
|
||||
}
|
||||
self.moved = true;
|
||||
}
|
||||
}
|
||||
// A move of the area's own ends a glide; a child reveal starts one. A running glide moves the offset toward
|
||||
// its aim.
|
||||
self.glide = if self.moved { None } else { stage.session::<ScrollState>(sub(id, "scroll")).glide };
|
||||
if let Some(child) = crate::contract::child_reveal(&ctx, id, quiet) {
|
||||
self.glide = Some(Glide { child, to: None, running: false });
|
||||
}
|
||||
self.glide_at_read = self.glide;
|
||||
if let Some(glide) = self.glide.as_mut()
|
||||
&& let Some(to) = glide.to
|
||||
&& (glide.running || !quiet)
|
||||
{
|
||||
let driver = Driver { stage: &*stage, base: id, policy: env.motion };
|
||||
if !glide.running {
|
||||
driver.jump("glide", Vec2::new(self.offset.x as f32, self.offset.y as f32));
|
||||
glide.running = true;
|
||||
}
|
||||
let at = driver.anim("glide", to, spec::FOLLOW);
|
||||
self.offset = ScrollPos { x: f64::from(at.x), y: f64::from(at.y) };
|
||||
self.moved = true;
|
||||
if at == to {
|
||||
self.glide = None;
|
||||
}
|
||||
}
|
||||
let follows = stage.session::<ScrollState>(sub(id, "scroll")).follow_end.unwrap_or(true);
|
||||
self.follows_end = scroll.anchor == crate::contract::ScrollAnchor::End && follows;
|
||||
if self.follows_end && !self.moved {
|
||||
self.offset.y = f64::from((self.last_extent.1 - view.y).max(0.0));
|
||||
}
|
||||
self.clamp_offset(scroll, view);
|
||||
self.view_offset = self.offset;
|
||||
}
|
||||
|
||||
/// Step 13 of a body, without the component: what `updated` does for every container type, kept out of the
|
||||
/// generic hook so the web build carries it once. The placement changes it reports wait in `self.reports`.
|
||||
fn updated_core(&mut self, props: &ContainerProps, surface: bool, style_min: Vec2, core: &mut CxCore<'_>) {
|
||||
use crate::contract::Pointer as _;
|
||||
let (scroll, layer) = (scroll_of(props), matches!(props.mount, Mount::Layer(_) | Mount::Viewport { .. }));
|
||||
// The OS asked a viewport mount's window to close: the container closes at step 15.
|
||||
if matches!(props.mount, Mount::Viewport { .. }) && windows::take_close_request(core.memory.ctx(), core.id) {
|
||||
self.close = true;
|
||||
self.reason = self.reason.or(Some(CloseReason::Requested));
|
||||
}
|
||||
if scroll.is_some() {
|
||||
self.scroll_input(props, core);
|
||||
}
|
||||
// A reveal queued for the body moves its offset against the view this pass shows, on top of a move
|
||||
// `scroll_input` queued, within the offsets the content allows; the next pass takes the offset at step 4, as it
|
||||
// takes the scroll bar's, and places by it. A reveal that moves nothing queues no jump, so it costs no pass. The
|
||||
// part of the rect the moved view shows goes on to the scroll owner around.
|
||||
if let Some((scroll, view)) = scroll.zip(self.view)
|
||||
&& let Some(rect) = crate::contract::take_reveal(&core.ctx, core.id)
|
||||
{
|
||||
let view = self.shown_view(scroll, view);
|
||||
let (by, _) = crate::contract::steps::reveal_move(rect, view);
|
||||
let rtl = core.env.direction().is_rtl();
|
||||
let id = core.id;
|
||||
let from = super::scroll::queued_jump(&core.ctx, id).unwrap_or(self.offset);
|
||||
let mut offset = from;
|
||||
offset.y += f64::from(by.y);
|
||||
offset.x += f64::from(if rtl { -by.x } else { by.x });
|
||||
let offset = self.clamped(scroll, view.size(), offset);
|
||||
// A reveal of what the view shows moves nothing: no jump, so no repeated pass.
|
||||
if offset != from {
|
||||
super::scroll::queue_jump(&core.ctx, id, offset);
|
||||
}
|
||||
let moved = Vec2::new((offset.x - from.x) as f32, (offset.y - from.y) as f32);
|
||||
let moved = Vec2::new(if rtl { -moved.x } else { moved.x }, moved.y);
|
||||
crate::contract::Focus::reveal(core, rect.translate(-moved).intersect(view));
|
||||
}
|
||||
// AccessKit Expand, Collapse and Click reach a collapsible container as an activation: it folds or unfolds.
|
||||
if props.collapse.is_some() && core.activation().is_some_and(|activation| activation.by_key) {
|
||||
self.open = !self.open;
|
||||
}
|
||||
self.band_double(core);
|
||||
self.surface_press(surface, core);
|
||||
let band = props.header.is_some_and(|header| header.band == DragBand::Move);
|
||||
if (band || matches!(props.mount, Mount::Viewport { .. } | Mount::Window { .. }))
|
||||
&& let Some(viewport) = os_window(props, core.memory.ctx(), core.id, &core.env)
|
||||
{
|
||||
self.window_os(viewport, props, core, style_min);
|
||||
self.window_movable(viewport, core);
|
||||
}
|
||||
self.pane_drag(props, core);
|
||||
if layer && !(matches!(props.mount, Mount::Viewport { .. }) && windows::mount_window(core.memory.ctx(), core.id)) {
|
||||
self.window_keys(props, core, style_min);
|
||||
self.window_drag(props, core, style_min);
|
||||
}
|
||||
self.window_placed(props, core);
|
||||
}
|
||||
|
||||
/// The measuring run of the regions in `self.room`, under the inputs `key`: what they took together, padding
|
||||
/// included. `content`: the size the body's content took in the run taken back before this one, recorded with it.
|
||||
fn measure_run<C: Container>(
|
||||
|
||||
@@ -219,12 +219,12 @@ impl BodyHooks<'_> {
|
||||
/// it, so the content laid out for the view (out-of-view children skip their run, `runtime::lazy`) is the content
|
||||
/// shown. Every input read here is the pass's own, and the strips step by the pass's elapsed time, so a pass that
|
||||
/// repeats a frame moves nothing.
|
||||
pub(super) fn scroll_input<C: Container>(&self, props: &ContainerProps, cx: &mut Cx<'_, C>) {
|
||||
pub(super) fn scroll_input(&self, props: &ContainerProps, core: &mut CxCore<'_>) {
|
||||
use crate::contract::Pointer as _;
|
||||
let Some(scroll) = scroll_of(props) else { return };
|
||||
let ctx = cx.core.ctx.clone();
|
||||
let ctx = core.ctx.clone();
|
||||
let mut offset = self.offset;
|
||||
if let Some(range) = cx.scroll_moved(SCROLL_Y) {
|
||||
if let Some(range) = core.scroll_moved(SCROLL_Y) {
|
||||
offset.y = range.start;
|
||||
}
|
||||
// Resting the pointer on a strip scrolls toward it at a steady speed.
|
||||
@@ -232,19 +232,19 @@ impl BodyHooks<'_> {
|
||||
let elapsed = crate::runtime::frame::facts(&ctx).elapsed.clamp(0.0, 0.1);
|
||||
let step = f64::from(STRIP_ROWS_PER_SECOND * self.row) * elapsed;
|
||||
for (strip, toward) in [(STRIP_BACK, -1.0), (STRIP_FORWARD, 1.0)] {
|
||||
if cx.core.results.get(&(strip, None)).is_some_and(|result| result.hovered) {
|
||||
if core.results.get(&(strip, None)).is_some_and(|result| result.hovered) {
|
||||
offset.y += toward * step;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(range) = cx.scroll_moved(SCROLL_X) {
|
||||
if let Some(range) = core.scroll_moved(SCROLL_X) {
|
||||
offset.x = range.start;
|
||||
}
|
||||
self.access_scroll(scroll, &mut offset, cx.core);
|
||||
self.access_scroll(scroll, &mut offset, core);
|
||||
let view = self.last.view.map_or(Vec2::ZERO, |view| self.shown_view(scroll, rect_of(view)).size());
|
||||
let offset = self.clamped(scroll, view, offset);
|
||||
if offset != self.offset {
|
||||
queue_jump(&ctx, cx.core.id, offset);
|
||||
queue_jump(&ctx, core.id, offset);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ use crate::runtime::env::{EnvView, ShellEntry};
|
||||
use crate::runtime::memory::sub;
|
||||
use crate::runtime::windows::{self, ResizeEdge, WindowAction, WindowHit};
|
||||
use crate::runtime::{keys, pointer};
|
||||
use crate::style::{ComponentStyle as _, UiTokens};
|
||||
use crate::style::UiTokens;
|
||||
use craft_behavior::{CursorIcon, GesturePhase, HitLevel, HitPriority, PartKey, PointerEvent, PressPhase};
|
||||
use craft_host::target::{Caps, WindowChrome, WindowState};
|
||||
use craft_keymap::{Chord, Key, Mods};
|
||||
@@ -402,15 +402,15 @@ impl BodyHooks<'_> {
|
||||
/// resize by a step (Shift: four steps), Enter, the command again or a primary press keeps the placement, Escape
|
||||
/// restores it, and focus leaving the container ends the mode. The mode holds its chords through the key stage, so no
|
||||
/// component under focus sees them. Each step is reported as a `PlacementKind::Keyboard` change.
|
||||
pub(super) fn window_keys<C: Container>(&mut self, props: &ContainerProps, cx: &mut Cx<'_, C>) {
|
||||
let (id, ctx) = (cx.core.id, cx.core.ctx.clone());
|
||||
pub(super) fn window_keys(&mut self, props: &ContainerProps, core: &mut CxCore<'_>, style_min: Vec2) {
|
||||
let (id, ctx) = (core.id, core.ctx.clone());
|
||||
let (Some(window), Some(overlay)) = (window_instance(props, id), overlay_of(props)) else { return };
|
||||
let overlay = overlay.in_screen(crate::runtime::overlay::parent_space(&ctx, id));
|
||||
let overlay = &*overlay;
|
||||
let limits = Limits::new(overlay, window_min(props, cx.style.metrics().min_size));
|
||||
let rect = cx.core.rect;
|
||||
let rtl = cx.core.env.direction().is_rtl();
|
||||
let mut slot = PlacementSlot::new(&mut *cx.core.memory, id, self.save.as_ref(), overlay);
|
||||
let limits = Limits::new(overlay, window_min(props, style_min));
|
||||
let rect = core.rect;
|
||||
let rtl = core.env.direction().is_rtl();
|
||||
let mut slot = PlacementSlot::new(&mut *core.memory, id, self.save.as_ref(), overlay);
|
||||
let current = slot.read();
|
||||
let step = |rect: Rect, phase: GesturePhase| PlacementChange { rect, phase, pointer: None, kind: PlacementKind::Keyboard, continued: false };
|
||||
let started = commands::take_for_instance(&ctx, Some(window), false, WindowCommand::from_ref).map(|(command, _)| command);
|
||||
@@ -480,21 +480,21 @@ impl BodyHooks<'_> {
|
||||
/// A drag of the move band or a grip of a layer (not an OS window): the layer follows the pointer within the
|
||||
/// limits, and each step is reported. The drag runs from the rect the layer had when the press went down. Escape,
|
||||
/// which cancels the press, restores the placement from before.
|
||||
pub(super) fn window_drag<C: Container>(&mut self, props: &ContainerProps, cx: &mut Cx<'_, C>) {
|
||||
pub(super) fn window_drag(&mut self, props: &ContainerProps, core: &mut CxCore<'_>, style_min: Vec2) {
|
||||
let Some(overlay) = overlay_of(props) else { return };
|
||||
// A band that moves the window below starts the OS move of the window the layer is shown in.
|
||||
if overlay.moves_window {
|
||||
let viewport = pass::current_viewport(&cx.core.ctx);
|
||||
self.window_os(viewport, props, cx);
|
||||
let viewport = pass::current_viewport(&core.ctx);
|
||||
self.window_os(viewport, props, core, style_min);
|
||||
return;
|
||||
}
|
||||
let id = cx.core.id;
|
||||
let overlay = overlay.in_screen(crate::runtime::overlay::parent_space(&cx.core.ctx, id));
|
||||
let id = core.id;
|
||||
let overlay = overlay.in_screen(crate::runtime::overlay::parent_space(&core.ctx, id));
|
||||
let overlay = &*overlay;
|
||||
let limits = Limits::new(overlay, window_min(props, cx.style.metrics().min_size));
|
||||
let rect = cx.core.rect;
|
||||
let limits = Limits::new(overlay, window_min(props, style_min));
|
||||
let rect = core.rect;
|
||||
// A part the container did not declare this pass (no band, no grips) has no result.
|
||||
let phase = |key: (PartKey, Option<u64>)| cx.core.results.get(&key).map(|result| result.press.phase);
|
||||
let phase = |key: (PartKey, Option<u64>)| core.results.get(&key).map(|result| result.press.phase);
|
||||
let mut pressed = vec![(None, phase((MOVE_BAND, None)))];
|
||||
pressed.extend((0..GRIPS.len()).map(|index| (Some(index), phase((GRIP, Some(index as u64))))));
|
||||
let Some((grip, phase)) = pressed.into_iter().find_map(|(grip, phase)| match phase? {
|
||||
@@ -507,7 +507,7 @@ impl BodyHooks<'_> {
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
let mut slot = PlacementSlot::new(&mut *cx.core.memory, id, self.save.as_ref(), overlay);
|
||||
let mut slot = PlacementSlot::new(&mut *core.memory, id, self.save.as_ref(), overlay);
|
||||
let current = slot.read();
|
||||
let (start, pos, gesture) = match phase {
|
||||
PressPhase::Down { .. } => {
|
||||
@@ -563,30 +563,30 @@ impl BodyHooks<'_> {
|
||||
/// caller sizes that resize ([`Self::window_resize`]). Where the platform answers the hit test
|
||||
/// (`answered_by_platform`), the parts it takes stand for its sink only; the grips of a window its caller sizes
|
||||
/// are never its.
|
||||
pub(super) fn window_os<C: Container>(&mut self, viewport: ViewportId, props: &ContainerProps, cx: &mut Cx<'_, C>) {
|
||||
pub(super) fn window_os(&mut self, viewport: ViewportId, props: &ContainerProps, core: &mut CxCore<'_>, style_min: Vec2) {
|
||||
let by_caller = overlay_of(props).is_some_and(|overlay| overlay.resize.by_caller);
|
||||
if by_caller {
|
||||
let limits = overlay_of(props).map(|overlay| Limits::new(overlay, window_min(props, cx.style.metrics().min_size)));
|
||||
let limits = overlay_of(props).map(|overlay| Limits::new(overlay, window_min(props, style_min)));
|
||||
if let Some(limits) = limits {
|
||||
self.window_resize(viewport, &limits, cx.core);
|
||||
self.window_resize(viewport, &limits, core);
|
||||
}
|
||||
}
|
||||
if answered_by_platform(&cx.core.ctx, viewport) {
|
||||
if answered_by_platform(&core.ctx, viewport) {
|
||||
return;
|
||||
}
|
||||
let app_moves = windows::app_moves(&cx.core.ctx, viewport);
|
||||
let app_moves = windows::app_moves(&core.ctx, viewport);
|
||||
if app_moves {
|
||||
self.window_move(viewport, cx.core);
|
||||
self.window_move(viewport, core);
|
||||
}
|
||||
// The parts stand only by `WindowParts`, and the results of a part not registered this pass are gone.
|
||||
let started =
|
||||
|key: (PartKey, Option<u64>)| cx.core.results.get(&key).is_some_and(|result| matches!(result.press.phase, PressPhase::DragStart { .. }));
|
||||
|key: (PartKey, Option<u64>)| core.results.get(&key).is_some_and(|result| matches!(result.press.phase, PressPhase::DragStart { .. }));
|
||||
if !app_moves && started((MOVE_BAND, None)) {
|
||||
windows::act(&cx.core.ctx, viewport, WindowAction::StartMove);
|
||||
windows::act(&core.ctx, viewport, WindowAction::StartMove);
|
||||
}
|
||||
for (index, (dx, dy, _)) in GRIPS.into_iter().enumerate() {
|
||||
if !by_caller && started((GRIP, Some(index as u64))) {
|
||||
windows::act(&cx.core.ctx, viewport, WindowAction::StartResize(edge_of(dx, dy)));
|
||||
windows::act(&core.ctx, viewport, WindowAction::StartResize(edge_of(dx, dy)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loaded 100 of 188 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user