Files
Dylan M. Taylor 6f20a6b9f2 gpu, camera_raw: develop Detail on the GPU using craft_develop (#13519, #587) (#16480)
* gpu,camera_raw: develop Detail on the GPU using craft_develop::camera_raw (#13519, #587)

* ui-egui/camera_raw_gpu: remove temporary gpu_stages Detail filter (#16485)
2026-11-23 08:55:17 -05:00

807 lines
33 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Camera Raw's GPU preview pass against the CPU develop (the oracle), stage by stage, at an
//! integer depth (8 or 16 bits) and at 32 bits (see [`depths`]). Skips, with a message, when
//! there is no adapter or device or it can't render `Rgba32Float`; with `WGPU_BACKEND` set those
//! fail instead, as in `parity.rs`. A pipeline that doesn't build on an adapter that can run it
//! fails. The shader itself is validated without a GPU ([`the_shader_validates_without_a_gpu`]),
//! so a WGSL error fails on every runner.
use photocraft_algo::camera_raw::{self as raw, CameraRaw, DevelopInputs, StoredVignetteStyle, Wheel};
use photocraft_gpu::{CameraRawDevelop, DeviceHealth, Fault};
/// The settings and the job inputs (scale, grain seed, encoding) of one develop; `CameraRaw` is `#[non_exhaustive]`, so
/// cases are built by [`cr!`].
#[derive(Clone, Debug, Default)]
struct Case {
p: CameraRaw,
inputs: DevelopInputs,
}
/// A [`Case`] with the named fields set: `seed`, `pixel_scale` and `encoding_gamma` go to the inputs, the rest to the settings.
/// A bare field name takes the local of that name.
macro_rules! cr {
(@set $s:ident;) => {};
(@set $s:ident; seed: $v:expr $(, $($rest:tt)*)?) => {
$s.inputs.seed = $v;
cr!(@set $s; $($($rest)*)?);
};
(@set $s:ident; pixel_scale: $v:expr $(, $($rest:tt)*)?) => {
$s.inputs.pixel_scale = $v;
cr!(@set $s; $($($rest)*)?);
};
(@set $s:ident; encoding_gamma: $v:expr $(, $($rest:tt)*)?) => {
$s.inputs.encoding_gamma = $v;
cr!(@set $s; $($($rest)*)?);
};
(@set $s:ident; $f:ident : $v:expr $(, $($rest:tt)*)?) => {
$s.p.$f = $v;
cr!(@set $s; $($($rest)*)?);
};
(@set $s:ident; $f:ident $(, $($rest:tt)*)?) => {
$s.p.$f = $f;
cr!(@set $s; $($($rest)*)?);
};
($($t:tt)*) => {{
let mut s = Case::default();
cr!(@set s; $($t)*);
s
}};
}
fn develop(px: &mut [[f32; 4]], w: usize, h: usize, c: &Case, float: bool) {
raw::develop(px, w, h, &c.p, &c.inputs, float);
}
fn per_pixel(c: &Case, w: usize, h: usize, float: bool, points: Option<(f32, f32)>) -> Option<raw::PerPixel> {
raw::per_pixel(&c.p, &c.inputs, w, h, float, points)
}
fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, c: &Case) -> Option<(f32, f32)> {
raw::white_black_points(px, w, h, &c.p, &c.inputs)
}
fn spatial(c: &Case) -> bool {
raw::spatial(&c.p)
}
/// Largest difference from the CPU develop, per channel. The pass evaluates the same
/// expressions in f32, so what remains is the GPU's own `pow`, `exp2` and `sin` (a few ulps) and
/// how they move a value across a table entry; measured at most about 1e-5 on NVIDIA (Vulkan,
/// DX12) and WARP. 1/4096 keeps a margin and stays well under one 8-bit step (the compositor's
/// tolerance is 1/255).
const TOL: f32 = 1.0 / 4096.0;
struct Gpu {
device: wgpu::Device,
queue: wgpu::Queue,
dev: CameraRawDevelop,
_lock: std::sync::MutexGuard<'static, ()>,
}
fn gpu() -> Option<Gpu> {
let lock = crate::GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let required = std::env::var_os("WGPU_BACKEND").is_some();
// `WGPU_BACKEND` picks the backend; `PHOTOCRAFT_TEST_FALLBACK_ADAPTER=1` the software one (WARP).
let instance = crate::instance();
let fallback = std::env::var_os("PHOTOCRAFT_TEST_FALLBACK_ADAPTER").is_some();
let options = wgpu::RequestAdapterOptions { force_fallback_adapter: fallback, ..Default::default() };
let adapter = match pollster::block_on(instance.request_adapter(&options)) {
Ok(a) => a,
Err(e) => {
assert!(!required, "WGPU_BACKEND is set but has no adapter: {e}");
eprintln!("skipping Camera Raw GPU tests: no adapter ({e})");
return None;
}
};
let info = adapter.get_info();
if !CameraRawDevelop::supported(&adapter) {
assert!(!required, "WGPU_BACKEND is set but {} can't render Rgba32Float", info.name);
eprintln!("skipping Camera Raw GPU tests: adapter can't render Rgba32Float");
return None;
}
let (device, queue) = match pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())) {
Ok(d) => d,
Err(e) => {
assert!(!required, "WGPU_BACKEND is set but {} has no device: {e}", info.name);
eprintln!("skipping Camera Raw GPU tests: no device ({e})");
return None;
}
};
eprintln!("Camera Raw GPU tests on {:?} ({})", info.backend, info.name);
// The adapter can run the pass: a pipeline that doesn't build is a bug in it, not a skip.
let dev = CameraRawDevelop::new(&device).unwrap_or_else(|e| panic!("the Camera Raw pipeline didn't build on {}: {}", info.name, e.0));
Some(Gpu { device, queue, dev, _lock: lock })
}
/// The Camera Raw shaders parse and validate (naga, as wgpu does before any driver sees them),
/// with no adapter: the GPU tests below skip on runners without one. The filters are compiled
/// appended to the tone shader, as the pass builds them.
#[test]
fn the_shaders_validate_without_a_gpu() {
let tone = format!("{}\n{}", photocraft_gpu::CAMERA_RAW_TONE_SHADER, photocraft_gpu::CAMERA_RAW_FILTERS_SHADER);
for src in [photocraft_gpu::CAMERA_RAW_SHADER, tone.as_str()] {
let module = wgpu::naga::front::wgsl::parse_str(src).unwrap_or_else(|e| panic!("{}", e.emit_to_string(src)));
wgpu::naga::valid::Validator::new(wgpu::naga::valid::ValidationFlags::all(), wgpu::naga::valid::Capabilities::empty())
.validate(&module)
.unwrap_or_else(|e| panic!("{}", e.emit_to_string(src)));
assert!(!module.entry_points.is_empty());
}
}
#[derive(Clone, Copy, Debug)]
enum Depth {
Eight,
Sixteen,
Float,
}
const DEPTHS: [Depth; 3] = [Depth::Eight, Depth::Sixteen, Depth::Float];
/// The depths the `i`th case of a set runs at: one integer depth and 32 bits. 8 and 16 bits both
/// develop with `float = false` (the dialog hands the develop only `float`, see
/// `crates/ui-egui/src/dialogs/camera_raw_gpu.rs`), so they share every line of the CPU develop
/// and the pass and differ only in how [`image`] quantizes the input; cases alternate between
/// them so both quantizations still run.
fn depths(i: usize) -> [Depth; 2] {
[DEPTHS[i % 2], Depth::Float]
}
fn hash(i: usize, c: u64) -> f32 {
let mut z = (i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ c.wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
z = (z ^ (z >> 29)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
(z >> 40) as f32 / (1u64 << 24) as f32
}
/// Gradients, noise and saturated patches (every Color Mixer band), quantized to `depth`. The
/// 32-bit image also has values above 1 and a few below 0.
fn image(w: usize, h: usize, depth: Depth) -> Vec<[f32; 4]> {
(0..w * h)
.map(|i| {
let (x, y) = ((i % w) as f32 / w as f32, (i / w) as f32 / h as f32);
let mut c = if (i / w).is_multiple_of(4) {
// A hue sweep at full and half saturation.
let hue = x * 6.0;
let f = |n: f32| (((hue + n) % 6.0 - 3.0).abs() - 1.0).clamp(0.0, 1.0);
let s = if (i / w).is_multiple_of(8) { 1.0 } else { 0.5 };
[f(0.0), f(4.0), f(2.0)].map(|v| (1.0 - s) * 0.6 + s * v)
} else {
[0.1 + 0.8 * x, 0.2 + 0.6 * y, 0.5 - 0.4 * x * y].map(|v| v + (hash(i, 1) - 0.5) * 0.15)
};
if let Depth::Float = depth {
c = c.map(|v| v * (1.0 + 1.5 * y) - 0.02 * hash(i, 2));
}
let q = |v: f32| match depth {
Depth::Eight => (v.clamp(0.0, 1.0) * 255.0).round() / 255.0,
Depth::Sixteen => (v.clamp(0.0, 1.0) * 32768.0).round() / 32768.0,
Depth::Float => v,
};
[q(c[0]), q(c[1]), q(c[2]), 1.0]
})
.collect()
}
/// Develops `p` both ways and returns the largest channel difference.
fn compare_at(g: &mut Gpu, p: &Case, depth: Depth, (w, h): (usize, usize)) -> f32 {
compare_image(g, p, depth, &image(w, h, depth), (w, h))
}
fn compare_image(g: &mut Gpu, p: &Case, depth: Depth, src: &[[f32; 4]], (w, h): (usize, usize)) -> f32 {
let float = matches!(depth, Depth::Float);
let src = src.to_vec();
let mut cpu = src.clone();
develop(&mut cpu, w, h, p, float);
let points = white_black_points(&src, w, h, p);
let stages = per_pixel(p, w, h, float, points).unwrap_or_else(|| panic!("{p:?} has a spatial stage"));
let out = g.dev.develop(&g.device, &g.queue, None, &src, None, [w as u32, h as u32], &stages).unwrap();
assert_eq!(out.len(), cpu.len());
let mut worst = (0.0f32, 0usize);
for (i, (a, b)) in out.iter().zip(&cpu).enumerate() {
assert!(a.iter().all(|v| v.is_finite()), "{p:?} {depth:?}: non-finite GPU pixel {i}: {a:?}");
assert_eq!(a[3], b[3], "alpha is kept");
for c in 0..3 {
let d = (a[c] - b[c]).abs();
if d > worst.0 {
worst = (d, i);
}
}
}
let (d, i) = worst;
assert!(d <= TOL, "{p:?} {depth:?}: GPU {:?} vs CPU {:?} at pixel {i} (source {:?}), off by {d}", out[i], cpu[i], src[i]);
if !float {
assert!(out.iter().all(|q| q[..3].iter().all(|v| (0.0..=1.0).contains(v))), "{p:?} {depth:?}: clipped like the CPU");
}
d
}
fn check(name: &str, sets: &[Case]) {
check_at(name, sets, (171, 113));
}
fn check_at(name: &str, sets: &[Case], size: (usize, usize)) {
let Some(mut g) = gpu() else { return };
for (i, p) in sets.iter().enumerate() {
for depth in depths(i) {
let d = compare_at(&mut g, p, depth, size);
eprintln!("{name} {depth:?}: max |GPU - CPU| = {d:.2e}");
}
}
}
#[test]
fn white_balance_and_exposure() {
check("white balance", &[cr! { temperature: 40.0, tint: -25.0}, cr! { temperature: -70.0, tint: 60.0, exposure: -1.2}, cr! { exposure: 1.5}]);
}
#[test]
fn contrast_without_texture_or_clarity() {
check("contrast", &[cr! { contrast: 60.0}, cr! { contrast: -80.0, exposure: 0.4}]);
}
#[test]
fn whites_and_blacks() {
check(
"whites/blacks",
&[
cr! { whites: 70.0, blacks: -45.0},
cr! { whites: -60.0, blacks: 50.0, temperature: 20.0},
cr! { whites: 30.0},
cr! { blacks: -100.0, exposure: -0.5},
// ProPhoto's power-law encoding.
cr! { whites: 50.0, blacks: -30.0, encoding_gamma: 1.8},
],
);
}
#[test]
fn tone_curves() {
check(
"tone curves",
&[
cr! {
curve_highlights: -60.0,
curve_lights: 30.0,
curve_darks: 40.0,
curve_shadows: -20.0,
curve_splits: [20.0, 45.0, 80.0]},
cr! { point_curve: vec![[0.0, 20.0], [64.0, 50.0], [192.0, 220.0], [255.0, 245.0]]},
cr! {
point_curve_red: vec![[0.0, 0.0], [128.0, 160.0], [255.0, 255.0]],
point_curve_green: vec![[0.0, 10.0], [255.0, 230.0]],
point_curve_blue: vec![[0.0, 0.0], [100.0, 70.0], [255.0, 255.0]]},
],
);
}
#[test]
fn vibrance_and_saturation() {
check("presence", &[cr! { vibrance: 70.0}, cr! { saturation: -60.0}, cr! { vibrance: -40.0, saturation: 50.0}]);
}
#[test]
fn color_mixer() {
let ramp = |k: f32| std::array::from_fn(|i| ((i as f32 * 37.0 + k) % 200.0) - 100.0);
check(
"color mixer",
&[
cr! { hsl_hue: ramp(0.0)},
cr! { hsl_sat: ramp(50.0)},
cr! { hsl_lum: ramp(120.0)},
cr! { hsl_hue: ramp(10.0), hsl_sat: ramp(80.0), hsl_lum: ramp(150.0)},
],
);
}
#[test]
fn color_grading() {
check(
"color grading",
&[
cr! { grade_shadows: Wheel { hue: 220.0, sat: 70.0, lum: 20.0 }},
cr! {
grade_midtones: Wheel { hue: 120.0, sat: 30.0, lum: -15.0 },
grade_highlights: Wheel { hue: 40.0, sat: 50.0, lum: 10.0 },
grade_global: Wheel { hue: 300.0, sat: 15.0, lum: 5.0 },
grade_blending: 80.0,
grade_balance: -40.0},
],
);
}
#[test]
fn vignette() {
check(
"vignette",
&[
cr! { vignette_amount: -70.0},
cr! { vignette_amount: -50.0, vignette_roundness: -60.0, vignette_feather: 20.0, vignette_highlights: 70.0},
cr! {
vignette_amount: 60.0,
vignette_roundness: 80.0,
vignette_midpoint: 20.0,
vignette_style: StoredVignetteStyle::ColorPriority},
cr! { vignette_amount: -40.0, vignette_style: StoredVignetteStyle::PaintOverlay},
cr! { vignette_amount: 40.0, vignette_style: StoredVignetteStyle::PaintOverlay},
],
);
}
#[test]
fn grain_in_full_resolution_coordinates() {
check(
"grain",
&[
cr! { grain_amount: 60.0, seed: 3},
// A preview proxy: the noise lattice is sampled at full-resolution positions.
cr! { grain_amount: 80.0, grain_size: 60.0, grain_roughness: 90.0, seed: u32::MAX, pixel_scale: 0.143},
cr! { grain_amount: 25.0, grain_size: 0.0, grain_roughness: 0.0, seed: 77, pixel_scale: 0.5},
],
);
}
#[test]
fn every_per_pixel_stage_at_once() {
let mut hsl = [0.0; 8];
hsl[1] = 35.0;
hsl[5] = -50.0;
check(
"all stages",
&[cr! {
temperature: 25.0,
tint: 10.0,
exposure: 0.3,
contrast: 25.0,
whites: 20.0,
blacks: -15.0,
vibrance: 30.0,
saturation: 10.0,
curve_darks: 20.0,
point_curve: vec![[0.0, 8.0], [255.0, 250.0]],
hsl_hue: hsl,
hsl_sat: hsl,
hsl_lum: hsl,
grade_shadows: Wheel { hue: 210.0, sat: 25.0, lum: 0.0 },
vignette_amount: -30.0,
grain_amount: 20.0,
pixel_scale: 0.2}],
);
}
#[test]
fn identity_leaves_pixels_alone_and_detail_has_stages() {
let Some(mut g) = gpu() else { return };
let p = Case::default();
let src = image(64, 32, Depth::Float);
let stages = per_pixel(&p, 64, 32, false, None).unwrap();
let out = g.dev.develop(&g.device, &g.queue, None, &src, Some(1), [64, 32], &stages).unwrap();
assert_eq!(out, src, "the CPU develop returns early, unclipped");
// The stages hand Detail over (craft-libs#3101), but the pass has no Detail stage yet, so the
// dialog keeps these on the CPU (`camera_raw_gpu::gpu_stages` in photocraft-ui-egui).
for set in [cr! { sharpen_amount: 10.0}, cr! { noise_luminance: 10.0, clarity: 20.0}, cr! { noise_color: 10.0, dehaze: 20.0}] {
assert!(spatial(&set) && per_pixel(&set, 64, 32, false, Some((0.0, 1.0))).is_some_and(|s| s.detail.is_some()), "{set:?}");
}
// Whites and Blacks need the image's points, unless a spatial stage's passes measure them.
// Detail comes after them, so with only Detail the points are measured on the CPU.
assert!(per_pixel(&cr! { whites: 10.0}, 64, 32, false, None).is_none());
let sharpened = cr! { whites: 10.0, sharpen_amount: 30.0};
assert!(per_pixel(&sharpened, 64, 32, false, None).is_none());
let points = white_black_points(&src, 64, 32, &sharpened);
let s = per_pixel(&sharpened, 64, 32, false, points).unwrap();
assert!(s.whites_blacks.is_some() && s.measure_whites_blacks.is_none() && s.detail.is_some());
let toned = per_pixel(&cr! { whites: 10.0, shadows: 20.0}, 64, 32, false, None).unwrap();
assert!(toned.local_tone.is_some() && toned.whites_blacks.is_none() && toned.measure_whites_blacks == Some([10.0, 0.0]));
for p in [cr! { blacks: -10.0, dehaze: 20.0}, cr! { blacks: -10.0, clarity: 20.0}, cr! { blacks: -10.0, texture: 20.0}] {
let s = per_pixel(&p, 64, 32, false, None).unwrap();
assert!(s.whites_blacks.is_none() && s.measure_whites_blacks == Some([0.0, -10.0]), "{p:?}");
}
// Wider than the filter's working copy, the develop filters a reduced copy: the CPU's.
assert!(per_pixel(&cr! { shadows: 20.0}, 1601, 32, false, None).is_none());
// At 2 pixels on the short side the pass's pyramid has one level: the CPU's too.
for (w, h) in [(2, 2), (40, 2), (2, 40)] {
assert!(per_pixel(&cr! { highlights: -20.0}, w, h, false, None).is_none(), "{w}×{h}");
}
}
#[test]
fn a_cached_source_is_reused_and_a_new_key_uploads() {
let Some(mut g) = gpu() else { return };
let p = cr! { exposure: 0.5};
let stages = per_pixel(&p, 64, 32, false, None).unwrap();
let a = image(64, 32, Depth::Eight);
let b: Vec<[f32; 4]> = a.iter().map(|q| [q[2], q[0], q[1], 1.0]).collect();
let first = g.dev.develop(&g.device, &g.queue, None, &a, Some(7), [64, 32], &stages).unwrap();
// Same key: the uploaded source stays (callers key by the proxy's identity).
assert_eq!(g.dev.develop(&g.device, &g.queue, None, &b, Some(7), [64, 32], &stages).unwrap(), first);
let mut cpu = b.clone();
develop(&mut cpu, 64, 32, &p, false);
let other = g.dev.develop(&g.device, &g.queue, None, &b, Some(8), [64, 32], &stages).unwrap();
assert!(other.iter().zip(&cpu).all(|(x, y)| (0..3).all(|c| (x[c] - y[c]).abs() <= TOL)));
}
#[test]
fn bad_sizes_and_faulted_devices_are_errors() {
let Some(mut g) = gpu() else { return };
let stages = per_pixel(&cr! { exposure: 0.5}, 4, 4, false, None).unwrap();
let px = vec![[0.5f32; 4]; 16];
for size in [[0, 4], [4, 0], [5, 4], [3, 3], [u32::MAX, 1]] {
assert!(g.dev.develop(&g.device, &g.queue, None, &px, None, size, &stages).is_err(), "{size:?}");
}
let health = DeviceHealth::new();
health.mark(Fault::Lost("test".into()));
assert!(g.dev.develop(&g.device, &g.queue, Some(&health), &px, None, [4, 4], &stages).is_err());
// And the pass still works afterwards.
assert!(g.dev.develop(&g.device, &g.queue, Some(&DeviceHealth::new()), &px, None, [4, 4], &stages).is_ok());
}
#[test]
fn shadows_and_highlights() {
let sets = [
cr! { shadows: 50.0},
cr! { shadows: -70.0},
cr! { highlights: -50.0},
cr! { highlights: 60.0},
cr! { shadows: 100.0, highlights: -100.0},
cr! { shadows: 35.0, highlights: -45.0, encoding_gamma: 1.8},
];
assert_moves(&sets);
// The long side preserves the spatial filter scale; 48 rows keep several pyramid levels.
check_at("shadows/highlights", &sets, (171, 48));
}
#[test]
fn shadows_and_highlights_on_tiny_odd_and_flat_frames() {
let Some(mut g) = gpu() else { return };
let p = cr! { shadows: 60.0, highlights: -40.0, whites: 20.0};
// A frame 2 pixels on a side has a one-level pyramid: `per_pixel` sends it to the CPU, and
// the pass still refuses stages built for it elsewhere.
for (w, h) in [(2, 2), (40, 2)] {
assert!(per_pixel(&p, w, h, false, None).is_none(), "{w}×{h}");
let stages = per_pixel(&p, 3, 3, false, None).unwrap();
assert!(g.dev.develop(&g.device, &g.queue, None, &image(w, h, Depth::Eight), None, [w as u32, h as u32], &stages).is_err());
}
// One depth per size, in turn: the size decides the pyramid and the edges, the depth only the
// input's quantization and whether the result clips, which `shadows_and_highlights` checks
// at every depth.
for (i, size) in [(3, 3), (5, 3), (37, 23), (300, 7)].into_iter().enumerate() {
let depth = DEPTHS[i % DEPTHS.len()];
let d = compare_at(&mut g, &p, depth, size);
eprintln!("shadows/highlights {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}");
}
// A flat frame has no range to filter. It isn't quantized, so one integer depth.
let flat = vec![[0.4, 0.35, 0.3, 1.0]; 64 * 48];
for depth in depths(0) {
compare_image(&mut g, &p, depth, &flat, (64, 48));
}
}
#[test]
fn shadows_and_highlights_with_per_pixel_stages() {
let mut hsl = [0.0; 8];
hsl[1] = 35.0;
hsl[5] = -50.0;
let all = cr! {
temperature: 25.0,
tint: 10.0,
exposure: 0.3,
contrast: 25.0,
shadows: 45.0,
highlights: -55.0,
whites: 20.0,
blacks: -15.0,
vibrance: 30.0,
saturation: 10.0,
curve_darks: 20.0,
point_curve: vec![[0.0, 8.0], [255.0, 250.0]],
hsl_hue: hsl,
hsl_sat: hsl,
hsl_lum: hsl,
grade_shadows: Wheel { hue: 210.0, sat: 25.0, lum: 0.0 },
vignette_amount: -30.0,
grain_amount: 20.0,
pixel_scale: 0.2};
check_at(
"shadows/highlights + per pixel",
&[
all,
// Whites and Blacks measured after the filter, both directions.
cr! { shadows: 60.0, whites: 70.0, blacks: -45.0},
cr! { highlights: -60.0, whites: -60.0, blacks: 50.0, exposure: -0.4},
cr! { shadows: 30.0, highlights: -30.0, whites: 40.0, blacks: -30.0, encoding_gamma: 1.8},
],
(171, 48),
);
// The dialog's proxy width (the pyramid levels and range cells at that size) runs in
// `clarity_texture_and_dehaze_with_shadows_highlights_and_per_pixel_stages`, whose first set
// has Shadows and Highlights too.
}
/// Asserts that each of `sets` moves some pixel of the test image by over 2 %, so a comparison
/// with the CPU can't pass trivially.
fn assert_moves(sets: &[Case]) {
for p in sets {
let src = image(171, 48, Depth::Sixteen);
let mut out = src.clone();
develop(&mut out, 171, 48, p, false);
let moved = out.iter().zip(&src).flat_map(|(a, b)| (0..3).map(move |c| (a[c] - b[c]).abs())).fold(0.0f32, f32::max);
assert!(moved > 0.02, "{p:?} moves pixels by at most {moved}");
}
}
#[test]
fn clarity_texture_and_dehaze() {
let sets = [
cr! { clarity: 50.0},
cr! { clarity: -80.0},
cr! { texture: 50.0},
cr! { texture: -70.0, pixel_scale: 0.143},
cr! { dehaze: 40.0},
cr! { dehaze: 100.0},
cr! { dehaze: -60.0},
// With Contrast, which then runs after them on the same luminance.
cr! { clarity: 40.0, texture: 30.0, contrast: -35.0},
cr! { dehaze: 30.0, clarity: 45.0, texture: -40.0, contrast: 20.0},
cr! { dehaze: -30.0, clarity: -25.0, texture: 60.0, encoding_gamma: 1.8},
];
assert_moves(&sets);
// Match the movement check while retaining several pyramid levels.
check_at("clarity/texture/dehaze", &sets, (171, 48));
}
#[test]
fn clarity_texture_and_dehaze_with_shadows_highlights_and_per_pixel_stages() {
let mut hsl = [0.0; 8];
hsl[1] = 35.0;
hsl[5] = -50.0;
let all = cr! {
temperature: 25.0,
tint: 10.0,
exposure: 0.3,
contrast: 25.0,
dehaze: 35.0,
shadows: 45.0,
highlights: -55.0,
clarity: 40.0,
texture: 30.0,
whites: 20.0,
blacks: -15.0,
vibrance: 30.0,
saturation: 10.0,
curve_darks: 20.0,
point_curve: vec![[0.0, 8.0], [255.0, 250.0]],
hsl_hue: hsl,
hsl_sat: hsl,
hsl_lum: hsl,
grade_shadows: Wheel { hue: 210.0, sat: 25.0, lum: 0.0 },
vignette_amount: -30.0,
grain_amount: 20.0,
pixel_scale: 0.2};
let sets = [
all.clone(),
cr! { dehaze: 50.0, shadows: 60.0, highlights: -40.0},
cr! { clarity: 60.0, texture: 50.0, shadows: 40.0},
// Whites and Blacks measured after them, without Shadows and Highlights, both directions.
cr! { dehaze: 40.0, whites: 60.0, blacks: -40.0},
cr! { clarity: 50.0, whites: -50.0, blacks: 45.0, exposure: -0.3},
cr! { texture: -60.0, whites: 30.0, blacks: -60.0},
];
check_at("clarity/texture/dehaze + shadows/highlights + per pixel", &sets, (171, 48));
let Some(mut g) = gpu() else { return };
// At the dialog's proxy width (Dehaze and Clarity on a copy subsampled twice), and wider (three
// times). One depth per size: the depth only changes how the input is quantized (8 and 16
// bits both develop with `float = false`), and every depth already ran above at 171×48. The
// long side sets the subsampling; the short one only needs to keep several pyramid levels, so
// the frames are strips.
for (size, depth) in [((858, 120), Depth::Eight), ((1600, 120), Depth::Float)] {
let d = compare_at(&mut g, &all, depth, size);
eprintln!("everything {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}");
}
}
#[test]
fn clarity_texture_and_dehaze_on_tiny_and_odd_frames() {
let Some(mut g) = gpu() else { return };
let p = cr! { dehaze: 45.0, clarity: 50.0, texture: 60.0, whites: 20.0, blacks: -20.0};
// Without Shadows and Highlights even 1 and 2 pixel frames develop on the GPU.
// One depth per size, in turn, as in `shadows_and_highlights_on_tiny_odd_and_flat_frames`;
// `clarity_texture_and_dehaze` checks the stages at every depth.
for (i, size) in [(1, 1), (2, 2), (40, 2), (3, 3), (5, 3), (37, 23), (300, 7)].into_iter().enumerate() {
let depth = DEPTHS[i % DEPTHS.len()];
let d = compare_at(&mut g, &p, depth, size);
eprintln!("clarity/texture/dehaze {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}");
}
// Texture's blur on a small proxy is too narrow to change anything; the stage still runs.
let narrow = cr! { texture: 80.0, contrast: 10.0, pixel_scale: 0.1};
assert!(per_pixel(&narrow, 64, 48, true, None).and_then(|s| s.texture).is_some_and(|t| t.radii.is_empty()));
for depth in depths(1) {
compare_at(&mut g, &narrow, depth, (64, 48));
}
// A flat frame: no haze to find, no detail to raise. Not quantized, so one integer depth.
let flat = vec![[0.4, 0.35, 0.3, 1.0]; 64 * 48];
for depth in depths(0) {
compare_image(&mut g, &p, depth, &flat, (64, 48));
}
}
/// #9273: the GPU opens the dark channel like the CPU, so a sky beside a dark tower clears as it
/// does there. The scene of algo's `dehaze_leaves_no_halo_beside_dark_objects`: a clear sky and a
/// dark tower hazed with `I = J·t + A·(1 − t)`.
#[test]
fn dehaze_opens_the_dark_channel_like_the_cpu() {
let Some(mut g) = gpu() else { return };
let (w, h) = (600usize, 400usize);
let tower = |x: usize, y: usize| (250..350).contains(&x) && y >= 120;
let (t, air) = (0.55f32, [0.9f32, 0.9, 0.9]);
let src: Vec<[f32; 4]> = (0..w * h)
.map(|i| {
let (x, y) = (i % w, i / w);
let j = if tower(x, y) { [0.06, 0.06, 0.07] } else { [0.35 + 0.1 * y as f32 / h as f32, 0.5, 0.8] };
let c: [f32; 3] = std::array::from_fn(|k| j[k] * t + air[k] * (1.0 - t));
[c[0], c[1], c[2], 1.0]
})
.collect();
// The scene isn't quantized, so the depth only picks `float` (whether the result clips); one
// per strength, both in turn.
for (dehaze, depth) in [(100.0, Depth::Float), (60.0, Depth::Eight), (-40.0, Depth::Float)] {
let d = compare_image(&mut g, &cr! { dehaze: dehaze }, depth, &src, (w, h));
eprintln!("dehaze {dehaze} on the tower {depth:?}: max |GPU - CPU| = {d:.2e}");
}
}
/// Each of Detail's controls alone and together: sharpening (Detail at 0 and 100, Masking off
/// and on), luminance and colour noise reduction (their Detail at 0 and 100), at full size and on
/// a proxy.
#[test]
fn detail_sharpening_and_noise_reduction() {
let sets = [
cr! { sharpen_amount: 60.0},
cr! { sharpen_amount: 100.0, sharpen_radius: 3.0, sharpen_detail: 100.0},
// Detail at 0 limits each change to 1.5 % of Amount's strength: 150 still moves over 2 %.
cr! { sharpen_amount: 150.0, sharpen_radius: 0.5, sharpen_detail: 0.0},
cr! { sharpen_amount: 80.0, sharpen_radius: 1.5, sharpen_masking: 60.0},
cr! { sharpen_amount: 120.0, sharpen_detail: 70.0, sharpen_masking: 100.0},
cr! { sharpen_amount: 100.0, sharpen_masking: 15.0},
cr! { noise_luminance: 50.0},
cr! { noise_luminance: 100.0, noise_luminance_detail: 0.0},
cr! { noise_luminance: 80.0, noise_luminance_detail: 100.0},
cr! { noise_color: 60.0},
cr! { noise_color: 100.0, noise_color_detail: 0.0},
cr! { noise_color: 30.0, noise_color_detail: 100.0},
cr! { noise_luminance: 40.0, noise_color: 50.0, sharpen_amount: 70.0},
cr! { noise_luminance: 40.0, noise_color: 50.0, sharpen_amount: 90.0, sharpen_masking: 40.0, sharpen_detail: 60.0},
// A proxy: the radii scale with the pixel scale (sharpening's and its mask's at their floor).
cr! { noise_luminance: 60.0, noise_color: 70.0, sharpen_amount: 100.0, sharpen_masking: 30.0, pixel_scale: 0.143},
cr! { sharpen_amount: 120.0, sharpen_radius: 3.0, encoding_gamma: 1.8, pixel_scale: 0.5},
];
assert_moves(&sets);
check("detail", &sets);
}
#[test]
fn detail_with_every_other_stage() {
let mut hsl = [0.0; 8];
hsl[1] = 35.0;
hsl[5] = -50.0;
let all = cr! {
temperature: 25.0,
tint: 10.0,
exposure: 0.3,
contrast: 25.0,
dehaze: 35.0,
shadows: 45.0,
highlights: -55.0,
clarity: 40.0,
texture: 30.0,
whites: 20.0,
blacks: -15.0,
vibrance: 30.0,
saturation: 10.0,
curve_darks: 20.0,
point_curve: vec![[0.0, 8.0], [255.0, 250.0]],
hsl_hue: hsl,
hsl_sat: hsl,
hsl_lum: hsl,
grade_shadows: Wheel { hue: 210.0, sat: 25.0, lum: 0.0 },
sharpen_amount: 80.0,
sharpen_masking: 25.0,
noise_luminance: 30.0,
noise_color: 40.0,
vignette_amount: -30.0,
grain_amount: 20.0,
pixel_scale: 0.2};
let sets = [
all.clone(),
// Whites and Blacks measured on the CPU (Detail, after them, is the only spatial stage),
cr! { whites: 60.0, blacks: -40.0, contrast: 20.0, sharpen_amount: 90.0, noise_luminance: 30.0},
cr! { whites: -50.0, blacks: 45.0, exposure: -0.3, noise_color: 60.0},
// and on the GPU after Clarity.
cr! { clarity: 50.0, whites: 30.0, blacks: -60.0, sharpen_amount: 70.0, sharpen_masking: 50.0},
cr! {
shadows: 50.0,
vignette_amount: 40.0,
vignette_style: StoredVignetteStyle::PaintOverlay,
noise_color: 50.0,
sharpen_amount: 60.0},
];
check("detail + every stage", &sets);
let Some(mut g) = gpu() else { return };
// At the dialog's proxy size, with and without the other stages.
let proxy = cr! { noise_luminance: 50.0, noise_color: 50.0, sharpen_amount: 100.0, sharpen_masking: 20.0, pixel_scale: 0.143};
for p in [Case { inputs: DevelopInputs { pixel_scale: 0.143, ..all.inputs }, ..all.clone() }, proxy] {
for depth in DEPTHS {
let d = compare_at(&mut g, &p, depth, (858, 572));
eprintln!("detail 858x572 {depth:?}: max |GPU - CPU| = {d:.2e}");
}
}
}
#[test]
fn detail_on_tiny_odd_and_flat_frames() {
let Some(mut g) = gpu() else { return };
let p = cr! { noise_luminance: 60.0, noise_color: 50.0, sharpen_amount: 100.0, sharpen_masking: 30.0, whites: 20.0};
for size in [(1, 1), (2, 2), (40, 2), (2, 40), (3, 3), (5, 3), (37, 23), (300, 7)] {
for depth in DEPTHS {
let d = compare_at(&mut g, &p, depth, size);
eprintln!("detail {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}");
}
}
// A flat frame: nothing to reduce or sharpen, no edges for the mask.
let flat = vec![[0.4, 0.35, 0.3, 1.0]; 64 * 48];
for depth in DEPTHS {
compare_image(&mut g, &p, depth, &flat, (64, 48));
}
}
/// Settings that change which of Detail's parts run, in turn on one pass: each develop picks its
/// own plan and textures and still matches the CPU.
#[test]
fn detail_parts_switch_on_and_off_between_develops() {
let Some(mut g) = gpu() else { return };
let sets = [
cr! { noise_color: 50.0},
cr! { sharpen_amount: 80.0, sharpen_masking: 40.0},
cr! { exposure: 0.3},
cr! { noise_luminance: 50.0, sharpen_amount: 80.0},
cr! { noise_color: 50.0},
];
for p in &sets {
for depth in DEPTHS {
compare_at(&mut g, p, depth, (171, 113));
}
}
}
#[test]
fn dehaze_remakes_its_copy_when_the_white_balance_changes() {
let Some(mut g) = gpu() else { return };
// The dialog's proxy width, so the copy is subsampled as there; the cache key doesn't hold the
// size, so the frame is a strip.
let (w, h) = (858, 120);
let src = image(w, h, Depth::Eight);
// Same source key throughout: the copy is cached by it and by the white balance.
for temperature in [25.0, -40.0, -40.0, 0.0] {
let p = cr! { dehaze: 50.0, temperature};
let mut cpu = src.clone();
develop(&mut cpu, w, h, &p, false);
let stages = per_pixel(&p, w, h, false, None).unwrap();
let out = g.dev.develop(&g.device, &g.queue, None, &src, Some(3), [w as u32, h as u32], &stages).unwrap();
let d = out.iter().zip(&cpu).flat_map(|(a, b)| (0..3).map(move |c| (a[c] - b[c]).abs())).fold(0.0f32, f32::max);
assert!(d <= TOL, "temperature {temperature}: off by {d}");
}
}
/// Each luminance noise reduction setting makes its own plan; a drag through a hundred of them
/// keeps at most 64 cached, and every develop still matches the CPU.
#[test]
fn a_slider_drag_keeps_the_plan_cache_bounded() {
let Some(mut g) = gpu() else { return };
for (i, amount) in (1..=100).enumerate() {
let p = cr! { noise_luminance: amount as f32, noise_luminance_detail: (i % 7) as f32 * 10.0};
if i % 33 == 0 {
compare_at(&mut g, &p, Depth::Eight, (64, 48));
} else {
let stages = per_pixel(&p, 64, 48, false, None).unwrap();
g.dev.develop(&g.device, &g.queue, None, &image(64, 48, Depth::Eight), None, [64, 48], &stages).unwrap();
}
assert!(g.dev.cached_plans() <= 64, "{} plans after {} settings", g.dev.cached_plans(), i + 1);
}
assert!(g.dev.cached_plans() > 0);
}