diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a90fad3905..a9d4d065a3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -85,3 +85,4 @@ jobs: AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} diff --git a/.gitignore b/.gitignore index 8c2047fe6b..c88ace5fa4 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,6 @@ plan/ # model weights are never committed (SAM 3: docs/ai-masks.md) *.safetensors *.safetensors.part + +# Python tools import their public operator family. +__pycache__/ diff --git a/Cargo.lock b/Cargo.lock index 037865f87f..1d0bb2bdc2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1688,6 +1688,19 @@ dependencies = [ "winit", ] +[[package]] +name = "egui_extras" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +dependencies = [ + "ahash", + "egui", + "enum-map", + "itertools 0.15.0", + "log", + "profiling", +] + [[package]] name = "egui_glow" version = "0.37.0" @@ -1774,6 +1787,26 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "enum-map" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06" +dependencies = [ + "enum-map-derive", +] + +[[package]] +name = "enum-map-derive" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "enumflags2" version = "0.7.12" @@ -3732,6 +3765,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", + "unicode-normalization", "unicode-segmentation", "web-time", ] @@ -3762,6 +3796,13 @@ dependencies = [ "webpki-roots", ] +[[package]] +name = "lightcraft-film" +version = "0.18.0" +dependencies = [ + "libm", +] + [[package]] name = "lightcraft-geocode" version = "0.18.0" @@ -3991,6 +4032,7 @@ dependencies = [ "craft-update", "craft-window", "egui", + "egui_extras", "egui_kittest", "lightcraft-catalog", "lightcraft-codecs", @@ -4008,6 +4050,7 @@ dependencies = [ "lightcraft-slideshow", "lightcraft-testkit", "log", + "pollster 1.0.1", "serde", "serde_json", "toml", @@ -4023,9 +4066,11 @@ dependencies = [ "egui", "js-sys", "lightcraft-codecs", + "lightcraft-color", "lightcraft-engine", "lightcraft-preview", "lightcraft-raster", + "lightcraft-raw", "lightcraft-ui-egui", "log", "serde", @@ -6608,6 +6653,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" version = "1.53.1" @@ -6814,6 +6865,15 @@ version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + [[package]] name = "unicode-properties" version = "0.1.4" @@ -8221,11 +8281,6 @@ name = "egui_demo_lib" version = "0.37.0" source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" -[[patch.unused]] -name = "egui_extras" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" - [[patch.unused]] name = "egui_inspection" version = "0.37.0" diff --git a/Cargo.toml b/Cargo.toml index 4cfd43f3a3..061507c999 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,7 @@ lightcraft-raw = { path = "crates/raw" } lightcraft-codecs = { path = "crates/codecs" } lightcraft-meta = { path = "crates/meta" } lightcraft-develop = { path = "crates/develop" } +lightcraft-film = { path = "crates/film" } lightcraft-lensdb = { path = "crates/lensdb" } lightcraft-inpaint = { path = "crates/inpaint" } lightcraft-scenes = { path = "crates/scenes" } @@ -62,6 +63,7 @@ proptest = "1" bytemuck = { version = "1", features = ["derive"] } crc32fast = "1" siphasher = "1" +libm = "0.2" # pure-Rust maths for lightcraft-film (target-independent results) libc = "0.2" # dev-only: process CPU time in benches dhat = "0.3" # opt-in heap profiling (lightcraft-cli --features dhat-heap) and heap tests; never in product builds diff --git a/apps/lightcraft-web/Cargo.toml b/apps/lightcraft-web/Cargo.toml index d4ae0f6674..a5732beeaa 100644 --- a/apps/lightcraft-web/Cargo.toml +++ b/apps/lightcraft-web/Cargo.toml @@ -80,3 +80,5 @@ heif = ["lightcraft-codecs/heif"] [dev-dependencies] egui = { workspace = true } +lightcraft-color = { workspace = true } +lightcraft-raw = { workspace = true } diff --git a/apps/lightcraft-web/src/store.rs b/apps/lightcraft-web/src/store.rs index 729e794077..8f7c8e2839 100644 --- a/apps/lightcraft-web/src/store.rs +++ b/apps/lightcraft-web/src/store.rs @@ -12,7 +12,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex}; -use lightcraft_engine::files::{load_bytes, probe_bytes}; +use lightcraft_engine::files::{load_bytes_with, probe_bytes}; use lightcraft_engine::media::{FileLoader, FileProbe}; /// Prefix of the catalog paths of files kept in browser storage. @@ -144,9 +144,11 @@ impl Originals { /// Engine hooks that decode/probe from memory. pub fn hooks(&self) -> (FileLoader, FileProbe) { let s = self.clone(); - let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize| { + // (an imported camera profile is not applied on the web, as in the render worker: a raw keeps its own colour, + // whether it decodes in a worker or inline when workers are unavailable) + let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, _dcp: Option<&lightcraft_engine::media::DcpProfile>| { let bytes = s.get(path).ok_or_else(|| format!("{path}: the original is still loading from browser storage"))?; - load_bytes(&bytes, max_edge) + load_bytes_with(&bytes, max_edge, None) }); let s = self.clone(); let probe: FileProbe = Arc::new(move |path: &str| { @@ -237,6 +239,64 @@ mod tests { assert_eq!(out.image.width, 20); } + /// CodeRabbit on #1063: without web workers a render runs inline and handed the selected camera profile to this + /// loader, which applied it, so the picture differed from the worker's (which keeps the raw's own colour, the + /// documented web behaviour). The loader now ignores it. + #[test] + fn the_web_loader_keeps_a_raws_own_colour_with_a_camera_profile() { + use lightcraft_raw::*; + let (w, h) = (32usize, 24usize); + let raw = RawImage { + format: RawFormat::Dng, + width: w, + height: h, + cpp: 1, + data: RawData::U16((0..w * h).map(|i| 256 + ((i % w) * 300 + (i / w) * 200) as u16).collect()), + cfa: Cfa::bayer("RGGB"), + bits: 14, + black: BlackLevel::uniform(256.0), + white: vec![16000.0], + active_area: Rect::new(0, 0, w, h), + crop: Rect::new(0, 0, w, h), + orientation: Orientation::Normal, + color: ColorData { + illuminant: [21, 0], + color_matrix: [Some(lightcraft_color::Mat3([[0.9, 0.2, -0.15], [-0.3, 1.25, 0.08], [0.02, -0.12, 0.85]])), None], + as_shot_neutral: Some([0.5, 1.0, 0.7]), + ..Default::default() + }, + wb_multipliers: None, + linearized: false, + pixel_aspect: 1.0, + opcodes: OpcodeLists::default(), + metadata: Default::default(), + lens_metadata: Default::default(), + }; + let dng = write_dng(&raw, &DngWriteOptions::default()).unwrap(); + // our own numbers: a matrix that swaps the camera's red and blue + let swap = lightcraft_color::Mat3([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]).mul(&lightcraft_color::Mat3([ + [3.2406, -1.5372, -0.4986], + [-0.9689, 1.8758, 0.0415], + [0.0557, -0.2040, 1.0570], + ])); + let profile = dcp::DcpProfile { + name: "Swap".into(), + camera_model: "LightCraft Test Camera".into(), + color: ColorData { illuminant: [21, 0], color_matrix: [Some(swap), None], ..Default::default() }, + }; + assert_ne!( + load_bytes_with(&dng, 64, Some(&profile)).unwrap().0.data, + load_bytes_with(&dng, 64, None).unwrap().0.data, + "the profile changes a raw's colour where it is applied" + ); + let store = Originals::default(); + store.insert("h1", Arc::from(dng)); + let (loader, _) = store.hooks(); + let with = loader("web/h1/a.dng", 64, Some(&profile)).unwrap(); + let without = loader("web/h1/a.dng", 64, None).unwrap(); + assert_eq!(with.0.data, without.0.data, "the web loader leaves it out"); + } + #[test] fn download_names() { assert_eq!(download_name("dir/x-lightcraft.png"), "x-lightcraft.png"); diff --git a/apps/lightcraft-web/src/workers.rs b/apps/lightcraft-web/src/workers.rs index 9df4d5c553..56f7abea4a 100644 --- a/apps/lightcraft-web/src/workers.rs +++ b/apps/lightcraft-web/src/workers.rs @@ -318,6 +318,7 @@ impl Workers { loaded: None, quick: None, display: None, + frame: None, }; g.done.push((b.slot, r, 0.0)); } @@ -409,6 +410,7 @@ impl Workers { loaded: None, quick: None, display: None, + frame: None, }, ms, )); @@ -463,6 +465,7 @@ impl RenderOffload for Workers { loaded: None, quick: None, display: None, + frame: None, }; g.done.push((slot, r, 0.0)); return None; diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 2f98abafe1..31ae7229f5 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -79,7 +79,67 @@ fn app_icon() -> egui::IconData { eframe::icon_data::from_png_bytes(png).unwrap_or_default() } -struct App(LightcraftApp, PrefsWriter, #[cfg(target_os = "macos")] Option); +struct App(LightcraftApp, PrefsWriter, Option, #[cfg(target_os = "macos")] Option); + +/// Draws renders that stayed on the GPU: registers their textures with the window's egui-wgpu +/// renderer (the GPU renderer runs on the window's device, see [`adopt_window_device`]). +struct WindowTextures { + device: eframe::wgpu::Device, + queue: eframe::wgpu::Queue, + renderer: std::sync::Arc>, +} + +impl lightcraft_ui_egui::render::ScreenTextures for WindowTextures { + fn show(&mut self, frame: &lightcraft_engine::media::ScreenFrame, id: Option) -> Option { + let view = frame.texture.create_view(&Default::default()); + let mut r = self.renderer.write(); + let filter = eframe::wgpu::FilterMode::Linear; + Some(match id { + Some(id) => { + r.update_egui_texture_from_wgpu_texture(&self.device, &view, filter, id); + id + } + None => r.register_native_texture(&self.device, &view, filter), + }) + } + + fn free(&mut self, id: egui::TextureId) { + self.renderer.write().free_texture(&id); + } + + fn read(&self, frame: &lightcraft_engine::media::ScreenFrame) -> Option { + match lightcraft_engine::gpu::read_texture(&self.device, &self.queue, &frame.texture, frame.width, frame.height) { + Ok(img) => Some(egui::ColorImage::from_rgba_unmultiplied([img.width, img.height], img.data.as_flattened())), + Err(e) => { + log::warn!("gpu: a view can't be read back for the screenshot: {e}"); + None + } + } + } +} + +/// Render on the window's device (off the UI thread: building the kernels takes a moment), so the +/// loupe's drafts are drawn straight from the GPU; the textures they leave are shown through +/// [`WindowTextures`] once that worked. Otherwise the GPU renderer makes a device of its own, as +/// before, and every render comes back as pixels. +fn adopt_window_device(rs: &eframe::egui_wgpu::RenderState, ctx: &egui::Context) -> WindowTextures { + let (device, queue, info) = (rs.device.clone(), rs.queue.clone(), rs.adapter.get_info()); + let ctx = ctx.clone(); + // before the first frame's GPU warm-up can start a device of its own + lightcraft_engine::gpu::set_window_device_pending(true); + let spawned = std::thread::Builder::new().name("lc-gpu-window".into()).spawn(move || { + match lightcraft_engine::gpu::adopt_window_device(device, queue, info) { + Ok(()) => log::info!("gpu: rendering on the window's device"), + Err(e) => log::info!("gpu: renders come back as pixels: {e}"), + } + ctx.request_repaint(); + }); + if let Err(e) = spawned { + log::warn!("gpu: {e}"); + lightcraft_engine::gpu::set_window_device_pending(false); + } + WindowTextures { device: rs.device.clone(), queue: rs.queue.clone(), renderer: rs.renderer.clone() } +} impl eframe::App for App { fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] { @@ -89,7 +149,7 @@ impl eframe::App for App { } fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { #[cfg(target_os = "macos")] - if let Some(m) = self.2.as_mut() + if let Some(m) = self.3.as_mut() && m.update(&mut self.0, ctx) && lightcraft_ui_egui::panels::notices::may_close(&mut self.0) { @@ -109,6 +169,13 @@ impl eframe::App for App { } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { self.0.perf.host_frame_ms = frame.info().cpu_usage.map(|s| f64::from(s) * 1000.0); + // the GPU renderer adopted the window's device: its renders can be drawn as they are + if self.2.is_some() + && lightcraft_engine::gpu::on_window_device() + && let Some(t) = self.2.take() + { + self.0.renderer.set_screen_textures(Box::new(t)); + } self.0.ui(ui); } fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) { @@ -358,9 +425,16 @@ fn main() -> eframe::Result { #[cfg(target_os = "macos")] let menu = (std::env::var_os("LIGHTCRAFT_NO_NATIVE_MENU").is_none()).then(|| native_menu::NativeMenu::install(&mut app, &cc.egui_ctx)); + // the GPU renderer on the window's device, when GPU rendering is on + // (LIGHTCRAFT_GPU_WINDOW=0: a device of its own, renders read back - for comparison or a driver + // that misbehaves with compute and drawing on one device) + let window_device = std::env::var_os("LIGHTCRAFT_GPU_WINDOW").is_none_or(|v| v != "0"); + let window_textures = + cc.wgpu_render_state.as_ref().filter(|_| gpu_on && window_device).map(|rs| adopt_window_device(rs, &cc.egui_ctx)); Ok(Box::new(App( app, writer, + window_textures, #[cfg(target_os = "macos")] menu, ))) diff --git a/apps/lightcraft/src/tests.rs b/apps/lightcraft/src/tests.rs index 286838175e..ca90ebb5cc 100644 --- a/apps/lightcraft/src/tests.rs +++ b/apps/lightcraft/src/tests.rs @@ -5,6 +5,7 @@ fn desktop_clear_color_stays_opaque_with_a_modal_open() { let mut app = App( LightcraftApp::new(Session::new(), Services::default()), PrefsWriter::default(), + None, #[cfg(target_os = "macos")] None, ); @@ -566,6 +567,7 @@ fn on_exit_ends_the_process_on_macos() { let mut app = App( app, PrefsWriter::default(), + None, #[cfg(target_os = "macos")] None, ); @@ -598,6 +600,7 @@ fn on_exit_removes_the_lock_owner_note() { let mut app = App( LightcraftApp::new(session, Services::default()), PrefsWriter::default(), + None, #[cfg(target_os = "macos")] None, ); diff --git a/apps/lightcraft/src/window_gpu.rs b/apps/lightcraft/src/window_gpu.rs index e8caedf738..1b3e2d6809 100644 --- a/apps/lightcraft/src/window_gpu.rs +++ b/apps/lightcraft/src/window_gpu.rs @@ -154,6 +154,15 @@ pub fn base_options() -> WgpuConfiguration { n.instance_descriptor.backend_options = backend::backend_options(); // no indirect-call validation pipeline: Intel Metal fails to compile it and the window never opens (#250) n.instance_descriptor.flags = backend::instance_flags_from_env(n.instance_descriptor.flags); + // the GPU renderer may run on this device (`adopt_window_device`): it needs the adapter's + // buffer limits (a 24 MP photo is a 275 MiB buffer), not wgpu's defaults + let default = n.device_descriptor.clone(); + n.device_descriptor = std::sync::Arc::new(move |adapter| { + if adapter.get_info().backend == wgpu::Backend::Gl { + return default(adapter); + } + wgpu::DeviceDescriptor { label: Some("lightcraft window"), required_limits: adapter.limits(), ..Default::default() } + }); } c } @@ -192,7 +201,8 @@ fn probe(backends: Backends, compose_window: bool) -> Result io::Result<()> + Send + Sync>; + +static HOOKS: Mutex> = Mutex::new(Vec::new()); + +/// Run `hook` before every write and sync of the catalog log in `dir` (replacing an earlier one). +#[doc(hidden)] +pub fn install(dir: &Path, hook: Hook) { + let mut hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner); + hooks.retain(|(d, _)| d != dir); + hooks.push((dir.to_path_buf(), hook)); +} + +/// Remove the hook of `dir`. +#[doc(hidden)] +pub fn remove(dir: &Path) { + HOOKS.lock().unwrap_or_else(PoisonError::into_inner).retain(|(d, _)| d != dir); +} + +static ON_CALLER: Mutex> = Mutex::new(Vec::new()); + +/// Write the log in `dir` on the caller's thread, syncing before each append returns, as builds +/// before PERF-STEP-STALL did: a test's "before" (stores opened afterwards; the hooks run there too). +#[doc(hidden)] +pub fn write_on_caller(dir: &Path, on: bool) { + let mut dirs = ON_CALLER.lock().unwrap_or_else(PoisonError::into_inner); + dirs.retain(|d| d != dir); + if on { + dirs.push(dir.to_path_buf()); + } +} + +pub(crate) fn on_caller(dir: &Path) -> bool { + let dirs = ON_CALLER.lock().unwrap_or_else(PoisonError::into_inner); + !dirs.is_empty() && dirs.iter().any(|d| d == dir) +} + +pub(crate) fn check(dir: &Path, step: Step) -> io::Result<()> { + let hook = { + let hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner); + if hooks.is_empty() { + return Ok(()); + } + hooks.iter().find(|(d, _)| d == dir).map(|(_, h)| h.clone()) + }; + match hook { + Some(h) => h(step), + None => Ok(()), + } +} diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index b50a6d52eb..ffdb2ede1e 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -6,7 +6,10 @@ //! rename). //! - `catalog.log` — JSON lines, one per op applied after the snapshot: //! `{"seq":N,"crc":C,"op":{…}}` where `C` is the CRC-32 of the op's JSON text. Appends are -//! fsynced before [`Journal::append`] returns. +//! fsynced before [`Journal::append`] returns, except natively: [`crate::FsStore`] hands them to +//! a thread of its own that writes and syncs them in order right after (so a flag never waits +//! for the drive), holds and retries whatever fails ([`Journal::unwritten`]) and refuses later +//! appends meanwhile, so the log never has a gap and nothing handed over is dropped. //! //! Loading = snapshot + replay of the records with `seq > snapshot seq`. Recovery rules: //! - a **torn final record** (crash mid-append: truncated line or bad CRC at the end) is dropped @@ -195,6 +198,10 @@ pub struct Journal { /// A failed append may have left part of its records after `log_bytes`, and cutting them off /// failed too: the next append cuts the log back to `log_bytes` first. tail_dirty: bool, + /// An append failed (natively that can be the store's own log thread failing to write records + /// handed over before, which it holds and retries): the next chance writes a snapshot, a fresh + /// file holding everything, in case only the log's file is broken. + snapshot_due: bool, } /// A background snapshot in flight. @@ -383,6 +390,7 @@ impl Journal { pending: None, retry_at_records: 0, tail_dirty: false, + snapshot_due: false, }; let log = log.unwrap_or_default(); @@ -516,6 +524,7 @@ impl Journal { self.tail_dirty = false; } if let Err(e) = self.store.append(LOG, buf.as_bytes()) { + self.snapshot_due = true; // Part of the batch may be in the file. Cut it back to the last whole record, so the // retry (same seqs) starts on a clean line instead of after a fragment that would // read back as damage. @@ -678,6 +687,7 @@ impl Journal { } fn record_snapshot(&mut self, t: SnapshotTiming) { + self.snapshot_due = false; self.stats.snapshots += 1; self.stats.last_snapshot = t; self.stats.max_snapshot_ms = self.stats.max_snapshot_ms.max(t.total_ms); @@ -697,6 +707,23 @@ impl Journal { } } + /// Wait until every appended record is in the file and synced (natively the store writes the + /// log on a thread of its own, [`crate::FsStore`]): before the files are read or copied from + /// outside. An error says why some aren't yet: they are held and retried, never dropped. + pub fn flush(&mut self) -> Result<()> { + self.store.flush().map_err(io) + } + + /// Appended records the store holds because writing them failed (retried), and why; `None` + /// when nothing is held back. Never waits for the drive. + pub fn unwritten(&self) -> Option<(usize, String)> { + // a snapshot that holds every op holds whatever the log's thread still holds + if self.snapshot_seq >= self.seq && self.pending.is_none() { + return None; + } + self.store.unwritten() + } + /// Where persistence time went so far. pub fn stats(&self) -> PersistStats { PersistStats { snapshot_running: self.pending.is_some(), ..self.stats } @@ -706,7 +733,10 @@ impl Journal { pub fn wants_snapshot(&self) -> bool { self.pending.is_none() && self.log_records >= self.retry_at_records - && (self.log_records >= self.policy.max_records || self.log_bytes >= self.policy.max_bytes) + && (self.snapshot_due + || self.unwritten().is_some() + || self.log_records >= self.policy.max_records + || self.log_bytes >= self.policy.max_bytes) } pub fn seq(&self) -> u64 { diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 7995546434..a892943c9f 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -14,12 +14,17 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod dates; +#[cfg(not(target_arch = "wasm32"))] +#[doc(hidden)] +pub mod fault; pub mod folders; mod index; pub mod journal; pub mod keywords; pub mod local; pub mod lock; +#[cfg(not(target_arch = "wasm32"))] +mod log_writer; pub mod model; pub mod query; pub mod rules; @@ -1490,6 +1495,8 @@ mod tests_journal; mod tests_local; #[cfg(test)] mod tests_lock; +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests_log_thread; #[cfg(test)] mod tests_repair; #[cfg(test)] diff --git a/crates/catalog/src/log_writer.rs b/crates/catalog/src/log_writer.rs new file mode 100644 index 0000000000..6018f71f66 --- /dev/null +++ b/crates/catalog/src/log_writer.rs @@ -0,0 +1,377 @@ +//! The thread that writes the catalog log for [`crate::FsStore`] (natively). +//! +//! An append hands its bytes over and returns; the thread writes them in order and makes each batch +//! durable (`sync_data`) before the next. The caller (the UI thread, for the app) never waits for +//! the drive: on Windows a write to a file waits for a sync of that file in flight, so with the log +//! written and synced on the UI thread every flag, rating and step waited for the drive, 30–90 ms +//! on a busy disk in a test and over a second on a photographer's machine while previews were +//! written. +//! +//! **Nothing handed over is ever dropped.** The store's log is the file's first `good` bytes (written +//! and synced) followed by `held`, the bytes handed over and not yet synced. A write or sync that +//! fails keeps `held` and retries it (on every later message, and every [`RETRY`] meanwhile), first +//! cutting the file back to `good` so a fragment of the failed write never stays in it. While a +//! failure stands, [`LogWriter::append`] refuses new bytes with the failure (the journal keeps those +//! records queued, as for any failed append) and [`LogWriter::unwritten`] says how many records are +//! held, so the app counts them as not saved and its quit prompt warns before anything could be +//! lost. Cutting the log back, replacing it and reading it act on that logical content, after +//! everything handed over before; the caller waits for them. Dropping the writer waits for +//! everything handed over and tries a last time. + +use std::io::{self, Seek, Write}; +use std::path::PathBuf; +use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; + +/// How long a caller waits for the thread at most (a cut, a replace, a read, a flush). +const WAIT: Duration = Duration::from_secs(60); +/// How often held bytes are retried while a failure stands and nothing else arrives. +pub(crate) const RETRY: Duration = Duration::from_millis(500); + +enum Msg { + Append(Vec), + Truncate(u64, Sender>), + Replace(Vec, Sender>), + Read(Sender>>>), + /// Reply once everything before is written and synced (or why it isn't). + Flush(Sender>), +} + +/// What the caller can see without waiting. +#[derive(Default)] +struct Shared { + /// Why the held bytes couldn't be written (until they are, or the log is cut or replaced). + failed: Option, + /// Records (lines) handed over and not yet written and synced, while `failed` stands. + held_records: usize, +} + +pub(crate) struct LogWriter { + pub(crate) name: String, + tx: Option>, + shared: Arc>, + thread: Option>, +} + +fn stopped() -> io::Error { + io::Error::other("the catalog log writer stopped") +} + +fn not_written(why: &str) -> io::Error { + io::Error::other(format!("the catalog log could not be written: {why}")) +} + +impl LogWriter { + /// A writer for `dir/name` (`None` when no thread can start: the store then writes itself). + pub(crate) fn start(dir: PathBuf, name: &str) -> Option { + let (tx, rx) = channel::(); + let shared = Arc::new(Mutex::new(Shared::default())); + let sh = shared.clone(); + let mut w = Writer::new(dir, name); + let thread = std::thread::Builder::new().name("catalog-log".into()).spawn(move || w.run(&rx, &sh)).ok()?; + Some(LogWriter { name: name.to_string(), tx: Some(tx), shared, thread: Some(thread) }) + } + + fn send(&self, m: Msg) -> io::Result<()> { + self.tx.as_ref().ok_or_else(stopped)?.send(m).map_err(|_| stopped()) + } + + fn ask(&self, make: impl FnOnce(Sender>) -> Msg) -> io::Result { + let (tx, rx) = channel(); + self.send(make(tx))?; + rx.recv_timeout(WAIT).map_err(|e| match e { + RecvTimeoutError::Timeout => io::Error::new(io::ErrorKind::TimedOut, "the drive took over a minute to write the catalog log"), + RecvTimeoutError::Disconnected => stopped(), + })? + } + + /// Hand `data` over (never waits for the drive). Refused while bytes handed over before can't + /// be written: the caller keeps `data` and appends it again later. + pub(crate) fn append(&self, data: &[u8]) -> io::Result<()> { + if let Some(why) = self.shared.lock().unwrap_or_else(PoisonError::into_inner).failed.clone() { + return Err(not_written(&why)); + } + self.send(Msg::Append(data.to_vec())) + } + + /// Cut the log to `len` bytes, after everything handed over; waits for it. + pub(crate) fn truncate(&self, len: u64) -> io::Result<()> { + self.ask(|r| Msg::Truncate(len, r)) + } + + /// Replace the log with `data` (atomically, durably), after everything handed over; waits. + pub(crate) fn replace(&self, data: &[u8]) -> io::Result<()> { + self.ask(|r| Msg::Replace(data.to_vec(), r)) + } + + /// The log as appended so far (written or still held), after everything handed over. + pub(crate) fn read(&self) -> io::Result>> { + self.ask(Msg::Read) + } + + /// Wait until everything handed over is written and synced; an error says why it isn't (the + /// bytes are still held and retried). + pub(crate) fn flush(&self) -> io::Result<()> { + self.ask(Msg::Flush) + } + + /// Records handed over that can't be written yet, and why (`None`: nothing is held back by a + /// failure). Never waits. + pub(crate) fn unwritten(&self) -> Option<(usize, String)> { + let sh = self.shared.lock().unwrap_or_else(PoisonError::into_inner); + sh.failed.clone().map(|why| (sh.held_records.max(1), why)) + } +} + +impl Drop for LogWriter { + fn drop(&mut self) { + drop(self.tx.take()); + if let Some(t) = self.thread.take() { + let _ = t.join(); + } + } +} + +/// The thread's side: the file and what is held for it. +struct Writer { + dir: PathBuf, + path: PathBuf, + tmp: PathBuf, + file: Option, + /// Bytes of the file written whole and synced (`None` until the file was first opened). + good: Option, + /// Handed over, not yet written and synced. + held: Vec, + failed: Option, +} + +fn lines(b: &[u8]) -> usize { + b.iter().filter(|c| **c == b'\n').count() +} + +impl Writer { + fn new(dir: PathBuf, name: &str) -> Writer { + let path = dir.join(name); + let tmp = dir.join(format!("{name}.tmp")); + Writer { dir, path, tmp, file: None, good: None, held: Vec::new(), failed: None } + } + + fn hook(&self, step: crate::fault::Step) -> io::Result<()> { + crate::fault::check(&self.dir, step) + } + + /// Open the file positioned at `good` (a fragment past it, from a write that failed, is cut). + fn open(&mut self) -> io::Result { + if let (Some(_), Some(g)) = (&self.file, self.good) { + return Ok(g); + } + // (a link or a device planted at the name meanwhile is refused, as at the first append) + crate::store::check_regular_directory_entry(&self.path)?; + let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(false).open(&self.path)?; + let len = f.metadata()?.len(); + let good = match self.good { + None => len, + Some(g) if len > g => { + f.set_len(g)?; + g + } + Some(g) if len < g => { + // shorter than what was synced: someone else cut it; continue at its end + log::error!("catalog: {} is {len} bytes, {g} were written", self.path.display()); + len + } + Some(g) => g, + }; + f.seek(io::SeekFrom::Start(good))?; + self.good = Some(good); + self.file = Some(f); + Ok(good) + } + + /// Write and sync what is held. + fn write_held(&mut self) -> io::Result<()> { + if self.held.is_empty() { + return Ok(()); + } + let r = (|| { + self.hook(crate::fault::Step::Write)?; + self.open()?; + let f = self.file.as_mut().ok_or_else(|| io::Error::other("catalog log not open"))?; + f.write_all(&self.held)?; + self.hook(crate::fault::Step::Sync)?; + self.file.as_ref().ok_or_else(|| io::Error::other("catalog log not open"))?.sync_data() + })(); + match r { + Ok(()) => { + let n = self.held.len() as u64; + self.good = Some(self.good.unwrap_or(0).saturating_add(n)); + self.held.clear(); + Ok(()) + } + Err(e) => { + // the handle may be dead (a network share that reconnected, a removed volume): the + // retry opens the file again and cuts what this attempt left past `good` + self.file = None; + Err(e) + } + } + } + + /// Cut the logical log (file then held) to `len` bytes. + fn truncate(&mut self, len: u64) -> io::Result<()> { + let good = match self.good { + Some(g) => g, + None => match self.open() { + Ok(g) => g, + Err(e) if e.kind() == io::ErrorKind::NotFound => 0, + Err(e) => return Err(e), + }, + }; + // (to exactly `good` with bytes held: the file is cut, since a write that failed may have + // left some of them past `good`) + if len > good || (len == good && self.held.is_empty()) { + // within what is held: nothing on the drive changes (what a failed write left past + // `good` is cut before the next write) + let keep = usize::try_from(len - good).unwrap_or(usize::MAX).min(self.held.len()); + self.held.truncate(keep); + return Ok(()); + } + self.file = None; + let f = match std::fs::OpenOptions::new().write(true).open(&self.path) { + Ok(f) => f, + Err(e) if e.kind() == io::ErrorKind::NotFound => { + self.good = None; + self.held.clear(); + return Ok(()); + } + Err(e) => return Err(e), + }; + f.set_len(len)?; + f.sync_all()?; + self.good = Some(len); + self.held.clear(); + Ok(()) + } + + fn replace(&mut self, data: &[u8]) -> io::Result<()> { + self.file = None; + let written = (|| { + self.hook(crate::fault::Step::Write)?; + let mut f = crate::store::create_staging(&self.tmp)?; + f.write_all(data)?; + self.hook(crate::fault::Step::Sync)?; + f.sync_all()?; + drop(f); + std::fs::rename(&self.tmp, &self.path) + })(); + match written { + Ok(()) => { + // what was held is part of what the caller replaced the log with (a snapshot holds + // the records before it, `data` the ones after) + self.good = Some(data.len() as u64); + self.held.clear(); + self.failed = None; + Ok(()) + } + Err(e) => { + let _ = std::fs::remove_file(&self.tmp); + Err(e) + } + } + } + + fn read(&mut self) -> io::Result>> { + let mut bytes = match std::fs::read(&self.path) { + Ok(b) => b, + Err(e) if e.kind() == io::ErrorKind::NotFound && self.held.is_empty() => return Ok(None), + Err(e) if e.kind() == io::ErrorKind::NotFound => Vec::new(), + Err(e) => return Err(e), + }; + if let Some(g) = self.good { + bytes.truncate(usize::try_from(g).unwrap_or(usize::MAX)); + } + bytes.extend_from_slice(&self.held); + Ok(Some(bytes)) + } + + fn publish(&self, shared: &Mutex) { + let mut sh = shared.lock().unwrap_or_else(PoisonError::into_inner); + sh.failed = self.failed.clone().filter(|_| !self.held.is_empty()); + sh.held_records = if sh.failed.is_some() { lines(&self.held) } else { 0 }; + } + + fn run(&mut self, rx: &Receiver, shared: &Mutex) { + loop { + let first = if self.failed.is_some() && !self.held.is_empty() { + match rx.recv_timeout(RETRY) { + Ok(m) => Some(m), + Err(RecvTimeoutError::Timeout) => None, + Err(RecvTimeoutError::Disconnected) => break, + } + } else { + match rx.recv() { + Ok(m) => Some(m), + Err(_) => break, + } + }; + let mut batch: Vec = first.into_iter().collect(); + while let Ok(m) = rx.try_recv() { + batch.push(m); + } + let mut flushes = Vec::new(); + for m in batch { + match m { + Msg::Append(data) => self.held.extend_from_slice(&data), + // (published before the reply: the caller reads what it left at once) + Msg::Truncate(len, reply) => { + let r = self.truncate(len); + self.publish(shared); + let _ = reply.send(r); + } + Msg::Replace(data, reply) => { + let r = self.replace(&data); + self.publish(shared); + let _ = reply.send(r); + } + Msg::Read(reply) => { + let _ = reply.send(self.read()); + } + Msg::Flush(reply) => flushes.push(reply), + } + } + self.step(); + self.publish(shared); + for r in flushes { + let _ = r.send(match &self.failed { + Some(why) if !self.held.is_empty() => Err(not_written(why)), + _ => Ok(()), + }); + } + } + // the store is closing: everything handed over gets one more try + self.step(); + self.publish(shared); + if !self.held.is_empty() { + log::error!("catalog: {} record(s) could not be written to {} (the closing snapshot holds them)", lines(&self.held), self.path.display()); + } + } + + /// Write what is held; a failure is kept (and logged when it is new). + fn step(&mut self) { + match self.write_held() { + Ok(()) => { + if self.failed.take().is_some() { + log::info!("catalog: {} written again", self.path.display()); + } + } + Err(e) => { + let why = e.to_string(); + if self.failed.as_deref() != Some(why.as_str()) { + log::error!("catalog: {}: {why} ({} record(s) held, retried)", self.path.display(), lines(&self.held)); + } + self.failed = Some(why); + } + } + } +} diff --git a/crates/catalog/src/store.rs b/crates/catalog/src/store.rs index a79930f14a..3345ef884f 100644 --- a/crates/catalog/src/store.rs +++ b/crates/catalog/src/store.rs @@ -28,7 +28,9 @@ pub trait Store: Send { self.write_atomic(name, &buf)?; Ok(buf.len() as u64) } - /// Append and make durable (fsync) before returning. On an error, part of `data` may have + /// Append and make durable (fsync): before returning, or, natively, by the store's own log + /// thread right after ([`FsStore`]: a write that fails is returned by a later append, and a + /// read through the store sees every byte handed over). On an error, part of `data` may have /// been written (a full disk, a dropped network share): the journal cuts the file back to its /// previous length with [`Store::truncate`] before appending again. fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()>; @@ -43,12 +45,23 @@ pub trait Store: Send { fn background_writer(&self) -> Option> { None } + /// Wait until every append handed over is in the file and synced ([`FsStore`] writes them on a + /// thread of its own; the default has nothing to wait for). An error says why some aren't: they + /// are still held and retried, never dropped. + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + /// Records handed over by [`Store::append`] that can't be written yet (a write or sync on the + /// store's own thread failed: they are held and retried), and why. `None`: nothing held back. + fn unwritten(&self) -> Option<(usize, String)> { + None + } } /// Appends and truncates open the name's own file, so anything else at the name is the library's /// problem: a link planted there redirects the write outside the directory (CWE-59), and a device /// hangs the open. Refused with an error the open can show, before anything is written through. -fn check_regular_directory_entry(path: &Path) -> io::Result<()> { +pub(crate) fn check_regular_directory_entry(path: &Path) -> io::Result<()> { match std::fs::symlink_metadata(path) { Ok(md) if md.is_file() => Ok(()), Ok(md) => Err(io::Error::other(format!("{} is a {:?}, not a regular file", path.display(), md.file_type()))), @@ -60,15 +73,24 @@ fn check_regular_directory_entry(path: &Path) -> io::Result<()> { /// Files in a directory. pub struct FsStore { dir: PathBuf, - /// Open append handle (kept between appends; dropped on rewrite/truncate). + /// Open append handle (kept between appends; dropped on rewrite/truncate). Used when no thread + /// writes the log (the browser build, or one that couldn't start). appender: Option<(String, std::fs::File)>, + /// The thread that writes the log (natively; started by the first append). + #[cfg(not(target_arch = "wasm32"))] + log: Option, } impl FsStore { /// Use `dir` (created if missing). pub fn open(dir: impl AsRef) -> io::Result { std::fs::create_dir_all(dir.as_ref())?; - Ok(FsStore { dir: dir.as_ref().to_path_buf(), appender: None }) + Ok(FsStore { + dir: dir.as_ref().to_path_buf(), + appender: None, + #[cfg(not(target_arch = "wasm32"))] + log: None, + }) } pub fn dir(&self) -> &Path { &self.dir @@ -76,6 +98,21 @@ impl FsStore { fn path(&self, name: &str) -> PathBuf { self.dir.join(name) } + /// The log thread, when it writes `name`. + #[cfg(not(target_arch = "wasm32"))] + fn log_for(&self, name: &str) -> Option<&crate::log_writer::LogWriter> { + self.log.as_ref().filter(|w| w.name == name) + } + + /// Wait until the log thread has written and synced everything handed to it. + pub fn flush_log(&self) -> io::Result<()> { + #[cfg(not(target_arch = "wasm32"))] + if let Some(w) = &self.log { + return w.flush(); + } + Ok(()) + } + fn sync_dir(&self) { // Makes the rename durable on POSIX; opening a directory fails on Windows (where // `rename` is already journaled by NTFS), so errors are ignored. @@ -97,6 +134,11 @@ pub(crate) fn create_staging(tmp: &std::path::Path) -> io::Result impl Store for FsStore { fn read(&mut self, name: &str) -> io::Result>> { + #[cfg(not(target_arch = "wasm32"))] + if let Some(w) = self.log_for(name) { + // what was handed over, written or still held + return w.read(); + } match std::fs::read(self.path(name)) { Ok(b) => Ok(Some(b)), Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), @@ -106,6 +148,13 @@ impl Store for FsStore { fn write_atomic(&mut self, name: &str, data: &[u8]) -> io::Result<()> { use std::io::Write; + #[cfg(not(target_arch = "wasm32"))] + if let Some(w) = self.log_for(name) { + // (after the appends handed over before) + w.replace(data)?; + self.sync_dir(); + return Ok(()); + } if self.appender.as_ref().is_some_and(|(n, _)| n == name) { self.appender = None; } @@ -122,6 +171,15 @@ impl Store for FsStore { fn write_atomic_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn io::Write) -> io::Result<()>) -> io::Result { use std::io::Write; + #[cfg(not(target_arch = "wasm32"))] + if let Some(w) = self.log_for(name) { + // (the log is small: buffered, and replaced by its thread after the appends before) + let mut buf = Vec::new(); + fill(&mut buf)?; + w.replace(&buf)?; + self.sync_dir(); + return Ok(buf.len() as u64); + } if self.appender.as_ref().is_some_and(|(n, _)| n == name) { self.appender = None; } @@ -148,6 +206,23 @@ impl Store for FsStore { fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()> { use std::io::Write; + #[cfg(not(target_arch = "wasm32"))] + { + if self.log.is_none() && !crate::fault::on_caller(&self.dir) { + check_regular_directory_entry(&self.path(name))?; + if !self.path(name).exists() { + // created here, so the open's errors are this append's and its entry is durable + std::fs::OpenOptions::new().create(true).append(true).open(self.path(name))?; + self.sync_dir(); + } + self.appender = None; + self.log = crate::log_writer::LogWriter::start(self.dir.clone(), name); + } + // (another name than the log's is written here, as without a thread) + if let Some(w) = self.log_for(name) { + return w.append(data); + } + } if self.appender.as_ref().is_none_or(|(n, _)| n != name) { check_regular_directory_entry(&self.path(name))?; let existed = self.path(name).exists(); @@ -158,6 +233,12 @@ impl Store for FsStore { self.appender = Some((name.to_string(), f)); } let Some((_, f)) = self.appender.as_mut() else { return Err(io::Error::other("appender not open")) }; + #[cfg(not(target_arch = "wasm32"))] + let written = crate::fault::check(&self.dir, crate::fault::Step::Write) + .and_then(|()| f.write_all(data)) + .and_then(|()| crate::fault::check(&self.dir, crate::fault::Step::Sync)) + .and_then(|()| f.sync_data()); + #[cfg(target_arch = "wasm32")] let written = f.write_all(data).and_then(|()| f.sync_data()); if written.is_err() { // The handle may be dead (a network share that reconnected, a removed volume): the next @@ -169,6 +250,10 @@ impl Store for FsStore { } fn truncate(&mut self, name: &str, len: u64) -> io::Result<()> { + #[cfg(not(target_arch = "wasm32"))] + if let Some(w) = self.log_for(name) { + return w.truncate(len); + } if self.appender.as_ref().is_some_and(|(n, _)| n == name) { self.appender = None; } @@ -189,7 +274,16 @@ impl Store for FsStore { #[cfg(not(target_arch = "wasm32"))] fn background_writer(&self) -> Option> { - Some(Box::new(FsStore { dir: self.dir.clone(), appender: None })) + Some(Box::new(FsStore { dir: self.dir.clone(), appender: None, log: None })) + } + + fn flush(&mut self) -> io::Result<()> { + self.flush_log() + } + + #[cfg(not(target_arch = "wasm32"))] + fn unwritten(&self) -> Option<(usize, String)> { + self.log.as_ref().and_then(|w| w.unwritten()) } } @@ -256,13 +350,13 @@ impl Store for MemStore { } } +// (its one test plants a symlink, so the module is Unix-only: elsewhere `use super::*` would be unused) #[cfg(all(test, unix))] mod tests_staging { use super::*; /// A link planted at a staging name (`.tmp`) is removed, never followed: the file it points to keeps its /// bytes and the save still lands (issue #1502). - #[cfg(unix)] #[test] fn a_link_at_the_staging_name_is_never_written_through() { let dir = std::env::temp_dir().join(format!("lc-staging-link-{}", std::process::id())); diff --git a/crates/catalog/src/tests_background.rs b/crates/catalog/src/tests_background.rs index 5235c3e171..056d90afbc 100644 --- a/crates/catalog/src/tests_background.rs +++ b/crates/catalog/src/tests_background.rs @@ -269,9 +269,10 @@ fn fs_store_background_snapshot() { } // a previous crash mid-snapshot left a partial temp file std::fs::write(dir.join(format!("{SNAPSHOT}.tmp")), b"{\"format\":\"lightcraft-catal").unwrap(); + // (closed first: its log thread writes what was handed over) + drop(j); let (mut j2, c2, r) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); assert_eq!((c2.to_snapshot(), r.snapshot_seq), (live.to_snapshot(), 0)); - drop(j); let n = j2.seq(); j2.snapshot_in_background(&live).unwrap(); for k in 200..260 { diff --git a/crates/catalog/src/tests_log_thread.rs b/crates/catalog/src/tests_log_thread.rs new file mode 100644 index 0000000000..9c78d61f69 --- /dev/null +++ b/crates/catalog/src/tests_log_thread.rs @@ -0,0 +1,232 @@ +//! PERF-STEP-STALL: the catalog log's own thread ([`crate::log_writer`]). Appends return at once +//! however slow the drive is; everything handed over is written in order; a write that fails is +//! held, reported and retried, never dropped, and the log never has a gap. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; + +use crate::fault::{self, Step}; +use crate::store::{FsStore, Store}; + +const LOG: &str = "catalog.log"; + +fn temp_dir(tag: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("lc-log-thread-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + d +} + +fn wait_until(what: &str, mut done: impl FnMut() -> bool) { + let t = Instant::now(); + while !done() { + assert!(t.elapsed() < Duration::from_secs(20), "{what}"); + std::thread::sleep(Duration::from_millis(10)); + } +} + +/// Appends are written by the thread in order; a read through the store sees every one; a cut +/// and a replace come after the appends before them; dropping the store writes what is left. +#[test] +fn appends_are_written_in_order_and_cuts_and_replaces_come_after_them() { + let dir = temp_dir("order"); + let mut store = FsStore::open(&dir).unwrap(); + let mut want = Vec::new(); + for i in 0..200u32 { + let line = format!("{i}\n"); + store.append(LOG, line.as_bytes()).unwrap(); + want.extend_from_slice(line.as_bytes()); + if i % 50 == 0 { + assert_eq!(store.read(LOG).unwrap().unwrap(), want, "all of it, through the store"); + } + } + store.flush().unwrap(); + assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), want, "all of it, in the file"); + store.truncate(LOG, 4).unwrap(); + assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n"); + // never longer than it is + store.truncate(LOG, 400).unwrap(); + assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n"); + store.append(LOG, b"x\n").unwrap(); + store.write_atomic(LOG, b"tail\n").unwrap(); + assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\n"); + store.append(LOG, b"more\n").unwrap(); + drop(store); + assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\nmore\n"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// (a) Each sync takes 300 ms: 100 appends still return at once, and a flush then finds all of +/// them in the file (before, each append waited for its own sync: 30 s for these). +#[test] +fn an_append_never_waits_for_a_slow_sync() { + let dir = temp_dir("slow"); + let mut store = FsStore::open(&dir).unwrap(); + store.append(LOG, b"first\n").unwrap(); + let syncs = Arc::new(AtomicUsize::new(0)); + let n = syncs.clone(); + fault::install( + &dir, + Arc::new(move |step| { + if step == Step::Sync { + n.fetch_add(1, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(300)); + } + Ok(()) + }), + ); + let mut want = b"first\n".to_vec(); + let mut slowest = Duration::ZERO; + for i in 0..100u32 { + let line = format!("{i}\n"); + let t = Instant::now(); + store.append(LOG, line.as_bytes()).unwrap(); + slowest = slowest.max(t.elapsed()); + want.extend_from_slice(line.as_bytes()); + std::thread::sleep(Duration::from_millis(2)); + } + assert!(slowest < Duration::from_millis(50), "an append waited {slowest:?}"); + store.flush().unwrap(); + assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), want); + // batched: far fewer syncs than appends + assert!(syncs.load(Ordering::SeqCst) < 50, "{} syncs", syncs.load(Ordering::SeqCst)); + fault::remove(&dir); + let _ = std::fs::remove_dir_all(&dir); +} + +/// (c) Writes fail for a while: what was handed over is held (reported, with the reason), later +/// appends are refused so the caller keeps them, and once writes work again the held bytes land, +/// in order, with no fragment of the failed attempts and no gap. +#[test] +fn a_failed_write_is_held_reported_and_retried() { + let dir = temp_dir("fail"); + let mut store = FsStore::open(&dir).unwrap(); + store.append(LOG, b"0\n").unwrap(); + store.flush().unwrap(); + let fail = Arc::new(AtomicBool::new(true)); + let f = fail.clone(); + fault::install(&dir, Arc::new(move |_| if f.load(Ordering::SeqCst) { Err(std::io::Error::other("disk full (test)")) } else { Ok(()) })); + // (one append: the log thread can fail the first before a second arrives, and then refuses it) + store.append(LOG, b"1\n2\n").unwrap(); + wait_until("the failure is published", || store.unwritten().is_some()); + let (held, why) = store.unwritten().unwrap(); + assert!(why.contains("disk full"), "{why}"); + assert!(held >= 1, "{held}"); + let refused = store.append(LOG, b"3\n"); + assert!(refused.is_err(), "refused while held"); + assert!(store.flush().is_err(), "a flush says it isn't written"); + // a read through the store still sees what was handed over + assert_eq!(store.read(LOG).unwrap().unwrap(), b"0\n1\n2\n"); + // a cut within what is held keeps it (the journal cuts back to its own length on an error) + store.truncate(LOG, 6).unwrap(); + assert_eq!(store.read(LOG).unwrap().unwrap(), b"0\n1\n2\n"); + // a fragment of a failed write left in the file is cut before the retry + { + use std::io::Write; + let mut file = std::fs::OpenOptions::new().append(true).open(dir.join(LOG)).unwrap(); + file.write_all(b"{\"seq\":").unwrap(); + } + fail.store(false, Ordering::SeqCst); + wait_until("retried on its own", || store.unwritten().is_none()); + store.append(LOG, b"3\n").unwrap(); + store.flush().unwrap(); + assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n2\n3\n"); + fault::remove(&dir); + let _ = std::fs::remove_dir_all(&dir); +} + +/// (b, c) Through the journal: ops appended while the drive is slow or failing all reopen, and a +/// journal over a log that failed has no gap (no damage on load). +#[test] +fn the_journal_reopens_every_op_after_a_slow_then_failing_drive() { + use crate::{Catalog, Journal, Op, Photo, PhotoId, Source}; + let dir = temp_dir("journal"); + let (mut j, mut c, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); + let fail = Arc::new(AtomicBool::new(false)); + let f = fail.clone(); + fault::install( + &dir, + Arc::new(move |step| { + if f.load(Ordering::SeqCst) { + return Err(std::io::Error::other("network share dropped (test)")); + } + if step == Step::Sync { + std::thread::sleep(Duration::from_millis(40)); + } + Ok(()) + }), + ); + let mut queued: Vec = Vec::new(); + for id in 1..=60u64 { + if id == 20 { + fail.store(true, Ordering::SeqCst); + } + if id == 40 { + fail.store(false, Ordering::SeqCst); + } + let p = Photo::new(PhotoId(id), Source::Demo { scene: 0 }, &format!("p{id}.jpg"), "JPEG", 4, 3, "2026-11-02"); + let op = Op::AddPhoto { photo: Box::new(p) }; + c.apply(op.clone()).unwrap(); + queued.push(op); + // as the engine does: a failed append keeps its ops queued for the next one + if j.append(&queued).is_ok() { + queued.clear(); + } + std::thread::sleep(Duration::from_millis(5)); + } + wait_until("everything written", || { + if !queued.is_empty() && j.append(&queued).is_ok() { + queued.clear(); + } + queued.is_empty() && j.unwritten().is_none() + }); + j.flush().unwrap(); + let expect = c.to_snapshot(); + drop(j); + fault::remove(&dir); + let (_, again, report): (_, Catalog, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); + assert!(report.damaged.is_none(), "{report:?}"); + assert_eq!(again.to_snapshot(), expect); + assert_eq!(again.len(), 60); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A sync that fails leaves the written bytes past the synced length in the file; a cut to exactly +/// that length removes them from the file too, so they never come back on the next open (review +/// of #3557). +#[test] +fn a_cut_to_the_synced_length_removes_bytes_a_failed_sync_left() { + let dir = temp_dir("cut-synced"); + let mut store = FsStore::open(&dir).unwrap(); + store + .append( + LOG, b"0 +", + ) + .unwrap(); + store.flush().unwrap(); + fault::install(&dir, Arc::new(|step| if step == Step::Sync { Err(std::io::Error::other("sync failed (test)")) } else { Ok(()) })); + store + .append( + LOG, b"1 +", + ) + .unwrap(); + wait_until("the failure is published", || store.unwritten().is_some()); + assert_eq!( + std::fs::read(dir.join(LOG)).unwrap(), + b"0 +1 +", + "written, not synced" + ); + store.truncate(LOG, 2).unwrap(); + fault::remove(&dir); + drop(store); + assert_eq!( + std::fs::read(dir.join(LOG)).unwrap(), + b"0 +" + ); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/catalog/src/tests_torn_append.rs b/crates/catalog/src/tests_torn_append.rs index 0b6cf05af3..f7cee57d23 100644 --- a/crates/catalog/src/tests_torn_append.rs +++ b/crates/catalog/src/tests_torn_append.rs @@ -88,6 +88,9 @@ fn partial_append_then_retry_loads_cleanly() { assert!(j.append(&batch).is_err(), "tear at {tear}"); // cut back to the last whole record assert_eq!(t.files.get(LOG).unwrap().len(), good_len, "tear at {tear}"); + // and a snapshot is due (records handed over before may be missing from a log written + // by a thread of its own: note 2 of 2026-10-25) + assert!(j.wants_snapshot(), "tear at {tear}"); j.append(&batch).unwrap(); let more = apply(&mut c, vec![Op::SetLabel { id, label: Some(ColorLabel::ALL[0]) }]); j.append(&more).unwrap(); diff --git a/crates/catalog/tests/path_fold_heap.rs b/crates/catalog/tests/path_fold_heap.rs index 4fc1c8ef14..9c41f3fcf2 100644 --- a/crates/catalog/tests/path_fold_heap.rs +++ b/crates/catalog/tests/path_fold_heap.rs @@ -55,5 +55,8 @@ fn a_file_path_rule_allocates_nothing_per_photo() { } let blocks = dhat::HeapStats::get().total_blocks - before; assert!(hits > 0, "the rules matched nothing: the test measures nothing"); - assert_eq!(blocks, 0, "{blocks} heap blocks for {} rule tests", 100 * rules.len() * photos.len()); + // dhat counts every thread, and the test harness's own thread can allocate a few blocks while this + // runs. An allocation per photo would be thousands, two per rule test. + let tests = 100 * rules.len() * photos.len(); + assert!(blocks < 64, "{blocks} heap blocks for {tests} rule tests"); } diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index 8b8d4f8746..201b33d5f0 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -84,17 +84,25 @@ pub enum Process { /// Highlights and Shadows keep the local contrast of the tones they move: their edge-aware base /// is taken of a fine median of log luminance (issue #632). V2, + /// Pixel-scale sharpening with working Radius and Detail controls. + V3, + /// V3, with Contrast and Blacks on a raw's camera look calibrated to Lightroom: the + /// camera curve keeps V2 Whites and fitted pointwise operators follow it + /// (`lightcraft_pipeline::light_v3`, `docs/light-v3.md`). + V4, } impl Process { /// Every process, oldest first. - pub const ALL: [Process; 2] = [Process::V1, Process::V2]; - pub const LATEST: Process = Process::V2; + pub const ALL: [Process; 4] = [Process::V1, Process::V2, Process::V3, Process::V4]; + pub const LATEST: Process = Process::V4; pub const fn version(self) -> ProcessVersion { match self { Process::V1 => ProcessVersion(1), Process::V2 => ProcessVersion(2), + Process::V3 => ProcessVersion(3), + Process::V4 => ProcessVersion(4), } } } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0b203f7954..0d40c73184 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -40,6 +40,7 @@ log = { workspace = true } ab_glyph = { workspace = true } # Apply the font’s vertical substitutions and origins to Japanese watermarks. harfrust = { version = "0.13", default-features = false, features = ["std"] } +unicode-normalization = "0.1" unicode-segmentation = "1.13" lightcraft-segment = { workspace = true, optional = true } diff --git a/crates/engine/examples/render_bench.rs b/crates/engine/examples/render_bench.rs index 54b6cfe82d..789867c665 100644 --- a/crates/engine/examples/render_bench.rs +++ b/crates/engine/examples/render_bench.rs @@ -144,7 +144,7 @@ fn benchmark_load(args: &[String], n: usize, only: &str) { } println!(" {:<36} {}", "load_bytes(2560):", best(n, || drop(lightcraft_engine::files::load_bytes(&bytes, 2560).expect("load")))); let (loader, _) = lightcraft_engine::files::fs_hooks(); - println!(" {:<36} {}", "fs loader (2560, read+load):", best(n, || drop(loader(path, 2560).expect("load")))); + println!(" {:<36} {}", "fs loader (2560, read+load):", best(n, || drop(loader(path, 2560, None).expect("load")))); } } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 9a20fc3117..0c93a56a65 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -11,6 +11,7 @@ mod color; pub(crate) mod convert; mod cull; pub mod curves; +pub mod dcp_profiles; pub(crate) mod denoise; mod develop; mod edit; @@ -40,6 +41,7 @@ mod print; mod query; pub mod recheck; pub mod reload; +pub mod similar; mod slideshow; mod sync; mod xmp; @@ -153,6 +155,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(manage::specs()); v.extend(previews::specs()); v.extend(lut_profiles::specs()); + v.extend(dcp_profiles::specs()); v.extend(mask_effects::specs()); v.extend(cull::specs()); v.extend(convert::specs()); diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 383ed890d9..c847852261 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -105,43 +105,6 @@ fn burst_params(p: &Value) -> Result<(f64, f32)> { Ok((num("burstGap", BURST_GAP, MAX_GAP)?, num("similarity", SAME, 1.0)? as f32)) } -/// Find Similar: photos that look like `id` (signatures from thumbnail-level sources, cached by -/// content), most similar first; the view is filtered to them. -fn find_similar(s: &mut Session, p: &Value) -> Result { - const C: &str = "library.findSimilar"; - let id = super::photo_id(p, C)?.or(s.active()).ok_or_else(|| super::bad(C, "no photo"))?; - let min = p.get("similarity").and_then(Value::as_f64).unwrap_or(0.8) as f32; - let all: Vec = s.catalog.photos().filter(|q| q.in_library()).map(|q| q.id).collect(); - let sig = |s: &mut Session, id: PhotoId| -> Option<[f32; 64]> { - let key = s.catalog.photo(id).map(|p| crate::media::content_key(p))?; - if let Some(v) = s.signatures.get(&key) { - return Some(*v); - } - let src = s.source_now(id, crate::media::SourceLevel::Thumb).ok()?; - let v = lightcraft_pipeline::cull::signature(&src); - s.signatures.insert(key, v); - Some(v) - }; - let me = sig(s, id).ok_or_else(|| super::bad(C, "can't read the photo"))?; - let mut hits: Vec<(PhotoId, f32)> = Vec::new(); - for q in all { - if let Some(v) = sig(s, q) { - let sim = lightcraft_pipeline::cull::similarity(&me, &v); - if sim >= min { - hits.push((q, sim.clamp(0.0, 1.0))); - } - } - } - hits.sort_by(|a, b| b.1.total_cmp(&a.1)); - if p.get("filter").and_then(Value::as_bool).unwrap_or(true) { - s.shelved_filter = None; - s.filter.only = hits.iter().map(|h| h.0).collect(); - // an empty `only` means "no constraint": no hits is its own state that shows no photos - s.filter.only_none = s.filter.only.is_empty(); - } - Ok(json!({"photos": hits.iter().map(|(i, v)| json!({"id": i.0, "similarity": (v * 1000.0).round() / 1000.0})).collect::>()})) -} - pub fn specs() -> Vec { vec![ cmd!( @@ -149,9 +112,9 @@ pub fn specs() -> Vec { "Find Similar Photos", ["Photo"], None, - "{id?, similarity?: 0..1 (0.8), filter?: bool (true)} — photos that look like the active one (composition and tones), most similar first; filters the view to them (Clear Filters to go back) → {photos: [{id, similarity}]}", - always, - find_similar + "{id?, similarity?: 0..1 (0.8), filter?: bool (true)} — photos that look like the active one (composition and tones), most similar first; filters the view to them (Clear Filters to go back) → {photos: [{id, similarity}]}. In the app the photos are read on a worker thread under an activity row: a control request is answered with this when the search ends, and from a menu the answer is {background: true, count}", + super::similar::no_search_running, + super::similar::run ), cmd!( "photo.analyze", diff --git a/crates/engine/src/cmd/dcp_profiles.rs b/crates/engine/src/cmd/dcp_profiles.rs new file mode 100644 index 0000000000..a7c6d4c02c --- /dev/null +++ b/crates/engine/src/cmd/dcp_profiles.rs @@ -0,0 +1,212 @@ +//! Imported camera profiles: the user's own DNG Camera Profiles (`.dcp`), chosen like any other +//! profile (`develop.profile {id: "dcp:…"}`). Unlike the built-in looks and LUT profiles, which +//! work on developed colour, a camera profile replaces the raw file's colour model when it is +//! decoded (its matrices and hue/saturation map; see [`lightcraft_raw::dcp`]), so the photo's +//! source is decoded again when it changes. Other photos (JPEG, TIFF…) ignore it. +//! +//! A library on disk keeps a copy of each file in its `Profiles/` folder; the list lives in the +//! library's prefs and the profiles are parsed again when the library opens. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use super::{CommandSpec, always, bad, cmd, str_param}; +use crate::media::LoadedCameraProfile; +use crate::{Result, Session}; + +/// Profile id prefix of imported camera profiles. +pub const DCP_PREFIX: &str = "dcp:"; +/// Profile browser group of imported camera profiles. +pub const DCP_GROUP: &str = "Camera Profiles"; + +/// One imported camera profile. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DcpEntry { + /// `dcp:`. + pub id: String, + /// `ProfileName`, else the file name. + pub name: String, + /// The camera it was made for (`UniqueCameraModel`). + #[serde(default)] + pub camera_model: String, + /// The `.dcp` file (the library's copy when there is a library on disk). + pub file: String, +} + +/// Is `id` an imported camera profile id? +pub fn is_dcp_id(id: &str) -> bool { + id.starts_with(DCP_PREFIX) +} + +fn profiles_dir(s: &Session) -> Option { + s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Profiles")) +} + +/// Parse every imported camera profile again and hand them to the decoder (missing or damaged +/// files are skipped: photos using them develop with the file's own colour, and the profile is not offered or +/// accepted by `develop.profile` until its file is back; the entry is kept). +/// +/// A library's own copies are found in `profiles`, the `Profiles/` folder of the library being opened (`None`: not on +/// disk), wherever the saved path points: a library moved or restored elsewhere keeps its profiles (the saved path is +/// updated). +pub fn register_all(s: &mut Session, profiles: Option<&Path>) { + if let Some(dir) = profiles { + for p in &mut s.dcp_profiles { + if let Some(here) = library_copy(dir, &p.file) { + p.file = here.to_string_lossy().to_string(); + } + } + } + let loaded: Vec<(String, LoadedCameraProfile)> = s + .dcp_profiles + .iter() + .filter_map(|p| { + lightcraft_raw::dcp::read_dcp(Path::new(&p.file)).ok().and_then(|b| LoadedCameraProfile::parse(&b).ok()).map(|d| (p.id.clone(), d)) + }) + .collect(); + s.media.camera_profiles = loaded.into_iter().collect(); +} + +/// The copy of saved profile file `file` in the open library's profiles folder `dir`, when it is there under the +/// same name and `file` is not already it. +fn library_copy(dir: &Path, file: &str) -> Option { + let saved = Path::new(file); + let here = dir.join(saved.file_name()?); + (here != saved && here.is_file()).then_some(here) +} + +/// `.dcp` files under `paths` (folders searched). +pub fn dcp_files(paths: &[String]) -> Vec { + let is_dcp = |f: &Path| f.extension().is_some_and(|x| x.eq_ignore_ascii_case("dcp")); + let mut out = Vec::new(); + for p in paths { + let path = Path::new(p); + if path.is_dir() { + out.extend(crate::walk::files_in(path, None, crate::walk::Limits::default(), is_dcp).files); + } else if is_dcp(path) { + out.push(path.to_path_buf()); + } + } + out +} + +/// Import the `.dcp` files under `paths` → (imported `[{id, name, cameraModel}]`, failed `[[file, error]]`). +/// A profile already imported (same name, camera and bytes) is not added twice. +pub fn import_files(s: &mut Session, paths: &[String]) -> Result<(Vec, Vec)> { + const C: &str = "profile.import"; + let dir = profiles_dir(s); + if let Some(d) = &dir { + std::fs::create_dir_all(d).map_err(|e| bad(C, format!("{}: {e}", d.display())))?; + } + let (mut imported, mut failed) = (Vec::new(), Vec::new()); + for f in dcp_files(paths) { + let shown = f.display().to_string(); + let bytes = match lightcraft_raw::dcp::read_dcp(&f) { + Ok(b) => b, + Err(e) => { + failed.push(json!([shown, e.to_string()])); + continue; + } + }; + let loaded = match LoadedCameraProfile::parse(&bytes) { + Ok(p) => p, + Err(e) => { + failed.push(json!([shown, e.to_string()])); + continue; + } + }; + let profile = loaded.profile.clone(); + let stem = f.file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "Camera Profile".into()); + let name = if profile.name.trim().is_empty() { stem.clone() } else { profile.name.trim().to_string() }; + // the same profile imported again: keep the one there is + let same = s.dcp_profiles.iter().find(|p| { + p.name == name && p.camera_model == profile.camera_model && lightcraft_raw::dcp::read_dcp(Path::new(&p.file)).is_ok_and(|b| b == bytes) + }); + if let Some(p) = same { + imported.push(json!({"id": p.id, "name": p.name, "cameraModel": p.camera_model, "existing": true})); + continue; + } + // (the file name keeps profiles with the same ProfileName apart, e.g. per-body copies) + let slug = crate::presets::slug(&format!("{}-{stem}", profile.camera_model)); + let mut id = format!("{DCP_PREFIX}{slug}"); + let mut n = 2; + while s.dcp_profiles.iter().any(|x| x.id == id) { + id = format!("{DCP_PREFIX}{slug}-{n}"); + n += 1; + } + let file = match &dir { + Some(d) => { + let to = d.join(format!("{}.dcp", id.trim_start_matches(DCP_PREFIX))); + // a copy that fails (disk full, no access) fails this file only: the profiles + // copied before it stay imported, and nothing half-written is left behind + if let Err(e) = std::fs::write(&to, &bytes) { + if to.is_file() { + let _ = std::fs::remove_file(&to); + } + failed.push(json!([shown, format!("{}: {e}", to.display())])); + continue; + } + to.to_string_lossy().to_string() + } + // no library on disk: remember the original (the in-memory session ends with the app) + None => f.to_string_lossy().to_string(), + }; + s.media.camera_profiles.insert(id.clone(), loaded); + s.dcp_profiles.push(DcpEntry { id: id.clone(), name: name.clone(), camera_model: profile.camera_model.clone(), file }); + imported.push(json!({"id": id, "name": name, "cameraModel": profile.camera_model})); + } + Ok((imported, failed)) +} + +fn delete(s: &mut Session, p: &Value) -> Result { + const C: &str = "profile.deleteCamera"; + let id = str_param(p, "id").ok_or_else(|| bad(C, "missing id"))?.to_string(); + let Some(i) = s.dcp_profiles.iter().position(|x| x.id == id) else { + return Err(bad(C, format!("no imported camera profile `{id}`"))); + }; + // the library's copy goes first; a file outside the library is the user's and stays. A copy that can't be + // removed (in use, no access) keeps the profile, so the library never holds a file it no longer lists. A path + // with `..` in it is never the library's copy (it could lead out of the profiles folder). + if let Some(d) = profiles_dir(s) + && let Some(entry) = s.dcp_profiles.get(i) + && Path::new(&entry.file).starts_with(&d) + && !Path::new(&entry.file).components().any(|c| c == std::path::Component::ParentDir) + { + match std::fs::remove_file(&entry.file) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(bad(C, format!("could not delete {}: {e}", entry.file))), + } + } + s.dcp_profiles.remove(i); + s.media.camera_profiles.remove(&id); + s.profile_favorites.retain(|f| f != &id); + s.profile_recent.retain(|f| f != &id); + s.save_prefs()?; + Ok(json!({"deleted": id})) +} + +pub fn specs() -> Vec { + vec![ + cmd!( + query "profiles.camera", + "Imported Camera Profiles", + [], + None, + "{} → {profiles: [{id, name, cameraModel, file}]}: the imported .dcp camera profiles (use with develop.profile)", + always, + |s, _| Ok(json!({"profiles": s.dcp_profiles})) + ), + cmd!( + "profile.deleteCamera", + "Delete Imported Camera Profile", + [], + None, + "{id: dcp:…} — photos using it develop with their file's own colour again", + always, + delete + ), + ] +} diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index df1089925d..292ad27795 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -557,9 +557,17 @@ pub fn specs() -> Vec { }), cmd!("develop.profile", "Set Profile", [], None, "{id: profile id (see profiles.list), amount?: 0..200}", has_active, |s, p| { let id = str_param(p, "id").ok_or_else(|| bad("develop.profile", "missing id"))?.to_string(); - if !crate::presets::PROFILES.iter().any(|x| x.id == id) && !s.lut_profiles.iter().any(|x| x.id == id) { + if !crate::presets::PROFILES.iter().any(|x| x.id == id) + && !s.lut_profiles.iter().any(|x| x.id == id) + && !s.dcp_profiles.iter().any(|x| x.id == id) + { return Err(bad("develop.profile", format!("unknown profile `{id}`"))); } + // an imported camera profile whose file is missing or damaged: choosing it would develop with the + // file's own colour without saying so + if crate::cmd::dcp_profiles::is_dcp_id(&id) && !s.media.camera_profiles.contains_key(&id) { + return Err(bad("develop.profile", format!("camera profile `{id}` can't be used: its file is missing or damaged"))); + } edit(s, "develop.profile", "Profile", |d| { d.profile.id = id.clone(); d.profile.amount = f64_or(p, "amount", d.profile.amount).clamp(0.0, 200.0); @@ -570,7 +578,7 @@ pub fn specs() -> Vec { }), cmd!("profile.favorite", "Favorite Profile", [], None, "{id, favorite?: bool} (toggles when omitted)", always, |s, p| { let id = str_param(p, "id").ok_or_else(|| bad("profile.favorite", "missing id"))?.to_string(); - if crate::presets::profile(&id).is_none() && !s.lut_profiles.iter().any(|x| x.id == id) { + if crate::presets::profile(&id).is_none() && !s.lut_profiles.iter().any(|x| x.id == id) && !s.dcp_profiles.iter().any(|x| x.id == id) { return Err(bad("profile.favorite", format!("unknown profile `{id}`"))); } let on = s.profile_favorites.contains(&id); diff --git a/crates/engine/src/cmd/geocode.rs b/crates/engine/src/cmd/geocode.rs index 63f8d8f173..d811f80209 100644 --- a/crates/engine/src/cmd/geocode.rs +++ b/crates/engine/src/cmd/geocode.rs @@ -47,6 +47,10 @@ pub struct PlaceNames { shared: Arc>, /// (cities file, its size, its modification time, the parsed names). cache: Option<(PathBuf, u64, Option, Arc)>, + /// (folder, server) a download goes to instead of `/geonames` and GeoNames. Only + /// tests set it: no command can, so a client never chooses where the files land (#2575). + #[cfg(not(target_arch = "wasm32"))] + download_to: Option<(PathBuf, String)>, } impl PlaceNames { @@ -188,10 +192,7 @@ mod download { use lightcraft_geocode::{GEONAMES_BASE, GEONAMES_ZIP}; - use super::{ - Cancel, DownloadOutcome, GEONAMES_ATTRIBUTION, GEONAMES_FILES, GeoNames, PoisonError, Result, Session, Value, bad, dataset_dir, json, - str_param, - }; + use super::{Cancel, DownloadOutcome, GEONAMES_ATTRIBUTION, GEONAMES_FILES, GeoNames, PoisonError, Result, Session, Value, bad, json}; use crate::activity::Unit; const MAX_ZIP: u64 = 64 * 1024 * 1024; @@ -218,7 +219,11 @@ mod download { return Err("the downloaded place list is empty".into()); } let _ = std::fs::remove_file(staging.join(GEONAMES_ZIP)); - let write = |name: &str, data: &[u8]| std::fs::write(dir.join(name), data).map_err(|e| format!("could not save {name}: {e}")); + // a temp file renamed over the old one: never half-written, and a link in its place is + // replaced, not written through (#2575); not synced, as a download can always be repeated + let write = |name: &str, data: &[u8]| { + lightcraft_catalog::safe_file::write_atomic_nosync(&dir.join(name), data).map_err(|e| format!("could not save {name}: {e}")) + }; for name in &GEONAMES_FILES[1..] { // optional: without them states stay blank and countries are ISO codes match get(name, base, &staging, cancel, task).and_then(|()| std::fs::read(staging.join(name)).map_err(|e| e.to_string())) { @@ -241,10 +246,21 @@ mod download { } /// `metadata.downloadPlaceNames`: starts a background download (shown in the activity stack, cancellable). + /// The files always go to `/geonames`, from GeoNames: a control or MCP client naming a + /// folder (`dataset`) or a server (`base`) could have written a server's bytes into any folder (#2575). pub(super) fn start(s: &mut Session, p: &Value) -> Result { const C: &str = "metadata.downloadPlaceNames"; - let dir = dataset_dir(p).ok_or_else(|| bad(C, "no settings folder: give `dataset`"))?; - let base = str_param(p, "base").unwrap_or(GEONAMES_BASE).to_string(); + if p.get("dataset").is_some() || p.get("base").is_some() { + return Err(bad(C, "the place names always download from GeoNames into the settings folder: `dataset` and `base` are not accepted")); + } + let target = s.place_names.download_to.clone(); + let (dir, base) = match target { + Some(t) => t, + None => ( + crate::config::config_dir().ok_or_else(|| bad(C, "no settings folder to save the place names in"))?.join("geonames"), + GEONAMES_BASE.to_string(), + ), + }; if !base_allowed(&base) { return Err(bad(C, "`base` must be an https:// address")); } @@ -309,7 +325,7 @@ pub fn specs() -> Vec { "Download Place Names (GeoNames)", ["Photo"], None, - "{dataset?: folder} → {started, path, attribution} — downloads the GeoNames cities list (CC-BY 4.0, ~3 MB, from download.geonames.org) in the background for Fill Location from GPS; no photo data is sent", + "{} → {started, path, attribution} — downloads the GeoNames cities list (CC-BY 4.0, ~3 MB, from download.geonames.org) in the background for Fill Location from GPS, always into `geonames` in the settings folder (a folder or server named by the caller is refused); no photo data is sent", always, download::start )); @@ -468,7 +484,8 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] fn download(s: &mut Session, base: &str, dir: &Path) -> DownloadOutcome { - s.execute("metadata.downloadPlaceNames", &json!({"dataset": dir, "base": base})).unwrap(); + s.place_names.download_to = Some((dir.to_path_buf(), base.to_string())); + s.execute("metadata.downloadPlaceNames", &json!({})).unwrap(); assert!(s.place_names.downloading() || s.place_names.lock().unreported.is_some()); let started = std::time::Instant::now(); loop { @@ -493,7 +510,8 @@ mod tests { let base = serve(); let dir = std::env::temp_dir().join(format!("lightcraft-geocode-dl-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); - assert!(s.execute("metadata.downloadPlaceNames", &json!({"dataset": dir, "base": "http://example.com/"})).is_err()); + s.place_names.download_to = Some((dir.clone(), "http://example.com/".into())); + assert!(s.execute("metadata.downloadPlaceNames", &json!({})).is_err(), "plain http to another machine"); for bad in ["missing", "garbage", "short"] { let o = download(&mut s, &format!("{base}/{bad}/"), &dir); @@ -516,6 +534,53 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Issue #2575: a control or MCP client named the folder (`dataset`) and the server (`base`), + /// so it could have a server's bytes written as `cities15000.txt`, `admin1CodesASCII.txt` and + /// `countryInfo.txt` into any folder. Both are refused now, before anything starts. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_client_cannot_choose_where_the_place_names_download_to() { + let mut s = Session::with_demo(); + let dir = std::env::temp_dir().join(format!("lightcraft-geocode-elsewhere-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for p in [json!({"dataset": dir}), json!({"base": "https://example.com/"}), json!({"dataset": dir, "base": "https://example.com/"})] { + let e = s.execute("metadata.downloadPlaceNames", &p).unwrap_err().to_string(); + assert!(e.contains("not accepted"), "{p}: {e}"); + } + assert!(!s.place_names.downloading() && s.activity.list().is_empty(), "nothing started"); + assert!(!dir.exists(), "nothing written"); + } + + /// The downloaded files replace what is there by renaming a complete temp file over it, so a + /// link planted under one of their names is replaced, not followed to the file it points at. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_download_replaces_a_planted_link_instead_of_writing_through_it() { + let mut s = Session::with_demo(); + let base = serve(); + let root = std::env::temp_dir().join(format!("lightcraft-geocode-link-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let dir = root.join("geonames"); + std::fs::create_dir_all(&dir).unwrap(); + let victim = root.join("victim.txt"); + std::fs::write(&victim, "keep me").unwrap(); + let link = dir.join("countryInfo.txt"); + #[cfg(unix)] + let linked = std::os::unix::fs::symlink(&victim, &link); + #[cfg(windows)] + let linked = std::os::windows::fs::symlink_file(&victim, &link); + if let Err(e) = linked { + lightcraft_testkit::skip!(System, "can't create a symbolic link here: {e}"); + let _ = std::fs::remove_dir_all(&root); + return; + } + assert_eq!(download(&mut s, &format!("{base}/good/"), &dir), DownloadOutcome::Done(2)); + assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep me", "the link's target is untouched"); + assert!(!std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link is now the downloaded file"); + assert!(std::fs::read_to_string(&link).unwrap().contains("France")); + let _ = std::fs::remove_dir_all(&root); + } + #[test] fn download_base_is_https_or_loopback_only() { assert!(download::base_allowed("https://download.geonames.org/export/dump/")); diff --git a/crates/engine/src/cmd/lut_profiles.rs b/crates/engine/src/cmd/lut_profiles.rs index 56a0169a10..3f3c2b3428 100644 --- a/crates/engine/src/cmd/lut_profiles.rs +++ b/crates/engine/src/cmd/lut_profiles.rs @@ -77,11 +77,14 @@ fn cube_files(paths: &[String]) -> (Vec<(String, String, Option)>, Vec out.push((stem(path), t, None)), Err(e) => failed.push(json!([stem(path), e.to_string()])), } + } else if !path.extension().is_some_and(|x| x.eq_ignore_ascii_case("dcp")) { + // (a .dcp is a camera profile: `dcp_profiles::import_files` takes it) + failed.push(json!([stem(path), "not a .cube, .dcp or .zip file"])); } } (out, failed) @@ -133,6 +136,10 @@ fn import(s: &mut Session, p: &Value) -> Result { s.lut_profiles.push(LutProfile { id: id.clone(), name: display.clone(), group: group.clone(), file }); imported.push(json!({"id": id, "name": display, "group": group})); } + // camera profiles (.dcp) among them + let (cameras, camera_failed) = super::dcp_profiles::import_files(s, &paths)?; + imported.extend(cameras); + failed.extend(camera_failed); s.save_prefs()?; // presets that name these profiles use them now crate::profile_refs::refresh(s); @@ -146,12 +153,15 @@ pub fn specs() -> Vec { "Import Profiles", [], None, - "{paths: [.cube file, folder or .zip]} — 3D LUTs become creative profiles (Amount 0–200 %; rendered on the CPU) in the profile browser's groups (folder / zip name, else Imported) → {imported: [{id, name, group}], failed}", + "{paths: [.cube / .dcp file, folder or .zip]} — 3D LUTs become creative profiles (Amount 0–200 %; rendered on the CPU) in the profile browser's groups (folder / zip name, else Imported); DNG camera profiles (.dcp, the user's own) become camera profiles (dcp: ids, group Camera Profiles) that replace a raw file's colour model when it is decoded → {imported: [{id, name, group | cameraModel}], failed}", always, import ), - cmd!("profile.deleteImported", "Delete Imported Profile", [], None, "{id: lut:…}", always, |s, p| { + cmd!("profile.deleteImported", "Delete Imported Profile", [], None, "{id: lut:… | dcp:…}", always, |s, p| { let id = str_param(p, "id").ok_or_else(|| bad("profile.deleteImported", "missing id"))?.to_string(); + if super::dcp_profiles::is_dcp_id(&id) { + return s.execute("profile.deleteCamera", p); + } let Some(i) = s.lut_profiles.iter().position(|x| x.id == id) else { return Err(bad("profile.deleteImported", format!("no imported profile `{id}`"))); }; diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index dc1f2c864a..95aff90b79 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -360,8 +360,9 @@ struct SmartCounts { fn original_only(source: crate::media::SourceRef) -> Option { use crate::media::SourceRef; match source { + // (a smart preview keeps the file's own colour: an imported camera profile is applied when the original is read) SourceRef::File { path, max_edge, loader, denoise, .. } => { - Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, reduced: None }) + Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, camera_profile: None, reduced: None }) } SourceRef::Loaded(d) if d.info.is_some() && !d.from_proxy && !d.reduced => Some(SourceRef::Loaded(d)), _ => None, @@ -486,7 +487,9 @@ fn smart(s: &mut Session, p: &Value) -> Result { continue; } let path = crate::smart::sharded_file_path(&dir, &ph); - let source = (!discard).then(|| s.media.source_ref(&ph, crate::media::SourceLevel::Preview)); + // (a smart preview keeps the file's own colour: never built with the photo's imported camera profile, nor + // from a cached source developed with it) + let source = (!discard).then(|| s.media.source_ref_without_profile(&ph, crate::media::SourceLevel::Preview)); jobs.push((id, path, source, preview_fitted_look(&ph))); } let custom = s.smart_previews_dir.is_some(); @@ -720,8 +723,15 @@ mod tests { let mut jobs = jobs_for(&mut s, id, Some(512)); assert_eq!(jobs.len(), 2, "view and thumbnail"); assert!(jobs[0].view_cache.is_some(), "the view renders first"); - jobs[1].source = - SourceRef::File { path: "/nonexistent/photo.arw".into(), max_edge: 512, loader: None, fallback: None, denoise: None, reduced: None }; + jobs[1].source = SourceRef::File { + path: "/nonexistent/photo.arw".into(), + max_edge: 512, + loader: None, + fallback: None, + denoise: None, + camera_profile: None, + reduced: None, + }; assert!(run_photo(jobs), "the thumbnail rendered from the view's decoded source"); } diff --git a/crates/engine/src/cmd/similar.rs b/crates/engine/src/cmd/similar.rs new file mode 100644 index 0000000000..fd608ac2b7 --- /dev/null +++ b/crates/engine/src/cmd/similar.rs @@ -0,0 +1,399 @@ +//! Find Similar (`library.findSimilar`), split so the app can read the photos on a worker thread: the +//! first search reads a thumbnail-level source of every photo in the library, and in a large +//! library that froze the window for as long as it took (issue #3468). [`plan`] lists what is to be +//! read (no file-system calls), [`measure`] reads it without the session (cancellable, with +//! progress), [`keep`] adds what it found to the session's signatures and [`apply`] answers from +//! those. The command itself (the CLI, MCP without an app) does all of them at once. +//! +//! A search keeps no decoded source and learns nothing from one: it only looks, and in a large library +//! it would push out of memory what the grid and the loupe are showing. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Mutex, PoisonError}; + +use lightcraft_catalog::PhotoId; +use serde_json::{Value, json}; + +use super::bad; +use crate::media::{SourceLevel, SourceRef, content_key}; +use crate::{Result, Session}; + +const C: &str = "library.findSimilar"; + +/// The kind of the row in the activity stack that a search on a worker thread holds. +pub const KIND: &str = "similar"; + +/// A content key and that content's look-alike signature. +pub type Signature = (String, [f32; 64]); + +/// Whether a search can start (the command's `enabled`): one at a time, for what a second one would +/// read the first is reading. +pub fn no_search_running(s: &Session) -> std::result::Result<(), String> { + if s.activity.list().iter().any(|r| r.kind == KIND) { Err("a search for similar photos is already running".to_string()) } else { Ok(()) } +} + +/// What a search asks. +#[derive(Debug)] +pub struct Search { + id: PhotoId, + min: f32, + filter: bool, +} + +/// A content whose signature isn't known yet, and how to read it: from the first of its photos that +/// can be read (a copy that is offline gives way to the next). +struct Content { + key: String, + sources: Vec, +} + +/// What a search has to read: the searched photo first, as nothing can be compared without it. +pub struct Reads { + me: Option, + rest: Vec, +} + +impl Reads { + /// How many contents are to be read. + pub fn len(&self) -> usize { + self.rest.len().saturating_add(usize::from(self.me.is_some())) + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +/// The search `p` asks for and what it has to read, once for each content not known yet. No +/// file-system calls. +pub fn plan(s: &mut Session, p: &Value) -> Result<(Search, Reads)> { + let id = super::photo_id(p, C)?.or(s.active()).ok_or_else(|| bad(C, "no photo"))?; + let min = p.get("similarity").and_then(Value::as_f64).unwrap_or(0.8) as f32; + let filter = p.get("filter").and_then(Value::as_bool).unwrap_or(true); + let photo = s.catalog.photo(id).ok_or_else(|| bad(C, "can't read the photo"))?; + let my_key = content_key(photo); + let me = + (!s.signatures.contains_key(&my_key)).then(|| Content { sources: vec![s.media.source_ref(photo, SourceLevel::Thumb)], key: my_key.clone() }); + let mut rest: Vec = Vec::new(); + let mut at = std::collections::HashMap::new(); + for q in s.catalog.photos().filter(|q| q.in_library()) { + let key = content_key(q); + // (the searched photo's content is known by the time these are read, or the search has ended) + if key == my_key || s.signatures.contains_key(&key) { + continue; + } + let source = s.media.source_ref(q, SourceLevel::Thumb); + match at.get(&key).and_then(|i: &usize| rest.get_mut(*i)) { + Some(content) => content.sources.push(source), + None => { + at.insert(key.clone(), rest.len()); + rest.push(Content { key, sources: vec![source] }); + } + } + } + Ok((Search { id, min, filter }, Reads { me, rest })) +} + +/// `content`'s signature, or `None` when none of its photos can be read or `cancel` is set first. A +/// decoder's panic is that photo's failure, not the search's. +fn signature_of(content: &Content, cancel: &AtomicBool) -> Option<[f32; 64]> { + content.sources.iter().find_map(|source| { + if cancel.load(Ordering::Relaxed) { + return None; + } + crate::guard::catch("Find Similar", || { + crate::memory::in_background(|| source.load_source()).ok().map(|decoded| lightcraft_pipeline::cull::signature(&decoded.image)) + }) + .ok() + .flatten() + }) +} + +/// Read what [`plan`] listed, several photos at once. Doesn't touch the session. `progress(done)` is +/// called from the threads doing the reading; once `cancel` is set no further file is started, and +/// what was read until then comes back. A searched photo that can't be read ends it there. +pub fn measure(reads: Reads, cancel: &AtomicBool, progress: &(dyn Fn(usize) + Sync)) -> Vec { + let found = Mutex::new(Vec::with_capacity(reads.len().min(4096))); + let done = AtomicUsize::new(0); + let keep = |key: String, v: [f32; 64]| found.lock().unwrap_or_else(PoisonError::into_inner).push((key, v)); + if let Some(me) = reads.me { + let Some(v) = signature_of(&me, cancel) else { return Vec::new() }; + keep(me.key, v); + done.store(1, Ordering::Relaxed); + progress(1); + } + let lanes = crate::export::export_parallelism(reads.rest.len()); + let queue = Mutex::new(reads.rest.into_iter()); + let work = || { + while !cancel.load(Ordering::Relaxed) { + let next = queue.lock().unwrap_or_else(PoisonError::into_inner).next(); + let Some(content) = next else { break }; + if let Some(v) = signature_of(&content, cancel) { + keep(content.key, v); + } + progress(done.fetch_add(1, Ordering::Relaxed).saturating_add(1)); + } + }; + #[cfg(not(target_arch = "wasm32"))] + std::thread::scope(|sc| { + for k in 1..lanes.max(1) { + // a lane that can't start leaves its photos to the others (and to this thread) + if std::thread::Builder::new().name(format!("similar-{k}")).spawn_scoped(sc, work).is_err() { + break; + } + } + work(); + }); + #[cfg(target_arch = "wasm32")] + { + let _ = lanes; + work(); + } + found.into_inner().unwrap_or_else(PoisonError::into_inner) +} + +/// Add what [`measure`] found to the signatures, also when the search was stopped: they hold for the +/// contents they were read from, and the next search doesn't read those again. +pub fn keep(s: &mut Session, found: Vec) { + s.signatures.extend(found); +} + +/// Answer `search` from the signatures known now, most similar first, and filter the view to the +/// photos found. A photo with none (it can't be read, or came after the [`plan`]) isn't compared. +pub fn apply(s: &mut Session, search: &Search) -> Result { + let known = s.catalog.photo(search.id).and_then(|photo| s.signatures.get(&content_key(photo))); + let me = *known.ok_or_else(|| bad(C, "can't read the photo"))?; + let mut hits: Vec<(PhotoId, f32)> = Vec::new(); + for q in s.catalog.photos().filter(|q| q.in_library()) { + if let Some(v) = s.signatures.get(&content_key(q)) { + let sim = lightcraft_pipeline::cull::similarity(&me, v); + if sim >= search.min { + hits.push((q.id, sim.clamp(0.0, 1.0))); + } + } + } + hits.sort_by(|a, b| b.1.total_cmp(&a.1)); + if search.filter { + s.shelved_filter = None; + s.filter.only = hits.iter().map(|h| h.0).collect(); + // an empty `only` means "no constraint": no hits is its own state that shows no photos + s.filter.only_none = s.filter.only.is_empty(); + } + Ok(json!({"photos": hits.iter().map(|(i, v)| json!({"id": i.0, "similarity": (v * 1000.0).round() / 1000.0})).collect::>()})) +} + +/// Find Similar: photos that look like `id` (signatures from thumbnail-level sources, cached by +/// content), most similar first; the view is filtered to them. +pub(super) fn run(s: &mut Session, p: &Value) -> Result { + let (search, reads) = plan(s, p)?; + let found = measure(reads, &AtomicBool::new(false), &|_| {}); + keep(s, found); + apply(s, &search) +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::sync::Arc; + + use lightcraft_catalog::{Op, Photo, Source}; + use lightcraft_raster::Rgb32f; + + use super::*; + + /// Reads per file, the files that can't be read and the file whose decoder panics. + #[derive(Default)] + struct Files { + reads: Mutex>, + unreadable: Mutex>, + panics: Mutex>, + /// Set once this many reads have started. + cancel_after: Option<(usize, Arc)>, + } + + impl Files { + fn reads_of(&self, path: &str) -> usize { + self.reads.lock().unwrap().get(path).copied().unwrap_or(0) + } + fn reads(&self) -> usize { + self.reads.lock().unwrap().values().sum() + } + } + + /// A session of photos `/p/.jpg`, each with its content hash when it has one. Odd numbers + /// in a name mean a picture that gets brighter to the right, others one that does downwards. + fn session(photos: &[(&str, Option<&str>)], files: Files) -> (Session, Arc) { + let files = Arc::new(files); + let mut s = Session::new(); + for (i, (name, hash)) in photos.iter().enumerate() { + let source = Source::File { path: format!("/p/{name}.jpg") }; + let mut p = Photo::new(PhotoId(i as u64 + 1), source, &format!("{name}.jpg"), "JPEG", 64, 64, "2026-01-01T00:00:00"); + p.content_hash = hash.map(str::to_string); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + let seen = files.clone(); + s.media.file_loader = Some(Arc::new(move |path: &str, _, _| { + let started = { + let mut reads = seen.reads.lock().unwrap(); + *reads.entry(path.to_string()).or_default() += 1; + reads.values().sum::() + }; + if let Some((after, cancel)) = &seen.cancel_after + && started >= *after + { + cancel.store(true, Ordering::SeqCst); + } + if seen.panics.lock().unwrap().as_deref() == Some(path) { + panic!("a decoder fails on {path}"); + } + if seen.unreadable.lock().unwrap().iter().any(|f| f == path) { + return Err(format!("{path}: gone")); + } + let across = path.bytes().filter(u8::is_ascii_digit).any(|b| b % 2 == 1); + let image = Rgb32f::from_fn(64, 64, |x, y| { + let v = if across { x } else { y }; + [v as f32 / 64.0; 3] + }); + Ok((image, Default::default())) + })); + (s, files) + } + + fn ids(r: &Value) -> Vec { + r["photos"].as_array().unwrap().iter().map(|h| h["id"].as_u64().unwrap()).collect() + } + + /// A search on a worker thread holds a row of its kind: the command is off until the row goes. + #[test] + fn a_running_search_turns_the_command_off() { + let (mut s, files) = session(&[("a1", None), ("b2", None)], Files::default()); + let row = s.activity.start(KIND, "Find Similar Photos", crate::activity::Cancel::No); + let off = s.commands().into_iter().find(|c| c.id == C).is_some_and(|c| !c.enabled); + assert!(off, "the menu shows it off"); + assert!(matches!(s.execute(C, &json!({"id": 1})), Err(crate::EngineError::Disabled(..)))); + assert_eq!(files.reads(), 0); + drop(row); + assert!(s.execute(C, &json!({"id": 1})).is_ok()); + } + + #[test] + fn making_the_plan_reads_no_file() { + let (mut s, files) = session(&[("a1", None), ("b2", None), ("c1", None)], Files::default()); + let (_, reads) = plan(&mut s, &json!({"id": 1})).unwrap(); + assert_eq!(reads.len(), 3); + assert_eq!(files.reads(), 0); + } + + #[test] + fn the_command_reads_each_photo_and_finds_the_ones_alike() { + let names: Vec = (0..40).map(|i| format!("p{i}")).collect(); + let photos: Vec<(&str, Option<&str>)> = names.iter().map(|n| (n.as_str(), None)).collect(); + let (mut s, files) = session(&photos, Files::default()); + let r = s.execute("library.findSimilar", &json!({"id": 1})).unwrap(); + assert_eq!(files.reads(), 40, "each once"); + assert!(ids(&r).contains(&1) && ids(&r).len() < 40, "{r}"); + // known now: no file is read again + let again = s.execute("library.findSimilar", &json!({"id": 1})).unwrap(); + assert_eq!(files.reads(), 40); + assert_eq!(ids(&again), ids(&r)); + } + + #[test] + fn a_content_is_read_once_and_an_unreadable_copy_gives_way_to_the_next() { + let files = Files::default(); + files.unreadable.lock().unwrap().push("/p/copy2.jpg".into()); + let photos = [("me1", None), ("copy2", Some("h")), ("copy4", Some("h")), ("copy6", Some("h"))]; + let (mut s, files) = session(&photos, files); + let r = s.execute("library.findSimilar", &json!({"id": 1, "similarity": -1.0})).unwrap(); + assert_eq!(files.reads_of("/p/copy2.jpg"), 1); + assert_eq!(files.reads_of("/p/copy4.jpg"), 1, "the next copy stands in"); + assert_eq!(files.reads_of("/p/copy6.jpg"), 0, "its content is known by then"); + assert_eq!(ids(&r).len(), 4, "every copy is compared: {r}"); + } + + #[test] + fn a_searched_photo_that_cannot_be_read_ends_the_search_before_any_other_is_read() { + let files = Files::default(); + files.unreadable.lock().unwrap().push("/p/me1.jpg".into()); + let (mut s, files) = session(&[("me1", None), ("b2", None), ("c1", None)], files); + let e = s.execute("library.findSimilar", &json!({"id": 1})).unwrap_err(); + assert!(e.to_string().contains("can't read the photo"), "{e}"); + assert_eq!(files.reads(), 1, "only the searched photo"); + assert!(s.signatures.is_empty()); + assert_eq!(s.filter, Default::default(), "the view stays as it was"); + } + + #[test] + fn a_photo_nobody_has_is_refused_at_once() { + let (mut s, files) = session(&[("a1", None)], Files::default()); + assert!(matches!(plan(&mut s, &json!({"id": 99})), Err(crate::EngineError::BadParams { .. }))); + assert_eq!(files.reads(), 0); + } + + #[test] + fn a_photo_whose_decoder_panics_is_left_out_and_the_search_goes_on() { + let files = Files::default(); + *files.panics.lock().unwrap() = Some("/p/bad3.jpg".into()); + let (mut s, _) = session(&[("me1", None), ("bad3", None), ("ok1", None), ("ok5", None)], files); + let r = s.execute("library.findSimilar", &json!({"id": 1, "similarity": -1.0})).unwrap(); + assert_eq!(ids(&r).len(), 3, "{r}"); + assert!(!ids(&r).contains(&2), "{r}"); + } + + /// Stopped after some reads: what was read is kept, the view is left alone, and the next search + /// reads only the rest. + #[test] + fn a_stopped_search_keeps_what_it_read_and_the_next_reads_the_rest() { + let cancel = Arc::new(AtomicBool::new(false)); + let files = Files { cancel_after: Some((5, cancel.clone())), ..Default::default() }; + let names: Vec = (0..64).map(|i| format!("p{i}")).collect(); + let photos: Vec<(&str, Option<&str>)> = names.iter().map(|n| (n.as_str(), None)).collect(); + let (mut s, _) = session(&photos, files); + let (_, reads) = plan(&mut s, &json!({"id": 1})).unwrap(); + let found = measure(reads, &cancel, &|_| {}); + let read = found.len(); + assert!((1..64).contains(&read), "stopped along the way: {read}"); + keep(&mut s, found); + assert_eq!(s.filter, Default::default()); + let (_, rest) = plan(&mut s, &json!({"id": 1})).unwrap(); + assert_eq!(rest.len(), 64 - read); + } + + #[test] + fn a_stopped_search_reads_nothing_more() { + let (mut s, files) = session(&[("a1", None), ("b2", None), ("c1", None)], Files::default()); + let (_, reads) = plan(&mut s, &json!({"id": 1})).unwrap(); + assert!(measure(reads, &AtomicBool::new(true), &|_| {}).is_empty()); + assert_eq!(files.reads(), 0); + } + + /// What changed while the files were read: a photo deleted since isn't an answer, and one added + /// since has no signature to compare. + #[test] + fn photos_that_changed_during_the_search_are_answered_as_they_are_now() { + let (mut s, _) = session(&[("a1", None), ("b1", None), ("c1", None)], Files::default()); + let (search, reads) = plan(&mut s, &json!({"id": 1, "similarity": -1.0})).unwrap(); + let found = measure(reads, &AtomicBool::new(false), &|_| {}); + s.catalog.apply(Op::RemovePhoto { id: PhotoId(2) }).unwrap(); + let added = Photo::new(PhotoId(9), Source::File { path: "/p/new1.jpg".into() }, "new1.jpg", "JPEG", 64, 64, "2026-01-01T00:00:00"); + s.catalog.apply(Op::AddPhoto { photo: Box::new(added) }).unwrap(); + keep(&mut s, found); + let mut answer = ids(&apply(&mut s, &search).unwrap()); + answer.sort_unstable(); + assert_eq!(answer, [1, 3]); + } + + #[test] + fn progress_counts_every_content_read_or_not() { + let files = Files::default(); + files.unreadable.lock().unwrap().push("/p/b2.jpg".into()); + let (mut s, _) = session(&[("a1", None), ("b2", None), ("c1", None), ("d2", None)], files); + let (_, reads) = plan(&mut s, &json!({"id": 1})).unwrap(); + let top = AtomicUsize::new(0); + let found = measure(reads, &AtomicBool::new(false), &|done| { + top.fetch_max(done, Ordering::SeqCst); + }); + assert_eq!(top.load(Ordering::SeqCst), 4); + assert_eq!(found.len(), 3); + } +} diff --git a/crates/engine/src/export/params.rs b/crates/engine/src/export/params.rs index 795d8f3672..34397fad3c 100644 --- a/crates/engine/src/export/params.rs +++ b/crates/engine/src/export/params.rs @@ -1,4 +1,5 @@ use super::options::{Conflict, DestinationMode, ExportFormat, HdrCurve, MetadataPolicy, Resize, ResizeMode, SharpenAmount, SharpenFor}; +use super::place::clean_subfolder; use super::prepare::DngCompression; use super::watermark::{Anchor, Watermark}; use super::{ExportOptions, JxlColour, JxlEffort, JxlOptions, OutputDepth, OutputSpace, TiffCompression}; @@ -429,7 +430,7 @@ impl ExportOptions { naming: s("naming").map_or(d.naming, str::to_string), start_number: u("startNumber").map_or(d.start_number, |v| v.min(999_999) as u32), destination_mode: s("destinationMode").and_then(DestinationMode::parse).unwrap_or(d.destination_mode), - subfolder: s("subfolder").map_or(d.subfolder, |v| v.trim().replace(['\\', ':', '\0'], "_")), + subfolder: s("subfolder").map_or(d.subfolder, clean_subfolder), conflict: s("conflict").and_then(Conflict::parse).unwrap_or(d.conflict), tiff_compression: match s("tiffCompression").map(str::to_ascii_lowercase).as_deref() { Some("none") => TiffCompression::None, diff --git a/crates/engine/src/export/place.rs b/crates/engine/src/export/place.rs index d223a3a791..c36f5e26bc 100644 --- a/crates/engine/src/export/place.rs +++ b/crates/engine/src/export/place.rs @@ -60,6 +60,14 @@ fn join_path(a: &str, b: &str) -> String { if a.is_empty() { b.to_string() } else { format!("{}/{b}", a.trim_end_matches('/')) } } +/// A subfolder that stays inside the destination folder (issue #2571): `\`, `:` and NUL become `_` +/// (so no drive, root or Windows separator), and empty, `.` and `..` parts are dropped; `a/b` still +/// nests. Applied where the folder is used, so presets and the Export dialog's field are covered too. +pub(super) fn clean_subfolder(s: &str) -> String { + let s = s.trim().replace(['\\', ':', '\0'], "_"); + s.split('/').map(str::trim).filter(|p| !p.is_empty() && *p != "." && *p != "..").collect::>().join("/") +} + impl<'a> Placer<'a> { pub(super) fn new( o: &'a ExportOptions, @@ -89,7 +97,8 @@ impl<'a> Placer<'a> { d.to_string() } }; - Ok(if self.o.subfolder.is_empty() { base } else { join_path(&base, &self.o.subfolder) }) + let sub = clean_subfolder(&self.o.subfolder); + Ok(if sub.is_empty() { base } else { join_path(&base, &sub) }) } /// Place photo `photo`'s export result (file `name`, its original in `source_dir`): write it diff --git a/crates/engine/src/export/tests.rs b/crates/engine/src/export/tests.rs index b8482a7df2..86600ddb57 100644 --- a/crates/engine/src/export/tests.rs +++ b/crates/engine/src/export/tests.rs @@ -912,6 +912,8 @@ fn ramp(depth: OutputDepth, space: OutputSpace) -> lightcraft_pipeline::Rendered fn distinct_levels(bytes: &[u8]) -> (usize, lightcraft_codecs::Decoded) { let d = lightcraft_codecs::decode(bytes, Default::default()).expect("decodes"); let mut v: Vec = (0..d.image.width).map(|x| d.image.get(x, 1)[1].to_bits()).collect(); + // sorted first: 8-bit output is dithered, so equal levels aren't all side by side + v.sort_unstable(); v.dedup(); (v.len(), d) } diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 5ab68ff0eb..4f09be75ba 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -11,6 +11,8 @@ use lightcraft_pipeline::SourceInfo; use lightcraft_raster::Rgb32f; use lightcraft_raster::resample::{Filter, fit}; +use lightcraft_raw::dcp::DcpProfile; + use crate::media::{DenoiseSpec, FileLoader, FileProbe, PairLoader, PreviewLoader, ProbeInfo, ReducedLoader}; mod colour; @@ -25,7 +27,7 @@ pub(crate) use colour::clipped_white; use fs::quick_image_srgb; pub use fs::{fs_hooks, fs_pair_loader, fs_reduced_loader}; pub(crate) use load::{DngWhite, WbScaleOf, dng_tone_curve}; -pub use load::{load_bytes, load_vec, load_vec_pair, load_vec_reduced}; +pub use load::{load_bytes, load_bytes_with, load_vec, load_vec_pair, load_vec_reduced}; #[cfg(test)] use preview::PLAN_PREFIX; pub(crate) use preview::decode_raw_preview; diff --git a/crates/engine/src/files/fs.rs b/crates/engine/src/files/fs.rs index 549c83b19c..05784d542b 100644 --- a/crates/engine/src/files/fs.rs +++ b/crates/engine/src/files/fs.rs @@ -1,7 +1,7 @@ use super::load::{load_vec, load_vec_pair, load_vec_reduced}; use super::preview::{fit_box, fs_preview_loader, preview_orientation}; use super::probe::probe_bytes; -use super::{Arc, DenoiseSpec, FileLoader, FileProbe, Filter, PairLoader, ReducedLoader, fit}; +use super::{Arc, DcpProfile, DenoiseSpec, FileLoader, FileProbe, Filter, PairLoader, ReducedLoader, fit}; /// The file's first [`lightcraft_raw::PREVIEW_PREFIX`] bytes (or the whole file when it is shorter), /// which is what every format [`lightcraft_raw::bounded_preview`] covers keeps its pointer in. @@ -54,13 +54,13 @@ pub(super) fn quick_image_srgb(header: &[u8], window: &[u8], adobe_rgb: bool, ma /// The filesystem-backed [`PairLoader`]: the file is read and decoded once, and developed as usual and from the photo's /// denoised picture. It holds two pictures at once, so it counts for more at the memory gate than a plain load. pub fn fs_pair_loader() -> PairLoader { - Arc::new(|path: &str, max_edge: usize, spec: &DenoiseSpec| { + Arc::new(|path: &str, max_edge: usize, spec: &DenoiseSpec, dcp: Option<&DcpProfile>| { let len = std::fs::metadata(path).map(|m| m.len() as usize).unwrap_or(0); let weight = len * if max_edge <= crate::media::SourceLevel::Thumb.max_edge() { 4 } else { 10 }; let gate = crate::memory::work_gate(); let _permit = if crate::memory::is_background() { gate.acquire(weight) } else { gate.acquire_urgent(weight) }; let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?; - let r = load_vec_pair(bytes, max_edge, spec); + let r = load_vec_pair(bytes, max_edge, spec, dcp); crate::memory::release(); r }) @@ -74,7 +74,8 @@ pub fn fs_pair_loader() -> PairLoader { /// interactive loads (the loupe, exports) never wait — they are counted, so background work /// yields to them. pub fn fs_hooks() -> (FileLoader, FileProbe) { - let loader: FileLoader = Arc::new(|path: &str, max_edge: usize| fs_load(path, max_edge, |bytes| load_vec(bytes, max_edge))); + let loader: FileLoader = + Arc::new(|path: &str, max_edge: usize, dcp: Option<&DcpProfile>| fs_load(path, max_edge, |bytes| load_vec(bytes, max_edge, dcp))); let probe: FileProbe = Arc::new(|path: &str| { use std::io::Read; // one open, then everything from the open file: its size and modification time are not @@ -94,7 +95,7 @@ pub fn fs_hooks() -> (FileLoader, FileProbe) { /// The filesystem [`ReducedLoader`]: [`load_vec_reduced`] of the file, gated like [`fs_hooks`]' loader. pub fn fs_reduced_loader() -> ReducedLoader { - Arc::new(|path: &str, max_edge: usize| fs_load(path, max_edge, |bytes| load_vec_reduced(bytes, max_edge))) + Arc::new(|path: &str, max_edge: usize, dcp: Option<&DcpProfile>| fs_load(path, max_edge, |bytes| load_vec_reduced(bytes, max_edge, dcp))) } /// Read `path` and `load` it, waiting on [`crate::memory::work_gate`] as [`fs_hooks`] explains. diff --git a/crates/engine/src/files/load.rs b/crates/engine/src/files/load.rs index 428a84eda9..004723dca8 100644 --- a/crates/engine/src/files/load.rs +++ b/crates/engine/src/files/load.rs @@ -1,7 +1,7 @@ use super::colour::bin_factor; use super::preview::{fit_box, load_embedded_preview}; use super::probe::preview_reason; -use super::{Arc, CameraColourModel, DenoiseSpec, Filter, HIGHLIGHT_CLIP, Orientation, Rgb32f, SourceInfo, fit, xy_to_temp_tint}; +use super::{Arc, CameraColourModel, DcpProfile, DenoiseSpec, Filter, HIGHLIGHT_CLIP, Orientation, Rgb32f, SourceInfo, fit, xy_to_temp_tint}; /// Decode a file into a linear Rec.2020 image no larger than `max_edge`, oriented. /// @@ -9,27 +9,41 @@ use super::{Arc, CameraColourModel, DenoiseSpec, Filter, HIGHLIGHT_CLIP, Orienta /// instead of each one waking the pool from outside and waiting for it (which costs more than the /// loops themselves when the machine is busy). pub fn load_bytes(bytes: &[u8], max_edge: usize) -> Result<(Rgb32f, SourceInfo), String> { - rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false).map(|(img, _, info, _)| (img, info))) + rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false, None).map(|(img, _, info, _)| (img, info))) +} + +/// [`load_bytes`] developing a raw file with an imported camera profile (`dcp`) in place of its own colour model. +pub fn load_bytes_with(bytes: &[u8], max_edge: usize, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo), String> { + rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false, dcp).map(|(img, _, info, _)| (img, info))) } /// [`load_bytes`] taking the file's bytes: a raw file's bytes are freed as soon as it is decoded /// (less memory held while it is developed). -pub fn load_vec(bytes: Vec, max_edge: usize) -> Result<(Rgb32f, SourceInfo), String> { - rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, false).map(|(img, _, info, _)| (img, info))) +pub fn load_vec(bytes: Vec, max_edge: usize, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo), String> { + rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, false, dcp).map(|(img, _, info, _)| (img, info))) } /// [`load_vec`] for a thumbnail: a DNG that keeps reduced-resolution copies of its raw image (Lightroom's HDR and /// panorama merges) develops the smallest that covers `max_edge` instead of the whole image. The flag says whether /// it did: such a picture is not the full image, and an export never renders from it. -pub fn load_vec_reduced(bytes: Vec, max_edge: usize) -> Result<(Rgb32f, SourceInfo, bool), String> { - rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, true).map(|(img, _, info, reduced)| (img, info, reduced))) +pub fn load_vec_reduced(bytes: Vec, max_edge: usize, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo, bool), String> { + rayon::scope(move |_| { + load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, true, dcp).map(|(img, _, info, reduced)| (img, info, reduced)) + }) } /// [`load_vec`] that also develops the photo's cached denoised picture (`spec`) from the same decode: the plain /// picture, the denoised one (`None` when it cannot be read or does not fit this raw: the plain one is then all /// there is) and the source facts. Both pictures are the same size. -pub fn load_vec_pair(bytes: Vec, max_edge: usize, spec: &DenoiseSpec) -> Result<(Rgb32f, Option, SourceInfo), String> { - rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, Some(spec), false).map(|(img, twin, info, _)| (img, twin, info))) +pub fn load_vec_pair( + bytes: Vec, + max_edge: usize, + spec: &DenoiseSpec, + dcp: Option<&DcpProfile>, +) -> Result<(Rgb32f, Option, SourceInfo), String> { + rayon::scope(move |_| { + load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, Some(spec), false, dcp).map(|(img, twin, info, _)| (img, twin, info)) + }) } /// The denoised camera RGB of `raw` from its cached product, as the plain development would have it: the default @@ -59,6 +73,7 @@ fn load_bytes_now( max_edge: usize, denoise: Option<&DenoiseSpec>, allow_reduced: bool, + dcp: Option<&DcpProfile>, ) -> Result<(Rgb32f, Option, SourceInfo, bool), String> { if lightcraft_raw::probe(&bytes).is_some() { // a thumbnail (`allow_reduced`, never an export) of a DNG that keeps smaller copies of its raw image @@ -92,20 +107,46 @@ fn load_bytes_now( let dng_lens_ops = (raw.format == lightcraft_raw::RawFormat::Dng && raw.opcodes.list3.iter().any(|op| op.is_lens_correction())) .then(|| raw.opcodes.list3.clone()); raw.opcodes.list3.retain(|op| !op.is_lens_correction()); + // A camera profile without a tone curve of its own (most chart-made ones: a matrix, maybe a hue/saturation map) + // keeps the contrast the photo has without it: the file's own DNG tone curve, else the tone of the look fitted + // to its camera JPEG. (A chart pins colour, not a rendering: its curve would be a choice, and this one is the + // camera's.) + let kept_tone = match dcp { + Some(p) if p.color.profile.tone_curve.is_none() => raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve).or_else(|| { + let own = raw.color.clone(); + // the same proxy as the starting colour's fit below: the DNG's lens opcodes back in, no embedded lens + let tone = with_dng_lens_ops(&mut raw, dng_lens_ops.as_ref(), lens.as_ref(), list3, |raw, embedded| { + crate::camera_preview::starting_colour(raw, &bytes, lens_geometry.as_ref(), embedded) + }) + .2 + .map(|look| look.tone); + raw.color = own; + tone + }), + _ => None, + }; + // An imported camera profile replaces the file's colour model (its matrices and look; the shot's white stays), so + // the starting colour and the white balance scale below come from it, not from a fitted or built-in look. + // (the white balance stays on the scale the file and its camera give, the one the catalog's + // `Photo::relative_wb` and the quick previews use: a profile's matrices must not turn a relative white balance + // into Kelvin, which would read existing edits as absolute temperatures) + let own_scale = dcp.map(|_| WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata)); + if let Some(p) = dcp { + raw.color = p.applied_to(&raw.color); + } // Which scale white balance is edited on, and the as-shot white on it, from the file's own colour tags or // the camera's measured matrices (`Photo::relative_wb` decides the same from the catalog's camera) let scale = WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata); + let scale = match &own_scale { + Some(own) => scale.keeping_classification_of(own), + None => scale, + }; // the source's segmentation mattes (DNG semantic masks), read while the starting colour is fitted let ((xy, t, camera_look), mattes) = rayon::join( || { - let removed = dng_lens_ops.map(|ops| std::mem::replace(&mut raw.opcodes.list3, ops)); - // With the opcodes restored, the proxy already includes vignetting; do not apply it twice. - let embedded = if removed.is_some() { None } else { lens.as_ref() }; - let colour = crate::camera_preview::starting_colour(&mut raw, &bytes, lens_geometry.as_ref(), embedded); - if let Some(ops) = removed { - raw.opcodes.list3 = ops; - } - colour + with_dng_lens_ops(&mut raw, dng_lens_ops.as_ref(), lens.as_ref(), list3, |raw, embedded| { + crate::camera_preview::starting_colour(raw, &bytes, lens_geometry.as_ref(), embedded) + }) }, || dng_mattes(&bytes, &info), ); @@ -183,7 +224,12 @@ fn load_bytes_now( let tags = lightcraft_raw::ColorData { profile: Default::default(), ..raw.color.clone() }; Arc::new(lightcraft_pipeline::CameraColor { tags, developed_for: xy }) }); - let camera_tone = camera_look.as_ref().map(|p| p.tone).or_else(|| raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve)); + let camera_tone = camera_tone_of( + dcp.is_some(), + camera_look.as_ref().map(|p| p.tone), + raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve), + kept_tone, + ); let local_tone = local_tone(&raw); let (temp, tint) = scale.as_shot(xy); return Ok(( @@ -262,6 +308,13 @@ impl WbScaleOf { WbScaleOf { own_matrix, relative: fitted && !covered, legacy_relative: fitted && covered, scale_white, camera } } + /// This scale (a raw's, with an imported camera profile's colour model) on the white-balance scale `own` (the + /// same raw's with its own colour) gives: relative, or Kelvin edited on the relative scale before. The matrices, + /// and so the colour and the as-shot reading, stay this scale's. + pub(super) fn keeping_classification_of(self, own: &WbScaleOf) -> Self { + WbScaleOf { relative: own.relative, legacy_relative: own.legacy_relative, ..self } + } + /// What a DNG of this raw's camera RGB declares so that it shows the white balance as this scale does: the /// camera's measured matrices when they give the scale, else the white the scale shows at As Shot (the presets' /// reading; 6500 K / 0 on the relative scale; else `own`, the white the file's tags give). @@ -348,3 +401,105 @@ pub(crate) fn dng_tone_curve(curve: &lightcraft_raw::profile::ToneCurve) -> Opti }); lightcraft_pipeline::tone::CameraTone::new(knots) } + +/// A raw's `OpcodeList3`. +fn list3(raw: &mut lightcraft_raw::RawImage) -> &mut Vec { + &mut raw.opcodes.list3 +} + +/// `fit(raw, embedded)` with a DNG's lens opcodes `ops` back in `raw`'s `OpcodeList3` (`list3`), as its preview has +/// them applied, and the list as it was afterwards. With the opcodes restored the proxy already includes the +/// vignetting, so `embedded` is `None` then (else `lens`): every tone fit of one photo sees the same proxy. +fn with_dng_lens_ops( + raw: &mut R, + ops: Option<&Vec>, + lens: Option<&L>, + list3: fn(&mut R) -> &mut Vec, + fit: impl FnOnce(&mut R, Option<&L>) -> T, +) -> T { + let removed = ops.map(|ops| std::mem::replace(list3(raw), ops.clone())); + let embedded = if removed.is_some() { None } else { lens }; + let out = fit(raw, embedded); + if let Some(ops) = removed { + *list3(raw) = ops; + } + out +} + +/// The tone a raw's starting look gets from its camera: `look` (the tone of the look fitted to the camera JPEG), +/// `curve` (the colour model's own tone curve: the file's, or with an imported camera profile, the profile's) and +/// `kept` (the photo's own tone, kept for a profile without a curve). With a camera profile (`profile`), its curve +/// comes first, then the kept tone, and the fitted look's only last: the look was fitted without the profile, so it +/// must not replace the profile's curve or the contrast kept for it. Without one, the fitted look leads as before. +fn camera_tone_of(profile: bool, look: Option, curve: Option, kept: Option) -> Option { + if profile { curve.or(kept).or(look) } else { look.or(curve).or(kept) } +} + +#[cfg(test)] +mod camera_tone_tests { + use super::camera_tone_of; + + /// CodeRabbit on #1063: with an imported camera profile, a fitted camera look's tone replaced the profile's own + /// tone curve and the tone kept for a profile without one. Without a profile the order is unchanged. + #[test] + fn a_camera_profiles_curve_and_kept_tone_come_before_the_fitted_look() { + assert_eq!(camera_tone_of(true, Some("look"), Some("profile"), Some("kept")), Some("profile")); + assert_eq!(camera_tone_of(true, Some("look"), None, Some("kept")), Some("kept")); + assert_eq!(camera_tone_of(true, Some("look"), None, None), Some("look")); + assert_eq!(camera_tone_of(false, Some("look"), Some("file"), Some("kept")), Some("look")); + assert_eq!(camera_tone_of(false, None, Some("file"), Some("kept")), Some("file")); + assert_eq!(camera_tone_of::<&str>(false, None, None, None), None); + } +} + +#[cfg(test)] +mod wb_scale_tests { + use super::WbScaleOf; + + /// CodeRabbit on #1063: a raw edited on the relative white-balance scale (no colour matrices, none measured for + /// its camera) turned to Kelvin once an imported camera profile's matrices replaced its colour, so its existing + /// edits (6500 K / 0 = as shot) were read as absolute temperatures, and the catalog and quick previews still + /// used the relative scale. The profile's matrices stay; the scale is the file's. + #[test] + fn a_camera_profile_keeps_a_relative_white_balance_relative() { + let format = lightcraft_raw::RawFormat::Cr3; + let meta = lightcraft_meta::Metadata::default(); + let own_color = lightcraft_raw::ColorData::default(); + let own = WbScaleOf::new(format, &own_color, Some([2.0, 1.0, 1.5]), &meta); + assert!(own.relative && !own.own_matrix, "a matrix-less raw of an unmeasured camera is relative"); + let m = lightcraft_color::Mat3([[0.9, 0.1, 0.0], [0.1, 0.8, 0.1], [0.0, 0.2, 0.8]]); + let profiled = lightcraft_raw::ColorData { illuminant: [21, 0], color_matrix: [Some(m), None], ..Default::default() }; + let with = WbScaleOf::new(format, &profiled, Some([2.0, 1.0, 1.5]), &meta); + assert!(!with.relative, "the profile's matrices alone would make it Kelvin"); + let kept = with.keeping_classification_of(&own); + assert!(kept.relative && !kept.legacy_relative && kept.own_matrix, "relative, with the profile's matrices"); + assert_eq!(kept.as_shot(lightcraft_color::Xy { x: 0.3127, y: 0.329 }), (6500.0, 0.0)); + } +} + +#[cfg(test)] +mod lens_ops_tests { + use lightcraft_raw::Opcode; + + use super::with_dng_lens_ops; + + fn same(v: &mut Vec) -> &mut Vec { + v + } + + /// Both tone fits of a DNG (the kept tone for a camera profile without a curve, and the starting colour) see its + /// lens opcodes restored and no embedded lens; the list is as it was afterwards (CodeRabbit on #1063: the + /// kept-tone fit ran without the opcodes and with the embedded lens). + #[test] + fn a_dngs_tone_fit_sees_its_lens_opcodes_and_no_embedded_lens() { + let vignette = Opcode::FixVignetteRadial { k: [0.1, 0.0, 0.0, 0.0, 0.0], center: [0.5, 0.5] }; + let ops = vec![vignette.clone()]; + let mut list: Vec = Vec::new(); + let lens = 7; + let seen = with_dng_lens_ops(&mut list, Some(&ops), Some(&lens), same, |l, embedded| (l.clone(), embedded.copied())); + assert_eq!(seen, (vec![vignette], None), "the opcodes are in, the embedded lens is not"); + assert!(list.is_empty(), "the list is as it was"); + let seen = with_dng_lens_ops(&mut list, None, Some(&lens), same, |l, embedded| (l.len(), embedded.copied())); + assert_eq!(seen, (0, Some(7)), "without DNG lens opcodes the embedded lens is used"); + } +} diff --git a/crates/engine/src/files/tests.rs b/crates/engine/src/files/tests.rs index 33ad692d4c..4fab917c82 100644 --- a/crates/engine/src/files/tests.rs +++ b/crates/engine/src/files/tests.rs @@ -591,7 +591,7 @@ fn cached_denoise_uses_the_same_white_balance_profile_and_orientation_as_plain_r product::write(&path, &camera_rgb, key).unwrap(); let spec = DenoiseSpec { product: path, key: key.into(), make: None }; let (ordinary, _) = load_bytes(&bytes, 2048).unwrap(); - let (plain, cached, _) = load_vec_pair(bytes, 2048, &spec).unwrap(); + let (plain, cached, _) = load_vec_pair(bytes, 2048, &spec, None).unwrap(); assert_eq!(plain.data, ordinary.data, "requesting a twin must not change the ordinary path"); let cached = cached.unwrap(); assert_eq!((plain.width, plain.height), (24, 32)); @@ -1255,10 +1255,10 @@ fn exports_never_develop_a_dngs_reduced_copy() { let mean = |img: &lightcraft_raster::Rgba8| img.data.iter().map(|p| p[1] as f64).sum::() / img.data.len().max(1) as f64; // the loaders: only the thumbnail's develops the copy, and only when it covers the size - let (copy, _, used) = load_vec_reduced(bytes.clone(), 512).unwrap(); + let (copy, _, used) = load_vec_reduced(bytes.clone(), 512, None).unwrap(); assert!(used, "a thumbnail develops the copy"); - assert!(!load_vec_reduced(bytes.clone(), 1024).unwrap().2, "no copy covers 1024 px"); - let (full, _) = load_vec(bytes.clone(), 512).unwrap(); + assert!(!load_vec_reduced(bytes.clone(), 1024, None).unwrap().2, "no copy covers 1024 px"); + let (full, _) = load_vec(bytes.clone(), 512, None).unwrap(); assert!(g(©) > 4.0 * g(&full), "the fixture's copy is much brighter: {} vs {}", g(©), g(&full)); let dir = std::env::temp_dir().join(format!("lc-reduced-export-{}", std::process::id())); diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index 8846738fe9..ae635cb10d 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -512,6 +512,7 @@ impl Session { stages: None, view_cache: None, display: None, + on_screen: false, slide: None, preview_cut: None, display_fit: None, diff --git a/crates/engine/src/import/job/tests.rs b/crates/engine/src/import/job/tests.rs index 82490915b7..08447ac02c 100644 --- a/crates/engine/src/import/job/tests.rs +++ b/crates/engine/src/import/job/tests.rs @@ -14,7 +14,7 @@ fn fixture(preview_edge: Option, renderable: bool, preview_only: bool) -> let mut session = Session::new(); let reads = Arc::new(AtomicUsize::new(0)); let count = reads.clone(); - session.media.file_loader = Some(Arc::new(move |_, edge| { + session.media.file_loader = Some(Arc::new(move |_, edge, _| { count.fetch_add(1, Ordering::SeqCst); if !renderable { return Err("synthetic raw cannot be rendered".into()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 704602e4be..f71f9becd1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -80,6 +80,7 @@ pub mod slideshow; pub mod slideshow_export; pub mod smart; pub mod sync; +mod sync_same; pub mod text; mod view; pub mod walk; @@ -359,6 +360,8 @@ pub struct Session { /// The user's point-curve presets (`curve.*`; built-ins: [`cmd::curves::builtin_presets`]), /// persisted in prefs.json. pub curve_presets: Vec, + /// Imported camera profiles (`.dcp`). + pub dcp_profiles: Vec, /// Mask effect presets (the Masking panel's Effect menu). pub mask_effects: Vec, /// The effect a new mask of each kind (`brush`, `linear`…) starts with: the one last applied @@ -518,6 +521,7 @@ impl Session { metadata_presets: Vec::new(), filter_presets: Vec::new(), curve_presets: Vec::new(), + dcp_profiles: Vec::new(), mask_effects: Vec::new(), mask_tool_effects: Default::default(), label_sets: Vec::new(), @@ -614,7 +618,8 @@ impl Session { } } if self.depth == 0 && self.library.is_some() { - // Make the command durable before reporting success. When the command's own records + // Make the command durable before reporting success (natively: handed to the catalog + // log's own thread, which syncs it right after and holds it until it can). When the command's own records // can't be appended, it fails with `NotSaved`: the change stays applied in memory and // queued, and the next save (any later command, or the frame loop) retries it. Other // persistence trouble (a failed compaction, an older queued change still unwritten by @@ -946,8 +951,9 @@ impl Session { i.crop_edited |= crop_edited; return self.apply_silent(Op::SetDevelop { id, settings, label: label.into(), edited: Some(now) }); } + let own_auto = self.own_auto_wb(id, &requested, label); let mut ops = vec![self.develop_op(id, (*settings).clone(), label).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?]; - ops.extend(self.auto_sync_ops(id, &requested, label)); + ops.extend(self.auto_sync_ops(id, &requested, label, &own_auto)); let op = if ops.len() == 1 { ops.remove(0) } else { Op::Batch { ops } }; self.commit(label, op) } @@ -988,13 +994,12 @@ impl Session { /// never spot removal or red eye (they belong to one photo's pixels), nor the rendering process /// (Sync doesn't carry it either), nor history / snapshot restores. Constrain Crop then fits each /// photo's own crop: the active photo's fitted crop is never copied over another's. - fn auto_sync_ops(&self, id: PhotoId, new: &DevelopSettings, label: &str) -> Vec { - if !self.auto_sync - || self.active() != Some(id) - || self.selection.ids.len() < 2 - || label.starts_with("History:") - || label.starts_with("Restore ") - { + /// + /// White balance goes on each photo as the active photo's mode or value on the photo's own + /// scale ([`sync_same`]): As Shot its own camera white, Auto its own (`own_auto`, worked out on + /// its pixels), a Temp or Tint the same number, only the slider that moved. + fn auto_sync_ops(&self, id: PhotoId, new: &DevelopSettings, label: &str, own_auto: &std::collections::HashMap) -> Vec { + if !self.auto_sync_applies(id, label) { return Vec::new(); } let Some(old) = self.develop_of(id) else { return Vec::new() }; @@ -1016,18 +1021,35 @@ impl Session { return Vec::new(); } } + let ainfo = self.source_info(id); + let wb_changed = old.wb != new.wb; self.selection .ids .iter() .filter(|x| **x != id) .filter_map(|x| self.develop_of(*x).map(|d| (*x, d))) .filter_map(|(x, d)| { - let synced = self.fit_constrained_crop(x, lightcraft_develop::apply_partial(&d, &delta, 1.0)); + let mut synced = lightcraft_develop::apply_partial(&d, &delta, 1.0); + if wb_changed { + sync_same::synced_wb(&ainfo, &old, new, &self.source_info(x), &d, own_auto.get(&x).copied(), &mut synced); + } + let synced = self.fit_constrained_crop(x, synced); (synced != *d).then(|| self.develop_op(x, synced, label)).flatten() }) .collect() } + /// Auto Sync carries an edit of photo `id` labelled `label` to the other selected photos: it is + /// on, `id` is the active photo of a selection of two or more, and the edit is not a History or + /// snapshot restore. + fn auto_sync_applies(&self, id: PhotoId, label: &str) -> bool { + self.auto_sync + && self.active() == Some(id) + && self.selection.ids.len() >= 2 + && !label.starts_with("History:") + && !label.starts_with("Restore ") + } + /// The op that sets a photo's develop settings and appends a History entry (for batches). pub fn develop_op(&self, id: PhotoId, settings: DevelopSettings, label: &str) -> Option { self.catalog.photo(id)?; diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index caf51a0ab6..23e333c4ca 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -13,8 +13,12 @@ //! The files live in [`Store`]s: a directory ([`FsStore`]) natively, or any other implementation //! via [`Session::open_library_in`] (the browser build keeps them in OPFS or IndexedDB). //! -//! Every top-level [`Session::execute`] persists the ops it produced (fsynced) before returning, -//! so a crash loses at most the command in flight. When that write fails the command returns +//! Every top-level [`Session::execute`] persists the ops it produced before returning: fsynced +//! there, or natively handed to the catalog log's own thread, which writes and syncs them right +//! after (the UI thread never waits for the drive), so a crash or power cut loses at most the +//! batch in flight (what arrived during one sync). A write that thread +//! can't make is held and retried, counts as unsaved ([`Session::unsaved`]) and makes a snapshot +//! due. When that write fails the command returns //! [`EngineError::NotSaved`]: its change stays applied in memory and queued, and every later save //! retries the queue ([`Session::unsaved`] reports it meanwhile), so nothing is lost once the //! disk is writable again. The log is compacted into a snapshot when it @@ -134,6 +138,10 @@ pub struct Library { /// Why the last write of presets.json failed; `None` once it is written. While set, the preset /// changes exist only in memory and count as unsaved ([`Session::unsaved`], issue #2266). presets_error: Option, + /// Records the catalog log's own thread holds because writing them failed (it retries them), + /// and why; refreshed by every persist and every frame ([`Session::persist_if_dirty`]). While + /// set they count as unsaved ([`Session::unsaved`]), so quitting asks first. + log_held: Option<(usize, String)>, /// When the frame loop may retry a failed append ([`Session::persist_if_dirty`] backs off). retry_at: Option, /// What forgetting untouched Local records did when the library opened. @@ -277,6 +285,8 @@ struct PrefsFile { label_sets: Vec, /// Imported LUT profiles. lut_profiles: Vec, + /// Imported camera profiles (`.dcp`). + dcp_profiles: Vec, /// Keyword sets, the one in use, recent keywords. keyword_sets: Vec, keyword_set: Option, @@ -322,6 +332,8 @@ fn poll_compaction(lib: &mut Library) { log::error!("library: compaction: {e}"); lib.last_error = Some(format!("compaction: {e}")); } + // (never waits: the log's thread publishes what it holds) + lib.log_held = lib.journal.unwritten(); } /// How long the frame loop waits before retrying a failed append (commands retry at once). @@ -501,13 +513,24 @@ impl Session { /// Open `stores`; the new library takes `lock` once nothing can fail any more. fn open_stores(&mut self, stores: LibraryStores, seed_demo: bool, lock: &mut Option) -> Result<()> { let LibraryStores { dir, catalog, mut files, on_disk } = stores; - self.media.smart_dir = on_disk.then(|| crate::smart::dir(&dir)); - // the current library may be these same files: let its background snapshot land first - if let Some(old) = self.library.as_mut() - && let Err(e) = old.journal.wait() - { - log::error!("library: {e}"); + // the current library may be these same files: let its background snapshot land first, and + // what its log's thread was handed reach the file before the new journal reads it. When + // that can't be written, the open fails and the current library stays open with what its + // thread holds (retried): read now, the files would miss it (review of #3557). + if let Some(old) = self.library.as_mut() { + if let Err(e) = old.journal.wait() { + log::error!("library: {e}"); + } + if let Err(e) = old.journal.flush() { + old.log_held = old.journal.unwritten(); + // a snapshot that holds every op leaves nothing for the files to miss + if old.journal.snapshot_seq() < old.journal.seq() { + return Err(EngineError::NotSaved(format!("the open library's changes aren't on disk yet, so it stays open: {e}"))); + } + log::error!("library: {e} (every change is in its snapshot)"); + } } + self.media.smart_dir = on_disk.then(|| crate::smart::dir(&dir)); // Photo ids belong to one library; denoise work must not carry into the next. self.denoise.library_changed(); self.media.denoise.clear(); @@ -555,6 +578,8 @@ impl Session { self.label_sets = prefs.label_sets; self.lut_profiles = prefs.lut_profiles; crate::cmd::lut_profiles::register_all(self); + self.dcp_profiles = prefs.dcp_profiles; + crate::cmd::dcp_profiles::register_all(self, on_disk.then(|| dir.join("Profiles")).as_deref()); self.keyword_sets = prefs.keyword_sets; self.keyword_set = prefs.keyword_set; self.recent_keywords = prefs.recent_keywords; @@ -582,7 +607,11 @@ impl Session { self.presets.push(u); } } - let known = |id: &String| crate::presets::profile(id).is_some() || self.lut_profiles.iter().any(|p| &p.id == id); + let known = |id: &String| { + crate::presets::profile(id).is_some() + || self.lut_profiles.iter().any(|p| &p.id == id) + || self.dcp_profiles.iter().any(|p| &p.id == id) + }; self.profile_favorites = f.profile_favorites.into_iter().filter(known).collect(); self.profile_recent = f.profile_recent.into_iter().filter(known).take(crate::presets::RECENT_PROFILES).collect(); } @@ -631,6 +660,7 @@ impl Session { last_error: None, unsaved_error: None, presets_error: None, + log_held: None, retry_at: None, forgot_local: None, presets_saved, @@ -661,7 +691,7 @@ impl Session { Ok(()) } - /// Write pending ops to the log (fsynced), compact when due, and save changed presets. + /// Write pending ops to the log (fsynced, or handed to the log's own thread natively), compact when due, and save changed presets. /// Called after every top-level command; cheap when nothing changed. Fails (with /// [`EngineError::NotSaved`]) only when the queued ops couldn't be written; they stay queued. pub fn persist(&mut self) -> Result<()> { @@ -726,13 +756,40 @@ impl Session { pub fn persist_if_dirty(&mut self) { let backing_off = self.library.as_ref().and_then(|l| l.retry_at).is_some_and(|t| web_time::Instant::now() < t); let presets_unsaved = self.library.as_ref().is_some_and(|l| l.presets_error.is_some()); - if self.library.is_some() && (!self.pending_log.is_empty() || presets_unsaved) && !backing_off { + // records the log's thread can't write: a snapshot (a fresh file holding everything) is due + let log_held = self.library.as_ref().is_some_and(|l| l.log_held.is_some()); + if self.library.is_some() && (!self.pending_log.is_empty() || presets_unsaved || log_held) && !backing_off { let _ = self.persist(); } else if let Some(lib) = self.library.as_mut() { poll_compaction(lib); } } + /// Read again what the catalog log's own thread holds because writing it failed (never waits): + /// before a check of [`Session::unsaved`] that must be current, such as the quit prompt's. + pub fn refresh_unsaved(&mut self) { + if let Some(lib) = self.library.as_mut() { + lib.log_held = lib.journal.unwritten(); + } + } + + /// Every change applied is in the library's last snapshot (a closing snapshot landed), whatever + /// the catalog log's thread still holds or failed to reset. `false` without a library. + pub fn snapshot_holds_everything(&self) -> bool { + self.pending_log.is_empty() && self.library.as_ref().is_some_and(|l| l.journal.snapshot_seq() >= l.journal.seq()) + } + + /// Wait until what the catalog log's thread was handed is on disk, then read again what it + /// holds ([`Session::refresh_unsaved`]). Before the quit check: a change the thread accepted + /// but hasn't written yet is in no count of [`Session::unsaved`]. An error (a write failed, or + /// the drive took over a minute) means some changes may not be on disk yet. + pub fn flush_log(&mut self) -> Result<()> { + let Some(lib) = self.library.as_mut() else { return Ok(()) }; + let flushed = lib.journal.flush(); + lib.log_held = lib.journal.unwritten(); + Ok(flushed?) + } + /// Changes applied in memory but not yet written to disk because saving failed: the number of /// queued ops (plus one for presets.json) and why (`None` when everything is saved, or no library /// is open). Retried by every command and by [`Session::persist_if_dirty`]. @@ -740,8 +797,9 @@ impl Session { let lib = self.library.as_ref()?; let ops = lib.unsaved_error.as_deref().filter(|_| !self.pending_log.is_empty()); let presets = lib.presets_error.as_deref(); - let n = ops.map_or(0, |_| self.pending_log.len()) + usize::from(presets.is_some()); - ops.or(presets).map(|why| (n, why)) + let held = lib.log_held.as_ref().map(|(n, why)| (*n, why.as_str())); + let n = ops.map_or(0, |_| self.pending_log.len()) + held.map_or(0, |(n, _)| n) + usize::from(presets.is_some()); + ops.or(held.map(|(_, why)| why)).or(presets).map(|why| (n, why)) } /// Flush everything and write a snapshot (on quit). Ends an open interaction first. @@ -760,6 +818,8 @@ impl Session { let Some(lib) = self.library.as_mut() else { return Ok(()) }; let before = lib.journal.seq(); let snapshot = lib.journal.snapshot_with_unlogged(&self.catalog, unlogged); + // (a snapshot that landed holds what the log's thread held) + lib.log_held = lib.journal.unwritten(); if unlogged > 0 && lib.journal.seq() == before + unlogged { // the snapshot holds the queued ops: they are saved, never append them again log::info!("library: {unlogged} queued change(s) saved in the closing snapshot"); @@ -834,6 +894,7 @@ impl Session { mask_tool_effects: self.mask_tool_effects.clone(), label_sets: self.label_sets.clone(), lut_profiles: self.lut_profiles.clone(), + dcp_profiles: self.dcp_profiles.clone(), keyword_sets: self.keyword_sets.clone(), keyword_set: self.keyword_set.clone(), recent_keywords: self.recent_keywords.clone(), diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 7377e23f1b..a4528795b1 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -24,6 +24,7 @@ use lightcraft_develop::DevelopSettings; use lightcraft_pipeline::{Quality, RenderRequest, Rendered, SourceInfo, StageCache}; use lightcraft_preview::{Hash128, Hasher128, Lru, PreviewCache}; use lightcraft_raster::{Histogram, Rgb32f, Rgba8}; +pub use lightcraft_raw::dcp::DcpProfile; use serde::{Deserialize, Serialize}; mod cache; @@ -35,7 +36,7 @@ mod source; pub use cache::DenoiseIndex; pub use quick::{QuickJob, QuickSource, content_key, source_info}; -pub use render::{RenderJob, RenderResult, develop, develop_reporting, fit_for_display}; +pub use render::{RenderJob, RenderResult, ScreenFrame, develop, develop_reporting, fit_for_display}; #[cfg(test)] use settings_hash::SETTINGS_HASH_ENTRIES; use settings_hash::SettingsHashes; @@ -79,6 +80,26 @@ pub struct MediaCache { pub rendered: Arc, /// Which photos have a cached denoised picture, and how to read it. pub denoise: DenoiseIndex, + /// Imported camera profiles by id ([`crate::cmd::dcp_profiles`]), handed to the decoder of photos using them. + pub camera_profiles: std::collections::HashMap, +} + +/// An imported camera profile ready for the decoder, with a fingerprint of its file: decoded sources and cached renders +/// made with it carry the fingerprint, so a profile deleted, or replaced by another under the same id, never has +/// its old pictures stand in. +#[derive(Clone, Debug)] +pub struct LoadedCameraProfile { + pub profile: Arc, + /// Never 0 (0 is "no camera profile" in a render key). + pub fingerprint: u64, +} + +impl LoadedCameraProfile { + /// Parse a `.dcp` file's bytes. + pub fn parse(bytes: &[u8]) -> Result { + let profile = lightcraft_raw::dcp::parse_dcp(bytes)?; + Ok(LoadedCameraProfile { profile: Arc::new(profile), fingerprint: Hasher128::new().update(bytes).finish().0 as u64 | 1 }) + } } #[cfg(test)] diff --git a/crates/engine/src/media/cache.rs b/crates/engine/src/media/cache.rs index 238870c07a..234efb1485 100644 --- a/crates/engine/src/media/cache.rs +++ b/crates/engine/src/media/cache.rs @@ -1,6 +1,6 @@ use super::settings_hash::SettingsHashes; use super::source::{DecodedSource, DenoiseSpec, PairLoader, RENDERED_MEM_BYTES, SourceLevel, SourceRef, THUMB_SOURCE_BYTES}; -use super::{Arc, DevelopSettings, Hasher128, Lru, MediaCache, Photo, PhotoId, PreviewCache, Rgb32f, Source, SourceInfo}; +use super::{Arc, DcpProfile, DevelopSettings, HashMap, Hasher128, Lru, MediaCache, Photo, PhotoId, PreviewCache, Rgb32f, Source, SourceInfo}; /// The photos that have a cached denoised picture for the denoise model in use. Only memory: nothing here touches the /// file system, so it can be asked on the UI thread. @@ -70,6 +70,7 @@ impl Default for MediaCache { scenes: Vec::new(), rendered: Arc::new(PreviewCache::memory(rendered_budget(budget))), denoise: DenoiseIndex::default(), + camera_profiles: HashMap::new(), } } } @@ -202,14 +203,16 @@ impl MediaCache { } /// The facts of photo `id`'s cached sources: the decoder's when one has them, else `header` - /// (with a smart preview's stored camera tone curve). - pub(super) fn source_facts(&self, id: PhotoId, header: SourceInfo) -> SourceInfo { + /// (with a smart preview's stored camera tone curve). Only sources developed with `profile` (the photo's imported + /// camera profile tag, [`Self::camera_profile_of`], or none) count: one made with another profile has its facts. + pub(super) fn source_facts(&self, id: PhotoId, header: SourceInfo, profile: Option<&str>) -> SourceInfo { let cached = || { self.thumbs .peek(&id) .into_iter() .chain(self.previews.iter().filter(|e| e.0 == id).map(|e| &e.1)) .chain(self.full.iter().filter(|e| e.0 == id).map(|e| &e.1)) + .filter(|s| s.camera_profile.as_deref() == profile) }; match cached().find(|s| s.info.is_some()).or_else(|| cached().next()) { Some(s) => s.info_or(header), @@ -221,7 +224,13 @@ impl MediaCache { self.insert_source(id, level, DecodedSource::new(img, None)); } - pub(super) fn insert_source(&mut self, id: PhotoId, level: SourceLevel, img: DecodedSource) { + /// A decoded source with what the decoder reported about it (tests: photos of another as-shot white). + #[cfg(test)] + pub(crate) fn insert_with_info(&mut self, id: PhotoId, level: SourceLevel, img: Arc, info: lightcraft_pipeline::SourceInfo) { + self.insert_source(id, level, DecodedSource::new(img, Some(info))); + } + + pub(crate) fn insert_source(&mut self, id: PhotoId, level: SourceLevel, img: DecodedSource) { let tick = lightcraft_preview::next_tick(); match level { SourceLevel::Thumb => { @@ -296,24 +305,49 @@ impl MediaCache { self.source_ref_with(p, level, false) } + /// [`Self::source_ref`] without the photo's imported camera profile (keeping its denoised picture): a smart + /// preview keeps the file's own colour, and a cached source developed with the profile doesn't stand in for it. + #[cfg(not(target_arch = "wasm32"))] + pub fn source_ref_without_profile(&mut self, p: &Photo, level: SourceLevel) -> SourceRef { + self.source_ref_for(p, level, true, None) + } + fn source_ref_with(&mut self, p: &Photo, level: SourceLevel, cached: bool) -> SourceRef { - let mut r = self.source_ref_plain(p, level, cached); + let wanted = self.camera_profile_of(p); + self.source_ref_for(p, level, cached, wanted) + } + + /// [`Self::source_ref_with`] developed with camera profile `wanted` (none: the file's own colour). + fn source_ref_for(&mut self, p: &Photo, level: SourceLevel, cached: bool, wanted: Option<(String, Arc)>) -> SourceRef { + let mut r = self.source_ref_plain(p, level, cached, wanted); if let (SourceRef::File { denoise, .. }, Some((spec, loader))) = (&mut r, self.denoise.get(p.id)) { *denoise = Some((spec.clone(), loader.clone())); } r } - fn source_ref_plain(&mut self, p: &Photo, level: SourceLevel, cached: bool) -> SourceRef { - if cached && let Some(a) = self.get_source(p.id, level) { + /// Is photo `p`'s original known to be missing (cached answer only)? + fn original_offline(&self, p: &Photo) -> bool { + matches!(&p.source, Source::File { path } if self.availability.is_offline(path)) + } + + fn source_ref_plain(&mut self, p: &Photo, level: SourceLevel, cached: bool, wanted: Option<(String, Arc)>) -> SourceRef { + // (a source developed with another camera profile, or none, doesn't stand in; a smart preview + // has no camera profile, and decoding it again gives the same picture, so it stands in while the + // original is offline) + if cached + && let Some(a) = self.get_source(p.id, level) + && (a.camera_profile == wanted.as_ref().map(|(id, _)| id.clone()) || (a.from_proxy && self.original_offline(p))) + { return SourceRef::Loaded(Box::new(a)); } // a thumbnail of a photo whose preview is decoded (the one in the loupe) is cut from it; not - // with a denoised picture, which the thumbnail would lose + // with a denoised picture, which the thumbnail would lose, nor from one decoded with another camera profile if cached && level == SourceLevel::Thumb && self.denoise.spec(p.id).is_none() && let Some(big) = self.get_source(p.id, SourceLevel::Preview) + && (big.camera_profile == wanted.as_ref().map(|(tag, _)| tag.clone()) || (big.from_proxy && self.original_offline(p))) { return SourceRef::Fit { from: Box::new(big), max_edge: level.max_edge() }; } @@ -336,12 +370,36 @@ impl MediaCache { return SourceRef::Smart { path: sp }; } let mut r = self.origin_ref(&p.source, max_edge); - if let SourceRef::File { fallback, .. } = &mut r { + if let SourceRef::File { fallback, camera_profile, .. } = &mut r { *fallback = Some(sp); + *camera_profile = wanted; } return r; } - self.origin_ref(&p.source, max_edge) + let mut r = self.origin_ref(&p.source, max_edge); + if let SourceRef::File { camera_profile, .. } = &mut r { + *camera_profile = wanted; + } + r + } + + /// The imported camera profile photo `p` develops with, when its profile setting names one this library has: what a + /// source decoded with it is tagged with (its id and the file's fingerprint), and the profile. + pub fn camera_profile_of(&self, p: &Photo) -> Option<(String, Arc)> { + let id = &p.develop.profile.id; + if !crate::cmd::dcp_profiles::is_dcp_id(id) { + return None; + } + self.camera_profiles.get(id).map(|d| (format!("{id}#{:016x}", d.fingerprint), d.profile.clone())) + } + + /// What a render with profile `profile_id` adds to its cache keys: the imported camera profile's fingerprint, 0 + /// for any other profile and for a camera profile this library no longer has (it renders without it). + pub fn camera_profile_salt(&self, profile_id: &str) -> u64 { + if !crate::cmd::dcp_profiles::is_dcp_id(profile_id) { + return 0; + } + self.camera_profiles.get(profile_id).map_or(0, |d| d.fingerprint) } /// How to load `origin` at most `max_edge` pixels long, ignoring decoded sources in memory (a @@ -354,12 +412,26 @@ impl MediaCache { } match self.scenes.iter().find(|s| s.id == *scene) { Some(s) => SourceRef::Demo { scene: Box::new(s.clone()), max_edge }, - None => SourceRef::File { path: format!("demo:{scene}"), max_edge, loader: None, fallback: None, denoise: None, reduced: None }, + None => SourceRef::File { + path: format!("demo:{scene}"), + max_edge, + loader: None, + fallback: None, + denoise: None, + camera_profile: None, + reduced: None, + }, } } - Source::File { path } => { - SourceRef::File { path: path.clone(), max_edge, loader: self.file_loader.clone(), fallback: None, denoise: None, reduced: None } - } + Source::File { path } => SourceRef::File { + path: path.clone(), + max_edge, + loader: self.file_loader.clone(), + fallback: None, + denoise: None, + camera_profile: None, + reduced: None, + }, } } } diff --git a/crates/engine/src/media/quick.rs b/crates/engine/src/media/quick.rs index 78fcebdfd0..335a118ca6 100644 --- a/crates/engine/src/media/quick.rs +++ b/crates/engine/src/media/quick.rs @@ -49,6 +49,7 @@ impl QuickJob { loaded: None, quick: None, display: None, + frame: None, }) } @@ -66,6 +67,7 @@ impl QuickJob { loaded: None, quick, display: None, + frame: None, }; let rendered = |image: Rgba8| { let histogram = Histogram::of_srgb8(&image); diff --git a/crates/engine/src/media/render.rs b/crates/engine/src/media/render.rs index 4c28e1214f..56dc3b7cb9 100644 --- a/crates/engine/src/media/render.rs +++ b/crates/engine/src/media/render.rs @@ -32,6 +32,9 @@ pub struct RenderJob { pub view_cache: Option<(Arc, Hash128)>, /// Render for this monitor profile ([`Self::with_display`]). pub display: Option>, + /// Shown on screen at once and not kept: the result may stay on the GPU as a texture + /// ([`Self::on_screen`]). + pub on_screen: bool, /// Compose the render into a slideshow slide ([`Self::with_slide`]). pub slide: Option>, /// A face tile that can be cut from the raw's embedded preview, tried before `source` @@ -57,6 +60,17 @@ pub fn fit_for_display(img: &Rgba8, max_w: usize, max_h: usize) -> Rgba8 { Rgba8 { width: small.width, height: small.height, data: small.data.iter().map(|p| [c(p[0]), c(p[1]), c(p[2]), c(p[3])]).collect() } } +/// A render left on the GPU for the window to draw ([`RenderResult::frame`]). +#[cfg(not(target_arch = "wasm32"))] +pub type ScreenFrame = lightcraft_gpu::DisplayFrame; +/// A render left on the GPU for the window to draw (never, in the browser build). +#[cfg(target_arch = "wasm32")] +#[derive(Clone, Debug)] +pub struct ScreenFrame { + pub width: usize, + pub height: usize, +} + pub struct RenderResult { pub request_id: u64, pub source_key: Option, @@ -74,6 +88,9 @@ pub struct RenderResult { /// The display profile (id) the image is encoded for; `None`: sRGB (see /// [`crate::display::present`]). pub display: Option, + /// The result as a texture on the window's GPU device ([`RenderJob::on_screen`]); `rendered` + /// then holds its histogram and an empty image. + pub frame: Option, } impl RenderJob { @@ -123,6 +140,15 @@ impl RenderJob { self } + /// The result is only drawn (an interactive draft of a view): when the GPU renderer runs on the + /// window's device it may hand back a texture ([`RenderResult::frame`]) instead of reading the + /// pixels back. Ignored where pixels are needed: thumbnails (cached), a full-quality render + /// kept as the view preview, and a monitor profile (corrected on the CPU). + pub fn on_screen(mut self) -> Self { + self.on_screen = true; + self + } + /// Render with some colour grading wheels (shadows, midtones, highlights) switched off for /// viewing (the wheel eyes in the Edit panel). The photo's settings are untouched; the result /// gets its own key and is never cached as the photo's preview or thumbnail. @@ -189,6 +215,7 @@ impl RenderJob { loaded: None, quick: None, display: None, + frame: None, } } @@ -232,6 +259,7 @@ impl RenderJob { loaded: None, quick: None, display: None, + frame: None, }; } // a face tile of an unedited raw: cut from the camera's embedded preview when it is big enough @@ -252,6 +280,7 @@ impl RenderJob { loaded: None, quick: None, display: None, + frame: None, }; } let was_loaded = matches!(self.source, SourceRef::Loaded(_)); @@ -267,14 +296,43 @@ impl RenderJob { // the plain picture, or (Denoise amount above 0 and a denoised picture cached) the mix the amount asks for let src = &source.image_for(self.settings.denoise_amount()); let info = source.info_or(self.info); - // Thumbnails (many small jobs side by side) stay on the CPU; views and exports use - // the GPU when there is one. - let gpu = self.cache.is_none(); + // Views and exports use the GPU when there is one (waiting for the device if it is + // still being created). Thumbnails (grid, filmstrip, preset and profile previews) + // use it once it is ready - ~20-30 % faster than the CPU at 256 px with six jobs + // side by side (`crates/gpu/tests/it/thumbs_bench.rs`), and the cores stay free for + // decoding - but never wait for it: at startup they render on the CPU. + let gpu = self.cache.is_none() || lightcraft_gpu::ready(); // a clipping preview tests sRGB values, like the histogram: rendered in sRGB, then // converted for the display below let clip_view = self.request.overlay.is_clipping(); let request = if clip_view { RenderRequest { display: None, ..self.request } } else { self.request }; - let (mut rendered, gpu_fallback) = develop_reporting(src, &info, &self.settings, &request, self.stages.as_deref(), gpu); + let pixels_needed = + self.cache.is_some() || self.display.is_some() || (self.view_cache.is_some() && self.request.quality == Quality::Full); + let frame = (self.on_screen && !pixels_needed && gpu) + .then(|| develop_on_screen(src, &info, &self.settings, &request, self.stages.as_deref())); + let (mut rendered, gpu_fallback) = match frame { + Some(OnScreen::Frame(frame, histogram)) => { + return RenderResult { + request_id: self.request_id, + source_key: self.source_key, + photo: self.photo, + level: self.level, + key: self.key, + rendered: Ok(Rendered { + image: lightcraft_raster::Rgba8 { width: 0, height: 0, data: Vec::new() }, + histogram, + deep: None, + }), + gpu_fallback: None, + loaded: (!was_loaded).then_some(source), + quick: None, + display: None, + frame: Some(frame), + }; + } + Some(OnScreen::Pixels(r)) => (r, None), + None => develop_reporting(src, &info, &self.settings, &request, self.stages.as_deref(), gpu), + }; // for a display profile: the image goes to the display's values, the histogram // and the cached view preview stay sRGB let mut srgb = None; @@ -329,6 +387,7 @@ impl RenderJob { loaded: (!was_loaded).then_some(source), quick: None, display, + frame: None, } } Err(e) => self.failed(e), @@ -370,12 +429,8 @@ fn develop_image( stages: Option<&StageCache>, gpu: bool, ) -> (Rendered, Option) { - // LUT profiles have no GPU stage: they render on the CPU - let fallback = if gpu - && !lightcraft_pipeline::lut::is_lut_profile(&s.profile.id) - && !s.masks.iter().any(|m| m.visible && m.refine > 0.0) - && req.proof.is_none() - { + // (LUT profiles, Refine Edges and soft proofs render on the GPU too) + let fallback = if gpu { match lightcraft_gpu::try_render(src, info, s, req, stages) { Ok(r) => return (r, None), Err(lightcraft_gpu::Fallback::Failed(why)) => Some(why), @@ -390,3 +445,33 @@ fn develop_image( }; (rendered, fallback) } + +/// What [`develop_on_screen`] made. +enum OnScreen { + /// A texture on the window's device, and the histogram (never in the browser build). + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + Frame(ScreenFrame, Histogram), + /// Pixels (GPU or CPU). + Pixels(Rendered), +} + +/// [`develop`] for a render that is only drawn: a texture on the window's device when the GPU +/// renderer can hand one over, else the pixels. +fn develop_on_screen(src: &Arc, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest, stages: Option<&StageCache>) -> OnScreen { + #[cfg(not(target_arch = "wasm32"))] + match lightcraft_gpu::render_display(src, info, s, req, stages) { + // an HDR edit's histogram shows the HDR range, as `develop_reporting` gives it + Some(lightcraft_gpu::Output::Display { frame, histogram }) => { + OnScreen::Frame(frame, lightcraft_pipeline::hdr_histogram(src, info, s, req).unwrap_or(histogram)) + } + Some(lightcraft_gpu::Output::Image(mut r)) => { + if let Some(h) = lightcraft_pipeline::hdr_histogram(src, info, s, req) { + r.histogram = h; + } + OnScreen::Pixels(r) + } + None => OnScreen::Pixels(develop(src, info, s, req, stages, false)), + } + #[cfg(target_arch = "wasm32")] + OnScreen::Pixels(develop(src, info, s, req, stages, false)) +} diff --git a/crates/engine/src/media/session.rs b/crates/engine/src/media/session.rs index 2c34996481..ac1b8145a9 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -1,5 +1,6 @@ use super::quick::{QuickJob, content_key, source_info}; use super::render::{RenderJob, RenderResult}; +use super::settings_hash::with_process; use super::source::{PreviewLoader, RENDER_CACHE_VERSION, SourceLevel, SourceRef, THUMB_SIZES, face_edge, source_edge_needed, thumb_bucket}; use super::{Arc, DevelopSettings, Hash128, Hasher128, MediaKind, Op, Photo, PhotoId, RenderRequest, Rendered, Rgb32f, Source, SourceInfo}; @@ -41,7 +42,14 @@ impl crate::Session { } else { source_edge_needed(&p, &settings, apply_crop, max_w.max(max_h)) }); - let source = self.media.source_ref(&p, level); + // the Before side develops with the Before settings' camera profile (or none), not the edit's + let source = if before { + let mut q = (*p).clone(); + q.develop = settings.clone(); + self.media.source_ref(&q, level) + } else { + self.media.source_ref(&p, level) + }; let request = RenderRequest { apply_crop, ..RenderRequest::fit(max_w, max_h) }; // the photo id is part of the key: two photos with the same settings and size must not // share a result (a view slot showing photo A would otherwise look current for photo B) @@ -52,6 +60,7 @@ impl crate::Session { // Temporary "before" settings must not replace the photo's cached develop hash. let settings_hash = if before { settings.hash64() } else { self.media.settings_hashes.get(id, &settings) }; let salt = self.media.denoise_salt(id, &settings); + let profile_salt = self.media.camera_profile_salt(&settings.profile.id); let lens = super::quick::lens_key(&p); let key = settings_hash ^ ((max_w as u64) << 40) @@ -61,14 +70,20 @@ impl crate::Session { ^ id.0.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ content.rotate_left(17) ^ salt - ^ lens.rotate_left(29); + ^ profile_salt.rotate_left(29) + ^ lens.rotate_left(37); let cache = thumb_bucket.map(|b| { let mut k = Hasher128::new(); - k.str(&content_key).u64(settings_hash).u64(b as u64).u64(RENDER_CACHE_VERSION).u64(crate::camera_profiles::cache_key()); + k.str(&content_key).u64(settings_hash).u64(b as u64).u64(RENDER_CACHE_VERSION); + with_process(&mut k, &settings).u64(crate::camera_profiles::cache_key()); // (only a render that uses a denoised picture has it in its key, so every other thumbnail stays valid) if salt != 0 { k.u64(salt); } + // (likewise an imported camera profile's file: deleted or replaced, the thumbnail renders afresh) + if profile_salt != 0 { + k.str("dcp").u64(profile_salt); + } // (likewise a database lens profile: thumbnails of every other photo keep their keys) if lens != 0 { k.u64(lens); @@ -91,6 +106,7 @@ impl crate::Session { stages: None, view_cache: None, display: None, + on_screen: false, slide: None, preview_cut: None, display_fit: None, @@ -101,7 +117,17 @@ impl crate::Session { /// temporary preview while hovering a preset or profile; nothing is committed or cached). pub fn preview_job(&mut self, id: PhotoId, max_w: usize, max_h: usize, apply_crop: bool, settings: &DevelopSettings) -> Option { let mut job = self.render_job(id, max_w, max_h, false, apply_crop)?; + // the source as these settings develop it: another camera profile (or none) decodes anew + let mut p = (**self.catalog.photo(id)?).clone(); + let own_profile = self.media.camera_profile_of(&p).map(|c| c.0); + p.develop = Arc::new(settings.clone()); + if self.media.camera_profile_of(&p).map(|c| c.0) != own_profile { + job.source = self.media.source_ref(&p, job.level); + } job.settings = Arc::new(settings.clone()); + // (the imported camera profile's file is in the key, as in `render_job`'s: a profile file replaced under the + // same id is a new picture) + let profile_salt = self.media.camera_profile_salt(&settings.profile.id); // (the photo's database lens profile stays part of it: a profile looked up again renders afresh) let lens = self.catalog.photo(id).map_or(0, |p| super::quick::lens_key(p)); job.key = settings.hash64() @@ -109,19 +135,20 @@ impl crate::Session { ^ ((max_h as u64) << 20) ^ (apply_crop as u64) ^ (job.level as u64) << 60 - ^ lens.rotate_left(29); + ^ profile_salt.rotate_left(29) + ^ lens.rotate_left(37); Some(job) } /// Cache key of a variant thumbnail ([`Self::variant_job`]). - pub fn variant_key(p: &Photo, settings: &DevelopSettings, edge: usize) -> Hash128 { + /// `profile_salt`: [`MediaCache::camera_profile_salt`] of `settings`' profile. + pub fn variant_key(p: &Photo, settings: &DevelopSettings, edge: usize, profile_salt: u64) -> Hash128 { let mut k = Hasher128::new(); - k.str(&content_key(p)) - .str("variant") - .u64(settings.hash64()) - .u64(edge as u64) - .u64(RENDER_CACHE_VERSION) - .u64(crate::camera_profiles::cache_key()); + k.str(&content_key(p)).str("variant").u64(settings.hash64()).u64(edge as u64).u64(RENDER_CACHE_VERSION); + with_process(&mut k, settings).u64(crate::camera_profiles::cache_key()); + if profile_salt != 0 { + k.str("dcp").u64(profile_salt); + } let lens = super::quick::lens_key(p); if lens != 0 { k.u64(lens); @@ -135,11 +162,13 @@ impl crate::Session { /// hash, so a variant renders once; `key` is derived from the same hash, so a frontend can /// keep one texture per variant. pub fn variant_job(&mut self, id: PhotoId, settings: &DevelopSettings, edge: usize) -> Option { - let p = self.catalog.photo(id)?.clone(); + let mut p = (**self.catalog.photo(id)?).clone(); let edge = edge.clamp(16, SourceLevel::Thumb.max_edge()); let level = SourceLevel::Thumb; + // decoded as these settings develop it (their camera profile, or none) + p.develop = Arc::new(settings.clone()); let source = self.media.source_ref(&p, level); - let ck = Self::variant_key(&p, settings, edge); + let ck = Self::variant_key(&p, settings, edge, self.media.camera_profile_salt(&settings.profile.id)); Some(RenderJob { request_id: 0, cache_generation: self.media.rendered.generation(), @@ -156,6 +185,7 @@ impl crate::Session { stages: None, view_cache: None, display: None, + on_screen: false, slide: None, preview_cut: None, display_fit: None, @@ -193,7 +223,7 @@ impl crate::Session { let needed = (edge as f64 * w.max(h) / side).ceil().min(SourceLevel::Preview.max_edge() as f64); let level = SourceLevel::for_size(needed as usize); let source = self.media.source_ref(&p, level); - let ck = Self::variant_key(&p, &settings, edge); + let ck = Self::variant_key(&p, &settings, edge, self.media.camera_profile_salt(&settings.profile.id)); let preview_cut = self.face_preview_cut(&p, rect, edge, needed as usize); Some(RenderJob { request_id: 0, @@ -211,6 +241,7 @@ impl crate::Session { stages: None, view_cache: None, display: None, + on_screen: false, slide: None, preview_cut, display_fit: None, @@ -234,15 +265,14 @@ impl crate::Session { } /// Size-independent cache key of a photo's view render (loupe) for its current settings, its lens profile - /// included as in [`Self::variant_key`]. - pub(crate) fn view_key(p: &Photo, apply_crop: bool) -> Hash128 { + /// included as in [`Self::variant_key`]. `profile_salt`: [`MediaCache::camera_profile_salt`] of the photo's profile. + pub(crate) fn view_key(p: &Photo, apply_crop: bool, profile_salt: u64) -> Hash128 { let mut k = Hasher128::new(); - k.str(&content_key(p)) - .str("view") - .u64(p.develop.hash64()) - .u64(apply_crop as u64) - .u64(RENDER_CACHE_VERSION) - .u64(crate::camera_profiles::cache_key()); + k.str(&content_key(p)).str("view").u64(p.develop.hash64()).u64(apply_crop as u64).u64(RENDER_CACHE_VERSION); + with_process(&mut k, &p.develop).u64(crate::camera_profiles::cache_key()); + if profile_salt != 0 { + k.str("dcp").u64(profile_salt); + } let lens = super::quick::lens_key(p); if lens != 0 { k.u64(lens); @@ -255,7 +285,8 @@ impl crate::Session { pub fn loupe_job(&mut self, id: PhotoId, max_w: usize, max_h: usize, apply_crop: bool) -> Option { let mut job = self.render_job(id, max_w, max_h, false, apply_crop)?; let p = self.catalog.photo(id)?; - job.view_cache = Some((self.media.rendered.clone(), Self::view_key(p, apply_crop))); + let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id); + job.view_cache = Some((self.media.rendered.clone(), Self::view_key(p, apply_crop, profile_salt))); Some(job) } @@ -364,8 +395,9 @@ impl crate::Session { let p = self.catalog.photo(id)?.clone(); let small = self.thumb_job(id, THUMB_SIZES[THUMB_SIZES.len() - 1])?; // (the thumbnail job itself starts with the cached thumbnail, after the sharper embedded preview) - let cached = vec![(self.media.rendered.clone(), Self::view_key(&p, apply_crop))]; - let h = Hasher128::new().str(&content_key(&p)).str("quick").u64(p.develop.hash64()).u64(apply_crop as u64).finish(); + let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id); + let cached = vec![(self.media.rendered.clone(), Self::view_key(&p, apply_crop, profile_salt))]; + let h = Hasher128::new().str(&content_key(&p)).str("quick").u64(p.develop.hash64()).u64(apply_crop as u64).u64(profile_salt).finish(); let key = h.0 as u64; let embedded = self.embedded_of(&p).map(|(path, l)| (path, l, max_edge.clamp(1, SourceLevel::Preview.max_edge()))); Some(QuickJob { request_id: 0, photo: id, key, cached, embedded, minimum_embedded_edge: None, small: apply_crop.then(|| Box::new(small)) }) @@ -496,8 +528,10 @@ impl crate::Session { /// Prefer decoder facts to header-only metadata for pixel-statistics commands. pub fn source_info(&self, id: PhotoId) -> SourceInfo { - let header = self.catalog.photo(id).map(|p| source_info(p)).unwrap_or_default(); - self.media.source_facts(id, header) + let photo = self.catalog.photo(id); + let header = photo.map(|p| source_info(p)).unwrap_or_default(); + let profile = photo.and_then(|p| self.media.camera_profile_of(p)).map(|(tag, _)| tag); + self.media.source_facts(id, header, profile.as_deref()) } /// The source proxy for pixel-statistics commands (auto tone/WB), loading synchronously. @@ -511,4 +545,37 @@ impl crate::Session { self.media.insert_source(id, level, r); Ok(image) } + + /// [`Session::source_now`] for several photos at once, each with the facts its decoder gave + /// ([`Session::source_info`], read before another photo can push it out of the cache): the + /// ones not in memory are decoded in parallel, so a selection costs about one decode per core, + /// not one after another. In the order of `ids`. Callers pass a few at a time (all of them are + /// held decoded until this returns). + pub(crate) fn sources_now(&mut self, ids: &[PhotoId], level: SourceLevel) -> Vec<(PhotoId, Result<(Arc, SourceInfo), String>)> { + use rayon::prelude::*; + let refs: Vec<(PhotoId, Option)> = + ids.iter().map(|&id| (id, self.catalog.photo(id).cloned().map(|p| self.media.source_ref(&p, level)))).collect(); + let loaded: Vec<(PhotoId, Result)> = + refs.into_par_iter().map(|(id, r)| (id, r.ok_or_else(|| "no such photo".to_string()).and_then(|r| r.load_source()))).collect(); + loaded + .into_iter() + .map(|(id, r)| { + let r = r.map(|r| { + let image = r.image.clone(); + if let Some(info) = &r.info { + self.learn_as_shot_wb(id, info); + } + // read before the insert: the cache's budget may evict this very entry, and + // the header facts alone lack the decoder's camera colour + let facts = match r.info { + Some(_) => r.info_or(self.catalog.photo(id).map(|p| source_info(p)).unwrap_or_default()), + None => self.source_info(id), + }; + self.media.insert_source(id, level, r); + (image, facts) + }); + (id, r) + }) + .collect() + } } diff --git a/crates/engine/src/media/settings_hash.rs b/crates/engine/src/media/settings_hash.rs index 802918fb90..39f76d52bb 100644 --- a/crates/engine/src/media/settings_hash.rs +++ b/crates/engine/src/media/settings_hash.rs @@ -1,4 +1,4 @@ -use super::{Arc, DevelopSettings, HashMap, PhotoId, VecDeque, Weak}; +use super::{Arc, DevelopSettings, HashMap, Hasher128, PhotoId, VecDeque, Weak}; pub(super) const SETTINGS_HASH_ENTRIES: usize = 1024; @@ -34,3 +34,18 @@ impl SettingsHashes { hash } } + +/// Add the rendering process `s` renders with in this build to persistent render key `h`, from +/// process V3 on: a process number from a newer LightCraft renders with an older build's latest +/// process, so the same settings (and settings hash) render differently in a build that knows that +/// process, and the keys must tell those renders apart. Builds before V3 (which have no process in +/// their keys) resolve every number above V2 to V2: naming V3 and later keeps this build's renders +/// of those numbers apart from theirs, and V1 and V2 keep the keys they always had, so their +/// cached renders stay valid (`docs/process-versions.md`). +pub(super) fn with_process<'a>(h: &'a mut Hasher128, s: &DevelopSettings) -> &'a mut Hasher128 { + let v = s.process.process().version().0; + if v >= lightcraft_develop::Process::V3.version().0 { + h.u64(u64::from(v)); + } + h +} diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index cf4a5fa2dc..f13349f18c 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -1,7 +1,7 @@ -use super::{Arc, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo}; +use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo}; /// Bump when the pipeline's output changes, to invalidate cached thumbnails. -pub const RENDER_CACHE_VERSION: u64 = 74; +pub const RENDER_CACHE_VERSION: u64 = 75; /// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache). pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512]; @@ -75,12 +75,14 @@ pub(super) fn source_edge_needed(p: &Photo, settings: &DevelopSettings, apply_cr } /// Decodes a file into a linear Rec.2020 image no larger than `max_edge` (set by the app). -pub type FileLoader = Arc Result<(Rgb32f, SourceInfo), String> + Send + Sync>; +/// The third argument is the photo's imported camera profile ([`crate::cmd::dcp_profiles`]): a raw file is developed +/// with its colour model. +pub type FileLoader = Arc) -> Result<(Rgb32f, SourceInfo), String> + Send + Sync>; /// [`FileLoader`] for a thumbnail: a raw file that keeps smaller copies of its raw image (Lightroom's merged DNGs) /// develops the smallest that covers `max_edge` (set by the app); the flag says it did. Never used for an export, /// which must render the full image. -pub type ReducedLoader = Arc Result<(Rgb32f, SourceInfo, bool), String> + Send + Sync>; +pub type ReducedLoader = Arc) -> Result<(Rgb32f, SourceInfo, bool), String> + Send + Sync>; /// A raw file's embedded (camera-rendered) preview as display sRGB, oriented, no larger than /// `max_edge` (set by the app). `None`: no usable preview. @@ -103,7 +105,8 @@ pub struct DenoiseSpec { /// Decodes a raw file once and develops it twice: as usual, and from the denoised picture in `spec` when that can be /// read (`None` when it cannot). Both are at most `max_edge` long and the same size. -pub type PairLoader = Arc Result<(Rgb32f, Option, SourceInfo), String> + Send + Sync>; +pub type PairLoader = + Arc) -> Result<(Rgb32f, Option, SourceInfo), String> + Send + Sync>; /// A photo's denoised picture next to its plain one, and the last mix of the two that was asked for. pub struct Twin { @@ -133,6 +136,9 @@ pub struct DecodedSource { pub camera_tone: Option, /// The same picture developed from the AI-denoised mosaic, when the photo has one cached. pub denoised: Option>, + /// The imported camera profile (`dcp:…` id) the raw file was developed with, if any: a cached source made with + /// another one (or none) doesn't stand in for it. + pub camera_profile: Option, /// These pixels came from the photo's smart preview (an offline original), not from its file. /// A refresh must never rebuild a proxy from itself: that would stamp its older look as current. pub from_proxy: bool, @@ -143,7 +149,7 @@ pub struct DecodedSource { impl DecodedSource { pub fn new(image: Arc, info: Option) -> Self { - DecodedSource { image, info, camera_tone: None, denoised: None, from_proxy: false, reduced: false } + DecodedSource { image, info, camera_tone: None, denoised: None, camera_profile: None, from_proxy: false, reduced: false } } /// The picture to develop for a Denoise `amount` (0 to 1, see [`DevelopSettings::denoise_amount`]): the plain one, @@ -235,6 +241,8 @@ pub enum SourceRef { fallback: Option, /// The photo has a cached denoised picture: load it with the plain one (see [`PairLoader`]). denoise: Option<(DenoiseSpec, PairLoader)>, + /// The photo's imported camera profile (id and profile): its raw file is developed with it. + camera_profile: Option<(String, Arc)>, /// A thumbnail's loader, used instead of `loader` (see [`ReducedLoader`]); `None` for every other job. reduced: Option, }, @@ -262,12 +270,17 @@ impl SourceRef { return Ok(DecodedSource { image: Arc::new(image), denoised: None, ..(**from).clone() }); } SourceRef::Demo { scene, max_edge } => crate::demo::scene_pixels(scene, *max_edge)?, - SourceRef::File { path, max_edge, loader, fallback, denoise, reduced } => { + SourceRef::File { path, max_edge, loader, fallback, denoise, camera_profile, reduced } => { + let dcp = camera_profile.as_ref().map(|(_, p)| p.as_ref()); + let made_with = camera_profile.as_ref().map(|(id, _)| id.clone()); let plain = || match (reduced, loader) { - (Some(l), _) => { - l(path, *max_edge).map(|(image, info, reduced)| DecodedSource { reduced, ..DecodedSource::new(Arc::new(image), Some(info)) }) - } - (None, Some(l)) => l(path, *max_edge).map(|(image, info)| DecodedSource::new(Arc::new(image), Some(info))), + (Some(l), _) => l(path, *max_edge, dcp).map(|(image, info, reduced)| DecodedSource { + reduced, + camera_profile: made_with.clone(), + ..DecodedSource::new(Arc::new(image), Some(info)) + }), + (None, Some(l)) => l(path, *max_edge, dcp) + .map(|(image, info)| DecodedSource { camera_profile: made_with.clone(), ..DecodedSource::new(Arc::new(image), Some(info)) }), (None, None) => Err(format!("no decoder available for {path}")), }; // the denoised picture comes with the plain one from a single decode; when it cannot be read the @@ -281,7 +294,7 @@ impl SourceRef { None => true, }; if made { - pair(path, *max_edge, spec).and_then(|(image, twin, info)| { + pair(path, *max_edge, spec, dcp).and_then(|(image, twin, info)| { if spec.make.is_some() && twin.is_none() { return Err("the cached AI Denoise picture could not be read; clear the denoise cache and retry".into()); } @@ -290,6 +303,7 @@ impl SourceRef { info: Some(info), camera_tone: None, denoised: twin.map(|t| Arc::new(Twin::new(Arc::new(t)))), + camera_profile: made_with.clone(), from_proxy: false, reduced: false, }) diff --git a/crates/engine/src/media/tests.rs b/crates/engine/src/media/tests.rs index efa6a504ca..7d5f80b6e5 100644 --- a/crates/engine/src/media/tests.rs +++ b/crates/engine/src/media/tests.rs @@ -83,13 +83,14 @@ fn decoder_info_survives_render_jobs_cache_and_eviction() { job.source = SourceRef::File { path: "synthetic.arw".into(), max_edge: 64, - loader: Some(Arc::new(move |_, _| { + loader: Some(Arc::new(move |_, _, _| { let mut image = Rgb32f::new(64, 64); image.data.fill([0.1; 3]); Ok((image, loaded_info.clone())) })), fallback: None, denoise: None, + camera_profile: None, reduced: None, }; job.info = SourceInfo::default(); // Header facts cannot override decoder facts. @@ -143,9 +144,10 @@ fn old_relative_white_balance_on_a_kelvin_camera_keeps_its_look_and_learns_the_a job.source = SourceRef::File { path: "/photos/DSC00001.ARW".into(), max_edge: 64, - loader: Some(Arc::new(move |_, _| Ok((loaded_pixels.clone(), loaded_info.clone())))), + loader: Some(Arc::new(move |_, _, _| Ok((loaded_pixels.clone(), loaded_info.clone())))), fallback: None, denoise: None, + camera_profile: None, reduced: None, }; let undo_before = s.undo.len(); diff --git a/crates/engine/src/media/thumbnail_hash_tests.rs b/crates/engine/src/media/thumbnail_hash_tests.rs index dccc6c28c0..85089d231d 100644 --- a/crates/engine/src/media/thumbnail_hash_tests.rs +++ b/crates/engine/src/media/thumbnail_hash_tests.rs @@ -6,6 +6,77 @@ fn session() -> crate::Session { s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); s } +/// Settings saved by a newer LightCraft (a process number this build doesn't know) render with +/// this build's latest process, and a build that resolved the number to an older process +/// cached other pixels under the same settings hash: the persistent keys (thumbnails, the +/// loupe's view render, variants) name the process the settings render with, so those are +/// never served (review of 5a7016c8: a catalog saved with a newer process kept main's V2 thumbnails). +#[test] +fn persistent_keys_name_the_process_the_settings_render_with() { + use lightcraft_develop::ProcessVersion; + let mut s = session(); + let newer = DevelopSettings { process: ProcessVersion(ProcessVersion::LATEST.0 + 1), ..DevelopSettings::default() }; + s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(newer.clone()), label: "newer".into(), edited: None }).unwrap(); + let p = s.catalog.photo(PhotoId(1)).unwrap().clone(); + let unnamed = |kind: Option<&str>, size: u64| { + let mut h = Hasher128::new(); + h.str(&content_key(&p)); + if let Some(k) = kind { + h.str(k); + } + h.u64(newer.hash64()).u64(size).u64(RENDER_CACHE_VERSION).u64(crate::camera_profiles::cache_key()).finish() + }; + let named = |kind: Option<&str>, size: u64, process: u64| { + let mut h = Hasher128::new(); + h.str(&content_key(&p)); + if let Some(k) = kind { + h.str(k); + } + h.u64(newer.hash64()).u64(size).u64(RENDER_CACHE_VERSION).u64(process).u64(crate::camera_profiles::cache_key()).finish() + }; + let resolved = u64::from(lightcraft_develop::Process::LATEST.version().0); + let keys = [ + (s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1, None, 256), + (crate::Session::view_key(&p, true, 0), Some("view"), 1), + (crate::Session::variant_key(&p, &newer, 256, 0), Some("variant"), 256), + ]; + for (key, kind, size) in keys { + assert_ne!(key, unnamed(kind, size), "old builds did not name their resolved process"); + assert_eq!(key, named(kind, size, resolved), "the key names the process used for rendering"); + assert_ne!(key, named(kind, size, u64::from(newer.process.0)), "the saved future number is not the resolved process"); + } +} + +/// Photos on V1 and V2 keep the persistent keys builds before process V3 gave them (no process +/// in them), so their cached thumbnails, view renders and variants stay valid after upgrading +/// (review of 26cd2df1: every V1/V2 photo rendered again, and offline ones without smart +/// previews lost their thumbnails); V3 and later name their process. +#[test] +fn v1_and_v2_photos_keep_the_render_cache_keys_they_had() { + use lightcraft_develop::Process; + let mut s = session(); + for process in [Process::V1, Process::V2, Process::V3] { + let settings = DevelopSettings { process: process.version(), ..DevelopSettings::default() }; + s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(settings.clone()), label: "p".into(), edited: None }).unwrap(); + let p = s.catalog.photo(PhotoId(1)).unwrap().clone(); + let before_v3 = |kind: Option<&str>, size: u64| { + let mut h = Hasher128::new(); + h.str(&content_key(&p)); + if let Some(k) = kind { + h.str(k); + } + h.u64(settings.hash64()).u64(size).u64(RENDER_CACHE_VERSION).u64(crate::camera_profiles::cache_key()).finish() + }; + let keys = [ + s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1 == before_v3(None, 256), + crate::Session::view_key(&p, true, 0) == before_v3(Some("view"), 1), + crate::Session::variant_key(&p, &settings, 256, 0) == before_v3(Some("variant"), 256), + ]; + let old = process <= Process::V2; + assert_eq!(keys, [old; 3], "{process:?}: thumbnail, view and variant keys"); + } +} + #[test] fn hashes_match_uncached_keys_and_are_not_recomputed_for_sizes_metadata_or_before() { let mut s = session(); @@ -21,6 +92,7 @@ fn hashes_match_uncached_keys_and_are_not_recomputed_for_sizes_metadata_or_befor .u64(settings) .u64(b as u64) .u64(RENDER_CACHE_VERSION) + .u64(u64::from(p.develop.process.process().version().0)) .u64(crate::camera_profiles::cache_key()) .finish(); let job = s.thumb_job(p.id, edge).unwrap(); @@ -70,7 +142,7 @@ fn hash_cache_is_bounded_weak_and_shared_settings_remain_independent() { #[test] fn source_from_before_content_reload_is_not_accepted() { let mut s = session(); - s.media.file_loader = Some(Arc::new(|_, _| Ok((Rgb32f::new(8, 8), SourceInfo::default())))); + s.media.file_loader = Some(Arc::new(|_, _, _| Ok((Rgb32f::new(8, 8), SourceInfo::default())))); let old = s.thumb_job(PhotoId(1), 256).unwrap().run(); assert!(old.loaded.is_some()); s.catalog @@ -94,7 +166,7 @@ fn source_from_before_content_reload_is_not_accepted() { #[test] fn source_from_before_a_lens_profile_change_is_not_accepted() { let mut s = session(); - s.media.file_loader = Some(Arc::new(|_, _| Ok((Rgb32f::new(8, 8), SourceInfo::default())))); + s.media.file_loader = Some(Arc::new(|_, _, _| Ok((Rgb32f::new(8, 8), SourceInfo::default())))); let old = s.thumb_job(PhotoId(1), 256).unwrap().run(); assert!(old.loaded.is_some()); let lens = lightcraft_develop::EmbeddedLens { source: lightcraft_develop::LensSource::Database, ..Default::default() }; @@ -132,7 +204,7 @@ fn a_hover_preview_key_follows_the_lens_profile() { #[test] fn a_render_that_panics_fails_instead_of_never_answering() { let mut s = session(); - s.media.file_loader = Some(Arc::new(|_, _| panic!("decoder bug"))); + s.media.file_loader = Some(Arc::new(|_, _, _| panic!("decoder bug"))); let mut job = s.thumb_job(PhotoId(1), 256).unwrap(); job.request_id = 42; let (key, level, source_key) = (job.key, job.level, job.source_key); diff --git a/crates/engine/src/presets.rs b/crates/engine/src/presets.rs index 0dee84f3e1..9ce4c3e916 100644 --- a/crates/engine/src/presets.rs +++ b/crates/engine/src/presets.rs @@ -523,7 +523,23 @@ impl Session { if let Some(p) = profile(id) { return Some((p.name, p.group)); } - self.lut_profiles.iter().find(|p| p.id == id).map(|p| (p.name.as_str(), p.group.as_str())) + if let Some(p) = self.lut_profiles.iter().find(|p| p.id == id) { + return Some((p.name.as_str(), p.group.as_str())); + } + self.dcp_profiles.iter().find(|p| p.id == id).map(|p| (p.name.as_str(), crate::cmd::dcp_profiles::DCP_GROUP)) + } + + /// The imported profiles as (id, name, group): LUT profiles, then camera profiles (`.dcp`). A camera profile + /// whose file is missing or damaged (not loaded when the library opened) is left out, so it can't be chosen; its + /// entry stays and it is offered again once the file is back. + pub fn imported_profiles(&self) -> Vec<(String, String, String)> { + let luts = self.lut_profiles.iter().map(|p| (p.id.clone(), p.name.clone(), p.group.clone())); + let dcps = self + .dcp_profiles + .iter() + .filter(|p| self.media.camera_profiles.contains_key(&p.id)) + .map(|p| (p.id.clone(), p.name.clone(), crate::cmd::dcp_profiles::DCP_GROUP.to_string())); + luts.chain(dcps).collect() } /// Remember `id` as the most recently applied profile. @@ -537,28 +553,31 @@ impl Session { pub fn profile_menu(&self) -> Value { let item = |p: &ProfileInfo| json!({"id": p.id, "name": p.name, "group": p.group, "favorite": self.profile_favorites.iter().any(|f| f == p.id)}); - let lut_item = |id: &str| { - self.lut_profiles - .iter() - .find(|p| p.id == id) - .map(|p| json!({"id": p.id, "name": p.name, "group": p.group, "favorite": self.profile_favorites.contains(&p.id), "imported": true})) + let imported = self.imported_profiles(); + let imported_item = |(id, name, group): &(String, String, String)| { + let mut v = json!({"id": id, "name": name, "group": group, "favorite": self.profile_favorites.contains(id), "imported": true}); + if let Some(d) = self.dcp_profiles.iter().find(|d| &d.id == id) { + v["cameraModel"] = json!(d.camera_model); + } + v }; + let lut_item = |id: &str| imported.iter().find(|p| p.0 == id).map(imported_item); let list = |ids: &[String]| ids.iter().filter_map(|id| profile(id).map(item).or_else(|| lut_item(id))).collect::>(); let mut groups: Vec = profile_groups() .into_iter() .map(|g| json!({"name": g, "profiles": PROFILES.iter().filter(|p| p.group == g).map(item).collect::>()})) .collect(); - // imported LUT profiles, by their groups + // imported LUT profiles by their groups, then camera profiles let mut lut_groups: Vec<&str> = self.lut_profiles.iter().map(|p| p.group.as_str()).collect(); lut_groups.sort_unstable(); lut_groups.dedup(); + // the camera profiles' group once, last (a LUT group of the same name joins it rather than showing twice) + lut_groups.retain(|g| *g != crate::cmd::dcp_profiles::DCP_GROUP); + if imported.iter().any(|p| p.2 == crate::cmd::dcp_profiles::DCP_GROUP) { + lut_groups.push(crate::cmd::dcp_profiles::DCP_GROUP); + } for g in lut_groups { - let profiles: Vec = self - .lut_profiles - .iter() - .filter(|p| p.group == g) - .map(|p| json!({"id": p.id, "name": p.name, "group": p.group, "favorite": self.profile_favorites.contains(&p.id), "imported": true})) - .collect(); + let profiles: Vec = imported.iter().filter(|p| p.2 == g).map(imported_item).collect(); groups.push(json!({"name": g, "profiles": profiles, "imported": true})); } json!({ diff --git a/crates/engine/src/slide_title.rs b/crates/engine/src/slide_title.rs index 5885463b1c..0acda876d1 100644 --- a/crates/engine/src/slide_title.rs +++ b/crates/engine/src/slide_title.rs @@ -363,6 +363,7 @@ impl TitleCompose { quick: None, display: None, gpu_fallback: None, + frame: None, } } } diff --git a/crates/engine/src/smart.rs b/crates/engine/src/smart.rs index 156f33d42a..77f78bd299 100644 --- a/crates/engine/src/smart.rs +++ b/crates/engine/src/smart.rs @@ -502,6 +502,7 @@ pub fn load(path: &Path) -> Result { info, camera_tone, denoised: None, + camera_profile: None, from_proxy: true, reduced: false, }) diff --git a/crates/engine/src/sync_same.rs b/crates/engine/src/sync_same.rs new file mode 100644 index 0000000000..0f20dcf571 --- /dev/null +++ b/crates/engine/src/sync_same.rs @@ -0,0 +1,132 @@ +//! Auto Sync carries the active photo's VALUE to every selected photo, as Lightroom Classic does +//! (test notes 2026-10-24 note 18, the user's rule "same value for all synced values"). Where white +//! balance is a mode rather than a number, the mode travels and each photo applies it to itself: +//! As Shot gives each photo its own camera white, Auto each photo's own white from its pixels, a +//! light preset its numbers. +//! +//! A typed or dragged Temp or Tint is set on each photo's own scale: a raw edited in Kelvin gets +//! the same Kelvin (an old relative-scale value converted first, never read as Kelvin, which turned +//! photos blue: test notes 2026-10-15), and only the slider that moved changes (a Temp move keeps +//! each photo's own tint). A photo on another scale than the active one (a JPEG next to a raw) has +//! no "same" number and moves by as much as the active photo instead. + +use std::collections::HashMap; + +use lightcraft_catalog::PhotoId; +use lightcraft_develop::{DevelopSettings, WbMode}; +use lightcraft_pipeline::SourceInfo; + +use crate::Session; + +/// White balance on this source is edited in Kelvin (a raw with a measured camera scale), not on +/// the relative scale (6500 K / 0 = as shot). +fn kelvin(info: &SourceInfo) -> bool { + info.raw && !info.relative_wb +} + +/// The temperature and tint `mode` stands for on a source with `info` (As Shot and the light +/// presets; `None` for Auto and Custom, which need the pixels or the numbers). +fn wb_of_mode(info: &SourceInfo, mode: WbMode) -> Option<(f64, f64)> { + match mode { + WbMode::AsShot => Some((info.as_shot_temp, info.as_shot_tint)), + m => m.preset().map(|(t, ti)| { + // presets are Kelvin on raws with that scale, relative to daylight (6500 K = as shot) elsewhere + if kelvin(info) { (t, ti) } else { (6500.0 * t / 5500.0, ti) } + }), + } +} + +/// `synced.wb` for a photo (source `oinfo`, settings `own` before the sync) when the active +/// photo's white balance went from `old` to `new` (source `ainfo`). `auto`: the photo's own Auto +/// white balance, when `new` is Auto (`None`: it couldn't be worked out, and the photo keeps its +/// white balance). +pub(crate) fn synced_wb( + ainfo: &SourceInfo, + old: &DevelopSettings, + new: &DevelopSettings, + oinfo: &SourceInfo, + own: &DevelopSettings, + auto: Option<(f64, f64)>, + synced: &mut DevelopSettings, +) { + use lightcraft_pipeline::local::{effective_wb, normalize_wb}; + let mut d = own.clone(); + normalize_wb(&mut d, oinfo); + // A light preset with numbers of its own (`develop.wb {mode, tint}` on a photo on the + // relative scale, where the stored numbers are what renders): those numbers travel, as a + // Custom white balance does (review of #3585) + let overridden = new.wb.mode.preset().is_some() + && wb_of_mode(ainfo, new.wb.mode).is_some_and(|(t, ti)| { + let (at, ati) = effective_wb(ainfo, new); + (at - t).abs() > 1e-6 || (ati - ti).abs() > 1e-6 + }); + let mode = if overridden { WbMode::Custom } else { new.wb.mode }; + let resolved = match mode { + WbMode::Auto => auto, + WbMode::Custom => None, + m => wb_of_mode(oinfo, m), + }; + match (mode, resolved) { + (WbMode::Custom, _) => { + let (ot, oti) = effective_wb(oinfo, own); + let (at0, ati0) = effective_wb(ainfo, old); + let (at, ati) = effective_wb(ainfo, new); + let same_scale = kelvin(ainfo) == kelvin(oinfo); + // only what moved: a Temp move leaves each photo's own tint + let pick = |own: f64, was: f64, now: f64| { + if (now - was).abs() < 1e-9 { + own + } else if same_scale { + now + } else { + own + (now - was) + } + }; + d.wb.temp = pick(ot, at0, at); + d.wb.tint = pick(oti, ati0, ati); + d.wb.mode = WbMode::Custom; + } + (m, Some((t, ti))) => { + d.wb.temp = t; + d.wb.tint = ti; + d.wb.mode = m; + } + // Auto couldn't be worked out on this photo (its pixels didn't load): it keeps its own + (_, None) => { + synced.wb = own.wb; + return; + } + } + let (t, ti) = (d.wb.temp, d.wb.tint); + lightcraft_develop::controls::set(&mut d, "wb.temp", t); + lightcraft_develop::controls::set(&mut d, "wb.tint", ti); + synced.wb = d.wb; +} + +impl Session { + /// Each other selected photo's own Auto white balance, worked out on its own pixels, when + /// Auto Sync is about to carry the active photo's (`id`) switch to Auto (`new`) over. Empty + /// otherwise. A photo whose pixels don't load is left out (it keeps its white balance). + pub(crate) fn own_auto_wb(&mut self, id: PhotoId, new: &DevelopSettings, label: &str) -> HashMap { + let mut own = HashMap::new(); + if !self.auto_sync_applies(id, label) || new.wb.mode != WbMode::Auto || self.develop_of(id).is_some_and(|old| old.wb == new.wb) { + return own; + } + let others: Vec = self.selection.ids.iter().copied().filter(|x| *x != id).collect(); + // decoded in parallel, a core's worth at a time: a big selection never holds more + // decoded thumbnails at once than that, whatever the cache keeps + let batch = rayon::current_num_threads().clamp(1, 16); + for chunk in others.chunks(batch) { + for (x, src) in self.sources_now(chunk, crate::media::SourceLevel::Thumb) { + match src { + // with the facts its own decoder gave + Ok((src, info)) => { + own.insert(x, lightcraft_pipeline::auto::auto_wb(&src, &info)); + } + Err(e) => log::warn!("Auto Sync: Auto white balance on photo {}: {e}", x.0), + } + } + } + own + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e571ec1d65..a22547ec4a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7,10 +7,13 @@ mod album_missing; mod album_order; mod album_remove; mod albums_local; +mod autosync_wb; mod color; mod constrain_crop; mod crop_angle; mod crop_aspect; +mod dcp; +mod dcp_corpus; mod denoise; mod export; mod face_models; @@ -49,6 +52,8 @@ mod settings_files; mod shelved_folder; mod slide; mod slideshow_export; +#[cfg(not(target_arch = "wasm32"))] +mod slow_drive; mod spots; mod sync; mod view_follow; diff --git a/crates/engine/src/tests/autosync_wb.rs b/crates/engine/src/tests/autosync_wb.rs new file mode 100644 index 0000000000..1d05ddebf0 --- /dev/null +++ b/crates/engine/src/tests/autosync_wb.rs @@ -0,0 +1,189 @@ +//! LRC-DEV-AUTOSYNC (N-A3, test notes 2026-10-24 note 18): Auto Sync sets every selected photo to +//! the active photo's value, and where white balance is a mode or another scale, each photo applies +//! it to itself. As Shot gives each photo its own camera white, Auto each photo's own from its +//! pixels, a light preset its numbers. A typed or dragged Temp is the same number on each photo of +//! the same scale (the same Kelvin on raws edited in Kelvin; an old relative-scale value converted +//! first, never read as Kelvin), moves a photo of another scale (a JPEG beside a raw) by as much as +//! the active photo, and leaves each photo's own tint. + +use lightcraft_catalog::PhotoId; +use lightcraft_develop::{WbMode, WbScale, WhiteBalance}; +use serde_json::json; + +use crate::Session; + +/// Give photo `id` a decoded raw source (thumbnail and preview) with as-shot white `(temp, tint)`; +/// `legacy`: a camera whose settings without a scale were written on the relative scale; `warm` +/// tints its pixels, so Auto finds another white on each photo. +fn raw_as_shot(s: &mut Session, id: PhotoId, temp: f64, tint: f64, legacy: bool, warm: f32) { + use crate::media::SourceLevel; + let mut img = lightcraft_raster::Rgb32f::new(48, 32); + for (i, px) in img.data.iter_mut().enumerate() { + let v = 0.1 + 0.6 * ((i % 48) as f32 / 48.0); + *px = [v * warm, v, v / warm]; + } + let img = std::sync::Arc::new(img); + let info = + lightcraft_pipeline::SourceInfo { raw: true, legacy_relative_wb: legacy, as_shot_temp: temp, as_shot_tint: tint, ..Default::default() }; + s.media.insert_with_info(id, SourceLevel::Thumb, img.clone(), info.clone()); + s.media.insert_with_info(id, SourceLevel::Preview, img, info); +} + +/// The white balance photo `id` renders with (Kelvin, tint). +fn wb(s: &Session, id: PhotoId) -> (f64, f64) { + lightcraft_pipeline::local::effective_wb(&s.source_info(id), &s.develop_of(id).unwrap()) +} + +fn close(x: (f64, f64), y: (f64, f64)) -> bool { + (x.0 - y.0).abs() < 1.0 && (x.1 - y.1).abs() < 0.5 +} + +/// Three demo photos (a active, b, c) selected, Auto Sync on, each a raw of another as-shot white; +/// c still holds an old relative-scale white (7000 there meant "a little warmer than as shot"). +fn three_raws() -> (Session, [PhotoId; 3]) { + let mut s = Session::with_demo(); + let ids: Vec = s.visible_cloned().into_iter().take(3).collect(); + let (a, b, c) = (ids[0], ids[1], ids[2]); + raw_as_shot(&mut s, a, 5200.0, 4.0, false, 1.0); + raw_as_shot(&mut s, b, 3300.0, -12.0, false, 1.4); + raw_as_shot(&mut s, c, 6100.0, 8.0, true, 0.7); + let mut d = (*s.develop_of(c).unwrap()).clone(); + d.wb = WhiteBalance { mode: WbMode::Custom, temp: 7000.0, tint: 0.0, scale: WbScale::Legacy }; + s.catalog.apply(lightcraft_catalog::Op::SetDevelop { id: c, settings: std::sync::Arc::new(d), label: "x".into(), edited: None }).unwrap(); + s.execute("library.select", &json!({"ids": [a.0, b.0, c.0], "active": a.0})).unwrap(); + s.execute("develop.autoSync", &json!({"on": true})).unwrap(); + (s, [a, b, c]) +} + +/// As Shot and Auto are modes: each photo gets its own camera white, or its own Auto white worked +/// out on its own pixels, never the active photo's numbers. A light preset gives its numbers. +#[test] +fn auto_sync_white_balance_modes_apply_to_each_photo() { + let (mut s, [a, b, c]) = three_raws(); + // As Shot: each photo's own camera white + s.execute("develop.wb", &json!({"mode": "asShot"})).unwrap(); + for (id, own) in [(a, (5200.0, 4.0)), (b, (3300.0, -12.0)), (c, (6100.0, 8.0))] { + assert!(close(wb(&s, id), own), "As Shot on photo {}: {:?}, its own is {own:?}", id.0, wb(&s, id)); + assert_eq!(s.develop_of(id).unwrap().wb.mode, WbMode::AsShot); + } + // a light preset: its numbers on every raw + s.execute("develop.wb", &json!({"mode": "tungsten"})).unwrap(); + for id in [a, b, c] { + assert!(close(wb(&s, id), (2850.0, 0.0)), "Tungsten on photo {}: {:?}", id.0, wb(&s, id)); + } + // Auto: each photo's own, from its own pixels + s.execute("develop.wb", &json!({"mode": "auto"})).unwrap(); + for id in [b, c] { + let src = s.source_now(id, crate::media::SourceLevel::Thumb).unwrap(); + let own = lightcraft_pipeline::auto::auto_wb(&src, &s.source_info(id)); + assert!(close(wb(&s, id), own), "Auto on photo {}: {:?}, its own Auto is {own:?}", id.0, wb(&s, id)); + assert_eq!(s.develop_of(id).unwrap().wb.mode, WbMode::Auto); + } + assert!(!close(wb(&s, a), wb(&s, b)), "not the active photo's Auto copied over: {:?}", wb(&s, a)); + // one undo step puts every photo back + s.execute("edit.undo", &json!({})).unwrap(); + for id in [a, b, c] { + assert!(close(wb(&s, id), (2850.0, 0.0)), "undo, photo {}: {:?}", id.0, wb(&s, id)); + } +} + +/// A Temp typed or dragged from As Shot: the same Kelvin on every raw, each keeping its own tint; +/// the photo holding an old relative-scale value gets the Kelvin too, never read on that scale. +#[test] +fn auto_sync_temp_is_the_same_kelvin_and_keeps_each_photos_tint() { + let (mut s, [a, b, c]) = three_raws(); + s.execute("develop.wb", &json!({"mode": "asShot"})).unwrap(); + // typed + s.execute("develop.set", &json!({"control": "wb.temp", "value": 5600.0})).unwrap(); + assert!(close(wb(&s, a), (5600.0, 4.0)), "a: {:?}", wb(&s, a)); + assert!(close(wb(&s, b), (5600.0, -12.0)), "b keeps its own tint: {:?}", wb(&s, b)); + assert!(close(wb(&s, c), (5600.0, 8.0)), "c keeps its own tint: {:?}", wb(&s, c)); + // a drag, synced on release + s.execute("develop.beginInteraction", &json!({"label": "Temp"})).unwrap(); + for v in [5000.0, 4600.0] { + s.execute("develop.set", &json!({"control": "wb.temp", "value": v})).unwrap(); + } + s.execute("develop.endInteraction", &json!({})).unwrap(); + assert!(close(wb(&s, b), (4600.0, -12.0)) && close(wb(&s, c), (4600.0, 8.0)), "b {:?} c {:?}", wb(&s, b), wb(&s, c)); + // a Tint move: the same tint on every photo, each keeping its Kelvin (all at 4600 here) + s.execute("develop.set", &json!({"control": "wb.tint", "value": 10.0})).unwrap(); + for id in [a, b, c] { + assert!(close(wb(&s, id), (4600.0, 10.0)), "photo {}: {:?}", id.0, wb(&s, id)); + } +} + +/// A photo still holding an old relative-scale value: a Temp synced from a photo in Kelvin reaches +/// it as Kelvin, never as a number on the relative scale (where 6500 is as shot), which turned +/// photos blue (test notes 2026-10-15). Main already got this right; the guard keeps it so. +#[test] +fn auto_sync_temp_never_lands_on_an_old_relative_scale() { + let (mut s, [_, _, c]) = three_raws(); + s.execute("develop.set", &json!({"control": "wb.temp", "value": 5600.0})).unwrap(); + assert!((wb(&s, c).0 - 5600.0).abs() < 1.0, "c renders at {:?}", wb(&s, c)); + assert_eq!(s.develop_of(c).unwrap().wb.scale, WbScale::Kelvin); +} + +/// A JPEG selected with a raw has no "same" Kelvin (its white balance is relative to its own +/// colours): it moves by as much as the raw did. Before, it got the raw's Kelvin number, read on +/// its own scale. +#[test] +fn auto_sync_temp_moves_a_jpeg_by_as_much_as_the_raw() { + let mut s = Session::with_demo(); + let ids: Vec = s.visible_cloned().into_iter().take(2).collect(); + let (a, b) = (ids[0], ids[1]); + raw_as_shot(&mut s, a, 5200.0, 4.0, false, 1.0); + // b: a JPEG (no raw white balance scale: 6500 / 0 = its own colours) + let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::filled(48, 32, [0.4, 0.4, 0.4])); + let info = lightcraft_pipeline::SourceInfo { raw: false, as_shot_temp: 6500.0, as_shot_tint: 0.0, ..Default::default() }; + s.media.insert_with_info(b, crate::media::SourceLevel::Thumb, img.clone(), info.clone()); + s.media.insert_with_info(b, crate::media::SourceLevel::Preview, img, info); + assert!(!s.source_info(b).raw); + s.execute("library.select", &json!({"ids": [a.0, b.0], "active": a.0})).unwrap(); + s.execute("develop.autoSync", &json!({"on": true})).unwrap(); + s.execute("develop.wb", &json!({"mode": "asShot"})).unwrap(); + let before = wb(&s, b); + s.execute("develop.set", &json!({"control": "wb.temp", "value": 5600.0})).unwrap(); + assert!(close(wb(&s, b), (before.0 + 400.0, before.1)), "the JPEG: {:?}, was {before:?}", wb(&s, b)); +} + +/// The other photos' pixels for Auto are read together (in parallel, review of #3571): in the +/// order asked, each photo its own, and a photo the library doesn't have is an error, not a panic. +#[test] +fn sources_for_auto_come_back_in_order_and_per_photo() { + let (mut s, [a, b, c]) = three_raws(); + let want: Vec<_> = [b, c, a].iter().map(|&x| s.source_now(x, crate::media::SourceLevel::Thumb).unwrap()).collect(); + let got = s.sources_now(&[b, PhotoId(u64::MAX), c, a], crate::media::SourceLevel::Thumb); + assert_eq!(got.iter().map(|(x, _)| *x).collect::>(), vec![b, PhotoId(u64::MAX), c, a]); + assert!(got[1].1.is_err()); + for (i, k) in [0, 2, 3].into_iter().enumerate() { + let (img, info) = got[k].1.as_ref().unwrap(); + assert!(std::sync::Arc::ptr_eq(img, &want[i]), "photo {k}"); + // the facts its decoder gave (the as-shot whites differ per photo here) + assert_eq!(info.as_shot_temp, s.source_info(got[k].0).as_shot_temp, "photo {k}"); + } + assert_eq!(got[0].1.as_ref().unwrap().1.as_shot_temp, 3300.0, "b's own"); +} + +/// Review of #3585: a light preset given a tint of its own on a JPEG (where the stored numbers are +/// what renders) carries that tint to the other photos, as a Custom white balance would, not the +/// preset's tint. +#[test] +fn a_preset_with_its_own_tint_on_a_jpeg_carries_that_tint() { + let mut s = Session::with_demo(); + let ids: Vec = s.visible_cloned().into_iter().take(2).collect(); + let (a, b) = (ids[0], ids[1]); + let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::filled(48, 32, [0.4, 0.4, 0.4])); + let info = lightcraft_pipeline::SourceInfo { raw: false, as_shot_temp: 6500.0, as_shot_tint: 0.0, ..Default::default() }; + for id in [a, b] { + s.media.insert_with_info(id, crate::media::SourceLevel::Thumb, img.clone(), info.clone()); + s.media.insert_with_info(id, crate::media::SourceLevel::Preview, img.clone(), info.clone()); + } + s.execute("library.select", &json!({"ids": [a.0, b.0], "active": a.0})).unwrap(); + s.execute("develop.autoSync", &json!({"on": true})).unwrap(); + s.execute("develop.wb", &json!({"mode": "daylight", "tint": 30.0})).unwrap(); + assert!(close(wb(&s, a), (6500.0, 30.0)), "a: {:?}", wb(&s, a)); + assert!(close(wb(&s, b), wb(&s, a)), "b renders a's numbers: {:?}", wb(&s, b)); + // a plain preset still gives the preset's numbers + s.execute("develop.wb", &json!({"mode": "shade"})).unwrap(); + assert!(close(wb(&s, b), (6500.0 * 7500.0 / 5500.0, 10.0)), "b: {:?}", wb(&s, b)); +} diff --git a/crates/engine/src/tests/dcp.rs b/crates/engine/src/tests/dcp.rs new file mode 100644 index 0000000000..87f926f591 --- /dev/null +++ b/crates/engine/src/tests/dcp.rs @@ -0,0 +1,563 @@ +//! Imported camera profiles (`.dcp`): import, choosing one for a raw photo, decoding with it, the +//! source cache, persistence and deletion. Profiles are built in memory (no profile file is committed). + +use std::path::PathBuf; + +use lightcraft_catalog::PhotoId; +use lightcraft_raw::dcp::{DcpProfile, write_dcp}; +use lightcraft_raw::{ColorData, Mat3}; +use serde_json::json; + +use crate::Session; +use crate::media::SourceRef; + +fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lc-dcp-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// A profile whose matrix swaps the camera's red and blue (our own numbers): photos developed with it +/// come out with red and blue exchanged, which is easy to see in a test. +fn swapping_profile(name: &str) -> DcpProfile { + let m = Mat3([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]); + let xyz_to_cam = m.mul(&Mat3([[3.2406, -1.5372, -0.4986], [-0.9689, 1.8758, 0.0415], [0.0557, -0.2040, 1.0570]])); + DcpProfile { + name: name.into(), + camera_model: "LightCraft Test Camera".into(), + color: ColorData { illuminant: [21, 0], color_matrix: [Some(xyz_to_cam), None], ..Default::default() }, + } +} + +fn mean_rgb(img: &lightcraft_raster::Rgb32f) -> [f32; 3] { + let n = img.data.len().max(1) as f32; + let s = img.data.iter().fold([0.0f32; 3], |a, p| [a[0] + p[0], a[1] + p[1], a[2] + p[2]]); + [s[0] / n, s[1] / n, s[2] / n] +} + +#[test] +fn a_camera_profile_replaces_the_raw_colour_model_when_decoding() { + let dng = crate::tests_xmp::synthetic_dng_with(None, Default::default()); + let (plain, plain_info) = crate::files::load_bytes(&dng, 64).unwrap(); + let p = swapping_profile("Swap"); + let (with, info) = crate::files::load_bytes_with(&dng, 64, Some(&p)).unwrap(); + let (a, b) = (mean_rgb(&plain), mean_rgb(&with)); + assert!((a[0] - b[0]).abs() > 1e-3 || (a[2] - b[2]).abs() > 1e-3, "the profile changes the colour: {a:?} vs {b:?}"); + // white balance at render time works from the profile's matrices + let tags = &info.camera_color.as_ref().expect("a matrix colour model").tags; + assert_eq!(tags.color_matrix, p.color.color_matrix); + assert_ne!(plain_info.camera_color.as_ref().map(|c| c.tags.color_matrix), Some(p.color.color_matrix)); +} + +#[test] +fn a_profile_without_a_tone_curve_keeps_the_photos_contrast() { + use lightcraft_raw::profile::ToneCurve; + // a DNG with a tone curve of its own (our numbers: 18 % grey → 30 %) + let plain = crate::tests_xmp::synthetic_dng_with(None, Default::default()); + let mut raw = lightcraft_raw::decode(&plain).unwrap(); + raw.color.profile.tone_curve = ToneCurve::from_tag(&[0.0, 0.0, 0.18, 0.3, 1.0, 1.0]); + let dng = lightcraft_raw::write_dng(&raw, &Default::default()).unwrap(); + // a chart-style profile (no curve) keeps the file's curve + let (_, info) = crate::files::load_bytes_with(&dng, 64, Some(&swapping_profile("Swap"))).unwrap(); + let tone = info.camera_tone.expect("the file's tone curve stays"); + assert!((tone.apply(0.18) - 0.3).abs() < 0.01, "{}", tone.apply(0.18)); + // a profile with a curve of its own uses that one (18 % → 45 %) + let mut curved = swapping_profile("Curved"); + curved.color.profile.tone_curve = ToneCurve::from_tag(&[0.0, 0.0, 0.18, 0.45, 1.0, 1.0]); + let (_, info) = crate::files::load_bytes_with(&dng, 64, Some(&curved)).unwrap(); + let tone = info.camera_tone.expect("the profile's tone curve"); + assert!((tone.apply(0.18) - 0.45).abs() < 0.01, "{}", tone.apply(0.18)); +} + +#[test] +fn import_choose_cache_persist_and_delete() { + let dir = temp_dir("session"); + let (lib, files) = (dir.join("lib"), dir.join("files")); + std::fs::create_dir_all(files.join("profiles")).unwrap(); + let raw = files.join("IMG_0001.dng"); + std::fs::write(&raw, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); + std::fs::write(files.join("profiles").join("Swap.dcp"), write_dcp(&swapping_profile("Swap")).unwrap()).unwrap(); + std::fs::write(files.join("profiles").join("Broken.dcp"), b"IIRC\x08\0\0\0junk").unwrap(); + let id; + let dcp_id; + { + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let r = s.execute("library.import", &json!({"paths": [raw.to_string_lossy()]})).unwrap(); + id = PhotoId(r["imported"][0].as_u64().unwrap()); + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + // a folder: the good profile comes in, the broken one is reported + let r = s.execute("profile.import", &json!({"paths": [files.join("profiles").to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"].as_array().unwrap().len(), 1, "{r}"); + assert_eq!(r["failed"].as_array().unwrap().len(), 1, "{r}"); + dcp_id = r["imported"][0]["id"].as_str().unwrap().to_string(); + assert!(dcp_id.starts_with("dcp:")); + assert_eq!(r["imported"][0]["cameraModel"], "LightCraft Test Camera"); + // importing it again adds nothing + let again = s.execute("profile.import", &json!({"paths": [files.join("profiles").join("Swap.dcp").to_string_lossy()]})).unwrap(); + assert_eq!(again["imported"][0]["existing"], true); + // a single .dcp file is a camera profile only, not also a LUT that "couldn't be read" + assert_eq!(again["failed"], json!([]), "{again}"); + assert_eq!(s.dcp_profiles.len(), 1); + // the library keeps its own copy + assert!(std::path::Path::new(&s.dcp_profiles[0].file).starts_with(&lib)); + // listed in the profile menu under Camera Profiles + let menu = s.profile_menu(); + let group = menu["groups"].as_array().unwrap().iter().find(|g| g["name"] == "Camera Profiles").expect("a Camera Profiles group"); + assert_eq!(group["profiles"][0]["id"], dcp_id.as_str()); + // develop the photo with it: a decode made without it doesn't stand in + let before = s.render_job(id, 48, 48, false, true).unwrap().run(); + let loaded = before.loaded.clone().expect("decoded from the file"); + assert!(loaded.camera_profile.is_none()); + s.media.insert(id, before.level, loaded.image.clone()); + assert!(matches!(s.render_job(id, 48, 48, false, true).unwrap().source, SourceRef::Loaded(_)), "cached while nothing changed"); + s.execute("develop.profile", &json!({"id": dcp_id})).unwrap(); + let job = s.render_job(id, 48, 48, false, true).unwrap(); + match &job.source { + SourceRef::File { camera_profile: Some((pid, _)), .. } => assert!(pid.starts_with(&format!("{dcp_id}#")), "{pid}"), + _ => panic!("the photo is decoded again with its camera profile"), + } + let after = job.run(); + assert_eq!( + after.loaded.as_ref().and_then(|l| l.camera_profile.clone()), + s.media.camera_profile_of(s.catalog.photo(id).unwrap()).map(|c| c.0) + ); + assert!(after.rendered.is_ok()); + assert_ne!(mean_rgb(&before.loaded.unwrap().image), mean_rgb(&after.loaded.unwrap().image)); + s.persist().unwrap(); + s.close_library().unwrap(); + } + // reopened: the profile is there and decodes again + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + assert_eq!(s.dcp_profiles.len(), 1); + assert!(s.media.camera_profiles.contains_key(&dcp_id)); + assert_eq!(s.catalog.photo(id).unwrap().develop.profile.id, dcp_id); + assert_eq!(s.profile_info(&dcp_id).map(|(_, g)| g), Some("Camera Profiles")); + // deleted: photos using it develop with their file's own colour, the library's copy goes + let file = s.dcp_profiles[0].file.clone(); + s.execute("profile.deleteImported", &json!({"id": dcp_id})).unwrap(); + assert!(s.dcp_profiles.is_empty() && !std::path::Path::new(&file).exists()); + let p = s.catalog.photo(id).unwrap().clone(); + assert!(s.media.camera_profile_of(&p).is_none()); + assert!(s.execute("develop.profile", &json!({"id": dcp_id})).is_err(), "no longer a known profile"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Hovering a camera profile (the loupe's preview, the browser's thumbnails) develops the photo with +/// it, and hovering a built-in profile while one is applied develops without it. Before, both used +/// the photo's own decode: a camera profile's colour never showed in a hover. +#[test] +fn hover_previews_and_browser_thumbnails_decode_with_the_hovered_camera_profile() { + let dir = temp_dir("hover"); + let (lib, files) = (dir.join("lib"), dir.join("files")); + std::fs::create_dir_all(&files).unwrap(); + let raw = files.join("IMG_0002.dng"); + std::fs::write(&raw, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); + let dcp_file = files.join("Swap.dcp"); + std::fs::write(&dcp_file, write_dcp(&swapping_profile("Swap")).unwrap()).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let r = s.execute("library.import", &json!({"paths": [raw.to_string_lossy()]})).unwrap(); + let id = PhotoId(r["imported"][0].as_u64().unwrap()); + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + let dcp_id = + s.execute("profile.import", &json!({"paths": [dcp_file.to_string_lossy()]})).unwrap()["imported"][0]["id"].as_str().unwrap().to_string(); + let mean = |j: crate::media::RenderJob| { + let img = j.run().rendered.unwrap().image; + let n = img.data.len().max(1) as f64; + img.data.iter().fold([0.0f64; 3], |a, p| [a[0] + f64::from(p[0]) / n, a[1] + f64::from(p[1]) / n, a[2] + f64::from(p[2]) / n]) + }; + let differ = |a: [f64; 3], b: [f64; 3]| a.iter().zip(b).any(|(x, y)| (x - y).abs() > 2.0); + let close = |a: [f64; 3], b: [f64; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.6); + let own = (*s.develop_of(id).unwrap()).clone(); + let mut hovered = own.clone(); + hovered.profile.id = dcp_id.clone(); + let builtin = mean(s.render_job(id, 64, 64, false, true).unwrap()); + let hover = mean(s.preview_job(id, 64, 64, true, &hovered).unwrap()); + assert!(differ(hover, builtin), "the hover shows the camera profile: {hover:?} vs {builtin:?}"); + // the browser's thumbnail too, under its own cache key + let (va, vb) = (s.variant_job(id, &own, 64).unwrap(), s.variant_job(id, &hovered, 64).unwrap()); + assert_ne!(va.cache.as_ref().unwrap().1, vb.cache.as_ref().unwrap().1); + assert!(matches!(&vb.source, SourceRef::File { camera_profile: Some(_), .. }), "decoded with the camera profile"); + assert!(differ(mean(va), mean(vb))); + // selected: the same picture as the hover; hovering the built-in profile then: without it + s.execute("develop.profile", &json!({"id": dcp_id})).unwrap(); + let selected = mean(s.render_job(id, 64, 64, false, true).unwrap()); + assert!(close(hover, selected), "{hover:?} vs {selected:?}"); + let back = mean(s.preview_job(id, 64, 64, true, &own).unwrap()); + assert!(close(back, builtin), "{back:?} vs {builtin:?}"); + // the profile's file replaced under the same id: the hover's key changes with it, so the old picture isn't + // taken for current (CodeRabbit on #1063) + let before = s.preview_job(id, 64, 64, true, &hovered).unwrap().key; + s.media.camera_profiles.get_mut(&dcp_id).unwrap().fingerprint ^= 0x10; + assert_ne!(s.preview_job(id, 64, 64, true, &hovered).unwrap().key, before); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A library with one raw photo and the `Swap` profile imported from `files//Swap.dcp` and selected for it. +fn library_with_profile(dir: &std::path::Path) -> (Session, PhotoId, String) { + let (lib, files) = (dir.join("lib"), dir.join("files")); + std::fs::create_dir_all(files.join("a")).unwrap(); + let raw = files.join("IMG_0003.dng"); + std::fs::write(&raw, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); + std::fs::write(files.join("a").join("Swap.dcp"), write_dcp(&swapping_profile("Swap")).unwrap()).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let r = s.execute("library.import", &json!({"paths": [raw.to_string_lossy()]})).unwrap(); + let id = PhotoId(r["imported"][0].as_u64().unwrap()); + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + let r = s.execute("profile.import", &json!({"paths": [files.join("a").join("Swap.dcp").to_string_lossy()]})).unwrap(); + let dcp_id = r["imported"][0]["id"].as_str().unwrap().to_string(); + s.execute("develop.profile", &json!({"id": dcp_id})).unwrap(); + (s, id, dcp_id) +} + +/// The thumbnail, browser-thumbnail and loupe cache keys of photo `id` (as it is now), and its source tag. +fn render_keys(s: &mut Session, id: PhotoId) -> [lightcraft_preview::Hash128; 3] { + let settings = (*s.develop_of(id).unwrap()).clone(); + [ + s.thumb_job(id, 256).unwrap().cache.unwrap().1, + s.variant_job(id, &settings, 64).unwrap().cache.unwrap().1, + s.loupe_job(id, 200, 200, true).unwrap().view_cache.unwrap().1, + ] +} + +/// A camera profile deleted, or replaced by a different file under the same id, never has renders or decoded +/// sources made with the old one stand in: before, the cache keys followed only the profile id, which the photo keeps. +#[test] +fn a_deleted_or_replaced_camera_profile_never_reuses_renders_made_with_it() { + let dir = temp_dir("replace"); + let (mut s, id, dcp_id) = library_with_profile(&dir); + let with = render_keys(&mut s, id); + let level = s.render_job(id, 48, 48, false, true).unwrap().level; + let old_tag = s.media.camera_profile_of(s.catalog.photo(id).unwrap()).map(|c| c.0); + assert!(old_tag.is_some()); + // deleted: the photo keeps the id, renders without the profile, under other keys + s.execute("profile.deleteImported", &json!({"id": dcp_id})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().develop.profile.id, dcp_id); + let without = render_keys(&mut s, id); + for (a, b) in with.iter().zip(&without) { + assert_ne!(a, b, "a render made with the deleted profile would stand in"); + } + // another profile under the same file name gets the same id back, and other keys again + let other_dir = dir.join("files").join("b"); + std::fs::create_dir_all(&other_dir).unwrap(); + let mut other = swapping_profile("Swap"); + other.color.color_matrix = [Some(Mat3([[3.2406, -1.5372, -0.4986], [-0.9689, 1.8758, 0.0415], [0.0557, -0.2040, 1.0570]])), None]; + std::fs::write(other_dir.join("Swap.dcp"), write_dcp(&other).unwrap()).unwrap(); + let r = s.execute("profile.import", &json!({"paths": [other_dir.join("Swap.dcp").to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"][0]["id"], dcp_id.as_str(), "{r}"); + let replaced = render_keys(&mut s, id); + for ((a, b), c) in with.iter().zip(&without).zip(&replaced) { + assert_ne!(a, c, "a render made with the replaced profile would stand in"); + assert_ne!(b, c); + } + // nor does a source decoded with the old file + let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::new(4, 4)); + s.media.insert_source(id, level, crate::media::DecodedSource { camera_profile: old_tag, ..crate::media::DecodedSource::new(img, None) }); + assert!(!matches!(s.render_job(id, 48, 48, false, true).unwrap().source, SourceRef::Loaded(_)), "decoded again with the new file"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A grid thumbnail is cut from the photo's decoded preview only when that preview was decoded with the camera profile +/// the photo uses now; before, one made with another profile (or none) was fitted and cached under the new key. +#[test] +fn a_thumbnail_is_not_cut_from_a_preview_decoded_with_another_camera_profile() { + let dir = temp_dir("fit"); + let (mut s, id, _) = library_with_profile(&dir); + let p = (**s.catalog.photo(id).unwrap()).clone(); + let tag = s.media.camera_profile_of(&p).map(|c| c.0); + let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::new(1600, 1000)); + let preview = |camera_profile| crate::media::DecodedSource { camera_profile, ..crate::media::DecodedSource::new(img.clone(), None) }; + use crate::media::SourceLevel; + s.media.insert_source(id, SourceLevel::Preview, preview(None)); + assert!(!matches!(s.media.source_ref(&p, SourceLevel::Thumb), SourceRef::Fit { .. }), "decoded without the profile"); + s.media.insert_source(id, SourceLevel::Preview, preview(tag)); + assert!(matches!(s.media.source_ref(&p, SourceLevel::Thumb), SourceRef::Fit { .. }), "decoded with it: still cut from it"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A library moved (or restored) elsewhere finds its camera profiles in its own `Profiles/` folder, and a camera +/// profile can be a favourite, which survives reopening like the recent list. +#[test] +fn a_moved_library_keeps_its_camera_profiles_and_their_favourites() { + let dir = temp_dir("moved"); + let (mut s, id, dcp_id) = library_with_profile(&dir); + assert_eq!(s.execute("profile.favorite", &json!({"id": dcp_id})).unwrap()["favorite"], true); + assert!(s.profile_recent.contains(&dcp_id)); + s.persist().unwrap(); + s.close_library().unwrap(); + drop(s); + let moved = dir.join("moved"); + std::fs::rename(dir.join("lib"), &moved).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&moved, false).unwrap(); + assert!(s.media.camera_profiles.contains_key(&dcp_id), "the profile is found in the moved library"); + assert!(std::path::Path::new(&s.dcp_profiles[0].file).starts_with(&moved), "{}", s.dcp_profiles[0].file); + assert!(s.media.camera_profile_of(s.catalog.photo(id).unwrap()).is_some()); + assert!(s.profile_favorites.contains(&dcp_id) && s.profile_recent.contains(&dcp_id)); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +fn distance(a: [f32; 3], b: [f32; 3]) -> f32 { + (0..3).map(|i| (a[i] - b[i]).abs()).sum() +} + +/// A smart preview keeps the file's own colour: Build Smart Previews never develops it with the photo's imported +/// camera profile, nor takes a cached source decoded with it. Before, only the stale-proxy refresh left the profile out. +#[test] +fn smart_previews_are_built_without_the_imported_camera_profile() { + use crate::media::{DecodedSource, SourceLevel}; + let dir = temp_dir("smart"); + let (mut s, id, _) = library_with_profile(&dir); + let p = (**s.catalog.photo(id).unwrap()).clone(); + s.execute("library.smartPreviews", &json!({"ids": [id.0], "discard": true})).unwrap(); + // a cached preview decoded with the profile (flat magenta, so it shows if the proxy is cut from it) + let tag = s.media.camera_profile_of(&p).map(|c| c.0); + let mut magenta = lightcraft_raster::Rgb32f::new(8, 8); + magenta.data.iter_mut().for_each(|px| *px = [1.0, 0.0, 1.0]); + s.media.insert_source(id, SourceLevel::Preview, DecodedSource { camera_profile: tag, ..DecodedSource::new(std::sync::Arc::new(magenta), None) }); + let r = s.execute("library.smartPreviews", &json!({"ids": [id.0]})).unwrap(); + assert_eq!((r["built"].as_u64(), r["repaired"].as_u64()), (Some(1), Some(0)), "{r}"); + let smart_dir = s.media.smart_dir.clone().unwrap(); + let proxy = crate::smart::load(&crate::smart::existing_file_path(&smart_dir, crate::smart::sharded_file_path(&smart_dir, &p))).unwrap(); + let got = mean_rgb(&proxy.image); + let dng = std::fs::read(dir.join("files").join("IMG_0003.dng")).unwrap(); + let edge = SourceLevel::Preview.max_edge(); + let plain = mean_rgb(&crate::files::load_bytes(&dng, edge).unwrap().0); + let with = mean_rgb(&crate::files::load_bytes_with(&dng, edge, Some(&swapping_profile("Swap"))).unwrap().0); + assert!(distance(got, plain) < distance(got, with), "the proxy has the file's own colour: {got:?}, plain {plain:?}, profiled {with:?}"); + // nor from the file developed with the profile + s.media.forget(id); + s.execute("library.smartPreviews", &json!({"ids": [id.0], "discard": true})).unwrap(); + s.execute("library.smartPreviews", &json!({"ids": [id.0]})).unwrap(); + let proxy = crate::smart::load(&crate::smart::existing_file_path(&smart_dir, crate::smart::sharded_file_path(&smart_dir, &p))).unwrap(); + let got = mean_rgb(&proxy.image); + assert!(distance(got, plain) < distance(got, with), "the proxy has the file's own colour: {got:?}, plain {plain:?}, profiled {with:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// While the original is offline, a cached smart preview stands in for a photo developed with an imported camera +/// profile: it has no profile and decoding it again gives the same picture. Before, it was decoded again for every +/// render. Once the original is back, the photo is decoded from it with its profile. +#[test] +fn a_cached_smart_preview_stands_in_while_the_original_is_offline() { + use crate::media::{DecodedSource, SourceLevel, SourceRef}; + let dir = temp_dir("proxy-offline"); + let (mut s, id, _) = library_with_profile(&dir); + let p = (**s.catalog.photo(id).unwrap()).clone(); + assert!(s.media.camera_profile_of(&p).is_some()); + let proxy = DecodedSource { from_proxy: true, ..DecodedSource::new(std::sync::Arc::new(lightcraft_raster::Rgb32f::new(8, 8)), None) }; + s.media.insert_source(id, SourceLevel::Preview, proxy); + let offline = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); + let probe_offline = offline.clone(); + s.media.availability.set_probe(std::sync::Arc::new(move |path: &str| { + !(path.ends_with("IMG_0003.dng") && probe_offline.load(std::sync::atomic::Ordering::Relaxed)) && std::path::Path::new(path).exists() + })); + assert!(matches!(s.media.source_ref(&p, SourceLevel::Preview), SourceRef::Loaded(a) if a.from_proxy), "the proxy stands in"); + assert!(matches!(s.media.source_ref(&p, SourceLevel::Thumb), SourceRef::Fit { .. }), "the thumbnail is cut from it"); + offline.store(false, std::sync::atomic::Ordering::Relaxed); + assert!(!matches!(s.media.source_ref(&p, SourceLevel::Preview), SourceRef::Loaded(_)), "the original is back: decoded with the profile"); + assert!(!matches!(s.media.source_ref(&p, SourceLevel::Thumb), SourceRef::Fit { .. })); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The decoder facts reported for a photo come from a cached source developed with the camera profile it uses now; +/// before, a thumbnail decoded with another profile (or none) answered first. +#[test] +fn source_facts_come_from_a_source_developed_with_the_current_camera_profile() { + use crate::media::{DecodedSource, SourceLevel}; + let dir = temp_dir("facts"); + let (mut s, id, _) = library_with_profile(&dir); + let tag = s.media.camera_profile_of(s.catalog.photo(id).unwrap()).map(|c| c.0); + let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::new(4, 4)); + let facts = |temp: f64, camera_profile| DecodedSource { + camera_profile, + ..DecodedSource::new(img.clone(), Some(lightcraft_pipeline::SourceInfo { as_shot_temp: temp, ..Default::default() })) + }; + s.media.insert_source(id, SourceLevel::Thumb, facts(3100.0, None)); + s.media.insert_source(id, SourceLevel::Preview, facts(6200.0, tag)); + assert_eq!(s.source_info(id).as_shot_temp, 6200.0); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The Before side (and its region renders) decodes with the Before settings' camera profile — here none, the +/// import defaults — not with the edit's: before, it reused or decoded a source developed with the edit's profile. +#[test] +fn the_before_side_decodes_with_its_own_camera_profile() { + use crate::media::{DecodedSource, SourceLevel}; + let dir = temp_dir("before"); + let (mut s, id, _) = library_with_profile(&dir); + let camera = |job: &crate::media::RenderJob| match &job.source { + SourceRef::File { camera_profile, .. } => camera_profile.as_ref().map(|c| c.0.clone()), + SourceRef::Loaded(a) => a.camera_profile.clone(), + _ => None, + }; + s.media.forget(id); + let after = s.render_job(id, 256, 256, false, true).unwrap(); + let tag = camera(&after); + assert!(tag.is_some(), "the edit develops with the imported profile"); + let before = s.render_job(id, 256, 256, true, true).unwrap(); + assert_eq!(camera(&before), None, "the Before side develops with the file's own colour"); + // nor does a cached source developed with the edit's profile stand in for it + for level in [SourceLevel::Thumb, SourceLevel::Preview, SourceLevel::Full] { + let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::new(4, 4)); + s.media.insert_source(id, level, DecodedSource { camera_profile: tag.clone(), ..DecodedSource::new(img, None) }); + } + let before = s.render_job(id, 256, 256, true, true).unwrap(); + assert!(!matches!(before.source, SourceRef::Loaded(_)), "the Before side is decoded afresh"); + assert_eq!(camera(&before), None); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A profile whose copy into the library fails is reported as failed on its own: the profiles imported with +/// it stay imported (and are saved), and the command does not fail. +#[test] +fn a_profile_that_cannot_be_copied_fails_on_its_own() { + let dir = temp_dir("copy-fails"); + let (lib, files) = (dir.join("lib"), dir.join("files")); + std::fs::create_dir_all(&files).unwrap(); + for name in ["A", "B"] { + std::fs::write(files.join(format!("{name}.dcp")), write_dcp(&swapping_profile(name)).unwrap()).unwrap(); + } + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + // a folder where B's copy goes: writing it fails + let blocked = lib.join("Profiles").join(format!("{}.dcp", crate::presets::slug("LightCraft Test Camera-B"))); + std::fs::create_dir_all(&blocked).unwrap(); + let r = s.execute("profile.import", &json!({"paths": [files.to_string_lossy()]})).unwrap(); + let imported: Vec<&str> = r["imported"].as_array().unwrap().iter().filter_map(|p| p["name"].as_str()).collect(); + assert_eq!(imported, ["A"], "{r}"); + let failed = r["failed"].as_array().unwrap(); + assert_eq!(failed.len(), 1, "{r}"); + assert!(failed[0][0].as_str().is_some_and(|f| f.ends_with("B.dcp")), "{r}"); + assert_eq!(s.dcp_profiles.iter().map(|p| p.name.as_str()).collect::>(), ["A"]); + assert!(blocked.is_dir(), "the folder in the way is left alone"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A file that is neither a `.cube`, a `.dcp` nor a `.zip` is reported as failed instead of being passed over. +#[test] +fn importing_an_unsupported_profile_file_reports_it() { + let dir = temp_dir("unsupported"); + let notes = dir.join("notes.txt"); + std::fs::write(¬es, "not a profile").unwrap(); + let mut s = Session::new(); + let r = s.execute("profile.import", &json!({"paths": [notes.to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(0), "{r}"); + assert_eq!(r["failed"], json!([["notes", "not a .cube, .dcp or .zip file"]]), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A library copy that can't be removed keeps its profile: the command fails and nothing is forgotten, so the +/// library never holds a profile file it no longer lists (CodeRabbit on #1063). +#[test] +fn a_profile_whose_copy_cannot_be_deleted_stays() { + let dir = temp_dir("delete-fails"); + let (mut s, _, dcp_id) = library_with_profile(&dir); + let file = s.dcp_profiles.iter().find(|p| p.id == dcp_id).map(|p| PathBuf::from(&p.file)).unwrap(); + // a folder in the copy's place: removing it as a file fails (as a file in use does) + std::fs::remove_file(&file).unwrap(); + std::fs::create_dir_all(&file).unwrap(); + let r = s.execute("profile.deleteCamera", &json!({"id": dcp_id})); + assert!(r.is_err(), "{r:?}"); + assert!(s.dcp_profiles.iter().any(|p| p.id == dcp_id), "the profile is still listed"); + // gone already: deleting just forgets it + std::fs::remove_dir_all(&file).unwrap(); + s.execute("profile.deleteCamera", &json!({"id": dcp_id})).unwrap(); + assert!(s.dcp_profiles.iter().all(|p| p.id != dcp_id)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A listed path that climbs out of the profiles folder with `..` is not the library's copy: deleting the profile +/// leaves that file alone (CodeRabbit on #1063). +#[test] +fn deleting_a_profile_never_follows_dot_dot_out_of_the_profiles_folder() { + let dir = temp_dir("delete-dotdot"); + let (mut s, _, dcp_id) = library_with_profile(&dir); + let entry = s.dcp_profiles.iter_mut().find(|p| p.id == dcp_id).unwrap(); + let profiles = PathBuf::from(&entry.file).parent().unwrap().to_path_buf(); + let outside = profiles.parent().unwrap().join("keep.txt"); + std::fs::write(&outside, b"the user's").unwrap(); + entry.file = profiles.join("..").join("keep.txt").to_string_lossy().into_owned(); + s.execute("profile.deleteCamera", &json!({"id": dcp_id})).unwrap(); + assert!(s.dcp_profiles.iter().all(|p| p.id != dcp_id), "forgotten"); + assert!(outside.exists(), "the file outside the profiles folder stays"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// CodeRabbit on #1063: a camera profile whose library copy is missing or damaged when the library opens stayed in the +/// profile browser and `develop.profile` accepted it, and the photo then silently developed with the raw's own +/// colour. It is no longer offered or accepted; its entry stays, and once the file is back it is offered again. +#[test] +fn a_damaged_camera_profile_is_not_offered_until_its_file_is_back() { + let dir = temp_dir("damaged"); + let (mut s, _id, dcp_id) = library_with_profile(&dir); + let file = std::path::PathBuf::from(&s.dcp_profiles[0].file); + s.persist().unwrap(); + s.close_library().unwrap(); + drop(s); + let good = std::fs::read(&file).unwrap(); + std::fs::write(&file, b"not a profile").unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(dir.join("lib"), false).unwrap(); + assert_eq!(s.dcp_profiles.len(), 1, "the entry stays"); + assert!(!s.imported_profiles().iter().any(|p| p.0 == dcp_id), "not offered"); + let menu = s.profile_menu().to_string(); + assert!(!menu.contains(&dcp_id), "not in the profile menu: {menu}"); + assert!(s.execute("develop.profile", &json!({"id": dcp_id})).is_err(), "not accepted"); + s.close_library().unwrap(); + drop(s); + std::fs::write(&file, good).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(dir.join("lib"), false).unwrap(); + assert!(s.imported_profiles().iter().any(|p| p.0 == dcp_id), "offered again"); + s.execute("develop.profile", &json!({"id": dcp_id})).unwrap(); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// CodeRabbit on #1063: a LUT profile group named like the camera profiles' ("Camera Profiles") that doesn't sort last +/// made the profile menu list that group twice, each with the same profiles. It is one group, last. +#[test] +fn a_lut_group_named_camera_profiles_joins_the_camera_profiles_group() { + let dir = temp_dir("group"); + let (mut s, _id, dcp_id) = library_with_profile(&dir); + for (id, group) in [("lut:a", crate::cmd::dcp_profiles::DCP_GROUP), ("lut:z", "Zebra")] { + s.lut_profiles.push(crate::cmd::lut_profiles::LutProfile { id: id.into(), name: id.into(), group: group.into(), file: String::new() }); + } + let menu = s.profile_menu(); + let groups: Vec<&str> = menu["groups"].as_array().unwrap().iter().filter_map(|g| g["name"].as_str()).collect(); + assert_eq!(groups.iter().filter(|g| **g == crate::cmd::dcp_profiles::DCP_GROUP).count(), 1, "{groups:?}"); + assert_eq!(groups.last(), Some(&crate::cmd::dcp_profiles::DCP_GROUP), "{groups:?}"); + let ids: Vec<&str> = menu["groups"] + .as_array() + .unwrap() + .iter() + .filter(|g| g["name"] == crate::cmd::dcp_profiles::DCP_GROUP) + .flat_map(|g| g["profiles"].as_array().unwrap().iter().filter_map(|p| p["id"].as_str())) + .collect(); + assert!(ids.contains(&"lut:a") && ids.contains(&dcp_id.as_str()), "{ids:?}"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A `.dcp` file larger than the parser accepts is refused while it is read, before the whole file is loaded into +/// memory (CodeRabbit on #1063): the import reports it as failed with its own reason. +#[test] +fn an_oversized_camera_profile_is_refused_while_it_is_read() { + let dir = temp_dir("oversized"); + let big = dir.join("Big.dcp"); + let mut bytes = write_dcp(&swapping_profile("Big")).unwrap(); + bytes.truncate(4); + std::fs::write(&big, &bytes).unwrap(); + std::fs::OpenOptions::new().write(true).open(&big).unwrap().set_len(lightcraft_raw::dcp::MAX_DCP_BYTES + 1).unwrap(); + let mut s = Session::new(); + let r = s.execute("profile.import", &json!({"paths": [big.to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"], json!([]), "{r}"); + assert_eq!(r["failed"][0][1], json!("the camera profile is larger than 64 MiB"), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/tests/dcp_corpus.rs b/crates/engine/src/tests/dcp_corpus.rs new file mode 100644 index 0000000000..48ed68467d --- /dev/null +++ b/crates/engine/src/tests/dcp_corpus.rs @@ -0,0 +1,243 @@ +//! A real camera profile end to end: the Nikon D750 ColorChecker DCP and chart NEFs dieli released +//! under CC0 (github.com/dieli/d750-lightcraft-colorchecker, pinned in `D750_COLORCHECKER`, +//! xtask/src/main.rs; `cargo xtask corpus --download`). Each chart is imported, developed with the +//! imported profile, white balanced on the second-lightest grey patch (as in the reference) and +//! exported as sRGB; the 24 patches are then compared in CIELAB (ΔE2000) with Lightroom Classic +//! 15.6's render of the same NEF with the same profile. +//! +//! The comparison is lenient on purpose: the profile is matrix-only, so the colour model is the same, +//! but Lightroom adds its own default tone curve and rendering, which LightCraft does not copy. The +//! test pins the measured agreement against regressions (see `MEAN_LIMIT`, `MAX_LIMIT`) and prints +//! every patch's ΔE. Missing files are reported as skipped. + +use std::path::{Path, PathBuf}; + +use lightcraft_catalog::PhotoId; +use serde_json::json; + +use crate::Session; +use crate::export::{ExportOptions, export_photo}; + +/// Upper bounds for the mean and the largest patch ΔE2000 against Lightroom. Measured when this test +/// was written (2026-10-22): daylight/flash mean 3.84, max 7.77 (patch 16, yellow); indoor mean 3.35, +/// max 5.24 (patch 13, blue). The grey row agrees within about 1-3; the colour patches come out less +/// saturated than Lightroom's (its own rendering on top of the profile), which is most of the rest. +const MEAN_LIMIT: f64 = 5.0; +const MAX_LIMIT: f64 = 10.0; + +fn set_dir() -> PathBuf { + std::env::var_os("LIGHTCRAFT_CORPUS") + .map(PathBuf::from) + .unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus")) + .join("d750-colorchecker") +} + +/// Patch centres (row-major, normalized x, y) in Lightroom's render of each chart, a crop around the +/// ColorChecker. Row 4 is the grey row, white to black. +fn reference_centres(chart: &str) -> Vec<(f64, f64)> { + let (xs, ys): (&[f64], &[f64]) = if chart.contains("indoor") { + (&[193.0, 361.0, 527.0, 692.0, 857.0, 1022.0], &[152.0, 318.0, 486.0, 660.0]) + } else { + (&[197.0, 378.0, 555.0, 731.0, 906.0, 1080.0], &[135.0, 312.0, 490.0, 668.0]) + }; + ys.iter().flat_map(|y| xs.iter().map(move |x| (x / 1200.0, y / 801.0))).collect() +} + +/// The same patches in the whole NEF frame (our export, uncropped), read off a 1200 × 802 render. +fn frame_centres(chart: &str) -> Vec<(f64, f64)> { + let (xs, ys): (&[f64], &[f64]) = if chart.contains("indoor") { + (&[468.0, 528.0, 587.0, 645.0, 704.0, 765.0], &[527.0, 585.0, 644.0, 705.0]) + } else { + (&[462.0, 512.0, 560.0, 609.0, 658.0, 706.0], &[381.0, 430.0, 479.0, 529.0]) + }; + ys.iter().flat_map(|y| xs.iter().map(move |x| (x / 1200.0, y / 802.0))).collect() +} + +/// Mean CIELAB (D50) of a box of half-width `radius` (a fraction of the image width) around each +/// centre, and the largest standard deviation of L* inside a box (a box on a patch edge shows up there). +fn patch_labs(bytes: &[u8], centres: &[(f64, f64)], radius: f64) -> (Vec<[f64; 3]>, f64) { + let d = lightcraft_codecs::decode(bytes, Default::default()).unwrap(); + let to_xyz = d.space.to_xyz_d50; + let (w, h) = (d.image.width, d.image.height); + let r = (w as f64 * radius).max(1.0) as isize; + let mut worst = 0.0f64; + let labs = centres + .iter() + .map(|&(x, y)| { + let (cx, cy) = ((x * w as f64) as isize, (y * h as f64) as isize); + let (mut acc, mut ls) = ([0.0f64; 3], Vec::new()); + for yy in (cy - r).max(0)..(cy + r).min(h as isize) { + for xx in (cx - r).max(0)..(cx + r).min(w as isize) { + let p = d.image.data[yy as usize * w + xx as usize]; + let rgb = [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])]; + for (a, v) in acc.iter_mut().zip(rgb) { + *a += v; + } + ls.push(lab(to_xyz.apply(rgb))[0]); + } + } + let n = ls.len().max(1) as f64; + let mean_l = ls.iter().sum::() / n; + worst = worst.max((ls.iter().map(|l| (l - mean_l).powi(2)).sum::() / n).sqrt()); + lab(to_xyz.apply(acc.map(|v| v / n))) + }) + .collect(); + (labs, worst) +} + +fn lab(xyz: [f64; 3]) -> [f64; 3] { + let white = [0.9642, 1.0, 0.8249]; + let f = |t: f64| if t > 216.0 / 24389.0 { t.cbrt() } else { (24389.0 / 27.0 * t + 16.0) / 116.0 }; + let [fx, fy, fz] = [f(xyz[0] / white[0]), f(xyz[1] / white[1]), f(xyz[2] / white[2])]; + [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)] +} + +/// CIEDE2000 (Sharma, Wu and Dalal 2005). +fn de2000(a: [f64; 3], b: [f64; 3]) -> f64 { + use std::f64::consts::PI; + let (l1, a1, b1, l2, a2, b2) = (a[0], a[1], a[2], b[0], b[1], b[2]); + let c_bar = ((a1 * a1 + b1 * b1).sqrt() + (a2 * a2 + b2 * b2).sqrt()) / 2.0; + let g = 0.5 * (1.0 - (c_bar.powi(7) / (c_bar.powi(7) + 25f64.powi(7))).sqrt()); + let (a1p, a2p) = ((1.0 + g) * a1, (1.0 + g) * a2); + let (c1p, c2p) = ((a1p * a1p + b1 * b1).sqrt(), (a2p * a2p + b2 * b2).sqrt()); + let hue = |b: f64, a: f64| if b == 0.0 && a == 0.0 { 0.0 } else { b.atan2(a).rem_euclid(2.0 * PI) }; + let (h1p, h2p) = (hue(b1, a1p), hue(b2, a2p)); + let dl = l2 - l1; + let dc = c2p - c1p; + let dh = if c1p * c2p == 0.0 { + 0.0 + } else { + let d = h2p - h1p; + if d.abs() <= PI { + d + } else if d > PI { + d - 2.0 * PI + } else { + d + 2.0 * PI + } + }; + let dhh = 2.0 * (c1p * c2p).sqrt() * (dh / 2.0).sin(); + let l_bar = (l1 + l2) / 2.0; + let cp_bar = (c1p + c2p) / 2.0; + let hp_bar = if c1p * c2p == 0.0 { + h1p + h2p + } else if (h1p - h2p).abs() <= PI { + (h1p + h2p) / 2.0 + } else if h1p + h2p < 2.0 * PI { + (h1p + h2p + 2.0 * PI) / 2.0 + } else { + (h1p + h2p - 2.0 * PI) / 2.0 + }; + let t = 1.0 - 0.17 * (hp_bar - PI / 6.0).cos() + 0.24 * (2.0 * hp_bar).cos() + 0.32 * (3.0 * hp_bar + PI / 30.0).cos() + - 0.20 * (4.0 * hp_bar - 63.0 * PI / 180.0).cos(); + let d_theta = 30.0 * (-(((hp_bar * 180.0 / PI) - 275.0) / 25.0).powi(2)).exp(); + let rc = 2.0 * (cp_bar.powi(7) / (cp_bar.powi(7) + 25f64.powi(7))).sqrt(); + let sl = 1.0 + 0.015 * (l_bar - 50.0).powi(2) / (20.0 + (l_bar - 50.0).powi(2)).sqrt(); + let sc = 1.0 + 0.045 * cp_bar; + let sh = 1.0 + 0.015 * cp_bar * t; + let rt = -(2.0 * d_theta * PI / 180.0).sin() * rc; + ((dl / sl).powi(2) + (dc / sc).powi(2) + (dhh / sh).powi(2) + rt * (dc / sc) * (dhh / sh)).sqrt() +} + +#[test] +fn de2000_matches_the_published_test_pairs() { + // Sharma, Wu and Dalal (2005), table 1: pairs 1, 7 and 17 + let cases = [ + ([50.0, 2.6772, -79.7751], [50.0, 0.0, -82.7485], 2.0425), + ([50.0, 0.0, 0.0], [50.0, -1.0, 2.0], 2.3669), + ([50.0, 2.5, 0.0], [73.0, 25.0, -18.0], 27.1492), + ]; + for (a, b, e) in cases { + assert!((de2000(a, b) - e).abs() < 1e-3, "{a:?} {b:?}: {} vs {e}", de2000(a, b)); + } +} + +#[test] +fn the_d750_profile_develops_its_charts_close_to_lightroom() { + let set = set_dir(); + let dcp = set.join("profiles/20261016_NikonD750_DualIllumination_ColorCheckerPassport.dcp"); + let charts = [("daylight_flash", "raw/chart-daylight_flash.NEF"), ("indoor", "raw/chart-indoor.NEF")]; + let mut needed = vec![dcp.clone()]; + for (name, raw) in charts { + needed.push(set.join(raw)); + needed.push(set.join(format!("images/{name}-lightroom.jpg"))); + } + if let Some(missing) = needed.iter().find(|p| !p.exists()) { + lightcraft_testkit::skip!(Corpus, "{} absent (cargo xtask corpus --download)", missing.display()); + return; + } + let lib = std::env::temp_dir().join(format!("lc-dcp-d750-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&lib); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let r = s.execute("profile.import", &json!({"paths": [dcp.to_string_lossy()]})).unwrap(); + let dcp_id = r["imported"][0]["id"].as_str().expect("the D750 profile imports").to_string(); + assert!(r["imported"][0]["cameraModel"].as_str().unwrap().contains("D750"), "{r}"); + let o = ExportOptions::from_json(&json!({"format": "png", "longEdge": 1200, "colorSpace": "srgb"})); + let mut report = String::new(); + let mut means = Vec::new(); + for (name, raw) in charts { + let r = s.execute("library.import", &json!({"paths": [set.join(raw).to_string_lossy()]})).unwrap(); + let id = PhotoId(r["imported"][0].as_u64().expect("the NEF imports")); + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + s.execute("develop.profile", &json!({"id": dcp_id})).unwrap(); + let centres = frame_centres(name); + let (reference, spread) = + patch_labs(&std::fs::read(set.join(format!("images/{name}-lightroom.jpg"))).unwrap(), &reference_centres(name), 0.02); + assert!(spread < 4.0, "{name}: every reference box lies inside its patch (L* spread {spread:.1})"); + // white balance on the second-lightest grey (patch 20), as the reference was made + let wb = s.execute("develop.wbPick", &json!({"x": centres[19].0, "y": centres[19].1})).unwrap(); + // exposure: the value whose grey row is closest to the reference's (golden-section search) + let render = |s: &mut Session, ev: f64| { + s.execute("develop.set", &json!({"control": "light.exposure", "value": ev})).unwrap(); + let e = export_photo(s, id, &o, 1).expect("the chart develops with the D750 profile"); + patch_labs(&e.bytes, ¢res, 0.006) + }; + let grey_de = |(labs, _): &(Vec<[f64; 3]>, f64)| (18..24).map(|i| de2000(labs[i], reference[i])).sum::() / 6.0; + let (mut lo, mut hi) = (-1.5f64, 1.5f64); + let phi = (5f64.sqrt() - 1.0) / 2.0; + let (mut m1, mut m2) = (hi - phi * (hi - lo), lo + phi * (hi - lo)); + let (mut f1, mut f2) = (grey_de(&render(&mut s, m1)), grey_de(&render(&mut s, m2))); + for _ in 0..8 { + if f1 < f2 { + (hi, m2, f2) = (m2, m1, f1); + m1 = hi - phi * (hi - lo); + f1 = grey_de(&render(&mut s, m1)); + } else { + (lo, m1, f1) = (m1, m2, f2); + m2 = lo + phi * (hi - lo); + f2 = grey_de(&render(&mut s, m2)); + } + } + let ev = (lo + hi) / 2.0; + let (ours, spread) = render(&mut s, ev); + assert!(spread < 4.0, "{name}: every box lies inside its patch (L* spread {spread:.1})"); + // LIGHTCRAFT_DCP_DUMP=: keep our renders, to check the patch boxes by eye + if let Some(dir) = std::env::var_os("LIGHTCRAFT_DCP_DUMP") { + s.execute("develop.set", &json!({"control": "light.exposure", "value": ev})).unwrap(); + let _ = std::fs::write(Path::new(&dir).join(format!("{name}.png")), export_photo(&mut s, id, &o, 1).unwrap().bytes); + } + let des: Vec = ours.iter().zip(&reference).map(|(a, b)| de2000(*a, *b)).collect(); + let mean = des.iter().sum::() / des.len() as f64; + let max = des.iter().cloned().fold(0.0, f64::max); + report += &format!("{name}: wb {} K / tint {}, exposure {ev:+.2}, mean ΔE2000 {mean:.2}, max {max:.2}\n", wb["temp"], wb["tint"]); + for (i, d) in des.iter().enumerate() { + report += &format!( + " patch {:2}: ΔE {d:5.2} ours L*a*b* {:6.1} {:6.1} {:6.1} Lightroom {:6.1} {:6.1} {:6.1}\n", + i + 1, + ours[i][0], + ours[i][1], + ours[i][2], + reference[i][0], + reference[i][1], + reference[i][2] + ); + } + means.push((name, mean, max)); + } + eprintln!("{report}"); + let _ = std::fs::remove_dir_all(&lib); + for (name, mean, max) in means { + assert!(mean < MEAN_LIMIT && max < MAX_LIMIT, "{name}: mean ΔE2000 {mean:.2}, max {max:.2}\n{report}"); + } +} diff --git a/crates/engine/src/tests/export.rs b/crates/engine/src/tests/export.rs index 54f370279b..9e892e4e21 100644 --- a/crates/engine/src/tests/export.rs +++ b/crates/engine/src/tests/export.rs @@ -189,6 +189,40 @@ fn presets_conflicts_and_subfolders() { assert_eq!(written, ["out/Sub/LC01347.png"]); } +/// Issue #2571: a subfolder with `..`, a root or a drive wrote outside the chosen folder. It is +/// cleaned where the folder is used, so a preset or the Export dialog's field (which set it +/// without `from_json`) are covered as well as command parameters. +#[test] +fn a_subfolder_never_leaves_the_destination_folder() { + use crate::export::{Destination, export_batch}; + let mut s = Session::with_demo(); + let id = s.active().unwrap(); + let to = Destination { dir: "out".into(), exact: None }; + let written_to = |s: &mut Session, sub: &str| { + let o = ExportOptions { subfolder: sub.into(), naming: "x".into(), ..ExportOptions::from_json(&json!({"format": "png", "width": 16})) }; + let mut written: Vec = Vec::new(); + let mut write = |p: &str, _: &[u8]| { + written.push(p.to_string()); + Ok(()) + }; + export_batch(s, &[id], &o, &to, &mut write, &|_| false).unwrap(); + written + }; + for (sub, want) in [ + ("../../escaped", "out/escaped/x.png"), + ("..", "out/x.png"), + ("/etc", "out/etc/x.png"), + ("C:\\Windows", "out/C__Windows/x.png"), + ("a/./b/../c", "out/a/b/c/x.png"), + (" Client / Jobs ", "out/Client/Jobs/x.png"), + ] { + assert_eq!(written_to(&mut s, sub), [want], "{sub:?}"); + } + // command parameters get the same cleaning + let o = ExportOptions::from_json(&json!({"subfolder": "../up"})); + assert_eq!(o.subfolder, "up"); +} + #[test] fn prepared_exports_run_on_another_thread() { fn send(_: &T) {} diff --git a/crates/engine/src/tests/face_tiles.rs b/crates/engine/src/tests/face_tiles.rs index 9aa4b05e84..b166dcd859 100644 --- a/crates/engine/src/tests/face_tiles.rs +++ b/crates/engine/src/tests/face_tiles.rs @@ -91,9 +91,9 @@ fn count_loads(s: &mut Session) -> Loads { let loads = Loads::default(); let file = s.media.file_loader.clone().unwrap(); let n = loads.files.clone(); - s.media.file_loader = Some(Arc::new(move |p: &str, e: usize| { + s.media.file_loader = Some(Arc::new(move |p: &str, e: usize, dcp: Option<&crate::media::DcpProfile>| { n.fetch_add(1, Ordering::SeqCst); - file(p, e) + file(p, e, dcp) })); let preview = s.media.preview_loader.clone().unwrap(); let n = loads.previews.clone(); diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index ca26e4a3ad..e87e2883d2 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -974,7 +974,7 @@ fn smart_previews_keep_the_decoder_facts_offline_edits_need() { let mut s = Session::new().with_fs(); s.open_library(&lib, false).unwrap(); let (p, i) = (pixels.clone(), info.clone()); - s.media.file_loader = Some(std::sync::Arc::new(move |_path, _max_edge| Ok((p.clone(), i.clone())))); + s.media.file_loader = Some(std::sync::Arc::new(move |_path, _max_edge, _| Ok((p.clone(), i.clone())))); s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()]})).unwrap(); let id = s.active().unwrap(); let r = s.execute("library.smartPreviews", &json!({})).unwrap(); @@ -2107,9 +2107,9 @@ fn look_loader( tone: lightcraft_pipeline::tone::CameraTone, calls: std::sync::Arc, ) -> crate::media::FileLoader { - std::sync::Arc::new(move |path, max_edge| { + std::sync::Arc::new(move |path, max_edge, dcp| { calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - let (img, mut info) = plain(path, max_edge)?; + let (img, mut info) = plain(path, max_edge, dcp)?; info.camera_tone = Some(tone); Ok((img, info)) }) @@ -2277,7 +2277,7 @@ fn a_proxy_with_an_older_encoding_is_refreshed_without_the_camera_look() { let pixels = lightcraft_raster::Rgb32f::from_fn(48, 32, |x, y| [0.02 + (x % 9) as f32 * 0.05, 0.03 + (y % 7) as f32 * 0.04, 0.06]); let info = lightcraft_pipeline::SourceInfo { raw: true, as_shot_temp: 5200.0, as_shot_tint: 6.0, ..Default::default() }; let (p, i) = (pixels.clone(), info.clone()); - s.media.file_loader = Some(std::sync::Arc::new(move |_path, _max_edge| Ok((p.clone(), i.clone())))); + s.media.file_loader = Some(std::sync::Arc::new(move |_path, _max_edge, _| Ok((p.clone(), i.clone())))); s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()]})).unwrap(); let id = s.active().unwrap(); let mut raw = (**s.catalog.photo(id).unwrap()).clone(); @@ -2321,7 +2321,7 @@ fn a_stale_refresh_never_rebuilds_a_proxy_from_itself() { let pixels = lightcraft_raster::Rgb32f::from_fn(48, 32, |x, y| [0.02 + (x % 9) as f32 * 0.05, 0.03 + (y % 7) as f32 * 0.04, 0.06]); let info = lightcraft_pipeline::SourceInfo { raw: true, as_shot_temp: 5200.0, as_shot_tint: 6.0, ..Default::default() }; let (p, i) = (pixels.clone(), info.clone()); - s.media.file_loader = Some(std::sync::Arc::new(move |_path, _max_edge| Ok((p.clone(), i.clone())))); + s.media.file_loader = Some(std::sync::Arc::new(move |_path, _max_edge, _| Ok((p.clone(), i.clone())))); s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()]})).unwrap(); let id = s.active().unwrap(); // a raw that takes the per-file camera look, so an older fit makes its proxy stale diff --git a/crates/engine/src/tests/lens_refresh.rs b/crates/engine/src/tests/lens_refresh.rs index 8885c2f7ca..7678c93a3d 100644 --- a/crates/engine/src/tests/lens_refresh.rs +++ b/crates/engine/src/tests/lens_refresh.rs @@ -237,7 +237,7 @@ fn a_new_database_profile_changes_the_render_and_cache_keys() { let render = s.render_job(id, 800, 600, false, true).unwrap().key; let thumb = s.thumb_job(id, 256).unwrap().cache.unwrap().1; let p = s.catalog.photo(id).unwrap().clone(); - (render, thumb, Session::variant_key(&p, &p.develop, 128), Session::view_key(&p, true)) + (render, thumb, Session::variant_key(&p, &p.develop, 128, 0), Session::view_key(&p, true, 0)) }; let before = keys(&mut s); s.catalog.apply(Op::SetEmbeddedLens { id, lens: Some(Box::new(lens(-0.03))) }).unwrap(); diff --git a/crates/engine/src/tests/library.rs b/crates/engine/src/tests/library.rs index 32b4130ac7..00f418e674 100644 --- a/crates/engine/src/tests/library.rs +++ b/crates/engine/src/tests/library.rs @@ -69,7 +69,9 @@ fn threshold_compaction_runs_in_the_background() { background += 1; } if k == 30 { - // a crash while a compaction may be in flight + // a crash while a compaction may be in flight (once the log's thread has written what it + // was handed: a process that crashes in LightCraft's code keeps running it) + s.library.as_mut().unwrap().journal_mut().flush().unwrap(); let expect = s.catalog.to_snapshot(); let copy = temp_dir("bg-compact-crash"); std::fs::create_dir_all(©).unwrap(); @@ -544,6 +546,8 @@ fn a_library_open_elsewhere_is_refused() { let dir = temp_dir("locked"); let mut s = open(&dir, true); s.execute("photo.rate", &json!({"rating": 3})).unwrap(); + // (written by the log's own thread) + s.library.as_mut().unwrap().journal_mut().flush().unwrap(); let log = std::fs::read(dir.join("catalog.log")).unwrap(); let mut other = Session::new(); diff --git a/crates/engine/src/tests/slow_drive.rs b/crates/engine/src/tests/slow_drive.rs new file mode 100644 index 0000000000..f9942986aa --- /dev/null +++ b/crates/engine/src/tests/slow_drive.rs @@ -0,0 +1,317 @@ +//! PERF-STEP-STALL: culling on a slow or failing drive. A flag or rating never waits for the drive +//! (the catalog log is written and synced by a thread of its own), and nothing made meanwhile is +//! lost: it is on disk once the save lands, after a clean quit, after a quit with no close, and, +//! when the drive fails, held, retried and reported as unsaved until it is written. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use lightcraft_catalog::fault::{self, Step}; +use lightcraft_catalog::{Flag, PhotoId}; +use serde_json::json; + +use crate::Session; + +fn temp_dir(tag: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("lc-engine-slow-drive-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + d +} + +fn open(dir: &std::path::Path) -> Session { + let mut s = Session::new(); + s.open_library(dir, true).unwrap(); + s +} + +fn ids(s: &Session) -> Vec { + let mut v: Vec = s.catalog.photos().map(|p| p.id).collect(); + v.sort(); + v +} + +/// Every sync of the log in `dir` takes `sync` (a busy disk: Windows makes a write wait for a sync +/// of the same file in flight); `fail` makes every write fail while it is set. +fn slow_drive(dir: &std::path::Path, sync: Duration, fail: Arc) { + fault::install( + dir, + Arc::new(move |step| { + if fail.load(Ordering::SeqCst) { + return Err(std::io::Error::other("the drive is gone (test)")); + } + if step == Step::Sync { + std::thread::sleep(sync); + } + Ok(()) + }), + ); +} + +/// The flag or rating each photo got, as `(id, flag, rating)`. +fn culled(s: &Session) -> Vec<(PhotoId, Flag, u8)> { + ids(s).into_iter().filter_map(|id| s.catalog.photo(id).map(|p| (id, p.flag, p.rating))).collect() +} + +/// Flag and rate every photo the way a photographer culls: pick / reject in turn, a rating on +/// every other one. Returns the slowest command, in ms. +fn cull(s: &mut Session, rounds: usize) -> f64 { + let all = ids(s); + let mut slowest = 0.0f64; + for k in 0..rounds { + for (i, id) in all.iter().enumerate() { + let flag = if (i + k) % 2 == 0 { "pick" } else { "reject" }; + let t = Instant::now(); + s.execute("photo.flag", &json!({"flag": flag, "ids": [id.0]})).unwrap(); + slowest = slowest.max(t.elapsed().as_secs_f64() * 1000.0); + if i % 2 == 0 { + let t = Instant::now(); + s.execute("photo.rate", &json!({"rating": ((i + k) % 5) as u8 + 1, "ids": [id.0]})).unwrap(); + slowest = slowest.max(t.elapsed().as_secs_f64() * 1000.0); + } + } + } + slowest +} + +/// (a) With every sync of the log taking 300 ms, a flag or rating returns long before one sync. +/// The same culling with the log written on the caller's thread (as before PERF-STEP-STALL) waits +/// for a sync on every key, which is what this test would see without the fix. +#[test] +fn a_flag_never_waits_for_a_slow_drive() { + let sync = Duration::from_millis(300); + let mut seen = Vec::new(); + for on_caller in [true, false] { + let dir = temp_dir(if on_caller { "wait-before" } else { "wait" }); + fault::write_on_caller(&dir, on_caller); + let mut s = open(&dir); + slow_drive(&dir, sync, Arc::new(AtomicBool::new(false))); + let t = Instant::now(); + let slowest = cull(&mut s, 1); + let total = t.elapsed().as_secs_f64() * 1000.0; + let n = s.library.as_ref().map_or(0, |l| l.journal().stats().appends); + eprintln!( + "{} drive syncing in 300 ms: slowest command {slowest:.1} ms, {total:.0} ms for the culling", + if on_caller { "before (log written on the caller):" } else { "after (log on its own thread):" } + ); + seen.push((slowest, total, n)); + drop(s); + fault::remove(&dir); + fault::write_on_caller(&dir, false); + let _ = std::fs::remove_dir_all(&dir); + } + let ((before, _, _), (after, _, _)) = (seen[0], seen[1]); + assert!(before >= 300.0, "the caller waited for its sync before: {before:.1} ms"); + // a debug build of the whole workspace's tests at once leaves room; one sync is 300 ms + assert!(after < 120.0, "a command waited for the drive: {after:.1} ms"); +} + +/// (b) Everything flagged and rated while slow saves are in flight is on disk once they land +/// (a flush), after a quit with no close (the process ends normally: the log's thread finishes), +/// and after a clean quit (`close_library`). +#[test] +fn every_change_made_during_a_slow_save_is_on_disk() { + for how in ["flush", "drop", "close"] { + let dir = temp_dir(&format!("kept-{how}")); + let mut s = open(&dir); + slow_drive(&dir, Duration::from_millis(150), Arc::new(AtomicBool::new(false))); + cull(&mut s, 3); + let want = culled(&s); + let expect = s.catalog.to_snapshot(); + match how { + "flush" => { + s.library.as_mut().unwrap().journal_mut().flush().unwrap(); + // a copy of the files taken now (the next crash) holds everything + let copy = temp_dir("kept-copy"); + std::fs::create_dir_all(©).unwrap(); + for f in [lightcraft_catalog::journal::SNAPSHOT, lightcraft_catalog::journal::LOG] { + if dir.join(f).exists() { + std::fs::copy(dir.join(f), copy.join(f)).unwrap(); + } + } + let (_, c, _) = lightcraft_catalog::Journal::open(Box::new(lightcraft_catalog::store::FsStore::open(©).unwrap())).unwrap(); + assert_eq!(c.to_snapshot(), expect, "{how}"); + let _ = std::fs::remove_dir_all(©); + } + "close" => s.close_library().unwrap(), + _ => {} + } + assert!(s.unsaved().is_none(), "{how}: {:?}", s.unsaved()); + drop(s); + fault::remove(&dir); + let again = open(&dir); + assert_eq!(culled(&again), want, "{how}"); + assert_eq!(again.catalog.to_snapshot(), expect, "{how}"); + drop(again); + let _ = std::fs::remove_dir_all(&dir); + } +} + +/// Wait (bounded) until `done` holds, calling the frame loop's save meanwhile. +fn frames_until(s: &mut Session, what: &str, mut done: impl FnMut(&Session) -> bool) { + let t = Instant::now(); + while !done(s) { + assert!(t.elapsed() < Duration::from_secs(20), "{what}: {:?}", s.unsaved()); + s.persist_if_dirty(); + std::thread::sleep(Duration::from_millis(20)); + } +} + +/// (c) A drive that fails: the flags handed over before the failure are held and retried, never +/// dropped; the failure is reported (`unsaved`, the quit prompt's source) and later flags fail +/// with `NotSaved` and stay queued; once the drive is back, all of it is written, in order, with +/// no gap in the log. +#[test] +fn a_failed_write_is_reported_and_retried_never_dropped() { + let dir = temp_dir("fail"); + let mut s = open(&dir); + let fail = Arc::new(AtomicBool::new(false)); + slow_drive(&dir, Duration::from_millis(5), fail.clone()); + let all = ids(&s); + fail.store(true, Ordering::SeqCst); + // handed over before the thread found out: accepted, then held + s.execute("photo.flag", &json!({"flag": "pick", "ids": [all[0].0]})).unwrap(); + // the quit check reads it at once, not as of the last frame (review of #3557) + let t = Instant::now(); + while s.library.as_ref().unwrap().journal().unwritten().is_none() { + assert!(t.elapsed() < Duration::from_secs(20), "the log thread never reported the failure"); + std::thread::sleep(Duration::from_millis(10)); + } + s.refresh_unsaved(); + assert!(s.unsaved().is_some(), "refreshed for the quit check"); + let (n, why) = s.unsaved().map(|(n, w)| (n, w.to_string())).unwrap(); + assert!(n >= 1 && why.contains("the drive is gone"), "{n} {why}"); + // later flags: refused with the reason, kept in memory and queued + let r = s.execute("photo.flag", &json!({"flag": "reject", "ids": [all[1].0]})); + assert!(matches!(r, Err(crate::EngineError::NotSaved(_))), "{r:?}"); + assert_eq!(s.catalog.photo(all[1]).unwrap().flag, Flag::Reject, "applied in memory"); + let _ = s.execute("photo.rate", &json!({"rating": 4, "ids": [all[2].0]})); + assert!(s.unsaved().is_some_and(|(n, _)| n >= 3), "{:?}", s.unsaved()); + // the drive is back: the held record and the queued ones are written by the frame loop + fail.store(false, Ordering::SeqCst); + frames_until(&mut s, "written once the drive is back", |s| s.unsaved().is_none() && s.pending_log.is_empty()); + let want = culled(&s); + let expect = s.catalog.to_snapshot(); + // a crash now: the files alone hold everything, and the log has no gap (no damage on load) + s.library.as_mut().unwrap().journal_mut().flush().unwrap(); + let copy = temp_dir("fail-copy"); + std::fs::create_dir_all(©).unwrap(); + for f in [lightcraft_catalog::journal::SNAPSHOT, lightcraft_catalog::journal::LOG] { + if dir.join(f).exists() { + std::fs::copy(dir.join(f), copy.join(f)).unwrap(); + } + } + let (_, c, report) = lightcraft_catalog::Journal::open(Box::new(lightcraft_catalog::store::FsStore::open(©).unwrap())).unwrap(); + assert!(report.damaged.is_none(), "{report:?}"); + assert_eq!(c.to_snapshot(), expect); + let _ = std::fs::remove_dir_all(©); + fault::remove(&dir); + drop(s); + assert_eq!(culled(&open(&dir)), want); + let _ = std::fs::remove_dir_all(&dir); +} + +/// (c) The drive stays broken for the log until the quit: the quit prompt is told (unsaved), and +/// the closing snapshot (a fresh file) saves the held flags, so they are there on the next open. +#[test] +fn a_log_that_stays_broken_is_saved_by_the_closing_snapshot() { + let dir = temp_dir("broken"); + let mut s = open(&dir); + let all = ids(&s); + let fail = Arc::new(AtomicBool::new(false)); + slow_drive(&dir, Duration::from_millis(5), fail.clone()); + fail.store(true, Ordering::SeqCst); + s.execute("photo.flag", &json!({"flag": "reject", "ids": [all[0].0]})).unwrap(); + frames_until(&mut s, "the failure is reported", |s| s.unsaved().is_some()); + let _ = s.execute("photo.flag", &json!({"flag": "pick", "ids": [all[1].0]})); + let want = culled(&s); + // (the snapshot itself is written by the store, which the hook leaves alone; the log's reset + // after it fails, so close reports it, but the snapshot holds everything) + let _ = s.close_library(); + // the snapshot holds them: the quit prompt must not say they would be lost (review of #3557) + assert!(s.unsaved().is_none(), "{:?}", s.unsaved()); + drop(s); + fault::remove(&dir); + let again = open(&dir); + assert!(again.library.as_ref().unwrap().report.damaged.is_none()); + assert_eq!(culled(&again), want); + drop(again); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The same library opened again in the same session (Settings, Libraries; a reopen after an +/// error): everything the old session's log thread was handed is in the files before the new one +/// reads them (review of #3557). +#[test] +fn reopening_the_same_library_reads_what_its_log_thread_was_handed() { + let dir = temp_dir("reopen"); + let mut s = open(&dir); + fault::install( + &dir, + Arc::new(|step| { + if step == Step::Write { + std::thread::sleep(Duration::from_millis(300)); + } + Ok(()) + }), + ); + let all = ids(&s); + s.execute("photo.flag", &json!({"flag": "reject", "ids": [all[0].0]})).unwrap(); + s.open_library(&dir, true).unwrap(); + fault::remove(&dir); + assert_eq!(s.catalog.photo(all[0]).unwrap().flag, Flag::Reject); + drop(s); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The same library opened again while its log's thread can't write what it was handed: the open +/// fails and the current library stays open with the change (held, retried), instead of a new +/// catalog read from files that miss it (review of #3557). Once the drive is back, the reopen +/// reads it. +#[test] +fn a_reopen_waits_for_what_the_log_thread_could_not_write() { + let dir = temp_dir("reopen-fail"); + let mut s = open(&dir); + let all = ids(&s); + let fail = Arc::new(AtomicBool::new(false)); + slow_drive(&dir, Duration::from_millis(5), fail.clone()); + fail.store(true, Ordering::SeqCst); + s.execute("photo.flag", &json!({"flag": "reject", "ids": [all[0].0]})).unwrap(); + let r = s.open_library(&dir, true); + assert!(matches!(r, Err(crate::EngineError::NotSaved(_))), "{r:?}"); + assert_eq!(s.catalog.photo(all[0]).unwrap().flag, Flag::Reject, "the open library keeps the change"); + assert!(s.unsaved().is_some(), "and says it isn't saved yet"); + fail.store(false, Ordering::SeqCst); + let t = Instant::now(); + while s.library.as_mut().unwrap().journal_mut().flush().is_err() { + assert!(t.elapsed() < Duration::from_secs(20), "never written"); + std::thread::sleep(Duration::from_millis(50)); + } + s.open_library(&dir, true).unwrap(); + fault::remove(&dir); + assert_eq!(s.catalog.photo(all[0]).unwrap().flag, Flag::Reject); + drop(s); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A reopen while the log still can't be written, but after a snapshot that holds every change +/// (the log's reset after it failed): nothing is missing from the files, so the open goes ahead +/// (review of #3557). +#[test] +fn a_reopen_after_a_snapshot_that_holds_everything_goes_ahead() { + let dir = temp_dir("reopen-snap"); + let mut s = open(&dir); + let all = ids(&s); + let fail = Arc::new(AtomicBool::new(false)); + slow_drive(&dir, Duration::from_millis(5), fail.clone()); + fail.store(true, Ordering::SeqCst); + s.execute("photo.flag", &json!({"flag": "reject", "ids": [all[0].0]})).unwrap(); + let _ = s.close_library(); + assert!(s.snapshot_holds_everything()); + s.open_library(&dir, true).unwrap(); + assert_eq!(s.catalog.photo(all[0]).unwrap().flag, Flag::Reject); + fault::remove(&dir); + drop(s); + assert_eq!(open(&dir).catalog.photo(all[0]).unwrap().flag, Flag::Reject); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/text.rs b/crates/engine/src/text.rs index 0e2e39c1ea..c3585c3b88 100644 --- a/crates/engine/src/text.rs +++ b/crates/engine/src/text.rs @@ -57,6 +57,19 @@ pub fn cell_glyphs(font: &FontRef<'_>, data: &harfrust::ShaperData, text: &str, Some(glyphs) } +/// NFC, except CJK compatibility ideographs, which NFC would swap for their unified forms. +fn compose(text: &str) -> String { + use unicode_normalization::UnicodeNormalization; + let compatibility = |c: char| matches!(c, '\u{F900}'..='\u{FAFF}' | '\u{2F800}'..='\u{2FA1F}'); + let mut out = String::with_capacity(text.len()); + for part in text.split_inclusive(compatibility) { + let kept = part.chars().next_back().filter(|&c| compatibility(c)); + out.extend(kept.and_then(|c| part.strip_suffix(c)).unwrap_or(part).nfc()); + out.extend(kept); + } + out +} + /// A string laid out at one size: its glyphs relative to the box's top-left corner and the box's /// size in pixels (lines are `px` apart; vertical text: columns `px` wide, right to left). pub struct TextLayout { @@ -79,6 +92,9 @@ impl TextLayout { Some((i, _)) => text.get(..i).unwrap_or(text), None => text, }; + // macOS file names are often decomposed (NFD); the layout below draws one glyph per char + let composed = compose(text); + let text = composed.as_str(); let fonts = faces(craft); let latin = fonts.first()?.clone(); let vertical_data: Vec<_> = if vertical { @@ -264,6 +280,48 @@ mod tests { } } + fn assert_draws_composed(text: &str, craft: &'static [CraftFont]) { + use unicode_normalization::UnicodeNormalization; + let nfc: String = text.nfc().collect(); + let nfd: String = text.nfd().collect(); + assert_ne!(nfc, nfd); + let (a, b) = (TextLayout::new(&nfc, 40.0, false, craft).unwrap(), TextLayout::new(&nfd, 40.0, false, craft).unwrap()); + let ids = |l: &TextLayout| l.glyphs.iter().map(|(face, g, _)| (*face, g.id.0)).collect::>(); + assert_eq!(ids(&b), ids(&a)); + assert_eq!(b.width, a.width); + assert!(a.glyphs.iter().all(|(_, g, _)| g.id.0 != 0)); + } + + #[test] + fn decomposed_vietnamese_draws_its_composed_letters() { + assert_draws_composed("HỌC ĐỂ ỨNG DỤNG", &[]); + } + + #[test] + fn decomposed_hangul_draws_whole_syllables() { + if !CRAFT_FONTS.iter().any(|font| font.covers("Hang")) { + lightcraft_testkit::skip!(Fonts, "built without a Hangul face from craft-fonts"); + return; + } + assert_draws_composed("제주도 바다 여행.jpg", CRAFT_FONTS); + } + + #[test] + fn compatibility_ideographs_keep_their_code_points() { + use unicode_normalization::UnicodeNormalization; + let nfd = |s: &str| s.nfd().collect::(); + let text = format!("\u{FA10}{} \u{2F800}{}\u{F900}", nfd("본 제주"), nfd("Ọ")); + assert_eq!(compose(&text), "\u{FA10}본 제주 \u{2F800}Ọ\u{F900}"); + } + + #[test] + fn already_composed_text_stays_as_it_is() { + for text in ["", "plain.jpg", "제주도 바다 여행.jpg", "HỌC ĐỂ ỨNG DỤNG"] { + assert!(unicode_normalization::is_nfc(text), "{text}"); + assert_eq!(compose(text), text); + } + } + #[test] fn bundled_thai_uses_its_glyphs() { assert_script_glyphs("Thai", "สวัสดีครับ"); diff --git a/crates/film/Cargo.toml b/crates/film/Cargo.toml new file mode 100644 index 0000000000..bf3d911b97 --- /dev/null +++ b/crates/film/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "lightcraft-film" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "LightCraft film-negative conversion: film base, levels in density space, film presets, colour and tone (L1)" + +[lints] +workspace = true + +[dependencies] +# Pure-Rust libm: the conversion's maths gives the same numbers on every target, the browser included. +libm = { workspace = true } diff --git a/crates/film/src/analysis.rs b/crates/film/src/analysis.rs new file mode 100644 index 0000000000..e2417033ea --- /dev/null +++ b/crates/film/src/analysis.rs @@ -0,0 +1,202 @@ +//! What the conversion needs to know about one negative, and how to measure it from pixels +//! without an allocator (a fixed-size histogram per channel). + +use crate::{RANGE_STOPS, color::Encoding, film}; + +/// Film base and levels, per channel. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Analysis { + /// The film base (unexposed film, the border) in linear light: scene black. + pub base: [f32; 3], + /// Relative exposure ([`film::exposure`]) that maps to black. + pub black: [f32; 3], + /// Relative exposure that maps to white. + pub white: [f32; 3], +} + +impl Analysis { + /// Levels from the base alone: the base is black and a scene [`RANGE_STOPS`] stops brighter + /// is white, on every channel. Needs nothing from the image, so it is identical on every band. + pub fn manual(base_linear: [f32; 3]) -> Self { + Self::from_base(base_linear, [crate::NEGATIVE_GAMMA; 3]) + } + + /// [`Analysis::manual`] for a film whose layers have the given density per log-exposure: a + /// steeper layer reaches the same scene brightness at a higher density, so its white point + /// sits further from the base. Relative exposures stay in the [`film::exposure`] convention. + pub fn from_base(base_linear: [f32; 3], gamma: [f32; 3]) -> Self { + let mut white = [0.0; 3]; + for (w, g) in white.iter_mut().zip(gamma) { + let g = if g.is_finite() && g > 0.05 { g } else { crate::NEGATIVE_GAMMA }; + *w = libm::exp2f(g / crate::NEGATIVE_GAMMA * RANGE_STOPS); + } + Self { base: base_linear, black: [1.0; 3], white } + } + + /// Levels from three scan values per channel in the host encoding: the film base, the + /// brightest value that still counts as exposed (black) and the darkest (white). `None` + /// when a channel has no range between black and white. + pub fn from_scan_values(base: [f32; 3], black: [f32; 3], white: [f32; 3], enc: Encoding) -> Option { + let mut a = Self { base: [0.0; 3], black: [0.0; 3], white: [0.0; 3] }; + for ch in 0..3 { + a.base[ch] = enc.decode(base[ch]); + a.black[ch] = film::exposure(enc.decode(black[ch]), a.base[ch]); + a.white[ch] = film::exposure(enc.decode(white[ch]), a.base[ch]); + if !a.white[ch].is_finite() || !a.black[ch].is_finite() || a.white[ch] <= a.black[ch] * 1.0001 { + return None; + } + } + Some(a) + } +} + +/// Bins per channel. +pub const BINS: usize = 1024; + +/// Per-channel histogram of scan values in the host encoding, 0..1. One pass over a band gives +/// the film base (a high quantile: the unexposed border is the brightest the scan gets) and the +/// black and white points (the quantiles the black and white clips leave). +#[derive(Clone, Copy, Debug)] +pub struct ValueHistogram { + bins: [[u32; BINS]; 3], + count: u32, +} + +impl Default for ValueHistogram { + fn default() -> Self { + Self::new() + } +} + +impl ValueHistogram { + pub const fn new() -> Self { + Self { bins: [[0; BINS]; 3], count: 0 } + } + + /// Account for one sample (host encoding, 0..1 per channel). + pub fn push(&mut self, rgb: [f32; 3]) { + for (bins, v) in self.bins.iter_mut().zip(rgb) { + if let Some(b) = bins.get_mut(bin(v)) { + *b = b.saturating_add(1); + } + } + self.count = self.count.saturating_add(1); + } + + pub fn count(&self) -> u32 { + self.count + } + + /// The value below which a fraction `q` (0..1) of channel `ch` lies. + pub fn quantile(&self, ch: usize, q: f32) -> Option { + self.bins.get(ch).and_then(|bins| quantile_bin(bins, self.count, q)).map(|b| b as f32 / (BINS - 1) as f32) + } + + /// The analysis of the pixels seen: the base at the `1 − base_clip` quantile, black at + /// `1 − black_clip`, white at `white_clip` (all fractions, 0..1), for samples in `enc`. + pub fn analysis(&self, base_clip: f32, black_clip: f32, white_clip: f32, enc: Encoding) -> Option { + let (mut base, mut black, mut white) = ([0.0; 3], [0.0; 3], [0.0; 3]); + for ch in 0..3 { + base[ch] = self.quantile(ch, 1.0 - base_clip.clamp(0.0, 0.5))?; + black[ch] = self.quantile(ch, 1.0 - black_clip.clamp(0.0, 0.5))?; + white[ch] = self.quantile(ch, white_clip.clamp(0.0, 0.5))?; + } + Analysis::from_scan_values(base, black, white, enc) + } +} + +/// The bin of a value in 0..1. +fn bin(v: f32) -> usize { + if v.is_finite() { (v.clamp(0.0, 1.0) * (BINS - 1) as f32) as usize } else { 0 } +} + +/// The first bin at which the cumulative count reaches `q` of `count` (`None` when empty). +fn quantile_bin(bins: &[u32; BINS], count: u32, q: f32) -> Option { + if count == 0 { + return None; + } + let target = libm::ceil(f64::from(q.clamp(0.0, 1.0)) * f64::from(count)).max(1.0) as u64; + let mut seen = 0u64; + for (i, n) in bins.iter().enumerate() { + seen += u64::from(*n); + if seen >= target { + return Some(i); + } + } + Some(BINS - 1) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::color; + + const BASE: [f32; 3] = [0.6, 0.35, 0.15]; + + #[test] + fn histogram_finds_base_and_levels_of_a_synthetic_negative() { + let mut h = ValueHistogram::new(); + assert_eq!(h.analysis(0.001, 0.0, 0.0, Encoding::Srgb), None); + // Scene exposures from 1 (black, at the base) to 2^5 (white), evenly on a log scale, + // plus a hot pixel brighter than the base. + for i in 0..=1000 { + let e = libm::exp2f(5.0 * i as f32 / 1000.0); + let mut rgb = [0.0; 3]; + for (v, b) in rgb.iter_mut().zip(BASE) { + *v = color::srgb_encode(film::transmittance(e, b)); + } + h.push(rgb); + } + h.push([1.0; 3]); + assert_eq!(h.count(), 1002); + let a = h.analysis(0.005, 0.0, 0.0, Encoding::Srgb).unwrap(); + for (ch, b) in BASE.iter().enumerate() { + // The clip takes the top 0.5 % of a 5-stop log ramp: 0.025 stops under the base. + assert!((a.base[ch] - b).abs() < 0.01, "{a:?}"); + assert!((a.black[ch] - 1.0).abs() < 0.03, "{a:?}"); + assert!((a.white[ch] - 32.0).abs() / 32.0 < 0.05, "{a:?}"); + } + let clipped = h.analysis(0.005, 0.1, 0.1, Encoding::Srgb).unwrap(); + assert!(clipped.black[0] > a.black[0] * 1.2 && clipped.white[0] < a.white[0] * 0.8, "{clipped:?}"); + // A flat band (all one value) has no range. + let mut flat = ValueHistogram::new(); + flat.push([0.3; 3]); + assert_eq!(flat.analysis(0.0, 0.0, 0.0, Encoding::Srgb), None); + } + + #[test] + fn a_steeper_layer_puts_white_further_from_the_base() { + let a = Analysis::from_base(BASE, [0.6, 0.6, 0.72]); + assert_eq!(a.white[0], a.white[1]); + assert!(a.white[2] > a.white[0] * 1.5, "{a:?}"); + assert_eq!(Analysis::from_base(BASE, [f32::NAN, 0.0, 0.6]).white, Analysis::manual(BASE).white); + } + + #[test] + fn scan_values_give_levels_in_linear_too() { + let a = Analysis::from_scan_values(BASE, BASE, [0.1, 0.1, 0.1], Encoding::Linear).unwrap(); + assert_eq!(a.base, BASE); + assert_eq!(a.black, [1.0; 3]); + assert!(a.white[0] > a.white[2], "the same scan value is further below a brighter base: {a:?}"); + assert_eq!(Analysis::from_scan_values(BASE, [0.1; 3], [0.1; 3], Encoding::Linear), None); + } + + #[test] + fn quantile_edges() { + let mut bins = [0u32; BINS]; + bins[10] = 5; + bins[500] = 5; + assert_eq!(quantile_bin(&bins, 10, 0.0), Some(10)); + assert_eq!(quantile_bin(&bins, 10, 0.5), Some(10)); + assert_eq!(quantile_bin(&bins, 10, 0.51), Some(500)); + assert_eq!(quantile_bin(&bins, 10, 1.0), Some(500)); + assert_eq!(quantile_bin(&bins, 0, 0.5), None); + assert_eq!(bin(f32::NAN), 0); + assert_eq!(bin(1.0), BINS - 1); + let mut h = ValueHistogram::new(); + h.push([f32::NAN, 2.0, -1.0]); + assert_eq!(h.quantile(0, 0.5), Some(0.0)); + assert_eq!(h.quantile(1, 0.5), Some(1.0)); + assert_eq!(h.quantile(3, 0.5), None); + } +} diff --git a/crates/film/src/color.rs b/crates/film/src/color.rs new file mode 100644 index 0000000000..ff8597e3c5 --- /dev/null +++ b/crates/film/src/color.rs @@ -0,0 +1,145 @@ +//! sRGB transfer functions and luminance, including the fused forms the conversion runs on +//! (one `powf` where the naive chain would need two: the host meters instructions per sample). + +/// How a host's samples are encoded. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Encoding { + /// Display-referred, sRGB transfer (8- and 16-bit documents). + Srgb, + /// Scene-linear (32-bit float documents). + Linear, +} + +impl Encoding { + /// The usual encoding of a document of `depth` bits per sample. + pub fn for_depth(depth: u32) -> Self { + if depth >= 32 { Self::Linear } else { Self::Srgb } + } + + pub fn parse(s: &str) -> Option { + match s { + "srgb" => Some(Self::Srgb), + "linear" => Some(Self::Linear), + _ => None, + } + } + + /// A sample in this encoding as linear light. + pub fn decode(self, v: f32) -> f32 { + match self { + Self::Srgb => srgb_decode(v), + Self::Linear => v, + } + } + + /// Three linear values as samples in this encoding. + pub fn encode3(self, rgb: [f32; 3]) -> [f32; 3] { + [self.encode(rgb[0]), self.encode(rgb[1]), self.encode(rgb[2])] + } + + /// Linear light as a sample in this encoding. + pub fn encode(self, v: f32) -> f32 { + match self { + Self::Srgb => srgb_encode(v), + Self::Linear => v, + } + } +} + +/// Below this encoded value the sRGB curve is linear. +const SRGB_KNEE_ENCODED: f32 = 0.04045; +/// Below this linear value the sRGB curve is linear. +const SRGB_KNEE_LINEAR: f32 = 0.003_130_8; + +/// sRGB-encoded 0..1 to linear light (non-finite input reads as 0). +pub fn srgb_decode(v: f32) -> f32 { + if !v.is_finite() { + return 0.0; + } + let v = v.clamp(0.0, 1.0); + if v <= SRGB_KNEE_ENCODED { v / 12.92 } else { libm::powf((v + 0.055) / 1.055, 2.4) } +} + +/// `srgb_decode(v)^e` in one `powf`, for `v` in 0..1 and finite `e`. +pub fn srgb_decode_pow(v: f32, e: f32) -> f32 { + if !v.is_finite() { + return 0.0; + } + let v = v.clamp(0.0, 1.0); + if v <= SRGB_KNEE_ENCODED { libm::powf(v / 12.92, e) } else { libm::powf((v + 0.055) / 1.055, 2.4 * e) } +} + +/// Linear light 0..1 to sRGB-encoded (clamped; non-finite input reads as 0). +pub fn srgb_encode(v: f32) -> f32 { + if !v.is_finite() { + return 0.0; + } + let v = v.clamp(0.0, 1.0); + if v <= SRGB_KNEE_LINEAR { v * 12.92 } else { 1.055 * libm::powf(v, 1.0 / 2.4) - 0.055 } +} + +/// `srgb_encode(v^e)` in one `powf`, for `v` in 0..1 and `e > 0`; `knee` is +/// [`encode_pow_knee`]`(e)`, the `v` below which `v^e` is in the curve's linear part. +pub fn srgb_encode_pow(v: f32, e: f32, knee: f32) -> f32 { + if !v.is_finite() { + return 0.0; + } + let v = v.clamp(0.0, 1.0); + if v <= knee { 12.92 * libm::powf(v, e) } else { 1.055 * libm::powf(v, e / 2.4) - 0.055 } +} + +/// The `v` below which `v^e` falls in the sRGB curve's linear part. +pub fn encode_pow_knee(e: f32) -> f32 { + if e.is_finite() && e > 0.0 { libm::powf(SRGB_KNEE_LINEAR, 1.0 / e) } else { SRGB_KNEE_LINEAR } +} + +/// Rec. 709 luminance of a linear RGB triple. +pub fn luminance(rgb: [f32; 3]) -> f32 { + 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn srgb_round_trips_and_pins_known_points() { + for v in [0.0, 0.001, 0.04045, 0.1, 0.5, 0.9, 1.0] { + assert!((srgb_decode(srgb_encode(v)) - v).abs() < 1e-6, "{v}"); + } + assert!((srgb_encode(0.18) - 0.4613).abs() < 1e-3); + assert!((srgb_decode(0.5) - 0.2140).abs() < 1e-3); + assert_eq!(srgb_encode(f32::NAN), 0.0); + assert_eq!(srgb_decode(2.0), 1.0); + } + + #[test] + fn fused_forms_match_the_chains() { + for v in [0.0f32, 0.001, 0.02, 0.04045, 0.1, 0.5, 0.9, 1.0] { + for e in [0.5, 1.0, 1.7, -1.6] { + // Negative exponents blow up at 0; callers clamp first, as the test does. + let v = if e < 0.0 { v.max(0.001) } else { v }; + let want = libm::powf(srgb_decode(v), e); + let got = srgb_decode_pow(v, e); + assert!((got - want).abs() / want.max(1.0) < 1e-4, "decode {v}^{e}: {got} vs {want}"); + } + for e in [0.5, 1.0, 2.0] { + let want = srgb_encode(libm::powf(v, e)); + let got = srgb_encode_pow(v, e, encode_pow_knee(e)); + assert!((got - want).abs() < 1e-5, "encode {v}^{e}: {got} vs {want}"); + } + } + assert_eq!(srgb_decode_pow(f32::NAN, 2.0), 0.0); + assert_eq!(srgb_encode_pow(f32::INFINITY, 1.0, encode_pow_knee(1.0)), 0.0); + assert_eq!(encode_pow_knee(f32::NAN), SRGB_KNEE_LINEAR); + } + + #[test] + fn depth_picks_encoding() { + assert_eq!(Encoding::for_depth(8), Encoding::Srgb); + assert_eq!(Encoding::for_depth(16), Encoding::Srgb); + assert_eq!(Encoding::for_depth(32), Encoding::Linear); + assert_eq!(Encoding::parse("linear"), Some(Encoding::Linear)); + assert_eq!(Encoding::parse("auto"), None); + } +} diff --git a/crates/film/src/film.rs b/crates/film/src/film.rs new file mode 100644 index 0000000000..bee1ecbc4d --- /dev/null +++ b/crates/film/src/film.rs @@ -0,0 +1,105 @@ +//! The negative's characteristic curve, straight-line approximation. +//! +//! Density `D = D_base + γ · log10(E)` for scene exposure `E` relative to the exposure that just +//! starts to darken the film; what the scanner sees is the transmittance `T = 10^−D`. So the +//! relative exposure that produced a scan value `t` with film base `t_base` is +//! `E = (t_base / t)^(1/γ)`: 1 at the base (scene black), growing as the negative gets denser. + +use crate::{NEGATIVE_GAMMA, color::Encoding}; + +/// Transmittance below which a sample reads as fully dense (avoids division by zero). +pub const MIN_TRANSMITTANCE: f32 = 1e-5; +/// The sRGB-encoded value of [`MIN_TRANSMITTANCE`] (in the curve's linear part). +const MIN_TRANSMITTANCE_SRGB: f32 = MIN_TRANSMITTANCE * 12.92; + +/// Relative scene exposure (≥ 1) behind a linear scan value `t` of a negative with film base +/// `t_base` (both linear light, 0..1). Values brighter than the base read as the base. +pub fn exposure(t: f32, t_base: f32) -> f32 { + let t_base = if t_base.is_finite() { t_base.max(MIN_TRANSMITTANCE) } else { MIN_TRANSMITTANCE }; + let t = if t.is_finite() { t.clamp(MIN_TRANSMITTANCE, t_base) } else { t_base }; + libm::powf(t_base / t, 1.0 / NEGATIVE_GAMMA) +} + +/// `t_base^(1/γ)`: the factor that turns `t^(−1/γ)` into [`exposure`]. +pub fn base_factor(t_base: f32) -> f32 { + let t_base = if t_base.is_finite() { t_base.max(MIN_TRANSMITTANCE) } else { MIN_TRANSMITTANCE }; + libm::powf(t_base, 1.0 / NEGATIVE_GAMMA) +} + +/// `factor · t^(−exponent)` for a scan value `v` in its host encoding: one `powf` per sample. +/// With `exponent = 1/γ` and `factor` the base's [`base_factor`] this is [`exposure`]; a +/// different exponent per channel normalises channels of unequal density range +/// ([`crate::Converter`]). Results below 1 read as 1 (brighter than the base); non-finite +/// input reads as the base. +pub fn exposure_encoded(v: f32, enc: Encoding, factor: f32, exponent: f32) -> f32 { + exposure_encoded_raw(v, enc, factor, exponent).max(1.0) +} + +/// [`exposure_encoded`] before its floor at 1: it keeps going below 1 past the base, so that a +/// table of it interpolates straight through the black point instead of across a corner. +pub fn exposure_encoded_raw(v: f32, enc: Encoding, factor: f32, exponent: f32) -> f32 { + if !v.is_finite() { + return 1.0; + } + let e = match enc { + Encoding::Srgb => factor * color::srgb_decode_pow(v.max(MIN_TRANSMITTANCE_SRGB), -exponent), + Encoding::Linear => factor * libm::powf(v.max(MIN_TRANSMITTANCE), -exponent), + }; + if e.is_finite() { e } else { 1.0 } +} + +use crate::color; + +/// The inverse: the linear scan value a relative exposure `e` (≥ 1) leaves on a negative with +/// film base `t_base`. Used to synthesise negatives in tests and to reason about levels. +pub fn transmittance(e: f32, t_base: f32) -> f32 { + transmittance_at(e, t_base, NEGATIVE_GAMMA) +} + +/// [`transmittance`] for a channel whose density grows by `gamma` per log-exposure: a scan of +/// colour film, whose channels spread apart ([`crate::SCAN_SPREAD`]). +pub fn transmittance_at(e: f32, t_base: f32, gamma: f32) -> f32 { + t_base * libm::powf(e.max(1.0), -gamma) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn base_is_unit_exposure_and_density_grows_with_exposure() { + assert_eq!(exposure(0.5, 0.5), 1.0); + assert_eq!(exposure(0.9, 0.5), 1.0, "brighter than the base clamps"); + let e1 = exposure(0.25, 0.5); + let e2 = exposure(0.125, 0.5); + assert!(e1 > 1.0 && e2 > e1); + // Halving the transmittance (0.3 density) is 0.5 log-exposure at γ 0.6: ×2^(1/0.6) ≈ 3.17. + assert!((e2 / e1 - 3.175).abs() < 0.01, "{e1} {e2}"); + } + + #[test] + fn transmittance_inverts_exposure() { + for e in [1.0, 2.0, 10.0, 64.0] { + let t = transmittance(e, 0.6); + assert!((exposure(t, 0.6) - e).abs() / e < 1e-4, "{e}"); + } + assert!(exposure(0.0, 0.6).is_finite()); + assert!(exposure(f32::NAN, f32::NAN).is_finite()); + } + + #[test] + fn encoded_form_matches_the_linear_one() { + let base = 0.6; + let k = base_factor(base); + for t in [0.6, 0.3, 0.1, 0.02, 0.001, 0.0] { + let want = exposure(t, base); + let lin = exposure_encoded(t, Encoding::Linear, k, 1.0 / NEGATIVE_GAMMA); + let srgb = exposure_encoded(color::srgb_encode(t), Encoding::Srgb, k, 1.0 / NEGATIVE_GAMMA); + assert!((lin - want).abs() / want < 1e-3, "linear {t}: {lin} vs {want}"); + assert!((srgb - want).abs() / want < 2e-3, "srgb {t}: {srgb} vs {want}"); + } + assert_eq!(exposure_encoded(0.9, Encoding::Linear, k, 1.0 / NEGATIVE_GAMMA), 1.0, "brighter than the base"); + assert_eq!(exposure_encoded(f32::NAN, Encoding::Srgb, k, 1.0 / NEGATIVE_GAMMA), 1.0); + assert!(exposure_encoded(0.0, Encoding::Srgb, f32::INFINITY, 1.0 / NEGATIVE_GAMMA).is_finite()); + } +} diff --git a/crates/film/src/lib.rs b/crates/film/src/lib.rs new file mode 100644 index 0000000000..3c76ab7a74 --- /dev/null +++ b/crates/film/src/lib.rs @@ -0,0 +1,718 @@ +//! Film-negative conversion: a scanned colour or black-and-white negative to a positive. +//! +//! Ported from Film Lab (github.com/smyrgeorge/film-lab, by the same author), whose PhotoCraft +//! plug-ins run the same maths. Hosts hand over RGB samples in 0..1 and say how they are encoded +//! ([`Encoding`]); this crate gives back the positive. Nothing in here knows a host's pixel layout; +//! [`measure`] analyses a whole scan once, so every render (a preview, a zoomed window, an export) +//! uses the same numbers. +//! +//! # The model +//! +//! A negative records scene exposure as density. In the straight part of its characteristic +//! curve, density grows by [`NEGATIVE_GAMMA`] per stop, so the light a scanner sees through the +//! film falls as the scene brightens. Reading that back: +//! +//! 1. **Film base.** The unexposed film (the border, orange on colour negative film) is the +//! brightest the scan gets and stands for scene black. Every channel is measured relative to +//! it, which also removes the orange mask ([`film::exposure`]). +//! 2. **Levels.** Each channel's density range between its black and white points is mapped onto +//! the same [`RANGE_STOPS`] of scene brightness, so channels of unequal range (a scan whose +//! blue runs much denser than its red) come out balanced, and black and white land on 0 and 1 +//! ([`Analysis`]: the base for black and the fixed range for white when only the base is +//! known, or scan values for black and white from an analysis of the image). +//! 3. **Colour** in linear light ([`look::Colour`]): exposure, white balance (sliders, a preset, +//! a neutral sample), the colour model, pre-saturation, mid-tone balance; black-and-white. +//! 4. **Tone** ([`tone::Curve`]): white and black points, brightness as a gamma, then in display +//! (sRGB-encoded) space a tone profile, contrast, lights / darks, fade / glow and soft ends. +//! 5. **Toning** ([`look::Toning`]): highlight and shadow colour balance and saturation on the +//! encoded result. +//! +//! The workflow this serves is the usual one for negatives: sample the film border, exclude +//! the border and sprocket holes from the evaluated area, convert, then edit. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod analysis; +pub mod color; +pub mod film; +pub mod look; +pub mod measure; +pub mod preset; +pub mod tone; + +pub use analysis::{Analysis, ValueHistogram}; +pub use color::Encoding; +pub use look::{Look, WbPreset}; +pub use measure::{MeasureOptions, Measurement}; +pub use preset::{PRESETS, Preset, SCAN_SPREAD, Sliders}; +pub use tone::Tone; + +/// The negative's contrast: density per log-exposure in the straight part of its characteristic +/// curve. Colour negative film sits near 0.6; the brightness and contrast controls absorb the +/// difference for other stocks. +pub const NEGATIVE_GAMMA: f32 = 0.6; + +/// Stops of scene brightness between the film base and the positive's white when only the base +/// is known (a density range of about 1.1 at [`NEGATIVE_GAMMA`], typical of a well-exposed +/// colour negative). +pub const RANGE_STOPS: f32 = 6.0; + +/// Stops the density range between the black and white points is rendered over by default +/// ([`Params::range`]). Fewer stops than the film's own [`RANGE_STOPS`] render mid-tones the way +/// a lab scan does: measured against a lab-converted reference, 3 matches its mid-tones; 6 is +/// the scene-linear rendition. +pub const DISPLAY_STOPS: f32 = 3.0; + +/// Channel indices in the RGB triples. +pub const RED: usize = 0; +pub const GREEN: usize = 1; +pub const BLUE: usize = 2; + +/// The user's edits. Slider ranges follow the Convert Negative panel: ±50 for the bipolar controls, +/// 0..100 for amounts, exposure in stops, pre-saturation 1..5. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Params { + /// Stops of scene brightness mapped between the black and white points (default + /// [`DISPLAY_STOPS`]); fewer stops render mid-tones brighter, as lab scans do, and + /// [`RANGE_STOPS`] is the scene-linear rendition. + pub range: f32, + /// Stops; positive brightens the whole positive. + pub exposure: f32, + /// Mid-tone gamma, −50..50; positive brightens mid-tones without moving black or white. + pub brightness: f32, + /// Added to the tone profile's contrast, −50..50. + pub contrast: f32, + pub tone: Tone, + /// −50..50; positive brightens the lighter tones. + pub lights: f32, + /// −50..50; positive brightens the darker tones. + pub darks: f32, + /// −50..50; moves the white point (positive brightens whites; clipped detail stays clipped). + pub whites: f32, + /// −50..50; moves the black point (positive lifts it for a faded look). + pub blacks: f32, + /// −100..100: positive lifts black for smoother shadows with no pure black; negative + /// expands the shadow tonality. + pub fade: f32, + /// −100..100: positive compresses the highlights into a soft shoulder; negative expands them. + pub glow: f32, + /// 0..100: tonal roll-off into white. + pub soft_highs: f32, + /// 0..100: tonal roll-off into black. + pub soft_lows: f32, + pub wb: WbPreset, + /// −50..50; positive is warmer. + pub temp: f32, + /// −50..50; positive is more magenta, negative more green. + pub tint: f32, + /// Per-channel mid-tone gammas (0.4..2.5, 1 = none): a colour balance that leaves black and + /// white alone, what an automatic neutral balance computes from the channel medians. + pub balance: [f32; 3], + /// 1..5, default 3: saturation before the tone curve, which also sets colour separation. + pub presat: f32, + /// −50..50: saturation after the tone curve. + pub saturation: f32, + pub look: Look, + /// Mid-tone colour balance, −50..50 each: red / cyan, green / magenta, blue / yellow. + pub mids_red: f32, + pub mids_green: f32, + pub mids_blue: f32, + /// Highlight toning balance, −50..50 each, and how far down it reaches (0..100). + pub highs_red: f32, + pub highs_green: f32, + pub highs_blue: f32, + pub highs_range: f32, + /// Shadow toning balance, −50..50 each, and how far up it reaches (0..100). + pub lows_red: f32, + pub lows_green: f32, + pub lows_blue: f32, + pub lows_range: f32, + /// Black-and-white film: the positive is the luminance (toning still colours it). + pub monochrome: bool, + /// Density per log-exposure of the red, green and blue channels of the scan, for levels + /// derived from a base alone ([`Analysis::from_base`]); a measured range makes it irrelevant. + /// A preset sets it to its [`Preset::scan_gamma`]. + pub film_gamma: [f32; 3], +} + +impl Default for Params { + fn default() -> Self { + Self { + range: DISPLAY_STOPS, + exposure: 0.0, + brightness: 0.0, + contrast: 0.0, + tone: Tone::LabStandard, + lights: 0.0, + darks: 0.0, + whites: 0.0, + blacks: 0.0, + fade: 0.0, + glow: 0.0, + soft_highs: 0.0, + soft_lows: 0.0, + wb: WbPreset::AsIs, + temp: 0.0, + tint: 0.0, + balance: [1.0; 3], + presat: 3.0, + saturation: 0.0, + look: Look::Neutral, + mids_red: 0.0, + mids_green: 0.0, + mids_blue: 0.0, + highs_red: 0.0, + highs_green: 0.0, + highs_blue: 0.0, + highs_range: 30.0, + lows_red: 0.0, + lows_green: 0.0, + lows_blue: 0.0, + lows_range: 30.0, + monochrome: false, + film_gamma: [NEGATIVE_GAMMA; 3], + } + } +} + +/// A conversion ready to run on pixels of one encoding: the analysis and the edits folded into +/// per-channel factors, one exponent, one colour pipeline and one tone curve. [`Converter::convert`] +/// is the exact path (two `powf` per channel, and an `expf` when the curve has contrast); +/// [`Converter::convert_with`] runs through [`Tables`] instead, with no transcendental call per +/// sample, for hosts that meter instructions. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Converter { + enc: Encoding, + /// Per channel, the normalised exposure `2^(u · RANGE_STOPS)` of a scan value `t` is + /// `factor · t^(−exponent)`, where `u` is the position of its density between the black and + /// white points (0..1): levels in density space folded into one `powf`. + factor: [f32; 3], + exponent: [f32; 3], + /// `gain / (2^RANGE_STOPS − 1)`: the normalised exposure to a positive, exposure folded in. + scale: f32, + colour: look::Colour, + monochrome: bool, + /// White point as a gain on the linear positive. + white_gain: f32, + /// Black point: lifted (positive) or crushed (negative), as a fraction of the range. + black_point: f32, + /// Exponent applied to the levelled positive per channel (brightness and balance). + gamma: [f32; 3], + /// [`color::encode_pow_knee`] of each `gamma`. + knee: [f32; 3], + curve: tone::Curve, + toning: look::Toning, +} + +impl Converter { + /// `neutral` is a scan sample (host encoding) of something that should come out grey, if the + /// user picked one with the colour picker. + pub fn new(a: &Analysis, p: &Params, enc: Encoding, neutral: Option<[f32; 3]>) -> Self { + let gain = libm::exp2f(finite(p.exposure, 0.0).clamp(-10.0, 10.0)); + let stops = finite(p.range, DISPLAY_STOPS).clamp(1.0, 10.0); + let scale = gain / (libm::exp2f(stops) - 1.0); + let mut factor = [0.0; 3]; + let mut exponent = [0.0; 3]; + for ch in 0..3 { + // Stops between the black and white points; the base-only default is RANGE_STOPS. + let black = if a.black[ch].is_finite() { a.black[ch].max(1.0) } else { 1.0 }; + let white = if a.white[ch].is_finite() { a.white[ch] } else { 0.0 }; + let range = libm::log2f(white) - libm::log2f(black); + let range = if range.is_finite() && range > 1e-3 { range } else { RANGE_STOPS }; + // 2^(u · S) = (E / black)^(S / range) = base^(S/(γ range)) · black^(−S/range) · t^(−S/(γ range)). + let e = stops / (NEGATIVE_GAMMA * range); + exponent[ch] = e; + let base = if a.base[ch].is_finite() { a.base[ch].max(film::MIN_TRANSMITTANCE) } else { film::MIN_TRANSMITTANCE }; + factor[ch] = libm::powf(base, e) * libm::powf(black, -stops / range); + } + let levelled = |neg: [f32; 3]| { + let mut out = [0.0; 3]; + for ch in 0..3 { + let e = film::exposure_encoded(neg[ch], enc, factor[ch], exponent[ch]); + out[ch] = ((e - 1.0) * scale).max(0.0); + } + out + }; + // Brightness, the profile's mid-tone gamma and the per-channel balance as one exponent per + // channel on the linear positive (a gamma in encoded space is close to the same gamma on + // the linear value, after encoding). + let brightness = libm::exp2f(-finite(p.brightness, 0.0).clamp(-50.0, 50.0) / 50.0) * p.tone.gamma(); + // The per-channel balance corrects a colour cast; a monochrome positive has none, and + // unequal gammas would tint it. + let balance = if p.monochrome { [1.0; 3] } else { p.balance }; + let mut gamma = [0.0; 3]; + let mut knee = [0.0; 3]; + for ch in 0..3 { + gamma[ch] = brightness * finite(balance[ch], 1.0).clamp(0.4, 2.5); + knee[ch] = color::encode_pow_knee(gamma[ch]); + } + Self { + enc, + factor, + exponent, + scale, + colour: look::Colour::new(p, neutral.map(levelled)), + monochrome: p.monochrome, + white_gain: libm::exp2f(finite(p.whites, 0.0).clamp(-50.0, 50.0) / 100.0), + black_point: finite(p.blacks, 0.0).clamp(-50.0, 50.0) / 100.0 * 0.2, + gamma, + knee, + curve: tone::Curve::new(p), + toning: look::Toning::new(p), + } + } + + pub fn encoding(&self) -> Encoding { + self.enc + } + + /// The levelled linear positive of channel `ch`'s scan value, exposure folded in, capped at + /// [`LEVELS_CAP`]. + fn levelled(&self, v: f32, ch: usize) -> f32 { + let e = film::exposure_encoded(v, self.enc, self.factor[ch], self.exponent[ch]); + ((e - 1.0) * self.scale).clamp(0.0, LEVELS_CAP) + } + + /// The white and black points on a linear positive, clamped to 0..1. + fn points(&self, v: f32) -> f32 { + let mut x = v * self.white_gain; + if self.black_point > 0.0 { + x = self.black_point + x * (1.0 - self.black_point); + } else if self.black_point < 0.0 { + x = (x + self.black_point) / (1.0 + self.black_point); + } + x.clamp(0.0, 1.0) + } + + /// The colour stage, monochrome and the points on a levelled positive. + fn graded(&self, mut p: [f32; 3]) -> [f32; 3] { + p = self.colour.apply(p); + if self.monochrome { + p = [color::luminance(p).max(0.0); 3]; + } + for v in &mut p { + *v = self.points(*v); + } + p + } + + /// One RGB sample of the negative, in the converter's encoding, as the linear positive before + /// the gammas and the tone curve: levels, exposure, colour, the white and black points. + fn positive(&self, neg: [f32; 3]) -> [f32; 3] { + let mut p = [0.0f32; 3]; + for (ch, (v, n)) in p.iter_mut().zip(neg).enumerate() { + *v = self.levelled(n, ch); + } + self.graded(p) + } + + /// Channel `ch` of a linear positive (after the points) as the sRGB-encoded sample before + /// toning: brightness (a gamma) and the tone curve, which act in sRGB-encoded space. + fn encoded(&self, p: f32, ch: usize) -> f32 { + self.curve.apply(color::srgb_encode_pow(p, self.gamma[ch], self.knee[ch])) + } + + /// The toning and the host's encoding on an sRGB-encoded positive. + fn finished(&self, mut out: [f32; 3]) -> [f32; 3] { + out = self.toning.apply(out); + match self.enc { + Encoding::Srgb => out, + Encoding::Linear => [color::srgb_decode(out[0]), color::srgb_decode(out[1]), color::srgb_decode(out[2])], + } + } + + /// One RGB sample of the negative, in the converter's encoding, as the positive in the same + /// encoding, 0..1: the exact path, two `powf` per channel. + pub fn convert(&self, neg: [f32; 3]) -> [f32; 3] { + let p = self.positive(neg); + if self.enc == Encoding::Linear && self.curve.is_identity() && self.toning.is_identity { + // Encoding and decoding again would cancel: a gamma on the linear value. + return [libm::powf(p[0], self.gamma[0]), libm::powf(p[1], self.gamma[1]), libm::powf(p[2], self.gamma[2])]; + } + self.finished([self.encoded(p[0], 0), self.encoded(p[1], 1), self.encoded(p[2], 2)]) + } + + /// Channel `ch` of a linear positive as the output table holds it: sRGB-encoded, or in the + /// host's encoding when `folded` (no toning to follow). + fn output_entry(&self, p: f32, ch: usize, folded: bool) -> f32 { + let out = self.encoded(p, ch); + if folded && self.enc == Encoding::Linear { color::srgb_decode(out) } else { out } + } + + /// Where a scan value sits in the levels table: as it is for an sRGB host, whose samples are + /// already spaced the way the levels curve bends; by its square root for a linear host, so + /// that the dense end (small values, the highlights) gets most of the entries. + fn levels_index(&self, v: f32) -> f32 { + match self.enc { + Encoding::Srgb => v, + Encoding::Linear => libm::sqrtf(v.max(0.0)), + } + } + + /// Fills `t` with this conversion's transfer functions, for [`Converter::convert_with`]. + pub fn tables(&self, t: &mut Tables) { + let step = 1.0 / (TABLE_SIZE - 1) as f32; + t.folded = self.toning.is_identity; + for (ch, (levels, output)) in t.levels.iter_mut().zip(t.output.iter_mut()).enumerate() { + // The scan value at which the relative exposure is 1: the black point. + let black = libm::powf(self.factor[ch], 1.0 / self.exponent[ch]); + t.black[ch] = self.levels_index(match self.enc { + Encoding::Srgb => color::srgb_encode(black), + Encoding::Linear => black, + }); + for (i, v) in levels.iter_mut().enumerate() { + let u = i as f32 * step; + let scan = match self.enc { + Encoding::Srgb => u, + Encoding::Linear => u * u, + }; + // Unfloored, so the entries run straight through the black point and an + // interpolation lands on it; `convert_with` floors the result. + let e = film::exposure_encoded_raw(scan, self.enc, self.factor[ch], self.exponent[ch]); + *v = ((e - 1.0) * self.scale).min(LEVELS_CAP); + } + for (i, v) in output.iter_mut().enumerate() { + *v = self.output_entry(i as f32 * step, ch, t.folded); + } + } + } + + /// [`Converter::convert`] through `t`, filled by [`Converter::tables`] for this converter: + /// the same positive to within the tables' interpolation (under a thousandth of the range) + /// with no transcendental call per sample, which is what counts under an interpreter. The + /// darkest inputs, where a steep gamma or a dense highlight outruns any table, take the + /// exact path: few pixels, so little cost. + pub fn convert_with(&self, t: &Tables, neg: [f32; 3]) -> [f32; 3] { + let index = match self.enc { + Encoding::Srgb => neg, + Encoding::Linear => [libm::sqrtf(neg[0].max(0.0)), libm::sqrtf(neg[1].max(0.0)), libm::sqrtf(neg[2].max(0.0))], + }; + let mut p = [0.0f32; 3]; + for (ch, (v, (table, (n, u)))) in p.iter_mut().zip(t.levels.iter().zip(neg.into_iter().zip(index))).enumerate() { + // At and past the black point (and for NaN) the positive is 0; the darkest inputs + // take the exact path; the rest interpolate. + *v = if u >= t.black[ch] || u.is_nan() { + 0.0 + } else if u < EXACT_BELOW { + self.levelled(n, ch) + } else { + lookup(table, u).max(0.0) + }; + } + p = self.graded(p); + let mut out = [0.0f32; 3]; + for (ch, (o, (table, v))) in out.iter_mut().zip(t.output.iter().zip(p)).enumerate() { + *o = if v < EXACT_BELOW { self.output_entry(v, ch, t.folded) } else { lookup(table, v) }; + } + if t.folded { out } else { self.finished(out) } + } +} + +/// Entries per channel in [`Tables`]. +pub const TABLE_SIZE: usize = 2048; + +/// Where the levelled positive stops: four stops over white, deep in what the white point clips. +/// Without it a scan value near zero puts a channel at 10⁸ and the colour stage's rounding +/// then zeroes the other two. +const LEVELS_CAP: f32 = 16.0; + +/// Inputs below this (the tables' first eight entries) take the exact path in +/// [`Converter::convert_with`]: a gamma of 0.2 or a highlight denser than the second entry +/// changes faster there than an interpolation can follow. +const EXACT_BELOW: f32 = 8.0 / (TABLE_SIZE - 1) as f32; + +/// The per-channel transfer functions of a [`Converter`] sampled over their input range, so that +/// a sample costs an interpolation per channel and stage instead of a `powf`. 48 KiB: keep one +/// in static memory and refill it per converter with [`Converter::tables`]. +pub struct Tables { + /// Host-encoded scan value (0..1; its square root for a linear host) → levelled linear + /// positive, exposure folded in, unfloored (negative past the black point). + levels: [[f32; TABLE_SIZE]; 3], + /// Linear positive after the colour stage and the points (0..1) → the output sample: the + /// brightness gamma and the tone curve, and the host's encoding when `folded`. + output: [[f32; TABLE_SIZE]; 3], + /// Where in `levels` each channel reaches its black point: at and past it the positive is + /// exactly 0, as on the exact path, rather than an interpolation's few millionths (which a + /// lifting gamma would make visible). + black: [f32; 3], + /// The toning (which mixes channels, so cannot be a table) is identity, and `output` ends + /// in the host's encoding; otherwise it ends sRGB-encoded for the toning to follow. + folded: bool, +} + +impl Tables { + pub const fn blank() -> Self { + Self { levels: [[0.0; TABLE_SIZE]; 3], output: [[0.0; TABLE_SIZE]; 3], black: [0.0; 3], folded: false } + } +} + +impl Default for Tables { + fn default() -> Self { + Self::blank() + } +} + +/// `table` at `x` (0..1, finite), linearly interpolated. +fn lookup(table: &[f32; TABLE_SIZE], x: f32) -> f32 { + let x = x.clamp(0.0, 1.0) * (TABLE_SIZE - 1) as f32; + let i = x as usize; + match (table.get(i), table.get(i + 1)) { + (Some(a), Some(b)) => a + (b - a) * (x - i as f32), + (Some(a), None) => *a, + _ => 0.0, + } +} + +/// `v`, or `fallback` when it is NaN or infinite. +pub(crate) fn finite(v: f32, fallback: f32) -> f32 { + if v.is_finite() { v } else { fallback } +} + +#[cfg(test)] +mod tests { + use super::*; + + const BASE: [f32; 3] = [0.6, 0.35, 0.15]; + + /// No edits and the scene-linear rendition: the film model's round trip. + fn neutral() -> Params { + Params { tone: Tone::Linear, range: RANGE_STOPS, ..Params::default() } + } + + /// The linear scan value a scene value `s` (0..1 of the positive's range) leaves, per channel. + fn negative(s: f32, ch: usize) -> f32 { + let white = libm::exp2f(RANGE_STOPS); + film::transmittance(1.0 + s * (white - 1.0), BASE[ch]) + } + + fn scan(s: f32, enc: Encoding) -> [f32; 3] { + [enc.encode(negative(s, 0)), enc.encode(negative(s, 1)), enc.encode(negative(s, 2))] + } + + fn convert(p: &Params, s: f32) -> [f32; 3] { + Converter::new(&Analysis::manual(BASE), p, Encoding::Srgb, None).convert(scan(s, Encoding::Srgb)) + } + + #[test] + fn manual_conversion_inverts_the_film_model_in_both_encodings() { + for enc in [Encoding::Srgb, Encoding::Linear] { + let c = Converter::new(&Analysis::manual(BASE), &neutral(), enc, None); + assert_eq!(c.encoding(), enc); + for s in [0.0, 0.01, 0.1, 0.18, 0.5, 0.9, 1.0] { + let out = c.convert(scan(s, enc)); + let want = enc.encode(s); + for v in out { + assert!((v - want).abs() < 2e-3, "{enc:?} scene {s}: got {out:?}, want {want}"); + } + } + } + } + + #[test] + fn base_is_black_and_brighter_than_base_stays_black() { + let c = Converter::new(&Analysis::manual(BASE), &neutral(), Encoding::Linear, None); + assert_eq!(c.convert(BASE), [0.0; 3]); + assert_eq!(c.convert([0.9, 0.9, 0.9]), [0.0; 3]); + // Nothing transmitted at all: the brightest possible scene tone. + assert!(c.convert([0.0; 3]).iter().all(|v| (v - 1.0).abs() < 1e-6)); + } + + #[test] + fn exposure_brightness_whites_and_blacks_move_tones_the_right_way() { + let base = convert(&neutral(), 0.18)[0]; + let up = convert(&Params { exposure: 1.0, ..neutral() }, 0.18)[0]; + let bright = convert(&Params { brightness: 25.0, ..neutral() }, 0.18)[0]; + let dark = convert(&Params { brightness: -25.0, ..neutral() }, 0.18)[0]; + assert!(up > base && bright > base && dark < base, "{base} {up} {bright} {dark}"); + assert!((color::srgb_decode(up) / color::srgb_decode(base) - 2.0).abs() < 0.02, "one stop doubles linear light"); + // Brightness is a gamma: black and white stay put. + assert_eq!(convert(&Params { brightness: 40.0, ..neutral() }, 0.0)[0], 0.0); + assert!((convert(&Params { brightness: 40.0, ..neutral() }, 1.0)[0] - 1.0).abs() < 1e-5); + // Whites scale towards white, blacks lift or crush the black point. + assert!(convert(&Params { whites: 50.0, ..neutral() }, 0.5)[0] > convert(&neutral(), 0.5)[0]); + assert!(convert(&Params { whites: 50.0, ..neutral() }, 0.0)[0] == 0.0); + assert!(convert(&Params { blacks: 50.0, ..neutral() }, 0.0)[0] > 0.05, "lifted black"); + assert!(convert(&Params { blacks: -50.0, ..neutral() }, 0.05)[0] == 0.0, "crushed black"); + assert!((convert(&Params { blacks: -50.0, ..neutral() }, 1.0)[0] - 1.0).abs() < 1e-5); + } + + #[test] + fn white_balance_presets_looks_and_monochrome() { + let warm = convert(&Params { temp: 50.0, ..neutral() }, 0.3); + assert!(warm[0] > warm[1] && warm[1] > warm[2], "{warm:?}"); + let magenta = convert(&Params { tint: 50.0, ..neutral() }, 0.3); + assert!(magenta[1] < magenta[0] && magenta[1] < magenta[2], "{magenta:?}"); + let preset = convert(&Params { wb: WbPreset::Warm, ..neutral() }, 0.3); + assert!(preset[0] > preset[2], "{preset:?}"); + let lab = convert(&Params { look: Look::LabWarm, ..neutral() }, 0.3); + assert!(lab[0] > lab[2], "{lab:?}"); + assert!(convert(&Params { tone: Tone::LinearDeep, ..neutral() }, 0.3)[0] < convert(&neutral(), 0.3)[0], "deep darkens mid-tones"); + let mono = convert(&Params { monochrome: true, temp: 50.0, ..neutral() }, 0.3); + assert!(mono[0] == mono[1] && mono[1] == mono[2], "{mono:?}"); + let toned = convert(&Params { monochrome: true, lows_blue: 50.0, lows_range: 100.0, ..neutral() }, 0.1); + assert!(toned[2] > toned[0], "toning colours a black-and-white positive: {toned:?}"); + let grey = convert(&Params { saturation: -50.0, temp: 50.0, ..neutral() }, 0.3); + assert!((grey[0] - grey[2]).abs() < 1e-5, "{grey:?}"); + } + + #[test] + fn unequal_channel_ranges_are_balanced_by_the_levels() { + // A scan whose blue runs twice as dense as its red for the same scene: with black and + // white points per channel, a scene grey still comes out grey at every tone. + let stops = [4.0f32, 6.0, 8.0]; + let scan = |s: f32| { + let mut v = [0.0; 3]; + for ch in 0..3 { + v[ch] = Encoding::Srgb.encode(film::transmittance(libm::exp2f(s * stops[ch]), BASE[ch])); + } + v + }; + let a = Analysis::from_scan_values( + [Encoding::Srgb.encode(BASE[0]), Encoding::Srgb.encode(BASE[1]), Encoding::Srgb.encode(BASE[2])], + scan(0.0), + scan(1.0), + Encoding::Srgb, + ) + .unwrap(); + let c = Converter::new(&a, &neutral(), Encoding::Srgb, None); + for s in [0.0, 0.2, 0.5, 0.8, 1.0] { + let out = c.convert(scan(s)); + assert!((out[0] - out[1]).abs() < 4e-3 && (out[1] - out[2]).abs() < 4e-3, "scene {s}: {out:?}"); + let want = color::srgb_encode((libm::exp2f(s * RANGE_STOPS) - 1.0) / (libm::exp2f(RANGE_STOPS) - 1.0)); + assert!((out[1] - want).abs() < 4e-3, "scene {s}: {out:?} vs {want}"); + } + } + + #[test] + fn range_and_balance_move_midtones_without_moving_the_ends() { + let wide = convert(&neutral(), 0.18)[0]; + let narrow = convert(&Params { range: 3.0, ..neutral() }, 0.18)[0]; + assert!(narrow > wide, "fewer stops between black and white render mid-tones brighter: {narrow} vs {wide}"); + assert_eq!(Params::default().range, DISPLAY_STOPS); + assert_eq!(convert(&Params { range: 3.0, ..neutral() }, 0.0)[0], 0.0); + assert!((convert(&Params { range: 3.0, ..neutral() }, 1.0)[0] - 1.0).abs() < 1e-5); + let balanced = convert(&Params { balance: [0.8, 1.0, 1.25], ..neutral() }, 0.3); + assert!(balanced[0] > balanced[1] && balanced[1] > balanced[2], "{balanced:?}"); + assert_eq!(convert(&Params { balance: [0.8, 1.0, 1.25], ..neutral() }, 0.0), [0.0; 3]); + assert!(convert(&Params { balance: [0.8, 1.0, 1.25], ..neutral() }, 1.0).iter().all(|v| (v - 1.0).abs() < 1e-5)); + } + + #[test] + fn neutral_sample_balances_the_positive() { + // A scene grey that the scan renders with a cast (a stronger red mask than the base says). + let a = Analysis::manual(BASE); + let cast = [0.8, 1.0, 1.0]; + let scan_of = + |s: f32| [Encoding::Srgb.encode(negative(s, 0) * cast[0]), Encoding::Srgb.encode(negative(s, 1)), Encoding::Srgb.encode(negative(s, 2))]; + let before = Converter::new(&a, &neutral(), Encoding::Srgb, None).convert(scan_of(0.4)); + assert!(before[0] > before[1] + 0.02, "the cast shows: {before:?}"); + let after = Converter::new(&a, &neutral(), Encoding::Srgb, Some(scan_of(0.4))).convert(scan_of(0.4)); + assert!((after[0] - after[1]).abs() < 2e-3 && (after[1] - after[2]).abs() < 2e-3, "{after:?}"); + } + + #[test] + fn a_balance_never_tints_a_monochrome_positive() { + let p = Params { monochrome: true, balance: [0.7, 1.0, 1.5], ..neutral() }; + for s in [0.05, 0.3, 0.7] { + let out = convert(&p, s); + assert!((out[0] - out[1]).abs() < 1e-6 && (out[1] - out[2]).abs() < 1e-6, "{out:?}"); + } + let colour = convert(&Params { balance: [0.7, 1.0, 1.5], ..neutral() }, 0.3); + assert!(colour[0] > colour[2] + 0.02, "the same balance does tint a colour positive: {colour:?}"); + } + + #[test] + fn tables_match_the_exact_conversion() { + let mut t = std::boxed::Box::new(Tables::blank()); + let cases = [ + Params::default(), + neutral(), + Params { + brightness: 20.0, + contrast: 25.0, + temp: 15.0, + tint: -10.0, + saturation: 20.0, + lows_blue: 30.0, + lows_range: 40.0, + ..Params::default() + }, + Params { monochrome: true, balance: [0.8, 1.0, 1.3], ..Params::default() }, + // The steepest gammas the sliders and a balance reach, and the hardest curve. + Params { brightness: 50.0, balance: [0.4, 1.0, 2.5], contrast: 50.0, ..Params::default() }, + Params { brightness: -50.0, balance: [2.5, 1.0, 0.4], whites: 30.0, blacks: -20.0, ..Params::default() }, + ]; + for enc in [Encoding::Srgb, Encoding::Linear] { + // The base alone, and a measurement whose blue highlight sits two entries from black. + let dense = [0.2, 0.1, if enc == Encoding::Linear { 0.001 } else { 0.03 }]; + let analyses = [Analysis::manual(BASE), Analysis::from_scan_values(enc.encode3(BASE), enc.encode3(BASE), dense, enc).unwrap()]; + for (p, a) in cases.iter().flat_map(|p| analyses.iter().map(move |a| (p, a))) { + let c = Converter::new(a, p, enc, None); + c.tables(&mut t); + // Compared as displayed: a linear host's output is sRGB-encoded first. + let shown = |v: f32| if enc == Encoding::Linear { color::srgb_encode(v) } else { v }; + let (mut worst, mut at) = (0.0f32, [0.0f32; 3]); + for i in 0..=255u32 { + for j in (0..=255u32).step_by(15) { + for k in (0..=255u32).step_by(15) { + let neg = [i as f32 / 255.0, j as f32 / 255.0, k as f32 / 255.0]; + // A hair above the black point no path is stable: a lifting gamma + // turns the rounding of a millionth into percents. + if (0..3).any(|ch| (0.0..1e-5).contains(&c.levelled(neg[ch], ch)) && c.levelled(neg[ch], ch) > 0.0) { + continue; + } + let exact = c.convert(neg); + let fast = c.convert_with(&t, neg); + for ch in 0..3 { + let d = (shown(exact[ch]) - shown(fast[ch])).abs(); + if d > worst { + (worst, at) = (d, neg); + } + } + } + } + } + let (exact, fast) = (c.convert(at), c.convert_with(&t, at)); + std::eprintln!( + "{enc:?}, brightness {}, contrast {}, white {:?}: the tables stray by {worst} at {at:?}: {exact:?} vs {fast:?}", + p.brightness, + p.contrast, + a.white + ); + assert!(worst < 1e-3, "{enc:?}: the tables stray by {worst} (an 8-bit level is 0.0039)"); + } + } + // Non-finite input is black, as on the exact path. + let c = Converter::new(&Analysis::manual(BASE), &Params::default(), Encoding::Srgb, None); + c.tables(&mut t); + let odd = [f32::NAN, 0.5, f32::INFINITY]; + assert!(c.convert_with(&t, odd).iter().zip(c.convert(odd)).all(|(a, b)| (a - b).abs() < 1e-3)); + } + + #[test] + fn tone_curves_reach_linear_documents_too() { + let strong = Params { tone: Tone::LabHard, range: RANGE_STOPS, ..Params::default() }; + let lin = Converter::new(&Analysis::manual(BASE), &strong, Encoding::Linear, None).convert(scan(0.05, Encoding::Linear))[0]; + let srgb = Converter::new(&Analysis::manual(BASE), &strong, Encoding::Srgb, None).convert(scan(0.05, Encoding::Srgb))[0]; + assert!((color::srgb_encode(lin) - srgb).abs() < 2e-3, "{lin} vs {srgb}"); + assert!(lin < 0.05, "a dark tone drops under a hard curve: {lin}"); + } + + #[test] + fn hostile_parameters_do_not_poison_the_output() { + let p = Params { + exposure: f32::NAN, + brightness: f32::INFINITY, + temp: -1e9, + saturation: f32::NEG_INFINITY, + presat: f32::NAN, + whites: 1e9, + ..Params::default() + }; + let out = convert(&p, 0.5); + assert!(out.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{out:?}"); + let c = Converter::new(&Analysis::manual([f32::NAN, 0.0, f32::INFINITY]), &Params::default(), Encoding::Srgb, Some([f32::NAN; 3])); + let out = c.convert([f32::NAN, -1.0, 2.0]); + assert!(out.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{out:?}"); + } +} diff --git a/crates/film/src/look.rs b/crates/film/src/look.rs new file mode 100644 index 0000000000..d36a4ba38e --- /dev/null +++ b/crates/film/src/look.rs @@ -0,0 +1,331 @@ +//! Colour: white-balance presets, the colour models (looks), mid-tone colour balance and +//! highlight / shadow toning. Everything here is a per-channel gain or a small matrix, so the +//! conversion stays within the host's instruction budget. + +use crate::{Params, color, finite}; + +/// White-balance presets: fixed temperature / tint offsets for film stocks whose balance a +/// neutral conversion tends to miss. `AsIs` leaves the sliders alone. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum WbPreset { + #[default] + AsIs, + /// A touch of warmth, what most colour negative film wants after an inversion. + Warm, + Cool, + /// Tungsten-balanced cine stock shot in daylight: a stronger warm correction. + TungstenFilm, +} + +impl WbPreset { + pub const ALL: [(WbPreset, &'static str); 4] = + [(WbPreset::AsIs, "as_is"), (WbPreset::Warm, "warm"), (WbPreset::Cool, "cool"), (WbPreset::TungstenFilm, "tungsten_film")]; + + pub fn parse(s: &str) -> Option { + Self::ALL.iter().find(|(_, name)| *name == s).map(|(t, _)| *t) + } + + /// (temperature, tint) offsets in slider units. + pub fn offsets(self) -> (f32, f32) { + match self { + Self::AsIs => (0.0, 0.0), + Self::Warm => (8.0, 2.0), + Self::Cool => (-8.0, -2.0), + Self::TungstenFilm => (18.0, 4.0), + } + } +} + +/// Colour models: how the positive's colours are rendered. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Look { + /// Colour accuracy over character. + #[default] + Neutral, + /// The rendering of a minilab scanner: teal blues, golden yellows, warm neutrals. + LabWarm, + /// The same family, less warm. + LabCool, + /// Print-like depth: denser shadows with a touch of green, lifted saturation. + Print, + /// Luminosity first: clean contrast, restrained colour. + Clean, +} + +impl Look { + pub const ALL: [(Look, &'static str); 5] = + [(Look::Neutral, "neutral"), (Look::LabWarm, "lab_warm"), (Look::LabCool, "lab_cool"), (Look::Print, "print"), (Look::Clean, "clean")]; + + pub fn parse(s: &str) -> Option { + Self::ALL.iter().find(|(_, name)| *name == s).map(|(t, _)| *t) + } + + pub fn name(self) -> &'static str { + Self::ALL.iter().find(|(t, _)| *t == self).map_or("neutral", |(_, name)| name) + } + + /// A row-major matrix on linear RGB (rows sum to 1, so neutrals stay neutral), plus + /// temperature / tint offsets, a saturation factor and a shadow tint (linear RGB gains + /// weighted towards black). + pub fn recipe(self) -> Recipe { + let identity = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]; + match self { + Self::Neutral => Recipe { matrix: identity, temp: 0.0, tint: 0.0, saturation: 1.0, shadow_tint: [1.0; 3] }, + Self::LabWarm => Recipe { + matrix: [[1.00, 0.06, -0.06], [0.02, 1.00, -0.02], [-0.08, 0.12, 0.96]], + temp: 5.0, + tint: 1.0, + saturation: 1.12, + shadow_tint: [1.0; 3], + }, + Self::LabCool => Recipe { + matrix: [[1.00, 0.03, -0.03], [0.0, 1.00, 0.0], [-0.06, 0.10, 0.96]], + temp: 0.0, + tint: 0.0, + saturation: 1.08, + shadow_tint: [1.0; 3], + }, + Self::Print => Recipe { matrix: identity, temp: 2.0, tint: -1.0, saturation: 1.1, shadow_tint: [0.97, 1.02, 0.98] }, + Self::Clean => Recipe { matrix: identity, temp: 0.0, tint: 0.0, saturation: 0.92, shadow_tint: [1.0; 3] }, + } + } +} + +/// What a [`Look`] does, see [`Look::recipe`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Recipe { + pub matrix: [[f32; 3]; 3], + pub temp: f32, + pub tint: f32, + pub saturation: f32, + pub shadow_tint: [f32; 3], +} + +/// Per-channel gains for a temperature / tint pair (slider units, −50..50 each; larger values +/// from presets are allowed), applied in linear light. +pub fn white_balance(temp: f32, tint: f32) -> [f32; 3] { + let t = finite(temp, 0.0).clamp(-100.0, 100.0) / 50.0; + let u = finite(tint, 0.0).clamp(-100.0, 100.0) / 50.0; + [(1.0 + 0.4 * t).max(0.05), (1.0 - 0.3 * u).max(0.05), (1.0 - 0.4 * t).max(0.05)] +} + +/// Gains that make the linear positive `sample` neutral (the colour picker on a grey card or a +/// white wall): each channel to the sample's luminance. `None` for a sample without colour. +pub fn neutralise(sample: [f32; 3]) -> Option<[f32; 3]> { + let y = color::luminance(sample); + if !y.is_finite() || y <= 1e-6 || sample.iter().any(|v| !v.is_finite() || *v <= 1e-6) { + return None; + } + Some([(y / sample[0]).clamp(0.2, 5.0), (y / sample[1]).clamp(0.2, 5.0), (y / sample[2]).clamp(0.2, 5.0)]) +} + +/// Weight of the highlights for toning: 0 below `1 − reach`, 1 at white (`reach` 0..1). +pub fn highs_weight(y: f32, reach: f32) -> f32 { + let reach = reach.clamp(0.05, 1.0); + smoothstep((y - (1.0 - reach)) / reach) +} + +/// Weight of the shadows for toning: 1 at black, 0 above `reach` (`reach` 0..1). +pub fn lows_weight(y: f32, reach: f32) -> f32 { + let reach = reach.clamp(0.05, 1.0); + smoothstep((reach - y) / reach) +} + +/// Weight of the mid-tones: 1 at middle grey, 0 at black and white. +pub fn mids_weight(y: f32) -> f32 { + let y = y.clamp(0.0, 1.0); + 4.0 * y * (1.0 - y) +} + +fn smoothstep(x: f32) -> f32 { + let x = finite(x, 0.0).clamp(0.0, 1.0); + x * x * (3.0 - 2.0 * x) +} + +/// The colour part of a conversion, folded from [`Params`]: everything in linear light. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Colour { + /// White balance (sliders, preset, look and neutral sample) as gains. + pub gains: [f32; 3], + pub matrix: [[f32; 3]; 3], + /// Saturation before the tone curve (pre-saturation and the look), as a chroma factor. + pub presat: f32, + /// Mid-tone balance gains at full weight (red/cyan, green/magenta, blue/yellow). + pub mids: [f32; 3], + pub shadow_tint: [f32; 3], + /// The matrix is not the identity. + mixes: bool, + /// The mid-tone balance or the shadow tint is not neutral, so the luminance weights are needed. + weighted: bool, + pub is_identity: bool, +} + +impl Colour { + /// `neutral` is a linear positive sample that should come out grey, if the user picked one. + pub fn new(p: &Params, neutral: Option<[f32; 3]>) -> Self { + let recipe = p.look.recipe(); + let (pt, pu) = p.wb.offsets(); + let mut gains = white_balance(finite(p.temp, 0.0) + pt + recipe.temp, finite(p.tint, 0.0) + pu + recipe.tint); + if let Some(n) = neutral.and_then(neutralise) { + for (g, k) in gains.iter_mut().zip(n) { + *g *= k; + } + } + let presat = (finite(p.presat, 3.0).clamp(1.0, 5.0) / 3.0 * recipe.saturation).max(0.0); + let mut mids = [1.0; 3]; + for (m, v) in mids.iter_mut().zip([p.mids_red, p.mids_green, p.mids_blue]) { + *m = 1.0 + finite(v, 0.0).clamp(-50.0, 50.0) / 50.0 * 0.25; + } + let mixes = recipe.matrix != Look::Neutral.recipe().matrix; + let weighted = mids != [1.0; 3] || recipe.shadow_tint != [1.0; 3]; + let is_identity = gains == [1.0; 3] && !mixes && (presat - 1.0).abs() < 1e-6 && !weighted; + Self { gains, matrix: recipe.matrix, presat, mids, shadow_tint: recipe.shadow_tint, mixes, weighted, is_identity } + } + + /// One linear positive sample (levelled, 0..1-ish) through the colour pipeline. + pub fn apply(&self, mut p: [f32; 3]) -> [f32; 3] { + if self.is_identity { + return p; + } + for (v, g) in p.iter_mut().zip(self.gains) { + *v *= g; + } + if self.mixes { + let m = &self.matrix; + p = [ + m[0][0] * p[0] + m[0][1] * p[1] + m[0][2] * p[2], + m[1][0] * p[0] + m[1][1] * p[1] + m[1][2] * p[2], + m[2][0] * p[0] + m[2][1] * p[1] + m[2][2] * p[2], + ]; + } + let y = color::luminance(p).max(0.0); + if !self.weighted { + for v in &mut p { + *v = (y + (*v - y) * self.presat).max(0.0); + } + return p; + } + // Perceptual weights from the luminance; a square root is one instruction. + let yl = libm::sqrtf(y); + let w_mid = mids_weight(yl); + let w_low = lows_weight(yl, 0.35); + for (ch, v) in p.iter_mut().enumerate() { + let mut x = y + (*v - y) * self.presat; + x *= 1.0 + (self.mids[ch] - 1.0) * w_mid; + x *= 1.0 + (self.shadow_tint[ch] - 1.0) * w_low; + *v = x.max(0.0); + } + p + } +} + +/// Highlight and shadow toning, applied to the encoded positive after the tone curve: a +/// red / cyan, green / magenta and blue / yellow balance for each end, with a `range` that +/// says how far from the end the toning reaches. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Toning { + highs: [f32; 3], + highs_reach: f32, + lows: [f32; 3], + lows_reach: f32, + /// Saturation after the curve, as a chroma factor. + saturation: f32, + pub is_identity: bool, +} + +impl Toning { + pub fn new(p: &Params) -> Self { + let slider = |v: f32| finite(v, 0.0).clamp(-50.0, 50.0) / 50.0 * 0.15; + let reach = |v: f32| 0.2 + finite(v, 30.0).clamp(0.0, 100.0) / 100.0 * 0.6; + let highs = [slider(p.highs_red), slider(p.highs_green), slider(p.highs_blue)]; + let lows = [slider(p.lows_red), slider(p.lows_green), slider(p.lows_blue)]; + let saturation = (1.0 + finite(p.saturation, 0.0).clamp(-50.0, 50.0) / 50.0).max(0.0); + let is_identity = highs == [0.0; 3] && lows == [0.0; 3] && (saturation - 1.0).abs() < 1e-6; + Self { highs, highs_reach: reach(p.highs_range), lows, lows_reach: reach(p.lows_range), saturation, is_identity } + } + + /// One encoded RGB sample (0..1) toned and saturated, 0..1. + pub fn apply(&self, mut c: [f32; 3]) -> [f32; 3] { + if self.is_identity { + return c; + } + let y = (c[0] + c[1] + c[2]) / 3.0; + let w_hi = highs_weight(y, self.highs_reach); + let w_lo = lows_weight(y, self.lows_reach); + for (ch, x) in c.iter_mut().enumerate() { + let v = y + (*x - y) * self.saturation; + *x = (v + self.highs[ch] * w_hi + self.lows[ch] * w_lo).clamp(0.0, 1.0); + } + c + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn presets_and_looks_parse_and_keep_neutrals_neutral() { + for (preset, name) in WbPreset::ALL { + assert_eq!(WbPreset::parse(name), Some(preset)); + } + for (look, name) in Look::ALL { + assert_eq!(Look::parse(name), Some(look)); + let m = look.recipe().matrix; + for row in m { + assert!((row.iter().sum::() - 1.0).abs() < 1e-6, "{name}: {row:?}"); + } + } + assert_eq!(Look::parse("frontier"), None); + let warm = Colour::new(&Params { look: Look::LabWarm, ..Params::default() }, None); + let grey = warm.apply([0.3, 0.3, 0.3]); + assert!(grey[0] > grey[2], "the warm lab look warms neutrals: {grey:?}"); + let neutral = Colour::new(&Params::default(), None); + assert!(neutral.is_identity); + assert_eq!(neutral.apply([0.2, 0.4, 0.6]), [0.2, 0.4, 0.6]); + } + + #[test] + fn toning_colours_the_ends_and_post_saturation_scales_chroma() { + let warm_highs = Toning::new(&Params { highs_blue: -50.0, highs_range: 10.0, ..Params::default() }); + assert!(!warm_highs.is_identity); + let hi = warm_highs.apply([0.95, 0.95, 0.95]); + assert!(hi[2] < hi[0] && hi[0] == 0.95, "yellow highlights: {hi:?}"); + assert_eq!(warm_highs.apply([0.3, 0.3, 0.3]), [0.3, 0.3, 0.3], "mid-tones untouched at a short range"); + let cool_lows = Toning::new(&Params { lows_blue: 50.0, lows_range: 100.0, ..Params::default() }); + let lo = cool_lows.apply([0.1, 0.1, 0.1]); + assert!(lo[2] > lo[0], "{lo:?}"); + assert_eq!(cool_lows.apply([1.0; 3]), [1.0; 3]); + let grey = Toning::new(&Params { saturation: -50.0, ..Params::default() }).apply([0.2, 0.5, 0.8]); + assert!((grey[0] - grey[2]).abs() < 1e-6, "{grey:?}"); + assert!(Toning::new(&Params::default()).is_identity); + } + + #[test] + fn neutral_sample_is_made_grey() { + let sample = [0.5, 0.4, 0.3]; + let c = Colour::new(&Params::default(), Some(sample)); + let out = c.apply(sample); + assert!((out[0] - out[1]).abs() < 1e-5 && (out[1] - out[2]).abs() < 1e-5, "{out:?}"); + assert_eq!(neutralise([0.0, 0.5, 0.5]), None); + assert_eq!(neutralise([f32::NAN; 3]), None); + } + + #[test] + fn presat_mids_and_toning_helpers() { + let vivid = Colour::new(&Params { presat: 5.0, ..Params::default() }, None).apply([0.6, 0.3, 0.3]); + let flat = Colour::new(&Params { presat: 1.0, ..Params::default() }, None).apply([0.6, 0.3, 0.3]); + assert!(vivid[0] - vivid[1] > 0.3 && flat[0] - flat[1] < 0.3, "{vivid:?} {flat:?}"); + let mids = Colour::new(&Params { mids_red: 50.0, ..Params::default() }, None); + let mid = mids.apply([0.2, 0.2, 0.2]); + assert!(mid[0] > mid[1], "{mid:?}"); + let black = mids.apply([0.0; 3]); + assert_eq!(black, [0.0; 3]); + assert_eq!(highs_weight(1.0, 0.5), 1.0); + assert_eq!(highs_weight(0.4, 0.5), 0.0); + assert_eq!(lows_weight(0.0, 0.3), 1.0); + assert_eq!(lows_weight(0.5, 0.3), 0.0); + assert_eq!(mids_weight(0.5), 1.0); + assert_eq!(white_balance(0.0, 0.0), [1.0; 3]); + } +} diff --git a/crates/film/src/measure.rs b/crates/film/src/measure.rs new file mode 100644 index 0000000000..b68136d579 --- /dev/null +++ b/crates/film/src/measure.rs @@ -0,0 +1,173 @@ +//! What belongs to the scan rather than the film, measured once on the whole image: the film base +//! and each channel's black and white point, and a mid-tone balance that makes the scene average +//! grey. A host stores the result with the photo's settings, so every render of it (a draft, a +//! zoomed window, a full-size export) converts with the same numbers. + +use crate::{Analysis, Converter, Encoding, Params, Tone, ValueHistogram, color}; + +/// How a scan is measured. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MeasureOptions { + /// Fraction of each edge left out (film holder, sprocket holes, the border itself), 0..0.45. + pub border: f32, + /// Share of the brightest samples that may lie above the film base (dust, hot pixels). + pub base_clip: f32, + /// Shares of samples allowed beyond black and white. + pub black_clip: f32, + pub white_clip: f32, + /// Bring each channel's median to the common one with a per-channel gamma (a grey scene + /// average). Off: the black and white points are neutral and the scene keeps its own colour. + pub neutral: bool, + /// At most this many pixels are sampled (a regular grid over the image). + pub max_samples: usize, +} + +impl Default for MeasureOptions { + fn default() -> Self { + Self { border: 0.08, base_clip: 0.001, black_clip: 0.003, white_clip: 0.003, neutral: true, max_samples: 1_000_000 } + } +} + +/// A measured scan: scan values in linear light, 0..1, per channel. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Measurement { + /// The film base: the unexposed film, scene black. + pub base: [f32; 3], + /// The brightest value that still counts as exposed (the positive's black). + pub black: [f32; 3], + /// The densest value (the positive's white). + pub white: [f32; 3], + /// Per-channel mid-tone gammas that neutralise the scene average (1 = none). + pub balance: [f32; 3], +} + +impl Measurement { + /// The levels of this measurement for linear samples; with a `base` picked from the border, + /// that base is black and the measured white point still applies. `None` when a channel has + /// no range left between black and white. + pub fn analysis(&self, base: Option<[f32; 3]>) -> Option { + match base { + Some(b) => Analysis::from_scan_values(b, b, self.white, Encoding::Linear), + None => Analysis::from_scan_values(self.base, self.black, self.white, Encoding::Linear), + } + } +} + +/// Measures a `w × h` scan of linear samples (row-major, 0..1 per channel). +pub fn measure(pixels: &[[f32; 3]], w: usize, h: usize, o: &MeasureOptions) -> Result { + if pixels.len() < w.saturating_mul(h) { + return Err("the image is smaller than its size says".into()); + } + let border = if o.border.is_finite() { o.border.clamp(0.0, 0.45) } else { 0.0 }; + let (bx, by) = ((w as f32 * border) as usize, (h as f32 * border) as usize); + let (x0, x1, y0, y1) = (bx, w.saturating_sub(bx), by, h.saturating_sub(by)); + if x1 <= x0 || y1 <= y0 { + return Err("the border leaves no pixels to measure".into()); + } + let area = (x1 - x0).saturating_mul(y1 - y0); + let step = (libm::ceil(libm::sqrt(area as f64 / o.max_samples.max(1) as f64)) as usize).max(1); + // The histogram is binned on the sRGB-encoded values, which spread the dense end (the + // highlights, near 0 in linear light) over many more bins than a linear scale would. + let mut hist = ValueHistogram::new(); + for y in (y0..y1).step_by(step) { + for x in (x0..x1).step_by(step) { + if let Some(p) = pixels.get(y * w + x) { + hist.push(Encoding::Srgb.encode3(*p)); + } + } + } + if hist.count() == 0 { + return Err("no pixels to measure".into()); + } + let q = |ch: usize, frac: f32| hist.quantile(ch, frac).map(color::srgb_decode).ok_or_else(|| "empty histogram".to_string()); + let mut m = Measurement { base: [0.0; 3], black: [0.0; 3], white: [0.0; 3], balance: [1.0; 3] }; + let mut median = [0.0; 3]; + for (ch, med) in median.iter_mut().enumerate() { + m.base[ch] = q(ch, 1.0 - o.base_clip.clamp(0.0, 0.5))?; + m.black[ch] = q(ch, 1.0 - o.black_clip.clamp(0.0, 0.5))?; + m.white[ch] = q(ch, o.white_clip.clamp(0.0, 0.5))?; + *med = q(ch, 0.5)?; + if m.white[ch] >= m.black[ch] { + return Err("the scan has no tonal range between black and white (a flat image, or the border leaves too little)".into()); + } + } + if o.neutral { + m.balance = neutral_balance(&m, median); + } + Ok(m) +} + +/// Per-channel gammas that bring each channel's median positive to the geometric mean of the +/// three: the scene averages grey, black and white stay put. +fn neutral_balance(m: &Measurement, median: [f32; 3]) -> [f32; 3] { + let Some(a) = m.analysis(None) else { return [1.0; 3] }; + let c = Converter::new(&a, &Params { tone: Tone::Linear, ..Params::default() }, Encoding::Linear, None); + let out = c.convert(median).map(|v| v.clamp(1e-3, 0.999)); + let target = (libm::logf(out[0]) + libm::logf(out[1]) + libm::logf(out[2])) / 3.0; + out.map(|v| { + let b = target / libm::logf(v); + if b.is_finite() { b.clamp(0.4, 2.5) } else { 1.0 } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{RANGE_STOPS, film}; + + const BASE: [f32; 3] = [0.6, 0.35, 0.15]; + + /// A synthetic negative: a log ramp of scene exposures across the width, with a cast in the + /// blue mid-tones the neutral balance should take out, framed by a border of film base. + fn scan(w: usize, h: usize) -> Vec<[f32; 3]> { + let mut px = Vec::with_capacity(w * h); + for y in 0..h { + for x in 0..w { + let inside = x >= w / 10 && x < w - w / 10 && y >= h / 10 && y < h - h / 10; + let s = x as f32 / (w - 1) as f32; + let e = libm::exp2f(s * RANGE_STOPS); + px.push(if inside { + [film::transmittance(e, BASE[0]), film::transmittance(e, BASE[1]), film::transmittance(e, BASE[2]) * 0.8] + } else { + BASE + }); + } + } + px + } + + #[test] + fn measures_base_levels_and_balance_of_a_synthetic_negative() { + let (w, h) = (300, 200); + let px = scan(w, h); + let m = measure(&px, w, h, &MeasureOptions { border: 0.12, ..MeasureOptions::default() }).unwrap(); + for ch in 0..3 { + assert!(m.white[ch] < m.black[ch] && m.black[ch] <= m.base[ch] * 1.01, "{m:?}"); + } + assert!(m.balance[2] != 1.0, "the blue cast gets a balance: {m:?}"); + // With the border in the measured area, the base is the border. + let framed = measure(&px, w, h, &MeasureOptions { border: 0.0, ..MeasureOptions::default() }).unwrap(); + for ch in 0..3 { + assert!((framed.base[ch] - BASE[ch]).abs() < 0.01, "{framed:?}"); + } + let a = m.analysis(None).unwrap(); + assert!(a.white.iter().zip(a.black).all(|(w, b)| *w > b)); + // A picked base is black; the measured white point stays. + let picked = m.analysis(Some(BASE)).unwrap(); + assert_eq!(picked.base, BASE); + assert_eq!(picked.black, [1.0; 3]); + } + + #[test] + fn bad_input_is_an_error_not_a_panic() { + assert!(measure(&[], 0, 0, &MeasureOptions::default()).is_err()); + assert!(measure(&[[0.5; 3]; 4], 10, 10, &MeasureOptions::default()).is_err(), "short buffer"); + assert!(measure(&[[0.5; 3]; 100], 10, 10, &MeasureOptions::default()).is_err(), "flat image"); + let px = scan(40, 30); + assert!(measure(&px, 40, 30, &MeasureOptions { border: f32::NAN, ..MeasureOptions::default() }).is_ok()); + // One sample has no range: an error too. + assert!(measure(&px, 40, 30, &MeasureOptions { max_samples: 0, ..MeasureOptions::default() }).is_err()); + let nan = vec![[f32::NAN, f32::INFINITY, -1.0]; 100]; + assert!(measure(&nan, 10, 10, &MeasureOptions::default()).is_err()); + } +} diff --git a/crates/film/src/preset.rs b/crates/film/src/preset.rs new file mode 100644 index 0000000000..740ec25824 --- /dev/null +++ b/crates/film/src/preset.rs @@ -0,0 +1,416 @@ +//! Presets: the character of a film stock as a conversion recipe. +//! +//! A preset carries what belongs to the *film*: the contrast of each colour layer (density per +//! log-exposure), the typical colour of its mask, a tone profile, a colour model, saturation, +//! a warmth offset and a touch of toning. It does not carry what belongs to the *scan* (the +//! actual film base and the black and white points), which is measured; the preset's mask +//! colour is only the fallback when nothing was measured. +//! +//! The recipes are starting points derived from the stocks' published characteristic curves +//! and the way they are known to render, named after the stock they take after. Names are +//! lower-case words and numbers, which a host that labels a choice from its value renders +//! capitalised (`portra 400` → "Portra 400"); [`Preset::parse`] accepts any spelling of them. + +use crate::{Look, NEGATIVE_GAMMA, Params, Tone, color, finite}; + +/// How much more density each channel of a scan of colour negative film spans than the layer's +/// own gamma gives, red, green, blue: a scan's blue runs far denser than its red (the orange +/// mask, the dyes' side absorptions, the scanner's or camera's channel sensitivities). Only the +/// levels derived from a base alone use it ([`Preset::scan_gamma`]); a measurement makes it +/// irrelevant. +/// +/// Provisional: fitted on three frames of one Kodak Ektar 100 strip photographed against +/// daylight, matching the colour of each frame's mean to the photographer's own positive (the +/// best fit per preset ran 0.62 to 0.78 for red and 1.30 to 1.52 for blue). Without it, those +/// frames came out strongly blue. More scans are needed to settle it. +pub const SCAN_SPREAD: [f32; 3] = [0.7, 1.0, 1.4]; + +/// One recipe. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Preset { + /// The parameter value and its menu entry, as shown ([`Preset::parse`] takes any spelling). + pub name: &'static str, + /// Density per log-exposure of the red, green and blue layers (as the film's data gives + /// it; a scan spreads them further, [`SCAN_SPREAD`]). + pub gamma: [f32; 3], + /// Typical mask colour of an unexposed, normally scanned frame, sRGB-encoded 0..1: the + /// fallback film base. + pub base: [f32; 3], + pub tone: Tone, + pub look: Look, + pub presat: f32, + /// Offsets added to the sliders. + pub contrast: f32, + pub temp: f32, + pub tint: f32, + pub saturation: f32, + /// Highlight and shadow toning (red, green, blue balance, −50..50) at the default range. + pub highs: [f32; 3], + pub lows: [f32; 3], + pub monochrome: bool, +} + +/// Every preset, in menu order. The first is the default. +/// +/// The film names are the trademarks of their makers (Eastman Kodak, FUJIFILM, CineStill), used +/// to say which stock a recipe takes after; the recipes are this project's own, built from the +/// stocks' published characteristics and the way they are known to render, and are starting +/// points to tune against your own scans. +pub const PRESETS: [Preset; 12] = [ + // A neutral lab scan: even layer contrast, neutral colour, the lab tone profile. + Preset { + name: "Standard", + gamma: [NEGATIVE_GAMMA; 3], + base: [0.80, 0.52, 0.36], + tone: Tone::LabStandard, + look: Look::Neutral, + presat: 3.0, + contrast: 0.0, + temp: 0.0, + tint: 0.0, + saturation: 0.0, + highs: [0.0; 3], + lows: [0.0; 3], + monochrome: false, + }, + // Kodak Portra 160: the gentlest of the family. Low contrast, pastel saturation, warm + // natural skin, soft warm highlights. + Preset { + name: "Portra 160", + gamma: [0.56, 0.58, 0.60], + base: [0.79, 0.53, 0.37], + tone: Tone::LabSoft, + look: Look::Neutral, + presat: 2.4, + contrast: -4.0, + temp: 4.0, + tint: 1.0, + saturation: -8.0, + highs: [3.0, 1.0, -4.0], + lows: [0.0, 0.0, 1.0], + monochrome: false, + }, + // Kodak Portra 400: the portrait standard. Moderate contrast, warm natural skin, muted but + // full colour, warm highlights, a touch of cool in the shadows. + Preset { + name: "Portra 400", + gamma: [0.58, 0.60, 0.63], + base: [0.79, 0.53, 0.37], + tone: Tone::LabSoft, + look: Look::Neutral, + presat: 2.8, + contrast: 0.0, + temp: 9.0, + tint: -2.0, + saturation: -2.0, + highs: [5.0, 1.0, -6.0], + lows: [-1.0, 1.0, 0.0], + monochrome: false, + }, + // Kodak Ektar 100: the saturated one. Steep layers, strong separation, vivid reds and + // blues, clean neutrals, contrast to match. + Preset { + name: "Ektar 100", + gamma: [0.63, 0.65, 0.69], + base: [0.78, 0.50, 0.33], + tone: Tone::LabStandard, + look: Look::Neutral, + presat: 4.0, + contrast: 10.0, + temp: 3.0, + tint: 1.0, + saturation: 14.0, + highs: [2.0, 0.0, -2.0], + lows: [0.0, 0.0, -3.0], + monochrome: false, + }, + // Kodak Gold 200: golden. Warm yellow highlights, warm neutrals, saturated reds and + // yellows, the minilab rendering. + Preset { + name: "Gold 200", + gamma: [0.60, 0.62, 0.66], + base: [0.82, 0.54, 0.35], + tone: Tone::LabStandard, + look: Look::LabWarm, + presat: 3.2, + contrast: 2.0, + temp: 12.0, + tint: 3.0, + saturation: 6.0, + highs: [8.0, 3.0, -10.0], + lows: [3.0, 0.0, -3.0], + monochrome: false, + }, + // Kodak ColorPlus 200: the everyday stock. Warm like Gold but softer and less saturated, + // warm shadows, a little faded: the look of old snapshots. + Preset { + name: "ColorPlus 200", + gamma: [0.58, 0.60, 0.63], + base: [0.83, 0.55, 0.36], + tone: Tone::LabSoft, + look: Look::LabWarm, + presat: 2.8, + contrast: -2.0, + temp: 10.0, + tint: 2.0, + saturation: -2.0, + highs: [6.0, 2.0, -8.0], + lows: [4.0, 1.0, -2.0], + monochrome: false, + }, + // Kodak UltraMax 400: the punchy consumer stock. Saturated, contrasty, warm, strong blues. + Preset { + name: "UltraMax 400", + gamma: [0.61, 0.63, 0.67], + base: [0.81, 0.53, 0.35], + tone: Tone::LabStandard, + look: Look::LabWarm, + presat: 3.5, + contrast: 6.0, + temp: 6.0, + tint: 2.0, + saturation: 10.0, + highs: [4.0, 2.0, -6.0], + lows: [1.0, 0.0, -1.0], + monochrome: false, + }, + // Fujifilm Superia X-TRA 400: Fuji's greens. Cooler than Kodak, a steeper green layer, + // vivid, teal shadows, a touch of magenta in skin. + Preset { + name: "Superia 400", + gamma: [0.60, 0.64, 0.66], + base: [0.76, 0.50, 0.34], + tone: Tone::LabStandard, + look: Look::LabCool, + presat: 3.4, + contrast: 6.0, + temp: -5.0, + tint: -5.0, + saturation: 8.0, + highs: [0.0, 3.0, -2.0], + lows: [-3.0, 2.0, 5.0], + monochrome: false, + }, + // Fujifilm C200: clean and cool. Soft contrast, restrained saturation, cool neutrals, a + // green-cyan lean in the shadows. + Preset { + name: "C200", + gamma: [0.58, 0.61, 0.63], + base: [0.77, 0.51, 0.35], + tone: Tone::LabSoft, + look: Look::LabCool, + presat: 2.8, + contrast: 0.0, + temp: -4.0, + tint: -3.0, + saturation: -4.0, + highs: [0.0, 2.0, 0.0], + lows: [-2.0, 2.0, 3.0], + monochrome: false, + }, + // Fujifilm Pro 400H: the pastel wedding stock. Flat layers, airy highlights, mint greens, + // cyan shadows, soft skin; made to be overexposed. + Preset { + name: "Pro 400H", + gamma: [0.55, 0.58, 0.60], + base: [0.78, 0.52, 0.36], + tone: Tone::LabSoft, + look: Look::Clean, + presat: 2.3, + contrast: -8.0, + temp: -3.0, + tint: -6.0, + saturation: -6.0, + highs: [-2.0, 2.0, 2.0], + lows: [-4.0, 3.0, 5.0], + monochrome: false, + }, + // CineStill 800T: tungsten cine stock shot in daylight. Low, cinematic contrast, muted + // colour, teal-blue shadows against warm orange highlights. (The halation it is known for + // is not a colour and is not modelled.) + Preset { + name: "CineStill 800", + gamma: [0.55, 0.57, 0.60], + base: [0.80, 0.52, 0.36], + tone: Tone::Cinematic, + look: Look::Clean, + presat: 2.6, + contrast: 0.0, + temp: -3.0, + tint: 2.0, + saturation: -8.0, + highs: [10.0, 2.0, -8.0], + lows: [-8.0, 0.0, 12.0], + monochrome: false, + }, + // Black-and-white: a paper-like straight line with some contrast, no colour. + Preset { + name: "Monochrome", + gamma: [0.65; 3], + base: [0.74; 3], + tone: Tone::Linear, + look: Look::Neutral, + presat: 3.0, + contrast: 15.0, + temp: 0.0, + tint: 0.0, + saturation: 0.0, + highs: [0.0; 3], + lows: [0.0; 3], + monochrome: true, + }, +]; + +/// The sliders a user sets on top of a preset. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Sliders { + pub exposure: f32, + pub brightness: f32, + pub contrast: f32, + pub temp: f32, + pub tint: f32, + pub saturation: f32, +} + +/// A preset name reduced to what [`Preset::parse`] compares: its letters and digits, lower-case. +fn name_key(s: &str) -> impl Iterator + '_ { + s.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()) +} + +impl Preset { + /// The preset with this name, spelled any way: case, spaces, hyphens and underscores do not + /// count (`portra 400`, `portra400` and `PORTRA_400` are the same preset). + pub fn parse(name: &str) -> Option<&'static Preset> { + PRESETS.iter().find(|p| name_key(p.name).eq(name_key(name))) + } + + pub fn default_preset() -> &'static Preset { + &PRESETS[0] + } + + /// The fallback film base in linear light. + pub fn base_linear(&self) -> [f32; 3] { + [color::srgb_decode(self.base[0]), color::srgb_decode(self.base[1]), color::srgb_decode(self.base[2])] + } + + /// Density per log-exposure of each channel as a scan sees it: [`Preset::gamma`] spread by + /// [`SCAN_SPREAD`] for colour film, as it is for black-and-white (no mask, one dye). + pub fn scan_gamma(&self) -> [f32; 3] { + if self.monochrome { + return self.gamma; + } + [self.gamma[0] * SCAN_SPREAD[0], self.gamma[1] * SCAN_SPREAD[1], self.gamma[2] * SCAN_SPREAD[2]] + } + + /// The conversion parameters for this preset with `s` on top. + pub fn params(&self, s: &Sliders) -> Params { + let d = Params::default(); + Params { + exposure: finite(s.exposure, 0.0), + brightness: finite(s.brightness, 0.0), + contrast: self.contrast + finite(s.contrast, 0.0), + tone: self.tone, + temp: self.temp + finite(s.temp, 0.0), + tint: self.tint + finite(s.tint, 0.0), + presat: self.presat, + saturation: self.saturation + finite(s.saturation, 0.0), + look: self.look, + highs_red: self.highs[0], + highs_green: self.highs[1], + highs_blue: self.highs[2], + lows_red: self.lows[0], + lows_green: self.lows[1], + lows_blue: self.lows[2], + monochrome: self.monochrome, + film_gamma: self.scan_gamma(), + ..d + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Analysis, Converter, Encoding, RANGE_STOPS, film}; + + #[test] + fn presets_parse_and_the_first_is_standard() { + assert_eq!(Preset::default_preset().name, "Standard"); + for p in &PRESETS { + assert_eq!(Preset::parse(p.name).map(|q| q.name), Some(p.name)); + assert!(p.gamma.iter().all(|g| (0.4..=0.8).contains(g)), "{}", p.name); + assert!(p.base.iter().all(|b| (0.3..=0.95).contains(b)), "{}", p.name); + } + assert!(Preset::parse("portra").is_none()); + } + + #[test] + fn names_parse_in_any_spelling() { + for (spelling, name) in [ + ("portra 400", "Portra 400"), + ("portra400", "Portra 400"), + ("PORTRA_400", "Portra 400"), + ("pro 400h", "Pro 400H"), + ("CineStill-800", "CineStill 800"), + ] { + assert_eq!(Preset::parse(spelling).map(|p| p.name), Some(name), "{spelling}"); + } + assert!(Preset::parse("kodachrome").is_none() && Preset::parse("").is_none()); + // A host shows a choice with a space exactly as written (PhotoCraft does), so the names + // are the menu's text: capitalised words and numbers, distinct however they are spelled. + for p in &PRESETS { + assert!(p.name.starts_with(|c: char| c.is_ascii_uppercase()), "{}", p.name); + assert!(p.name.chars().all(|c| c.is_ascii_alphanumeric() || c == ' '), "{}", p.name); + assert_eq!(PRESETS.iter().filter(|q| name_key(q.name).eq(name_key(p.name))).count(), 1, "{}", p.name); + } + } + + #[test] + fn every_preset_converts_a_ramp_monotonically_and_finitely() { + let white = libm::exp2f(RANGE_STOPS); + for preset in &PRESETS { + let base = preset.base_linear(); + let p = preset.params(&Sliders::default()); + let c = Converter::new(&Analysis::from_base(base, p.film_gamma), &p, Encoding::Srgb, None); + let mut last = [-1.0f32; 3]; + for i in 0..=40 { + let s = i as f32 / 40.0; + let e = 1.0 + s * (white - 1.0); + let scan = [ + color::srgb_encode(film::transmittance(e, base[0])), + color::srgb_encode(film::transmittance(e, base[1])), + color::srgb_encode(film::transmittance(e, base[2])), + ]; + let out = c.convert(scan); + assert!(out.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{}: {out:?}", preset.name); + let y = color::luminance(out); + assert!(y >= color::luminance(last) - 1e-3, "{} not monotonic at {s}: {out:?} after {last:?}", preset.name); + if preset.monochrome { + assert!((out[0] - out[1]).abs() < 1e-5 && (out[1] - out[2]).abs() < 1e-5, "{}: {out:?}", preset.name); + } + last = out; + } + assert!(color::luminance(last) > 0.9, "{} reaches white: {last:?}", preset.name); + } + } + + #[test] + fn sliders_add_to_the_preset() { + let golden = Preset::parse("gold 200").unwrap(); + let p = golden.params(&Sliders { temp: 10.0, contrast: -8.0, exposure: f32::NAN, ..Sliders::default() }); + assert_eq!(p.temp, golden.temp + 10.0); + assert_eq!(p.contrast, golden.contrast - 8.0); + assert_eq!(p.exposure, 0.0); + assert_eq!(p.look, Look::LabWarm); + assert_eq!(p.film_gamma, golden.scan_gamma()); + } + + #[test] + fn a_scan_spreads_colour_layers_but_not_black_and_white() { + let portra = Preset::parse("portra 400").unwrap(); + let g = portra.scan_gamma(); + assert!(g[0] < portra.gamma[0] && g[1] == portra.gamma[1] && g[2] > portra.gamma[2], "{g:?}"); + let mono = Preset::parse("monochrome").unwrap(); + assert_eq!(mono.scan_gamma(), mono.gamma); + } +} diff --git a/crates/film/src/tone.rs b/crates/film/src/tone.rs new file mode 100644 index 0000000000..8db6f0bef5 --- /dev/null +++ b/crates/film/src/tone.rs @@ -0,0 +1,331 @@ +//! Tone shaping in display (sRGB-encoded) space: the tone profiles, the tone sliders, and the +//! lab-scanner look of a lifted toe (fade) and a soft shoulder (glow). + +use crate::{Params, finite}; + +/// The tone profiles: three families, as lab-style negative conversion software offers them. +/// +/// - **Linear**: a flat, neutral start, a straight line between the black and white points; +/// `Deep` darkens the mid-tones, `Flat` lifts black and lowers white a little. +/// - **Cinematic**: smooth, low-contrast mid-tones and shadows with strong highlight +/// separation, the look of scanned cine film; `Flat` lifts the toe further, `Rich` adds +/// contrast. +/// - **Lab**: the contrast of a lab scanner, tones close to clipping. `Standard` is the +/// default; the others change the steepness on one side or both. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Tone { + Linear, + LinearDeep, + LinearFlat, + Cinematic, + CinematicFlat, + CinematicRich, + LabSoft, + #[default] + LabStandard, + LabHard, + LabHighlightSoft, + LabHighlightHard, + LabShadowSoft, + LabShadowHard, +} + +/// A profile's shape: logistic steepness on the shadow and highlight sides (0 = straight), +/// a black lift, a white ceiling and a mid-tone gamma. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Profile { + k_lo: f32, + k_hi: f32, + lift: f32, + ceiling: f32, + gamma: f32, +} + +impl Tone { + /// Every profile with its parameter name, in menu order. + pub const ALL: [(Tone, &'static str); 13] = [ + (Tone::Linear, "linear"), + (Tone::LinearDeep, "linear_deep"), + (Tone::LinearFlat, "linear_flat"), + (Tone::Cinematic, "cinematic"), + (Tone::CinematicFlat, "cinematic_flat"), + (Tone::CinematicRich, "cinematic_rich"), + (Tone::LabSoft, "lab_soft"), + (Tone::LabStandard, "lab_standard"), + (Tone::LabHard, "lab_hard"), + (Tone::LabHighlightSoft, "lab_highlight_soft"), + (Tone::LabHighlightHard, "lab_highlight_hard"), + (Tone::LabShadowSoft, "lab_shadow_soft"), + (Tone::LabShadowHard, "lab_shadow_hard"), + ]; + + pub fn parse(s: &str) -> Option { + Self::ALL.iter().find(|(_, name)| *name == s).map(|(t, _)| *t) + } + + pub fn name(self) -> &'static str { + Self::ALL.iter().find(|(t, _)| *t == self).map_or("linear", |(_, name)| name) + } + + /// The profile's mid-tone gamma (> 1 darkens), applied with brightness by the converter. + pub fn gamma(self) -> f32 { + self.profile().gamma + } + + fn profile(self) -> Profile { + let p = |k_lo, k_hi, lift, ceiling, gamma| Profile { k_lo, k_hi, lift, ceiling, gamma }; + match self { + Self::Linear => p(0.0, 0.0, 0.0, 1.0, 1.0), + Self::LinearDeep => p(0.0, 0.0, 0.0, 1.0, 1.15), + Self::LinearFlat => p(0.0, 0.0, 0.04, 0.97, 1.0), + Self::Cinematic => p(1.5, 3.5, 0.03, 1.0, 0.95), + Self::CinematicFlat => p(1.0, 2.5, 0.06, 0.98, 0.95), + Self::CinematicRich => p(2.5, 4.5, 0.0, 1.0, 1.05), + Self::LabSoft => p(2.5, 2.5, 0.0, 1.0, 1.0), + Self::LabStandard => p(4.0, 4.0, 0.0, 1.0, 1.0), + Self::LabHard => p(6.0, 6.0, 0.0, 1.0, 1.0), + Self::LabHighlightSoft => p(4.0, 2.0, 0.0, 1.0, 1.0), + Self::LabHighlightHard => p(4.0, 6.5, 0.0, 1.0, 1.0), + Self::LabShadowSoft => p(2.0, 4.0, 0.0, 1.0, 1.0), + Self::LabShadowHard => p(6.5, 4.0, 0.0, 1.0, 1.0), + } + } +} + +/// Steepness the contrast slider adds at ±50. +const CONTRAST_STEEPNESS: f32 = 4.0; +/// Steepest logistic allowed. +const MAX_STEEPNESS: f32 = 10.0; + +/// The folded tone curve of one conversion. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Curve { + /// Logistic steepness on the shadow and highlight sides; both ≤ 0 means "towards flat" + /// by `−k / MAX_STEEPNESS`. + k_lo: f32, + k_hi: f32, + lights: f32, + darks: f32, + /// Black lift (positive fade and the profile's lift) and shadow expansion (negative fade). + lift: f32, + expand_lows: f32, + ceiling: f32, + /// Highlight compression (positive glow) and expansion (negative glow). + glow: f32, + expand_highs: f32, + soft_highs: f32, + soft_lows: f32, +} + +impl Curve { + pub fn new(p: &Params) -> Self { + let prof = p.tone.profile(); + let contrast = finite(p.contrast, 0.0).clamp(-50.0, 50.0) / 50.0 * CONTRAST_STEEPNESS; + let fade = finite(p.fade, 0.0).clamp(-100.0, 100.0) / 100.0; + let glow = finite(p.glow, 0.0).clamp(-100.0, 100.0) / 100.0; + Self { + k_lo: (prof.k_lo + contrast).clamp(-MAX_STEEPNESS, MAX_STEEPNESS), + k_hi: (prof.k_hi + contrast).clamp(-MAX_STEEPNESS, MAX_STEEPNESS), + lights: finite(p.lights, 0.0).clamp(-50.0, 50.0) / 100.0, + darks: finite(p.darks, 0.0).clamp(-50.0, 50.0) / 100.0, + lift: prof.lift + fade.max(0.0) * 0.2, + expand_lows: (-fade).max(0.0) * 2.0, + ceiling: prof.ceiling, + glow: glow.max(0.0) * 2.0, + expand_highs: (-glow).max(0.0) * 2.0, + soft_highs: finite(p.soft_highs, 0.0).clamp(0.0, 100.0) / 100.0 * 2.0, + soft_lows: finite(p.soft_lows, 0.0).clamp(0.0, 100.0) / 100.0 * 2.0, + } + } + + /// True when the curve changes nothing, so a host can skip the encode / decode around it. + pub fn is_identity(&self) -> bool { + self.k_lo.abs() <= 1e-6 + && self.k_hi.abs() <= 1e-6 + && self.lights == 0.0 + && self.darks == 0.0 + && self.lift <= 0.0 + && self.expand_lows <= 0.0 + && self.ceiling >= 1.0 + && self.glow <= 0.0 + && self.expand_highs <= 0.0 + && self.soft_highs <= 0.0 + && self.soft_lows <= 0.0 + } + + /// `x` (sRGB-encoded, 0..1) through the curve, 0..1. + pub fn apply(&self, x: f32) -> f32 { + let mut y = finite(x, 0.0).clamp(0.0, 1.0); + // The contrast S: one symmetric logistic per side (each pinned at 0, ½ and 1), blended + // across the middle so the join is smooth and mid-grey stays where it is. + if (self.k_lo - self.k_hi).abs() <= 1e-6 { + y = s_curve(y, self.k_lo); + } else { + let w = smoothstep((y - 0.3) / 0.4); + y = s_curve(y, self.k_lo) * (1.0 - w) + s_curve(y, self.k_hi) * w; + } + // Bumps centred on the shadows (⅓) and highlights (⅔), zero at both ends. + y += self.darks * 3.0 * y * (1.0 - y) * (1.0 - y); + y += self.lights * 3.0 * y * y * (1.0 - y); + y = y.clamp(0.0, 1.0); + // Shadow and highlight tonality: expansion steepens an end, compression softens it. + if self.expand_lows > 0.0 { + y = remap(y, 0.0, 0.5, |t| compress_top(t, self.expand_lows)); + } + if self.expand_highs > 0.0 { + y = remap(y, 0.5, 1.0, |t| compress_bottom(t, self.expand_highs)); + } + if self.glow > 0.0 { + y = remap(y, 0.5, 1.0, |t| compress_top(t, self.glow)); + } + if self.soft_lows > 0.0 { + y = remap(y, 0.0, 0.3, |t| compress_bottom(t, self.soft_lows)); + } + if self.soft_highs > 0.0 { + y = remap(y, 0.7, 1.0, |t| compress_top(t, self.soft_highs)); + } + // Lift and ceiling last, so black and white land where the profile and fade say. + if self.lift > 0.0 || self.ceiling < 1.0 { + y = self.lift + y * (self.ceiling - self.lift); + } + y.clamp(0.0, 1.0) + } +} + +fn sigmoid(x: f32) -> f32 { + 1.0 / (1.0 + libm::expf(-x)) +} + +/// A symmetric contrast curve through (0, 0), (½, ½) and (1, 1): a logistic of steepness `k` +/// when `k > 0`, a pull towards flat when `k < 0`, identity at 0. +fn s_curve(y: f32, k: f32) -> f32 { + if k > 1e-6 { + let half = sigmoid(k * 0.5) - 0.5; + (0.5 + 0.5 * (sigmoid(k * (y - 0.5)) - 0.5) / half).clamp(0.0, 1.0) + } else if k < -1e-6 { + y + (0.5 - y) * (-k / MAX_STEEPNESS) + } else { + y + } +} + +fn smoothstep(x: f32) -> f32 { + let x = x.clamp(0.0, 1.0); + x * x * (3.0 - 2.0 * x) +} + +/// `t` in 0..1 with its slope reduced towards 1 (Reinhard with the white point kept at 1). +fn compress_top(t: f32, a: f32) -> f32 { + t * (1.0 + a) / (1.0 + a * t) +} + +/// `t` in 0..1 with its slope reduced towards 0. +fn compress_bottom(t: f32, a: f32) -> f32 { + 1.0 - compress_top(1.0 - t, a) +} + +/// `y` with `f` applied to the part of it inside `lo..hi` (unchanged outside). +fn remap(y: f32, lo: f32, hi: f32, f: impl Fn(f32) -> f32) -> f32 { + if y <= lo || y >= hi { + return y; + } + lo + f((y - lo) / (hi - lo)) * (hi - lo) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn curve(p: Params) -> Curve { + Curve::new(&p) + } + + fn linear() -> Params { + Params { tone: Tone::Linear, ..Params::default() } + } + + #[test] + fn names_round_trip_and_default_is_lab_standard() { + for (tone, name) in Tone::ALL { + assert_eq!(Tone::parse(name), Some(tone)); + assert_eq!(tone.name(), name); + } + assert_eq!(Tone::parse("lab"), None); + assert_eq!(Tone::default(), Tone::LabStandard); + assert_eq!(Params::default().tone, Tone::LabStandard); + } + + #[test] + fn linear_profile_is_identity_and_every_profile_is_monotonic_and_pinned() { + let c = curve(linear()); + assert!(c.is_identity()); + for x in [0.0, 0.25, 0.5, 0.75, 1.0] { + assert!((c.apply(x) - x).abs() < 1e-6); + } + for (tone, name) in Tone::ALL { + let c = curve(Params { tone, ..Params::default() }); + let mut last = -1.0; + for i in 0..=200 { + let y = c.apply(i as f32 / 200.0); + assert!(y >= last - 1e-5, "{name} not monotonic at {i}: {y} < {last}"); + last = y; + } + let lo = c.apply(0.0); + let hi = c.apply(1.0); + assert!((0.0..=0.07).contains(&lo) && (0.96..=1.0).contains(&hi), "{name}: ends {lo} {hi}"); + if tone != Tone::Linear && tone != Tone::LinearDeep { + assert!(!c.is_identity(), "{name}"); + } + } + } + + #[test] + fn lab_profiles_order_by_steepness_on_each_side() { + let at = |tone, x: f32| curve(Params { tone, ..Params::default() }).apply(x); + assert!(at(Tone::LabHard, 0.25) < at(Tone::LabStandard, 0.25) && at(Tone::LabStandard, 0.25) < at(Tone::LabSoft, 0.25)); + assert!(at(Tone::LabHard, 0.75) > at(Tone::LabStandard, 0.75) && at(Tone::LabStandard, 0.75) > at(Tone::LabSoft, 0.75)); + // Highlight-side variants leave the shadows where Standard has them, and mid-grey stays put. + assert!((at(Tone::LabHighlightHard, 0.15) - at(Tone::LabStandard, 0.15)).abs() < 1e-5); + assert!((at(Tone::LabHighlightSoft, 0.5) - 0.5).abs() < 1e-5 && (at(Tone::LabShadowHard, 0.5) - 0.5).abs() < 1e-5); + assert!(at(Tone::LabHighlightHard, 0.85) > at(Tone::LabStandard, 0.85)); + assert!(at(Tone::LabHighlightSoft, 0.85) < at(Tone::LabStandard, 0.85)); + assert!(at(Tone::LabShadowHard, 0.15) < at(Tone::LabStandard, 0.15)); + assert!(at(Tone::LabShadowSoft, 0.15) > at(Tone::LabStandard, 0.15)); + // Cinematic: flatter shadows than Lab Standard, a lifted toe, separated highlights. + assert!(at(Tone::Cinematic, 0.0) > 0.0 && at(Tone::Cinematic, 0.2) > at(Tone::LabStandard, 0.2)); + assert!(Tone::LinearDeep.gamma() > 1.0 && Tone::Cinematic.gamma() < 1.0 && Tone::LabStandard.gamma() == 1.0); + assert!(at(Tone::LinearFlat, 0.0) > 0.0 && at(Tone::LinearFlat, 1.0) < 1.0); + } + + #[test] + fn contrast_slider_adds_and_removes_steepness() { + let more = curve(Params { contrast: 30.0, ..Params::default() }).apply(0.25); + let standard = curve(Params::default()).apply(0.25); + let less = curve(Params { contrast: -50.0, ..linear() }).apply(0.25); + assert!(more < standard, "{more} {standard}"); + assert!(less > 0.25, "negative contrast on a straight line flattens: {less}"); + assert!(curve(Params { contrast: -50.0, ..linear() }).apply(0.0) > 0.0); + } + + #[test] + fn lights_darks_fade_glow_and_soft_ends_act_where_they_should() { + let lin = linear(); + let darks = curve(Params { darks: 50.0, ..lin }); + assert!(darks.apply(0.3) > 0.3 && (darks.apply(0.3) - 0.3) > (darks.apply(0.9) - 0.9), "darks lift the low end most"); + let lights = curve(Params { lights: -50.0, ..lin }); + assert!(lights.apply(0.7) < 0.7 && (0.7 - lights.apply(0.7)) > (0.1 - lights.apply(0.1)), "lights act on the high end"); + let fade = curve(Params { fade: 100.0, ..lin }); + assert!((fade.apply(0.0) - 0.2).abs() < 1e-6 && (fade.apply(1.0) - 1.0).abs() < 1e-6); + let unfade = curve(Params { fade: -100.0, ..lin }); + assert!(unfade.apply(0.1) > 0.1 && unfade.apply(0.0) == 0.0 && (unfade.apply(0.5) - 0.5).abs() < 1e-6, "negative fade steepens the shadows"); + let glow = curve(Params { glow: 100.0, ..lin }); + assert!(glow.apply(0.75) > 0.75 && (glow.apply(1.0) - 1.0).abs() < 1e-6 && (glow.apply(0.5) - 0.5).abs() < 1e-6); + assert!(glow.apply(0.99) - glow.apply(0.9) < 0.09, "the shoulder compresses the top"); + let unglow = curve(Params { glow: -100.0, ..lin }); + assert!(unglow.apply(0.75) < 0.75 && (unglow.apply(1.0) - 1.0).abs() < 1e-6, "negative glow expands the highlights"); + let soft = curve(Params { soft_highs: 100.0, soft_lows: 100.0, ..lin }); + assert!((soft.apply(0.5) - 0.5).abs() < 1e-6 && soft.apply(0.85) > 0.85 && soft.apply(0.15) < 0.15); + assert!(soft.apply(0.02) < 0.02 * 0.6 && (1.0 - soft.apply(0.98)) < 0.02 * 0.6, "flatter at both ends"); + assert!(curve(Params { fade: f32::NAN, glow: f32::INFINITY, darks: -1e9, ..lin }).apply(f32::NAN).is_finite()); + } +} diff --git a/crates/gpu/src/backend.rs b/crates/gpu/src/backend.rs index 8d8456a265..741475a83a 100644 --- a/crates/gpu/src/backend.rs +++ b/crates/gpu/src/backend.rs @@ -12,6 +12,9 @@ //! (the platform default), or `off` (no GPU compute; the window still needs one backend and //! keeps the platform default); //! - else `WGPU_BACKEND` (wgpu's own variable, same names) for both the window and compute. +//! - `LIGHTCRAFT_GPU_ADAPTER` = (part of) a graphics card's name, any case (`4070`): the card for +//! the compute devices — the render device, the denoise network's, the face detector's +//! ([`pick_adapter`]). The window stays on the card that drives the screen. //! //! Backends this build doesn't contain (e.g. `gl`: the GL backend isn't compiled in) are ignored //! with a warning and the platform default is used. @@ -166,6 +169,173 @@ pub fn instance_flags_from_env(flags: wgpu::InstanceFlags) -> wgpu::InstanceFlag instance_flags(flags, std::env::var("WGPU_VALIDATION_INDIRECT_CALL").ok().as_deref()) } +/// The graphics card `LIGHTCRAFT_GPU_ADAPTER` asks for: (part of) its name, trimmed and in lower +/// case; `None` when it is unset or blank. +pub fn wanted_adapter() -> Option { + wanted_adapter_from(std::env::var("LIGHTCRAFT_GPU_ADAPTER").ok().as_deref()) +} + +/// [`wanted_adapter`] from the variable's value `env`. +pub fn wanted_adapter_from(env: Option<&str>) -> Option { + env.map(|s| s.trim().to_lowercase()).filter(|s| !s.is_empty()) +} + +/// Whether the adapter called `name` is the one `wanted` asks for: `wanted` is part of its name, +/// ignoring case (`4070` matches "NVIDIA GeForce RTX 4070 SUPER"). +pub fn adapter_name_matches(wanted: &str, name: &str) -> bool { + let wanted = wanted.trim().to_lowercase(); + !wanted.is_empty() && name.to_lowercase().contains(&wanted) +} + +/// One adapter as [`choose_named_adapter`] sees it, in wgpu's order. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Candidate<'a> { + pub name: &'a str, + /// Order among several matching cards, lower first ([`kind_rank`]). + pub rank: u8, + /// A software renderer (WARP, llvmpipe): never picked, the CPU pipeline is faster. + pub software: bool, +} + +impl<'a> Candidate<'a> { + /// A candidate from an adapter's name and kind. + pub fn of(name: &'a str, kind: wgpu::DeviceType) -> Candidate<'a> { + Candidate { name, rank: kind_rank(kind), software: kind == wgpu::DeviceType::Cpu } + } +} + +/// The order among cards that all match: dedicated, built-in, virtual, other, software. +pub fn kind_rank(kind: wgpu::DeviceType) -> u8 { + match kind { + wgpu::DeviceType::DiscreteGpu => 0, + wgpu::DeviceType::IntegratedGpu => 1, + wgpu::DeviceType::VirtualGpu => 2, + wgpu::DeviceType::Other => 3, + wgpu::DeviceType::Cpu => 4, + } +} + +/// What a `LIGHTCRAFT_GPU_ADAPTER` name picks among the candidates ([`choose_named_adapter`]). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct NamedChoice { + /// The card used (the first of `matches`), `None`: the default choice. + pub index: Option, + /// Every hardware card whose name matches, in the defined order. + pub matches: Vec, + /// Software renderers whose name matches (never used). + pub software: Vec, +} + +/// Which of `candidates` (in wgpu's order) `wanted` picks: of the hardware cards whose name +/// contains it (any case), the one whose whole name it is, then dedicated before built-in before +/// virtual cards ([`kind_rank`]), then wgpu's order. Software renderers are never picked. +pub fn choose_named_adapter(wanted: &str, candidates: &[Candidate<'_>]) -> NamedChoice { + let w = wanted.trim().to_lowercase(); + let hits = || candidates.iter().enumerate().filter(|(_, c)| adapter_name_matches(&w, c.name)); + let software: Vec = hits().filter(|(_, c)| c.software).map(|(i, _)| i).collect(); + let mut ranked: Vec<(bool, u8, usize)> = + hits().filter(|(_, c)| !c.software).map(|(i, c)| (c.name.trim().to_lowercase() != w, c.rank, i)).collect(); + // (the index last: equal ones keep wgpu's order) + ranked.sort_unstable(); + let matches: Vec = ranked.into_iter().map(|(_, _, i)| i).collect(); + NamedChoice { index: matches.first().copied(), matches, software } +} + +/// The log line for `choice` (warning: `true`): which card the name picked and why, or why none. +pub fn named_choice_note(wanted: &str, choice: &NamedChoice, candidates: &[Candidate<'_>]) -> (bool, String) { + let name = |i: &usize| candidates.get(*i).map_or("?", |c| c.name); + let list = |v: &[usize]| v.iter().map(name).collect::>().join(", "); + match (choice.index, choice.matches.len()) { + (Some(i), 1) => (false, format!("gpu: LIGHTCRAFT_GPU_ADAPTER={wanted}: using {}", name(&i))), + (Some(i), n) => ( + false, + format!( + "gpu: LIGHTCRAFT_GPU_ADAPTER={wanted} matches {n} graphics cards ({}): using {} (a card's whole name first, then dedicated before built-in cards, then the system's order); give more of the name to pick another", + list(&choice.matches), + name(&i) + ), + ), + (None, _) if !choice.software.is_empty() => ( + true, + format!( + "gpu: LIGHTCRAFT_GPU_ADAPTER={wanted} names only a software renderer ({}), never used: the processor is faster; using the default choice", + list(&choice.software) + ), + ), + (None, _) => { + let all: Vec<&str> = candidates.iter().map(|c| c.name).collect(); + (true, format!("gpu: LIGHTCRAFT_GPU_ADAPTER={wanted} names none of the graphics cards ({}); using the default choice", all.join(", "))) + } + } +} + +/// Lines already logged by [`log_once`] (each device that picks a card asks again). +static LOGGED: Mutex> = Mutex::new(Vec::new()); + +/// Log `line` (as a warning when `warn`) the first time only; whether it was logged now. +pub fn log_once(warn: bool, line: &str) -> bool { + let mut seen = LOGGED.lock().unwrap_or_else(|e| e.into_inner()); + if seen.iter().any(|l| l == line) { + return false; + } + // (a handful of distinct lines in a run; the cap only bounds a pathological caller) + if seen.len() < 64 { + seen.push(line.to_string()); + } + if warn { + log::warn!("{line}"); + } else { + log::info!("{line}"); + } + true +} + +/// Which of `adapters` (name and kind, in wgpu's order) `wanted` picks ([`choose_named_adapter`]). +pub fn find_named_adapter<'a>(wanted: &str, adapters: impl IntoIterator) -> Option { + let candidates: Vec> = adapters.into_iter().map(|(n, k)| Candidate::of(n, k)).collect(); + choose_named_adapter(wanted, &candidates).index +} + +/// The adapter for a compute device (the render device, the denoise network's, the face detector's) +/// on `instance` with `backends`: the card `LIGHTCRAFT_GPU_ADAPTER` names, else the +/// high-performance one. A name that matches no card is logged (once) and the high-performance one +/// is used; never a panic. Each device makes its own instance and device on the card, so two +/// devices never share a buffer, pipeline or queue. +pub fn pick_adapter(instance: &wgpu::Instance, backends: Backends) -> Result { + pick_adapter_named(instance, backends, wanted_adapter().as_deref()) +} + +/// [`pick_adapter`] for an explicit `wanted` name (part of it, any case) instead of the variable's. +pub fn pick_adapter_named(instance: &wgpu::Instance, backends: Backends, wanted: Option<&str>) -> Result { + if let Some(w) = wanted { + let all = pollster::block_on(instance.enumerate_adapters(backends)); + let infos: Vec = all.iter().map(|a| a.get_info()).collect(); + let candidates: Vec> = infos.iter().map(|i| Candidate::of(&i.name, i.device_type)).collect(); + let choice = choose_named_adapter(w, &candidates); + let (warn, line) = named_choice_note(w, &choice, &candidates); + log_once(warn, &line); + if let Some(adapter) = choice.index.and_then(|i| all.into_iter().nth(i)) { + return Ok(adapter); + } + } + pollster::block_on( + instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }), + ) + .map_err(|e| format!("no GPU adapter among {backends:?} ({e})")) +} + +/// Whether the render device may share the window's device (adapter `window_adapter`): yes unless +/// `LIGHTCRAFT_GPU_ADAPTER` names another card, which then renders on a device of its own (the +/// window stays on the card that drives the screen; renders come back as pixels). +pub fn may_adopt_window_device(window_adapter: &str) -> bool { + may_adopt_window_device_for(wanted_adapter().as_deref(), window_adapter) +} + +/// [`may_adopt_window_device`] for an explicit `wanted` name. +pub fn may_adopt_window_device_for(wanted: Option<&str>, window_adapter: &str) -> bool { + wanted.is_none_or(|w| adapter_name_matches(w, window_adapter)) +} + /// `LIGHTCRAFT_GPU_BACKEND=off`. pub(crate) fn env_off() -> bool { env_choice() == BackendChoice::Off @@ -410,6 +580,97 @@ mod tests { } } + /// `LIGHTCRAFT_GPU_ADAPTER` picks a card by part of its name, any case; software adapters never. + #[test] + fn gpu_adapter_variable_matches_part_of_the_card_name() { + use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu}; + assert_eq!(wanted_adapter_from(None), None); + assert_eq!(wanted_adapter_from(Some(" ")), None); + assert_eq!(wanted_adapter_from(Some(" RTX 4070 ")).as_deref(), Some("rtx 4070")); + assert!(adapter_name_matches("4070", "NVIDIA GeForce RTX 4070 SUPER")); + assert!(adapter_name_matches("geforce rtx 4070 super", "NVIDIA GeForce RTX 4070 SUPER")); + assert!(adapter_name_matches(" Super ", "NVIDIA GeForce RTX 4070 SUPER")); + assert!(!adapter_name_matches("4070", "NVIDIA GeForce RTX 5070")); + assert!(!adapter_name_matches("", "NVIDIA GeForce RTX 5070"), "a blank name matches nothing"); + // two cards: the screen's card first in wgpu's order, as here + let two = [("NVIDIA GeForce RTX 5070", DiscreteGpu), ("NVIDIA GeForce RTX 4070 SUPER", DiscreteGpu), ("Microsoft Basic Render Driver", Cpu)]; + assert_eq!(find_named_adapter("4070", two), Some(1)); + assert_eq!(find_named_adapter("5070", two), Some(0)); + // "070" is in both: the first one in wgpu's order + assert_eq!(find_named_adapter("070", two), Some(0)); + assert_eq!(find_named_adapter("radeon", two), None, "no match: the caller falls back to the default choice"); + assert_eq!(find_named_adapter("basic render", two), None, "a software adapter is never picked"); + assert_eq!(find_named_adapter("intel", [("Intel(R) UHD Graphics 770", IntegratedGpu)]), Some(0)); + assert_eq!(find_named_adapter("4070", [] as [(&str, wgpu::DeviceType); 0]), None); + } + + /// A fake adapter list (a laptop: built-in card first, a dedicated one, WARP; and two of a + /// kind): no match, several matches, software, and the one log line each gives. + #[test] + fn a_fake_adapter_list_picks_in_a_defined_order() { + use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu, VirtualGpu}; + let laptop = [ + Candidate::of("Intel(R) Iris(R) Xe Graphics", IntegratedGpu), + Candidate::of("NVIDIA GeForce RTX 4060 Laptop GPU", DiscreteGpu), + Candidate::of("Microsoft Basic Render Driver", Cpu), + ]; + // no match: the default choice, and a warning that lists the cards + let none = choose_named_adapter("radeon", &laptop); + assert_eq!(none, NamedChoice::default()); + let (warn, line) = named_choice_note("radeon", &none, &laptop); + assert!(warn && line.contains("names none") && line.contains("RTX 4060 Laptop GPU") && line.contains("default choice"), "{line}"); + // several: dedicated before built-in although the built-in card comes first in wgpu's order + let g = choose_named_adapter("g", &laptop); + assert_eq!((g.index, g.matches.clone()), (Some(1), vec![1, 0])); + let (warn, line) = named_choice_note("g", &g, &laptop); + assert!(!warn && line.contains("matches 2") && line.contains("using NVIDIA GeForce RTX 4060 Laptop GPU"), "{line}"); + // one: says which + let one = choose_named_adapter("iris", &laptop); + assert_eq!(one.index, Some(0)); + assert_eq!( + named_choice_note("iris", &one, &laptop), + (false, "gpu: LIGHTCRAFT_GPU_ADAPTER=iris: using Intel(R) Iris(R) Xe Graphics".to_string()) + ); + // a software renderer: never, and the warning says so + let warp = choose_named_adapter("basic render", &laptop); + assert_eq!((warp.index, warp.software.clone()), (None, vec![2])); + let (warn, line) = named_choice_note("basic render", &warp, &laptop); + assert!(warn && line.contains("only a software renderer"), "{line}"); + // a card's whole name beats a longer name that contains it, wherever it is listed + let twins = [ + Candidate::of("NVIDIA GeForce RTX 4070 SUPER", DiscreteGpu), + Candidate::of("NVIDIA GeForce RTX 4070", DiscreteGpu), + Candidate::of("Virtual RTX 4070", VirtualGpu), + ]; + assert_eq!(choose_named_adapter("nvidia geforce rtx 4070", &twins).matches, vec![1, 0]); + // same kind: wgpu's order; virtual after dedicated + assert_eq!(choose_named_adapter("4070", &twins).matches, vec![0, 1, 2]); + // the same card on two backends (Vulkan and GL on Linux): the first listed + let both = [Candidate::of("AMD Radeon RX 7800 XT", DiscreteGpu), Candidate::of("AMD Radeon RX 7800 XT", DiscreteGpu)]; + assert_eq!(choose_named_adapter("7800", &both).index, Some(0)); + assert_eq!(choose_named_adapter("7800", &[]), NamedChoice::default()); + } + + /// The render device, the denoise network's and the face detector's each ask for a card: the + /// line about it is logged once, not three times. + #[test] + fn a_choice_is_logged_once() { + let line = "gpu: LIGHTCRAFT_GPU_ADAPTER=test-only-name names none of the graphics cards (); using the default choice"; + assert!(log_once(true, line)); + assert!(!log_once(true, line)); + assert!(!log_once(false, line)); + assert!(log_once(true, &format!("{line} (another)"))); + } + + /// The render device shares the window's device only when the variable names the window's card. + #[test] + fn window_device_is_adopted_only_for_the_wanted_card() { + assert!(may_adopt_window_device_for(None, "NVIDIA GeForce RTX 5070")); + assert!(may_adopt_window_device_for(Some("5070"), "NVIDIA GeForce RTX 5070")); + assert!(!may_adopt_window_device_for(Some("4070"), "NVIDIA GeForce RTX 5070")); + assert!(may_adopt_window_device_for(Some("4070"), "NVIDIA GeForce RTX 4070 SUPER")); + } + #[test] fn resolves_against_the_build() { let compiled = Backends::DX12 | Backends::VULKAN; diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index ea93008fed..2735116e39 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -30,7 +30,12 @@ const MODULES: &[Module] = &[ Module { src: include_str!("wgsl/blur.wgsl"), bindings: &[("src", false, "f32"), ("dst", true, "f32")], - entries: &["box_h", "box_v", "median_h", "median_v"], + entries: &["box_h", "box_v", "minmax", "median_h", "median_v"], + }, + Module { + src: include_str!("wgsl/gauss.wgsl"), + bindings: &[("src", false, "f32"), ("taps", false, "f32"), ("dst", true, "f32")], + entries: &["gauss_h", "gauss_v"], }, Module { src: include_str!("wgsl/resize.wgsl"), @@ -55,13 +60,26 @@ const MODULES: &[Module] = &[ "xguided_pre", "xguided_ab", "xguided_apply", + "fringe_lab", + "fringe_apply", ], }, + Module { + src: include_str!("wgsl/spot.wgsl"), + bindings: &[("img", true, "f32"), ("pts", false, "f32"), ("al", true, "f32"), ("sp", true, "f32"), ("df", true, "f32"), ("wt", true, "f32")], + entries: &["spot_prep", "spot_apply", "spot_score"], + }, + Module { src: include_str!("wgsl/hist.wgsl"), bindings: &[("px", false, "u32"), ("bins", true, "atomic")], entries: &["histogram"] }, Module { src: include_str!("wgsl/mask.wgsl"), bindings: &[("img", false, "f32"), ("log_l", false, "f32"), ("aux", false, "f32"), ("c", true, "f32"), ("alpha", true, "f32")], entries: &["shape", "combine", "finalize"], }, + Module { + src: include_str!("wgsl/present.wgsl"), + bindings: &[("px", false, "u32"), ("dst", true, "u32"), ("count", true, "atomic")], + entries: &["unwritten", "pad_rows"], + }, Module { src: include_str!("wgsl/geom.wgsl"), bindings: &[("src", false, "f32"), ("dst", true, "f32"), ("coverage", false, "u32")], @@ -337,6 +355,8 @@ pub struct Gpu { free: std::sync::Mutex>, /// Largest storage buffer the device accepts (bytes). pub max_buffer: u64, + /// The device is the window's (eframe's): renders can hand it textures to draw directly. + pub window: bool, } /// WGSL constants shared by every module (generated from the CPU pipeline's values). @@ -345,7 +365,15 @@ fn constants() -> String { use lightcraft_pipeline::tone::{CHROMA_N, LUT_MAX_EV, LUT_MIN_EV, LUT_N}; let mut s = String::new(); let [to_lms, from_lms, to_lab, from_lab] = lightcraft_color::perceptual::oklab_matrices(); - for (name, m) in [("OK_TO_LMS", to_lms), ("OK_FROM_LMS", from_lms), ("OK_TO_LAB", to_lab), ("OK_FROM_LAB", from_lab)] { + let (to_pro, from_pro) = lightcraft_pipeline::light_v3::prophoto_matrices(); + for (name, m) in [ + ("OK_TO_LMS", to_lms), + ("OK_FROM_LMS", from_lms), + ("OK_TO_LAB", to_lab), + ("OK_FROM_LAB", from_lab), + ("PRO_FROM_2020", to_pro), + ("PRO_TO_2020", from_pro), + ] { let rows: Vec = m.iter().map(|r| format!("vec3({:?}, {:?}, {:?})", r[0], r[1], r[2])).collect(); s += &format!("const {name} = array, 3>({});\n", rows.join(", ")); } @@ -360,10 +388,18 @@ fn constants() -> String { crate::params::CURVE_N ); s += &format!("const POINT_WORDS: u32 = {}u;\n", lightcraft_pipeline::colorops::POINT_WORDS); + let y = lightcraft_pipeline::light_v3::PRO_Y; + s += &format!("const PRO_Y = vec3({:?}, {:?}, {:?});\nconst LIGHT_N: u32 = {}u;\n", y[0], y[1], y[2], lightcraft_pipeline::light_v3::LUT_N); s += &format!("const EYE_WORDS: u32 = {}u;\n", lightcraft_pipeline::redeye::EYE_WORDS); use lightcraft_pipeline::masks::{AUTO_TOL_CHROMA, AUTO_TOL_EV}; s += &format!("const AUTO_TOL_EV: f32 = {AUTO_TOL_EV:?};\nconst AUTO_TOL_CHROMA: f32 = {AUTO_TOL_CHROMA:?};\n"); s += &format!("const SHADOW_TINT_K: f32 = {:?};\n", lightcraft_pipeline::colorops::SHADOW_TINT); + s += &format!("const GAMUT_WARN: f32 = {:?};\n", lightcraft_pipeline::finish::GAMUT_WARN); + s += &format!("const NCAND: u32 = {}u;\n", lightcraft_pipeline::spots::candidates(1.0).len()); + use lightcraft_pipeline::output::{PROOF_DEST_WARNING, PROOF_DISPLAY_WARNING}; + for (name, c) in [("PROOF_DEST", PROOF_DEST_WARNING), ("PROOF_DISP", PROOF_DISPLAY_WARNING)] { + s += &format!("const {name}_R: f32 = {:?};\nconst {name}_G: f32 = {:?};\nconst {name}_B: f32 = {:?};\n", c[0], c[1], c[2]); + } for (i, h) in GRAIN_HASH.iter().enumerate() { s += &format!("const GRAIN_H{i}: u32 = {h}u;\n"); } @@ -397,10 +433,8 @@ impl Gpu { // no indirect-call validation pipeline: Intel Metal fails to compile it (#250) desc.flags = crate::backend::instance_flags_from_env(desc.flags); let instance = wgpu::Instance::new(desc); - let adapter = pollster::block_on( - instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }), - ) - .map_err(|e| format!("no GPU adapter among {backends:?} ({e})"))?; + // the card LIGHTCRAFT_GPU_ADAPTER names, else the high-performance one + let adapter = crate::backend::pick_adapter(&instance, backends)?; let info = adapter.get_info(); if refuse_adapter(info.device_type, software_allowed()) { log::info!("gpu: only a software adapter ({}), using the CPU pipeline", info.name); @@ -414,17 +448,46 @@ impl Gpu { log::info!("gpu: {} has too few storage buffers per stage", info.name); return Err(format!("{} has too few storage buffers per shader stage ({} < 10)", info.name, limits.max_storage_buffers_per_shader_stage)); } - if let Some((binding, buffer)) = limits_override() { - limits.max_storage_buffer_binding_size = limits.max_storage_buffer_binding_size.min(binding); - limits.max_buffer_size = limits.max_buffer_size.min(buffer); - log::info!("gpu: LIGHTCRAFT_GPU_LIMITS: storage bindings ≤ {} MiB, buffers ≤ {} MiB", binding >> 20, buffer >> 20); - } + limits = capped(limits, limits_override()); let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("lightcraft"), required_limits: limits.clone(), ..Default::default() })) .map_err(|e| format!("{}: device creation failed ({e})", info.name))?; + Gpu::with_device(device, queue, info, limits, false) + } + + /// The renderer on the window's device ([`crate::adopt_window_device`]), within its limits + /// lowered by `LIGHTCRAFT_GPU_LIMITS` as a device of its own would be. + pub fn adopt(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo) -> Result { + Gpu::adopt_capped(device, queue, info, limits_override()) + } + + /// [`Gpu::adopt`] with the limits override given (`LIGHTCRAFT_GPU_LIMITS`, parsed). + fn adopt_capped(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo, cap: Option<(u64, u64)>) -> Result { + let limits = capped(device.limits(), cap); + Gpu::with_device(device, queue, info, limits, true) + } + + /// The renderer on an existing device: the window's (`window`, see [`crate::adopt_window_device`]) + /// or one [`Gpu::new`] created with `limits`. Builds the kernels (~0.4–2 s: not on the UI thread). + pub fn with_device(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo, limits: wgpu::Limits, window: bool) -> Result { + if limits.max_storage_buffers_per_shader_stage < 10 { + return Err(format!("{} has too few storage buffers per shader stage ({} < 10)", info.name, limits.max_storage_buffers_per_shader_stage)); + } + let started = std::time::Instant::now(); + let kernels = match build_kernels(&device) { + Ok(kernels) => kernels, + Err(e) => { + log::error!("gpu: kernels failed to build on {}: {e}", info.name); + return Err(format!("{}: kernels failed to build ({e})", info.name)); + } + }; + let build_ms = started.elapsed().as_millis(); + // Only a device the renderer keeps gets these: a window's device declined above keeps the + // window's own handler, so a later error of the window's can't stop the renderer's device + // (review of PR #1065). // Errors outside a render's error scopes (see `ErrorScopes`): log, and stop using the GPU. device.on_uncaptured_error(std::sync::Arc::new(|e| { log::error!("gpu: {e}"); @@ -437,15 +500,6 @@ impl Gpu { log::error!("gpu: device lost ({reason:?}): {msg}"); crate::mark_broken(&format!("device lost ({reason:?}): {msg}")); }); - let started = std::time::Instant::now(); - let kernels = match build_kernels(&device) { - Ok(kernels) => kernels, - Err(e) => { - log::error!("gpu: kernels failed to build on {}: {e}", info.name); - return Err(format!("{}: kernels failed to build ({e})", info.name)); - } - }; - let build_ms = started.elapsed().as_millis(); let dummy = device.create_buffer(&wgpu::BufferDescriptor { label: Some("dummy"), size: 16, @@ -453,8 +507,15 @@ impl Gpu { mapped_at_creation: false, }); let max_buffer = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size); - log::info!("gpu: {} ({:?}), {} kernels in {build_ms} ms, buffers ≤ {} MiB", info.name, info.backend, kernels.len(), max_buffer >> 20); - Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer }) + log::info!( + "gpu: {} ({:?}), {} kernels in {build_ms} ms, buffers ≤ {} MiB{}", + info.name, + info.backend, + kernels.len(), + max_buffer >> 20, + if window { ", the window's device" } else { "" } + ); + Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer, window }) } /// A buffer of `len` 32-bit values with undefined contents (a recycled one when possible). @@ -542,24 +603,7 @@ impl Gpu { /// second panic while a failed render unwinds aborts the process. A lost device is not polled /// again; a poll that panics counts as one and stops the GPU. pub(crate) fn poll(&self, t: wgpu::PollType) -> Result { - if DEVICE_LOST.load(Ordering::Relaxed) { - return Err("the device is lost".into()); - } - let polled = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - #[cfg(test)] - if SIMULATED_LOST_POLL.with(std::cell::Cell::get) { - panic!("Error in Device::poll: Validation Error\n\nCaused by:\n Parent device is lost (simulated)"); - } - self.device.poll(t) - })); - match polled { - Ok(r) => r.map_err(|e| e.to_string()), - Err(_) => { - DEVICE_LOST.store(true, Ordering::Relaxed); - crate::mark_broken("device lost: Device::poll failed"); - Err("the device is lost (Device::poll failed)".into()) - } - } + poll_device(&self.device, t) } /// Upload 32-bit values. @@ -771,6 +815,108 @@ fn limits_override() -> Option<(u64, u64)> { parse_limits(&std::env::var("LIGHTCRAFT_GPU_LIMITS").ok()?) } +/// `limits` lowered to `cap` ([`limits_override`]: storage binding bytes, buffer bytes). +fn capped(mut limits: wgpu::Limits, cap: Option<(u64, u64)>) -> wgpu::Limits { + if let Some((binding, buffer)) = cap { + limits.max_storage_buffer_binding_size = limits.max_storage_buffer_binding_size.min(binding); + limits.max_buffer_size = limits.max_buffer_size.min(buffer); + log::info!("gpu: LIGHTCRAFT_GPU_LIMITS: storage bindings ≤ {} MiB, buffers ≤ {} MiB", binding >> 20, buffer >> 20); + } + limits +} + +/// `device.poll` that never panics: see [`Gpu::poll`]. [`read_texture`] uses it too: its device +/// (the window's, when adopted) shares the device-lost flag. +fn poll_device(device: &wgpu::Device, t: wgpu::PollType) -> Result { + if DEVICE_LOST.load(Ordering::Relaxed) { + return Err("the device is lost".into()); + } + let polled = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + #[cfg(test)] + if SIMULATED_LOST_POLL.with(std::cell::Cell::get) { + panic!("Error in Device::poll: Validation Error\n\nCaused by:\n Parent device is lost (simulated)"); + } + device.poll(t) + })); + match polled { + Ok(r) => r.map_err(|e| e.to_string()), + Err(_) => { + DEVICE_LOST.store(true, Ordering::Relaxed); + crate::mark_broken("device lost: Device::poll failed"); + Err("the device is lost (Device::poll failed)".into()) + } + } +} + +/// See [`crate::read_texture`]. +pub(crate) fn read_texture( + device: &wgpu::Device, + queue: &wgpu::Queue, + texture: &wgpu::Texture, + width: usize, + height: usize, +) -> Result { + if DEVICE_LOST.load(Ordering::Relaxed) { + return Err("the device is lost".into()); + } + if width == 0 || height == 0 { + return Err("an empty texture".into()); + } + let (Ok(w32), Ok(h32)) = (u32::try_from(width), u32::try_from(height)) else { return Err("texture too large".into()) }; + if w32 > texture.width() || h32 > texture.height() || texture.format() != wgpu::TextureFormat::Rgba8Unorm { + return Err("not an 8-bit view texture of that size".into()); + } + // texture copies take rows of a multiple of 256 bytes + let stride = width.checked_mul(4).ok_or("texture too large")?.next_multiple_of(256); + let size = stride.checked_mul(height).ok_or("texture too large")?; + let (Ok(stride32), Ok(size64)) = (u32::try_from(stride), u64::try_from(size)) else { return Err("texture too large".into()) }; + let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); + let staging = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("view readback"), + size: size64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("view readback") }); + enc.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyBufferInfo { + buffer: &staging, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(stride32), rows_per_image: Some(h32) }, + }, + wgpu::Extent3d { width: w32, height: h32, depth_or_array_layers: 1 }, + ); + queue.submit([enc.finish()]); + if let Some(e) = pollster::block_on(scope.pop()) { + return Err(format!("texture copy failed: {e}")); + } + let slice = staging.slice(..); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |r| { + let _ = tx.send(r); + }); + // (the render path's wait: queued work ahead of the copy can take that long too) + let wait = READBACK_TIMEOUT; + poll_device(device, wgpu::PollType::Wait { submission_index: None, timeout: Some(wait) })?; + match rx.recv_timeout(wait) { + Ok(Ok(())) => {} + Ok(Err(e)) => return Err(format!("{e}")), + Err(e) => return Err(format!("map callback: {e}")), + } + let bytes = slice.get_mapped_range().map_err(|e| format!("{e:?}"))?; + let mut data = Vec::with_capacity(width * height); + for row in bytes.chunks(stride).take(height) { + let row = row.get(..width * 4).ok_or("short readback row")?; + data.extend(row.as_chunks::<4>().0.iter().copied()); + } + drop(bytes); + staging.unmap(); + if data.len() != width * height { + return Err("incomplete readback".into()); + } + Ok(lightcraft_raster::Rgba8 { width, height, data }) +} + fn parse_limits(v: &str) -> Option<(u64, u64)> { let v = v.trim().to_ascii_lowercase(); match v.as_str() { @@ -927,6 +1073,54 @@ mod tests { assert_eq!(super::parse_limits("17592186044416"), None); } + /// `LIGHTCRAFT_GPU_LIMITS` caps the window's device as it caps a device of its own (review of + /// PR #1065: adopting the window's device skipped it, so a 1024 × 1024 RGB float buffer — 12 MiB — + /// was taken under an 8 MiB cap). + #[test] + fn the_limits_override_caps_an_adopted_device() { + let big = wgpu::Limits { max_storage_buffer_binding_size: 1 << 30, max_buffer_size: 1 << 31, ..wgpu::Limits::default() }; + let c = super::capped(big.clone(), super::parse_limits("8")); + assert_eq!((c.max_storage_buffer_binding_size, c.max_buffer_size), (8 << 20, 16 << 20)); + let c = super::capped(big.clone(), None); + assert_eq!((c.max_storage_buffer_binding_size, c.max_buffer_size), (1 << 30, 1 << 31)); + + let _lock = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let Some((device, queue, info)) = test_device() else { + lightcraft_testkit::skip!(Gpu, "no GPU adapter"); + return; + }; + let full = device.limits().max_storage_buffer_binding_size.min(device.limits().max_buffer_size); + if full <= 12 << 20 { + lightcraft_testkit::skip!(Gpu, "the adapter's buffers are already ≤ 12 MiB"); + return; + } + let g = super::Gpu::adopt_capped(device, queue, info, super::parse_limits("8")).expect("kernels build"); + assert!(g.window); + assert_eq!(g.limit(), 8 << 20, "the cap applies to the adopted device"); + assert!(1024 * 1024 * 3 * 4 > g.limit(), "a 12 MiB buffer is over it"); + } + + /// A device as eframe makes the window's (the adapter's own limits). + fn test_device() -> Option<(wgpu::Device, wgpu::Queue, wgpu::AdapterInfo)> { + let backends = crate::backend::compute_backends()?; + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = backends; + desc.backend_options = crate::backend::backend_options(); + let instance = wgpu::Instance::new(desc); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; + let info = adapter.get_info(); + if info.device_type == wgpu::DeviceType::Cpu { + return None; + } + let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + label: Some("test window"), + required_limits: adapter.limits(), + ..Default::default() + })) + .ok()?; + Some((device, queue, info)) + } + /// Issue #2936: the kernels are built on several threads; every entry point of every module has one. #[test] fn every_entry_point_has_a_kernel() { @@ -1009,6 +1203,42 @@ mod tests { } } + /// Review of PR #1065: a view readback (headless screenshot) whose poll finds the device lost + /// returns an error instead of panicking, stops the GPU, and doesn't poll the device again. + #[test] + fn a_view_readback_on_a_lost_device_fails_without_a_panic() { + if run_child("lost_readback_child").is_none() { + lightcraft_testkit::skip!(Gpu, "no GPU device"); + } + } + + #[test] + #[ignore = "run in its own process by a_view_readback_on_a_lost_device_fails_without_a_panic"] + fn lost_readback_child() { + let Some(g) = crate::device() else { + println!("CHILD: no GPU"); + return; + }; + let texture = g.device.create_texture(&wgpu::TextureDescriptor { + label: Some("view"), + size: wgpu::Extent3d { width: 8, height: 8, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }); + assert!(super::read_texture(&g.device, &g.queue, &texture, 8, 8).is_ok(), "a live device reads back"); + super::SIMULATED_LOST_POLL.with(|c| c.set(true)); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| super::read_texture(&g.device, &g.queue, &texture, 8, 8))); + assert!(matches!(r, Ok(Err(_))), "the lost device fails the readback without a panic"); + assert!(!crate::available(), "the GPU is not used again"); + super::SIMULATED_LOST_POLL.with(|c| c.set(false)); + assert!(super::read_texture(&g.device, &g.queue, &texture, 8, 8).is_err(), "a lost device is not polled again"); + println!("CHILD: survived"); + } + /// A Metal device really lost (its command buffers exhausted) is never polled again. #[test] fn a_really_lost_device_is_not_polled_again() { diff --git a/crates/gpu/src/faces.rs b/crates/gpu/src/faces.rs index 9192677867..e85b1bd98b 100644 --- a/crates/gpu/src/faces.rs +++ b/crates/gpu/src/faces.rs @@ -107,20 +107,7 @@ fn make_device(backends: wgpu::Backends) -> Result { desc.backend_options = crate::backend::backend_options(); desc.flags = crate::backend::instance_flags_from_env(desc.flags); let instance = wgpu::Instance::new(desc); - let wanted = std::env::var("LIGHTCRAFT_GPU_ADAPTER").ok().map(|s| s.trim().to_lowercase()).filter(|s| !s.is_empty()); - let adapter = match &wanted { - Some(w) => pollster::block_on(instance.enumerate_adapters(backends)) - .into_iter() - .find(|a| { - let i = a.get_info(); - i.device_type != wgpu::DeviceType::Cpu && i.name.to_lowercase().contains(w.as_str()) - }) - .ok_or_else(|| format!("no GPU adapter named like `{w}`"))?, - None => pollster::block_on( - instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }), - ) - .map_err(|e| format!("no GPU adapter among {backends:?} ({e})"))?, - }; + let adapter = crate::backend::pick_adapter(&instance, backends)?; let info = adapter.get_info(); if info.device_type == wgpu::DeviceType::Cpu { return Err(format!("software adapter ({}) skipped: the CPU is faster", info.name)); diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 51a8aa45bc..8863b45a04 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -45,7 +45,14 @@ mod params; mod render; #[cfg(not(target_arch = "wasm32"))] -pub use render::GpuStages; +pub use render::{DisplayFrame, GpuStages, Output}; +/// The wgpu the renderer is built on (the same crate eframe uses: hosts hand over its device). +#[cfg(not(target_arch = "wasm32"))] +pub use wgpu; + +/// Unit tests that create the device or swap the crash sentinel's path take turns. +#[cfg(test)] +pub(crate) static DEVICE_TEST_LOCK: Mutex<()> = Mutex::new(()); static ENABLED: AtomicBool = AtomicBool::new(true); /// Set when a GPU render failed: the process stays on the CPU from then on. @@ -277,6 +284,21 @@ fn env_disabled() -> bool { #[cfg(not(target_arch = "wasm32"))] static GPU: std::sync::OnceLock> = std::sync::OnceLock::new(); +/// Set while [`adopt_window_device`] is about to run or running: [`device`] and [`warm_up`] then +/// don't create a device of their own (review of PR #1065: the settings' warm-up raced the +/// adoption thread and could win, so the window's device went unused). +#[cfg(not(target_arch = "wasm32"))] +static WINDOW_PENDING: AtomicBool = AtomicBool::new(false); + +/// Announce (before spawning it) that [`adopt_window_device`] will run, or withdraw that when it +/// can't (`false`). Until it has finished, renders take the CPU path and [`warm_up`] does nothing. +pub fn set_window_device_pending(pending: bool) { + #[cfg(not(target_arch = "wasm32"))] + WINDOW_PENDING.store(pending, Ordering::Release); + #[cfg(target_arch = "wasm32")] + let _ = pending; +} + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn device() -> Option<&'static ctx::Gpu> { // turned off (preference, environment): don't even load the driver (issue #136) @@ -286,6 +308,11 @@ pub(crate) fn device() -> Option<&'static ctx::Gpu> { if let Some(g) = GPU.get() { return g.as_ref().ok(); } + // the window's device is being adopted: render on the CPU until it is, rather than create a + // device of our own first (which would leave the window's unused) + if WINDOW_PENDING.load(Ordering::Acquire) { + return None; + } // creating the device is a long call into the driver: not once the process is ending let _work = exit::enter()?; GPU.get_or_init(|| { @@ -313,7 +340,7 @@ pub(crate) fn existing_device() -> Option<&'static ctx::Gpu> { /// while GPU rendering is turned off. Repeated calls start one thread at most. pub fn warm_up() { #[cfg(not(target_arch = "wasm32"))] - if !env_disabled() && ENABLED.load(Ordering::SeqCst) && GPU.get().is_none() { + if !env_disabled() && ENABLED.load(Ordering::SeqCst) && GPU.get().is_none() && !WINDOW_PENDING.load(Ordering::Acquire) { static STARTED: AtomicBool = AtomicBool::new(false); if STARTED.swap(true, Ordering::SeqCst) { return; @@ -328,8 +355,9 @@ pub fn warm_up() { // again. Released first, then the preference read again: a call made while this // thread still held the flag (turned back on meanwhile) returned without starting // one, so this thread tries again itself rather than leave "starting" for good. + // The window's device being adopted meanwhile: that creates the device, not this. STARTED.store(false, Ordering::SeqCst); - if !ENABLED.load(Ordering::SeqCst) || STARTED.swap(true, Ordering::SeqCst) { + if WINDOW_PENDING.load(Ordering::Acquire) || !ENABLED.load(Ordering::SeqCst) || STARTED.swap(true, Ordering::SeqCst) { break; } } @@ -492,6 +520,114 @@ pub fn try_render( stages: Option<&StageCache>, ) -> Result { #[cfg(not(target_arch = "wasm32"))] + { + match run(src, info, s, req, stages, false)? { + render::Output::Image(r) => Ok(r), + // (not asked for) + render::Output::Display { .. } => Err(Fallback::NotTried), + } + } + #[cfg(target_arch = "wasm32")] + { + let _ = (src, info, s, req, stages); + Err(Fallback::NotTried) + } +} + +/// [`render`] for the window: when the device is the window's ([`adopt_window_device`]) and the +/// render allows it, the result stays on the device as a texture to draw ([`Output::Display`]); +/// otherwise pixels as from [`render`]. `None`: render on the CPU instead. +#[cfg(not(target_arch = "wasm32"))] +pub fn render_display(src: &Arc, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest, stages: Option<&StageCache>) -> Option { + run(src, info, s, req, stages, true).ok() +} + +/// Whether renders run on the window's device (and so can be handed over as textures). +pub fn on_window_device() -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + existing_device().is_some_and(|g| g.window) + } + #[cfg(target_arch = "wasm32")] + { + false + } +} + +/// Render on the window's device (eframe's) instead of a device of its own, so finished views can +/// be drawn without reading them back ([`render_display`]). Builds the kernels on it (~0.4–2 s: +/// call it off the UI thread), in place of [`warm_up`]. When that fails, or the window's device +/// doesn't suit (a software adapter, too few storage buffers), a device of its own is created as +/// before; `Err` says why the window's wasn't used. Does nothing once a device exists. +#[cfg(not(target_arch = "wasm32"))] +pub fn adopt_window_device(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo) -> Result<(), String> { + /// Whatever the outcome, renders may create or use a device again afterwards. + struct Done; + impl Drop for Done { + fn drop(&mut self) { + WINDOW_PENDING.store(false, Ordering::Release); + } + } + let _done = Done; + if env_disabled() || !ENABLED.load(Ordering::Relaxed) { + return Err("GPU rendering is off".into()); + } + let _work = exit::enter().ok_or("LightCraft is closing")?; + let mut declined = None; + let g = GPU.get_or_init(|| { + let adopted = if info.device_type == wgpu::DeviceType::Cpu { + Err(format!("software adapter ({}) skipped: the CPU pipeline is faster", info.name)) + } else if !backend::may_adopt_window_device(&info.name) { + // (the photos render on the card LIGHTCRAFT_GPU_ADAPTER names, on a device of its own) + Err(format!("LIGHTCRAFT_GPU_ADAPTER names another card than the window's ({})", info.name)) + } else { + // (building the kernels is a long call into the driver: the crash sentinel covers it) + backend::with_init_marker(wgpu::Backends::from(info.backend), || { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ctx::Gpu::adopt(device, queue, info))) + .unwrap_or_else(|_| Err("kernel setup panicked".into())) + }) + }; + adopted.or_else(|e| { + log::warn!("gpu: not rendering on the window's device ({e}); creating one"); + declined = Some(e); + let Some(backends) = backend::compute_backends() else { return Err("disabled by LIGHTCRAFT_GPU_BACKEND=off".into()) }; + backend::with_init_marker(backends, || { + std::panic::catch_unwind(|| ctx::Gpu::new(backends)).unwrap_or_else(|_| Err("device creation panicked".into())) + }) + }) + }); + match (g, declined) { + (Ok(g), None) if g.window => Ok(()), + (_, Some(e)) => Err(e), + (Ok(_), None) => Err("a device of its own was created first".into()), + (Err(e), None) => Err(e.clone()), + } +} + +/// The pixels of a texture on `device` (a [`DisplayFrame`]'s, or any `Rgba8Unorm` texture with +/// `COPY_SRC`): for a headless screenshot of a view drawn straight from the GPU, and for tests. The +/// app never needs them to draw. Waits for the GPU (at most a minute); `Err` when the copy or +/// the wait fails. +#[cfg(not(target_arch = "wasm32"))] +pub fn read_texture( + device: &wgpu::Device, + queue: &wgpu::Queue, + texture: &wgpu::Texture, + width: usize, + height: usize, +) -> Result { + ctx::read_texture(device, queue, texture, width, height) +} + +#[cfg(not(target_arch = "wasm32"))] +fn run( + src: &Arc, + info: &SourceInfo, + s: &DevelopSettings, + req: &RenderRequest, + stages: Option<&StageCache>, + display: bool, +) -> Result { { // sections switched off with their eye render as if at their defaults (issue #316) let effective = s.effective(); @@ -501,6 +637,10 @@ pub fn try_render( return Err(Fallback::NotTried); } let s = &*lightcraft_pipeline::settings_for(s, req); + // content-aware Fill spots (`spots::fill_box`) have no GPU kernel: the CPU renders the photo + if s.spots.iter().any(|sp| sp.mode == lightcraft_develop::SpotMode::Fill) { + return Err(Fallback::NotTried); + } // in flight until this returns; not tried once the process is ending (issue #620) let _work = exit::enter().ok_or(Fallback::NotTried)?; let gpu = device().ok_or(Fallback::NotTried)?; @@ -512,7 +652,7 @@ pub fn try_render( let (r, scoped) = { let _scope = ctx::RenderScope::new(gpu); let errors = ctx::ErrorScopes::push(gpu); - let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| render::render(gpu, src, info, s, req, ext.as_deref(), fault))); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| render::render(gpu, src, info, s, req, ext.as_deref(), fault, display))); (r, errors.pop()) }; // An error the device raised explains the readback failures that follow it; a buffer @@ -533,7 +673,8 @@ pub fn try_render( e.clear(); } let what = match &r { - Some(r) => format!("{}×{}", r.image.width, r.image.height), + Some(Output::Image(r)) => format!("{}×{}", r.image.width, r.image.height), + Some(Output::Display { frame, .. }) => format!("{}×{}", frame.width, frame.height), None => "GPU render".into(), }; let reason = match f.kind { @@ -568,11 +709,6 @@ pub fn try_render( record_fallback(reason.clone()); Err(Fallback::Failed(reason)) } - #[cfg(target_arch = "wasm32")] - { - let _ = (src, info, s, req, stages); - Err(Fallback::NotTried) - } } /// Tests: parse and validate a WGSL module with naga, as wgpu does before it hands a shader to the driver. Needs no diff --git a/crates/gpu/src/nn.rs b/crates/gpu/src/nn.rs index 235ba9be68..334a663919 100644 --- a/crates/gpu/src/nn.rs +++ b/crates/gpu/src/nn.rs @@ -4,7 +4,8 @@ //! The runner has a device of its own, so a denoise job and the interactive renders are separate contexts that the //! driver time-slices, and a failure of one never takes the other down. It respects the same switches as GPU rendering //! (`LIGHTCRAFT_GPU`, `LIGHTCRAFT_GPU_BACKEND`, the GPU preference) and the same crash sentinel around device creation. -//! `LIGHTCRAFT_GPU_ADAPTER` picks an adapter by (part of) its name, e.g. to try another card. +//! `LIGHTCRAFT_GPU_ADAPTER` picks an adapter by (part of) its name, e.g. to try another card (`backend::pick_adapter`, +//! shared with the render device). //! //! Every failure is an `Err` (never a panic), and a device that errs or is lost stops being used: callers then run the //! CPU runner. The kernels (`wgsl/nn_conv.wgsl`, `wgsl/nn_pool.wgsl`) are tested against the plain-loop reference @@ -89,23 +90,7 @@ fn make_device(backends: wgpu::Backends) -> Result { // no indirect-call validation pipeline: Intel Metal fails to compile it (#250) desc.flags = crate::backend::instance_flags_from_env(desc.flags); let instance = wgpu::Instance::new(desc); - let wanted = std::env::var("LIGHTCRAFT_GPU_ADAPTER").ok().map(|s| s.trim().to_lowercase()).filter(|s| !s.is_empty()); - let adapter = match &wanted { - Some(w) => { - let all = pollster::block_on(instance.enumerate_adapters(backends)); - let names: Vec = all.iter().map(|a| a.get_info().name).collect(); - all.into_iter() - .find(|a| { - let i = a.get_info(); - i.device_type != wgpu::DeviceType::Cpu && i.name.to_lowercase().contains(w.as_str()) - }) - .ok_or_else(|| format!("no GPU adapter named like `{w}` (found: {})", names.join(", ")))? - } - None => pollster::block_on( - instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }), - ) - .map_err(|e| format!("no GPU adapter among {backends:?} ({e})"))?, - }; + let adapter = crate::backend::pick_adapter(&instance, backends)?; let info = adapter.get_info(); if info.device_type == wgpu::DeviceType::Cpu { return Err(format!("software adapter ({}) skipped: the CPU is faster", info.name)); @@ -968,6 +953,9 @@ mod tests { /// The runner, or `None` (with a note) on a machine with no usable GPU. fn gpu(net: &Net, tile: usize) -> Option { + // creating the device and building the kernels arms the crash sentinel: take turns with + // the tests that set its path (`backend::tests`) + let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); match runner(net, tile) { Ok(r) => Some(r), Err(e) => { @@ -1087,7 +1075,10 @@ mod tests { let net = onnx::read(std::path::Path::new(&model)).unwrap(); let tile = 512usize; let started = Instant::now(); - let g = runner(&net, tile).unwrap(); + let g = { + let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + runner(&net, tile).unwrap() + }; println!("{}: set up in {:.2} s, {:.0} MB per tile in flight", g.adapter(), started.elapsed().as_secs_f64(), g.bytes_per_tile() as f64 / 1e6); println!("kernels: {}", g.build_report()); let manifest = DenoiserManifest { diff --git a/crates/gpu/src/params.rs b/crates/gpu/src/params.rs index b46b7cc1ac..8c8624a23c 100644 --- a/crates/gpu/src/params.rs +++ b/crates/gpu/src/params.rs @@ -28,6 +28,11 @@ const FIELDS: &[(&str, usize)] = &[ ("DEHAZE", 1), ("SHARPEN", 1), ("SHARPEN_MASK", 1), + ("SHARPEN_LIMIT", 1), + ("SHARPEN_GAIN", 1), + ("SHARPEN_V3", 1), + ("SHP_OFF", 1), + ("HAS_SHP", 1), ("HAS_CLAR", 1), ("HAS_TEX", 1), ("HAS_DARK", 1), @@ -73,6 +78,13 @@ const FIELDS: &[(&str, usize)] = &[ ("OUT_Y", 3), ("OUT_TRC", 1), ("OUT_GAMMA", 1), + // a LUT profile: its table in `aux` at LUT_OFF (size³ rgb, red fastest), amount and domain + ("LUT", 1), + ("LUT_OFF", 1), + ("LUT_N", 1), + ("LUT_AMT", 1), + ("LUT_MIN", 3), + ("LUT_MAX", 3), // soft proofing (matrix proofs; `ProofParams`): working → proof RGB, its luma, proof → output, warnings ("PROOF", 1), ("PROOF_M", 9), @@ -82,6 +94,13 @@ const FIELDS: &[(&str, usize)] = &[ ("PROOF_DISP_WARN", 1), // first row of a band dispatch (the kernel runs over rows Y0.., see `render`) ("Y0", 1), + // process V4's calibrated Contrast, Blacks (`FinishParams::light`): the number of active + // operators (0 = none), each one's mode (`light_v3::Mode::code`) and mix weight, and the offset + // of their tables in `aux` (LIGHT_N entries each, in order) + ("LIGHT_OPS", 1), + ("LIGHT_MODE", 2), + ("LIGHT_W", 2), + ("LIGHT_OFF", 1), ]; /// `(name, index)` of every field (for the WGSL constants). @@ -140,13 +159,15 @@ impl Block { pub struct Present { pub clarity: bool, pub texture: bool, + /// The sharpening blur plane (after the texture plane in `tex` when both are present). + pub sharpen: bool, pub dark: bool, /// The blurred chromaticity follows the mask planes in the `masks` buffer. pub chroma: bool, } /// The `finish` kernel's parameter block and auxiliary table (tone LUT | chroma curve | sRGB LUT | curve LUTs | -/// mask terms) for `fp` with `masks` (their local adjustments' terms). +/// mask terms | light operator tables) for `fp` with `masks` (their local adjustments' terms). pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present) -> (Vec, Vec) { let mut aux: Vec = fp.tone.lut().to_vec(); aux.extend_from_slice(fp.tone.chroma_lut()); @@ -163,8 +184,28 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr for m in masks { aux.extend_from_slice(m); } + let light_off = aux.len(); + let light = fp.light.as_ref().map_or(&[][..], |l| &l.ops[..]); + let light = &light[..light.len().min(2)]; + for op in light { + aux.extend_from_slice(&op.lut[..]); + } + let lut_off = aux.len(); + if let Some((l, _)) = &fp.lut { + aux.extend(l.data.iter().flatten()); + } let mut p = Block::new(); + p.u("LIGHT_OPS", light.len() as u32); + p.u("LIGHT_OFF", light_off as u32); + if let Some(i) = index("LIGHT_MODE") { + for (k, op) in light.iter().enumerate() { + if let Some(slot) = p.0.get_mut(i + k) { + *slot = op.mode.code(); + } + } + } + p.fs("LIGHT_W", &light.iter().map(|op| op.weight).collect::>()); p.u("W", fp.w as u32); p.u("H", fp.h as u32); p.u("NMASK", masks.len() as u32); @@ -184,6 +225,11 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr p.f("DEHAZE", fp.dehaze); p.f("SHARPEN", fp.sharpen); p.f("SHARPEN_MASK", fp.sharpen_mask); + p.f("SHARPEN_LIMIT", fp.sharpen_limit); + p.f("SHARPEN_GAIN", fp.sharpen_gain); + p.b("SHARPEN_V3", fp.pixel_sharpen); + p.u("SHP_OFF", if present.texture { (fp.w * fp.h) as u32 } else { 0 }); + p.b("HAS_SHP", present.sharpen); p.b("HAS_CLAR", present.clarity); p.b("HAS_TEX", present.texture); p.b("HAS_DARK", present.dark); @@ -211,6 +257,7 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr } p.f("SKIN", ops.skin); p.fs("BANDH", lightcraft_pipeline::colorops::band_hues()); + p.fs("VIG_VIEW", &fp.view); if let Some(v) = &fp.vig { p.b("VIG", true); @@ -220,7 +267,6 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr p.f("VIG_ASPECT_MIX", v.aspect_mix); p.f("VIG_POWER", v.power); p.f("VIG_HL", v.highlights); - p.fs("VIG_VIEW", &fp.view); p.u( "VIG_STYLE", match v.style { @@ -240,6 +286,14 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr let (trc, gamma) = fp.out_trc.code(); p.u("OUT_TRC", trc); p.f("OUT_GAMMA", gamma); + if let Some((l, amount)) = &fp.lut { + p.b("LUT", true); + p.u("LUT_OFF", lut_off as u32); + p.u("LUT_N", l.size as u32); + p.f("LUT_AMT", *amount); + p.fs("LUT_MIN", &l.domain_min); + p.fs("LUT_MAX", &l.domain_max); + } if let Some(pp) = fp.proof.as_ref().filter(|pp| pp.table.is_none()) { p.b("PROOF", true); p.fs("PROOF_M", pp.to_proof.as_flattened()); diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 3042df81a0..701cc3c5de 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -44,6 +44,7 @@ struct Planes { base: Option<(local::BaseKey, Arc)>, clarity: Option<(u32, Arc)>, texture: Option<(u32, Arc)>, + sharpen: Option<(local::SharpenKey, Arc)>, dark: Option<(u32, Arc, f32)>, chroma: Option<(u32, Arc)>, } @@ -105,6 +106,7 @@ impl GpuStages { p.base.iter().for_each(|(_, b)| add(b)); p.clarity.iter().for_each(|(_, b)| add(b)); p.texture.iter().for_each(|(_, b)| add(b)); + p.sharpen.iter().for_each(|(_, b)| add(b)); p.dark.iter().for_each(|(_, b, _)| add(b)); } if let Some((_, b)) = &*self.source.lock().unwrap_or_else(|e| e.into_inner()) { @@ -213,6 +215,20 @@ impl<'a> Cx<'a> { enc.copy_buffer_to_buffer(src.raw(), 0, dst.raw(), (offset * 4) as u64, (src.len * 4) as u64); } + /// Copy `w × h` texels from `b` (rows of `stride` 32-bit texels, a multiple of 64) into + /// `texture` (recorded). + pub fn copy_to_texture(&mut self, b: &Buf, stride: usize, texture: &wgpu::Texture, w: usize, h: usize) { + let enc = self.enc.get_or_insert_with(|| self.gpu.encoder()); + enc.copy_buffer_to_texture( + wgpu::TexelCopyBufferInfo { + buffer: b.raw(), + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some((stride * 4) as u32), rows_per_image: Some(h as u32) }, + }, + wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 }, + ); + } + pub fn read_rgb(&mut self, b: &Buf, w: usize, h: usize) -> Rgb32f { Rgb32f { width: w, height: h, data: self.read(b, w * h * 3) } } @@ -263,6 +279,18 @@ pub(crate) fn gaussian(cx: &mut Cx<'_>, src: &Buf, w: usize, h: usize, nc: usize if last == 0 { a } else { b } } +/// Exact Gaussian (`lightcraft_raster::blur::gaussian_taps`) of a one-channel plane. +pub(crate) fn gaussian_fir(cx: &mut Cx<'_>, src: &Buf, w: usize, h: usize, sigma: f32) -> Buf { + let taps = lightcraft_raster::blur::gauss_taps(sigma); + let taps_buf = cx.gpu.upload(&taps); + let r = (taps.len() / 2) as u32; + let (tmp, out) = (cx.gpu.buffer(w * h), cx.gpu.buffer(w * h)); + let p = [w as u32, h as u32, r]; + cx.run("gauss_h", &p, &[Some(src), Some(&taps_buf), Some(&tmp)], groups2(w, h, [16, 16])); + cx.run("gauss_v", &p, &[Some(&tmp), Some(&taps_buf), Some(&out)], groups2(w, h, [16, 16])); + out +} + /// Resample taps of `lightcraft_raster::resample::resize`, packed for the `resize_*` kernels. fn taps(src: usize, dst: usize, filter: Filter) -> Vec { let w = lightcraft_raster::resample::weights(src, dst, filter); @@ -579,8 +607,34 @@ pub(crate) fn profiling() -> bool { *ON.get_or_init(|| std::env::var_os("LIGHTCRAFT_PROFILE").is_some()) } -/// Render on `gpu`, reusing `stages` (if given). `None` (or a result the caller discards) when the -/// render failed: the reason is recorded with [`crate::ctx::fail`]. +/// A finished render on the window's device, ready to draw: an `Rgba8Unorm` texture (the 8-bit +/// output, sRGB-curve encoded, as egui's own textures) that never went through host memory. +#[derive(Clone, Debug)] +pub struct DisplayFrame { + pub texture: wgpu::Texture, + pub width: usize, + pub height: usize, +} + +/// What a render produced: pixels in host memory, or (asked for with `display` and possible) a +/// texture on the window's device plus the histogram. +pub enum Output { + Image(Rendered), + Display { frame: DisplayFrame, histogram: Histogram }, +} + +/// Whether a render of this plan can end in a texture instead of a readback: the device is the +/// window's, nothing is drawn over the image on the CPU (overlays) or cut from it (a window that +/// spots grew), and the texture fits the device. +fn can_display(gpu: &Gpu, plan: &Plan<'_>, req: &RenderRequest) -> bool { + let max = gpu.device.limits().max_texture_dimension_2d as usize; + gpu.window && req.overlay == lightcraft_pipeline::Overlay::None && plan.keep.is_none() && plan.w <= max && plan.h <= max && plan.w * plan.h > 0 +} + +/// Render on `gpu`, reusing `stages` (if given); with `display`, into a texture when +/// [`can_display`]. `None` (or a result the caller discards) when the render failed: the reason is +/// recorded with [`crate::ctx::fail`]. +#[allow(clippy::too_many_arguments)] pub fn render( gpu: &Gpu, src: &Arc, @@ -589,7 +643,8 @@ pub fn render( req: &RenderRequest, stages: Option<&GpuStages>, fault: Option, -) -> Option { + display: bool, +) -> Option { let mut t = profiling().then(std::time::Instant::now); // Each stage is submitted on its own; under `LIGHTCRAFT_PROFILE` also waited for, so the // timings are real. @@ -692,9 +747,22 @@ pub fn render( let present = Present { clarity: prep.clarity.is_some(), texture: prep.texture.is_some(), + sharpen: prep.sharpen.is_some(), dark: prep.dark.is_some(), chroma: masks.is_some() && prep.chroma.is_some(), }; + // the finish kernel's `tex` binding: the texture plane, then the sharpening plane (one binding + // for both keeps the kernel within the storage-buffer count every supported device has) + let tex_buf: Option> = match (&prep.texture, &prep.sharpen) { + (Some(t), Some(sh)) => { + let both = cx.gpu.buffer(2 * n); + cx.copy_into(t, &both, 0); + cx.copy_into(sh, &both, n); + Some(Arc::new(both)) + } + (Some(b), None) | (None, Some(b)) => Some(b.clone()), + (None, None) => None, + }; let (p, aux) = finish_block(&fp, &terms, &present); let aux = gpu.upload(&aux); // cleared, so that work which never ran cannot pass for an image (see the check below) @@ -717,7 +785,7 @@ pub fn render( Some(&prep.log_l), Some(&prep.base), prep.clarity.as_deref(), - prep.texture.as_deref(), + tex_buf.as_deref(), prep.dark.as_deref(), masks.as_ref(), Some(&aux), @@ -726,6 +794,9 @@ pub fn render( groups2(w, rows.min(h - y0), [16, 16]), ); } + if display && can_display(gpu, &plan, req) { + return to_texture(&mut cx, &out, w, h).map(|(frame, histogram)| Output::Display { frame, histogram }); + } // the alpha a mask overlay shows: copied out before the readback below submits let overlay_mask = req.overlay.mask(s).map(|m| { let list = s.masks.iter().filter(|m| m.visible && !m.components.is_empty()); @@ -769,10 +840,8 @@ pub fn render( fail(FailKind::Fatal, format!("the GPU returned an incomplete image ({unwritten} of {n} pixels unwritten)")); return None; } - let histogram = match plan.keep { - Some(k) => Histogram::of_srgb8(&image.crop(k.x, k.y, k.w, k.h)), - None => Histogram::of_srgb8(&image), - }; + let region = plan.keep.map_or((0, 0, w, h), |k| (k.x, k.y, k.w, k.h)); + let histogram = histogram(&mut cx, &out, w, region); lap("histogram", &mut t, &mut cx); // An entirely black result (upstream work that did not run would give that too): redo it on // the CPU, which costs time only for the rare photo that really is black. @@ -794,8 +863,9 @@ pub fn render( let overlay_mask = overlay_mask.or_else(|| { req.overlay.reads_detail().then(|| { let l = host.log_l.get_or_insert_with(|| Arc::new(cx.read_plane(&prep.log_l, w, h))).clone(); - let tex = prep.texture.as_deref().map(|b| cx.read_plane(b, w, h)); - lightcraft_pipeline::visualize::sharpen_plane(req.overlay, &plan.settings, &l, tex.as_ref(), plan.px_per_long) + let band = if local::pixel_sharpen(&plan.settings) { &prep.sharpen } else { &prep.texture }; + let blur = band.as_deref().map(|b| cx.read_plane(b, w, h)); + lightcraft_pipeline::visualize::sharpen_plane(req.overlay, &plan.settings, &l, blur.as_ref(), plan.px_per_long, plan.native_long as f64) })? }); lightcraft_pipeline::visualize::apply(&mut image, req.overlay, &plan, overlay_mask.as_ref(), all_overlay_alphas.as_deref()); @@ -803,7 +873,53 @@ pub fn render( if let Some(k) = plan.keep { image = image.crop(k.x, k.y, k.w, k.h); } - Some(Rendered { image, histogram, deep: None }) + Some(Output::Image(Rendered { image, histogram, deep: None })) +} + +/// The finished output `out` (`w × h` packed RGBA8) as a texture on the device, with its +/// histogram; the same checks as a readback (every pixel written, not entirely black), done on +/// the device: only the histogram and a pixel count come back. +fn to_texture(cx: &mut Cx<'_>, out: &Buf, w: usize, h: usize) -> Option<(DisplayFrame, Histogram)> { + let n = w * h; + let unwritten = cx.zeroed(1); + cx.run("unwritten", &[n as u32], &[Some(out), None, Some(&unwritten)], groups1(n)); + let histogram = histogram(cx, out, w, (0, 0, w, h)); + let left = cx.read::(&unwritten, 1).first().copied().unwrap_or(0); + if crate::ctx::failed() { + return None; + } + if left > 0 { + fail(FailKind::Fatal, format!("the GPU returned an incomplete image ({left} of {n} pixels unwritten)")); + return None; + } + if n >= 4096 && [&histogram.r, &histogram.g, &histogram.b].iter().all(|c| c.first() == Some(&histogram.total)) { + fail(FailKind::Blank, "the GPU result is entirely black; rendering it on the CPU to be sure".into()); + return None; + } + // texture copies take rows of a multiple of 256 bytes: pad them unless they already are + let stride = w.next_multiple_of(64); + let padded = (stride != w).then(|| { + let b = cx.gpu.buffer(stride * h); + cx.run("pad_rows", &[w as u32, h as u32, stride as u32], &[Some(out), Some(&b), None], groups2(w, h, [16, 16])); + b + }); + let texture = cx.gpu.device.create_texture(&wgpu::TextureDescriptor { + label: Some("lightcraft view"), + size: wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + // (COPY_SRC: a screenshot or a test can read it back) + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + cx.copy_to_texture(padded.as_ref().unwrap_or(out), stride, &texture, w, h); + cx.flush(); + if crate::ctx::failed() { + return None; + } + Some((DisplayFrame { texture, width: w, height: h }, histogram)) } /// Pixels whose alpha is not 255 (cheap: no early exit, so it vectorizes). @@ -816,8 +932,9 @@ fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, ho let (w, h) = (plan.w, plan.h); let n = w * h; let s = &*plan.settings; - let img = if lightcraft_pipeline::lin_needs_cpu(s, info) { - // defringe / spot removal / local tone mapping: CPU + let img = if lightcraft_pipeline::local_tone::enabled(info, s) { + // the camera's local tone mapping (ProRAW gain table, off by default): the whole + // scene-linear stage on the CPU let mut img = match host.sampled.take() { Some(i) => i, None => cx.read_rgb(sampled, w, h), @@ -825,11 +942,14 @@ fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, ho lightcraft_pipeline::lin_cpu(&mut img, info, plan); cx.gpu.upload(rgb_words(&img)) } else { + // `lin_cpu`'s order: white balance, defringe, spots, red eye let m = local::wb_matrix_for(info, s); let mut p = vec![m.is_some() as u32]; p.extend(m.unwrap_or_default().iter().flatten().map(|v| v.to_bits())); let out = cx.gpu.buffer(n * 3); map(cx, "wb_k", n, &p, [Some(sampled), None, None], &out); + let out = defringe(cx, out, plan); + let out = spots(cx, out, plan); if plan.eyes.is_empty() { out } else { @@ -843,6 +963,96 @@ fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, ho denoise(cx, img, plan) } +/// Defringe (`optics::defringe`) of the white-balanced image. +fn defringe(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf { + use lightcraft_pipeline::optics; + let Some(dp) = optics::defringe_params(&plan.settings, plan.px_per_long / optics::DEFRINGE_REF_LONG) else { return img }; + let (w, h) = (plan.w, plan.h); + let n = w * h; + let lab = cx.gpu.buffer(n * 3); + map(cx, "fringe_lab", n, &[], [Some(&img), None, None], &lab); + // the lightness channel, then its min and max around each pixel + let l = cx.gpu.buffer(n); + map(cx, "subsample", n, &[3], [Some(&lab), None, None], &l); + // (a radius past the image reads the same pixels as one at its size) + let r = dp.radius.min(w.max(h)) as u32; + let filtered = |cx: &mut Cx<'_>, max: u32| { + let tmp = cx.gpu.buffer(n); + cx.run("minmax", &[w as u32, h as u32, r, 0, max], &[Some(&l), Some(&tmp)], groups2(w, h, [16, 16])); + let out = cx.gpu.buffer(n); + cx.run("minmax", &[w as u32, h as u32, r, 1, max], &[Some(&tmp), Some(&out)], groups2(w, h, [16, 16])); + out + }; + let (lo, hi) = (filtered(cx, 0), filtered(cx, 1)); + // the kernel writes only the pixels it changes + let out = cx.copy(&img); + let p = [dp.purple.0, dp.purple.1, dp.green.0, dp.green.1, dp.purple_strength, dp.green_strength].map(f32::to_bits); + map(cx, "fringe_apply", n, &p, [Some(&lab), Some(&lo), Some(&hi)], &out); + out +} + +/// Spot removal (`spots::apply`), spot by spot on `img` in place: each spot reads the image as +/// the earlier ones left it. +fn spots(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf { + use lightcraft_pipeline::spots; + let (w, h) = (plan.w, plan.h); + for spot in &plan.settings.spots { + let Some(l) = spots::layout(spot, &plan.frame, w, h, plan.px_per_long) else { continue }; + let Some(&first) = l.pts.first() else { continue }; + let offset = match l.offset { + Some(o) => o, + None => auto_source(cx, &img, w, h, first, l.r), + }; + let pts = cx.gpu.upload(&l.pts.iter().flat_map(|p| [p.0, p.1]).collect::>()); + let nb = l.bw * l.bh; + let (al, sp, df, wt) = (cx.gpu.buffer(nb), cx.gpu.buffer(3 * nb), cx.gpu.buffer(3 * nb), cx.gpu.buffer(nb)); + let mut p = vec![w as u32, h as u32, l.bx as u32, l.by as u32, l.bw as u32, l.bh as u32, l.pts.len() as u32]; + p.extend([l.r, l.inner, l.opacity, offset.0, offset.1].map(f32::to_bits)); + p.push(l.heal as u32); + let groups = groups2(l.bw, l.bh, [16, 16]); + cx.run("spot_prep", &p, &[Some(&img), Some(&pts), Some(&al), Some(&sp), Some(&df), Some(&wt)], groups); + // Heal: the tone correction is the masked difference's normalized blur + let blurred = l.heal.then(|| { + let sigma = (l.r * 0.6).max(1.0); + (gaussian(cx, &df, l.bw, l.bh, 3, sigma), gaussian(cx, &wt, l.bw, l.bh, 1, sigma)) + }); + let (bd, bm) = blurred.as_ref().map_or((&df, &wt), |(d, m)| (d, m)); + cx.run("spot_apply", &p, &[Some(&img), Some(&pts), Some(&al), Some(&sp), Some(bd), Some(bm)], groups); + } + img +} + +/// `spots::auto_source` on the device: every candidate scored at once, the 48 scores read back. +fn auto_source(cx: &mut Cx<'_>, img: &Buf, w: usize, h: usize, target: (f32, f32), r: f32) -> (f32, f32) { + use lightcraft_pipeline::spots; + let cands = spots::candidates(r); + let mut data: Vec = cands.iter().flat_map(|d| [d.0, d.1]).collect(); + data.extend(spots::ring_dirs().iter().flat_map(|d| [d.0, d.1])); + let pts = cx.gpu.upload(&data); + let [around, within] = spots::score_radii(r); + let mut p = vec![w as u32, h as u32]; + p.extend([target.0, target.1].iter().chain(&around).chain(&within).map(|v| v.to_bits())); + let scores = cx.gpu.buffer(cands.len()); + cx.run("spot_score", &p, &[Some(img), Some(&pts), Some(&scores), None, None, None], [cands.len().div_ceil(64) as u32, 1, 1]); + let scores: Vec = cx.read(&scores, cands.len()); + spots::rank(&cands, &scores).first().copied().unwrap_or_else(|| spots::fallback_source(r)) +} + +/// The output's histogram (`Histogram::of_srgb8` of the `region` x, y, w, h of the `w`-wide +/// packed RGBA8 `out`, on the same sampling grid), counted on the device. +fn histogram(cx: &mut Cx<'_>, out: &Buf, w: usize, region: (usize, usize, usize, usize)) -> Histogram { + let (x0, y0, rw, rh) = region; + let step = (((rw * rh) as f64 / 1_000_000.0).sqrt().ceil() as usize).max(1); + let (nx, ny) = (rw.div_ceil(step), rh.div_ceil(step)); + let bins = cx.zeroed(4 * Histogram::BINS + 1); + let p = [w, x0, y0, nx, ny, step].map(|v| v as u32); + cx.run("histogram", &p, &[Some(out), Some(&bins)], groups2(nx, ny, [16, 16])); + let v: Vec = cx.read(&bins, 4 * Histogram::BINS + 1); + let part = |k: usize| v.get(k * Histogram::BINS..(k + 1) * Histogram::BINS).map_or_else(|| vec![0; Histogram::BINS], <[u32]>::to_vec); + // (SDR bins: an HDR edit's histogram is made after the render, `media::develop`) + Histogram { r: part(0), g: part(1), b: part(2), luma: part(3), total: v.get(4 * Histogram::BINS).copied().unwrap_or(0), hdr: None } +} + /// Noise reduction (`local::denoise`). fn denoise(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf { let (w, h) = (plan.w, plan.h); @@ -874,6 +1084,7 @@ struct Prep { base: Arc, clarity: Option>, texture: Option>, + sharpen: Option>, dark: Option>, /// Blurred chromaticity (local Moiré / Noise). chroma: Option>, @@ -884,7 +1095,7 @@ struct Prep { fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, planes: &mut Planes) -> Prep { let (w, h) = (plan.w, plan.h); let n = w * h; - let sig = local::plane_sigmas(&plan.settings, plan.px_per_long, req.quality); + let sig = local::plane_sigmas(&plan.settings, plan.px_per_long, plan.native_long as f64, req.quality); let log_l = match &planes.log_l { Some(b) => b.clone(), None => { @@ -904,6 +1115,7 @@ fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, pla }; let clarity = sig.clarity.map(|sg| plane_at(&mut planes.clarity, sg.to_bits(), || guided_fast(cx, &log_l, w, h, sg, local::CLARITY_EPS))); let texture = sig.texture.map(|sg| plane_at(&mut planes.texture, sg.to_bits(), || gaussian(cx, &log_l, w, h, 1, sg))); + let sharpen = sig.sharpen.map(|sg| plane_at(&mut planes.sharpen, local::sharpen_key(&plan.settings, sg), || gaussian_fir(cx, &log_l, w, h, sg))); let (dark, air) = match sig.dark { None => (None, 1.0), Some(sg) => match &planes.dark { @@ -931,7 +1143,7 @@ fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, pla gaussian(cx, &ch, w, h, 3, sg) }) }); - Prep { log_l, base, clarity, texture, dark, chroma, air } + Prep { log_l, base, clarity, texture, sharpen, dark, chroma, air } } /// Most brush dabs the mask kernel evaluates per pixel (more: the CPU rasterizes the brush). @@ -958,8 +1170,18 @@ fn brush_aux(dabs: &[&lightcraft_pipeline::masks::BrushDabs], erase: bool) -> Ve aux } -/// Cross guided filter (`masks::guided_cross`) of `p` steered by `guide`, max-combined with `p`. -fn guided_cross_max(cx: &mut Cx<'_>, guide: &Buf, p: &Buf, w: usize, h: usize, sigma: f32, eps: f32) -> Buf { +/// How [`guided_cross`] combines the filtered plane with its input. +#[derive(Clone, Copy)] +enum Combine { + /// The larger of the two (Auto Mask strokes). + Max, + /// The input moved towards the filtered plane by this much (Refine Edges). + Mix(f32), +} + +/// Cross guided filter (`masks::guided_cross`) of `p` steered by `guide`, combined with `p`. +#[allow(clippy::too_many_arguments)] +fn guided_cross(cx: &mut Cx<'_>, guide: &Buf, p: &Buf, w: usize, h: usize, sigma: f32, eps: f32, how: Combine) -> Buf { let n = w * h; let (m0, m1) = (cx.gpu.buffer(2 * n), cx.gpu.buffer(2 * n)); map(cx, "xguided_pre", n, &[0], [Some(guide), Some(p), None], &m0); @@ -969,7 +1191,11 @@ fn guided_cross_max(cx: &mut Cx<'_>, guide: &Buf, p: &Buf, w: usize, h: usize, s map(cx, "xguided_ab", n, &[eps.to_bits()], [Some(&b0), Some(&b1), None], &ab); let ab = gaussian(cx, &ab, w, h, 2, sigma); let q = cx.gpu.buffer(n); - map(cx, "xguided_apply", n, &[], [Some(guide), Some(&ab), Some(p)], &q); + let mode = match how { + Combine::Max => [0, 0], + Combine::Mix(k) => [1, k.to_bits()], + }; + map(cx, "xguided_apply", n, &mode, [Some(guide), Some(&ab), Some(p)], &q); q } @@ -1074,7 +1300,7 @@ fn masks(cx: &mut Cx<'_>, lin: &Buf, prep: &Prep, plan: &Plan<'_>, host: &mut Ho cx.run("shape", &q, &[Some(lin), Some(&prep.log_l), Some(&aux), Some(&stroke), Some(&brush)], groups2(w, h, [16, 16])); let refined = d.auto.then(|| { let (sigma, eps) = lightcraft_pipeline::masks::auto_refine(d.r); - guided_cross_max(cx, &prep.log_l, &stroke, w, h, sigma, eps) + guided_cross(cx, &prep.log_l, &stroke, w, h, sigma, eps, Combine::Max) }); let op = if d.erase { 2 } else { 1 }; cx.run( @@ -1120,6 +1346,15 @@ fn masks(cx: &mut Cx<'_>, lin: &Buf, prep: &Prep, plan: &Plan<'_>, host: &mut Ho let k = [n as u32, 0, mi as u32, op]; cx.run("combine", &k, &[None, None, None, Some(cbuf), Some(&alpha)], groups1(n)); } + if m.refine > 0.0 { + // Refine Edges (`masks::evaluate_one`): the combined alpha follows the photo's edges, + // before the mask's invert and amount + let k = (m.refine / 100.0).clamp(0.0, 1.0) as f32; + let sigma = (0.04 * frame.output_long(w, h) as f32 * k).max(1.0); + let plane = cx.slice(&alpha, mi * n, n); + let refined = guided_cross(cx, &prep.log_l, &plane, w, h, sigma, 0.02, Combine::Mix(k.sqrt())); + cx.copy_into(&refined, &alpha, mi * n); + } let amt = (m.adjust.amount / 100.0) as f32; cx.run( "finalize", @@ -1209,6 +1444,8 @@ mod tests { /// workgroup, windows wider than the image, and 1, 2 (as two planes) and 3 channels. #[test] fn gaussian_matches_cpu() { + // (creating the device writes the crash sentinel another test swaps out) + let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); use lightcraft_raster::blur; let Some(gpu) = crate::device() else { return }; let _scope = crate::ctx::RenderScope::new(gpu); @@ -1236,6 +1473,8 @@ mod tests { #[test] #[ignore] fn bench_kernels() { + // (creating the device writes the crash sentinel another test swaps out) + let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let Some(gpu) = crate::device() else { return }; let _scope = crate::ctx::RenderScope::new(gpu); let (w, h) = (6000, 4000); @@ -1273,6 +1512,31 @@ mod tests { time("guided sigma=1.75", &mut |cx| drop(guided(cx, &src, w, h, 1.75, 0.01))); } + /// The device scores Remove's candidate sources like the CPU and picks the same one. + #[test] + fn auto_source_picks_the_cpu_candidate() { + // (creating the device writes the crash sentinel another test swaps out) + let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(gpu) = crate::device() else { + let why = crate::unavailable_reason().unwrap_or_default(); + assert!(!why.contains("kernels failed to build"), "{why}"); + return; + }; + let _scope = crate::ctx::RenderScope::new(gpu); + let img = lightcraft_scenes::demo_library()[3].render(640, 427); + let buf = gpu.upload(rgb_words(&img)); + let mut differ = Vec::new(); + for (tx, ty, r) in [(25.6, 213.0, 19.2), (320.0, 192.0, 19.2), (100.0, 50.0, 12.0), (600.0, 400.0, 25.0), (320.0, 213.0, 6.0)] { + let mut cx = Cx::new(gpu); + let g = auto_source(&mut cx, &buf, img.width, img.height, (tx, ty), r); + let c = lightcraft_pipeline::spots::auto_source(&img, (tx, ty), r); + if g != c { + differ.push(((tx, ty, r), g, c)); + } + } + assert!(differ.is_empty(), "(target, gpu, cpu): {differ:?}"); + } + #[test] fn orient_map_matches_image_oriented() { use Orientation::*; diff --git a/crates/gpu/src/wgsl/blur.wgsl b/crates/gpu/src/wgsl/blur.wgsl index 375fb6d550..756457ade4 100644 --- a/crates/gpu/src/wgsl/blur.wgsl +++ b/crates/gpu/src/wgsl/blur.wgsl @@ -75,6 +75,43 @@ fn box_v(@builtin(global_invocation_id) g: vec3) { } } +// Square min (P[4] = 0) or max (1) filter of radius r, one axis at a time (`optics::min_filter`): +// clamped to the image, single channel. P: w, h, r, axis (0 horizontal, 1 vertical), max. +@compute @workgroup_size(16, 16) +fn minmax(@builtin(global_invocation_id) g: vec3) { + let w = pu(0u); + let h = pu(1u); + if (g.x >= w || g.y >= h) { + return; + } + let r = pu(2u); + let vertical = pu(3u) != 0u; + let is_max = pu(4u) != 0u; + let i = g.y * w + g.x; + var v = src[i]; + var lo = 0u; + var hi = 0u; + if (vertical) { + lo = g.y - min(g.y, r); + hi = min(g.y + r, h - 1u); + } else { + lo = g.x - min(g.x, r); + hi = min(g.x + r, w - 1u); + } + for (var k = lo; k <= hi; k++) { + var j = g.y * w + k; + if (vertical) { + j = k * w + g.x; + } + if (is_max) { + v = max(v, src[j]); + } else { + v = min(v, src[j]); + } + } + dst[i] = v; +} + // Separable median of a single-channel plane (`lightcraft_pipeline::local::median_hv`): 2r+1 // taps (r ≤ 24, clamped edges) along a row (median_h) or a column (median_v), one thread per // pixel. The median is a selection, so the result matches the CPU's bit for bit. diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl index 767ff44c99..9e589f4ca9 100644 --- a/crates/gpu/src/wgsl/finish.wgsl +++ b/crates/gpu/src/wgsl/finish.wgsl @@ -1,7 +1,7 @@ // The per-pixel stage: a straight port of `lightcraft_pipeline::finish` (keep in step with it). // Bindings: img (rgb, pre-exposure), log_l, base, clar, tex, dark, masks (NMASK planes, then the // blurred chromaticity when HAS_CHROMA), aux -// (tone LUT | chroma curve | sRGB LUT | curve LUTs | mask terms), out (packed RGBA8). +// (tone LUT | chroma curve | sRGB LUT | curve LUTs | mask terms | light operator tables), out (packed RGBA8). fn tone_apply(y: f32) -> f32 { if (y <= 0.0) { @@ -47,6 +47,56 @@ fn curve(ch: u32, x: f32) -> f32 { return aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * t; } +// Process V4's calibrated Contrast, Blacks (`lightcraft_pipeline::light_v3`): operator `k`'s +// table (linear output over encoded v) at v (`Operator::eval`). +fn light_eval(k: u32, v: f32) -> f32 { + let o = pu(F_LIGHT_OFF) + k * LIGHT_N; + let f = clamp(v, 0.0, 1.0) * f32(LIGHT_N - 1u); + let i = min(u32(f), LIGHT_N - 2u); + let t = f - f32(i); + return aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * t; +} + +// `Operator::channel`: one linear value; above 1 unchanged, below 0 shifted by F(0). +fn light_channel(k: u32, x: f32) -> f32 { + if (x > 1.0) { + return x; + } + if (x < 0.0) { + return aux[pu(F_LIGHT_OFF) + k * LIGHT_N] + x; + } + return light_eval(k, encode_srgb(x)); +} + +// `Operator::luminance`: scaled by F of the ProPhoto luminance over it. +fn light_lum(k: u32, p: vec3) -> vec3 { + let y = PRO_Y.x * p.x + PRO_Y.y * p.y + PRO_Y.z * p.z; + if (!(y > 1e-6) || y > 1.0) { + return p; + } + return p * (light_channel(k, y) / y); +} + +// `LightOps::apply`: linear Rec.2020 → ProPhoto, the operators in order, back. +fn light_ops(d: vec3) -> vec3 { + var p = mul3(PRO_FROM_2020, d); + let n = min(pu(F_LIGHT_OPS), 2u); + for (var k = 0u; k < n; k++) { + let mode = pu(F_LIGHT_MODE + k); + if (mode == 0u) { + p = vec3(light_channel(k, p.x), light_channel(k, p.y), light_channel(k, p.z)); + } else if (mode == 1u) { + p = light_lum(k, p); + } else { + let a = vec3(light_channel(k, p.x), light_channel(k, p.y), light_channel(k, p.z)); + let b = light_lum(k, p); + let w = pf(F_LIGHT_W + k); + p = vec3(w * a.x + (1.0 - w) * b.x, w * a.y + (1.0 - w) * b.y, w * a.z + (1.0 - w) * b.z); + } + } + return mul3(PRO_TO_2020, p); +} + fn band_weights(h: f32) -> array { var w: array; for (var i = 0u; i < 8u; i++) { @@ -230,8 +280,69 @@ fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { return a + (b - a) * v; } -fn enc8(v: f32) -> u32 { - return u32(clamp(v, 0.0, 1.0) * 255.0 + 0.5); +// The 3×3 matrix at parameter `o` (row-major). +fn mat_at(o: u32) -> array, 3> { + return array, 3>( + vec3(pf(o), pf(o + 1u), pf(o + 2u)), + vec3(pf(o + 3u), pf(o + 4u), pf(o + 5u)), + vec3(pf(o + 6u), pf(o + 7u), pf(o + 8u)), + ); +} + +// `finish::out_of_gamut`: needed real desaturation, and isn't a neutral clipping at white/black. +fn out_of_gamut(r: vec3, t: f32) -> bool { + let lo = min(r.x, min(r.y, r.z)); + let hi = max(r.x, max(r.y, r.z)); + return t < GAMUT_WARN && (hi - lo) > 0.02 * max(abs(hi), 1e-3) && hi - lo > 1e-3 && (lo < -1e-3 || (hi > 1.0 && lo < 1.0)); +} + +// `Lut3d::apply` (trilinear) on the LUT profile's table in `aux` (red fastest). +fn lut_at(r: u32, g: u32, b: u32) -> vec3 { + let n = pu(F_LUT_N); + let o = pu(F_LUT_OFF) + 3u * (r + n * (g + n * b)); + return vec3(aux[o], aux[o + 1u], aux[o + 2u]); +} + +fn lut_apply(c: vec3) -> vec3 { + let n = pu(F_LUT_N); + let s = f32(n - 1u); + var idx = vec3(0u); + var fr = vec3(0.0); + for (var k = 0u; k < 3u; k++) { + let lo = pf(F_LUT_MIN + k); + let span = max(pf(F_LUT_MAX + k) - lo, 1e-6); + let x = clamp((c[k] - lo) / span, 0.0, 1.0) * s; + let i = min(u32(floor(x)), n - 2u); + idx[k] = i; + fr[k] = x - f32(i); + } + let r = idx.x; + let g = idx.y; + let b = idx.z; + let c00 = mix(lut_at(r, g, b), lut_at(r + 1u, g, b), fr.x); + let c10 = mix(lut_at(r, g + 1u, b), lut_at(r + 1u, g + 1u, b), fr.x); + let c01 = mix(lut_at(r, g, b + 1u), lut_at(r + 1u, g, b + 1u), fr.x); + let c11 = mix(lut_at(r, g + 1u, b + 1u), lut_at(r + 1u, g + 1u, b + 1u), fr.x); + return mix(mix(c00, c10, fr.y), mix(c01, c11, fr.y), fr.z); +} + +const BAYER_8X8 = array( + 0.0, 32.0, 8.0, 40.0, 2.0, 34.0, 10.0, 42.0, + 48.0, 16.0, 56.0, 24.0, 50.0, 18.0, 58.0, 26.0, + 12.0, 44.0, 4.0, 36.0, 14.0, 46.0, 6.0, 38.0, + 60.0, 28.0, 52.0, 20.0, 62.0, 30.0, 54.0, 22.0, + 3.0, 35.0, 11.0, 43.0, 1.0, 33.0, 9.0, 41.0, + 51.0, 19.0, 59.0, 27.0, 49.0, 17.0, 57.0, 25.0, + 15.0, 47.0, 7.0, 39.0, 13.0, 45.0, 5.0, 37.0, + 63.0, 31.0, 55.0, 23.0, 61.0, 29.0, 53.0, 21.0, +); + +fn enc8(v: f32, d: f32) -> u32 { + let y = clamp(v, 0.0, 1.0) * 255.0; + if (y >= 254.9) { + return 255u; + } + return u32(clamp(y + d, 0.0, 255.0)); } // sRGB-curve-encoded value → the output space's own curve (`OutputTrc`: 0 sRGB, 1 gamma, 2 Rec.709). @@ -254,15 +365,6 @@ fn out_encode(v: f32) -> f32 { return 1.099 * pow(l, 0.45) - 0.099; } -// The 3×3 matrix stored row by row from field `o`. -fn mat_at(o: u32) -> array, 3> { - return array, 3>( - vec3(pf(o), pf(o + 1u), pf(o + 2u)), - vec3(pf(o + 3u), pf(o + 4u), pf(o + 5u)), - vec3(pf(o + 6u), pf(o + 7u), pf(o + 8u)), - ); -} - // `finish::gamut_map` (SDR): the chroma scale that brings `r` into 0..1 towards its luminance (1: in gamut) ... fn gamut_scale(r: vec3, luma: vec3) -> f32 { let yy = clamp(dot(luma, r), 0.0, 1.0); @@ -287,13 +389,6 @@ fn gamut_apply(r: vec3, luma: vec3, tg: f32) -> vec3 { return r; } -// `finish::out_of_gamut`: `r` needed desaturating by `t` to fit and isn't just a neutral beyond white or below black. -fn out_of_gamut(r: vec3, t: f32) -> bool { - let lo = min(r.x, min(r.y, r.z)); - let hi = max(r.x, max(r.y, r.z)); - return t < 0.995 && (hi - lo) > 0.02 * max(abs(hi), 1e-3) && hi - lo > 1e-3 && (lo < -1e-3 || (hi > 1.0 && lo < 1.0)); -} - @compute @workgroup_size(16, 16) fn main(@builtin(global_invocation_id) gid: vec3) { let w = pu(F_W); @@ -423,19 +518,28 @@ fn main(@builtin(global_invocation_id) gid: vec3) { delta += cl * 0.85 * det * (0.35 + 0.65 * mid); } let tx = pf(F_TEX) + lt[8]; - let sp = lt[13] * 0.6 + pf(F_SHARPEN); - if ((tx != 0.0 || sp != 0.0) && pu(F_HAS_TEX) != 0u) { + if (tx != 0.0 && pu(F_HAS_TEX) != 0u) { let det = l_pre - tex[i]; let tame = 1.0 - 0.6 * sstep(0.4, 1.6, abs(det)); delta += tx * 1.1 * clamp(det, -1.0, 1.0) * tame; - if (sp != 0.0) { - let sm = pf(F_SHARPEN_MASK); - var mk = 1.0; - if (sm > 0.0) { - mk = sstep(sm * 0.25, sm * 0.25 + 0.15, abs(det)); - } - delta += sp * 1.3 * clamp(det, -0.8, 0.8) * mk; + } + let sp = lt[13] * 0.6 + pf(F_SHARPEN); + if (pu(F_SHARPEN_V3) != 0u && sp != 0.0 && pu(F_HAS_SHP) != 0u) { + let det = l_pre - tex[pu(F_SHP_OFF) + i]; + let sm = pf(F_SHARPEN_MASK); + var mk = 1.0; + if (sm > 0.0) { + mk = sstep(sm * 0.1, sm * 0.1 + 0.06, abs(det)); } + delta += sp * pf(F_SHARPEN_GAIN) * 7.0 * mk * det / (1.0 + abs(det) / pf(F_SHARPEN_LIMIT)); + } else if (pu(F_SHARPEN_V3) == 0u && sp != 0.0 && pu(F_HAS_TEX) != 0u) { + let det = l_pre - tex[i]; + let sm = pf(F_SHARPEN_MASK); + var mk = 1.0; + if (sm > 0.0) { + mk = sstep(sm * 0.25, sm * 0.25 + 0.15, abs(det)); + } + delta += sp * 1.3 * clamp(det, -0.8, 0.8) * mk; } // local Noise: smooth (or, negative, boost) small-amplitude detail, keep edges if (l_noise != 0.0 && pu(F_HAS_TEX) != 0u) { @@ -468,6 +572,11 @@ fn main(@builtin(global_invocation_id) gid: vec3) { d = d + (o - d) * t; } + // --- process V4: calibrated Contrast, Blacks + if (pu(F_LIGHT_OPS) != 0u) { + d = light_ops(d); + } + // --- colour d = color_ops(d, lt[11], lt[12]); if (tint_on) { @@ -558,11 +667,18 @@ fn main(@builtin(global_invocation_id) gid: vec3) { let k = pf(F_GRAIN_AMT) * g * (0.35 + 2.6 * lum * (1.0 - lum)); e = e + k; } + if (pu(F_LUT) != 0u) { + let m = lut_apply(clamp(e, vec3(0.0), vec3(1.0))); + e = e + (m - e) * pf(F_LUT_AMT); + } if (warn == 1u) { - e = vec3(1.0, 0.0, 0.0); + e = vec3(PROOF_DEST_R, PROOF_DEST_G, PROOF_DEST_B); } else if (warn == 2u) { - e = vec3(0.0, 0.25, 1.0); + e = vec3(PROOF_DISP_R, PROOF_DISP_G, PROOF_DISP_B); } e = vec3(out_encode(e.x), out_encode(e.y), out_encode(e.z)); - out[i] = enc8(e.x) | (enc8(e.y) << 8u) | (enc8(e.z) << 16u) | (255u << 24u); + let abs_x = u32(pf(F_VIG_VIEW)) + x; + let abs_y = u32(pf(F_VIG_VIEW + 1u)) + y; + let dither = (BAYER_8X8[(abs_y & 7u) * 8u + (abs_x & 7u)] + 0.5) / 64.0; + out[i] = enc8(e.x, dither) | (enc8(e.y, dither) << 8u) | (enc8(e.z, dither) << 16u) | (255u << 24u); } diff --git a/crates/gpu/src/wgsl/gauss.wgsl b/crates/gpu/src/wgsl/gauss.wgsl new file mode 100644 index 0000000000..a3ad4e7234 --- /dev/null +++ b/crates/gpu/src/wgsl/gauss.wgsl @@ -0,0 +1,36 @@ +// Exact separable Gaussian with explicit taps over a one-channel plane (clamped edges); mirrors +// `lightcraft_raster::blur::gaussian_taps` (same taps, same accumulation order). +// P: w, h, r (taps has 2r+1 entries). Bindings: src, taps, dst. + +@compute @workgroup_size(16, 16) +fn gauss_h(@builtin(global_invocation_id) g: vec3) { + let w = pu(0u); + let h = pu(1u); + let r = i32(pu(2u)); + if (g.x >= w || g.y >= h) { + return; + } + let last = i32(w) - 1; + let row = g.y * w; + var acc = 0.0; + for (var k = 0; k <= 2 * r; k++) { + acc += src[row + u32(clamp(i32(g.x) + k - r, 0, last))] * taps[u32(k)]; + } + dst[row + g.x] = acc; +} + +@compute @workgroup_size(16, 16) +fn gauss_v(@builtin(global_invocation_id) g: vec3) { + let w = pu(0u); + let h = pu(1u); + let r = i32(pu(2u)); + if (g.x >= w || g.y >= h) { + return; + } + let last = i32(h) - 1; + var acc = 0.0; + for (var k = 0; k <= 2 * r; k++) { + acc += src[u32(clamp(i32(g.y) + k - r, 0, last)) * w + g.x] * taps[u32(k)]; + } + dst[g.y * w + g.x] = acc; +} diff --git a/crates/gpu/src/wgsl/hist.wgsl b/crates/gpu/src/wgsl/hist.wgsl new file mode 100644 index 0000000000..19d0a1a8e2 --- /dev/null +++ b/crates/gpu/src/wgsl/hist.wgsl @@ -0,0 +1,24 @@ +// The histogram (`Histogram::of_srgb8`) of a region of the packed RGBA8 output, on the same +// sampling grid: every STEP-th pixel of every STEP-th row. Bindings: px (packed RGBA8), bins +// (r | g | b | luma, 256 each, then the total; cleared beforehand). +// P: W (image width), X0, Y0 (region origin), NX, NY (sampled columns / rows), STEP. + +@compute @workgroup_size(16, 16) +fn histogram(@builtin(global_invocation_id) g: vec3) { + if (g.x >= pu(3u) || g.y >= pu(4u)) { + return; + } + let step = pu(5u); + let x = pu(1u) + g.x * step; + let y = pu(2u) + g.y * step; + let p = px[y * pu(0u) + x]; + let r = p & 255u; + let gg = (p >> 8u) & 255u; + let b = (p >> 16u) & 255u; + atomicAdd(&bins[r], 1u); + atomicAdd(&bins[256u + gg], 1u); + atomicAdd(&bins[512u + b], 1u); + let l = min((r * 54u + gg * 183u + b * 19u) >> 8u, 255u); + atomicAdd(&bins[768u + l], 1u); + atomicAdd(&bins[1024u], 1u); +} diff --git a/crates/gpu/src/wgsl/map.wgsl b/crates/gpu/src/wgsl/map.wgsl index fc8eebecfe..9b84b8d89d 100644 --- a/crates/gpu/src/wgsl/map.wgsl +++ b/crates/gpu/src/wgsl/map.wgsl @@ -105,14 +105,20 @@ fn xguided_ab(@builtin(global_invocation_id) g: vec3, @builtin(num_workgrou dst[2u * i + 1u] = mp - k * mi; } -// `max(p, clamp(a·guide + b, 0, 1))` (a: guide, b: blurred coefficients, c: the input p). +// q = clamp(a·guide + b, 0, 1) (a: guide, b: blurred coefficients, c: the input p), then +// P[1] = 0: max(p, q) (Auto Mask strokes); 1: p + (q − p)·P[2] (Refine Edges). @compute @workgroup_size(256) fn xguided_apply(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { let i = lin_index(g, nw); if (i >= pu(0u)) { return; } - dst[i] = max(c[i], clamp(b[2u * i] * a[i] + b[2u * i + 1u], 0.0, 1.0)); + let q = clamp(b[2u * i] * a[i] + b[2u * i + 1u], 0.0, 1.0); + if (pu(1u) == 0u) { + dst[i] = max(c[i], q); + } else { + dst[i] = c[i] + (q - c[i]) * pf(2u); + } } // White balance: 3×3 matrix (P[1] = has matrix, P[2..11] row-major), clamped at 0. @@ -226,3 +232,53 @@ fn redeye_k(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups } put_rgb(i, c); } + +// Defringe, first step (`optics::defringe`): OkLab of the clamped colour (a: image) → dst +// (lightness, a, b interleaved). +@compute @workgroup_size(256) +fn fringe_lab(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + put_rgb(i, oklab(max(rgb_a(i), vec3(0.0)))); +} + +// `optics::hue_weight`: membership of hue h (deg) in [lo, hi] with 8° shoulders. +fn hue_weight(h: f32, lo: f32, hi: f32) -> f32 { + let mid = (lo + hi) / 2.0; + let half = (hi - lo) / 2.0; + var d = abs(h - mid) % 360.0; + if (d > 180.0) { + d = 360.0 - d; + } + return 1.0 - sstep(half, half + 8.0, d); +} + +// Defringe, last step: desaturate fringe colours at edges (a: OkLab, b / c: lightness min / max +// around each pixel; dst: the image, written only where it changes, so it starts as a copy). +// P[1..7] = purple lo, hi, green lo, hi, purple strength, green strength. +@compute @workgroup_size(256) +fn fringe_apply(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + let edge = sstep(0.08, 0.25, c[i] - b[i]); + if (edge <= 0.0) { + return; + } + let lab = rgb_a(i); + let ch = sqrt(lab.y * lab.y + lab.z * lab.z); + let chroma_w = sstep(0.015, 0.05, ch); + if (chroma_w <= 0.0) { + return; + } + let hue = rem_euclid(degrees(atan2(lab.z, lab.y)), 360.0); + let k = max(pf(5u) * hue_weight(hue, pf(1u), pf(2u)), pf(6u) * hue_weight(hue, pf(3u), pf(4u))) * edge * chroma_w; + if (k <= 0.0) { + return; + } + let f = 1.0 - min(k, 1.0); + put_rgb(i, max(oklab_inv(vec3(lab.x, lab.y * f, lab.z * f)), vec3(0.0))); +} diff --git a/crates/gpu/src/wgsl/present.wgsl b/crates/gpu/src/wgsl/present.wgsl new file mode 100644 index 0000000000..6d586c7fad --- /dev/null +++ b/crates/gpu/src/wgsl/present.wgsl @@ -0,0 +1,24 @@ +// Handing a finished render to the window without a readback (`render::present`). +// Bindings: px (packed RGBA8 output), dst (packed RGBA8, padded rows), count (one atomic word). + +// Pixels whose alpha is not 255: work that never ran (the readback's `unwritten`). P[0] = pixels. +@compute @workgroup_size(256) +fn unwritten(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + if ((px[i] >> 24u) != 255u) { + atomicAdd(&count[0], 1u); + } +} + +// Rows of P[0] pixels (P[1] rows) re-laid at a stride of P[2] pixels (texture copies take rows of a +// multiple of 256 bytes). +@compute @workgroup_size(16, 16) +fn pad_rows(@builtin(global_invocation_id) g: vec3) { + if (g.x >= pu(0u) || g.y >= pu(1u)) { + return; + } + dst[g.y * pu(2u) + g.x] = px[g.y * pu(0u) + g.x]; +} diff --git a/crates/gpu/src/wgsl/spot.wgsl b/crates/gpu/src/wgsl/spot.wgsl new file mode 100644 index 0000000000..8151d1d5e9 --- /dev/null +++ b/crates/gpu/src/wgsl/spot.wgsl @@ -0,0 +1,177 @@ +// Spot removal (`lightcraft_pipeline::spots::apply`), one spot at a time, on the image in place. +// Bindings: img (rgb, read-write), pts (f32 data: see each kernel), al / sp / df / wt (work buffers +// over the spot's box: alpha, source patch, masked difference, weights). +// +// Parameters of spot_prep / spot_apply: W, H, BX, BY, BW, BH, NPTS, R, INNER, OPACITY, OFFX, OFFY, +// HEAL. `pts`: the stroke's points (x, y; output pixels). + +// `f32::MAX` exactly ("doesn't fit", as the CPU's score; a decimal literal may round below it, +// and naga can't evaluate bitcast in a const). +fn f32_max() -> f32 { + return bitcast(0x7f7fffffu); +} + +// `Rgb32f::get_clamped`. +fn px_at(x: i32, y: i32) -> vec3 { + let w = i32(pu(0u)); + let h = i32(pu(1u)); + let i = u32(clamp(y, 0, h - 1) * w + clamp(x, 0, w - 1)); + return vec3(img[3u * i], img[3u * i + 1u], img[3u * i + 2u]); +} + +// `Rgb32f::sample_bilinear` (pixel centres at +0.5). +fn bilinear(x: f32, y: f32) -> vec3 { + let fx = x - 0.5; + let fy = y - 0.5; + let x0 = floor(fx); + let y0 = floor(fy); + let tx = fx - x0; + let ty = fy - y0; + let ix = i32(x0); + let iy = i32(y0); + let a = px_at(ix, iy); + let b = px_at(ix + 1, iy); + let c = px_at(ix, iy + 1); + let d = px_at(ix + 1, iy + 1); + let top = a + (b - a) * tx; + let bot = c + (d - c) * tx; + return top + (bot - top) * ty; +} + +// `spots::smooth`, defined for e1 ≤ e0 as the step at e1 (no feather). +fn spot_smooth(e0: f32, e1: f32, x: f32) -> f32 { + if (e1 <= e0) { + return select(0.0, 1.0, x >= e1); + } + return sstep(e0, e1, x); +} + +// Alpha, source patch and (Heal) the difference outside the stroke, over the box. +@compute @workgroup_size(16, 16) +fn spot_prep(@builtin(global_invocation_id) gid: vec3) { + let bw = pu(4u); + let bh = pu(5u); + if (gid.x >= bw || gid.y >= bh) { + return; + } + let i = gid.y * bw + gid.x; + let gx = pu(2u) + gid.x; + let gy = pu(3u) + gid.y; + let px = f32(gx) + 0.5; + let py = f32(gy) + 0.5; + var d = f32_max(); + for (var k = 0u; k < pu(6u); k++) { + let ex = px - pts[2u * k]; + let ey = py - pts[2u * k + 1u]; + d = min(d, sqrt(ex * ex + ey * ey)); + } + let alpha = (1.0 - spot_smooth(pf(8u), pf(7u), d)) * pf(9u); + al[i] = alpha; + let s = bilinear(px + pf(10u), py + pf(11u)); + sp[3u * i] = s.x; + sp[3u * i + 1u] = s.y; + sp[3u * i + 2u] = s.z; + let gi = gy * pu(0u) + gx; + let t = vec3(img[3u * gi], img[3u * gi + 1u], img[3u * gi + 2u]); + let outside = select(0.0, 1.0, alpha < 0.02); + let m = (t - s) * outside; + df[3u * i] = m.x; + df[3u * i + 1u] = m.y; + df[3u * i + 2u] = m.z; + wt[i] = outside; +} + +// Blend the (healed) patch into the image (df, wt: the blurred difference and weights). +@compute @workgroup_size(16, 16) +fn spot_apply(@builtin(global_invocation_id) gid: vec3) { + let bw = pu(4u); + let bh = pu(5u); + if (gid.x >= bw || gid.y >= bh) { + return; + } + let i = gid.y * bw + gid.x; + let a = al[i]; + if (a <= 0.0) { + return; + } + var v = vec3(sp[3u * i], sp[3u * i + 1u], sp[3u * i + 2u]); + if (pu(12u) != 0u) { + let m = max(wt[i], 1e-4); + v = v + vec3(df[3u * i] / m, df[3u * i + 1u] / m, df[3u * i + 2u] / m); + } + let gi = (pu(3u) + gid.y) * pu(0u) + pu(2u) + gid.x; + let t = vec3(img[3u * gi], img[3u * gi + 1u], img[3u * gi + 2u]); + let o = max(t + (v - t) * a, vec3(0.0)); + img[3u * gi] = o.x; + img[3u * gi + 1u] = o.y; + img[3u * gi + 2u] = o.z; +} + +// `spots::ring_stats`: sample k (spoke-major, 3 radii each) of the rings around c, or a NaN-free +// flag in .w = 0 when it falls outside the image. +fn ring_sample(c: vec2, k: u32, radii: u32) -> vec4 { + let spoke = k / 3u; + let rr = pf(radii + k % 3u); + let o = 2u * NCAND + 2u * spoke; + let x = c.x + pts[o] * rr; + let y = c.y + pts[o + 1u] * rr; + if (x < 0.0 || y < 0.0 || x >= f32(pu(0u)) || y >= f32(pu(1u))) { + return vec4(0.0); + } + return vec4(bilinear(x, y), 1.0); +} + +fn ring_fits(c: vec2, radii: u32) -> bool { + for (var k = 0u; k < 72u; k++) { + if (ring_sample(c, k, radii).w == 0.0) { + return false; + } + } + return true; +} + +fn sq(v: f32) -> f32 { + return sqrt(max(v, 0.0)); +} + +// `spots::score` of every candidate source (one invocation each) into `al`. +// Parameters: W, H, TX, TY, then the surroundings' radii (3) and the inside's (3). +// `pts`: NCAND candidate offsets (x, y), then the 24 spoke directions (cos, sin). +@compute @workgroup_size(64) +fn spot_score(@builtin(global_invocation_id) gid: vec3) { + let j = gid.x; + if (j >= NCAND) { + return; + } + let tgt = vec2(pf(2u), pf(3u)); + let src = tgt + vec2(pts[2u * j], pts[2u * j + 1u]); + if (!ring_fits(tgt, 4u) || !ring_fits(src, 4u)) { + al[j] = f32_max(); + return; + } + var s = 0.0; + for (var k = 0u; k < 72u; k++) { + let p = ring_sample(tgt, k, 4u).xyz; + let q = ring_sample(src, k, 4u).xyz; + for (var c = 0u; c < 3u; c++) { + let u = sq(p[c]); + let v = sq(q[c]); + s += (u - v) * (u - v); + } + } + if (ring_fits(src, 7u)) { + var mean_a = 0.0; + for (var k = 0u; k < 72u; k++) { + mean_a += sq(ring_sample(tgt, k, 4u).y); + } + mean_a = mean_a / 72.0; + var var_ = 0.0; + for (var k = 0u; k < 72u; k++) { + let e = sq(ring_sample(src, k, 7u).y) - mean_a; + var_ += e * e; + } + var_ = var_ / 72.0; + s += var_ * 72.0 * 0.5; + } + al[j] = s; +} diff --git a/crates/gpu/tests/display.rs b/crates/gpu/tests/display.rs new file mode 100644 index 0000000000..525743b9fb --- /dev/null +++ b/crates/gpu/tests/display.rs @@ -0,0 +1,80 @@ +//! Renders handed to the window as textures (`render_display` on an adopted device): the texture +//! holds exactly the pixels a readback render returns, the histogram matches, and what can't be a +//! texture (overlays, a window grown by spots) comes back as pixels. Own process: adopting a +//! device is once per process. Skips (passes with a note) without an adapter. + +use std::sync::Arc; + +use lightcraft_develop::{DevelopSettings, Spot}; +use lightcraft_geom::Point; +use lightcraft_gpu::{Output, wgpu}; +use lightcraft_pipeline::{Overlay, PixelWindow, Quality, RenderRequest, SourceInfo, StageCache}; + +/// A device made the way eframe makes the window's (adapter limits, the window's backends). +fn window_device() -> Option<(wgpu::Device, wgpu::Queue, wgpu::AdapterInfo)> { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = lightcraft_gpu::backend::window_backends(); + desc.backend_options = lightcraft_gpu::backend::backend_options(); + let instance = wgpu::Instance::new(desc); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; + let info = adapter.get_info(); + let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + label: Some("test window"), + required_limits: adapter.limits(), + ..Default::default() + })) + .ok()?; + Some((device, queue, info)) +} + +#[test] +fn display_renders_match_readback_renders() { + // switched off for the process (`LIGHTCRAFT_GPU=0`): there is no device to adopt + if let Some(reason) = lightcraft_gpu::env_off_reason() { + lightcraft_testkit::skip!(Gpu, "{reason}"); + return; + } + let Some((device, queue, info)) = window_device() else { + lightcraft_testkit::skip!(Gpu, "no GPU adapter"); + return; + }; + if info.device_type == wgpu::DeviceType::Cpu { + lightcraft_testkit::skip!(Gpu, "software adapter"); + return; + } + lightcraft_gpu::adopt_window_device(device.clone(), queue.clone(), info).expect("adopted"); + assert!(lightcraft_gpu::on_window_device()); + let raw = SourceInfo { raw: true, ..Default::default() }; + let mut s = DevelopSettings::default(); + s.light.exposure = 0.5; + s.light.highlights = -40.0; + s.effects.clarity = 20.0; + s.detail.nr_luminance = 20.0; + s.grain.amount = 20.0; + // widths that are and aren't a multiple of 64 texels (row padding), draft and full quality + for (w, h, quality) in [(640, 427, Quality::Full), (1000, 667, Quality::Draft), (1024, 683, Quality::Full)] { + let src = Arc::new(lightcraft_scenes::demo_library()[0].render(w, h)); + let req = RenderRequest { quality, ..RenderRequest::fit(w, h) }; + let stages = StageCache::default(); + let pixels = lightcraft_gpu::render(&src, &raw, &s, &req, Some(&stages)).expect("gpu render"); + match lightcraft_gpu::render_display(&src, &raw, &s, &req, Some(&stages)).expect("display render") { + Output::Display { frame, histogram } => { + assert_eq!((frame.width, frame.height), (pixels.image.width, pixels.image.height)); + let shown = lightcraft_gpu::read_texture(&device, &queue, &frame.texture, frame.width, frame.height).expect("readback"); + assert!(shown.data == pixels.image.data, "{w}×{h}: the texture holds the readback's pixels"); + assert_eq!(histogram, pixels.histogram); + } + Output::Image(_) => panic!("{w}×{h}: expected a texture"), + } + } + // overlays are drawn on the CPU, and a window that spots grew is cut there: pixels + let src = Arc::new(lightcraft_scenes::demo_library()[0].render(3000, 2000)); + let req = RenderRequest { overlay: Overlay::Spots(50), ..RenderRequest::fit(800, 800) }; + assert!(matches!(lightcraft_gpu::render_display(&src, &raw, &s, &req, None), Some(Output::Image(_))), "overlay"); + s.spots = vec![Spot { points: vec![Point::new(0.5, 0.5)], size: 0.02, source_offset: Some(Point::new(0.15, 0.0)), ..Default::default() }]; + let req = RenderRequest { window: Some(PixelWindow { x: 1200, y: 800, w: 500, h: 400 }), ..RenderRequest::fit(3000, 2000) }; + match lightcraft_gpu::render_display(&src, &raw, &s, &req, None) { + Some(Output::Image(r)) => assert_eq!((r.image.width, r.image.height), (500, 400)), + _ => panic!("a grown window comes back as pixels"), + } +} diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 61f5b874ae..7a21768de1 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -20,11 +20,58 @@ const MAX_LSB: u8 = 3; fn gpu() -> bool { let ok = lightcraft_gpu::available(); if !ok { + let why = lightcraft_gpu::unavailable_reason().unwrap_or_default(); + // no adapter (CI) skips; an adapter whose kernels don't build is a bug in them + assert!(!why.contains("kernels failed to build"), "{why}"); lightcraft_testkit::skip!(Gpu, "no GPU adapter"); } + // which card the comparisons ran on (`LIGHTCRAFT_GPU_ADAPTER` picks one on a machine with two) + static NAMED: std::sync::Once = std::sync::Once::new(); + NAMED.call_once(|| eprintln!("GPU equivalence tests on {}", lightcraft_gpu::adapter_name().unwrap_or_default())); ok } +fn check_v3_luminance_cutoff(chroma: f32, pixel: [f32; 3], expected: [u8; 4]) { + if !gpu() { + return; + } + // These uniform nonnegative sources expose cancellation after camera chroma scaling + // and Contrast, just below the positive Blacks luminance cutoff. + let curve = lightcraft_pipeline::tone::CameraTone::new(std::array::from_fn(|i| { + let x = (i + 1) as f32 / 33.0; + [x, x] + })) + .unwrap() + .with_chroma([chroma; 8]) + .unwrap(); + let info = SourceInfo { raw: true, camera_tone: Some(curve), ..Default::default() }; + let src = Arc::new(Rgb32f::filled(64, 64, pixel)); + let mut s = DevelopSettings { process: Process::V4.version(), ..Default::default() }; + s.light.contrast = 100.0; + s.light.blacks = 80.0; + let req = RenderRequest::fit(64, 64); + let cpu = render(&src, &info, &s, &req).image; + let gpu = lightcraft_gpu::try_render(&src, &info, &s, &req, None).expect("GPU render without CPU fallback").image; + for image in [&cpu, &gpu] { + assert!(image.data.iter().all(|p| *p == image.data[0])); + for (actual, expected) in image.data[0].into_iter().zip(expected) { + assert!(actual.abs_diff(expected) <= 1, "chroma {chroma}: {:?}, expected {expected}", image.data[0]); + } + } + let (_, max, _) = diff(&cpu, &gpu); + assert!(max <= 1, "chroma {chroma}: CPU {:?}, GPU {:?}", cpu.data[0], gpu.data[0]); +} + +#[test] +fn v3_luminance_cutoff_chroma_2() { + check_v3_luminance_cutoff(2.0, [0.023_433_316, 0.000_071_107_73, 0.005_175_675], [27, 0, 8, 255]); +} + +#[test] +fn v3_luminance_cutoff_chroma_4() { + check_v3_luminance_cutoff(4.0, [0.035_338_085, 0.000_048_468_723, 0.010_193_758], [47, 0, 19, 255]); +} + #[test] fn camera_tone_and_relative_wb() { if !gpu() { @@ -236,6 +283,33 @@ fn cases() -> Vec<(&'static str, Edit)> { s.effects.clarity = -60.0; s.effects.texture = -40.0; }), + ("sharpen radius 2.5 detail 100", |s| { + s.detail.sharpen_amount = 100.0; + s.detail.sharpen_radius = 2.5; + s.detail.sharpen_detail = 100.0; + }), + ("sharpen radius 0.6 detail 0", |s| { + s.detail.sharpen_amount = 80.0; + s.detail.sharpen_radius = 0.6; + s.detail.sharpen_detail = 0.0; + }), + ("sharpen + texture + masking", |s| { + s.detail.sharpen_amount = 70.0; + s.detail.sharpen_masking = 30.0; + s.effects.texture = 40.0; + }), + ("local sharpness", |s| { + s.masks = vec![Mask { + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Linear { start: Point::new(0.5, 0.0), end: Point::new(0.5, 0.6) }, + }], + adjust: lightcraft_develop::LocalAdjustments { sharpness: 80.0, ..Default::default() }, + ..Default::default() + }]; + }), ("sharpen masking", |s| { s.detail.sharpen_amount = 90.0; s.detail.sharpen_masking = 60.0; @@ -417,7 +491,7 @@ fn cases() -> Vec<(&'static str, Edit)> { s.calibration.blue_sat = 60.0; s.calibration.blue_hue = 25.0; }), - ("spots + defringe (cpu stage)", |s| { + ("spots + defringe", |s| { s.spots = vec![Spot { points: vec![Point::new(0.3, 0.3)], size: 0.03, source_offset: Some(Point::new(0.1, 0.0)), ..Default::default() }]; s.optics.defringe_purple_amount = 5.0; }), @@ -616,6 +690,67 @@ fn cached_renders_match_uncached() { } } +/// Calibrated Contrast and Blacks, legacy Whites, combined edits, windows and cache reuse. +#[test] +fn light_v3_operators_match() { + if !gpu() { + return; + } + let src = scene(0, 960, 640); + let curve = lightcraft_pipeline::tone::CameraTone::new(std::array::from_fn(|i| { + let x = 0.004 * 1.18f32.powi(i as i32); + [x, 1.0 - (-2.0 * x).exp()] + })) + .unwrap() + .with_chroma([1.3, 1.2, 1.1, 1.0, 0.9, 0.7, 0.5, 0.4]) + .unwrap(); + let info = SourceInfo { raw: true, camera_tone: Some(curve), ..Default::default() }; + let req = RenderRequest::fit(720, 720); + for id in ["light.contrast", "light.whites", "light.blacks"] { + for v in [-100.0, -50.0, 50.0, 100.0] { + let mut s = DevelopSettings::default(); + assert_eq!(s.process.process(), Process::V4); + lightcraft_develop::controls::set(&mut s, id, v); + check(&format!("V4 {id} {v}"), &src, &info, &s, &req); + if id == "light.whites" { + let mut old = s.clone(); + old.process = Process::V2.version(); + assert_eq!( + lightcraft_gpu::render(&src, &info, &s, &req, None).unwrap().image, + lightcraft_gpu::render(&src, &info, &old, &req, None).unwrap().image + ); + } + } + } + let mut s = DevelopSettings::default(); + typical(&mut s); + s.light.contrast = 35.0; + s.light.whites = 40.0; + s.light.blacks = -30.0; + check("V4 combined, typical", &src, &info, &s, &req); + s.color.vibrance = 30.0; + s.vignette.amount = -20.0; + check("V4 combined, colour", &src, &info, &s, &req); + use lightcraft_pipeline::PixelWindow; + let win = RenderRequest { window: Some(PixelWindow { x: 1200, y: 800, w: 640, h: 480 }), ..RenderRequest::fit(3000, 2000) }; + check("V4 combined, window", &src, &info, &s, &win); + s.hdr.enabled = true; + s.hdr.max_ev = 2.0; + check("V4 HDR preview", &src, &info, &s, &req); + // High-bit-depth exports use the CPU; the GPU kernel writes 8-bit previews. + let hdr_req = RenderRequest { depth: lightcraft_pipeline::OutputDepth::F32Hdr, ..req }; + assert_eq!(lightcraft_gpu::try_render(&src, &info, &s, &hdr_req, None).err(), Some(lightcraft_gpu::Fallback::NotTried)); + s.hdr.enabled = false; + let cache = StageCache::default(); + for k in 0..3 { + s.light.exposure = 0.3 * k as f64; + let warm = lightcraft_gpu::render(&src, &info, &s, &req, Some(&cache)).expect("gpu"); + let fresh = lightcraft_gpu::render(&src, &info, &s, &req, None).expect("gpu"); + assert_eq!(warm.image, fresh.image, "exposure step {k}"); + check(&format!("V4 exposure step {k}"), &src, &info, &s, &req); + } +} + /// Issue #632: the Highlights / Shadows base of each process (V1: the edge-aware filter of log /// luminance; V2: of its fine median, a radius that grows with the render) matches the CPU's, and /// a warm cache never hands one process the other's base. @@ -648,7 +783,7 @@ fn highlights_shadows_base_matches_on_every_process() { }]; check(&format!("{p:?} local highlights {w}"), &src, &raw, &s, &req); } - for p in [Process::V1, Process::V2, Process::V1, Process::V2] { + for p in [Process::V1, Process::V2, Process::V4, Process::V1, Process::V2, Process::V4] { let mut s = DevelopSettings { process: p.version(), ..DevelopSettings::default() }; s.light.highlights = -100.0; let warm = lightcraft_gpu::render(&src, &raw, &s, &req, Some(&cache)).expect("gpu"); @@ -658,6 +793,30 @@ fn highlights_shadows_base_matches_on_every_process() { } } +#[test] +fn sharpening_matches_each_process_and_reduced_source() { + if !gpu() { + return; + } + let src = scene(0, 256, 192); + let info = SourceInfo { raw: true, native_long: Some(1024), ..Default::default() }; + let req = RenderRequest::fit(128, 128); + let cache = StageCache::default(); + for process in [Process::V1, Process::V2, Process::V3, Process::V2, Process::V3] { + let mut s = DevelopSettings { process: process.version(), ..Default::default() }; + s.detail.sharpen_amount = 80.0; + s.detail.sharpen_radius = 2.0; + s.detail.sharpen_detail = 75.0; + for nr in [0.0, 50.0, 20.0] { + s.detail.nr_luminance = nr; + check(&format!("{process:?} sharpening NR {nr}"), &src, &info, &s, &req); + let warm = lightcraft_gpu::render(&src, &info, &s, &req, Some(&cache)).expect("gpu"); + let fresh = lightcraft_gpu::render(&src, &info, &s, &req, None).expect("gpu"); + assert_eq!(warm.image, fresh.image, "{process:?} NR {nr}"); + } + } +} + #[test] fn overlays_match() { if !gpu() { @@ -797,7 +956,7 @@ fn red_eye_matches() { spots: vec![Spot { points: vec![Point::new(0.1, 0.2)], size: 0.02, source_offset: Some(Point::new(0.05, 0.0)), ..Default::default() }], ..Default::default() }; - check("red eye + spot (cpu stage)", &src, &info, &s, &RenderRequest::fit(600, 600)); + check("red eye + spot", &src, &info, &s, &RenderRequest::fit(600, 600)); } fn saturated(s: &mut DevelopSettings) { @@ -956,6 +1115,89 @@ fn windows_of_a_big_photo_share_one_uploaded_source() { assert_eq!(lightcraft_gpu::source_uploads() - start, 2); } +/// A non-trivial 3D LUT (cross-process look: lifted blacks, warm highlights, swapped-ish blues). +fn look_lut(n: usize, domain_max: f32) -> lightcraft_pipeline::lut::Lut3d { + let mut data = Vec::with_capacity(n * n * n); + for b in 0..n { + for g in 0..n { + for r in 0..n { + let c = [r, g, b].map(|v| v as f32 / (n - 1) as f32 * domain_max); + data.push([ + (0.06 + 0.9 * c[0].powf(0.9) + 0.05 * c[2]).min(1.0), + (0.04 + 0.92 * c[1] * (1.0 - 0.1 * c[2])).min(1.0), + (0.1 + 0.6 * c[2] + 0.2 * c[0] * c[1]).min(1.0), + ]); + } + } + } + lightcraft_pipeline::lut::Lut3d { size: n, data, domain_min: [0.0; 3], domain_max: [domain_max; 3], title: None } +} + +/// LUT profiles render on the GPU (the table is applied after grain, blended by the amount). +#[test] +fn lut_profiles_match() { + if !gpu() { + return; + } + let src = scene(1, 900, 600); + let raw = SourceInfo { raw: true, ..Default::default() }; + lightcraft_pipeline::lut::register("lut:gpu-test-17", look_lut(17, 1.0)); + lightcraft_pipeline::lut::register("lut:gpu-test-domain", look_lut(9, 1.2)); + for (id, amount) in [("lut:gpu-test-17", 100.0), ("lut:gpu-test-17", 160.0), ("lut:gpu-test-domain", 60.0)] { + for (name, edit) in [("default", (|_| {}) as Edit), ("saturated + curves + grain", saturated as Edit)] { + let mut s = DevelopSettings::default(); + edit(&mut s); + s.profile.id = id.into(); + s.profile.amount = amount; + check(&format!("{id} {amount} {name}"), &src, &raw, &s, &RenderRequest::fit(640, 640)); + } + } +} + +/// Refine Edges on a mask is the cross guided filter on the device, blended by √refine. +#[test] +fn refine_edges_match() { + if !gpu() { + return; + } + let src = scene(0, 900, 600); + let raw = SourceInfo { raw: true, ..Default::default() }; + for refine in [15.0, 60.0, 100.0] { + let mut s = DevelopSettings::default(); + typical(&mut s); + s.masks = vec![ + Mask { + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Radial { center: Point::new(0.45, 0.55), rx: 0.3, ry: 0.2, angle: 10.0, feather: 30.0, invert: false }, + }], + adjust: lightcraft_develop::LocalAdjustments { exposure: 0.9, saturation: -30.0, ..Default::default() }, + refine, + ..Default::default() + }, + Mask { + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Linear { start: Point::new(0.5, 0.0), end: Point::new(0.5, 0.5) }, + }], + adjust: lightcraft_develop::LocalAdjustments { exposure: -0.7, amount: 70.0, ..Default::default() }, + refine: refine / 2.0, + invert: true, + ..Default::default() + }, + ]; + check(&format!("refine edges {refine}"), &src, &raw, &s, &RenderRequest::fit(640, 640)); + let gpu = |s: &DevelopSettings| lightcraft_gpu::render(&src, &raw, s, &RenderRequest::fit(640, 640), None).expect("gpu render").image; + let unrefined = DevelopSettings { masks: s.masks.iter().map(|m| Mask { refine: 0.0, ..m.clone() }).collect(), ..s.clone() }; + // (a light refine barely moves a soft radial edge; a strong one visibly does) + assert!(refine < 50.0 || diff(&gpu(&s), &gpu(&unrefined)).1 > 3, "refine {refine} changes the mask"); + } +} + #[test] fn soft_proofs_match() { if !gpu() { @@ -1006,3 +1248,96 @@ fn soft_proofs_match() { }; assert!(lightcraft_gpu::render(&src, &raw, &DevelopSettings::default(), &req, None).is_none(), "declined: the CPU renders it"); } + +/// Spot removal on the device: Clone, Heal and Remove (automatic source, scored on the device), +/// brushed strokes, overlapping spots (each reads what the earlier ones left), feather 0 and +/// spots cut by the image edge. +#[test] +fn spots_match() { + if !gpu() { + return; + } + use lightcraft_develop::SpotMode; + let src = scene(3, 900, 600); + let raw = SourceInfo { raw: true, ..Default::default() }; + let spot = |mode, pts: &[(f64, f64)], size, feather, off: Option<(f64, f64)>| Spot { + mode, + points: pts.iter().map(|p| Point::new(p.0, p.1)).collect(), + size, + feather, + opacity: 100.0, + source_offset: off.map(|o| Point::new(o.0, o.1)), + }; + let sets: Vec<(&str, Vec)> = vec![ + ("clone", vec![spot(SpotMode::Clone, &[(0.3, 0.4)], 0.04, 40.0, Some((0.15, 0.05)))]), + ("heal", vec![spot(SpotMode::Heal, &[(0.6, 0.5)], 0.05, 60.0, Some((-0.12, 0.1)))]), + ("remove (auto source)", vec![spot(SpotMode::Remove, &[(0.5, 0.45)], 0.03, 50.0, None)]), + ("remove near the edge (auto)", vec![spot(SpotMode::Remove, &[(0.04, 0.5)], 0.03, 50.0, None)]), + ("brushed heal stroke", vec![spot(SpotMode::Heal, &[(0.2, 0.7), (0.3, 0.72), (0.4, 0.69)], 0.02, 30.0, Some((0.0, -0.15)))]), + ("feather 0, half opacity", vec![Spot { opacity: 50.0, ..spot(SpotMode::Clone, &[(0.7, 0.3)], 0.04, 0.0, Some((-0.2, 0.0))) }]), + ("cut by the edge", vec![spot(SpotMode::Heal, &[(0.99, 0.02)], 0.05, 50.0, Some((-0.2, 0.2)))]), + ( + "overlapping, auto after manual", + vec![ + spot(SpotMode::Clone, &[(0.45, 0.5)], 0.04, 50.0, Some((0.1, 0.0))), + spot(SpotMode::Remove, &[(0.47, 0.52)], 0.04, 50.0, None), + spot(SpotMode::Heal, &[(0.5, 0.5)], 0.03, 70.0, Some((0.0, 0.12))), + ], + ), + ]; + for (name, spots) in sets { + let mut s = DevelopSettings::default(); + typical(&mut s); + s.spots = spots; + check(&format!("spots: {name}"), &src, &raw, &s, &RenderRequest::fit(640, 640)); + } +} + +/// Defringe on the device: purple and green at several amounts and hue ranges, at preview and +/// full size (its filter radius follows the output size). +#[test] +fn defringe_matches() { + if !gpu() { + return; + } + let src = scene(1, 1800, 1200); + let raw = SourceInfo { raw: true, ..Default::default() }; + for (purple, green, hue) in [(4.0, 0.0, (30.0, 70.0)), (0.0, 10.0, (20.0, 80.0)), (20.0, 15.0, (0.0, 100.0))] { + let mut s = DevelopSettings::default(); + typical(&mut s); + s.color.saturation = 40.0; + s.optics.defringe_purple_amount = purple; + s.optics.defringe_green_amount = green; + s.optics.defringe_purple_hue_lo = hue.0; + s.optics.defringe_purple_hue_hi = hue.1; + s.optics.defringe_green_hue_lo = hue.0; + s.optics.defringe_green_hue_hi = hue.1; + for edge in [640, 1800] { + check(&format!("defringe {purple}/{green} {hue:?} @{edge}"), &src, &raw, &s, &RenderRequest::fit(edge, edge)); + } + } +} + +/// The histogram counted on the device is exactly the CPU's count of the image the GPU returned, +/// for whole frames (small and over 1 MP, where it samples) and for windows cut back after spots. +#[test] +fn device_histogram_is_exact() { + if !gpu() { + return; + } + let raw = SourceInfo { raw: true, ..Default::default() }; + let mut s = DevelopSettings::default(); + typical(&mut s); + for (w, h) in [(640, 427), (2400, 1600)] { + let src = scene(0, w, h); + let r = lightcraft_gpu::render(&src, &raw, &s, &RenderRequest::fit(w, h), None).expect("gpu render"); + assert_eq!(r.histogram, lightcraft_raster::Histogram::of_srgb8(&r.image), "{w}x{h}"); + } + // a window with a spot reading from outside it: the render grows, the histogram is of the cut + let src = scene(0, 3000, 2000); + s.spots = vec![Spot { points: vec![Point::new(0.5, 0.5)], size: 0.02, source_offset: Some(Point::new(0.15, 0.0)), ..Default::default() }]; + let req = RenderRequest { window: Some(lightcraft_pipeline::PixelWindow { x: 1200, y: 800, w: 500, h: 400 }), ..RenderRequest::fit(3000, 2000) }; + let r = lightcraft_gpu::render(&src, &raw, &s, &req, None).expect("gpu render"); + assert_eq!((r.image.width, r.image.height), (500, 400)); + assert_eq!(r.histogram, lightcraft_raster::Histogram::of_srgb8(&r.image), "window"); +} diff --git a/crates/gpu/tests/it/main.rs b/crates/gpu/tests/it/main.rs index d26d1efc94..1803370213 100644 --- a/crates/gpu/tests/it/main.rs +++ b/crates/gpu/tests/it/main.rs @@ -1,9 +1,11 @@ //! The integration tests, one module per file, linked into one test binary. //! Binaries of their own: `tests/shutdown.rs` and `tests/shutdown_first.rs` close the GPU for the whole -//! process, and `tests/memory.rs` checks the process's device-memory counters, which renders on other test -//! threads would change. +//! process, `tests/memory.rs` checks the process's device-memory counters, which renders on other test +//! threads would change, and `tests/display.rs` and `tests/window_pending.rs` adopt (or wait for) the +//! window's device, once per process. mod equivalence; mod fallback; #[cfg(not(target_arch = "wasm32"))] mod gpu_probe; +mod thumbs_bench; diff --git a/crates/gpu/tests/it/thumbs_bench.rs b/crates/gpu/tests/it/thumbs_bench.rs new file mode 100644 index 0000000000..e3ee63c284 --- /dev/null +++ b/crates/gpu/tests/it/thumbs_bench.rs @@ -0,0 +1,72 @@ +//! Thumbnail throughput, CPU vs GPU: `cargo test --release -p lightcraft-gpu --test it thumbs_bench -- --ignored --nocapture`. +//! Six threads (the app's render workers) each render thumbnails of 512 px sources at 256 px with +//! settings like a typical preset (noise reduction, sharpening, clarity, grading, a gradient mask). + +use std::sync::Arc; +use std::time::Instant; + +use lightcraft_develop::{DevelopSettings, Mask, MaskComponent, MaskOp, MaskShape}; +use lightcraft_geom::Point; +use lightcraft_pipeline::{RenderRequest, SourceInfo}; + +fn preset_like() -> DevelopSettings { + let mut s = DevelopSettings::default(); + s.light.exposure = 0.4; + s.light.contrast = 20.0; + s.light.highlights = -60.0; + s.light.shadows = 50.0; + s.effects.clarity = 15.0; + s.detail.nr_luminance = 16.0; + s.detail.sharpen_amount = 60.0; + s.color.vibrance = 15.0; + s.grading.shadows.hue = 220.0; + s.grading.shadows.sat = 30.0; + s.masks = vec![Mask { + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Linear { start: Point::new(0.5, 0.0), end: Point::new(0.5, 0.5) }, + }], + adjust: lightcraft_develop::LocalAdjustments { exposure: -0.6, ..Default::default() }, + ..Default::default() + }]; + s +} + +#[test] +#[ignore] +fn thumbnail_throughput() { + if !lightcraft_gpu::available() { + eprintln!("skipped: no GPU ({:?})", lightcraft_gpu::unavailable_reason()); + return; + } + let lib = lightcraft_scenes::demo_library(); + let sources: Vec> = (0..12).map(|i| Arc::new(lib[i % lib.len()].render(512, 341))).collect(); + let info = SourceInfo { raw: true, ..Default::default() }; + let s = preset_like(); + let req = RenderRequest::fit(256, 256); + let per_thread = 40; + for gpu in [false, true, false, true] { + let t = Instant::now(); + std::thread::scope(|sc| { + for k in 0..6 { + let (sources, info, s) = (&sources, &info, &s); + sc.spawn(move || { + for i in 0..per_thread { + let src = &sources[(k * per_thread + i) % sources.len()]; + let r = if gpu { + lightcraft_gpu::render(src, info, s, &req, None) + } else { + Some(lightcraft_pipeline::render(src, info, s, &req)) + }; + assert!(r.is_some()); + } + }); + } + }); + let n = 6 * per_thread; + let ms = t.elapsed().as_secs_f64() * 1e3; + eprintln!("{}: {n} thumbnails in {ms:.0} ms ({:.2} ms each)", if gpu { "gpu" } else { "cpu" }, ms / n as f64); + } +} diff --git a/crates/gpu/tests/window_pending.rs b/crates/gpu/tests/window_pending.rs new file mode 100644 index 0000000000..48381b591b --- /dev/null +++ b/crates/gpu/tests/window_pending.rs @@ -0,0 +1,25 @@ +//! Review of PR #1065: while the window's device is being adopted (announced with +//! `set_window_device_pending`), neither the settings' warm-up nor a render creates a device of +//! its own, which would leave the window's device unused. One test in its own process: it runs +//! before anything else uses the GPU. + +use std::sync::Arc; +use std::time::Duration; + +use lightcraft_develop::DevelopSettings; +use lightcraft_pipeline::{RenderRequest, SourceInfo}; + +#[test] +fn no_device_of_its_own_is_created_while_the_window_device_is_pending() { + lightcraft_gpu::set_window_device_pending(true); + lightcraft_gpu::warm_up(); + assert!(!lightcraft_gpu::available()); + let src = Arc::new(lightcraft_scenes::demo_library()[0].render(300, 200)); + let rendered = lightcraft_gpu::render(&src, &SourceInfo::default(), &DevelopSettings::default(), &RenderRequest::fit(300, 200), None); + assert!(rendered.is_none(), "the render takes the CPU path"); + assert!(lightcraft_gpu::wait_idle(Duration::from_secs(60))); + let switched_off = lightcraft_gpu::unavailable_reason().is_some_and(|r| r.starts_with("disabled by LIGHTCRAFT_GPU")); + assert!(switched_off || !lightcraft_gpu::ready(), "no device was created"); + // withdrawn (the adoption couldn't start): renders create one as before + lightcraft_gpu::set_window_device_pending(false); +} diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index aa194252e9..5a9c51b8cf 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -29,6 +29,31 @@ pub fn sharpen_mask_weight(masking: f32, det: f32) -> f32 { if masking > 0.0 { smooth(masking * 0.25, masking * 0.25 + 0.15, det.abs()) } else { 1.0 } } +/// Masking weight for the V3 pixel-scale sharpening band, also used by its Alt-drag preview. +#[inline] +pub fn pixel_sharpen_mask_weight(masking: f32, det: f32) -> f32 { + if masking > 0.0 { smooth(masking * 0.1, masking * 0.1 + 0.06, det.abs()) } else { 1.0 } +} + +/// Gain of the sharpening detail term (per unit of `Amount / 150`), in stops of luminance per stop of detail. +pub const SHARPEN_GAIN: f32 = 7.0; + +/// Soft-clip limit (stops) of the sharpening detail term for Detail `0..=100`: 0.03 stops (large +/// edge detail is flattened so halos stay small) up to 1.5 stops (practically linear). +pub fn sharpen_limit(detail: f64) -> f32 { + let d = (detail / 100.0).clamp(0.0, 1.0) as f32; + 0.03 * 50f32.powf(d) +} + +/// The sharpening boost (stops) for pixel-scale detail `det` (log luminance minus its blur at the +/// sharpen radius): linear for small detail, soft-clipped at `limit`, and gated by the Masking edge +/// mask (`mask` = Masking / 100) so flat areas and noise can be left alone. +#[inline] +pub fn sharpen_term(det: f32, limit: f32, mask: f32) -> f32 { + let m = pixel_sharpen_mask_weight(mask, det); + SHARPEN_GAIN * m * det / (1.0 + det.abs() / limit) +} + /// Parametric region curve (encoded domain) composed with the master point curve. fn curve_luts(c: &ToneCurve) -> Option<[Lut1; 3]> { let parametric = c.highlights != 0.0 || c.lights != 0.0 || c.darks != 0.0 || c.shadows != 0.0; @@ -155,6 +180,9 @@ pub struct FinishParams { /// A LUT profile and its amount (0..2), applied to the display-encoded colour. pub lut: Option<(std::sync::Arc, f32)>, pub tone: ToneMap, + /// Process V4's calibrated Contrast and Blacks on the camera-look path, applied after + /// the tone map (`None`: another process or path, or both at 0; see [`crate::light_v3`]). + pub light: Option, pub ops: ColorOps, /// Calibration: primaries matrix (row-major, linear Rec.2020) and shadows tint (−1..1). pub calib: Option<[[f32; 3]; 3]>, @@ -169,7 +197,7 @@ pub struct FinishParams { pub to_out: [[f32; 3]; 3], pub out_luma: [f32; 3], pub out_trc: OutputTrc, - /// Soft proofing (CPU only; the GPU path declines proof renders). + /// Soft proofing (the GPU kernel reads the same parameters). pub proof: Option, pub hl: f32, pub sh: f32, @@ -178,6 +206,12 @@ pub struct FinishParams { pub dehaze: f32, pub sharpen: f32, pub sharpen_mask: f32, + /// V1/V2 retain their texture-band sharpening; V3 uses the pixel-scale plane. + pub pixel_sharpen: bool, + /// Soft-clip limit (stops) of the sharpening detail term: small damps halos (Detail 0), large keeps all (100). + pub sharpen_limit: f32, + /// Response compensation for a sharpening radius below one output pixel. + pub sharpen_gain: f32, /// Airlight after and before exposure, exposure gain and EV (see [`crate::Prepared`]). pub air: f32, pub air_pre: f32, @@ -240,6 +274,7 @@ impl FinishParams { calib: if calibration { crate::colorops::calibration_matrix(&s.calibration) } else { None }, shadow_tint: if calibration { (s.calibration.shadows_tint / 100.0) as f32 } else { 0.0 }, tone: base_tone(s, info, peak), + light: crate::light_v3::LightOps::new(s, info), lut: crate::lut::get(&s.profile.id).map(|l| (l, (s.profile.amount / 100.0).clamp(0.0, 2.0) as f32)), ops: ColorOps::new(s), curves: curve_luts(&s.curve), @@ -256,6 +291,13 @@ impl FinishParams { dehaze, sharpen: (s.detail.sharpen_amount / 150.0) as f32, sharpen_mask: (s.detail.sharpen_masking / 100.0) as f32, + pixel_sharpen: crate::local::pixel_sharpen(s), + sharpen_limit: sharpen_limit(s.detail.sharpen_detail), + sharpen_gain: crate::local::sharpen_gain(crate::local::sharpen_sigma_raw( + s, + px_per_long, + info.native_long.unwrap_or(0).max(frame.ow.max(frame.oh) as usize).max(1) as f64, + )), air: air_pre * gain, air_pre, gain, @@ -285,6 +327,8 @@ impl FinishParams { /// rendering process. This is where a new tone model branches: a retuned default tone curve (issue /// #146) is a new [`Process`] with its own arm here, and V1's arm stays as it is, so photos edited /// under V1 keep their look (`docs/process-versions.md`). CPU and GPU both take it from here. +/// From V4 the camera curve keeps V2 Whites; its Contrast and Blacks are the +/// calibrated operators that follow the tone map ([`crate::light_v3`], [`FinishParams::light`]). /// `peak` is the HDR render's peak relative to SDR white ([`lightcraft_develop::Hdr::peak`]); at 1.0 (SDR) /// every arm is the SDR tone map. An HDR render keeps the camera's look through the midtones and /// lifts its highlights past white ([`ToneMap::camera_hdr`]), so it matches the SDR render below them. @@ -292,14 +336,21 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap { let l = &s.light; match s.process.process() { // V2 changes the Highlights/Shadows base (`local::tone_base`), not the tone map - Process::V1 | Process::V2 => match info.camera_tone.as_ref().filter(|_| info.raw) { + Process::V1 | Process::V2 | Process::V3 => match info.camera_tone.as_ref().filter(|_| info.raw) { Some(curve) => ToneMap::camera_hdr(curve, l.contrast, l.whites, l.blacks, peak), None if info.raw => ToneMap::hdr(l.contrast, l.whites, l.blacks, peak), None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak), }, + // Keep V2 Whites in the camera curve; calibrated Contrast and Blacks follow it. + Process::V4 => match info.camera_tone.as_ref().filter(|_| info.raw) { + Some(curve) => ToneMap::camera_hdr(curve, 0.0, l.whites, 0.0, peak), + None if info.raw => ToneMap::hdr(l.contrast, l.whites, l.blacks, peak), + None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak), + }, } } +/// Finish the prepared pipeline stages into an 8-bit RGBA image in `space` (or `display`). pub(crate) fn finish( p: &Prepared, s: &DevelopSettings, @@ -317,11 +368,14 @@ pub(crate) fn finish( fp.for_display(d, proof); } let trc = fp.out_trc; - let data = finish_with(p, &fp, false, |e| match trc { - OutputTrc::Srgb => [enc(e[0]), enc(e[1]), enc(e[2]), 255], - t => { - let x = e.map(|v| enc(t.encode(lightcraft_color::transfer::srgb_to_linear(v.clamp(0.0, 1.0))))); - [x[0], x[1], x[2], 255] + let data = finish_with(p, &fp, false, |x, y, e| { + let d = bayer_dither_offset(x, y); + match trc { + OutputTrc::Srgb => [enc(e[0], d), enc(e[1], d), enc(e[2], d), 255], + t => { + let c = e.map(|v| enc(t.encode(lightcraft_color::transfer::srgb_to_linear(v.clamp(0.0, 1.0))), d)); + [c[0], c[1], c[2], 255] + } } }); Rgba8 { width: w, height: h, data } @@ -345,18 +399,18 @@ pub(crate) fn finish_deep( let trc = fp.out_trc; let samples = match depth { OutputDepth::F32Linear => { - let v = finish_with(p, &fp, true, |e| e.map(|v| srgb_to_linear(v.clamp(0.0, 1.0)))); + let v = finish_with(p, &fp, true, |_x, _y, e| e.map(|v| srgb_to_linear(v.clamp(0.0, 1.0)))); DeepSamples::F32(v.into_flattened()) } OutputDepth::F32Hdr => { // the sRGB curve extended past 1 (it is unbounded), so values up to `peak` survive let peak = fp.peak; - let v = finish_with(p, &fp, true, |e| e.map(|v| srgb_to_linear(v.max(0.0)).clamp(0.0, peak))); + let v = finish_with(p, &fp, true, |_x, _y, e| e.map(|v| srgb_to_linear(v.max(0.0)).clamp(0.0, peak))); DeepSamples::F32(v.into_flattened()) } _ => { let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16; - let v = finish_with(p, &fp, true, |e| match trc { + let v = finish_with(p, &fp, true, |_x, _y, e| match trc { OutputTrc::Srgb => e.map(q), t => e.map(|v| q(t.encode(srgb_to_linear(v.clamp(0.0, 1.0))))), }); @@ -373,19 +427,21 @@ pub(crate) fn finish_with( p: &Prepared, fp: &FinishParams, exact: bool, - store: impl Fn([f32; 3]) -> T + Sync + Send, + store: impl Fn(usize, usize, [f32; 3]) -> T + Sync + Send, ) -> Vec { let (w, h) = (p.img.width, p.img.height); let p_lut = fp.lut.clone(); - let FinishParams { curves, vig, to_out, out_luma, grain, .. } = fp; + let FinishParams { light, curves, vig, to_out, out_luma, grain, .. } = fp; let terms: Vec<[f32; MASK_TERMS]> = p.masks.iter().map(|m| mask_terms(&m.adjust)).collect(); let out_to_norm = fp.out_to_norm; let long = fp.ow.max(fp.oh); let [vx, vy, vw, vh] = fp.view; + let (vx_u, vy_u) = (vx.round() as usize, vy.round() as usize); // the vignette belongs to the whole output frame, not to the window being drawn let aspect = vw / vh; let srgb = srgb_lut(); + let preview_light = if exact { None } else { light.as_ref().and_then(|lo| crate::light_v3::PreviewOps::new(lo, &|v| encode_srgb(srgb, v))) }; let peak = fp.peak; let hdr = peak > 1.0; let mut out = vec![T::default(); w * h]; @@ -428,6 +484,9 @@ pub(crate) fn finish_with( d = d.map(|v| v + (o - v) * t); } + // --- process V4: calibrated Contrast, Blacks (ProPhoto with the sRGB transfer) + d = apply_light(d, light.as_ref(), preview_light.as_ref(), exact, srgb); + // --- colour d = fp.ops.apply(d, l_sat, l_hue); if let Some((dir, amt)) = local.tint { @@ -549,12 +608,29 @@ pub(crate) fn finish_with( } None => e, }; - *px = store(warn.unwrap_or(e)); + *px = store(vx_u + x, vy_u + y, warn.unwrap_or(e)); } }); out } +#[inline] +fn apply_light( + color: [f32; 3], + light: Option<&crate::light_v3::LightOps>, + preview: Option<&crate::light_v3::PreviewOps>, + exact: bool, + srgb: &[f32; SRGB_LUT_N + 1], +) -> [f32; 3] { + if let Some(lo) = preview { + lo.apply(color) + } else if let Some(lo) = light { + if exact { lo.apply(color, &linear_to_srgb) } else { lo.apply(color, &|v| encode_srgb(srgb, v)) } + } else { + color + } +} + struct PixelLocalTerms { values: [f32; MASK_SUMS], tint: Option<([f32; 3], f32)>, @@ -662,17 +738,26 @@ fn local_tone_delta(p: &Prepared, fp: &FinishParams, index: usize, base: f32, l1 delta += clarity * 0.85 * detail * (0.35 + 0.65 * midtone); } let texture = fp.tex + l_tex; - let sharpen = l_sharp * 0.6 + fp.sharpen; - if (texture != 0.0 || sharpen != 0.0) + if texture != 0.0 && let Some(blur) = &p.texture_blur { let detail = p.log_l.data[index] - blur.data[index]; let tame = 1.0 - 0.6 * smooth(0.4, 1.6, detail.abs()); delta += texture * 1.1 * detail.clamp(-1.0, 1.0) * tame; - if sharpen != 0.0 { - let mask = sharpen_mask_weight(fp.sharpen_mask, detail); - delta += sharpen * 1.3 * detail.clamp(-0.8, 0.8) * mask; + } + let sharpen = l_sharp * 0.6 + fp.sharpen; + if fp.pixel_sharpen { + if sharpen != 0.0 + && let Some(blur) = &p.sharpen_blur + { + delta += sharpen * fp.sharpen_gain * sharpen_term(p.log_l.data[index] - blur.data[index], fp.sharpen_limit, fp.sharpen_mask); } + } else if sharpen != 0.0 + && let Some(blur) = &p.texture_blur + { + let detail = p.log_l.data[index] - blur.data[index]; + let mask = sharpen_mask_weight(fp.sharpen_mask, detail); + delta += sharpen * 1.3 * detail.clamp(-0.8, 0.8) * mask; } if l_noise != 0.0 && let Some(blur) = &p.texture_blur @@ -685,7 +770,7 @@ fn local_tone_delta(p: &Prepared, fp: &FinishParams, index: usize, base: f32, l1 /// A colour needing more desaturation than this (scale < `GAMUT_WARN`) to fit is out of gamut for /// the gamut warnings (tolerates rounding at the gamut boundary). -const GAMUT_WARN: f32 = 0.995; +pub const GAMUT_WARN: f32 = 0.995; /// For the gamut warnings: `r` needed desaturating by `t` to fit, and isn't simply a neutral /// beyond white or below black (that's clipping, which the clipping warnings show). @@ -770,17 +855,42 @@ pub fn srgb_lut() -> &'static [f32; SRGB_LUT_N + 1] { /// Linear → sRGB-encoded (clamped to 0..1) by an interpolated table: within 2e-5 of the exact /// curve (≪ one 8-bit or 10-bit step), several times faster than `powf`. #[inline] -fn encode_srgb(lut: &[f32; SRGB_LUT_N + 1], v: f32) -> f32 { +pub(crate) fn encode_srgb(lut: &[f32; SRGB_LUT_N + 1], v: f32) -> f32 { let f = v.clamp(0.0, 1.0) * SRGB_LUT_N as f32; let i = (f as usize).min(SRGB_LUT_N - 1); let t = f - i as f32; lut[i] + (lut[i + 1] - lut[i]) * t } +#[rustfmt::skip] +const BAYER_8X8: [u8; 64] = [ + 0, 32, 8, 40, 2, 34, 10, 42, + 48, 16, 56, 24, 50, 18, 58, 26, + 12, 44, 4, 36, 14, 46, 6, 38, + 60, 28, 52, 20, 62, 30, 54, 22, + 3, 35, 11, 43, 1, 33, 9, 41, + 51, 19, 59, 27, 49, 17, 57, 25, + 15, 47, 7, 39, 13, 45, 5, 37, + 63, 31, 55, 23, 61, 29, 53, 21, +]; + +/// Returns the ordered Bayer 8×8 dither threshold offset in `0..1` for pixel `(x, y)`. #[inline] -fn enc(v: f32) -> u8 { - // `v` is already sRGB-encoded; round to 8 bits. - (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8 +fn bayer_dither_offset(x: usize, y: usize) -> f32 { + let idx = (y & 7) * 8 + (x & 7); + (BAYER_8X8[idx] as f32 + 0.5) / 64.0 +} + +/// Quantizes display-curve-encoded value `v` (0..1) to 8-bit integer with 8×8 ordered Bayer dithering. +#[inline] +fn enc(v: f32, dither: f32) -> u8 { + let y = v.clamp(0.0, 1.0) * 255.0; + // Guard against floating point rounding error (e.g. sRGB <-> Rec.2020 matrix conversion) + // where numerical white (1.0) evaluates to ~254.95. + if y >= 254.9 { + return 255; + } + (y + dither).clamp(0.0, 255.0) as u8 } #[cfg(test)] @@ -822,4 +932,62 @@ mod tests { assert_eq!(encode_srgb(lut, -1.0), 0.0); assert!((encode_srgb(lut, 2.0) - 1.0).abs() < 1e-6); } + + /// Verifies 8x8 Bayer dithering preserves endpoints, exact 8-bit quantization steps, and fractional levels. + #[test] + fn bayer_dithering_preserves_extremes_and_dithers_smoothly() { + for y in 0..8 { + for x in 0..8 { + let d = bayer_dither_offset(x, y); + // Zero is strictly 0 across all dither offsets + assert_eq!(enc(0.0, d), 0); + // One is strictly 255 across all dither offsets + assert_eq!(enc(1.0, d), 255); + // Exact 8-bit quantization steps have zero spatial noise + for k in 0..=255 { + assert_eq!(enc(k as f32 / 255.0, d), k); + } + } + } + + // Fractional level: 128.5 / 255.0 should dither equally between 128 and 129 + let v = 128.5 / 255.0; + let mut sum = 0u32; + let mut count_128 = 0; + let mut count_129 = 0; + for y in 0..8 { + for x in 0..8 { + let val = enc(v, bayer_dither_offset(x, y)); + sum += val as u32; + if val == 128 { + count_128 += 1; + } else if val == 129 { + count_129 += 1; + } + } + } + assert_eq!(count_128, 32); + assert_eq!(count_129, 32); + assert_eq!(sum, 32 * 128 + 32 * 129); + + // Fractional highlight level: 254.5 / 255.0 should dither equally between 254 and 255 + let v = 254.5 / 255.0; + let mut sum_hl = 0u32; + let mut count_254 = 0; + let mut count_255 = 0; + for y in 0..8 { + for x in 0..8 { + let val = enc(v, bayer_dither_offset(x, y)); + sum_hl += val as u32; + if val == 254 { + count_254 += 1; + } else if val == 255 { + count_255 += 1; + } + } + } + assert_eq!(count_254, 32); + assert_eq!(count_255, 32); + assert_eq!(sum_hl, 32 * 254 + 32 * 255); + } } diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index 7124383998..5969447657 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -31,6 +31,10 @@ pub mod curve; pub mod dust; pub mod finish; pub mod geometry; +pub mod light_v3; +// generated (`light_v3_params.rs`), kept in its own compact layout +#[rustfmt::skip] +pub mod light_v3_params; pub mod local; pub mod local_tone; pub mod lut; @@ -227,6 +231,8 @@ pub(crate) struct Prepared { pub base: Arc, pub clarity_blur: Option>, pub texture_blur: Option>, + /// Log luminance blurred at the sharpen radius (the pixel-scale band sharpening boosts). + pub sharpen_blur: Option>, pub dark: Option>, /// Blurred chromaticity (`rgb / Y`) for local Moiré / Noise. pub chroma_blur: Option>, @@ -329,7 +335,7 @@ impl StageCache { } let pl = &e.planes; let planes = pl.log_l.iter().chain(pl.base.iter().map(|x| &x.1)).chain(pl.clarity.iter().map(|x| &x.1)); - for p in planes.chain(pl.texture.iter().map(|x| &x.1)).chain(pl.dark.iter().map(|x| &x.1)) { + for p in planes.chain(pl.texture.iter().map(|x| &x.1)).chain(pl.sharpen.iter().map(|x| &x.1)).chain(pl.dark.iter().map(|x| &x.1)) { add(Arc::as_ptr(p) as usize, size(p)); } } @@ -389,6 +395,8 @@ pub struct Plan<'a> { pub px_per_long: f64, /// Long edge of the source buffer (px). pub src_long: usize, + /// Long edge of the original photo, shared by sharpening and noise reduction. + pub native_long: usize, /// Output pixels per pixel of the original photo ([`SourceInfo::native_long`], else the source /// buffer), at most 1: the scale of noise reduction, whose radii are in the original's pixels. pub detail_scale: f32, @@ -478,7 +486,23 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R [d.nr_luminance, d.nr_detail, d.nr_color, d.nr_color_detail, d.nr_color_smoothness].map(f64::to_bits), detail_scale.to_bits(), )); - Plan { settings, frame, w, h, px_per_long, src_long, detail_scale, geo, lin_key, pre_nr_key, eyes, fixed_air, keep, mattes: info.mattes.clone() } + Plan { + settings, + frame, + w, + h, + px_per_long, + src_long, + native_long, + detail_scale, + geo, + lin_key, + pre_nr_key, + eyes, + fixed_air, + keep, + mattes: info.mattes.clone(), + } } /// Whether the scene-linear stage needs work only the CPU does (defringe, spot removal). @@ -611,7 +635,7 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende Some(p) if req.quality == Quality::Draft && p.pre_nr == plan.pre_nr_key => p.for_other_nr(), _ => local::Planes { key: lin_key, pre_nr: plan.pre_nr_key, ..Default::default() }, }; - let mut prep = local::prepare(lin.clone(), s, frame, px_per_long, req.quality, &mut planes, plan.mattes.as_deref()); + let mut prep = local::prepare(lin.clone(), s, frame, px_per_long, plan.native_long as f64, req.quality, &mut planes, plan.mattes.as_deref()); if let Some(a) = plan.fixed_air { prep.air = a; } @@ -689,7 +713,8 @@ pub fn color_range_sample(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, /// (the one the render evaluated, or for a hidden mask a fresh evaluation). fn overlay_alpha(o: Overlay, plan: &Plan<'_>, prep: &Prepared) -> Option { if o.reads_detail() { - return visualize::sharpen_plane(o, &plan.settings, &prep.log_l, prep.texture_blur.as_deref(), plan.px_per_long); + let band = if local::pixel_sharpen(&plan.settings) { &prep.sharpen_blur } else { &prep.texture_blur }; + return visualize::sharpen_plane(o, &plan.settings, &prep.log_l, band.as_deref(), plan.px_per_long, plan.native_long as f64); } let m = o.mask(&plan.settings)?; if let Some(e) = prep.masks.iter().find(|e| e.id == m.id) { @@ -757,12 +782,18 @@ mod tests_geometry; #[cfg(test)] mod tests_hdr; #[cfg(test)] +mod tests_legacy; +#[cfg(test)] +mod tests_light; +#[cfg(test)] mod tests_local; #[cfg(test)] mod tests_mask_geometry; #[cfg(test)] mod tests_nr_scale; #[cfg(test)] +mod tests_sharpen; +#[cfg(test)] mod tests_tone; #[cfg(test)] mod tests_window; diff --git a/crates/pipeline/src/light_v3.rs b/crates/pipeline/src/light_v3.rs new file mode 100644 index 0000000000..43f836101a --- /dev/null +++ b/crates/pipeline/src/light_v3.rs @@ -0,0 +1,439 @@ +//! Process V4's Contrast and Blacks on the camera-look path (a raw with its camera's tone +//! curve): pointwise operators fitted to how Lightroom's sliders move a photo's tones, applied +//! after the camera curve with V2 Whites. Method, operator family and the fitted constants' provenance: +//! `docs/light-v3.md`; the constants are in [`crate::light_v3_params`] (generated). +//! +//! Each slider is an operator `F_a` on encoded values `v` (linear ProPhoto RGB, D50, Bradford from +//! the D65 working space, through the sRGB transfer curve), anchored at `F_0` = identity: +//! +//! - `a > 0`: `F_a(v) = v + s(a)·D₊(v)`; `a < 0`: `F_a(v) = max(0, v − s(a)·D₋(v))`, with `D` piecewise +//! linear on 12 fixed knots (`D(1) = 0`, and for Contrast `D(0) = 0`) and the amount law +//! `s(t) = ((1 − e^(−t/τ)) / (1 − e^(−1/τ)))^q`, `t = |a|/100`, one `(τ, q)` per sign; +//! - applied per channel ([`Mode::PerChannel`]), to the encoded ProPhoto luminance with linear RGB +//! scaled by the luminance ratio ([`Mode::Luminance`]), or a blend of the two in linear light +//! ([`Mode::Mix`], one weight per sign). +//! +//! The functions here port `Family.curve`, `Family.apply`, `Family.law` of +//! `fit_pointwise.py` (the fitting tool) exactly; [`Fit::unpack`] is its `Family.unpack`. Each +//! active operator is tabulated once per render ([`LUT_N`] entries over `v` in 0..1, interpolated +//! linearly). High-bit-depth CPU exports and the GPU read these tables ([`LightOps`]); 8-bit CPU +//! renders compose per-channel operations over linear input ([`PreviewOps`]). Luminance operations +//! retain the original evaluation, including any preceding per-channel operation. + +use lightcraft_color::{Mat3, PROPHOTO, REC2020}; +use lightcraft_develop::{DevelopSettings, Process}; + +use crate::SourceInfo; +use crate::light_v3_params as fitted; + +/// Entries of an operator's table over encoded `v` in 0..=1. +pub const LUT_N: usize = 1024; + +/// Linear ProPhoto RGB luminance (the Y row of ProPhoto → XYZ D50), as the fit computes it. +pub const PRO_Y: [f32; 3] = [0.288_040_2, 0.711_874_1, 0.000_085_7]; + +/// How an operator is applied to a pixel. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// To each encoded ProPhoto channel. + PerChannel, + /// To the encoded ProPhoto luminance; linear RGB is scaled by the luminance ratio. + Luminance, + /// `w·PerChannel + (1 − w)·Luminance` in linear light, with a weight per sign. + Mix, +} + +impl Mode { + /// The GPU kernel's code (`LIGHT_MODE` in `crates/gpu/src/params.rs`). + pub fn code(self) -> u32 { + match self { + Mode::PerChannel => 0, + Mode::Luminance => 1, + Mode::Mix => 2, + } + } +} + +/// One slider's fitted parameters, laid out as `fit_pointwise.py`'s `Family`: 11 values of `D₊` at +/// the knots but the last (`D(1) = 0`), 11 of `D₋`, then `ln τ₊, ln q₊, ln τ₋, ln q₋`, then two mix +/// logits (positive, negative amounts) in [`Mode::Mix`]. +#[derive(Clone, Copy, Debug)] +pub struct Fit { + pub mode: Mode, + /// Contrast moves tones both ways around a pivot: its shapes are anchored at black too (`D(0) = 0`). + pub signed: bool, + pub params: &'static [f64], +} + +const KNOTS_N: usize = fitted::KNOTS.len(); + +/// A [`Fit`] unpacked (`Family.unpack`). +#[derive(Clone, Copy, Debug)] +pub struct Unpacked { + pub d_pos: [f64; KNOTS_N], + pub d_neg: [f64; KNOTS_N], + /// `(τ, q)` of the amount law, positive and negative amounts. + pub law_pos: (f64, f64), + pub law_neg: (f64, f64), + /// Mix weights of the per-channel result for positive and negative amounts (1 outside [`Mode::Mix`]). + pub weights: (f64, f64), +} + +fn sigmoid(x: f64) -> f64 { + 1.0 / (1.0 + (-x).exp()) +} + +impl Fit { + /// The parameters unpacked; `None` when their number doesn't fit the layout. + pub fn unpack(&self) -> Option { + let n = KNOTS_N - 1; + let p = self.params; + let mix = self.mode == Mode::Mix; + let len = 2 * n + 4 + if mix { 2 } else { 0 }; + if p.len() != len { + return None; + } + // D(1) = 0 is appended (the last knot stays 0) + let shape = |off: usize| -> Option<[f64; KNOTS_N]> { + let mut d = [0.0; KNOTS_N]; + for (k, slot) in d.iter_mut().take(n).enumerate() { + *slot = *p.get(off + k)?; + } + Some(d) + }; + let (mut d_pos, mut d_neg) = (shape(0)?, shape(n)?); + if self.signed { + d_pos[0] = 0.0; + d_neg[0] = 0.0; + } + let at = |i: usize| p.get(i).copied(); + let i = 2 * n; + let law_pos = (at(i)?.exp(), at(i + 1)?.exp()); + let law_neg = (at(i + 2)?.exp(), at(i + 3)?.exp()); + let weights = if mix { (sigmoid(at(i + 4)?), sigmoid(at(i + 5)?)) } else { (1.0, 1.0) }; + Some(Unpacked { d_pos, d_neg, law_pos, law_neg, weights }) + } +} + +/// The amount law `s(t)` (`Family.law`): 1 at `|a| = 100`, linear as `τ` grows, saturating as it +/// shrinks. +pub fn law((tau, q): (f64, f64), a: f64) -> f64 { + let t = (a.abs() / 100.0).min(1.0); + let tau = tau.clamp(1e-3, 1e3); + ((1.0 - (-t / tau).exp()) / (1.0 - (-1.0 / tau).exp())).powf(q) +} + +/// `numpy.interp(v, KNOTS, d)`: piecewise linear, constant beyond the ends. +fn interp(v: f64, d: &[f64; KNOTS_N]) -> f64 { + let k = &fitted::KNOTS; + if v <= k[0] { + return d[0]; + } + for i in 1..KNOTS_N { + if v <= k[i] { + let t = (v - k[i - 1]) / (k[i] - k[i - 1]); + return d[i - 1] + t * (d[i] - d[i - 1]); + } + } + d[KNOTS_N - 1] +} + +impl Unpacked { + /// `F_a(v)` on an encoded value (`Family.curve`). + pub fn curve(&self, a: f64, v: f64) -> f64 { + if a == 0.0 { + return v; + } + if a > 0.0 { + return v + law(self.law_pos, a) * interp(v, &self.d_pos); + } + (v - law(self.law_neg, a) * interp(v, &self.d_neg)).max(0.0) + } +} + +/// One slider's operator at one amount, tabulated: `lut[i]` is the *linear* value of +/// `F_a(i / (LUT_N − 1))` (decoded with the sRGB curve), made non-decreasing (see [`Operator::new`]). +#[derive(Clone, Debug)] +pub struct Operator { + pub mode: Mode, + /// Weight of the per-channel result ([`Mode::Mix`]; 1 for per channel, 0 for luminance). + pub weight: f32, + pub lut: Box<[f32; LUT_N]>, +} + +impl Operator { + /// `fit` at `amount` (-100..100); `None` at 0 (the identity) or for parameters that do not unpack. + /// + /// The table is the running maximum of `F_a`: where a fitted shape folds back (a `D` rising + /// faster than 1), it is flat instead, so no two tones swap. None of the shipped fits folds. + /// The fitting tool inverts `F` the same way. + pub fn new(fit: &Fit, amount: f64) -> Option { + let a = if amount.is_finite() { amount.clamp(-100.0, 100.0) } else { 0.0 }; + if a == 0.0 { + return None; + } + let u = fit.unpack()?; + let weight = match fit.mode { + Mode::PerChannel => 1.0, + Mode::Luminance => 0.0, + Mode::Mix => (if a > 0.0 { u.weights.0 } else { u.weights.1 }) as f32, + }; + let mut lut = Box::new([0.0f32; LUT_N]); + let mut top = 0.0f64; + for (i, slot) in lut.iter_mut().enumerate() { + let v = i as f64 / (LUT_N - 1) as f64; + top = top.max(u.curve(a, v)); + *slot = srgb_decode(top) as f32; + } + // The negative Blacks fit rounds to exactly 1 in f32. Avoid calculating a luminance + // result that contributes nothing, on both CPU and GPU. + let mode = if weight == 1.0 { + Mode::PerChannel + } else if weight == 0.0 { + Mode::Luminance + } else { + Mode::Mix + }; + Some(Operator { mode, weight, lut }) + } + + /// The table at encoded `v` (clamped to 0..=1), interpolated: linear output. + #[inline] + pub fn eval(&self, v: f32) -> f32 { + let f = v.clamp(0.0, 1.0) * (LUT_N - 1) as f32; + let i = (f as usize).min(LUT_N - 2); + let t = f - i as f32; + self.lut[i] + (self.lut[i + 1] - self.lut[i]) * t + } + + /// One linear value through the operator: values above 1 (HDR renders) pass unchanged, which + /// is continuous because `F_a(1) = 1`; values below 0 (outside ProPhoto's gamut) keep their + /// distance below the image of 0, `F_a(0) + x` (continuous and increasing). This is the + /// per-channel domain: on luminance ([`Self::apply`]) a component above 1 is scaled with its + /// pixel unless the pixel's luminance is above 1. + #[inline] + pub fn channel(&self, x: f32, encode: &impl Fn(f32) -> f32) -> f32 { + if x > 1.0 { + x + } else if x < 0.0 { + self.lut[0] + x + } else { + self.eval(encode(x)) + } + } + + /// The luminance mode: linear ProPhoto `p` scaled by `F` of its luminance over its luminance + /// (unchanged when the luminance is at most 1e-6, or above 1). + #[inline] + fn luminance(&self, p: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] { + let y = PRO_Y[0] * p[0] + PRO_Y[1] * p[1] + PRO_Y[2] * p[2]; + if y.is_nan() || y <= 1e-6 || y > 1.0 { + return p; + } + let r = self.channel(y, encode) / y; + p.map(|c| c * r) + } + + /// The operator on a linear ProPhoto pixel (`Family.apply`). Per channel, each component goes + /// through [`Self::channel`] (one above 1 passes unchanged). On luminance, the pixel is scaled + /// by `F(Y) / Y` as a whole, components above 1 included, and passes unchanged only when `Y` + /// itself is above 1 (or at most 1e-6). Mix blends the two results in linear light, so an HDR + /// component of a pixel with `Y ≤ 1` moves by the luminance part's share. + #[inline] + pub fn apply(&self, p: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] { + match self.mode { + Mode::PerChannel => p.map(|c| self.channel(c, encode)), + Mode::Luminance => self.luminance(p, encode), + Mode::Mix => { + let (a, b) = (p.map(|c| self.channel(c, encode)), self.luminance(p, encode)); + let w = self.weight; + std::array::from_fn(|k| w * a[k] + (1.0 - w) * b[k]) + } + } + } +} + +/// sRGB decoding in f64 (the tables are built in f64, like the fit). +fn srgb_decode(e: f64) -> f64 { + if e <= 0.04045 { e / 12.92 } else { ((e + 0.055) / 1.055).powf(2.4) } +} + +/// Linear Rec.2020 (the working space) → linear ProPhoto RGB (D50, Bradford), and back. +pub fn prophoto_matrices() -> ([[f32; 3]; 3], [[f32; 3]; 3]) { + let to = REC2020.to_space(&PROPHOTO); + let from = to.inverse().unwrap_or(Mat3::IDENTITY); + (to.to_f32(), from.to_f32()) +} + +/// The active operators of a render, in order (Contrast, Blacks), and the conversions to +/// and from the space they work in. Applied after the tone map, chroma scaling and highlight +/// desaturation, before the colour stage (`finish::finish_with`, the GPU's `finish.wgsl`). +#[derive(Clone, Debug)] +pub struct LightOps { + pub ops: Vec, + pub to_pro: [[f32; 3]; 3], + pub from_pro: [[f32; 3]; 3], +} + +/// The fits of Contrast and Blacks, in the order they apply. +pub const FITS: [&Fit; 2] = [&fitted::CONTRAST, &fitted::BLACKS]; + +/// Whether `s` renders `info` with the V4 operators: process V4 and a raw with its camera's tone +/// curve (other sources keep the tone map's own Contrast and Blacks). +pub fn applies(s: &DevelopSettings, info: &SourceInfo) -> bool { + let camera_look = info.raw && info.camera_tone.is_some(); + match s.process.process() { + Process::V1 | Process::V2 | Process::V3 => false, + Process::V4 => camera_look, + } +} + +impl LightOps { + /// The operators of `s` for `info` (see [`applies`]); `None` when they don't apply or every + /// slider is at 0. + pub fn new(s: &DevelopSettings, info: &SourceInfo) -> Option { + if !applies(s, info) { + return None; + } + let l = &s.light; + let ops: Vec = FITS.iter().zip([l.contrast, l.blacks]).filter_map(|(f, a)| Operator::new(f, a)).collect(); + if ops.is_empty() { + return None; + } + let (to_pro, from_pro) = prophoto_matrices(); + Some(LightOps { ops, to_pro, from_pro }) + } + + /// The operators on a linear Rec.2020 pixel; `encode`: linear → sRGB-encoded on 0..1 (the + /// exact curve or the shared table, as the render encodes). + #[inline] + pub fn apply(&self, d: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] { + let mut p = mul3(&self.to_pro, d); + for op in &self.ops { + p = op.apply(p, encode); + } + mul3(&self.from_pro, p) + } +} + +/// Number of intervals over linear input for 8-bit CPU renders. Deep exports retain [`LightOps`] +/// with the exact sRGB encoder; this approximation is not used for U16 or F32 samples. +const PREVIEW_INTERVALS: usize = 16_384; + +/// An operator with its sRGB encoding and decoding included in one linear-input table. +struct LinearOperator { + black: f32, + white: f32, + // Each linear interval stores [intercept, slope], so a lookup needs no integer-to-float + // conversion or subtraction of neighbouring samples in the pixel loop. + segments: Box<[[f32; 2]; PREVIEW_INTERVALS]>, +} + +impl LinearOperator { + fn new(channel: impl Fn(f32) -> f32) -> Self { + let black = channel(0.0); + let mut previous = black; + let mut segments = Box::new([[0.0; 2]; PREVIEW_INTERVALS]); + for (i, segment) in segments.iter_mut().enumerate() { + let next = channel((i + 1) as f32 / PREVIEW_INTERVALS as f32); + let slope = (next - previous) * PREVIEW_INTERVALS as f32; + let intercept = (previous as f64 - slope as f64 * (i as f64 / PREVIEW_INTERVALS as f64)) as f32; + *segment = [intercept, slope]; + previous = next; + } + Self { black, white: previous, segments } + } + + #[inline(always)] + fn channel(&self, x: f32) -> f32 { + if x >= 1.0 { + if x == 1.0 { self.white } else { x } + } else if x < 0.0 { + self.black + x + } else { + let f = x * PREVIEW_INTERVALS as f32; + let i = (f as u32).min(PREVIEW_INTERVALS as u32 - 1) as usize; + let [intercept, slope] = self.segments[i]; + intercept + slope * x + } + } +} + +/// CPU preview tables for per-channel operations, built once per render. Luminance operations +/// use [`LightOps`] instead, so interpolation cannot change a nearly cancelling luminance sum. +pub(crate) struct PreviewOps { + ops: PreviewOperators, + to_pro: [[f32; 4]; 3], + from_pro: [[f32; 4]; 3], +} + +enum PreviewOperators { + PerChannel(LinearOperator), + Separate(Vec), +} + +impl PreviewOps { + pub(crate) fn new(exact: &LightOps, encode: &impl Fn(f32) -> f32) -> Option { + let ops = &exact.ops; + // Small per-channel errors can cross the luminance cutoff at 1e-6, or be amplified + // by F(Y) / Y. Keep every preceding operation exact too, including Contrast. + if ops.iter().any(|o| o.mode != Mode::PerChannel) { + return None; + } + // A preceding black lift could carry a negative input across zero. Only fuse when + // preceding operators fix zero, so the composed negative extension remains F(0) + x. + // Contrast fixes zero and negative Blacks is per channel, so their usual pair fuses. + let fuse = ops.iter().take(ops.len().saturating_sub(1)).all(|o| o.lut[0] == 0.0); + let ops = if fuse { + PreviewOperators::PerChannel(LinearOperator::new(|x| ops.iter().fold(x, |x, o| o.channel(x, encode)))) + } else { + PreviewOperators::Separate(ops.iter().map(|o| LinearOperator::new(|x| o.channel(x, encode))).collect()) + }; + let columns = |m: [[f32; 3]; 3]| std::array::from_fn(|i| [m[0][i], m[1][i], m[2][i], 0.0]); + Some(Self { ops, to_pro: columns(exact.to_pro), from_pro: columns(exact.from_pro) }) + } + + // Keep the single-table path in the finish loop. An out-of-line call per pixel saves + // little code here but adds register spills to this otherwise small operation. + #[inline(always)] + pub(crate) fn apply(&self, d: [f32; 3]) -> [f32; 3] { + let mut p = mul_preview(&self.to_pro, d); + match &self.ops { + PreviewOperators::PerChannel(op) => p = [op.channel(p[0]), op.channel(p[1]), op.channel(p[2])], + PreviewOperators::Separate(ops) => { + for op in ops { + p = p.map(|c| op.channel(c)); + } + } + } + mul_preview(&self.from_pro, p) + } +} + +/// Padded columns let the compiler multiply the RGB rows together in vector registers. +/// The fourth lane is unused; each RGB row keeps the same arithmetic order as `mul3`. +#[inline(always)] +fn mul_preview(m: &[[f32; 4]; 3], d: [f32; 3]) -> [f32; 3] { + let out: [f32; 4] = std::array::from_fn(|i| m[0][i] * d[0] + m[1][i] * d[1] + m[2][i] * d[2]); + [out[0], out[1], out[2]] +} + +#[inline] +fn mul3(m: &[[f32; 3]; 3], d: [f32; 3]) -> [f32; 3] { + [ + m[0][0] * d[0] + m[0][1] * d[1] + m[0][2] * d[2], + m[1][0] * d[0] + m[1][1] * d[1] + m[1][2] * d[2], + m[2][0] * d[0] + m[2][1] * d[1] + m[2][2] * d[2], + ] +} + +/// `fit_pointwise.py`'s own values for one fit at one amount (generated into +/// [`crate::light_v3_params`]; the tests check the port against them). +#[cfg(test)] +pub struct Reference { + pub amount: f64, + /// `Family.curve` at `light_v3_params::REF_V`. + pub curve: &'static [f64], + /// `Family.apply` on `light_v3_params::REF_PIX` (encoded ProPhoto), where the curve increases. + pub apply: Option<&'static [[f64; 3]]>, +} diff --git a/crates/pipeline/src/light_v3_params.rs b/crates/pipeline/src/light_v3_params.rs new file mode 100644 index 0000000000..07ce6dd0cd --- /dev/null +++ b/crates/pipeline/src/light_v3_params.rs @@ -0,0 +1,315 @@ +//! Fitted constants of process V4's Contrast and Blacks ([`crate::light_v3`]). +//! +//! GENERATED by `tools/light_v3_constants.py rust` from the committed fits named below: do not edit by hand, +//! regenerate (the script must reproduce this file byte for byte). +//! +//! The values are fitted to black-box Lightroom exports of one person's Sony ILCE-7CR photos (the exports' +//! pixels only: no Lightroom code, tables or files), each slider against the same photo's Neutral or another +//! amount exported in the same batch, on the tune photos; the check photos were held out. The exports are +//! private; errors are published only with at least three contributing photos. These are our operator family's +//! parameters (`docs/light-v3.md`), not Lightroom's. +//! +//! - Contrast: `tools/light_v3_fits/contrast.json` (fitted as `v2-contrast-pc.json`), mode `pc`; 155 tune pairs on 20 photos, 61 check pairs on 6 photos; +//! sha256 `2f04d078f1866ccb05fc279b493ccab545adbe2ac178b12df9ebc524c79c2ce1`. +//! - Blacks: `tools/light_v3_fits/blacks.json` (fitted as `v2-blacks-mix.json`), mode `mix`; 148 tune pairs on 19 photos, 60 check pairs on 6 photos; +//! sha256 `b8ee89df8f632d9559649fcba917607ade1511ecaa2041f481dd5b73a318c090`. + +use crate::light_v3::{Fit, Mode}; +#[cfg(test)] +use crate::light_v3::Reference; + +/// The family's knots: the displacement shapes are piecewise linear on them. +pub const KNOTS: [f64; 12] = [0.0, 0.02, 0.05, 0.09, 0.14, 0.2, 0.28, 0.38, 0.5, 0.65, 0.82, 1.0]; + +/// `tools/light_v3_fits/contrast.json`. +pub const CONTRAST: Fit = Fit { + mode: Mode::PerChannel, + signed: true, + params: &[ + 9.797174393178826e-18, -0.017053489024880908, -0.04260284838408044, -0.07195939270312468, -0.09738651081071477, + -0.1088504066519633, -0.10140378035603768, -0.06947815571389163, -0.007856500339789655, 0.08463087858854193, 0.1098534938016389, + 0.30583740028604467, -0.05850866310699469, -0.07854274245013221, -0.09074476735486797, -0.0906596002773617, -0.08429179542961336, + -0.07428102082426319, -0.05004459522573259, -0.00906946010144, 0.056653920573147026, 0.09818533983265328, 0.3070552562874873, + 0.10657448975892592, -0.13962415708911588, 0.37724097657204825, + ], +}; + +/// `tools/light_v3_fits/blacks.json`. +pub const BLACKS: Fit = Fit { + mode: Mode::Mix, + signed: false, + params: &[ + 0.0016748697345088984, 0.032126630862752484, 0.07188512588294256, 0.09530584096821723, 0.12925288090794965, 0.12680972925019743, + 0.10913227308994669, 0.10024857312175768, 0.0835198499581404, 0.05136152009684992, 0.02045048232256003, 0.00011845423640374467, + 0.2706623236742467, 0.42355931120492346, 0.37893058797626605, 0.22045052169596244, 0.20955478047682013, 0.2107908996685734, + 0.16685612159796198, 0.13055496600268582, 0.08667135921560576, 0.03499725744978859, 14.344979966519135, 0.1199976090379452, + 6.829791928600096, 0.5956122696562978, 0.6007994346537187, 22.053184691621333, + ], +}; + +/// Where the reference values are taken: encoded values and pixels (encoded ProPhoto). +#[cfg(test)] +pub const REF_V: [f64; 16] = [ + 0.0, 0.004, 0.012, 0.03, 0.07, 0.11, 0.17, 0.25, 0.33, 0.45, 0.58, 0.7, 0.81, 0.9, 0.97, 1.0, +]; +#[cfg(test)] +pub const REF_PIX: [[f64; 3]; 6] = [ + [0.02, 0.05, 0.01], [0.3, 0.25, 0.2], [0.55, 0.5, 0.62], [0.9, 0.85, 0.7], [0.15, 0.4, 0.35], [0.75, 0.97, 0.99], +]; + +/// The family's own `curve` at [`REF_V`] and `apply` on [`REF_PIX`] for `tools/light_v3_fits/contrast.json` (12 significant +/// digits). +#[cfg(test)] +pub const CONTRAST_REFERENCE: &[Reference] = &[ + Reference { + amount: -100.0, + curve: &[ + 0.0, 0.0157017326214, 0.0471051978642, 0.0951866895547, 0.154643754903, 0.200710700524, 0.257475697853, 0.328035061301, + 0.392162808025, 0.47614243307, 0.554016990408, 0.631130956115, 0.71425768483, 0.845452588982, 0.953635776695, 1.0, + ], + apply: Some(&[ + [0.078508663107, 0.12854274245, 0.0392543315535], [0.369433735705, 0.328035061301, 0.28429179543], + [0.537161666543, 0.509069460101, 0.576490755562], [0.845452588982, 0.768178883473, 0.631130956115], + [0.239598299469, 0.443215406038, 0.407315522905], [0.668915832804, 0.953635776695, 0.984545258898], + ]), + }, + Reference { + amount: -63.0, + curve: &[ + 0.0, 0.0117558826379, 0.0352676479138, 0.0732055944278, 0.126101694535, 0.170122852746, 0.227978700093, 0.301721466955, + 0.371201372402, 0.467327147126, 0.562778518405, 0.654353749223, 0.746542204136, 0.86384609598, 0.959153828794, 1.0, + ], + apply: Some(&[ + [0.0587794131897, 0.102057956904, 0.0293897065949], [0.346020527272, 0.301721466955, 0.255868416571], + [0.541490780829, 0.506011218203, 0.591162168506], [0.86384609598, 0.79576914397, 0.654353749223], + [0.209385555774, 0.428643076049, 0.387988602489], [0.696257592365, 0.959153828794, 0.986384609598], + ]), + }, + Reference { + amount: -25.0, + curve: &[ + 0.0, 0.00669797632024, 0.0200939289607, 0.0450295815589, 0.0895156438599, 0.130914451725, 0.19016858264, 0.267991929431, + 0.344332389013, 0.456027454879, 0.574009302137, 0.684121407008, 0.787925448518, 0.887423433092, 0.966227029927, 1.0, + ], + apply: Some(&[ + [0.0334898816012, 0.0681089814742, 0.0167449408006], [0.316008789537, 0.267991929431, 0.219434495337], + [0.547039966578, 0.502091073979, 0.609968416216], [0.887423433092, 0.831135149637, 0.684121407008], + [0.170657974176, 0.409963835778, 0.363214788663], [0.73130506224, 0.966227029927, 0.988742343309], + ]), + }, + Reference { + amount: -4.0, + curve: &[ + 0.0, 0.0042211975466, 0.0126635926398, 0.0312322222928, 0.0716000186917, 0.111714702007, 0.171653550835, 0.251475094729, + 0.331175061939, 0.450494169731, 0.579508843847, 0.698698170259, 0.808190185513, 0.898968891712, 0.969690667514, 1.0, + ], + apply: Some(&[ + [0.021105987733, 0.0514846914124, 0.0105529938665], [0.301312504095, 0.251475094729, 0.201593365611], + [0.549757317317, 0.500171439768, 0.619177545887], [0.898968891712, 0.848453337568, 0.698698170259], + [0.151693674318, 0.400816899693, 0.351083433835], [0.748467268102, 0.969690667514, 0.989896889171], + ]), + }, + Reference { + amount: -1.0, + curve: &[ + 0.0, 0.00403003956988, 0.0120901187096, 0.0301673410408, 0.0702172893598, 0.110232863843, 0.170224559253, 0.250200324153, + 0.330159578421, 0.450067110356, 0.5799332989, 0.699823205971, 0.809754219477, 0.899859971098, 0.96995799133, 1.0, + ], + apply: Some(&[ + [0.0201501978494, 0.0502016274236, 0.0100750989247], [0.300178243652, 0.250200324153, 0.200216385843], + [0.549967042657, 0.500023282251, 0.619888307225], [0.899859971098, 0.849789956648, 0.699823205971], + [0.150230008193, 0.400110938461, 0.350147134934], [0.749791848474, 0.96995799133, 0.98998599711], + ]), + }, + Reference { + amount: 1.0, + curve: &[ + 0.0, 0.00397028327185, 0.0119108498156, 0.0297772142058, 0.0695009210477, 0.109284415638, 0.169101549483, 0.249092158771, + 0.329255569926, 0.449707840731, 0.580361320706, 0.700802007104, 0.810944204495, 0.900531739739, 0.970159521922, 1.0, + ], + apply: Some(&[ + [0.0198514163593, 0.0496288098987, 0.00992570817964], [0.29917212145, 0.249092158771, 0.199051608167], + [0.550200155898, 0.499931547883, 0.620576207118], [0.900531739739, 0.850797609609, 0.700802007104], + [0.149134843694, 0.399484133579, 0.349311202243], [0.750866642282, 0.970159521922, 0.990053173974], + ]), + }, + Reference { + amount: 4.0, + curve: &[ + 0.0, 0.00386276829016, 0.0115883048705, 0.0289711762573, 0.067695255762, 0.106695434805, 0.165850959769, 0.245807593504, + 0.326562225444, 0.44865080988, 0.581668577311, 0.70370366501, 0.814360331887, 0.902455571598, 0.970736671479, 1.0, + ], + apply: Some(&[ + [0.0193138414508, 0.0482858458702, 0.0096569207254], [0.296176860778, 0.245807593504, 0.195620331007], + [0.550924318987, 0.499683888448, 0.622660921742], [0.902455571598, 0.853683357397, 0.70370366501], + [0.146004712278, 0.397617731312, 0.34681913522], [0.754002149954, 0.970736671479, 0.99024555716], + ]), + }, + Reference { + amount: 25.0, + curve: &[ + 0.0, 0.00303130723309, 0.00909392169928, 0.0227377271685, 0.0537312449465, 0.0866736973109, 0.140712707247, 0.220406592954, + 0.305733397543, 0.440476321314, 0.591778172653, 0.726143473036, 0.840778760722, 0.917333416951, 0.975200025085, 1.0, + ], + apply: Some(&[ + [0.0151565361655, 0.0379001091744, 0.00757826808274], [0.273013181027, 0.220406592954, 0.169084742294], + [0.556524593466, 0.497768628155, 0.638782944901], [0.917333416951, 0.876000125426, 0.726143473036], + [0.121798017215, 0.383184014474, 0.327546875221], [0.778250421984, 0.975200025085, 0.991733341695], + ]), + }, + Reference { + amount: 63.0, + curve: &[ + 0.0, 0.00166203669924, 0.00498611009773, 0.0124723297827, 0.0307349682338, 0.0537014072028, 0.0993144142548, 0.178575600043, + 0.271431971089, 0.427014372342, 0.608426903093, 0.763097901214, 0.884285279574, 0.941834618872, 0.982550385662, 1.0, + ], + apply: Some(&[ + [0.00831018349621, 0.0207966223556, 0.00415509174811], [0.234866663076, 0.178575600043, 0.125385281671], + [0.56574726332, 0.494614530364, 0.665333089458], [0.941834618872, 0.912751928309, 0.763097901214], + [0.0819338359776, 0.35941421432, 0.295808843098], [0.818183073196, 0.982550385662, 0.994183461887], + ]), + }, + Reference { + amount: 100.0, + curve: &[ + 0.0, 0.000589302195024, 0.00176790658507, 0.00443005785539, 0.0127188794564, 0.0278697600538, 0.0668815412687, 0.145803734783, + 0.244559031965, 0.416467809921, 0.621470101755, 0.792049294828, 0.918369810554, 0.961029718779, 0.988308915634, 1.0, + ], + apply: Some(&[ + [0.00294651097512, 0.00739715161592, 0.00147325548756], [0.204981344572, 0.145803734783, 0.091149593348], + [0.57297262597, 0.49214349966, 0.686133402803], [0.961029718779, 0.941544578168, 0.792049294828], + [0.0507028398824, 0.340792120182, 0.270944156893], [0.849467711067, 0.988308915634, 0.996102971878], + ]), + }, +]; + +/// The family's own `curve` at [`REF_V`] and `apply` on [`REF_PIX`] for `tools/light_v3_fits/blacks.json` (12 significant +/// digits). +#[cfg(test)] +pub const BLACKS_REFERENCE: &[Reference] = &[ + Reference { + amount: -100.0, + curve: &[ + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0396726450283, 0.141176489367, 0.304319552499, 0.472849624284, 0.62852690601, + 0.771963089505, 0.880557079195, 0.964167123758, 1.0, + ], + apply: Some(&[ + [0.0, 0.0, 0.0], [0.0979960559384, 0.0396726450312, 8.67909201708e-12], [0.434072902922, 0.369445033999, 0.524551919414], + [0.880557079192, 0.820835618793, 0.628526906024], [1.62784132506e-11, 0.239194070991, 0.169963444981], + [0.693725171247, 0.964167123755, 0.988055707915], + ]), + }, + Reference { + amount: -63.0, + curve: &[ + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0769799089595, 0.159002658298, 0.248306215942, 0.386971900482, 0.533641791607, 0.669077433807, + 0.793543473258, 0.891588093197, 0.967476427959, 1.0, + ], + apply: Some(&[ + [0.0, 0.0, 0.0], [0.212603750827, 0.159002658299, 0.109336909762], [0.49984457601, 0.443515883354, 0.578704745728], + [0.891588093196, 0.837382139795, 0.669077433813], [0.0554085751144, 0.330427917606, 0.27210785935], + [0.72565290629, 0.967476427958, 0.989158809318], + ]), + }, + Reference { + amount: -25.0, + curve: &[ + 0.0, 0.0, 0.0, 0.0039713718625, 0.0375281504298, 0.0844641752827, 0.152600319953, 0.232978681132, 0.314718938796, + 0.438210409673, 0.571328561555, 0.694215843567, 0.806921758549, 0.898426528234, 0.96952795847, 1.0, + ], + apply: Some(&[ + [1.38361828441e-12, 0.0157222994288, 6.91809142207e-13], [0.28365227602, 0.232978681132, 0.183041203846], + [0.540618281274, 0.489434480805, 0.612275601929], [0.898426528233, 0.84763979235, 0.694215843568], + [0.132306397362, 0.386986338539, 0.335430047312], [0.745445804924, 0.96952795847, 0.989842652823], + ]), + }, + Reference { + amount: -4.0, + curve: &[ + 0.0, 0.00384203333958, 0.0115267901451, 0.029063081396, 0.0688311531515, 0.109080820198, 0.169373686394, 0.249387305769, + 0.329449947556, 0.449575625482, 0.579687865532, 0.699791795259, 0.809889196554, 0.899943361788, 0.969983008536, 1.0, + ], + apply: Some(&[ + [0.0192115469507, 0.0487661502866, 0.00960560094376], [0.299411552286, 0.249387305769, 0.199389556317], + [0.549662298498, 0.499619686776, 0.61972195491], [0.899943361788, 0.849915042681, 0.699791795259], + [0.149363106446, 0.399531564189, 0.349475544402], [0.749836068575, 0.969983008536, 0.989994336179], + ]), + }, + Reference { + amount: -1.0, + curve: &[ + 0.0, 0.00398722513591, 0.0119617312187, 0.0299242307978, 0.0699054746135, 0.109925665346, 0.169949349621, 0.249950451029, + 0.32995551691, 0.449965680563, 0.579974757487, 0.69998316235, 0.809991039255, 0.899995419632, 0.96999862589, 1.0, + ], + apply: Some(&[ + [0.0199362373015, 0.0499002177906, 0.009968104698], [0.29995241186, 0.249950451029, 0.199950633032], + [0.549972689865, 0.499969243828, 0.619977514317], [0.899995419632, 0.849993129448, 0.69998316235], + [0.149948494014, 0.399962117299, 0.349957586943], [0.749986742762, 0.96999862589, 0.989999541963], + ]), + }, + Reference { + amount: 1.0, + curve: &[ + 9.31612027339e-06, 0.00404319245864, 0.0121109451354, 0.0302524139772, 0.0704649827756, 0.11060564863, 0.170712147943, + 0.250643898657, 0.330582319062, 0.450503332955, 0.580369162543, 0.700235118441, 0.810123865526, 0.900063195347, 0.970018958604, + 1.0, + ], + apply: Some(&[ + [0.0201752429349, 0.0503888012921, 0.0100906298252], [0.300630744288, 0.250626419466, 0.200631616538], + [0.550429399642, 0.500454032729, 0.620394920846], [0.90007223641, 0.850090998192, 0.700176696162], + [0.150565756988, 0.400578185286, 0.350572708933], [0.750135238759, 0.970032675648, 0.990024911688], + ]), + }, + Reference { + amount: 4.0, + curve: &[ + 4.44679248931e-05, 0.00420616726172, 0.0125295659354, 0.0312048283459, 0.0722194667453, 0.112890896317, 0.17339924135, + 0.253073472246, 0.332779539074, 0.452402520726, 0.581762095353, 0.701122272887, 0.810591237848, 0.900301645519, 0.970090493656, + 1.0, + ], + apply: Some(&[ + [0.0208391227968, 0.0518558616479, 0.0104339209625], [0.303010755867, 0.252990062923, 0.203015330491], + [0.55204964314, 0.502167204295, 0.621885228625], [0.900344802502, 0.850434355079, 0.700843514096], + [0.152703002383, 0.402759872928, 0.352733667786], [0.750645594216, 0.970155972394, 0.990118916658], + ]), + }, + Reference { + amount: 25.0, + curve: &[ + 0.000351031037929, 0.00562749010759, 0.0161804082469, 0.0395109485272, 0.0875205323187, 0.132820816064, 0.19683370592, + 0.274262075537, 0.351941758888, 0.468965565542, 0.593910029809, 0.708859253437, 0.814667248041, 0.902381198134, 0.97071435944, + 1.0, + ], + apply: Some(&[ + [0.0268094892594, 0.0646518089884, 0.0135180994291], [0.323771669718, 0.273605097162, 0.223833590382], + [0.566181459749, 0.517108276593, 0.63489439536], [0.902722015601, 0.853428836176, 0.7066658074], + [0.171494494367, 0.421790810113, 0.371579649929], [0.755101084946, 0.971231540587, 0.990939254456], + ]), + }, + Reference { + amount: 63.0, + curve: &[ + 0.000995014140305, 0.00861319796625, 0.0238495656181, 0.0569592350811, 0.11966278055, 0.174686686427, 0.246061413214, + 0.31877200482, 0.392194957135, 0.503758795817, 0.619428639797, 0.725111974413, 0.823229536124, 0.906749619145, 0.972024885744, + 1.0, + ], + apply: Some(&[ + [0.0404539765541, 0.0915381262658, 0.0205483468996], [0.367405560588, 0.316916949778, 0.267702217691], + [0.595875558955, 0.54849590131, 0.662288333975], [0.907716480454, 0.859719346711, 0.718935705489], + [0.211650252506, 0.461789763271, 0.411168543529], [0.764487032294, 0.973492582642, 0.992665468794], + ]), + }, + Reference { + amount: 100.0, + curve: &[ + 0.00167486973451, 0.0117652219602, 0.0319459264115, 0.0753794625361, 0.153595483426, 0.218884656944, 0.298031305079, + 0.36576131915, 0.434690423106, 0.540490151276, 0.646368740699, 0.742270038399, 0.832268778662, 0.911361379068, 0.97340841372, + 1.0, + ], + apply: Some(&[ + [0.055421940602, 0.119927912612, 0.0288346946948], [0.413495225374, 0.362648809539, 0.314154311953], + [0.627234264731, 0.5816340005, 0.691296631565], [0.912990263469, 0.866360468302, 0.731944464499], + [0.254705410536, 0.504042777472, 0.452962701964], [0.774433618221, 0.975881980047, 0.994492187831], + ]), + }, +]; diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index 6d09cf7557..22c17571f9 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -4,7 +4,7 @@ use lightcraft_color::cct::{temp_tint_to_xy, wb_matrix, xy_to_temp_tint}; use lightcraft_color::{REC2020, luminance_2020}; use lightcraft_develop::{DevelopSettings, Process}; -use lightcraft_raster::blur::gaussian; +use lightcraft_raster::blur::{gauss_taps, gaussian, gaussian_taps}; use std::sync::Arc; use lightcraft_raster::{Plane, Rgb32f, par_join}; @@ -371,11 +371,11 @@ pub fn base_detail_radius(px_per_long: f64) -> usize { } /// Median radius (px) of the highlights/shadows base of `s`'s rendering process at `px_per_long`: -/// 0 (no median) under V1, [`base_detail_radius`] from V2. +/// 0 (no median) under V1, [`base_detail_radius`] from V2 (later processes keep V2's base). pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize { match s.process.process() { Process::V1 => 0, - Process::V2 => base_detail_radius(px_per_long), + Process::V2 | Process::V3 | Process::V4 => base_detail_radius(px_per_long), } } @@ -521,6 +521,8 @@ pub(crate) struct Planes { pub base: Option<(BaseKey, Arc)>, pub clarity: Option<(u32, Arc)>, pub texture: Option<(u32, Arc)>, + /// Sharpening blur (exact Gaussian at the sharpen radius). + pub sharpen: Option<(SharpenKey, Arc)>, /// Dark channel and its airlight. pub dark: Option<(u32, Arc, f32)>, /// Blurred chromaticity (local Moiré / Noise). @@ -532,7 +534,7 @@ impl Planes { /// enough for a draft: the wide blurs (base, clarity, dehaze, chromaticity). Its `key` matches /// no image, so only another draft takes them. pub fn for_other_nr(self) -> Planes { - Planes { key: 0, pre_nr: self.pre_nr, log_l: None, texture: None, ..self } + Planes { key: 0, pre_nr: self.pre_nr, log_l: None, texture: None, sharpen: None, ..self } } } @@ -541,6 +543,16 @@ impl Planes { /// processes, so a photo moved to another one (Update to Current Process, undo) recomputes it. pub type BaseKey = (u32, Process, usize); +pub type SharpenKey = (u32, Process); + +pub fn sharpen_key(s: &DevelopSettings, sigma: f32) -> SharpenKey { + (sigma.to_bits(), s.process.process()) +} + +pub fn pixel_sharpen(s: &DevelopSettings) -> bool { + s.process.process() >= Process::V3 +} + /// The [`BaseKey`] of a base at `sigma` for `s` (`detail`: [`PlaneSigmas::base_detail`]). pub fn base_key(s: &DevelopSettings, sigma: f32, detail: usize) -> BaseKey { (sigma.to_bits(), s.process.process(), detail) @@ -584,6 +596,8 @@ pub struct PlaneSigmas { pub clarity: Option, /// Texture / sharpening band (Gaussian). pub texture: Option, + /// Sharpening blur (exact Gaussian, see [`sharpen_sigma`]). + pub sharpen: Option, /// Dehaze dark channel (Gaussian). pub dark: Option, /// Chromaticity blur for local Moiré / colour noise (Gaussian). @@ -595,7 +609,45 @@ pub fn texture_sigma(px_per_long: f64) -> f32 { (0.0018 * px_per_long as f32).max(0.6) } -pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, q: Quality) -> PlaneSigmas { +/// Sharpening blur radius in output pixels before clamping: Radius (source pixels) times the +/// output pixels per original pixel (`native_long` = the original photo's long edge), so a preview and +/// an export show the same detail at the same displayed scale. +pub fn sharpen_sigma_raw(s: &DevelopSettings, px_per_long: f64, native_long: f64) -> f32 { + let r = s.detail.sharpen_radius; + let radius = if r.is_finite() { r.clamp(0.1, 10.0) } else { 1.0 }; + (radius * px_per_long / native_long.max(1.0)) as f32 +} + +/// Smallest and largest sigma (px) of the sharpening blur. The largest is the most the Gaussian taps +/// support (CPU and GPU share them), so an enlarging export keeps every Radius step distinct. +pub const SHARPEN_SIGMA_MIN: f32 = 0.5; +pub const SHARPEN_SIGMA_MAX: f32 = lightcraft_raster::blur::GAUSS_SIGMA_MAX; + +/// The sharpening blur's sigma for a raw value of [`sharpen_sigma_raw`]. +pub fn sharpen_sigma(raw: f32) -> f32 { + raw.clamp(SHARPEN_SIGMA_MIN, SHARPEN_SIGMA_MAX) +} + +/// Match the continuous Gaussian's Nyquist response below half a pixel, using a representable +/// FIR blur. Blend the correction out between half and one pixel: no jump at the floor, and +/// full-pixel sharpening (including Radius 1 at native size) is unchanged. +pub fn sharpen_gain(raw: f32) -> f32 { + if !raw.is_finite() || raw <= 0.0 { + return 0.0; + } + if raw >= 1.0 { + return 1.0; + } + let taps = gauss_taps(sharpen_sigma(raw)); + let radius = taps.len() / 2; + let response = taps.iter().enumerate().map(|(i, &t)| if (i + radius).is_multiple_of(2) { t } else { -t }).sum::(); + let desired = -(-0.5 * std::f32::consts::PI.powi(2) * raw * raw).exp_m1(); + let ratio = desired / (1.0 - response).max(1e-6); + let blend = ((1.0 - raw) / 0.5).clamp(0.0, 1.0); + 1.0 + (ratio - 1.0) * blend +} + +pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, native_long: f64, q: Quality) -> PlaneSigmas { let ppl = px_per_long as f32; // A hidden mask, or one with no components, does not change the picture. Its sliders must // not pick the tone base Clarity reads (#1214). @@ -614,16 +666,19 @@ pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, q: Quality) -> PlaneS let clarity = (s.effects.clarity != 0.0 || local_any(|a| a.clarity)).then(|| (0.012 * ppl).max(1.0)); // local Noise and Defringe read the fine detail band too let texture = (s.effects.texture != 0.0 - || s.detail.sharpen_amount != 0.0 || local_any(|a| a.texture) - || local_any(|a| a.sharpness) || local_any(|a| a.noise) + || (!pixel_sharpen(s) && (s.detail.sharpen_amount != 0.0 || local_any(|a| a.sharpness))) || s.masks.iter().filter(live).any(|m| m.adjust.defringe > 0.0)) .then(|| texture_sigma(px_per_long)); let dark = (s.effects.dehaze != 0.0 || local_any(|a| a.dehaze)).then(|| (0.02 * ppl).max(1.0)); let chroma = (local_any(|a| a.moire) || s.masks.iter().filter(live).any(|m| m.adjust.noise > 0.0)).then(|| (CHROMA_SIGMA * ppl).max(1.0)); let base_detail = if base.is_some() { tone_base_detail(s, px_per_long) } else { 0 }; - PlaneSigmas { base, base_detail, clarity, texture, dark, chroma } + // V1/V2 keep their texture-band sharpening; only V3 requests the pixel-scale plane. + let sharpen_raw = sharpen_sigma_raw(s, px_per_long, native_long); + let sharpen = (pixel_sharpen(s) && sharpen_gain(sharpen_raw) > 0.0 && (s.detail.sharpen_amount != 0.0 || local_any(|a| a.sharpness))) + .then(|| sharpen_sigma(sharpen_raw)); + PlaneSigmas { base, base_detail, clarity, texture, sharpen, dark, chroma } } /// The spatial planes the per-pixel stage needs for `img` (white-balanced, before exposure), @@ -635,15 +690,23 @@ pub(crate) fn prepare( s: &DevelopSettings, frame: &Frame, px_per_long: f64, + native_long: f64, q: Quality, planes: &mut Planes, mattes: Option<&masks::Mattes>, ) -> Prepared { let log_l = planes.log_l.get_or_insert_with(|| Arc::new(timed("log_l", || img.map(log_lum)))).clone(); - let PlaneSigmas { base: base_sigma, base_detail, clarity: clarity_sigma, texture: texture_sigma, dark: dark_sigma, chroma: chroma_sigma } = - plane_sigmas(s, px_per_long, q); + let PlaneSigmas { + base: base_sigma, + base_detail, + clarity: clarity_sigma, + texture: texture_sigma, + sharpen: sharpen_sigma_px, + dark: dark_sigma, + chroma: chroma_sigma, + } = plane_sigmas(s, px_per_long, native_long, q); - let Planes { base: sb, clarity: sc, texture: st, dark: sd, chroma: sch, .. } = planes; + let Planes { base: sb, clarity: sc, texture: st, sharpen: ss, dark: sd, chroma: sch, .. } = planes; let chroma_blur = chroma_sigma.map(|sg| match sch { Some((k, c)) if *k == sg.to_bits() => c.clone(), _ => { @@ -653,14 +716,22 @@ pub(crate) fn prepare( } }); let l = &log_l; - let (base, (clarity_blur, (texture_blur, dark))) = par_join( + let (base, (clarity_blur, ((texture_blur, sharpen_blur), dark))) = par_join( || base_sigma.map(|sg| plane_at(sb, base_key(s, sg, base_detail), || timed("base", || tone_base(l, sg, base_detail)))), || { par_join( || clarity_sigma.map(|sg| plane_at(sc, sg.to_bits(), || timed("clarity", || guided_fast(l, sg, CLARITY_EPS)))), || { par_join( - || texture_sigma.map(|sg| plane_at(st, sg.to_bits(), || timed("texture", || gaussian(l, sg)))), + || { + par_join( + || texture_sigma.map(|sg| plane_at(st, sg.to_bits(), || timed("texture", || gaussian(l, sg)))), + || { + sharpen_sigma_px + .map(|sg| plane_at(ss, sharpen_key(s, sg), || timed("sharpen", || gaussian_taps(l, &gauss_taps(sg))))) + }, + ) + }, || { dark_sigma.map(|sg| match sd { Some((k, d, air)) if *k == sg.to_bits() => (d.clone(), *air), @@ -684,7 +755,7 @@ pub(crate) fn prepare( }; let ev = s.light.exposure as f32; let masks = timed("masks", || masks::evaluate(&s.masks, frame, img.width, img.height, &img, &log_l, ev, mattes)); - Prepared { img, log_l, base, clarity_blur, texture_blur, dark, chroma_blur, air, masks, px_per_long } + Prepared { img, log_l, base, clarity_blur, texture_blur, sharpen_blur, dark, chroma_blur, air, masks, px_per_long } } /// The airlight of the whole output frame, estimated on a small render of it (`proxy_w` px wide): @@ -814,17 +885,17 @@ mod tests { adjust: lightcraft_develop::LocalAdjustments { highlights: 40.0, ..Default::default() }, ..Default::default() }); - assert!(plane_sigmas(&s, 2000.0, Quality::Full).base.is_none()); + assert!(plane_sigmas(&s, 2000.0, 2000.0, Quality::Full).base.is_none()); s.masks[0].visible = true; s.masks[0].components.clear(); - assert!(plane_sigmas(&s, 2000.0, Quality::Full).base.is_none()); + assert!(plane_sigmas(&s, 2000.0, 2000.0, Quality::Full).base.is_none()); s.masks[0].components.push(MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: MaskShape::Linear { start: Point::new(0.0, 0.0), end: Point::new(1.0, 0.0) }, }); - assert!(plane_sigmas(&s, 2000.0, Quality::Full).base.is_some()); + assert!(plane_sigmas(&s, 2000.0, 2000.0, Quality::Full).base.is_some()); } #[test] diff --git a/crates/pipeline/src/lut.rs b/crates/pipeline/src/lut.rs index 00f6ea1852..971599cbbf 100644 --- a/crates/pipeline/src/lut.rs +++ b/crates/pipeline/src/lut.rs @@ -1,7 +1,7 @@ //! 3D LUT profiles: `.cube` files (the plain-text Cube LUT format: `LUT_3D_SIZE`, optional //! `DOMAIN_MIN` / `DOMAIN_MAX`, then size³ "r g b" lines with red changing fastest), applied to //! the display-encoded output colour and blended by the profile amount. Profiles are registered -//! here by id (`lut:…`) and found by the finishing stage; LUT profiles render on the CPU. +//! here by id (`lut:…`) and found by the finishing stage (CPU loop and GPU kernel alike). use std::collections::HashMap; use std::sync::{Arc, OnceLock, RwLock}; @@ -110,7 +110,7 @@ pub fn unregister(id: &str) { registry().write().unwrap_or_else(|e| e.into_inner()).remove(id); } -/// Profile ids that render with a LUT (and so on the CPU). +/// Profile ids that render with a LUT. pub fn is_lut_profile(id: &str) -> bool { id.starts_with("lut:") } diff --git a/crates/pipeline/src/optics.rs b/crates/pipeline/src/optics.rs index 640b7e620d..883be6730f 100644 --- a/crates/pipeline/src/optics.rs +++ b/crates/pipeline/src/optics.rs @@ -603,35 +603,60 @@ fn hue_weight(h: f32, lo: f32, hi: f32) -> f32 { /// Long edge (px) at which defringe widths are specified: fringes are 1–7 px wide on a ~4000 px image. pub const DEFRINGE_REF_LONG: f64 = 4000.0; -/// Defringe: desaturate purple / green colour fringes that sit next to high-contrast edges. `scale` is output -/// pixels per reference pixel (output long edge / [`DEFRINGE_REF_LONG`]) so the fringe width is the same -/// fraction of the image at any size. -pub fn defringe(img: &mut Rgb32f, s: &DevelopSettings, scale: f64) { +/// Defringe's resolved parameters (the CPU stage below and the GPU kernels both read these). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct DefringeParams { + /// Radius (output px) of the lightness min / max filters that find edges. + pub radius: usize, + /// Purple and green OkLab hue ranges (degrees, lo ≤ hi) and strengths (0..1). + pub purple: (f32, f32), + pub green: (f32, f32), + pub purple_strength: f32, + pub green_strength: f32, +} + +/// Defringe's parameters for `s` at `scale` output pixels per reference pixel, or `None` when it +/// does nothing. +pub fn defringe_params(s: &DevelopSettings, scale: f64) -> Option { let o = &s.optics; if !s.section_enabled("optics") || (o.defringe_purple_amount <= 0.0 && o.defringe_green_amount <= 0.0) { - return; + return None; } - let (w, h) = (img.width, img.height); // as far as the sliders go (0–20): an amount from a damaged catalog or sidecar made the // radius overflow let max_amt = o.defringe_purple_amount.max(o.defringe_green_amount).min(20.0); - // fringe width in source px grows with the amount (1..7 px), in output px at least one (and - // never wider than the picture) - let radius = ((1.0 + max_amt * 0.3) * scale).round(); - let radius = if radius.is_finite() { radius.clamp(1.0, w.max(h).max(1) as f64) as usize } else { 1 }; - // perceptual lightness and its local range (dilated contrast) - let lab: Vec<[f32; 3]> = img.data.iter().map(|p| oklab_from_2020([p[0].max(0.0), p[1].max(0.0), p[2].max(0.0)])).collect(); - let l = Plane { width: w, height: h, data: lab.iter().map(|p| p[0]).collect() }; - let (lo, hi) = (min_filter(&l, radius, false), min_filter(&l, radius, true)); + // fringe width in source px grows with the amount (1..7 px), in output px at least one + let radius = ((1.0 + max_amt * 0.3) * scale).round().max(1.0); + // (an absurd scale must not ask for a filter wider than any image; the stages clamp it to theirs) + let radius = if radius.is_finite() { radius.min(1e6) as usize } else { 1 }; let range = |lo: f64, hi: f64, span: (f32, f32)| { let a = span.0 + (span.1 - span.0) * (lo / 100.0) as f32; let b = span.0 + (span.1 - span.0) * (hi / 100.0) as f32; (a.min(b), a.max(b)) }; - let pr = range(o.defringe_purple_hue_lo, o.defringe_purple_hue_hi, PURPLE_HUES); - let gr = range(o.defringe_green_hue_lo, o.defringe_green_hue_hi, GREEN_HUES); - let ps = (o.defringe_purple_amount / 8.0).min(1.0) as f32; - let gs = (o.defringe_green_amount / 8.0).min(1.0) as f32; + Some(DefringeParams { + radius, + purple: range(o.defringe_purple_hue_lo, o.defringe_purple_hue_hi, PURPLE_HUES), + green: range(o.defringe_green_hue_lo, o.defringe_green_hue_hi, GREEN_HUES), + purple_strength: (o.defringe_purple_amount / 8.0).min(1.0) as f32, + green_strength: (o.defringe_green_amount / 8.0).min(1.0) as f32, + }) +} + +/// Defringe: desaturate purple / green colour fringes that sit next to high-contrast edges. `scale` is output +/// pixels per reference pixel (output long edge / [`DEFRINGE_REF_LONG`]) so the fringe width is the same +/// fraction of the image at any size. +pub fn defringe(img: &mut Rgb32f, s: &DevelopSettings, scale: f64) { + let Some(DefringeParams { radius, purple: pr, green: gr, purple_strength: ps, green_strength: gs }) = defringe_params(s, scale) else { + return; + }; + let (w, h) = (img.width, img.height); + // never wider than the picture + let radius = radius.clamp(1, w.max(h).max(1)); + // perceptual lightness and its local range (dilated contrast) + let lab: Vec<[f32; 3]> = img.data.iter().map(|p| oklab_from_2020([p[0].max(0.0), p[1].max(0.0), p[2].max(0.0)])).collect(); + let l = Plane { width: w, height: h, data: lab.iter().map(|p| p[0]).collect() }; + let (lo, hi) = (min_filter(&l, radius, false), min_filter(&l, radius, true)); for_rows(&mut img.data, w, |y, row| { for (x, px) in row.iter_mut().enumerate() { let i = y * w + x; diff --git a/crates/pipeline/src/spots.rs b/crates/pipeline/src/spots.rs index 0bd52f2c11..4062d6451e 100644 --- a/crates/pipeline/src/spots.rs +++ b/crates/pipeline/src/spots.rs @@ -39,14 +39,28 @@ fn radius_px(size: f64, ppl: f64) -> f64 { (size * ppl).max(1.0) } -/// Mean colour of `img` in a disc/annulus. -fn ring_stats(img: &Rgb32f, c: (f32, f32), r0: f32, r1: f32) -> Option> { +/// Directions (cos, sin) of the 24 spokes [`ring_stats`] samples along. +pub fn ring_dirs() -> [(f32, f32); 24] { + std::array::from_fn(|i| { + let a = i as f32 / 24.0 * std::f32::consts::TAU; + (a.cos(), a.sin()) + }) +} + +/// The radii (inner, middle, outer) of the rings a source is scored on for a spot of radius `r`: +/// the surroundings (compared between target and source) and the inside of the source. +pub fn score_radii(r: f32) -> [[f32; 3]; 2] { + let ring = |r0: f32, r1: f32| [r0, (r0 + r1) / 2.0, r1]; + [ring(r * 1.05, r * 1.6), ring(r * 0.2, r * 0.9)] +} + +/// Samples of `img` along the spokes at three radii (spoke by spoke); `None` when one falls +/// outside the image. +fn ring_stats(img: &Rgb32f, c: (f32, f32), radii: [f32; 3]) -> Option> { let mut out = Vec::new(); - let n = 24; - for i in 0..n { - let a = i as f32 / n as f32 * std::f32::consts::TAU; - for rr in [r0, (r0 + r1) / 2.0, r1] { - let (x, y) = (c.0 + a.cos() * rr, c.1 + a.sin() * rr); + for (cos, sin) in ring_dirs() { + for rr in radii { + let (x, y) = (c.0 + cos * rr, c.1 + sin * rr); if x < 0.0 || y < 0.0 || x >= img.width as f32 || y >= img.height as f32 { return None; } @@ -57,9 +71,10 @@ fn ring_stats(img: &Rgb32f, c: (f32, f32), r0: f32, r1: f32) -> Option f32 { - let (Some(a), Some(b)) = (ring_stats(img, target, r * 1.05, r * 1.6), ring_stats(img, source, r * 1.05, r * 1.6)) else { return f32::MAX }; + let [around, within] = score_radii(r); + let (Some(a), Some(b)) = (ring_stats(img, target, around), ring_stats(img, source, around)) else { return f32::MAX }; // also compare the inside of the source against the target's surroundings (texture continuity) - let inside = ring_stats(img, source, r * 0.2, r * 0.9); + let inside = ring_stats(img, source, within); let mut s = 0.0; for (p, q) in a.iter().zip(&b) { for c in 0..3 { @@ -78,24 +93,39 @@ fn score(img: &Rgb32f, target: (f32, f32), source: (f32, f32), r: f32) -> f32 { /// Candidate source offsets (output pixels) for a spot of radius `r` at `target`, best first /// (candidates reaching outside the image are left out). pub fn ranked_sources(img: &Rgb32f, target: (f32, f32), r: f32) -> Vec<(f32, f32)> { - let mut c: Vec<(f32, (f32, f32))> = Vec::new(); + let scores: Vec = candidates(r).iter().map(|d| score(img, target, (target.0 + d.0, target.1 + d.1), r)).collect(); + rank(&candidates(r), &scores) +} + +/// The source offsets [`ranked_sources`] tries for a spot of radius `r`, in order: 16 directions +/// on each of three rings. +pub fn candidates(r: f32) -> Vec<(f32, f32)> { + let mut c = Vec::with_capacity(48); for ring in [2.4f32, 3.2, 4.2] { for i in 0..16 { let a = i as f32 / 16.0 * std::f32::consts::TAU; - let d = (a.cos() * r * ring, a.sin() * r * ring); - let s = score(img, target, (target.0 + d.0, target.1 + d.1), r); - if s < f32::MAX { - c.push((s, d)); - } + c.push((a.cos() * r * ring, a.sin() * r * ring)); } } + c +} + +/// `candidates` ordered by `scores` (best first, ties in candidate order), leaving out those +/// that scored `f32::MAX` (they reach outside the image). +pub fn rank(candidates: &[(f32, f32)], scores: &[f32]) -> Vec<(f32, f32)> { + let mut c: Vec<(f32, (f32, f32))> = scores.iter().zip(candidates).filter(|(s, _)| **s < f32::MAX).map(|(s, d)| (*s, *d)).collect(); c.sort_by(|a, b| a.0.total_cmp(&b.0)); c.into_iter().map(|(_, d)| d).collect() } +/// The offset used when no candidate fits in the image. +pub fn fallback_source(r: f32) -> (f32, f32) { + (r * 2.5, 0.0) +} + /// Pick a source offset (in output pixels) for a remove/heal spot. pub fn auto_source(img: &Rgb32f, target: (f32, f32), r: f32) -> (f32, f32) { - ranked_sources(img, target, r).first().copied().unwrap_or((r * 2.5, 0.0)) + ranked_sources(img, target, r).first().copied().unwrap_or_else(|| fallback_source(r)) } /// A source offset (normalized, as [`Spot::source_offset`]) for `spot` on `src` developed with @@ -259,6 +289,86 @@ pub fn window_for_reads_checked( ) } +/// One spot as both renderers lay it out, in output pixels. +#[derive(Clone, Debug, PartialEq)] +pub struct SpotLayout { + /// Radius. + pub r: f32, + /// The stroke's points. + pub pts: Vec<(f32, f32)>, + /// Where the patch is read from, relative to the target; `None`: chosen automatically + /// ([`auto_source`] around the first point, on the image as the earlier spots left it). + pub offset: Option<(f32, f32)>, + /// The box the spot works in: left, top, width, height (inside the image, never empty). + pub bx: usize, + pub by: usize, + pub bw: usize, + pub bh: usize, + /// Alpha at distance d from the stroke: `(1 − smoothstep(inner, r, d)) · opacity`. + pub inner: f32, + pub opacity: f32, + /// Heal / Remove (tone from the surroundings) rather than Clone or Fill. + pub heal: bool, + /// Content-aware Fill: the stroke is rebuilt from the box around it (CPU only; the GPU + /// renderer leaves photos with a Fill spot to the CPU). + pub fill: bool, +} + +/// `spot`'s layout in a `w × h` output of `frame` (`ppl` = output pixels per long-edge unit); +/// `None` when it has no points or its box misses the image. +pub fn layout(spot: &Spot, frame: &Frame, w: usize, h: usize, ppl: f64) -> Option { + let to_out = frame.norm_to_out(w, h); + let r = radius_px(spot.size, ppl) as f32; + let pts: Vec<(f32, f32)> = spot + .points + .iter() + .map(|p| { + let q = to_out.apply(*p); + (q.x as f32, q.y as f32) + }) + .collect(); + pts.first()?; + let fill = spot.mode == SpotMode::Fill; + let offset = if fill { + Some((0.0, 0.0)) + } else { + spot.source_offset.map(|o| { + let a = to_out.apply(Point::new(0.0, 0.0)); + let b = to_out.apply(o); + ((b.x - a.x) as f32, (b.y - a.y) as f32) + }) + }; + // Bounding box of the stroke. + let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN); + for p in &pts { + x0 = x0.min(p.0 - r); + y0 = y0.min(p.1 - r); + x1 = x1.max(p.0 + r); + y1 = y1.max(p.1 + r); + } + // content-aware fill reads the spot's surroundings (the window holds 2 radii around it) + let pad = if fill { 2.0 * r } else { r }; + let (bx0, by0) = (((x0 - pad).floor().max(0.0)) as usize, ((y0 - pad).floor().max(0.0)) as usize); + let (bx1, by1) = (((x1 + pad).ceil() as usize).min(w), ((y1 + pad).ceil() as usize).min(h)); + if bx1 <= bx0 || by1 <= by0 { + return None; + } + let feather = (spot.feather / 100.0).clamp(0.0, 1.0) as f32; + Some(SpotLayout { + r, + pts, + offset, + bx: bx0, + by: by0, + bw: bx1 - bx0, + bh: by1 - by0, + inner: r * (1.0 - feather * 0.8), + opacity: (spot.opacity / 100.0).clamp(0.0, 1.0) as f32, + heal: matches!(spot.mode, SpotMode::Remove | SpotMode::Heal), + fill, + }) +} + /// Content-aware fill of the box: `src` becomes `tgt` with every pixel under the stroke (`alpha > 0`) /// rebuilt from the rest of the box. Falls back to a smooth membrane fill when the box holds no whole /// patch to copy from. @@ -275,50 +385,13 @@ fn fill_box(src: &mut [[f32; 3]], tgt: &[[f32; 3]], alpha: &[f32], bw: usize, bh /// Apply all spots to `img` (output resolution). `ppl` = output pixels per long-edge unit. pub fn apply(img: &mut Rgb32f, spots: &[Spot], frame: &Frame, ppl: f64) { - if spots.is_empty() { - return; - } let (w, h) = (img.width, img.height); - let to_out = frame.norm_to_out(w, h); for spot in spots { - let r = radius_px(spot.size, ppl) as f32; - let pts: Vec<(f32, f32)> = spot - .points - .iter() - .map(|p| { - let q = to_out.apply(*p); - (q.x as f32, q.y as f32) - }) - .collect(); - let Some(&first) = pts.first() else { continue }; - let fill = spot.mode == SpotMode::Fill; - let offset = match spot.source_offset { - _ if fill => (0.0, 0.0), - Some(o) => { - let a = to_out.apply(Point::new(0.0, 0.0)); - let b = to_out.apply(o); - ((b.x - a.x) as f32, (b.y - a.y) as f32) - } - None => auto_source(img, first, r), - }; - // Bounding box of the stroke. - let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN); - for p in &pts { - x0 = x0.min(p.0 - r); - y0 = y0.min(p.1 - r); - x1 = x1.max(p.0 + r); - y1 = y1.max(p.1 + r); - } - // content-aware fill reads the spot's surroundings (the window holds 2 radii around it) - let pad = if fill { 2.0 * r } else { r }; - let (bx0, by0) = (((x0 - pad).floor().max(0.0)) as usize, ((y0 - pad).floor().max(0.0)) as usize); - let (bx1, by1) = (((x1 + pad).ceil() as usize).min(w), ((y1 + pad).ceil() as usize).min(h)); - if bx1 <= bx0 || by1 <= by0 { + let Some(SpotLayout { r, pts, offset, bx: bx0, by: by0, bw, bh, inner, opacity, heal, fill }) = layout(spot, frame, w, h, ppl) else { continue; - } - let (bw, bh) = (bx1 - bx0, by1 - by0); - let feather = (spot.feather / 100.0).clamp(0.0, 1.0) as f32; - let opacity = (spot.opacity / 100.0).clamp(0.0, 1.0) as f32; + }; + let Some(&first) = pts.first() else { continue }; + let offset = offset.unwrap_or_else(|| auto_source(img, first, r)); // alpha of the stroke and source patch in the box let mut alpha = vec![0.0f32; bw * bh]; let mut src = vec![[0.0f32; 3]; bw * bh]; @@ -327,7 +400,6 @@ pub fn apply(img: &mut Rgb32f, spots: &[Spot], frame: &Frame, ppl: f64) { for x in 0..bw { let (px, py) = ((bx0 + x) as f32 + 0.5, (by0 + y) as f32 + 0.5); let d = pts.iter().map(|p| ((px - p.0).powi(2) + (py - p.1).powi(2)).sqrt()).fold(f32::MAX, f32::min); - let inner = r * (1.0 - feather * 0.8); alpha[y * bw + x] = (1.0 - smooth(inner, r, d)) * opacity; src[y * bw + x] = img.sample_bilinear(px + offset.0, py + offset.1); tgt[y * bw + x] = img.get(bx0 + x, by0 + y); @@ -336,7 +408,6 @@ pub fn apply(img: &mut Rgb32f, spots: &[Spot], frame: &Frame, ppl: f64) { if fill { fill_box(&mut src, &tgt, &alpha, bw, bh); } - let heal = matches!(spot.mode, SpotMode::Remove | SpotMode::Heal); let low = if heal { // Tone correction from the spot's *surroundings* only: normalized convolution of // (target − source) over pixels outside the stroke (a membrane-like interpolation). diff --git a/crates/pipeline/src/tests.rs b/crates/pipeline/src/tests.rs index 5c5f1b95c1..cee4ec1ffb 100644 --- a/crates/pipeline/src/tests.rs +++ b/crates/pipeline/src/tests.rs @@ -287,12 +287,16 @@ fn drafts_keep_wide_planes_across_a_noise_reduction_change_and_full_renders_do_n let full = RenderRequest { quality: Quality::Full, ..draft }; let mut s = typical_edits(); s.effects.clarity = 60.0; + s.detail.sharpen_amount = 80.0; render_cached(&src, &info, &s, &draft, &cache); let clarity_plane = |c: &StageCache| c.entries.lock().unwrap().first().and_then(|e| e.planes.clarity.clone()).unwrap().1; + let sharpen_plane = |c: &StageCache| c.entries.lock().unwrap().first().and_then(|e| e.planes.sharpen.clone()).unwrap().1; let first = clarity_plane(&cache); + let first_sharpen = sharpen_plane(&cache); s.detail.nr_luminance = 50.0; render_cached(&src, &info, &s, &draft, &cache); assert!(Arc::ptr_eq(&first, &clarity_plane(&cache)), "a draft redid the clarity plane for a noise-reduction change"); + assert!(!Arc::ptr_eq(&first_sharpen, &sharpen_plane(&cache)), "a draft reused the old sharpening plane after noise reduction changed"); for v in [10.0, 45.0, 80.0] { s.detail.nr_luminance = v; s.detail.nr_color = v / 2.0; diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index 4e076e8028..dcd38d28c3 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -27,6 +27,10 @@ pub(crate) fn line_x(img: &Rgba8, y: usize, x0: f64, win: f64) -> f64 { let (a, b) = ((x0 - win).max(0.0) as usize, ((x0 + win) as usize).min(img.width - 1)); let row: Vec = (a..=b).map(|x| img.get(x, y)[1] as f64).collect(); let max = row.iter().cloned().fold(0.0, f64::max); + let min = row.iter().cloned().fold(f64::MAX, f64::min); + if max - min <= 1.0 { + return (a as f64 + b as f64) / 2.0 + 0.5; + } let (mut s, mut sw) = (0.0, 0.0); for (i, v) in row.iter().enumerate() { let wgt = (max - v).max(0.0).powi(2); @@ -41,6 +45,10 @@ pub(crate) fn line_y(img: &Rgba8, x: usize, y0: f64, win: f64) -> f64 { let (a, b) = ((y0 - win).max(0.0) as usize, ((y0 + win) as usize).min(img.height - 1)); let col: Vec = (a..=b).map(|y| img.get(x, y)[1] as f64).collect(); let max = col.iter().cloned().fold(0.0, f64::max); + let min = col.iter().cloned().fold(f64::MAX, f64::min); + if max - min <= 1.0 { + return (a as f64 + b as f64) / 2.0 + 0.5; + } let (mut s, mut sw) = (0.0, 0.0); for (i, v) in col.iter().enumerate() { let wgt = (max - v).max(0.0).powi(2); @@ -54,6 +62,20 @@ fn spread(v: &[f64]) -> f64 { v.iter().cloned().fold(f64::MIN, f64::max) - v.iter().cloned().fold(f64::MAX, f64::min) } +/// Asserts that a vertical edge with contrast > 1 LSB exists in row `y` around `x0 ± win`. +fn assert_vertical_edge(img: &Rgba8, y: usize, x0: f64, win: f64) { + let (a, b) = ((x0 - win).max(0.0) as usize, ((x0 + win) as usize).min(img.width - 1)); + let values: Vec = (a..=b).map(|x| img.get(x, y)[1] as f64).collect(); + assert!(spread(&values) > 1.0, "no vertical edge near x={x0} on row {y}"); +} + +/// Asserts that a horizontal edge with contrast > 1 LSB exists in column `x` around `y0 ± win`. +fn assert_horizontal_edge(img: &Rgba8, x: usize, y0: f64, win: f64) { + let (a, b) = ((y0 - win).max(0.0) as usize, ((y0 + win) as usize).min(img.height - 1)); + let values: Vec = (a..=b).map(|y| img.get(x, y)[1] as f64).collect(); + assert!(spread(&values) > 1.0, "no horizontal edge near y={y0} on column {x}"); +} + /// Barrel distortion with coefficient `k` (< 0): distorted radius = r·(1 + k·r²), r in half-diagonal units. fn barrel_undistort(w: f64, h: f64, k: f64) -> impl Fn(Point) -> Point + Sync { let (cx, cy, hd) = (w / 2.0, h / 2.0, w.hypot(h) / 2.0); @@ -213,6 +235,7 @@ fn manual_vertical_keystone_widens_the_top() { assert!(lb.y - lt.y > rb.y - rt.y, "left side enlarged"); } +/// Verifies manual geometry corrections straighten a keystoned grid test fixture. #[test] fn manual_transforms_straighten_known_keystone() { let (w, h) = (480usize, 320usize); @@ -226,6 +249,12 @@ fn manual_transforms_straighten_known_keystone() { let src = keystoned_grid(w, h, fwd, 40.0); let s = DevelopSettings { geometry: g.clone(), ..Default::default() }; let img = render(&src, &SourceInfo::default(), &s, &RenderRequest::fit(w, h)).image; + for &y in &[60usize, 150, 260] { + assert_vertical_edge(&img, y, 200.0, 15.0); + } + for &x in &[60usize, 220, 420] { + assert_horizontal_edge(&img, x, 200.0, 15.0); + } let xs: Vec = [60usize, 150, 260].iter().map(|&y| line_x(&img, y, 200.0, 15.0)).collect(); let ys: Vec = [60usize, 220, 420].iter().map(|&x| line_y(&img, x, 200.0, 15.0)).collect(); assert!(spread(&xs) < 1.0 && (xs[0] - 200.0).abs() < 1.0, "{g:?}: vertical line at {xs:?}"); diff --git a/crates/pipeline/src/tests_legacy.rs b/crates/pipeline/src/tests_legacy.rs new file mode 100644 index 0000000000..c0584bf2c7 --- /dev/null +++ b/crates/pipeline/src/tests_legacy.rs @@ -0,0 +1,127 @@ +//! V1 and V2 render as they did before process V3, on every platform: 16-bit samples of small +//! synthetic renders, captured on main at 76b5377 (before process V3 existed), within +//! [`LSB`]. `tests_light::v1_and_v2_render_as_before_v3` checks the same byte for byte, but only +//! on macOS aarch64, where its hashes were captured. + +use lightcraft_develop::{DevelopSettings, ProcessVersion, controls}; +use lightcraft_raster::Rgb32f; + +use crate::{DeepSamples, OutputDepth, RenderRequest, SourceInfo, render}; + +/// 480 × 320, arithmetic only (no platform maths): luminance rising over 12 stops left to right, +/// four colour bands top to bottom, thin bright and dark lines every 16 px (so V2's +/// Highlights / Shadows median has something to keep), and a few clipped highlights. +fn scene() -> Rgb32f { + Rgb32f::from_fn(480, 320, |x, y| { + let v = 0.0002 * 1.0175f32.powi(x as i32); + let c = match y / 80 { + 0 => [v, v, v], + 1 => [v * 1.3, v * 0.8, v * 0.4], + 2 => [v * 0.35, v * 0.9, v * 1.4], + _ => [v * 0.9, v * 0.3, v * 1.1], + }; + if x % 16 == 7 { + c.map(|k| k * 2.5) + } else if y % 16 == 11 { + c.map(|k| k * 0.35) + } else if x > 440 && y % 40 < 3 { + [4.0, 4.0, 4.0] + } else { + c + } + }) +} + +fn camera_look() -> SourceInfo { + let knots = std::array::from_fn(|i| { + let x = 0.004 * 1.18f32.powi(i as i32); + [x, 1.0 - (-2.0 * x).exp()] + }); + let curve = crate::tone::CameraTone::new(knots).unwrap().with_chroma([1.3, 1.2, 1.1, 1.0, 0.9, 0.7, 0.5, 0.4]).unwrap(); + SourceInfo { raw: true, as_shot_temp: 5200.0, as_shot_tint: 4.0, camera_tone: Some(curve), ..Default::default() } +} + +/// Where the samples are taken (output pixels of the 480 × 320 render). +const AT: [(usize, usize); 12] = + [(20, 20), (120, 30), (232, 40), (300, 27), (400, 60), (470, 1), (60, 100), (200, 125), (350, 140), (90, 200), (263, 210), (420, 290)]; + +/// 16-bit samples of V1 and V2 renders (the same order as `LEGACY`): three sources (rendered, +/// raw, raw with a camera look) × two edits (plain, a typical edit with Contrast, Highlights, +/// Shadows, Whites, Blacks and Clarity) × two processes. +fn legacy_samples() -> Vec<[u16; 3]> { + let infos = [SourceInfo::default(), SourceInfo { raw: true, as_shot_temp: 5200.0, as_shot_tint: 4.0, ..Default::default() }, camera_look()]; + let mut edited = DevelopSettings::for_raw(5200.0, 4.0); + for (id, v) in [ + ("light.exposure", 0.4), + ("light.contrast", 30.0), + ("light.highlights", -60.0), + ("light.shadows", 40.0), + ("light.whites", 15.0), + ("light.blacks", -20.0), + ("effects.clarity", 20.0), + ] { + controls::set(&mut edited, id, v); + } + let req = RenderRequest { depth: OutputDepth::U16, ..RenderRequest::fit(480, 480) }; + let src = scene(); + let mut out = Vec::new(); + for info in &infos { + for s in [DevelopSettings::for_raw(5200.0, 4.0), edited.clone()] { + for process in [ProcessVersion(1), ProcessVersion(2)] { + let s = DevelopSettings { process, ..s.clone() }; + let deep = render(&src, info, &s, &req).deep.unwrap(); + let DeepSamples::U16(v) = deep.samples else { panic!("16-bit samples") }; + for (x, y) in AT { + let i = (y * deep.width + x) * 3; + out.push([v[i], v[i + 1], v[i + 2]]); + } + } + } + } + out +} + +/// Largest difference allowed from the captured samples, in 16-bit steps. The renders call the +/// platform's `powf` / `exp2` / `log2`, whose last bit can differ between platforms: a relative +/// change of ~1e-7, far below one step (1.5e-5), so a sample moves by at most one step where it +/// sits at a rounding boundary. A change of how V1 or V2 render moves samples by far more. +const LSB: u16 = 2; + +#[test] +fn v1_and_v2_samples_are_as_before_v3_on_every_platform() { + let got = legacy_samples(); + assert_eq!(got.len(), LEGACY.len()); + let worst = got.iter().zip(&LEGACY).flat_map(|(g, w)| (0..3).map(move |k| g[k].abs_diff(w[k]))).max().unwrap_or(0); + for (i, (g, w)) in got.iter().zip(&LEGACY).enumerate() { + assert!((0..3).all(|k| g[k].abs_diff(w[k]) <= LSB), "sample {i}: {g:?}, captured {w:?} (worst {worst})"); + } +} + +/// [`legacy_samples`] on main at 76b5377. +#[rustfmt::skip] +const LEGACY: [[u16; 3]; 144] = [ + [240, 240, 240], [1222, 1222, 1222], [6573, 6573, 6573], [6760, 6760, 6760], [34082, 34082, 34082], [65535, 65535, 65535], + [796, 355, 165], [6369, 3524, 1681], [28819, 19569, 13215], [0, 770, 1153], [0, 17104, 20902], [41649, 18367, 40817], + [240, 240, 240], [1222, 1222, 1222], [6573, 6573, 6573], [6760, 6760, 6760], [34082, 34082, 34082], [65535, 65535, 65535], + [796, 355, 165], [6369, 3524, 1681], [28819, 19569, 13215], [0, 770, 1153], [0, 17104, 20902], [41649, 18367, 40817], + [314, 314, 314], [1699, 1699, 1699], [8278, 8278, 8278], [6991, 6991, 6991], [34698, 34698, 34698], [65535, 65535, 65535], + [1062, 474, 220], [8221, 4847, 2529], [32250, 22021, 14995], [0, 1040, 1558], [0, 21972, 26663], [44088, 19551, 43211], + [314, 314, 314], [1699, 1699, 1699], [8271, 8271, 8271], [6646, 6646, 6646], [34667, 34667, 34667], [65535, 65535, 65535], + [1062, 474, 220], [8219, 4846, 2528], [32239, 22013, 14989], [0, 1040, 1558], [0, 22622, 27432], [44072, 19543, 43195], + [272, 272, 272], [1384, 1384, 1384], [7098, 7098, 7098], [7293, 7293, 7293], [34521, 34521, 34521], [65535, 65535, 65535], + [902, 403, 187], [6894, 3899, 1901], [29974, 20395, 13815], [0, 872, 1307], [0, 18017, 21983], [42788, 18920, 41935], + [272, 272, 272], [1384, 1384, 1384], [7098, 7098, 7098], [7293, 7293, 7293], [34521, 34521, 34521], [65535, 65535, 65535], + [902, 403, 187], [6894, 3899, 1901], [29974, 20395, 13815], [0, 872, 1307], [0, 18017, 21983], [42788, 18920, 41935], + [16, 16, 16], [127, 127, 127], [5866, 5866, 5866], [3892, 3892, 3892], [36157, 36157, 36157], [65535, 65535, 65535], + [59, 27, 12], [3177, 1437, 666], [32984, 22546, 15376], [0, 63, 95], [0, 22149, 26872], [45537, 20255, 44634], + [16, 16, 16], [127, 127, 127], [5856, 5856, 5856], [3340, 3340, 3340], [36123, 36123, 36123], [65535, 65535, 65535], + [59, 27, 12], [3174, 1436, 665], [32972, 22537, 15370], [0, 63, 95], [0, 22867, 27722], [45520, 20246, 44616], + [477, 477, 477], [2433, 2433, 2433], [9924, 9924, 9924], [10170, 10170, 10170], [42194, 42194, 42194], [65533, 65533, 65533], + [1800, 660, 167], [10387, 5624, 1736], [39549, 25689, 14987], [0, 1533, 2297], [0, 23519, 28494], [54941, 22090, 53814], + [477, 477, 477], [2433, 2433, 2433], [9924, 9924, 9924], [10170, 10170, 10170], [42194, 42194, 42194], [65533, 65533, 65533], + [1800, 660, 167], [10387, 5624, 1736], [39549, 25689, 14987], [0, 1533, 2297], [0, 23519, 28494], [54941, 22090, 53814], + [639, 639, 639], [3436, 3436, 3436], [12637, 12637, 12637], [10872, 10872, 10872], [43751, 43751, 43751], [65393, 65393, 65393], + [2464, 904, 228], [13380, 7612, 2802], [44578, 29433, 18028], [0, 2136, 3161], [0, 30532, 36793], [58572, 24437, 57388], + [639, 639, 639], [3436, 3436, 3436], [12627, 12627, 12627], [10397, 10397, 10397], [43721, 43721, 43721], [65393, 65393, 65393], + [2464, 904, 228], [13377, 7610, 2801], [44566, 29424, 18020], [0, 2136, 3161], [0, 31308, 37712], [58556, 24426, 57373], +]; diff --git a/crates/pipeline/src/tests_light.rs b/crates/pipeline/src/tests_light.rs new file mode 100644 index 0000000000..2b85a98043 --- /dev/null +++ b/crates/pipeline/src/tests_light.rs @@ -0,0 +1,514 @@ +//! Process V4's calibrated Contrast and Blacks (`light_v3`): V1 and V2 render as they +//! always did, and the V4 operators behave. + +use lightcraft_color::transfer::{linear_to_srgb, srgb_to_linear}; +use lightcraft_develop::{DevelopSettings, Process, ProcessVersion, controls}; +use lightcraft_raster::{Rgb32f, Rgba8}; + +use crate::light_v3::{self, FITS, LUT_N, LightOps, Mode, Operator, Reference}; +use crate::light_v3_params as fitted; +use crate::{DeepSamples, OutputDepth, PixelWindow, RenderRequest, SourceInfo, StageCache, render, render_cached}; + +fn camera_curve() -> crate::tone::CameraTone { + let knots = std::array::from_fn(|i| { + let x = 0.004 * 1.18f32.powi(i as i32); + [x, 1.0 - (-2.0 * x).exp()] + }); + crate::tone::CameraTone::new(knots).unwrap().with_chroma([1.3, 1.2, 1.1, 1.0, 0.9, 0.7, 0.5, 0.4]).unwrap() +} + +/// A raw with a camera look: the path V4 changes. +fn camera_look() -> SourceInfo { + SourceInfo { raw: true, as_shot_temp: 5200.0, as_shot_tint: 4.0, camera_tone: Some(camera_curve()), ..Default::default() } +} + +fn check_luminance_cutoff(chroma: f32, pixel: [f32; 3], expected: [u8; 4]) { + // Nonnegative source pixels become mixed-sign ProPhoto values after camera chroma + // scaling. Contrast must not move their nearly cancelling luminance across 1e-6. + let curve = crate::tone::CameraTone::new(std::array::from_fn(|i| { + let x = (i + 1) as f32 / 33.0; + [x, x] + })) + .unwrap() + .with_chroma([chroma; 8]) + .unwrap(); + let info = SourceInfo { raw: true, camera_tone: Some(curve), ..Default::default() }; + let src = Rgb32f::filled(64, 64, pixel); + let mut s = DevelopSettings { process: Process::V4.version(), ..Default::default() }; + s.light.contrast = 100.0; + s.light.blacks = 80.0; + let image = render(&src, &info, &s, &RenderRequest::fit(64, 64)).image; + assert!(image.data.iter().all(|p| *p == image.data[0])); + for (actual, expected) in image.data[0].into_iter().zip(expected) { + assert!(actual.abs_diff(expected) <= 1, "chroma {chroma}: {:?}, expected {expected}", image.data[0]); + } +} + +#[test] +fn v3_luminance_cutoff_chroma_2() { + check_luminance_cutoff(2.0, [0.023_433_316, 0.000_071_107_73, 0.005_175_675], [27, 0, 8, 255]); +} + +#[test] +fn v3_luminance_cutoff_chroma_4() { + check_luminance_cutoff(4.0, [0.035_338_085, 0.000_048_468_723, 0.010_193_758], [47, 0, 19, 255]); +} + +fn scenes() -> Vec { + let lib = lightcraft_scenes::demo_library(); + vec![lib[0].render(480, 320), lib[3].render(400, 300)] +} + +/// FNV-1a over the bytes of a render: its 8-bit image and its deep samples. +fn fnv(hash: &mut u64, bytes: impl IntoIterator) { + for b in bytes { + *hash = (*hash ^ b as u64).wrapping_mul(0x0000_0100_0000_01B3); + } +} + +fn render_hash(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest) -> u64 { + let r = render(src, info, s, req); + let mut h = 0xCBF2_9CE4_8422_2325u64; + fnv(&mut h, r.image.data.iter().flatten().copied()); + match r.deep.map(|d| d.samples) { + Some(DeepSamples::U16(v)) => fnv(&mut h, v.iter().flat_map(|x| x.to_le_bytes())), + Some(DeepSamples::F32(v)) => fnv(&mut h, v.iter().flat_map(|x| x.to_bits().to_le_bytes())), + None => {} + } + h +} + +/// The settings the V1 / V2 golden renders cover: plain, a typical edit, and Contrast, Whites and +/// Blacks at both ends on their own. +fn golden_settings() -> Vec { + let mut out = vec![DevelopSettings::for_raw(5200.0, 4.0)]; + let mut edited = DevelopSettings::for_raw(5200.0, 4.0); + for (id, v) in [("light.exposure", 0.4), ("light.contrast", 30.0), ("light.highlights", -60.0), ("light.whites", 15.0), ("light.blacks", -20.0)] { + controls::set(&mut edited, id, v); + } + out.push(edited); + for id in ["light.contrast", "light.whites", "light.blacks"] { + for v in [-100.0, 100.0] { + let mut s = DevelopSettings::for_raw(5200.0, 4.0); + controls::set(&mut s, id, v); + out.push(s); + } + } + let mut hdr = DevelopSettings::for_raw(5200.0, 4.0); + hdr.hdr.enabled = true; + hdr.hdr.max_ev = 2.0; + for (id, v) in [("light.contrast", 25.0), ("light.whites", 40.0), ("light.blacks", -30.0)] { + controls::set(&mut hdr, id, v); + } + out.push(hdr); + out +} + +/// One hash over every golden render of `process`: two scenes, three sources (rendered, raw, +/// raw with a camera look), the settings above, at 8 and 16 bits and as float HDR. +fn golden(process: ProcessVersion) -> u64 { + let infos = [SourceInfo::default(), SourceInfo { raw: true, as_shot_temp: 5200.0, as_shot_tint: 4.0, ..Default::default() }, camera_look()]; + let reqs = [ + // (at 480 px V2's Highlights / Shadows base takes its median: V1 and V2 differ) + RenderRequest::fit(480, 480), + RenderRequest { depth: OutputDepth::U16, ..RenderRequest::fit(320, 320) }, + RenderRequest { depth: OutputDepth::F32Hdr, ..RenderRequest::fit(240, 240) }, + ]; + let mut h = 0xCBF2_9CE4_8422_2325u64; + for src in scenes() { + for info in &infos { + for s in golden_settings() { + let s = DevelopSettings { process, ..s }; + for req in &reqs { + fnv(&mut h, render_hash(&src, info, &s, req).to_le_bytes()); + } + } + } + } + h +} + +/// V1 and V2 render byte for byte as they do on main before adding process V3. The hashes were captured +/// on main at e2d18b5fb (before `light_v3`) on macOS aarch64, where they are checked: the renders +/// call the platform's `powf` / `exp2` / `log2`, whose last bit can differ on other platforms, so +/// elsewhere the test only prints them. Before updating them during a rebase, run this exact fixture +/// on main and confirm that both hashes match. This PR must not change V1 or V2 rendering. +#[test] +fn v1_and_v2_render_as_before_v3() { + let got = [golden(ProcessVersion(1)), golden(ProcessVersion(2))]; + eprintln!("golden V1 {:#018x}, V2 {:#018x}", got[0], got[1]); + if cfg!(all(target_os = "macos", target_arch = "aarch64")) { + assert_eq!(got, GOLDEN, "V1 / V2 renders changed"); + } +} + +const GOLDEN: [u64; 2] = [0x5bf0_a7c8_579f_3f34, 0x87a3_598c_1597_9e4d]; + +fn on(process: Process, s: &DevelopSettings) -> DevelopSettings { + DevelopSettings { process: process.version(), ..s.clone() } +} + +/// Every slider and amount the operator checks sweep: Contrast and Blacks with +/// their fits and references. +fn fits() -> [(&'static str, &'static light_v3::Fit, &'static [Reference]); 2] { + [("contrast", &fitted::CONTRAST, fitted::CONTRAST_REFERENCE), ("blacks", &fitted::BLACKS, fitted::BLACKS_REFERENCE)] +} + +#[test] +fn the_shipped_fits_unpack_as_the_family_lays_them_out() { + assert!(std::ptr::eq(FITS[0], &fitted::CONTRAST) && std::ptr::eq(FITS[1], &fitted::BLACKS)); + for (name, fit, _) in fits() { + let u = fit.unpack().unwrap_or_else(|| panic!("{name} doesn't unpack")); + // D(1) = 0, and Contrast's shapes are anchored at black too + assert_eq!((u.d_pos[11], u.d_neg[11]), (0.0, 0.0), "{name}"); + assert_eq!(fit.signed, name == "contrast"); + if fit.signed { + assert_eq!((u.d_pos[0], u.d_neg[0]), (0.0, 0.0)); + } + assert!([u.law_pos, u.law_neg].iter().all(|(t, q)| t.is_finite() && q.is_finite() && *t > 0.0 && *q > 0.0), "{name}"); + let (w0, w1) = u.weights; + assert!((0.0..=1.0).contains(&w0) && (0.0..=1.0).contains(&w1), "{name}"); + } + assert_eq!(fitted::CONTRAST.mode, Mode::PerChannel); + assert_eq!(fitted::BLACKS.mode, Mode::Mix); + // a parameter vector that doesn't fit the layout is refused, not read past its end + let short = light_v3::Fit { params: &fitted::CONTRAST.params[..20], ..fitted::CONTRAST }; + assert!(short.unpack().is_none()); + assert!(Operator::new(&short, 50.0).is_none()); +} + +#[test] +fn exact_mix_endpoints_select_only_the_contributing_mode() { + assert_eq!(Operator::new(&fitted::BLACKS, -30.0).unwrap().mode, Mode::PerChannel); + assert_eq!(Operator::new(&fitted::BLACKS, 30.0).unwrap().mode, Mode::Mix); + // Synthetic logits also exercise a weight that rounds to exactly zero. + let mut params = fitted::BLACKS.params.to_vec(); + *params.last_mut().unwrap() = -1000.0; + let fit = light_v3::Fit { params: Box::leak(params.into_boxed_slice()), ..fitted::BLACKS }; + assert_eq!(Operator::new(&fit, -30.0).unwrap().mode, Mode::Luminance); +} + +#[test] +fn preview_tables_match_exact_operators_over_combined_amounts() { + let info = camera_look(); + let encode = |v| crate::finish::encode_srgb(crate::finish::srgb_lut(), v); + let mut worst = 0.0f32; + for contrast in [-100.0, -60.0, -30.0, 0.0, 30.0, 60.0, 100.0] { + for blacks in [-100.0, -60.0, -30.0, 0.0, 30.0, 60.0, 100.0] { + let mut s = DevelopSettings::default(); + s.light.contrast = contrast; + s.light.blacks = blacks; + let Some(exact) = LightOps::new(&s, &info) else { continue }; + let preview = light_v3::PreviewOps::new(&exact, &encode); + assert_eq!(preview.is_some(), blacks <= 0.0); + for i in 0..=8192 { + let v = i as f32 / 8192.0; + for p in [[v; 3], [v, v * 0.1, v * 0.02], [v * 0.04, v, v * 0.2], [v * 0.1, v * 0.03, v], [v * 3.0, -v * 0.2, v]] { + let a = exact.apply(p, &linear_to_srgb); + let b = preview.as_ref().map_or_else(|| exact.apply(p, &encode), |preview| preview.apply(p)); + for (a, b) in a.into_iter().zip(b) { + let error = (linear_to_srgb(a.clamp(0.0, 1.0)) - linear_to_srgb(b.clamp(0.0, 1.0))).abs() * 255.0; + worst = worst.max(error); + assert!(error <= 1.0, "Contrast {contrast}, Blacks {blacks}, input {p:?}: {error} levels"); + } + } + } + } + } + eprintln!("Preview table maximum encoded error {worst:.6} of an 8-bit level"); +} + +/// The port against the family's own Python (`tools/light_v3_family.py`, through the generated +/// references): `Family.curve` to the references' 12 digits, and `Family.apply` on pixels to the +/// tables' interpolation. +#[test] +fn the_operators_are_fit_pointwise_family() { + for (name, fit, refs) in fits() { + let u = fit.unpack().unwrap(); + assert!(!refs.is_empty()); + let mut worst = 0.0f64; + for r in refs { + for (v, want) in fitted::REF_V.iter().zip(r.curve) { + let got = u.curve(r.amount, *v); + // (the references are written at 12 significant digits) + assert!((got - want).abs() < 1e-11, "{name} {} at {v}: {got} vs {want}", r.amount); + } + let Some(apply) = r.apply else { continue }; + let op = Operator::new(fit, r.amount).unwrap(); + for (px, want) in fitted::REF_PIX.iter().zip(apply) { + let lin = px.map(|v| srgb_to_linear(v as f32)); + let got = op.apply(lin, &linear_to_srgb).map(linear_to_srgb); + for k in 0..3 { + worst = worst.max((got[k] as f64 - want[k]).abs()); + } + } + } + eprintln!("{name}: worst |apply - Family.apply| {worst:.2e} (encoded)"); + assert!(worst < 1e-3, "{name}: {worst}"); + } +} + +/// Each operator is non-decreasing at every integer amount and maps white to white. +#[test] +fn every_operator_is_monotone_and_keeps_white() { + for (name, fit, _) in fits() { + for a in (-100..=100).filter(|a| *a != 0) { + let op = Operator::new(fit, a as f64).unwrap(); + assert!(op.lut[0] >= 0.0, "{name} {a}: F(0) = {}", op.lut[0]); + assert!((op.lut[LUT_N - 1] - 1.0).abs() < 1e-6, "{name} {a}: F(1) = {}", op.lut[LUT_N - 1]); + assert!(op.lut.windows(2).all(|w| w[1] >= w[0]), "{name} {a} decreases"); + let mut prev = f32::MIN; + for i in -50..=1100 { + let x = i as f32 / 1000.0; + let y = op.channel(x, &linear_to_srgb); + assert!(y >= prev, "{name} {a} at {x}: {y} < {prev}"); + prev = y; + } + } + } +} + +/// The tables flatten a fold instead of letting tones swap; where the fit is increasing they are +/// the fit. +#[test] +fn a_folding_fit_is_flattened_and_others_are_untouched() { + for (name, fit, _) in fits() { + let u = fit.unpack().unwrap(); + for a in [-100.0, -50.0, -10.0, 10.0, 50.0, 100.0] { + let mut fold = 0.0f64; + let mut top = 0.0f64; + for i in 0..LUT_N { + let f = u.curve(a, i as f64 / (LUT_N - 1) as f64); + top = top.max(f); + fold = fold.max(top - f); + } + eprintln!("{name} {a}: fitted curve folds back by {fold:.4}"); + assert!(fold < 0.03, "{name} {a}: {fold}"); + } + } +} + +/// A grey ramp through the camera look: each V4 slider moves the tones its way, keeps their order +/// and keeps the ramp neutral. +#[test] +fn v3_sliders_move_a_grey_ramp_their_way() { + let ramp = Rgb32f::from_fn(256, 8, |x, _| [0.0005 * 1.035f32.powi(x as i32); 3]); + let shot = |id: &str, v: f64| { + let mut s = DevelopSettings::default(); + assert_eq!(s.process.process(), Process::V4); + controls::set(&mut s, id, v); + let r = render(&ramp, &camera_look(), &s, &RenderRequest::fit(256, 8)).image; + (0..256).map(|x| r.get(x, 4)).collect::>() + }; + let plain = shot("light.exposure", 0.0); + let luma = |p: [u8; 4]| p[1] as i32; + for (id, v) in [ + ("light.contrast", 60.0), + ("light.contrast", -60.0), + ("light.whites", 60.0), + ("light.whites", -60.0), + ("light.blacks", 60.0), + ("light.blacks", -60.0), + ] { + let r = shot(id, v); + assert!(r.windows(2).all(|w| luma(w[1]) >= luma(w[0])), "{id} {v}: the ramp is no longer increasing"); + assert!(r.iter().all(|p| p[0].abs_diff(p[1]) <= 1 && p[1].abs_diff(p[2]) <= 1), "{id} {v}: the ramp is no longer grey"); + let diff = |lo: usize, hi: usize| (lo..hi).map(|x| luma(r[x]) - luma(plain[x])).sum::(); + let (dark, light) = (diff(40, 90), diff(170, 220)); + match (id, v > 0.0) { + ("light.contrast", true) => assert!(dark < 0 && light > 0, "{id} {v}: {dark} {light}"), + ("light.contrast", false) => assert!(dark > 0 && light < 0, "{id} {v}: {dark} {light}"), + ("light.whites", true) => assert!(light > 0, "{id} {v}: {dark} {light}"), + ("light.whites", false) => assert!(light < 0, "{id} {v}: {dark} {light}"), + (_, true) => assert!(dark > 0, "{id} {v}: {dark} {light}"), + (_, false) => assert!(dark < 0, "{id} {v}: {dark} {light}"), + } + } +} + +/// V4 with Contrast, Whites and Blacks at 0 is the Neutral camera look exactly (V2's at 0), +/// whatever the other sliders; other sources render under V4 as under V2. +#[test] +fn v3_at_zero_is_the_neutral_camera_look_and_other_paths_are_v2() { + let reqs = [RenderRequest::fit(480, 480), RenderRequest { depth: OutputDepth::U16, ..RenderRequest::fit(320, 320) }]; + let mut typical = DevelopSettings::for_raw(5200.0, 4.0); + for (id, v) in [("light.exposure", 0.4), ("light.highlights", -60.0), ("light.shadows", 30.0), ("effects.clarity", 20.0)] { + controls::set(&mut typical, id, v); + } + let mut hdr = typical.clone(); + hdr.hdr.enabled = true; + let hdr_req = RenderRequest { depth: OutputDepth::F32Hdr, ..RenderRequest::fit(240, 240) }; + for src in scenes() { + for s in [DevelopSettings::for_raw(5200.0, 4.0), typical.clone()] { + for req in &reqs { + assert_eq!( + render_hash(&src, &camera_look(), &on(Process::V4, &s), req), + render_hash(&src, &camera_look(), &on(Process::V3, &s), req) + ); + } + } + assert_eq!( + render_hash(&src, &camera_look(), &on(Process::V4, &hdr), &hdr_req), + render_hash(&src, &camera_look(), &on(Process::V3, &hdr), &hdr_req) + ); + let mut edited = typical.clone(); + for (id, v) in [("light.contrast", 30.0), ("light.whites", 25.0), ("light.blacks", -20.0)] { + controls::set(&mut edited, id, v); + } + for info in [SourceInfo::default(), SourceInfo { raw: true, ..Default::default() }] { + for req in &reqs { + assert_eq!(render_hash(&src, &info, &on(Process::V4, &edited), req), render_hash(&src, &info, &on(Process::V3, &edited), req)); + } + } + // and on the camera look the sliders do something + assert_ne!( + render_hash(&src, &camera_look(), &on(Process::V4, &edited), &reqs[0]), + render_hash(&src, &camera_look(), &on(Process::V4, &typical), &reqs[0]) + ); + } + let info = camera_look(); + assert!(LightOps::new(&on(Process::V4, &typical), &info).is_none(), "nothing to apply at 0"); + assert!( + LightOps::new( + &on(Process::V3, &DevelopSettings { light: lightcraft_develop::Light { contrast: 50.0, ..Default::default() }, ..typical.clone() }), + &info + ) + .is_none() + ); +} + +/// Cached renders (a view's stage cache) render as uncached ones do, whole or as a window. +#[test] +fn calibrated_operators_match_in_cached_and_windowed_renders() { + let src = std::sync::Arc::new(lightcraft_scenes::demo_library()[3].render(1200, 800)); + let info = camera_look(); + let mut s = DevelopSettings::default(); + s.light.contrast = 40.0; + s.light.blacks = -60.0; + s.light.whites = 80.0; + let cache = StageCache::default(); + let req = RenderRequest::fit(1200, 1200); + for _ in 0..2 { + assert!(render_cached(&src, &info, &s, &req, &cache).image == render(&src, &info, &s, &req).image); + } + let win = PixelWindow { x: 300, y: 200, w: 400, h: 300 }; + let wreq = RenderRequest { window: Some(win), ..req }; + let (f, w) = (render(&src, &info, &s, &req).image, render_cached(&src, &info, &s, &wreq, &cache).image); + assert!(window_diff(&f, &w, win) <= 1, "the window is the frame's pixels"); +} + +/// Largest channel difference between window `win` of `full` and the window render `w`. +fn window_diff(full: &Rgba8, w: &Rgba8, win: PixelWindow) -> u8 { + let mut max = 0; + for y in 0..win.h { + for x in 0..win.w { + let (a, b) = (full.get(win.x + x, win.y + y), w.get(x, y)); + for k in 0..3 { + max = max.max(a[k].abs_diff(b[k])); + } + } + } + max +} + +/// HDR values follow the mode (review of 5a7016c8): per channel a component above 1 passes +/// unchanged; on luminance a pixel whose luminance is at most 1 is scaled as a whole, components +/// above 1 included, and one whose luminance is above 1 passes; Mix blends the two. Both are +/// continuous where a component or the luminance crosses 1. +#[test] +fn hdr_components_follow_the_operators_mode() { + let enc = &linear_to_srgb; + let lum = |p: [f32; 3]| light_v3::PRO_Y[0] * p[0] + light_v3::PRO_Y[1] * p[1] + light_v3::PRO_Y[2] * p[2]; + for (name, fit, _) in fits() { + for a in [-100.0, -40.0, 40.0, 100.0] { + let op = Operator::new(fit, a).unwrap(); + for p in [[1.2f32, 0.2, 0.05], [3.0, 1.5, 0.8], [0.4, 1.1, 0.02]] { + let pc = p.map(|c| op.channel(c, enc)); + assert!(p.iter().zip(&pc).all(|(c, o)| *c <= 1.0 || o == c), "{name} {a}: per channel {p:?} -> {pc:?}"); + let y = lum(p); + let l = if y > 1.0 { p } else { p.map(|c| c * op.channel(y, enc) / y) }; + let want: [f32; 3] = match op.mode { + Mode::PerChannel => pc, + Mode::Luminance => l, + Mode::Mix => std::array::from_fn(|k| op.weight * pc[k] + (1.0 - op.weight) * l[k]), + }; + let got = op.apply(p, enc); + assert!(got.iter().all(|v| v.is_finite())); + assert!(got.iter().zip(&want).all(|(g, w)| (g - w).abs() < 1e-6), "{name} {a} ({:?}): {p:?} -> {got:?}, want {want:?}", op.mode); + } + // continuous where a component crosses 1, and where the luminance does + let (lo, hi) = (op.apply([0.9999, 0.3, 0.1], enc), op.apply([1.0001, 0.3, 0.1], enc)); + assert!(lo.iter().zip(&hi).all(|(a, b)| (a - b).abs() < 2e-3), "{name} {a}: {lo:?} | {hi:?}"); + let (lo, hi) = (op.apply([0.9999; 3], enc), op.apply([1.0001; 3], enc)); + assert!(lo.iter().zip(&hi).all(|(a, b)| (a - b).abs() < 2e-3), "{name} {a}: {lo:?} | {hi:?}"); + } + } +} + +/// Whites keeps the V2 tone curve for both signs, including HDR and render windows. +#[test] +fn whites_is_byte_identical_to_v2() { + let src = scenes().remove(0); + let info = camera_look(); + let reqs = [ + RenderRequest::fit(480, 480), + RenderRequest { depth: OutputDepth::U16, ..RenderRequest::fit(320, 320) }, + RenderRequest { depth: OutputDepth::F32Hdr, ..RenderRequest::fit(240, 240) }, + RenderRequest { window: Some(PixelWindow { x: 80, y: 60, w: 160, h: 120 }), ..RenderRequest::fit(480, 480) }, + ]; + for amount in [-100.0, -50.0, -1.0, 0.0, 1.0, 50.0, 100.0] { + for hdr in [false, true] { + let mut s = DevelopSettings::for_raw(5200.0, 4.0); + s.light.whites = amount; + s.light.exposure = 0.35; + s.light.highlights = -30.0; + s.light.shadows = 20.0; + s.hdr.enabled = hdr; + s.hdr.max_ev = 2.0; + for req in &reqs { + assert_eq!( + render_hash(&src, &info, &on(Process::V4, &s), req), + render_hash(&src, &info, &on(Process::V3, &s), req), + "Whites {amount}, HDR {hdr}, {req:?}" + ); + } + } + } +} + +#[test] +fn invalid_amounts_are_skipped_and_finite_amounts_are_bounded() { + for fit in FITS { + for a in [0.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(Operator::new(fit, a).is_none()); + } + for (a, endpoint) in [(-101.0, -100.0), (101.0, 100.0)] { + assert_eq!(Operator::new(fit, a).unwrap().lut, Operator::new(fit, endpoint).unwrap().lut); + } + } +} + +#[test] +fn section_bypass_and_local_adjustments_keep_v2_behavior() { + let src = scenes().remove(0); + let info = camera_look(); + let req = RenderRequest::fit(480, 480); + let mut s = DevelopSettings::default(); + s.light.contrast = 70.0; + s.light.blacks = -50.0; + s.disabled_sections.push("light".into()); + assert_eq!(render_hash(&src, &info, &on(Process::V4, &s), &req), render_hash(&src, &info, &on(Process::V3, &s), &req)); + s.light = Default::default(); + s.disabled_sections.clear(); + s.masks = vec![lightcraft_develop::Mask { + components: vec![lightcraft_develop::MaskComponent { + name: None, + op: lightcraft_develop::MaskOp::Add, + invert: false, + shape: lightcraft_develop::MaskShape::Linear { start: lightcraft_geom::Point::new(0.2, 0.0), end: lightcraft_geom::Point::new(0.8, 1.0) }, + }], + adjust: lightcraft_develop::LocalAdjustments { contrast: 40.0, whites: 60.0, blacks: -30.0, ..Default::default() }, + ..Default::default() + }]; + assert_eq!(render_hash(&src, &info, &on(Process::V4, &s), &req), render_hash(&src, &info, &on(Process::V3, &s), &req)); +} diff --git a/crates/pipeline/src/tests_mask_geometry.rs b/crates/pipeline/src/tests_mask_geometry.rs index 0a12171100..08b084cf89 100644 --- a/crates/pipeline/src/tests_mask_geometry.rs +++ b/crates/pipeline/src/tests_mask_geometry.rs @@ -71,7 +71,12 @@ fn mark_at(s: &DevelopSettings) -> (f64, f64) { let req = RenderRequest::fit(W, H); let info = SourceInfo::default(); let (a, b) = (render(&marked(true), &info, s, &req).image, render(&marked(false), &info, s, &req).image); - centroid(a.width, (0..a.data.len()).map(|i| (luma(&a, i) - luma(&b, i)).max(0.0))) + centroid(a.width, (0..a.data.len()).map(|i| above_dither(luma(&a, i) - luma(&b, i)))) +} + +/// A difference between two renders, without the one level of 8-bit dither any pixel can differ by. +fn above_dither(d: f64) -> f64 { + (d - 1.5).max(0.0) } fn centroid(w: usize, weights: impl Iterator) -> (f64, f64) { @@ -87,7 +92,7 @@ fn centroid(w: usize, weights: impl Iterator) -> (f64, f64) { /// Where the mask brightened the render (`plain` is the same render without the mask). fn mask_at(masked: &Rgba8, plain: &Rgba8) -> (f64, f64) { - centroid(masked.width, (0..masked.data.len()).map(|i| (luma(masked, i) - luma(plain, i)).max(0.0))) + centroid(masked.width, (0..masked.data.len()).map(|i| above_dither(luma(masked, i) - luma(plain, i)))) } /// The geometry changes a user makes after drawing a mask. diff --git a/crates/pipeline/src/tests_sharpen.rs b/crates/pipeline/src/tests_sharpen.rs new file mode 100644 index 0000000000..69850c1600 --- /dev/null +++ b/crates/pipeline/src/tests_sharpen.rs @@ -0,0 +1,266 @@ +//! Sharpening: an unsharp mask at the pixel scale, with Radius (source pixels), Detail (halo +//! damping) and Masking (edge mask), the same at every preview and export size. + +use lightcraft_develop::DevelopSettings; +use lightcraft_raster::{Rgb32f, Rgba8}; + +use crate::{RenderRequest, SourceInfo, render}; + +fn info() -> SourceInfo { + SourceInfo { raw: true, ..Default::default() } +} + +fn render_at(src: &Rgb32f, s: &DevelopSettings, w: usize) -> Rgba8 { + render(src, &info(), s, &RenderRequest::fit(w, w)).image +} + +/// RMS difference of the green channel. +fn rms(a: &Rgba8, b: &Rgba8) -> f64 { + assert_eq!((a.width, a.height), (b.width, b.height)); + let sum: f64 = a.data.iter().zip(&b.data).map(|(p, q)| (p[1] as f64 - q[1] as f64).powi(2)).sum(); + (sum / a.data.len() as f64).sqrt() +} + +/// A grating with the given period (px at 512 wide), in scene-linear light. +fn grating(w: usize, period: f32) -> Rgb32f { + let h = w / 8; + Rgb32f::from_fn(w, h, |x, _| { + let k = w as f32 / 512.0; + let v = 0.18 * (1.0 + 0.4 * (std::f32::consts::TAU * x as f32 / (period * k)).sin()); + [v; 3] + }) +} + +/// A scene with a hard edge, fine texture and a gradient, defined in normalized coordinates so it +/// can be sampled at any size. +fn scene(w: usize) -> Rgb32f { + let h = w * 3 / 4; + Rgb32f::from_fn(w, h, |x, y| { + let (u, v) = (x as f32 / w as f32, y as f32 / w as f32); + let edge = if u > 0.5 { 0.3 } else { 0.08 }; + let tex = 0.03 * (u * 150.0).sin() * (v * 130.0).cos(); + let g = 0.1 * v; + let l = (edge + tex + g).max(0.001); + [l, l * 0.9, l * 0.8] + }) +} + +fn sharp(amount: f64, radius: f64, detail: f64, masking: f64) -> DevelopSettings { + let mut s = DevelopSettings::default(); + s.detail.sharpen_amount = amount; + s.detail.sharpen_radius = radius; + s.detail.sharpen_detail = detail; + s.detail.sharpen_masking = masking; + s +} + +#[test] +fn amount_zero_is_the_identity_whatever_radius_and_detail() { + let src = scene(256); + let plain = render_at(&src, &DevelopSettings::default(), 256); + for (r, d) in [(0.5, 0.0), (1.0, 25.0), (3.0, 100.0)] { + assert_eq!(render_at(&src, &sharp(0.0, r, d, 0.0), 256).data, plain.data, "radius {r} detail {d}"); + } +} + +#[test] +fn radius_changes_the_output() { + let src = scene(256); + let a = render_at(&src, &sharp(60.0, 0.8, 25.0, 0.0), 256); + let b = render_at(&src, &sharp(60.0, 2.5, 25.0, 0.0), 256); + assert_ne!(a.data, b.data); + assert!(rms(&a, &b) > 0.3, "{}", rms(&a, &b)); +} + +#[test] +fn larger_radius_boosts_coarser_detail() { + // gain on a fine (4 px) and a coarse (24 px) grating, for a small and a large radius + let gain = |period: f32, radius: f64| { + let src = grating(512, period); + rms(&render_at(&src, &sharp(80.0, radius, 100.0, 0.0), 512), &render_at(&src, &sharp(0.0, radius, 100.0, 0.0), 512)) + }; + let (fine_small, fine_large) = (gain(4.0, 0.6), gain(4.0, 3.0)); + let (coarse_small, coarse_large) = (gain(24.0, 0.6), gain(24.0, 3.0)); + eprintln!("fine {fine_small} {fine_large}, coarse {coarse_small} {coarse_large}"); + assert!(coarse_large > 2.0 * coarse_small, "coarse: small {coarse_small}, large {coarse_large}"); + assert!(fine_small > coarse_small, "a small radius favours fine detail: {fine_small} vs {coarse_small}"); + // the large radius moves its emphasis to coarser detail + assert!(coarse_large / fine_large > 2.0 * coarse_small / fine_small, "{coarse_large}/{fine_large} vs {coarse_small}/{fine_small}"); +} + +#[test] +fn detail_changes_the_output_and_damps_halos() { + let src = scene(256); + let lo = render_at(&src, &sharp(80.0, 1.5, 0.0, 0.0), 256); + let hi = render_at(&src, &sharp(80.0, 1.5, 100.0, 0.0), 256); + let plain = render_at(&src, &sharp(0.0, 1.5, 0.0, 0.0), 256); + assert_ne!(lo.data, hi.data); + // the overshoot next to the hard edge (u = 0.5) shrinks with Detail 0 + let row = 96 * 256; + let at = |img: &Rgba8, x: usize| img.data[row + x][1] as i32; + let over = |img: &Rgba8| (118..128).map(|x| (at(img, x) - at(&plain, x)).abs()).max().unwrap_or(0); + assert!(over(&lo) < over(&hi), "halo {} (detail 0) vs {} (detail 100)", over(&lo), over(&hi)); +} + +#[test] +fn masking_leaves_flat_areas_alone() { + // gentle noise on a flat field: unmasked sharpening changes it, a high Masking does not + let src = Rgb32f::from_fn(128, 96, |x, y| { + let n = ((x * 7 + y * 13) % 5) as f32 * 0.0015; + [0.18 + n; 3] + }); + let plain = render_at(&src, &sharp(0.0, 1.0, 25.0, 0.0), 128); + let open = render_at(&src, &sharp(100.0, 1.0, 25.0, 0.0), 128); + let masked = render_at(&src, &sharp(100.0, 1.0, 25.0, 100.0), 128); + assert!(rms(&open, &plain) > rms(&masked, &plain), "{} vs {}", rms(&open, &plain), rms(&masked, &plain)); +} + +#[test] +fn sharpening_is_the_same_at_every_size() { + // the same photo previewed at half size and rendered in full: what sharpening adds (sharpened + // minus plain) agrees between the preview and the shrunk full render far better than with zero + let src = scene(512); + let shrink = |img: &Rgba8| -> Vec { + (0..256 * 192) + .map(|i| { + let (x, y) = (i % 256 * 2, i / 256 * 2); + let p = |dx: usize, dy: usize| img.data[(y + dy) * 512 + x + dx][1] as f64; + (p(0, 0) + p(1, 0) + p(0, 1) + p(1, 1)) / 4.0 + }) + .collect() + }; + let added = |a: &[f64], b: &[f64]| -> Vec { a.iter().zip(b).map(|(p, q)| p - q).collect() }; + let norm = |v: &[f64]| (v.iter().map(|x| x * x).sum::() / v.len() as f64).sqrt(); + let (s, off) = (sharp(60.0, 2.0, 25.0, 0.0), sharp(0.0, 2.0, 25.0, 0.0)); + let full = added(&shrink(&render_at(&src, &s, 512)), &shrink(&render_at(&src, &off, 512))); + let half_on = render_at(&src, &s, 256); + let half_off = render_at(&src, &off, 256); + let half: Vec = half_on.data.iter().zip(&half_off.data).map(|(p, q)| p[1] as f64 - q[1] as f64).collect(); + let miss = norm(&added(&full, &half)); + eprintln!("size invariance: effect {} (half) {} (full, shrunk), disagreement {miss}", norm(&half), norm(&full)); + assert!(norm(&half) > 0.5, "the sharpening shows at half size"); + assert!(miss < 0.6 * norm(&half), "preview and export disagree: {miss} vs an effect of {}", norm(&half)); +} + +#[test] +fn subpixel_blur_response_is_continuous_and_does_not_vanish() { + use crate::local::{sharpen_gain, sharpen_sigma}; + use lightcraft_raster::{ + Plane, + blur::{gauss_taps, gaussian_taps}, + }; + // An alternating grating measures the actual FIR response at Nyquist, away from edges. + let src = Plane::from_fn(256, 16, |x, _| if x % 2 == 0 { 1.0 } else { -1.0 }); + let response = |sigma| { + let blur = gaussian_taps(&src, &gauss_taps(sharpen_sigma(sigma))); + (16..240).map(|x| (src.data[x] - blur.data[x]) * src.data[x]).sum::() / 224.0 * sharpen_gain(sigma) + }; + for sigma in [0.1, 0.25, 0.34, 0.4, 0.4999, 0.5001] { + let desired = -(-0.5 * std::f32::consts::PI.powi(2) * sigma * sigma).exp_m1(); + assert!((response(sigma) - desired).abs() < 0.001, "sigma {sigma}: {} vs {desired}", response(sigma)); + } + assert!((response(0.4999) - response(0.5001)).abs() < 0.001); + assert!(response(0.75) > response(0.5)); + assert_eq!(sharpen_gain(1.0), 1.0); + assert_eq!(sharpen_gain(2.0), 1.0); +} + +#[test] +fn reduced_source_uses_the_original_pixel_radius() { + let original = scene(512); + let told = SourceInfo { native_long: Some(512), ..info() }; + let req = RenderRequest::fit(128, 128); + let s = sharp(100.0, 2.0, 100.0, 0.0); + // Use the pipeline's own resampling for the smaller source level. Mixing resampling + // kernels adds edge ringing unrelated to whether the original pixel radius is retained. + let p = crate::plan(&original, &info(), &s, &req); + let reduced = p.frame.sample(&original, p.w, p.h); + let mut off = s.clone(); + off.detail.sharpen_amount = 0.0; + let from_original = render(&original, &info(), &s, &req).image; + let from_reduced = render(&reduced, &told, &s, &req).image; + let unknown = render(&reduced, &info(), &s, &req).image; + let resampling = rms(&render(&original, &info(), &off, &req).image, &render(&reduced, &told, &off, &req).image); + let (a, b) = (rms(&from_original, &from_reduced), rms(&from_original, &unknown)); + assert!(a < resampling + 0.5, "original-size radius: {a}, resampling {resampling}"); + assert!(b > a + 0.3, "copy-size radius: {b}, original-size radius: {a}"); +} + +#[test] +fn old_processes_keep_their_sharpening_and_cache_switches_are_exact() { + use crate::{StageCache, render_cached}; + use lightcraft_develop::Process; + use std::sync::Arc; + let src = Arc::new(scene(256)); + let req = RenderRequest::fit(256, 256); + let cache = StageCache::default(); + for process in [Process::V1, Process::V2, Process::V3, Process::V2, Process::V3] { + let mut s = sharp(80.0, 0.6, 0.0, 30.0); + s.process = process.version(); + let plain = render(&src, &info(), &s, &req).image; + assert_eq!(render_cached(&src, &info(), &s, &req, &cache).image, plain); + s.detail.sharpen_radius = 3.0; + s.detail.sharpen_detail = 100.0; + let changed = render(&src, &info(), &s, &req).image; + if process < Process::V3 { + assert_eq!(changed, plain, "{process:?}"); + } else { + assert_ne!(changed, plain); + } + for nr in [60.0, 20.0] { + s.detail.nr_luminance = nr; + assert_eq!(render_cached(&src, &info(), &s, &req, &cache).image, render(&src, &info(), &s, &req).image, "{process:?}, NR {nr}"); + } + } +} + +#[test] +fn texture_does_not_depend_on_sharpening_settings() { + let src = scene(256); + let mut a = DevelopSettings::default(); + a.effects.texture = 50.0; + let mut b = a.clone(); + b.detail.sharpen_radius = 3.0; + b.detail.sharpen_detail = 100.0; + assert_eq!(render_at(&src, &a, 256).data, render_at(&src, &b, 256).data); +} + +#[test] +fn local_sharpness_uses_the_sharpen_band() { + use lightcraft_develop::{LocalAdjustments, Mask, MaskComponent, MaskOp, MaskShape}; + use lightcraft_geom::Point; + let src = scene(256); + let mut s = DevelopSettings { + masks: vec![Mask { + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Linear { start: Point::new(0.5, 0.0), end: Point::new(0.5, 0.01) }, + }], + adjust: LocalAdjustments { sharpness: 100.0, ..Default::default() }, + ..Default::default() + }], + ..Default::default() + }; + let plain = render_at(&src, &DevelopSettings::default(), 256); + let with = render_at(&src, &s, 256); + assert!(rms(&with, &plain) > 0.05, "{}", rms(&with, &plain)); + s.detail.sharpen_radius = 3.0; + assert_ne!(render_at(&src, &s, 256).data, with.data, "Radius reaches the local sharpness band"); +} + +/// An enlarging export (2× the original) scales Radius 2 and 3 to 4 and 6 px: they stay distinct +/// rather than meeting at a 4 px cap. +#[test] +fn enlarged_export_keeps_radius_steps_apart() { + use crate::Quality; + use crate::local::plane_sigmas; + let sigma = |r: f64| plane_sigmas(&sharp(100.0, r, 0.0, 0.0), 1024.0, 512.0, Quality::Full).sharpen.unwrap(); + assert_eq!((sigma(2.0), sigma(3.0)), (4.0, 6.0)); + let src = scene(128); + let enlarged = SourceInfo { native_long: Some(64), ..info() }; + let at = |r: f64| render(&src, &enlarged, &sharp(100.0, r, 0.0, 0.0), &RenderRequest::fit(128, 128)).image; + let d = rms(&at(2.0), &at(3.0)); + assert!(d > 0.1, "Radius 2 and 3 render alike at 2x: {d}"); +} diff --git a/crates/pipeline/src/tests_tone.rs b/crates/pipeline/src/tests_tone.rs index 87e1b659ac..adfda3fc0d 100644 --- a/crates/pipeline/src/tests_tone.rs +++ b/crates/pipeline/src/tests_tone.rs @@ -152,8 +152,8 @@ fn zero_highlights_and_shadows_render_without_the_base() { controls::set(&mut s, "effects.clarity", 40.0); // no base plane is computed or read (the per-pixel stage sees log luminance): the render is // the one it always was - assert_eq!(local::plane_sigmas(&s, 1200.0, Quality::Full).base, None); - assert!(local::plane_sigmas(&with("light.shadows", 1.0), 1200.0, Quality::Full).base.is_some()); + assert_eq!(local::plane_sigmas(&s, 1200.0, 1200.0, Quality::Full).base, None); + assert!(local::plane_sigmas(&with("light.shadows", 1.0), 1200.0, 1200.0, Quality::Full).base.is_some()); } #[test] @@ -216,7 +216,7 @@ fn v1_keeps_the_base_it_always_had() { assert_eq!(ProcessVersion::legacy().process(), Process::V1); for ppl in [300.0, 1200.0, 5568.0, 1e6] { for q in [Quality::Full, Quality::Draft] { - let sig = local::plane_sigmas(&v1, ppl, q); + let sig = local::plane_sigmas(&v1, ppl, ppl, q); assert!(sig.base.is_some()); assert_eq!(sig.base_detail, 0, "V1 at {ppl} px"); assert_eq!(local::tone_base_detail(&v1, ppl), 0); @@ -229,8 +229,8 @@ fn v1_keeps_the_base_it_always_had() { } // V2 takes the median wherever the image is big enough for one let v2 = with("light.highlights", -100.0); - assert_eq!(local::plane_sigmas(&v2, 5568.0, Quality::Full).base_detail, local::base_detail_radius(5568.0)); - assert_eq!(local::plane_sigmas(&v2, 300.0, Quality::Full).base_detail, 0); + assert_eq!(local::plane_sigmas(&v2, 5568.0, 5568.0, Quality::Full).base_detail, local::base_detail_radius(5568.0)); + assert_eq!(local::plane_sigmas(&v2, 300.0, 300.0, Quality::Full).base_detail, 0); } #[test] @@ -259,7 +259,7 @@ fn the_base_plane_is_cached_per_process() { let warm = render_cached(&src, &info, s, &req, &cache).image; assert!(warm == render(&src, &info, s, &req).image, "process {:?}", s.process); } - let sig = local::plane_sigmas(&s2, W as f64, Quality::Full); + let sig = local::plane_sigmas(&s2, W as f64, W as f64, Quality::Full); let sg = sig.base.unwrap(); assert_ne!(local::base_key(&s1, sg, 0), local::base_key(&s2, sg, 0), "the process is part of the key"); assert_ne!(local::base_key(&s2, sg, 0), local::base_key(&s2, sg, sig.base_detail)); diff --git a/crates/pipeline/src/visualize.rs b/crates/pipeline/src/visualize.rs index cda511baa8..63bd7dc858 100644 --- a/crates/pipeline/src/visualize.rs +++ b/crates/pipeline/src/visualize.rs @@ -244,19 +244,25 @@ pub fn adjust_settings(o: Overlay, s: &mut Cow<'_, DevelopSettings>) { } /// The plane a sharpening view draws ([`Overlay::reads_detail`]), from the render's log luminance -/// `log_l` and its texture blur (`None` when the render didn't need it: blurred here with the same -/// sigma). [`Overlay::SharpenDetail`]: the detail band (log luminance minus its blur, in EV); +/// `log_l` and its process-specific sharpening blur (`None` when the render didn't need it: +/// blurred here with the same kernel and sigma). [`Overlay::SharpenDetail`]: the detail band (log luminance minus its blur, in EV); /// [`Overlay::SharpenMask`]: the sharpening weight under the photo's Masking. Both renderers call /// this with their own planes. -pub fn sharpen_plane(o: Overlay, s: &DevelopSettings, log_l: &Plane, texture: Option<&Plane>, px_per_long: f64) -> Option { +pub fn sharpen_plane(o: Overlay, s: &DevelopSettings, log_l: &Plane, band: Option<&Plane>, px_per_long: f64, native_long: f64) -> Option { if !o.reads_detail() { return None; } let own; - let blur = match texture.filter(|b| (b.width, b.height) == (log_l.width, log_l.height)) { + let pixel = crate::local::pixel_sharpen(s); + let blur = match band.filter(|b| (b.width, b.height) == (log_l.width, log_l.height)) { Some(b) => b, None => { - own = lightcraft_raster::blur::gaussian(log_l, crate::local::texture_sigma(px_per_long)); + own = if pixel { + let sigma = crate::local::sharpen_sigma(crate::local::sharpen_sigma_raw(s, px_per_long, native_long)); + lightcraft_raster::blur::gaussian_taps(log_l, &lightcraft_raster::blur::gauss_taps(sigma)) + } else { + lightcraft_raster::blur::gaussian(log_l, crate::local::texture_sigma(px_per_long)) + }; &own } }; @@ -268,7 +274,13 @@ pub fn sharpen_plane(o: Overlay, s: &DevelopSettings, log_l: &Plane, texture: Op .zip(&blur.data) .map(|(l, b)| { let det = l - b; - if mask { crate::finish::sharpen_mask_weight(masking, det) } else { det } + if !mask { + det + } else if pixel { + crate::finish::pixel_sharpen_mask_weight(masking, det) + } else { + crate::finish::sharpen_mask_weight(masking, det) + } }) .collect(); Some(Plane { width: log_l.width, height: log_l.height, data }) @@ -596,6 +608,48 @@ mod tests { assert_eq!(render(&src, &info, &s, &req(Overlay::None)).image, plain.image); } + #[test] + fn sharpening_preview_follows_the_process_radius_and_render_planes() { + use lightcraft_develop::Process; + use lightcraft_raster::blur::{gaussian, gaussian_taps}; + let l = Plane { width: 80, height: 16, data: (0..1280).map(|i| ((i % 80) as f32 * 0.73).sin() * 0.3).collect() }; + let mut s = DevelopSettings::default(); + let mut bands = Vec::new(); + for process in Process::ALL { + s.process = process.version(); + s.detail.sharpen_radius = 3.0; + s.detail.sharpen_masking = 70.0; + let pixel = crate::local::pixel_sharpen(&s); + let blur = if pixel { + let sigma = crate::local::sharpen_sigma(crate::local::sharpen_sigma_raw(&s, 80.0, 160.0)); + gaussian_taps(&l, &lightcraft_raster::blur::gauss_taps(sigma)) + } else { + gaussian(&l, crate::local::texture_sigma(80.0)) + }; + for o in [Overlay::SharpenDetail, Overlay::SharpenMask] { + let cached = sharpen_plane(o, &s, &l, Some(&blur), 80.0, 160.0).unwrap(); + let fresh = sharpen_plane(o, &s, &l, None, 80.0, 160.0).unwrap(); + assert_eq!(cached.data, fresh.data, "{process:?} {o:?}"); + for ((&actual, &log), &base) in fresh.data.iter().zip(&l.data).zip(&blur.data) { + let det = log - base; + let expected = if o == Overlay::SharpenDetail { + det + } else if pixel { + crate::finish::pixel_sharpen_mask_weight(0.7, det) + } else { + crate::finish::sharpen_mask_weight(0.7, det) + }; + assert_eq!(actual, expected); + } + } + bands.push(sharpen_plane(Overlay::SharpenDetail, &s, &l, None, 80.0, 160.0).unwrap().data); + } + assert_eq!(bands[0], bands[1], "the legacy previews stay unchanged"); + assert_ne!(bands[1], bands[2], "V3 previews use the pixel-scale band"); + s.detail.sharpen_radius = 1.0; + assert_ne!(bands[2], sharpen_plane(Overlay::SharpenDetail, &s, &l, None, 80.0, 160.0).unwrap().data); + } + #[test] fn sharpening_previews_show_the_mask_and_detail() { // a smooth ramp (left) and a hard edge (at x = 60) diff --git a/crates/raster/src/blur.rs b/crates/raster/src/blur.rs index 36e3a64cf2..9fefea9ca2 100644 --- a/crates/raster/src/blur.rs +++ b/crates/raster/src/blur.rs @@ -126,8 +126,67 @@ pub fn gaussian(img: &Image, sigma: f32) -> Image { a } +/// Largest sigma [`gauss_taps`] makes taps for (larger ones are clamped to it). The GPU blur reads +/// the same taps, so it is the limit of both paths. +pub const GAUSS_SIGMA_MAX: f32 = 64.0; + +/// Normalized Gaussian taps `[w(-r) .. w(r)]` for `sigma`, `r = ceil(3 sigma)`. +/// +/// An exact kernel, unlike the three-box approximation of [`gaussian`], which cannot represent +/// a sigma under about 0.8 px (its boxes collapse to the identity): sharpening needs those. +pub fn gauss_taps(sigma: f32) -> Vec { + let sigma = if sigma.is_nan() { 0.05 } else { sigma.clamp(0.05, GAUSS_SIGMA_MAX) }; + let r = (3.0 * sigma).ceil() as i32; + let k = -0.5 / (sigma * sigma); + let mut t: Vec = (-r..=r).map(|i| ((i * i) as f32 * k).exp()).collect(); + let sum: f32 = t.iter().sum(); + t.iter_mut().for_each(|v| *v /= sum); + t +} + +/// Separable blur with odd-length symmetric `taps` (clamped edges), see [`gauss_taps`]. +pub fn gaussian_taps(img: &Image, taps: &[f32]) -> Image { + let (w, h) = (img.width, img.height); + if w == 0 || h == 0 || taps.len() < 3 { + return img.clone(); + } + let r = (taps.len() / 2) as isize; + let mut a = Image::::new(w, h); + par_rows(&mut a.data, w, |y, row| { + let src = &img.data[y * w..(y + 1) * w]; + for (x, o) in row.iter_mut().enumerate() { + let mut acc = T::zero(); + for (k, t) in taps.iter().enumerate() { + let xi = (x as isize + k as isize - r).clamp(0, w as isize - 1) as usize; + acc = acc.madd(src[xi], *t); + } + *o = acc; + } + }); + let mut b = Image::::new(w, h); + par_rows(&mut b.data, w, |y, row| { + for (k, t) in taps.iter().enumerate() { + let yi = (y as isize + k as isize - r).clamp(0, h as isize - 1) as usize; + for (o, v) in row.iter_mut().zip(&a.data[yi * w..(yi + 1) * w]) { + *o = o.madd(*v, *t); + } + } + }); + b +} + #[cfg(test)] mod tests { + #[test] + fn fir_gaussian_has_bounded_finite_taps_for_hostile_sigmas() { + for sigma in [f32::NAN, f32::NEG_INFINITY, f32::INFINITY, f32::MAX, -5.0, 0.0, 0.1, 4.0] { + let taps = super::gauss_taps(sigma); + assert!(taps.len() <= 385 && taps.len() % 2 == 1); + assert!(taps.iter().all(|v| v.is_finite() && *v >= 0.0)); + assert!((taps.iter().sum::() - 1.0).abs() < 1e-5); + } + } + /// The box radii of the formula as it was, for the check below. fn box_radii_before(sigma: f32) -> [usize; 3] { let n = 3.0f32; diff --git a/crates/raw/src/dcp.rs b/crates/raw/src/dcp.rs new file mode 100644 index 0000000000..774b1ceab1 --- /dev/null +++ b/crates/raw/src/dcp.rs @@ -0,0 +1,335 @@ +//! DNG Camera Profiles (`.dcp`): the user's own camera colour profiles, read at run time from +//! files they supply (DNG specification, chapter 6 "Camera Profiles"). A `.dcp` is a TIFF-structured +//! file whose header carries the magic `RC` (0x4352) in place of 42, with the profile tags in IFD 0: +//! `UniqueCameraModel`, `ProfileName`, the colour/forward matrices and calibration illuminants, the +//! hue/saturation map, look table and tone curve. Nothing here ships a profile. + +use lightcraft_tiff::{Ifd, ParseOptions, Tiff, tags as t}; + +use crate::ColorData; +use crate::dng::color_data; + +/// The magic number of a DNG camera profile file (`IIRC` / `MMCR`). +pub const DCP_MAGIC: u16 = 0x4352; + +/// A parsed camera profile. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct DcpProfile { + /// `ProfileName` (empty when the file has none). + pub name: String, + /// `UniqueCameraModel`: the camera the profile was made for (empty when absent). + pub camera_model: String, + /// The colour model: illuminants, matrices and the profile look (hue/sat map, look table, tone curve). + pub color: ColorData, +} + +impl DcpProfile { + /// `color` (a raw file's own colour facts) with this profile's colour model in place of the + /// file's: its matrices, illuminants and look. The file's white balance (as-shot neutral or + /// white, and its white-balance presets), analog balance and baseline exposure stay, plus its + /// camera calibration when the profile has the same calibration illuminants (DNG 6.3: + /// calibration belongs to the camera, the profile to the look). + pub fn applied_to(&self, color: &ColorData) -> ColorData { + let calibration = if self.color.illuminant == color.illuminant { color.camera_calibration } else { [None, None] }; + ColorData { + illuminant: self.color.illuminant, + color_matrix: self.color.color_matrix, + forward_matrix: self.color.forward_matrix, + camera_calibration: calibration, + analog_balance: color.analog_balance, + as_shot_neutral: color.as_shot_neutral, + as_shot_white_xy: color.as_shot_white_xy, + baseline_exposure: color.baseline_exposure + self.color.baseline_exposure, + baseline_sharpness: color.baseline_sharpness, + profile: crate::profile::ProfileLook { gain_table_map: color.profile.gain_table_map.clone(), ..self.color.profile.clone() }, + kelvin_presets: color.kelvin_presets.clone(), + } + } +} + +/// Errors reading a `.dcp`. +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum DcpError { + #[error("not a DNG camera profile (.dcp)")] + NotDcp, + #[error("damaged camera profile: {0}")] + Damaged(String), + #[error("the camera profile has no usable colour matrix")] + NoMatrix, +} + +/// Is `bytes` a DCP file (by its header)? +pub fn is_dcp(bytes: &[u8]) -> bool { + matches!(bytes.get(0..4), Some([b'I', b'I', b'R', b'C'] | [b'M', b'M', b'C', b'R'])) +} + +/// The largest `.dcp` file read or parsed (real profiles are kilobytes to a few MB). +pub const MAX_DCP_BYTES: u64 = 64 << 20; + +/// Read the `.dcp` file at `path`, reading at most [`MAX_DCP_BYTES`] + 1 bytes: a larger file is refused +/// before it is loaded into memory. +pub fn read_dcp(path: &std::path::Path) -> std::io::Result> { + use std::io::Read; + let mut bytes = Vec::new(); + std::fs::File::open(path)?.take(MAX_DCP_BYTES.saturating_add(1)).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_DCP_BYTES { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "the camera profile is larger than 64 MiB")); + } + Ok(bytes) +} + +/// Parse a `.dcp` file. Files above 64 MiB ([`MAX_DCP_BYTES`]) are refused. +pub fn parse_dcp(bytes: &[u8]) -> Result { + if !is_dcp(bytes) { + return Err(DcpError::NotDcp); + } + if bytes.len() as u64 > MAX_DCP_BYTES { + return Err(DcpError::Damaged("larger than 64 MiB".into())); + } + // the TIFF reader only knows 42 / BigTIFF / raw magics: give it a header with 42 in place of RC + let mut data = bytes.to_vec(); + let forty_two: [u8; 2] = if bytes.first() == Some(&b'I') { [42, 0] } else { [0, 42] }; + if let Some(m) = data.get_mut(2..4) { + m.copy_from_slice(&forty_two); + } + let opts = ParseOptions { follow_children: false, max_ifds: 4, value_budget: Some(64 << 20), ..Default::default() }; + let tiff = Tiff::parse_with(&data, &opts).map_err(|e| DcpError::Damaged(e.to_string()))?; + let ifd: &Ifd = tiff.ifds.first().ok_or_else(|| DcpError::Damaged("no IFD".into()))?; + let mut color = color_data(ifd, ifd, tiff.order); + // a profile carries no white balance or calibration of a particular shot + color.as_shot_neutral = None; + color.as_shot_white_xy = None; + color.analog_balance = None; + color.camera_calibration = [None, None]; + color.baseline_sharpness = None; + color.profile.gain_table_map = None; + // only BaselineExposureOffset belongs to a profile (BaselineExposure is the camera's) + color.baseline_exposure = + ifd.f64s(t::BASELINE_EXPOSURE_OFFSET).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0).clamp(-4.0, 4.0); + // a single-illuminant profile names one illuminant; its second matrix slot stays empty + if color.color_matrix[0].is_none() { + // the first slot is the one every profile must fill (DNG: ColorMatrix1 is required) + return Err(DcpError::NoMatrix); + } + let text = |tag: u16| ifd.string(tag).map(|s| s.trim_matches(char::from(0)).trim().to_string()).unwrap_or_default(); + Ok(DcpProfile { name: text(t::PROFILE_NAME), camera_model: text(t::UNIQUE_CAMERA_MODEL), color }) +} + +/// Write `p` as a `.dcp` file (little-endian): its name, camera, illuminants, matrices, hue/saturation +/// map, look table, tone curve and baseline exposure offset. +pub fn write_dcp(p: &DcpProfile) -> Result, DcpError> { + use lightcraft_tiff::writer::srational; + use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; + let c = &p.color; + let mut ifd = IfdBuilder::new(); + ifd.set(t::UNIQUE_CAMERA_MODEL, Value::Ascii(p.camera_model.clone())); + ifd.set(t::PROFILE_NAME, Value::Ascii(p.name.clone())); + let mat = |m: &lightcraft_color::Mat3| Value::SRational(m.0.iter().flatten().map(|v| srational(*v)).collect()); + for i in 0..2 { + if let Some(m) = &c.color_matrix[i] { + ifd.set([t::CALIBRATION_ILLUMINANT_1, t::CALIBRATION_ILLUMINANT_2][i], Value::Short(vec![c.illuminant[i]])); + ifd.set([t::COLOR_MATRIX_1, t::COLOR_MATRIX_2][i], mat(m)); + } + if let Some(m) = &c.forward_matrix[i] { + ifd.set([t::FORWARD_MATRIX_1, t::FORWARD_MATRIX_2][i], mat(m)); + } + } + let flat = |table: &crate::profile::HsvTable| Value::Float(table.data.iter().flatten().copied().collect()); + let dims = + |table: &crate::profile::HsvTable| Value::Long(vec![table.hue_divisions as u32, table.sat_divisions as u32, table.val_divisions as u32]); + if let Some(a) = c.profile.hue_sat_map[0].as_ref() { + ifd.set(t::PROFILE_HUE_SAT_MAP_DIMS, dims(a)); + ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_1, flat(a)); + if a.srgb_value { + ifd.set(t::PROFILE_HUE_SAT_MAP_ENCODING, Value::Long(vec![1])); + } + if let Some(b) = c.profile.hue_sat_map[1] + .as_ref() + .filter(|b| (b.hue_divisions, b.sat_divisions, b.val_divisions) == (a.hue_divisions, a.sat_divisions, a.val_divisions)) + { + ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_2, flat(b)); + } + } + if let Some(l) = &c.profile.look_table { + ifd.set(t::PROFILE_LOOK_TABLE_DIMS, dims(l)); + ifd.set(t::PROFILE_LOOK_TABLE_DATA, flat(l)); + if l.srgb_value { + ifd.set(t::PROFILE_LOOK_TABLE_ENCODING, Value::Long(vec![1])); + } + } + if let Some(tc) = &c.profile.tone_curve { + ifd.set(t::PROFILE_TONE_CURVE, Value::Float(tc.points.iter().flatten().copied().collect())); + } + if c.baseline_exposure != 0.0 { + ifd.set(t::BASELINE_EXPOSURE_OFFSET, Value::SRational(vec![srational(c.baseline_exposure)])); + } + let mut out = TiffWriter::new(ByteOrder::Little, false).write(&[ifd]).map_err(|e| DcpError::Damaged(e.to_string()))?; + // the DCP magic in place of 42 + if let Some(m) = out.get_mut(2..4) { + m.copy_from_slice(&DCP_MAGIC.to_le_bytes()); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reading_a_profile_stops_past_the_size_limit() { + let dir = std::env::temp_dir().join(format!("lc-read-dcp-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (fits, big) = (dir.join("fits.dcp"), dir.join("big.dcp")); + std::fs::File::create(&fits).unwrap().set_len(MAX_DCP_BYTES).unwrap(); + std::fs::File::create(&big).unwrap().set_len(MAX_DCP_BYTES + 1).unwrap(); + assert_eq!(read_dcp(&fits).unwrap().len() as u64, MAX_DCP_BYTES); + assert_eq!(read_dcp(&big).unwrap_err().kind(), std::io::ErrorKind::InvalidData); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A minimal single-illuminant profile (our own numbers) built in memory: no profile file is + /// committed to the repository. + pub(crate) fn synthetic_dcp(little: bool, with_hue_sat: bool) -> Vec { + // entries: (tag, type, count, payload bytes) + let mut entries: Vec<(u16, u16, u32, Vec)> = Vec::new(); + let u16b = |v: u16| if little { v.to_le_bytes().to_vec() } else { v.to_be_bytes().to_vec() }; + let u32b = |v: u32| if little { v.to_le_bytes().to_vec() } else { v.to_be_bytes().to_vec() }; + let srat = |v: f64| { + let (n, d) = ((v * 10000.0).round() as i32, 10000i32); + let mut b = if little { n.to_le_bytes().to_vec() } else { n.to_be_bytes().to_vec() }; + b.extend(if little { d.to_le_bytes() } else { d.to_be_bytes() }); + b + }; + let ascii = |s: &str| { + let mut b = s.as_bytes().to_vec(); + b.push(0); + b + }; + entries.push((t::UNIQUE_CAMERA_MODEL, 2, 13, ascii("Test Camera1"))); + let m = [0.9, -0.3, -0.05, -0.4, 1.2, 0.2, -0.05, 0.15, 0.7]; + entries.push((t::COLOR_MATRIX_1, 10, 9, m.iter().flat_map(|v| srat(*v)).collect())); + entries.push((t::CALIBRATION_ILLUMINANT_1, 3, 1, [u16b(21), vec![0, 0]].concat())); + entries.push((t::PROFILE_NAME, 2, 9, ascii("My Look"))); + if with_hue_sat { + // 2 hues × 2 sats × 1 value: hue shift, sat scale, value scale per entry (FLOAT) + entries.push((t::PROFILE_HUE_SAT_MAP_DIMS, 4, 3, [u32b(2), u32b(2), u32b(1)].concat())); + let f = |v: f32| if little { v.to_le_bytes().to_vec() } else { v.to_be_bytes().to_vec() }; + entries.push(( + t::PROFILE_HUE_SAT_MAP_DATA_1, + 11, + 12, + [f(0.0), f(1.0), f(1.0), f(5.0), f(1.1), f(1.0), f(0.0), f(1.0), f(1.0), f(-5.0), f(0.9), f(1.0)].concat(), + )); + } + entries.sort_by_key(|e| e.0); + let mut out = if little { b"IIRC".to_vec() } else { b"MMCR".to_vec() }; + out.extend(u32b(8)); + let n = entries.len(); + let mut data_off = 8 + 2 + n * 12 + 4; + let mut ifd = u16b(n as u16); + let mut tail = Vec::new(); + for (tag, ty, count, payload) in &entries { + ifd.extend(u16b(*tag)); + ifd.extend(u16b(*ty)); + ifd.extend(u32b(*count)); + if payload.len() <= 4 { + let mut p = payload.clone(); + p.resize(4, 0); + ifd.extend(p); + } else { + ifd.extend(u32b(data_off as u32)); + tail.extend(payload); + data_off += payload.len(); + if data_off % 2 == 1 { + tail.push(0); + data_off += 1; + } + } + } + ifd.extend(u32b(0)); + out.extend(ifd); + out.extend(tail); + out + } + + #[test] + fn reads_a_single_illuminant_profile_in_both_byte_orders() { + for little in [true, false] { + let p = parse_dcp(&synthetic_dcp(little, true)).unwrap(); + assert_eq!(p.name, "My Look"); + assert_eq!(p.camera_model, "Test Camera1"); + assert_eq!(p.color.illuminant, [21, 0]); + let m = p.color.color_matrix[0].unwrap(); + assert!((m.0[1][1] - 1.2).abs() < 1e-4, "{m:?}"); + assert!(p.color.color_matrix[1].is_none()); + assert!(p.color.profile.hue_sat_map[0].is_some()); + assert!(p.color.as_shot_neutral.is_none()); + } + assert!(parse_dcp(&synthetic_dcp(true, false)).unwrap().color.profile.hue_sat_map[0].is_none()); + } + + #[test] + fn rejects_other_files_and_damage_without_panicking() { + assert_eq!(parse_dcp(b"II*\0\x08\0\0\0"), Err(DcpError::NotDcp)); + assert_eq!(parse_dcp(b""), Err(DcpError::NotDcp)); + let good = synthetic_dcp(true, true); + for cut in [4, 8, 10, 30, good.len() / 2, good.len() - 1] { + let _ = parse_dcp(&good[..cut]); + } + let mut bad = good.clone(); + bad[4..8].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(parse_dcp(&bad).is_err()); + } + + /// The hue/saturation map's header is the user's file too: dimensions far past the data, an entry count + /// claiming 4 billion values, or a data offset past the end drop the map (the matrix still reads) instead of + /// allocating for the claim or reading past the file. + #[test] + fn a_hostile_hue_sat_map_header_drops_the_map() { + let good = synthetic_dcp(true, true); + let at = |needle: &[u8]| good.windows(needle.len()).position(|w| w == needle).unwrap(); + let le = |v: &[u32]| v.iter().flat_map(|x| x.to_le_bytes()).collect::>(); + let dims = at(&le(&[2, 2, 1])); + // the map data's directory entry: tag, FLOAT, count 12, offset + let entry = at(&[t::PROFILE_HUE_SAT_MAP_DATA_1.to_le_bytes(), 11u16.to_le_bytes()].concat()); + let patched = |at: usize, bytes: &[u8]| { + let mut b = good.clone(); + b[at..at + bytes.len()].copy_from_slice(bytes); + b + }; + for (what, bytes) in [ + ("4096³ dimensions", patched(dims, &le(&[4096, 4096, 4096]))), + ("dimensions past u32 products", patched(dims, &le(&[u32::MAX, u32::MAX, u32::MAX]))), + ("a zero dimension", patched(dims, &le(&[0, 2, 1]))), + ("4 billion values", patched(entry + 4, &le(&[u32::MAX]))), + ("data past the end", patched(entry + 8, &le(&[u32::MAX - 16]))), + ] { + let p = parse_dcp(&bytes).unwrap_or_else(|e| panic!("{what}: {e:?}")); + assert!(p.color.profile.hue_sat_map[0].is_none(), "{what}: the map is dropped"); + assert!(p.color.color_matrix[0].is_some(), "{what}: the matrix still reads"); + } + } + + #[test] + fn written_profiles_read_back() { + let p = parse_dcp(&synthetic_dcp(false, true)).unwrap(); + let back = parse_dcp(&write_dcp(&p).unwrap()).unwrap(); + assert_eq!(back.name, p.name); + assert_eq!(back.camera_model, p.camera_model); + assert_eq!(back.color.illuminant, p.color.illuminant); + assert_eq!(back.color.profile.hue_sat_map, p.color.profile.hue_sat_map); + let (a, b) = (back.color.color_matrix[0].unwrap(), p.color.color_matrix[0].unwrap()); + assert!(a.0.iter().flatten().zip(b.0.iter().flatten()).all(|(x, y)| (x - y).abs() < 1e-6)); + } + + #[test] + fn applying_keeps_the_shot_and_replaces_the_look() { + let p = parse_dcp(&synthetic_dcp(true, true)).unwrap(); + let file = ColorData { as_shot_neutral: Some([0.5, 1.0, 0.7]), baseline_exposure: 0.25, ..Default::default() }; + let c = p.applied_to(&file); + assert_eq!(c.as_shot_neutral, Some([0.5, 1.0, 0.7])); + assert_eq!(c.color_matrix, p.color.color_matrix); + assert!(c.profile.hue_sat_map[0].is_some()); + assert!((c.baseline_exposure - 0.25).abs() < 1e-12); + } +} diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index b0398cd076..e8052c3bbb 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -28,6 +28,7 @@ mod binned; pub mod color; +pub mod dcp; pub mod demosaic; mod dng; pub mod dngwrite; diff --git a/crates/raw/tests/dcp_corpus.rs b/crates/raw/tests/dcp_corpus.rs new file mode 100644 index 0000000000..5f7a8e2ca9 --- /dev/null +++ b/crates/raw/tests/dcp_corpus.rs @@ -0,0 +1,148 @@ +//! A real camera profile: the Nikon D750 ColorChecker DCP dieli released under CC0 +//! (github.com/dieli/d750-lightcraft-colorchecker, pinned in `D750_COLORCHECKER`, xtask/src/main.rs; +//! `cargo xtask corpus --download` puts it in the gitignored `corpus/d750-colorchecker/`). +//! +//! Calibrite PROFILER made it from two chart shots: a dual-illuminant, matrix-only profile +//! (`ColorMatrix1/2` for Cool White Fluorescent and D55; no `ForwardMatrix`, hue/saturation map, +//! look table or tone curve). The tests check that it parses as such, that the matrices blend between +//! the two illuminants by the white's inverse temperature, that the matrix-only path (no forward +//! matrix) gives a usable camera transform, and that it develops the chart NEFs it was made from. +//! Missing files are reported as skipped. + +use lightcraft_color::{Xy, cct}; +use lightcraft_raw::color::{camera_to_xyz_d50, camera_transform_of, illuminant_weight, xyz_to_camera}; +use lightcraft_raw::dcp::{DcpProfile, parse_dcp, write_dcp}; +use lightcraft_raw::{Mat3, decode}; +use std::path::{Path, PathBuf}; + +const PROFILE: &str = "profiles/20261016_NikonD750_DualIllumination_ColorCheckerPassport.dcp"; +const CHARTS: [&str; 2] = ["raw/chart-daylight_flash.NEF", "raw/chart-indoor.NEF"]; + +fn set_dir() -> PathBuf { + std::env::var_os("LIGHTCRAFT_CORPUS") + .map(PathBuf::from) + .unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus")) + .join("d750-colorchecker") +} + +fn read(rel: &str) -> Option> { + let path = set_dir().join(rel); + let bytes = std::fs::read(&path).ok(); + if bytes.is_none() { + lightcraft_testkit::skip!(Corpus, "{} absent (cargo xtask corpus --download)", path.display()); + } + bytes +} + +fn profile() -> Option { + read(PROFILE).map(|b| parse_dcp(&b).expect("the D750 profile parses")) +} + +fn max_diff(a: &Mat3, b: &Mat3) -> f64 { + a.0.iter().flatten().zip(b.0.iter().flatten()).map(|(x, y)| (x - y).abs()).fold(0.0, f64::max) +} + +#[test] +fn the_d750_profile_parses_as_a_dual_illuminant_matrix_only_profile() { + let Some(p) = profile() else { return }; + assert!(p.camera_model.contains("D750"), "camera {:?}", p.camera_model); + // CalibrationIlluminant1/2: Cool White Fluorescent (14) and D55 (20) + assert_eq!(p.color.illuminant, [14, 20]); + let [Some(cm1), Some(cm2)] = p.color.color_matrix else { panic!("two colour matrices: {:?}", p.color.color_matrix) }; + assert!(max_diff(&cm1, &cm2) > 1e-3, "the two illuminants have their own matrices"); + for m in [cm1, cm2] { + assert!(m.0.iter().flatten().all(|v| v.is_finite() && v.abs() < 10.0), "{m:?}"); + assert!(m.inverse().is_some(), "invertible: {m:?}"); + } + assert_eq!(p.color.forward_matrix, [None, None], "matrix-only: no forward matrix"); + assert!(p.color.profile.hue_sat_map.iter().all(Option::is_none), "no hue/saturation map"); + assert!(p.color.profile.look_table.is_none(), "no look table"); + // nothing of a particular shot + assert_eq!((p.color.as_shot_neutral, p.color.analog_balance), (None, None)); + // our writer keeps what matters of it + let again = parse_dcp(&write_dcp(&p).unwrap()).unwrap(); + assert_eq!((again.name.as_str(), again.camera_model.as_str(), again.color.illuminant), (p.name.as_str(), p.camera_model.as_str(), [14, 20])); + for i in 0..2 { + assert!(max_diff(&again.color.color_matrix[i].unwrap(), &p.color.color_matrix[i].unwrap()) < 1e-6); + } +} + +#[test] +fn the_d750_matrices_blend_by_inverse_temperature_between_the_two_illuminants() { + let Some(p) = profile() else { return }; + let c = &p.color; + let [Some(cm1), Some(cm2)] = c.color_matrix else { panic!("two colour matrices") }; + let at = |k: f64| cct::temp_tint_to_xy(k, 0.0); + // at and beyond each calibration illuminant (4150 K / 5503 K) only its own matrix + for k in [2800.0, 4150.0] { + assert!((illuminant_weight(c, at(k)) - 1.0).abs() < 0.02, "{k} K: {}", illuminant_weight(c, at(k))); + assert!(max_diff(&xyz_to_camera(c, at(k)), &cm1) < 0.02 * 3.0, "{k} K takes ColorMatrix1"); + } + for k in [5503.0, 7500.0] { + assert!(illuminant_weight(c, at(k)).abs() < 0.02, "{k} K: {}", illuminant_weight(c, at(k))); + assert!(max_diff(&xyz_to_camera(c, at(k)), &cm2) < 0.02 * 3.0, "{k} K takes ColorMatrix2"); + } + // in between: the DNG weighting (1/T − 1/T2) / (1/T1 − 1/T2), and the matrix is that blend + let k = 4800.0; + let w = illuminant_weight(c, at(k)); + let t = cct::xy_to_temp_tint(at(k)).0; + let expected = (1.0 / t - 1.0 / 5503.0) / (1.0 / 4150.0 - 1.0 / 5503.0); + assert!((w - expected).abs() < 1e-6 && w > 0.2 && w < 0.8, "weight {w}, expected {expected}"); + let mut blend = [[0.0; 3]; 3]; + for (i, row) in blend.iter_mut().enumerate() { + for (j, v) in row.iter_mut().enumerate() { + *v = w * cm1.0[i][j] + (1.0 - w) * cm2.0[i][j]; + } + } + assert!(max_diff(&xyz_to_camera(c, at(k)), &Mat3(blend)) < 1e-9); + // weights fall monotonically with temperature + let ws: Vec = [3000.0, 4300.0, 4600.0, 5000.0, 5400.0, 6500.0].iter().map(|k| illuminant_weight(c, at(*k))).collect(); + assert!(ws.windows(2).all(|p| p[0] >= p[1]), "{ws:?}"); +} + +#[test] +fn the_matrix_only_path_inverts_the_colour_matrix_and_adapts_to_d50() { + let Some(p) = profile() else { return }; + let c = &p.color; + for k in [3200.0, 4500.0, 5500.0, 6500.0] { + let white: Xy = cct::temp_tint_to_xy(k, 0.0); + let to_d50 = camera_to_xyz_d50(c, white); + let expected = lightcraft_color::bradford(white, lightcraft_color::D50).mul(&xyz_to_camera(c, white).inverse().unwrap()); + assert!(max_diff(&to_d50, &expected) < 1e-9, "{k} K: no forward matrix, so XYZtoCamera⁻¹ then Bradford"); + // the camera's neutral under that white lands on D50 + let n = xyz_to_camera(c, white).apply(white.to_xyz()); + let xyz = to_d50.apply(n); + let xy = Xy::from_xyz(xyz); + assert!((xy.x - lightcraft_color::D50.x).abs() < 1e-6 && (xy.y - lightcraft_color::D50.y).abs() < 1e-6, "{k} K → {xy:?}"); + // the transform the pipeline uses maps white-balanced (1, 1, 1) to white + let t = camera_transform_of(c, white); + assert!(!t.matrix_is_fallback); + let w = t.matrix.apply([1.0; 3]); + assert!(w.iter().all(|v| (v - 1.0).abs() < 1e-6), "{k} K: {w:?}"); + assert!(t.wb.iter().all(|v| v.is_finite() && *v >= 1.0 && *v < 8.0), "{k} K: {:?}", t.wb); + } +} + +#[test] +fn the_d750_profile_takes_over_the_chart_nefs_colour() { + let Some(p) = profile() else { return }; + let mut whites = Vec::new(); + for chart in CHARTS { + let Some(bytes) = read(chart) else { return }; + let raw = decode(&bytes).expect("the D750 NEF decodes"); + let color = p.applied_to(&raw.color); + assert_eq!(color.color_matrix, p.color.color_matrix, "{chart}: the profile's matrices"); + assert_eq!(color.forward_matrix, [None, None]); + // the camera's own white balance stays and reads as a white under the profile's matrices + let mut with = raw.clone(); + with.color = color; + let white = lightcraft_raw::color::as_shot_white_xy(&with); + let (k, tint) = cct::xy_to_temp_tint(white); + assert!((2000.0..9000.0).contains(&k) && tint.abs() < 60.0, "{chart}: as-shot {k:.0} K, tint {tint:.1}"); + let t = lightcraft_raw::color::camera_transform(&with, white); + assert!(t.matrix.0.iter().flatten().all(|v| v.is_finite()), "{chart}: {t:?}"); + whites.push(k); + } + // the flash shot is the cooler light's opposite: warmer light indoors reads as a lower temperature + assert!(whites[0] > whites[1] + 300.0, "flash {:.0} K vs indoor {:.0} K", whites[0], whites[1]); +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 8e7b77f42f..83a18de446 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -24,6 +24,7 @@ lightcraft-engine = { workspace = true } lightcraft-slideshow = { workspace = true } lightcraft-preview = { workspace = true } egui = { workspace = true } +egui_extras = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } log = { workspace = true } @@ -41,6 +42,8 @@ lightcraft-denoise = { workspace = true, features = ["runtime"] } lightcraft-codecs = { workspace = true } lightcraft-faces = { workspace = true } lightcraft-merge = { workspace = true } +# a device for the GPU-resident view test (`render.rs`) +pollster = { workspace = true } [build-dependencies] serde_json = { workspace = true } diff --git a/crates/ui-egui/examples/thumb_request_bench.rs b/crates/ui-egui/examples/thumb_request_bench.rs index 34fe5fc883..ada42356de 100644 --- a/crates/ui-egui/examples/thumb_request_bench.rs +++ b/crates/ui-egui/examples/thumb_request_bench.rs @@ -113,7 +113,18 @@ fn micro(points: usize, pending: bool) { let key = app.session.thumb_job(id, 384).unwrap().key; app.renderer.textures.insert( Slot::Thumb(id), - Tex { look: None, key, photo: id, tex: texture.clone(), size: [1, 1], histogram: None, ms: 0.0, quick: None, pixels: None }, + Tex { + look: None, + key, + photo: id, + tex: texture.clone(), + size: [1, 1], + histogram: None, + ms: 0.0, + quick: None, + pixels: None, + native: None, + }, ); } request_thumb(&mut app, id, 384, 10); @@ -157,7 +168,7 @@ fn verify_texture(h: &Headless, id: PhotoId) { let edge = tex.size[0].max(tex.size[1]); assert!([128, 256, 384, 512].contains(&edge), "thumbnail must use a supported size bucket"); let Source::File { path } = &p.source else { unreachable!() }; - let (source, info) = h.app.session.media.file_loader.as_ref().unwrap()(path, 512).unwrap(); + let (source, info) = h.app.session.media.file_loader.as_ref().unwrap()(path, 512, None).unwrap(); println!("decode,path={path},raw={},preview_only={:?}", info.raw, p.preview_only); if std::env::var_os("REQUIRE_RAW").is_some() { assert!(p.preview_only.is_none(), "embedded-preview fallback does not validate RAW decoding"); diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 0080fa3504..91eebe1cee 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -306,6 +306,10 @@ impl LightcraftApp { if self.shown_library == Some(generation) { return; } + // (the first library shown takes the place of none: nothing was searching another one) + if self.shown_library.is_some() { + crate::find_similar::library_changed(self); + } self.shown_library = Some(generation); if let Some(l) = self.session.library.as_ref().filter(|l| l.on_disk) { let path = l.dir.to_string_lossy().into_owned(); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index a556e06393..3c6c2e1576 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -133,7 +133,7 @@ pub fn inspect(app: &LightcraftApp, ctx: &egui::Context) -> Value { "selection": app.session.selection.ids.iter().map(|p| p.0).collect::>(), "activeMask": app.session.active_mask, "widgetCount": app.widgets.len(), - "perf": {"viewFollowed": app.session.view_followed, "viewWorkedOut": app.session.view_worked_out, "frameMs": app.perf.frame_ms, "logicMs": app.perf.logic_ms, "updateMs": app.perf.update_ms, "maxUpdateMs": app.perf.max_update_ms, "fps": app.perf.fps, "lastRenderMs": app.renderer.last_main_ms, "renderQueue": app.renderer.queued(), "rendersInFlight": app.renderer.in_flight(), "pendingSlots": app.renderer.pending_slots(), "mergeRunning": app.merge.busy(), "lastMerge": app.merge.last_result, "rendersDone": app.renderer.completed, "thumbTextures": app.renderer.thumb_textures(), "variantTextures": app.renderer.variant_textures(), "gpu": (lightcraft_engine::gpu::ready() && lightcraft_engine::gpu::available()).then(lightcraft_engine::gpu::adapter_name).flatten(), "gpuReason": lightcraft_engine::gpu::unavailable_reason(), "gpuFallback": lightcraft_engine::gpu::last_fallback()}, + "perf": {"viewFollowed": app.session.view_followed, "viewWorkedOut": app.session.view_worked_out, "frameMs": app.perf.frame_ms, "logicMs": app.perf.logic_ms, "updateMs": app.perf.update_ms, "maxUpdateMs": app.perf.max_update_ms, "fps": app.perf.fps, "lastRenderMs": app.renderer.last_main_ms, "renderQueue": app.renderer.queued(), "rendersInFlight": app.renderer.in_flight(), "pendingSlots": app.renderer.pending_slots(), "mergeRunning": app.merge.busy(), "lastMerge": app.merge.last_result, "rendersDone": app.renderer.completed, "thumbTextures": app.renderer.thumb_textures(), "variantTextures": app.renderer.variant_textures(), "gpu": (lightcraft_engine::gpu::ready() && lightcraft_engine::gpu::available()).then(lightcraft_engine::gpu::adapter_name).flatten(), "gpuReason": lightcraft_engine::gpu::unavailable_reason(), "gpuFallback": lightcraft_engine::gpu::last_fallback(), "gpuWindowDevice": lightcraft_engine::gpu::on_window_device(), "screenTextures": app.renderer.has_screen_textures(), "mainOnGpu": app.renderer.textures.get(&crate::render::Slot::Main).is_some_and(|t| t.native.is_some())}, "loupe": app.loupe_shown.map(|(p, src)| json!({ "photo": p.0, "source": src, @@ -345,6 +345,12 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest ctx.request_repaint(); return started; } + if id == "library.findSimilar" { + // reads every photo: on a worker thread, answered when it is done + let started = crate::find_similar::ask(app, ¶ms, req.reply.clone()); + ctx.request_repaint(); + return started; + } let r = app.run(id, params); ctx.request_repaint(); wrap(r) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index d97041eed7..03a1ef5478 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1868,7 +1868,7 @@ fn remove_folder_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { /// The body of the About dialog. fn about_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { let Dialog::About = dlg else { return }; - ui.set_min_width(680.0); + ui.set_min_width(820.0); let tab_id = egui::Id::unique("about_tab"); let mut tab = ui.data_mut(|d| d.get_temp::(tab_id)).unwrap_or(0); ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/dialogs/credits.rs b/crates/ui-egui/src/dialogs/credits.rs index 12f857705a..049bf1eedb 100644 --- a/crates/ui-egui/src/dialogs/credits.rs +++ b/crates/ui-egui/src/dialogs/credits.rs @@ -271,12 +271,17 @@ pub fn contributors_ui(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.label(RichText::new(crate::i18n::tr_format!("{} contributors · {} commits", list.len(), group(TOTAL_COMMITS))).small().color(t.text_dim)); ui.separator(); let list_h = crate::panels::dialogs::list_height(ui, LIST_HEIGHT); - egui::ScrollArea::both().id_salt("credits_scroll").max_height(list_h).auto_shrink([false, true]).show(ui, |ui| { - if list.is_empty() { - ui.label(crate::i18n::tr("No contributor data was built into this copy.")); - } else if v.table { - table(app, ui, &list, &mut v); - } else { + if list.is_empty() { + ui.label(crate::i18n::tr("No contributor data was built into this copy.")); + } else if v.table { + // The table scrolls vertically itself, under a fixed header; it only scrolls sideways + // once its columns are dragged wider than the dialog. + ui.allocate_ui(egui::vec2(ui.available_width(), list_h), |ui| { + ui.set_max_height(list_h); + egui::ScrollArea::horizontal().id_salt("credits_scroll").auto_shrink([false, false]).show(ui, |ui| table(app, ui, &list, &mut v)); + }); + } else { + egui::ScrollArea::vertical().id_salt("credits_scroll").max_height(list_h).auto_shrink([false, true]).show(ui, |ui| { ui.horizontal_wrapped(|ui| { for (i, c) in list.iter().enumerate() { if i > 0 { @@ -285,49 +290,153 @@ pub fn contributors_ui(app: &mut LightcraftApp, ui: &mut egui::Ui) { name_link(app, ui, c, v.names); } }); - } - }); + }); + } ui.data_mut(|d| d.insert_temp(id, v)); } -fn table(app: &mut LightcraftApp, ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) { - egui::Grid::new("credits_table").striped(true).num_columns(SortKey::ALL.len()).show(ui, |ui| { - for k in SortKey::ALL { - let text = RichText::new(crate::i18n::tr(k.label().1)).strong(); - let header = if v.key == k { - crate::widgets::arrow_button( - ui, - text, - if v.ascending { crate::icons::Icon::ChevronUp } else { crate::icons::Icon::ChevronDown }, - false, - ) +/// How the contributor table's spare width is shared out: all of it to Name. +const CONTRIBUTOR_GROW: [f32; 10] = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; + +/// How the model table's spare width is shared out: to Company and Model, the text columns. +const MODEL_GROW: [f32; 6] = [1.0, 2.0, 0.0, 0.0, 0.0, 0.0]; + +/// The narrowest a column can be dragged. +const MIN_COLUMN: f32 = 28.0; + +/// The width a column needs for its header and its widest cell. +fn natural(ui: &egui::Ui, header: RichText, cells: impl Iterator) -> f32 { + let measure = |text: egui::WidgetText| text.into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Body).size().x; + let widest = cells.map(|c| measure(c.into())).fold(measure(header.into()), f32::max); + widest + 2.0 * ui.spacing().button_padding.x +} + +/// Opening column widths: each column's natural width, with the spare room shared out by `grow`, +/// so the columns fill `room` exactly. When there is too little room, only the growing columns +/// give way, each in proportion to its width above [`MIN_COLUMN`], and none goes below that. +fn fit_widths(natural: &[f32], grow: &[f32], room: f32) -> Vec { + let spare = room - natural.iter().sum::(); + let weight = grow.iter().sum::(); + let slack = |w: f32| (w - MIN_COLUMN).max(0.0); + let flexible: f32 = natural.iter().zip(grow).filter(|(_, g)| **g > 0.0).map(|(w, _)| slack(*w)).sum(); + natural + .iter() + .zip(grow) + .map(|(w, g)| { + if *g > 0.0 && spare >= 0.0 { + w + spare * g / weight + } else if *g > 0.0 && flexible > 0.0 { + w - (-spare).min(flexible) * slack(*w) / flexible } else { - ui.button(text) - }; - if header.on_hover_text(crate::i18n::tr(k.label().0)).clicked() { - if v.key == k { - v.ascending = !v.ascending; - } else { - v.key = k; - v.ascending = k.default_ascending(); - } + *w } - } - ui.end_row(); - for c in list { - name_link(app, ui, c, v.names); - ui.label(group(c.prs)); - ui.label(group(c.commits)); - ui.label(group(c.lines_added)); - ui.label(group(c.lines_deleted)); - ui.label(signed(c.lines_delta())); - ui.label(group(c.binary_added)); - ui.label(group(c.binary_deleted)); - ui.label(day(c.first_commit)); - ui.label(day(c.last_commit)); - ui.end_row(); - } - }); + }) + .collect() +} + +/// A striped table whose columns open at [`fit_widths`], so it fills the width and nothing scrolls +/// sideways. Every column, the last included, can be dragged wider or narrower at its right edge: +/// only a table dragged wider than the window scrolls sideways. Text too long for its column is +/// clipped. When a column's natural width or the window changes, the columns go back to a new fit, +/// dropping any dragged widths. +fn fitted_table<'a>(ui: &'a mut egui::Ui, id: &str, natural: &[f32], grow: &[f32]) -> egui_extras::TableBuilder<'a> { + // Every cell is followed by the item gap, and the vertical scrollbar keeps its margins. + let s = ui.spacing(); + let gaps = s.item_spacing.x * natural.len() as f32; + let bar = s.scroll.bar_width + s.scroll.bar_inner_margin + s.scroll.bar_outer_margin; + let widths = fit_widths(natural, grow, (ui.available_width() - gaps - bar).max(0.0)); + // The table keeps its own column widths, so a change in what they were fitted to has to clear + // them. A longer name can leave the fit itself unchanged, and scrolling can nudge the available + // width, so this compares the natural widths and the clip rect, which scrolling never moves. + let fit = egui::Id::unique(("credits_fit", id)); + let measured = (natural.to_vec(), ui.clip_rect().width()); + let refit = ui.data_mut(|d| d.get_temp::<(Vec, f32)>(fit)).as_ref() != Some(&measured); + ui.data_mut(|d| d.insert_temp(fit, measured)); + let mut t = + egui_extras::TableBuilder::new(ui).id_salt(id).striped(true).resizable(true).auto_shrink([false, false]).max_scroll_height(f32::INFINITY); + if refit { + t.reset(); + } + for w in widths { + t = t.column(egui_extras::Column::initial(w).at_least(MIN_COLUMN).clip(true)); + } + t +} + +/// Add a cell's widget right-aligned (counts, dates) or left-aligned (names), vertically centred. +fn aligned(ui: &mut egui::Ui, right: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + let layout = if right { egui::Layout::right_to_left(egui::Align::Center) } else { egui::Layout::left_to_right(egui::Align::Center) }; + ui.with_layout(layout, add).inner +} + +fn row_height(ui: &egui::Ui) -> f32 { + ui.text_style_height(&egui::TextStyle::Body) + 6.0 +} + +/// One contributor's table cells after the name, in `SortKey::ALL` order. +fn cells(c: &Contributor) -> [String; 9] { + [ + group(c.prs), + group(c.commits), + group(c.lines_added), + group(c.lines_deleted), + signed(c.lines_delta()), + group(c.binary_added), + group(c.binary_deleted), + day(c.first_commit).to_string(), + day(c.last_commit).to_string(), + ] +} + +/// A contributor-table header. The sorted column is highlighted; its direction shows on the +/// toolbar's sort-order button, so no arrow widens the column. +fn header_text(k: SortKey) -> RichText { + RichText::new(crate::i18n::tr(k.label().1)).strong() +} + +fn table(app: &mut LightcraftApp, ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) { + let h = row_height(ui); + let rows: Vec<[String; 9]> = list.iter().map(|c| cells(c)).collect(); + let widths: Vec = SortKey::ALL + .iter() + .enumerate() + .map(|(i, &k)| match i.checked_sub(1) { + None => natural(ui, header_text(k), list.iter().map(|c| c.name(v.names))), + Some(col) => natural(ui, header_text(k), rows.iter().filter_map(|r| r.get(col).cloned())), + }) + .collect(); + fitted_table(ui, "credits_table", &widths, &CONTRIBUTOR_GROW) + .header(h + 4.0, |mut header| { + for k in SortKey::ALL { + header.col(|ui| { + let r = aligned(ui, k != SortKey::Name, |ui| ui.selectable_label(v.key == k, header_text(k))) + .on_hover_text(crate::i18n::tr(k.label().0)); + + if r.clicked() { + if v.key == k { + v.ascending = !v.ascending; + } else { + v.key = k; + v.ascending = k.default_ascending(); + } + } + }); + } + }) + .body(|mut body| { + for (c, cells) in list.iter().zip(rows) { + body.row(h, |mut row| { + row.col(|ui| { + aligned(ui, false, |ui| name_link(app, ui, c, v.names)); + }); + for text in cells { + row.col(|ui| { + aligned(ui, true, |ui| ui.label(text)); + }); + } + }); + } + }); } /// About ▸ Models: AI models credited in Co-Authored-By trailers. @@ -337,22 +446,51 @@ pub fn models_ui(ui: &mut egui::Ui) { return; } let assisted: u64 = MODELS.iter().map(|m| m.commits).max().unwrap_or(0).max(1); + let h = row_height(ui); let list_h = crate::panels::dialogs::list_height(ui, LIST_HEIGHT); - egui::ScrollArea::both().id_salt("credits_models_scroll").max_height(list_h).auto_shrink([false, true]).show(ui, |ui| { - egui::Grid::new("credits_models").striped(true).num_columns(6).show(ui, |ui| { - for h in ["Company", "Model", "Version", "Commits", "% of all commits", "Lines +/−"] { - ui.label(RichText::new(crate::i18n::tr(h)).strong()); - } - ui.end_row(); - for m in MODELS { - ui.label(m.company); - ui.label(m.model); - ui.label(m.version); - ui.label(group(m.commits)); - ui.label(format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64)); - ui.label(format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted))); - ui.end_row(); - } + let titles = ["Company", "Model", "Version", "Commits", "% of all commits", "Lines +/−"]; + // Company, Model and Version read as text; the counts line up on the right. + let right = [false, false, false, true, true, true]; + let rows: Vec<[String; 6]> = MODELS + .iter() + .map(|m| { + [ + m.company.to_string(), + m.model.to_string(), + m.version.to_string(), + group(m.commits), + format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64), + format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted)), + ] + }) + .collect(); + let widths: Vec = titles + .iter() + .enumerate() + .map(|(i, title)| natural(ui, RichText::new(crate::i18n::tr(title)).strong(), rows.iter().filter_map(|r| r.get(i).cloned()))) + .collect(); + ui.allocate_ui(egui::vec2(ui.available_width(), list_h), |ui| { + ui.set_max_height(list_h); + egui::ScrollArea::horizontal().id_salt("credits_models_scroll").auto_shrink([false, false]).show(ui, |ui| { + fitted_table(ui, "credits_models", &widths, &MODEL_GROW) + .header(h + 4.0, |mut header| { + for (title, r) in titles.into_iter().zip(right) { + header.col(|ui| { + aligned(ui, r, |ui| ui.label(RichText::new(crate::i18n::tr(title)).strong())); + }); + } + }) + .body(|mut body| { + for cells in rows { + body.row(h, |mut row| { + for (text, r) in cells.into_iter().zip(right) { + row.col(|ui| { + aligned(ui, r, |ui| ui.label(text)); + }); + } + }); + } + }); }); }); } @@ -442,4 +580,131 @@ mod tests { assert_eq!(day("2026-10-07T18:45:23Z"), "2026-10-07"); assert_eq!(day(""), "—"); } + + #[test] + fn columns_fill_the_room_and_spare_width_goes_to_growing_columns() { + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 300.0), [200.0, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 2.0, 0.0], 230.0), [110.0, 60.0, 60.0]); + let w = fit_widths(&[123.0, 45.5, 67.25], &[1.0, 0.0, 2.0], 512.0); + assert!((w.iter().sum::() - 512.0).abs() < 0.01, "a fitted table neither scrolls nor leaves a gap: {w:?}"); + } + + #[test] + fn too_little_room_shrinks_only_growing_columns() { + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 150.0), [50.0, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 0.0), [MIN_COLUMN, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0], &[0.0, 0.0], 50.0), [100.0, 40.0]); + } + + #[test] + fn a_column_at_the_minimum_leaves_the_shortfall_to_the_others() { + let w = fit_widths(&[100.0, 300.0, 50.0], &[1.0, 1.0, 0.0], 140.0); + assert!((w.iter().sum::() - 140.0).abs() < 0.01, "the columns still fit the room: {w:?}"); + assert!(w.iter().all(|c| *c >= MIN_COLUMN), "no column goes below the minimum: {w:?}"); + assert_eq!(fit_widths(&[100.0, 300.0, 50.0], &[1.0, 1.0, 0.0], 0.0), [MIN_COLUMN, MIN_COLUMN, 50.0]); + } + + const WINDOW: f32 = 640.5; + const NATURAL: [f32; 3] = [120.0, 80.0, 80.0]; + const GROW: [f32; 3] = [1.0, 0.0, 0.0]; + + /// One frame of a table long enough to scroll; the rects of its header cells. + fn table_frame(ctx: &egui::Context, width: f32, natural: &[f32], events: Vec) -> Vec { + scrolled_frame(ctx, width, natural, 0.0, events) + } + + /// [`table_frame`], scrolled `offset` points sideways. + fn scrolled_frame(ctx: &egui::Context, width: f32, natural: &[f32], offset: f32, events: Vec) -> Vec { + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 300.0))); + let raw = egui::RawInput { screen_rect, events, ..Default::default() }; + let mut cells = Vec::new(); + let out = ctx.run_ui(raw, |ui| { + cells.clear(); + egui::ScrollArea::horizontal().auto_shrink([false, false]).horizontal_scroll_offset(offset).show(ui, |ui| { + fitted_table(ui, "test", natural, &GROW) + .header(20.0, |mut header| { + for _ in natural { + header.col(|ui| cells.push(ui.max_rect())); + } + }) + .body(|mut body| { + for _ in 0..40 { + body.row(20.0, |mut row| { + for _ in natural { + row.col(|ui| { + ui.label("x"); + }); + } + }); + } + }); + }); + }); + out.drop_without_applying_deltas(); + cells + } + + /// A new context with the table open and settled, and the rects of its header cells. + fn opened_table() -> (egui::Context, Vec) { + let ctx = egui::Context::default(); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let cells = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + (ctx, cells) + } + + /// Drags a column's right edge, which runs midway through the gap after `cell`, then lets go. + fn drag_edge(ctx: &egui::Context, cell: egui::Rect, by: f32) { + use egui::{Event, Modifiers, PointerButton}; + let start = egui::pos2(cell.right() + 4.0, cell.center().y); + let halfway = start + egui::vec2(by / 2.0, 0.0); + let end = start + egui::vec2(by, 0.0); + let moved = Event::PointerMoved; + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + for event in [moved(start), button(start, true), moved(halfway), moved(end), button(end, false)] { + table_frame(ctx, WINDOW, &NATURAL, vec![event]); + } + } + + #[test] + fn every_column_can_be_dragged_at_its_right_edge_and_stays_there() { + let (_, opened) = opened_table(); + for (dragged, cell) in opened.iter().enumerate() { + let (ctx, _) = opened_table(); + drag_edge(&ctx, *cell, -30.0); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let after = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + for (column, (was, now)) in opened.iter().zip(&after).enumerate() { + let want = if column == dragged { was.width() - 30.0 } else { was.width() }; + assert!((now.width() - want).abs() < 1.0, "dragging column {dragged}: column {column} is {now:?}, was {was:?}"); + } + } + } + + #[test] + fn a_changed_fit_replaces_the_column_widths() { + let (ctx, opened) = opened_table(); + drag_edge(&ctx, opened[0], -30.0); + let longer_name = table_frame(&ctx, WINDOW, &[200.0, 80.0, 80.0], Vec::new()); + assert!((longer_name[0].width() - opened[0].width()).abs() < 1.0, "a longer name drops a dragged width: {longer_name:?}"); + let wider = table_frame(&ctx, WINDOW, &[120.0, 200.0, 80.0], Vec::new()); + let widths: Vec = wider.iter().map(|c| c.width().round()).collect(); + assert!(widths.ends_with(&[200.0, 80.0]), "a longer cell widens its column: {widths:?}"); + assert!(wider[2].right() < WINDOW, "the table still fits the window: {wider:?}"); + let narrower = table_frame(&ctx, 400.0, &NATURAL, Vec::new()); + assert!(narrower[2].right() < 400.0, "a narrower window refits the table: {narrower:?}"); + } + + #[test] + fn scrolling_sideways_keeps_dragged_widths() { + let (ctx, opened) = opened_table(); + drag_edge(&ctx, opened[0], 100.0); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let dragged = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + assert!((dragged[0].width() - opened[0].width() - 100.0).abs() < 1.0, "the drag took: {dragged:?}"); + for offset in [13.3, 27.77, 41.1, 0.6] { + scrolled_frame(&ctx, WINDOW, &NATURAL, offset, Vec::new()); + let scrolled = scrolled_frame(&ctx, WINDOW, &NATURAL, offset, Vec::new()); + assert!((scrolled[0].width() - dragged[0].width()).abs() < 1.0, "scrolled {offset}: {scrolled:?}"); + } + } } diff --git a/crates/ui-egui/src/dialogs/import/body.rs b/crates/ui-egui/src/dialogs/import/body.rs index 0a4b9fb97f..61e0bfb1bd 100644 --- a/crates/ui-egui/src/dialogs/import/body.rs +++ b/crates/ui-egui/src/dialogs/import/body.rs @@ -450,7 +450,7 @@ fn candidate_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDial let s = ((img.width() - 8.0) / tw as f32).min((img.height() - 8.0) / th as f32); let fit = Rect::from_center_size(img.center(), vec2(tw as f32 * s, th as f32 * s)); let tint = if ok { Color32::WHITE } else { Color32::from_gray(110) }; - p.image(tex.tex.id(), fit, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), tint); + p.image(tex.id(), fit, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), tint); } let on = d.checked.get(i).copied().unwrap_or(false) && ok; if on { diff --git a/crates/ui-egui/src/dialogs/print_view.rs b/crates/ui-egui/src/dialogs/print_view.rs index c9af1d776d..3161aa96f7 100644 --- a/crates/ui-egui/src/dialogs/print_view.rs +++ b/crates/ui-egui/src/dialogs/print_view.rs @@ -883,7 +883,7 @@ fn paint_cell( let px = (shown.width().max(shown.height()) * 2.0).clamp(64.0, 1024.0) as usize; crate::panels::grid::request_thumb(app, id, px, 10); } - app.renderer.thumb(id).map(|tex| tex.tex.id()) + app.renderer.thumb(id).map(|tex| tex.id()) }); match tex { Some(id) => { diff --git a/crates/ui-egui/src/dialogs/settings/slide_layout.rs b/crates/ui-egui/src/dialogs/settings/slide_layout.rs index c78d3df4d9..d9595d2de9 100644 --- a/crates/ui-egui/src/dialogs/settings/slide_layout.rs +++ b/crates/ui-egui/src/dialogs/settings/slide_layout.rs @@ -258,7 +258,7 @@ pub fn preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, max_h: f3 return; }; let drawn = crate::panels::detail::fit_texture_rect(rect, tex.size); - p.image(tex.tex.id(), drawn, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), drawn, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); if s.show_guides { // the margins, as lines across the slide (where the image cell's edges are) let aspect = app.session.slide_photo_aspect(id).unwrap_or(1.5); @@ -302,7 +302,7 @@ fn title_preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, rect: R match app.renderer.textures.get(&Slot::SlidePreview).filter(|tex| tex.photo == lightcraft_catalog::PhotoId(0)) { Some(tex) => { let drawn = crate::panels::detail::fit_texture_rect(rect, tex.size); - p.image(tex.tex.id(), drawn, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), drawn, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } None => { let c = look.titles.screen(title).color; diff --git a/crates/ui-egui/src/find_similar.rs b/crates/ui-egui/src/find_similar.rs new file mode 100644 index 0000000000..d96424317c --- /dev/null +++ b/crates/ui-egui/src/find_similar.rs @@ -0,0 +1,110 @@ +//! Find Similar Photos in the app. The first search reads every photo of the library, which on the +//! UI thread left the window not responding for as long as that took: hours in a library of tens of +//! thousands of raws (issue #3468). The photos are read on a worker thread instead, under a row in +//! the activity stack that counts them and can stop. What was read before a stop is kept, so the +//! next search goes on from there. +//! +//! From a menu the command answers at once and says how it ended in a toast. A request from the +//! control channel (an agent, `mcp --connect`) gets the same `{photos}` as ever, when the search +//! ends; one that gave up waiting can ask again and is answered from what was read. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::Sender; + +use lightcraft_engine::cmd::similar; +use serde_json::{Value, json}; + +use crate::LightcraftApp; +use crate::control::{self, Outcome}; + +/// The activity stack's label (the menu item's name, already translated). +pub const LABEL: &str = "Find Similar Photos"; + +/// How a search ended. +enum End { + /// The command's answer. + Found(Value), + /// Nothing was asked of the view any more: why. + Dropped(&'static str), + Failed(String), +} + +/// Start a search for `p`: `end` runs on the UI thread when it is over. How many contents it has to +/// read, or why it can't start. +fn start(app: &mut LightcraftApp, p: &Value, end: impl FnOnce(&mut LightcraftApp, &egui::Context, End) + Send + 'static) -> Result { + similar::no_search_running(&app.session).map_err(|why| format!("library.findSimilar: {why}"))?; + let (search, reads) = similar::plan(&mut app.session, p).map_err(|e| e.to_string())?; + let count = reads.len(); + let library = app.session.library_generation(); + let cancel = Arc::new(AtomicBool::new(false)); + let (flag, stopped) = (cancel.clone(), cancel.clone()); + let work = move |task: lightcraft_engine::activity::TaskHandle| { + let total = count as u64; + task.progress(0, total); + lightcraft_engine::guard::catch(LABEL, || similar::measure(reads, &flag, &|done| task.progress(done as u64, total))) + }; + let done = move |app: &mut LightcraftApp, ctx: &egui::Context, found: Result, String>| { + let ended = match found { + _ if app.session.library_generation() != library => End::Dropped("another library was opened before the search ended"), + Err(e) => End::Failed(e), + Ok(found) => { + similar::keep(&mut app.session, found); + if stopped.load(Ordering::Relaxed) { + End::Dropped("the search was stopped") + } else { + match app.session.execute_fn("library.findSimilar", |s| similar::apply(s, &search)) { + Ok(answer) => End::Found(answer), + Err(e) => End::Failed(e.to_string()), + } + } + } + }; + end(app, ctx, ended); + }; + crate::tasks::spawn_tracked(app, LABEL, similar::KIND, cancel, work, done)?; + Ok(count) +} + +/// `library.findSimilar` from a menu: start reading → `{background: true, count}`. The grid shows +/// what it found, and a toast says how many. +pub fn command(app: &mut LightcraftApp, p: &Value) -> Result { + let count = start(app, p, |app, ctx, end| match end { + End::Found(answer) => { + let n = answer["photos"].as_array().map_or(0, Vec::len); + app.ui.view = crate::state::ViewMode::PhotoGrid; + app.toast(ctx, crate::i18n::tr_format!("{n} similar photo{} · View ▸ Clear Filters to see all", if n == 1 { "" } else { "s" }, n = n)); + } + // (whoever stopped it knows; a search of another library has nothing to say about this one) + End::Dropped(_) => {} + End::Failed(e) => app.toast(ctx, e), + })?; + Ok(json!({"background": true, "count": count})) +} + +/// `library.findSimilar` from the control channel: `reply` gets the command's answer when the search +/// ends, and the view stays where the agent left it. +pub fn ask(app: &mut LightcraftApp, p: &Value, reply: Sender) -> Outcome { + let started = start(app, p, move |_, _, end| { + let answer = match end { + End::Found(answer) => control::success(answer), + End::Dropped(why) => control::failure(format!("library.findSimilar: {why}")), + End::Failed(e) => control::failure(e), + }; + // (a caller that gave up has no one to send to; what was read stays known for its next request) + let _ = reply.send(answer); + }); + match started { + Ok(_) => Outcome::Later, + Err(e) => Outcome::Done(control::failure(e)), + } +} + +/// Another library was opened: stop a search of the one before, which has nothing left to find (it +/// could go on reading for hours). Its row goes when the photo being read is done. +pub fn library_changed(app: &LightcraftApp) { + for row in app.session.activity.list().into_iter().filter(|r| r.kind == similar::KIND) { + // (a row that has just ended can't be stopped: nothing to do) + let _ = app.session.activity.cancel(row.id); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5e794f105c..00311afd33 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -24,6 +24,7 @@ pub mod dialogs; pub mod docking; mod drop_overlay; pub mod export_task; +mod find_similar; mod focus_scan; mod frame_rate; pub mod headless; @@ -546,7 +547,7 @@ pub fn is_model_file(path: &str) -> bool { /// Files dropped on the window that are presets rather than photos. pub fn is_preset_file(path: &str) -> bool { let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); - ["lcpreset", "lrtemplate", "xmp", "zip", "cube", "lmp", "mplumpack", "lceffect"].contains(&ext.as_str()) + ["lcpreset", "lrtemplate", "xmp", "zip", "cube", "dcp", "lmp", "mplumpack", "lceffect"].contains(&ext.as_str()) } /// Splits dropped files into presets and everything else. An `.xmp` dropped next to a photo with the same diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index ec9835a39f..730bde3df4 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -158,6 +158,10 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option paths, Err(answer) => return answer, }; + // .cube LUTs (and those inside zips / folders) become profiles, .dcp files camera profiles let lut_paths: Vec<&String> = paths .iter() .filter(|p| { let l = p.to_ascii_lowercase(); - l.ends_with(".cube") || l.ends_with(".zip") || std::path::Path::new(p.as_str()).is_dir() + l.ends_with(".cube") || l.ends_with(".dcp") || l.ends_with(".zip") || std::path::Path::new(p.as_str()).is_dir() }) .collect(); let mut news = ImportNews::default(); let profiles = if lut_paths.is_empty() { Value::Null } else { import_luts(app, &lut_paths, &mut news) }; - let preset_paths: Vec<&String> = paths.iter().filter(|p| !p.to_ascii_lowercase().ends_with(".cube")).collect(); + // (.dcp camera profiles went to profile.import above) + let preset_paths: Vec<&String> = paths + .iter() + .filter(|p| { + let l = p.to_ascii_lowercase(); + !l.ends_with(".cube") && !l.ends_with(".dcp") + }) + .collect(); let r = import_preset_files(app, &preset_paths, &mut news); toast_import_news(app, ctx, &news); r.map(|mut v| { diff --git a/crates/ui-egui/src/panels/compare.rs b/crates/ui-egui/src/panels/compare.rs index b7034f3a6d..d3f11733b8 100644 --- a/crates/ui-egui/src/panels/compare.rs +++ b/crates/ui-egui/src/panels/compare.rs @@ -277,14 +277,14 @@ fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slo if let Some(tex) = app.renderer.textures.get(&slot).filter(|x| x.photo == id) { let texture_aspect = tex.size[0].max(1) as f32 / tex.size[1].max(1) as f32; display = super::detail::fit_rect(img_area, texture_aspect, zoom, native, ppp, app.ui.pan); - p.image(tex.tex.id(), display, uv, Color32::WHITE); + p.image(tex.id(), display, uv, Color32::WHITE); if let Some(i) = window { draw_window(&p, app, i, id, photo.develop.hash64(), display); } } else if let Some(tex) = app.renderer.textures.get(&Slot::Thumb(id)) { let texture_aspect = tex.size[0].max(1) as f32 / tex.size[1].max(1) as f32; display = super::detail::fit_rect(img_area, texture_aspect, zoom, native, ppp, app.ui.pan); - p.image(tex.tex.id(), display, uv, Color32::WHITE); + p.image(tex.id(), display, uv, Color32::WHITE); } else { p.rect_filled(img.intersect(img_area), 0.0, t.skeleton); } @@ -452,7 +452,7 @@ fn draw_window(p: &egui::Painter, app: &LightcraftApp, pane: u8, id: PhotoId, lo let (fw, fh) = (tile.full.0.max(1) as f32, tile.full.1.max(1) as f32); let at = display.min + vec2(tile.window.x as f32 / fw * display.width(), tile.window.y as f32 / fh * display.height()); let dst = Rect::from_min_size(at, vec2(tile.window.w as f32 / fw * display.width(), tile.window.h as f32 / fh * display.height())); - p.image(tex.tex.id(), dst, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), dst, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } /// Per frame, before the central view is shown: Compare and Reference keep two photos' originals @@ -581,8 +581,9 @@ pub fn show_survey(app: &mut LightcraftApp, ui: &mut egui::Ui) { let _ = app.run("library.select", json!({"ids": [id.0]})); app.ui.view = ViewMode::Detail; } - // remove from the survey (deselect) on hover - if resp.hovered() && photos.len() > 1 { + // remove from the survey (deselect) on hover; the × stays while the pointer is on it, where + // the tile has lost its hover to the × (tied to `hovered()`, it vanished before a click landed) + if resp.contains_pointer() && photos.len() > 1 { let xr = Rect::from_min_size(pos2(img.right() - 26.0, img.top() + 6.0), vec2(20.0, 20.0)); let xresp = ui.interact(xr, egui::Id::unique(("survey-x", id.0)), Sense::click()).on_hover_text(crate::i18n::tr("Remove from survey")); crate::widgets::announce(&xresp, crate::i18n::tr("Remove from survey")); diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 116c35b08e..3e321304d2 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -442,7 +442,7 @@ fn draw_wipe_before(app: &LightcraftApp, p: &egui::Painter, id: PhotoId, img_rec let before_rect = fit_texture_rect(img_rect, tex.size); let u = ((line.x - before_rect.left()) / before_rect.width().max(1.0)).clamp(0.0, 1.0); let left = Rect::from_min_max(before_rect.min, pos2(before_rect.left() + u * before_rect.width(), before_rect.bottom())); - p.image(tex.tex.id(), left, Rect::from_min_max(pos2(0.0, 0.0), pos2(u, 1.0)), Color32::WHITE); + p.image(tex.id(), left, Rect::from_min_max(pos2(0.0, 0.0), pos2(u, 1.0)), Color32::WHITE); } if app.ui.before_after == BeforeAfter::SplitTopBottom && let Some(tex) = app.renderer.textures.get(&Slot::Before).filter(|t| t.photo == id) @@ -450,7 +450,7 @@ fn draw_wipe_before(app: &LightcraftApp, p: &egui::Painter, id: PhotoId, img_rec let before_rect = fit_texture_rect(img_rect, tex.size); let v = ((line.y - before_rect.top()) / before_rect.height().max(1.0)).clamp(0.0, 1.0); let top = Rect::from_min_max(before_rect.min, pos2(before_rect.right(), before_rect.top() + v * before_rect.height())); - p.image(tex.tex.id(), top, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, v)), Color32::WHITE); + p.image(tex.id(), top, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, v)), Color32::WHITE); } } @@ -795,14 +795,14 @@ fn draw_slot(app: &LightcraftApp, p: &egui::Painter, id: PhotoId, ppp: f32, slot return "none"; }; let image_rect = snap_fit_rect(fit_texture_rect(r, tex.size), tex.size, ppp); - p.with_clip_rect(clip).image(tex.tex.id(), image_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.with_clip_rect(clip).image(tex.id(), image_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); what } /// The hovered look's render over the photo, with its label. fn draw_hover(p: &egui::Painter, t: &Tokens, tex: &crate::render::Tex, label: &str, [img_rect, canvas]: [Rect; 2], badge_top_inset: f32) { let hover_rect = fit_texture_rect(img_rect, tex.size); - p.image(tex.tex.id(), hover_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), hover_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); let g = p.layout_no_wrap(label.to_string(), t.font(12.0), Color32::WHITE); let bg = label_badge_rect(hover_rect, canvas, g.size(), badge_top_inset); paint_badge(p, bg, g); diff --git a/crates/ui-egui/src/panels/detail/filmstrip.rs b/crates/ui-egui/src/panels/detail/filmstrip.rs index 52e9c8b25a..268d021b20 100644 --- a/crates/ui-egui/src/panels/detail/filmstrip.rs +++ b/crates/ui-egui/src/panels/detail/filmstrip.rs @@ -17,7 +17,7 @@ pub(super) fn navigator(app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Rect let p = ui.painter_at(canvas); p.rect_filled(frame.expand(5.0), 4.0, Color32::from_black_alpha(190)); match tex { - Some(t) => p.image(t.tex.id(), frame, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE), + Some(t) => p.image(t.id(), frame, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE), None => p.rect_filled(frame, 0.0, Tokens::get(ui.ctx()).skeleton), }; // the visible part of the photo, in normalized image coordinates @@ -131,7 +131,7 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { let [tw, th] = tex.size; let s = (img_area.width() / tw as f32).min(img_area.height() / th as f32); let fr = Rect::from_center_size(img_area.center(), vec2(tw as f32 * s, th as f32 * s)); - p.image(tex.tex.id(), fr, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), fr, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); crate::panels::grid::selection_ring(p, &t, fr, state); if app.ui.settings.film_badges && let Some(ph) = app.session.catalog.photo(*id) diff --git a/crates/ui-egui/src/panels/detail/window.rs b/crates/ui-egui/src/panels/detail/window.rs index c9b78b5429..3351fab289 100644 --- a/crates/ui-egui/src/panels/detail/window.rs +++ b/crates/ui-egui/src/panels/detail/window.rs @@ -118,5 +118,5 @@ pub(super) fn draw_window(p: &egui::Painter, app: &LightcraftApp, c: &WindowCtx, let (fw, fh) = (tile.full.0 as f32, tile.full.1 as f32); let at = v.img.min + vec2(tile.window.x as f32 / fw * v.img.width(), tile.window.y as f32 / fh * v.img.height()); let dst = Rect::from_min_size(at, vec2(tile.window.w as f32 / fw * v.img.width(), tile.window.h as f32 / fh * v.img.height())); - p.image(tex.tex.id(), dst, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), dst, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index 7ede7acd14..632bad5cbb 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -19,6 +19,7 @@ use crate::widgets::{BAND_COLORS, SliderOut, divider, flyout_row, hex, register, mod curve; mod grading; +mod hdr_flow; mod histogram; mod mixer; mod sliders; @@ -152,7 +153,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { divider(ui); section(app, ui, &d, "light", "Light", |app, ui, d| { - hdr_row(app, ui, d); + hdr_row(app, ui, d, id); for c in ["light.exposure", "light.contrast", "light.highlights", "light.shadows", "light.whites", "light.blacks"] { control(app, ui, d, c, true); } diff --git a/crates/ui-egui/src/panels/edit/hdr_flow.rs b/crates/ui-egui/src/panels/edit/hdr_flow.rs new file mode 100644 index 0000000000..a9ddb7233a --- /dev/null +++ b/crates/ui-egui/src/panels/edit/hdr_flow.rs @@ -0,0 +1,319 @@ +//! The Edit panel's flow between SDR and HDR: pressing HDR moves the histogram and the HDR settings +//! to their new layout instead of swapping it in one frame. + +use lightcraft_raster::HdrBins; + +use super::{Color32, Histogram, Mesh, PhotoId, Pos2, Rect, Stroke, Vertex, hex, pos2, vec2}; + +/// How long the histogram and the HDR settings take to flow between their SDR and HDR layouts. +const FLOW_SECS: f32 = 0.45; + +pub(super) fn hdr_histogram_key(id: PhotoId) -> egui::Id { + egui::Id::unique(("hdrHistogram", id)) +} + +/// The photo's last SDR histogram, kept to draw the way back from the HDR layout and into it. +pub(super) fn sdr_histogram_key(id: PhotoId) -> egui::Id { + egui::Id::unique(("sdrHistogram", id)) +} + +/// The histogram on its way between its layouts this frame. Entering HDR squeezes the SDR curve into +/// the HDR histogram's SDR section while the HDR section opens beside it (and the legend row slides +/// open under the plot); leaving stretches it back. The last histogram of each kind is kept so both +/// ends can be drawn on the way. +pub(super) struct LayoutFlow { + /// 0 (the SDR layout) to 1 (the HDR layout), eased. + pub morph: f32, + bins: Option, + sdr: Option, + hdr: Option, +} + +impl LayoutFlow { + /// The flow towards the layout of `hist`, the histogram shown this frame. + pub fn of(ctx: &egui::Context, id: PhotoId, hist: Option<&Histogram>) -> Self { + let showing_hdr = hist.is_some_and(|h| h.hdr.is_some()); + let morph = + egui::emath::easing::cubic_in_out(ctx.animate_bool_with_time(egui::Id::unique(("histogramHdrLayout", id)), showing_hdr, FLOW_SECS)); + let hdr = if showing_hdr { + hist.cloned() + } else if morph > 0.0 { + ctx.data(|d| d.get_temp::(hdr_histogram_key(id))) + } else { + None + }; + let sdr = if !showing_hdr { + hist.cloned() + } else if morph < 1.0 { + ctx.data(|d| d.get_temp::(sdr_histogram_key(id))) + } else { + None + }; + let bins = hdr.as_ref().and_then(|h| h.hdr); + Self { morph: if bins.is_some() { morph } else { 0.0 }, bins, sdr, hdr } + } + + /// The HDR section's bins, while any of it is showing. + pub fn hdr_bins(&self) -> Option { + self.bins.filter(|_| self.morph > 0.0) + } + + /// The histogram being left, drawn alone mid-way when there is none of the new kind yet. + pub fn leaving(&self) -> Option { + self.hdr.clone().filter(|_| self.morph > 0.0) + } + + /// The first HDR bin: where the HDR histogram's SDR section ends. + fn from(&self) -> f32 { + self.bins.map_or(255.0, |b| b.from as f32) + } + + /// SDR white across `plot`: its right edge in SDR, the HDR layout's split in HDR. + pub fn sdr_white_x(&self, plot: Rect) -> f32 { + plot.left() + plot.width() * sdr_white_at(self.from(), self.morph) + } + + /// The curve, one through both layouts: the SDR section's heights morph from the SDR histogram's + /// to the HDR histogram's SDR bins as it narrows to SDR white, and the HDR bins fill the rest. + /// `shown` decides greyscale, whose three channels coincide: one neutral line is drawn. + pub fn paint_curve(&self, p: &egui::Painter, plot: Rect, shown: &Histogram) { + let sdr = self.sdr.as_ref().map(histogram_heights); + let hdr = self.hdr.as_ref().filter(|_| self.bins.is_some()).map(histogram_heights); + let pts = morph_curve(sdr.as_ref(), hdr.as_ref(), self.from(), self.morph); + let to = |x: f32, v: f32| pos2(plot.left() + plot.width() * x, plot.bottom() - plot.height() * v); + // luminance fill + let mut mesh = Mesh::default(); + for (i, (x, hs)) in pts.iter().enumerate() { + let top = to(*x, hs[0]); + mesh.vertices.push(Vertex { pos: top, uv: Pos2::ZERO, color: Color32::from_gray(120).gamma_multiply(0.35) }); + mesh.vertices.push(Vertex { pos: pos2(top.x, plot.bottom()), uv: Pos2::ZERO, color: Color32::from_gray(120).gamma_multiply(0.35) }); + if i > 0 { + let k = (i as u32) * 2; + mesh.indices.extend([k - 2, k - 1, k, k - 1, k + 1, k]); + } + } + p.add(mesh); + let line = |j: usize, c: Color32| egui::Shape::line(pts.iter().map(|(x, hs)| to(*x, hs[j])).collect(), Stroke::new(1.5, c)); + if is_greyscale(shown) { + p.add(line(2, Color32::from_gray(200))); + } else { + for (j, c) in [(1, hex("#df3939")), (2, hex("#44b072")), (3, hex("#3b6fe0"))] { + p.add(line(j, c)); + } + } + } +} + +/// SDR white across the plot (0..1), `morph` of the way to the HDR layout where it sits at bin `from`. +fn sdr_white_at(from: f32, morph: f32) -> f32 { + 1.0 + (from / 255.0 - 1.0) * morph +} + +/// A histogram's display heights per bin for luma, R, G and B: smoothed over 5 bins, then +/// square-root scaled against the R/G/B peak (the end bins left out) and capped at 1. +fn histogram_heights(h: &Histogram) -> [Vec; 4] { + let smooth = |v: &[u32]| -> Vec { + (0..256) + .map(|i: usize| { + let (a, b) = (i.saturating_sub(2), (i + 3).min(v.len())); + let w = v.get(a..b).unwrap_or_default(); + w.iter().map(|x| *x as f32).sum::() / w.len().max(1) as f32 + }) + .collect() + }; + let [l, r, g, b] = [smooth(&h.luma), smooth(&h.r), smooth(&h.g), smooth(&h.b)]; + let peak = [&r, &g, &b].iter().flat_map(|v| v.iter().skip(2).take(252)).fold(1.0f32, |a, b| a.max(*b)); + [l, r, g, b].map(|v| v.into_iter().map(|x| (x / peak).sqrt().min(1.0)).collect()) +} + +/// `v` at fractional bin `x`, linearly interpolated (clamped to its ends). +fn sample(v: &[f32], x: f32) -> f32 { + let x = x.clamp(0.0, v.len().saturating_sub(1) as f32); + let i = x.floor() as usize; + let (a, b) = (v.get(i).copied().unwrap_or(0.0), v.get(i + 1).or(v.get(i)).copied().unwrap_or(0.0)); + a + (b - a) * (x - i as f32) +} + +/// A greyscale image's histogram: its three channels coincide. +fn is_greyscale(h: &Histogram) -> bool { + let spread: f32 = h.r.iter().zip(&h.g).zip(&h.b).map(|((r, g), b)| (*r as f32 - *g as f32).abs() + (*g as f32 - *b as f32).abs()).sum(); + spread / (h.g.iter().map(|x| *x as f32).sum::().max(1.0)) < 0.02 +} + +/// The histogram curve `morph` of the way from the SDR layout (0) to the HDR one (1), as +/// (x across the plot 0..1, heights for luma, R, G, B). Left of SDR white ([`sdr_white_at`]), the SDR +/// histogram's heights morph into the HDR histogram's SDR bins (`0..from`); right of it, the HDR +/// bins fill what has opened. Either histogram may be missing: the other is drawn alone. +fn morph_curve(sdr: Option<&[Vec; 4]>, hdr: Option<&[Vec; 4]>, from: f32, morph: f32) -> Vec<(f32, [f32; 4])> { + let x0 = sdr_white_at(from, morph); + let mut pts: Vec<(f32, [f32; 4])> = (0..=255) + .map(|k| { + let u = k as f32 / 255.0; + let hs = std::array::from_fn(|j| match (sdr, hdr) { + (Some(s), Some(c)) => { + let (a, z) = (sample(&s[j], u * 255.0), sample(&c[j], u * from)); + a + (z - a) * morph + } + (Some(s), None) => sample(&s[j], u * 255.0), + (None, Some(c)) => sample(&c[j], u * from), + (None, None) => 0.0, + }); + (x0 * u, hs) + }) + .collect(); + if let Some(c) = hdr.filter(|_| morph > 0.0) { + let n = (255.0 - from).max(1.0) as usize; + pts.extend((1..=n).map(|k| { + let u = k as f32 / n as f32; + (x0 + (1.0 - x0) * u, std::array::from_fn(|j| sample(&c[j], from + u * (255.0 - from)))) + })); + } + pts +} + +/// `body` as a drawer sliding open (`open`) or shut over [`FLOW_SECS`], eased like the histogram: its +/// height grows from 0 to its full height, the rows below move with its edge, and the content slides +/// down from under the row above (clipped there: nothing past the edge is drawn or clickable). Fully +/// shut, `body` doesn't run. +pub(super) fn drawer(ui: &mut egui::Ui, id: egui::Id, open: bool, body: impl FnOnce(&mut egui::Ui)) { + let t = egui::emath::easing::cubic_in_out(ui.ctx().animate_bool_with_time(id, open, FLOW_SECS)); + if t <= 0.0 { + return; + } + // the height measured last frame (0 before the first: that frame draws nothing and measures) + let full = ui.ctx().data(|d| d.get_temp::(id)).unwrap_or(0.0); + let avail = ui.available_rect_before_wrap(); + let top = avail.top(); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(avail.translate(vec2(0.0, -full * (1.0 - t)))).layout(*ui.layout())); + if t < 1.0 { + child.shrink_clip_rect(Rect::from_min_max(pos2(avail.left(), top), pos2(avail.right(), top + full * t))); + } + body(&mut child); + let measured = child.min_rect().height(); + ui.ctx().data_mut(|d| d.insert_temp(id, measured)); + ui.advance_cursor_after_rect(Rect::from_min_size(pos2(avail.left(), top), vec2(child.min_rect().width(), measured * t))); + // the spacing after it grows with it too, so nothing below jumps when it starts or ends + ui.add_space(-ui.spacing().item_spacing.y * (1.0 - t)); +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::Sense; + + /// The whole panel, frame by frame: the HDR button's layout change moves the histogram's height + /// and the sliders below in small steps, both ways, and ends at the same layout it left. + #[test] + fn pressing_hdr_moves_the_panel_instead_of_swapping_its_layout() { + use crate::headless::Headless; + use crate::{LightcraftApp, Services}; + use serde_json::json; + use std::time::{Duration, Instant}; + + let widget = |h: &Headless, id: &str| h.app.widgets.iter().rev().find(|(w, _)| w == id).map(|(_, r)| *r); + // (the histogram's height, the Exposure slider's top) at each frame until both reach `end` + let run = |h: &mut Headless, on: bool, end: Option| { + h.app.run("develop.hdr", json!({"enabled": on})).expect("develop.hdr"); + let (t0, mut trail) = (Instant::now(), Vec::new()); + let mut still = 0; + while t0.elapsed() < Duration::from_secs(120) && still < 60 { + h.step(); + std::thread::sleep(Duration::from_millis(1)); + let at = |id| widget(h, id).unwrap_or_else(|| panic!("no widget {id}")); + let now = (at("histogram").height(), at("slider:light.exposure").top()); + still = if trail.last() == Some(&now) && end.is_none_or(|e| now.0 == e) { still + 1 } else { 0 }; + trail.push(now); + } + trail + }; + let moved = |v: &[f32]| -> (usize, f32) { + let (lo, hi) = (v.iter().copied().fold(f32::MAX, f32::min), v.iter().copied().fold(f32::MIN, f32::max)); + let steps = v.iter().filter(|x| **x > lo && **x < hi).count(); + (steps, v.windows(2).map(|w| (w[1] - w[0]).abs()).fold(0.0, f32::max) / (hi - lo).max(1.0)) + }; + + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1400.0, 1000.0], 1.0); + let r = h.request("ui.set", json!({"view": "detail", "right": "edit", "openSections": ["light"]}), Duration::from_secs(20)); + assert_eq!(r["ok"], true, "{r}"); + h.settle(Duration::from_secs(120)); + let (sdr_h, sdr_y) = (widget(&h, "histogram").expect("histogram").height(), widget(&h, "slider:light.exposure").expect("exposure").top()); + + let on = run(&mut h, true, Some(sdr_h + 26.0)); + let off = run(&mut h, false, Some(sdr_h)); + for (name, trail) in [("on", &on), ("off", &off)] { + let heights: Vec = trail.iter().map(|t| t.0).collect(); + let tops: Vec = trail.iter().map(|t| t.1).collect(); + let (h_steps, h_jump) = moved(&heights); + let (y_steps, y_jump) = moved(&tops); + assert!(h_steps >= 4 && h_jump < 0.5, "{name}: the histogram's height jumped: {heights:?}"); + assert!(y_steps >= 4 && y_jump < 0.5, "{name}: the sliders jumped: {tops:?}"); + } + assert_eq!(on.last().map(|t| t.0), Some(sdr_h + 26.0), "the legend row opened"); + assert_eq!(off.last().copied(), Some((sdr_h, sdr_y)), "back where it started"); + } + + #[test] + fn the_hdr_settings_slide_open_and_shut() { + let ctx = egui::Context::default(); + let id = egui::Id::unique("drawer"); + // the height the drawer takes in the layout at each frame + let frame = |time: f64, open: bool| { + let mut height = 0.0; + let input = egui::RawInput { time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + let top = ui.cursor().top(); + drawer(ui, id, open, |ui| { + ui.allocate_exact_size(vec2(100.0, 40.0), Sense::hover()); + }); + height = ui.cursor().top() - top; + }); + out.textures_delta.clear(); + height + }; + // shut from the start: nothing; opened: it grows a little each frame up to its height + assert_eq!(frame(0.0, false), 0.0); + let opening: Vec = (1..=15).map(|k| frame(k as f64 * 0.05, true)).collect(); + assert!(opening.windows(2).all(|w| w[1] >= w[0]), "{opening:?}"); + assert!(opening.iter().filter(|h| **h > 0.0 && **h < 40.0).count() >= 4, "{opening:?}"); + assert!(opening[0] < 3.0, "no jump as it starts: {opening:?}"); + let spaced = 40.0 + ctx.global_style().spacing.item_spacing.y; + assert_eq!(opening.last(), Some(&spaced)); + // and shrinks back the same way + let closing: Vec = (16..=30).map(|k| frame(k as f64 * 0.05, false)).collect(); + assert!(closing.windows(2).all(|w| w[1] <= w[0]), "{closing:?}"); + assert!(closing.iter().filter(|h| **h > 0.0 && **h < 40.0).count() >= 4, "{closing:?}"); + assert_eq!(closing.last(), Some(&0.0)); + } + + #[test] + fn the_histogram_flows_between_its_sdr_and_hdr_layouts() { + let flat = |v: f32| -> [Vec; 4] { std::array::from_fn(|_| vec![v; 256]) }; + let (sdr, hdr) = (flat(0.2), flat(0.6)); + let from = 128.0; + let x_of = |pts: &[(f32, [f32; 4])]| pts.iter().map(|p| p.0).collect::>(); + // SDR: the SDR histogram across the whole plot, no HDR section + let pts = morph_curve(Some(&sdr), Some(&hdr), from, 0.0); + assert_eq!(pts.len(), 256); + assert!(pts.iter().all(|p| (p.1[0] - 0.2).abs() < 1e-6)); + assert_eq!(pts.last().map(|p| p.0), Some(1.0)); + // half way: the SDR section squeezed half way to SDR white, its heights half morphed, + // the HDR section opened beside it, joined without a gap + let pts = morph_curve(Some(&sdr), Some(&hdr), from, 0.5); + let x0 = sdr_white_at(from, 0.5); + assert!((pts[255].0 - x0).abs() < 1e-6); + assert!((pts[100].1[2] - 0.4).abs() < 1e-6); + assert!((pts[256].1[2] - 0.6).abs() < 1e-6 && pts[256].0 > x0); + let xs = x_of(&pts); + assert!(xs.windows(2).all(|w| w[1] > w[0] && w[1] - w[0] < 0.02), "one continuous curve"); + assert_eq!(xs.last(), Some(&1.0)); + // HDR: the HDR histogram alone, SDR white at its bin + let pts = morph_curve(Some(&sdr), Some(&hdr), from, 1.0); + assert!((pts[255].0 - from / 255.0).abs() < 1e-6); + assert!(pts.iter().all(|p| (p.1[0] - 0.6).abs() < 1e-6)); + // a missing end draws the other alone + assert!(morph_curve(None, Some(&hdr), from, 0.3).iter().all(|p| (p.1[1] - 0.6).abs() < 1e-6)); + assert_eq!(morph_curve(Some(&sdr), None, from, 0.0).len(), 256); + assert_eq!((sample(&[0.0, 1.0], 0.25), sample(&[0.0, 1.0], 9.0), sample(&[], 1.0)), (0.25, 1.0, 0.0)); + } +} diff --git a/crates/ui-egui/src/panels/edit/histogram.rs b/crates/ui-egui/src/panels/edit/histogram.rs index df21b1d798..875053ce8f 100644 --- a/crates/ui-egui/src/panels/edit/histogram.rs +++ b/crates/ui-egui/src/panels/edit/histogram.rs @@ -1,8 +1,9 @@ +use super::hdr_flow::{LayoutFlow, hdr_histogram_key, sdr_histogram_key}; #[cfg(test)] use super::sliders::reset_tip; use super::{ - Align2, Color32, Histogram, Icon, LightcraftApp, Mesh, PhotoId, Pos2, Rect, RichText, RightPanel, Sense, Slot, Stroke, Tokens, Vertex, divider, - hex, json, paint, pos2, register, vec2, + Align2, Color32, Histogram, Icon, LightcraftApp, PhotoId, Rect, RichText, RightPanel, Sense, Slot, Stroke, Tokens, divider, json, paint, pos2, + register, vec2, }; // ------------------------------------------------------------------------------ histogram @@ -20,16 +21,21 @@ pub(super) fn preview_histogram(app: &LightcraftApp, id: PhotoId) -> Option) -> Option { - let key = egui::Id::unique(("hdrHistogram", id)); + let (hdr_key, sdr_key) = (hdr_histogram_key(id), sdr_histogram_key(id)); match hist { Some(h) if h.hdr.is_some() => { - ctx.data_mut(|d| d.insert_temp(key, h.clone())); - Some(h) + ctx.data_mut(|d| d.insert_temp(hdr_key, h.clone())); + if hdr_edit { Some(h) } else { ctx.data(|d| d.get_temp::(sdr_key)) } } - h if hdr_edit => ctx.data(|d| d.get_temp::(key)).or(h), - h => h, + Some(h) => { + ctx.data_mut(|d| d.insert_temp(sdr_key, h.clone())); + if hdr_edit { ctx.data(|d| d.get_temp::(hdr_key)).or(Some(h)) } else { Some(h) } + } + None if hdr_edit => ctx.data(|d| d.get_temp::(hdr_key)), + None => None, } } @@ -62,10 +68,12 @@ pub(crate) fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) // rendered it) let hist = live.or_else(|| preview_histogram(app, id)); let hist = steady_hdr_histogram(ui.ctx(), id, hdr_edit, hist); + // the SDR ⇄ HDR layout change flows instead of cutting + let flow = LayoutFlow::of(ui.ctx(), id, hist.as_ref()); // an HDR edit's histogram (`pipeline::hdr_histogram`) gets a colour bar and an SDR / HDR label // row under the plot - let hdr = hist.as_ref().and_then(|h| h.hdr); - let legend = if hdr.is_some() { 26.0 } else { 0.0 }; + let hdr = flow.hdr_bins(); + let legend = 26.0 * flow.morph; let (r, resp) = ui.allocate_exact_size(vec2(w, 118.0 + legend), Sense::click_and_drag()); crate::widgets::announce(&resp, crate::i18n::tr("Histogram")); register(ui, "histogram", r); @@ -79,10 +87,11 @@ pub(crate) fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) if let Some(a) = &zone { crate::panels::histogram::paint_zone(p, plot, a, &t); } + let x0 = flow.sdr_white_x(plot); if let Some(b) = hdr { // white for SDR, then one band per stop above SDR white: white too, or (Visualize HDR - // range on) in its colours - let x0 = plot.left() + plot.width() * b.from as f32 / 255.0; + // range on) in its colours; the row is revealed as it opens + let p = &p.with_clip_rect(Rect::from_min_max(pos2(r.left(), plot.bottom()), pos2(r.right(), plot.bottom() + legend))); let bar = |a: f32, z: f32, c: Color32| p.rect_filled(Rect::from_min_max(pos2(a, plot.bottom() + 2.0), pos2(z, plot.bottom() + 7.0)), 0.0, c); let white = Color32::from_rgb(228, 228, 230); bar(plot.left(), x0 - 1.0, white); @@ -104,18 +113,10 @@ pub(crate) fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) )); } let clipping = hist.as_ref().map(|h| h.clipping()); - if let Some(h) = hist { - let smooth = |v: &[u32]| -> Vec { - (0..256) - .map(|i| { - let (a, b) = (i.max(2) - 2, (i + 3).min(256)); - v[a..b].iter().map(|x| *x as f32).sum::() / (b - a) as f32 - }) - .collect() - }; - // HDR: SDR on the left half, a solid line at SDR white and dashed ones between the stops - if let Some(b) = h.hdr { - let x0 = plot.left() + plot.width() * b.from as f32 / 255.0; + // mid-way with no histogram of the new kind yet, the one being left is drawn alone + if let Some(h) = hist.or_else(|| flow.leaving()) { + // HDR: SDR on the left, a solid line at SDR white and dashed ones between the stops + if let Some(b) = hdr { let stops = b.stops.round().max(1.0) as usize; for k in 1..stops { let x = x0 + (plot.right() - x0) * k as f32 / stops as f32; @@ -134,34 +135,7 @@ pub(crate) fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) p.line_segment([pos2(x, plot.top()), pos2(x, plot.bottom())], Stroke::new(1.0, Color32::from_rgb(230, 150, 60))); } } - let chans = [(smooth(&h.r), hex("#df3939")), (smooth(&h.g), hex("#44b072")), (smooth(&h.b), hex("#3b6fe0"))]; - let peak = chans.iter().flat_map(|(v, _)| v.iter().skip(2).take(252)).fold(1.0f32, |a, b| a.max(*b)); - let to = |i: usize, v: f32| pos2(plot.left() + plot.width() * i as f32 / 255.0, plot.bottom() - plot.height() * (v / peak).sqrt().min(1.0)); - // luminance fill - let lum = smooth(&h.luma); - let mut mesh = Mesh::default(); - for i in 0..256 { - let top = to(i, lum[i]); - mesh.vertices.push(Vertex { pos: top, uv: Pos2::ZERO, color: Color32::from_gray(120).gamma_multiply(0.35) }); - mesh.vertices.push(Vertex { pos: pos2(top.x, plot.bottom()), uv: Pos2::ZERO, color: Color32::from_gray(120).gamma_multiply(0.35) }); - if i > 0 { - let k = (i as u32) * 2; - mesh.indices.extend([k - 2, k - 1, k, k - 1, k + 1, k]); - } - } - p.add(mesh); - // greyscale images: the three channels coincide — draw one neutral line - let spread: f32 = (0..256).map(|i| (chans[0].0[i] - chans[1].0[i]).abs() + (chans[1].0[i] - chans[2].0[i]).abs()).sum(); - let total: f32 = chans[1].0.iter().sum::().max(1.0); - if spread / total < 0.02 { - let pts: Vec = (0..256).map(|i| to(i, chans[1].0[i])).collect(); - p.add(egui::Shape::line(pts, Stroke::new(1.5, Color32::from_gray(200)))); - } else { - for (v, c) in &chans { - let pts: Vec = (0..256).map(|i| to(i, v[i])).collect(); - p.add(egui::Shape::line(pts, Stroke::new(1.5, *c))); - } - } + flow.paint_curve(p, plot, &h); } let mut clicked = resp.clicked(); // both buttons keep clear of the panel's right edge, where its floating scroll bar widens when @@ -363,6 +337,10 @@ mod tests { assert_eq!(steady_hdr_histogram(&ctx, id, true, Some(sdr.clone())), Some(hdr(4.0))); // HDR turned off: the SDR histogram at once; other photos keep their own assert_eq!(steady_hdr_histogram(&ctx, id, false, Some(sdr.clone())), Some(sdr.clone())); + // an SDR edit never shows an HDR histogram (a stale thumbnail's): its last SDR one instead, + // or none yet + assert_eq!(steady_hdr_histogram(&ctx, id, false, Some(hdr(4.0))), Some(sdr.clone())); + assert_eq!(steady_hdr_histogram(&ctx, PhotoId(9), false, Some(hdr(4.0))), None); assert_eq!(steady_hdr_histogram(&ctx, PhotoId(8), true, Some(sdr.clone())), Some(sdr)); } diff --git a/crates/ui-egui/src/panels/edit/sliders.rs b/crates/ui-egui/src/panels/edit/sliders.rs index 78a402087e..2a6a3a13eb 100644 --- a/crates/ui-egui/src/panels/edit/sliders.rs +++ b/crates/ui-egui/src/panels/edit/sliders.rs @@ -116,17 +116,21 @@ fn profile_menu_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSett crate::menu_level::set_anchor(ui.ctx(), 2, r.response.rect); } } - // imported LUT profile groups - let mut lut_groups: Vec = app.session.lut_profiles.iter().map(|p| p.group.clone()).collect(); - lut_groups.sort_unstable(); - lut_groups.dedup(); + // imported profile groups: LUT folders, then camera profiles + let imported = app.session.imported_profiles(); + let mut lut_groups: Vec = Vec::new(); + for (_, _, g) in &imported { + if !lut_groups.contains(g) { + lut_groups.push(g.clone()); + } + } for g in &lut_groups { // a folder's name as it is, and its own widget id even when it matches a built-in group let r = crate::widgets::menu_button(ui, g.as_str(), |ui| { crate::menu_level::level(ui, 2, Some(below), |ui| { ui.set_min_width(170.0); - for p in app.session.lut_profiles.iter().filter(|p| &p.group == g) { - item(ui, "group", &p.id, &p.name, &mut pick); + for (id, name, _) in imported.iter().filter(|p| &p.2 == g) { + item(ui, "group", id, name, &mut pick); } }); }); @@ -214,13 +218,14 @@ pub(super) fn section( // ------------------------------------------------------------------------------ HDR -/// The Light panel's HDR row: the HDR switch and Visualize HDR, then (HDR on) the headroom limit. /// The Light panel's HDR settings while HDR editing is on (the switch itself is the HDR button -/// next to B&W): Visualize HDR range and the headroom limit. -pub(super) fn hdr_row(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) { - if !d.hdr.enabled { - return; - } +/// next to B&W): Visualize HDR range and the headroom limit. They slide open and shut with the +/// histogram's change of layout; another photo shows its own at once. +pub(super) fn hdr_row(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings, id: PhotoId) { + super::hdr_flow::drawer(ui, egui::Id::unique(("hdrSettings", id)), d.hdr.enabled, |ui| hdr_settings(app, ui, d)); +} + +fn hdr_settings(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) { egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 4, bottom: 4 }).show(ui, |ui| { let mut v = app.ui.hdr_visualize; let r = ui.checkbox(&mut v, "Visualize HDR"); diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index 3b1f23db7a..db4dfa1b83 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -846,7 +846,7 @@ fn paint_cell_thumbnail(app: &mut LightcraftApp, p: &egui::Painter, t: &Tokens, let [tw, th] = tex.size; // Preserve the decoded preview's ratio when it differs from the catalog dimensions. let fit = super::detail::fit_texture_rect(img_rect, [tw, th]); - p.image(tex.tex.id(), fit, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), fit, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); selection_ring(p, t, fit, state); fit } else { @@ -1325,18 +1325,11 @@ fn context_menu_open_and_edit(app: &mut LightcraftApp, ui: &mut egui::Ui, id: Ph } }); }); - if ui.button(crate::i18n::tr("Find Similar Photos")).clicked() { - match app.run("library.findSimilar", json!({"id": id.0})) { - Ok(r) => { - let n = r["photos"].as_array().map_or(0, Vec::len); - app.ui.view = crate::state::ViewMode::PhotoGrid; - app.toast( - ui.ctx(), - crate::i18n::tr_format!("{n} similar photo{} · View ▸ Clear Filters to see all", if n == 1 { "" } else { "s" }, n = n), - ); - } - Err(e) => app.toast(ui.ctx(), e), - } + let can_search = lightcraft_engine::cmd::similar::no_search_running(&app.session).is_ok(); + if ui.add_enabled(can_search, egui::Button::new(crate::i18n::tr("Find Similar Photos"))).clicked() + && let Err(e) = app.run("library.findSimilar", json!({"id": id.0})) + { + app.toast(ui.ctx(), e); } let live = super::compare::live(app, id); let set_reference = ui diff --git a/crates/ui-egui/src/panels/notices.rs b/crates/ui-egui/src/panels/notices.rs index cec974aa64..cc01701932 100644 --- a/crates/ui-egui/src/panels/notices.rs +++ b/crates/ui-egui/src/panels/notices.rs @@ -76,21 +76,34 @@ pub fn may_close(app: &mut LightcraftApp) -> bool { app.quit_prompt = Some(QuitPrompt::Tasks(tasks_message(names.len(), &names.join(", ")))); return false; } - if app.session.unsaved().is_none() { + // what the catalog log's thread was handed is written first, and what it holds read now: a + // change it accepted but hasn't written yet must not pass for saved (review of #3557) + let flushed = app.session.flush_log(); + if flushed.is_ok() && app.session.unsaved().is_none() { return true; } let _ = app.session.persist(); - if app.session.unsaved().is_some() - && let Err(e) = app.session.close_library() - { - log::error!("quit: library not saved: {e}"); + // a snapshot of everything in memory saves what the log couldn't take + let mut closed = Ok(()); + if flushed.is_err() || app.session.unsaved().is_some() { + closed = app.session.close_library(); + if let Err(e) = &closed { + log::error!("quit: library not saved: {e}"); + } } - match app.session.unsaved() { - None => true, - Some((n, e)) => { + match (app.session.unsaved(), flushed, closed) { + (None, Ok(()), _) | (None, _, Ok(())) => true, + (Some((n, e)), _, _) => { app.quit_prompt = Some(QuitPrompt::Unsaved(unsaved_message(n, e))); false } + // the snapshot landed; only the log's reset after it failed + (None, Err(_), Err(_)) if app.session.snapshot_holds_everything() => true, + // the log's thread didn't finish and the snapshot failed: changes may be lost + (None, Err(_), Err(e)) => { + app.quit_prompt = Some(QuitPrompt::Unsaved(unsaved_message(1, &e.to_string()))); + false + } } } diff --git a/crates/ui-egui/src/panels/people.rs b/crates/ui-egui/src/panels/people.rs index 18403d75df..da10075ca9 100644 --- a/crates/ui-egui/src/panels/people.rs +++ b/crates/ui-egui/src/panels/people.rs @@ -175,7 +175,7 @@ fn card(app: &mut LightcraftApp, ui: &mut egui::Ui, person: &Person, r: Rect, ed if let Some(job) = app.session.face_job(person.photo, view, (edge * ppp).ceil() as usize) && let Some(tex) = app.renderer.variant(job) { - p.image(tex.tex.id(), face, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), face, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } // how many photos they are in, on the picture let g = p.layout_no_wrap(badge_count(person.count), t.font(11.5), Color32::WHITE); diff --git a/crates/ui-egui/src/panels/person.rs b/crates/ui-egui/src/panels/person.rs index 0b6b946aa1..1063de935c 100644 --- a/crates/ui-egui/src/panels/person.rs +++ b/crates/ui-egui/src/panels/person.rs @@ -327,7 +327,7 @@ fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, spec: &TileSpec) -> Hit { if let Some(job) = app.session.face_job(lightcraft_catalog::PhotoId(f.photo), f.rect, (r.width() * ppp).ceil() as usize) && let Some(tex) = app.renderer.variant(job) { - p.image(tex.tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } if hovered { p.rect_stroke(r, 3.0, Stroke::new(1.5, Color32::WHITE), StrokeKind::Outside); diff --git a/crates/ui-egui/src/panels/presets.rs b/crates/ui-egui/src/panels/presets.rs index 6d35a50274..277c62b26b 100644 --- a/crates/ui-egui/src/panels/presets.rs +++ b/crates/ui-egui/src/panels/presets.rs @@ -228,7 +228,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if let Some(job) = app.session.variant_job(id, s, THUMB_EDGE) && let Some(tex) = app.renderer.variant(job) { - ui.painter().image(tex.tex.id(), tr, cover_uv(tr, tex.size), Color32::WHITE); + ui.painter().image(tex.id(), tr, cover_uv(tr, tex.size), Color32::WHITE); } text_x = tr.right() + 10.0; } diff --git a/crates/ui-egui/src/panels/profiles.rs b/crates/ui-egui/src/panels/profiles.rs index cf9a6c50cd..4757e9c504 100644 --- a/crates/ui-egui/src/panels/profiles.rs +++ b/crates/ui-egui/src/panels/profiles.rs @@ -62,12 +62,16 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { PROFILES.iter().filter(|p| p.group == g).map(|p| (p.id.to_string(), p.name.to_string(), p.group.to_string())).collect(), )); } - // imported LUT profile groups - let mut lut_groups: Vec = app.session.lut_profiles.iter().map(|p| p.group.clone()).collect(); - lut_groups.sort_unstable(); - lut_groups.dedup(); + // imported profile groups: LUT folders, then camera profiles + let imported = app.session.imported_profiles(); + let mut lut_groups: Vec = Vec::new(); + for (_, _, g) in &imported { + if !lut_groups.contains(g) { + lut_groups.push(g.clone()); + } + } for g in &lut_groups { - let profiles = app.session.lut_profiles.iter().filter(|p| &p.group == g).map(|p| (p.id.clone(), p.name.clone(), p.group.clone())).collect(); + let profiles = imported.iter().filter(|p| &p.2 == g).cloned().collect(); sections.push((g.as_str(), "", true, profiles)); } for (title, tag, imported, list) in sections { @@ -163,7 +167,7 @@ fn cell_ui( if let Some(job) = app.session.variant_job(id, &s, THUMB_EDGE) && let Some(tex) = app.renderer.variant(job) { - painter.image(tex.tex.id(), thumb, cover_uv(thumb, tex.size), Color32::WHITE); + painter.image(tex.id(), thumb, cover_uv(thumb, tex.size), Color32::WHITE); } let applied = d.profile.id == p_id; if applied { diff --git a/crates/ui-egui/src/panels/right/history.rs b/crates/ui-egui/src/panels/right/history.rs index d434075adc..86cdf1b19f 100644 --- a/crates/ui-egui/src/panels/right/history.rs +++ b/crates/ui-egui/src/panels/right/history.rs @@ -42,7 +42,7 @@ pub(super) fn versions(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) if let Some(job) = app.session.variant_job(id, &v.settings, 160) && let Some(tex) = app.renderer.variant(job) { - ui.painter().image(tex.tex.id(), tr, crate::panels::presets::cover_uv(tr, tex.size), egui::Color32::WHITE); + ui.painter().image(tex.id(), tr, crate::panels::presets::cover_uv(tr, tex.size), egui::Color32::WHITE); } let x = tr.right() + 10.0; ui.painter().with_clip_rect(r.with_max_x(r.right() - 24.0)).text( diff --git a/crates/ui-egui/src/panels/second.rs b/crates/ui-egui/src/panels/second.rs index 57fc5756a4..710079bef0 100644 --- a/crates/ui-egui/src/panels/second.rs +++ b/crates/ui-egui/src/panels/second.rs @@ -55,9 +55,10 @@ fn body(app: &mut LightcraftApp, ui: &mut egui::Ui) { let mine = |s: Slot| app.renderer.textures.get(&s).filter(|t| t.photo == id); let tex = mine(Slot::Second).or_else(|| mine(Slot::Main)).or_else(|| app.renderer.thumb(id)); if let Some(t) = tex { - let [tw, th] = t.tex.size(); + // (the frame's size: a GPU-resident render's `tex` is only a placeholder) + let [tw, th] = t.size.map(|n| n.max(1)); let s = (area.width() / tw as f32).min(area.height() / th as f32); let r = Rect::from_center_size(area.center(), vec2(tw as f32 * s, th as f32 * s)); - ui.painter().image(t.tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + ui.painter().image(t.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } } diff --git a/crates/ui-egui/src/panels/slideshow.rs b/crates/ui-egui/src/panels/slideshow.rs index cfe0ce6e68..8b0ade6cf3 100644 --- a/crates/ui-egui/src/panels/slideshow.rs +++ b/crates/ui-egui/src/panels/slideshow.rs @@ -328,7 +328,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let draw = |id: Item, alpha: f32| -> Option { let t = texture(app, id)?; let r = rect_of(t); - p.image(t.tex.id(), r, full_uv(), Color32::WHITE.gamma_multiply(alpha.clamp(0.0, 1.0))); + p.image(t.id(), r, full_uv(), Color32::WHITE.gamma_multiply(alpha.clamp(0.0, 1.0))); Some(r) }; let k = frame.progress.clamp(0.0, 1.0); @@ -352,13 +352,13 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let r = rect_of(t); match new_rect { Some(n) => { - p.with_clip_rect(n.intersect(canvas)).image(t.tex.id(), r, full_uv(), Color32::WHITE); + p.with_clip_rect(n.intersect(canvas)).image(t.id(), r, full_uv(), Color32::WHITE); for band in outside(r, n) { - p.with_clip_rect(band).image(t.tex.id(), r, full_uv(), Color32::WHITE.gamma_multiply(1.0 - k)); + p.with_clip_rect(band).image(t.id(), r, full_uv(), Color32::WHITE.gamma_multiply(1.0 - k)); } } None => { - p.image(t.tex.id(), r, full_uv(), Color32::WHITE.gamma_multiply(1.0 - k)); + p.image(t.id(), r, full_uv(), Color32::WHITE.gamma_multiply(1.0 - k)); } } } diff --git a/crates/ui-egui/src/panels/unnamed.rs b/crates/ui-egui/src/panels/unnamed.rs index 7f42437b2e..71f1a2803d 100644 --- a/crates/ui-egui/src/panels/unnamed.rs +++ b/crates/ui-egui/src/panels/unnamed.rs @@ -243,7 +243,7 @@ pub fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, list: &Unnamed, i: usize if let Some(job) = app.session.face_job(lightcraft_catalog::PhotoId(f.photo), f.view, (r.width() * ppp).ceil() as usize) && let Some(tex) = app.renderer.variant(job) { - p.image(tex.tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } if selected { p.rect_filled(r, 3.0, Color32::from_rgba_unmultiplied(70, 130, 255, 55)); diff --git a/crates/ui-egui/src/pick.rs b/crates/ui-egui/src/pick.rs index b9d58cee6c..c7e8e742db 100644 --- a/crates/ui-egui/src/pick.rs +++ b/crates/ui-egui/src/pick.rs @@ -58,7 +58,7 @@ impl PickRequest { } /// What File ▸ Import Profiles & Presets… opens. -pub const PRESET_EXTENSIONS: &[&str] = &["lcpreset", "xmp", "lrtemplate", "zip", "dng", "lmp", "mplumpack", "cube", "lceffect"]; +pub const PRESET_EXTENSIONS: &[&str] = &["lcpreset", "xmp", "lrtemplate", "zip", "dng", "lmp", "mplumpack", "cube", "dcp", "lceffect"]; /// What Import Point Curve Presets… opens. pub const CURVE_PRESET_EXTENSIONS: &[&str] = &["lccurve", "json"]; diff --git a/crates/ui-egui/src/render.rs b/crates/ui-egui/src/render.rs index fd2bc1706f..9237e43066 100644 --- a/crates/ui-egui/src/render.rs +++ b/crates/ui-egui/src/render.rs @@ -93,6 +93,44 @@ pub struct Tex { pub quick: Option, /// CPU copy of the pixels (only with [`Renderer::keep_pixels`]; for headless screenshots). pub pixels: Option>, + /// Showing a render that stayed on the GPU ([`ScreenTextures`]): drawn by this id instead of `tex`. + pub native: Option, +} + +impl Tex { + /// Draw this slot from the GPU-resident texture `id` from now on. On the switch from pixels, the egui texture + /// (never drawn while `native` is set) drops its full-size image for a 1 × 1 placeholder, so a view slot on the + /// GPU path doesn't keep a second copy of the picture until it is released (review of PR #1065). + fn show_native(&mut self, id: egui::TextureId) { + if self.native.is_none() { + self.tex.set(egui::ColorImage::filled([1, 1], egui::Color32::BLACK), egui::TextureOptions::LINEAR); + } + self.native = Some(id); + self.pixels = None; + } + + /// The texture to draw. + pub fn id(&self) -> egui::TextureId { + self.native.unwrap_or_else(|| egui::TextureHandle::id(&self.tex)) + } +} + +/// Draws renders that stayed on the GPU ([`lightcraft_engine::media::ScreenFrame`]): the window's +/// renderer registers their textures. Installed by a host whose GPU renderer runs on the window's +/// device (the desktop app); without one, every render comes back as pixels. +pub trait ScreenTextures { + /// Show `frame` under `id` (one this returned before, updated in place) or a new id; `None` + /// when it can't be shown. + fn show(&mut self, frame: &lightcraft_engine::media::ScreenFrame, id: Option) -> Option; + /// Release `id` (and the texture it shows). + fn free(&mut self, id: egui::TextureId); + /// The pixels `frame` holds, read back from the GPU: only for a headless screenshot of a view + /// that shows it ([`Renderer::cpu_textures`]). `None` when they can't be read (the view is + /// then left out of the picture). + fn read(&self, frame: &lightcraft_engine::media::ScreenFrame) -> Option { + let _ = frame; + None + } } /// Runs render jobs outside this thread's job pool (the browser build: Web Workers, each with its @@ -214,6 +252,9 @@ pub struct Renderer { offload_looks: HashMap, #[cfg(test)] failure_messages: Vec, + /// The render decisions [`Self::decided`] logged. + #[cfg(test)] + decisions: Vec, /// Request id of the pixels each interactive view (loupe, before, hover) shows: a draft that /// finishes after a newer request was made still replaces older pixels, so a long slider drag /// keeps updating the loupe instead of waiting for the drag to pause. @@ -276,6 +317,14 @@ pub struct Renderer { /// Since when nothing has been pending, and whether the GPU pool was trimmed since. #[cfg(not(target_arch = "wasm32"))] idle: Option<(std::time::Instant, bool)>, + /// Draws GPU-resident renders; with it, interactive drafts of views stay on the GPU. + screen: Option>, + /// The texture id each view slot shows GPU-resident renders under (one per slot, reused). + natives: HashMap, + /// The GPU-resident render each of those shows, kept with [`Self::keep_pixels`]: a headless + /// screenshot reads it back ([`Self::cpu_textures`]) instead of finding no pixels (a white + /// photo, review of PR #1065). + native_frames: HashMap, } /// After this long without renders the GPU renderer's pool of recycled buffers is freed. @@ -329,6 +378,8 @@ impl Renderer { offload_looks: HashMap::new(), #[cfg(test)] failure_messages: Vec::new(), + #[cfg(test)] + decisions: Vec::new(), shown_ids: HashMap::new(), epoch: 0, preview_generation: None, @@ -360,6 +411,9 @@ impl Renderer { display: None, #[cfg(not(target_arch = "wasm32"))] idle: None, + screen: None, + natives: HashMap::new(), + native_frames: HashMap::new(), } } } @@ -521,7 +575,23 @@ impl Renderer { /// `job` as [`Self::request`] would run it for `slot` (its key included): views render for /// the display profile in use. pub fn job_for(&self, slot: Slot, job: RenderJob) -> RenderJob { - if Self::renders_for_display(slot) { job.with_display(self.display.clone()) } else { job } + if !Self::renders_for_display(slot) { + return job; + } + let job = job.with_display(self.display.clone()); + // a drag's drafts are only drawn: they may stay on the GPU when the window can show them + if self.screen.is_some() && job.request.quality == lightcraft_pipeline::Quality::Draft { job.on_screen() } else { job } + } + + /// Show GPU-resident renders through `screen` from now on (the desktop app, once its GPU + /// renderer runs on the window's device). + pub fn set_screen_textures(&mut self, screen: Box) { + self.screen = Some(screen); + } + + /// Whether GPU-resident renders can be shown. + pub fn has_screen_textures(&self) -> bool { + self.screen.is_some() } /// The display profile in use (id). @@ -567,6 +637,19 @@ impl Renderer { pub fn release(&mut self, slot: Slot) { self.textures.remove(&slot); self.stages.remove(&slot); + // and its GPU-resident texture, which can be window-sized (review of PR #1065) + self.free_native(slot); + } + + /// Let go of `slot`'s GPU-resident texture: its registration with the window, and the frame + /// kept for headless screenshots. + fn free_native(&mut self, slot: Slot) { + self.native_frames.remove(&slot); + if let Some(id) = self.natives.remove(&slot) + && let Some(screen) = self.screen.as_mut() + { + screen.free(id); + } } /// Run jobs through `offload` from now on (instead of the job pool / inline). @@ -597,6 +680,7 @@ impl Renderer { if !self.request_needed(slot, job.key, priority) { return; } + self.note_request(slot, job.key, priority, "requested", || render_subject(slot, job.photo, Some(&job.origin))); self.pending.insert(slot, (job.key, priority)); job.request_id = lightcraft_preview::next_tick(); self.requests.insert( @@ -664,18 +748,24 @@ impl Renderer { }); if queued && let Some(p) = self.pending.get_mut(&slot) { p.1 = priority; + if logs_decisions() { + let source = self.requests.get(&slot).and_then(|r| r.source.as_ref()); + let line = format!("{}: still waiting, moved to priority {priority}", render_subject(slot, job.photo, source)); + self.decided(|| line); + } } } return; } self.quick_tried.insert(slot, job.key); - self.pending.insert(slot, (job.key, priority)); - job.request_id = lightcraft_preview::next_tick(); let source = job .small .as_ref() .map(|job| job.origin.clone()) .or_else(|| job.embedded.as_ref().map(|(path, _, _)| lightcraft_catalog::Source::File { path: path.clone() })); + self.note_request(slot, job.key, priority, "stand-in requested", || render_subject(slot, job.photo, source.as_ref())); + self.pending.insert(slot, (job.key, priority)); + job.request_id = lightcraft_preview::next_tick(); self.requests.insert( slot, Requested { look: job.small.as_ref().map(|j| (geometry_look(&j.settings), j.request.apply_crop)), id: job.request_id, source }, @@ -696,6 +786,7 @@ impl Renderer { if !self.request_needed(slot, key, priority) { return; } + self.note_request(slot, key, priority, "title screen requested", || format!("render {slot:?}")); self.pending.insert(slot, (key, priority)); let request_id = lightcraft_preview::next_tick(); self.requests.insert(slot, Requested { look: None, id: request_id, source: None }); @@ -710,6 +801,7 @@ impl Renderer { return; } self.prefetched.insert(slot, job.key); + self.note_request(slot, job.key, priority, "prefetch requested", || render_subject(slot, job.photo, Some(&job.origin))); self.pending.insert(slot, (job.key, priority)); job.request_id = lightcraft_preview::next_tick(); self.requests.insert( @@ -732,6 +824,7 @@ impl Renderer { return; } let gone = |s: &Slot| matches!(s, Slot::Slide(id) if !keep.contains(id)); + self.abandon_pending(gone, "no longer near the slide shown"); self.textures.retain(|s, _| !gone(s)); let _ = self.pool.reprioritize(|s, p| if gone(s) { None } else { Some(p) }); self.queue.retain(|q| !gone(&q.slot)); @@ -745,6 +838,7 @@ impl Renderer { /// Is a request for `slot` queued or running? /// Drop every texture and cached stage (another library was opened: photo ids changed meaning). pub fn forget_all(&mut self) { + self.abandon_pending(|_| true, "the renderer started over (another library, or the previews were cleared)"); self.requests.clear(); self.offload_looks.clear(); self.shown_ids.clear(); @@ -759,6 +853,20 @@ impl Renderer { self.prefetched.clear(); self.pending.clear(); self.queue.clear(); + self.free_natives(); + } + + /// Release every GPU-resident texture shown. + fn free_natives(&mut self) { + if let Some(screen) = self.screen.as_mut() { + for (_, id) in self.natives.drain() { + screen.free(id); + } + } + self.natives.clear(); + self.native_frames.clear(); + // a view drawn from a freed texture would show nothing: it is rendered again, as pixels + self.textures.retain(|_, t| t.native.is_none()); } pub fn is_pending(&self, slot: Slot) -> bool { @@ -1008,8 +1116,9 @@ impl Renderer { } } - /// Turn finished jobs into textures. Returns true if anything changed. - fn collect(&mut self, ctx: &egui::Context, session: &mut Session, inline_ms: f64) -> bool { + /// The jobs the pool and the offload finished: (slot, result, texture pixels, look, ms). + #[allow(clippy::type_complexity)] + fn take_finished(&mut self, inline_ms: f64) -> Vec<(Slot, RenderResult, Option>, Option<(u64, bool)>, f64)> { let mut finished = Vec::new(); while let Some(done) = self.pool.try_recv() { finished.push((done.slot, done.result.result, done.result.color, done.result.look, if done.ms > 0.0 { done.ms } else { inline_ms })); @@ -1020,12 +1129,22 @@ impl Renderer { (slot, r, None, look, ms) })); } + finished + } + + /// Turn finished jobs into textures. Returns true if anything changed. + fn collect(&mut self, ctx: &egui::Context, session: &mut Session, inline_ms: f64) -> bool { + let finished = self.take_finished(inline_ms); self.dispatch(); let mut changed = false; for (mut slot, mut r, mut color, completed_look, ms) in finished { self.completed += 1; // made for another display profile than the one in use: obsolete if r.display.is_some_and(|id| Some(id) != self.display_id()) { + self.decided(|| { + let source = session.catalog.photo(r.photo).map(|p| &p.source); + format!("{}: abandoned, made for another display profile", render_subject(slot, r.photo, source)) + }); continue; } // Ignore obsolete pixels, failures and decoded sources, even for the same render key; @@ -1040,6 +1159,12 @@ impl Renderer { && r.rendered.is_ok(); if !newer_draft { self.discarded += 1; + let replaced = self.requests.contains_key(&slot); + self.decided(|| { + let why = if replaced { "a newer request replaced it" } else { "no longer wanted when it finished" }; + let source = session.catalog.photo(r.photo).map(|p| &p.source); + format!("{}: abandoned, {why}", render_subject(slot, r.photo, source)) + }); continue; } session.accept(&r); @@ -1065,9 +1190,72 @@ impl Renderer { if self.pending.get(&slot).is_some_and(|p| p.0 == r.key) { self.pending.remove(&slot); } + // a render that stayed on the GPU: drawn from its texture + if let (Some(frame), Ok(rendered)) = (r.frame.as_ref(), r.rendered.as_ref()) { + self.failed.remove(&slot); + let shown = self.screen.as_mut().and_then(|s| s.show(frame, self.natives.get(&slot).copied())); + let Some(id) = shown else { + // can't be shown: from now on views come back as pixels + log::warn!("render {slot:?}: a GPU-resident render can't be shown; rendering pixels"); + self.free_natives(); + self.screen = None; + continue; + }; + self.natives.insert(slot, id); + if self.keep_pixels { + self.native_frames.insert(slot, frame.clone()); + } + let (size, histogram) = ([frame.width, frame.height], rendered.histogram.clone()); + match self.textures.get_mut(&slot) { + Some(t) => { + t.show_native(id); + t.look = look; + t.key = r.key; + t.photo = r.photo; + t.size = size; + t.histogram = Some(histogram); + t.ms = ms; + t.quick = None; + } + None => { + // (`tex` is never drawn while `native` is set) + let blank = egui::ColorImage::filled([1, 1], egui::Color32::BLACK); + let tex = ctx.load_texture(format!("{slot:?}"), blank, egui::TextureOptions::LINEAR); + let t = Tex { + look, + key: r.key, + photo: r.photo, + tex, + size, + histogram: Some(histogram), + ms, + quick: None, + pixels: None, + native: Some(id), + }; + self.textures.insert(slot, t); + } + } + if slot == Slot::Main { + self.last_main_ms = ms; + } + changed = true; + continue; + } let rendered = match r.rendered { Ok(x) => { self.failed.remove(&slot); + // (a stand-in that comes back after the thumbnail itself is thrown away below) + let unused = matches!(slot, Slot::ThumbQuick(id) if self.textures.contains_key(&Slot::Thumb(id))); + self.decided(|| { + let source = source.as_ref().or_else(|| session.catalog.photo(r.photo).map(|p| &p.source)); + let subject = render_subject(slot, r.photo, source); + if unused { + format!("{subject}: abandoned, the thumbnail itself came first") + } else { + format!("{subject}: produced in {ms:.0} ms") + } + }); x } Err(e) => { @@ -1077,6 +1265,9 @@ impl Renderer { self.failure_messages.push(message.clone()); log::warn!("{message}"); self.failed.insert(slot, (r.key, e, self.catalog_rev, r.photo)); + } else { + // (a prefetch only prepares: its failure is no warning, but the trace says how it ended) + self.decided(|| format!("{}: prefetch failed: {e}", render_subject(slot, r.photo, source.as_ref()))); } continue; } @@ -1107,9 +1298,12 @@ impl Renderer { let color = color.unwrap_or_else(|| Arc::new(color_image(img))); let pixels = self.keep_pixels.then(|| color.clone()); let name = format!("{slot:?}"); + // pixels again: the slot's GPU-resident texture is let go + self.free_native(slot); match self.textures.get_mut(&slot) { Some(t) => { t.tex.set(color, egui::TextureOptions::LINEAR); + t.native = None; t.pixels = pixels; t.look = look; t.key = r.key; @@ -1133,6 +1327,7 @@ impl Renderer { ms, quick: r.quick, pixels, + native: None, }, ); } @@ -1202,9 +1397,20 @@ impl Renderer { }) } - /// CPU copies of the current textures by id (see [`Self::keep_pixels`]). + /// CPU copies of the current textures by id (see [`Self::keep_pixels`]); a view drawn straight + /// from the GPU is read back from it (only here: drawing it never does). pub fn cpu_textures(&self) -> HashMap { - self.textures.values().filter_map(|t| Some((t.tex.id(), crate::softpaint::CpuTexture::linear(t.pixels.clone()?)))).collect() + self.textures + .iter() + .filter_map(|(slot, t)| { + let pixels = match (&t.pixels, t.native, self.native_frames.get(slot), self.screen.as_ref()) { + (Some(p), ..) => p.clone(), + (None, Some(_), Some(frame), Some(screen)) => Arc::new(screen.read(frame)?), + _ => return None, + }; + Some((t.id(), crate::softpaint::CpuTexture::linear(pixels))) + }) + .collect() } /// Drop the import review thumbnails (a new review, or the dialog closed). @@ -1235,19 +1441,24 @@ impl Renderer { }); for s in dropped { self.pending.remove(&s); - self.requests.remove(&s); + let request = self.requests.remove(&s); self.quick_tried.remove(&s); + self.decided(|| abandoned_line(s, request.as_ref(), "scrolled out of view before it started")); } + let mut gone = Vec::new(); let requests = &mut self.requests; let pending = &mut self.pending; self.queue.retain(|q| match q.slot { Slot::Thumb(id) if !keep.contains(&id) && q.priority <= 10 => { pending.remove(&q.slot); - requests.remove(&q.slot); + gone.push((q.slot, requests.remove(&q.slot))); false } _ => true, }); + for (s, request) in gone { + self.decided(|| abandoned_line(s, request.as_ref(), "scrolled out of view before it started")); + } let thumbs = self.thumb_textures(); if thumbs <= max { return; @@ -1255,15 +1466,91 @@ impl Renderer { self.textures.retain(|s, _| !matches!(s, Slot::Thumb(id) | Slot::ThumbQuick(id) if !keep.contains(id))); self.quick_tried.retain(|s, _| !matches!(s, Slot::ThumbQuick(id) if !keep.contains(id))); } + + /// Log a render decision at debug level: each request, and how it ended when it ended without + /// a picture or a failure (failures stay warnings). One "requested" line per request tells a + /// file asked for 37 times from one asked once and failing inside (issue #2682). `line` is only + /// built when the log takes debug lines (`LIGHTCRAFT_LOG=debug`, or + /// `RUST_LOG=lightcraft_ui_egui::render=debug`), so the grid's requests cost nothing more otherwise. + fn decided(&mut self, line: impl FnOnce() -> String) { + if !logs_decisions() { + return; + } + let line = line(); + log::debug!("{line}"); + #[cfg(test)] + self.decisions.push(line); + } + + /// Log a new request for `slot`, and first what becomes of the one it replaces while that one + /// still waits: a queue holds one job per slot, so a newer render drops it, and the same render + /// is only moved to the new priority. One already running says so when its result comes back. + fn note_request(&mut self, slot: Slot, key: u64, priority: u32, what: &str, subject: impl FnOnce() -> String) { + if !logs_decisions() { + return; + } + let waiting = self.pending.get(&slot).map(|p| p.0).filter(|_| self.is_queued(slot)); + if waiting == Some(key) { + let line = format!("{}: still waiting, moved to priority {priority}", subject()); + self.decided(|| line); + return; + } + if waiting.is_some() { + let line = abandoned_line(slot, self.requests.get(&slot), "a newer request replaced it before it started"); + self.decided(|| line); + } + let again = if self.failed.get(&slot).is_some_and(|f| f.0 == key) { " again after a failure" } else { "" }; + let line = format!("{}: {what}{again}", subject()); + self.decided(|| line); + } + + /// Log each request in `which` that still waits in a queue as abandoned (`why`), before they are + /// dropped. One already running says so once, when its result comes back unclaimed. + fn abandon_pending(&mut self, which: impl Fn(&Slot) -> bool, why: &str) { + if !logs_decisions() { + return; + } + let mut slots: Vec = self.pending.keys().copied().filter(|s| which(s) && self.is_queued(*s)).collect(); + slots.sort_by_key(|s| format!("{s:?}")); + for s in slots { + let line = abandoned_line(s, self.requests.get(&s), why); + self.decided(|| line); + } + } } -/// Include the source identity in diagnostics for every catalog-backed render slot (#1890). -/// Debug-format paths so whitespace/control characters cannot forge another log entry. -fn render_failure_message(slot: Slot, photo: PhotoId, source: Option<&lightcraft_catalog::Source>, error: &str) -> String { +/// Whether render decisions are logged ([`Renderer::decided`]): the log takes debug lines from this +/// module, or a test is looking. +fn logs_decisions() -> bool { + cfg!(test) || log::log_enabled!(log::Level::Debug) +} + +/// How the log names a render: its slot, its photo and that photo's source, for every +/// catalog-backed render slot (#1890). Debug-format paths so whitespace/control characters cannot +/// forge another log entry. +fn render_subject(slot: Slot, photo: PhotoId, source: Option<&lightcraft_catalog::Source>) -> String { match source { - Some(lightcraft_catalog::Source::File { path }) => format!("render {slot:?}, {photo:?}, file {path:?}: {error}"), - Some(lightcraft_catalog::Source::Demo { scene }) => format!("render {slot:?}, {photo:?}, demo scene {scene}: {error}"), - None => format!("render {slot:?}, {photo:?}, source unavailable: {error}"), + Some(lightcraft_catalog::Source::File { path }) => format!("render {slot:?}, {photo:?}, file {path:?}"), + Some(lightcraft_catalog::Source::Demo { scene }) => format!("render {slot:?}, {photo:?}, demo scene {scene}"), + None => format!("render {slot:?}, {photo:?}, source unavailable"), + } +} + +/// Include the source identity in diagnostics ([`render_subject`]). +fn render_failure_message(slot: Slot, photo: PhotoId, source: Option<&lightcraft_catalog::Source>, error: &str) -> String { + format!("{}: {error}", render_subject(slot, photo, source)) +} + +/// The log line for a request dropped before its result came back, named by the source it was +/// requested from. A grid slot names its photo; a view or slide slot shows whichever photo is open, +/// so its file names it. +fn abandoned_line(slot: Slot, request: Option<&Requested>, why: &str) -> String { + let source = request.and_then(|r| r.source.as_ref()); + match (slot, source) { + (Slot::Thumb(id) | Slot::ThumbQuick(id), _) => format!("{}: abandoned, {why}", render_subject(slot, id, source)), + (_, Some(lightcraft_catalog::Source::File { path })) => format!("render {slot:?}, file {path:?}: abandoned, {why}"), + (_, Some(lightcraft_catalog::Source::Demo { scene })) => format!("render {slot:?}, demo scene {scene}: abandoned, {why}"), + (_, None) => format!("render {slot:?}: abandoned, {why}"), } } @@ -1286,7 +1573,7 @@ mod stage_budget_tests { let tex = ctx.load_texture("window", egui::ColorImage::new([1, 1], vec![egui::Color32::BLACK]), Default::default()); r.textures.insert( Slot::Region, - Tex { look: None, key: 1, photo: PhotoId(1), tex, size: [1, 1], histogram: None, ms: 0.0, quick: None, pixels: None }, + Tex { look: None, key: 1, photo: PhotoId(1), tex, native: None, size: [1, 1], histogram: None, ms: 0.0, quick: None, pixels: None }, ); let long_ago = std::time::Instant::now().checked_sub(IDLE_TRIM * 2).unwrap(); r.idle = Some((long_ago, false)); @@ -1298,6 +1585,59 @@ mod stage_budget_tests { assert_eq!(r.idle, Some((long_ago, true)), "trimmed once the window is gone"); } + // Given views drawn from GPU-resident frames, freeing those frames (the screen can't show one any more) drops + // the views that point at them, so they are rendered again as pixels; a view held as pixels stays + #[test] + fn freeing_gpu_frames_drops_the_views_drawn_from_them() { + let ctx = egui::Context::default(); + let mut r = Renderer::default(); + let tex = |name: &str| ctx.load_texture(name, egui::ColorImage::new([1, 1], vec![egui::Color32::BLACK]), Default::default()); + let view = |tex, native| Tex { + look: None, + key: 1, + photo: PhotoId(1), + tex, + native, + size: [64, 48], + histogram: None, + ms: 0.0, + quick: None, + pixels: None, + }; + r.textures.insert(Slot::Before, view(tex("before"), Some(egui::TextureId::User(7)))); + r.textures.insert(Slot::Compare(0), view(tex("compare"), Some(egui::TextureId::User(8)))); + r.textures.insert(Slot::Main, view(tex("main"), None)); + r.free_natives(); + assert!(!r.textures.contains_key(&Slot::Before), "its frame is gone"); + assert!(!r.textures.contains_key(&Slot::Compare(0)), "its frame is gone"); + assert!(r.textures.contains_key(&Slot::Main), "pixels stay"); + } + + /// A view slot switching from pixels to a GPU-resident texture lets go of its pixel image (it is never drawn + /// while the native texture is set): before, the full-size image stayed in egui's texture manager. + #[test] + fn a_view_switching_to_a_gpu_texture_drops_its_pixel_image() { + let ctx = egui::Context::default(); + let image = egui::ColorImage::new([64, 48], vec![egui::Color32::GRAY; 64 * 48]); + let mut t = Tex { + look: None, + key: 1, + photo: PhotoId(1), + tex: ctx.load_texture("main", image, Default::default()), + native: None, + size: [64, 48], + histogram: None, + ms: 0.0, + quick: None, + pixels: Some(std::sync::Arc::new(egui::ColorImage::new([1, 1], vec![egui::Color32::BLACK]))), + }; + t.show_native(egui::TextureId::User(7)); + assert_eq!(t.tex.size(), [1, 1], "the pixel image is released"); + assert_eq!((t.native, t.pixels.is_none()), (Some(egui::TextureId::User(7)), true)); + t.show_native(egui::TextureId::User(8)); + assert_eq!((t.native, t.tex.size()), (Some(egui::TextureId::User(8)), [1, 1])); + } + // Given stage caches within the budget, nothing is cleared #[test] fn nothing_is_trimmed_within_the_budget() { @@ -1418,6 +1758,7 @@ mod color_image_tests { loaded: None, quick: None, display: None, + frame: None, }; let histogram = Histogram::of_srgb8(&image); let ok = Renderer::run_for(|| result(Ok(lightcraft_pipeline::Rendered { image: image.clone(), histogram, deep: None })), &None); diff --git a/crates/ui-egui/src/render/thumbnail_tests.rs b/crates/ui-egui/src/render/thumbnail_tests.rs index 769f9378b2..7a2cb1a6a9 100644 --- a/crates/ui-egui/src/render/thumbnail_tests.rs +++ b/crates/ui-egui/src/render/thumbnail_tests.rs @@ -23,6 +23,129 @@ fn render_failure_paths_are_escaped_and_missing_sources_still_identified() { assert!(render_failure_message(Slot::Main, PhotoId(42), Some(&demo), "decode failed").contains("demo scene 7")); } +/// Issue #2682: the log could not tell a file asked for 37 times from one asked once and failing +/// inside. At debug level every request is a line naming its file, and so is how it ended when it +/// drew nothing (a failure stays the warning it was). +#[test] +fn each_render_request_and_how_it_ended_is_a_debug_line_with_its_file() { + let ends = + |lines: &[String]| -> Vec { lines.iter().map(|l| l.rsplit_once(": ").map_or(l.clone(), |(_, end)| end.to_string())).collect() }; + let (mut app, work, ctx) = fixture(); + let slot = Slot::Thumb(PhotoId(1)); + let job = |app: &mut crate::LightcraftApp, edge| app.session.render_job(PhotoId(1), edge, edge, false, true).unwrap(); + // asked once, drawn + let j = job(&mut app, 64); + app.renderer.request(slot, j, 10); + let (_, j) = take_job(&work); + finish(&mut app, &work, &ctx, slot, j.run()); + // asked twice: the first answer comes after the second request and is dropped + let (a, b) = (job(&mut app, 128), job(&mut app, 160)); + app.renderer.request(slot, a, 10); + app.renderer.request(slot, b, 10); + let (_, b) = take_job(&work); + let (_, a) = take_job(&work); + finish(&mut app, &work, &ctx, slot, a.run()); + finish(&mut app, &work, &ctx, slot, b.run()); + // a stand-in that comes back after the thumbnail itself is not used + let quick = Slot::ThumbQuick(PhotoId(1)); + let mut j = job(&mut app, 64); + j.request_id = lightcraft_preview::next_tick(); + app.renderer.requests.insert(quick, Requested { look: None, id: j.request_id, source: Some(j.origin.clone()) }); + finish(&mut app, &work, &ctx, quick, j.run()); + // a render still running when everything is forgotten says so once, when it comes back + let j = job(&mut app, 200); + app.renderer.request(slot, j, 10); + let (_, j) = take_job(&work); + app.renderer.forget_all(); + finish(&mut app, &work, &ctx, slot, j.run()); + assert_eq!( + ends(&app.renderer.decisions), + [ + "requested", + "produced in 0 ms", + "requested", + "requested", + "abandoned, a newer request replaced it", + "produced in 0 ms", + "abandoned, the thumbnail itself came first", + "requested", + "abandoned, no longer wanted when it finished" + ] + ); + let named = |app: &crate::LightcraftApp| { + assert!( + app.renderer.decisions.iter().all(|l| l.starts_with("render Thumb") && l.contains(", PhotoId(1), file \"audit.jpg\": ")), + "{:?}", + app.renderer.decisions + ); + }; + named(&app); + + // a file that fails asks nothing while its failure stands, and says so when it is asked again + let (mut app, work, ctx) = fixture(); + app.session.media.file_loader = Some(Arc::new(|_, _, _| Err("simulated decode failure".into()))); + let j = job(&mut app, 64); + app.renderer.request(slot, j, 10); + let (_, j) = take_job(&work); + finish(&mut app, &work, &ctx, slot, j.run()); + assert_eq!(app.renderer.failure_messages.len(), 1, "the failure is the warning it was"); + let j = job(&mut app, 64); + app.renderer.request(slot, j, 10); + app.session.catalog.apply(Op::SetRating { id: PhotoId(1), rating: 3 }).unwrap(); + app.renderer.poll(&ctx, &mut app.session); + let j = job(&mut app, 64); + app.renderer.request(slot, j, 10); + assert_eq!(ends(&app.renderer.decisions), ["requested", "requested again after a failure"]); + named(&app); + + // requests that end before they run: the same render moved to another priority, a newer render + // in its place, scrolled out of view, everything forgotten + let (mut app, _, _) = fixture(); + app.renderer.set_offload(Box::new(Blocked)); + let j = job(&mut app, 64); + app.renderer.request(slot, j, 5); + let j = job(&mut app, 64); + app.renderer.request(slot, j, 10); + let j = job(&mut app, 128); + app.renderer.request(slot, j, 10); + app.renderer.evict_thumbs(&Default::default(), 0); + let j = job(&mut app, 64); + app.renderer.request(slot, j, 5); + app.renderer.forget_all(); + assert_eq!( + ends(&app.renderer.decisions), + [ + "requested", + "still waiting, moved to priority 10", + "abandoned, a newer request replaced it before it started", + "requested", + "abandoned, scrolled out of view before it started", + "requested", + "abandoned, the renderer started over (another library, or the previews were cleared)" + ] + ); + named(&app); + + // a stand-in still waiting that the grid moves up while it scrolls says so + let mut s = Session::new(); + s.media.preview_loader = Some(Arc::new(|_, _| Some(lightcraft_raster::Rgba8 { width: 4, height: 4, data: vec![[200, 100, 50, 255]; 16] }))); + let mut raw = (*photo()).clone(); + raw.kind = lightcraft_catalog::MediaKind::Raw; + raw.develop = Arc::new(raw.camera_defaults()); + let (mut app, _, _) = fixture_with(s, raw); + app.renderer.pool = JobPool::new(0); // nothing starts until run_inline + crate::panels::grid::request_thumb(&mut app, PhotoId(1), 384, 5); + crate::panels::grid::request_thumb(&mut app, PhotoId(1), 384, 10); + assert_eq!(ends(&app.renderer.decisions), ["stand-in requested", "still waiting, moved to priority 11"]); + named(&app); + // a view shows whichever photo is open: its file names it + let main = Requested { look: None, id: 1, source: Some(Source::File { path: "trip/IMG_1.nef".into() }) }; + assert_eq!( + abandoned_line(Slot::Main, Some(&main), "a newer request replaced it"), + "render Main, file \"trip/IMG_1.nef\": abandoned, a newer request replaced it" + ); +} + struct Blocked; impl RenderOffload for Blocked { fn try_start(&mut self, _: Slot, job: RenderJob) -> Option { @@ -206,6 +329,7 @@ fn larger_texture_for_another_key_does_not_count_as_current() { ms: 0.0, quick: None, pixels: None, + native: None, }; let mut r = Renderer::default(); // A completed larger bucket: the remembered request is bucket 512, key 77. @@ -270,7 +394,7 @@ fn a_failed_thumbnail_is_retried_only_when_its_photo_changes() { #[test] fn a_fast_draft_is_drawn_in_the_frame_that_asked_for_it() { let mut s = Session::new(); - s.media.file_loader = Some(Arc::new(|_, _| Ok((lightcraft_raster::Rgb32f::new(8, 8), Default::default())))); + s.media.file_loader = Some(Arc::new(|_, _, _| Ok((lightcraft_raster::Rgb32f::new(8, 8), Default::default())))); s.catalog.apply(Op::AddPhoto { photo: Box::new((*photo()).clone()) }).unwrap(); let mut r = Renderer::with_worker_threads(1); let ctx = egui::Context::default(); @@ -317,7 +441,7 @@ fn raw_quick_fixture() -> (crate::LightcraftApp, std::rc::Rc (crate::LightcraftApp, std::rc::Rc>, egui::Context) { - s.media.file_loader = Some(Arc::new(|_, _| { + s.media.file_loader = Some(Arc::new(|_, _, _| { let mut image = lightcraft_raster::Rgb32f::new(8, 8); image.data.fill([0.3, 0.2, 0.1]); Ok((image, Default::default())) @@ -344,6 +468,117 @@ fn request(app: &mut crate::LightcraftApp) { crate::panels::grid::request_thumb(app, PhotoId(1), 256, 10); } +/// Draws GPU-resident renders under one fixed id, and reads them back from the test's device. +#[cfg(not(target_arch = "wasm32"))] +struct TestScreen(lightcraft_engine::gpu::wgpu::Device, lightcraft_engine::gpu::wgpu::Queue, std::sync::Arc>>); +#[cfg(not(target_arch = "wasm32"))] +impl ScreenTextures for TestScreen { + fn show(&mut self, _: &lightcraft_engine::media::ScreenFrame, _: Option) -> Option { + Some(egui::TextureId::User(7)) + } + fn free(&mut self, id: egui::TextureId) { + self.2.lock().unwrap().push(id); + } + fn read(&self, frame: &lightcraft_engine::media::ScreenFrame) -> Option { + let img = lightcraft_engine::gpu::read_texture(&self.0, &self.1, &frame.texture, frame.width, frame.height).ok()?; + Some(color_image(&img)) + } +} + +/// A headless screenshot (driven by the control channel: `keep_pixels`) of a view drawn straight +/// from the GPU has its pixels. Before, a mid-drag `ui.screenshot {"headless": true}` showed the +/// photo as a white rectangle: the GPU-resident draft left no CPU copy (review of PR #1065). +/// The test fixture with a small GPU texture (5 × 3 known texels) and a [`TestScreen`] that +/// records the ids it frees; `None` without a GPU adapter. +#[cfg(not(target_arch = "wasm32"))] +#[allow(clippy::type_complexity)] +fn gpu_drawn_fixture( + freed: std::sync::Arc>>, +) -> Option<(crate::LightcraftApp, std::rc::Rc>, egui::Context, lightcraft_engine::media::ScreenFrame)> { + use lightcraft_engine::gpu::wgpu; + let device = (|| { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = lightcraft_engine::gpu::backend::window_backends(); + desc.backend_options = lightcraft_engine::gpu::backend::backend_options(); + let instance = wgpu::Instance::new(desc); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; + pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("test window"), ..Default::default() })).ok() + })(); + let (device, queue) = device?; + let (w, h) = (5usize, 3usize); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: w as u32, height: h as u32, 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 | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let texels: Vec = (0..w * h).flat_map(|i| [i as u8 * 10, 100, 200, 255]).collect(); + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + &texels, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w as u32 * 4), rows_per_image: Some(h as u32) }, + wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 }, + ); + let (mut app, work, ctx) = fixture(); + app.renderer.set_screen_textures(Box::new(TestScreen(device, queue, freed))); + Some((app, work, ctx, lightcraft_engine::media::ScreenFrame { texture, width: w, height: h })) +} + +/// A headless screenshot (driven by the control channel: `keep_pixels`) of a view drawn straight +/// from the GPU has its pixels. Before, a mid-drag `ui.screenshot {"headless": true}` showed the +/// photo as a white rectangle: the GPU-resident draft left no CPU copy (review of PR #1065). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_headless_screenshot_reads_back_a_view_drawn_from_the_gpu() { + let Some((mut app, work, ctx, frame)) = gpu_drawn_fixture(Default::default()) else { + lightcraft_testkit::skip!(Gpu, "no GPU adapter"); + return; + }; + let (w, h) = (frame.width, frame.height); + assert!(app.renderer.keep_pixels); + let job = app.session.render_job(PhotoId(1), 64, 64, false, true).unwrap().draft(); + app.renderer.request(Slot::Main, job, 100); + let (slot, job) = take_job(&work); + let mut result = job.run(); + result.frame = Some(frame); + finish(&mut app, &work, &ctx, slot, result); + let t = app.renderer.textures.get(&Slot::Main).unwrap(); + assert_eq!(t.id(), egui::TextureId::User(7), "the draft is drawn from the GPU"); + assert!(t.pixels.is_none()); + let cpu = app.renderer.cpu_textures(); + let shot = cpu.get(&egui::TextureId::User(7)).expect("the headless screenshot has the view's pixels"); + assert_eq!(shot.image.size, [w, h]); + assert_eq!(shot.image.pixels[4], egui::Color32::from_rgb(40, 100, 200)); +} + +/// Releasing a slot (a zoomed loupe leaving its window, a Compare region) lets go of its +/// GPU-resident texture too, which can be window-sized (review of PR #1065: it was kept until +/// the slot was drawn from the GPU again). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn releasing_a_slot_frees_its_gpu_texture() { + let freed = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let Some((mut app, work, ctx, frame)) = gpu_drawn_fixture(freed.clone()) else { + lightcraft_testkit::skip!(Gpu, "no GPU adapter"); + return; + }; + let job = app.session.render_job(PhotoId(1), 64, 64, false, true).unwrap().draft(); + app.renderer.request(Slot::Main, job, 100); + let (slot, job) = take_job(&work); + let mut result = job.run(); + result.frame = Some(frame); + finish(&mut app, &work, &ctx, slot, result); + assert_eq!(app.renderer.textures.get(&Slot::Main).map(|t| t.id()), Some(egui::TextureId::User(7))); + assert!(freed.lock().unwrap().is_empty()); + app.renderer.release(Slot::Main); + assert_eq!(*freed.lock().unwrap(), vec![egui::TextureId::User(7)], "the window's texture is freed"); + assert!(app.renderer.natives.is_empty() && app.renderer.native_frames.is_empty()); +} + fn relink_destination() -> std::path::PathBuf { let path = std::env::temp_dir().join(format!("lc-render-relinked-{}-{}.nef", std::process::id(), lightcraft_preview::next_tick())); std::fs::write(&path, b"replacement source").unwrap(); @@ -355,7 +590,7 @@ fn completed_failure_keeps_requested_source_after_relink() { let replacement = relink_destination(); for slot in [Slot::Thumb(PhotoId(1)), Slot::Main, Slot::Before, Slot::Compare(1), Slot::Region] { let (mut app, work, ctx) = fixture(); - app.session.media.file_loader = Some(Arc::new(|_, _| Err("simulated decode failure".into()))); + app.session.media.file_loader = Some(Arc::new(|_, _, _| Err("simulated decode failure".into()))); let job = app.session.render_job(PhotoId(1), 64, 64, false, true).unwrap(); app.renderer.request(slot, job, 100); let (submitted, job) = take_job(&work); @@ -381,7 +616,7 @@ fn completed_failure_keeps_requested_source_after_relink() { fn superseded_failure_does_not_take_the_new_requests_source() { let replacement = relink_destination(); let (mut app, work, ctx) = fixture(); - app.session.media.file_loader = Some(Arc::new(|_, _| Err("simulated decode failure".into()))); + app.session.media.file_loader = Some(Arc::new(|_, _, _| Err("simulated decode failure".into()))); let slot = Slot::Main; let old_job = app.session.render_job(PhotoId(1), 64, 64, false, true).unwrap(); app.renderer.request(slot, old_job, 100); @@ -564,7 +799,7 @@ fn resizing_the_disk_cache_keeps_textures_and_skips_rebuilds() { #[test] fn a_panicking_render_is_a_failure_not_a_dead_worker() { let (mut app, _, ctx) = fixture_with(Session::new(), (*photo()).clone()); - app.session.media.file_loader = Some(Arc::new(|_, _| panic!("decoder bug"))); + app.session.media.file_loader = Some(Arc::new(|_, _, _| panic!("decoder bug"))); app.renderer.offload = None; // the real job pool let slot = Slot::Thumb(PhotoId(1)); let ask = |app: &mut crate::LightcraftApp| { @@ -800,7 +1035,7 @@ fn library_reset_rejects_old_job_even_when_photo_id_and_key_are_reused() { let photo = app.session.catalog.photo(PhotoId(1)).unwrap().as_ref().clone(); app.session = lightcraft_engine::Session::new(); app.session.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); - app.session.media.file_loader = Some(Arc::new(|_, _| { + app.session.media.file_loader = Some(Arc::new(|_, _, _| { let mut image = lightcraft_raster::Rgb32f::new(8, 8); image.data.fill([0.1, 0.2, 0.9]); Ok((image, Default::default())) diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index d9705fdbdb..4401d5d179 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -31,6 +31,7 @@ mod empty_library; mod error_kinds; mod filmstrip; mod filmstrip_drag; +mod find_similar; mod focus_point; mod folder_drop; mod grading; diff --git a/crates/ui-egui/src/tests/compare.rs b/crates/ui-egui/src/tests/compare.rs index f570df33a8..0baffa06b6 100644 --- a/crates/ui-egui/src/tests/compare.rs +++ b/crates/ui-egui/src/tests/compare.rs @@ -405,6 +405,39 @@ fn survey_command_click_takes_the_photo_out() { assert_eq!((sel(&h), active(&h)), (vec![a], Some(a)), "the last photo stays in the survey"); } +/// Hover photo `id`'s survey tile, as a person does, so its × appears; then click the × in its corner. +fn click_x(h: &mut Headless, id: u64) { + let name = format!("cull:{id}"); + let tile = h.app.widgets.iter().find(|(w, _)| *w == name).map(|(_, r)| *r).expect("the tile is laid out"); + h.app.synthetic.push(egui::Event::PointerMoved(tile.center())); + h.settle(SETTLE); + click_with(h, egui::pos2(tile.right() - 16.0, tile.top() + 16.0), egui::Modifiers::NONE); +} + +/// The × in a survey tile's corner takes the photo out of the survey. It shows while the pointer is +/// over the tile, and it must stay while the pointer is on the × itself (#1639, #3614): the tile +/// loses its hover to the ×, and an × tied to that hover vanished before the click landed. +#[test] +fn survey_x_takes_the_photo_out() { + let mut h = demo(); + let [a, b, c] = survey_of_three(&mut h); + click_x(&mut h, c); + let sel: Vec = h.app.session.selection.ids.iter().map(|p| p.0).collect(); + let active = h.app.session.selection.active.map(|p| p.0); + assert_eq!((sel, active), (vec![a, b], Some(b)), "the photo whose × was clicked left the survey; the active one stays active"); +} + +/// The × on the active survey photo takes it out too, and the last remaining photo becomes active, +/// as a ⌘/Ctrl-click on it does. +#[test] +fn survey_x_on_the_active_photo_activates_the_last_one() { + let mut h = demo(); + let [a, b, c] = survey_of_three(&mut h); + click_x(&mut h, b); + let sel: Vec = h.app.session.selection.ids.iter().map(|p| p.0).collect(); + assert_eq!((sel, h.app.session.selection.active.map(|p| p.0)), (vec![a, c], Some(c))); +} + /// ⌘/Ctrl-click on the active survey photo while others remain: it leaves, and the last /// remaining photo becomes active, so the keys still act on a photo on screen. #[test] diff --git a/crates/ui-egui/src/tests/find_similar.rs b/crates/ui-egui/src/tests/find_similar.rs new file mode 100644 index 0000000000..b75995a1ca --- /dev/null +++ b/crates/ui-egui/src/tests/find_similar.rs @@ -0,0 +1,301 @@ +//! Find Similar Photos reads every photo of the library the first time, which left the window not +//! responding for as long as that took (issue #3468): the photos are read on a worker thread under a +//! row of the activity stack. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::mpsc::Receiver; +use std::time::{Duration, Instant}; + +use lightcraft_catalog::{Op, Photo, PhotoId, Source}; +use lightcraft_raster::Rgb32f; +use serde_json::{Value, json}; + +use crate::find_similar::LABEL; +use crate::headless::Headless; +use crate::state::ViewMode; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(60); +const PHOTOS: u64 = 12; +/// How long a read waits for a drive that isn't opened, and how long the frames may take while it does. +const GUARD: Duration = Duration::from_secs(20); +const FRAMES: Duration = Duration::from_secs(15); + +/// The photos' files: a read waits for `open` (a slow drive), at most `guard`, and is counted, as +/// are the reads made on the UI thread. +struct Drive { + open: Arc, + reads: Arc, + on_ui: Arc, +} + +fn app_on_a_slow_drive(guard: Duration) -> (Headless, Drive) { + let mut app = LightcraftApp::new(lightcraft_engine::Session::new(), Services { png: None, ..Default::default() }); + for i in 0..PHOTOS { + let path = format!("/drive/IMG_{i:04}.arw"); + let p = Photo::new(PhotoId(i + 1), Source::File { path }, &format!("IMG_{i:04}.arw"), "ARW", 64, 64, "2026-01-01T00:00:00"); + app.session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + let drive = Drive { open: Arc::new(AtomicBool::new(false)), reads: Arc::new(AtomicUsize::new(0)), on_ui: Arc::new(AtomicUsize::new(0)) }; + let (ui, open, reads, on_ui) = (std::thread::current().id(), drive.open.clone(), drive.reads.clone(), drive.on_ui.clone()); + let deadline = Instant::now() + guard; + app.session.media.file_loader = Some(Arc::new(move |path: &str, _, _| { + // (the grid reads the photos for its thumbnails too, on threads of its own) + let thread = std::thread::current(); + if thread.name().is_some_and(|n| n.starts_with("similar-") || n.contains(LABEL)) { + reads.fetch_add(1, Ordering::SeqCst); + } + if thread.id() == ui { + on_ui.fetch_add(1, Ordering::SeqCst); + } + // (a hang guard: the read goes on after it, so a regression fails the test instead of hanging it) + while !open.load(Ordering::SeqCst) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(1)); + } + // even photos get brighter to the right, odd ones downwards + let across = path.bytes().rfind(u8::is_ascii_digit).is_some_and(|d| d % 2 == 0); + let image = Rgb32f::from_fn(64, 64, |x, y| { + let v = if across { x } else { y }; + [v as f32 / 64.0; 3] + }); + Ok((image, Default::default())) + })); + (Headless::new(app, [1200.0, 800.0], 1.0), drive) +} + +fn rows(h: &Headless) -> Vec { + h.app.session.activity.list().into_iter().filter(|r| r.kind == "similar").collect() +} + +/// The row's wait is over once the task has gone. +fn until_done(h: &mut Headless) { + assert!(h.step_until(T, |h| h.app.tasks.is_empty()), "the search never ended"); +} + +fn ask(h: &mut Headless) -> Receiver { + h.send("engine.execute", json!({"command": "library.findSimilar", "params": {"id": 1}})).unwrap() +} + +fn answer(h: &mut Headless, rx: &Receiver) -> Value { + let t0 = Instant::now(); + loop { + h.step(); + if let Ok(v) = rx.try_recv() { + return v; + } + assert!(t0.elapsed() < T, "never answered"); + std::thread::sleep(Duration::from_millis(1)); + } +} + +/// The issue's report: from the menu, the command answers at once while the files are read, the +/// window takes its frames, the row counts and can stop, and the grid shows what was found. +#[test] +fn a_search_from_the_menu_reads_off_the_ui_thread_and_the_window_goes_on() { + let (mut h, drive) = app_on_a_slow_drive(GUARD); + h.app.ui.view = ViewMode::Detail; + let t0 = Instant::now(); + let r = h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); + assert_eq!(r, json!({"background": true, "count": PHOTOS})); + for _ in 0..3 { + h.step(); + } + // nothing has been read yet: the command and the frames waited for none of it + assert!(t0.elapsed() < FRAMES, "the window waited for the files: {:?}", t0.elapsed()); + assert_eq!(h.app.session.filter, Default::default(), "no answer before the files are read"); + let row = &rows(&h)[0]; + assert_eq!(row.label, LABEL); + assert_eq!(row.total, PHOTOS); + assert!(row.cancellable, "the row can stop the search"); + + drive.open.store(true, Ordering::SeqCst); + until_done(&mut h); + assert_eq!(drive.on_ui.load(Ordering::SeqCst), 0, "a file was read on the UI thread"); + assert_eq!(drive.reads.load(Ordering::SeqCst), PHOTOS as usize); + assert!(rows(&h).is_empty(), "the row goes with the search"); + let shown = h.app.session.filter.only.len(); + assert_eq!(shown, PHOTOS as usize / 2, "the photos alike are shown"); + assert_eq!(h.app.ui.view, ViewMode::PhotoGrid); + let toast = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(toast.starts_with(&format!("{shown} similar photos")), "{toast}"); +} + +/// One search at a time: the menu row is off while one runs and on again after it, and a second +/// request is refused without touching the first. +#[test] +fn a_second_search_waits_for_the_first() { + // what the menu bar draws the row from + let row_is_on = |h: &Headless| crate::menus::menu_entries(&h.app).into_iter().find(|e| e.id == "library.findSimilar").is_some_and(|e| e.enabled); + let (mut h, drive) = app_on_a_slow_drive(GUARD); + assert!(row_is_on(&h)); + h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); + assert!(!row_is_on(&h), "the row is off while one runs"); + let e = h.app.run("library.findSimilar", json!({"id": 2})).unwrap_err(); + assert!(e.contains("already running"), "{e}"); + assert_eq!(rows(&h).len(), 1); + drive.open.store(true, Ordering::SeqCst); + until_done(&mut h); + assert!(row_is_on(&h)); + assert!(h.app.session.filter.only.contains(&PhotoId(1)), "the first search answered"); +} + +/// ✕ on the row: the view stays as it was, nothing is said, and the next search doesn't read again +/// what was read. +#[test] +fn stopping_leaves_the_view_alone_and_the_next_search_reads_only_the_rest() { + let (mut h, drive) = app_on_a_slow_drive(GUARD); + h.app.ui.view = ViewMode::Detail; + h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); + // stopped while the searched photo is being read: that one read is all it does + assert!(h.step_until(T, |_| drive.reads.load(Ordering::SeqCst) == 1), "the first read never started"); + h.app.session.activity.cancel(rows(&h)[0].id).unwrap(); + drive.open.store(true, Ordering::SeqCst); + until_done(&mut h); + assert!(rows(&h).is_empty()); + assert_eq!(h.app.session.filter, Default::default()); + assert_eq!(h.app.ui.view, ViewMode::Detail); + assert!(h.app.ui.toast.is_none(), "{:?}", h.app.ui.toast); + assert_eq!(drive.reads.load(Ordering::SeqCst), 1); + + let r = h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); + assert_eq!(r["count"], PHOTOS - 1, "what was read isn't read again"); + until_done(&mut h); + assert_eq!(drive.reads.load(Ordering::SeqCst), PHOTOS as usize); + assert_eq!(h.app.session.filter.only.len(), PHOTOS as usize / 2); +} + +/// Nothing to read: the answer comes on the next frames, with no photo read. +#[test] +fn a_search_of_what_is_known_reads_nothing() { + let (mut h, drive) = app_on_a_slow_drive(Duration::ZERO); + drive.open.store(true, Ordering::SeqCst); + h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); + until_done(&mut h); + let reads = drive.reads.load(Ordering::SeqCst); + let r = h.app.run("library.findSimilar", json!({"id": 2})).unwrap(); + assert_eq!(r["count"], 0); + until_done(&mut h); + assert_eq!(drive.reads.load(Ordering::SeqCst), reads); + assert!(h.app.session.filter.only.contains(&PhotoId(2))); +} + +/// A refusal comes at once and starts nothing (no photo active, a photo the library doesn't have). +#[test] +fn a_search_that_cannot_start_leaves_no_row() { + let (mut h, drive) = app_on_a_slow_drive(Duration::ZERO); + assert!(h.app.run("library.findSimilar", json!({"id": 999})).is_err()); + assert!(h.app.run("library.findSimilar", json!({"id": "x"})).is_err()); + assert!(h.app.tasks.is_empty()); + assert!(rows(&h).is_empty()); + assert_eq!(drive.reads.load(Ordering::SeqCst), 0); +} + +/// A searched photo that can't be read says so where the person is. +#[test] +fn a_photo_that_cannot_be_read_says_so() { + let (mut h, _) = app_on_a_slow_drive(Duration::ZERO); + h.app.session.media.file_loader = Some(Arc::new(|path: &str, _, _| Err(format!("{path}: gone")))); + h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); + until_done(&mut h); + let toast = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(toast.contains("can't read the photo"), "{toast}"); + assert_eq!(h.app.session.filter, Default::default()); +} + +/// A control request is answered when the search ends, with the command's `{photos}`, and the window +/// takes its frames meanwhile. An agent's view isn't switched for it. +#[test] +fn a_control_request_is_answered_when_the_search_ends() { + let (mut h, drive) = app_on_a_slow_drive(GUARD); + h.app.ui.view = ViewMode::Detail; + let t0 = Instant::now(); + let rx = ask(&mut h); + for _ in 0..3 { + h.step(); + } + assert!(t0.elapsed() < FRAMES, "the frames waited for the files: {:?}", t0.elapsed()); + assert!(rx.try_recv().is_err(), "no answer before the files are read"); + assert_eq!(rows(&h).len(), 1); + drive.open.store(true, Ordering::SeqCst); + let reply = answer(&mut h, &rx); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(reply["result"]["photos"][0]["id"], 1, "{reply}"); + assert_eq!(reply["result"]["photos"].as_array().unwrap().len(), PHOTOS as usize / 2, "{reply}"); + assert_eq!(drive.on_ui.load(Ordering::SeqCst), 0); + assert_eq!(h.app.ui.view, ViewMode::Detail); + assert!(h.app.ui.toast.is_none(), "{:?}", h.app.ui.toast); +} + +/// `activity.cancel` stops the search; the request is told so. +#[test] +fn stopping_answers_the_request_with_an_error() { + let (mut h, drive) = app_on_a_slow_drive(GUARD); + let rx = ask(&mut h); + for _ in 0..3 { + h.step(); + } + let id = rows(&h)[0].id; + let r = h.request("engine.execute", json!({"command": "activity.cancel", "params": {"id": id}}), T); + assert_eq!(r["ok"], true, "{r}"); + drive.open.store(true, Ordering::SeqCst); + let reply = answer(&mut h, &rx); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().is_some_and(|e| e.contains("stopped")), "{reply}"); + assert_eq!(h.app.session.filter, Default::default()); +} + +/// A request that comes while a search runs is refused at once, not left to wait. +#[test] +fn a_second_request_is_refused_at_once() { + let (mut h, drive) = app_on_a_slow_drive(GUARD); + let first = ask(&mut h); + for _ in 0..3 { + h.step(); + } + let second = ask(&mut h); + let refused = answer(&mut h, &second); + assert_eq!(refused["ok"], false, "{refused}"); + assert!(refused["error"].as_str().is_some_and(|e| e.contains("already running")), "{refused}"); + drive.open.store(true, Ordering::SeqCst); + assert_eq!(answer(&mut h, &first)["ok"], true); +} + +/// A caller whose request timed out asks again: what was read stays known, so it isn't read again. +#[test] +fn a_request_nobody_waits_for_any_more_leaves_what_it_read() { + let (mut h, drive) = app_on_a_slow_drive(Duration::ZERO); + drive.open.store(true, Ordering::SeqCst); + drop(ask(&mut h)); + // (a frame takes the request and starts the search) + h.step(); + until_done(&mut h); + let reads = drive.reads.load(Ordering::SeqCst); + assert_eq!(reads, PHOTOS as usize); + let rx = ask(&mut h); + assert_eq!(answer(&mut h, &rx)["ok"], true); + assert_eq!(drive.reads.load(Ordering::SeqCst), reads); +} + +/// Another library was opened: the search stops, and neither its answer nor what it read reaches the +/// new library. +#[test] +fn another_library_stops_the_search_and_gets_nothing_from_it() { + let (mut h, drive) = app_on_a_slow_drive(GUARD); + let rx = ask(&mut h); + for _ in 0..3 { + h.step(); + } + let dir = std::env::temp_dir().join(format!("lc-ui-similar-other-{}", std::process::id())); + h.app.session.open_library(&dir, false).unwrap(); + h.step(); + drive.open.store(true, Ordering::SeqCst); + let reply = answer(&mut h, &rx); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().is_some_and(|e| e.contains("another library")), "{reply}"); + let read = drive.reads.load(Ordering::SeqCst); + assert!(read < PHOTOS as usize, "it stopped reading: {read}"); + assert!(h.app.session.signatures.is_empty()); + assert_eq!(h.app.session.filter, Default::default()); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/ui-egui/src/tests/lifecycle_037.rs b/crates/ui-egui/src/tests/lifecycle_037.rs index d994b93001..7b51cb3feb 100644 --- a/crates/ui-egui/src/tests/lifecycle_037.rs +++ b/crates/ui-egui/src/tests/lifecycle_037.rs @@ -609,7 +609,7 @@ fn hidden_slideshow_pauses_and_keeps_its_remaining_time() { let tex = ctx.load_texture(format!("slide-{}", id.0), egui::ColorImage::filled([2, 2], egui::Color32::WHITE), Default::default()); app.renderer.textures.insert( Slot::Slide(Item::Photo(id)), - Tex { look: None, key: 0, photo: id, tex, size: [2, 2], histogram: None, ms: 0.0, quick: None, pixels: None }, + Tex { look: None, key: 0, photo: id, tex, native: None, size: [2, 2], histogram: None, ms: 0.0, quick: None, pixels: None }, ); } let first = app.ui.slideshow.as_ref().unwrap().play.current(); diff --git a/crates/ui-egui/src/tests/preview_limit.rs b/crates/ui-egui/src/tests/preview_limit.rs index 1b8c37212f..ce5a5aba42 100644 --- a/crates/ui-egui/src/tests/preview_limit.rs +++ b/crates/ui-egui/src/tests/preview_limit.rs @@ -588,7 +588,7 @@ mod in_the_loupe { // Given soft proofing against an output-device profile (rendered on the CPU even with a GPU), a // drag drafts small (#330); proofs into an output space run on the GPU like any render #[test] - fn a_soft_proofed_drag_drafts_small() { + fn a_drag_soft_proofed_to_a_device_profile_drafts_small() { // the GPU device up front (the loupe never waits for it): with one, this is the case where // the GPU is there and the render still goes to the CPU let _ = lightcraft_engine::gpu::available(); @@ -601,6 +601,24 @@ mod in_the_loupe { assert!(main <= small, "the draft is {main} px, a small one at most {small}"); } + // Given soft proofing into a colour space (the GPU renders it), a drag drafts as it does + // without the proof: at full size where the GPU draws the view (review of PR #1065: it + // drafted small, as if the proof went to the CPU) + #[test] + fn a_drag_soft_proofed_into_a_colour_space_drafts_full_size_on_the_gpu() { + let gpu = lightcraft_engine::gpu::available(); + let (_fx, mut h, _) = detail(); + assert_eq!(h.app.ui.proof.profile, 0, "a colour space, no device profile"); + h.app.ui.soft_proof = true; + h.settle(SETTLE); + let (main, small) = drag_exposure(&mut h); + if !gpu { + lightcraft_testkit::skip!(Gpu, "no GPU: every drag drafts small"); + return; + } + assert!(main > small, "the draft is {main} px, a small one would be at most {small}"); + } + fn tile(h: &Headless, slot: Slot) -> Option<(usize, usize)> { h.app.renderer.textures.get(&slot).map(|t| (t.size[0], t.size[1])) } @@ -1211,7 +1229,7 @@ mod in_the_loupe { .iter() .enumerate() .filter_map(|(i, c)| match &c.shape { - egui::epaint::Shape::Mesh(m) if m.texture_id == tex.tex.id() => Some((i, c.clip_rect, m.calc_bounds())), + egui::epaint::Shape::Mesh(m) if m.texture_id == tex.id() => Some((i, c.clip_rect, m.calc_bounds())), _ => None, }) .collect() diff --git a/crates/ui-egui/src/tests/quit_unsaved.rs b/crates/ui-egui/src/tests/quit_unsaved.rs index f703c24a67..bdfb3550a9 100644 --- a/crates/ui-egui/src/tests/quit_unsaved.rs +++ b/crates/ui-egui/src/tests/quit_unsaved.rs @@ -164,3 +164,51 @@ fn damaged_settings_file_is_shown() { h.step(); assert!(!has(&h, "button:noticeOk")); } + +/// A change the catalog log's thread accepted but hadn't written yet (a drive that takes a moment, +/// then fails) is not taken for saved: the quit check waits for the thread, finds the failure and +/// saves everything with the closing snapshot before the window may close (review of #3557). It +/// used to read only the failure the thread had already reported, and close with the change in +/// no file. +#[test] +fn quitting_waits_for_what_the_log_thread_has_not_written_yet() { + use lightcraft_catalog::fault::{self, Step}; + let dir = std::env::temp_dir().join(format!("lc-ui-quit-log-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = lightcraft_engine::Session::new(); + s.open_library(&dir, true).unwrap(); + let id = s.catalog.photos().map(|p| p.id).min().unwrap(); + fault::install( + &dir, + Arc::new(|step| { + if step == Step::Write { + std::thread::sleep(Duration::from_millis(400)); + return Err(std::io::Error::other("the drive is gone (test)")); + } + Ok(()) + }), + ); + let app = LightcraftApp::new(s, Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + let r = h.request("engine.execute", json!({"command": "photo.flag", "params": {"flag": "reject", "ids": [id.0]}}), T); + assert_eq!(r["ok"], true, "{r}"); + let closes = crate::panels::notices::may_close(&mut h.app); + let prompt = h.app.quit_prompt.as_ref().map(|p| p.text().to_string()); + // the files alone, as the next start reads them, hold the change + let copy = dir.with_extension("copy"); + let _ = std::fs::remove_dir_all(©); + std::fs::create_dir_all(©).unwrap(); + for f in [lightcraft_catalog::journal::SNAPSHOT, lightcraft_catalog::journal::LOG] { + if dir.join(f).exists() { + std::fs::copy(dir.join(f), copy.join(f)).unwrap(); + } + } + let (_, c, _) = lightcraft_catalog::Journal::open(Box::new(lightcraft_catalog::store::FsStore::open(©).unwrap())).unwrap(); + let saved = c.photo(id).map(|p| p.flag); + fault::remove(&dir); + drop(h); + let _ = std::fs::remove_dir_all(©); + let _ = std::fs::remove_dir_all(&dir); + assert!(!closes || saved == Some(lightcraft_catalog::Flag::Reject), "closed with the flag in no file: {saved:?}"); + assert!(closes, "the closing snapshot saved it, so the window may close: {:?} {saved:?}", prompt); +} diff --git a/crates/ui-egui/src/tests/zoom.rs b/crates/ui-egui/src/tests/zoom.rs index ebe3ecd22f..518bd477af 100644 --- a/crates/ui-egui/src/tests/zoom.rs +++ b/crates/ui-egui/src/tests/zoom.rs @@ -70,7 +70,18 @@ fn a_pending_crop_or_rotation_does_not_reuse_the_old_textures_aspect() { let tex = h.view.ctx.load_texture("old loupe", egui::ColorImage::filled([4, 3], egui::Color32::BLACK), Default::default()); h.app.renderer.textures.insert( Slot::Main, - Tex { look: Some((old_look, true)), key: 0, photo: id, tex, size: [64, 48], histogram: None, ms: 0.0, quick: None, pixels: None }, + Tex { + look: Some((old_look, true)), + key: 0, + photo: id, + tex, + native: None, + size: [64, 48], + histogram: None, + ms: 0.0, + quick: None, + pixels: None, + }, ); edit(&mut h, |d| d.crop.geometry.rect = lightcraft_geom::Rect::new(0.25, 0.2, 0.75, 0.2 + 1.0 / 3.0)); for (rotate, expected) in [(false, egui::vec2(32.0, 16.0)), (true, egui::vec2(16.0, 32.0))] { diff --git a/docs/background-tasks.md b/docs/background-tasks.md index 0c9281dfc2..6f2b003477 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -61,6 +61,7 @@ guard.detail(&file_name); | Face scan, AI Denoise | `crates/engine/src/cmd/face_recognize.rs`, `crates/engine/src/denoise.rs` | a continuous job with no ✕, kept in session state | | Find Missing Photos | `crates/ui-egui/src/tasks.rs` | a generic background task with a row (`kind: Some(..)`) | | Reload from Disk | `crates/ui-egui/src/reload.rs`, `crates/engine/src/cmd/reload.rs` | a command split into plan / probe / apply so the app reads the files on a worker thread (`tasks::spawn_tracked`: progress and `Cancel::Flag`); the result is committed through `Session::execute_fn` (undo step, save, XMP auto-write), and dropped for a photo a later-started reload has already updated; `wait: true` runs it in place | +| Find Similar Photos | `crates/ui-egui/src/find_similar.rs`, `crates/engine/src/cmd/similar.rs` | a command split into plan / measure / apply, whose reads are kept when it is stopped; a control request is answered when it ends (`Outcome::Later`) | | Reading focus points | `crates/engine/src/focus_scan.rs` | a worker paced by the UI's per-frame pump (`focus.pump {pace}`); `Cancel::Flag`; commits in batches without undo steps | ## Testing diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9c086e5c6f..43ff7a7175 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -89,7 +89,7 @@ filmstrip is visible. | `engine.commands` | — | Engine + UI commands: id, label, menu, shortcut, params doc, enabled | | `ui.menu.list` | — | Menu entries (flat: id, label, menu path, shortcut, enabled) | | `ui.menu.tree` | — | The menu bar as shown (File … Help): items `{id, params?, label, shortcut?, enabled, checked?}`, separators, submenus — the model behind the native macOS menu bar and the in-window menus | -| `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why — see `docs/gpu-pipeline.md`), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file; OK = `button:noticeOk`), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight as the activity stack in the top-left corner shows it, same shape as `activity.list`; a row appears once its task is 0.5 s old, ids `activity:row:`, ✕ = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | +| `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why, `gpuWindowDevice` / `screenTextures` / `mainOnGpu` = renders run on the window's device / can be drawn from the GPU / the loupe shows one now — see `docs/gpu-pipeline.md`), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file; OK = `button:noticeOk`), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight as the activity stack in the top-left corner shows it, same shape as `activity.list`; a row appears once its task is 0.5 s old, ids `activity:row:`, ✕ = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | | `ui.widgets` | `{filter?}` | On-screen widgets `{id, rect: [x, y, w, h]}` (screen points) | | `ui.clickWidget` / `ui.dragWidget` / `ui.hoverWidget` | `{id, count?, button?, fx?, fy?}` (`button: "right"` right-clicks; `count` is capped at 16) / `{id, toX?, toY?, dx?, dy?, steps?}` (steps are capped at 1000) / `{id, fx?, fy?}` | Real egui input on a widget (hover: the pointer rests on it, e.g. for preset/profile previews). `fx`/`fy` are fractions of the registered rect and may lie outside `[0,1]`; the resulting point must still be inside egui's clipped interaction rect, and a non-finite fraction or resolved point is rejected before any input is queued. Geometry comes from the latest completed layout; if the widget moves before the first event or before a press, or its latest clipped rect no longer contains the point, the request fails with an error instead of clicking another widget or retargeting. A target below an ordinary modal dialog may succeed as a no-op or a backdrop click, because egui routes that input to the dialog; a target covered by a non-modal overlay fails. The blocking library-problem/launch-list window is explicit: its dim takes the modal layer, but a background target fails instead of reporting a no-op success, and only that window's own controls (`button:library…`) pass. Its creation frame is shielded and redrawn with empty input like a prompt's, so background text/pointer input cannot act while the new modal areas settle. A quit prompt or settings notice is a real egui modal scope with a foreground backdrop. Only its own buttons (`button:quit…`, `button:noticeOk`) accept a `ui.clickWidget`; background targets fail, and background keystrokes, text/clipboard input, wheel/zoom input and AccessKit actions are dropped before panels see them. The prompt itself takes Tab/Shift+Tab, Enter/Space on the focused button, and Escape/Enter for the safe default Cancel; AccessKit Focus/Click works when targeted at a prompt button. Its first creation frame (including a Tasks→Unsaved or notice→next-notice transition) is shielded and redrawn with empty input, so a press/release in that frame, or a held press from before it, cannot act underneath it; a synthetic drag already in progress is canceled. Once settled, raw `ui.click`/`ui.drag`/`ui.pointer` and backdrop clicks are still delivered to the prompt backdrop as no-ops, and the prompt's own button clicks work normally. The area/layer check cannot see a different widget covering the point in the same layer. A `ui.clickWidget` whose widget disappears before its release also fails, after canceling the pointer press without a click or drag (the same rules apply when a click spans several host frames) | | `ui.move` / `ui.click` / `ui.drag` | `{x, y, count?, button?}` / `{x, y, toX, toY, steps?}` | Raw pointer input, screen points (the same click and step caps apply). In every pointer and scroll gesture a number other than `count` and `steps` must lie between −1,000,000 and 1,000,000, or the request is refused and queues nothing | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d54b897309..4372518e5b 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (lossy DNG export; Render to DNG as an export format) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (LR-PROF-IMPORT: the user's own `.dcp` camera profiles import; Render to DNG as an export format) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 Every format Lightroom reads or writes, with our support, fidelity and tests. Camera raw formats are deep enough to have their own document: [raw-parity.md](raw-parity.md). @@ -48,7 +48,7 @@ import and export formats. Ours come from `crates/codecs/src/sniff.rs`, `crates/ | EXIF / IPTC / XMP embedded on export | ✅ | ✅ with metadata filters | `crates/meta` | | Develop presets `.xmp` | ✅ | ✅ import (mapping of supported settings) | | | Legacy presets `.lrtemplate` | ✅ (converted) | ✅ import | | -| Camera / creative profiles (`.dcp`, `.xmp` profiles) | ✅ | ⬜ deliberately (Adobe profile formats are never used); `.cube` LUT profiles ✅ | | +| Camera / creative profiles (`.dcp`, `.xmp` profiles) | ✅ | 🟡 the user's own `.dcp` camera profiles import (`profile.import`) and replace a raw file's colour model; none ship with the app; `.xmp` profiles ⬜; `.cube` LUT profiles ✅ | | | Lens profiles `.lcp` | ✅ | ⬜ deliberately | | | Other apps' presets | — | ✅ Luminar `.lmp` / `.mplumpack`, `.zip` bundles | beyond target | | Lightroom Classic catalog `.lrcat` | native | 🟡 import (ratings, flags, labels, keywords, collections, virtual copies, supported develop settings; read-only pure-Rust SQLite incl. WAL) | [lightroom-catalog-import.md](lightroom-catalog-import.md) | @@ -75,6 +75,7 @@ Remaining: **26–47 h** (AVIF decode 8–15 h if a permissive decoder is writte | Date | Change | Summary | |---|---|---| +| 2026-10-12 | minor | LR-PROF-IMPORT: the user's own DNG camera profiles (`.dcp`) import as camera profiles; none ship | | 2026-10-10 | major | Created from the code and the installed Lightroom's document types | | 2026-10-10 | minor | JPEG XL export (#247): JXL write ✅ (native only), PQ JPEG XL HDR | | 2026-10-12 | minor | Render to DNG: "Rendered DNG" export format (linear 16-bit float DNG of the rendered photo) | diff --git a/docs/gaps.md b/docs/gaps.md index 535479fa10..566786a5f0 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps: where LightCraft falls short of Lightroom -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-29 · **Change:** minor (gap 1: the Canon EOS D60 is the first chart-calibrated model, its matrices from our own ColorChecker shots give its white balance a Kelvin scale; gap 20: Canon CRW decodes; LR-LIB-VIRTUALCOPY: default number exhaustion is validated before copy creation; gap 8: lens profile work is tracked in #329; gap 8: lensfun's lens database offered on the first launch and downloaded on request, looked up for the library; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; typed GPS input now rejects malformed coordinates before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in coordinates, elevations and timestamps; malformed references error; CDATA stays literal; ranked gaps unchanged; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; import: checked rename-sequence exhaustion; import review: remembered thumbnail size and density-aware previews (#2237, part of #2056); pre-import loupe/keyboard culling remains open; no ranked gap closes; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 9: CI runs the tests on Linux x64 since #2667; macOS, Windows and the GPU equivalence tests still don't; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 8: Sony ILCE-7RM6 in-file distortion conversion extends to the APS-C ILCE-6700; LR-META-EXIF-FULL rejects extra EXIF clock components and preserves date fallbacks; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; JPEG ICC APP2 sequence validation; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 24: extreme brush segments skip the intermediate dabs; **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-20 · **Change:** minor (gap 15: Print Page Options — page numbers, page info, crop marks) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-05 · **Change:** minor (Contrast and Blacks calibrated in process V4, #523; PERF-STEP-STALL: flags, ratings and edits never wait for the drive; before: gap 1: the Canon EOS D60 is the first chart-calibrated model, its matrices from our own ColorChecker shots give its white balance a Kelvin scale; gap 20: Canon CRW decodes; LR-LIB-VIRTUALCOPY: default number exhaustion is validated before copy creation; gap 8: lens profile work is tracked in #329; gap 8: lensfun's lens database offered on the first launch and downloaded on request, looked up for the library; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; typed GPS input now rejects malformed coordinates before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in coordinates, elevations and timestamps; malformed references error; CDATA stays literal; ranked gaps unchanged; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; import: checked rename-sequence exhaustion; import review: remembered thumbnail size and density-aware previews (#2237, part of #2056); pre-import loupe/keyboard culling remains open; no ranked gap closes; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 9: CI runs the tests on Linux x64 since #2667; macOS, Windows and the GPU equivalence tests still don't; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 8: Sony ILCE-7RM6 in-file distortion conversion extends to the APS-C ILCE-6700; LR-META-EXIF-FULL rejects extra EXIF clock components and preserves date fallbacks; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; JPEG ICC APP2 sequence validation; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 24: extreme brush segments skip the intermediate dabs; **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-20 · **Change:** minor (gap 15: Print Page Options — page numbers, page info, crop marks) Every known shortfall, one entry each, ranked by user impact (how many Lightroom users hit it, and how hard it blocks them), then by effort. **Agents pick work from the top** (the first entry nobody is @@ -17,7 +17,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app |---:|---|---|---|---:|---| | 1 B | **Camera colour is estimated, not measured** (LR-PROF-CAMERACOLOR). Raws start from a per-file fit to the camera JPEG, 10 bundled profiles, 52 spectral matrices (plus same-sensor bodies, e.g. the X-T30 through the X-T3) or chart-measured matrices (the EOS D60); others use a neutral matrix (a black-and-white camera JPEG gives its tone curve only, #577; dark JPEG tones also guide the toe, #1307) | ΔE vs camera JPEG 2.9–10 after fitting (raw-parity.md); 1 chart-calibrated model (EOS D60: its Kelvin scale and fallback colour, the look stays the JPEG fit) vs 1,500 Adobe Standard profiles | every raw shooter sees colour that is close but not Lightroom's; some get neutral-matrix colour | 50–90 | [raw-parity](raw-parity.md#colour) | | 2 B | **CR3 variants no public file uses** (LR-IMP-FORMATS): `crx.rs` refuses vertical-tile C-RAW, partial-subband and other plane coding, multi-tile 0x200 and adaptive low-frequency gains, and those files fall back to the preview. All 110 CC0 CR3s on raw.pixls.us (31 folders) decode from sensor data, so none of these variants has a public sample; 26 CR3 bodies are verified (M50 / R100 / R8 exact, R5 Mark II pinned, 22 more pinned on one CC0 file each and checked against the camera JPEG, [cr3.md](cr3.md#further-bodies-one-cc0-file-each)). HEIF stills are `.HIF` files, not CR3; no CR3 sRAW / mRAW sample exists | measured: Canon's share whose camera fully works 73% → 94% (raw-parity.md); 18 of 22 popular Canon bodies write CR3, all 18 now verified | +0.3 points of photographers; the variants surface only as user files that open as a preview | 10–25 | [raw-parity](raw-parity.md#remaining-work-ranked-by-photographers-unlocked-per-hour) | -| 3 B | **Render fidelity unmeasured** (LR-BEHAV-RENDER-FIDELITY): tone, highlights, texture / clarity / dehaze, NR and sharpening are tuned by eye | no side-by-side suite; a retune needs a new process version (only V1 exists) | edits imported from Lightroom look different; the look "isn't Lightroom's" | 30–60 | [raw-parity](raw-parity.md), [process-versions](process-versions.md) | +| 3 B | **Render fidelity partial** (LR-BEHAV-RENDER-FIDELITY): calibrated camera-look Contrast and Blacks; other operators need measurement | process V3 reduces held-out response error from 0.136 to 0.038 stops for Contrast and 0.424 to 0.077 for Blacks on one Sony camera; Whites remains V2 pending a follow-up | imported Lightroom edits still differ, especially on uncalibrated operators and cameras | 30–60 | [calibrated Light operators](light-v3.md), [process versions](process-versions.md) | | 4 | ~~Original-pixel detail at 100%~~ (LR-VIEW-ZOOM): closed 2026-10-12, see Closed recently | checklist row ✅ | — | 0 | [ui-parity](ui-parity.md) | | 5 B | **AI masks: Subject, Sky, People, Background, Landscape** are heuristics; Object / Describe run SAM 3 but its download has no mirror configured | `crates/segment`; ai-masks.md; MASK rows 67% | masking is how most Lightroom users edit today | 40–70 + model decision | [target-app-parity](target-app-parity.md#ai) | | 6 B | **Compressed ORF** (every Olympus / OM body since ~2008) | measured: 66 of 78 Olympus / OM models preview-only; `orf.rs` refuses; OM bucket 3% of photographers, 3% of them fully work | +2.6 points; best gain per hour of any raw gap (~0.2) | 8–15 | [raw-parity](raw-parity.md#compressed-orf-a-clean-room-starting-point) (the two Olympus patents that describe the method) | @@ -40,7 +40,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 22 | **Pen pressure on macOS / Linux tablets** (brush size and flow follow pressure where winit reports a pen force), OS monitor profiles on Windows (Linux reads colord's, macOS the screen's), follow-window colour on Linux / Windows | hardware-parity.md | brush users with tablets; multi-monitor setups | 11–22 | [hardware-parity](hardware-parity.md) | | 24 | **Brush live preview and masking feel** (#517, #518); Feather / Edge mask refinement (15.5) | issues | masking feels slower than Lightroom; extreme brush segments now skip the intermediate dabs | 8–12 | [ui-parity](ui-parity.md) | | 25 | **File writes**: AVIF import; Render to DNG as a catalog command (lossy DNG and the Render to DNG export format landed) (PSD export landed with Edit in PhotoCraft, #953) | file-format-parity.md | interchange edge cases | 19–34 | [file-format-parity](file-format-parity.md) | -| 26 | **Performance at scale**: 85k-photo library opens in 1.7–4.7 s; 100k grid test pending; colour NR at half resolution; at 100k photos stack and album lookups are indexed (an "In a Stack" or "Album" smart album counts in ~14 ms, was 0.6–2.7 s) | ROADMAP log, gpu-pipeline.md | large-catalog users | 15–30 | [target-app-parity](target-app-parity.md#by-dimension) | +| 26 | **Performance at scale**: flags, ratings and edits are written and synced to the catalog log by a thread of its own, so a key never waits for a busy drive (a 300 ms sync: 0.2 ms per flag, was 305 ms), and a write that fails is held, retried and counted as unsaved, never dropped (PERF-STEP-STALL); 85k-photo library opens in 1.7–4.7 s; 100k grid test pending; colour NR at half resolution; at 100k photos stack and album lookups are indexed (an "In a Stack" or "Album" smart album counts in ~14 ms, was 0.6–2.7 s) | ROADMAP log, gpu-pipeline.md | large-catalog users | 15–30 | [target-app-parity](target-app-parity.md#by-dimension) | | 27 | **Windows / Linux runtime coverage**: the Windows x64 installer is verified on Windows 11 (0.9.1: install and upgrade end on the completion page, a custom folder is kept, Launch works, removal is clean), but uninstalling from Settings → Apps ends with no confirmation (#892, #931); GPU path proven on Apple and on one AMD GPU on Linux (Radeon 8060S, Vulkan); NVIDIA, Intel and DX12 unverified; Windows DirectComposition VRR workaround implemented, monitor verification pending; the Linux riscv64 tarball (new in 0.6.0, #844) is cross-compiled and never run beyond a QEMU smoke test | ROADMAP, issues, `release.yml` | non-Mac users find bugs first | 13–27 | [hardware-parity](hardware-parity.md) | | 29 | **HDR merge leftovers** (LR-MERGE-HDR): AI Denoise doesn't run on merged (linear) DNGs; JPEG brackets are treated as linear (no camera response curve); every frame is held as 32-bit float, ~0.86 GB per 67 MP frame (half-float frames would halve it) | tested on Sony A7R VI brackets 2026-10-14 ([merge.md](merge.md)); Lightroom's Denoise supports HDR DNGs | HDR shooters who denoise their merges, merge JPEGs, or merge 7+ frames of high-resolution raws on 16 GB machines | 10–20 (+ denoise linear-RGB contract, gap 11) | [merge](merge.md) | | 28 | **Small Classic shortcuts and keys**: Tab / ⇧Tab (hide the side panels / all panels; Tab moves the keyboard focus here) and F5. Rating `[` `]`, flag cycling (`` ` ``), `\` (Filter Bar), ⌘L (Enable Filters), ⌘⌥⇧C / ⌘⌥⇧V (Copy / Paste Metadata), F1 help, F6 / F7 / F8 (filmstrip, left panel, right panel) are bound; the grid-cycle key is shown beside both grid rows in View (#2500) | [ui-parity](ui-parity.md#shortcuts) | Classic muscle memory | 2–4 | [ui-parity](ui-parity.md) | @@ -90,6 +90,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | PERF-STEP-STALL: the catalog log is written and synced off the UI thread, so stepping and flagging never wait for the drive (a 300 ms sync: slowest flag 0.2 ms, was 305 ms); a failed write is held and retried, counted as unsaved, never dropped; gap 26 not closed | | 2026-10-28 | minor | Gap 8 shrinks: the desktop app offers lensfun's lens database (CC BY-SA, pinned) once on the first launch and downloads it on request and looks the library's raws up when it arrives; validation, a profile picker and own calibration remain | | 2026-10-23 | patch | Gap 8: the Sigma 10–18 mm on the ILCE-6700 gets a measured lens exception at 10–10.5 mm (0.55 px worst over 99 photos, was about 1.4 px) | | 2026-10-29 | minor | Import thumbnails render when the camera JPEG is too small, retaining preview-only/error fallbacks; import review: remembered thumbnail size and density-aware previews (#2237, part of #2056); pre-import loupe/keyboard culling remains open; no ranked gap closes | @@ -128,6 +129,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-12 | minor | Gap 10: SR2/SRF folder discovery fixed; F828 imports as preview-only. Sensor decoding remains a gap; readiness scores unchanged | | 2026-10-23 | minor | Gap 28: ⌘L / Ctrl+L (Library ▸ Enable Filters) puts the filter aside and brings it back as it was; the entry drops ⌘L; hours unchanged | | 2026-10-15 | minor | Gap 28: `\` shows / hides the Filter Bar in the grids; the entry drops `[` `]` (#509), flag cycling (#1490) and F1 (Help), already on main; ⌘L is the filter-bar key left; hours unchanged | +| 2026-10-12 | minor | Measured Contrast and Blacks calibration; Whites and broader fidelity remain open | | 2026-10-16 | patch | Gap 13: catalog VIDEO records match the Videos filter, including after reimport of older records (#1940, filter issue only). Video playback, frame previews and folder-sync discovery remain outside this repair; no gap closed or counts changed. | | 2026-10-14 | minor | Gap 26: at 100k photos stack and album lookups are indexed, so an "In a Stack" or "Album" smart album counts in ~14 ms (was 0.6–2.7 s); open time unchanged | | 2026-10-14 | minor | Gap 10: Camera-coverage sweep (#1327): 30 models verified on 40 CC0 files (coverage.py 515 → 545 verified); sensor verification does not establish colour parity (#1277) | diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index a35218c46d..6e063e6f90 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -8,6 +8,11 @@ CPU fast guided-filter allocation measurements and reproduction commands are doc [guided-filter-memory.md](guided-filter-memory.md). That optimization retains the full-size base and does not change the GPU's coefficient buffers. +Process V4's camera-look Contrast and Blacks share the CPU's generated lookup tables and +ProPhoto matrices. `finish.wgsl::light_ops` applies them after V2's Whites tone curve and +before the colour stage. Full frames and render windows use the same pointwise operators; +see [calibrated Light operators](light-v3.md) for HDR rules and limits. + Warped geometry uses a CPU-computed coverage bit mask for the source boundary. The CPU reference evaluates that boundary in double precision; GPU float rounding otherwise can turn a blank edge pixel into a photo pixel. The mask @@ -49,6 +54,21 @@ Overrides (read once at launch): - `LIGHTCRAFT_GPU=0`: GPU rendering off for the process (the window is unaffected). - Both `LIGHTCRAFT_GPU=0` and `LIGHTCRAFT_GPU_BACKEND=off` also keep AI Denoise, the face models and the AI mask model (SAM 3 on Metal) on the CPU. +- `LIGHTCRAFT_GPU_ADAPTER=` (any case, e.g. `4070`, `radeon`, `"rtx 4070 super"`): + the graphics card for GPU rendering, AI Denoise and the face models, on a machine with more than one + (`backend::pick_adapter`). Of the hardware cards whose name contains it, the one whose whole name it + is wins, then dedicated before built-in before virtual cards, then wgpu's order + (`backend::choose_named_adapter`); the log says which when several match (`… matches 2 graphics + cards (…): using …`). Software renderers (WARP, llvmpipe) never: a name that matches only one is + logged as such. A name that matches no card is logged + (`gpu: LIGHTCRAFT_GPU_ADAPTER=… names none of the graphics cards (…); using the default choice`) and + the default high-performance card is used. Each line is logged once, though the render device, AI + Denoise and the face models each ask. Each of those makes its own wgpu instance and device, so + devices on different cards share no buffer, pipeline or queue. The window keeps the card wgpu picks for it by power preference, and + rendering runs on a device of its own on the chosen card (the photo is copied to the window's card). + Rendering shares the window's device when the variable is unset or names the window's card + (`backend::may_adopt_window_device`). The log's `gpu: LIGHTCRAFT_GPU_ADAPTER=…: using …` line names the card + used. Handy to keep test runs or a long export off the card the screens hang on. - `LIGHTCRAFT_GPU_ALLOW_SOFTWARE=1`: accept a software adapter (llvmpipe / lavapipe, WARP), which is otherwise refused because the CPU pipeline is faster. For running the GPU tests on a machine without a GPU (below); the app never sets it. @@ -152,7 +172,18 @@ walks the drive. ## Where it is used - `lightcraft_engine::media::develop` (called by every `RenderJob`): loupe / before / compare views, `render_now` (CLI, MCP, control channel renders) and exports render on the GPU when one is - available; grid/filmstrip thumbnails (many small jobs in parallel) stay on the CPU. + available. Thumbnails (grid, filmstrip, preset and profile previews, faces) render on the GPU + once the device is ready (`lightcraft_gpu::ready()`) and on the CPU until then, so they never + wait for device creation at startup. Six workers rendering 256 px thumbnails: 3.6 ms each on an + RTX 5070 vs 4.3–5.2 ms on 32 CPU threads (`crates/gpu/tests/it/thumbs_bench.rs`), and the cores stay + free for raw decoding. +- 8-bit renders take the GPU path with LUT profiles (the `.cube` table rides in the kernel's + `aux` buffer, trilinear like `Lut3d::apply`, after grain), masks with Refine Edges (the cross + guided filter of Auto Mask, blended by √refine before the mask's invert and amount) and soft + proofs into a colour space (proof-space gamut mapping and both gamut warnings, into an output + space or a display). These render on the CPU: high-bit-depth exports and Visualize HDR (both + need float output), soft proofs to an output device's profile (a printer or paper profile), and + photos with a content-aware Fill spot (no GPU kernel for it). - Anything the GPU path cannot do returns `None` and the CPU renders instead: no adapter (CI machines, software-only adapters), `LIGHTCRAFT_GPU=0` or `LIGHTCRAFT_GPU_BACKEND=off` (whole process; see [Backends](#backends-environment-variables-and-troubleshooting-issue-136)), the `app.gpu {enabled}` @@ -178,10 +209,17 @@ walks the drive. (log luminance, dark channel, guided-filter steps, white balance, luminance / colour NR, airlight sampling), `mask` (linear / radial / luminance / colour range / brush shapes, combine, finalize), `finish` (the whole per-pixel stage) — each mirrors a named CPU function. +- Defringe (`fringe_lab`, a separable lightness `minmax` filter, `fringe_apply`; parameters from + `optics::defringe_params`) and spot removal (`spot` module, spot by spot in place: `spot_prep`, + the Heal tone correction as two device Gaussians, `spot_apply`; Remove's 48 candidate sources are + scored by `spot_score` and only the scores are read back; layout and candidates from + `spots::{layout, candidates, ring_dirs, score_radii, rank}`) run on the device in `lin_cpu`'s + order. The histogram is counted on the device (`hist`, atomics, the same sampling grid as + `Histogram::of_srgb8`, so it is exact). - Soft proofing against an output space (`RenderRequest::proof`, with its destination and display gamut warnings) runs in `finish`; a proof against an output-device profile (its 3D table) renders on the CPU. -- Per-stage hybrid: defringe and spot removal (rare, CPU-only for now) download the resampled image, - run on the CPU and upload; heuristic mask shapes (Sky, Subject, Background, …) and brushes of more +- Per-stage hybrid: the camera's local tone mapping (ProRAW gain tables, off by default) runs the + scene-linear stage on the CPU and uploads; heuristic mask shapes (Sky, Subject, Background, …) and brushes of more than 4096 dabs are evaluated on the CPU and uploaded; sources over the buffer limit are resampled on the CPU. - Stage cache: `GpuStages` mirrors `StageCache` (same keys: source identity + `geo`, `lin_key`, @@ -247,7 +285,8 @@ thread. A render's *own* reason comes from `lightcraft_gpu::try_render` (`Err(Fa passes on as `RenderResult::gpu_fallback`; an export carries it as `Exported::gpu_fallback`, and each file of an `app.export` batch result has `gpuFallback` when its render fell back (issue #675). **Reproducing a smaller GPU:** `LIGHTCRAFT_GPU_LIMITS=webgpu` (or `downlevel`) creates the device -with 128 MiB storage bindings / 256 MiB buffers, `LIGHTCRAFT_GPU_LIMITS=` with n MiB / 2n MiB. +with 128 MiB storage bindings / 256 MiB buffers, `LIGHTCRAFT_GPU_LIMITS=` with n MiB / 2n MiB; +the window's device, when adopted, is capped the same way. Tests inject failures with `lightcraft_gpu::inject_fault` (`crates/gpu/tests/it/fallback.rs`, `export_falls_back_to_the_cpu_when_gpu_work_is_lost`). The fault is thread-local, and so are its consequences: a simulated fatal failure stops GPU use on the injecting thread only (`available()` @@ -348,6 +387,38 @@ most likely the largest kernel (`finish.wgsl`) alone (not timed per kernel). wgp opens its own; a refused kernel still means no GPU. The `gpu:` info log line gives the kernel count and build time. +## Drawing renders straight from the GPU +The desktop app creates the window's wgpu device with the adapter's limits and hands it to the GPU +renderer (`lightcraft_gpu::adopt_window_device`, on a background thread at startup: the kernels +build there; the crash sentinel covers it), so rendering and drawing share one device. A slider +drag's drafts of the views (Detail, Before, the zoomed window, hover, Compare, the second window) +are then marked `RenderJob::on_screen`: the render ends in an `Rgba8Unorm` texture +(`lightcraft_gpu::render_display` → `Output::Display`) that egui-wgpu draws as a native texture +(`ScreenTextures` in `ui-egui`, implemented by the app) - no readback, no conversion to egui's +pixels, no re-upload. The per-render checks run on the device instead: every pixel written (an +atomic count), not entirely black (the device histogram). Rows are re-laid at a 256-byte stride +for the texture copy when the width needs it. + +Renders that need pixels keep the readback: the settled full-quality render after a drag (the cached +view preview, overlays, screenshots), thumbnails, exports, overlays (Visualize Spots, mask +overlays), windows that spots grew (cut on the CPU), a monitor profile (corrected on the CPU), and +anything the GPU path declines. A device that doesn't suit (software adapter, too few storage +buffers, kernels that don't build there) makes the renderer create a device of its own, as before. +A headless `ui.screenshot` (the control channel keeps CPU copies of what is drawn) taken while a +view shows a GPU-resident draft reads that texture back for the picture (`ScreenTextures::read`, +`lightcraft_gpu::read_texture`); drawing never does. + +- `LIGHTCRAFT_GPU_WINDOW=0`: never adopt the window's device (a device of its own, renders read + back) - to compare, or for a driver that misbehaves with compute and drawing on one device. +- `ui.inspect` → `perf.gpuWindowDevice` (renders run on the window's device), `perf.screenTextures` + (the UI can draw GPU-resident renders), `perf.mainOnGpu` (the loupe shows one now). +- Measured (RTX 5070, DX12, a 45 MP CR3, 90 exposure steps of a drag at 30 Hz): the loupe's draft + render 1.69 ms median from the texture vs 2.05 ms with the readback; the UI thread unchanged + within noise (~1 ms). The difference grows with the loupe's size (4K/5K displays, zoom). +- With the renderer on the window's device, errors the device raises outside a render (the window's + own included) are logged and stop GPU rendering (CPU from then on) instead of wgpu's default + panic. + ## Opening a photo (M5.4) - The loupe shows a stand-in at once (`media::QuickJob`): the photo's cached view render for its current settings, else (raws with their import look) the embedded camera JPEG, else a @@ -389,10 +460,8 @@ A view's stages keep an uploaded source only up to 96 MB (a Preview-level source 2.5–2.6 GB → 0.91–0.96 GB, heap peak 930 → ~600 MB; stepping median ~13 ms (unchanged). ## Open items -- Keep the loupe texture on the GPU (render into an `egui-wgpu` texture on eframe's device instead of - reading back); share the device with eframe. - WebGPU in the browser build (async init, single device per canvas). -- Defringe and spot removal kernels; Sky/Subject heuristics (replaced by the segmenter in M12). +- Sky/Subject heuristics (replaced by the segmenter in M12); the ProRAW local tone map. - Tiling for sources / outputs beyond the buffer limit (24 MP+ on WebGPU-default limits, 60 MP+ on most desktop adapters; these render on the CPU now): tile with overlap equal to the largest filter radius, with global values (airlight) from a first pass. @@ -400,4 +469,3 @@ A view's stages keep an uploaded source only up to 96 MB (a Preview-level source faster path for exports. - Large-radius blurs at full size (dehaze dark channel at 24 MP) dominate the export: a summed-area table or a downsampled dark channel would cut them further. -- GPU histogram (atomics) to skip the CPU pass over the readback. diff --git a/docs/light-v3.md b/docs/light-v3.md new file mode 100644 index 0000000000..3f97a4b391 --- /dev/null +++ b/docs/light-v3.md @@ -0,0 +1,187 @@ +# Calibrated Contrast and Blacks + +> **Last updated:** 2026-10-13 · **Change:** minor (preserve exact evaluation for luminance mixes) + +Process V4 calibrates global Contrast and Blacks on the camera-look path: a raw with +`SourceInfo::camera_tone`. Contrast acts per channel. Blacks blends a per-channel result with +luminance scaling. Whites in V4 behaves exactly as V2, for positive and negative amounts. +Whites calibration is a planned follow-up. + +This is the Contrast and Blacks split of the original V4 calibration work. The serialized +number is defined by the `Process::V4` arm in `Process::version()`; callers use the enum. +Open PR #944 also proposes V4 and V4, #1283 proposes V4 for Dehaze, and #1286 follows #1283. +Maintainers must assign the final process numbers and inheritance in merge order. V4 here +inherits V2 only. + +Raw files without a camera curve, rendered sources such as JPEG and TIFF, and local mask +adjustments keep their V2 operators. This process does not change decoding, source metadata, +smart-preview formats, library opening, or Update and Reset checks. + +## Render order + +The camera tone curve uses V2 Whites with Contrast and Blacks set to zero. The renderer +maps luminance through that curve, applies its chroma scaling and highlight desaturation, +then applies calibrated Contrast followed by calibrated Blacks, before the colour stage. +When both calibrated sliders are zero, no new operator or colour conversion runs. With any +Whites value and both calibrated sliders at zero, the result is byte-identical to V2. +Combined edits use V2 Whites before the two calibrated operators. + +The operators convert linear Rec.2020 to linear ProPhoto RGB (D50, with Bradford white-point +adaptation), encode values with the sRGB transfer curve, apply the fitted curves, and convert +back. The matrices come from `RgbSpace::to_space`. CPU `finish.rs` and GPU `finish.wgsl` use +the same matrices and operator tables. CPU previews compose per-channel operations into +tables indexed by linear input. The computation is pointwise, so a render window needs +no whole-photo measurement. + +## Operator family + +For a slider amount `a` between -100 and 100, with `t = abs(a) / 100`: + +- Positive amounts use `F_a(v) = v + s_pos(t) * D_pos(v)`. +- Negative amounts use `F_a(v) = max(0, v - s_neg(t) * D_neg(v))`. +- Each displacement shape is piecewise linear on 12 knots: 0, .02, .05, .09, .14, .2, .28, + .38, .5, .65, .82 and 1. Both shapes satisfy `D(1) = 0`. Contrast also fixes `D(0) = 0`. +- The amount law is `s(t) = ((1 - exp(-t / tau)) / (1 - exp(-1 / tau)))^q`, with separate + fitted `tau` and `q` for each sign. Zero amount is the identity. + +Contrast applies `F` to each encoded ProPhoto channel. For Blacks, the luminance result +scales linear RGB by `F(Y) / Y`, where the linear ProPhoto luminance coefficients are +`[0.2880402, 0.7118741, 0.0000857]` and `F(Y)` includes encoding and decoding. Blacks blends +that result with the per-channel result in linear light, using one fitted weight per sign. + +Each active operator has 1024 table entries over encoded values between 0 and 1. The entries +store linear output and are interpolated linearly. A running maximum prevents a fitted +curve from reversing tone order. Neither shipped fit folds back. Non-finite amounts are +skipped, and finite amounts are clamped to the slider range. + +When the resolved per-channel weight is exactly one or zero in f32, the renderer selects +only the per-channel or luminance operation. In particular, negative Blacks is per channel. +For 8-bit CPU renders, per-channel Contrast and Blacks share one table with 16,384 intervals +over linear input. If any operator uses luminance, the renderer retains the original +evaluation for every operator, including Contrast before positive Blacks. Preview renders +use the existing sRGB encoding table and the source operator tables without the additional +linear-input approximation. U16 and F32 exports retain the original operator tables and +exact sRGB encoding. Metal retains the original tables too. + +Camera chroma scaling can create mixed-sign ProPhoto components from nonnegative source +pixels. Their luminance terms can nearly cancel. A small Contrast approximation error can +then cross the `1e-6` luminance cutoff or be amplified by `F(Y) / Y`. A scalar interpolation +error bound does not bound the rendered error after this scaling. Exact evaluation avoids +introducing this disagreement with the earlier CPU path and Metal. It retains their +pre-existing rounding differences near the cutoff. + +### HDR and gamut limits + +A per-channel component above 1 passes unchanged. A component below zero keeps its distance +below the image of zero. Luminance scaling leaves a pixel unchanged when its luminance is +above 1 or at most `1e-6`. Otherwise it scales the entire pixel, including components above +1. Blacks blends these two results, so an above-white component can move when the pixel's +luminance is below white. The functions are continuous at white. HDR tone mapping and +Whites retain V2's behavior. GPU renders use 8-bit previews; high-bit-depth exports use the +CPU. These are numerical rules, not measured Lightroom HDR parity. + +## Fit provenance and reproduction + +The coefficients were fitted to black-box observations of the owner's Lightroom exports: +16-bit sRGB exports of Sony ILCE-7CR photos, paired with the same photo's Neutral or another +slider amount exported in the same batch. Only exported pixels were used. No Adobe code, +profiles, tables or application assets were used. The photos were split into tune photos +used for fitting and check photos held out for measurement. + +| Slider | Fit | Mode | Tune | Check | +|---|---|---|---|---| +| Contrast | `v2-contrast-pc` | Per channel | 155 pairs, 20 photos | 61 pairs, 6 photos | +| Blacks | `v2-blacks-mix` | Per-channel/luminance mix | 148 pairs, 19 photos | 60 pairs, 6 photos | + +The exports and the optimizer that reads them remain private. Public tools in this change +contain the operator family, sanitized fits with coefficients and aggregate errors, and the +generator. Fit files contain no photo names, paths or per-photo values. Their provenance +records the original fit filename and SHA-256. The Rust constants record each sanitized +fit's SHA-256 as well. + +The sanitizer omits error groups and individual bands with fewer than three distinct +contributing photos. Published rows record the distinct photo counts for the group and its +retained bands. Repeated pairs from one photo do not satisfy the threshold. Coefficients +and overall counts remain available. These omissions do not change the fits or the full +paired agreement measurements below. + +```sh +python3 -m pip install -r tools/requirements-light-v3.txt +python3 tools/light_v3_constants.py rust +python3 tools/light_v3_constants.py rust --check +``` + +`--check` must reproduce `crates/pipeline/src/light_v3_params.rs` byte for byte. The generator +writes reference outputs from `tools/light_v3_family.py` to 12 significant digits, avoiding +platform-dependent final bits in NumPy. Rust tests compare the port against those references. +`sanitize` accepts only Contrast and Blacks fits and writes their public aggregate form. +`python3 -m unittest discover -s tools -p 'test_light_v3_constants.py'` checks the publication +threshold with synthetic inputs and scans all committed fit files. + +## Measured agreement + +The private agreement harness compares the log2-luminance response of each export pair with +LightCraft's response to the same two recipes. The reported error, in stops, is the mean over +rows (amount, reference and size) of the median over photos. Both builds use the same photos; +a registration rejected in either run is omitted from the paired comparison. The historical +V2 baseline is main at `76b53778`. The six check photos were not used to fit the operators. + +| Slider | V2 tune | Calibrated tune | V2 check | Calibrated check | +|---|---:|---:|---:|---:| +| Contrast | 0.168 | 0.059 | 0.136 | 0.038 | +| Blacks | 0.540 | 0.112 | 0.424 | 0.077 | +| Whites | 0.176 | 0.176 | 0.075 | 0.075 | + +Contrast and Blacks values are the source calibration's measured results, reproduced by +this split's verification. Whites uses V2. A single camera and one person's photos do not +establish fidelity across cameras. Blacks still has larger errors in the darkest band. +Exposure, Highlights, Shadows, Whites and other operators need further work. Local +adjustments and sources without a camera curve have no new calibration. + +## Cost and stability + +Each active operator has a 4 KiB source table, at most 8 KiB for both. CPU previews also +build one composed table of 128 KiB when all active operators are per channel. Each of its +16,384 intervals stores an intercept and slope. The composed per-channel path uses three +lookups per pixel and two colour matrix multiplications. A luminance mix builds no composed +table. It evaluates the original encoding and source tables, luminance scaling and blend. +There is no extra image pass, source read, per-photo state or statistic. Zero Contrast and +Blacks skip the new work. Metal and high-bit-depth CPU exports allocate only the source tables. + +Release measurements on an M3 Max used two Rayon threads and nine interleaved samples per +case against main `701f78ea` and round 2 `41074392`. The two public raw files were from a +Sony ILCE-7M3 and Nikon D750. Fit used a 2560-pixel source preview in a 1920 by 1280 viewport; +1:1 windows used native source pixels in that viewport. Each worker decoded once and warmed +its cache; every timed sample changed exposure. Decode, cache preparation and file encoding +are excluded. + +With Contrast +40 and Blacks -30, CPU wall times were 1.22 to 1.28 times main and 1.01 to +1.024 times round 2. A 27-sample confirmation of the slowest Nikon window case measured +75.33 ms on main, 94.76 ms on round 2 and 96.45 ms here. Its ratio is 1.28 times main and +1.018 times round 2. The fused path remains, with a small measured cost increase in this run. + +With Contrast +40 and Blacks +30, CPU wall times were 1.97 to 2.02 times main and 1.20 to +1.28 times round 2. Blacks +30 alone took 1.61 to 1.64 times main and 1.17 to 1.19 times +round 2. These positive-Blacks cases exceed the approximate 1.25-times-main cost target. +They need the original operator evaluation because the extra preview interpolation can +change the luminance cutoff result or have its error amplified by luminance scaling. + +Metal medians for these settings were 3.25 to 4.97 ms, with the original GPU operators. +CPU neutral controls were 0.99 to 1.00 times main. The general `cargo xtask bench` run also +completed before and after the fix, with no CPU-time regression above its 20% threshold. +Other work on the shared machine was not controlled. These measurements do not establish +tail latency or performance on other GPU backends. + +V1 and V2 keep their rendering and persistent cache keys. Persistent keys from process V4 +on include the process this build actually renders with, so saved settings from a newer +build cannot reuse pixels generated by a different resolved process. V4 keeps V2's +Highlights and Shadows base. New imports and Reset select the latest process; Update to +Current Process remains one undoable settings change and never downgrades a future number. + +## Revision history + +| Date | Change | Summary | +|---|---|---| +| 2026-10-13 | minor | Preserve the original evaluation for luminance mixes, including preceding Contrast, and cover two uniform cutoff regressions | +| 2026-10-13 | minor | Compose CPU preview lookups, preserve exact deep exports, and require three distinct photos per published error aggregate | +| 2026-10-12 | new | Split Contrast and Blacks calibration, preserve V2 Whites and legacy rendering | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 147c90a1eb..4ed88eb44d 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (LR-MASK-LINEAR: masks stay on the photo's content under lens corrections, Upright, Transform and Rotate; LR-IMP-FORMATS: the Canon CRW decoder is the shared craft-libs crate `craft-crw`; LR-PROF-CAMERACOLOR: chart-measured matrices for the Canon EOS D60, its white balance in Kelvin; CRW imports name their camera; LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; LR-LIB-ALBUM: album commands leave out photos the library no longer has and record nothing when they add nothing; LR-BEHAV-DRAGDROP: a right-click on a text field while photos are carried from the grid opens no Cut / Copy / Paste menu; LR-BEHAV-DRAGDROP: a right-click while photos are carried from the grid opens no context menu; LR-LIB-VIRTUALCOPY: default numbering is preflighted across the requested batch and explicit names bypass suffix allocation; LR-BEHAV-DRAGDROP: only the primary button drags photos out of the grid and drops them; KEYC-RATING: deleting a keyword while Enable Filters has the filter put aside no longer leaves an empty one there; LR-BEHAV-DRAGDROP: a drop's destination is named with its parent when another folder or album has the same name; LR-VIEW-FILMSTRIP: photos drag from the filmstrip to the same sidebar targets as from the grid; LRC-LIB-LIBFOLDERS: a deep row's count follows its name in a narrow panel; LR-FILT-FLAG / LRC-LIB-FILTERBAR: the flag toggles combine, Picked + Unflagged, #2588; LR-VIEW-PHOTOGRID, LR-VIEW-FILMSTRIP, LR-VIEW-COMPARE, LR-VIEW-SURVEY, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: the active photo's selection ring shows on light themes and in Compare, Survey and the face tiles, and needs a loaded thumbnail; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-LOCATION: Info GPS text is fully validated before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in point fields; malformed references error; CDATA stays literal; LR-BEHAV-ACCESS: the Thumbnail size control is a slider to screen readers; LR-BEHAV-ACCESS: the Detail photo is named with its file name; LR-VIEW-PHOTOGRID: the grid's empty-view message names its shortcut as this platform writes it and as it is bound; LR-BEHAV-ACCESS: the grid's date headers are named as they read; LR-BEHAV-ACCESS: the sidebar's disclosure triangles name their row; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K Set Keyword Shortcut and ⇧K; KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K Edit Keywords; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-FOLDERS: Local's built-in places (Pictures, Desktop, Downloads, Home) offer no Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; LRC-LIB-CATALOG-SWITCH: a library's catalog.snap or folder given at launch opens that library; LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the dialog makes a new preview each time it opens, also after a failed one, #2708; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-MISSING: `library.missing` from the control channel checks the files on a worker thread instead of the UI thread; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-CROP-AUTO: Auto straighten reads the vertical vanishing point and the horizon; LR-META-EXIF-FULL: reject extra EXIF clock components so invalid capture-time candidates fall through to valid metadata; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-XMP / LRC-MAP-TRACKLOG: malformed ISO times are not projected or matched; LR-IMP-FORMATS: JPEG ICC APP2 chunk validation; LR-BEHAV-TITLEBAR: a dialog leaves the title bar undimmed, as a macOS sheet does; LR-BEHAV-ACCESS: the bars are toolbars and the panels landmarks for screen readers; LR-BEHAV-ACCESS: every dialog and prompt is exposed as a dialog (a modal one, an alert dialog for the prompts); LR-BEHAV-ACCESS: icon-only buttons are named by their label, with the shortcut as the description; MENU-HELP-HELP: on macOS the Help menu is registered with the application only once the menu bar is installed (muda ignores the call before), so AppKit knows which menu is Help; LR-BEHAV-ACCESS: a slider's value field is named ` value`, with how to use it as its description; MENU-BAR: every shortcut the app shows on macOS lists its modifiers ⌃⌥⇧⌘, as the menu bar does; MENU-BAR: on macOS two menu rows that run the same command each get their own native row and label (File ▸ Export… and File ▸ Export with Preset ▸ Custom…; File ▸ New Album… and Photo ▸ Add to Album ▸ New Album…); LR-BEHAV-DIALOGS: a one-line prompt that is refused stays open and says why, and a New Folder on Disk says it was made; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-VIEW-HISTOGRAM: the shadow and highlight clipping buttons take their tile and chevron from the theme, so the chevron reads in every theme; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MASK-BRUSH: extreme brush segments skip the intermediate dabs; LR-MASK-BRUSH: with the mask overlay hidden, the stroke being painted no longer tints the photo) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (LR-PROF-IMPORT: the user's own .dcp camera profiles import, checked on a real D750 profile against Lightroom; before: LRC-DEV-AUTOSYNC: white balance syncs on each photo's own scale, As Shot and Auto per photo; LR-LIB-FLAG: a flag or rating never waits for the drive, PERF-STEP-STALL; LRC-LIB-VISUALSEARCH: Find Similar Photos reads the photos on a worker thread, so a large library no longer freezes the window; LR-MASK-LINEAR: masks stay on the photo's content under lens corrections, Upright, Transform and Rotate; LR-IMP-FORMATS: the Canon CRW decoder is the shared craft-libs crate `craft-crw`; LR-PROF-CAMERACOLOR: chart-measured matrices for the Canon EOS D60, its white balance in Kelvin; CRW imports name their camera; LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; LR-LIB-ALBUM: album commands leave out photos the library no longer has and record nothing when they add nothing; LR-BEHAV-DRAGDROP: a right-click on a text field while photos are carried from the grid opens no Cut / Copy / Paste menu; LR-BEHAV-DRAGDROP: a right-click while photos are carried from the grid opens no context menu; LR-LIB-VIRTUALCOPY: default numbering is preflighted across the requested batch and explicit names bypass suffix allocation; LR-BEHAV-DRAGDROP: only the primary button drags photos out of the grid and drops them; KEYC-RATING: deleting a keyword while Enable Filters has the filter put aside no longer leaves an empty one there; LR-BEHAV-DRAGDROP: a drop's destination is named with its parent when another folder or album has the same name; LR-VIEW-FILMSTRIP: photos drag from the filmstrip to the same sidebar targets as from the grid; LRC-LIB-LIBFOLDERS: a deep row's count follows its name in a narrow panel; LR-FILT-FLAG / LRC-LIB-FILTERBAR: the flag toggles combine, Picked + Unflagged, #2588; LR-VIEW-PHOTOGRID, LR-VIEW-FILMSTRIP, LR-VIEW-COMPARE, LR-VIEW-SURVEY, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: the active photo's selection ring shows on light themes and in Compare, Survey and the face tiles, and needs a loaded thumbnail; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-LOCATION: Info GPS text is fully validated before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in point fields; malformed references error; CDATA stays literal; LR-BEHAV-ACCESS: the Thumbnail size control is a slider to screen readers; LR-BEHAV-ACCESS: the Detail photo is named with its file name; LR-VIEW-PHOTOGRID: the grid's empty-view message names its shortcut as this platform writes it and as it is bound; LR-BEHAV-ACCESS: the grid's date headers are named as they read; LR-BEHAV-ACCESS: the sidebar's disclosure triangles name their row; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K Set Keyword Shortcut and ⇧K; KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K Edit Keywords; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-FOLDERS: Local's built-in places (Pictures, Desktop, Downloads, Home) offer no Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; LRC-LIB-CATALOG-SWITCH: a library's catalog.snap or folder given at launch opens that library; LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the dialog makes a new preview each time it opens, also after a failed one, #2708; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-MISSING: `library.missing` from the control channel checks the files on a worker thread instead of the UI thread; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-CROP-AUTO: Auto straighten reads the vertical vanishing point and the horizon; LR-META-EXIF-FULL: reject extra EXIF clock components so invalid capture-time candidates fall through to valid metadata; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-XMP / LRC-MAP-TRACKLOG: malformed ISO times are not projected or matched; LR-IMP-FORMATS: JPEG ICC APP2 chunk validation; LR-BEHAV-TITLEBAR: a dialog leaves the title bar undimmed, as a macOS sheet does; LR-BEHAV-ACCESS: the bars are toolbars and the panels landmarks for screen readers; LR-BEHAV-ACCESS: every dialog and prompt is exposed as a dialog (a modal one, an alert dialog for the prompts); LR-BEHAV-ACCESS: icon-only buttons are named by their label, with the shortcut as the description; MENU-HELP-HELP: on macOS the Help menu is registered with the application only once the menu bar is installed (muda ignores the call before), so AppKit knows which menu is Help; LR-BEHAV-ACCESS: a slider's value field is named ` value`, with how to use it as its description; MENU-BAR: every shortcut the app shows on macOS lists its modifiers ⌃⌥⇧⌘, as the menu bar does; MENU-BAR: on macOS two menu rows that run the same command each get their own native row and label (File ▸ Export… and File ▸ Export with Preset ▸ Custom…; File ▸ New Album… and Photo ▸ Add to Album ▸ New Album…); LR-BEHAV-DIALOGS: a one-line prompt that is refused stays open and says why, and a New Folder on Disk says it was made; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-VIEW-HISTOGRAM: the shadow and highlight clipping buttons take their tile and chevron from the theme, so the chevron reads in every theme; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MASK-BRUSH: extreme brush segments skip the intermediate dabs; LR-MASK-BRUSH: with the mask overlay hidden, the stroke being painted no longer tints the photo) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -31,7 +31,7 @@ cited here still exists. Formerly docs/parity.md. | C. Views & navigation (VIEW) | 16 | 1 | 1 | 0 | 9/9 (100%) | 4/4 (100%) | | D. Search & filter (FILT) | 11 | 1 | 1 | 0 | 4/4 (100%) | 4/4 (100%) | | E. Metadata (META) | 5 | 1 | 0 | 0 | 2/2 (100%) | 2/2 (100%) | -| F. Edit panel — global adjustments (EDIT) | 43 | 3 | 3 | 1 | 27/28 (96%) | 13/14 (93%) | +| F. Edit panel — global adjustments (EDIT) | 40 | 6 | 3 | 1 | 24/28 (86%) | 13/14 (93%) | | G. Profiles (PROF) | 7 | 1 | 3 | 0 | 3/4 (75%) | 3/3 (100%) | | H. Crop & rotate (CROP) | 10 | 1 | 0 | 1 | 8/8 (100%) | 2/3 (67%) | | I. Remove / healing (REM) | 8 | 1 | 2 | 2 | 4/4 (100%) | 2/3 (67%) | @@ -53,9 +53,9 @@ cited here still exists. Formerly docs/parity.md. | Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 78 | 4 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | | Lightroom Classic extras | 41 | 25 | 21 | 8 | — | 24/26 (92%) | -| **Total** | 420 | 66 | 57 | 35 | 195/203 (96%) | 146/161 (91%) | +| **Total** | 417 | 69 | 57 | 35 | 192/203 (95%) | 146/161 (91%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.4%** of 543 in-scope rows — P0 98.0% of 203 · P1 94.4% of 161 · P2 56.7% of 178. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.1%** of 543 in-scope rows — P0 97.3% of 203 · P1 94.4% of 161 · P2 56.7% of 178. ## Top gaps and shortcut notes @@ -101,7 +101,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-OFFLINE | Keep album offline | P2 | 🚫 | | not applicable: local-first library | | LR-LIB-TARGET | Target album | P2 | ✅ | `cmd:album.setTarget`, `cmd:album.toggleTarget` | see LRC-LIB-COLLECTIONS | | LR-LIB-RATING | Star ratings | P0 | ✅ | `cmd:photo.rate` (`advance`), `cmd:photo.decreaseRating`, `cmd:photo.increaseRating`, `crates/ui-egui/src/shortcuts.rs`, `crates/ui-egui/src/widgets/rating.rs` | one shared star row in the bottom bar, Info panel and filter bar (hover previews, ←/→ on a focused star) and one painter for badges (grid cells, filmstrip, Compare caption); menu rows with star text (Photo ▸ Set Rating, Select By Rating, the grid context menu) are separate menu items, unchanged; 0 clears; 1–5 set; Shift+0–5 applies and advances once, including with Auto Advance. A rating, flag or label that takes the active photo out of the view (filter bar, Picks, smart album) makes the photo after it active (the one before at the end), and Shift / Auto Advance doesn't step past it (#2312). Default grid brackets adjust each photo by one, clamped to 0–5; one batch undo and AutoWrite. Batch grid and undo/redo regressions; macOS native ownership corrected (PR #261) | -| LR-LIB-FLAG | Pick / reject flags | P0 | ✅ | `cmd:photo.pick`, `cmd:photo.reject`, `cmd:photo.unflag`, `cmd:photo.flag` | P pick, X reject, U clear; Shift+P picks and advances in both grids (Presets elsewhere); Shift+X/U and legacy Shift+Z advance; no flag cycle; rejection does not delete the file; a pick shows as a filled flag on thumbnails, in Compare, in the loupe and on the Pick button, a reject outlined (#1013) | +| LR-LIB-FLAG | Pick / reject flags | P0 | ✅ | `cmd:photo.pick`, `cmd:photo.reject`, `cmd:photo.unflag`, `cmd:photo.flag` | P pick, X reject, U clear; a flag or rating never waits for the drive: the catalog log is written and synced by a thread of its own, a failed write is held, retried and counted as unsaved (`crates/catalog/src/log_writer.rs`, PERF-STEP-STALL); Shift+P picks and advances in both grids (Presets elsewhere); Shift+X/U and legacy Shift+Z advance; no flag cycle; rejection does not delete the file; a pick shows as a filled flag on thumbnails, in Compare, in the loupe and on the Pick button, a reject outlined (#1013) | | LR-LIB-LABEL | Colour labels | P1 | ✅ | `cmd:photo.label`, `cmd:photo.clearLabel`, `cmd:label.setNames`, `cmd:label.names`, `cmd:dialog.labelNames`, keys 6–9 in `crates/ui-egui/src/shortcuts.rs` | Photo menu and grid context menu (coloured, named), Info-panel swatches, label dot plus translucent colour on square-grid/filmstrip surrounds and photo-grid footers (photo pixels unchanged); colour-label toasts have pale matching backgrounds; setting/clearing through keys (including Shift), menus or Info swatches shows the same bottom toast as ratings, with the colour/custom name; editable label names (undoable, journaled); no purple key (as in Lightroom), Clear Color Label (`photo.clearLabel`) has no key until one is given in Help → Keyboard Shortcuts, no custom extra labels | | LR-LIB-KEYWORD | Keywords | P0 | ✅ | `cmd:panel.keywords`, `cmd:photo.setMeta` (`addKeywords`/`removeKeywords`), `cmd:keyword.list`, `cmd:keyword.rename`, `cmd:keyword.delete`, `cmd:keyword.merge`, `cmd:keyword.suggest`, `crates/catalog/src/keywords.rs`, `crates/ui-egui/src/panels/left.rs` | left-panel keyword tree with counts (click filters, children included; context menu rename / merge / delete / add / remove); library-wide ops are one undo step and replay from the op log; suggestions (co-occurring / most used / completions) in the Keywords panel; keywords reorganize by drag and drop in the Keyword List (LRC-LIB-KEYWORDS) | | LR-LIB-PEOPLE | People / faces | P2 | 🟡 | `cmd:faces.detect`, `cmd:view.people`, `cmd:view.faceBoxes`, `cmd:photo.removeRegion`, `cmd:photo.setRegion`, `cmd:library.filter`, `crates/ui-egui/src/panels/people.rs`, `crates/catalog/src/query.rs` (`people`), `crates/engine/src/media.rs` (`face_job`), `crates/meta/src/xmp.rs` | MVP: named face regions read from XMP (MWG-RS, read-only, see `docs/xmp-interop.md`; clipped to the photo; Lightroom's `Rotation` of ±π/2 and π handled, mirrored orientations taken as written; boxes follow Rotate Left/Right and flips; a sidecar stating `mwg-rs:Regions`, even empty, replaces the photo's on re-read, one without leaves them) become cards in the People view (View ▸ People, or the People button in the toolbar): a close-up of the person's largest face, name and photo count; a click filters the grid (`person` in `library.filter`, `person:` search token, filter chip). Face boxes in the loupe can be switched off (View ▸ Face Boxes, toolbar) resized with eight drag handles and removed with the × shown on hover (catalog-only and undoable, one undo step per drag; the sidecar is never rewritten for either); no moving a box by dragging it yet. Photo ▸ Detect Faces (`cmd:faces.detect`) finds faces with the YuNet detector (pure Rust, about 200 ms a photo, matches OpenCV's own YuNet on a 45-photo test set; the 232 KB model is a one-time download offered in the same step, never part of LightCraft) and adds them as unnamed boxes; names are suggested from the faces already named (recognition models are opt-in downloads, run on the CPU in a background thread; a face is named only when you confirm it); a person's page shows their cropped faces and the unnamed faces that look like them (LRC-LIB-PEOPLE), with a user-triggered ↑ action or targeted A key to name all shown suggestions at or above one score in one undo step; with recognition on, a background scan finds faces in photos that have none and embeds every face (one to three worker threads, raws through their embedded preview); an Unnamed faces section orders faces by likeness and names a selected group at once; no separated clusters, no manual tagging, no writing regions back | @@ -139,7 +139,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-VIEW-SLIDESHOW | Slideshow | P2 | ✅ | `cmd:view.slideshow` | View ▸ Slideshow (⌥⌘↩): the photos in view full screen from the selected one, played with the library's playback settings (see LRC-SS-PLAYBACK: fades, random order, repeat, previews prepared ahead; `interval` / any setting overrides one run); Space pauses, ←/→ step (a cut), Esc ends; playback controls on pointer movement | | LR-VIEW-SECONDWINDOW | Second display window [Classic] | P2 | ✅ | `cmd:view.secondWindow`, `crates/ui-egui/src/panels/second.rs` | Window ▸ Second Window (⌘F11): the active photo fitted in its own native window with its own render (a floating panel where there are no native windows); loupe view only (no grid / compare / survey there) | | LR-VIEW-CLIPPING | Clipping indicators | P0 | ✅ | `cmd:view.clipping` | | -| LR-VIEW-HISTOGRAM | Histogram | P0 | ✅ | `cmd:view.histogram`, `crates/ui-egui/src/panels/edit/histogram.rs`, `crates/ui-egui/src/panels/right.rs`, `crates/pipeline/src/lib.rs` (`hdr_histogram`) | stays at the top of the Edit panel while its sliders scroll under it (issue #2679, `the_histogram_stays_in_view_while_the_sliders_scroll`); HDR edits: SDR on the left half, the HDR range (0 to 5 stops above SDR white, a fixed scale) on the right with the headroom limit marked; colour bar (white, or Visualize HDR range's colours when that is on) and SDR / HDR labels; the plot's five tonal zones also drag to adjust their Basic control (LRC-DEV-HISTOGRAM-DRAG); it follows slider drags of an HDR edit live (a small render beside the drafts, `Slot::HdrHistogram`) and never drops to the SDR layout mid-drag; an edit with HDR switched off keeps its SDR histogram while it is dragged (#2819); the shadow and highlight clipping buttons at its top corners are the theme's raised fill with a chevron that stands 3:1 on it in every theme and state | +| LR-VIEW-HISTOGRAM | Histogram | P0 | ✅ | `cmd:view.histogram`, `crates/ui-egui/src/panels/edit/histogram.rs`, `crates/ui-egui/src/panels/right.rs`, `crates/pipeline/src/lib.rs` (`hdr_histogram`) | stays at the top of the Edit panel while its sliders scroll under it (issue #2679, `the_histogram_stays_in_view_while_the_sliders_scroll`); HDR edits: SDR on the left half, the HDR range (0 to 5 stops above SDR white, a fixed scale) on the right with the headroom limit marked; colour bar (white, or Visualize HDR range's colours when that is on) and SDR / HDR labels; the plot's five tonal zones also drag to adjust their Basic control (LRC-DEV-HISTOGRAM-DRAG); it follows slider drags of an HDR edit live (a small render beside the drafts, `Slot::HdrHistogram`) and never drops to the SDR layout mid-drag; an edit with HDR switched off keeps its SDR histogram while it is dragged (#2819); turning HDR on or off flows between the layouts (`crates/ui-egui/src/panels/edit/hdr_flow.rs`: the SDR curve squeezes into the HDR layout's SDR section as the HDR section and legend open, and stretches back); the shadow and highlight clipping buttons at its top corners are the theme's raised fill with a chevron that stands 3:1 on it in every theme and state | | LR-VIEW-HDR-DISPLAY | HDR display output | P2 | ⬜ | |, `apps/lightcraft/src/hdr_display.rs` (`choose`, `preferred_hdr_format`) | SDR/HDR decision (platform, surface format, OS headroom, `LIGHTCRAFT_HDR_DISPLAY=0`) is unit-tested and logged at start; always SDR today because eframe configures an 8-bit surface; no OS headroom query yet; | ## D. Search & filter (FILT) @@ -177,13 +177,13 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). |---|---|---|---|---|---| | LR-EDIT-AUTO | Auto settings | P0 | ✅ | `cmd:develop.auto`, `crates/pipeline/src/auto.rs` | a Lightroom-like recipe calibrated black-box on Lightroom's Auto results for 24 Sony raws: Exposure from the scene's scene-linear log-average luminance (Lightroom's observed slope, -0.41 EV per EV), Highlights -66 and Shadows +52 (Lightroom's average Auto values), Contrast +68 and Vibrance +30 fitted on our scales. Held out one photo at a time: on the 16 photos whose start Sony's DRO doesn't brighten, a median dE76 of 6.4 from Lightroom's Auto results against 8.3 unedited; on all 24, 7.7 against 7.9 (issues #318, #209). Calibrated on Sony files only; Whites and Blacks stay 0 | | LR-EDIT-BW | Black & white | P0 | ✅ | `cmd:develop.treatment` | | -| LR-EDIT-HDR-MODE | HDR editing | P2 | ✅ | `cmd:develop.hdr`, `ctl:hdr.maxEv`, `crates/ui-egui/src/panels/edit.rs` (`hdr_row`) | HDR button next to B&W in the Edit panel header, as Lightroom (Visualize HDR and the headroom limit in the Light panel while it's on); see Q. HDR | +| LR-EDIT-HDR-MODE | HDR editing | P2 | ✅ | `cmd:develop.hdr`, `ctl:hdr.maxEv`, `crates/ui-egui/src/panels/edit.rs` (`hdr_row`) | HDR button next to B&W in the Edit panel header, as Lightroom (Visualize HDR and the headroom limit in the Light panel while it's on, sliding open and shut with the histogram's layout change); see Q. HDR | | LR-EDIT-LIGHT-EXPOSURE | Exposure | P0 | ✅ | `ctl:light.exposure` | Alt/Option-drag shows highlight clipping (black, clipped channels in colour) | -| LR-EDIT-LIGHT-CONTRAST | Contrast | P0 | ✅ | `ctl:light.contrast` | | +| LR-EDIT-LIGHT-CONTRAST | Contrast | P0 | 🟡 | `ctl:light.contrast` | From process V4, global Contrast on the camera-look path is fitted per channel in ProPhoto with the sRGB transfer. Check response error 0.136 to 0.038 stops on six held-out Sony photos. Other sources and local adjustments retain V2; broader parity remains unverified (`docs/light-v3.md`). | | LR-EDIT-LIGHT-HIGHLIGHTS | Highlights | P0 | ✅ | `ctl:light.highlights`, `crates/raw/src/highlight.rs` | sensor-clipped highlights stay neutral when Highlights (or Exposure, Whites) darkens them: fully clipped content is rebuilt to the neutral of the colour model applied after it, partly clipped content takes its colour from reliable unclipped content nearby (not from dark objects, lens fringes or another surface beside it) and white where there is none, and pale partly clipped content (a white sky) turns white on its way to clipping (#523); binned previews and thumbnails decide clipping per sample before averaging (`develop_binned_masked`, `highlight::reconstruct_masked`), so a block with one clipped specular sample keeps its mean instead of jumping to the clip level, which reconstruction turned into green speckles at 500 px (#548) From process V2 the Highlights/Shadows base is the edge-aware filter of the 0.15 %-of-long-edge median of log luminance: twigs and fine texture take their surroundings' shift, so bright areas keep their local contrast as with Exposure (V1's base kept ~0.6 of it at −100, #632); region edges stay sharp. Alt/Option-drag shows highlight clipping | | LR-EDIT-LIGHT-SHADOWS | Shadows | P0 | ✅ | `ctl:light.shadows` | From process V2, the same base as Highlights: dark areas keep their local contrast when lifted (#632). Alt/Option-drag shows shadow clipping (white, clipped channels in colour) | -| LR-EDIT-LIGHT-WHITES | Whites | P0 | ✅ | `ctl:light.whites`, `crates/pipeline/src/visualize.rs` | Alt/Option-drag shows highlight clipping (black, clipped channels in colour) | -| LR-EDIT-LIGHT-BLACKS | Blacks | P0 | ✅ | `ctl:light.blacks`, `crates/pipeline/src/visualize.rs` | Alt/Option-drag shows shadow clipping (white, clipped channels in colour) | +| LR-EDIT-LIGHT-WHITES | Whites | P0 | 🟡 | `ctl:light.whites`, `crates/pipeline/src/visualize.rs` | V4 preserves V2 Whites for both signs. Calibration is a planned follow-up; measured V2 check response error is 0.075 stops on the Sony test photos (`docs/light-v3.md`). Alt/Option-drag shows highlight clipping (black, clipped channels in colour) | +| LR-EDIT-LIGHT-BLACKS | Blacks | P0 | 🟡 | `ctl:light.blacks`, `crates/pipeline/src/visualize.rs` | From process V4, global Blacks on the camera-look path uses a fitted per-channel/luminance mix. Check response error 0.424 to 0.077 stops on six held-out Sony photos; deepest tones still differ. Other sources and local adjustments retain V2 (`docs/light-v3.md`). Alt/Option-drag shows shadow clipping (white, clipped channels in colour) | | LR-EDIT-LIGHT-CURVE-PARAM | Parametric curve | P0 | ✅ | `ctl:curve.highlights`, `ctl:curve.lights`, `ctl:curve.darks`, `ctl:curve.shadows`, `ctl:curve.split*`, `crates/pipeline/src/curve.rs` | the graph draws the renderer's own curve model; dragging the line moves the region under the pointer (one undo step) | | LR-EDIT-LIGHT-CURVE-POINT | Point curve | P0 | ✅ | `cmd:develop.curve`, `cmd:curve.reset`, `cmd:curve.presets`, `cmd:curve.applyPreset`, `cmd:curve.savePreset`, `cmd:curve.deletePreset`, `cmd:curve.importPresets`, `cmd:curve.exportPresets`, `cmd:file.importCurvePresets`, `cmd:file.exportCurvePresets`, `crates/engine/src/cmd/curves.rs`, `crates/ui-egui/src/panels/edit.rs` | click to add a point; drag a point in both axes (between its neighbours, input / output readout, one undo step per drag; ⌥-drag moves it a tenth as far for fine adjustment, issue #1363); drag empty space to add and drag; double-click removes; reset: double-click a channel selector (that channel), the Reset button under the graph (every curve incl. parametric) or right-click the graph (channel / all); Point Curve preset dropdown: own Linear / Medium Contrast / Strong Contrast, user presets (save the current point curves, delete by right-click; saved with the library), import / export as `.lccurve` JSON | | LR-EDIT-LIGHT-CURVE-RGB | Per-channel curves | P0 | ✅ | `cmd:develop.curve` (`channel`) | | @@ -204,7 +204,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-EFFECTS-DEHAZE | Dehaze | P0 | ✅ | `ctl:effects.dehaze` | | | LR-EDIT-EFFECTS-VIGNETTE | Post-crop vignette | P0 | ✅ | `ctl:vignette.*`, `crates/pipeline/src/finish.rs`, `crates/ui-egui/src/panels/edit.rs` | style picker (Highlight / Color / Paint) in the Effects section | | LR-EDIT-EFFECTS-GRAIN | Grain | P1 | ✅ | `ctl:grain.*` | | -| LR-EDIT-DETAIL-SHARPEN | Sharpening | P0 | 🟡 | `ctl:detail.sharpenAmount`, `ctl:detail.sharpenRadius`, `ctl:detail.sharpenDetail`, `ctl:detail.sharpenMasking`, `crates/pipeline/src/visualize.rs` | Amount and Masking work; Radius and Detail are stored (XMP round trip) but do not change the render yet (the band is a fixed 0.18 % of the long edge). Alt/Option-drag previews: Amount greyscale, Radius / Detail the detail band sharpening amplifies, Masking the mask (white = sharpened) | +| LR-EDIT-DETAIL-SHARPEN | Sharpening | P0 | ✅ | `ctl:detail.sharpenAmount`, `ctl:detail.sharpenRadius`, `ctl:detail.sharpenDetail`, `ctl:detail.sharpenMasking`, `crates/pipeline/src/visualize.rs` | Process V3: pixel-scale sharpening, working Radius and Detail, original-photo scale in previews and exports; V1/V2 preserve the previous rendering (`crates/pipeline/src/tests_sharpen.rs`). Alt/Option-drag previews: Amount greyscale, Radius / Detail the detail band sharpening amplifies, Masking the mask (white = sharpened) | | LR-EDIT-DETAIL-NR | Luminance noise reduction | P0 | ✅ | `ctl:detail.nrLuminance`, `ctl:detail.nrDetail`, `ctl:detail.nrContrast` | radii in the original's pixels, so grid, loupe and smaller exports look like the full-size render scaled down (`local::nr_params`, `Plan::detail_scale`, #960). Alt/Option-drag on Luminance, Detail and Contrast shows the photo in greyscale | | LR-EDIT-DETAIL-CNR | Colour noise reduction | P0 | ✅ | `ctl:detail.nrColor`, `ctl:detail.nrColorDetail`, `ctl:detail.nrColorSmoothness` | preview-size independent like luminance NR (#960) | | LR-EDIT-DETAIL-DENOISE | AI denoise | P2 | 🟡 | cmd:denoise.toggle, cmd:denoise.models.install, cmd:denoise.queue, ctl:enhance.denoise, `crates/denoise/`, `docs/denoise.md` | non-destructive Bayer RAW, opt-in weights, pure-Rust CPU/GPU; GPU convolution uses independently written shared scalars (Metal equivalence regression, issue #479); tiles can also run on another computer's graphics card (`lightcraft-cli denoise-serve`, `crates/denoise/src/remote.rs`); X-Trans/linear RGB, model policy and Lightroom fidelity remain; closing the model setup without installing turns the switch back off (#922) | @@ -236,12 +236,12 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-PROF-ADOBE | Standard raw looks (own equivalents) | P0 | ✅ | `crates/engine/src/presets.rs` (`PROFILES`), `crates/pipeline/src/profiles.rs` | six own looks: Color, Neutral, Vivid, Landscape, Portrait, Monochrome | | LR-PROF-ADAPTIVE | Adaptive profiles | P2 | ⬜ | | | | LR-PROF-CAMERA | Camera-matching looks | P2 | ⬜ | | | -| LR-PROF-CAMERACOLOR | Camera colour calibration (own) | P0 | 🟡 | `crates/raw/src/color.rs`, `crates/raw/src/profile.rs`, `crates/raw/src/gaintable.rs`, `crates/engine/src/camera_preview.rs` | DNG files use the colour matrices and the camera-profile look they carry (`ProfileHueSatMap`, `ProfileLookTable`, `ProfileToneCurve`, read from the file at run time per DNG spec ch. 6 — Lightroom-converted DNGs rendered flat and muted without them, issue #138). A DNG whose profile defines no tone curve (absent or identity `ProfileToneCurve`, with or without a `LookTable`, as Adobe Standard in Lightroom-written DNGs) gets its tone fitted to its embedded preview when that is at least 10% of the raw's long edge and 384 px (Lightroom's 1024 px previews qualify): two Lightroom Classic 15.1 lossy ILCE-7CM2 DNGs went from about 0.8 EV darker and flat to within 3% of Lightroom's mean linear RGB. A DNG's `ProfileGainTableMap` / `ProfileGainTableMap2` (Apple ProRAW's local tone map; both versions, DNG 1.7 precedence, the file's byte order with a big-endian fallback) is read and written back by DNG export and not rendered by default, as Lightroom Classic renders ProRAW without it (measured on one CC0 iPhone 12 Pro ProRAW); the Profile option "Camera local tone mapping" (`profile.camera_local_tone`, per photo, off by default, `crates/pipeline/src/local_tone.rs`) renders it as the camera does, per output pixel in the scene-linear stage (CPU, also under the GPU path); Sony ARW, Nikon NEF, Panasonic RW2, Fujifilm RAF, Canon CR3 and CR2, Pentax PEF, Samsung SRW and Olympus ORF get a guarded file-local fit to their own embedded JPEG — chromaticity matrix + hue/saturation/value table + tone and chroma curves, relative WB — or, with a bundled or local per-model profile pooled from many photos (`lightcraft-cli calibrate`, ARW, NEF and RAF so far, `crates/engine/src/camera_profiles.rs`), the profile's colour and only their own tone/chroma curves (on 29 held-out ILCE-7M4 photos mean ΔE vs the camera JPEG 3.54 → 3.10; bundled ILCE-7CR from 125 photos: 26 held-out 4.07 → 3.29, and every one of the 131 photos accepted, 8 of which fell back to neutral without it; bundled ILCA-99M2 from 144 photos: 30 held-out 5.11 → 4.87, 25 of them closer); the tone fit also uses dark JPEG samples excluded from colour training, so deep shadows follow the camera toe (#1307); near-black frames with too few colour pairs can take a guarded tone-only fallback on their existing source colour (#1587); Sony ARWs shot with DRO on (maker note `0xb025`, on by default) keep that colour but their tone curve is lowered to Sony's curve without DRO, whose lifted shadows are in the camera JPEG only (issue #244: 8 ILCE-7CR photos +6.4 → +0.8 L* from Lightroom's default, median ΔE 7.5 → 3.3); 52 models without a profile whose JPEG fit fails (or that have no usable JPEG) start from DNG-style matrices fitted to their measured spectral sensitivities instead of the neutral fallback (`crates/raw/src/spectral.rs`, rawtoaces-data v1.1.0, Apache-2.0, aliases included; not yet measured against the camera JPEG); the Canon EOS D60 (CRW) has DNG-style matrices of our own, fitted to ColorChecker Classic shots under a tungsten bulb and direct sun (`crates/raw/src/chart_table.rs`, `clean-room/crw/10-chart-calibration.md`; CIEDE2000 on the chart mean 2.4 / 1.7, 2.7 / 2.0 leaving each patch out), which give its white balance a Kelvin scale (the camera's own presets read Tungsten 3,264 K, Daylight 5,603 K, Cloudy 6,612 K) while its look stays the JPEG fit; ARW: on 10 public raw.pixls.us samples from 8 bodies 7 fits were accepted, mean ΔE vs the camera JPEG 17–26 → 3–10; NEF: 13 of 13 decodable samples (D750, D780, D850, D7500, Z 50 and local D7500 shots) accepted, ΔE 13–46 → 3–8 (issue #150); RW2 / RWL: 140 of 174 public samples accepted, from 93 of the 114 bodies with a preview, median ΔE 5.0 with matching lightness (13 of the 14 corpus files with a preview: ΔE 9.6–27 → 2.8–8.9; most rejections are compacts and kit zooms whose camera JPEG is distortion-corrected); a fit that fails the gates on all pixels is retried away from edges, where a lens-corrected camera JPEG still lines up (issue #232: the six distortion-corrected public ILCE-7RM2 samples ΔE 16.6–16.9 → 3.7–3.8, the corpus GX80 19.1 → 7.9); RAF: bundled X-H2S/X-T4 profiles from 201/545 photos; on 150 withheld files mean ΔE improves slightly over per-file fitting (X-H2S 1.70 → 1.62, X-T4 2.43 → 2.34); 23 of 24 references from 13 bodies accepted, including the dark X-H2S samples (8.74 → 2.25); ORF: the 3 decodable corpus files (E-1, E-400, XZ-2) accepted (`docs/camera-preview-colour.md`); a raw whose camera JPEG is black and white (a monochrome picture style) takes only the JPEG's tone curve, on the camera profile's, spectral or neutral colour (issue #577); this is not measured camera calibration; other raws and rejected fits use a neutral fallback (camera RGB ≈ linear sRGB, `matrix_is_fallback`) with as-shot white balance, so colours are muted and not accurate. Needs our own per-camera calibration: matrices the files carry themselves (e.g. Olympus `ColorMatrix`), fitting each camera to its own embedded JPEG, then chart shots. Adobe matrices / DCPs are never used. Biggest image-quality gap today; ILCE-7RM6: per-file fit now runs on previews above 64 MP, a pooled profile (46 photos) was tried and not bundled (withheld ΔE 5.71 → 6.40, 11 of 15 regressed), kept with smart previews (see docs/camera-preview-colour.md); the fit pairs the sensor moved into the file's lens-warp geometry when that lines up better with a lens-corrected camera JPEG (29 CC0 raws: alignment +0.13, mean ΔE 3.73 → 3.61); bundled NIKON Z 6_2 profile (296 photos; 59 held-back photos mean ΔE 2.73 → 2.54) NIKON Z 8 profile (261 photos; 55 held back 2.55 → 2.33) and NIKON D5300 profile (264 photos; 53 held back 2.86 → 2.66) | +| LR-PROF-CAMERACOLOR | Camera colour calibration (own) | P0 | 🟡 | `crates/raw/src/color.rs`, `crates/raw/src/profile.rs`, `crates/raw/src/gaintable.rs`, `crates/engine/src/camera_preview.rs` | DNG files use the colour matrices and the camera-profile look they carry (`ProfileHueSatMap`, `ProfileLookTable`, `ProfileToneCurve`, read from the file at run time per DNG spec ch. 6 — Lightroom-converted DNGs rendered flat and muted without them, issue #138). A DNG whose profile defines no tone curve (absent or identity `ProfileToneCurve`, with or without a `LookTable`, as Adobe Standard in Lightroom-written DNGs) gets its tone fitted to its embedded preview when that is at least 10% of the raw's long edge and 384 px (Lightroom's 1024 px previews qualify): two Lightroom Classic 15.1 lossy ILCE-7CM2 DNGs went from about 0.8 EV darker and flat to within 3% of Lightroom's mean linear RGB. A DNG's `ProfileGainTableMap` / `ProfileGainTableMap2` (Apple ProRAW's local tone map; both versions, DNG 1.7 precedence, the file's byte order with a big-endian fallback) is read and written back by DNG export and not rendered by default, as Lightroom Classic renders ProRAW without it (measured on one CC0 iPhone 12 Pro ProRAW); the Profile option "Camera local tone mapping" (`profile.camera_local_tone`, per photo, off by default, `crates/pipeline/src/local_tone.rs`) renders it as the camera does, per output pixel in the scene-linear stage (CPU, also under the GPU path); Sony ARW, Nikon NEF, Panasonic RW2, Fujifilm RAF, Canon CR3 and CR2, Pentax PEF, Samsung SRW and Olympus ORF get a guarded file-local fit to their own embedded JPEG — chromaticity matrix + hue/saturation/value table + tone and chroma curves, relative WB — or, with a bundled or local per-model profile pooled from many photos (`lightcraft-cli calibrate`, ARW, NEF and RAF so far, `crates/engine/src/camera_profiles.rs`), the profile's colour and only their own tone/chroma curves (on 29 held-out ILCE-7M4 photos mean ΔE vs the camera JPEG 3.54 → 3.10; bundled ILCE-7CR from 125 photos: 26 held-out 4.07 → 3.29, and every one of the 131 photos accepted, 8 of which fell back to neutral without it; bundled ILCA-99M2 from 144 photos: 30 held-out 5.11 → 4.87, 25 of them closer); the tone fit also uses dark JPEG samples excluded from colour training, so deep shadows follow the camera toe (#1307); near-black frames with too few colour pairs can take a guarded tone-only fallback on their existing source colour (#1587); Sony ARWs shot with DRO on (maker note `0xb025`, on by default) keep that colour but their tone curve is lowered to Sony's curve without DRO, whose lifted shadows are in the camera JPEG only (issue #244: 8 ILCE-7CR photos +6.4 → +0.8 L* from Lightroom's default, median ΔE 7.5 → 3.3); 52 models without a profile whose JPEG fit fails (or that have no usable JPEG) start from DNG-style matrices fitted to their measured spectral sensitivities instead of the neutral fallback (`crates/raw/src/spectral.rs`, rawtoaces-data v1.1.0, Apache-2.0, aliases included; not yet measured against the camera JPEG); the Canon EOS D60 (CRW) has DNG-style matrices of our own, fitted to ColorChecker Classic shots under a tungsten bulb and direct sun (`crates/raw/src/chart_table.rs`, `clean-room/crw/10-chart-calibration.md`; CIEDE2000 on the chart mean 2.4 / 1.7, 2.7 / 2.0 leaving each patch out), which give its white balance a Kelvin scale (the camera's own presets read Tungsten 3,264 K, Daylight 5,603 K, Cloudy 6,612 K) while its look stays the JPEG fit; ARW: on 10 public raw.pixls.us samples from 8 bodies 7 fits were accepted, mean ΔE vs the camera JPEG 17–26 → 3–10; NEF: 13 of 13 decodable samples (D750, D780, D850, D7500, Z 50 and local D7500 shots) accepted, ΔE 13–46 → 3–8 (issue #150); RW2 / RWL: 140 of 174 public samples accepted, from 93 of the 114 bodies with a preview, median ΔE 5.0 with matching lightness (13 of the 14 corpus files with a preview: ΔE 9.6–27 → 2.8–8.9; most rejections are compacts and kit zooms whose camera JPEG is distortion-corrected); a fit that fails the gates on all pixels is retried away from edges, where a lens-corrected camera JPEG still lines up (issue #232: the six distortion-corrected public ILCE-7RM2 samples ΔE 16.6–16.9 → 3.7–3.8, the corpus GX80 19.1 → 7.9); RAF: bundled X-H2S/X-T4 profiles from 201/545 photos; on 150 withheld files mean ΔE improves slightly over per-file fitting (X-H2S 1.70 → 1.62, X-T4 2.43 → 2.34); 23 of 24 references from 13 bodies accepted, including the dark X-H2S samples (8.74 → 2.25); ORF: the 3 decodable corpus files (E-1, E-400, XZ-2) accepted (`docs/camera-preview-colour.md`); a raw whose camera JPEG is black and white (a monochrome picture style) takes only the JPEG's tone curve, on the camera profile's, spectral or neutral colour (issue #577); this is not measured camera calibration; other raws and rejected fits use a neutral fallback (camera RGB ≈ linear sRGB, `matrix_is_fallback`) with as-shot white balance, so colours are muted and not accurate. Needs our own per-camera calibration: matrices the files carry themselves (e.g. Olympus `ColorMatrix`), fitting each camera to its own embedded JPEG, then chart shots. Adobe matrices / DCPs are never shipped or used (a user can import their own `.dcp`, LR-PROF-IMPORT). Biggest image-quality gap today; ILCE-7RM6: per-file fit now runs on previews above 64 MP, a pooled profile (46 photos) was tried and not bundled (withheld ΔE 5.71 → 6.40, 11 of 15 regressed), kept with smart previews (see docs/camera-preview-colour.md); the fit pairs the sensor moved into the file's lens-warp geometry when that lines up better with a lens-corrected camera JPEG (29 CC0 raws: alignment +0.13, mean ΔE 3.73 → 3.61); bundled NIKON Z 6_2 profile (296 photos; 59 held-back photos mean ΔE 2.73 → 2.54) NIKON Z 8 profile (261 photos; 55 held back 2.55 → 2.33) and NIKON D5300 profile (264 photos; 53 held back 2.86 → 2.66) | | LR-PROF-CREATIVE | Creative profiles (own) | P2 | ✅ | `cmd:develop.profile`, `crates/pipeline/src/profiles.rs` | 16 own looks in Film / Cinematic / Muted / B&W (tone + point-curve fades, colour grading, mixer / B&W mix); scale with `ctl:profile.amount`; sliders untouched | | LR-PROF-LEGACY | Legacy profiles | P2 | ⬜ | | | | LR-PROF-NONRAW | Profiles for non-raw files | P0 | ✅ | `cmd:develop.profile` | same looks apply to JPEG/TIFF | | LR-PROF-AMOUNT | Profile amount | P1 | ✅ | `ctl:profile.amount` | | -| LR-PROF-IMPORT | Import profiles | P1 | ✅ | `cmd:profile.import`, `cmd:profile.deleteImported`, `crates/pipeline/src/lut.rs`, `crates/engine/src/cmd/lut_profiles.rs`, `crates/ui-egui/src/panels/edit.rs`, `crates/ui-egui/src/panels/profiles.rs` | `.cube` 3D LUTs (files, folders, zips) become creative profiles with Amount, grouped in the profile browser, kept with the library; rendered on the CPU; Adobe profile formats deliberately unsupported | +| LR-PROF-IMPORT | Import profiles | P1 | ✅ | `cmd:profile.import`, `cmd:profile.deleteImported`, `crates/pipeline/src/lut.rs`, `crates/engine/src/cmd/lut_profiles.rs`, `cmd:profiles.camera`, `cmd:profile.deleteCamera`, `crates/engine/src/cmd/dcp_profiles.rs`, `crates/raw/src/dcp.rs`, `crates/ui-egui/src/panels/edit.rs`, `crates/ui-egui/src/panels/profiles.rs` | `.cube` 3D LUTs (files, folders, zips) become creative profiles with Amount, grouped in the profile browser, kept with the library; rendered on the CPU; the user's own DNG camera profiles (`.dcp`: matrices, illuminants, hue/sat map, look table, tone curve) become camera profiles (`dcp:` ids, group Camera Profiles) that replace a raw file's colour model when it is decoded (a profile without a tone curve keeps the photo's own contrast; the photo is decoded again when the profile changes; smart previews and the web worker keep the file's own colour); none ship with the app; XMP camera/creative profiles unsupported; a single `.dcp` is not also reported as an unreadable LUT. Checked on a real profile: a CC0 Calibrite PROFILER profile for the Nikon D750 (matrix-only, Cool White Fluorescent + D55; `cargo xtask corpus --download`, never committed) develops its two chart NEFs within mean ΔE2000 3.8 (flash) and 3.4 (indoor) of Lightroom Classic 15.6 with the same profile, max 7.8 (`crates/engine/src/tests/dcp_corpus.rs`, `crates/raw/tests/dcp_corpus.rs`) | ## H. Crop & rotate (CROP) @@ -399,7 +399,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EXP-HDR | HDR output | P2 | 🟡 | `cmd:app.export`, `crates/ui-egui/src/dialogs.rs` | HDR output checkbox in the export dialog: gain map JPEG, PQ or HLG AVIF, PQ PNG, PQ JPEG XL, float TIFF; no HDR presets yet | | LR-EXP-SHARPEN | Output sharpening | P1 | ✅ | `cmd:app.export` (`sharpen`, `sharpenAmount`) | | | LR-EXP-METADATA | Metadata policy | P1 | ✅ | `cmd:app.export` (`metadata`, `removeLocation`) | Original export is refused when Remove Location Info is on and the source embeds GPS or a nonblank sublocation, city, state or country; for HEIF, HEIC and AVIF, `lightcraft_meta::embeds_location` also checks every EXIF and XMP item, including auxiliary images, and an unreadable item counts as a location; rendered exports and XMP sidecars remove those modeled fields | -| LR-EXP-WATERMARK | Watermark | P1 | 🟡 | `cmd:app.export` (`watermark`: text, or `{text, vertical, size, opacity, anchor, insetX, insetY, inset, rotation, color, shadow, image, imageWidth}`), `crates/engine/src/export.rs` (`Watermark`, `WATERMARK_PARAMS`) | text uses Inter SemiBold, the existing Mincho-first CJK chain, then Thai faces from `CRAFT_FONTS_DIR`, shared with contact-sheet captions and slideshow overlays (#2052, partial). Horizontal Thai mark positioning remains incomplete. Arabic export fallback is deferred until joining and bidi reordering exist; UI font fallback is unchanged. Text (`size` = height as a fraction of the short edge, 0.005..0.5, default 0.035; `color` sRGB `[r,g,b]`; `shadow`; Japanese vertical glyph forms and origins, tested by `biz_ud_vertical_watermarks_place_punctuation_at_the_top_right`; extended grapheme cells keep decomposed dakuten/handakuten and Latin accents together, tested by `vertical_watermarks_keep_combining_marks_in_one_cell` and `upright_watermark_cell_retains_multiple_glyphs` (see `docs/vertical-watermarks.md`)) or a graphic with transparency (EXIF orientation applied before sizing; oversized graphics fit the rotated image bounds without stretching, tested by `graphic_watermark_honours_exif_orientation` and `graphic_watermark_keeps_aspect_when_fitted_and_rotated`; `image` path, `imageWidth` = fraction of the photo's width, 0.01..1, converted to the output colour space); `anchor` (nine positions), `insetX` / `insetY` (margins from the side and from the top/bottom edges, each a fraction of the short edge, 0..0.4; the Export dialog's Horizontal and Vertical inset sliders, as in Lightroom Classic; the older single `inset` still reads as both; tested by `watermark_insets_are_horizontal_and_vertical`), `rotation` (0, 90, 180 or 270 degrees clockwise, the Export dialog's Rotate row, as Lightroom Classic's rotate buttons; sized before it is turned, placed and inset by the turned box; tested by `watermark_rotation_turns_the_text_in_its_corner` and `graphic_watermark_is_placed_scaled_and_blended`), `opacity` 0..1. Unknown keys and out-of-range values are errors (issue #183). The Export dialog previews it on the first exported photo's thumbnail (`draw_watermark_preview` scales the 6 px minimum text size to the preview so it matches the file), tested by `watermark_preview_scales_the_minimum_text_size` and `export_dialog_previews_the_watermark` | +| LR-EXP-WATERMARK | Watermark | P1 | 🟡 | `cmd:app.export` (`watermark`: text, or `{text, vertical, size, opacity, anchor, insetX, insetY, inset, rotation, color, shadow, image, imageWidth}`), `crates/engine/src/export.rs` (`Watermark`, `WATERMARK_PARAMS`) | text uses Inter SemiBold, the existing Mincho-first CJK chain, then Thai faces from `CRAFT_FONTS_DIR`, shared with contact-sheet captions and slideshow overlays (#2052, partial). Decomposed (NFD) text, as macOS often writes file names, is composed to NFC first, so Hangul syllables and Vietnamese letters draw whole instead of as loose jamo and marks; CJK compatibility ideographs keep their code points (issue #3480, #3277; `decomposed_hangul_draws_whole_syllables`, `decomposed_vietnamese_draws_its_composed_letters`, `compatibility_ideographs_keep_their_code_points`). Horizontal Thai mark positioning remains incomplete. Arabic export fallback is deferred until joining and bidi reordering exist; UI font fallback is unchanged. Text (`size` = height as a fraction of the short edge, 0.005..0.5, default 0.035; `color` sRGB `[r,g,b]`; `shadow`; Japanese vertical glyph forms and origins, tested by `biz_ud_vertical_watermarks_place_punctuation_at_the_top_right`; extended grapheme cells keep decomposed dakuten/handakuten and Latin accents together, tested by `vertical_watermarks_keep_combining_marks_in_one_cell` and `upright_watermark_cell_retains_multiple_glyphs` (see `docs/vertical-watermarks.md`)) or a graphic with transparency (EXIF orientation applied before sizing; oversized graphics fit the rotated image bounds without stretching, tested by `graphic_watermark_honours_exif_orientation` and `graphic_watermark_keeps_aspect_when_fitted_and_rotated`; `image` path, `imageWidth` = fraction of the photo's width, 0.01..1, converted to the output colour space); `anchor` (nine positions), `insetX` / `insetY` (margins from the side and from the top/bottom edges, each a fraction of the short edge, 0..0.4; the Export dialog's Horizontal and Vertical inset sliders, as in Lightroom Classic; the older single `inset` still reads as both; tested by `watermark_insets_are_horizontal_and_vertical`), `rotation` (0, 90, 180 or 270 degrees clockwise, the Export dialog's Rotate row, as Lightroom Classic's rotate buttons; sized before it is turned, placed and inset by the turned box; tested by `watermark_rotation_turns_the_text_in_its_corner` and `graphic_watermark_is_placed_scaled_and_blended`), `opacity` 0..1. Unknown keys and out-of-range values are errors (issue #183). The Export dialog previews it on the first exported photo's thumbnail (`draw_watermark_preview` scales the 6 px minimum text size to the preview so it matches the file), tested by `watermark_preview_scales_the_minimum_text_size` and `export_dialog_previews_the_watermark` | | LR-EXP-NAMING | File naming | P1 | ✅ | `cmd:app.export` (`naming`, `startNumber`), `crates/engine/src/rename.rs` (`expand_tokens`) | one template language for export, Rename Photos and import renaming: `{name}`, `{num}` (number at the end of the name), `{seq}` / `{seq:N}`, `{date}` / `{date:%Y-%m-%d}`, `{folder}`, `{camera}`, `{lens}`, `{iso}`, `{rating}`, `{title}`, `{creator}`, `{ext}`; free-form template rather than a list of named schemes | | LR-EXP-LOCATION | Destination folder | P0 | ✅ | `cmd:app.export` (`dir`, `destinationMode`: specificFolder / sameAsOriginal, `subfolder`, `conflict`: unique / overwrite / skip), `cmd:export.checkTarget`, `crates/ui-egui/src/dialogs.rs` (Choose… folder picker), `crates/engine/src/originals.rs`, `crates/catalog/src/safe_file.rs` | folder picker on the desktop; Export to: Specific folder or Same folder as original photo (each photo into its original's folder + the subfolder; a demo/browser photo or a missing folder is that photo's error, issue #956); existing files get `-2`, `-3`… by default; the policy covers a file and its sidecars together; a catalogued original (or its sidecar) is never written over, whatever the policy or an exact `path` (export, `ui.render`, MCP `render_photo`, merge `previewPath`, `lightcraft-cli render`); files are written to a temp file and renamed into place (issue #93; not synced file by file — exports can be made again, issue #134) | | LR-EXP-PREVIOUS | Export with previous settings | P0 | ✅ | `cmd:app.exportPrevious`, `cmd:dialog.export` | last options persist in prefs.json; dialog prefilled; no named export presets yet | @@ -465,7 +465,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-OFFLINE | Offline editing | P1 | ✅ | | local-first: everything works offline | | LR-BEHAV-WEB-SAFETY | Library safety in the browser build | P1 | 🟡 | `cmd:file.backupLibrary`, `cmd:file.restoreLibrary`, `apps/lightcraft-web/src/safety.rs`, `apps/lightcraft-web/src/backup.rs`, `apps/lightcraft-web/src/files.rs` | web only (experimental): Back Up Library (zip of the catalog and every stored original) and a non-destructive Restore; failed saves show as unsaved and are retried; a photo that can't be stored isn't added; one tab per library (Web Locks); notices for storage that isn't persistent and for a library that can't open; `?reset` asks first; a panic shows a message. Missing: `?safe` start, deleting originals of removed photos, zip64 (backups > 4 GB) | | LR-BEHAV-GPU | GPU acceleration | P0 | ✅ | `crates/gpu/src/render.rs`, `cmd:app.gpu`, `docs/gpu-pipeline.md`, `crates/ui-egui/src/panels/notices.rs` | CPU fallback per render on device limits, out of memory, device errors / loss, incomplete or black results (`perf.gpuReason`, `perf.gpuFallback`; each render reports its own reason — `lightcraft_gpu::try_render`, `gpuFallback` per exported file — issue #675); short submissions for slow iGPUs; backend choice (DX12 only on Windows, `LIGHTCRAFT_GPU_BACKEND` / `WGPU_BACKEND`), device created after the window opens, crash sentinel (issue #136); a GPU lost while LightCraft runs (driver reset) stops it with that message and turns GPU rendering off for the next start, which says why (issue #1337; the window's renderer can't survive the lost device); quitting waits (up to 2 s) for renders in flight and starts no new GPU work, so none is inside the driver when the process exits (`crates/gpu/src/exit.rs`, issue #620; seen crashing only on Linux + NVIDIA, other drivers unverified); with GPU rendering on and no adapter found at all (e.g. no Vulkan loader on NixOS outside `nix develop`), the desktop app says once per session that it renders on the CPU and points to Help ▸ System Info (`gpu_notice`; not when the GPU is turned off or only a software adapter exists); no tiling beyond the buffer limit (CPU) | -| LR-BEHAV-RENDER-FIDELITY | Rendering matches Lightroom | P1 | 🟡 | `crates/pipeline/src/lib.rs`, `crates/pipeline/src/tone.rs` | every slider exists and works, but the character of the result (tone curve shape, highlight recovery, texture / clarity / dehaze, noise reduction, sharpening, default look) is tuned by eye; there is no systematic side-by-side comparison against Lightroom on the same CC0 raws. Needs a fidelity suite: Lightroom reference renders kept only in the local `plan/` (never committed), compared per slider and preset with a perceptual metric. Tuning that changes how existing settings render ships as a new process version (LRC-DEV-PROCESS, `docs/process-versions.md`) | +| LR-BEHAV-RENDER-FIDELITY | Rendering matches Lightroom | P1 | 🟡 | `crates/pipeline/src/lib.rs`, `crates/pipeline/src/tone.rs` | Process V4 calibrates global camera-look Contrast and Blacks against black-box Lightroom exports of Sony ILCE-7CR photos. Held-out response errors are 0.038 and 0.077 stops; V1/V2 keep their rendering. Whites retains V2 and awaits a follow-up. Exposure, Highlights/Shadows, other operators and broader camera coverage remain open (`docs/light-v3.md`). | | LR-BEHAV-DRAGDROP | Drag and drop | P1 | ✅ | `crates/ui-egui/src/lib.rs`, `crates/ui-egui/src/panels/grid.rs` (`drag_feedback`), `crates/ui-egui/src/panels/left.rs` (`drop_target`, `album_drag_over`, `top_level_drop_target`, `drag_auto_scroll`), `crates/ui-egui/src/destination.rs`, `crates/ui-egui/src/widgets.rs` (`context_menu`), `crates/ui-egui/src/widgets/text_field.rs`, `crates/ui-egui/src/tests/carried_right_click.rs`, `crates/ui-egui/src/tests/carried_text_field_menu.rs` | a right-click while photos are carried opens no context menu (every menu opened through `widgets::context_menu`: sidebar rows, grid cells, lists; a text field's own Cut / Copy / Paste menu too); files → app (a drop-target card while they hover, then the import review); grid photos → an album row (adds the selection, with a count badge while dragging); sidebar album / folder rows → a folder (moves it; its name follows the pointer); a drag of albums or grid photos near the top or bottom edge of the sidebar scrolls it (faster nearer the edge, only while the pointer is over the sidebar); when another folder has the same name, the dragged label, the Move question and the toast name the folder it is in (`home (/a)`); an album drop's toast does the same for an album of that name in another album folder (two in the same place have nothing to tell them apart and keep the plain name); only the primary button drags photos and drops them: a right-button drag over a grid cell neither picks photos up nor changes the selection, and a right-button release while photos are dragged neither drops them nor ends the drag | | LR-BEHAV-TOAST | Toast notifications | P1 | ✅ | `crates/ui-egui/src/panels.rs` | | | LR-BEHAV-DIALOGS | Dialogs fit the window | P1 | ✅ | `crates/ui-egui/src/dialogs.rs` (`dialog_body`, `list_height`), `crates/ui-egui/src/tests/dialog_fit.rs`, `crates/ui-egui/src/tests/dialog_copy.rs`, `crates/ui-egui/src/tests/dialogs.rs` (`a_click_outside_closes_the_dialog_when_settings_allow_it`) | a dialog taller than the window (Export on a 1366×768 screen, issue #781) never runs off it: its options scroll while the title bar and the Cancel / confirm row stay on screen (the confirm button names its action: Create, Rename, Create Stacks, Export 3 Photos…, with "OK" kept only for a one-field prompt opened with a command that has no verb, `crates/ui-egui/src/tests/dialog_copy.rs`); lists that scroll on their own (What's New, All Metadata, shortcuts, smart-album rules, credits) get shorter first; dialogs that fit look as before; Import keeps its own resizable, scrolling window; Settings → Dialogs → Close a dialog by clicking outside it (off by default, so a stray click never throws away a dialog's choices): a click pressed and released on the dimmed backdrop closes the dialog like Esc and doesn't reach the panels below, while a drag that ends outside (a slider pulled past the edge) or a click that closes a dropdown keeps it; the import review never closes this way (`clicked_backdrop`); a one-line prompt (Rename Folder, New Folder on Disk, the preset and version names, New Library when its name can't be used, Auto-Tag from Tracklog) the engine refuses stays open with its text and shows the reason in a toast, so the name can be corrected, where it used to close without a word; a New Folder on Disk that works says so (“Created folder “Selects” in “2026/Shoot””, naming the parent by its last two folders as dialogs do) | @@ -716,7 +716,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-QUICKDEV | Quick develop | P2 | ✅ | `cmd:develop.quickAdjust`, `crates/ui-egui/src/panels/edit.rs` (`quick_develop`) | grid with several photos selected: Edit panel ▸ Quick Develop steps (exposure ⅓ / 1 stop, contrast, highlights, shadows, whites, blacks, clarity, vibrance, temperature) added to each photo's own value, one undo step | | LRC-LIB-PEOPLE | People view | P2 | 🟡 | `cmd:view.people`, `cmd:view.person`, `cmd:faces.person`, `cmd:faces.unnamed`, `cmd:faces.nameFaces`, `crates/ui-egui/src/panels/people.rs`, `crates/ui-egui/src/panels/person.rs`, `crates/ui-egui/src/panels/unnamed.rs`, `crates/engine/src/face_tiles.rs` | Named People cards (face close-up, the photo count on the picture, name) for the photos the active filters let through, with the filter chips shown above them, sized by the thumbnail slider. Below them the **Unnamed faces**: every face nobody has named as a cropped picture, look-alikes next to each other once recognition has looked at them, a suggested name on a face the named ones recognise; click or Shift-click to select, type a name, Enter names the whole group in one undo step. A click on a person opens their page: only cropped faces, then **More** (unnamed faces that look like them, best first; click to confirm one, × to hide for the session, or ↑ / hovered-or-focused A key to confirm all currently shown non-hidden suggestions at or above that face's score, including ties, in one undo step). Every face is shown by the detector's box where the scan has one, so faces are equally close. Until recognition is set up a line at the top offers the next step (Settings ▸ Faces, or Turn on), as does the loupe's name box. Face pictures of unedited raws are cut from the largest embedded preview (planned read: header and JPEG only, never the sensor data) when it holds at least ¾ of the tile's pixels across the face, else developed as before; all are kept in the thumbnail disk cache at 16 px size steps, so a later launch shows them without reading the originals (#1440, `docs/faces.md`). No clusters with separators between groups, no persistent reject, no merge of two people | LRC-LIB-COMMENTS | Comments panel | P2 | ⬜ | | | -| LRC-LIB-VISUALSEARCH | Find similar photos | P2 | ✅ | `cmd:library.findSimilar`, `crates/pipeline/src/cull.rs` (`signature`) | photo menu / Photo ▸ Find Similar Photos: look-alike photos (composition and tones), most similar first, as a filter (`only`) | +| LRC-LIB-VISUALSEARCH | Find similar photos | P2 | ✅ | `cmd:library.findSimilar`, `crates/pipeline/src/cull.rs` (`signature`), `crates/engine/src/cmd/similar.rs`, `crates/ui-egui/src/find_similar.rs` | photo menu / Photo ▸ Find Similar Photos: look-alike photos (composition and tones), most similar first, as a filter (`only`); the app reads the photos on a worker thread under an activity row with ✕ | | LRC-LIB-MISSING | Missing files & relink | P1 | ✅ | `cmd:library.missing`, `cmd:photo.relink`, `cmd:library.findMissing`, `cmd:file.findMissing`, `cmd:photo.locate`, `crates/engine/src/cmd/missing.rs` (`checked_path`), `crates/ui-egui/src/missing_sweep.rs`, `crates/ui-egui/src/panels/left.rs` (`locate_missing_item`) | File → Find Missing Photos… (anywhere in a folder: same name, size and content hash; renamed files by size + content hash; same name and size alone only when unambiguous — look-alikes are skipped and reported; searched on a worker thread, one undo step), photo menu → Locate Missing File…; a folder or disk row's Locate Missing Files… chooses its new location and scopes the same recursive background finder to that folder and its subfolders. Unreadable files show "!" in the grid and a reason in the loupe; undo never moves files. Missing Photos in the sidebar (counted on a worker thread; the view, the Info panel, the grid's context menu and thumbnails read file availability from a cache a worker thread fills, so an offline NAS never stalls a frame); it covers library photos only — Local browse records are never checked, for the count, the view, `library.missing` and Find Missing alike; `library.missing` from the control channel or `mcp --connect` checks the files on a worker thread (a "Missing Photos" row in the activity stack, ✕ stops it) and answers when it ends, so a large library on a network share never stalls the window; the same request meanwhile shares the running check | | LRC-LIB-CONVERT | Convert to DNG | P2 | ✅ | `cmd:photo.convertToDng`, `crates/engine/src/cmd/convert.rs` | Photo ▸ Convert to DNG: lossless DNG next to the raw with the settings embedded, photo (and its virtual copies) relinked; originals kept; undoable; the DNG is decoded and compared with the raw data, written to a temp file, synced, read back and only then given a free name (never replacing a file) — a failed write leaves no DNG and the photo on its raw (issue #106) | | LRC-LIB-PREVIEWS | Build / discard previews | P1 | ✅ | `cmd:library.buildPreviews`, `cmd:library.previewProgress`, `cmd:library.cancelPreviews`, `cmd:library.clearPreviews`, `crates/engine/src/cmd/previews.rs`, `crates/preview/src/lib.rs` | File ▸ Previews: build standard-sized (Settings → Performance size) or 1:1 previews of the selected / visible photos in the background (a row in the activity stack, ✕ to stop), discard the cache; disk thumbnail + view cache; no smart previews (offline proxies) | @@ -724,12 +724,12 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-DEV-SNAPSHOTS | Named snapshots | P1 | ✅ | `cmd:version.create`, `cmd:version.restore` | = versions | | LRC-DEV-HISTORY | Full history panel | P1 | ✅ | `cmd:history.list`, `cmd:history.restore`, `cmd:history.previous`, `cmd:history.next`, `cmd:history.clear` | row menu: copy step to before, create version from step, clear history; clicking a step loads it without adding one (current step highlighted, later steps greyed and returnable until a new edit truncates them; one undo step; cursor saved in the catalog, old catalogs open at the latest step) | | LRC-DEV-SOFTPROOF | Soft proofing | P2 | 🟡 | `cmd:view.softProof`, `crates/pipeline/src/output.rs` (`Proof`), `crates/ui-egui/src/panels/edit.rs` (`soft_proofing`) | S in the loupe (in grids S stays Expand/Collapse Stack): paper-white surround and "Proof Preview", proof profile (sRGB / Display P3 / Adobe RGB / ProPhoto / Rec. 2020), destination (red) and display (blue) gamut warnings (the display's gamut is the monitor profile's, `cmd:app.displayProfile`, else sRGB), Create Proof Copy (a named virtual copy). printer / paper ICC profiles can be loaded as the proof profile (size-capped, the last few kept), with rendering intent (Perceptual / Relative Colorimetric), Simulate Paper & Ink and a device-gamut warning (`crates/codecs/src/proof.rs`, `crates/engine/src/proof.rs`); on the GPU for output-space proofs (destination and display gamut warnings included; equivalence-tested), an output-device profile's 3D table on the CPU | -| LRC-DEV-AUTOSYNC | Sync / auto sync / paste previous | P1 | ✅ | `cmd:develop.sync`, `cmd:develop.autoSync`, `cmd:develop.pastePrevious` | Edit ▸ Sync Settings / Auto Sync (⌥⇧⌘A): only the changed settings carry over, one undo step, slider drags sync on release, spots / red eye stay per photo; Edit panel banner | +| LRC-DEV-AUTOSYNC | Sync / auto sync / paste previous | P1 | ✅ | `cmd:develop.sync`, `cmd:develop.autoSync`, `cmd:develop.pastePrevious` | Edit ▸ Sync Settings / Auto Sync (⌥⇧⌘A): only the changed settings carry over, one undo step, slider drags sync on release, spots / red eye stay per photo; every synced setting gets the active photo's value; with Auto Sync, white balance goes on each photo as its mode or on its own scale (As Shot: its own camera white; Auto: its own, from its pixels; a light preset: its numbers; a Temp or Tint: only the slider that moved, so each keeps its own tint, as the same number on a photo of the same scale (the same Kelvin on raws edited in Kelvin) and moved by as much as the active photo on one of another scale, such as a JPEG beside a raw), `crates/engine/src/sync_same.rs`; Sync Settings copies the active photo's stored white balance; Edit panel banner | | LRC-DEV-MATCHEXP | Match total exposures | P2 | ✅ | `cmd:develop.matchExposure` | Photo ▸ Match Total Exposures: the selected photos' Exposure set so shutter × ISO ÷ aperture² plus the slider matches the active photo's | | LRC-DEV-CALIB | Calibration panel | P1 | ✅ | `ctl:calibration.*` | | | LRC-DEV-TAT | Targeted adjustment tools | P1 | ✅ | `cmd:develop.targeted` (`target`: curve / hue / sat / lum) | | | LRC-DEV-DEFAULTS | Per-camera raw defaults | P1 | ✅ | `cmd:library.preferences` (`camera`, `import.perCamera`), `crates/ui-egui/src/dialogs/settings.rs` | Settings → Import: raw default and per-camera presets | -| LRC-DEV-PROCESS | Process versions, Update to Current Process | P1 | ✅ | `cmd:develop.updateProcess`, `cmd:develop.reset`, `cmd:develop.get`, `crates/develop/src/settings.rs`, `crates/pipeline/src/finish.rs`, `docs/process-versions.md` | each photo records the rendering process its settings are interpreted by: settings saved before this existed load as V1, new photos and Reset get the latest, virtual copies inherit, copy / paste / sync / presets keep each photo's own; Photo ▸ Update to Current Process (one undo step, enabled while a selected photo is on an older process); a number from a newer LightCraft is kept and renders with the newest known process. Only V1 exists so far: this is what lets a retuned default tone (#146) or stronger Light sliders (#196) ship without changing existing edits | +| LRC-DEV-PROCESS | Process versions, Update to Current Process | P1 | ✅ | `cmd:develop.updateProcess`, `cmd:develop.reset`, `cmd:develop.get`, `crates/develop/src/settings.rs`, `crates/pipeline/src/finish.rs`, `docs/process-versions.md` | Each photo keeps its saved rendering process. V1 is legacy, V2 preserves Highlights/Shadows detail, V3 is pixel-scale sharpening, V4 calibrates camera-look Contrast and Blacks. New photos and Reset use the latest; Update is one undoable step and never downgrades a future number. Copy/paste/sync preserve the receiving process. Persistent render keys include the resolved process from V3 on; V1/V2 keys remain unchanged. | | LRC-DEV-VIEWOPTIONS | Develop view options | P2 | 🟡 | `cmd:view.viewOptions`, `crates/ui-egui/src/dialogs/settings.rs` (`view_options`) | View ▸ View Options… (⌘J), the Loupe View part: Show Info Overlay with Info 1 / Info 2, and the three lines of each (none, file name, capture date, dimensions, exposure, camera, lens, camera + lens) with Use Defaults; Show Briefly When Photo Changes under each Info (one at most): with the overlay off, that Info shows for 3 s each time the loupe changes photo; General's Show message when loading or rendering photos (on by default; off, the loupe does not say "Rendering…"); applied as they change, saved with the app settings; `view.viewOptions {info1, info2, briefly, loupeMessages}` sets them for agents. Not yet: the Grid View tab, more fields (ratings, metadata, copy name), the video-frame option | | LRC-DEV-LOUPEOVERLAY | Loupe overlay: layout image | P2 | 🟡 | `cmd:view.chooseLayoutImage`, `cmd:view.layoutImage`, `cmd:view.layoutImageOpacity`, `cmd:view.layoutImageMatte`, `crates/ui-egui/src/panels/layout_overlay.rs` | View ▸ Loupe Overlay: a PNG with transparency (a cover layout, a banner's safe areas) fitted and centred over the loupe photo, following zoom and pan; opacity and matte (the photo darkened outside the graphic's box) in steps; ⌥⌘O shows / hides it; read off the UI thread; saved with the UI state. Not yet: the Grid and Guides overlays, moving and resizing the layout with ⌘ held, free opacity / matte sliders | | LRC-DEV-VIDEO | Video frame capture | P2 | ⬜ | | | @@ -799,6 +799,8 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | LRC-DEV-AUTOSYNC (N-A3, note 18): Auto Sync carries white balance as a mode or on each photo's own scale: As Shot and Auto per photo (were the active photo's numbers), a Temp move keeps each photo's tint, the same number on photos of the same scale, a photo of another scale (a JPEG beside a raw) moves by as much; Sync Settings unchanged; status unchanged | +| 2026-11-02 | minor | LR-LIB-FLAG (PERF-STEP-STALL): flags, ratings and edits are written and synced to the catalog log off the UI thread (a 300 ms sync: slowest flag 0.2 ms, was 305 ms); a failed write is held and retried, never dropped | | 2026-10-28 | minor | LR-EDIT-OPTICS-PROFILE: lensfun's database offered once on the first launch and downloaded on request (Download / Not Now, Settings) (pinned, CC BY-SA, never bundled), the library looked up when it arrives or Enable Lens Corrections is ticked, the Optics panel names the profile or the lens without one; status unchanged (🟡) | | 2026-10-30 | patch | LR-BEHAV-ACCESS: the Flatpak manifests grant `--talk-name=org.a11y.Bus`, so AccessKit can find out whether a screen reader is running and publish the window inside the sandbox; packaging lint requires it in both manifests; status unchanged (🟡), not tried with Orca | | 2026-10-27 | patch | LR-LIB-LABEL, MENU-PHOTO-LABEL, KEY-LABELS: Clear Color Label (`photo.clearLabel`) is a command of its own, so Help → Keyboard Shortcuts can give it a key (#2980); the Photo ▸ Set Color Label ▸ None row runs it; status unchanged | @@ -873,9 +875,12 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-15 | minor | LRC-PRINT-PAGE: Page Options (Page Numbers, Page Info, Crop Marks) on Single Image and Contact Sheet pages, in the Print dialog, `print.set` and templates; still 🟡 (no identity plate, watermark, photo info or Cut Guides) | | 2026-10-15 | minor | LR-IMP-FORMATS: Hasselblad 3FR and FFF show their uncompressed RGB preview (no JPEG in these files) in the grid and loupe until developed, and as the stand-in when a file fails to decode; status unchanged (🟡) | | 2026-10-15 | minor | LR-IMP-FORMATS: a Hasselblad FFF develops with the camera's colour matrix from the original 3FR header it embeds (tag `0xC51B`) instead of the neutral matrix; status unchanged (🟡) | +| 2026-10-22 | patch | LR-PROF-IMPORT: a real CC0 D750 profile (matrix-only, dual illuminant) and its chart NEFs are a pinned test corpus; against Lightroom Classic 15.6 mean ΔE2000 3.8 / 3.4; status unchanged (✅) | +| 2026-10-12 | minor | LR-PROF-IMPORT: the user's own DNG camera profiles (`.dcp`) import as camera profiles; none ship | | 2026-10-13 | minor | LRC-LIB-KEYWORDS: the Keyword List marks a keyword that has an applied keyword inside it (a dot in its box); status unchanged | | 2026-10-12 | minor | LR-IMP-FORMATS: folder discovery includes SR2/SRF; MCP and CLI reuse the engine extension list. DSC-F828 remains preview-only; decoder support and row status unchanged | | 2026-10-15 | patch | KEYC-RATING: `\` shows / hides the Filter Bar in Photo Grid and Square Grid (Show Original in Detail); status unchanged (🟡) | +| 2026-10-12 | minor | Calibrated Contrast and Blacks; mark the measured but incomplete Light controls partial and retain V2 Whites | | 2026-10-16 | minor | KEY-TOGGLEZOOM: Space held over a tool on the photo is the view's hand (click zooms, drag pans, the tool gets neither), a tap still toggles; a held Space toggles once (issue #1895); status unchanged | | 2026-10-16 | patch | LRC-LIB-CATALOG-IMPORT: VIDEO records appear in the Videos filter; reimport repairs older classification with edits, memberships and undo preserved (#1940, filter issue only). Status and summary counts unchanged. | | 2026-10-12 | minor | LR-EXP-METADATA: "remove location" refuses an original HEIF whose GPS is in any EXIF or XMP item (a thumbnail's, a second item), and offers DNG only for raws; LR-META-EXIF-FULL: a derived primary image's inputs count as the photo; statuses unchanged | @@ -1033,3 +1038,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-29 | patch | LR-BEHAV-TITLEBAR: a dialog's backdrop leaves the integrated title bar undimmed, as a macOS sheet does (the bar's controls stay inactive, a click on it is not a click outside the dialog, dragging its empty space still moves the window); status unchanged (🟡) | | 2026-10-29 | minor | LR-MASK-OBJECTS: an Object / Describe selection's stored grid is enlarged along the photo's edges (fast guided filter of its logits by log luminance, a 1.5-cell window), so a raised Exposure no longer draws an outline around the subject (#3272); existing AI masks are 1–2 px tighter at edges; status unchanged (🟡) | | 2026-10-30 | patch | LR-MASK-COLORRANGE: a colour-range mask keeps its first 64 samples however it is loaded (sidecar `lc:settings`, presets, `develop.merge`, `render --settings`, catalog and history), not only through `mask.add` / `mask.update`, so a document with thousands can't stall a render or lose the GPU device (issue #2556); status unchanged (✅) | +| 2026-10-31 | patch | LRC-LIB-VISUALSEARCH: Find Similar Photos reads the photos on a worker thread under an activity row with ✕ instead of on the UI thread, where a large library left the window not responding (#3468). A stopped search leaves the view as it was and keeps what it read; a control request gets the same `{photos}` when the search ends. | diff --git a/docs/process-versions.md b/docs/process-versions.md index 7e6788f11e..d477b6834d 100644 --- a/docs/process-versions.md +++ b/docs/process-versions.md @@ -1,5 +1,7 @@ # Process versions +> **Last updated:** 2026-10-12 · **Change:** minor (calibrated Contrast and Blacks) + Every photo's develop settings record the **rendering process** they are interpreted by (`DevelopSettings::process`, a `ProcessVersion` in `crates/develop/src/settings.rs`). Lightroom calls this the process version. It lets the look of LightCraft improve (a new default tone curve, issue #146; @@ -8,7 +10,9 @@ stronger Light sliders, issue #196) without changing a single photo someone has | Process | What it changes | |---|---| | **V1** | LightCraft's rendering from before process versions existed. Frozen. | -| **V2** (the latest) | Highlights and Shadows keep fine detail (issue #632): their base layer (`local::tone_base`) is the edge-aware filter of a separable median of log luminance (radius 0.15 % of the long edge, at most 24 px, `local::BASE_DETAIL`) instead of log luminance itself, so twigs, lines and texture take their surroundings' shift and keep their contrast; region edges stay sharp. CPU (`local::prepare`) and GPU prepare branch on `local::tone_base_detail` (0 = no median under V1); the base plane is cached per process (`local::BaseKey`). Renders without Highlights or Shadows (global or local) are the same as V1's. Tone map unchanged. | +| **V2** | Highlights and Shadows keep fine detail (issue #632): their base layer (`local::tone_base`) is the edge-aware filter of a separable median of log luminance (radius 0.15 % of the long edge, at most 24 px, `local::BASE_DETAIL`) instead of log luminance itself, so twigs, lines and texture take their surroundings' shift and keep their contrast; region edges stay sharp. CPU (`local::prepare`) and GPU prepare branch on `local::tone_base_detail` (0 = no median under V1); the base plane is cached per process (`local::BaseKey`). Renders without Highlights or Shadows (global or local) are the same as V1's. Tone map unchanged. | +| **V3** | Pixel-scale sharpening (issue #757): Radius uses the original photo’s pixels, Detail controls halo damping, and downsized sources retain a response-matched sharpening band. V1 and V2 keep texture-band sharpening exactly. The sharpen plane is keyed by radius and process and invalidated after noise-reduction changes. The Highlights/Shadows base and tone map are unchanged from V2. | +| **V4** (the latest) | V3 plus calibrated global Contrast (per channel) and Blacks (per-channel/luminance mix) on raws with a camera tone curve. Whites behaves exactly as V2, both signs; its calibration is a planned follow-up. Other sources and local adjustments retain V2 operators. See [calibrated Light operators](light-v3.md). | ## The rule @@ -73,7 +77,7 @@ written against the current rendering. `crs:ProcessVersion` numbers Adobe's rend ignored; a photo imported with Lightroom edits is on LightCraft's latest process, and an existing LightCraft photo that receives them keeps its own. -**A number this build doesn't know** (a library or sidecar written by a newer LightCraft) loads, is +**A number above this build's latest** (a library or sidecar written by a newer LightCraft) loads, is kept when saved, and renders with the newest process this build has. Update to Current Process never moves a photo to an older process; Reset does move it to this build's latest. @@ -88,3 +92,14 @@ The process is saved as `"process": ` in the settings JSON, except V1, w Settings made before process versions existed are therefore saved exactly as before, and their preview-cache keys (`DevelopSettings::hash64`) don't change. `develop.get` (MCP `get_develop`) always states the process. + +From process V3 on, persistent thumbnail, view-render and variant keys also include the +resolved rendering process. A future number can keep the same settings hash across builds +while resolving to different operators, so those keys must differ. V1 and V2 omit this +extra field and retain their existing cached renders. No cache-version bump is needed. + +## Revision history + +| Date | Change | Summary | +|---|---|---| +| 2026-10-12 | minor | Calibrated Contrast and Blacks, V2 Whites, resolved-process cache keys and number coordination | diff --git a/docs/raw-parity.md b/docs/raw-parity.md index 68589e3471..c5f138d5f0 100644 --- a/docs/raw-parity.md +++ b/docs/raw-parity.md @@ -1,6 +1,6 @@ # RAW parity: cameras, formats, demosaic, colour and lens profiles -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (Canon CRW decoder shared via craft-libs `craft-crw`; Canon EOS D60: chart-measured colour matrices, white balance in Kelvin; Canon CRW merged with MRW: 557 verified; CRW variant rows split by verification status; Sony ILCE-6700 in-file distortion; Minolta MRW decoded, 6 bodies verified; lossy JPEG XL DNG tiles with a non-linear declared transfer curve decode; Canon ColorData Kelvin; X-Trans CMOS 4 bodies take the X-T3's spectral matrices; AHD no longer turns flat noise into a maze pattern) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 (Camera Raw 18.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (LR-PROF-IMPORT: the user's own `.dcp` camera profiles import, checked on a real D750 profile; Canon CRW decoder shared via craft-libs `craft-crw`; Canon EOS D60: chart-measured colour matrices, white balance in Kelvin; Canon CRW merged with MRW: 557 verified; CRW variant rows split by verification status; Sony ILCE-6700 in-file distortion; Minolta MRW decoded, 6 bodies verified; lossy JPEG XL DNG tiles with a non-linear declared transfer curve decode; Canon ColorData Kelvin; X-Trans CMOS 4 bodies take the X-T3's spectral matrices; AHD no longer turns flat noise into a maze pattern) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 (Camera Raw 18.7) Raw processing is the deepest single dimension of Lightroom parity: a photographer whose camera does not decode, or decodes with the wrong colour, cannot switch. This document measures it model by @@ -219,7 +219,7 @@ sample files. A pointer for contributors, not legal advice. | Default profile per model | Adobe Standard for every model (1,500 profile names in the bundle) | the DNG's own matrices; else a pooled profile (**10 bundled**: EOS D60, ILCA-99M2, ILCE-7CR, ILCE-7M4, ILCE-7RM5, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300); else a guarded per-file fit to the camera's embedded JPEG; else spectral matrices (**52 models**, rawtoaces-data, and the bodies sharing their sensors: 6 Fujifilm bodies take the X-T3's (X-T30, X-T30 II, X-Pro3, X100V, X-E4, X-M5) and 2 take the X-T4's (X-S10, X-S20)) or chart-measured ones (**1 model**, the EOS D60); else a neutral matrix | | Camera Matching looks | 481 models (plus phone-maker looks) | none (the per-file JPEG fit imitates the camera's own look) | | Creative profiles | Adobe Color, Portrait, Landscape, Vivid, Monochrome… | our own looks (Color, Neutral, Vivid, Landscape, Portrait, Monochrome) | -| DCP / dual-illuminant model | ✅ | dual-illuminant DNG colour (ColorMatrix / ForwardMatrix 1-2, CameraCalibration, AnalogBalance), HueSatMap, LookTable, ProfileToneCurve; external `.dcp` never loaded (clean-room) | +| DCP / dual-illuminant model | ✅ | dual-illuminant DNG colour (ColorMatrix / ForwardMatrix 1-2, CameraCalibration, AnalogBalance), HueSatMap, LookTable, ProfileToneCurve; the user's own `.dcp` files can be imported as camera profiles (`crates/raw/src/dcp.rs`), none ship with the app (clean-room); a CC0 D750 chart profile develops its charts within mean ΔE2000 3.8 / 3.4 of Lightroom with the same profile | | White balance in Kelvin | ✅ for every model | absolute Kelvin where the camera has colour matrices (its own, one of the 52 spectral rows or the chart-measured EOS D60), also for files whose look is a per-file fit (#730), or where the camera's white-balance presets in the file give the scale (6 Sony bodies and the Canon PowerShot G1 X Mark III, `kelvin_presets`), or the neutral pair a Fujifilm X-Trans III RAF stores (6 bodies, #730); other raws keep the relative scale (#296) | **How far the default rendering is from Adobe's** (CIE ΔE; measured where stated): @@ -308,6 +308,8 @@ Beyond decoding: | 2026-10-15 | minor | Lossy JPEG XL DNG tiles that declare a non-linear SDR transfer curve (sRGB, BT.709, DCI, gamma) decode with that curve restored instead of falling back to the embedded preview: Lightroom Classic 15.1 LinearRaw DNGs (Rec. 2100 primaries, sRGB curve; 2 private ILCE-7CM2 files) | | 2026-10-15 | minor | Hasselblad 3FR / FFF embedded previews: the uncompressed 8-bit RGB image, handed on as a baseline TIFF (checked on the CC0 H4D-40 FFF, 1217 × 913, and CFV 3FR, 218 × 218, upright through the file's orientation); counts unchanged | | 2026-10-15 | minor | Hasselblad 3FR / FFF get their own reader (`crates/raw/src/vendor/hasselblad.rs`): an FFF takes its colour matrix from the original 3FR header in tag `0xC51B` instead of developing with the neutral matrix; RGGB checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; counts unchanged | +| 2026-10-22 | patch | LR-PROF-IMPORT: a CC0 Nikon D750 ColorChecker profile (Calibrite PROFILER, matrix-only, Cool White Fluorescent + D55) and its chart NEFs are a pinned corpus (`D750_COLORCHECKER`); with it LightCraft develops the charts within mean ΔE2000 3.84 (flash) / 3.35 (indoor), max 7.77 / 5.24, of Lightroom Classic 15.6's renders; colour patches come out less saturated | +| 2026-10-12 | minor | LR-PROF-IMPORT: the user's own DNG camera profiles (`.dcp`) import as camera profiles; none ship | | 2026-10-12 | minor | SR2/SRF folder discovery and shared CLI/MCP extensions; public DSC-R1 sensor import and DSC-F828 preview-only import agree with direct import. F828 reclassified as preview-only (219 preview, 37 unsupported in the current generated coverage); sensor-decoding scores unchanged | | 2026-10-14 | minor | Camera-coverage sweep (#1327): 30 models verified on 40 CC0 files (`coverage_sweep_corpus.rs`, `coverage-sweep.tsv`; `docs/raw/coverage.py` 515 → 545 verified rows); the counts above are not re-measured here. Sensor verification does not establish colour parity (#1277) | | 2026-10-13 | minor | Bundled camera profiles 4 → 5 (ILCA-99M2) | diff --git a/docs/roadmap.md b/docs/roadmap.md index b16c77d3f0..e8b84b8da4 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones, current focus and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** major (gap 9: roadmap item 8 no longer lists Linux, where CI runs the tests since #2667, and lists the GPU tests; created; milestones moved here from ROADMAP.md, focus re-ranked after the 2026-10-10 re-measure) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** major (LR-PROF-IMPORT: the user's own `.dcp` camera profiles import; gap 9: roadmap item 8 no longer lists Linux, where CI runs the tests since #2667, and lists the GPU tests; created; milestones moved here from ROADMAP.md, focus re-ranked after the 2026-10-10 re-measure) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 Forward-looking plan. The summary with the headline numbers is [ROADMAP.md](../ROADMAP.md); the ranked shortfalls are [gaps.md](gaps.md); the numbers come from [target-app-parity.md](target-app-parity.md). @@ -84,7 +84,7 @@ calibration: M0–M13 took ≈ 25 active hours against an estimate of ≈ 110– - **AI features** (subject / sky / people masks, generative remove) need model weights with licences we can ship; classical fallbacks first. No permissively licensed sky-segmentation or raw-denoise model was found; we may need to train our own. -- **Camera colour and lens data** is a data problem: we never use Adobe's matrices, DCPs or LCPs. +- **Camera colour and lens data** is a data problem: we never use Adobe's matrices, DCPs or LCPs (users may import their own `.dcp` camera profiles). DNG-embedded data first, then our own calibration; long-tail coverage grows over time and needs people with cameras, lenses and charts. - **Raw-format sources:** decoders are written from prose format descriptions (even ones published @@ -109,6 +109,7 @@ calibration: M0–M13 took ≈ 25 active hours against an estimate of ≈ 110– | Date | Change | Summary | |---|---|---| | 2026-10-24 | patch | Item 8 (gap 9): Linux dropped from "Tests in CI" and "the GPU tests in CI" added, because the CI gate has run the tests there since #2667; hours unchanged | +| 2026-10-12 | minor | LR-PROF-IMPORT: the user's own DNG camera profiles (`.dcp`) import as camera profiles; none ship | | 2026-10-10 | minor | Beta hours 340–600; full ready ~59% in the gate note | | 2026-10-10 | minor | Added the Alpha gate table (core-workflow gate from the revised standard): passes, stays alpha | | 2026-10-10 | major | Created: milestones moved from ROADMAP.md (statuses refreshed: M3 ✅, M11 / M12 / M15 detail), current focus re-ranked toward beta, risks and design notes kept | diff --git a/docs/user/troubleshooting/get-help.md b/docs/user/troubleshooting/get-help.md index 963c582213..5490bd1ab6 100644 --- a/docs/user/troubleshooting/get-help.md +++ b/docs/user/troubleshooting/get-help.md @@ -21,6 +21,18 @@ Open an issue in the [issue tracker](https://github.com/storytold/lightcraft/iss LightCraft writes its log to `logs/lightcraft.log` in its settings folder. On Windows that is `%APPDATA%\LightCraft\logs\`. Each start moves the previous log to `lightcraft.1.log`, and that one to `lightcraft.2.log`, so the log of a run that crashed survives the next start. +## A more detailed log + +When thumbnails or previews don't appear, appear slowly, or keep the computer busy, a log of every picture LightCraft draws helps. Start LightCraft with the environment variable `RUST_LOG` set to `warn,lightcraft*=info,lightcraft_ui_egui::render=debug`. On Windows, in PowerShell: + +```powershell +$env:RUST_LOG = "warn,lightcraft*=info,lightcraft_ui_egui::render=debug"; & "C:\Program Files\LightCraft\lightcraft.exe" +``` + +The log then has a line for each picture LightCraft asks for, with its file, and usually a line for how it ended: drawn, or dropped and why (for example, scrolled out of view, or replaced by a newer request). A few requests that are dropped while they wait, such as when photos are removed or LightCraft quits, have no ending line. A file that can't be read is still a warning. So the log shows whether a file was asked for once or many times. `LIGHTCRAFT_LOG=debug` instead turns on the detailed log of all of LightCraft. + +This log names the files LightCraft draws, with their folders. Look through it before you share it, and remove any names you'd rather keep private. + ## Still stuck? Ask in [Discord](https://discord.gg/artcraft). diff --git a/docs/whats-new.md b/docs/whats-new.md index ba7c55b843..e1ebcc7827 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,26 @@ # What's new in LightCraft +## 2026-11-01 + +### Korean and Vietnamese text in exports draws whole +- macOS often stores Korean file names decomposed (NFD), each syllable as its jamo. Contact-sheet captions, export + watermarks, slideshow overlays and print page text drew those as loose jamo (`ㅈㅔㅈㅜㄷㅗ` for `제주도`), and + decomposed Vietnamese letters lost their stacked marks. Text is now composed before it is laid out, so both draw as + they do in the app (issue #3480, #3277). + +## 2026-10-31 + +### Find Similar Photos no longer freezes the window +- The first search reads every photo in the library, and it did that on the thread that draws the window, so in a large + library the app stopped responding and Windows offered to close it (issue #3468). The photos are now read in the + background: a "Find Similar Photos" row in the activity stack counts them, you can keep working meanwhile, and its ✕ + stops the search. A stopped search leaves the view as it was, and the next one goes on from what was read. The menu + item is off while a search runs, and opening another library stops it. When a search ends the grid shows the photos it + found, also from the Photo menu, and a message says how many. `library.findSimilar` from the control channel and + `mcp --connect` still gets `{photos}`, now when the search ends; a caller that stops waiting (the control server + gives a request 60 s) can ask again once that search has ended (while it runs, a new request is refused as already + running), and what was read isn't read again. + ## 2026-10-30 ### Lens distortion correction for the Sony A7 III @@ -354,6 +375,18 @@ ## 2026-10-23 +### Export subfolders stay inside the export folder +- An export subfolder (typed in the Export dialog, saved in a preset or passed to `export`) can no longer lead + outside the chosen folder (issue #2571). `..` and `.` parts and a leading `/` are dropped, and `\` and `:` become + `_`, so a shared preset with `../..` in its subfolder writes inside your folder instead of elsewhere on disk. + Nested subfolders such as `Client/Jobs` still work. + +### Place names always download into the settings folder +- Download Place Names (for Fill Location from GPS) always saves the GeoNames files in the settings folder (issue + #2575). An agent or script driving LightCraft could name another folder and another server, and have that + server's files written there; it is now refused. Each file is saved complete or not at all, and replaces whatever + is in its place instead of writing through a link to somewhere else. + ### Videos in the grid are no longer sent to the image decoders - A video in the library (an MP4 or MOV brought in from a Lightroom catalog) no longer asks the image decoders for a grid thumbnail (issue #2682). They can't read one, so each video failed with "unrecognised image format", showed a @@ -425,6 +458,13 @@ - Saving a sidecar keeps another application's properties even when its namespace uses prefixes such as `lc` or `xmp`. Those foreign properties no longer become LightCraft settings or ratings when imported. +### The log can show every thumbnail and preview LightCraft asks for +- With `RUST_LOG=warn,lightcraft*=info,lightcraft_ui_egui::render=debug` (or `LIGHTCRAFT_LOG=debug`), the log has a + line for each picture LightCraft asks for, with its file, and one for how it ended: drawn, or dropped and why. + Before, only failures were logged, so the log couldn't tell a file asked for 37 times from one asked for once and + failing inside (issue #2682). + The usual log is unchanged. See [Get help with a problem](user/troubleshooting/get-help.md). + ### Find Missing Photos finds the files of a library made on Windows - A library made on Windows records its originals with Windows paths. Opened on macOS or Linux, its photos are missing until relinked, and Find Missing Photos found them only by their content, so it missed every photo it had @@ -1435,6 +1475,15 @@ file name, then id, instead of import order. Recently Added keeps a batch in file name order, and Auto-Stack orders a burst by file name, so the first file is the cover. +### More of the rendering on the GPU +- LUT profiles, masks with Refine Edges and soft proofing into a colour space render on the GPU (they used to send the + whole render to the CPU; soft proofing to a printer or paper profile still renders on the CPU), and so do spot removal, defringe and the histogram (they used to bounce the image through the CPU mid-render). + Results match the CPU within 3 levels in 8 bits (mean under half a level; `docs/gpu-pipeline.md`). +- Grid, filmstrip, preset and profile thumbnails render on the GPU once it is ready (about a quarter faster on an RTX + 5070, and the CPU stays free for decoding raws). +- While a slider is dragged, the loupe is drawn straight from the GPU: rendering and drawing share the window's + graphics device, so drafts are never copied to memory and back (`LIGHTCRAFT_GPU_WINDOW=0` turns this off). + ### Large preset collections - A library holding thousands of presets (a Lightroom collection imported whole: 11 000 presets, a 42 MB presets.json) stays responsive. Every command used to re-serialize the whole list to see whether it had changed diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index 254574d91b..3df5c29995 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -315,5 +315,20 @@ with a blend mode other than Normal or with a mask are reported, not applied. Bi or `.zip` bundles — as creative profiles: they appear in the profile browser under their folder's (or zip's) name and take the Amount slider (0–200 %) like the built-in looks. The LUT is applied to the finished, display-encoded colour (trilinear; `DOMAIN_MIN` / `DOMAIN_MAX` honoured; 1D LUTs are not supported); photos with a LUT profile render on the -CPU. A library on disk keeps a copy of each file in its `Profiles/` folder. Adobe's own profile formats (`.dcp`, XMP -camera/creative profiles with embedded tables) are deliberately not read. +CPU. A library on disk keeps a copy of each file in its `Profiles/` folder. XMP camera/creative profiles with embedded +tables are not read. + +## Profiles: camera profiles (`.dcp`) + +The same command (and File ▸ Import Profiles & Presets…, drag & drop) reads DNG Camera Profiles — the user's own `.dcp` +files, e.g. made with a colour-checker tool — as camera profiles (`dcp:-` ids, group *Camera Profiles*, +listed by `profiles.camera`). Read per DNG specification chapter 6 (`crates/raw/src/dcp.rs`): `ProfileName`, +`UniqueCameraModel`, `CalibrationIlluminant1/2`, `ColorMatrix1/2`, `ForwardMatrix1/2`, `ProfileHueSatMap*`, +`ProfileLookTable*`, `ProfileToneCurve` and `BaselineExposureOffset`. Choosing one (`develop.profile {id}`) replaces a raw +file's colour model when it is decoded — the file's own white balance, analog balance and baseline exposure stay, and a +profile without a `ProfileToneCurve` (most chart-made ones) keeps the photo's own contrast: the DNG's tone curve, else the +tone of the look fitted to its camera JPEG — so the +photo's source is decoded again when its profile changes; rendered (non-raw) photos ignore it. Smart previews and the +web build's render worker keep the file's own colour. A library on disk keeps a copy of each file in `Profiles/`; +`profile.deleteCamera` (or `profile.deleteImported`) removes one. No profile ships with LightCraft, and the repository +holds none: tests build theirs in memory (`lightcraft_raw::dcp::write_dcp`). diff --git a/tools/light_v3_constants.py b/tools/light_v3_constants.py new file mode 100644 index 0000000000..e5188afcd4 --- /dev/null +++ b/tools/light_v3_constants.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python3 +"""Process V4's fitted Light constants: the committed fits and the Rust file generated from them (docs/light-v3.md). + + light_v3_constants.py rust [-o crates/pipeline/src/light_v3_params.rs] [--check] + Write the Rust constants from the committed fits (tools/light_v3_fits/{contrast,blacks}.json): each + fit's parameter vector verbatim (shortest round-trip literals; crates/pipeline/src/light_v3.rs unpacks it as + Family.unpack does), where it came from, and, for the Rust tests only, Family's own curve and apply values at + fixed points (rounded to 12 significant digits, so the file is the same on every machine). Running it on a + checkout must reproduce the committed file byte for byte: --check says whether it does, writing nothing. + light_v3_constants.py sanitize FIT.json SLIDER [-o tools/light_v3_fits/SLIDER.json] + Turn a result of the fitting tool (fit_pointwise.py, kept with the private fitting data) into the committed + form: the coefficients, the counts and aggregate errors only (median per amount, reference, size and split). + Publish an error group or band only when at least three distinct photos contribute, + with no photo names, paths or per-photo values. Swapping a fit is sanitizing the new one over the slider's + file, then `rust`. + +The fitting data are private: black-box Lightroom exports of the owner's photos. A public render-fidelity tool for +measuring your own exports is proposed separately in #1181; it is not included in this checkout. + +Needs numpy only: tools/requirements-light-v3.txt. +""" + +import argparse +import hashlib +import json +import sys +from collections import defaultdict +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from light_v3_family import KNOTS as FAMILY_KNOTS, Family # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +FITS = ROOT / "tools" / "light_v3_fits" +OUT = ROOT / "crates" / "pipeline" / "src" / "light_v3_params.rs" +SLIDERS = {"contrast": "light.contrast", "blacks": "light.blacks"} +MODES = {"pc": "PerChannel", "lum": "Luminance", "mix": "Mix"} +KNOTS = [float(k) for k in FAMILY_KNOTS] +BANDS = ["<.03", ".03-.10", ".10-.25", ".25-.50", ".50-.90", ">.90"] +MIN_PHOTOS = 3 +# where the reference values are taken (encoded ProPhoto values, amounts, pixels) +REF_V = [0.0, 0.004, 0.012, 0.03, 0.07, 0.11, 0.17, 0.25, 0.33, 0.45, 0.58, 0.7, 0.81, 0.9, 0.97, 1.0] +REF_A = [-100.0, -63.0, -25.0, -4.0, -1.0, 1.0, 4.0, 25.0, 63.0, 100.0] +REF_PIX = [[0.02, 0.05, 0.01], [0.3, 0.25, 0.2], [0.55, 0.5, 0.62], [0.9, 0.85, 0.7], [0.15, 0.4, 0.35], [0.75, 0.97, 0.99]] + + +def layout(name, fit, path): + """Whether a fit is signed, after checking it against the family.""" + if fit.get("slider") != SLIDERS[name]: + sys.exit(f"{path}: a fit of {fit.get('slider')}, not {SLIDERS[name]}") + if fit.get("knots") != KNOTS: + sys.exit(f"{path}: knots {fit.get('knots')} are not the family's {KNOTS}") + if fit.get("mode") not in MODES: + sys.exit(f"{path}: unknown mode {fit.get('mode')}") + base = Family(fit["mode"]).size + n = len(fit["params"]) + if n != base: + sys.exit(f"{path}: {n} parameters, the family needs {base}") + return name == "contrast" + + + +def sanitize(args): + path = Path(args.fit) + raw = path.read_bytes() + fit = json.loads(raw) + signed = layout(args.slider, fit, path) + errors = {} + for split in ("tune", "check"): + by = defaultdict(list) + for r in fit.get(split, []): + by[(r["a_tgt"], r["a_ref"], r["long_edge"])].append(r) + rows = [] + for (a_tgt, a_ref, edge), g in sorted(by.items()): + photos = len({r["photo"] for r in g}) + if photos < MIN_PHOTOS: + continue + band_photos = {b: len({r["photo"] for r in g if b in r["cells"]}) for b in BANDS} + band_photos = {b: n for b, n in band_photos.items() if n >= MIN_PHOTOS} + bands = {b: float(np.median([r["cells"][b]["error"] for r in g if b in r["cells"]])) + for b in band_photos} + rows.append({"amount": a_tgt, "reference": a_ref, "long_edge": edge, "pairs": len(g), + "photos": photos, "encoded_error": float(np.median([r["encoded_error"] for r in g])), + "band_error": bands, "band_photos": band_photos}) + errors[split] = rows + out = { + "slider": fit["slider"], "mode": fit["mode"], "signed": signed, + "knots": fit["knots"], "params": fit["params"], "amounts": fit.get("amounts"), + "tune_pairs": fit.get("tune_pairs"), "tune_photos": fit.get("tune_photos"), + "check_pairs": fit.get("check_pairs"), "check_photos": len({r["photo"] for r in fit.get("check", [])}), + "cost": fit.get("cost") if len({r["photo"] for r in fit.get("tune", [])}) >= MIN_PHOTOS else None, + "status": fit.get("status"), + "fitted_as": {"file": path.name, "sha256": hashlib.sha256(raw).hexdigest()}, + "median_errors": errors, + } + text = json.dumps(out, indent=1) + "\n" + for bad in ("DSC", "/Users", "photo\"", ".ARW", ".arw", ".tif"): + if bad in text: + sys.exit(f"{path}: the sanitized fit still contains {bad!r}") + dest = Path(args.o) if args.o else FITS / f"{args.slider}.json" + dest.write_text(text) + print(f"{args.slider}: {path.name} -> {dest}") + + +def wrap(tokens, indent, width=140): + """Comma-separated tokens packed into lines of at most `width` characters, each indented.""" + lines, line = [], "" + for t in tokens: + if line and len(indent) + len(line) + len(t) + 2 > width: + lines.append(indent + line.rstrip()) + line = "" + line += t + ", " + if line: + lines.append(indent + line.rstrip()) + return lines + + +def exact(v): + return repr(float(v)) + + +def ref12(v): + """A reference value at 12 significant digits (numpy's last bit differs between machines and libraries).""" + s = f"{float(v):.12g}" + return s if any(c in s for c in ".en") else s + ".0" + + +def load(name): + path = FITS / f"{name}.json" + raw = path.read_bytes() + fit = json.loads(raw) + signed = layout(name, fit, path) + fam = Family(fit["mode"], signed=signed) + p = np.array(fit["params"], dtype=np.float64) + grid = np.linspace(0, 1, 20001) + ref = [] + for a in REF_A: + curve = fam.curve(p, a, np.array(REF_V)) + # Apply where the curve increases everywhere (the Rust tables flatten a fold). + increasing = bool(np.all(np.diff(fam.curve(p, a, grid)) >= 0)) + apply = fam.apply(p, a, np.array(REF_PIX)) if increasing else None + ref.append((a, list(curve), None if apply is None else [list(r) for r in apply])) + return {"name": name, "path": path.relative_to(ROOT).as_posix(), "sha256": hashlib.sha256(raw).hexdigest(), + "fit": fit, "signed": signed, "reference": ref} + + +def rust(args): + fits = [load(name) for name in SLIDERS] + out = [ + "//! Fitted constants of process V4's Contrast and Blacks ([`crate::light_v3`]).", + "//!", + "//! GENERATED by `tools/light_v3_constants.py rust` from the committed fits named below: do not edit by hand,", + "//! regenerate (the script must reproduce this file byte for byte).", + "//!", + "//! The values are fitted to black-box Lightroom exports of one person's Sony ILCE-7CR photos (the exports'", + "//! pixels only: no Lightroom code, tables or files), each slider against the same photo's Neutral or another", + "//! amount exported in the same batch, on the tune photos; the check photos were held out. The exports are", + "//! private; errors are published only with at least three contributing photos. These are our operator family's", + "//! parameters (`docs/light-v3.md`), not Lightroom's.", + "//!", + ] + for f in fits: + fit = f["fit"] + out += [f"//! - {f['name'].capitalize()}: `{f['path']}` (fitted as `{fit['fitted_as']['file']}`), mode " + f"`{fit['mode']}`; {fit['tune_pairs']} tune pairs on " + f"{fit['tune_photos']} photos, {fit['check_pairs']} check pairs on {fit['check_photos']} photos;", + f"//! sha256 `{f['sha256']}`."] + out += ["", "use crate::light_v3::{Fit, Mode};", "#[cfg(test)]", "use crate::light_v3::Reference;", "", + "/// The family's knots: the displacement shapes are piecewise linear on them.", + f"pub const KNOTS: [f64; {len(KNOTS)}] = [{', '.join(exact(k) for k in KNOTS)}];", ""] + for f in fits: + fit = f["fit"] + doc = [f"/// `{f['path']}`."] + out += [*doc, + f"pub const {f['name'].upper()}: Fit = Fit {{", + f" mode: Mode::{MODES[fit['mode']]},", + f" signed: {'true' if f['signed'] else 'false'},", + " params: &[", + *wrap([exact(v) for v in fit["params"]], " "), + " ],", + "};", + ""] + out += ["/// Where the reference values are taken: encoded values and pixels (encoded ProPhoto).", + "#[cfg(test)]", f"pub const REF_V: [f64; {len(REF_V)}] = [", *wrap(map(exact, REF_V), " "), "];", + "#[cfg(test)]", f"pub const REF_PIX: [[f64; 3]; {len(REF_PIX)}] = [", + *wrap(("[" + ", ".join(map(exact, r)) + "]" for r in REF_PIX), " "), "];", + ""] + for f in fits: + rows = [] + for a, curve, apply in f["reference"]: + rows += [" Reference {", f" amount: {exact(a)},", " curve: &[", + *wrap(map(ref12, curve), " "), " ],"] + if apply is None: + rows.append(" apply: None,") + else: + rows += [" apply: Some(&[", + *wrap(("[" + ", ".join(map(ref12, r)) + "]" for r in apply), " "), " ]),"] + rows.append(" },") + out += [f"/// The family's own `curve` at [`REF_V`] and `apply` on [`REF_PIX`] for `{f['path']}` (12 significant", + "/// digits).", "#[cfg(test)]", f"pub const {f['name'].upper()}_REFERENCE: &[Reference] = &[", *rows, + "];", ""] + dest = Path(args.o) if args.o else OUT + text = "\n".join(out) + if args.check: + same = dest.exists() and dest.read_text() == text + print(f"{dest}: {'reproduced byte for byte' if same else 'DIFFERS from what the committed fits give'}") + return 0 if same else 1 + dest.write_text(text) + for f in fits: + print(f"{f['name']}: {f['path']} ({f['fit']['fitted_as']['file']}) {f['fit']['mode']}" + f", {len(f['fit']['params'])} parameters") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + r = sub.add_parser("rust") + r.add_argument("-o"), r.add_argument("--check", action="store_true") + s = sub.add_parser("sanitize") + s.add_argument("fit"), s.add_argument("slider", choices=list(SLIDERS)), s.add_argument("-o") + args = ap.parse_args() + return rust(args) if args.cmd == "rust" else sanitize(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/light_v3_family.py b/tools/light_v3_family.py new file mode 100644 index 0000000000..c0562c48ed --- /dev/null +++ b/tools/light_v3_family.py @@ -0,0 +1,78 @@ +"""Process V3's Light operator family (docs/light-v3.md), as the fitting tool defines it. + +This is the part of the fitting tool (`fit_pointwise.py`, kept with the private fitting data) that +`light_v3_constants.py` needs to write the Rust tests' reference values: `Family.curve`, `Family.apply`, +`Family.law` and `Family.unpack` for Contrast and Blacks. `crates/pipeline/src/light_v3.rs` is the Rust port +of the same functions, and its tests compare the two. + +F_a(v) = v + s(a) D+(v) for a > 0, max(0, v - s(a) D-(v)) for a < 0, with D piecewise linear on KNOTS (D(1) = 0; +signed shapes also D(0) = 0) and s(t) = ((1 - exp(-t / tau)) / (1 - exp(-1 / tau)))^q, t = |a| / 100. v is a channel value of linear ProPhoto RGB (D50) through the sRGB +transfer curve. Modes: pc (per channel), lum (on the encoded ProPhoto luminance, linear RGB scaled by the ratio), +mix (w pc + (1 - w) lum in linear light, a weight per sign). +""" + +import numpy as np + +PRO_Y = np.array([0.2880402, 0.7118741, 0.0000857]) +KNOTS = np.array([0.0, 0.02, 0.05, 0.09, 0.14, 0.2, 0.28, 0.38, 0.5, 0.65, 0.82, 1.0]) + + +def lin(e): + return np.where(e <= 0.04045, e / 12.92, ((e + 0.055) / 1.055) ** 2.4) + + +def enc(l): + l = np.clip(l, 0.0, None) + return np.where(l <= 0.0031308, 12.92 * l, 1.055 * np.power(l, 1 / 2.4) - 0.055) + + +class Family: + def __init__(self, mode, signed=False): + self.mode = mode + # Contrast moves tones both ways around a pivot: signed shapes, anchored at black and white + self.signed = signed + self.n_shape = len(KNOTS) - 1 # D(1) = 0 + self.size = 2 * self.n_shape + 4 + (2 if mode == "mix" else 0) + + def unpack(self, p): + n = self.n_shape + d_pos = np.append(p[:n], 0.0) + d_neg = np.append(p[n:2 * n], 0.0) + if self.signed: + d_pos[0] = d_neg[0] = 0.0 + i = 2 * n + s_pos = (float(np.exp(p[i])), float(np.exp(p[i + 1]))) # (tau, q), positive amounts + s_neg = (float(np.exp(p[i + 2])), float(np.exp(p[i + 3]))) # negative amounts + i += 4 + w = (1 / (1 + np.exp(-p[i])), 1 / (1 + np.exp(-p[i + 1]))) if self.mode == "mix" else None + return d_pos, d_neg, s_pos, s_neg, w + + @staticmethod + def law(tq, a): + tau, q = tq + t = min(abs(a) / 100.0, 1.0) + tau = min(max(tau, 1e-3), 1e3) + return float(((1 - np.exp(-t / tau)) / (1 - np.exp(-1 / tau))) ** q) + + def curve(self, p, a, v): + """F_a on encoded values v (any shape).""" + if a == 0: + return v + d_pos, d_neg, s_pos, s_neg, _ = self.unpack(p) + if a > 0: + return v + self.law(s_pos, a) * np.interp(v, KNOTS, d_pos) + return np.maximum(v - self.law(s_neg, a) * np.interp(v, KNOTS, d_neg), 0.0) + + def apply(self, p, a, v): + """F_a applied to (n, 3) encoded ProPhoto pixels per the mode.""" + if self.mode == "pc": + return self.curve(p, a, v) + yl = lin(v) @ PRO_Y + ye = enc(yl) + y2 = lin(self.curve(p, a, ye)) + ratio = np.where(yl > 1e-6, y2 / np.maximum(yl, 1e-6), 1.0) + lum = enc(lin(v) * ratio[:, None]) + if self.mode == "lum": + return lum + w = self.unpack(p)[4][0 if a > 0 else 1] + return enc(w * lin(self.curve(p, a, v)) + (1 - w) * lin(lum)) diff --git a/tools/light_v3_fits/blacks.json b/tools/light_v3_fits/blacks.json new file mode 100644 index 0000000000..10be656b56 --- /dev/null +++ b/tools/light_v3_fits/blacks.json @@ -0,0 +1,629 @@ +{ + "slider": "light.blacks", + "mode": "mix", + "signed": false, + "knots": [ + 0.0, + 0.02, + 0.05, + 0.09, + 0.14, + 0.2, + 0.28, + 0.38, + 0.5, + 0.65, + 0.82, + 1.0 + ], + "params": [ + 0.0016748697345088984, + 0.032126630862752484, + 0.07188512588294256, + 0.09530584096821723, + 0.12925288090794965, + 0.12680972925019743, + 0.10913227308994669, + 0.10024857312175768, + 0.0835198499581404, + 0.05136152009684992, + 0.02045048232256003, + 0.00011845423640374467, + 0.2706623236742467, + 0.42355931120492346, + 0.37893058797626605, + 0.22045052169596244, + 0.20955478047682013, + 0.2107908996685734, + 0.16685612159796198, + 0.13055496600268582, + 0.08667135921560576, + 0.03499725744978859, + 14.344979966519135, + 0.1199976090379452, + 6.829791928600096, + 0.5956122696562978, + 0.6007994346537187, + 22.053184691621333 + ], + "amounts": { + "pos": [ + 1.0, + 2.0, + 10.0, + 25.0, + 50.0 + ], + "neg": [ + 1.0, + 2.0, + 10.0, + 25.0, + 50.0 + ] + }, + "tune_pairs": 148, + "tune_photos": 19, + "check_pairs": 60, + "check_photos": 6, + "cost": 0.0008745122527803675, + "status": "`xtol` termination condition is satisfied.", + "fitted_as": { + "file": "v2-blacks-mix.json", + "sha256": "7a4eaf80f609bce82796255f2143379c2a861d9e4ad837d8b1cee13d8ee8bbbf" + }, + "median_errors": { + "tune": [ + { + "amount": -100.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.003427741630935885, + "band_error": { + ".03-.10": 0.2213629580750902, + ".10-.25": 0.02608652782453921, + ".25-.50": 0.01578410979952499, + ".50-.90": 0.002808023738105474 + }, + "band_photos": { + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 10 + } + }, + { + "amount": -50.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.005919080768408077, + "band_error": { + "<.03": 2.540801442208995, + ".03-.10": 0.08111268411041608, + ".10-.25": 0.04438409233495842, + ".25-.50": 0.020550565205089452, + ".50-.90": 0.006222082011956415 + }, + "band_photos": { + "<.03": 13, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 10 + } + }, + { + "amount": -25.0, + "reference": 25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.0031214485072743755, + "band_error": { + "<.03": 0.16329115247026024, + ".03-.10": 0.036668113073784654, + ".10-.25": 0.022776150840884937, + ".25-.50": 0.014843370759525187, + ".50-.90": 0.0039038961386700737 + }, + "band_photos": { + "<.03": 15, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 11 + } + }, + { + "amount": -10.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0028229433114912773, + "band_error": { + "<.03": 0.13178410951728228, + ".03-.10": 0.04196128224444614, + ".10-.25": 0.01762880043633539, + ".25-.50": 0.007293565839224106, + ".50-.90": 0.002609491855638238 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": -2.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.00041129347233050275, + "band_error": { + "<.03": 0.019017656661272694, + ".03-.10": 0.005756775376322533, + ".10-.25": 0.002565234930383287, + ".25-.50": 0.001145782173166264, + ".50-.90": 0.000382322002835805 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 6 + } + }, + { + "amount": -1.0, + "reference": 1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0003722974487077393, + "band_error": { + "<.03": 0.018366070435347367, + ".03-.10": 0.004089734153371508, + ".10-.25": 0.0018553694269353212, + ".25-.50": 0.0009593820885241899, + ".50-.90": 0.0004271225438045706 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": 1.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0003760698824047078, + "band_error": { + "<.03": 0.017287292651452933, + ".03-.10": 0.004092564163348587, + ".10-.25": 0.0018455583699485529, + ".25-.50": 0.0009623571483044081, + ".50-.90": 0.0004186288558887353 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": 2.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.00020040955093125052, + "band_error": { + "<.03": 0.013753116645338119, + ".03-.10": 0.0007162453275012053, + ".10-.25": 0.0003540900235241904, + ".25-.50": 0.00038934971977656153, + ".50-.90": 0.0002782855548532337 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": 10.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.001783838738716413, + "band_error": { + "<.03": 0.05284982502051819, + ".03-.10": 0.03724809716093273, + ".10-.25": 0.019205512149578937, + ".25-.50": 0.006917961002757063, + ".50-.90": 0.0015806259646429421 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": 25.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.003709389204943277, + "band_error": { + "<.03": 0.09494415640775108, + ".03-.10": 0.0176749098453267, + ".10-.25": 0.018947490336089716, + ".25-.50": 0.013097052459767222, + ".50-.90": 0.003511734102272039 + }, + "band_photos": { + "<.03": 13, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 11 + } + }, + { + "amount": 50.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.002609444120265867, + "band_error": { + "<.03": 0.07482435736855328, + ".03-.10": 0.013436692118006998, + ".10-.25": 0.017886792958307664, + ".25-.50": 0.009087796540733195, + ".50-.90": 0.003603605087350397 + }, + "band_photos": { + "<.03": 13, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 10 + } + }, + { + "amount": 100.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.0052279389117479615, + "band_error": { + "<.03": 0.06867116555034346, + ".03-.10": 0.028802027760147397, + ".10-.25": 0.03517066425047481, + ".25-.50": 0.015005585548450773, + ".50-.90": 0.005419520070429491 + }, + "band_photos": { + "<.03": 13, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 10 + } + } + ], + "check": [ + { + "amount": -100.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.0026036276924897854, + "band_error": { + ".03-.10": 0.2724794859787279, + ".10-.25": 0.032524388827564095, + ".25-.50": 0.01623772080888221, + ".50-.90": 0.001974081452192045, + ">.90": 0.00327166522465544 + }, + "band_photos": { + ".03-.10": 6, + ".10-.25": 5, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": -50.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.00630845958129503, + "band_error": { + "<.03": 2.937882639375302, + ".03-.10": 0.08392136241031861, + ".10-.25": 0.046410663700769156, + ".25-.50": 0.020183223853684526, + ".50-.90": 0.004274811360970359, + ">.90": 0.0011760232124998261 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": -25.0, + "reference": 25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.0031592008349393005, + "band_error": { + "<.03": 0.14080623765681227, + ".03-.10": 0.0318373066028957, + ".10-.25": 0.03224211267963081, + ".25-.50": 0.016030589604536166, + ".50-.90": 0.0031808853864495733, + ">.90": 0.00110274155996526 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": -10.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.0032315112484176496, + "band_error": { + "<.03": 0.12510974742848963, + ".03-.10": 0.05015845177052797, + ".10-.25": 0.021326590472185665, + ".25-.50": 0.008380427925365043, + ".50-.90": 0.0016479323536602991, + ">.90": 0.00011413404472121791 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": -2.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.00045617733812925115, + "band_error": { + "<.03": 0.01925846038820568, + ".03-.10": 0.0063834108841469995, + ".10-.25": 0.003030159155055237, + ".25-.50": 0.001279033505962499, + ".50-.90": 0.0002698196294867122, + ">.90": 2.7633406386833942e-05 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": -1.0, + "reference": 1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.00038314168156171563, + "band_error": { + "<.03": 0.0179409887964789, + ".03-.10": 0.004554594316174306, + ".10-.25": 0.0021860614907081508, + ".25-.50": 0.0010348608044738427, + ".50-.90": 0.00027134539581991134, + ">.90": 2.327437207747032e-05 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": 1.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.00038163643693189483, + "band_error": { + "<.03": 0.01789697865555805, + ".03-.10": 0.0045282975606357224, + ".10-.25": 0.002195762186994404, + ".25-.50": 0.0009878774705477829, + ".50-.90": 0.0002783038732938448, + ">.90": 2.686083194581795e-05 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": 2.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.0001803959147575279, + "band_error": { + "<.03": 0.01212475922937082, + ".03-.10": 0.0009431699585146074, + ".10-.25": 0.000355929836981769, + ".25-.50": 0.0003440476619261129, + ".50-.90": 0.00019109718572074783, + ">.90": 1.9847289480291946e-05 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": 10.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.002290357662922615, + "band_error": { + "<.03": 0.05709934188572894, + ".03-.10": 0.0408071092493482, + ".10-.25": 0.020792684426191338, + ".25-.50": 0.007346519738751282, + ".50-.90": 0.0010646491817687589, + ">.90": 0.00026393508368777066 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": 25.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.0030198740694812503, + "band_error": { + "<.03": 0.0725997864669866, + ".03-.10": 0.022094528007660656, + ".10-.25": 0.026543951558102536, + ".25-.50": 0.01324388164672667, + ".50-.90": 0.0026208880613337988, + ">.90": 0.0010779135256942629 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": 50.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.002475906570262025, + "band_error": { + "<.03": 0.061356997170475686, + ".03-.10": 0.009863474631073559, + ".10-.25": 0.01476986021053679, + ".25-.50": 0.010247807139551512, + ".50-.90": 0.0031242534323023554, + ">.90": 0.002042051985148796 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": 100.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.004946325387271203, + "band_error": { + "<.03": 0.08131887755018244, + ".03-.10": 0.033910589363778845, + ".10-.25": 0.02538659945793769, + ".25-.50": 0.025997571830863868, + ".50-.90": 0.007104110918209644, + ">.90": 0.005182159260201775 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 5, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + } + ] + } +} diff --git a/tools/light_v3_fits/contrast.json b/tools/light_v3_fits/contrast.json new file mode 100644 index 0000000000..d6191b001d --- /dev/null +++ b/tools/light_v3_fits/contrast.json @@ -0,0 +1,688 @@ +{ + "slider": "light.contrast", + "mode": "pc", + "signed": true, + "knots": [ + 0.0, + 0.02, + 0.05, + 0.09, + 0.14, + 0.2, + 0.28, + 0.38, + 0.5, + 0.65, + 0.82, + 1.0 + ], + "params": [ + 9.797174393178826e-18, + -0.017053489024880908, + -0.04260284838408044, + -0.07195939270312468, + -0.09738651081071477, + -0.1088504066519633, + -0.10140378035603768, + -0.06947815571389163, + -0.007856500339789655, + 0.08463087858854193, + 0.1098534938016389, + 0.30583740028604467, + -0.05850866310699469, + -0.07854274245013221, + -0.09074476735486797, + -0.0906596002773617, + -0.08429179542961336, + -0.07428102082426319, + -0.05004459522573259, + -0.00906946010144, + 0.056653920573147026, + 0.09818533983265328, + 0.3070552562874873, + 0.10657448975892592, + -0.13962415708911588, + 0.37724097657204825 + ], + "amounts": { + "pos": [ + 1.0, + 2.0, + 10.0, + 20.0, + 25.0, + 50.0 + ], + "neg": [ + 1.0, + 2.0, + 10.0, + 25.0, + 50.0 + ] + }, + "tune_pairs": 155, + "tune_photos": 20, + "check_pairs": 61, + "check_photos": 6, + "cost": 0.007425023807942876, + "status": "`ftol` termination condition is satisfied.", + "fitted_as": { + "file": "v2-contrast-pc.json", + "sha256": "a3edbd6959efc611a62f77c35ec3d0228249a818e26d913a6813e966e245a218" + }, + "median_errors": { + "tune": [ + { + "amount": -100.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.011121768451379337, + "band_error": { + "<.03": 0.06473831720828421, + ".03-.10": 0.0930115027157312, + ".10-.25": 0.10855335247607187, + ".25-.50": 0.08458112931798814, + ".50-.90": 0.04951305393020604 + }, + "band_photos": { + "<.03": 15, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 11 + } + }, + { + "amount": -50.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.004286254992238507, + "band_error": { + "<.03": 0.08798561426579082, + ".03-.10": 0.023395491074571718, + ".10-.25": 0.04125160013916516, + ".25-.50": 0.02813656219386674, + ".50-.90": 0.01224863264329086 + }, + "band_photos": { + "<.03": 15, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 11 + } + }, + { + "amount": -50.0, + "reference": 50.0, + "long_edge": 6000, + "pairs": 3, + "photos": 3, + "encoded_error": 0.0056569939840179885, + "band_error": { + "<.03": 0.09798367558474397, + ".03-.10": 0.130792624631025 + }, + "band_photos": { + "<.03": 3, + ".03-.10": 3 + } + }, + { + "amount": -25.0, + "reference": 25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.006945703844995149, + "band_error": { + "<.03": 0.042459022563571834, + ".03-.10": 0.06599006511649402, + ".10-.25": 0.07119527732608275, + ".25-.50": 0.06194452558952893, + ".50-.90": 0.02380380595363875 + }, + "band_photos": { + "<.03": 15, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 12 + } + }, + { + "amount": -10.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0022531301423689854, + "band_error": { + "<.03": 0.03697373149772598, + ".03-.10": 0.03971304167226704, + ".10-.25": 0.022404234718419867, + ".25-.50": 0.009058685811361137, + ".50-.90": 0.010657569861098629 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": -2.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0003852393871073691, + "band_error": { + "<.03": 0.007012211524007572, + ".03-.10": 0.0066646566763887746, + ".10-.25": 0.00286755977345968, + ".25-.50": 0.0017240802086141635, + ".50-.90": 0.0018782060083671758 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": -1.0, + "reference": 1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0006543633779320837, + "band_error": { + "<.03": 0.01886873284344166, + ".03-.10": 0.010292594464825184, + ".10-.25": 0.005632954367000359, + ".25-.50": 0.002241935441265079, + ".50-.90": 0.0031058898304381823 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": 1.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0006527385589234222, + "band_error": { + "<.03": 0.018817926083770614, + ".03-.10": 0.010358472561087979, + ".10-.25": 0.005616058982285934, + ".25-.50": 0.0021934787509894807, + ".50-.90": 0.0030850495726458984 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": 2.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0008095368298390367, + "band_error": { + "<.03": 0.02333747747697981, + ".03-.10": 0.011422288253035966, + ".10-.25": 0.00742974381498245, + ".25-.50": 0.0038965317200995025, + ".50-.90": 0.0034447363133185732 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": 10.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0018082128746201764, + "band_error": { + "<.03": 0.045326689844745194, + ".03-.10": 0.011501487324692514, + ".10-.25": 0.019129575064688376, + ".25-.50": 0.0125055419250812, + ".50-.90": 0.0044824579865754555 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": 20.0, + "reference": 0.0, + "long_edge": 6000, + "pairs": 5, + "photos": 5, + "encoded_error": 0.00309267216217087, + "band_error": { + "<.03": 0.048859278779928295, + ".03-.10": 0.0445593256864193, + ".10-.25": 0.037886311299740134, + ".25-.50": 0.018012343705216413, + ".50-.90": 0.0076965072545667045 + }, + "band_photos": { + "<.03": 5, + ".03-.10": 5, + ".10-.25": 5, + ".25-.50": 5, + ".50-.90": 3 + } + }, + { + "amount": 25.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.007903821110042217, + "band_error": { + "<.03": 0.05150865439744394, + ".03-.10": 0.07246865874385416, + ".10-.25": 0.09144243025121834, + ".25-.50": 0.06400970326100287, + ".50-.90": 0.016674153313752264 + }, + "band_photos": { + "<.03": 15, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 10 + } + }, + { + "amount": 50.0, + "reference": -50.0, + "long_edge": 6000, + "pairs": 3, + "photos": 3, + "encoded_error": 0.006205513903254146, + "band_error": { + "<.03": 0.11470709333534655, + ".03-.10": 0.118067402841938, + ".10-.25": 0.2729320736520823 + }, + "band_photos": { + "<.03": 3, + ".03-.10": 3, + ".10-.25": 3 + } + }, + { + "amount": 50.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.013146197515222533, + "band_error": { + "<.03": 0.09093522091940583, + ".03-.10": 0.10255589841297505, + ".10-.25": 0.14165315810252282, + ".25-.50": 0.08784201480208256, + ".50-.90": 0.02373075387210262 + }, + "band_photos": { + "<.03": 15, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 10 + } + }, + { + "amount": 100.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.019644083854275383, + "band_error": { + "<.03": 0.14785079413511482, + ".03-.10": 0.28522605929536815, + ".10-.25": 0.2893249382631822, + ".25-.50": 0.15281210908420345, + ".50-.90": 0.02904286478459617 + }, + "band_photos": { + "<.03": 14, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 9 + } + } + ], + "check": [ + { + "amount": -100.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.00614368415261454, + "band_error": { + "<.03": 0.059928983720484864, + ".03-.10": 0.03849443290379879, + ".10-.25": 0.06826161779527672, + ".25-.50": 0.06509598397385213, + ".50-.90": 0.05217615569259957, + ">.90": 0.031190911184747684 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": -50.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.0023659145274087735, + "band_error": { + "<.03": 0.06470759304831414, + ".03-.10": 0.009370845846563901, + ".10-.25": 0.026351516593929925, + ".25-.50": 0.019327549018610488, + ".50-.90": 0.011562978286385712, + ">.90": 0.005461528273139457 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": -25.0, + "reference": 25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.003398590038466944, + "band_error": { + "<.03": 0.03840228695869055, + ".03-.10": 0.020796501758207908, + ".10-.25": 0.040684964046721867, + ".25-.50": 0.04701568701600178, + ".50-.90": 0.019288472096135365, + ">.90": 0.013499652156282174 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": -10.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.0020376188455170567, + "band_error": { + "<.03": 0.03620494381244924, + ".03-.10": 0.03208240175435808, + ".10-.25": 0.010473635357755147, + ".25-.50": 0.017871803195692943, + ".50-.90": 0.010263293012151831, + ">.90": 0.002715647895860737 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": -2.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.00039351188188189697, + "band_error": { + "<.03": 0.008615997075480056, + ".03-.10": 0.0061276905656996485, + ".10-.25": 0.0016374797966802114, + ".25-.50": 0.002600678552877267, + ".50-.90": 0.0017840523386103938, + ">.90": 0.0003802946498026381 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": -1.0, + "reference": 1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.0006805247753234763, + "band_error": { + "<.03": 0.018760298025893515, + ".03-.10": 0.008662470862737264, + ".10-.25": 0.00263534266805685, + ".25-.50": 0.004147011742721331, + ".50-.90": 0.0029838535914747215, + ">.90": 0.0007237557973570842 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": 1.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.0006726023263027637, + "band_error": { + "<.03": 0.01891795182475012, + ".03-.10": 0.008848860673192677, + ".10-.25": 0.0027310450646397463, + ".25-.50": 0.0042898284968232525, + ".50-.90": 0.0029359593356539817, + ">.90": 0.0007228384571375645 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": 2.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.0007419673662760145, + "band_error": { + "<.03": 0.02288867540873815, + ".03-.10": 0.008542193659454047, + ".10-.25": 0.0028634353466732527, + ".25-.50": 0.005128283993017973, + ".50-.90": 0.0033098642592463267, + ">.90": 0.0008105193292430162 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": 10.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.0011864056487623834, + "band_error": { + "<.03": 0.03999974952353827, + ".03-.10": 0.005283445715065133, + ".10-.25": 0.01467700568320757, + ".25-.50": 0.009489447536394666, + ".50-.90": 0.00398762454890003, + ">.90": 0.0016691396424735546 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": 25.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.0036202176280724597, + "band_error": { + "<.03": 0.04541808011087295, + ".03-.10": 0.032641002299673386, + ".10-.25": 0.04250708854059583, + ".25-.50": 0.049747993323797084, + ".50-.90": 0.015917120629692874, + ">.90": 0.004955059580255294 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": 50.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.005293621966822463, + "band_error": { + "<.03": 0.0887657367547818, + ".03-.10": 0.03648056023382013, + ".10-.25": 0.07667411207439194, + ".25-.50": 0.06098566466448595, + ".50-.90": 0.020046398187211347, + ">.90": 0.005424273085440311 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": 100.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.00927203928537906, + "band_error": { + "<.03": 0.11764958884120004, + ".03-.10": 0.1451408972189724, + ".10-.25": 0.10497093206952726, + ".25-.50": 0.12045842741876807, + ".50-.90": 0.023191055675967395, + ">.90": 0.0075026383932912995 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + } + ] + } +} diff --git a/tools/requirements-light-v3.txt b/tools/requirements-light-v3.txt new file mode 100644 index 0000000000..3064a1e8c3 --- /dev/null +++ b/tools/requirements-light-v3.txt @@ -0,0 +1,3 @@ +# Python packages for tools/light_v3_constants.py (crates/pipeline/src/light_v3_params.rs, docs/light-v3.md). +# python3 -m venv .venv-light-v3 && .venv-light-v3/bin/pip install -r tools/requirements-light-v3.txt +numpy==2.4.6 diff --git a/tools/test_light_v3_constants.py b/tools/test_light_v3_constants.py new file mode 100644 index 0000000000..fe3f99ca57 --- /dev/null +++ b/tools/test_light_v3_constants.py @@ -0,0 +1,69 @@ +"""Synthetic publication checks. Run with python3 -m unittest discover -s tools.""" + +import contextlib +import io +import json +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace + +import light_v3_constants as constants + + +class SanitizeTests(unittest.TestCase): + def test_counts_distinct_photos_for_each_group_and_band(self): + fit = json.loads((constants.FITS / "contrast.json").read_text()) + # Three repeated pairs from one photo must not qualify as three photos. + def row(photo, amount, bands): + return dict(photo=photo, a_tgt=amount, a_ref=0, long_edge=800, + encoded_error=0.25, cells={b: {"error": 0.5} for b in bands}) + + fit["check"] = [row("synthetic-a", 20, constants.BANDS) for _ in range(3)] + fit["check"] += [row(p, 40, constants.BANDS) for p in ("synthetic-a", "synthetic-b")] + fit["check"] += [row(p, 60, constants.BANDS[:2]) for p in ("synthetic-a", "synthetic-b", "synthetic-c")] + fit["check"] += [row("synthetic-a", 60, constants.BANDS) for _ in range(3)] + fit["check"] += [row("synthetic-b", 60, constants.BANDS[:3])] + fit["tune"] = fit["check"] + with tempfile.TemporaryDirectory() as temp: + source, dest = Path(temp) / "synthetic.json", Path(temp) / "public.json" + source.write_text(json.dumps(fit)) + with contextlib.redirect_stdout(io.StringIO()): + constants.sanitize(SimpleNamespace(fit=source, slider="contrast", o=dest)) + public = json.loads(dest.read_text()) + self.assertEqual(public["params"], fit["params"]) + self.assertEqual(public["check_photos"], 3) + for split in ("tune", "check"): + rows = public["median_errors"][split] + self.assertEqual([r["amount"] for r in rows], [60]) + self.assertEqual(rows[0]["photos"], 3) + self.assertEqual(set(rows[0]["band_error"]), set(constants.BANDS[:2])) + self.assertEqual(rows[0]["band_photos"], {b: 3 for b in constants.BANDS[:2]}) + + def test_single_photo_fit_has_no_error_aggregates(self): + fit = json.loads((constants.FITS / "contrast.json").read_text()) + fit["tune"] = [dict(photo="synthetic-a", a_tgt=20, a_ref=0, long_edge=800, + encoded_error=0.25, cells={})] + fit["check"] = [] + with tempfile.TemporaryDirectory() as temp: + source, dest = Path(temp) / "synthetic.json", Path(temp) / "public.json" + source.write_text(json.dumps(fit)) + with contextlib.redirect_stdout(io.StringIO()): + constants.sanitize(SimpleNamespace(fit=source, slider="contrast", o=dest)) + public = json.loads(dest.read_text()) + self.assertEqual(public["median_errors"], {"tune": [], "check": []}) + self.assertIsNone(public["cost"]) + + def test_committed_aggregates_have_at_least_three_photos(self): + for path in sorted(constants.FITS.glob("*.json")): + fit = json.loads(path.read_text()) + for rows in fit["median_errors"].values(): + for row in rows: + with self.subTest(fit=path.name, amount=row["amount"], edge=row["long_edge"]): + self.assertGreaterEqual(row.get("photos", row["pairs"]), 3) + self.assertEqual(set(row["band_error"]), set(row.get("band_photos", {}))) + self.assertTrue(all(n >= 3 for n in row.get("band_photos", {}).values())) + + +if __name__ == "__main__": + unittest.main() diff --git a/xtask/src/corpus.rs b/xtask/src/corpus.rs index 434d48b279..815da66b54 100644 --- a/xtask/src/corpus.rs +++ b/xtask/src/corpus.rs @@ -1,6 +1,39 @@ use super::raw_samples::RAW_SAMPLES; use super::{Command, Path, root, run}; +/// A Nikon D750 ColorChecker set released under CC0 by dieli (github.com/dieli/d750-lightcraft-colorchecker), +/// pinned to one commit: a matrix-only dual-illuminant DNG camera profile (Cool White Fluorescent + D55) +/// made with Calibrite PROFILER from the two chart shots, the chart NEFs, and Lightroom Classic 15.6's +/// renders of them with that profile. Downloaded into `corpus/d750-colorchecker/` (the repository's own +/// layout) for the `.dcp` import tests; never committed. Fields: path, URL, SHA-256. +const D750_COLORCHECKER: &[(&str, &str, &str)] = &[ + ( + "raw/chart-daylight_flash.NEF", + "https://raw.githubusercontent.com/dieli/d750-lightcraft-colorchecker/f37f4054b62fa7fb02f35ab8b7ce508f2196459d/raw/chart-daylight_flash.NEF", + "ebb6768ca1a82e3dc8b455e03842245a8e0d067045f720fbf2dcf20b90f06624", + ), + ( + "raw/chart-indoor.NEF", + "https://raw.githubusercontent.com/dieli/d750-lightcraft-colorchecker/f37f4054b62fa7fb02f35ab8b7ce508f2196459d/raw/chart-indoor.NEF", + "d687c3efd25697208bdd1015856f30d00f1c4d768237c936640b61997b6d713a", + ), + ( + "profiles/20261016_NikonD750_DualIllumination_ColorCheckerPassport.dcp", + "https://raw.githubusercontent.com/dieli/d750-lightcraft-colorchecker/f37f4054b62fa7fb02f35ab8b7ce508f2196459d/profiles/20261016_NikonD750_DualIllumination_ColorCheckerPassport.dcp", + "eb7e9465a42099628ffe61838ae4626a4bb51982492975076808c54ebf8d3d78", + ), + ( + "images/daylight_flash-lightroom.jpg", + "https://raw.githubusercontent.com/dieli/d750-lightcraft-colorchecker/f37f4054b62fa7fb02f35ab8b7ce508f2196459d/images/daylight_flash-lightroom.jpg", + "725ee289efb6edcbbb792a41df5c74df5c865d9e31e55811453a43ddfc5c7bb0", + ), + ( + "images/indoor-lightroom.jpg", + "https://raw.githubusercontent.com/dieli/d750-lightcraft-colorchecker/f37f4054b62fa7fb02f35ab8b7ce508f2196459d/images/indoor-lightroom.jpg", + "213580e9b0d8e2a76c29aa2eaa9884b724e9b605df2b723ac51af975ec84c414", + ), +]; + pub(crate) fn cmd_corpus(download: bool) -> Result<(), String> { let corpus = root().join("corpus"); println!( @@ -9,29 +42,16 @@ Tests that use a corpus skip cleanly when it is absent. corpus/raw/ raw.pixls.us samples (CC0) — lightcraft-raw decodes every file. corpus/images/ CC0 / public-domain JPEG/PNG/TIFF/HEIC samples (optional) + corpus/d750-colorchecker/ Nikon D750 ColorChecker set (CC0, dieli): a .dcp, chart NEFs, Lightroom renders ", corpus.display() ); if !download { return Ok(()); } - let dest = corpus.join("raw"); - std::fs::create_dir_all(&dest).map_err(|e| format!("create {}: {e}", dest.display()))?; let mut bad = Vec::new(); - for (name, url, sha256) in RAW_SAMPLES { - let out = dest.join(name); - if !out.exists() { - let mut curl = Command::new("curl"); - curl.args(["-fsSL", "-o"]).arg(&out).arg(url); - run(curl, &format!("curl {url}"))?; - } - let actual = file_sha256(&out)?; - if actual != *sha256 { - // delete it, so the next run downloads it again instead of trusting it - std::fs::remove_file(&out).map_err(|e| format!("remove {}: {e}", out.display()))?; - bad.push(format!("{name}: sha256 is {actual}, expected {sha256} (file deleted; source {url})")); - } - } + fetch_pinned(&corpus.join("raw"), RAW_SAMPLES, &mut bad)?; + fetch_pinned(&corpus.join("d750-colorchecker"), D750_COLORCHECKER, &mut bad)?; if bad.is_empty() { return Ok(()); } @@ -46,6 +66,29 @@ Tests that use a corpus skip cleanly when it is absent. )) } +/// Download each `(path, url, sha256)` of `files` under `dest` unless present, and check its SHA-256 +/// (a mismatch is deleted, so the next run downloads it again, and reported in `bad`). +fn fetch_pinned(dest: &Path, files: &[(&str, &str, &str)], bad: &mut Vec) -> Result<(), String> { + for (name, url, sha256) in files { + let out = dest.join(name); + if let Some(dir) = out.parent() { + std::fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?; + } + if !out.exists() { + let mut curl = Command::new("curl"); + curl.args(["-fsSL", "-o"]).arg(&out).arg(url); + run(curl, &format!("curl {url}"))?; + } + let actual = file_sha256(&out)?; + if actual != *sha256 { + // delete it, so the next run downloads it again instead of trusting it + std::fs::remove_file(&out).map_err(|e| format!("remove {}: {e}", out.display()))?; + bad.push(format!("{name}: sha256 is {actual}, expected {sha256} (file deleted; source {url})")); + } + } + Ok(()) +} + fn file_sha256(path: &Path) -> Result { use sha2::{Digest, Sha256}; let mut file = std::fs::File::open(path).map_err(|e| format!("open {}: {e}", path.display()))?; @@ -56,16 +99,25 @@ fn file_sha256(path: &Path) -> Result { #[cfg(test)] mod corpus_tests { - use super::RAW_SAMPLES; + use super::{D750_COLORCHECKER, RAW_SAMPLES}; #[test] fn every_sample_has_a_unique_name_and_a_sha256() { - let mut names: Vec<_> = RAW_SAMPLES.iter().map(|s| s.0).collect(); - names.sort_unstable(); - names.dedup(); - assert_eq!(names.len(), RAW_SAMPLES.len(), "duplicate file name"); - for (name, _, sha256) in RAW_SAMPLES { - assert!(sha256.len() == 64 && sha256.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')), "{name}: not a lowercase sha256"); + for set in [RAW_SAMPLES, D750_COLORCHECKER] { + let mut names: Vec<_> = set.iter().map(|s| s.0).collect(); + names.sort_unstable(); + names.dedup(); + assert_eq!(names.len(), set.len(), "duplicate file name"); + for (name, _, sha256) in set { + assert!(sha256.len() == 64 && sha256.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')), "{name}: not a lowercase sha256"); + } + } + } + + #[test] + fn the_d750_set_is_pinned_to_one_commit() { + for (name, url, _) in D750_COLORCHECKER { + assert!(url.contains("/f37f4054b62fa7fb02f35ab8b7ce508f2196459d/") && url.ends_with(name), "{name}: {url}"); } } } diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index 2a881155bc..934135a020 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -47,6 +47,7 @@ pub const TABLE: &[(&str, Class)] = &[ ("codecs", Class::Layer(1)), ("meta", Class::Layer(1)), ("develop", Class::Layer(1)), + ("film", Class::Layer(1)), ("lensdb", Class::Layer(2)), ("inpaint", Class::Layer(1)), ("faces", Class::Layer(1)),