From 6f20a6b9f2d668b090135af573bf6558171bd261 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 08:55:17 -0500 Subject: [PATCH] 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) --- crates/algo/src/camera_raw.rs | 7 +- crates/gpu/examples/bench_camera_raw.rs | 39 ++- crates/gpu/src/camera_raw.rs | 94 ++++++- crates/gpu/src/camera_raw.wgsl | 78 +++++- crates/gpu/src/camera_raw_filters.wgsl | 27 +- crates/gpu/src/camera_raw_tone.rs | 255 ++++++++++++++++--- crates/gpu/tests/it/camera_raw.rs | 149 ++++++++++- crates/ui-egui/src/dialogs/camera_raw_gpu.rs | 130 +++++----- docs/hardware-parity.md | 3 +- 9 files changed, 658 insertions(+), 124 deletions(-) diff --git a/crates/algo/src/camera_raw.rs b/crates/algo/src/camera_raw.rs index eab20f9b7e..3db5787c31 100644 --- a/crates/algo/src/camera_raw.rs +++ b/crates/algo/src/camera_raw.rs @@ -167,11 +167,16 @@ pub fn per_pixel(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize, floa craft_develop::camera_raw::per_pixel(&to_shared(p), inputs, w, h, float, points) } -/// Whether `p` needs a spatial pass on the GPU (`Dehaze`, `Shadows`/`Highlights`, `Clarity`, `Texture`). +/// Whether `p` needs a spatial pass on the GPU (`Dehaze`, `Shadows`/`Highlights`, `Clarity`, `Texture`, `Detail`). pub fn spatial(p: &CameraRaw) -> bool { craft_develop::camera_raw::spatial(&to_shared(p)) } +/// Whether a stage before Whites and Blacks reads neighbouring pixels (`Dehaze`, `Shadows`/`Highlights`, `Texture`, `Clarity`). +pub fn spatial_tone(p: &CameraRaw) -> bool { + craft_develop::camera_raw::spatial_tone(&to_shared(p)) +} + /// Image black and white points for `Whites` and `Blacks`, measured on the CPU. pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: &DevelopInputs) -> Option<(f32, f32)> { craft_develop::camera_raw::white_black_points(px, w, h, &to_shared(p), inputs) diff --git a/crates/gpu/examples/bench_camera_raw.rs b/crates/gpu/examples/bench_camera_raw.rs index 3b3ff6764a..93713758ae 100644 --- a/crates/gpu/examples/bench_camera_raw.rs +++ b/crates/gpu/examples/bench_camera_raw.rs @@ -1,11 +1,11 @@ //! Camera Raw's preview develop on the 858×572 proxy of a 6000×4000 image: the CPU develop //! against the GPU passes (upload, render, readback), for per-pixel settings and for the spatial -//! stages (Dehaze, Shadows and Highlights, Clarity, Texture) with them. "Source uploaded every +//! stages (Dehaze, Shadows and Highlights, Clarity, Texture, Detail) with them. "Source uploaded every //! time" also makes Dehaze's copy on the CPU every time, as a white balance drag does. //! `cargo run --release -p photocraft-gpu --example bench_camera_raw [-- --quick]` use std::time::Instant; -use photocraft_algo::camera_raw::{CameraRaw, DevelopInputs, Wheel, develop, per_pixel, spatial, white_black_points}; +use photocraft_algo::camera_raw::{CameraRaw, DevelopInputs, Wheel, develop, per_pixel, spatial, spatial_tone, white_black_points}; use photocraft_gpu::CameraRawDevelop; fn median(mut v: Vec) -> f64 { @@ -140,6 +140,39 @@ fn main() -> Result<(), Box> { p.highlights = -50.0; }), ), + ("Sharpening 40", with(&none, &|p| p.sharpen_amount = 40.0)), + ( + "Sharpening 40, Masking 30", + with(&none, &|p| { + p.sharpen_amount = 40.0; + p.sharpen_masking = 30.0; + }), + ), + ("Noise Reduction 30", with(&none, &|p| p.noise_luminance = 30.0)), + ("Color Noise Reduction 25", with(&none, &|p| p.noise_color = 25.0)), + ( + "Sharpening 40, Masking 30, both noise reductions, every per-pixel stage", + with(&per_pixel_stages, &|p| { + p.sharpen_amount = 40.0; + p.sharpen_masking = 30.0; + p.noise_luminance = 30.0; + p.noise_color = 25.0; + }), + ), + ( + "Detail, Clarity, Texture, Dehaze, Shadows, Highlights, every per-pixel stage", + with(&per_pixel_stages, &|p| { + p.sharpen_amount = 40.0; + p.sharpen_masking = 30.0; + p.noise_luminance = 30.0; + p.noise_color = 25.0; + p.clarity = 50.0; + p.texture = 50.0; + p.dehaze = 40.0; + p.shadows = 50.0; + p.highlights = -50.0; + }), + ), ]; for (name, (p, inputs)) in &sets { let toned = spatial(p); @@ -156,7 +189,7 @@ fn main() -> Result<(), Box> { println!(" CPU develop {cpu:7.2} ms"); println!(" GPU, source uploaded every time {upload:7.2} ms"); println!(" GPU, source cached (slider drag) {cached:7.2} ms"); - if !toned && (p.whites != 0.0 || p.blacks != 0.0) { + if !spatial_tone(p) && (p.whites != 0.0 || p.blacks != 0.0) { let points_ms = time(runs, || { std::hint::black_box(white_black_points(&src, w, h, p, inputs)); }); diff --git a/crates/gpu/src/camera_raw.rs b/crates/gpu/src/camera_raw.rs index f7e1d2b190..2feda849a4 100644 --- a/crates/gpu/src/camera_raw.rs +++ b/crates/gpu/src/camera_raw.rs @@ -9,8 +9,9 @@ //! passes of `camera_raw_tone.rs`, which then also measure the image's points for Whites and //! Blacks; this pass applies their change. Dehaze runs before them (its filters on the copy of //! [`Dehaze::cells`], then `fs_dehaze`, which the later passes read instead of the source), -//! Clarity and Texture after them (`fs_luma`, then their filters, applied in `tonal`). Settings with Detail have no -//! [`PerPixel`] and stay on the CPU. +//! Clarity and Texture after them (`fs_luma`, then their filters, applied in `tonal`). With +//! Detail, the pass stops after Color Grading (`fs_colour`), Detail's filters run on that, and +//! the last pass combines them before the vignette and grain. //! //! The pipelines are built on demand ([`CameraRawDevelop::new`]), not with the compositor //! (#6419). They render into `Rgba32Float`, `R32Float` and `Rgba32Uint`; @@ -27,8 +28,8 @@ use crate::camera_raw_tone::{Segment, ToneFrame, TonePipelines, WB_ROW}; pub const CAMERA_RAW_SHADER: &str = include_str!("camera_raw.wgsl"); const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float; -/// `Params` in the shader: 23 rows of 16 bytes. -const PARAMS_SIZE: u64 = 23 * 16; +/// `Params` in the shader: 25 rows of 16 bytes. +const PARAMS_SIZE: u64 = 25 * 16; /// Rows of the table texture: parametric, master, red, green, blue curves; Whites, Blacks. const LUT_ROWS: u32 = 7; const LUT_WIDTH: u32 = CURVE_LUT as u32; @@ -67,6 +68,8 @@ pub struct CameraRawDevelop { /// `fs_dehaze` and `fs_luma`: Dehaze's result, Clarity and Texture's input. dehaze: wgpu::RenderPipeline, luma: wgpu::RenderPipeline, + /// `fs_colour`: stages 1 to 7, Detail's input. + colour: wgpu::RenderPipeline, tone: TonePipelines, tone_frame: Option, layout: wgpu::BindGroupLayout, @@ -80,6 +83,12 @@ pub struct CameraRawDevelop { } impl CameraRawDevelop { + /// Spatial plans cached, for tests: at most 64 however many settings a session tries. + #[doc(hidden)] + pub fn cached_plans(&self) -> usize { + self.tone_frame.as_ref().map_or(0, ToneFrame::plans) + } + /// Whether `adapter` can render the passes' `Rgba32Float`, `R32Float` and `Rgba32Uint` targets. pub fn supported(adapter: &wgpu::Adapter) -> bool { [FORMAT, wgpu::TextureFormat::R32Float, wgpu::TextureFormat::Rgba32Uint] @@ -123,6 +132,11 @@ impl CameraRawDevelop { crate::tex_entry(8), crate::tex_entry(9), crate::tex_entry(10), + crate::tex_entry(11), + crate::tex_entry(12), + crate::tex_entry(13), + crate::tex_entry(14), + crate::tex_entry(15), ], }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { @@ -153,6 +167,7 @@ impl CameraRawDevelop { let points = pipeline_for("fs_points", FORMAT); let dehaze = pipeline_for("fs_dehaze", FORMAT); let luma = pipeline_for("fs_luma", wgpu::TextureFormat::R32Float); + let colour = pipeline_for("fs_colour", FORMAT); let params = device.create_buffer(&wgpu::BufferDescriptor { label: Some("pc_camera_raw_params"), size: PARAMS_SIZE, @@ -177,6 +192,7 @@ impl CameraRawDevelop { points, dehaze, luma, + colour, tone: TonePipelines::build(device), tone_frame: None, layout, @@ -223,7 +239,8 @@ impl CameraRawDevelop { } let clarity = stages.clarity.is_some(); let texture = stages.texture.as_ref().is_some_and(|t| t.radii.iter().any(|r| *r > 0)); - let filtered = stages.local_tone.is_some() || stages.dehaze.is_some() || clarity || texture || stages.measure_whites_blacks.is_some(); + let filtered = + stages.local_tone.is_some() || stages.dehaze.is_some() || clarity || texture || stages.measure_whites_blacks.is_some() || stages.detail.is_some(); let frame = if filtered { let frame = match self.tone_frame.take() { Some(f) if f.size() == size => f, @@ -257,7 +274,21 @@ impl CameraRawDevelop { }; let target = self.target.insert(target); let (dummy, dummy_uint) = (self.tone.dummy(), self.tone.dummy_uint()); - let mut all = Bound { log_in: dummy, log_out: dummy, stats: dummy_uint, base: dummy, haze: dummy, air: dummy, clarity: dummy, texture: dummy }; + let mut all = Bound { + log_in: dummy, + log_out: dummy, + stats: dummy_uint, + base: dummy, + haze: dummy, + air: dummy, + clarity: dummy, + texture: dummy, + colored: dummy, + noise: dummy, + chroma: dummy, + sharpen: dummy, + mask: dummy, + }; if let Some(f) = frame { all.stats = f.stats(); if let Some((log_in, log_out)) = f.log() { @@ -266,10 +297,17 @@ impl CameraRawDevelop { if let Some([t, air, dehazed]) = f.haze() { (all.haze, all.air, all.base) = (t, air, dehazed); } - if let Some((_, c, t)) = f.detail() { + if let Some((_, c, t)) = f.local() { all.clarity = c.unwrap_or(dummy); all.texture = t.unwrap_or(dummy); } + if let Some(d) = f.detail() { + all.colored = d.colored; + all.noise = d.noise.unwrap_or(dummy); + all.chroma = d.chroma.unwrap_or(dummy); + all.sharpen = d.sharpen.unwrap_or(dummy); + all.mask = d.mask.unwrap_or(dummy); + } } let group = |b: &Bound| { let entries = [ @@ -284,6 +322,11 @@ impl CameraRawDevelop { wgpu::BindGroupEntry { binding: 8, resource: wgpu::BindingResource::TextureView(b.air) }, wgpu::BindGroupEntry { binding: 9, resource: wgpu::BindingResource::TextureView(b.clarity) }, wgpu::BindGroupEntry { binding: 10, resource: wgpu::BindingResource::TextureView(b.texture) }, + wgpu::BindGroupEntry { binding: 11, resource: wgpu::BindingResource::TextureView(b.colored) }, + wgpu::BindGroupEntry { binding: 12, resource: wgpu::BindingResource::TextureView(b.noise) }, + wgpu::BindGroupEntry { binding: 13, resource: wgpu::BindingResource::TextureView(b.chroma) }, + wgpu::BindGroupEntry { binding: 14, resource: wgpu::BindingResource::TextureView(b.sharpen) }, + wgpu::BindGroupEntry { binding: 15, resource: wgpu::BindingResource::TextureView(b.mask) }, ]; device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("pc_camera_raw"), layout: &self.layout, entries: &entries }) }; @@ -303,14 +346,19 @@ impl CameraRawDevelop { f.record(encoder, &self.tone, Segment::Tone); } if clarity || texture { - let (lc, _, _) = f.detail().ok_or_else(missing)?; + let (lc, _, _) = f.local().ok_or_else(missing)?; pass(encoder, &self.luma, &main, lc); - f.record(encoder, &self.tone, Segment::Detail); + f.record(encoder, &self.tone, Segment::Local); } if stages.measure_whites_blacks.is_some() { pass(encoder, &self.points, &main, f.points().0); f.record(encoder, &self.tone, Segment::WhitesBlacks); } + if stages.detail.is_some() { + let colored = f.detail().ok_or_else(missing)?.colored; + pass(encoder, &self.colour, &group(&Bound { colored: dummy, ..all }), colored); + f.record(encoder, &self.tone, Segment::Detail); + } } pass(encoder, &self.pipeline, &main, &target.view); Ok(&target.texture) @@ -424,6 +472,13 @@ struct Bound<'a> { /// Clarity's coefficients and Texture's blur. clarity: &'a wgpu::TextureView, texture: &'a wgpu::TextureView, + /// Detail: stages 1 to 7, the reduced luminance, the chroma's blur, sharpening's blur and its + /// mask's. + colored: &'a wgpu::TextureView, + noise: &'a wgpu::TextureView, + chroma: &'a wgpu::TextureView, + sharpen: &'a wgpu::TextureView, + mask: &'a wgpu::TextureView, } /// One full-frame pass of `pipeline` into `target`. @@ -460,6 +515,8 @@ fn check_size(device: &wgpu::Device, source: &[[f32; 4]], [w, h]: [u32; 2]) -> R /// Flags of `Params.flags`, in the shader's bit order; `texture` is whether Texture's blur ran. fn flags(s: &PerPixel, texture: bool) -> u32 { let wb = s.whites_blacks.as_ref(); + let detail = s.detail.as_ref(); + let sharpen = detail.and_then(|d| d.sharpen.as_ref()); // Measured after Shadows and Highlights, the amounts keep the sliders' signs. let measured = s.measure_whites_blacks; let on = [ @@ -484,6 +541,11 @@ fn flags(s: &PerPixel, texture: bool) -> u32 { s.dehaze.is_some(), s.clarity.is_some(), texture, + detail.is_some(), + detail.is_some_and(|d| d.luminance.is_some()), + detail.is_some_and(|d| d.color.is_some()), + sharpen.is_some(), + sharpen.is_some_and(|s| s.mask.is_some()), ]; on.iter().enumerate().fold(0, |f, (bit, on)| if *on { f | 1 << bit } else { f }) } @@ -541,6 +603,20 @@ fn params(size: [u32; 2], s: &PerPixel, tone: [u32; 4], texture: bool) -> Vec, @@ -35,6 +37,10 @@ struct Params { spatial: vec4, // Dehaze's and Clarity's subsampling, the transmission's floor. spatial2: vec4, + // Detail: colour noise reduction's kept share; sharpening's amount, limit and scale. + detail: vec4, + // Sharpening's mask: its smoothstep edges. + detail2: vec4, } @group(0) @binding(0) var P: Params; @@ -53,6 +59,13 @@ struct Params { // Clarity's coefficients (a, b) on its copy; Texture's blur (red). @group(0) @binding(9) var clarity: texture_2d; @group(0) @binding(10) var blur: texture_2d; +// Detail: stages 1 to 7 (`fs_colour`), the reduced luminance (red), the chroma's blur (red B − Y, +// green R − Y), sharpening's blur and its mask's (red). +@group(0) @binding(11) var colored: texture_2d; +@group(0) @binding(12) var noise: texture_2d; +@group(0) @binding(13) var chroma: texture_2d; +@group(0) @binding(14) var sharp: texture_2d; +@group(0) @binding(15) var sharp_mask: texture_2d; const GAINS: u32 = 0u; // The luminance stage: Contrast, Clarity or Texture. @@ -73,6 +86,11 @@ const LOCAL_TONE: u32 = 16u; const DEHAZE: u32 = 17u; const CLARITY: u32 = 18u; const TEXTURE: u32 = 19u; +const DETAIL: u32 = 20u; +const LUMINANCE_NOISE: u32 = 21u; +const COLOR_NOISE: u32 = 22u; +const SHARPEN: u32 = 23u; +const MASKING: u32 = 24u; const CURVE_LUT: i32 = 1024; const WB_STEPS: i32 = 33; @@ -457,10 +475,8 @@ fn fs_points(@builtin(position) pos: vec4) -> @location(0) vec4 { return vec4(luma(m), max(max(m.x, m.y), m.z), 0.0, 1.0); } -@fragment -fn fs(@builtin(position) pos: vec4) -> @location(0) vec4 { - let p = vec2(floor(pos.xy)); - let q = textureLoad(src, p, 0); +// Stages 1 to 7 on the pixel at `p`: what Detail filters. +fn colour(p: vec2) -> vec3 { var c = tonal(p); // 3b. Whites and Blacks. if on(WHITES) || on(BLACKS) { @@ -523,6 +539,58 @@ fn fs(@builtin(position) pos: vec4) -> @location(0) vec4 { } } } + return c; +} + +// 8. Detail at `p` (develop's `detail`): `fs_colour`'s pixel as luminance Y and chroma B − Y, +// R − Y, the noise reductions' results put in, Y sharpened, and back to RGB. +fn detail(p: vec2) -> vec3 { + let q = textureLoad(colored, p, 0).rgb; + let y0 = luma(q); + var cb = q.z - y0; + var cr = q.x - y0; + var y = y0; + if on(LUMINANCE_NOISE) { + y = textureLoad(noise, p, 0).r; + } + if on(COLOR_NOISE) { + let b = textureLoad(chroma, p, 0); + cb = b.x + (cb - b.x) * P.detail.x; + cr = b.y + (cr - b.y) * P.detail.x; + } + if on(SHARPEN) { + let hp = clamp(y - textureLoad(sharp, p, 0).r, -P.detail.z, P.detail.z) * P.detail.w; + var m = 1.0; + if on(MASKING) { + // The smoothed luminance's central differences, edges clamped. + let n = vec2(P.size) - vec2(1); + let gx = textureLoad(sharp_mask, vec2(min(p.x + 1, n.x), p.y), 0).r - textureLoad(sharp_mask, vec2(max(p.x - 1, 0), p.y), 0).r; + let gy = textureLoad(sharp_mask, vec2(p.x, min(p.y + 1, n.y)), 0).r - textureLoad(sharp_mask, vec2(p.x, max(p.y - 1, 0)), 0).r; + m = smoothstep_(P.detail2.x, P.detail2.y, length(vec2(gx, gy))); + } + y += P.detail.y * hp * m; + } + let r = cr + y; + let b = cb + y; + return vec3(r, (y - 0.2126 * r - 0.0722 * b) / 0.7152, b); +} + +// Stages 1 to 7, which Detail's filters read. +@fragment +fn fs_colour(@builtin(position) pos: vec4) -> @location(0) vec4 { + return vec4(colour(vec2(floor(pos.xy))), 1.0); +} + +@fragment +fn fs(@builtin(position) pos: vec4) -> @location(0) vec4 { + let p = vec2(floor(pos.xy)); + let q = textureLoad(src, p, 0); + var c: vec3; + if on(DETAIL) { + c = detail(p); + } else { + c = colour(p); + } // 9. Vignette. if on(VIGNETTE) { let amt = P.vignette[0].x; diff --git a/crates/gpu/src/camera_raw_filters.wgsl b/crates/gpu/src/camera_raw_filters.wgsl index 3294ce1a24..aef6e599a6 100644 --- a/crates/gpu/src/camera_raw_filters.wgsl +++ b/crates/gpu/src/camera_raw_filters.wgsl @@ -1,6 +1,6 @@ -// Dehaze, Clarity and Texture for Camera Raw's GPU preview: develop's `box_mean`, `guided`, -// `guided_fast` and `dehaze` (constants from `photocraft_algo::camera_raw::spatial`) as fragment -// passes. Appended to `camera_raw_tone.wgsl`, whose bindings and helpers it uses; +// Dehaze, Clarity, Texture and Detail for Camera Raw's GPU preview: develop's `box_mean`, +// `guided`, `guided_fast`, `dehaze` and `detail` (constants from +// `photocraft_algo::camera_raw::spatial`) as fragment passes. Appended to `camera_raw_tone.wgsl`, whose bindings and helpers it uses; // `camera_raw_tone.rs` orders the passes and `camera_raw.wgsl` applies their results. fn luma(c: vec3) -> f32 { @@ -10,7 +10,8 @@ fn luma(c: vec3) -> f32 { // `box_mean` along one axis (misc.x: 0 rows, 1 columns) at radius misc.y, edges clamped. Mode // misc.z: 0 the means; 1 then the guided filter's coefficients (a, b) from the means of // (I, p, I·p, I·I), regularised by misc.w's bits; 2 then the guided filter's output a·I + b, I -// the red channel of `plane_b`. +// the red channel of `plane_b`; 3 that output s moved back toward I by misc.w's bits k, +// s + (I − s)·k (Detail's luminance noise reduction). @fragment fn fs_box(@builtin(position) pos: vec4) -> @location(0) vec4 { let p = pixel(pos); @@ -34,9 +35,27 @@ fn fs_box(@builtin(position) pos: vec4) -> @location(0) vec4 { if S.misc.z == 2u { return vec4(m.x * textureLoad(plane_b, p, 0).r + m.y, 0.0, 0.0, 1.0); } + if S.misc.z == 3u { + let i = textureLoad(plane_b, p, 0).r; + let s = m.x * i + m.y; + return vec4(s + (i - s) * bitcast(S.misc.w), 0.0, 0.0, 1.0); + } return m; } +// Detail's planes from stages 1 to 7 (`plane_a`, which `camera_raw.wgsl`'s `fs_colour` renders). +// Mode misc.x 0: the luminance Y as the guided filter's (I, p, I·p, I·I) with I = p = Y; 1: the +// chroma (B − Y, R − Y). +@fragment +fn fs_detail_in(@builtin(position) pos: vec4) -> @location(0) vec4 { + let c = textureLoad(plane_a, pixel(pos), 0).rgb; + let y = luma(c); + if S.misc.x == 1u { + return vec4(c.b - y, c.r - y, 0.0, 1.0); + } + return vec4(y, y, y * y, y * y); +} + // `guided_fast`'s subsampled copy of `plane_a`'s red channel (`edge × edge` block means), as the // guided filter's (I, p, I·p, I·I) with I = p. @fragment diff --git a/crates/gpu/src/camera_raw_tone.rs b/crates/gpu/src/camera_raw_tone.rs index c3bc938432..912399666b 100644 --- a/crates/gpu/src/camera_raw_tone.rs +++ b/crates/gpu/src/camera_raw_tone.rs @@ -1,6 +1,6 @@ //! The spatial stages of Camera Raw's GPU preview (#6916) as fragment passes, with no compute //! shaders, so the same passes can run on WebGL2: Dehaze, Shadows and Highlights, Clarity and -//! Texture, and the measurement of Whites and Blacks' points after them. +//! Texture, the measurement of Whites and Blacks' points after them, and Detail. //! //! Shadows and Highlights are the local Laplacian filter of //! `photocraft_algo::camera_raw::local_tone` (`camera_raw_tone.wgsl`). Each @@ -9,9 +9,10 @@ //! of a level in one atlas), and the output from coarse to fine, each coefficient interpolated //! between the two references around the input there. //! -//! Dehaze, Clarity and Texture (`camera_raw_filters.wgsl`, constants from +//! Dehaze, Clarity, Texture and Detail (`camera_raw_filters.wgsl`, constants from //! `photocraft_algo::camera_raw::spatial`) are separable box and minimum filters and guided -//! filters on small copies; `camera_raw.wgsl` applies their results per pixel. +//! filters, Dehaze's and Clarity's on small copies; `camera_raw.wgsl` applies their results per +//! pixel. //! //! The quantiles the filters and Whites and Blacks read (including Dehaze's brightest cells) are //! exact order statistics, found on the GPU by narrowing an interval of keys in [`ROUNDS`] rounds @@ -49,6 +50,10 @@ const ROUNDS: usize = rounds(); /// at most [`SUM_MAX`] tiles remain, which a round's update sums. const COUNT_TILE: u32 = 16; const SUM_MAX: u32 = 256; +/// Plans kept at most. Each distinct setting of a key's values (luminance noise reduction's +/// regularisation and kept share, for one) makes a plan with its own buffers, so a slider drag +/// would otherwise keep adding them; past this many the cache starts again. +pub(crate) const MAX_PLANS: usize = 64; /// [`ROUNDS`]: the widest part `fs_update` can leave of an interval `span` keys wide (less one), /// until it is 0. @@ -142,10 +147,12 @@ enum Pipe { MinPack, HazeRank, Air, + /// `fs_detail_in`: Detail's luminance or chroma from the developed colour. + DetailIn, } impl Pipe { - const ALL: [Pipe; 18] = [ + const ALL: [Pipe; 19] = [ Pipe::Down, Pipe::DownRemap, Pipe::DownAtlas, @@ -164,6 +171,7 @@ impl Pipe { Pipe::MinPack, Pipe::HazeRank, Pipe::Air, + Pipe::DetailIn, ]; fn entry(self) -> &'static str { @@ -184,12 +192,13 @@ impl Pipe { Pipe::Min | Pipe::MinPack => "fs_min", Pipe::HazeRank => "fs_haze_rank", Pipe::Air => "fs_air", + Pipe::DetailIn => "fs_detail_in", } } fn targets(self) -> &'static [wgpu::TextureFormat] { match self { - Pipe::DownRemap | Pipe::DownAtlas | Pipe::Box | Pipe::Block | Pipe::MinPack | Pipe::Air => &[RGBA], + Pipe::DownRemap | Pipe::DownAtlas | Pipe::Box | Pipe::Block | Pipe::MinPack | Pipe::Air | Pipe::DetailIn => &[RGBA], Pipe::Init | Pipe::Update => &[UINT], Pipe::Count | Pipe::Reduce => &[UINT, UINT], _ => &[PLANE], @@ -465,6 +474,15 @@ impl Chain { } } +/// How [`Builder::guided`] ends: the box means of the coefficients (a, b) in `t[0]`; the output +/// a·I + b in `t[2]`; or that output `s` moved back toward I, to `s + (I − s)·keep`, in `t[2]`. +#[derive(Clone, Copy)] +enum Guided { + Coefficients, + Output, + Kept(f32), +} + /// Collects a plan's passes. #[derive(Default)] struct Builder { @@ -485,16 +503,26 @@ impl Builder { } /// Develop's `guided` (radius `r`, regularised by `eps`) on the (I, p, I·p, I·I) in `t[0]` - /// (`size` texels): the box means of its coefficients (a, b) in `t[0]`, or with `output` - /// a·I + b in `t[2]`. - fn guided(&mut self, size: [u32; 2], r: u32, eps: f32, t: &[Tex; 3], output: bool) { - self.filter(Pipe::Box, size, size, [0, r, 0, 0], &t[0], None, &t[1]); - self.filter(Pipe::Box, size, size, [1, r, 1, eps.to_bits()], &t[1], None, &t[2]); - self.filter(Pipe::Box, size, size, [0, r, 0, 0], &t[2], None, &t[1]); - if output { - self.filter(Pipe::Box, size, size, [1, r, 2, 0], &t[1], Some(&t[0]), &t[2]); - } else { - self.filter(Pipe::Box, size, size, [1, r, 0, 0], &t[1], None, &t[0]); + /// (`size` texels), ending as `out` says. + fn guided(&mut self, size: [u32; 2], r: u32, eps: f32, t: [&Tex; 3], out: Guided) { + self.filter(Pipe::Box, size, size, [0, r, 0, 0], t[0], None, t[1]); + self.filter(Pipe::Box, size, size, [1, r, 1, eps.to_bits()], t[1], None, t[2]); + self.filter(Pipe::Box, size, size, [0, r, 0, 0], t[2], None, t[1]); + match out { + Guided::Coefficients => self.filter(Pipe::Box, size, size, [1, r, 0, 0], t[1], None, t[0]), + Guided::Output => self.filter(Pipe::Box, size, size, [1, r, 2, 0], t[1], Some(t[0]), t[2]), + Guided::Kept(keep) => self.filter(Pipe::Box, size, size, [1, r, 3, keep.to_bits()], t[1], Some(t[0]), t[2]), + } + } + + /// Develop's `box_means` of `from` (`size` texels) at `radii`, through `pair` (in `pipe`'s + /// target format); the result ends in `pair[1]`, also when `radii` is empty. + fn blur(&mut self, pipe: Pipe, size: [u32; 2], radii: &[u32], from: &Tex, pair: [&Tex; 2]) { + let mut from = from; + for &r in if radii.is_empty() { &[0] } else { radii } { + self.filter(pipe, size, size, [0, r, 0, 0], from, None, pair[0]); + self.filter(pipe, size, size, [1, r, 0, 0], pair[0], None, pair[1]); + from = pair[1]; } } @@ -621,6 +649,27 @@ struct PlanKey { texture: Vec, /// Whether Whites and Blacks measure the points. whites_blacks: bool, + /// Detail. + detail: Option, +} + +/// What a plan runs of Detail: luminance noise reduction's radius, regularisation and kept share +/// (their bits), and the box radii of colour noise reduction, sharpening and its mask (those of 0 +/// left out). +#[derive(Clone, PartialEq, Eq, Hash)] +struct DetailKey { + luminance: Option<[u32; 3]>, + color: Option>, + sharpen: Option>, + mask: Option>, +} + +impl DetailKey { + /// Whether the plan reads `fs_colour`'s luminance: luminance noise reduction filters it and + /// sharpening blurs it (or what the reduction made of it). Colour noise reduction alone doesn't. + fn reads_luma(&self) -> bool { + self.luminance.is_some() || self.sharpen.is_some() + } } impl PlanKey { @@ -632,6 +681,15 @@ impl PlanKey { clarity: s.clarity.as_ref().map(|c| [n(c.subsample), n(c.sub_radius)]), texture: s.texture.as_ref().map_or(Vec::new(), |t| t.radii.iter().filter(|r| **r > 0).map(|r| n(*r)).collect()), whites_blacks: s.measure_whites_blacks.is_some(), + detail: s.detail.as_ref().map(|d| { + let radii = |r: &[usize]| r.iter().filter(|r| **r > 0).map(|r| n(*r)).collect::>(); + DetailKey { + luminance: d.luminance.as_ref().map(|l| [n(l.radius), l.eps.to_bits(), l.keep.to_bits()]), + color: d.color.as_ref().map(|c| radii(&c.radii)), + sharpen: d.sharpen.as_ref().map(|s| radii(&s.radii)), + mask: d.sharpen.as_ref().and_then(|s| s.mask.as_ref()).map(|(r, _)| radii(r)), + } + }), } } } @@ -644,16 +702,18 @@ pub(crate) enum Segment { /// After `fs_log`: Shadows and Highlights. Tone, /// After `fs_luma`: Clarity's coefficients and Texture's blur. - Detail, + Local, /// After `fs_points`: Whites and Blacks' points and curves. WhitesBlacks, + /// After `fs_colour`: Detail's filters. + Detail, } /// The recorded passes for one [`PlanKey`], by [`Segment`]. struct Plan { /// Holds the passes' uniform slots. _steps: wgpu::Buffer, - segments: [Vec; 4], + segments: [Vec; 5], } /// Pyramid level sizes down to about 2 pixels on the short side (`local_tone::depth`). @@ -788,7 +848,7 @@ impl Haze { } /// Clarity and Texture's textures. -struct Detail { +struct Local { /// The luminance clipped to 1, which `camera_raw.wgsl`'s `fs_luma` renders. lc: Tex, /// Texture's blur, back and forth; it ends in the second. @@ -797,6 +857,30 @@ struct Detail { sub: Option<([u32; 2], [Tex; 3])>, } +/// Detail's textures, at full size; each part's from when it first runs. +struct Detail { + /// Stages 1 to 7, which `camera_raw.wgsl`'s `fs_colour` renders. + colored: Tex, + /// The luminance as a guided filter's (I, p, I·p, I·I), for noise reduction or sharpening. + luma: Option, + /// Luminance noise reduction's guided filter; the reduced luminance ends in the second. + noise: Option<[Tex; 2]>, + /// The chroma, then its blur back and forth; the blur ends in the third. + chroma: Option<[Tex; 3]>, + /// Sharpening's blur and its mask's, back and forth; each ends in the second. + sharpen: Option<[Tex; 2]>, + mask: Option<[Tex; 2]>, +} + +/// The textures `camera_raw.wgsl` reads for Detail (`None` where a part has never run). +pub(crate) struct DetailViews<'a> { + pub(crate) colored: &'a wgpu::TextureView, + pub(crate) noise: Option<&'a wgpu::TextureView>, + pub(crate) chroma: Option<&'a wgpu::TextureView>, + pub(crate) sharpen: Option<&'a wgpu::TextureView>, + pub(crate) mask: Option<&'a wgpu::TextureView>, +} + /// The cells of a `size` frame at most `side` across: their size and edge in pixels. fn cells_of(size: [u32; 2], side: usize) -> ([u32; 2], u32) { let f = size[0].max(size[1]).div_ceil(u32::try_from(side).unwrap_or(u32::MAX)).max(1); @@ -809,6 +893,7 @@ pub(crate) struct ToneFrame { size: [u32; 2], pyramid: Option, haze: Option, + local: Option, detail: Option, /// Whites and Blacks' cells, which `fs_points` renders. points: Tex, @@ -830,6 +915,7 @@ impl ToneFrame { size, pyramid: None, haze: None, + local: None, detail: None, points: Tex::target(device, "pc_camera_raw_wb_cells", points_size, RGBA), points_size, @@ -877,23 +963,58 @@ impl ToneFrame { } if stages.clarity.is_some() || stages.texture.is_some() { let full = self.size; - let detail = self.detail.get_or_insert_with(|| Detail { lc: Tex::target(device, "pc_camera_raw_luma", full, PLANE), blur: None, sub: None }); - if stages.texture.is_some() && detail.blur.is_none() { - detail.blur = Some([0, 1].map(|_| Tex::target(device, "pc_camera_raw_texture", full, PLANE))); + let local = self.local.get_or_insert_with(|| Local { lc: Tex::target(device, "pc_camera_raw_luma", full, PLANE), blur: None, sub: None }); + if stages.texture.is_some() && local.blur.is_none() { + local.blur = Some([0, 1].map(|_| Tex::target(device, "pc_camera_raw_texture", full, PLANE))); } if let Some(c) = &stages.clarity { let size = dim(c.sub_size); if size[0] == 0 || size[1] == 0 || size[0] > max || size[1] > max { return Err(Unsupported(format!("Clarity's {}×{} copy doesn't fit the GPU's {max} px textures", size[0], size[1]))); } - if detail.sub.as_ref().is_none_or(|(s, _)| *s != size) { - detail.sub = Some((size, [0, 1, 2].map(|_| Tex::target(device, "pc_camera_raw_clarity", size, RGBA)))); + if local.sub.as_ref().is_none_or(|(s, _)| *s != size) { + local.sub = Some((size, [0, 1, 2].map(|_| Tex::target(device, "pc_camera_raw_clarity", size, RGBA)))); self.plans.clear(); } } } + if let Some(d) = &stages.detail { + // A plan made before a part's textures existed doesn't read them, so it stays valid. + let full = self.size; + let rgba = |label: &str| Tex::target(device, label, full, RGBA); + let plane = |label: &str| Tex::target(device, label, full, PLANE); + let t = self.detail.get_or_insert_with(|| Detail { + colored: rgba("pc_camera_raw_colored"), + luma: None, + noise: None, + chroma: None, + sharpen: None, + mask: None, + }); + if (d.luminance.is_some() || d.sharpen.is_some()) && t.luma.is_none() { + t.luma = Some(rgba("pc_camera_raw_detail_luma")); + } + if d.luminance.is_some() && t.noise.is_none() { + t.noise = Some([0, 1].map(|_| rgba("pc_camera_raw_noise"))); + } + if d.color.is_some() && t.chroma.is_none() { + t.chroma = Some([0, 1, 2].map(|_| rgba("pc_camera_raw_chroma"))); + } + if let Some(s) = &d.sharpen { + if t.sharpen.is_none() { + t.sharpen = Some([0, 1].map(|_| plane("pc_camera_raw_sharpen"))); + } + if s.mask.is_some() && t.mask.is_none() { + t.mask = Some([0, 1].map(|_| plane("pc_camera_raw_sharpen_mask"))); + } + } + } let key = PlanKey::new(stages); if !self.plans.contains_key(&key) { + // `current` is set below, so the frame records the plan made here. + if self.plans.len() >= MAX_PLANS { + self.plans.clear(); + } let plan = self.plan(device, queue, pipes, &key, luts); self.plans.insert(key.clone(), plan); } @@ -901,6 +1022,11 @@ impl ToneFrame { Ok(()) } + /// Plans cached ([`MAX_PLANS`] at most). + pub(crate) fn plans(&self) -> usize { + self.plans.len() + } + /// Records segment `seg` of the plan [`prepare`](Self::prepare) picked; results go into `stats`. pub(crate) fn record(&self, encoder: &mut wgpu::CommandEncoder, pipes: &TonePipelines, seg: Segment) { let ops = self.current.as_ref().and_then(|k| self.plans.get(k)).and_then(|p| p.segments.get(seg as usize)); @@ -964,11 +1090,23 @@ impl ToneFrame { } /// The clipped luminance (which `fs_luma` renders), Clarity's coefficients and Texture's blur. - pub(crate) fn detail(&self) -> Option<(&wgpu::TextureView, Option<&wgpu::TextureView>, Option<&wgpu::TextureView>)> { - let d = self.detail.as_ref()?; + pub(crate) fn local(&self) -> Option<(&wgpu::TextureView, Option<&wgpu::TextureView>, Option<&wgpu::TextureView>)> { + let d = self.local.as_ref()?; Some((&d.lc.view, d.sub.as_ref().map(|(_, t)| &t[0].view), d.blur.as_ref().map(|t| &t[1].view))) } + /// Detail's textures: the colour `fs_colour` renders, and its filters' results. + pub(crate) fn detail(&self) -> Option> { + let d = self.detail.as_ref()?; + Some(DetailViews { + colored: &d.colored.view, + noise: d.noise.as_ref().map(|t| &t[1].view), + chroma: d.chroma.as_ref().map(|t| &t[2].view), + sharpen: d.sharpen.as_ref().map(|t| &t[1].view), + mask: d.mask.as_ref().map(|t| &t[1].view), + }) + } + /// The statistics slots of the last pass of `tone`: its input's and its output's. pub(crate) fn last_slots(tone: &LocalTone) -> [u32; 2] { let i = tone.passes.len().saturating_sub(1) as u32; @@ -977,7 +1115,7 @@ impl ToneFrame { fn plan(&self, device: &wgpu::Device, queue: &wgpu::Queue, pipes: &TonePipelines, key: &PlanKey, luts: &wgpu::TextureView) -> Plan { let mut b = Builder::default(); - let mut bounds = [0usize; 3]; + let mut bounds = [0usize; 4]; let full = self.size; let rank = |len: u32, q: f32| (quantile_rank(len as usize, q) as u32).min(len.saturating_sub(1)); let v = |t: &Tex| Some(t.view.clone()); @@ -1013,7 +1151,7 @@ impl ToneFrame { let mut pack = Step::sized(s, s); pack.misc = [1, 0, 3, 0]; b.draw(Pipe::MinPack, pack, Reads { a: v(&hz.opened), b: v(&hz.cells), fine: v(&hz.weight), ..Default::default() }, &[&hz.guide[0].view], None); - b.guided(s, gr, DEHAZE_EPS, &hz.guide, true); + b.guided(s, gr, DEHAZE_EPS, hz.guide.each_ref(), Guided::Output); } bounds[0] = b.ops.len(); if let Some(py) = &self.pyramid { @@ -1081,12 +1219,12 @@ impl ToneFrame { } bounds[1] = b.ops.len(); // Clarity's coefficients and Texture's blur, from the luminance of `fs_luma`. - if let Some(d) = &self.detail { + if let Some(d) = &self.local { if let (Some([s, rs]), Some((size, sub))) = (key.clarity, &d.sub) { let mut step = Step::sized(*size, full); step.sizes2[3] = s; b.draw(Pipe::Block, step, Reads { a: v(&d.lc), ..Default::default() }, &[&sub[0].view], None); - b.guided(*size, rs, CLARITY_EPS, sub, false); + b.guided(*size, rs, CLARITY_EPS, sub.each_ref(), Guided::Coefficients); } if let Some(blur) = &d.blur { let mut from = &d.lc; @@ -1115,11 +1253,37 @@ impl ToneFrame { let rows = Some([0.0, WB_ROW as f32, photocraft_algo::camera_raw::WB_STEPS as f32, 2.0]); b.draw(Pipe::WbRows, step, Reads::default(), &[luts], rows); } + bounds[3] = b.ops.len(); + // Detail, from the colour of `fs_colour`: the luminance's noise reduction (a guided filter + // of itself), the chroma's (a Gaussian), then sharpening's blur and its mask's of the + // reduced luminance. `camera_raw.wgsl` combines them. + if let (Some(k), Some(d)) = (&key.detail, &self.detail) { + // The texture outlives the plan that made it: only a plan that reads it fills it. + let luma = d.luma.as_ref().filter(|_| k.reads_luma()); + if let Some(luma) = luma { + b.filter(Pipe::DetailIn, full, full, [0, 0, 0, 0], &d.colored, None, luma); + } + let mut reduced = luma; + if let (Some([r, eps, keep]), Some(luma), Some(noise)) = (k.luminance, luma, &d.noise) { + b.guided(full, r, f32::from_bits(eps), [luma, &noise[0], &noise[1]], Guided::Kept(f32::from_bits(keep))); + reduced = Some(&noise[1]); + } + if let (Some(radii), Some([chroma, a, b2])) = (&k.color, &d.chroma) { + b.filter(Pipe::DetailIn, full, full, [1, 0, 0, 0], &d.colored, None, chroma); + b.blur(Pipe::Box, full, radii, chroma, [a, b2]); + } + for (radii, pair) in [(&k.sharpen, &d.sharpen), (&k.mask, &d.mask)] { + if let (Some(radii), Some(pair), Some(y)) = (radii, pair, reduced) { + b.blur(Pipe::BoxPlane, full, radii, y, pair.each_ref()); + } + } + } let (steps, mut ops) = b.finish(device, queue, pipes, &self.stats.view); + let detail = ops.split_off(bounds[3].min(ops.len())); let whites_blacks = ops.split_off(bounds[2].min(ops.len())); - let detail = ops.split_off(bounds[1].min(ops.len())); + let local = ops.split_off(bounds[1].min(ops.len())); let tone = ops.split_off(bounds[0].min(ops.len())); - Plan { _steps: steps, segments: [ops, tone, detail, whites_blacks] } + Plan { _steps: steps, segments: [ops, tone, local, whites_blacks, detail] } } } @@ -1166,3 +1330,32 @@ fn record(encoder: &mut wgpu::CommandEncoder, ops: &[Op], pipes: &TonePipelines, } } } + +#[cfg(test)] +mod tests { + use super::*; + use photocraft_algo::camera_raw::{CameraRaw, DevelopInputs, per_pixel}; + + /// Whether Detail's stages for the default settings with `set` applied read the luminance. + fn reads_luma(set: impl FnOnce(&mut CameraRaw)) -> bool { + // `CameraRaw` is `#[non_exhaustive]`: start from the defaults and assign. + let mut p = CameraRaw::default(); + set(&mut p); + let stages = per_pixel(&p, &DevelopInputs::default(), 64, 48, false, None).expect("a per-pixel develop"); + PlanKey::new(&stages).detail.expect("Detail's stages").reads_luma() + } + + /// Colour noise reduction alone doesn't fill the luminance texture a sharpening or luminance + /// noise reduction frame left allocated (a full-frame pass nothing reads). + #[test] + fn only_luminance_noise_and_sharpening_read_the_luminance() { + assert!(!reads_luma(|p| p.noise_color = 50.0)); + assert!(reads_luma(|p| p.noise_luminance = 50.0)); + assert!(reads_luma(|p| p.sharpen_amount = 80.0)); + assert!(reads_luma(|p| { + p.noise_color = 50.0; + p.sharpen_amount = 80.0; + p.sharpen_masking = 40.0; + })); + } +} diff --git a/crates/gpu/tests/it/camera_raw.rs b/crates/gpu/tests/it/camera_raw.rs index ab06123581..b21dbc4a82 100644 --- a/crates/gpu/tests/it/camera_raw.rs +++ b/crates/gpu/tests/it/camera_raw.rs @@ -366,7 +366,7 @@ fn every_per_pixel_stage_at_once() { } #[test] -fn identity_leaves_pixels_alone_and_detail_has_no_pass() { +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); @@ -379,7 +379,13 @@ fn identity_leaves_pixels_alone_and_detail_has_no_pass() { 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}] { @@ -639,6 +645,129 @@ fn dehaze_opens_the_dark_channel_like_the_cpu() { } } +/// 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 }; @@ -657,3 +786,21 @@ fn dehaze_remakes_its_copy_when_the_white_balance_changes() { 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); +} diff --git a/crates/ui-egui/src/dialogs/camera_raw_gpu.rs b/crates/ui-egui/src/dialogs/camera_raw_gpu.rs index 8013d4eb11..bdb19d4a57 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_gpu.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_gpu.rs @@ -1,7 +1,6 @@ -//! Camera Raw's preview develop on the GPU (#6916). When the settings don't use Detail -//! (sharpening, noise reduction), the proxy develops in wgpu passes +//! Camera Raw's preview develop on the GPU (#6916). The proxy develops in wgpu passes //! (`photocraft_gpu::CameraRawDevelop`) on the canvas's device and is read back once for the -//! histogram, scopes and display conversion. Detail, Rendering Mode CPU, +//! histogram, scopes and display conversion. Calibration, Rendering Mode CPU, //! `PHOTOCRAFT_CPU_CAMERA_RAW`, no GPU canvas, a software adapter, a device fault or a failed //! develop all keep the CPU develop on the worker. //! @@ -129,8 +128,8 @@ impl CameraRawGpu { CameraRawGpu { device, queue, health, pass, failed: Arc::default(), points: Arc::default() } } - /// Develops `px` (`w × h`) with `p`, or `None` when the CPU must: Detail or Calibration, the - /// pass still building, a fault, or a GPU error (logged; the dialog then stays on the CPU). + /// Develops `px` (`w × h`) with `p`, or `None` when the CPU must: Calibration, the pass still + /// building, a fault, or a GPU error (logged; the dialog then stays on the CPU). /// `key` names the pixels when they are the dialog's unchanged proxy ([`source_key`]), so they /// upload once. Neutral settings are `None` too: the CPU develop returns them at once, a GPU /// round trip would only cost. `inputs` are the develop's seed, pixel scale and encoding gamma. @@ -149,7 +148,7 @@ impl CameraRawGpu { let Some(Some(pass)) = self.pass.get() else { return None }; let points = self.points(px, key, w, h, p, inputs); // PLAN: assumed `per_pixel(p, inputs, w, h, float, points)` (dialogs-w50 owns the algo signature) - let stages = gpu_stages(p, inputs, w, h, float, points)?; + let stages = photocraft_algo::camera_raw::per_pixel(p, inputs, w, h, float, points)?; let size = [u32::try_from(w).ok()?, u32::try_from(h).ok()?]; let mut pass = pass.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); match pass.develop(&self.device, &self.queue, Some(&self.health), px, key, size, &stages) { @@ -164,10 +163,10 @@ impl CameraRawGpu { } /// The image's black and white points for Whites and Blacks, measured on the CPU. With a - /// spatial stage the GPU measures them after it instead. + /// spatial stage before them the GPU measures them after it instead (Detail comes after). #[cfg(not(target_arch = "wasm32"))] fn points(&self, px: &[[f32; 4]], key: Option, w: usize, h: usize, p: &CameraRaw, inputs: &DevelopInputs) -> Option<(f32, f32)> { - if (p.whites == 0.0 && p.blacks == 0.0) || photocraft_algo::camera_raw::spatial(p) { + if (p.whites == 0.0 && p.blacks == 0.0) || photocraft_algo::camera_raw::spatial_tone(p) { return None; } // PLAN: assumed `white_black_points(px, w, h, p, inputs)` (dialogs-w50 owns the algo signature) @@ -185,22 +184,6 @@ impl CameraRawGpu { } } -/// The stages the GPU pass runs for `p`, or `None` when the CPU must develop. Besides what -/// [`per_pixel`](photocraft_algo::camera_raw::per_pixel) refuses, that is Detail: `per_pixel` -/// hands it over as a stage since craft-libs#3101, but the pass has none yet (#6916), so a -/// sharpened or noise-reduced frame would come back without it. -#[cfg(not(target_arch = "wasm32"))] -fn gpu_stages( - p: &CameraRaw, - inputs: &DevelopInputs, - w: usize, - h: usize, - float: bool, - points: Option<(f32, f32)>, -) -> Option { - photocraft_algo::camera_raw::per_pixel(p, inputs, w, h, float, points).filter(|stages| stages.detail.is_none()) -} - #[cfg(test)] mod gpu_tests { use super::*; @@ -274,6 +257,42 @@ mod gpu_tests { (frame.backend, frame.px, cpu) } + /// The open session's proxy pixel count, which every develop of it returns. + fn proxy_pixels(app: &PhotocraftApp) -> usize { + let (w, h) = app.raw.as_ref().expect("session").source.proxy_base().size; + w * h + } + + /// The largest channel difference between a GPU and a CPU develop. Both must hold all + /// `pixels` (a nonzero count) and only finite channels first: `zip` stops at the shorter + /// buffer and `f32::max` drops a NaN, so either would pass unchecked. + fn off_by(pixels: usize, gpu: &[[f32; 4]], cpu: &[[f32; 4]], what: &str) -> f32 { + assert!(pixels > 0, "{what}: the proxy has no pixels"); + assert_eq!((gpu.len(), cpu.len()), (pixels, pixels), "{what}: GPU and CPU pixel counts"); + for (side, px) in [("GPU", gpu), ("CPU", cpu)] { + assert!(px.iter().flatten().all(|c| c.is_finite()), "{what}: a non-finite {side} channel"); + } + gpu.iter().zip(cpu).flat_map(|(a, b)| (0..4).map(move |c| (a[c] - b[c]).abs())).fold(0.0f32, f32::max) + } + + #[test] + #[should_panic(expected = "GPU and CPU pixel counts")] + fn off_by_refuses_a_short_develop() { + off_by(2, &[[0.0; 4]], &[[0.0; 4]; 2], "short"); + } + + #[test] + #[should_panic(expected = "the proxy has no pixels")] + fn off_by_refuses_an_empty_proxy() { + off_by(0, &[], &[], "empty"); + } + + #[test] + #[should_panic(expected = "a non-finite GPU channel")] + fn off_by_refuses_a_non_finite_channel() { + off_by(1, &[[f32::NAN, 0.0, 0.0, 1.0]], &[[0.0, 0.0, 0.0, 1.0]], "nan"); + } + #[test] fn the_pass_is_built_when_camera_raw_first_opens_not_with_the_canvas() { let _gpu = photocraft_testkit::gpu_lock(); @@ -288,23 +307,8 @@ mod gpu_tests { assert_eq!(!has_gpu(&app), software, "a software adapter keeps the CPU develop"); } - fn worst_difference(gpu: &[[f32; 4]], cpu: &[[f32; 4]]) -> f32 { - assert_eq!(gpu.len(), cpu.len(), "preview frame lengths differ"); - gpu.iter() - .zip(cpu) - .enumerate() - .flat_map(|(pixel, (a, b))| { - (0..4).map(move |channel| { - let diff = (a[channel] - b[channel]).abs(); - assert!(diff.is_finite(), "nonfinite preview difference at pixel {pixel}, channel {channel}"); - diff - }) - }) - .fold(0.0, f32::max) - } - #[test] - fn per_pixel_settings_develop_on_the_gpu_like_the_cpu_and_the_rest_stays_on_the_cpu() { + fn every_stage_but_calibration_develops_on_the_gpu_like_the_cpu() { let _gpu = photocraft_testkit::gpu_lock(); // 8 and 32 bits: the dialog hands the develop only `float` (32-bit or not, `camera_raw_ui/convert.rs`), so 16 // bits takes 8 bits' path; every depth's develop is the gpu crate's `tests/it/camera_raw.rs` (#15652). @@ -316,6 +320,7 @@ mod gpu_tests { eprintln!("skipping: the device can't run the RAW Develop pass"); return; } + let pixels = proxy_pixels(&app); let per_pixel = cr! { temperature: 20.0, exposure: 0.4, @@ -330,14 +335,14 @@ mod gpu_tests { }; let (backend, gpu, cpu) = developed(&app, per_pixel.clone()); assert_eq!(backend, "gpu", "{depth}-bit"); - let worst = worst_difference(&gpu, &cpu); + let worst = off_by(pixels, &gpu, &cpu, &format!("{depth}-bit")); assert!(worst <= TOL, "{depth}-bit: off by {worst}"); // PLAN: the old `describe["developBackend"] == "gpu"` check read the dialog's own render; a `Job` can only be run by the host (no public runner), so the helper runs the job's body and the session's reported backend is not asserted here. // Shadows and Highlights develop on the GPU too, Whites and Blacks measured after them. let toned = cr!(per_pixel.clone() => shadows: 40.0, highlights: -35.0); let (backend, gpu, cpu) = developed(&app, toned.clone()); assert_eq!(backend, "gpu", "{depth}-bit, Shadows and Highlights"); - let worst = worst_difference(&gpu, &cpu); + let worst = off_by(pixels, &gpu, &cpu, &format!("{depth}-bit, Shadows and Highlights")); assert!(worst <= TOL, "{depth}-bit, Shadows and Highlights: off by {worst}"); // So do Dehaze, Clarity and Texture, with Whites and Blacks measured after them. for spatial in [ @@ -347,20 +352,25 @@ mod gpu_tests { ] { let (backend, gpu, cpu) = developed(&app, spatial.clone()); assert_eq!(backend, "gpu", "{depth}-bit, {spatial:?}"); - let worst = worst_difference(&gpu, &cpu); + let worst = off_by(pixels, &gpu, &cpu, &format!("{depth}-bit, {spatial:?}")); assert!(worst <= TOL, "{depth}-bit, {spatial:?}: off by {worst}"); } - // Detail develops the whole frame on the CPU, alone or after another stage. + // And Detail: sharpening and noise reduction, alone (Whites and Blacks measured on + // the CPU before it) and after every other stage. for detail in [ - cr!(toned.clone() => sharpen_amount: 40.0), - cr!(per_pixel.clone() => noise_luminance: 30.0, dehaze: 20.0), - cr!(exposure: 0.4, sharpen_amount: 40.0), - cr!(exposure: 0.4, noise_luminance: 30.0), - cr!(exposure: 0.4, noise_color: 25.0), + cr!(per_pixel.clone() => sharpen_amount: 60.0, sharpen_masking: 30.0), + cr!(per_pixel.clone() => noise_luminance: 40.0, noise_color: 50.0), + cr!(toned.clone() => sharpen_amount: 80.0, noise_luminance: 30.0, noise_color: 40.0, clarity: 30.0, texture: 25.0, dehaze: 20.0), ] { - let (backend, shown, cpu) = developed(&app, detail); - assert_eq!((backend, shown == cpu), ("cpu", true), "{depth}-bit"); + let (backend, gpu, cpu) = developed(&app, detail.clone()); + assert_eq!(backend, "gpu", "{depth}-bit, {detail:?}"); + let worst = off_by(pixels, &gpu, &cpu, &format!("{depth}-bit, {detail:?}")); + assert!(worst <= TOL, "{depth}-bit, {detail:?}: off by {worst}"); } + // Calibration develops the whole frame on the CPU (#5128). + let calibrated = cr!(per_pixel.clone() => sharpen_amount: 40.0, shadow_tint: 30.0); + let (backend, shown, cpu) = developed(&app, calibrated); + assert_eq!((backend, shown == cpu), ("cpu", true), "{depth}-bit"); // A device fault: the CPU, from the next frame on. app.gpu.as_ref().unwrap().health().mark(photocraft_gpu::Fault::Lost("test".into())); let (backend, shown, cpu) = developed(&app, per_pixel); @@ -368,24 +378,6 @@ mod gpu_tests { } } - #[test] - fn detail_keeps_the_cpu_develop_without_a_device() { - // Runs without a GPU, so hosted CI checks it too: `per_pixel` now hands Detail over as a - // stage (craft-libs#3101), and the pass must not run a frame without it. - let inputs = DevelopInputs::default(); - assert!(gpu_stages(&cr!(exposure: 0.4), &inputs, 64, 48, false, None).is_some(), "per-pixel settings reach the GPU"); - for detail in [ - cr!(exposure: 0.4, sharpen_amount: 40.0), - cr!(exposure: 0.4, noise_luminance: 30.0), - cr!(exposure: 0.4, noise_color: 25.0), - cr!(shadows: 40.0, sharpen_amount: 40.0), - ] { - let stages = photocraft_algo::camera_raw::per_pixel(&detail, &inputs, 64, 48, false, None); - assert!(stages.is_some_and(|s| s.detail.is_some()), "per_pixel hands Detail over: {detail:?}"); - assert!(gpu_stages(&detail, &inputs, 64, 48, false, None).is_none(), "the CPU develops Detail: {detail:?}"); - } - } - #[test] fn neutral_settings_skip_the_gpu_round_trip() { let _gpu = photocraft_testkit::gpu_lock(); diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index f5e4608d89..08c212c029 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -22,7 +22,7 @@ HDR display to verify. | GPU canvas, zoom/pan, rotate view | Metal (macOS), DirectX/OpenCL (Windows) | wgpu 30: Metal, Vulkan, DX12, GL; backend selectable | done | | GPU compositing of layers, blend modes, effects | partial (Photoshop composites mostly on CPU) | wgpu compositor, ≤ 1/255 vs CPU oracle; Multichannel and > texture-limit regions fall back to CPU | done (ahead in places) | | GPU compositor startup | available | Pipeline preparation runs in the background on native hardware; the CPU composites until ready. Windows WARP probe: 0.329 ms p95, 6.860 ms maximum device-work stall during two FXC builds; hardware measurements remain pending (#9157, #9364, #6419) | partial | -| GPU filters (Blur Gallery, Liquify, Smart Sharpen, Camera Raw) | yes | CPU (rayon) for filters; GPU for compose and effects. Camera Raw's preview runs its per-pixel stages (white balance to grain) in one wgpu pass, about 2-3 ms vs 11-28 ms on the CPU for the 858×572 proxy, depending on the machine, Shadows and Highlights (the local Laplacian filter) as fragment passes in front of it, 8.7-10.6 ms vs 147-300 ms, and Dehaze, Clarity and Texture (box, minimum and guided filters) as fragment passes too, 2.7-7.7 ms vs 7.6-17.7 ms each (Dehaze's dark channel opened as in the CPU develop, #9273); with all of them and every per-pixel stage 17-24 ms vs 222 ms on an RTX 5060 Ti. Detail, Calibration and OK still develop on the CPU (#6916) | partial | +| GPU filters (Blur Gallery, Liquify, Smart Sharpen, Camera Raw) | yes | CPU (rayon) for filters; GPU for compose and effects. Camera Raw's preview runs its per-pixel stages (white balance to grain) in one wgpu pass, about 2-3 ms vs 11-28 ms on the CPU for the 858×572 proxy, depending on the machine, Shadows and Highlights (the local Laplacian filter) as fragment passes in front of it, 8.7-10.6 ms vs 147-300 ms, and Dehaze, Clarity and Texture (box, minimum and guided filters) as fragment passes too, 2.7-7.7 ms vs 7.6-17.7 ms each (Dehaze's dark channel opened as in the CPU develop, #9273); with all of them and every per-pixel stage 17-24 ms vs 222 ms on an RTX 5060 Ti. Detail (sharpening and both noise reductions: a guided filter and box Gaussians after the colour stages) develops there too, 3.4-5.6 ms vs 9-23 ms for each control, 20-26 ms vs 433-466 ms with every other stage. Calibration and OK still develop on the CPU (#6916) | partial | | Documents larger than the GPU texture limit | yes (tiled) | paged GPU residency, composited page cell by page cell (`crates/gpu/src/lib.rs`, #49 closed) | done | | CPU-only fallback when no GPU | yes, reduced | `cpu` canvas preference; fails to start without an adapter on some Linux systems (#2519, #2412) | partial | | Choosing the GPU on a multi-GPU machine | Preferences › Performance › Use Graphics Processor | Linux only: Preferences › Performance › Advanced › GPU adapter and `PHOTOCRAFT_GPU_ADAPTER` (#1885); ignored on Windows and macOS | partial | @@ -71,6 +71,7 @@ rotation; its eraser end comes from the pointer hooks (#2285). | Date | Change | Summary | |---|---|---| +| 2026-11-12 | minor | GPU filters: RAW Develop's preview, Detail (#6916 step 4) | | 2026-11-06 | minor | Windows eraser end: the pointer hooks read `PEN_FLAG_INVERTED` and the Eraser switch follows it (Windows Ink on; #2285) | | 2026-11-05 | minor | Optional WinTab driver mode on Windows: pressure and eraser; tilt with orientation axes; rotation with a twist-reporting pen, with Windows Ink off | | 2026-10-28 | minor | Build GPU compositor pipelines in the background; benchmark baseline pending (#9157) |