Merge main into feat/craft-xtask-layers

This commit is contained in:
dotCooCoo committed 2026-11-28 02:15:19 -08:00
commit 4d38322be1
32 files changed
+7100 -17

No files matched your search

Generated
+21
View File
@@ -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"
@@ -15063,6 +15075,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"
+1
View File
@@ -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" }
+16 -9
View File
@@ -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,16 @@ 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. 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
+2 -1
View File
@@ -19,7 +19,8 @@ and contains no `unsafe` code.
them in samples). The pitch shifter's Keep Formants switch adds the formant shifter's latency,
and `latency()` reports it while the switch is on. A ring modulator for robotic and metallic
voices (ring, frequency modulation, and positive or negative comb resonators, with the
frequency moved by an LFO, the input's level or a sample-and-hold source) adds no latency.
frequency moved by an LFO, the input's level or a sample-and-hold source) adds no latency, and
neither does a bitcrusher that takes one sample in every 1 to 50 and rounds it to 1 to 16 bits.
- `loudness`: an ITU-R BS.1770-4 / EBU R128 meter with momentary, short-term and integrated
loudness, loudness range (EBU Tech 3342), sample peak and true peak.
- `pan`: stereo pan laws, a surround panner over any layout of up to 16 speakers, and first-order
+2 -1
View File
@@ -22,7 +22,7 @@ pub(crate) mod util;
pub(crate) mod voice;
pub(crate) use channel::{Amplify, Balance, ChannelVolume, Invert, Route, Routing};
pub use character::RingMod;
pub use character::{Bitcrusher, RingMod};
pub(crate) use declick::ClickRemover;
pub use dither::Dither;
pub use dynamics::{Compressor, Gate, Limiter, Maximizer};
@@ -158,6 +158,7 @@ static REGISTRY: &[EffectInfo] = &[
entry!("click_remover", "Automatic Click Remover", Restoration, ClickRemover),
entry!("channel_mixer", "Channel Mixer", Channel, ChannelMixer),
entry!("distortion", "Distortion", Special, Distortion),
entry!("bitcrusher", "Bitcrusher", Special, Bitcrusher),
entry!("guitar_suite", "GuitarSuite", Special, GuitarSuite),
entry!("mastering", "Mastering", Special, Mastering),
entry!("vocal_enhancer", "Vocal Enhancer", Special, VocalEnhancer),
@@ -991,6 +991,7 @@ fn direct_constructors_cap_the_channel_count() {
voice::VoiceFormant,
suppress::NoiseSuppression,
character::RingMod,
character::Bitcrusher,
);
}
+282
View File
@@ -14,6 +14,9 @@
//! An LFO, an envelope follower (5 ms attack, 100 ms release) or a sample-and-hold source moves the
//! frequency by up to two octaves either way at 100 % depth. The envelope follower moves it up
//! only.
//!
//! The bitcrusher (`bitcrusher`) takes one input sample every `rate_divide` samples, holds it until
//! the next one, and rounds it to a word length of 1 to 16 bits.
use super::util::{DelayLine, Envelope, Lfo, Prng, coef, delay_line_len, echo_tail};
use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, flush32, param_plumbing};
@@ -223,6 +226,102 @@ impl AudioEffect for RingMod {
}
}
/// Bit-depth and sample-rate reduction. The input is sampled once every `rate_divide` samples and
/// held in between; a fractional value alternates between the two nearest whole hold lengths, so
/// the holds average it. Each held sample is rounded to the nearest multiple of the step
/// `2^(1 - bits)`, so silence stays silence and the range -1 ..= 1 takes `2^bits + 1` levels;
/// fractional bits give steps between the whole-bit ones. Bits and Rate Divide take effect from
/// the next sample: a new Bits rounds the sample being held again, and a shorter hold cuts the
/// one in progress short. Mix moves to a new value over 20 ms.
pub struct Bitcrusher {
pv: ParamValues,
/// The input sample each channel holds, before rounding.
held: Vec<f32>,
/// Samples since the last capture, counted so that a capture happens when it reaches the hold
/// length. Infinite after a reset, so the next sample is captured.
since: f64,
mix: Smoothed,
}
impl Bitcrusher {
pub const PARAMS: &'static [ParamSpec] = &[
ParamSpec::new("bits", "Bits", 1.0, 16.0, 8.0, Unit::None),
ParamSpec::new("rate_divide", "Rate Divide", 1.0, 50.0, 4.0, Unit::None),
ParamSpec::new("mix", "Mix", 0.0, 100.0, 100.0, Unit::Percent),
];
pub fn new(sample_rate: f32, channels: usize) -> Self {
let sample_rate = crate::sane_sample_rate(sample_rate);
let ch = crate::sane_channels(channels);
let mut s = Bitcrusher {
pv: ParamValues::new(Self::PARAMS),
held: vec![0.0; ch],
since: f64::INFINITY,
mix: Smoothed::with_ms(1.0, sample_rate, SM),
};
s.apply_params(true);
s
}
fn apply_params(&mut self, snap: bool) {
self.mix.set(self.pv.v("mix") / 100.0);
if snap {
self.mix.snap();
}
}
}
impl AudioEffect for Bitcrusher {
param_plumbing!("bitcrusher");
/// A held sample lasts at most the hold length rounded up, so it sounds for up to that many
/// samples less one after the input ends.
fn tail_samples(&self) -> usize {
(self.pv.v("rate_divide").ceil() as usize).saturating_sub(1)
}
fn reset(&mut self) {
self.held.fill(0.0);
self.since = f64::INFINITY;
self.mix.snap();
}
fn process(&mut self, channels: &mut [&mut [f32]]) {
let n = block_len(channels);
let nch = channels.len().min(self.held.len());
let hold = f64::from(self.pv.v("rate_divide"));
// The rounding and the mix run in f64, so a finite input near the f32 limit stays finite.
let step = (1.0 - f64::from(self.pv.v("bits"))).exp2();
let limit = f64::from(f32::MAX);
for i in 0..n {
let capture = self.since >= hold;
if capture {
// On schedule, less than one sample is left over. More is left after a reset or
// after the hold got shorter; the new holds then count from this capture.
let left = self.since - hold;
self.since = if left < 1.0 { left } else { 0.0 };
}
self.since += 1.0;
let mix = f64::from(self.mix.tick());
for (ch, held) in self.held.iter_mut().enumerate() {
// A non-finite sample is taken as silence. A channel the block leaves out holds
// silence from its first left-out sample on, so it holds none of its earlier audio
// when it comes back.
let dry = match channels.get(ch).filter(|_| ch < nch) {
Some(c) if c[i].is_finite() => f64::from(c[i]),
_ => 0.0,
};
if capture || ch >= nch {
*held = dry as f32;
}
if ch < nch {
// The held input is rounded at the current step, so a change of Bits also
// applies to the hold in progress.
let crushed = ((f64::from(*held) / step).round() * step).clamp(-limit, limit);
channels[ch][i] = blend(dry, crushed, mix) as f32;
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -486,4 +585,187 @@ mod tests {
assert!(x.iter().all(|v| v.is_finite()), "effect {effect}");
}
}
fn crush(params: &[(&str, f32)], channels: usize) -> Bitcrusher {
let mut c = Bitcrusher::new(SR, channels);
for (id, v) in params {
assert!(c.set_param(id, *v), "{id}");
}
c.reset();
c
}
/// Indices of the samples where the output changes, with the first sample counted.
fn changes(x: &[f32]) -> Vec<usize> {
(0..x.len()).filter(|&i| i == 0 || x[i] != x[i - 1]).collect()
}
/// Every output sample is the multiple of `2^(1 - bits)` nearest the input, and silence stays
/// silence.
#[test]
fn bitcrusher_rounds_to_the_word_length() {
for (bits, step) in [(1.0, 1.0f32), (3.0, 0.25), (5.5, 2f32.powf(-4.5))] {
let mut c = crush(&[("bits", bits), ("rate_divide", 1.0)], 1);
let x: Vec<f32> = (0..2000).map(|i| -1.0 + i as f32 / 1000.0).collect();
let mut y = x.clone();
c.process(&mut [&mut y]);
for (a, b) in x.iter().zip(&y) {
let k = b / step;
assert!((k - k.round()).abs() < 1e-3, "bits {bits}: {b} is not a multiple of {step}");
assert!((a - b).abs() <= step / 2.0 + 1e-6, "bits {bits}: {a} became {b}");
}
let mut z = vec![0.0f32; 480];
c.process(&mut [&mut z]);
assert!(z.iter().all(|v| *v == 0.0), "bits {bits}");
}
}
/// The input is taken once every `rate_divide` samples and held: a whole value holds each
/// sample for exactly that many samples, and 2.5 alternates holds of 3 and 2.
#[test]
fn bitcrusher_holds_each_sample_for_the_rate_divide() {
let x: Vec<f32> = (0..200).map(|i| (i + 1) as f32 / 1024.0).collect();
for (divide, want) in [(1.0, vec![1usize]), (5.0, vec![5]), (2.5, vec![3, 2])] {
let mut c = crush(&[("bits", 16.0), ("rate_divide", divide)], 1);
let mut y = x.clone();
c.process(&mut [&mut y]);
let mut expected = vec![0usize];
while let Some(&last) = expected.last() {
let next = last + want[(expected.len() - 1) % want.len()];
if next >= x.len() {
break;
}
expected.push(next);
}
assert_eq!(changes(&y), expected, "divide {divide}");
assert!(expected.iter().all(|&i| y[i] == x[i]), "divide {divide}: a hold does not start with the input");
}
}
#[test]
fn full_mix_keeps_a_small_wet_sample_beside_a_huge_dry_one() {
let mut c = crush(&[("mix", 100.0), ("bits", 16.0), ("rate_divide", 4.0)], 1);
let mut y = vec![0.5, f32::MAX, f32::MAX, f32::MAX, 0.25];
c.process(&mut [&mut y]);
assert_eq!(y[1], 0.5, "the held sample was lost at full mix: {y:?}");
}
/// A shorter rate divide cuts the hold in progress short, and the holds after it have the new
/// length from the first one on.
#[test]
fn bitcrusher_follows_a_shorter_hold_at_once() {
let mut c = crush(&[("bits", 16.0), ("rate_divide", 50.0)], 1);
let mut a: Vec<f32> = (0..10).map(|i| (i + 1) as f32 / 1024.0).collect();
c.process(&mut [&mut a]);
assert!(c.set_param("rate_divide", 2.0));
let input: Vec<f32> = (10..40).map(|i| (i + 1) as f32 / 1024.0).collect();
let mut b = input.clone();
c.process(&mut [&mut b]);
// `changes` counts the first sample whatever it holds, so the capture is checked apart.
assert_eq!(b[0], input[0], "the hold in progress was not cut short");
assert_eq!(changes(&b), (0..30).step_by(2).collect::<Vec<_>>());
assert!((0..30).step_by(2).all(|i| b[i] == input[i]));
}
/// A new Bits rounds the sample being held again from the next sample on, from the input it
/// took rather than from its rounded value, and the hold keeps its length.
#[test]
fn bitcrusher_rounds_the_hold_in_progress_at_new_bits() {
let mut c = crush(&[("bits", 16.0), ("rate_divide", 4.0)], 1);
let mut a = [0.3f32];
c.process(&mut [&mut a]);
assert!((a[0] - 0.3).abs() < 1e-4);
assert!(c.set_param("bits", 1.0));
let mut b = [0.9f32];
c.process(&mut [&mut b]);
assert_eq!(b[0], 0.0, "1 bit did not round the held 0.3 to 0");
assert!(c.set_param("bits", 16.0));
let mut d = [0.9f32, 0.9, 0.7];
c.process(&mut [&mut d]);
assert!((d[0] - 0.3).abs() < 1e-4 && d[0] == d[1], "the held input was lost: {d:?}");
assert_eq!(changes(&[a[0], b[0], d[0], d[1], d[2]]), vec![0, 1, 2, 4], "the hold did not keep its length");
}
/// A channel left out of one block of a single sample, between two captures, holds silence
/// when it comes back instead of the sample it held before.
#[test]
fn bitcrusher_clears_a_channel_left_out_for_one_sample() {
let mut c = crush(&[("bits", 8.0), ("rate_divide", 4.0)], 2);
let (mut l, mut r) = ([1.0f32], [1.0f32]);
c.process(&mut [&mut l, &mut r]);
assert_eq!(r[0], 1.0);
let mut l = [0.0f32];
c.process(&mut [&mut l]);
let (mut l, mut r) = ([0.0f32; 2], [0.0f32; 2]);
c.process(&mut [&mut l, &mut r]);
assert_eq!(r, [0.0, 0.0], "the channel came back with its earlier hold");
assert_eq!(l, [1.0, 1.0], "the channel kept in the block lost its hold");
}
/// A held sample sounds for no longer than the tail reports after the input ends.
#[test]
fn bitcrusher_tail_covers_the_hold() {
for divide in [1.0, 4.0, 7.5, 50.0] {
let mut c = crush(&[("bits", 4.0), ("rate_divide", divide)], 1);
let tail = c.tail_samples();
let mut x = vec![0.0f32; 200];
x[0] = 0.5;
c.process(&mut [&mut x]);
let last = x.iter().rposition(|v| *v != 0.0).unwrap_or(0);
assert_eq!(last, tail, "divide {divide}");
}
}
/// A block that leaves a channel out feeds it silence, so the channel holds none of its earlier
/// audio when it comes back.
#[test]
fn bitcrusher_feeds_channels_a_block_leaves_out_silence() {
let p = [("bits", 6.0), ("rate_divide", 7.0)];
let (mut left_out, mut silent) = (crush(&p, 2), crush(&p, 2));
let x = sine(220.0, 0.5, SR as f64, 4801, 0.0);
for c in [&mut left_out, &mut silent] {
let (mut l, mut r) = (x.clone(), x.clone());
c.process(&mut [&mut l, &mut r]);
}
let mut l = x[..10].to_vec();
left_out.process(&mut [&mut l]);
let (mut l, mut r) = (x[..10].to_vec(), vec![0.0f32; 10]);
silent.process(&mut [&mut l, &mut r]);
let (mut la, mut ra) = (vec![0.0f32; 480], vec![0.0f32; 480]);
left_out.process(&mut [&mut la, &mut ra]);
let (mut lb, mut rb) = (vec![0.0f32; 480], vec![0.0f32; 480]);
silent.process(&mut [&mut lb, &mut rb]);
assert_eq!(ra, rb);
assert_eq!(la, lb);
}
/// At a mix of 0 the input passes through unchanged, and a non-finite sample comes out finite.
#[test]
fn bitcrusher_mix_zero_and_non_finite_input() {
let x = sine(220.0, 0.5, SR as f64, 4800, 0.0);
let mut c = crush(&[("mix", 0.0), ("bits", 2.0), ("rate_divide", 9.0)], 2);
let (mut l, mut r) = (x.clone(), x.clone());
c.process(&mut [&mut l, &mut r]);
assert!(l == x && r == x);
let mut c = crush(&[("bits", 2.0), ("rate_divide", 3.0)], 1);
let mut y = x.clone();
y[99] = f32::NAN;
y[200] = f32::INFINITY;
c.process(&mut [&mut y]);
assert!(y.iter().all(|v| v.is_finite()));
}
/// Finite samples at the f32 limit, held while the input swings to the other limit, come out
/// finite at every mix.
#[test]
fn bitcrusher_keeps_samples_at_the_f32_limit_finite() {
for mix in [0.0, 50.0, 100.0] {
for bits in [1.0, 7.3, 16.0] {
let mut c = crush(&[("mix", mix), ("bits", bits), ("rate_divide", 3.0)], 1);
let mut y: Vec<f32> = (0..30).map(|i| if i % 2 == 0 { f32::MAX } else { -f32::MAX }).collect();
c.process(&mut [&mut y]);
assert!(y.iter().all(|v| v.is_finite()), "mix {mix}, bits {bits}: {y:?}");
}
}
}
}
+10 -6
View File
@@ -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();
+2
View File
@@ -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
}
+3
View File
@@ -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"]
+1
View File
@@ -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`).
+2
View File
@@ -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")]
+29
View File
@@ -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"] }
+148
View File
@@ -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.
+142
View File
@@ -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)
}
+360
View File
@@ -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(())
}
}
+365
View File
@@ -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(&params.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 {}
}
}
}
+261
View File
@@ -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");
}
+123
View File
@@ -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(())
}
}
+36
View File
@@ -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;
+350
View File
@@ -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");
}
}
}
}
+193
View File
@@ -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 {}
+468
View File
@@ -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());
}
+29
View File
@@ -99,6 +99,17 @@ 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`.
@@ -349,6 +360,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 |
@@ -401,6 +422,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 |
+563
View File
@@ -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)
}
+7
View File
@@ -51,11 +51,18 @@
//! 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;
pub mod fonts;
pub mod guards;
pub mod hostile;
pub mod rng;
+630
View File
@@ -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
View File
@@ -1,4 +1,5 @@
//! The crate's integration tests, linked into one test binary.
mod fonts;
mod guards;
mod source_limits;
+108
View File
@@ -9,6 +9,7 @@ The crate is native only and is a dependency of an app's `xtask` package only.
| `runner` | always | `Step`, `run_steps` (steps in order, stop at the first failure, the `ok`, `FAIL` and `skip` summary), `root`, `cargo`, `run`, `run_cancelable`, `nextest_or_test`, `doctest`, `Cancel` |
| `assets` | always | `Policy`, `RowMode`, `check`, `run`, `list_files`, `read_document`, `is_asset`, `ASSET_EXT`: the asset attribution check against the document, folders and extensions the app supplies |
| `layers` | `layers` | `Policy`, `Class`, `check`, `wasm_set`, `from_metadata`, `cargo_metadata`, `read_json`: the crate-layer check against a table the app supplies |
| `names` | always | `Policy`, `Input`, `scan`, `scan_source`, `literals`, `test_path`: the display-name scanner, which looks for the words an app lists in its string literals, `Cargo.toml` descriptions and text files |
| `lock` | `lock` | `LockConfig`, `try_acquire`, `acquire`, `holders`: 1 to 64 slots held across processes through file locks in a directory the app chooses |
| `report` | `report` | `write` and `to_json`: the per-step JSON report (schema 1), replaced atomically through `craft-atomic` |
| `stats` | `stats` | `run`, `collect` and `write_table`: files, lines and tests of Rust per workspace crate (`cargo xtask stats`) |
@@ -162,6 +163,102 @@ The source copies differ in a few rules. An app that switches lists the results
PdfCraft does. PhotoCraft's `STANDALONE_EXCEPTIONS` pairs become `standalone_deps` entries.
- EffectCraft keeps a flat table with its own same-layer pairs and does not check dev-dependencies.
## Names
The app owns its word list, the paths it scans, the literals and exceptions that may keep a word,
the marker, the command or test that runs the scan, and the message it prints. The library reads the
files and returns the findings:
```rust,no_run
use std::path::Path;
use craft_xtask::names::{self, Input, Policy};
const BANNED: &[&str] = &["Amber Tool", "AzureKit"];
const ALLOWED: &[&str] = &["AzureKit Design"];
const POLICY: Policy<'static> = Policy { allowed: ALLOWED, ..Policy::new(BANNED) };
#[test]
fn production_display_names_stay_neutral() {
let base = Path::new(env!("CARGO_MANIFEST_DIR"));
let inputs = [Input::rust(Path::new("src")), Input::rust(Path::new("../engine/src/cmd"))];
let found = names::scan(base, &inputs, &POLICY).unwrap();
let list: Vec<String> = found.iter().map(ToString::to_string).collect();
assert!(list.is_empty(), "Banned display names:\n{}", list.join("\n"));
}
```
- `Input::rust` takes a Rust file or a folder, which is read recursively for `.rs` files that
`Policy::skip` keeps, given their path below the folder (`test_path` by default: `tests.rs`,
`*_tests.rs` and files under a `tests` folder). Links to folders are not followed, also when the
link is an input. A file input is read whatever its name.
- `Input::manifest` reads the values at the key paths `package.description` and
`workspace.package.description` of a `Cargo.toml`: the table header (`[package]`,
`[workspace.package]`) joined with the key, which may be bare, quoted or dotted. Headers and keys
inside strings and arrays do not count, and a key inside an inline table is not read. Before the
first header, the dotted keys `package.description` and `workspace.package.description` are read,
and a bare `description` is not. A `description` under any other table is not read. A TOML string,
single-line or multi-line, is decoded, and a comment after it is not read; any other value is
read as the rest of its line. `Input::text` reads every line of a text file, and
`Input::text_mark_above` also lets a `#` line with the marker exempt the line below it. Inputs
must not include binary files.
- In Rust, the scanner reads `"…"` and `r"…"` literals with any number of `#`, decodes every escape
(`\n`, `\x7A`, `\u{…}`, a backslash before a line break) and reads CRLF as LF. `b"…"`, `br"…"`,
`c"…"` and `cr"…"` are read when `Policy::literals` asks for them; their `\x` escapes are decoded
together as UTF-8, and bytes that are not UTF-8 become U+FFFD. A shebang line, comments,
character, byte and lifetime tokens, and the rest of a module after `#![cfg(test)]` are skipped.
So is the code under `#[cfg(test)]`, comments in the attribute included: a `const`, `static` or
`let` up to its `;`, another item up to the `}` that closes it or the `;` that ends it, and a
field, argument, arm or statement up to its `,` or `;`. A `,` in an expression's generic
arguments (`f::<A, B>`), in the type of a field, a parameter (after its name or pattern) or a
cast (`mut p: Pair<A, B>`, `ptr as *const Pair<A, B>`), or in the parameters of a closure that
starts the expression does not end it. An item keyword counts only when nothing
but qualifiers (`pub`, `unsafe`, `extern "C"` and the like) comes before it, so the `fn` in
`f::<fn()>(…)` or in a field's type does not start an item, and the braces of a macro in an
item's header (`-> ty! { u8 }`) are not its body. A block expression (a block, a macro's braces, a labeled block, or
`if`, `match`, `loop`, `while`, `for`, `unsafe`, `async` or `const`), as the whole statement or as
an arm's expression after `=>`, ends at its `}`, or at the last `}` of an `if` with `else`
branches. Braces in the condition of an `if`, `while`, `match` or `for` (a macro's, or a block
operand such as `if { ready } { … }`) are not its block. When a method call, field or `?` follows
that `}`, it runs up to its `,` or `;`
instead. Other `cfg` expressions and macros are not evaluated. A source the lexer cannot read
(an unterminated literal or comment, an unknown escape, unbalanced delimiters) is an error.
- A word matches as a whole word: the characters next to it are not letters, digits or `_`, in any
script. `MatchCase::Exact` compares characters exactly, and `MatchCase::AsciiInsensitive` ignores
the case of ASCII letters. `allowed` and `exceptions` exempt a whole decoded literal or
description or trimmed text line, never part of one.
- In Rust, the marker counts only inside a comment on a line the literal spans. In a manifest it
counts anywhere on a line the description spans, and in a text file anywhere on the line.
- `scan` identifies a file by its input path joined to the base folder, and joins a relative base
folder to the current folder before it lists any input (on Windows, a drive-relative base such as
`C:src` to the current folder of its drive), so a relative and an absolute input for one file are
read once; `..` and links are not resolved. A drive-relative input is joined to the current
folder of its drive once, before it is listed, and its files are opened under that path.
- `scan` reads each file once, in path order, and returns the findings in path order, then source
order, then the order of `banned`. A `Finding` has the path, the first line of the literal or
description, the word, the decoded text or text line and the kind; its `Display` text is
`path:line: "word" in "text"`. `scan_source` scans one source already in memory, and
`literals` returns a source's literals.
- `names::Error` is `Policy` (no banned words, an empty word or an empty marker), `Io` (with the
path), `InvalidUtf8`, `FileTooLarge`, `TotalTooLarge`, `TooDeep`, `Conflict` (a file given as two
kinds of input) or `Syntax` (with the path and line). `DEFAULT_LIMITS` is 8 MiB per file, 512 MiB
per scan and folders 64 deep; a file larger than the per-file limit, or than what is left of the
scan's limit, is rejected before it is read.
The source copies differ in a few rules. An app that switches lists the results that change:
- The eight `display_names.rs` tests compare exactly (`MatchCase::Exact`), read byte and C strings
like other strings, skip only `#[cfg(test)] mod` (GridCraft skips any `#[cfg(test)]` item up to
its `}` or `;`), pass `\x` and `\u{…}` through undecoded, can take the quote in `'\"'` as the
start of a string (LightCraft, FigCraft, PhotoCraft), follow folder links, skip a file root named
like a test file, and stop with a panic on a file they cannot read (FigCraft returns the error).
Each finds more or less here accordingly.
- VectorCraft's `brands` check compares ASCII letters without case (`MatchCase::AsciiInsensitive`)
and reads byte and C strings (`Literals`). It also takes a non-ASCII letter or `_` next to a word
as a word boundary, takes its marker anywhere on a line, literals included, reads an escape as a
space, reads manifest lines that start with `description` as they are (comments included, one
line of a multi-line value), and skips a file it cannot read.
- PhotoCraft's check of its locale catalogs stays in the app.
## Assets
The app owns its `cargo xtask assets` command, the printing and the gate step. The library lists the
@@ -369,10 +466,19 @@ fn version(rest: &[&str]) -> Result<(), String> {
| `layers`: format allowlists and the tests in `layers::tests::gridcraft` | GridCraft `xtask/src/layers.rs` at [06c2b14](https://github.com/storytold/gridcraft/blob/06c2b1440b0134ec184561dcc2275fdb5f18a5af/xtask/src/layers.rs) |
| `layers`: dev-only exceptions | DeckCraft `xtask/src/layers.rs` at [4b93429](https://github.com/storytold/deckcraft/blob/4b93429c9ec3921042f5d4ff27efa5ae999336fb/xtask/src/layers.rs) |
| `layers`: `SameLayer::Allowed` and `sideways` for a flat table (EffectCraft allows every same-layer dependency in L0 and listed pairs above it) | EffectCraft `xtask/src/main.rs` at [d4e33b2](https://github.com/storytold/effectcraft/blob/d4e33b2bda4515d456408b9bd8afb7e536770a40/xtask/src/main.rs) |
| `names`: the literal lexer, whole-word matching, allowed literals, the tree walk and the tests `production_display_names_stay_neutral`, `guard_distinguishes_labels_from_identifiers_and_comments`, `guard_scans_production_after_test_only_items`, `guard_skips_escaped_character_literals`, `guard_decodes_whitespace_escapes` | CADCraft `crates/ui-egui/tests/display_names.rs` at [8e69890](https://github.com/storytold/cadcraft/blob/8e6989022398ff5f79adaab77d19fdd7137591f3/crates/ui-egui/tests/display_names.rs) and DeckCraft at [b0c77eb](https://github.com/storytold/deckcraft/blob/b0c77ebd6a6fe6c9037cfbe1c8a7f397304b2205/crates/ui-egui/tests/display_names.rs) |
| `names`: the test `guard_scans_after_escaped_character_literals` | AniCraft `crates/engine/tests/display_names.rs` at [3435e98](https://github.com/storytold/anicraft/blob/3435e9868150312e54694c0a70082609b2fe8573/crates/engine/tests/display_names.rs) |
| `names`: read errors returned, and the test `source_read_failures_are_reported` | FigCraft `crates/mcp/tests/display_names.rs` at [bad07e4](https://github.com/storytold/figcraft/blob/bad07e4433240cad046589129c084bd2fc36f097/crates/mcp/tests/display_names.rs) |
| `names`: the tests `guard_scans_production_after_test_only_items_and_parses_raw_labels`, `guard_skips_escaped_character_literals_without_hiding_labels`, and `exceptions` for a group-label prefix | WordCraft `crates/ui-egui/tests/display_names.rs` at [323cf78](https://github.com/storytold/wordcraft/blob/323cf78232ff3c07f9dbb7989ed729d5851c9773/crates/ui-egui/tests/display_names.rs) |
| `names`: `exceptions` for a message prefix | LightCraft `crates/ui-egui/tests/display_names.rs` at [6b2b7e6](https://github.com/storytold/lightcraft/blob/6b2b7e6d1117e683a1701568e56f979d061e4699/crates/ui-egui/tests/display_names.rs) |
| `names`: a single file as a root | GridCraft `crates/ui-egui/tests/display_names.rs` at [f204433](https://github.com/storytold/gridcraft/blob/f2044337c7e195bdf6bec1b3914937a3dd386749/crates/ui-egui/tests/display_names.rs) |
| `names`: allowed literals | PhotoCraft `crates/ui-egui/tests/display_names.rs` at [d6557b9](https://github.com/storytold/photocraft/blob/d6557b9a8b40f0542a99e7382ec2b5250548e27b/crates/ui-egui/tests/display_names.rs) |
| `names`: `MatchCase::AsciiInsensitive`, manifest descriptions, text files, the marker and the line above it, the literal's first line, and the tests `rust_literals_skip_comments_identifiers_tests_and_marked_lines`, `whole_words_only`, `docs_packaging_and_manifests`, `scope`, `injected_strings_fail_the_gate`, `the_tree_is_clean` | VectorCraft `xtask/src/brands.rs` at [107078a](https://github.com/storytold/vectorcraft/blob/107078ad10870f8a8fdeade9bd5627a3eea34a67/xtask/src/brands.rs) |
| `stats`: the folder walk that skips directory links, and the table | DesignCraft `xtask/src/stats.rs` at `dc9eea2695` |
| `stats`: regular files only, and `a_walk_does_not_follow_directory_links` | WordCraft `xtask/src/stats.rs` at `6b163b33dc` |
| `stats`: the entry budget that returns an error, and its two tests | CADCraft `xtask/src/stats.rs` at `ca87680fb0` |
| `stats`: the per-file size limit, and its two tests | GridCraft `xtask/src/stats.rs` at `9e9f13114f` |
| The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report; in `names`, the full escape decoder, byte and C strings as an option, every `#[cfg(test)]` item form and `#![cfg(test)]`, the syntax errors, the marker only in comments, word boundaries in every script, the limits, the sorted findings and the skipped folder links; in `stats`, the metadata, total-size, depth and `--list` output limits, the metadata checks and the line naming failed listings | written here |
| The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report; in `stats`, the metadata, total-size, depth and `--list` output limits, the metadata checks and the line naming failed listings; in `layers`, the policy checks, membership by manifest directory, the strict metadata reader, the bounded metadata command, cycle detection, the build-tool class and `wasm_set` | written here |
| `version`: `read`, `validate` with the overflow and prerelease checks, the restore after a failed update, and the tests `reads_the_workspace_version`, `replaces_only_the_workspace_version`, `keeps_crlf_line_endings`, `validates_versions`, `rejects_what_cargo_rejects`, `a_failed_update_restores_the_manifest` | SoundCraft `xtask/src/version.rs` at [6c84416](https://github.com/storytold/soundcraft/blob/6c84416c3cffb72d8d350ddfefc4fc9ee954ca1a/xtask/src/version.rs) |
| `version`: the path dependency pins and the test `moves_the_workspace_crates_pins_with_it` | PdfCraft `xtask/src/version.rs` at [3e30645](https://github.com/storytold/pdfcraft/blob/3e3064532f04fd6ec769c6bd7b2c97464757970e/xtask/src/version.rs) |
@@ -392,6 +498,8 @@ No app uses this crate yet.
|---|---|
| DesignCraft | Planned: `cmd_ci`, `root`, `cargo`, `run`, `cmd_test` and `cmd_doctest` move to `runner`, with `TestMode::PreferNextest`. The step list, `TEST_TARGETS` and the i18n report stay in the app. |
| DesignCraft, CADCraft, VectorCraft, DeckCraft, WordCraft, PdfCraft, PhotoCraft, GridCraft, EffectCraft | Planned: `xtask/src/layers.rs` (EffectCraft: the check in `xtask/src/main.rs`) moves to `layers`. The table, chains, exceptions, UI layer and the tests of the app's own policy stay in the app. |
| AniCraft, CADCraft, DeckCraft, FigCraft, GridCraft, LightCraft, PhotoCraft, WordCraft | Planned: the lexer and matcher of `display_names.rs` move to `names`, with `MatchCase::Exact`. `BANNED`, `ALLOWED`, `ROOTS`, the prefix exceptions (LightCraft, WordCraft), PhotoCraft's catalog test and the tests named after them stay in the app. |
| VectorCraft | Planned: `cargo xtask brands` calls `names::scan` with `MatchCase::AsciiInsensitive`, byte and C strings, `brand-ok` and its desktop entry as `Input::text_mark_above`. The word list, the file selection from `git ls-files` and the message stay in the app. |
| LightCraft | Planned: `ci_lock.rs` moves to `lock`, with `LIGHTCRAFT_CI_LOCK` and `LIGHTCRAFT_CI_SLOTS` read by the app. The machine, GPU, corpus and skip report stays in the app. |
| CADCraft, DeckCraft, DesignCraft, GridCraft, LightCraft, PhotoCraft, VectorCraft, WordCraft | Planned: `xtask/src/stats.rs` moves to `stats`. Each app's switch lists its per-crate counts before and after in its pull request. |
| SoundCraft, PdfCraft | Planned: `xtask/src/version.rs` moves to `version`, with the app's root and `CARGO` passed to `run`. `the_real_manifest_has_a_valid_version`, and PdfCraft's `workspace_rust_version_covers_the_ui_crate`, stay in the app. |
+3
View File
@@ -15,6 +15,8 @@
//! - `layers` (feature `layers`): the crate-layer check. The app supplies its table of packages and
//! layers as a `layers::Policy`; `layers::check` reports each dependency the policy does not allow,
//! and `layers::wasm_set` picks the packages the app's wasm step builds.
//! - [`names`]: the display-name scanner. [`names::scan`] looks for the words an app lists in its
//! Rust string literals, `Cargo.toml` descriptions and text files, and returns what it finds.
//! - `lock` (feature `lock`): a fixed number of slots, held across processes through file locks, so
//! that gate runs in several checkouts of one machine take turns.
//! - `report` (feature `report`): the per-step JSON report, replaced atomically.
@@ -50,6 +52,7 @@ pub mod assets;
pub mod layers;
#[cfg(feature = "lock")]
pub mod lock;
pub mod names;
#[cfg(feature = "report")]
pub mod report;
pub mod runner;
File diff suppressed because it is too large. Load diff
+1
View File
@@ -7,6 +7,7 @@ Provider ids:
- `craft.mask`: CPU stand-in for FilmCraft mask composite until WGSL lands on wgpu
- `craft.composite.premul`: CPU premultiplied "over" (Normal path from `composite.wgsl`) until WGSL lands on wgpu
- `craft.readback`: CPU decode of staging buffers (`f16` RGBA → `f32`, or `fmt:u8` passthrough); uses [`chunk_buffer`](../crates/gpu/src/chunk.rs) against device caps and [`f16_to_f32*`](../crates/gpu/src/readback.rs) from **craft-gpu**
- `craft.yuv`: RGBA8 to NV12, P010 or I420 with scaling, registered from **craft-gpu-yuv** (`YuvProvider`, see [its README](../crates/gpu-yuv/README.md)). It is not in `register_all()`, since it depends on wgpu. `YuvProvider::new()` converts on the CPU on any context; `YuvProvider::with_device` runs its WGSL render passes on a device the host passes in.
- `{app}.*`: registered by application wasm at init
Generic worker code must only call `ProviderRegistry::dispatch`: never import app gpu crates.