From 423d209d164d0ac18426d0caf5dc823fd1ac4e1e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 22:24:20 -0700 Subject: [PATCH 01/39] LR-PREF-DISPLAY: Windows previews follow the monitor's colour profile While no monitor profile is chosen in Settings > Display, Windows now shows previews through the profile Windows Color System assigns to the monitor showing the window (per-user or system), as macOS and Linux already do. It is read about once a second, so moving the window to another monitor and changing the profile in Windows are followed without a restart. While Windows colour-manages the desktop itself (HDR, Auto Color Management), previews stay sRGB. The Win32 calls live in a new L0 helper crate, crates/wincolor, the second crate allowed `unsafe` after crates/sysmem (SAFETY comments on every block, safe API, Unknown on any failure); CLAUDE.md and AGENTS.md name it. GDI's GetICMProfileW keeps the profile a process first saw, so WCS is read directly and GetICMProfileW is only a fallback. The profile-file loader moves from the Linux-only colord.rs to a shared profile_file.rs (unchanged), with a cache that re-reads a file only when it changes. Verified on Windows 11 by setting and clearing a Display P3 profile and toggling HDR while the app ran. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K93HTyCiwYvbRGaAkjPvXn --- AGENTS.md | 7 +- CLAUDE.md | 7 +- Cargo.lock | 10 + Cargo.toml | 1 + apps/lightcraft/Cargo.toml | 5 + apps/lightcraft/src/colord.rs | 30 +- apps/lightcraft/src/main.rs | 10 +- apps/lightcraft/src/profile_file.rs | 87 ++++++ apps/lightcraft/src/win_screen_profile.rs | 40 +++ crates/ui-egui/src/lib.rs | 3 +- crates/wincolor/Cargo.toml | 32 ++ crates/wincolor/src/lib.rs | 345 ++++++++++++++++++++++ docs/architecture.md | 2 +- docs/display-profiles.md | 26 +- docs/gaps.md | 5 +- docs/hardware-parity.md | 11 +- docs/parity-checklist.md | 5 +- docs/whats-new.md | 12 + xtask/src/layers.rs | 1 + 19 files changed, 586 insertions(+), 53 deletions(-) create mode 100644 apps/lightcraft/src/profile_file.rs create mode 100644 apps/lightcraft/src/win_screen_profile.rs create mode 100644 crates/wincolor/Cargo.toml create mode 100644 crates/wincolor/src/lib.rs diff --git a/AGENTS.md b/AGENTS.md index c9f54b71da..21073fb4a9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,9 +40,10 @@ of it. Full standard: `../craftrules/standards/never-crash.md` "unsupported" error or is disabled. Sole exception: a provably infallible literal, as `#[allow(clippy::expect_used)]` + `.expect("why it can't fail")`. - **`unsafe` lives only in `crates/sysmem`** (one FFI call, `malloc_zone_pressure_relief`, that returns freed - allocator pages to macOS after raw decodes). Every other production crate root has `#![forbid(unsafe_code)]`. A new - unsafe need goes in an isolated, well-tested helper crate like it: `// SAFETY:` on every block, a safe API, a safe - fallback where possible, and a line here naming it. + allocator pages to macOS after raw decodes) **and `crates/wincolor`** (Win32 calls that read the colour profile + Windows assigns to the monitor showing the window, and whether Windows colour-manages that monitor itself). Every + other production crate root has `#![forbid(unsafe_code)]`. A new unsafe need goes in an isolated, well-tested helper + crate like them: `// SAFETY:` on every block, a safe API, a safe fallback where possible, and a line here naming it. - **Input-derived numbers are hostile:** `get()` instead of `[i]`/`[a..b]` for offsets from files, users, agents or arithmetic on them; checked/saturating math for lengths, offsets and counts; no division by zero, NaN/inf or negative casts to `usize`; cap allocations sized by input; slice strings only at char boundaries. diff --git a/CLAUDE.md b/CLAUDE.md index 00a2314aa9..0ba29f185a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -41,9 +41,10 @@ of it. Full standard: `../craftrules/standards/never-crash.md` "unsupported" error or is disabled. Sole exception: a provably infallible literal, as `#[allow(clippy::expect_used)]` + `.expect("why it can't fail")`. - **`unsafe` lives only in `crates/sysmem`** (one FFI call, `malloc_zone_pressure_relief`, that returns freed - allocator pages to macOS after raw decodes). Every other production crate root has `#![forbid(unsafe_code)]`. A new - unsafe need goes in an isolated, well-tested helper crate like it: `// SAFETY:` on every block, a safe API, a safe - fallback where possible, and a line here naming it. + allocator pages to macOS after raw decodes) **and `crates/wincolor`** (Win32 calls that read the colour profile + Windows assigns to the monitor showing the window, and whether Windows colour-manages that monitor itself). Every + other production crate root has `#![forbid(unsafe_code)]`. A new unsafe need goes in an isolated, well-tested helper + crate like them: `// SAFETY:` on every block, a safe API, a safe fallback where possible, and a line here naming it. - **Input-derived numbers are hostile:** `get()` instead of `[i]`/`[a..b]` for offsets from files, users, agents or arithmetic on them; checked/saturating math for lengths, offsets and counts; no division by zero, NaN/inf or negative casts to `usize`; cap allocations sized by input; slice strings only at char boundaries. diff --git a/Cargo.lock b/Cargo.lock index a49ec38db9..625613a279 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3088,12 +3088,14 @@ dependencies = [ "lightcraft-sysmem", "lightcraft-testkit", "lightcraft-ui-egui", + "lightcraft-wincolor", "log", "muda", "objc2 0.6.4", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "pollster 1.0.1", + "raw-window-handle", "rfd", "serde_json", "winit", @@ -3553,6 +3555,14 @@ dependencies = [ "web-sys", ] +[[package]] +name = "lightcraft-wincolor" +version = "0.10.0" +dependencies = [ + "lightcraft-testkit", + "windows-sys 0.61.2", +] + [[package]] name = "linebender_resource_handle" version = "0.1.1" diff --git a/Cargo.toml b/Cargo.toml index c76095d2d6..31d872bcfe 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ lightcraft-denoise = { path = "crates/denoise", default-features = false } lightcraft-geom = { path = "crates/geom" } lightcraft-faces = { path = "crates/faces" } lightcraft-sysmem = { path = "crates/sysmem" } +lightcraft-wincolor = { path = "crates/wincolor" } lightcraft-color = { path = "crates/color" } lightcraft-raster = { path = "crates/raster" } lightcraft-tiff = { path = "crates/tiff" } diff --git a/apps/lightcraft/Cargo.toml b/apps/lightcraft/Cargo.toml index 26122c3e62..16d5d56e71 100644 --- a/apps/lightcraft/Cargo.toml +++ b/apps/lightcraft/Cargo.toml @@ -43,6 +43,11 @@ rfd = { workspace = true } [target.'cfg(target_os = "linux")'.dependencies] zbus = { workspace = true } +[target.'cfg(windows)'.dependencies] +# the colour profile of the monitor showing the window (`win_screen_profile`) +lightcraft-wincolor = { workspace = true } +raw-window-handle = "0.6" + [target.'cfg(target_os = "macos")'.dependencies] muda = { workspace = true } objc2 = { workspace = true } diff --git a/apps/lightcraft/src/colord.rs b/apps/lightcraft/src/colord.rs index 70f7fbdd27..a517ba2b03 100644 --- a/apps/lightcraft/src/colord.rs +++ b/apps/lightcraft/src/colord.rs @@ -18,8 +18,6 @@ use std::time::Duration; const POLL: Duration = Duration::from_secs(3); /// A wait before trying again when colord isn't there (not installed, no system bus). const RETRY: Duration = Duration::from_secs(30); -/// The largest profile file read (real display profiles are a few KiB to a few MiB). -const MAX_PROFILE: u64 = 16 << 20; const SERVICE: &str = "org.freedesktop.ColorManager"; const DEVICE: &str = "org.freedesktop.ColorManager.Device"; @@ -72,7 +70,7 @@ fn read(conn: &zbus::blocking::Connection) -> Option> { } } let file = pick(&files)?; - load(std::path::Path::new(file)) + crate::profile_file::load(std::path::Path::new(file)) } /// The profile to use for these displays' profile files: the one they share, `None` with none or @@ -83,15 +81,6 @@ fn pick(files: &[String]) -> Option<&str> { named.all(|f| f == first).then_some(first) } -/// The bytes of profile file `path`, `None` when it can't be read or is implausibly large. -fn load(path: &std::path::Path) -> Option> { - use std::io::Read as _; - let file = std::fs::File::open(path).ok()?; - let mut bytes = Vec::new(); - file.take(MAX_PROFILE + 1).read_to_end(&mut bytes).ok()?; - (!bytes.is_empty() && bytes.len() as u64 <= MAX_PROFILE).then_some(bytes) -} - #[cfg(test)] mod tests { use super::*; @@ -105,21 +94,4 @@ mod tests { assert_eq!(pick(&s(&["/a.icc", "/b.icc"])), None, "which one the window is on isn't known"); assert_eq!(pick(&s(&[""])), None); } - - #[test] - fn profile_files_are_read_with_a_size_cap() { - let dir = std::env::temp_dir().join(format!("colord-test-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let small = dir.join("small.icc"); - std::fs::write(&small, b"acsp").unwrap(); - assert_eq!(load(&small).as_deref(), Some(&b"acsp"[..])); - let empty = dir.join("empty.icc"); - std::fs::write(&empty, b"").unwrap(); - assert_eq!(load(&empty), None); - assert_eq!(load(&dir.join("missing.icc")), None); - let big = dir.join("big.icc"); - std::fs::File::create(&big).unwrap().set_len(MAX_PROFILE + 1).unwrap(); - assert_eq!(load(&big), None); - std::fs::remove_dir_all(&dir).unwrap(); - } } diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 95739b3e97..b589ceecab 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -33,8 +33,12 @@ mod hdr_display; mod logging; #[cfg(target_os = "macos")] mod native_menu; +#[cfg(any(target_os = "linux", windows))] +mod profile_file; #[cfg(target_os = "macos")] mod screen_profile; +#[cfg(windows)] +mod win_screen_profile; mod window_gpu; use dialog_filter::FileDialogExt as _; @@ -633,7 +637,11 @@ fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::path::Path> // Linux: the profile the desktop assigns in colord, read off the UI thread #[cfg(target_os = "linux")] screen_profile: Some(colord::service()), - #[cfg(not(any(target_os = "macos", target_os = "linux")))] + // Windows: the profile it uses for the window's monitor, unless it colour-manages the + // desktop itself (HDR, Auto Color Management) + #[cfg(windows)] + screen_profile: win_screen_profile::service(cc), + #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))] screen_profile: None, pick_display_profile: Some(Box::new(|| { let mut d = file_dialog() diff --git a/apps/lightcraft/src/profile_file.rs b/apps/lightcraft/src/profile_file.rs new file mode 100644 index 0000000000..605fa3e2c9 --- /dev/null +++ b/apps/lightcraft/src/profile_file.rs @@ -0,0 +1,87 @@ +//! Reading a display's ICC profile file for the screen-profile services (`colord` on Linux, +//! `win_screen_profile` on Windows). + +use std::path::{Path, PathBuf}; +use std::time::SystemTime; + +/// The largest profile file read (real display profiles are a few KiB to a few MiB). +pub const MAX_PROFILE: u64 = 16 << 20; + +/// The bytes of profile file `path`, `None` when it can't be read or is implausibly large. +pub fn load(path: &Path) -> Option> { + use std::io::Read as _; + let file = std::fs::File::open(path).ok()?; + let mut bytes = Vec::new(); + file.take(MAX_PROFILE + 1).read_to_end(&mut bytes).ok()?; + (!bytes.is_empty() && bytes.len() as u64 <= MAX_PROFILE).then_some(bytes) +} + +/// A profile file read again only when it changes: the services are asked about once a second, and +/// calibration software rewrites its profile under the same name. +#[cfg_attr(not(windows), allow(dead_code))] +#[derive(Default)] +pub struct Cached { + /// The file last read: its path, length and modification time. + stamp: Option<(PathBuf, u64, Option)>, + bytes: Option>, +} + +#[cfg_attr(not(windows), allow(dead_code))] +impl Cached { + /// The bytes of profile file `path`, read again when it isn't the file read last time or has + /// changed since (see [`load`]). + pub fn read(&mut self, path: &Path) -> Option> { + let stamp = std::fs::metadata(path).ok().map(|m| (path.to_path_buf(), m.len(), m.modified().ok())); + if stamp.is_none() || stamp != self.stamp { + self.bytes = stamp.as_ref().and_then(|_| load(path)); + self.stamp = stamp; + } + self.bytes.clone() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn profile_files_are_read_with_a_size_cap() { + let dir = std::env::temp_dir().join(format!("profile-file-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let small = dir.join("small.icc"); + std::fs::write(&small, b"acsp").unwrap(); + assert_eq!(load(&small).as_deref(), Some(&b"acsp"[..])); + let empty = dir.join("empty.icc"); + std::fs::write(&empty, b"").unwrap(); + assert_eq!(load(&empty), None); + assert_eq!(load(&dir.join("missing.icc")), None); + let big = dir.join("big.icc"); + std::fs::File::create(&big).unwrap().set_len(MAX_PROFILE + 1).unwrap(); + assert_eq!(load(&big), None); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn a_cached_profile_is_read_again_when_the_file_changes() { + let dir = std::env::temp_dir().join(format!("profile-cache-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (a, b) = (dir.join("a.icc"), dir.join("b.icc")); + std::fs::write(&a, b"first").unwrap(); + std::fs::write(&b, b"other").unwrap(); + let mut cache = Cached::default(); + assert_eq!(cache.read(&a).as_deref(), Some(&b"first"[..])); + assert_eq!(cache.read(&a).as_deref(), Some(&b"first"[..])); + // another monitor's profile + assert_eq!(cache.read(&b).as_deref(), Some(&b"other"[..])); + // rewritten under the same name (a different length, so the change shows whatever the + // file system's time resolution) + std::fs::write(&b, b"calibrated").unwrap(); + assert_eq!(cache.read(&b).as_deref(), Some(&b"calibrated"[..])); + // gone: nothing, then read again once it is back + std::fs::remove_file(&b).unwrap(); + assert_eq!(cache.read(&b), None); + std::fs::write(&b, b"back").unwrap(); + assert_eq!(cache.read(&b).as_deref(), Some(&b"back"[..])); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/apps/lightcraft/src/win_screen_profile.rs b/apps/lightcraft/src/win_screen_profile.rs new file mode 100644 index 0000000000..4fc91d8df0 --- /dev/null +++ b/apps/lightcraft/src/win_screen_profile.rs @@ -0,0 +1,40 @@ +//! The ICC profile Windows assigns to the monitor showing LightCraft's window. +//! +//! On an SDR desktop Windows passes what an app draws to the monitor unchanged, so sRGB previews +//! look oversaturated on a wide-gamut monitor and ignore a calibration. While no monitor profile is +//! chosen in Settings ▸ Display, previews are shown through the profile Windows uses for the window's +//! monitor (`Services::screen_profile`, see `lightcraft_wincolor`), followed when the window moves to +//! another monitor or the profile changes in Windows' Color Management. When Windows colour-manages +//! the desktop itself (HDR, Auto Color Management) previews stay sRGB, as Windows expects then. + +use lightcraft_wincolor::MonitorColor; + +/// The service the UI polls, for the window `cc` belongs to; `None` when its handle isn't a Win32 one. +pub fn service(cc: &eframe::CreationContext<'_>) -> Option { + use raw_window_handle::{HasWindowHandle, RawWindowHandle}; + let RawWindowHandle::Win32(handle) = cc.window_handle().ok()?.as_raw() else { return None }; + let hwnd = handle.hwnd.get(); + let mut file = crate::profile_file::Cached::default(); + let mut last: Option = None; + Some(Box::new(move || { + let answer = lightcraft_wincolor::monitor_color(hwnd); + if last.as_ref() != Some(&answer) { + log::info!("screen profile: {}", describe(&answer)); + last = Some(answer.clone()); + } + match answer { + MonitorColor::Profile(path) => file.read(&path), + MonitorColor::ManagedByWindows | MonitorColor::NoProfile | MonitorColor::Unknown => None, + } + })) +} + +/// For the log: what the window's monitor answered. +fn describe(answer: &MonitorColor) -> String { + match answer { + MonitorColor::Profile(path) => format!("the monitor's profile, {}", path.display()), + MonitorColor::ManagedByWindows => "Windows colour-manages this monitor (HDR or Auto Color Management): previews are sRGB".into(), + MonitorColor::NoProfile => "no profile is assigned to the monitor: previews are sRGB".into(), + MonitorColor::Unknown => "not known for this monitor: previews are sRGB".into(), + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bb290bd86e..9713e94705 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -248,7 +248,8 @@ pub struct Services { /// Open dialog for a monitor ICC profile (`.icc` / `.icm`; Settings ▸ Display; desktop only). pub pick_display_profile: Option, /// The profile of the screen showing the window, used while none is chosen in Settings ▸ - /// Display (macOS, whose windows aren't colour-managed: issue #787). + /// Display: macOS's screen profile (its windows aren't colour-managed: issue #787), colord's on + /// Linux, and on Windows the monitor's (none while Windows colour-manages the desktop itself). pub screen_profile: Option, /// Save dialog for an exported `.lcpreset` file. pub save_preset_file: Option, diff --git a/crates/wincolor/Cargo.toml b/crates/wincolor/Cargo.toml new file mode 100644 index 0000000000..d7b1c6e8df --- /dev/null +++ b/crates/wincolor/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "lightcraft-wincolor" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "LightCraft wincolor (L0): the colour profile Windows assigns to the monitor showing a window. One of the two crates allowed `unsafe` (Win32 calls)." + +# Opts out of the workspace lints only to keep `unsafe_code = "deny"` overridable for the Win32 +# module below, as `crates/sysmem` does; every other crate root has `#![forbid(unsafe_code)]`. See +# AGENTS.md and craftrules standards/never-crash.md ("isolated helper library crate"). +[lints.rust] +unsafe_code = "deny" + +[lints.clippy] +dbg_macro = "warn" +todo = "warn" + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = [ + "Win32_Foundation", + "Win32_Graphics_Gdi", + "Win32_UI_ColorSystem", + "Win32_Devices_Display", +] } + +[dev-dependencies] +# tests record why they skip (`cargo xtask ci` lists the skips) +lightcraft-testkit = { workspace = true } + +# the desktop window, for a test +[target.'cfg(windows)'.dev-dependencies] +windows-sys = { version = "0.61", features = ["Win32_UI_WindowsAndMessaging"] } diff --git a/crates/wincolor/src/lib.rs b/crates/wincolor/src/lib.rs new file mode 100644 index 0000000000..1e7cec935a --- /dev/null +++ b/crates/wincolor/src/lib.rs @@ -0,0 +1,345 @@ +//! The colour profile Windows assigns to the monitor showing a window. +//! +//! On an SDR desktop Windows doesn't colour-manage ordinary windows: the values an app draws go to +//! the monitor as they are, so on a wide-gamut monitor sRGB previews look oversaturated, and on a +//! calibrated one the calibration is ignored. Photo apps convert to the monitor's profile themselves. +//! LightCraft reads it here and shows previews through it while no profile is chosen in Settings ▸ +//! Display, as it does with the screen's profile on macOS and colord's on Linux. +//! +//! When Windows colour-manages the desktop itself (HDR, or Auto Color Management on Windows 11), it +//! treats what an ordinary app draws as sRGB and converts it for the monitor; converting in the app +//! too would do it twice, so the answer is then [`MonitorColor::ManagedByWindows`]. +//! +//! The profile comes from Windows Color System, which holds what Settings ▸ Display ▸ Color profile +//! and Color Management assign, per user or for the system: it is read afresh on every call, so a +//! change shows without restarting. (GDI's `GetICMProfileW` answers what the profile was when the +//! process first asked, and serves only as a fallback when the monitor's device can't be found.) +//! +//! The Win32 calls (`MonitorFromWindow`, `GetMonitorInfoW`, `EnumDisplayDevicesW`, the `Wcs…` +//! profile functions, `QueryDisplayConfig` + `DisplayConfigGetDeviceInfo`) are in the `win32` module, +//! the only place besides `crates/sysmem` where LightCraft allows `unsafe`. The API is safe, and any +//! failure answers [`MonitorColor::Unknown`]. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::path::PathBuf; + +/// What Windows says about colour on the monitor showing a window. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum MonitorColor { + /// Windows colour-manages this monitor's desktop (HDR or Auto Color Management): an app draws + /// sRGB and converts nothing. + ManagedByWindows, + /// The ICC profile assigned to the monitor (the user's own when they chose per-user profiles, + /// else the system's). + Profile(PathBuf), + /// No profile is assigned: Windows treats the monitor as sRGB. + NoProfile, + /// Not known: not Windows, no such window, or a call failed. + Unknown, +} + +/// What Windows says about colour on the monitor the window `hwnd` is mostly on (the nearest one +/// when it is off screen or minimised). `hwnd` is the window's `HWND` as an integer; anything that +/// isn't a window answers [`MonitorColor::Unknown`]. +pub fn monitor_color(hwnd: isize) -> MonitorColor { + #[cfg(windows)] + { + win32::monitor_color(hwnd) + } + #[cfg(not(windows))] + { + let _ = hwnd; + MonitorColor::Unknown + } +} + +/// `true` when Windows colour-manages the desktop on a display with these advanced-colour flags +/// (`DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO`'s bit field): advanced colour enabled (bit 1: HDR, or +/// Auto Color Management) or wide colour enforced (bit 2). +#[cfg(any(windows, test))] +fn managed(flags: u32) -> bool { + flags & 0b110 != 0 +} + +/// The text of a NUL-terminated UTF-16 buffer (all of it without a NUL). +#[cfg(any(windows, test))] +fn until_nul(units: &[u16]) -> &[u16] { + units.iter().position(|&u| u == 0).and_then(|n| units.get(..n)).unwrap_or(units) +} + +#[cfg(windows)] +#[allow(unsafe_code)] +mod win32 { + use super::{MonitorColor, managed, until_nul}; + use std::ffi::OsString; + use std::os::windows::ffi::OsStringExt; + use std::path::PathBuf; + use windows_sys::Win32::Devices::Display::{ + DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO, DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_DEVICE_INFO_HEADER, + DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO, DISPLAYCONFIG_MODE_INFO, DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_SOURCE_DEVICE_NAME, + DisplayConfigGetDeviceInfo, GetDisplayConfigBufferSizes, QDC_ONLY_ACTIVE_PATHS, QueryDisplayConfig, + }; + use windows_sys::Win32::Foundation::{ERROR_SUCCESS, HWND}; + use windows_sys::Win32::Graphics::Gdi::{ + CreateDCW, DISPLAY_DEVICE_ACTIVE, DISPLAY_DEVICEW, DeleteDC, EnumDisplayDevicesW, GetMonitorInfoW, MONITOR_DEFAULTTONEAREST, MONITORINFO, + MONITORINFOEXW, MonitorFromWindow, + }; + use windows_sys::Win32::UI::ColorSystem::{ + CPST_NONE, CPT_ICC, GetColorDirectoryW, GetICMProfileW, WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER, WCS_PROFILE_MANAGEMENT_SCOPE_SYSTEM_WIDE, + WcsGetDefaultColorProfile, WcsGetDefaultColorProfileSize, WcsGetUsePerUserProfiles, + }; + + /// The most display paths read (a machine has a handful). + const MAX_PATHS: u32 = 64; + /// The most monitors looked at on one display output (several in clone mode). + const MAX_MONITORS: u32 = 16; + /// The device class of monitors in Windows Color System (`'mntr'`, as in an ICC header). + const CLASS_MONITOR: u32 = u32::from_be_bytes(*b"mntr"); + /// The longest profile name read, in bytes (names are file names in the colour directory). + const MAX_NAME_BYTES: u32 = 64 << 10; + + pub fn monitor_color(hwnd: isize) -> MonitorColor { + let Some(device) = monitor_device(hwnd) else { return MonitorColor::Unknown }; + if managed_by_windows(&device) == Some(true) { + return MonitorColor::ManagedByWindows; + } + // (an unknown advanced-colour state, as on Windows before 10 1709 or with a driver that + // doesn't say, counts as not managed) + match monitor_id(&device) { + Some(id) => wcs_profile(&id), + None => icm_profile(&device).map_or(MonitorColor::Unknown, MonitorColor::Profile), + } + } + + /// The GDI device name (`\\.\DISPLAY1`) of the monitor showing `hwnd`, NUL-terminated. + fn monitor_device(hwnd: isize) -> Option<[u16; 32]> { + if hwnd == 0 { + return None; + } + // SAFETY: `MonitorFromWindow` takes any handle value: window handles are looked up in the + // system's table, not dereferenced, and one that isn't a window gives a null monitor (or + // the nearest monitor). It writes nothing. + let monitor = unsafe { MonitorFromWindow(hwnd as HWND, MONITOR_DEFAULTTONEAREST) }; + if monitor.is_null() { + return None; + } + let mut info = MONITORINFOEXW::default(); + info.monitorInfo.cbSize = size_of::() as u32; + // SAFETY: `info` is a `MONITORINFOEXW` whose `cbSize` says so, and the pointer is taken from + // the whole struct, so `GetMonitorInfoW` may write all of it (it writes at most `cbSize` + // bytes). `monitor` came from `MonitorFromWindow` just above. + let ok = unsafe { GetMonitorInfoW(monitor, (&raw mut info).cast::()) }; + (ok != 0 && !until_nul(&info.szDevice).is_empty() && info.szDevice.contains(&0)).then_some(info.szDevice) + } + + /// The device id (`MONITOR\GSM7750\{…}\0002`) of the monitor on display output `device`, as + /// Windows Color System names it, NUL-terminated: the first active monitor there. + fn monitor_id(device: &[u16; 32]) -> Option<[u16; 128]> { + if !device.contains(&0) { + return None; + } + let mut first = None; + for i in 0..MAX_MONITORS { + let mut dd = DISPLAY_DEVICEW { cb: size_of::() as u32, ..Default::default() }; + // SAFETY: `device` is NUL-terminated (checked above) and `dd` is a `DISPLAY_DEVICEW` whose + // `cb` says so; `EnumDisplayDevicesW` writes at most that struct and fails past the last + // monitor. + if unsafe { EnumDisplayDevicesW(device.as_ptr(), i, &mut dd, 0) } == 0 { + break; + } + if until_nul(&dd.DeviceID).is_empty() || !dd.DeviceID.contains(&0) { + continue; + } + if dd.StateFlags & DISPLAY_DEVICE_ACTIVE != 0 { + return Some(dd.DeviceID); + } + first.get_or_insert(dd.DeviceID); + } + first + } + + /// The profile Windows Color System assigns to monitor `id`: in the user's scope when they chose + /// per-user profiles for it, else the system's. + fn wcs_profile(id: &[u16; 128]) -> MonitorColor { + let mut per_user = 0; + // SAFETY: `id` is NUL-terminated (from `monitor_id`); one `BOOL` to write. + let asked = unsafe { WcsGetUsePerUserProfiles(id.as_ptr(), CLASS_MONITOR, &mut per_user) }; + let scope = if asked != 0 && per_user != 0 { WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER } else { WCS_PROFILE_MANAGEMENT_SCOPE_SYSTEM_WIDE }; + let mut bytes = 0u32; + // SAFETY: as above; one `u32` to write (the name's size in bytes, its NUL included). It fails + // when no profile is assigned in that scope. + if unsafe { WcsGetDefaultColorProfileSize(scope, id.as_ptr(), CPT_ICC, CPST_NONE, 0, &mut bytes) } == 0 { + return MonitorColor::NoProfile; + } + if !(4..=MAX_NAME_BYTES).contains(&bytes) { + return MonitorColor::Unknown; + } + let mut name = vec![0u16; bytes.div_ceil(2) as usize]; + // SAFETY: `name` holds at least `bytes` bytes, the size given; Windows writes at most that. + if unsafe { WcsGetDefaultColorProfile(scope, id.as_ptr(), CPT_ICC, CPST_NONE, 0, bytes, name.as_mut_ptr()) } == 0 { + return MonitorColor::Unknown; + } + let name = PathBuf::from(OsString::from_wide(until_nul(&name))); + if name.as_os_str().is_empty() { + return MonitorColor::NoProfile; + } + // a name is a file in the colour directory (a full path is kept as it is) + if name.is_absolute() { + return MonitorColor::Profile(name); + } + color_directory().map_or(MonitorColor::Unknown, |dir| MonitorColor::Profile(dir.join(name))) + } + + /// The system's colour directory (`…\spool\drivers\color`), where profiles are installed. + fn color_directory() -> Option { + let mut dir = [0u16; 1024]; + let mut bytes = size_of_val(&dir) as u32; + // SAFETY: a null machine name means this one; `dir` holds `bytes` bytes, and Windows writes at + // most that many (failing when the path doesn't fit), updating `bytes`. + let ok = unsafe { GetColorDirectoryW(std::ptr::null(), dir.as_mut_ptr(), &mut bytes) }; + let dir = until_nul(&dir); + (ok != 0 && !dir.is_empty()).then(|| PathBuf::from(OsString::from_wide(dir))) + } + + /// GDI's profile for the display `device`: what it was when this process first asked (see the + /// crate notes), for when the monitor's device isn't found. + fn icm_profile(device: &[u16; 32]) -> Option { + if !device.contains(&0) { + return None; + } + // SAFETY: `device` is NUL-terminated (checked above); the driver, port and mode may be null, + // which makes a DC for that display. A null result is handled below. + let dc = unsafe { CreateDCW(std::ptr::null(), device.as_ptr(), std::ptr::null(), std::ptr::null()) }; + if dc.is_null() { + return None; + } + // (profile paths are under the colour directory, well within this) + let mut name = [0u16; 1024]; + let mut len = name.len() as u32; + // SAFETY: `dc` is the valid DC created above; `name` holds `len` UTF-16 units and + // `GetICMProfileW` writes at most that many (failing when the name doesn't fit), updating `len`. + let ok = unsafe { GetICMProfileW(dc, &mut len, name.as_mut_ptr()) }; + // SAFETY: `dc` came from `CreateDCW` and is deleted exactly once, after its last use. + unsafe { DeleteDC(dc) }; + let path = until_nul(&name); + (ok != 0 && !path.is_empty()).then(|| PathBuf::from(OsString::from_wide(path))) + } + + /// Whether Windows colour-manages the desktop on the display `device`; `None` when it can't be + /// told. + fn managed_by_windows(device: &[u16; 32]) -> Option { + let (mut paths, mut modes) = (0u32, 0u32); + // SAFETY: two counts to write; nothing else is passed. + if unsafe { GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut paths, &mut modes) } != ERROR_SUCCESS { + return None; + } + if paths == 0 || paths > MAX_PATHS || modes > 2 * MAX_PATHS { + return None; + } + let mut path = vec![DISPLAYCONFIG_PATH_INFO::default(); paths as usize]; + let mut mode = vec![DISPLAYCONFIG_MODE_INFO::default(); modes as usize]; + // SAFETY: the arrays hold `paths` and `modes` elements as the counts say; Windows writes at + // most that many and lowers the counts to what it wrote. The topology id must be null with + // `QDC_ONLY_ACTIVE_PATHS`. + let r = + unsafe { QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &mut paths, path.as_mut_ptr(), &mut modes, mode.as_mut_ptr(), std::ptr::null_mut()) }; + if r != ERROR_SUCCESS { + return None; + } + path.truncate(paths as usize); + let wanted = until_nul(device); + for p in &path { + let mut source = DISPLAYCONFIG_SOURCE_DEVICE_NAME { + header: DISPLAYCONFIG_DEVICE_INFO_HEADER { + r#type: DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, + size: size_of::() as u32, + adapterId: p.sourceInfo.adapterId, + id: p.sourceInfo.id, + }, + ..Default::default() + }; + // SAFETY: the header's type and size describe `source`, and the pointer is taken from the + // whole struct, which `DisplayConfigGetDeviceInfo` fills (at most `size` bytes). + if unsafe { DisplayConfigGetDeviceInfo((&raw mut source).cast::()) } != 0 { + continue; + } + if until_nul(&source.viewGdiDeviceName) != wanted { + continue; + } + let mut color = DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO { + header: DISPLAYCONFIG_DEVICE_INFO_HEADER { + r#type: DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO, + size: size_of::() as u32, + adapterId: p.targetInfo.adapterId, + id: p.targetInfo.id, + }, + ..Default::default() + }; + // SAFETY: as above, for `color`. + if unsafe { DisplayConfigGetDeviceInfo((&raw mut color).cast::()) } != 0 { + return None; + } + // SAFETY: the union's two views are a bit field and the same 32 bits as a `u32`; every + // bit pattern is a valid `u32`. + let flags = unsafe { color.Anonymous.value }; + return Some(managed(flags)); + } + None + } + + #[cfg(test)] + pub fn desktop_window() -> isize { + // SAFETY: `GetDesktopWindow` takes nothing and returns the desktop's handle. + unsafe { windows_sys::Win32::UI::WindowsAndMessaging::GetDesktopWindow() as isize } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn no_window_is_unknown() { + assert_eq!(monitor_color(0), MonitorColor::Unknown); + } + + #[test] + fn hostile_handles_never_crash() { + // not windows: unknown, or (Windows answers the nearest monitor) a profile or managed + for h in [1isize, -1, 0x7fff_ffff, isize::MIN, isize::MAX] { + let _ = monitor_color(h); + } + } + + #[test] + fn advanced_colour_flags_decide_who_manages_colour() { + // supported only (an SDR desktop on an HDR-capable monitor): the app converts + assert!(!managed(0b0001)); + assert!(!managed(0)); + // HDR on / Auto Color Management (advanced colour enabled), or wide colour enforced + assert!(managed(0b0011)); + assert!(managed(0b0101)); + // forced off (bit 3) alone + assert!(!managed(0b1000)); + } + + #[test] + fn utf16_text_stops_at_its_nul() { + assert_eq!(until_nul(&[65, 66, 0, 67]), &[65, 66]); + assert_eq!(until_nul(&[65, 66]), &[65, 66]); + assert_eq!(until_nul(&[0, 65]), &[] as &[u16]); + } + + /// The desktop's monitor has an answer, and a profile it names is a file that exists. + #[cfg(windows)] + #[test] + fn the_desktop_monitor_names_a_profile_that_exists_or_windows_manages_colour() { + let answer = monitor_color(win32::desktop_window()); + eprintln!("the desktop's monitor: {answer:?}"); + match answer { + MonitorColor::Profile(p) => assert!(p.is_file(), "{}", p.display()), + MonitorColor::ManagedByWindows | MonitorColor::NoProfile => {} + MonitorColor::Unknown => lightcraft_testkit::skip!(System, "no monitor answers for the desktop window (a session without a display)"), + } + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 7d1b7a3aeb..b20bb39349 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -13,7 +13,7 @@ L5 depends on egui, eframe, winit or rfd, and that each crate only uses lower la | Layer | Crates (lines) | Role | |---|---|---| -| L0 | `geom` (1.4k), `color` (0.9k), `raster` (0.8k), `tiff` (2.0k), `fetch` (1.4k), `sysmem` (0.1k) | Matrices and warps, colour spaces and transfer functions, float image buffers, TIFF/IFD read and write, pinned HTTPS model downloads, the one `unsafe` FFI call (`malloc_zone_pressure_relief`) | +| L0 | `geom` (1.4k), `color` (0.9k), `raster` (0.8k), `tiff` (2.0k), `fetch` (1.4k), `sysmem` (0.1k), `wincolor` (0.3k) | Matrices and warps, colour spaces and transfer functions, float image buffers, TIFF/IFD read and write, pinned HTTPS model downloads, and the two crates with `unsafe` FFI: `malloc_zone_pressure_relief` (macOS) and the Win32 calls that read the window's monitor profile (Windows) | | L1 | `raw` (22.3k), `codecs` (7.3k), `meta` (4.3k), `develop` (2.5k), `denoise-core` (2.2k), `denoise` (2.7k), `faces` (5.3k), `scenes` (1.0k), `heif` (2.1k, optional) | Raw decoders and demosaic, DNG colour model; standard codecs and encoders; EXIF/XMP/IPTC; the non-destructive edit model and control specs; AI denoise; face detection and recognition; procedural demo photos; HEIC | | L2 | `pipeline` (9.8k) | The develop pipeline: scene-referred float, resolution independent; the CPU reference (oracle) for everything else | | L3 | `catalog` (11.0k), `gpu` (5.1k), `preview` (1.3k), `merge` (3.8k), `segment` (2.3k) | Library model and persistence; wgpu compute twin of the pipeline; thumbnail/preview cache and job pool; HDR and panorama merge; SAM 3 segmentation | diff --git a/docs/display-profiles.md b/docs/display-profiles.md index 67892a3cbb..25735dee37 100644 --- a/docs/display-profiles.md +++ b/docs/display-profiles.md @@ -16,17 +16,30 @@ have one share it; otherwise, and without colord, previews stay sRGB (choose a p that colour-manages windows itself with the same profile (KWin with an ICC profile set in Display Configuration) would correct twice; KWin keeps that profile in its own settings, not colord, so this only happens when both are set. +**Windows uses the profile it assigns to the monitor showing the window** (Settings ▸ System ▸ Display ▸ Color +profile, Color Management, or a calibrator) while none is chosen. On an SDR desktop Windows passes what an app draws to +the monitor unchanged, so without it a wide-gamut monitor shows sRGB previews oversaturated and a calibration is +ignored. `crates/wincolor` finds the monitor the window is mostly on and asks Windows Color System for its default +profile, in the user's scope when they chose per-user profiles for that monitor, else the system's. It is asked about +once a second, so moving the window to another monitor and changing the profile in Windows are both followed without +a restart. (GDI's `GetICMProfileW` keeps answering the profile a process first saw, so it is only the fallback when the +monitor's device can't be found.) With no profile assigned, previews are sRGB. **While Windows colour-manages the +desktop itself** (HDR on, or Auto Color Management on Windows 11: its advanced-colour state, from +`DisplayConfigGetDeviceInfo`), it treats an ordinary app's output as sRGB and converts it for the monitor, so previews +stay sRGB rather than be converted twice. The log says which applies (`screen profile: …`) whenever it changes. + ## Using it Settings ▸ Display ▸ **Choose Profile…** picks an `.icc` / `.icm` file (the dialog opens where the system keeps -them: `~/.local/share/icc` on Linux, ColorSync's folders on macOS, `…\spool\drivers\color` on Windows). **Use sRGB** -(on macOS and Linux **Use Screen Profile**) goes back to no profile. The choice is an app setting (`ui.json`, `displayProfile`) +them: `~/.local/share/icc` on Linux, ColorSync's folders on macOS, `…\spool\drivers\color` on Windows). **Use Screen +Profile** (in hosts without one, **Use sRGB**) goes back to no profile. The choice is an app setting (`ui.json`, `displayProfile`) and applies at once; a file that can't be used is reported there and previews stay sRGB. Agents and scripts: `app.displayProfile {"path": "/path/to/monitor.icc"}` (`""` or `null`: none; no `path`: report only) returns `{path, description, kind: "matrix" | "lut", primaries: {red, green, blue: [x, y]}}`; the screen's -profile (macOS or Linux, none chosen) reports `path: null, screen: true`. Hosts supply it as `Services::screen_profile` -(`apps/lightcraft/src/screen_profile.rs`, `apps/lightcraft/src/colord.rs`); headless sessions have none and stay sRGB. +profile (none chosen) reports `path: null, screen: true`. Hosts supply it as `Services::screen_profile` +(`apps/lightcraft/src/screen_profile.rs`, `apps/lightcraft/src/colord.rs`, `apps/lightcraft/src/win_screen_profile.rs`); +headless sessions have none and stay sRGB. ## How it works @@ -55,5 +68,6 @@ LUT-based profile's correction about 65 ms. Drafts during slider drags skip the ## Not yet -- Picking up the profile Windows assigns (WCS: needs FFI, so an isolated `unsafe` helper crate) and X11's - `_ICC_PROFILE`; following the window across monitors on Linux and Windows (macOS does both, above). +- X11's `_ICC_PROFILE`, and following the window across monitors on Linux (macOS and Windows do both, above). +- Windows' advanced-colour profiles (what a monitor uses while Auto Color Management is on): LightCraft leaves colour + to Windows then. diff --git a/docs/gaps.md b/docs/gaps.md index 1b4a385fac..126c981f10 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-15 · **Change:** minor (gap 15: Print Page Options — page numbers, page info, crop marks) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-20 · **Change:** minor (gap 22: Windows previews follow the monitor's profile) 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 @@ -37,7 +37,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 20 | **Long-tail raw formats**: compressed SRW, ARQ pixel shift, IIQ, Hasselblad compression, X3F, CRW, MRW, ERF, KDC, DCR, MEF, GPR, old FinePix | raw-parity.md | small user share each | 45–85 | [raw-parity](raw-parity.md) | | 21 | **Localization**: 9 of 15 shipped languages partial (de, es, fr, ja, uk now 97–99% of catalog messages, awaiting native review; pt-BR, ru, zh-hans, zh-hant 74–92%), lower-layer errors English; Hindi, Arabic, Indonesian, Korean, Vietnamese absent; no RTL or complex shaping | measured from catalogs | non-English users see mixed English | 40–70 (shipped to full); 145–255 (five new) | [localization-parity](localization-parity.md) | | 23 | **Accessibility**: AccessKit tree audited by a test; canvas handles, spots and mask pins by keyboard; left: brush and red-eye by keyboard, a session with a real screen reader | LR-BEHAV-ACCESS 🟡 | blind and low-vision users | 2–4 | [ui-parity](ui-parity.md) | -| 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) | +| 22 | **Pen pressure on macOS / Linux tablets** (brush size and flow follow pressure where winit reports a pen force), follow-window colour on Linux (Windows reads the monitor's profile from Windows Color System and follows the window, macOS the screen's, Linux colord's) | hardware-parity.md | brush users with tablets; multi-monitor setups | 9–18 | [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 | 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) | @@ -77,6 +77,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-10-20 | minor | Gap 22 shrinks (11–22 → 9–18 h): on Windows, previews follow the profile Windows Color System assigns to the window's monitor (sRGB while Windows colour-manages the desktop: HDR, Auto Color Management) | | 2026-10-18 | patch | Gap 1: six X-Trans CMOS 4 Fujifilm bodies (X-T30 …) take the X-T3's spectral matrices instead of the neutral matrix | | 2026-10-15 | minor | Gap 15 shrinks: the Page panel's Page Options (Page Numbers, Page Info, Crop Marks) print on Single Image and Contact Sheet pages; identity plate, watermark, photo info, Cut Guides, direct printing and JPEG output remain | | 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 | diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index a6c63b816a..ce52ce63ad 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (pen pressure for brush masks; monitor profile from colord on Linux); previously major (created from the code, gpu-pipeline.md and the parity checklist) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-20 · **Change:** minor (monitor profile from Windows Color System on Windows); previously major (created from the code, gpu-pipeline.md and the parity checklist) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 What Lightroom does with the machine's hardware, per platform, and what LightCraft does. Sources: [gpu-pipeline.md](gpu-pipeline.md), [display-profiles.md](display-profiles.md), [denoise.md](denoise.md), @@ -12,7 +12,7 @@ What Lightroom does with the machine's hardware, per platform, and what LightCra | GPU export | ✅ | ✅ (6000 × 4000 in ~0.3 s vs ~1.2 s CPU) | ✅ | ✅ | — | ✅ (black-export fix on an Intel iGPU, #78) | | AI on GPU / neural engine | Metal / DirectML / Core ML, model per feature | AI denoise on GPU or CPU (setting); SAM 3 on Metal via candle; faces on CPU | CPU / GPU denoise | CPU / GPU denoise | — | 🟡 no Core ML / Neural Engine / DirectML | | HDR (EDR) display | ✅ (macOS EDR, Windows HDR) | ⬜ | ⬜ | ⬜ | ⬜ | ⬜ (LR-VIEW-HDR-DISPLAY) | -| Monitor profile | automatic per display, follows the window | ✅ the screen's profile, followed across screens | 🟡 picked by hand (WCS needs FFI) | 🟡 colord's profile (one display, or all sharing one); no follow across monitors | — | 🟡 Windows OS profile not read; Linux per-monitor follow missing | +| Monitor profile | automatic per display, follows the window | ✅ the screen's profile, followed across screens | ✅ the profile Windows Color System assigns to the window's monitor, followed across monitors and profile changes; sRGB while Windows colour-manages the desktop (HDR, Auto Color Management) | 🟡 colord's profile (one display, or all sharing one); no follow across monitors | — | 🟡 Linux per-monitor follow missing | | Second window / second monitor | ✅ (Classic) | ✅ (⌘F11) | ✅ | ✅ | — | ✅ (Classic secondary-window keys missing) | | Pen pressure / tilt (brush masks) | ✅ pressure for size / flow | ⬜ winit reports no tablet pressure on macOS | 🟡 pen force from winit touch events (untested on a tablet) | ⬜ winit has no X11 / Wayland tablet input | 🟡 pointer-event force where winit passes it | 🟡 brush size and flow follow pen pressure wherever egui gets a touch force (Brush ▸ Pen Pressure); no tilt; macOS / Linux tablets wait on winit | | Trackpad gestures | pinch zoom, pan | ✅ pinch, two-finger pan | 🟡 (winit) | 🟡 | 🟡 | ✅ on macOS | @@ -27,7 +27,7 @@ What Lightroom does with the machine's hardware, per platform, and what LightCra **~40% ready** (estimated): the GPU editing path is real and fast (measured: 24 MP exposure drag 3.9 ms on GPU vs 22–42 ms CPU; NR drag 18 ms vs 301–471 ms), but HDR display, pen pressure, -tethering, printing, automatic monitor profiles and neural-engine inference are missing. GPU +tethering, printing, per-monitor profiles on Linux and neural-engine inference are missing. GPU correctness is proven on Apple GPUs and on one AMD GPU on Linux (Radeon 8060S, Vulkan / RADV: the equivalence suite passes with the same max 1–2 LSB as on Metal, [gpu-pipeline.md](gpu-pipeline.md#correctness-cpu-oracle-and-equivalence-tests)). NVIDIA, Intel and Windows DX12 still rely on user reports. @@ -37,18 +37,19 @@ NVIDIA, Intel and Windows DX12 still rely on user reports. | Work | Hours | Needs | |---|---:|---| | HDR display (EDR on macOS, Windows HDR, Linux where possible) | 10–20 | an HDR display to verify (human) | -| OS monitor profile: Windows WCS (an FFI helper crate, like `crates/sysmem`), follow the window across displays on Linux | 4–8 | multi-monitor setup | +| OS monitor profile: follow the window across displays on Linux | 2–4 | multi-monitor setup | | Pen pressure for brush masks: done where winit reports a touch force; macOS and Linux tablets need winit tablet events (or a pure-Rust tablet layer) | 3–8 | a tablet | | Remaining stages on GPU (defringe, spot removal, masks) | 10–20 | | | Tethered capture (PTP over USB in pure Rust, Canon / Nikon / Sony first) | 25–45 | cameras (human) | | Printing with colour management | 15–25 | printers (human) | | Neural-engine / DirectML inference for AI features | 10–20 | depends on the AI model decision | -| **Total** | **80–150 h** (the core set for beta, HDR display + monitor profile + pen pressure: 20–40 h) | | +| **Total** | **78–146 h** (the core set for beta, HDR display + monitor profile + pen pressure: 18–36 h) | | ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-10-20 | minor | Monitor profile: Windows reads the window's monitor profile from Windows Color System (`crates/wincolor`), sRGB while Windows colour-manages the desktop; verified on Windows 11 by setting and clearing a Display P3 profile while the app ran. Remaining monitor-profile work 4–8 h → 2–4 h | | 2026-10-12 | minor | Monitor profile: Linux reads the display profile from colord; macOS row reflects #787 | | 2026-10-12 | minor | CPU ↔ GPU equivalence suite run on an AMD Radeon 8060S (Vulkan, RADV, Linux): 16 tests / 135 cases pass, max 2 LSB, mean ≤ 0.0003; first GPU verified outside Apple | | 2026-10-12 | minor | Pen pressure: strokes record per-point pressure from egui touch force, scaling dab size and flow; per-platform status | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 4e05317933..cfd790ac96 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-10-15 · **Change:** minor (LRC-PRINT-PAGE: Print Page Options) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-20 · **Change:** minor (LR-PREF-DISPLAY: Windows previews follow the monitor's profile) · **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 @@ -433,7 +433,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-PREF-LOCALSTORAGE | Storage & cache | P1 | ✅ | `cmd:library.preferences`, `cmd:library.clearPreviews`, `cmd:library.compact` | thumbnail cache size + clear in Settings → Performance; library location + Open Library… in General | | LR-PREF-ACCOUNT | Account | OOS | 🚫 | | | | LR-PREF-INTERFACE | Interface options | P1 | ✅ | `cmd:app.settings`, `cmd:view.appearance`, `cmd:view.theme` | Appearance Mode (Sync with System / Dark / Light; the top bar button cycles Auto, Light, Dark) with separate dark (Charcoal, Midnight) and light (Silver, Paper) themes previewed in cards; hover stars persist favorite themes, the appearance button context menu opens Interface settings and lists light favorites before dark favorites; filmstrip names/badges, grid badges (auto/always/never), square-grid names, navigator, info overlay | -| LR-PREF-DISPLAY | Monitor (display) colour management | P1 | 🟡 | `cmd:app.displayProfile`, `crates/codecs/src/display.rs`, `crates/engine/src/display.rs`, `crates/ui-egui/src/panels/settings.rs`, `apps/lightcraft/src/screen_profile.rs`, `apps/lightcraft/src/colord.rs`, `docs/display-profiles.md` | Settings ▸ Display: a monitor ICC profile (matrix/TRC exactly, LUT-based through the CMS) chosen by hand, or on macOS the profile of the screen showing the window (followed across screens, #787), on Linux the profile the desktop assigns in colord (read off the UI thread every 3 s; used with one display, or several sharing one profile); the loupe, Before, Compare, hover previews and the second window render into the display's primaries (its full gamut, CPU and GPU), thumbnails and stand-ins are converted from sRGB; histogram, preview caches and exports stay sRGB; soft proofing's display gamut warning uses the display's gamut. Missing: Windows' WCS profile (needs FFI, so `unsafe`), X11 `_ICC_PROFILE`, per-monitor profiles on Linux (eframe doesn't say which monitor the window is on) | +| LR-PREF-DISPLAY | Monitor (display) colour management | P1 | 🟡 | `cmd:app.displayProfile`, `crates/codecs/src/display.rs`, `crates/engine/src/display.rs`, `crates/ui-egui/src/panels/settings.rs`, `apps/lightcraft/src/screen_profile.rs`, `apps/lightcraft/src/colord.rs`, `apps/lightcraft/src/win_screen_profile.rs`, `crates/wincolor/src/lib.rs`, `docs/display-profiles.md` | Settings ▸ Display: a monitor ICC profile (matrix/TRC exactly, LUT-based through the CMS) chosen by hand, or on macOS the profile of the screen showing the window (followed across screens, #787), on Linux the profile the desktop assigns in colord (read off the UI thread every 3 s; used with one display, or several sharing one profile), on Windows the profile Windows Color System assigns to the monitor showing the window (per-user or system, followed across monitors and profile changes; sRGB while Windows colour-manages the desktop itself: HDR or Auto Color Management; verified on Windows 11 with a Display P3 profile set and unset while the app ran); the loupe, Before, Compare, hover previews and the second window render into the display's primaries (its full gamut, CPU and GPU), thumbnails and stand-ins are converted from sRGB; histogram, preview caches and exports stay sRGB; soft proofing's display gamut warning uses the display's gamut. Missing: X11 `_ICC_PROFILE`, per-monitor profiles on Linux (eframe doesn't say which monitor the window is on) | | LR-PREF-PERFORMANCE | GPU / performance | P1 | ✅ | `cmd:app.gpu`, `cmd:app.memoryBudget`, `cmd:app.settings` | GPU on/off (a crash while the GPU device or its kernels are built, issue #250, turns it off for the next launch), preview size (Automatic = the whole-frame loupe render at canvas size, up to 2560 px; or a 1600–5120 px size for it; zoomed views add a window at up to 100 %, issue #323), memory budget (a quarter of it is the idle per-view stage caches' share; the open photo's views are counted and reported, and cut only past four times that, the before side's and the zoom window's first — a Before/After at 1:1 on a 2800 px canvas holds about 1 GB of GPU stages, plus the one 288 MB copy of the original, which `ui.inspect` reports as `sharedSourceBytes`), thumbnail cache size in Settings | | LR-PREF-PEOPLE | Face recognition | P2 | 🟡 | `cmd:faces.enable`, `cmd:faces.models.list`, `cmd:faces.models.inspect`, `cmd:faces.models.install`, `cmd:faces.models.download`, `cmd:faces.models.downloads`, `cmd:faces.models.downloadCancel`, `cmd:faces.models.remove`, `cmd:faces.models.select`, `cmd:dialog.faceModel`, `crates/faces/src/lib.rs`, `crates/ui-egui/src/panels/faces.rs` | Settings ▸ Faces: an off-by-default toggle and the face model list. Models are opt-in and never bundled, the 232 KB YuNet detector included. Press Download (terms first; then a pinned address, size and SHA-256 checked, fetched over pure-Rust https with `lightcraft-fetch`), or add any `.onnx` by picking or dropping it: it is recognised by hash or described from its shape, shows its licence terms and training-data note, runs a self-test, and installs only after an "I accept" box; an installed model is chosen and recognition switched on at once (the newest wins, each model keeps its own embedding cache). Non-commercial models are add-by-file only, never offered for download. Suggestions of names run on the shared pure-Rust CPU interpreter (`crates/faces/src/net.rs`, `crates/faces/src/runtime.rs`; bounded im2col/GEMM, checked ONNX shapes/operators; no external inference runtime; 40 public crops agree within 2.1e-6, one-thread SFace 34–36 ms / AuraFace 233–252 ms, see docs/faces.md) in a background worker and are never applied automatically. Thresholds are starting points calibrated on busts, not yet on live faces; the Recognise faces switch is off until a recognition model is chosen and installed (`faces.enable {enabled: true}` refuses otherwise; removing the last recogniser switches it off), issue #678 | | LR-PREF-WATERMARK | Watermark settings | P1 | ✅ | `cmd:export.savePreset`, `crates/ui-egui/src/panels/dialogs.rs` | set in the Export dialog; kept with Export with Previous and in saved export presets | @@ -797,6 +797,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-20 | minor | LR-PREF-DISPLAY: on Windows, previews follow the profile Windows Color System assigns to the window's monitor (sRGB while Windows colour-manages the desktop: HDR, Auto Color Management); still 🟡 (X11 `_ICC_PROFILE`, Linux per-monitor) | | 2026-10-14 | patch | LR-EXP-TYPE: opaque 8-bit PNG/TIFF/WebP use RGB; transparent exports retain alpha (#1670). Statuses and feature counts unchanged. | | 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 (🟡) | diff --git a/docs/whats-new.md b/docs/whats-new.md index 2f02ffb91b..1c8073793c 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,17 @@ # What's new in LightCraft +## 2026-10-20 + +### Windows: photos follow the monitor's colour profile +- On Windows, photos are now shown through the colour profile Windows assigns to the monitor the window is on + (Settings ▸ System ▸ Display ▸ Color profile, Color Management, or a calibrator's profile), while no monitor profile + is chosen in Settings ▸ Display. Before, they were shown as sRGB, so a wide-gamut monitor showed them oversaturated + and a calibration was ignored unless you picked the profile by hand. Moving the window to another monitor, or + changing the profile in Windows, is followed within about a second. +- While Windows manages colour itself (HDR on, or Auto Color Management on Windows 11), photos stay sRGB: Windows + converts them for the monitor then. Settings ▸ Display ▸ **Use Screen Profile** goes back to this after choosing a + profile by hand. See [display profiles](display-profiles.md). + ## 2026-10-14 ### Model downloads time out on a name that doesn't resolve diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index d5be5523f3..dcefa6629c 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -38,6 +38,7 @@ pub const TABLE: &[(&str, Class)] = &[ ("raster", Class::Layer(0)), ("tiff", Class::Layer(0)), ("sysmem", Class::Layer(0)), + ("wincolor", Class::Layer(0)), ("fetch", Class::Layer(0)), ("denoise-core", Class::Layer(1)), ("denoise", Class::Layer(1)), From 71ae9fe975365d8b65f7d0a00a8c7276d8c50665 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 22:43:32 -0700 Subject: [PATCH 02/39] LR-PREF-DISPLAY: hardware-parity totals are the sums of their rows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The overall total and the beta core set were the old rounded figures minus the monitor-profile reduction; they are now the exact sums of the rows: 75–142 h, and 15–32 h for HDR display + monitor profile + pen pressure (CodeRabbit review). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K93HTyCiwYvbRGaAkjPvXn --- docs/hardware-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index ce52ce63ad..ed4ead9329 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -43,7 +43,7 @@ NVIDIA, Intel and Windows DX12 still rely on user reports. | Tethered capture (PTP over USB in pure Rust, Canon / Nikon / Sony first) | 25–45 | cameras (human) | | Printing with colour management | 15–25 | printers (human) | | Neural-engine / DirectML inference for AI features | 10–20 | depends on the AI model decision | -| **Total** | **78–146 h** (the core set for beta, HDR display + monitor profile + pen pressure: 18–36 h) | | +| **Total** | **75–142 h** (the core set for beta, HDR display + monitor profile + pen pressure: 15–32 h) | | ## Revision history From 2136819e7bdaa3823708441747fed7de35743664 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 21 Oct 2026 22:16:38 -0700 Subject: [PATCH 03/39] Cargo.lock: lightcraft-wincolor at the workspace version 0.11.0 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K93HTyCiwYvbRGaAkjPvXn --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 2185acba84..ef394f65de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3570,7 +3570,7 @@ dependencies = [ [[package]] name = "lightcraft-wincolor" -version = "0.10.0" +version = "0.11.0" dependencies = [ "lightcraft-testkit", "windows-sys 0.61.2", From 8066a98d48fde46912ec21d59a0f248ebfc56314 Mon Sep 17 00:00:00 2001 From: insideTheFlux Date: Thu, 22 Oct 2026 20:03:28 -0700 Subject: [PATCH 04/39] LR-META-LOCATION: place names always download into the settings folder (#2575) metadata.downloadPlaceNames took `dataset` (any folder) and `base` (any https server) from its params, so a control or MCP client could have a server's bytes written as cities15000.txt, admin1CodesASCII.txt and countryInfo.txt into any folder, through std::fs::write, which follows a link in their place. - Both params are refused; the files always go to /geonames, from GeoNames. Tests point the download at their local server through a session field no command can set. - Each file is written to a temp file and renamed over the old one (safe_file::write_atomic_nosync): never half-written, and a planted link is replaced, not written through. The issue's other two parts (SAM 3 tokenizer hashes, TLS close_notify in lightcraft-fetch) are left for their own changes, as the ticket bot asked. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PtjHGt5gnCHXgLt4NbGorf --- crates/engine/src/cmd/geocode.rs | 80 +++++++++++++++++++++++++++++--- docs/whats-new.md | 8 ++++ 2 files changed, 82 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/geocode.rs b/crates/engine/src/cmd/geocode.rs index c9ffb6b7e7..c031eb7d33 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 { @@ -208,7 +212,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())) { @@ -231,10 +239,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")); } @@ -299,7 +318,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 )); @@ -458,7 +477,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 { @@ -483,7 +503,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); @@ -506,6 +527,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/docs/whats-new.md b/docs/whats-new.md index cffff83e2b..b7c47dbb17 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,13 @@ # What's new in LightCraft +## 2026-10-22 + +### 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. + ## 2026-10-21 ### Sharper resampling in HDR and panorama merges From 8d34a14166b707f0781b3e9e55d9a6feae57b56a Mon Sep 17 00:00:00 2001 From: insideTheFlux Date: Fri, 23 Oct 2026 16:50:03 -0700 Subject: [PATCH 05/39] Cargo.lock: lightcraft-wincolor at the workspace version 0.13.0 The merge of main kept this PR's lock entry for the new crate at 0.11.0 while main moved the workspace to 0.13.0, so the gate's Cargo.lock check and the --locked git-dependency check failed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PtjHGt5gnCHXgLt4NbGorf --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 4d41a0e63e..7d24a49e49 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3570,7 +3570,7 @@ dependencies = [ [[package]] name = "lightcraft-wincolor" -version = "0.11.0" +version = "0.13.0" dependencies = [ "lightcraft-testkit", "windows-sys 0.61.2", From 30780eb9a89b2e3aafec4de59803b5157f40201d Mon Sep 17 00:00:00 2001 From: insideTheFlux Date: Sat, 24 Oct 2026 15:33:53 -0700 Subject: [PATCH 06/39] LR-LIB-PEOPLE: face boxes drawn on a photo as stored land on the upright photo (#2674) Some applications give a rotated photo's MWG regions on its stored pixels and say so only through mwg-rs:AppliedToDimensions (the stored, sideways size), without Lightroom's mwg-rs:Rotation. Those boxes were taken as upright, so on a portrait photo they sat where the landscape photo had the faces. When AppliedToDimensions has the shape of the photo as stored rather than upright, the boxes are now turned with the file's own Exif orientation (mirror included): for embedded XMP at import (with the header's size when the metadata states none), and for sidecars and a raw's embedded XMP at import, on Read Metadata from File and in Synchronize Folder. Boxes drawn on the upright size, square photos and Lightroom's turned boxes are taken as written. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016TuX1qw9ieyuJ1ZFrrUxzc --- crates/engine/src/files.rs | 14 ++++ crates/engine/src/import.rs | 2 + crates/engine/src/media.rs | 3 + crates/engine/src/sidecar.rs | 32 ++++++++ crates/engine/src/sync.rs | 4 +- crates/engine/src/tests_xmp.rs | 69 +++++++++++++++++ crates/meta/src/lib.rs | 135 +++++++++++++++++++++++++++++++-- crates/meta/src/xmp.rs | 56 ++++++++++++-- docs/parity-checklist.md | 5 +- docs/xmp-interop.md | 8 +- 10 files changed, 311 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 82d4c57d60..0aac050bf3 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -154,6 +154,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { as_shot_wb: None, content_hash, xmp: lightcraft_meta::embedded(bytes).xmp, + orientation: m.orientation, preview_only: Some(why), ..Default::default() }); @@ -181,6 +182,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { as_shot_wb, content_hash, xmp: lightcraft_meta::embedded(bytes).xmp, + orientation: Some(raw.orientation), preview_only: None, }); } @@ -196,6 +198,17 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { if o.swaps_axes() { std::mem::swap(&mut w, &mut h); } + // regions another app drew on the photo as stored: `extract` turned them upright where the metadata says how + // big the photo is; otherwise the header does (#2674) + let mut meta = meta; + if (m.width.is_none() || m.height.is_none()) + && o.swaps_axes() + && !meta.regions.is_empty() + && let Some(drawn_on) = + lightcraft_meta::embedded(bytes).xmp.and_then(|x| lightcraft_meta::parse_xmp(&x).ok()).and_then(|x| x.regions_drawn_on()) + { + lightcraft_meta::upright_regions(&mut meta.regions, drawn_on, o, (header.width, header.height)); + } let format = match ext_upper(name).as_str() { "JPG" | "JPEG" => "JPEG".to_string(), "" => format!("{fmt:?}").to_uppercase(), @@ -214,6 +227,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { content_hash, embedded_lens: None, xmp: None, + orientation: m.orientation, preview_only: None, }) } diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index bb81bd2407..4e68b53347 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -1461,6 +1461,8 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare } } let sidecar = sidecar.map(|sc| sc.resolve_label(&s.catalog)).filter(|sc| *sc != crate::sidecar::SidecarData::default()); + // the photo is upright as the file's own orientation turns it, when the file states one + let sidecar = sidecar.map(|sc| crate::sidecar::SidecarData { orientation: info.orientation.or(sc.orientation), ..sc }); // a copy is catalogued under its new name let name = Path::new(&stored).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.clone()); let mut p = Photo::new(id, Source::File { path: stored }, &name, &info.format, info.width, info.height, &now); diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index e76ef81691..e9f1d30c93 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -1744,6 +1744,9 @@ pub struct ProbeInfo { pub embedded_lens: Option, /// The file's embedded XMP packet (raw/DNG files), for develop settings stored inside the file. pub xmp: Option, + /// The file's Exif orientation, when it states one: how its stored pixels turn upright (`width` and `height` are + /// the upright size). + pub orientation: Option, /// A raw variant that can't be decoded yet: why. The file is described (and will be shown and /// edited) from its embedded preview; see [`lightcraft_catalog::Photo::preview_only`]. pub preview_only: Option, diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index d13b951257..db655ada2c 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -138,6 +138,12 @@ pub struct SidecarData { pub extended_description: Option, pub keywords: Option>, pub regions: Option>, + /// The size the regions were drawn on, when they don't say how the photo was turned + /// ([`lightcraft_meta::XmpData::regions_drawn_on`]), and how the photo's stored pixels turn upright: the + /// sidecar's `tiff:Orientation`, or the file's own Exif orientation where the caller knows it. With both, + /// [`merge_into`] puts boxes drawn on the photo as stored where the upright photo has them (#2674). + pub regions_drawn_on: Option<(f64, f64)>, + pub orientation: Option, /// Capture time (ISO 8601) from `exif:DateTimeOriginal`, `photoshop:DateCreated` or /// `xmp:CreateDate` (first found). Used only when the file itself has no capture time. pub captured: Option, @@ -184,6 +190,9 @@ pub fn parse_sidecar(xmp: &str, target: crate::crs::Target) -> std::result::Resu // `mwg-rs:Regions` byte for byte but never writes one) says nothing about regions, and the // photo's are kept. regions: d.values.contains_key("mwg-rs:Regions").then(|| m.regions.clone()), + regions_drawn_on: d.regions_drawn_on(), + // (only what the regions need: a packet that says nothing else still says nothing) + orientation: d.regions_drawn_on().and(m.orientation), captured: m.capture_time.map(|d| d.to_iso()), ..Default::default() }; @@ -313,6 +322,11 @@ pub fn merge_into(p: &mut Photo, sc: &SidecarData, now: &str) -> bool { } if let Some(r) = &sc.regions { m.regions = r.clone(); + // (the photo's size is the upright one) + if let (Some(drawn_on), Some(o)) = (sc.regions_drawn_on, sc.orientation) { + let stored = if o.swaps_axes() { (p.height, p.width) } else { (p.width, p.height) }; + lightcraft_meta::upright_regions(&mut m.regions, drawn_on, o, stored); + } } let develop = match &sc.develop { Some(DevelopPatch::Full(s)) => (**s).clone(), @@ -342,8 +356,25 @@ impl SidecarData { } self } + + /// Take the orientation of the photo file at `original` (LightCraft shows the photo turned by it, and the packet + /// may not repeat it) when the regions need it: they were drawn on a stated size ([`SidecarData::regions_drawn_on`]). + /// Only then is the start of the file read. + pub fn with_file_orientation(self, original: &str) -> Self { + if self.regions_drawn_on.is_none() { + return self; + } + let mut head = Vec::new(); + let read = std::fs::File::open(original).and_then(|f| f.take(ORIENTATION_SPAN).read_to_end(&mut head)); + let orientation = read.ok().and_then(|_| lightcraft_meta::extract(&head).orientation); + SidecarData { orientation: orientation.or(self.orientation), ..self } + } } +/// How much of a photo file [`SidecarData::with_file_orientation`] reads: Exif sits at the start of every format +/// LightCraft reads. +const ORIENTATION_SPAN: u64 = 1 << 20; + /// The sidecar packet for a photo; the colour label is written by its name in `cat` (custom /// label names included, as other editors do). pub fn sidecar_packet(p: &Photo, cat: &lightcraft_catalog::Catalog) -> String { @@ -832,6 +863,7 @@ impl Session { let Some(orig) = file_path(p) else { return Ok(None) }; let Some((packet, from)) = read_packet(orig, p.kind, self.sidecar_naming(id)) else { return Ok(None) }; let sc = parse_sidecar(&packet, crate::crs::Target::for_photo(p)).map_err(|e| EngineError::Other(format!("{}: {e}", from.display())))?; + let sc = sc.with_file_orientation(orig); let mut warnings = sc.warnings.clone(); for warning in &mut warnings { warning.path = orig.to_string(); diff --git a/crates/engine/src/sync.rs b/crates/engine/src/sync.rs index f20ad9c95e..d56a7513c3 100644 --- a/crates/engine/src/sync.rs +++ b/crates/engine/src/sync.rs @@ -618,7 +618,7 @@ fn sidecar_has_news(labels: &Catalog, p: &Photo, naming: SidecarNaming, listing: } let Ok(text) = std::fs::read_to_string(&file) else { return false }; let Ok(sc) = crate::sidecar::parse_sidecar(&text, crate::crs::Target::for_photo(p)) else { return false }; - let sc = sc.resolve_label(labels); + let sc = sc.with_file_orientation(path).resolve_label(labels); let mut q = p.clone(); crate::sidecar::merge_into(&mut q, &sc, ""); (q.rating, q.flag, q.label, &q.meta, &q.captured, &q.develop) != (p.rating, p.flag, p.label, &p.meta, &p.captured, &p.develop) @@ -801,7 +801,7 @@ fn read_sidecar(path: &str, naming: SidecarNaming, target: crate::crs::Target) - return Err(format!("{}: too large for an XMP sidecar", file.display())); } let text = std::fs::read_to_string(&file).map_err(|e| format!("{}: {e}", file.display()))?; - crate::sidecar::parse_sidecar(&text, target).map_err(|e| format!("{}: {e}", file.display())) + crate::sidecar::parse_sidecar(&text, target).map(|sc| sc.with_file_orientation(path)).map_err(|e| format!("{}: {e}", file.display())) } impl SyncCommit { diff --git a/crates/engine/src/tests_xmp.rs b/crates/engine/src/tests_xmp.rs index 129662e4dc..52ddfa0f1b 100644 --- a/crates/engine/src/tests_xmp.rs +++ b/crates/engine/src/tests_xmp.rs @@ -462,6 +462,75 @@ fn regions_from_sidecar_are_read_on_import() { let _ = std::fs::remove_dir_all(&src); } +/// MWG regions as an app that draws on the photo as stored writes them for [`write_turned_jpeg`]'s photo: its stored +/// 32 × 24 as `AppliedToDimensions` and no box saying how the photo was turned (no `mwg-rs:Rotation`). One face, its +/// box centred at (0.25, 0.4), 0.1 × 0.15 of that size. +const STORED_FRAME_REGIONS: &str = r#" + + + + + + + + + + + + + + +"#; + +/// A JPEG of 32 × 24 pixels stored sideways (Exif orientation 6, shown 24 × 32), with `packet` embedded when given. +fn write_turned_jpeg(path: &Path, packet: Option<&str>) { + let img = lightcraft_raster::Rgba8::from_fn(32, 24, |x, y| [(x * 7) as u8, (y * 9) as u8, 90, 255]); + let exif = + lightcraft_meta::write_exif(&lightcraft_meta::Metadata { orientation: Some(lightcraft_meta::Orientation::Rotate90), ..Default::default() }); + let meta = lightcraft_codecs::EncodeMeta { exif: Some(&exif), xmp: packet, ..Default::default() }; + let bytes = lightcraft_codecs::encode_jpeg(&lightcraft_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &meta).unwrap(); + std::fs::write(path, bytes).unwrap(); +} + +/// The face's box from [`STORED_FRAME_REGIONS`] on the upright photo: turned a quarter turn clockwise with it. +fn assert_on_the_upright_face(s: &Session, id: PhotoId, when: &str) { + let p = s.catalog.photo(id).unwrap(); + assert_eq!((p.width, p.height), (24, 32), "the photo is upright"); + let r = p.meta.regions.first().map(|r| r.rect).unwrap_or_default(); + let want = [0.525, 0.2, 0.675, 0.3]; + let got = [r.x0, r.y0, r.x1, r.y1]; + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-9), "{when}: the box is where the photo as stored had the face: {got:?}"); + assert_eq!(p.meta.regions.len(), 1, "{when}"); +} + +/// Issue #2674: face boxes an app drew on a photo as stored (its sideways size as `AppliedToDimensions`, no +/// `mwg-rs:Rotation`) land on the faces of the photo as LightCraft shows it, upright: when imported, and when the +/// file's metadata is read again (the packet itself doesn't say how the photo turns; the file's Exif does). +#[test] +fn regions_drawn_on_the_photo_as_stored_land_on_the_upright_photo() { + let src = temp_dir("regions-stored-frame"); + let embedded = src.join("embedded.jpg"); + write_turned_jpeg(&embedded, Some(STORED_FRAME_REGIONS)); + let beside = src.join("sidecar.jpg"); + write_turned_jpeg(&beside, None); + std::fs::write(src.join("sidecar.xmp"), STORED_FRAME_REGIONS).unwrap(); + for (file, what) in [(&embedded, "embedded XMP"), (&beside, "sidecar")] { + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(1), "{r}"); + let id = only(&s); + assert_on_the_upright_face(&s, id, &format!("{what}, imported")); + let read = s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(read["failed"], json!([]), "{read}"); + assert_eq!(read["read"].as_array().map(Vec::len), Some(1), "{what}: {read}"); + assert_on_the_upright_face(&s, id, &format!("{what}, read again")); + } + let _ = std::fs::remove_dir_all(&src); +} + /// Removing a face box is a catalog-only, undoable edit: it never rewrites the sidecar (Lightroom's /// regions and everything else in it stay byte for byte), even with auto-write on. #[test] diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index baebbfe0f3..8f0fb432df 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -284,7 +284,7 @@ impl Metadata { pub fn extract(bytes: &[u8]) -> Metadata { let e = embedded(bytes); let exif = e.exif.as_deref().map(read_exif).unwrap_or_default(); - let xmp = e.xmp.as_deref().and_then(|xmp| parse_xmp(xmp).ok()).map(|xmp| xmp.metadata); + let xmp = e.xmp.as_deref().and_then(|xmp| parse_xmp(xmp).ok()); extract_embedded(e, exif, xmp) } @@ -299,24 +299,46 @@ pub fn try_extract(bytes: &[u8]) -> Result { None => Metadata::default(), }; let xmp = match e.xmp.as_deref() { - Some(xmp) if is_psd => Some(parse_xmp(xmp).map_err(|_| ExtractError::MalformedPsd)?.metadata), - Some(xmp) => parse_xmp(xmp).ok().map(|xmp| xmp.metadata), + Some(xmp) if is_psd => Some(parse_xmp(xmp).map_err(|_| ExtractError::MalformedPsd)?), + Some(xmp) => parse_xmp(xmp).ok(), None => None, }; Ok(extract_embedded(e, exif, xmp)) } -fn extract_embedded(e: Embedded, mut m: Metadata, xmp: Option) -> Metadata { +fn extract_embedded(e: Embedded, mut m: Metadata, xmp: Option) -> Metadata { if let Some(i) = e.iptc.as_deref() { m.fill_missing(&parse_iptc(i)); } if let Some(xmp) = xmp { - m.overlay_user_fields(&xmp); - m.fill_missing(&xmp); + m.overlay_user_fields(&xmp.metadata); + m.fill_missing(&xmp.metadata); + // boxes another app drew on the photo as stored go where the upright photo has them (#2674) + if let (Some(drawn_on), Some(orientation), Some(w), Some(h)) = (xmp.regions_drawn_on(), m.orientation, m.width, m.height) { + upright_regions(&mut m.regions, drawn_on, orientation, (w, h)); + } } m } +/// Turn regions drawn on a photo as it is stored onto the upright photo. MWG gives each box as a fraction of +/// `AppliedToDimensions` (`drawn_on`); for a photo whose Exif `orientation` turns it a quarter turn, some apps give the +/// stored, sideways size there and boxes on the stored pixels to match (Lightroom says so per box with +/// `mwg-rs:Rotation` instead, which [`parse_xmp`] reads). When `drawn_on` has the shape of the photo as stored +/// (`stored`, before `orientation`) rather than the upright one, every box is turned with `orientation`. Returns +/// whether they were. A square photo or `drawn_on` looks the same both ways, and a half turn or a mirror doesn't +/// change the shape: their boxes are left as they are. +pub fn upright_regions(regions: &mut [Region], drawn_on: (f64, f64), orientation: Orientation, stored: (u32, u32)) -> bool { + let ((dw, dh), (sw, sh)) = (drawn_on, stored); + if regions.is_empty() || !orientation.swaps_axes() || sw == sh || dw == dh || (dw > dh) != (sw > sh) { + return false; + } + for r in regions.iter_mut() { + r.rect = orientation.map_norm_rect(r.rect); + } + true +} + /// A container-level error reported by [`try_extract`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ExtractError { @@ -423,4 +445,105 @@ mod tests { assert_eq!(m.metering_name(), Some("Pattern")); assert_eq!(m.exposure_program_name(), Some("Aperture-priority AE")); } + + /// An MWG regions packet with one face, its box centred at (0.25, 0.4) and 0.1 × 0.15 of `AppliedToDimensions` + /// `w` × `h`; `extra` goes on the region (e.g. Lightroom's `mwg-rs:Rotation`). + fn regions_packet(w: u32, h: u32, extra: &str) -> String { + format!( + r#" + + + + + + + + + + "# + ) + } + + fn near(r: Rect, b: [f64; 4]) -> bool { + [r.x0 - b[0], r.y0 - b[1], r.x1 - b[2], r.y1 - b[3]].iter().all(|d| d.abs() < 1e-9) + } + + /// The face's box as drawn: on the photo as stored, or on the upright one by apps that draw there. + const DRAWN: [f64; 4] = [0.2, 0.325, 0.3, 0.475]; + /// The same box on the photo turned upright by Exif orientation 6 (a quarter turn clockwise). + const TURNED_6: [f64; 4] = [0.525, 0.2, 0.675, 0.3]; + + #[test] + fn boxes_drawn_on_the_stored_photo_turn_with_its_orientation() { + let region = || Region { + rect: Rect { x0: DRAWN[0], y0: DRAWN[1], x1: DRAWN[2], y1: DRAWN[3] }, + kind: RegionKind::Face, + name: None, + description: None, + }; + let turned = |o: Orientation, drawn_on: (f64, f64), stored: (u32, u32)| { + let mut regions = [region()]; + let did = upright_regions(&mut regions, drawn_on, o, stored); + (did, regions[0].rect) + }; + // drawn on the 6000 × 4000 photo as stored: every quarter turn and its mirror image land elsewhere + for (o, want) in [ + (Orientation::Rotate90, TURNED_6), + (Orientation::Rotate270, [0.325, 0.7, 0.475, 0.8]), + (Orientation::Transpose, [0.325, 0.2, 0.475, 0.3]), + (Orientation::Transverse, [0.525, 0.7, 0.675, 0.8]), + ] { + let (did, r) = turned(o, (6000.0, 4000.0), (6000, 4000)); + assert!(did && near(r, want), "{o:?}: {r:?}"); + // a smaller copy of the photo as stored is the same frame + assert!(near(turned(o, (1500.0, 1000.0), (6000, 4000)).1, want), "{o:?} on a smaller size"); + } + // drawn on the upright photo (MWG's own frame), or where the shape can't tell the two apart: as they are + for (o, drawn_on, stored) in [ + (Orientation::Rotate90, (4000.0, 6000.0), (6000, 4000)), + (Orientation::Rotate90, (4000.0, 4000.0), (6000, 4000)), + (Orientation::Rotate90, (4000.0, 4000.0), (4000, 4000)), + (Orientation::Rotate180, (6000.0, 4000.0), (6000, 4000)), + (Orientation::FlipH, (6000.0, 4000.0), (6000, 4000)), + (Orientation::Normal, (6000.0, 4000.0), (6000, 4000)), + ] { + let (did, r) = turned(o, drawn_on, stored); + assert!(!did && near(r, DRAWN), "{o:?} drawn on {drawn_on:?} of {stored:?}: {r:?}"); + } + } + + /// Issue #2674: an app that doesn't say how the photo was turned (no `mwg-rs:Rotation`) drew the faces of a photo + /// with Exif orientation 6 on its stored pixels, with the stored 6000 × 4000 as `AppliedToDimensions`. The boxes + /// land on the faces of the upright photo, not where the stored photo had them. + #[test] + fn regions_drawn_on_the_stored_photo_are_read_onto_the_upright_one() { + let jpeg = |packet: &str| { + let mut j = vec![0xff, 0xd8]; + let mut seg = |payload: Vec| { + j.extend([0xff, 0xe1]); + j.extend(u16::try_from(payload.len() + 2).unwrap().to_be_bytes()); + j.extend(payload); + }; + // orientation 6, 6000 × 4000 as stored + seg([b"Exif\0\0".as_slice(), &crate::exif::tests::sample_exif(lightcraft_tiff::ByteOrder::Little)].concat()); + seg([b"http://ns.adobe.com/xap/1.0/\0".as_slice(), packet.as_bytes()].concat()); + j.extend([0xff, 0xd9]); + j + }; + let read = |packet: &str| { + let m = extract(&jpeg(packet)); + assert_eq!((m.orientation, m.width, m.height), (Some(Orientation::Rotate90), Some(6000), Some(4000))); + assert_eq!(try_extract(&jpeg(packet)).unwrap().regions, m.regions); + assert_eq!(m.regions.len(), 1); + m.regions[0].rect + }; + let stored = read(®ions_packet(6000, 4000, "")); + assert!(near(stored, TURNED_6), "drawn on the photo as stored: {stored:?}"); + let upright = read(®ions_packet(4000, 6000, "")); + assert!(near(upright, DRAWN), "drawn on the upright photo, MWG's way: {upright:?}"); + // Lightroom's boxes say how the photo was turned: turned once, by that + let lightroom = read(®ions_packet(6000, 4000, r#" mwg-rs:Rotation="-1.57080""#)); + assert!(near(lightroom, TURNED_6), "Lightroom's −π/2: {lightroom:?}"); + } } diff --git a/crates/meta/src/xmp.rs b/crates/meta/src/xmp.rs index 2dbf59482e..8c54c5f196 100644 --- a/crates/meta/src/xmp.rs +++ b/crates/meta/src/xmp.rs @@ -77,6 +77,17 @@ pub struct XmpData { pub values: BTreeMap, } +impl XmpData { + /// The pixel size the packet's regions were drawn on (`mwg-rs:AppliedToDimensions`), unless one of them says how + /// the photo was turned (`mwg-rs:Rotation`: Lightroom's boxes, which the reader already turns upright). It tells + /// boxes drawn on the photo as stored from boxes drawn on it upright: see [`crate::upright_regions`]. + pub fn regions_drawn_on(&self) -> Option<(f64, f64)> { + let regions = self.values.get("mwg-rs:Regions")?; + let turned = regions.field("mwg-rs:RegionList").is_some_and(|l| l.items().iter().any(|r| r.field("mwg-rs:Rotation").is_some())); + if turned { None } else { applied_to(regions) } + } +} + /// A structured XMP value. #[derive(Clone, Debug, PartialEq)] pub enum XmpValue { @@ -416,15 +427,20 @@ fn parse_gps_coord(s: &str) -> Option { /// Malformed or out-of-range entries are skipped rather than rejecting the whole list: one bad region /// (from Lightroom, digiKam, Picasa, or a hand-edited file) shouldn't hide the rest. fn parse_regions(regions: &XmpValue) -> Vec { - // `AppliedToDimensions` documents the pixel size regions were authored against. It's only consulted + // `AppliedToDimensions` documents the pixel size regions were authored against. Here it's only consulted // for the rare region whose own Area is in pixel units instead of MWG's normalized default below. - let px_dims = regions.field("mwg-rs:AppliedToDimensions").and_then(|d| { + let px_dims = applied_to(regions); + let Some(list) = regions.field("mwg-rs:RegionList") else { return Vec::new() }; + list.items().iter().filter_map(|item| parse_one_region(item, px_dims)).collect() +} + +/// `mwg-rs:AppliedToDimensions` of a `mwg-rs:Regions` struct: (width, height) in pixels, both positive. +fn applied_to(regions: &XmpValue) -> Option<(f64, f64)> { + regions.field("mwg-rs:AppliedToDimensions").and_then(|d| { let w = d.field("stDim:w").and_then(XmpValue::text).and_then(parse_number)?; let h = d.field("stDim:h").and_then(XmpValue::text).and_then(parse_number)?; (w > 0.0 && h > 0.0).then_some((w, h)) - }); - let Some(list) = regions.field("mwg-rs:RegionList") else { return Vec::new() }; - list.items().iter().filter_map(|item| parse_one_region(item, px_dims)).collect() + }) } fn parse_one_region(item: &XmpValue, px_dims: Option<(f64, f64)>) -> Option { @@ -1045,6 +1061,36 @@ mod tests { assert!(near(regions[4].rect, [0.6, 0.45, 0.8, 0.75]), "−π (orientation 3): {:?}", regions[4].rect); } + /// The size a packet's boxes were drawn on is its `AppliedToDimensions`, unless a box says how the photo was turned + /// (Lightroom's `mwg-rs:Rotation`: those are upright already) or there is no size to go by. + #[test] + fn regions_drawn_on_is_the_applied_to_size_unless_a_box_says_how_it_was_turned() { + let packet = |dims: &str, rotation: &str| { + format!( + r#" + + {dims} + + + + + + + + + + "# + ) + }; + let dims = r#""#; + let drawn_on = |x: &str| parse_xmp(x).unwrap().regions_drawn_on(); + assert_eq!(drawn_on(&packet(dims, "")), Some((6000.0, 4000.0))); + assert_eq!(drawn_on(&packet(dims, r#" mwg-rs:Rotation="-1.57080""#)), None, "one box turned by Lightroom"); + assert_eq!(drawn_on(&packet("", "")), None, "no AppliedToDimensions"); + assert_eq!(drawn_on(r#""#), None); + } + /// A second, differently-shaped encoding: each region is its own `rdf:Description` (rather than an /// `rdf:li rdf:parseType="Resource"`), `mwg-rs:Type` as an attribute instead of an element, and an /// unrecognised `mwg-rs:Type` value kept verbatim. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index d059494cef..96696048d3 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-10-24 · **Change:** minor (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) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (LR-LIB-PEOPLE: face boxes another app drew on the photo as stored land on the upright photo, #2674; 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) · **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 @@ -104,7 +104,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | 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-LABEL | Colour labels | P1 | ✅ | `cmd:photo.label`, `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), 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 | +| 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 another app drew on the photo as stored (a sideways `AppliedToDimensions`, no `Rotation`) turned with the file's Exif orientation, #2674; 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 | | LR-LIB-STACK | Stacks | P1 | ✅ | `cmd:stack.group`, `cmd:stack.ungroup`, `cmd:stack.toggle`, `cmd:stack.setTop`, `cmd:stack.remove`, `cmd:stack.auto`, `cmd:photo.delete`, `crates/catalog/src/stacks.rs` | grid/filmstrip count badges (a click expands / collapses the stack, selected or not), expand/collapse (a click or double-click on a grid badge toggles the stack once, #2233), auto-stack by capture time; delete / remove folder drop the photo from the stack so `i/n` updates (#1493); no visual-similarity auto-stack | | LR-LIB-VERSIONS | Versions | P1 | ✅ | `cmd:version.create` | see section M | | LR-LIB-DELETE | Delete / Recently Deleted | P0 | ✅ | `cmd:photo.delete`, `cmd:photo.restore`, `cmd:photo.deletePermanently` | Delete and Delete Permanently retain surviving selected photos; if none remain, select the next visible survivor (previous at the end) in the current source/filter/sort; permanent deletion removes catalog records, not files on disk; Restore and Delete Permanently in the Photo menu and the photo context menus for photos in Recently Deleted (before, the UI had no way to restore); importing a file that is in Recently Deleted again restores the photo with its edits, rating and albums (issues #298, #706: before, the import skipped it as "already in the library" while the grid showed it deleted) — the review dialog checks it, badges it "Will be restored", counts it as "in Recently Deleted" rather than "already in the library", and its choice Restore them / Import as new / Leave them starts on Restore; with Leave them such a file starts unchecked and Check All and the file-type toggles leave it out, but a click still checks it and it is restored (issue #1285: before, the click did nothing and the "In Recently Deleted" badge was drawn over the checkbox, which now sits above it); dropped files restore too ("Restored 1 photo from Recently Deleted"); a deleted photo matched by content whose file is gone is relinked to the imported file; Photo ▸ Empty Recently Deleted (`cmd:library.emptyRecentlyDeleted`, one undo step, shown while the trash is the source); import takes `onDeleted` restore (default) / skip / fresh for files in the trash (`cmd:library.import`; the report lists `restored`, and with skip flags the duplicate `existingDeleted`); browsing a folder in Local (`cmd:library.browse`), Auto Import and a Lightroom catalog import never restore a deleted photo; no confirmation dialog, no auto-purge after N days (needs a deleted-at date in the catalog); Delete asks first ("Move this photo to Recently Deleted?") from the key, the Photo menu and the photo context menu, on by default and switched off in Settings ▸ General (#1239: before, it was off by default and the context menu never asked); no auto-purge after N days (needs a deleted-at date in the catalog) | @@ -956,3 +956,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-23 | patch | LR-BEHAV-ACCESS: the name field of New Album, New Smart Album, Rename and the other one-field dialogs takes the keyboard focus once when the dialog opens instead of every frame, so Tab and Shift+Tab reach the check box, Cancel and OK; status unchanged (🟡) | | 2026-10-22 | minor | LR-CROP-AUTO: Auto straighten turns by at most 10° and only on at least 3 agreeing lines, and says when it finds nothing to level by; measured on 68 photos straightened by hand and 300 left as shot, unwanted turns of more than 1° fell from 79 to 19 of the 300. Downgraded ✅ → 🟡: it still leaves most tilted photos alone | | 2026-10-23 | patch | LRC-LIB-FILTERBAR: showing an album (`library.source`) while the filter holds an album drops the filter's album, as showing a library folder already dropped its folder filter; before, the old album stayed in the filter unseen (the filter bar has no album chip) and narrowed the next source such as All Photos; the row's note says so; status unchanged (✅) | +| 2026-10-24 | patch | LR-LIB-PEOPLE: face regions whose `mwg-rs:AppliedToDimensions` is the photo's stored, sideways size (and no `mwg-rs:Rotation` says how it was turned) are turned with the file's Exif orientation when imported and when read again, so they land on the faces of the upright photo instead of where the stored photo had them (#2674); status unchanged (🟡) | diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index 7fd11a1728..5ce8e6a7e3 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -118,8 +118,12 @@ write them, from sidecars and from XMP embedded in the file. Named faces become that misses it entirely, or has a non-finite, zero or negative size, is skipped (the rest of the list is kept). - **Orientation**: regions are stored on the upright (EXIF-oriented) photo. A `mwg-rs:Rotation` of −π/2, +π/2 or ±π (how Lightroom marks a box given in the sensor's frame for Exif orientation 6, 8 or 3) is turned back into the - upright frame; MWG can't say "mirrored", so boxes on mirrored photos (orientations 2, 4, 5, 7) are taken as written. - Boxes follow LightCraft's own Rotate Left/Right and flips. + upright frame; MWG can't say "mirrored", so Lightroom's boxes on mirrored photos (orientations 2, 4, 5, 7) are + taken as written. Other applications mark boxes drawn on the photo as stored only by their size: when + `mwg-rs:AppliedToDimensions` has the shape of the photo as stored rather than upright (a photo that Exif orientation + 5–8 turns a quarter turn, and no `mwg-rs:Rotation`), the boxes are turned with the file's own Exif orientation, + mirror included, when imported and when read again (#2674). A square photo or size looks the same both ways and is + taken as written. Boxes follow LightCraft's own Rotate Left/Right and flips. - **Re-reading**: a sidecar that has `mwg-rs:Regions` — even with an empty list — replaces the photo's regions, so regions removed in another application go away here too. A sidecar without `mwg-rs:Regions` (an application that doesn't do regions) leaves the photo's regions as they are. From e69f8b160dbede254f66d6e0062cc4b4ba59af77 Mon Sep 17 00:00:00 2001 From: insideTheFlux Date: Sat, 24 Oct 2026 18:01:25 -0700 Subject: [PATCH 07/39] LR-LIB-PEOPLE: the image's own size decides, and its orientation is found past the first MiB (#2674) From CodeRabbit's review of #2857: - Import: when the file's orientation swaps the axes and the XMP's boxes were drawn on a stated size, the probe turns the boxes as written by the image header's stored size, not by a size the metadata states (missing, or written for the upright photo). - Read Metadata from File and Synchronize Folder: the file's orientation is read from its first MiB and, when that part states none, from the rest of the file. WebP keeps its EXIF chunk after the image data, many TIFF writers put the first IFD after the strips, and a JPEG's Exif can follow other long segments. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016TuX1qw9ieyuJ1ZFrrUxzc --- crates/engine/src/files.rs | 13 +++---- crates/engine/src/sidecar.rs | 64 ++++++++++++++++++++++++++++++---- crates/engine/src/tests_xmp.rs | 26 ++++++++++++-- docs/xmp-interop.md | 5 +-- 4 files changed, 91 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 0aac050bf3..d1df2e3fcc 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -198,15 +198,16 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { if o.swaps_axes() { std::mem::swap(&mut w, &mut h); } - // regions another app drew on the photo as stored: `extract` turned them upright where the metadata says how - // big the photo is; otherwise the header does (#2674) + // regions another app drew on the photo as stored: `extract` could only tell by the size the metadata states, which + // can be missing or wrong; the header's is the size as stored, so the boxes as written are turned by it (#2674) let mut meta = meta; - if (m.width.is_none() || m.height.is_none()) - && o.swaps_axes() + if o.swaps_axes() && !meta.regions.is_empty() - && let Some(drawn_on) = - lightcraft_meta::embedded(bytes).xmp.and_then(|x| lightcraft_meta::parse_xmp(&x).ok()).and_then(|x| x.regions_drawn_on()) + && let Some(xmp) = lightcraft_meta::embedded(bytes).xmp.and_then(|x| lightcraft_meta::parse_xmp(&x).ok()) + && let Some(drawn_on) = xmp.regions_drawn_on() + && !xmp.metadata.regions.is_empty() { + meta.regions = xmp.metadata.regions; lightcraft_meta::upright_regions(&mut meta.regions, drawn_on, o, (header.width, header.height)); } let format = match ext_upper(name).as_str() { diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index db655ada2c..cfff053076 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -359,20 +359,33 @@ impl SidecarData { /// Take the orientation of the photo file at `original` (LightCraft shows the photo turned by it, and the packet /// may not repeat it) when the regions need it: they were drawn on a stated size ([`SidecarData::regions_drawn_on`]). - /// Only then is the start of the file read. + /// Only then is the file read ([`file_orientation`]). pub fn with_file_orientation(self, original: &str) -> Self { if self.regions_drawn_on.is_none() { return self; } - let mut head = Vec::new(); - let read = std::fs::File::open(original).and_then(|f| f.take(ORIENTATION_SPAN).read_to_end(&mut head)); - let orientation = read.ok().and_then(|_| lightcraft_meta::extract(&head).orientation); - SidecarData { orientation: orientation.or(self.orientation), ..self } + SidecarData { orientation: file_orientation(original).or(self.orientation), ..self } } } -/// How much of a photo file [`SidecarData::with_file_orientation`] reads: Exif sits at the start of every format -/// LightCraft reads. +/// The orientation the photo file at `path` states. Most files state it in their first [`ORIENTATION_SPAN`]; when +/// that part doesn't, the rest is read too: WebP keeps its EXIF chunk after the image data, many TIFF writers put the +/// first IFD after the strips, and a JPEG's Exif can follow other long segments. +fn file_orientation(path: &str) -> Option { + let mut file = std::fs::File::open(path).ok()?; + let mut bytes = Vec::new(); + (&mut file).take(ORIENTATION_SPAN).read_to_end(&mut bytes).ok()?; + if let Some(o) = lightcraft_meta::extract(&bytes).orientation { + return Some(o); + } + if (bytes.len() as u64) < ORIENTATION_SPAN { + return None; + } + file.read_to_end(&mut bytes).ok()?; + lightcraft_meta::extract(&bytes).orientation +} + +/// How much of a photo file [`file_orientation`] reads first. const ORIENTATION_SPAN: u64 = 1 << 20; /// The sidecar packet for a photo; the colour label is written by its name in `cat` (custom @@ -975,6 +988,43 @@ impl Session { #[cfg(test)] mod tests { + /// Issue #2674: a WebP keeps its EXIF chunk after the image data, so its orientation can be past the first + /// [`super::ORIENTATION_SPAN`] of the file; a file that states none has none. + #[test] + fn the_file_orientation_is_found_after_the_image_data() { + let dir = std::env::temp_dir().join(format!("lightcraft-file-orientation-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { + orientation: Some(lightcraft_meta::Orientation::Rotate90), + ..Default::default() + }); + let webp = |image: usize| { + let mut w = b"RIFF\0\0\0\0WEBP".to_vec(); + for (id, data) in [(&b"VP8X"[..], vec![0; 10]), (b"VP8L", vec![0; image]), (b"EXIF", [&b"Exif\0\0"[..], &exif].concat())] { + w.extend_from_slice(id); + w.extend_from_slice(&(data.len() as u32).to_le_bytes()); + w.extend_from_slice(&data); + if data.len() % 2 == 1 { + w.push(0); + } + } + w + }; + let span = super::ORIENTATION_SPAN as usize; + for (name, bytes, want) in [ + ("small.webp", webp(64), Some(lightcraft_meta::Orientation::Rotate90)), + ("large.webp", webp(span + 64), Some(lightcraft_meta::Orientation::Rotate90)), + ("none.webp", webp(span + 64)[..span + 100].to_vec(), None), + ] { + let path = dir.join(name); + std::fs::write(&path, bytes).unwrap(); + assert_eq!(super::file_orientation(&path.to_string_lossy()), want, "{name}"); + } + assert_eq!(super::file_orientation(&dir.join("missing.webp").to_string_lossy()), None); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn sidecars_are_written_only_beside_an_existing_original() { let dir = std::env::temp_dir().join(format!("lightcraft-sidecar-local-{}", std::process::id())); diff --git a/crates/engine/src/tests_xmp.rs b/crates/engine/src/tests_xmp.rs index 52ddfa0f1b..3e88a9735e 100644 --- a/crates/engine/src/tests_xmp.rs +++ b/crates/engine/src/tests_xmp.rs @@ -495,6 +495,18 @@ fn write_turned_jpeg(path: &Path, packet: Option<&str>) { std::fs::write(path, bytes).unwrap(); } +/// Put more than the first MiB of APP15 segments between the JPEG at `path`'s start and its Exif. +fn pad_before_exif(path: &Path) { + let bytes = std::fs::read(path).unwrap(); + let mut padded = bytes[..2].to_vec(); + for _ in 0..17 { + padded.extend_from_slice(&[0xFF, 0xEF, 0xFF, 0xFF]); + padded.extend(std::iter::repeat_n(0, 0xFFFD)); + } + padded.extend_from_slice(&bytes[2..]); + std::fs::write(path, padded).unwrap(); +} + /// The face's box from [`STORED_FRAME_REGIONS`] on the upright photo: turned a quarter turn clockwise with it. fn assert_on_the_upright_face(s: &Session, id: PhotoId, when: &str) { let p = s.catalog.photo(id).unwrap(); @@ -508,7 +520,8 @@ fn assert_on_the_upright_face(s: &Session, id: PhotoId, when: &str) { /// Issue #2674: face boxes an app drew on a photo as stored (its sideways size as `AppliedToDimensions`, no /// `mwg-rs:Rotation`) land on the faces of the photo as LightCraft shows it, upright: when imported, and when the -/// file's metadata is read again (the packet itself doesn't say how the photo turns; the file's Exif does). +/// file's metadata is read again (the packet itself doesn't say how the photo turns; the file's Exif does). The +/// image's own size decides, not one the XMP states upright, and the Exif is found past the first MiB of the file. #[test] fn regions_drawn_on_the_photo_as_stored_land_on_the_upright_photo() { let src = temp_dir("regions-stored-frame"); @@ -517,7 +530,16 @@ fn regions_drawn_on_the_photo_as_stored_land_on_the_upright_photo() { let beside = src.join("sidecar.jpg"); write_turned_jpeg(&beside, None); std::fs::write(src.join("sidecar.xmp"), STORED_FRAME_REGIONS).unwrap(); - for (file, what) in [(&embedded, "embedded XMP"), (&beside, "sidecar")] { + // an Exif without a pixel size, and an XMP size of the upright photo + let stated = src.join("stated.jpg"); + let upright_size = r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:ImageWidth="24" tiff:ImageLength="32""#; + write_turned_jpeg(&stated, Some(&STORED_FRAME_REGIONS.replace(r#"rdf:about="""#, upright_size))); + let late = src.join("late.jpg"); + write_turned_jpeg(&late, None); + pad_before_exif(&late); + std::fs::write(src.join("late.xmp"), STORED_FRAME_REGIONS).unwrap(); + for (file, what) in [(&embedded, "embedded XMP"), (&beside, "sidecar"), (&stated, "upright size in the XMP"), (&late, "Exif after the first MiB")] + { let mut s = Session::new().with_fs(); let r = s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); assert_eq!(r["imported"].as_array().map(Vec::len), Some(1), "{r}"); diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index 5ce8e6a7e3..f7d36e972c 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -122,8 +122,9 @@ write them, from sidecars and from XMP embedded in the file. Named faces become taken as written. Other applications mark boxes drawn on the photo as stored only by their size: when `mwg-rs:AppliedToDimensions` has the shape of the photo as stored rather than upright (a photo that Exif orientation 5–8 turns a quarter turn, and no `mwg-rs:Rotation`), the boxes are turned with the file's own Exif orientation, - mirror included, when imported and when read again (#2674). A square photo or size looks the same both ways and is - taken as written. Boxes follow LightCraft's own Rotate Left/Right and flips. + mirror included, when imported and when read again (#2674). The image's own pixel size decides, not a size the + metadata states, and the orientation is found wherever the file keeps its Exif (WebP after the image data, for + one). A square photo or size looks the same both ways and is taken as written. Boxes follow LightCraft's own Rotate Left/Right and flips. - **Re-reading**: a sidecar that has `mwg-rs:Regions` — even with an empty list — replaces the photo's regions, so regions removed in another application go away here too. A sidecar without `mwg-rs:Regions` (an application that doesn't do regions) leaves the photo's regions as they are. From 4eecf8b8a053b53fc419309306af75c5892d08d1 Mon Sep 17 00:00:00 2001 From: insideTheFlux Date: Sat, 24 Oct 2026 18:26:59 -0700 Subject: [PATCH 08/39] LR-LIB-PEOPLE: find a late orientation by the file's structure, not by reading it whole (#2674) From CodeRabbit's second review of #2857: when a file's first MiB states no orientation, the fallback read the rest of the file into memory, uncapped, and Synchronize Folder checks photos on several threads. It now reads only what holds the orientation: - JPEG: the segment walk Read Metadata from File already uses for XMP (bounded span and steps), stopping at the first APP1 that states one. - WebP: the chunk headers, then the EXIF chunk (at most 1 MiB). - TIFF: the first IFD's entries (under 1 MiB). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016TuX1qw9ieyuJ1ZFrrUxzc --- crates/engine/src/sidecar.rs | 113 +++++++++++++++++++++++++++++++---- 1 file changed, 101 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index cfff053076..a4aaedef9e 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -369,20 +369,77 @@ impl SidecarData { } /// The orientation the photo file at `path` states. Most files state it in their first [`ORIENTATION_SPAN`]; when -/// that part doesn't, the rest is read too: WebP keeps its EXIF chunk after the image data, many TIFF writers put the -/// first IFD after the strips, and a JPEG's Exif can follow other long segments. +/// that part doesn't, the Exif may come later ([`late_orientation`]). fn file_orientation(path: &str) -> Option { let mut file = std::fs::File::open(path).ok()?; - let mut bytes = Vec::new(); - (&mut file).take(ORIENTATION_SPAN).read_to_end(&mut bytes).ok()?; - if let Some(o) = lightcraft_meta::extract(&bytes).orientation { + let mut head = Vec::new(); + (&mut file).take(ORIENTATION_SPAN).read_to_end(&mut head).ok()?; + if let Some(o) = lightcraft_meta::extract(&head).orientation { return Some(o); } - if (bytes.len() as u64) < ORIENTATION_SPAN { + if (head.len() as u64) < ORIENTATION_SPAN { return None; } - file.read_to_end(&mut bytes).ok()?; - lightcraft_meta::extract(&bytes).orientation + late_orientation(&mut file, &head) +} + +/// The orientation of a file whose `head` doesn't state it, found by the file's structure without reading its image +/// data: a JPEG's Exif can follow other long segments, WebP keeps its EXIF chunk after the image data, and many TIFF +/// writers put the first IFD after the strips. +fn late_orientation(file: &mut (impl Read + Seek), head: &[u8]) -> Option { + file.rewind().ok()?; + match head.get(..4)? { + [0xff, 0xd8, ..] => read_jpeg_app1(file, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS, |s| lightcraft_meta::extract(s).orientation), + b"RIFF" if head.get(8..12) == Some(b"WEBP") => webp_orientation(file), + b"II*\0" => tiff_orientation(file, head, true), + b"MM\0*" => tiff_orientation(file, head, false), + _ => None, + } +} + +/// A WebP's orientation from its `EXIF` chunk (at most [`ORIENTATION_SPAN`]), found by walking the chunk headers from +/// the start of `file` (at most [`WEBP_CHUNK_STEPS`]). +fn webp_orientation(file: &mut (impl Read + Seek)) -> Option { + file.seek(SeekFrom::Start(12)).ok()?; + for _ in 0..WEBP_CHUNK_STEPS { + let mut header = [0; 8]; + file.read_exact(&mut header).ok()?; + let [a, b, c, d, s0, s1, s2, s3] = header; + let size = u32::from_le_bytes([s0, s1, s2, s3]); + if [a, b, c, d] == *b"EXIF" { + if u64::from(size) > ORIENTATION_SPAN { + return None; + } + let mut chunk = b"RIFF\0\0\0\0WEBP".to_vec(); + chunk.extend_from_slice(&header); + (&mut *file).take(u64::from(size)).read_to_end(&mut chunk).ok()?; + return lightcraft_meta::extract(&chunk).orientation; + } + // chunks are padded to an even size + file.seek(SeekFrom::Current(i64::from(size) + i64::from(size & 1))).ok()?; + } + None +} + +/// How many chunks [`webp_orientation`] passes over (an animated WebP has one per frame). +const WEBP_CHUNK_STEPS: usize = 4096; + +/// A TIFF's orientation from the first IFD that `head` points to, of which only the 12-byte entries are read (at most +/// 65535 of them, under 1 MiB). `le`: little-endian (`II`). +fn tiff_orientation(file: &mut (impl Read + Seek), head: &[u8], le: bool) -> Option { + let u16_of = |b: [u8; 2]| if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }; + let [o0, o1, o2, o3] = <[u8; 4]>::try_from(head.get(4..8)?).ok()?; + let ifd = if le { u32::from_le_bytes([o0, o1, o2, o3]) } else { u32::from_be_bytes([o0, o1, o2, o3]) }; + file.seek(SeekFrom::Start(u64::from(ifd))).ok()?; + let mut count = [0; 2]; + file.read_exact(&mut count).ok()?; + let mut entries = vec![0; usize::from(u16_of(count)) * 12]; + file.read_exact(&mut entries).ok()?; + let orientation = entries.as_chunks::<12>().0.iter().find_map(|&[t0, t1, y0, y1, _, _, _, _, v0, v1, _, _]| { + // tag 274, one SHORT + (u16_of([t0, t1]) == 274 && u16_of([y0, y1]) == 3).then(|| u16_of([v0, v1])) + })?; + (1..=8).contains(&orientation).then(|| lightcraft_meta::Orientation::from_exif(orientation)) } /// How much of a photo file [`file_orientation`] reads first. @@ -593,6 +650,11 @@ const JPEG_XMP_HEADER_STEPS: usize = 4096; /// consumes one iteration. Only a complete APP1 payload (at most 65533 bytes) reaches the shared /// parser, in a single SOI+APP1 wrapper (at most 65539 bytes). This does not validate the whole JPEG. fn read_jpeg_xmp(reader: &mut (impl Read + Seek), header_span: u64, marker_steps: usize) -> Option { + read_jpeg_app1(reader, header_span, marker_steps, |segment| lightcraft_meta::jpeg_segments(segment).xmp) +} + +/// Like [`read_jpeg_xmp`], stopping at the first APP1 segment (in its SOI+APP1 wrapper) that `pick` finds something in. +fn read_jpeg_app1(reader: &mut (impl Read + Seek), header_span: u64, marker_steps: usize, pick: impl Fn(&[u8]) -> Option) -> Option { let mut header = reader.take(header_span); let mut soi = [0; 2]; header.read_exact(&mut soi).ok()?; @@ -633,8 +695,8 @@ fn read_jpeg_xmp(reader: &mut (impl Read + Seek), header_span: u64, marker_steps segment.extend_from_slice(&[0xff, 0xd8, 0xff, 0xe1, hi, lo]); segment.resize(segment_len, 0); header.read_exact(segment.get_mut(6..)?).ok()?; - if let Some(xmp) = lightcraft_meta::jpeg_segments(&segment).xmp { - return Some(xmp); + if let Some(found) = pick(&segment) { + return Some(found); } } None @@ -988,8 +1050,8 @@ impl Session { #[cfg(test)] mod tests { - /// Issue #2674: a WebP keeps its EXIF chunk after the image data, so its orientation can be past the first - /// [`super::ORIENTATION_SPAN`] of the file; a file that states none has none. + /// Issue #2674: a WebP keeps its EXIF chunk after the image data, and a TIFF's first IFD can follow its strips, so + /// the orientation can be past the first [`super::ORIENTATION_SPAN`] of the file; a file that states none has none. #[test] fn the_file_orientation_is_found_after_the_image_data() { let dir = std::env::temp_dir().join(format!("lightcraft-file-orientation-{}", std::process::id())); @@ -1012,10 +1074,37 @@ mod tests { w }; let span = super::ORIENTATION_SPAN as usize; + // a TIFF whose first IFD (orientation 8, then a tag pointing elsewhere) follows `strips` bytes of image data + let tiff = |le: bool, strips: usize| { + let (u16_of, u32_of): (fn(u16) -> [u8; 2], fn(u32) -> [u8; 4]) = + if le { (u16::to_le_bytes, u32::to_le_bytes) } else { (u16::to_be_bytes, u32::to_be_bytes) }; + let mut t = if le { b"II*\0".to_vec() } else { b"MM\0*".to_vec() }; + t.extend_from_slice(&u32_of(8 + strips as u32)); + t.resize(8 + strips, 0); + t.extend_from_slice(&u16_of(2)); + for (tag, kind, count, value) in [(274u16, 3u16, 1u32, [u16_of(8), [0, 0]].concat()), (305, 2, 64, u32_of(4).to_vec())] { + t.extend_from_slice(&u16_of(tag)); + t.extend_from_slice(&u16_of(kind)); + t.extend_from_slice(&u32_of(count)); + t.extend_from_slice(&value); + } + t.extend_from_slice(&[0; 4]); + t + }; + // a JPEG whose first MiB is other segments, then the start of its image data: no Exif + let mut jpeg = vec![0xff, 0xd8]; + for _ in 0..17 { + jpeg.extend_from_slice(&[0xff, 0xef, 0xff, 0xff]); + jpeg.resize(jpeg.len() + 0xfffd, 0); + } + jpeg.extend_from_slice(&[0xff, 0xda, 0, 2, 0xff, 0xd9]); for (name, bytes, want) in [ ("small.webp", webp(64), Some(lightcraft_meta::Orientation::Rotate90)), ("large.webp", webp(span + 64), Some(lightcraft_meta::Orientation::Rotate90)), ("none.webp", webp(span + 64)[..span + 100].to_vec(), None), + ("le.tif", tiff(true, span + 64), Some(lightcraft_meta::Orientation::Rotate270)), + ("be.tif", tiff(false, span + 64), Some(lightcraft_meta::Orientation::Rotate270)), + ("none.jpg", jpeg, None), ] { let path = dir.join(name); std::fs::write(&path, bytes).unwrap(); From 26f73e49781c577cad109fc48c76bd8e01a1706d Mon Sep 17 00:00:00 2001 From: insideTheFlux Date: Sat, 24 Oct 2026 18:47:52 -0700 Subject: [PATCH 09/39] LR-LIB-PEOPLE: a late TIFF orientation is one SHORT; a late WebP one may be in its XMP (#2674) From CodeRabbit's third review of #2857: the TIFF fallback took tag 274's value field without checking its count, so a malformed entry with three or more values, whose field is then an offset, read the offset as the orientation. It now needs exactly one SHORT. Also found applying the review checklist: the WebP fallback read only the EXIF chunk, while the first-MiB path also takes the orientation from XMP. It now reads the EXIF chunk, else the XMP one, each only up to 1 MiB. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016TuX1qw9ieyuJ1ZFrrUxzc --- crates/engine/src/sidecar.rs | 70 ++++++++++++++++++++++-------------- 1 file changed, 43 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index a4aaedef9e..383f55e752 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -397,8 +397,9 @@ fn late_orientation(file: &mut (impl Read + Seek), head: &[u8]) -> Option Option { file.seek(SeekFrom::Start(12)).ok()?; for _ in 0..WEBP_CHUNK_STEPS { @@ -406,17 +407,18 @@ fn webp_orientation(file: &mut (impl Read + Seek)) -> Option ORIENTATION_SPAN { - return None; - } + // chunks are padded to an even size + let mut skip = i64::from(size) + i64::from(size & 1); + if matches!(&[a, b, c, d], b"EXIF" | b"XMP ") && u64::from(size) <= ORIENTATION_SPAN { let mut chunk = b"RIFF\0\0\0\0WEBP".to_vec(); chunk.extend_from_slice(&header); (&mut *file).take(u64::from(size)).read_to_end(&mut chunk).ok()?; - return lightcraft_meta::extract(&chunk).orientation; + if let Some(o) = lightcraft_meta::extract(&chunk).orientation { + return Some(o); + } + skip = i64::from(size & 1); } - // chunks are padded to an even size - file.seek(SeekFrom::Current(i64::from(size) + i64::from(size & 1))).ok()?; + file.seek(SeekFrom::Current(skip)).ok()?; } None } @@ -428,16 +430,16 @@ const WEBP_CHUNK_STEPS: usize = 4096; /// 65535 of them, under 1 MiB). `le`: little-endian (`II`). fn tiff_orientation(file: &mut (impl Read + Seek), head: &[u8], le: bool) -> Option { let u16_of = |b: [u8; 2]| if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }; - let [o0, o1, o2, o3] = <[u8; 4]>::try_from(head.get(4..8)?).ok()?; - let ifd = if le { u32::from_le_bytes([o0, o1, o2, o3]) } else { u32::from_be_bytes([o0, o1, o2, o3]) }; + let u32_of = |b: [u8; 4]| if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }; + let ifd = u32_of(<[u8; 4]>::try_from(head.get(4..8)?).ok()?); file.seek(SeekFrom::Start(u64::from(ifd))).ok()?; let mut count = [0; 2]; file.read_exact(&mut count).ok()?; let mut entries = vec![0; usize::from(u16_of(count)) * 12]; file.read_exact(&mut entries).ok()?; - let orientation = entries.as_chunks::<12>().0.iter().find_map(|&[t0, t1, y0, y1, _, _, _, _, v0, v1, _, _]| { - // tag 274, one SHORT - (u16_of([t0, t1]) == 274 && u16_of([y0, y1]) == 3).then(|| u16_of([v0, v1])) + let orientation = entries.as_chunks::<12>().0.iter().find_map(|&[t0, t1, y0, y1, c0, c1, c2, c3, v0, v1, _, _]| { + // tag 274, exactly one SHORT (with more, the field also holds a second value, or an offset to them all) + (u16_of([t0, t1]) == 274 && u16_of([y0, y1]) == 3 && u32_of([c0, c1, c2, c3]) == 1).then(|| u16_of([v0, v1])) })?; (1..=8).contains(&orientation).then(|| lightcraft_meta::Orientation::from_exif(orientation)) } @@ -1050,8 +1052,9 @@ impl Session { #[cfg(test)] mod tests { - /// Issue #2674: a WebP keeps its EXIF chunk after the image data, and a TIFF's first IFD can follow its strips, so - /// the orientation can be past the first [`super::ORIENTATION_SPAN`] of the file; a file that states none has none. + /// Issue #2674: a WebP keeps its EXIF and XMP chunks after the image data, and a TIFF's first IFD can follow its + /// strips, so the orientation can be past the first [`super::ORIENTATION_SPAN`] of the file; EXIF wins over XMP, a + /// chunk over that span isn't read, and a file that states none has none. #[test] fn the_file_orientation_is_found_after_the_image_data() { let dir = std::env::temp_dir().join(format!("lightcraft-file-orientation-{}", std::process::id())); @@ -1061,28 +1064,38 @@ mod tests { orientation: Some(lightcraft_meta::Orientation::Rotate90), ..Default::default() }); - let webp = |image: usize| { + let span = super::ORIENTATION_SPAN as usize; + // a WebP: `image` bytes of image data, then the `meta` chunks + let webp = |image: usize, meta: &[(&[u8], Vec)]| { let mut w = b"RIFF\0\0\0\0WEBP".to_vec(); - for (id, data) in [(&b"VP8X"[..], vec![0; 10]), (b"VP8L", vec![0; image]), (b"EXIF", [&b"Exif\0\0"[..], &exif].concat())] { + for (id, data) in [(&b"VP8X"[..], vec![0; 10]), (b"VP8L", vec![0; image])].iter().chain(meta) { w.extend_from_slice(id); w.extend_from_slice(&(data.len() as u32).to_le_bytes()); - w.extend_from_slice(&data); + w.extend_from_slice(data); if data.len() % 2 == 1 { w.push(0); } } w }; - let span = super::ORIENTATION_SPAN as usize; + let exif_chunk = (&b"EXIF"[..], [&b"Exif\0\0"[..], &exif].concat()); + // an EXIF chunk over the span that is read (orientation 6 too), and an XMP packet stating orientation 8 + let huge_exif = (&b"EXIF"[..], [&b"Exif\0\0"[..], &exif, &vec![0; span]].concat()); + let packet = lightcraft_meta::write_xmp( + &lightcraft_meta::Metadata { orientation: Some(lightcraft_meta::Orientation::Rotate270), ..Default::default() }, + None, + ); + let xmp_chunk = (&b"XMP "[..], packet.into_bytes()); // a TIFF whose first IFD (orientation 8, then a tag pointing elsewhere) follows `strips` bytes of image data - let tiff = |le: bool, strips: usize| { + // (`values` of the orientation tag: more than two are at an offset, here 8) + let tiff = |le: bool, strips: usize, values: u32| { let (u16_of, u32_of): (fn(u16) -> [u8; 2], fn(u32) -> [u8; 4]) = if le { (u16::to_le_bytes, u32::to_le_bytes) } else { (u16::to_be_bytes, u32::to_be_bytes) }; let mut t = if le { b"II*\0".to_vec() } else { b"MM\0*".to_vec() }; t.extend_from_slice(&u32_of(8 + strips as u32)); t.resize(8 + strips, 0); t.extend_from_slice(&u16_of(2)); - for (tag, kind, count, value) in [(274u16, 3u16, 1u32, [u16_of(8), [0, 0]].concat()), (305, 2, 64, u32_of(4).to_vec())] { + for (tag, kind, count, value) in [(274u16, 3u16, values, [u16_of(8), [0, 0]].concat()), (305, 2, 64, u32_of(4).to_vec())] { t.extend_from_slice(&u16_of(tag)); t.extend_from_slice(&u16_of(kind)); t.extend_from_slice(&u32_of(count)); @@ -1099,11 +1112,14 @@ mod tests { } jpeg.extend_from_slice(&[0xff, 0xda, 0, 2, 0xff, 0xd9]); for (name, bytes, want) in [ - ("small.webp", webp(64), Some(lightcraft_meta::Orientation::Rotate90)), - ("large.webp", webp(span + 64), Some(lightcraft_meta::Orientation::Rotate90)), - ("none.webp", webp(span + 64)[..span + 100].to_vec(), None), - ("le.tif", tiff(true, span + 64), Some(lightcraft_meta::Orientation::Rotate270)), - ("be.tif", tiff(false, span + 64), Some(lightcraft_meta::Orientation::Rotate270)), + ("small.webp", webp(64, std::slice::from_ref(&exif_chunk)), Some(lightcraft_meta::Orientation::Rotate90)), + ("large.webp", webp(span + 64, &[exif_chunk.clone(), xmp_chunk.clone()]), Some(lightcraft_meta::Orientation::Rotate90)), + ("none.webp", webp(span + 64, &[exif_chunk])[..span + 100].to_vec(), None), + ("xmp.webp", webp(span + 64, std::slice::from_ref(&xmp_chunk)), Some(lightcraft_meta::Orientation::Rotate270)), + ("huge.webp", webp(span + 64, &[huge_exif, xmp_chunk]), Some(lightcraft_meta::Orientation::Rotate270)), + ("le.tif", tiff(true, span + 64, 1), Some(lightcraft_meta::Orientation::Rotate270)), + ("be.tif", tiff(false, span + 64, 1), Some(lightcraft_meta::Orientation::Rotate270)), + ("offset.tif", tiff(true, span + 64, 3), None), ("none.jpg", jpeg, None), ] { let path = dir.join(name); From 4e350dc756e4d8d121d16dec62832621fe88b39f Mon Sep 17 00:00:00 2001 From: insideTheFlux Date: Sat, 24 Oct 2026 19:12:41 -0700 Subject: [PATCH 10/39] LR-LIB-PEOPLE: a re-read takes the file's orientation in the import's order, Exif before XMP (#2674) From CodeRabbit's fourth review of #2857: a WebP whose XMP chunk comes before its EXIF chunk gave XMP's orientation on a re-read, while the import (reading the whole file) takes Exif's. When the two disagree, Read Metadata from File would move the boxes and Synchronize Folder would see news every time. Now only an Exif orientation ends the search, in the first MiB and in the late walks (JPEG APP1 segments, WebP chunks in any order); XMP is used only when no Exif states one. Also, from going over the other sources: the TIFF walk reads the IFD's XMP packet (tag 700, at most 1 MiB) when its orientation tag is missing or invalid, as read_exif does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016TuX1qw9ieyuJ1ZFrrUxzc --- crates/engine/src/sidecar.rs | 194 ++++++++++++++++++++++++----------- 1 file changed, 134 insertions(+), 60 deletions(-) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 383f55e752..858a609249 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -368,28 +368,42 @@ impl SidecarData { } } -/// The orientation the photo file at `path` states. Most files state it in their first [`ORIENTATION_SPAN`]; when -/// that part doesn't, the Exif may come later ([`late_orientation`]). +/// The orientation the photo file at `path` states, by the precedence [`lightcraft_meta::extract`] gives a whole file +/// (the import's): Exif wherever it is, else XMP. Most files state it in the Exif of their first +/// [`ORIENTATION_SPAN`]; when that part doesn't, the Exif may come later ([`late_orientation`]). fn file_orientation(path: &str) -> Option { let mut file = std::fs::File::open(path).ok()?; let mut head = Vec::new(); (&mut file).take(ORIENTATION_SPAN).read_to_end(&mut head).ok()?; - if let Some(o) = lightcraft_meta::extract(&head).orientation { + if let Some(o) = exif_orientation(&head) { return Some(o); } - if (head.len() as u64) < ORIENTATION_SPAN { - return None; - } - late_orientation(&mut file, &head) + let late = if (head.len() as u64) < ORIENTATION_SPAN { None } else { late_orientation(&mut file, &head) }; + late.or_else(|| lightcraft_meta::extract(&head).orientation) } -/// The orientation of a file whose `head` doesn't state it, found by the file's structure without reading its image -/// data: a JPEG's Exif can follow other long segments, WebP keeps its EXIF chunk after the image data, and many TIFF -/// writers put the first IFD after the strips. +/// The orientation the Exif in `bytes` (a file, or the start of one) states, leaving out XMP. +fn exif_orientation(bytes: &[u8]) -> Option { + lightcraft_meta::embedded(bytes).exif.as_deref().map(lightcraft_meta::read_exif).and_then(|m| m.orientation) +} + +/// The orientation of a file whose `head` has no Exif stating it, found by the file's structure without reading its +/// image data (a JPEG's Exif can follow other long segments, WebP keeps its metadata chunks after the image data, and +/// many TIFF writers put the first IFD after the strips): Exif's, else the first XMP packet's. fn late_orientation(file: &mut (impl Read + Seek), head: &[u8]) -> Option { file.rewind().ok()?; match head.get(..4)? { - [0xff, 0xd8, ..] => read_jpeg_app1(file, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS, |s| lightcraft_meta::extract(s).orientation), + [0xff, 0xd8, ..] => { + let mut xmp = None; + let exif = read_jpeg_app1(file, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS, |segment| { + let exif = exif_orientation(segment); + if exif.is_none() && xmp.is_none() { + xmp = lightcraft_meta::extract(segment).orientation; + } + exif + }); + exif.or(xmp) + } b"RIFF" if head.get(8..12) == Some(b"WEBP") => webp_orientation(file), b"II*\0" => tiff_orientation(file, head, true), b"MM\0*" => tiff_orientation(file, head, false), @@ -397,37 +411,48 @@ fn late_orientation(file: &mut (impl Read + Seek), head: &[u8]) -> Option Option { file.seek(SeekFrom::Start(12)).ok()?; + let mut xmp = None; for _ in 0..WEBP_CHUNK_STEPS { let mut header = [0; 8]; - file.read_exact(&mut header).ok()?; + if file.read_exact(&mut header).is_err() { + break; + } let [a, b, c, d, s0, s1, s2, s3] = header; let size = u32::from_le_bytes([s0, s1, s2, s3]); // chunks are padded to an even size let mut skip = i64::from(size) + i64::from(size & 1); - if matches!(&[a, b, c, d], b"EXIF" | b"XMP ") && u64::from(size) <= ORIENTATION_SPAN { + let exif = &[a, b, c, d] == b"EXIF"; + if (exif || (&[a, b, c, d] == b"XMP " && xmp.is_none())) && u64::from(size) <= ORIENTATION_SPAN { let mut chunk = b"RIFF\0\0\0\0WEBP".to_vec(); chunk.extend_from_slice(&header); - (&mut *file).take(u64::from(size)).read_to_end(&mut chunk).ok()?; - if let Some(o) = lightcraft_meta::extract(&chunk).orientation { - return Some(o); + if (&mut *file).take(u64::from(size)).read_to_end(&mut chunk).is_err() { + break; } + let found = lightcraft_meta::extract(&chunk).orientation; + if exif && found.is_some() { + return found; + } + xmp = xmp.or(found); skip = i64::from(size & 1); } - file.seek(SeekFrom::Current(skip)).ok()?; + if file.seek(SeekFrom::Current(skip)).is_err() { + break; + } } - None + xmp } /// How many chunks [`webp_orientation`] passes over (an animated WebP has one per frame). const WEBP_CHUNK_STEPS: usize = 4096; /// A TIFF's orientation from the first IFD that `head` points to, of which only the 12-byte entries are read (at most -/// 65535 of them, under 1 MiB). `le`: little-endian (`II`). +/// 65535 of them, under 1 MiB): its orientation tag, else (as [`lightcraft_meta::read_exif`] does) the XMP packet its +/// tag 700 holds, read if it is at most [`ORIENTATION_SPAN`]. `le`: little-endian (`II`). fn tiff_orientation(file: &mut (impl Read + Seek), head: &[u8], le: bool) -> Option { let u16_of = |b: [u8; 2]| if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }; let u32_of = |b: [u8; 4]| if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }; @@ -437,11 +462,27 @@ fn tiff_orientation(file: &mut (impl Read + Seek), head: &[u8], le: bool) -> Opt file.read_exact(&mut count).ok()?; let mut entries = vec![0; usize::from(u16_of(count)) * 12]; file.read_exact(&mut entries).ok()?; - let orientation = entries.as_chunks::<12>().0.iter().find_map(|&[t0, t1, y0, y1, c0, c1, c2, c3, v0, v1, _, _]| { - // tag 274, exactly one SHORT (with more, the field also holds a second value, or an offset to them all) - (u16_of([t0, t1]) == 274 && u16_of([y0, y1]) == 3 && u32_of([c0, c1, c2, c3]) == 1).then(|| u16_of([v0, v1])) - })?; - (1..=8).contains(&orientation).then(|| lightcraft_meta::Orientation::from_exif(orientation)) + let mut xmp = None; + for &[t0, t1, y0, y1, c0, c1, c2, c3, v0, v1, v2, v3] in entries.as_chunks::<12>().0 { + let (tag, kind, count) = (u16_of([t0, t1]), u16_of([y0, y1]), u32_of([c0, c1, c2, c3])); + match (tag, kind) { + // exactly one SHORT (with more, the field also holds a second value, or an offset to them all) + (274, 3) if count == 1 => { + let v = u16_of([v0, v1]); + if (1..=8).contains(&v) { + return Some(lightcraft_meta::Orientation::from_exif(v)); + } + } + // BYTE or UNDEFINED, at an offset (a packet longer than the field's four bytes) + (700, 1 | 7) if count > 4 && u64::from(count) <= ORIENTATION_SPAN => xmp = Some((u32_of([v0, v1, v2, v3]), count)), + _ => {} + } + } + let (offset, len) = xmp?; + file.seek(SeekFrom::Start(u64::from(offset))).ok()?; + let mut packet = Vec::new(); + (&mut *file).take(u64::from(len)).read_to_end(&mut packet).ok()?; + lightcraft_meta::parse_xmp(&String::from_utf8_lossy(&packet)).ok()?.metadata.orientation } /// How much of a photo file [`file_orientation`] reads first. @@ -656,7 +697,7 @@ fn read_jpeg_xmp(reader: &mut (impl Read + Seek), header_span: u64, marker_steps } /// Like [`read_jpeg_xmp`], stopping at the first APP1 segment (in its SOI+APP1 wrapper) that `pick` finds something in. -fn read_jpeg_app1(reader: &mut (impl Read + Seek), header_span: u64, marker_steps: usize, pick: impl Fn(&[u8]) -> Option) -> Option { +fn read_jpeg_app1(reader: &mut (impl Read + Seek), header_span: u64, marker_steps: usize, mut pick: impl FnMut(&[u8]) -> Option) -> Option { let mut header = reader.take(header_span); let mut soi = [0; 2]; header.read_exact(&mut soi).ok()?; @@ -1052,9 +1093,10 @@ impl Session { #[cfg(test)] mod tests { - /// Issue #2674: a WebP keeps its EXIF and XMP chunks after the image data, and a TIFF's first IFD can follow its - /// strips, so the orientation can be past the first [`super::ORIENTATION_SPAN`] of the file; EXIF wins over XMP, a - /// chunk over that span isn't read, and a file that states none has none. + /// Issue #2674: a WebP keeps its EXIF and XMP chunks after the image data, a TIFF's first IFD can follow its strips + /// and a JPEG's Exif other long segments, so the orientation can be past the first [`super::ORIENTATION_SPAN`] of + /// the file. Exif wins over XMP wherever each is, as when the import reads the whole file; a chunk over that span + /// isn't read, and a file that states none has none. #[test] fn the_file_orientation_is_found_after_the_image_data() { let dir = std::env::temp_dir().join(format!("lightcraft-file-orientation-{}", std::process::id())); @@ -1065,10 +1107,11 @@ mod tests { ..Default::default() }); let span = super::ORIENTATION_SPAN as usize; - // a WebP: `image` bytes of image data, then the `meta` chunks - let webp = |image: usize, meta: &[(&[u8], Vec)]| { + let (o6, o8) = (Some(lightcraft_meta::Orientation::Rotate90), Some(lightcraft_meta::Orientation::Rotate270)); + // a WebP: VP8X, then `chunks` + let webp = |chunks: &[(&[u8], Vec)]| { let mut w = b"RIFF\0\0\0\0WEBP".to_vec(); - for (id, data) in [(&b"VP8X"[..], vec![0; 10]), (b"VP8L", vec![0; image])].iter().chain(meta) { + for (id, data) in [(&b"VP8X"[..], vec![0; 10])].iter().chain(chunks) { w.extend_from_slice(id); w.extend_from_slice(&(data.len() as u32).to_le_bytes()); w.extend_from_slice(data); @@ -1078,49 +1121,80 @@ mod tests { } w }; + let image = |len: usize| (&b"VP8L"[..], vec![0; len]); let exif_chunk = (&b"EXIF"[..], [&b"Exif\0\0"[..], &exif].concat()); // an EXIF chunk over the span that is read (orientation 6 too), and an XMP packet stating orientation 8 let huge_exif = (&b"EXIF"[..], [&b"Exif\0\0"[..], &exif, &vec![0; span]].concat()); - let packet = lightcraft_meta::write_xmp( - &lightcraft_meta::Metadata { orientation: Some(lightcraft_meta::Orientation::Rotate270), ..Default::default() }, - None, - ); - let xmp_chunk = (&b"XMP "[..], packet.into_bytes()); - // a TIFF whose first IFD (orientation 8, then a tag pointing elsewhere) follows `strips` bytes of image data - // (`values` of the orientation tag: more than two are at an offset, here 8) - let tiff = |le: bool, strips: usize, values: u32| { + let packet = lightcraft_meta::write_xmp(&lightcraft_meta::Metadata { orientation: o8, ..Default::default() }, None); + let xmp_chunk = (&b"XMP "[..], packet.clone().into_bytes()); + // a TIFF whose first IFD follows more than the first MiB of image data: an orientation tag of `values` values + // whose field starts with `value` (with more than two, it is an offset), a tag pointing elsewhere, and an XMP + // packet (tag 700) stored after the IFD + let tiff = |le: bool, orientation: Option<(u32, u16)>, xmp: Option<&str>| { let (u16_of, u32_of): (fn(u16) -> [u8; 2], fn(u32) -> [u8; 4]) = if le { (u16::to_le_bytes, u32::to_le_bytes) } else { (u16::to_be_bytes, u32::to_be_bytes) }; + let strips = span + 64; + let mut entries = Vec::new(); + if let Some((values, value)) = orientation { + entries.push((274u16, 3u16, values, [u16_of(value), [0, 0]].concat())); + } + entries.push((305, 2, 64, u32_of(4).to_vec())); + let packet_at = 8 + strips + 2 + 12 * (entries.len() + usize::from(xmp.is_some())) + 4; + if let Some(x) = xmp { + entries.push((700, 7, x.len() as u32, u32_of(packet_at as u32).to_vec())); + } let mut t = if le { b"II*\0".to_vec() } else { b"MM\0*".to_vec() }; t.extend_from_slice(&u32_of(8 + strips as u32)); t.resize(8 + strips, 0); - t.extend_from_slice(&u16_of(2)); - for (tag, kind, count, value) in [(274u16, 3u16, values, [u16_of(8), [0, 0]].concat()), (305, 2, 64, u32_of(4).to_vec())] { + t.extend_from_slice(&u16_of(entries.len() as u16)); + for (tag, kind, count, value) in entries { t.extend_from_slice(&u16_of(tag)); t.extend_from_slice(&u16_of(kind)); t.extend_from_slice(&u32_of(count)); t.extend_from_slice(&value); } t.extend_from_slice(&[0; 4]); + t.extend_from_slice(xmp.unwrap_or_default().as_bytes()); t }; - // a JPEG whose first MiB is other segments, then the start of its image data: no Exif - let mut jpeg = vec![0xff, 0xd8]; - for _ in 0..17 { - jpeg.extend_from_slice(&[0xff, 0xef, 0xff, 0xff]); - jpeg.resize(jpeg.len() + 0xfffd, 0); - } - jpeg.extend_from_slice(&[0xff, 0xda, 0, 2, 0xff, 0xd9]); + // a JPEG: the APP1 payloads `early`, more than the first MiB of other segments, `late`, the image data + let jpeg = |early: &[Vec], late: &[Vec]| { + let app1 = |j: &mut Vec, payload: &Vec| { + j.extend_from_slice(&[0xff, 0xe1]); + j.extend_from_slice(&(payload.len() as u16 + 2).to_be_bytes()); + j.extend_from_slice(payload); + }; + let mut j = vec![0xff, 0xd8]; + early.iter().for_each(|p| app1(&mut j, p)); + for _ in 0..17 { + j.extend_from_slice(&[0xff, 0xef, 0xff, 0xff]); + j.resize(j.len() + 0xfffd, 0); + } + late.iter().for_each(|p| app1(&mut j, p)); + j.extend_from_slice(&[0xff, 0xda, 0, 2, 0xff, 0xd9]); + j + }; + let exif_app1 = [&b"Exif\0\0"[..], &exif].concat(); + let xmp_app1 = [&b"http://ns.adobe.com/xap/1.0/\0"[..], packet.as_bytes()].concat(); for (name, bytes, want) in [ - ("small.webp", webp(64, std::slice::from_ref(&exif_chunk)), Some(lightcraft_meta::Orientation::Rotate90)), - ("large.webp", webp(span + 64, &[exif_chunk.clone(), xmp_chunk.clone()]), Some(lightcraft_meta::Orientation::Rotate90)), - ("none.webp", webp(span + 64, &[exif_chunk])[..span + 100].to_vec(), None), - ("xmp.webp", webp(span + 64, std::slice::from_ref(&xmp_chunk)), Some(lightcraft_meta::Orientation::Rotate270)), - ("huge.webp", webp(span + 64, &[huge_exif, xmp_chunk]), Some(lightcraft_meta::Orientation::Rotate270)), - ("le.tif", tiff(true, span + 64, 1), Some(lightcraft_meta::Orientation::Rotate270)), - ("be.tif", tiff(false, span + 64, 1), Some(lightcraft_meta::Orientation::Rotate270)), - ("offset.tif", tiff(true, span + 64, 3), None), - ("none.jpg", jpeg, None), + ("small.webp", webp(&[image(64), exif_chunk.clone()]), o6), + ("large.webp", webp(&[image(span + 64), exif_chunk.clone(), xmp_chunk.clone()]), o6), + // EXIF wins in whichever order the chunks come, and an XMP in the first MiB doesn't stop the search + ("reversed.webp", webp(&[image(span + 64), xmp_chunk.clone(), exif_chunk.clone()]), o6), + ("xmp-first.webp", webp(&[xmp_chunk.clone(), image(span + 64), exif_chunk.clone()]), o6), + ("none.webp", webp(&[image(span + 64), exif_chunk])[..span + 100].to_vec(), None), + ("xmp.webp", webp(&[image(span + 64), xmp_chunk.clone()]), o8), + ("huge.webp", webp(&[image(span + 64), huge_exif, xmp_chunk]), o8), + ("le.tif", tiff(true, Some((1, 8)), None), o8), + ("be.tif", tiff(false, Some((1, 8)), None), o8), + ("offset.tif", tiff(true, Some((3, 8)), None), None), + // the tag wins over the IFD's XMP; XMP fills in for no tag or an invalid one + ("both.tif", tiff(true, Some((1, 6)), Some(&packet)), o6), + ("xmp.tif", tiff(false, None, Some(&packet)), o8), + ("invalid.tif", tiff(true, Some((1, 0)), Some(&packet)), o8), + ("none.jpg", jpeg(&[], &[]), None), + ("xmp-first.jpg", jpeg(std::slice::from_ref(&xmp_app1), std::slice::from_ref(&exif_app1)), o6), + ("xmp-only.jpg", jpeg(&[], std::slice::from_ref(&xmp_app1)), o8), ] { let path = dir.join(name); std::fs::write(&path, bytes).unwrap(); From 64998a1acf2328caa6b3c4a56989a480b6cf4e38 Mon Sep 17 00:00:00 2001 From: insideTheFlux Date: Sat, 24 Oct 2026 19:57:51 -0700 Subject: [PATCH 11/39] LR-LIB-PEOPLE: a WebP's EXIF chunk of any size is read by its IFD, and the last one counts, as at import (#2674) From CodeRabbit's fifth review of #2857: in a WebP longer than the first MiB, an EXIF chunk over 1 MiB was skipped and the XMP after it used, while the import (reading the whole file) takes the Exif's orientation. The WebP walk now reads only the first IFD of the EXIF chunk, whatever its size: the TIFF walk takes the stream's start and end, its offsets count from that start, and nothing outside it is read. Also, from checking each fallback against what the import reads: a WebP takes its last EXIF and last XMP chunk (the walk notes where they are and reads one of each at most), so its chunks are walked even when the first MiB holds an EXIF chunk; a JPEG takes its first Exif segment, else its first XMP segment. A file under 1 MiB is read as the import reads it. Every test case is now also checked against lightcraft_meta::extract; an XMP chunk over 1 MiB stays unread, and a test says so. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018U5oDm8hZ4tVD3Kqvg7iat --- crates/engine/src/sidecar.rs | 185 ++++++++++++++++++++++++----------- 1 file changed, 127 insertions(+), 58 deletions(-) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 858a609249..271ab76777 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -368,99 +368,130 @@ impl SidecarData { } } -/// The orientation the photo file at `path` states, by the precedence [`lightcraft_meta::extract`] gives a whole file -/// (the import's): Exif wherever it is, else XMP. Most files state it in the Exif of their first -/// [`ORIENTATION_SPAN`]; when that part doesn't, the Exif may come later ([`late_orientation`]). +/// The orientation the photo file at `path` states, as [`lightcraft_meta::extract`] reads it from the whole file (the +/// import's): Exif's, else XMP's. A file shorter than [`ORIENTATION_SPAN`] is read whole. Most others state it in the +/// Exif of their first [`ORIENTATION_SPAN`]; when that part doesn't, the Exif may come later ([`late_orientation`]). +/// A WebP's chunks are always walked, since its last EXIF chunk is the one that counts ([`webp_orientation`]). fn file_orientation(path: &str) -> Option { let mut file = std::fs::File::open(path).ok()?; let mut head = Vec::new(); (&mut file).take(ORIENTATION_SPAN).read_to_end(&mut head).ok()?; + if (head.len() as u64) < ORIENTATION_SPAN { + return lightcraft_meta::extract(&head).orientation; + } + if head.get(..4) == Some(b"RIFF") && head.get(8..12) == Some(b"WEBP") { + return webp_orientation(&mut file); + } if let Some(o) = exif_orientation(&head) { return Some(o); } - let late = if (head.len() as u64) < ORIENTATION_SPAN { None } else { late_orientation(&mut file, &head) }; - late.or_else(|| lightcraft_meta::extract(&head).orientation) + late_orientation(&mut file, &head).or_else(|| lightcraft_meta::extract(&head).orientation) } -/// The orientation the Exif in `bytes` (a file, or the start of one) states, leaving out XMP. +/// The orientation the Exif in `bytes` (a file, or the start of one) states, leaving out a separate XMP packet (the +/// one the Exif holds in tag 700 counts, as in [`lightcraft_meta::read_exif`]). fn exif_orientation(bytes: &[u8]) -> Option { lightcraft_meta::embedded(bytes).exif.as_deref().map(lightcraft_meta::read_exif).and_then(|m| m.orientation) } -/// The orientation of a file whose `head` has no Exif stating it, found by the file's structure without reading its -/// image data (a JPEG's Exif can follow other long segments, WebP keeps its metadata chunks after the image data, and -/// many TIFF writers put the first IFD after the strips): Exif's, else the first XMP packet's. +/// The orientation of a JPEG or TIFF whose `head` has no Exif stating it, found by the file's structure without reading +/// its image data (a JPEG's Exif can follow other long segments, and many TIFF writers put the first IFD after the +/// strips). As the import does, a JPEG takes its first Exif segment, else its first XMP segment. fn late_orientation(file: &mut (impl Read + Seek), head: &[u8]) -> Option { + let len = file.seek(SeekFrom::End(0)).ok()?; file.rewind().ok()?; match head.get(..4)? { [0xff, 0xd8, ..] => { - let mut xmp = None; + let (mut exif_seen, mut xmp) = (false, None); let exif = read_jpeg_app1(file, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS, |segment| { - let exif = exif_orientation(segment); - if exif.is_none() && xmp.is_none() { - xmp = lightcraft_meta::extract(segment).orientation; + let embedded = lightcraft_meta::embedded(segment); + if let Some(exif) = embedded.exif + && !exif_seen + { + // the first Exif segment ends the walk if it states one; later ones don't count + exif_seen = true; + return lightcraft_meta::read_exif(&exif).orientation; } - exif + if xmp.is_none() { + xmp = embedded.xmp.map(|x| lightcraft_meta::parse_xmp(&x).ok().and_then(|x| x.metadata.orientation)); + } + None }); - exif.or(xmp) + exif.or(xmp.flatten()) } - b"RIFF" if head.get(8..12) == Some(b"WEBP") => webp_orientation(file), - b"II*\0" => tiff_orientation(file, head, true), - b"MM\0*" => tiff_orientation(file, head, false), + b"II*\0" | b"MM\0*" => tiff_orientation(file, 0, len), _ => None, } } -/// A WebP's orientation from its `EXIF` chunk, else its `XMP ` chunk, in whichever order they come, found by walking -/// the chunk headers from the start of `file` (at most [`WEBP_CHUNK_STEPS`]). Only those chunks are read, each if it is -/// at most [`ORIENTATION_SPAN`]. +/// A WebP's orientation as the import takes it: from its last `EXIF` chunk, else its last `XMP ` chunk, in whichever +/// order they come. The chunk headers are walked from the start of `file` (at most [`WEBP_CHUNK_STEPS`], ending at a +/// chunk that runs past the end of the file); then only the first IFD of the EXIF chunk is read, whatever its size +/// ([`tiff_orientation`]), and the XMP chunk if it is at most [`ORIENTATION_SPAN`]. fn webp_orientation(file: &mut (impl Read + Seek)) -> Option { - file.seek(SeekFrom::Start(12)).ok()?; - let mut xmp = None; + let len = file.seek(SeekFrom::End(0)).ok()?; + let (mut exif, mut xmp) = (None, None); + let mut at = 12u64; for _ in 0..WEBP_CHUNK_STEPS { let mut header = [0; 8]; - if file.read_exact(&mut header).is_err() { + if file.seek(SeekFrom::Start(at)).is_err() || file.read_exact(&mut header).is_err() { break; } let [a, b, c, d, s0, s1, s2, s3] = header; - let size = u32::from_le_bytes([s0, s1, s2, s3]); - // chunks are padded to an even size - let mut skip = i64::from(size) + i64::from(size & 1); - let exif = &[a, b, c, d] == b"EXIF"; - if (exif || (&[a, b, c, d] == b"XMP " && xmp.is_none())) && u64::from(size) <= ORIENTATION_SPAN { - let mut chunk = b"RIFF\0\0\0\0WEBP".to_vec(); - chunk.extend_from_slice(&header); - if (&mut *file).take(u64::from(size)).read_to_end(&mut chunk).is_err() { - break; - } - let found = lightcraft_meta::extract(&chunk).orientation; - if exif && found.is_some() { - return found; - } - xmp = xmp.or(found); - skip = i64::from(size & 1); + let size = u64::from(u32::from_le_bytes([s0, s1, s2, s3])); + let Some(end) = at.checked_add(8 + size).filter(|&end| end <= len) else { break }; + match &[a, b, c, d] { + b"EXIF" => exif = Some((at + 8, end)), + b"XMP " => xmp = Some((at + 8, size)), + _ => {} } - if file.seek(SeekFrom::Current(skip)).is_err() { - break; + // chunks are padded to an even size + at = end + (size & 1); + } + if let Some((start, end)) = exif { + // the TIFF stream, after an `Exif\0\0` if the chunk starts with one (as `strip_exif_header` takes it) + let mut prefix = [0; 5]; + file.seek(SeekFrom::Start(start)).ok()?; + let prefixed = start + 6 <= end && file.read_exact(&mut prefix).is_ok() && &prefix == b"Exif\0"; + if let Some(o) = tiff_orientation(file, if prefixed { start + 6 } else { start }, end) { + return Some(o); } } - xmp + let (start, size) = xmp?; + xmp_orientation(file, start, size) } /// How many chunks [`webp_orientation`] passes over (an animated WebP has one per frame). const WEBP_CHUNK_STEPS: usize = 4096; -/// A TIFF's orientation from the first IFD that `head` points to, of which only the 12-byte entries are read (at most -/// 65535 of them, under 1 MiB): its orientation tag, else (as [`lightcraft_meta::read_exif`] does) the XMP packet its -/// tag 700 holds, read if it is at most [`ORIENTATION_SPAN`]. `le`: little-endian (`II`). -fn tiff_orientation(file: &mut (impl Read + Seek), head: &[u8], le: bool) -> Option { +/// The orientation the TIFF stream from `start` to `end` in `file` states in its first IFD (a TIFF file, or the Exif +/// block of a WebP's EXIF chunk; its offsets count from `start`, and nothing past `end` is read). Only the IFD's 12-byte +/// entries are read (at most 65535 of them, under 1 MiB): its orientation tag, else (as [`lightcraft_meta::read_exif`] +/// does) the XMP packet its tag 700 holds, read if it is at most [`ORIENTATION_SPAN`]. +fn tiff_orientation(file: &mut (impl Read + Seek), start: u64, end: u64) -> Option { + // where the `len` bytes at `offset` in the stream are in the file, when all of them are in the stream + let within = |offset: u32, len: u64| { + let at = start.checked_add(u64::from(offset))?; + (at.checked_add(len)? <= end).then_some(at) + }; + file.seek(SeekFrom::Start(within(0, 8)?)).ok()?; + let mut header = [0; 8]; + file.read_exact(&mut header).ok()?; + let [b0, b1, b2, b3, i0, i1, i2, i3] = header; + let le = match &[b0, b1, b2, b3] { + b"II*\0" => true, + b"MM\0*" => false, + _ => return None, + }; let u16_of = |b: [u8; 2]| if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }; let u32_of = |b: [u8; 4]| if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }; - let ifd = u32_of(<[u8; 4]>::try_from(head.get(4..8)?).ok()?); - file.seek(SeekFrom::Start(u64::from(ifd))).ok()?; + let ifd = u32_of([i0, i1, i2, i3]); + file.seek(SeekFrom::Start(within(ifd, 2)?)).ok()?; let mut count = [0; 2]; file.read_exact(&mut count).ok()?; - let mut entries = vec![0; usize::from(u16_of(count)) * 12]; + let count = u16_of(count); + within(ifd, 2 + 12 * u64::from(count))?; + let mut entries = vec![0; usize::from(count) * 12]; file.read_exact(&mut entries).ok()?; let mut xmp = None; for &[t0, t1, y0, y1, c0, c1, c2, c3, v0, v1, v2, v3] in entries.as_chunks::<12>().0 { @@ -474,14 +505,22 @@ fn tiff_orientation(file: &mut (impl Read + Seek), head: &[u8], le: bool) -> Opt } } // BYTE or UNDEFINED, at an offset (a packet longer than the field's four bytes) - (700, 1 | 7) if count > 4 && u64::from(count) <= ORIENTATION_SPAN => xmp = Some((u32_of([v0, v1, v2, v3]), count)), + (700, 1 | 7) if count > 4 => xmp = Some((u32_of([v0, v1, v2, v3]), u64::from(count))), _ => {} } } let (offset, len) = xmp?; - file.seek(SeekFrom::Start(u64::from(offset))).ok()?; + xmp_orientation(file, within(offset, len)?, len) +} + +/// The orientation the XMP packet of `len` bytes at `at` in `file` states, read if it is at most [`ORIENTATION_SPAN`]. +fn xmp_orientation(file: &mut (impl Read + Seek), at: u64, len: u64) -> Option { + if len > ORIENTATION_SPAN { + return None; + } + file.seek(SeekFrom::Start(at)).ok()?; let mut packet = Vec::new(); - (&mut *file).take(u64::from(len)).read_to_end(&mut packet).ok()?; + (&mut *file).take(len).read_to_end(&mut packet).ok()?; lightcraft_meta::parse_xmp(&String::from_utf8_lossy(&packet)).ok()?.metadata.orientation } @@ -1095,8 +1134,8 @@ impl Session { mod tests { /// Issue #2674: a WebP keeps its EXIF and XMP chunks after the image data, a TIFF's first IFD can follow its strips /// and a JPEG's Exif other long segments, so the orientation can be past the first [`super::ORIENTATION_SPAN`] of - /// the file. Exif wins over XMP wherever each is, as when the import reads the whole file; a chunk over that span - /// isn't read, and a file that states none has none. + /// the file. Every file gives what the import gives reading it whole: Exif over XMP wherever each is, a WebP's last + /// EXIF chunk and a JPEG's first Exif segment, and none for a file that states none. #[test] fn the_file_orientation_is_found_after_the_image_data() { let dir = std::env::temp_dir().join(format!("lightcraft-file-orientation-{}", std::process::id())); @@ -1123,10 +1162,22 @@ mod tests { }; let image = |len: usize| (&b"VP8L"[..], vec![0; len]); let exif_chunk = (&b"EXIF"[..], [&b"Exif\0\0"[..], &exif].concat()); - // an EXIF chunk over the span that is read (orientation 6 too), and an XMP packet stating orientation 8 + // an EXIF chunk over the span (orientation 6 too), one stating no orientation, and an XMP packet stating 8 let huge_exif = (&b"EXIF"[..], [&b"Exif\0\0"[..], &exif, &vec![0; span]].concat()); + let plain = lightcraft_meta::write_exif(&lightcraft_meta::Metadata::default()); + let plain_chunk = (&b"EXIF"[..], [&b"Exif\0\0"[..], &plain].concat()); let packet = lightcraft_meta::write_xmp(&lightcraft_meta::Metadata { orientation: o8, ..Default::default() }, None); let xmp_chunk = (&b"XMP "[..], packet.clone().into_bytes()); + // the XMP packet padded with whitespace to `len` bytes + let padded_xmp = |len: usize| { + let mut p = packet.clone().into_bytes(); + p.resize(len, b' '); + (&b"XMP "[..], p) + }; + // an EXIF chunk holding only a TIFF header, whose IFD offset (16) points past the chunk's end into the next + // chunk's data, where an IFD stating orientation 6 sits + let stray_exif = (&b"EXIF"[..], b"II*\0\x10\0\0\0".to_vec()); + let stray_ifd = (&b"JUNK"[..], vec![1, 0, 0x12, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0]); // a TIFF whose first IFD follows more than the first MiB of image data: an orientation tag of `values` values // whose field starts with `value` (with more than two, it is an offset), a tag pointing elsewhere, and an XMP // packet (tag 700) stored after the IFD @@ -1175,6 +1226,7 @@ mod tests { j }; let exif_app1 = [&b"Exif\0\0"[..], &exif].concat(); + let plain_app1 = [&b"Exif\0\0"[..], &plain].concat(); let xmp_app1 = [&b"http://ns.adobe.com/xap/1.0/\0"[..], packet.as_bytes()].concat(); for (name, bytes, want) in [ ("small.webp", webp(&[image(64), exif_chunk.clone()]), o6), @@ -1182,9 +1234,18 @@ mod tests { // EXIF wins in whichever order the chunks come, and an XMP in the first MiB doesn't stop the search ("reversed.webp", webp(&[image(span + 64), xmp_chunk.clone(), exif_chunk.clone()]), o6), ("xmp-first.webp", webp(&[xmp_chunk.clone(), image(span + 64), exif_chunk.clone()]), o6), - ("none.webp", webp(&[image(span + 64), exif_chunk])[..span + 100].to_vec(), None), + ("none.webp", webp(&[image(span + 64), exif_chunk.clone()])[..span + 100].to_vec(), None), ("xmp.webp", webp(&[image(span + 64), xmp_chunk.clone()]), o8), - ("huge.webp", webp(&[image(span + 64), huge_exif, xmp_chunk]), o8), + // an EXIF chunk of any size is read by its IFD: one over the span, one (without `Exif\0\0`, big-endian) + // whose IFD is more than the span into it + ("huge.webp", webp(&[image(span + 64), huge_exif, xmp_chunk.clone()]), o6), + ("late-ifd.webp", webp(&[image(span + 64), (&b"EXIF"[..], tiff(false, Some((1, 6)), None)), xmp_chunk.clone()]), o6), + // nothing outside the EXIF chunk is read for its IFD + ("outside.webp", webp(&[image(span + 64), stray_exif, stray_ifd, xmp_chunk.clone()]), o8), + // the last EXIF chunk counts, here a late one stating no orientation after one in the first MiB + ("last-exif.webp", webp(&[exif_chunk, image(span + 64), plain_chunk, xmp_chunk]), o8), + // an XMP chunk of the span is read + ("span-xmp.webp", webp(&[image(64), padded_xmp(span)]), o8), ("le.tif", tiff(true, Some((1, 8)), None), o8), ("be.tif", tiff(false, Some((1, 8)), None), o8), ("offset.tif", tiff(true, Some((3, 8)), None), None), @@ -1195,11 +1256,19 @@ mod tests { ("none.jpg", jpeg(&[], &[]), None), ("xmp-first.jpg", jpeg(std::slice::from_ref(&xmp_app1), std::slice::from_ref(&exif_app1)), o6), ("xmp-only.jpg", jpeg(&[], std::slice::from_ref(&xmp_app1)), o8), + // the first Exif segment counts, though it states no orientation + ("two-exif.jpg", jpeg(&[plain_app1], &[exif_app1, xmp_app1]), o8), ] { + assert_eq!(lightcraft_meta::extract(&bytes).orientation, want, "import: {name}"); let path = dir.join(name); std::fs::write(&path, bytes).unwrap(); assert_eq!(super::file_orientation(&path.to_string_lossy()), want, "{name}"); } + // a larger XMP chunk isn't read, where the import (reading the whole file) takes its orientation + let over = webp(&[image(64), padded_xmp(span + 1)]); + assert_eq!(lightcraft_meta::extract(&over).orientation, o8); + std::fs::write(dir.join("over-xmp.webp"), over).unwrap(); + assert_eq!(super::file_orientation(&dir.join("over-xmp.webp").to_string_lossy()), None); assert_eq!(super::file_orientation(&dir.join("missing.webp").to_string_lossy()), None); std::fs::remove_dir_all(dir).unwrap(); } From 0b610c8307bc4c5045b31560f1124c0e40bb7aaa Mon Sep 17 00:00:00 2001 From: insideTheFlux Date: Sun, 25 Oct 2026 22:05:23 -0700 Subject: [PATCH 12/39] LR-PREF-DISPLAY: an unreadable Windows advanced-colour state leaves previews sRGB When the display configuration, the window's display path or its advanced-colour state can't be read, `monitor_color` answered with the monitor's profile as if Windows weren't colour-managing the desktop. If it was (HDR, Auto Color Management), previews were converted twice. It now answers `Unknown`, as the crate's other failures do, so previews stay sRGB (Windows 10 before 1709 and drivers that don't report the state included). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GfjNkJiMUagz3DN3zoV2rV --- crates/wincolor/src/lib.rs | 31 ++++++++++++++++++++++++++----- docs/display-profiles.md | 3 ++- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/crates/wincolor/src/lib.rs b/crates/wincolor/src/lib.rs index 1e7cec935a..8a1112ad0d 100644 --- a/crates/wincolor/src/lib.rs +++ b/crates/wincolor/src/lib.rs @@ -61,6 +61,19 @@ fn managed(flags: u32) -> bool { flags & 0b110 != 0 } +/// The answer Windows' own colour management settles, `None` when the monitor's profile decides: +/// [`MonitorColor::ManagedByWindows`] while it colour-manages the desktop, and +/// [`MonitorColor::Unknown`] when its state can't be read (`managed` is `None`), since applying the +/// monitor's profile on top of Windows' conversion would convert twice. +#[cfg(any(windows, test))] +fn settled_by_windows(managed: Option) -> Option { + match managed { + Some(true) => Some(MonitorColor::ManagedByWindows), + Some(false) => None, + None => Some(MonitorColor::Unknown), + } +} + /// The text of a NUL-terminated UTF-16 buffer (all of it without a NUL). #[cfg(any(windows, test))] fn until_nul(units: &[u16]) -> &[u16] { @@ -70,7 +83,7 @@ fn until_nul(units: &[u16]) -> &[u16] { #[cfg(windows)] #[allow(unsafe_code)] mod win32 { - use super::{MonitorColor, managed, until_nul}; + use super::{MonitorColor, managed, settled_by_windows, until_nul}; use std::ffi::OsString; use std::os::windows::ffi::OsStringExt; use std::path::PathBuf; @@ -100,11 +113,11 @@ mod win32 { pub fn monitor_color(hwnd: isize) -> MonitorColor { let Some(device) = monitor_device(hwnd) else { return MonitorColor::Unknown }; - if managed_by_windows(&device) == Some(true) { - return MonitorColor::ManagedByWindows; + // (an advanced-colour state that can't be read, as on Windows before 10 1709 or with a + // driver that doesn't say, is unknown: previews then stay sRGB, as before profiles were read) + if let Some(answer) = settled_by_windows(managed_by_windows(&device)) { + return answer; } - // (an unknown advanced-colour state, as on Windows before 10 1709 or with a driver that - // doesn't say, counts as not managed) match monitor_id(&device) { Some(id) => wcs_profile(&id), None => icm_profile(&device).map_or(MonitorColor::Unknown, MonitorColor::Profile), @@ -323,6 +336,14 @@ mod tests { assert!(!managed(0b1000)); } + #[test] + fn an_unreadable_advanced_colour_state_is_unknown_rather_than_a_profile() { + assert_eq!(settled_by_windows(Some(true)), Some(MonitorColor::ManagedByWindows)); + assert_eq!(settled_by_windows(Some(false)), None, "an SDR desktop: the monitor's profile decides"); + // Windows may be converting already: a profile on top would convert twice + assert_eq!(settled_by_windows(None), Some(MonitorColor::Unknown)); + } + #[test] fn utf16_text_stops_at_its_nul() { assert_eq!(until_nul(&[65, 66, 0, 67]), &[65, 66]); diff --git a/docs/display-profiles.md b/docs/display-profiles.md index 25735dee37..1a63ce7de5 100644 --- a/docs/display-profiles.md +++ b/docs/display-profiles.md @@ -26,7 +26,8 @@ a restart. (GDI's `GetICMProfileW` keeps answering the profile a process first s monitor's device can't be found.) With no profile assigned, previews are sRGB. **While Windows colour-manages the desktop itself** (HDR on, or Auto Color Management on Windows 11: its advanced-colour state, from `DisplayConfigGetDeviceInfo`), it treats an ordinary app's output as sRGB and converts it for the monitor, so previews -stay sRGB rather than be converted twice. The log says which applies (`screen profile: …`) whenever it changes. +stay sRGB rather than be converted twice. So do they when that state can't be read (Windows 10 before 1709, a driver +that doesn't report it). The log says which applies (`screen profile: …`) whenever it changes. ## Using it From 089f02e994f09111e29a74aee0adad162bf481a3 Mon Sep 17 00:00:00 2001 From: insideTheFlux Date: Wed, 28 Oct 2026 08:27:24 -0700 Subject: [PATCH 13/39] Tests: geocode's test module no longer imports names it doesn't use Main's explicit import list for this test module (#3111) names `dataset_dir` and `str_param`, which this PR's tests don't use, and clippy now fails on unused imports. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01CvoftLURuf4uBmSatewB6V --- crates/engine/src/cmd/geocode.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/geocode.rs b/crates/engine/src/cmd/geocode.rs index f5971a4aca..d811f80209 100644 --- a/crates/engine/src/cmd/geocode.rs +++ b/crates/engine/src/cmd/geocode.rs @@ -192,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; From 72a074b9bc844566999a790727f502056c7135d9 Mon Sep 17 00:00:00 2001 From: insideTheFlux Date: Fri, 30 Oct 2026 17:08:13 -0700 Subject: [PATCH 14/39] LR-LIB-PEOPLE: a size only the XMP states doesn't turn face boxes (#2674) extract turned regions by the shape of the size it had, and that could be the XMP's: tiff:ImageWidth and tiff:ImageLength fill it in when Exif states no size, and for a TIFF-based file from_tiff has already merged the file's own XMP. An XMP size of the upright photo then matched boxes drawn on the upright photo, so they were turned by mistake. Other paths don't get here (the image header decides for images, merge_into for a packet read as a sidecar). A raw with its own sidecar without mwg-rs:Regions does, because it keeps extract's boxes. from_tiff now keeps the size Exif states when it merges the XMP, and extract decides with that size; with none, boxes stay as written, as they do on main. extract still reports the XMP's size. Every raw decoder sets its own size after from_tiff, so none of them sees a difference. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CvoftN82NMM6Ebbf3YAK9e --- crates/engine/src/tests/xmp.rs | 48 ++++++++++++++++++++++++++++++++++ crates/meta/src/exif.rs | 3 +++ crates/meta/src/lib.rs | 38 +++++++++++++++++++++++++-- docs/xmp-interop.md | 4 ++- 4 files changed, 90 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index 3e88a9735e..969b14e241 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -553,6 +553,54 @@ fn regions_drawn_on_the_photo_as_stored_land_on_the_upright_photo() { let _ = std::fs::remove_dir_all(&src); } +/// A raw LightCraft can't decode: a TIFF whose first IFD holds Exif orientation 6, a 40 × 30 JPEG and `packet`. +fn turned_preview_only_raw(packet: &str) -> Vec { + let img = lightcraft_raster::Rgba8::from_fn(40, 30, |x, y| [(x * 6) as u8, (y * 8) as u8, 90, 255]); + let jpeg = lightcraft_codecs::encode_jpeg(&lightcraft_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &Default::default()).unwrap(); + let data = 8 + 2 + 4 * 12 + 4; + let (jpeg_len, packet_at) = (u32::try_from(jpeg.len()).unwrap(), u32::try_from(data + jpeg.len()).unwrap()); + let mut f = b"II*\0\x08\0\0\0\x04\0".to_vec(); + for (tag, kind, count, value) in [(274u16, 3u16, 1, 6), (513, 4, 1, data as u32), (514, 4, 1, jpeg_len), (700, 1, packet.len() as u32, packet_at)] + { + f.extend(tag.to_le_bytes()); + f.extend(kind.to_le_bytes()); + f.extend(u32::to_le_bytes(count)); + f.extend(u32::to_le_bytes(value)); + } + f.extend([0; 4]); + f.extend(jpeg); + f.extend(packet.as_bytes()); + f +} + +/// A sidecar with no `mwg-rs:Regions` leaves the boxes read from the file itself, and a raw's Exif may state no pixel +/// size. A size only its XMP states, of the upright photo, has the shape of boxes drawn on it upright: they stay put. +#[test] +fn a_size_only_a_raws_xmp_states_leaves_upright_regions_as_written() { + let src = temp_dir("regions-xmp-size"); + let file = src.join("p.iiq"); + let upright_size = r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:ImageWidth="24" tiff:ImageLength="32""#; + let packet = + STORED_FRAME_REGIONS.replace(r#"stDim:w="32" stDim:h="24""#, r#"stDim:w="24" stDim:h="32""#).replace(r#"rdf:about="""#, upright_size); + std::fs::write(&file, turned_preview_only_raw(&packet)).unwrap(); + std::fs::write( + src.join("p.xmp"), + r#" + "#, + ) + .unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); + let p = s.catalog.photo(only(&s)).unwrap(); + assert!(p.preview_only.is_some() && (p.width, p.height) == (30, 40), "{:?} {}x{}", p.preview_only, p.width, p.height); + assert_eq!(p.rating, 2, "the sidecar was read"); + assert_eq!(p.meta.regions.len(), 1); + let r = p.meta.regions[0].rect; + let got = [r.x0, r.y0, r.x1, r.y1]; + assert!(got.iter().zip([0.2, 0.325, 0.3, 0.475]).all(|(g, w)| (g - w).abs() < 1e-9), "{got:?}"); + let _ = std::fs::remove_dir_all(&src); +} + /// Removing a face box is a catalog-only, undoable edit: it never rewrites the sidecar (Lightroom's /// regions and everything else in it stay byte for byte), even with auto-write on. #[test] diff --git a/crates/meta/src/exif.rs b/crates/meta/src/exif.rs index adcba0f807..8cadd8ff24 100644 --- a/crates/meta/src/exif.rs +++ b/crates/meta/src/exif.rs @@ -129,8 +129,11 @@ pub fn from_tiff(tiff: &Tiff) -> Metadata { if let Some(x) = ifd0.and_then(|i| i.bytes(t::XMP)).map(String::from_utf8_lossy) && let Ok(x) = crate::parse_xmp(&x) { + // (the size stays the one Exif states: `extract` turns regions by it, and a size only the XMP states may be the upright one) + let size = (m.width, m.height); m.overlay_user_fields(&x.metadata); m.fill_missing(&x.metadata); + (m.width, m.height) = size; } m } diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index 20b73c2776..38d648a48f 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -316,6 +316,8 @@ pub fn try_extract(bytes: &[u8]) -> Result { } fn extract_embedded(e: Embedded, mut m: Metadata, xmp: Option) -> Metadata { + // the size the Exif states: a size only the XMP states may be the upright one, so it can't tell how the photo is stored + let stored = m.width.zip(m.height); if let Some(i) = e.iptc.as_deref() { m.fill_missing(&parse_iptc(i)); } @@ -323,8 +325,8 @@ fn extract_embedded(e: Embedded, mut m: Metadata, xmp: Option) -> Metad m.overlay_user_fields(&xmp.metadata); m.fill_missing(&xmp.metadata); // boxes another app drew on the photo as stored go where the upright photo has them (#2674) - if let (Some(drawn_on), Some(orientation), Some(w), Some(h)) = (xmp.regions_drawn_on(), m.orientation, m.width, m.height) { - upright_regions(&mut m.regions, drawn_on, orientation, (w, h)); + if let (Some(drawn_on), Some(orientation), Some(stored)) = (xmp.regions_drawn_on(), m.orientation, stored) { + upright_regions(&mut m.regions, drawn_on, orientation, stored); } } m @@ -566,4 +568,36 @@ mod tests { let lightroom = read(®ions_packet(6000, 4000, r#" mwg-rs:Rotation="-1.57080""#)); assert!(near(lightroom, TURNED_6), "Lightroom's −π/2: {lightroom:?}"); } + + /// A size only the XMP states can't tell how the photo is stored: `tiff:ImageWidth` and `tiff:ImageLength` of the + /// upright photo have the shape of boxes drawn on it upright, and those must not be turned. + #[test] + fn a_size_only_the_xmp_states_turns_no_regions() { + // orientation 6, no pixel size + let exif = write_exif(&Metadata { orientation: Some(Orientation::Rotate90), ..Default::default() }); + let exif = strip_exif_header(&exif); + let packet = regions_packet(4000, 6000, "") + .replace(r#"rdf:about="""#, r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:ImageWidth="4000" tiff:ImageLength="6000""#); + let mut j = vec![0xff, 0xd8]; + let mut seg = |payload: Vec| { + j.extend([0xff, 0xe1]); + j.extend(u16::try_from(payload.len() + 2).unwrap().to_be_bytes()); + j.extend(payload); + }; + seg([b"Exif\0\0".as_slice(), exif].concat()); + seg([b"http://ns.adobe.com/xap/1.0/\0".as_slice(), packet.as_bytes()].concat()); + j.extend([0xff, 0xd9]); + let m = extract(&j); + assert_eq!((m.orientation, m.width, m.height), (Some(Orientation::Rotate90), Some(4000), Some(6000))); + assert_eq!(m.regions.len(), 1); + assert!(near(m.regions[0].rect, DRAWN), "{:?}", m.regions[0].rect); + assert_eq!(try_extract(&j).unwrap().regions, m.regions); + // a TIFF-based file: the whole file is the Exif block, with the XMP in its first IFD + let mut ifd0 = lightcraft_tiff::IfdBuilder::new(); + ifd0.set(lightcraft_tiff::tags::ORIENTATION, lightcraft_tiff::Value::Short(vec![6])); + ifd0.set(lightcraft_tiff::tags::XMP, lightcraft_tiff::Value::Byte(packet.into_bytes())); + let m = extract(&lightcraft_tiff::TiffWriter::default().write(&[ifd0]).unwrap()); + assert_eq!((m.orientation, m.width, m.height), (Some(Orientation::Rotate90), Some(4000), Some(6000))); + assert!(near(m.regions[0].rect, DRAWN), "TIFF: {:?}", m.regions[0].rect); + } } diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index a0b0e2aed3..bd920e6ff2 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -124,7 +124,9 @@ write them, from sidecars and from XMP embedded in the file. Named faces become 5–8 turns a quarter turn, and no `mwg-rs:Rotation`), the boxes are turned with the file's own Exif orientation, mirror included, when imported and when read again (#2674). The image's own pixel size decides, not a size the metadata states, and the orientation is found wherever the file keeps its Exif (WebP after the image data, for - one). A square photo or size looks the same both ways and is taken as written. Boxes follow LightCraft's own Rotate Left/Right and flips. + one). The exception is a raw with a sidecar that has no `mwg-rs:Regions`: its boxes come from the file and the size + its Exif states decides, and with no such size they are taken as written. A square photo or size looks the same both + ways and is taken as written. Boxes follow LightCraft's own Rotate Left/Right and flips. - **Re-reading**: a sidecar that has `mwg-rs:Regions` — even with an empty list — replaces the photo's regions, so regions removed in another application go away here too. A sidecar without `mwg-rs:Regions` (an application that doesn't do regions) leaves the photo's regions as they are. From a763c3c180241ab85b6e706cff610e22da9da4ca Mon Sep 17 00:00:00 2001 From: insideTheFlux Date: Fri, 30 Oct 2026 21:59:54 -0700 Subject: [PATCH 15/39] LR-LIB-PEOPLE: a re-read finds a PNG's or PSD's orientation past the first MiB (#2674) Read Metadata from File and Synchronize Folder look for the file's orientation in its first MiB and then by its structure, but only JPEG, TIFF and WebP had one to walk. A PNG with its eXIf past the first MiB, or a PSD whose image resources outgrow it, gave no orientation though the import finds one, so boxes drawn on the stored photo stayed sideways when the sidecar stated none. A PNG's chunk headers are now walked as a WebP's are, and a PSD is read up to the end of its image resources, at most 16 MiB. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CvoftM8ZqGRb62UWw9DAKP --- crates/engine/src/sidecar.rs | 256 +++++++++++++++++++++++++++++++++-- 1 file changed, 241 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 271ab76777..a656383c69 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -371,7 +371,8 @@ impl SidecarData { /// The orientation the photo file at `path` states, as [`lightcraft_meta::extract`] reads it from the whole file (the /// import's): Exif's, else XMP's. A file shorter than [`ORIENTATION_SPAN`] is read whole. Most others state it in the /// Exif of their first [`ORIENTATION_SPAN`]; when that part doesn't, the Exif may come later ([`late_orientation`]). -/// A WebP's chunks are always walked, since its last EXIF chunk is the one that counts ([`webp_orientation`]). +/// A WebP's or PNG's chunks are always walked, since the last Exif chunk is the one that counts ([`webp_orientation`], +/// [`png_orientation`]). fn file_orientation(path: &str) -> Option { let mut file = std::fs::File::open(path).ok()?; let mut head = Vec::new(); @@ -382,6 +383,9 @@ fn file_orientation(path: &str) -> Option { if head.get(..4) == Some(b"RIFF") && head.get(8..12) == Some(b"WEBP") { return webp_orientation(&mut file); } + if head.starts_with(b"\x89PNG\r\n\x1a\n") { + return png_orientation(&mut file); + } if let Some(o) = exif_orientation(&head) { return Some(o); } @@ -394,9 +398,10 @@ fn exif_orientation(bytes: &[u8]) -> Option { lightcraft_meta::embedded(bytes).exif.as_deref().map(lightcraft_meta::read_exif).and_then(|m| m.orientation) } -/// The orientation of a JPEG or TIFF whose `head` has no Exif stating it, found by the file's structure without reading -/// its image data (a JPEG's Exif can follow other long segments, and many TIFF writers put the first IFD after the -/// strips). As the import does, a JPEG takes its first Exif segment, else its first XMP segment. +/// The orientation of a JPEG, TIFF or PSD whose `head` has no Exif stating it, found by the file's structure without +/// reading its image data (a JPEG's Exif can follow other long segments, many TIFF writers put the first IFD after the +/// strips, and a PSD's image resources can outgrow `head`). As the import does, a JPEG takes its first Exif segment, +/// else its first XMP segment. fn late_orientation(file: &mut (impl Read + Seek), head: &[u8]) -> Option { let len = file.seek(SeekFrom::End(0)).ok()?; file.rewind().ok()?; @@ -420,6 +425,7 @@ fn late_orientation(file: &mut (impl Read + Seek), head: &[u8]) -> Option tiff_orientation(file, 0, len), + b"8BPS" => psd_orientation(file), _ => None, } } @@ -448,14 +454,8 @@ fn webp_orientation(file: &mut (impl Read + Seek)) -> Option Option Option { + let mut prefix = [0; 5]; + file.seek(SeekFrom::Start(start)).ok()?; + let prefixed = start + 6 <= end && file.read_exact(&mut prefix).is_ok() && &prefix == b"Exif\0"; + tiff_orientation(file, if prefixed { start + 6 } else { start }, end) +} + +/// A PNG's orientation as the import takes it: from its last `eXIf` chunk, else its last uncompressed XMP `iTXt` chunk, +/// wherever they come (a writer may put them after the image data). The chunk headers are walked from the start of +/// `file` to `IEND` (at most [`png_chunk_steps`], ending at a chunk that runs past the end of the file); then only the +/// first IFD of the `eXIf` chunk is read, whatever its size ([`tiff_orientation`]), and the `iTXt` chunk if it is at +/// most [`ORIENTATION_SPAN`]. +fn png_orientation(file: &mut (impl Read + Seek)) -> Option { + let len = file.seek(SeekFrom::End(0)).ok()?; + let (mut exif, mut xmp) = (None, None); + let mut at = 8u64; + for _ in 0..png_chunk_steps(len) { + let (mut header, mut key) = ([0; 8], [0; 19]); + if at + 12 > len || file.seek(SeekFrom::Start(at)).is_err() || file.read_exact(&mut header).is_err() { + break; + } + let [s0, s1, s2, s3, a, b, c, d] = header; + let size = u64::from(u32::from_be_bytes([s0, s1, s2, s3])); + let Some(end) = at.checked_add(8 + size).filter(|&end| end <= len) else { break }; + match &[a, b, c, d] { + b"eXIf" => exif = Some((at + 8, end)), + // the keyword, then compression flag 0 + b"iTXt" if size >= 20 && file.read_exact(&mut key).is_ok() && &key == b"XML:com.adobe.xmp\0\0" => xmp = Some((at + 8, size)), + b"IEND" => break, + _ => {} + } + // past the chunk's CRC + at = end + 4; + } + if let Some(o) = exif.and_then(|(start, end)| exif_chunk_orientation(file, start, end)) { + return Some(o); + } + let (start, size) = xmp?; + let chunk = read_within_span(file, start, size)?; + // keyword\0 compression-flag compression-method language\0 translated\0 text + let text = chunk.get(20..)?.splitn(3, |&c| c == 0).nth(2)?; + lightcraft_meta::parse_xmp(&String::from_utf8_lossy(text)).ok()?.metadata.orientation +} + +/// How many chunks [`png_orientation`] passes over in a file of `len` bytes: 4096 and one per KiB of the file, at most +/// 2^20. Image data is often split into many `IDAT` chunks (libpng writes 8 KiB ones by default), so the limit grows +/// with the file; each chunk costs two system calls, so a short file of empty chunks can't hold a worker for seconds. +fn png_chunk_steps(len: u64) -> u64 { + (4096 + len / 1024).min(1 << 20) +} + +/// A PSD's or PSB's orientation as the import takes it, from its image resources: the file's start up to their end is +/// read if it is at most [`PSD_RESOURCES_SPAN`]. They come before the layers and the image data, after the 26-byte +/// header and the colour-mode data; each of those two sections starts with its length. +fn psd_orientation(file: &mut (impl Read + Seek)) -> Option { + let mut length = [0; 4]; + file.seek(SeekFrom::Start(26)).ok()?; + file.read_exact(&mut length).ok()?; + let resources = 30 + u64::from(u32::from_be_bytes(length)); + file.seek(SeekFrom::Start(resources)).ok()?; + file.read_exact(&mut length).ok()?; + let end = resources + 4 + u64::from(u32::from_be_bytes(length)); + if end > PSD_RESOURCES_SPAN { + return None; + } + file.rewind().ok()?; + let mut bytes = Vec::new(); + (&mut *file).take(end).read_to_end(&mut bytes).ok()?; + lightcraft_meta::extract(&bytes).orientation +} + +/// How far into a PSD or PSB [`psd_orientation`] reads. +const PSD_RESOURCES_SPAN: u64 = 16 * 1024 * 1024; + /// The orientation the TIFF stream from `start` to `end` in `file` states in its first IFD (a TIFF file, or the Exif /// block of a WebP's EXIF chunk; its offsets count from `start`, and nothing past `end` is read). Only the IFD's 12-byte /// entries are read (at most 65535 of them, under 1 MiB): its orientation tag, else (as [`lightcraft_meta::read_exif`] @@ -515,13 +591,19 @@ fn tiff_orientation(file: &mut (impl Read + Seek), start: u64, end: u64) -> Opti /// The orientation the XMP packet of `len` bytes at `at` in `file` states, read if it is at most [`ORIENTATION_SPAN`]. fn xmp_orientation(file: &mut (impl Read + Seek), at: u64, len: u64) -> Option { + let packet = read_within_span(file, at, len)?; + lightcraft_meta::parse_xmp(&String::from_utf8_lossy(&packet)).ok()?.metadata.orientation +} + +/// The `len` bytes at `at` in `file`, read if they are at most [`ORIENTATION_SPAN`]. +fn read_within_span(file: &mut (impl Read + Seek), at: u64, len: u64) -> Option> { if len > ORIENTATION_SPAN { return None; } file.seek(SeekFrom::Start(at)).ok()?; - let mut packet = Vec::new(); - (&mut *file).take(len).read_to_end(&mut packet).ok()?; - lightcraft_meta::parse_xmp(&String::from_utf8_lossy(&packet)).ok()?.metadata.orientation + let mut bytes = Vec::new(); + (&mut *file).take(len).read_to_end(&mut bytes).ok()?; + Some(bytes) } /// How much of a photo file [`file_orientation`] reads first. @@ -1273,6 +1355,150 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + /// Issue #2674: the same for a PNG, whose `eXIf` and XMP `iTXt` chunks can follow the image data, and a PSD, whose + /// image resources can outgrow the first [`super::ORIENTATION_SPAN`]. + #[test] + fn a_png_or_psd_gives_the_orientation_the_import_gives() { + let dir = std::env::temp_dir().join(format!("lightcraft-png-psd-orientation-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let span = super::ORIENTATION_SPAN as usize; + let (o6, o8) = (Some(lightcraft_meta::Orientation::Rotate90), Some(lightcraft_meta::Orientation::Rotate270)); + let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { orientation: o6, ..Default::default() }); + let plain = lightcraft_meta::write_exif(&lightcraft_meta::Metadata::default()); + let packet = lightcraft_meta::write_xmp(&lightcraft_meta::Metadata { orientation: o8, ..Default::default() }, None); + // a PNG: its IHDR, then `chunks`, each with a CRC (nothing checks it) + let png = |chunks: &[(&[u8], Vec)]| { + let mut p = b"\x89PNG\r\n\x1a\n".to_vec(); + for (id, data) in [(&b"IHDR"[..], vec![0; 13])].iter().chain(chunks) { + p.extend_from_slice(&(data.len() as u32).to_be_bytes()); + p.extend_from_slice(id); + p.extend_from_slice(data); + p.extend_from_slice(&[0; 4]); + } + p + }; + let idat = |len: usize| (&b"IDAT"[..], vec![0; len]); + let iend = (&b"IEND"[..], Vec::new()); + let exif_chunk = (&b"eXIf"[..], exif.clone()); + let plain_chunk = (&b"eXIf"[..], plain.clone()); + // an `iTXt` chunk: the keyword, compression flag `flag`, method, no language, no translated keyword, the text + let itxt = |keyword: &[u8], flag: u8, text: &[u8]| (&b"iTXt"[..], [keyword, &[0, flag, 0, 0, 0], text].concat()); + let xmp_key = &b"XML:com.adobe.xmp"[..]; + let xmp_chunk = itxt(xmp_key, 0, packet.as_bytes()); + // the XMP packet padded with whitespace, in a chunk of `len` bytes + let padded_xmp = |len: usize| { + let mut p = packet.clone().into_bytes(); + p.resize(len - 22, b' '); + itxt(xmp_key, 0, &p) + }; + // a big-endian TIFF stream whose IFD, stating orientation 6, is more than the span into it + let ifd = [0u8, 1, 1, 0x12, 0, 3, 0, 0, 0, 1, 0, 6, 0, 0, 0, 0, 0, 0]; + let late_ifd = [&b"MM\0*"[..], &(8 + span as u32).to_be_bytes(), &vec![0; span], &ifd].concat(); + // an `eXIf` holding only a TIFF header, whose IFD offset (20) points past the chunk's end into the next chunk's + // data, where an IFD stating orientation 6 sits + let stray_exif = (&b"eXIf"[..], b"II*\0\x14\0\0\0".to_vec()); + let stray_ifd = (&b"juNK"[..], vec![1, 0, 0x12, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0]); + // a PSD: its header, `colour` bytes of colour-mode data, the image resources (id, data), `pixels` other bytes + let psd = |colour: usize, resources: &[(u16, &[u8])], pixels: usize| { + let mut section = Vec::new(); + for (id, data) in resources { + section.extend_from_slice(b"8BIM"); + section.extend_from_slice(&id.to_be_bytes()); + section.extend_from_slice(&[0, 0]); + section.extend_from_slice(&(data.len() as u32).to_be_bytes()); + section.extend_from_slice(data); + if data.len() % 2 == 1 { + section.push(0); + } + } + let mut p = b"8BPS\0\x01".to_vec(); + p.resize(26, 0); + p.extend_from_slice(&(colour as u32).to_be_bytes()); + p.resize(p.len() + colour, 0); + p.extend_from_slice(&(section.len() as u32).to_be_bytes()); + p.extend_from_slice(§ion); + p.resize(p.len() + pixels, 0); + p + }; + let long = vec![0; span + 64]; + let (exif_res, plain_res, xmp_res, long_res) = ((1058, &exif[..]), (1058, &plain[..]), (1060, packet.as_bytes()), (1039, &long[..])); + let late_png = png(&[idat(span + 64), exif_chunk.clone()]); + let late_psd = psd(0, &[long_res, exif_res], 0); + for (name, bytes, want) in [ + ("early.png", png(&[exif_chunk.clone(), idat(span + 64), iend.clone()]), o6), + ("late.png", png(&[idat(span + 64), exif_chunk.clone(), xmp_chunk.clone(), iend.clone()]), o6), + // the `eXIf` wins in whichever order the chunks come, and an XMP in the first MiB doesn't stop the search + ("reversed.png", png(&[idat(span + 64), xmp_chunk.clone(), exif_chunk.clone(), iend.clone()]), o6), + ("xmp-first.png", png(&[xmp_chunk.clone(), idat(span + 64), exif_chunk.clone(), iend.clone()]), o6), + ("xmp.png", png(&[idat(span + 64), xmp_chunk.clone(), iend.clone()]), o8), + ("none.png", png(&[idat(span + 64), iend.clone()]), None), + // the `eXIf` is cut short, or comes after the end of the image + ("cut.png", late_png[..late_png.len() - 6].to_vec(), None), + ("after-iend.png", png(&[idat(span + 64), iend.clone(), exif_chunk.clone()]), None), + // an `eXIf` of any size is read by its IFD: with `Exif\0\0`, over the span, and with its IFD past the span + ("prefixed.png", png(&[idat(span + 64), (&b"eXIf"[..], [&b"Exif\0\0"[..], &exif].concat())]), o6), + ("huge.png", png(&[idat(64), (&b"eXIf"[..], [&exif[..], &vec![0; span]].concat()), xmp_chunk.clone()]), o6), + ("late-ifd.png", png(&[idat(span + 64), (&b"eXIf"[..], late_ifd), xmp_chunk.clone()]), o6), + // nothing outside the `eXIf` is read for its IFD + ("outside.png", png(&[idat(span + 64), stray_exif, stray_ifd, xmp_chunk.clone()]), o8), + // the last `eXIf` counts, here a late one stating no orientation after one in the first MiB + ("last-exif.png", png(&[exif_chunk.clone(), idat(span + 64), plain_chunk, xmp_chunk.clone()]), o8), + // a compressed packet or another keyword isn't the XMP; a chunk of the span is read + ("compressed.png", png(&[idat(span + 64), xmp_chunk.clone(), itxt(xmp_key, 1, packet.as_bytes())]), o8), + ("only-compressed.png", png(&[idat(span + 64), itxt(xmp_key, 1, packet.as_bytes())]), None), + ("other-text.png", png(&[idat(span + 64), itxt(b"Comment", 0, packet.as_bytes())]), None), + ("short-text.png", png(&[idat(span + 64), xmp_chunk.clone(), (&b"iTXt"[..], b"XML:com.adobe.xmp\0\0".to_vec())]), o8), + ("span-xmp.png", png(&[idat(64), padded_xmp(span)]), o8), + ("late.psd", late_psd.clone(), o6), + ("early.psd", psd(0, &[exif_res], span + 64), o6), + // Exif wins in whichever order the resources come; XMP fills in for none, or none stating an orientation + ("both.psd", psd(0, &[xmp_res, long_res, exif_res], 0), o6), + ("xmp.psd", psd(768, &[long_res, xmp_res], 0), o8), + ("plain.psd", psd(0, &[long_res, plain_res, xmp_res], 0), o8), + ("none.psd", psd(0, &[long_res], span), None), + // as at import, nothing is taken from resources that are cut short or state their Exif twice + ("cut.psd", late_psd[..late_psd.len() - 1].to_vec(), None), + ("two-exif.psd", psd(0, &[long_res, exif_res, exif_res], 0), None), + ] { + assert_eq!(lightcraft_meta::extract(&bytes).orientation, want, "import: {name}"); + let path = dir.join(name); + std::fs::write(&path, bytes).unwrap(); + assert_eq!(super::file_orientation(&path.to_string_lossy()), want, "{name}"); + } + // a larger XMP chunk isn't read, where the import (reading the whole file) takes its orientation + let over = png(&[idat(64), padded_xmp(span + 1)]); + assert_eq!(lightcraft_meta::extract(&over).orientation, o8); + std::fs::write(dir.join("over-xmp.png"), over).unwrap(); + assert_eq!(super::file_orientation(&dir.join("over-xmp.png").to_string_lossy()), None); + std::fs::remove_dir_all(dir).unwrap(); + + // the `eXIf` as the last chunk walked, and as the first one not: IHDR, `chunks` of empty `IDAT`, the `eXIf` + let steps = super::png_chunk_steps; + let split = |chunks: usize| png(&[vec![idat(0); chunks], vec![exif_chunk.clone()]].concat()); + let len = |chunks: usize| (8 + 25 + 12 * chunks + 12 + exif.len()) as u64; + let walked = (0..).find(|&n| n as u64 + 2 == steps(len(n)) && n as u64 + 3 > steps(len(n + 1))).unwrap(); + let (last, past) = (split(walked), split(walked + 1)); + assert_eq!(last.len() as u64, len(walked)); + assert_eq!(super::png_orientation(&mut std::io::Cursor::new(&last)), o6); + assert_eq!(lightcraft_meta::extract(&past).orientation, o6); + assert_eq!(super::png_orientation(&mut std::io::Cursor::new(&past)), None); + // image data split into chunks of a KiB is walked whatever its length, up to the limit + let kib_chunks = png(&[vec![idat(1012); 6000], vec![exif_chunk.clone()]].concat()); + assert_eq!(super::png_orientation(&mut std::io::Cursor::new(&kib_chunks)), o6); + assert_eq!(steps(u64::MAX), 1 << 20); + + // image resources that end exactly at the limit, and a byte past it + let limit = super::PSD_RESOURCES_SPAN as usize; + let padding = vec![0; limit - 58 - exif.len().next_multiple_of(2)]; + let within = psd(0, &[(1039, &padding[..]), exif_res], 0); + assert_eq!(within.len(), limit); + assert_eq!(super::psd_orientation(&mut std::io::Cursor::new(&within)), o6); + let past = psd(1, &[(1039, &padding[..]), exif_res], 0); + assert_eq!(lightcraft_meta::extract(&past).orientation, o6); + assert_eq!(super::psd_orientation(&mut std::io::Cursor::new(&past)), None); + } + #[test] fn sidecars_are_written_only_beside_an_existing_original() { let dir = std::env::temp_dir().join(format!("lightcraft-sidecar-local-{}", std::process::id())); From 59b7247ea71b3473913bff09e2bf297cdf0fc6ec Mon Sep 17 00:00:00 2001 From: insideTheFlux Date: Mon, 2 Nov 2026 18:27:36 -0800 Subject: [PATCH 16/39] LR-BEHAV-TITLEBAR: the Windows title bar takes LightCraft's theme at launch (#3381) When LightCraft's appearance differs from Windows' (its dark default on a light Windows), the first theme egui sends the just-shown, focused window changed the title's colour but not the caption's: white on a light caption, which looks blank, until focus moved. The same command sent once the window is up repaints the caption, so the UI phase sends it again the first frame the window has focus (Windows only). With a test, which fails without the send, and a What's New entry. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CvoftKWm1wYSXdzRBwvFR3 --- crates/ui-egui/src/app/frame.rs | 1 + crates/ui-egui/src/theme.rs | 41 +++++++++++++++++++++++++++++++++ docs/whats-new.md | 7 ++++++ 3 files changed, 49 insertions(+) diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index a434881ae5..a757af1aef 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -263,6 +263,7 @@ impl LightcraftApp { self.import_dropped_files(ctx); } self.check_external_editor(ctx); + theme::refresh_window_on_first_focus(ctx); // Alt (Option on macOS) while a slider is dragged shows its temporary preview self.ui.alt_held = ctx.input(|i| i.modifiers.alt); // Recent-library checks and launch-list keys read focus/time/keys: they belong to the UI diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 0c562f451f..9f1873521b 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -412,6 +412,25 @@ pub fn current(ctx: &egui::Context) -> Option { ctx.data(|d| d.get_temp::(theme_id())) } +/// Windows only: tell the window its theme again, the first time it has focus. A first theme that +/// reaches a focused window as it comes up changes the title's colour but not the caption's, so +/// with LightCraft dark on a light system the title is white on a light caption (it looks blank), +/// and light on dark is dark on dark, until focus next moves (#3381). The same command repaints +/// the caption once the window is up. A window that opens without focus shows the right colours +/// from the start. +pub fn refresh_window_on_first_focus(ctx: &egui::Context) { + let done = egui::Id::unique("lightcraft-window-theme-refreshed"); + if !cfg!(target_os = "windows") || !ctx.input(|i| i.focused) || ctx.data(|d| d.get_temp::(done)).is_some() { + return; + } + ctx.data_mut(|d| d.insert_temp(done, true)); + let theme = match ctx.theme() { + egui::Theme::Dark => egui::SystemTheme::Dark, + egui::Theme::Light => egui::SystemTheme::Light, + }; + ctx.send_viewport_cmd(egui::ViewportCommand::SetTheme(theme)); +} + /// Style `ctx` with the default theme. pub fn apply(ctx: &egui::Context) { apply_kind(ctx, ThemeKind::default()); @@ -506,6 +525,28 @@ mod tests { } } + /// #3381: egui sends the theme with the first frame, and the window hears it once more the + /// first time it has focus, not on every later focus. + #[cfg(target_os = "windows")] + #[test] + fn the_window_hears_its_theme_again_the_first_time_it_has_focus() { + let ctx = egui::Context::default(); + apply_kind(&ctx, ThemeKind::Silver); + let sent = |focused: bool| { + let raw = egui::RawInput { focused, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| refresh_window_on_first_focus(ui.ctx())); + out.textures_delta.clear(); + let commands = out.viewport_output.remove(&egui::ViewportId::ROOT).map(|v| v.commands).unwrap_or_default(); + commands.iter().filter(|c| matches!(c, egui::ViewportCommand::SetTheme(egui::SystemTheme::Light))).count() + }; + assert_eq!(sent(false), 1, "egui's own, with the first frame"); + assert_eq!(sent(false), 0, "no focus yet"); + assert_eq!(sent(true), 1, "the first frame with focus"); + assert_eq!(sent(true), 0, "still focused"); + assert_eq!(sent(false), 0, "focus lost"); + assert_eq!(sent(true), 0, "focus back: Windows repaints this by itself"); + } + /// Every theme scrolls 100 points a wheel notch, and a zoom notch stays egui's stock ~1.22x /// (`exp(40 / 200)`) instead of growing with the longer scroll. #[test] diff --git a/docs/whats-new.md b/docs/whats-new.md index 98a0ac7157..5289b03b66 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,12 @@ # What's new in LightCraft +## 2026-11-02 + +### The Windows title bar is readable from the moment the window opens +- When LightCraft's appearance differs from the one set in Windows (the dark default on a light Windows, for one), the + title bar kept the system's colour with the title in LightCraft's, so the title looked blank until focus moved to + another window. It now takes LightCraft's colours as soon as the window has focus. + ## 2026-10-30 ### The Flatpak may talk to the accessibility bus From bd2f8e9670970b3f54393829b0f5af6a1fe3f49f Mon Sep 17 00:00:00 2001 From: insideTheFlux Date: Mon, 2 Nov 2026 18:58:42 -0800 Subject: [PATCH 17/39] LR-BEHAV-TITLEBAR: test a window that has focus from its first frame (#3381) A fresh context whose first frame is focused sends the theme once more than egui's own command in that frame, compared with the same frame without the refresh rather than with a fixed count (CodeRabbit). Both tests share a helper that counts the frame's SetTheme(Light) commands. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CvoftKWm1wYSXdzRBwvFR3 --- crates/ui-egui/src/theme.rs | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 9f1873521b..de2be96a6c 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -525,6 +525,21 @@ mod tests { } } + /// The `SetTheme(Light)` commands one frame of `ctx` sends the window, with or without + /// [`refresh_window_on_first_focus`] in it. + #[cfg(target_os = "windows")] + fn light_theme_commands(ctx: &egui::Context, focused: bool, refresh: bool) -> usize { + let raw = egui::RawInput { focused, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if refresh { + refresh_window_on_first_focus(ui.ctx()); + } + }); + out.textures_delta.clear(); + let commands = out.viewport_output.remove(&egui::ViewportId::ROOT).map(|v| v.commands).unwrap_or_default(); + commands.iter().filter(|c| matches!(c, egui::ViewportCommand::SetTheme(egui::SystemTheme::Light))).count() + } + /// #3381: egui sends the theme with the first frame, and the window hears it once more the /// first time it has focus, not on every later focus. #[cfg(target_os = "windows")] @@ -532,13 +547,7 @@ mod tests { fn the_window_hears_its_theme_again_the_first_time_it_has_focus() { let ctx = egui::Context::default(); apply_kind(&ctx, ThemeKind::Silver); - let sent = |focused: bool| { - let raw = egui::RawInput { focused, ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| refresh_window_on_first_focus(ui.ctx())); - out.textures_delta.clear(); - let commands = out.viewport_output.remove(&egui::ViewportId::ROOT).map(|v| v.commands).unwrap_or_default(); - commands.iter().filter(|c| matches!(c, egui::ViewportCommand::SetTheme(egui::SystemTheme::Light))).count() - }; + let sent = |focused: bool| light_theme_commands(&ctx, focused, true); assert_eq!(sent(false), 1, "egui's own, with the first frame"); assert_eq!(sent(false), 0, "no focus yet"); assert_eq!(sent(true), 1, "the first frame with focus"); @@ -547,6 +556,20 @@ mod tests { assert_eq!(sent(true), 0, "focus back: Windows repaints this by itself"); } + /// #3381: a window that has focus from its very first frame hears the theme once more in that + /// frame, on top of egui's own command. (In the app the first frame never gets here: `ui` + /// returns before the fonts are ready, so egui's command always goes a frame earlier.) + #[cfg(target_os = "windows")] + #[test] + fn a_window_focused_from_its_first_frame_hears_its_theme_again_in_that_frame() { + let first_frame = |refresh: bool| { + let ctx = egui::Context::default(); + apply_kind(&ctx, ThemeKind::Silver); + light_theme_commands(&ctx, true, refresh) + }; + assert_eq!(first_frame(true), first_frame(false) + 1); + } + /// Every theme scrolls 100 points a wheel notch, and a zoom notch stays egui's stock ~1.22x /// (`exp(40 / 200)`) instead of growing with the longer scroll. #[test] From d94479f8d4ee1e1fcaceb8db47079d8311947b70 Mon Sep 17 00:00:00 2001 From: insideTheFlux Date: Mon, 2 Nov 2026 21:32:24 -0800 Subject: [PATCH 18/39] LR-PREF-DISPLAY: wincolor inherits the workspace lints `[lints] workspace = true` in place of its own tables, as CLAUDE.md asks of every new crate (CodeRabbit): it now also gets the workspace's cognitive_complexity, too_many_arguments and wildcard_imports denies. The workspace's unsafe_code is deny, not forbid, so the win32 module's #[allow(unsafe_code)] still applies, and an unsafe block anywhere else in the crate fails to compile. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CvoftKWm1wYSXdzRBwvFR3 --- crates/wincolor/Cargo.toml | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/crates/wincolor/Cargo.toml b/crates/wincolor/Cargo.toml index d7b1c6e8df..8cf4739a11 100644 --- a/crates/wincolor/Cargo.toml +++ b/crates/wincolor/Cargo.toml @@ -5,15 +5,11 @@ edition.workspace = true license.workspace = true description = "LightCraft wincolor (L0): the colour profile Windows assigns to the monitor showing a window. One of the two crates allowed `unsafe` (Win32 calls)." -# Opts out of the workspace lints only to keep `unsafe_code = "deny"` overridable for the Win32 -# module below, as `crates/sysmem` does; every other crate root has `#![forbid(unsafe_code)]`. See +# The workspace lints: they deny `unsafe_code` (deny, not forbid), which the `win32` module in +# src/lib.rs allows for its Win32 calls; every other crate root has `#![forbid(unsafe_code)]`. See # AGENTS.md and craftrules standards/never-crash.md ("isolated helper library crate"). -[lints.rust] -unsafe_code = "deny" - -[lints.clippy] -dbg_macro = "warn" -todo = "warn" +[lints] +workspace = true [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61", features = [ From b99bd447851df21f10a394bd61af7809aa5bba67 Mon Sep 17 00:00:00 2001 From: Fridtjof Michels Date: Tue, 3 Nov 2026 21:08:25 +0100 Subject: [PATCH 19/39] =?UTF-8?q?LR-VIEW-SURVEY:=20the=20=C3=97=20on=20a?= =?UTF-8?q?=20survey=20tile=20stays=20clickable=20while=20the=20pointer=20?= =?UTF-8?q?is=20on=20it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The × was drawn only while the tile was hovered; the pointer on the × took that hover, so the × vanished before the click landed. It now shows while the pointer is in the tile. Root cause and fix idea from #1639. Co-Authored-By: SarimSyed --- crates/ui-egui/src/panels/compare.rs | 5 +++-- crates/ui-egui/src/tests/compare.rs | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/compare.rs b/crates/ui-egui/src/panels/compare.rs index b7034f3a6d..229ed0f653 100644 --- a/crates/ui-egui/src/panels/compare.rs +++ b/crates/ui-egui/src/panels/compare.rs @@ -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/tests/compare.rs b/crates/ui-egui/src/tests/compare.rs index f570df33a8..621eea975a 100644 --- a/crates/ui-egui/src/tests/compare.rs +++ b/crates/ui-egui/src/tests/compare.rs @@ -405,6 +405,22 @@ 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"); } +/// 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); + let tile = h.app.widgets.iter().find(|(w, _)| *w == format!("cull:{c}")).map(|(_, r)| *r).expect("the tile is laid out"); + // hover the tile first, as a person does, so the × appears; then click the × in its corner + h.app.synthetic.push(egui::Event::PointerMoved(tile.center())); + h.settle(SETTLE); + click_with(&mut h, egui::pos2(tile.right() - 16.0, tile.top() + 16.0), egui::Modifiers::NONE); + let sel: Vec = h.app.session.selection.ids.iter().map(|p| p.0).collect(); + assert_eq!(sel, vec![a, b], "the photo whose × was clicked left the survey"); +} + /// ⌘/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] From 85c1265da7653f2c231ca0d33e99a97985ab9f93 Mon Sep 17 00:00:00 2001 From: insideTheFlux Date: Wed, 4 Nov 2026 18:04:57 -0800 Subject: [PATCH 20/39] LR-LIB-PEOPLE: face boxes turn only by an orientation the Exif states (#2674, review) A photo whose Exif states a size but no orientation, and whose XMP says tiff:Orientation=6, is displayed as stored (by the Exif alone). extract turned its stored-frame boxes by the XMP's orientation anyway, so import stored them turned while Read Metadata from File did not (review of #2857). extract_embedded now turns by the orientation the Exif's own first IFD states (exif::ifd0_orientation, which also leaves out the XMP in a TIFF's tag 700), the same rule as for the size. Metadata::orientation is still filled from the XMP as before. Tests (both fail on the previous head, with the reviewer's numbers): the photo as a JPEG and as a TIFF in lightcraft-meta, and through library.import and photo.readMetadataFromFile in the engine. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01CvoftP5JSqAEJ9t7FSczTs --- crates/engine/src/tests/xmp.rs | 43 +++++++++++++++++++++++++++++++ crates/meta/src/exif.rs | 8 ++++++ crates/meta/src/lib.rs | 46 +++++++++++++++++++++++++++++++++- 3 files changed, 96 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index 9054665994..e79262ff9a 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -627,6 +627,49 @@ fn regions_drawn_on_the_photo_as_stored_land_on_the_upright_photo() { let _ = std::fs::remove_dir_all(&src); } +/// Review of #2857: a photo whose Exif states no orientation, but whose XMP says `tiff:Orientation=6`, is shown as +/// stored (LightCraft turns by the Exif alone), so boxes drawn on its stored frame are right as written: at import +/// and when the file's metadata is read again, which must agree. +#[test] +fn an_orientation_only_the_xmp_states_leaves_stored_frame_regions_as_written() { + let src = temp_dir("regions-xmp-orientation"); + let file = src.join("p.jpg"); + let packet = STORED_FRAME_REGIONS.replace(r#"rdf:about="""#, r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:Orientation="6""#); + let img = lightcraft_raster::Rgba8::from_fn(32, 24, |x, y| [(x * 7) as u8, (y * 9) as u8, 90, 255]); + // an Exif that states the size as stored (32 × 24, as cameras do) and no orientation + let exif = { + use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t}; + let mut sub = IfdBuilder::new(); + sub.set(t::PIXEL_X_DIMENSION, Value::Long(vec![32])); + sub.set(t::PIXEL_Y_DIMENSION, Value::Long(vec![24])); + let mut ifd0 = IfdBuilder::new(); + ifd0.set_child(t::EXIF_IFD, sub); + [b"Exif\0\0".as_slice(), &TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap()].concat() + }; + let meta = lightcraft_codecs::EncodeMeta { exif: Some(&exif), xmp: Some(&packet), ..Default::default() }; + std::fs::write(&file, lightcraft_codecs::encode_jpeg(&lightcraft_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &meta).unwrap()) + .unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); + let id = only(&s); + let boxes = |s: &Session, when: &str| { + let p = s.catalog.photo(id).unwrap(); + assert_eq!((p.width, p.height), (32, 24), "{when}: shown as stored"); + assert_eq!(p.meta.regions.len(), 1, "{when}"); + let r = p.meta.regions[0].rect; + [r.x0, r.y0, r.x1, r.y1] + }; + let want = [0.2, 0.325, 0.3, 0.475]; + let close = |got: [f64; 4]| got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-9); + let imported = boxes(&s, "imported"); + assert!(close(imported), "imported: the box was turned by an orientation the Exif doesn't state: {imported:?}"); + let read = s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(read["failed"], json!([]), "{read}"); + let again = boxes(&s, "read again"); + assert!(close(again), "read again: {again:?}"); + let _ = std::fs::remove_dir_all(&src); +} + /// A raw LightCraft can't decode: a TIFF whose first IFD holds Exif orientation 6, a 40 × 30 JPEG and `packet`. fn turned_preview_only_raw(packet: &str) -> Vec { let img = lightcraft_raster::Rgba8::from_fn(40, 30, |x, y| [(x * 6) as u8, (y * 8) as u8, 90, 255]); diff --git a/crates/meta/src/exif.rs b/crates/meta/src/exif.rs index 5e9d3e368a..9894f016ba 100644 --- a/crates/meta/src/exif.rs +++ b/crates/meta/src/exif.rs @@ -46,6 +46,14 @@ fn pos(v: Option) -> Option { v.filter(|x| x.is_finite() && *x > 0.0) } +/// The orientation the Exif's own first IFD states. [`from_tiff`] also reports one that only the XMP packet in +/// the Exif's tag 700 states; LightCraft displays a photo by the Exif's alone, so that one can't tell how a photo +/// is stored. +pub(crate) fn ifd0_orientation(bytes: &[u8]) -> Option { + let tiff = Tiff::parse_with(strip_exif_header(bytes), &ParseOptions::default()).ok()?; + tiff.ifds.first().and_then(|i| i.u16(t::ORIENTATION)).filter(|v| (1..=8).contains(v)).map(Orientation::from_exif) +} + /// Build [`Metadata`] from a parsed TIFF stream (IFD0 + Exif + GPS; DNG tags as fallbacks). pub fn from_tiff(tiff: &Tiff) -> Metadata { let ifd0 = tiff.ifds.first(); diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index 72986e0cde..ffa0d2f83b 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -321,6 +321,9 @@ pub fn try_extract(bytes: &[u8]) -> Result { fn extract_embedded(e: Embedded, mut m: Metadata, xmp: Option) -> Metadata { // the size the Exif states: a size only the XMP states may be the upright one, so it can't tell how the photo is stored let stored = m.width.zip(m.height); + // and the orientation the Exif states: the photo is displayed by that alone, so an orientation only the XMP + // states ([`Metadata::fill_missing`] reports it below) can't tell how the photo is stored either + let exif_orientation = e.exif.as_deref().and_then(exif::ifd0_orientation); if let Some(i) = e.iptc.as_deref() { m.fill_missing(&parse_iptc(i)); } @@ -328,7 +331,7 @@ fn extract_embedded(e: Embedded, mut m: Metadata, xmp: Option) -> Metad m.overlay_user_fields(&xmp.metadata); m.fill_missing(&xmp.metadata); // boxes another app drew on the photo as stored go where the upright photo has them (#2674) - if let (Some(drawn_on), Some(orientation), Some(stored)) = (xmp.regions_drawn_on(), m.orientation, stored) { + if let (Some(drawn_on), Some(orientation), Some(stored)) = (xmp.regions_drawn_on(), exif_orientation, stored) { upright_regions(&mut m.regions, drawn_on, orientation, stored); } } @@ -603,4 +606,45 @@ mod tests { assert_eq!((m.orientation, m.width, m.height), (Some(Orientation::Rotate90), Some(4000), Some(6000))); assert!(near(m.regions[0].rect, DRAWN), "TIFF: {:?}", m.regions[0].rect); } + + /// A photo whose Exif has a size but no orientation, and whose XMP says `tiff:Orientation=6`: LightCraft + /// displays it by the Exif alone, so it stays as stored, and boxes drawn on that stored frame are right as + /// written. Turning them by an orientation only the XMP states put them where the photo isn't (review of #2857). + #[test] + fn an_orientation_only_the_xmp_states_turns_no_regions() { + // 6000 × 4000 in the Exif, and no orientation + let size_ifd = || { + let mut sub = lightcraft_tiff::IfdBuilder::new(); + sub.set(lightcraft_tiff::tags::PIXEL_X_DIMENSION, lightcraft_tiff::Value::Long(vec![6000])); + sub.set(lightcraft_tiff::tags::PIXEL_Y_DIMENSION, lightcraft_tiff::Value::Long(vec![4000])); + sub + }; + let mut exif_ifd0 = lightcraft_tiff::IfdBuilder::new(); + exif_ifd0.set_child(lightcraft_tiff::tags::EXIF_IFD, size_ifd()); + let exif = lightcraft_tiff::TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[exif_ifd0]).unwrap(); + let packet = regions_packet(6000, 4000, "") + .replace(r#"rdf:about="""#, r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:Orientation="6""#); + let mut j = vec![0xff, 0xd8]; + let mut seg = |payload: Vec| { + j.extend([0xff, 0xe1]); + j.extend(u16::try_from(payload.len() + 2).unwrap().to_be_bytes()); + j.extend(payload); + }; + seg([b"Exif\0\0".as_slice(), &exif].concat()); + seg([b"http://ns.adobe.com/xap/1.0/\0".as_slice(), packet.as_bytes()].concat()); + j.extend([0xff, 0xd9]); + let m = extract(&j); + assert_eq!((m.width, m.height), (Some(6000), Some(4000))); + assert_eq!(m.orientation, Some(Orientation::Rotate90), "the XMP's orientation is still reported"); + assert_eq!(m.regions.len(), 1); + assert!(near(m.regions[0].rect, DRAWN), "turned by an orientation the Exif doesn't state: {:?}", m.regions[0].rect); + assert_eq!(try_extract(&j).unwrap().regions, m.regions); + // a TIFF-based file: the first IFD has no orientation, its XMP (tag 700) has + let mut ifd0 = lightcraft_tiff::IfdBuilder::new(); + ifd0.set(lightcraft_tiff::tags::XMP, lightcraft_tiff::Value::Byte(packet.into_bytes())); + ifd0.set_child(lightcraft_tiff::tags::EXIF_IFD, size_ifd()); + let m = extract(&lightcraft_tiff::TiffWriter::default().write(&[ifd0]).unwrap()); + assert_eq!(m.orientation, Some(Orientation::Rotate90)); + assert!(near(m.regions[0].rect, DRAWN), "TIFF: {:?}", m.regions[0].rect); + } } From ed6dd3c22db8a1cd5721fd855c74d1a05159b16e Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 5 Nov 2026 04:42:25 +0100 Subject: [PATCH 21/39] =?UTF-8?q?survey=20=C3=97=20test:=20active=20photo?= =?UTF-8?q?=20stays=20or=20moves=20on,=20and=20removing=20the=20active=20t?= =?UTF-8?q?ile?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/src/tests/compare.rs | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/tests/compare.rs b/crates/ui-egui/src/tests/compare.rs index 621eea975a..0baffa06b6 100644 --- a/crates/ui-egui/src/tests/compare.rs +++ b/crates/ui-egui/src/tests/compare.rs @@ -405,6 +405,15 @@ 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. @@ -412,13 +421,21 @@ fn survey_command_click_takes_the_photo_out() { fn survey_x_takes_the_photo_out() { let mut h = demo(); let [a, b, c] = survey_of_three(&mut h); - let tile = h.app.widgets.iter().find(|(w, _)| *w == format!("cull:{c}")).map(|(_, r)| *r).expect("the tile is laid out"); - // hover the tile first, as a person does, so the × appears; then click the × in its corner - h.app.synthetic.push(egui::Event::PointerMoved(tile.center())); - h.settle(SETTLE); - click_with(&mut h, egui::pos2(tile.right() - 16.0, tile.top() + 16.0), egui::Modifiers::NONE); + click_x(&mut h, c); let sel: Vec = h.app.session.selection.ids.iter().map(|p| p.0).collect(); - assert_eq!(sel, vec![a, b], "the photo whose × was clicked left the survey"); + 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 From 4432fee1b1af4578ef19b5dffe72fd93422618e2 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 5 Nov 2026 04:45:17 +0100 Subject: [PATCH 22/39] Screen profile: wake an idle window once a second to read it again --- crates/ui-egui/src/app/prefs.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs index 9a5c612f12..b0b6cb1498 100644 --- a/crates/ui-egui/src/app/prefs.rs +++ b/crates/ui-egui/src/app/prefs.rs @@ -84,9 +84,14 @@ impl LightcraftApp { /// While no display profile is chosen, show previews through the profile of the screen the /// window is on (`services.screen_profile`), read about once a second so moving the window to /// another screen is followed. Without the service (or a profile) the display is sRGB. - fn follow_screen_profile(&mut self, _ctx: &egui::Context) { + fn follow_screen_profile(&mut self, ctx: &egui::Context) { + if self.services.screen_profile.is_none() { + return; + } + // an idle window draws no frames: wake up to read again, so a profile changed in Windows is followed + ctx.request_repaint_after(std::time::Duration::from_secs(1)); let now = self.tick_now(); - if self.services.screen_profile.is_none() || self.screen_profile_read.is_some_and(|t| (0.0..1.0).contains(&(now - t))) { + if self.screen_profile_read.is_some_and(|t| (0.0..1.0).contains(&(now - t))) { return; } self.screen_profile_read = Some(now); From 077f4a507f92903dba245518c87f91eac6274bca Mon Sep 17 00:00:00 2001 From: OneSlip Date: Thu, 5 Nov 2026 14:10:32 +1000 Subject: [PATCH 23/39] GPU-FULL: more of the render on the GPU, loupe drafts from GPU textures (#1065) * GPU-FULL-1: LUT profiles, Refine Edges and soft proofs render on the GPU These three sent the whole loupe / compare / export render back to the CPU pipeline (media::develop and lightcraft_gpu::render declined them). - LUT profiles: the .cube table rides in the finish kernel's aux buffer (LUT_* parameters); lut_apply mirrors Lut3d::apply (trilinear, domain), applied after grain and blended by the profile amount, as on the CPU. - Refine Edges: the cross guided filter Auto Mask already ran on the device, now with a combine mode (max for strokes, mix by sqrt(refine) for Refine), applied to the combined alpha before the mask's invert and amount. - Soft proofing: proof-space gamut mapping and the destination / display gamut warnings in the kernel (PROOF_* parameters, GAMUT_WARN and warning colours generated from the CPU constants), for output spaces and displays. Equivalence tests (RTX 5070, DX12): LUT profiles at three amounts and a non-default domain, Refine 15/60/100 on two masks, proofs in 16 combinations of space, output, display and warnings - all max 1 LSB, mean <= 0.0005 LSB. The tests also check that strong refine and the destination warning change the image (so they aren't comparing two unchanged renders). Co-Authored-By: Claude Opus 5.5 * GPU-FULL-2: spot removal, defringe and the histogram on the GPU Spots and defringe made every render that had them (and every white balance or spot edit) read the resampled image back, run the scene-linear stage on the CPU and upload it again. Now only the ProRAW local tone map (off by default) does. - Defringe: OkLab pass, separable lightness min/max filter, per-pixel apply. Parameters come from the new optics::defringe_params, which the CPU stage now uses too. - Spots: new spot module (spot_prep / spot_apply over each spot's box, the Heal tone correction as device Gaussians), spot by spot in place so each reads what the earlier ones left, as on the CPU. Remove's automatic source: spot_score rates the 48 candidates on the device and only the scores come back. Layout, candidates, spoke directions, radii and ranking are shared helpers in pipeline::spots (spots::apply uses them; behaviour unchanged, pipeline tests green). - Histogram: counted with atomics on the device on Histogram::of_srgb8's sampling grid (exact), instead of a CPU pass over the readback. Tests: spots (clone, heal, auto remove incl. near the edge where no candidate fits, brushed strokes, feather 0, cut by the edge, overlapping) and defringe (purple/green, hue ranges, preview and full size) max 1 LSB; the device histogram equals the CPU count of the returned image for small, sampled (>1 MP) and windowed renders; the scoring kernel picks the CPU's candidate. (The edge case caught a real bug: "doesn't fit" was written as a decimal literal that rounds below f32::MAX.) Unit tests that create the device now take turns with the crash-sentinel test, which swaps a global. Co-Authored-By: Claude Opus 5.5 * GPU-FULL-2: fix the spot kernels' build; GPU tests fail when kernels don't build 07d4680b's spot module declared `const F32_MAX = bitcast(...)`, which naga can't evaluate as a constant: the kernels failed to build, the device was unavailable, and the equivalence tests skipped as if there were no adapter - so that commit's GPU tests didn't actually run. f32::MAX is now a function, and the equivalence suite (and the device unit test) fail instead of skipping when an adapter exists but the kernels don't build. Re-verified on the RTX 5070 (DX12), all on the device: 21 equivalence tests incl. the 8 spot cases (max 1 LSB), defringe, the exact device histogram, and the auto-source unit test. Adds an ignored thumbnail throughput bench (tests/thumbs_bench.rs). Co-Authored-By: Claude Opus 5.5 * GPU-FULL-3: thumbnails render on the GPU once the device is ready Every cached job (grid and filmstrip thumbnails, preset and profile previews, faces, quick stand-ins) was forced onto the CPU. They now use the GPU when lightcraft_gpu::ready() - so they never block on device creation at startup (1.8 s incl. kernels here) and render on the CPU until then. Views and exports keep waiting for the device as before. tests/thumbs_bench.rs (ignored): six workers rendering 256 px thumbnails of 512 px sources with preset-like settings (NR, sharpening, clarity, grading, a gradient mask): RTX 5070 3.6 ms each vs 4.3-5.2 ms on 32 CPU threads, with the cores left free for raw decoding. Engine and UI suites: unchanged (only the 12 failures that predate this branch on Windows: tests_sync paths, tests_model_setup). Co-Authored-By: Claude Opus 5.5 * GPU-FULL-4: the loupe's drafts are drawn straight from the GPU Rendering and drawing now share one device: 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, under the crash sentinel; a device that doesn't suit falls back to one of the renderer's own, as before). A drag's drafts of the views are RenderJob::on_screen: the render ends in an Rgba8Unorm texture (lightcraft_gpu::render_display -> Output::Display, new `present` kernels: unwritten-pixel count, row padding for the copy) and egui-wgpu draws it as a native texture (ui-egui ScreenTextures, implemented by the app) - no readback, no conversion to egui pixels, no re-upload. The readback's checks run on the device (atomic unwritten count, device histogram). Renders that need pixels keep the readback: the settled full render (view cache, overlays, screenshots), thumbnails, exports, overlays, windows that spots grew, a monitor profile. - engine: RenderJob::on_screen, RenderResult::frame (ScreenFrame). - ui-egui: Tex::native / Tex::id() (21 draw sites), Renderer set_screen_textures, natives per slot (freed when pixels return), ui.inspect perf.gpuWindowDevice / screenTextures / mainOnGpu. - app: WindowTextures, window device limits, LIGHTCRAFT_GPU_WINDOW=0 to opt out. Tests: crates/gpu/tests/display.rs adopts a device in its own process and checks the texture holds exactly the readback's pixels (padded and unpadded widths, draft and full), the histogram matches, and overlays / grown windows come back as pixels. In the app (RTX 5070, a 45 MP CR3 from the user's library copy): all 90 drafts of a drag drawn from GPU textures, 1.69 ms vs 2.05 ms median per draft render with the readback; the frame screenshot shows the image correctly; pixels return after the drag. Co-Authored-By: Claude Opus 5.5 * GPU-FULL-2: the denoise runner tests take turns with the crash-sentinel tests Building a denoise runner creates a device and compiles kernels under the init marker. Running in parallel with backend::tests, it could arm the marker the test had just set, so "is removed afterwards" failed now and then. The runner tests now hold DEVICE_TEST_LOCK while they build, like the render tests. Co-Authored-By: Claude Opus 5.5 * GPU-FULL-4: fix the build after merging upstream main Upstream's QuickJob panic guard builds a RenderResult (add `frame: None`), its idle-trim test builds a Tex (add `native: None`), and its on_exit test builds App (add the WindowTextures slot). Co-Authored-By: Claude Opus 5.5 * GPU-FULL-2: upstream's blur tests take turns with the crash-sentinel tests gaussian_matches_cpu and bench_kernels create the device, so they hold DEVICE_TEST_LOCK like every other device test in lightcraft-gpu. Co-Authored-By: Claude Opus 5.5 * Tests: the same-folder export test compares paths separator-blind (Windows) The written path is the original's folder (`\` on Windows) joined with `Exports/IMG_1.jpg`; the expected one had `\Exports`. Co-Authored-By: Claude Opus 5.5 * Tests: the folder-drop tests find folder widgets separator-blind (Windows) The folder tree spells its paths with `/`; the tests built widget ids from Windows paths with `\`, so none was found and every test failed on Windows. Co-Authored-By: Claude Opus 5.5 * Tests: the Windows path fixes take the same form as in the other PR branches So the branches merge into main without conflicts between their copies of the fix. Co-Authored-By: Claude Opus 5.5 * GPU-FULL: headless screenshots read back GPU-drawn views; LIGHTCRAFT_GPU_LIMITS caps the adopted device Review of PR #1065: - A headless `ui.screenshot` taken mid-drag showed the photo as a white rectangle: the GPU-resident draft left no CPU copy. With keep_pixels (control channel) the renderer now keeps each view's frame, and `cpu_textures` reads it back through `ScreenTextures::read` (`lightcraft_gpu::read_texture`). Drawing still never reads back, so drags keep the speed-up. - Adopting the window's device skipped LIGHTCRAFT_GPU_LIMITS; `Gpu::adopt` now caps its limits the same way `Gpu::new` does. Tests: a_headless_screenshot_reads_back_a_view_drawn_from_the_gpu (ui-egui), the_limits_override_caps_an_adopted_device (gpu); the display test uses read_texture and skips through lightcraft_testkit::skip!. Co-Authored-By: Claude Opus 5.5 * GPU-FULL: review fixes (CodeRabbit 2026-10-21) and slideshow/print draw GPU-drawn views - the window-device adoption is announced before its thread starts: until it finishes, the settings' warm-up and renders don't create a device of their own (they raced it) - the device error / device-lost handlers go on only after the kernels build, so a declined window device keeps the window's own handler - releasing a slot frees its GPU-resident texture and kept frame - a soft proof into a colour space drafts full size on the GPU; only one to a device profile counts as proofed for `handles` - docs: Fill spots and device-profile soft proofs render on the CPU - slideshow, slide layout and print draw `Tex::id()` (the GPU texture when there is one) Co-Authored-By: Claude Opus 5.5 * GPU-FULL: the display test skips when LIGHTCRAFT_GPU=0 switches the GPU off It panicked ("GPU rendering is off") instead of skipping like the other GPU tests. Co-Authored-By: Claude Opus 5.5 * GPU-FULL: a view readback never panics on a lost device read_texture (headless screenshots of GPU-drawn views) polled the device directly. On a lost device wgpu 30 panics in Device::poll; it now goes through the same guard as the renderer's own polls (poll_device): a lost device returns an error, stops the GPU and is not polled again. Review of PR #1065. Also quiets a browser-build dead-code warning on OnScreen::Frame. Co-Authored-By: Claude Opus 5.5 * GPU-FULL: an HDR edit's histogram shows the HDR range on the on-screen GPU path too develop_on_screen returned the GPU's SDR histogram for both its Display and Image arms; it now applies lightcraft_pipeline::hdr_histogram as develop_reporting does (None for drafts, windows, proofs and non-HDR edits, which keep the GPU's histogram). Co-Authored-By: Claude Opus 5.5 * GPU-FULL: the Navigator draws the photo's texture as it is drawn in the loupe The Navigator falls back to the main view's texture before the photo has a thumbnail. It drew `t.tex`, which is stale (or the 1x1 placeholder) when the main view holds a GPU-resident draft; it now draws `Tex::id()`, like every other draw site. Co-Authored-By: Claude Opus 5.5 * GPU-FULL: the egui 0.37 lifecycle test's texture names no native id Co-Authored-By: Claude Opus 5.5 * GPU-FULL: rustfmt the lifecycle test Co-Authored-By: Claude Opus 5.5 * GPU-FULL: the second window fits the frame's size; freed GPU frames drop their views The second window sized its image from the texture handle, which is only a 1x1 placeholder for a GPU-resident render; it now uses the frame's size. When a GPU-resident render can't be shown and every native texture is freed, the views pointing at them (Before, Region, Compare tiles) are dropped too, so they render again as pixels instead of drawing a freed id. Test: freeing_gpu_frames_drops_the_views_drawn_from_them. Co-Authored-By: Claude Opus 5.5 * feat(gpu): LIGHTCRAFT_GPU_ADAPTER picks the card for rendering too The variable chose the card only for AI Denoise and the face detector (two copies of the same enumerate-and-match code); photo rendering always took the first high-performance adapter, on a two-card machine the one driving the screens. One helper, backend::pick_adapter, now serves the render device (Gpu::new), the denoise network and the face detector: the first hardware card whose name contains the value (any case), else the high-performance one. A name that matches no card is logged and falls back instead of failing. backend::may_adopt_window_device says whether rendering may share the window's device (only for the window's card). Name matching is unit-tested without a GPU; the equivalence tests print the card they ran on. Documented in docs/gpu-pipeline.md. Co-Authored-By: Claude Opus 5.5 * GPU-FULL: a view switching to a GPU texture releases its pixel image Review of #1065 (CodeRabbit nitpick): when a slot that had pixels switched to a GPU-resident texture, its egui texture kept the full-size image, never drawn while the native texture is set. Tex::show_native now swaps it for a 1x1 placeholder on the switch. Co-Authored-By: Claude Opus 5.5 * fix(gpu): LIGHTCRAFT_GPU_ADAPTER picks among several matches in a defined order and logs once Review of #3428: - several cards match: the one whose whole name it is, then dedicated before built-in before virtual cards, then wgpu's order (backend::choose_named_adapter); the log names every match and the one used; - no match: the default choice, with a warning that lists the cards; - a name matching only a software renderer: never used, and the warning says so; - each line is logged once (backend::log_once), though the render device, AI Denoise and the face models each ask; - tests on fake adapter lists: a_fake_adapter_list_picks_in_a_defined_order, a_choice_is_logged_once. Co-Authored-By: Claude Opus 5.5 * GPU-FULL: the release note gives the GPU's documented bound against the CPU (3 levels, mean under half a level) Review of PR #3544. Co-Authored-By: Claude Opus 5.5 * GPU-FULL: the window's device isn't adopted when LIGHTCRAFT_GPU_ADAPTER names another card With #3428 merged, Gpu::new already makes the render device on the named card; the window's device was still adopted first, so the app rendered on the screen's card whatever the variable said. backend::may_adopt_window_device (tested on names in backend.rs) now decides: another card named renders on a device of its own, and the window stays on the screen's card. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- Cargo.lock | 1 + apps/lightcraft-web/src/workers.rs | 3 + apps/lightcraft/src/main.rs | 78 ++++- apps/lightcraft/src/tests.rs | 3 + apps/lightcraft/src/window_gpu.rs | 12 +- crates/catalog/src/store.rs | 1 - crates/engine/src/import/job.rs | 1 + crates/engine/src/media.rs | 2 +- crates/engine/src/media/quick.rs | 2 + crates/engine/src/media/render.rs | 105 ++++++- crates/engine/src/media/session.rs | 3 + crates/engine/src/slide_title.rs | 1 + crates/gpu/src/backend.rs | 261 ++++++++++++++++ crates/gpu/src/ctx.rs | 292 +++++++++++++++--- crates/gpu/src/faces.rs | 15 +- crates/gpu/src/lib.rs | 156 +++++++++- crates/gpu/src/nn.rs | 29 +- crates/gpu/src/params.rs | 19 ++ crates/gpu/src/render.rs | 262 +++++++++++++++- crates/gpu/src/wgsl/blur.wgsl | 37 +++ crates/gpu/src/wgsl/finish.wgsl | 70 +++-- crates/gpu/src/wgsl/hist.wgsl | 24 ++ crates/gpu/src/wgsl/map.wgsl | 60 +++- crates/gpu/src/wgsl/present.wgsl | 24 ++ crates/gpu/src/wgsl/spot.wgsl | 177 +++++++++++ crates/gpu/tests/display.rs | 80 +++++ crates/gpu/tests/it/equivalence.rs | 186 ++++++++++- crates/gpu/tests/it/main.rs | 6 +- crates/gpu/tests/it/thumbs_bench.rs | 72 +++++ crates/gpu/tests/window_pending.rs | 25 ++ crates/pipeline/src/finish.rs | 4 +- crates/pipeline/src/lut.rs | 4 +- crates/pipeline/src/optics.rs | 61 ++-- crates/pipeline/src/spots.rs | 189 ++++++++---- crates/ui-egui/Cargo.toml | 2 + .../ui-egui/examples/thumb_request_bench.rs | 13 +- crates/ui-egui/src/control.rs | 2 +- crates/ui-egui/src/dialogs/import/body.rs | 2 +- crates/ui-egui/src/dialogs/print_view.rs | 2 +- .../src/dialogs/settings/slide_layout.rs | 4 +- crates/ui-egui/src/panels/compare.rs | 6 +- crates/ui-egui/src/panels/detail.rs | 8 +- crates/ui-egui/src/panels/detail/filmstrip.rs | 4 +- crates/ui-egui/src/panels/detail/window.rs | 2 +- crates/ui-egui/src/panels/grid.rs | 2 +- crates/ui-egui/src/panels/people.rs | 2 +- crates/ui-egui/src/panels/person.rs | 2 +- crates/ui-egui/src/panels/presets.rs | 2 +- crates/ui-egui/src/panels/profiles.rs | 2 +- crates/ui-egui/src/panels/right/history.rs | 2 +- crates/ui-egui/src/panels/second.rs | 5 +- crates/ui-egui/src/panels/slideshow.rs | 8 +- crates/ui-egui/src/panels/unnamed.rs | 2 +- crates/ui-egui/src/render.rs | 232 +++++++++++++- crates/ui-egui/src/render/thumbnail_tests.rs | 112 +++++++ crates/ui-egui/src/tests/lifecycle_037.rs | 2 +- crates/ui-egui/src/tests/preview_limit.rs | 22 +- crates/ui-egui/src/tests/zoom.rs | 13 +- docs/control-protocol.md | 2 +- docs/gpu-pipeline.md | 79 ++++- docs/whats-new.md | 9 + 61 files changed, 2544 insertions(+), 264 deletions(-) create mode 100644 crates/gpu/src/wgsl/hist.wgsl create mode 100644 crates/gpu/src/wgsl/present.wgsl create mode 100644 crates/gpu/src/wgsl/spot.wgsl create mode 100644 crates/gpu/tests/display.rs create mode 100644 crates/gpu/tests/it/thumbs_bench.rs create mode 100644 crates/gpu/tests/window_pending.rs diff --git a/Cargo.lock b/Cargo.lock index 31b2dab5d2..dfe5c5cbdf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4043,6 +4043,7 @@ dependencies = [ "lightcraft-slideshow", "lightcraft-testkit", "log", + "pollster 1.0.1", "serde", "serde_json", "toml", 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.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/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/media.rs b/crates/engine/src/media.rs index 7377e23f1b..93395576c1 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -35,7 +35,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; 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..3fac3b6777 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -91,6 +91,7 @@ impl crate::Session { stages: None, view_cache: None, display: None, + on_screen: false, slide: None, preview_cut: None, display_fit: None, @@ -156,6 +157,7 @@ impl crate::Session { stages: None, view_cache: None, display: None, + on_screen: false, slide: None, preview_cut: None, display_fit: None, @@ -211,6 +213,7 @@ impl crate::Session { stages: None, view_cache: None, display: None, + on_screen: false, slide: None, preview_cut, display_fit: None, 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/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..3554064626 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -30,7 +30,7 @@ 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/resize.wgsl"), @@ -55,13 +55,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 +350,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). @@ -364,6 +379,12 @@ fn constants() -> String { 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 +418,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 +433,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 +485,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 +492,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 +588,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 +800,107 @@ 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); + }); + let wait = std::time::Duration::from_secs(10); + 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 +1057,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 +1187,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..c187a764ed 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 few seconds); `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..61d8b5a80b 100644 --- a/crates/gpu/src/params.rs +++ b/crates/gpu/src/params.rs @@ -73,6 +73,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), @@ -163,6 +170,10 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr for m in masks { aux.extend_from_slice(m); } + let lut_off = aux.len(); + if let Some((l, _)) = &fp.lut { + aux.extend(l.data.iter().flatten()); + } let mut p = Block::new(); p.u("W", fp.w as u32); @@ -240,6 +251,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..1f079285af 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -213,6 +213,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) } } @@ -579,8 +593,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 +629,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. @@ -726,6 +767,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 +813,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. @@ -803,7 +845,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 +904,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 +914,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 +935,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); @@ -958,8 +1140,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 +1161,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 +1270,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 +1316,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 +1414,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 +1443,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 +1482,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..b5f35eac2a 100644 --- a/crates/gpu/src/wgsl/finish.wgsl +++ b/crates/gpu/src/wgsl/finish.wgsl @@ -230,6 +230,52 @@ fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { return a + (b - a) * v; } +// 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); +} + fn enc8(v: f32) -> u32 { return u32(clamp(v, 0.0, 1.0) * 255.0 + 0.5); } @@ -254,15 +300,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 +324,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); @@ -558,10 +588,14 @@ 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); 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..68b9fd2227 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -20,8 +20,14 @@ 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 } @@ -417,7 +423,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; }), @@ -797,7 +803,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 +962,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 +1095,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..99a6e50246 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -169,7 +169,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, @@ -685,7 +685,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). 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/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index eb73f22fdc..83a18de446 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -42,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..a4e869805c 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); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index be39917530..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, 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/panels/compare.rs b/crates/ui-egui/src/panels/compare.rs index b7034f3a6d..b3a6a0f027 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 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/grid.rs b/crates/ui-egui/src/panels/grid.rs index 9e7d84d6f0..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 { 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..c95e8d7a76 100644 --- a/crates/ui-egui/src/panels/profiles.rs +++ b/crates/ui-egui/src/panels/profiles.rs @@ -163,7 +163,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/render.rs b/crates/ui-egui/src/render.rs index 93af459559..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 @@ -279,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. @@ -365,6 +411,9 @@ impl Renderer { display: None, #[cfg(not(target_arch = "wasm32"))] idle: None, + screen: None, + natives: HashMap::new(), + native_frames: HashMap::new(), } } } @@ -526,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). @@ -572,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). @@ -775,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 { @@ -1024,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 })); @@ -1036,6 +1129,12 @@ 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 { @@ -1091,6 +1190,58 @@ 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); @@ -1147,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; @@ -1173,6 +1327,7 @@ impl Renderer { ms, quick: r.quick, pixels, + native: None, }, ); } @@ -1242,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). @@ -1407,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)); @@ -1419,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() { @@ -1539,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 bb03986f0d..922a9b8a47 100644 --- a/crates/ui-egui/src/render/thumbnail_tests.rs +++ b/crates/ui-egui/src/render/thumbnail_tests.rs @@ -329,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. @@ -467,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(); 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/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/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/gpu-pipeline.md b/docs/gpu-pipeline.md index a35218c46d..ac09990036 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -49,6 +49,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 stays on the card that drives the screen, + and rendering runs on a device of its own on the chosen card (the photo is copied to the screen's + card); a build that lets rendering share the window's device does so only when the variable 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 +167,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 +204,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 +280,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 +382,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 +455,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 +464,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/whats-new.md b/docs/whats-new.md index 3721421fd1..5442020aed 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1469,6 +1469,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 From d977d3e1a4e9f687b3cffcb4fadca41dcb966c1b Mon Sep 17 00:00:00 2001 From: Phil Hart Date: Wed, 4 Nov 2026 23:21:13 -0500 Subject: [PATCH 24/39] LR-EDIT-DETAIL-SHARPEN: Radius and Detail work, and sharpening acts at pixel scale (#757) (#762) * LR-EDIT-DETAIL-SHARPEN: Radius and Detail work, and sharpening acts at pixel scale (#757) * LR-EDIT-DETAIL-SHARPEN: an enlarging export keeps every Radius step (#757) The sharpening blur's sigma was capped at 4 px, so a 2x export rendered Radius 2 and 3 alike (both scaled past 4 px). The cap is now the largest sigma the Gaussian taps support, GAUSS_SIGMA_MAX (64), which the CPU and GPU blurs share. Test: enlarged_export_keeps_radius_steps_apart. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014ti8KemZbjE2ZgHgV1q1BM * LR-EDIT-DETAIL-SHARPEN: preserve process-aware previews after rebase (#757) Use the V3 pixel-scale blur and Masking weight for the Radius, Detail and Masking previews on both renderers. Preserve the legacy texture-band previews for V1/V2 and compute the same Gaussian when sharpening is disabled. Cover process selection, radius changes, and prepared/fresh plane equivalence. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014ti8KemZbjE2ZgHgV1q1BM --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/develop/src/settings.rs | 7 +- crates/engine/src/media/source.rs | 2 +- crates/gpu/src/ctx.rs | 5 + crates/gpu/src/params.rs | 12 ++ crates/gpu/src/render.rs | 40 +++- crates/gpu/src/wgsl/finish.wgsl | 27 ++- crates/gpu/src/wgsl/gauss.wgsl | 36 ++++ crates/gpu/tests/it/equivalence.rs | 51 +++++ crates/pipeline/src/finish.rs | 59 +++++- crates/pipeline/src/lib.rs | 31 +++- crates/pipeline/src/local.rs | 103 +++++++++-- crates/pipeline/src/tests.rs | 4 + crates/pipeline/src/tests_sharpen.rs | 266 +++++++++++++++++++++++++++ crates/pipeline/src/tests_tone.rs | 12 +- crates/pipeline/src/visualize.rs | 66 ++++++- crates/raster/src/blur.rs | 59 ++++++ docs/parity-checklist.md | 2 +- docs/process-versions.md | 3 +- 18 files changed, 728 insertions(+), 57 deletions(-) create mode 100644 crates/gpu/src/wgsl/gauss.wgsl create mode 100644 crates/pipeline/src/tests_sharpen.rs diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index 8b8d4f8746..f422bba08b 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -84,17 +84,20 @@ 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, } 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; 3] = [Process::V1, Process::V2, Process::V3]; + pub const LATEST: Process = Process::V3; pub const fn version(self) -> ProcessVersion { match self { Process::V1 => ProcessVersion(1), Process::V2 => ProcessVersion(2), + Process::V3 => ProcessVersion(3), } } } diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index cf4a5fa2dc..c1ee14ca89 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}; /// 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]; diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index 3554064626..ff1e287082 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -32,6 +32,11 @@ const MODULES: &[Module] = &[ bindings: &[("src", false, "f32"), ("dst", true, "f32")], 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"), bindings: &[("src", false, "f32"), ("table", false, "u32"), ("dst", true, "f32")], diff --git a/crates/gpu/src/params.rs b/crates/gpu/src/params.rs index 61d8b5a80b..6d7f025dfa 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), @@ -147,6 +152,8 @@ 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, @@ -195,6 +202,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); diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 1f079285af..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()) { @@ -277,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); @@ -733,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) @@ -758,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), @@ -836,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()); @@ -1056,6 +1084,7 @@ struct Prep { base: Arc, clarity: Option>, texture: Option>, + sharpen: Option>, dark: Option>, /// Blurred chromaticity (local Moiré / Noise). chroma: Option>, @@ -1066,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 => { @@ -1086,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 { @@ -1113,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). diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl index b5f35eac2a..a7f74b80cb 100644 --- a/crates/gpu/src/wgsl/finish.wgsl +++ b/crates/gpu/src/wgsl/finish.wgsl @@ -453,19 +453,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) { 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/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 68b9fd2227..01686b034c 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -242,6 +242,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; @@ -664,6 +691,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() { diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index 99a6e50246..65d7976bac 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; @@ -178,6 +203,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, @@ -256,6 +287,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, @@ -292,7 +330,7 @@ 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), @@ -662,17 +700,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 diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index 7124383998..2c7700ed4c 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -227,6 +227,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 +331,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 +391,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 +482,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 +631,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 +709,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) { @@ -763,6 +784,8 @@ 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/local.rs b/crates/pipeline/src/local.rs index 6d09cf7557..547131b8bf 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}; @@ -375,7 +375,7 @@ pub fn base_detail_radius(px_per_long: f64) -> usize { 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 => 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/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_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/docs/parity-checklist.md b/docs/parity-checklist.md index d693fd8a7e..fea5c08248 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -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) | diff --git a/docs/process-versions.md b/docs/process-versions.md index 7e6788f11e..318e6d8931 100644 --- a/docs/process-versions.md +++ b/docs/process-versions.md @@ -8,7 +8,8 @@ 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** (the latest) | 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. | ## The rule From 2ddb43896b0c3bab2be3029f75e5f4b5bb7df18e Mon Sep 17 00:00:00 2001 From: OneSlip Date: Thu, 5 Nov 2026 14:25:04 +1000 Subject: [PATCH 25/39] PERF-STEP-STALL: stepping and flagging never wait for the drive, and no change is ever dropped (#3557) * PERF-STEP-STALL: stepping and flagging never wait for the drive; the catalog log is written and synced by its own thread, and nothing handed to it is ever dropped On Windows a write to the catalog log waited for a sync of the same file in flight, and each flag, rating or step synced on the UI thread, so culling on a busy drive froze the window. FsStore now hands log appends to a thread that writes and syncs them in order, batching what arrives during a sync. No change is lost: the thread keeps every byte it has not yet synced. A write or sync that fails is held and retried (cutting any fragment first), later appends are refused with the reason (the engine keeps them queued, as for any failed save), the held records count as unsaved so the quit prompt warns, and a snapshot is made due. Cuts, replaces and reads act on the logical log (synced bytes plus held ones), so the log never has a gap. A clean quit's closing snapshot holds everything; dropping the store waits for the thread. Tests drive a slow drive (a sync hook that sleeps) and a failing one through test-only fault hooks (doc-hidden, keyed by library folder): with 300 ms syncs the slowest flag is 0.2 ms (305 ms with the log written on the caller, as before); every change made during slow saves reopens after a flush, a drop and a close; a failed write is reported, retried and lands with no gap. Co-Authored-By: Claude Opus 5.5 * PERF-STEP-STALL: review fixes: a reopen reads what the log thread was handed, the quit check reads the held status now, a covering snapshot clears it, a cut to the synced length reaches the file - open_stores flushes the old journal's log thread before the same library's files are read again (Settings, Libraries; a reopen). - Session::refresh_unsaved, called by the quit check, reads what the log thread holds at that moment, not as of the last frame. - Journal::unwritten is None once a snapshot holds every op (the closing snapshot after a failed log reset no longer makes the quit prompt say changes would be lost); wants_snapshot follows it. - A cut to exactly the synced length with bytes held cuts the file, so bytes a failed sync left there never come back on the next open. - A caller that waits over a minute for the drive gets a timed-out error, not "the writer stopped". Each fix has a test that fails without it. Co-Authored-By: Claude Opus 5.5 * PERF-STEP-STALL: a reopen and the quit check wait for what the log thread was handed Review of #3557: - Opening the same library again while its log thread can't write what it was handed now fails and keeps the open library (with the held change, retried). Before, the new catalog was read from files missing it. - The quit check flushes the log thread first instead of reading only the failure it had already reported. A change accepted but not yet written, then failed, is saved by the closing snapshot before the window may close; if that fails too, the unsaved prompt shows. Co-Authored-By: Claude Opus 5.5 * PERF-STEP-STALL: a reopen goes ahead when the snapshot already holds every change Review of #3557: the reopen was refused whenever the old log's flush failed. When a completed snapshot covers every op, nothing is missing from the files, so the open now goes ahead and only logs the error. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/catalog/src/fault.rs | 70 +++++ crates/catalog/src/journal.rs | 34 +- crates/catalog/src/lib.rs | 7 + crates/catalog/src/log_writer.rs | 377 +++++++++++++++++++++++ crates/catalog/src/store.rs | 105 ++++++- crates/catalog/src/tests_background.rs | 3 +- crates/catalog/src/tests_log_thread.rs | 232 ++++++++++++++ crates/catalog/src/tests_torn_append.rs | 3 + crates/engine/src/lib.rs | 3 +- crates/engine/src/library.rs | 76 ++++- crates/engine/src/tests.rs | 2 + crates/engine/src/tests/library.rs | 6 +- crates/engine/src/tests/slow_drive.rs | 317 +++++++++++++++++++ crates/ui-egui/src/panels/notices.rs | 29 +- crates/ui-egui/src/tests/quit_unsaved.rs | 48 +++ docs/gaps.md | 5 +- docs/parity-checklist.md | 5 +- 17 files changed, 1288 insertions(+), 34 deletions(-) create mode 100644 crates/catalog/src/fault.rs create mode 100644 crates/catalog/src/log_writer.rs create mode 100644 crates/catalog/src/tests_log_thread.rs create mode 100644 crates/engine/src/tests/slow_drive.rs diff --git a/crates/catalog/src/fault.rs b/crates/catalog/src/fault.rs new file mode 100644 index 0000000000..29ec39da79 --- /dev/null +++ b/crates/catalog/src/fault.rs @@ -0,0 +1,70 @@ +//! Fault injection for the catalog log's writer thread (tests only: nothing in the product +//! installs a hook, and with none installed a check is one uncontended lock of an empty list). +//! +//! A test makes the drive under one library directory slow (a hook that sleeps) or failing (a +//! hook that returns an error) and proves that a flag never waits for it and that nothing handed +//! over is lost: `crates/catalog/src/tests_log_thread.rs`, `crates/engine/src/tests/slow_drive.rs`. + +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; + +/// Where the log thread is about to touch the drive. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Step { + /// Writing bytes to the log (or to the file that replaces it). + Write, + /// Syncing them. + Sync, +} + +/// Runs before each [`Step`] in the hooked directory: an error fails that step. +pub type Hook = Arc 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 bad9384a29..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,6 +350,7 @@ 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::*; 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..b7da3f7090 --- /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(()) })); + store.append(LOG, b"1\n").unwrap(); + store.append(LOG, b"2\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/engine/src/lib.rs b/crates/engine/src/lib.rs index 704602e4be..73677df004 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -614,7 +614,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 diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index caf51a0ab6..bbe590fd3f 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. @@ -322,6 +330,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 +511,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(); @@ -631,6 +652,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 +683,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 +748,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 +789,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 +810,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"); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e571ec1d65..4878ea4976 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -49,6 +49,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/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/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/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/docs/gaps.md b/docs/gaps.md index 535479fa10..404dd37be3 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 (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 @@ -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 | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index fea5c08248..285837a696 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 (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 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (LR-LIB-FLAG: a flag or rating never waits for the drive, PERF-STEP-STALL; before: 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 @@ -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 | @@ -799,6 +799,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 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 | From 35d56543665fd38b5ef8f18cc3842ed2235b8aa0 Mon Sep 17 00:00:00 2001 From: "Yorgos S." Date: Thu, 5 Nov 2026 05:31:15 +0100 Subject: [PATCH 26/39] Convert Negative 1/4: lightcraft-film, the negative conversion maths from Film Lab (#2490) The film model, levels in density space, film presets, colour and tone of Film Lab's core (same author, MIT), without the PhotoCraft-only sharpening and JSON scanning, plus a whole-scan measurement (base, black and white points, neutral balance) a host stores with a photo's settings. A library with no caller yet. Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- Cargo.lock | 7 + Cargo.toml | 2 + crates/film/Cargo.toml | 13 + crates/film/src/analysis.rs | 202 ++++++++++ crates/film/src/color.rs | 145 ++++++++ crates/film/src/film.rs | 105 ++++++ crates/film/src/lib.rs | 718 ++++++++++++++++++++++++++++++++++++ crates/film/src/look.rs | 331 +++++++++++++++++ crates/film/src/measure.rs | 173 +++++++++ crates/film/src/preset.rs | 416 +++++++++++++++++++++ crates/film/src/tone.rs | 331 +++++++++++++++++ xtask/src/layers.rs | 1 + 12 files changed, 2444 insertions(+) create mode 100644 crates/film/Cargo.toml create mode 100644 crates/film/src/analysis.rs create mode 100644 crates/film/src/color.rs create mode 100644 crates/film/src/film.rs create mode 100644 crates/film/src/lib.rs create mode 100644 crates/film/src/look.rs create mode 100644 crates/film/src/measure.rs create mode 100644 crates/film/src/preset.rs create mode 100644 crates/film/src/tone.rs diff --git a/Cargo.lock b/Cargo.lock index dfe5c5cbdf..c04455a37f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3796,6 +3796,13 @@ dependencies = [ "webpki-roots", ] +[[package]] +name = "lightcraft-film" +version = "0.18.0" +dependencies = [ + "libm", +] + [[package]] name = "lightcraft-geocode" version = "0.18.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/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/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)), From 67782d8f659a958552bff5cc8180d3a470bb85eb Mon Sep 17 00:00:00 2001 From: OneSlip Date: Thu, 5 Nov 2026 15:09:04 +1000 Subject: [PATCH 27/39] Auto Sync: As Shot, Auto and Temp apply to each selected photo's own white balance (#3571) * LRC-DEV-AUTOSYNC: Auto Sync carries white balance as a mode or on each photo's own scale: As Shot and Auto per photo, a Temp move keeps each photo's tint (N-A3, note 18) Auto Sync already sets every other setting to the active photo's number. White balance is the exception: main stores the resolved Kelvin and tint with the mode, and Auto Sync copied those numbers. As Shot then gave every selected photo the active photo's camera white, Auto gave them the active photo's Auto white, a Temp move from As Shot gave them the active photo's tint too, and a JPEG beside a raw got the raw's Kelvin read on its own scale. Now (sync_same.rs) the mode goes on each photo and each applies it to itself: As Shot its own camera white, Auto its own white worked out on its own pixels, a light preset its numbers. A typed or dragged Temp or Tint sets the same Kelvin on every raw (an old relative-scale value converted first) and only the slider that moved, and a photo on another scale moves by as much as the active one did. One undo step, as before. Tests (tests/autosync_wb.rs): As Shot / Tungsten / Auto per photo with three different as-shot whites and undo; a typed and a dragged Temp keep each photo's tint; the old relative scale; a JPEG beside a raw. Three of the four fail on main. Co-Authored-By: Claude Opus 5.5 * LRC-DEV-AUTOSYNC: Auto's per-photo pixels are read in parallel; the row says which sync does what Review of #3571: - When Auto is synced, the other selected photos' thumbnails that aren't in memory are now decoded in parallel (one per core), not one after another on the UI thread. - The checklist row says the per-photo white balance belongs to Auto Sync, while Sync Settings copies the active photo's stored one. - The row and the test notes now say a Temp is the same number only on a photo of the same scale, and that other photos move by as much as the active photo did. Co-Authored-By: Claude Opus 5.5 * LRC-DEV-AUTOSYNC: Auto's per-photo pixels are read a core's worth at a time, each with its decoder's facts Review of #3571: - A large selection no longer holds every decoded thumbnail at once. They are decoded in batches of one per core (at most 16), and each batch's white balance is worked out before the next is decoded. - Each photo's Auto uses the facts its own decoder gave, read right after its source is cached, so a photo pushed out of the cache by later ones never falls back to catalog metadata. Co-Authored-By: Claude Opus 5.5 * LRC-DEV-AUTOSYNC: a light preset with a tint of its own on a JPEG carries that tint; Auto's facts are read before the cache can evict them (review of #3585) - On the relative scale the stored numbers are what renders, so a preset the active photo overrides (`develop.wb {mode, tint}`) travels as its numbers, like Custom, not as the preset's tint. - `sources_now` reads each photo's decoder facts before storing the decoded source: the cache's budget may evict that entry at once, and the header facts alone lack the camera colour Auto uses. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/engine/src/lib.rs | 36 +++-- crates/engine/src/media/cache.rs | 6 + crates/engine/src/media/session.rs | 33 +++++ crates/engine/src/sync_same.rs | 132 +++++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/autosync_wb.rs | 189 +++++++++++++++++++++++++ docs/parity-checklist.md | 5 +- 7 files changed, 391 insertions(+), 11 deletions(-) create mode 100644 crates/engine/src/sync_same.rs create mode 100644 crates/engine/src/tests/autosync_wb.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 73677df004..33397f8476 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; @@ -947,8 +948,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) } @@ -989,13 +991,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() }; @@ -1017,18 +1018,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/media/cache.rs b/crates/engine/src/media/cache.rs index 238870c07a..925427d4e6 100644 --- a/crates/engine/src/media/cache.rs +++ b/crates/engine/src/media/cache.rs @@ -221,6 +221,12 @@ impl MediaCache { self.insert_source(id, level, DecodedSource::new(img, None)); } + /// 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(super) fn insert_source(&mut self, id: PhotoId, level: SourceLevel, img: DecodedSource) { let tick = lightcraft_preview::next_tick(); match level { diff --git a/crates/engine/src/media/session.rs b/crates/engine/src/media/session.rs index 3fac3b6777..3dda3f9a67 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -514,4 +514,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/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 4878ea4976..b5f08f6ae1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7,6 +7,7 @@ mod album_missing; mod album_order; mod album_remove; mod albums_local; +mod autosync_wb; mod color; mod constrain_crop; mod crop_angle; 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/docs/parity-checklist.md b/docs/parity-checklist.md index 285837a696..866f96e29f 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-05 · **Change:** minor (LR-LIB-FLAG: a flag or rating never waits for the drive, PERF-STEP-STALL; before: 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 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (LRC-DEV-AUTOSYNC: white balance syncs on each photo's own scale, As Shot and Auto per photo; before: 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 @@ -724,7 +724,7 @@ 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) | | @@ -799,6 +799,7 @@ 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 | From fc97c728644d399843d8201f83d25ccf81b89669 Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Thu, 5 Nov 2026 06:15:05 +0100 Subject: [PATCH 28/39] LR-BEHAV-RENDER-FIDELITY: calibrated Contrast and Blacks in process V3 (#523) (#1383) * LR-BEHAV-RENDER-FIDELITY: split V3 Contrast and Blacks Port calibrated global Contrast and Blacks with shared CPU and GPU tables. Preserve V2 Whites, local adjustments, other source paths, and all V1 and V2 renders and persistent cache keys. Generate the constants from public Contrast and Blacks fits. Cover numeric references, legacy renders, keys that include the resolved process, windows and GPU parity. Document the measurements, limits and provisional number. Co-Authored-By: Codex * LR-BEHAV-RENDER-FIDELITY: reduce V3 preview cost and sanitize fits Compose calibrated CPU preview operators over linear input and skip unused mix endpoints. Keep high-bit-depth exports on the original operator path. Require three distinct photos per published error group and band, regenerate the fit hashes, and cover the sanitizer with synthetic tests. Document release measurements and identify the separate measurement tool proposed in #1181. Co-Authored-By: Codex * LR-BEHAV-RENDER-FIDELITY: preserve V3 luminance evaluation Retain the original operator evaluation for luminance mixes, including preceding Contrast, so preview interpolation cannot change the cutoff. Keep the fused per-channel path and exact deep exports. Add CPU and GPU regressions for both uniform cutoff fixtures. Document the measured CPU cost of positive Blacks and the retained fused path. Co-Authored-By: Codex * LR-BEHAV-RENDER-FIDELITY: finish split-module integration Import the persistent process-key helper directly in the session module. Keep the existing V3 operator selection and evaluation order in an inline helper so the combined finish-stage closure stays within the complexity limit. Refresh the V1/V2 golden hashes only after the exact fixture produces identical hashes on plain current main. Keep the cross-platform legacy samples unchanged. Co-Authored-By: Claude Opus 5.5 * LR-BEHAV-RENDER-FIDELITY: date the calibrated Light gap summary Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Codex Co-authored-by: Claude Opus 5.5 Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- .gitignore | 3 + crates/develop/src/settings.rs | 9 +- crates/engine/src/media/session.rs | 20 +- crates/engine/src/media/settings_hash.rs | 17 +- .../engine/src/media/thumbnail_hash_tests.rs | 72 ++ crates/gpu/src/ctx.rs | 12 +- crates/gpu/src/params.rs | 25 +- crates/gpu/src/wgsl/finish.wgsl | 57 +- crates/gpu/tests/it/equivalence.rs | 104 ++- crates/pipeline/src/finish.rs | 37 +- crates/pipeline/src/lib.rs | 8 + crates/pipeline/src/light_v3.rs | 439 +++++++++++ crates/pipeline/src/light_v3_params.rs | 315 ++++++++ crates/pipeline/src/local.rs | 4 +- crates/pipeline/src/tests_legacy.rs | 127 ++++ crates/pipeline/src/tests_light.rs | 514 +++++++++++++ docs/gaps.md | 5 +- docs/gpu-pipeline.md | 5 + docs/light-v3.md | 187 +++++ docs/parity-checklist.md | 17 +- docs/process-versions.md | 18 +- tools/light_v3_constants.py | 228 ++++++ tools/light_v3_family.py | 78 ++ tools/light_v3_fits/blacks.json | 629 ++++++++++++++++ tools/light_v3_fits/contrast.json | 688 ++++++++++++++++++ tools/requirements-light-v3.txt | 3 + tools/test_light_v3_constants.py | 69 ++ 27 files changed, 3654 insertions(+), 36 deletions(-) create mode 100644 crates/pipeline/src/light_v3.rs create mode 100644 crates/pipeline/src/light_v3_params.rs create mode 100644 crates/pipeline/src/tests_legacy.rs create mode 100644 crates/pipeline/src/tests_light.rs create mode 100644 docs/light-v3.md create mode 100644 tools/light_v3_constants.py create mode 100644 tools/light_v3_family.py create mode 100644 tools/light_v3_fits/blacks.json create mode 100644 tools/light_v3_fits/contrast.json create mode 100644 tools/requirements-light-v3.txt create mode 100644 tools/test_light_v3_constants.py 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/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index f422bba08b..201b33d5f0 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -86,18 +86,23 @@ pub enum Process { 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; 3] = [Process::V1, Process::V2, Process::V3]; - pub const LATEST: Process = Process::V3; + 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/src/media/session.rs b/crates/engine/src/media/session.rs index 3dda3f9a67..5b6cb9c028 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}; @@ -64,7 +65,8 @@ impl crate::Session { ^ lens.rotate_left(29); 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); @@ -117,12 +119,8 @@ impl crate::Session { /// Cache key of a variant thumbnail ([`Self::variant_job`]). pub fn variant_key(p: &Photo, settings: &DevelopSettings, edge: usize) -> 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()); let lens = super::quick::lens_key(p); if lens != 0 { k.u64(lens); @@ -240,12 +238,8 @@ impl crate::Session { /// included as in [`Self::variant_key`]. pub(crate) fn view_key(p: &Photo, apply_crop: bool) -> 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()); let lens = super::quick::lens_key(p); if lens != 0 { k.u64(lens); 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/thumbnail_hash_tests.rs b/crates/engine/src/media/thumbnail_hash_tests.rs index dccc6c28c0..2ca0f5cab5 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), Some("view"), 1), + (crate::Session::variant_key(&p, &newer, 256), 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) == before_v3(Some("view"), 1), + crate::Session::variant_key(&p, &settings, 256) == 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(); diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index ff1e287082..640ef28b77 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -365,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(", ")); } @@ -380,6 +388,8 @@ 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"); diff --git a/crates/gpu/src/params.rs b/crates/gpu/src/params.rs index 6d7f025dfa..af61cf6c78 100644 --- a/crates/gpu/src/params.rs +++ b/crates/gpu/src/params.rs @@ -94,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). @@ -160,7 +167,7 @@ pub struct Present { } /// 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()); @@ -177,12 +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); diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl index a7f74b80cb..834de14141 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++) { @@ -507,6 +557,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) { diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 01686b034c..7a21768de1 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -31,6 +31,47 @@ fn gpu() -> bool { 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() { @@ -649,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. @@ -681,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"); diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index 65d7976bac..22ef07bc7b 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -180,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]>, @@ -271,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), @@ -323,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. @@ -335,6 +341,12 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap { 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), + }, } } @@ -415,7 +427,7 @@ pub(crate) fn finish_with( ) -> 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); @@ -424,6 +436,7 @@ pub(crate) fn finish_with( 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]; @@ -466,6 +479,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 { @@ -593,6 +609,23 @@ pub(crate) fn finish_with( 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)>, @@ -817,7 +850,7 @@ 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; diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index 2c7700ed4c..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; @@ -778,6 +782,10 @@ 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; 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 547131b8bf..22c17571f9 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -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 | Process::V3 => base_detail_radius(px_per_long), + Process::V2 | Process::V3 | Process::V4 => base_detail_radius(px_per_long), } } 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/docs/gaps.md b/docs/gaps.md index 404dd37be3..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-11-05 · **Change:** minor (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) +> **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) | @@ -129,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 ac09990036..42b3578860 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 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 866f96e29f..ced72e47cf 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -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 @@ -179,11 +179,11 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | 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, 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`) | | @@ -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) | @@ -729,7 +729,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | 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 | ⬜ | | | @@ -878,6 +878,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 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-EDIT-OPTICS-PROFILE: Sony ARW shading, CA and distortion tables decoded with settings and provenance (raw IFD, `SR2SubIFD` fallback); applied corrections unchanged (ILCE-7RM4A and ILCE-7RM6 distortion); status unchanged (🟡) | diff --git a/docs/process-versions.md b/docs/process-versions.md index 318e6d8931..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; @@ -9,7 +11,8 @@ stronger Light sliders, issue #196) without changing a single photo someone has |---|---| | **V1** | LightCraft's rendering from before process versions existed. Frozen. | | **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** (the latest) | 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. | +| **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 @@ -74,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. @@ -89,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/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() From 2e66a00d554508341a83f0942b9224f2161f2ba8 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 5 Nov 2026 06:39:08 +0100 Subject: [PATCH 29/39] Tests: two catalog flakes; a readback waits as long as a render (#3777) a_failed_write_is_held_reported_and_retried raced the log thread: it could fail the first append before the second arrived, which is then refused by design. The test now hands both over in one append. a_file_path_rule_allocates_nothing_per_photo counted heap blocks on every thread, so the test harness's own thread could fail it (four blocks, on PRs that don't touch this code). An allocation per photo is thousands, so the bound stays far below that. read_texture waited 10 s where the render path waits 60 s, so a view could be dropped from a headless screenshot while earlier work ran. The GPU guide now says what the code does about the window's card. Co-authored-by: Claude Opus 5.5 --- crates/catalog/src/tests_log_thread.rs | 4 ++-- crates/catalog/tests/path_fold_heap.rs | 5 ++++- crates/gpu/src/ctx.rs | 3 ++- crates/gpu/src/lib.rs | 2 +- docs/gpu-pipeline.md | 8 ++++---- 5 files changed, 13 insertions(+), 9 deletions(-) diff --git a/crates/catalog/src/tests_log_thread.rs b/crates/catalog/src/tests_log_thread.rs index b7da3f7090..9c78d61f69 100644 --- a/crates/catalog/src/tests_log_thread.rs +++ b/crates/catalog/src/tests_log_thread.rs @@ -106,8 +106,8 @@ fn a_failed_write_is_held_reported_and_retried() { 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(()) })); - store.append(LOG, b"1\n").unwrap(); - store.append(LOG, b"2\n").unwrap(); + // (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}"); 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/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index 640ef28b77..2735116e39 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -895,7 +895,8 @@ pub(crate) fn read_texture( slice.map_async(wgpu::MapMode::Read, move |r| { let _ = tx.send(r); }); - let wait = std::time::Duration::from_secs(10); + // (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(())) => {} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index c187a764ed..8863b45a04 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -606,7 +606,7 @@ pub fn adopt_window_device(device: wgpu::Device, queue: wgpu::Queue, info: wgpu: /// 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 few seconds); `Err` when the copy or +/// 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( diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index 42b3578860..6e063e6f90 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -64,10 +64,10 @@ Overrides (read once at launch): (`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 stays on the card that drives the screen, - and rendering runs on a device of its own on the chosen card (the photo is copied to the screen's - card); a build that lets rendering share the window's device does so only when the variable names - the window's card (`backend::may_adopt_window_device`). The log's `gpu: LIGHTCRAFT_GPU_ADAPTER=…: using …` line names the card + 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 From 56d1cc28652d1dd37f21b846755b88999197bb4a Mon Sep 17 00:00:00 2001 From: stephen schuresko Date: Thu, 5 Nov 2026 00:47:45 -0500 Subject: [PATCH 30/39] pipeline: apply 8x8 ordered Bayer dithering to prevent display banding (#3509) * pipeline: apply 8x8 ordered Bayer dithering to prevent display banding Quantizing float linear/display pixel values to 8-bit integers using round-to-nearest produces noticeable Mach bands and contour stepping on smooth gradients (skies, shallow depth-of-field backgrounds, skin tones). This applies an 8x8 ordered Bayer dithering pattern centered around round-to-nearest with sub-LSB amplitude in both CPU finish (crates/pipeline) and GPU compute shader (crates/gpu/src/wgsl/finish.wgsl). Exact integer levels, pure black, and white remain noise-free, while fractional gradients smoothly dissolve into continuous gradations. Dithering coordinates account for window/tile view offsets to maintain phase alignment across zoom tiles. * pipeline, gpu: address review feedback on Bayer dithering - Always pack VIG_VIEW in GPU params so windowed renders without a vignette maintain the correct absolute view origin for Bayer dithering coordinates. - Restore the full Bayer threshold range (0..1) without deadzones, preserving float white via direct half-LSB rounding to prevent edge quantization drop. - Return the true sampled bounds midpoint in geometry sub-pixel edge detector fallbacks. - Add docstrings to satisfy coverage checks. * pipeline, gpu: narrow highlight white guard to allow dithering on 254.5 * tests(pipeline): assert edge contrast in manual keystone tracking windows * docs(pipeline): add docstrings to touched test functions * Export tests: count distinct levels however the dither orders them * Mask geometry tests ignore a level of 8-bit dither --------- Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/engine/src/export/tests.rs | 2 + crates/gpu/src/params.rs | 2 +- crates/gpu/src/wgsl/finish.wgsl | 24 ++++- crates/pipeline/src/finish.rs | 114 ++++++++++++++++++--- crates/pipeline/src/tests_geometry.rs | 29 ++++++ crates/pipeline/src/tests_mask_geometry.rs | 9 +- 6 files changed, 161 insertions(+), 19 deletions(-) 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/gpu/src/params.rs b/crates/gpu/src/params.rs index af61cf6c78..8c8624a23c 100644 --- a/crates/gpu/src/params.rs +++ b/crates/gpu/src/params.rs @@ -257,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); @@ -266,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 { diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl index 834de14141..9e589f4ca9 100644 --- a/crates/gpu/src/wgsl/finish.wgsl +++ b/crates/gpu/src/wgsl/finish.wgsl @@ -326,8 +326,23 @@ fn lut_apply(c: vec3) -> vec3 { return mix(mix(c00, c10, fr.y), mix(c01, c11, fr.y), fr.z); } -fn enc8(v: f32) -> u32 { - return u32(clamp(v, 0.0, 1.0) * 255.0 + 0.5); +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). @@ -662,5 +677,8 @@ fn main(@builtin(global_invocation_id) gid: vec3) { 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/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index 22ef07bc7b..5a9c51b8cf 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -350,6 +350,7 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap { } } +/// Finish the prepared pipeline stages into an 8-bit RGBA image in `space` (or `display`). pub(crate) fn finish( p: &Prepared, s: &DevelopSettings, @@ -367,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 } @@ -395,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))))), }); @@ -423,7 +427,7 @@ 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(); @@ -432,6 +436,7 @@ pub(crate) fn finish_with( 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; @@ -603,7 +608,7 @@ 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 @@ -857,10 +862,35 @@ pub(crate) fn encode_srgb(lut: &[f32; SRGB_LUT_N + 1], v: f32) -> 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)] @@ -902,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/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_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. From 8972565249b496ccdf3a7f23321c84622615a353 Mon Sep 17 00:00:00 2001 From: OneSlip Date: Thu, 5 Nov 2026 16:09:30 +1000 Subject: [PATCH 31/39] LR-PROF-IMPORT: import the user's own DNG camera profiles (.dcp) (#1063) * LR-PROF-IMPORT: import the user's own DNG camera profiles (.dcp) profile.import (File > Import Profiles & Presets, drag & drop) now also reads DNG Camera Profiles: the user's own .dcp files, e.g. made with a colour-checker tool. They appear in the profile browser and menu under Camera Profiles with dcp:- ids; profiles.camera lists them and profile.deleteCamera / profile.deleteImported remove them. A library on disk keeps a copy in Profiles/. No profile ships with the app and the repository holds none: tests build theirs in memory (write_dcp). lightcraft_raw::dcp parses the file per DNG spec ch. 6 (magic RC in place of 42; IFD 0 read through the existing DNG colour builders) and DcpProfile::applied_to puts its matrices, illuminants and look in place of a raw file's, keeping the shot's white balance, analog balance and baseline exposure. Choosing one (develop.profile) replaces the raw file's colour model when it is decoded, before the starting colour and the white-balance scale (WbScaleOf) are worked out, so the matrix path takes over from the fitted JPEG look (CR3/CR2/ARW...) and white balance follows the profile. A profile without a tone curve of its own (most chart-made ones) keeps the photo's contrast: the DNG's tone curve, else the tone of the camera-JPEG fit. The profile travels with SourceRef::File into FileLoader / PairLoader (new Option<&DcpProfile> argument); a decoded source records the profile it was made with and is not reused for another. Smart previews and the web render worker keep the file's own colour; rendered (non-raw) photos ignore it. This reverses the documented "Adobe profile formats deliberately unsupported" stance for user-supplied files only; docs updated. Split out of #1012. Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: build against upstream main (kelvin_presets, 3-arg loaders) DcpProfile::applied_to keeps the file's white-balance presets (new ColorData::kelvin_presets upstream): they are camera facts like as-shot neutral. Upstream's new FileLoader test closures take the profile argument. Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: hover previews and browser thumbnails develop the hovered camera profile The loupe's hover preview (preview_job) and the profile browser's thumbnails (variant_job) took the photo's own decoded source, so hovering an imported camera profile showed the built-in colour (and hovering a built-in profile while one was applied kept the camera profile's). Both now decode as the hovered settings develop: the source follows the settings' camera profile, as the main render does, and a variant's cache key already follows its settings. Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: build against upstream main (face-tile test loader and render_bench take the camera profile) Co-Authored-By: Claude Opus 5.5 * CI: the catalog's staging-link test module is Unix-only (unused import broke clippy on Windows) Co-Authored-By: Claude Opus 5.5 * CI: same-folder export test expects the '/'-joined subfolder (failed on Windows) Co-Authored-By: Claude Opus 5.5 * CI: folder-drop tests build widget ids with the Folders tree's '/' paths (failed on Windows) Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: rustfmt after merging main Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: a real D750 camera profile as a pinned test corpus, checked against Lightroom dieli's CC0 Nikon D750 ColorChecker set (Calibrite PROFILER dual-illuminant DCP, matrix-only; the two chart NEFs; Lightroom Classic 15.6 renders with the profile) is fetched by cargo xtask corpus --download into corpus/d750-colorchecker/, pinned to commit f37f4054 and by sha256; nothing is committed. Tests (skip without the corpus): the profile parses as matrix-only with Cool White Fluorescent + D55; the matrices blend by inverse temperature; the matrix-only path inverts the colour matrix and adapts to D50; it takes over the chart NEFs' colour; imported and applied end to end, the charts develop within mean dE2000 3.84 (flash) / 3.35 (indoor) of Lightroom's renders. Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: a single .dcp file is a camera profile only, not also an unreadable LUT profile.import read every plain file that was neither a folder nor a .zip as a .cube LUT, so importing one .dcp imported the camera profile and also reported it as failed ("stream did not contain valid UTF-8"). Only .cube files are read as LUTs now. Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: review fixes for imported camera profiles - A library moved or restored elsewhere finds its camera profiles in its own Profiles/ folder. - A grid thumbnail is cut from the decoded preview only when that preview used the same camera profile. - Render and source cache keys carry a fingerprint of the profile file, so a deleted or replaced profile never has its old renders stand in. - Camera profiles can be favourites, and favourites/recent entries survive reopening the library. Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: smart previews without the camera profile, current-profile source facts, unsupported files reported CodeRabbit review of 4ef025d9: - Build Smart Previews develops the proxy without the photo's imported camera profile and never takes a cached source decoded with it (the denoised picture is kept); before, only the stale-proxy refresh left it out. - Session::source_info reports decoder facts only from a cached source developed with the camera profile the photo uses now, else the catalog's. - profile.import reports a file that is neither .cube, .dcp nor .zip as failed instead of passing over it. Each with a regression test in tests_dcp.rs. Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: the Before side decodes with its own camera profile; a failed profile copy fails that file only - build_job (and region_job_before through it) picks the Before render's source with the Before settings, so it never reuses or decodes a source developed with the edit's camera profile. - profile.import: a .dcp whose copy into the library fails is reported in `failed`; the profiles imported with it stay imported and are saved, and nothing half-written is left. Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: a cached smart preview stands in while the original is offline A smart preview carries no camera profile, so with an imported profile the profile check rejected the cached proxy and every render decoded it again (it gives the same picture). It now stands in, for its own level and for the thumbnail cut from it, while the original is known to be offline; otherwise the profile check is as before, so once the original is back the photo is decoded from it with its profile. Photos without an imported profile keep main's behaviour. Test `tests_dcp::a_cached_smart_preview_stands_in_while_the_original_is_offline` (fails without the fix). Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: deleting a camera profile removes the library's copy before forgetting it profile.deleteCamera now removes the library's copy of the profile file first. A copy that is already gone is fine; any other error (file in use, no access) fails the command and keeps the profile listed, so the library never holds a profile file it no longer lists. Test: a_profile_whose_copy_cannot_be_deleted_stays. Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: deleting a camera profile never follows `..` out of the profiles folder A listed path with a `..` component can start with the profiles folder and still lead out of it; such a path is not treated as the library's copy, so deleting the profile leaves that file alone. Test: deleting_a_profile_never_follows_dot_dot_out_of_the_profiles_folder. Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: both tone fits of a DNG see its lens opcodes; no side effect in the profile-tag comparison Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: a hover preview's key carries the camera profile file's fingerprint Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: unusable camera profiles not offered; file's WB scale and the profile's tone kept Review of #1063 (CodeRabbit, outside-diff findings): - a camera profile whose file is missing or damaged when the library opens is no longer offered in the profile browser or accepted by develop.profile (it silently developed with the raw's own colour); the entry stays, so it is offered again once the file is back. - a raw on the relative white-balance scale stays relative with a camera profile (its matrices turned it to Kelvin, so existing edits were read as absolute temperatures and the catalog and quick previews disagreed). - with a camera profile its tone curve, then the tone kept for a curve-less profile, come before the fitted camera look's tone. Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: one Camera Profiles group; the web loader keeps a raw's own colour Review of #1063 (CodeRabbit): - a LUT group named "Camera Profiles" that didn't sort last made the profile menu list that group twice; it is now one group, last, with both kinds. - without web workers a render ran inline and the web loader applied the selected camera profile, unlike the worker (the documented web behaviour keeps the raw's own colour); the loader now leaves it out. Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: camera profile files are read at most to the 64 MiB limit A .dcp larger than the parser accepts was read whole into memory before being refused. One bounded read (lightcraft_raw::dcp::read_dcp) stops one byte past the limit and is used for import, reopening a library and the duplicate check. Co-Authored-By: Claude Opus 5.5 * LR-PROF-IMPORT: a test that a hostile hue/saturation map header in a camera profile drops the map (FredApps, #1063) Dimensions far past the data, past u32 products or zero, an entry count of 4 billion values and a data offset past the end each drop the map while the profile's matrix still reads. Co-Authored-By: Claude Opus 5.5 * Docs: parity checklist keeps both sides of the merge * LR-PROF-IMPORT: tests added on main take the file loader's camera-profile argument * Merge main; a thumbnail test takes the file loader's camera-profile argument * Docs: one camera colour row, with main's notes and the import note * Process key tests take the profile salt argument --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- Cargo.lock | 2 + apps/lightcraft-web/Cargo.toml | 2 + apps/lightcraft-web/src/store.rs | 66 +- crates/engine/examples/render_bench.rs | 2 +- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/dcp_profiles.rs | 212 +++++++ crates/engine/src/cmd/develop.rs | 12 +- crates/engine/src/cmd/lut_profiles.rs | 16 +- crates/engine/src/cmd/previews.rs | 18 +- crates/engine/src/cmd/similar.rs | 2 +- crates/engine/src/files.rs | 4 +- crates/engine/src/files/fs.rs | 11 +- crates/engine/src/files/load.rs | 189 +++++- crates/engine/src/files/tests.rs | 8 +- crates/engine/src/import/job/tests.rs | 2 +- crates/engine/src/lib.rs | 3 + crates/engine/src/library.rs | 11 +- crates/engine/src/media.rs | 21 + crates/engine/src/media/cache.rs | 94 ++- crates/engine/src/media/session.rs | 65 +- crates/engine/src/media/source.rs | 36 +- crates/engine/src/media/tests.rs | 6 +- .../engine/src/media/thumbnail_hash_tests.rs | 14 +- crates/engine/src/presets.rs | 45 +- crates/engine/src/smart.rs | 1 + crates/engine/src/tests.rs | 2 + crates/engine/src/tests/dcp.rs | 563 ++++++++++++++++++ crates/engine/src/tests/dcp_corpus.rs | 243 ++++++++ crates/engine/src/tests/face_tiles.rs | 4 +- crates/engine/src/tests/import.rs | 10 +- crates/engine/src/tests/lens_refresh.rs | 2 +- crates/raw/src/dcp.rs | 335 +++++++++++ crates/raw/src/lib.rs | 1 + crates/raw/tests/dcp_corpus.rs | 148 +++++ .../ui-egui/examples/thumb_request_bench.rs | 2 +- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/menus/run.rs | 12 +- crates/ui-egui/src/panels/edit/sliders.rs | 16 +- crates/ui-egui/src/panels/profiles.rs | 14 +- crates/ui-egui/src/pick.rs | 2 +- crates/ui-egui/src/render/thumbnail_tests.rs | 14 +- crates/ui-egui/src/tests/find_similar.rs | 4 +- docs/file-format-parity.md | 5 +- docs/parity-checklist.md | 8 +- docs/raw-parity.md | 6 +- docs/roadmap.md | 5 +- docs/xmp-interop.md | 19 +- xtask/src/corpus.rs | 98 ++- 48 files changed, 2188 insertions(+), 171 deletions(-) create mode 100644 crates/engine/src/cmd/dcp_profiles.rs create mode 100644 crates/engine/src/tests/dcp.rs create mode 100644 crates/engine/src/tests/dcp_corpus.rs create mode 100644 crates/raw/src/dcp.rs create mode 100644 crates/raw/tests/dcp_corpus.rs diff --git a/Cargo.lock b/Cargo.lock index c04455a37f..1d0bb2bdc2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4066,9 +4066,11 @@ dependencies = [ "egui", "js-sys", "lightcraft-codecs", + "lightcraft-color", "lightcraft-engine", "lightcraft-preview", "lightcraft-raster", + "lightcraft-raw", "lightcraft-ui-egui", "log", "serde", 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/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 6ba113b35e..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; @@ -154,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/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/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 index b8af1b2494..fd608ac2b7 100644 --- a/crates/engine/src/cmd/similar.rs +++ b/crates/engine/src/cmd/similar.rs @@ -232,7 +232,7 @@ mod tests { s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); } let seen = files.clone(); - s.media.file_loader = Some(Arc::new(move |path: &str, _| { + 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; 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/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 33397f8476..f71f9becd1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -360,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 @@ -519,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(), diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index bbe590fd3f..23e333c4ca 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -285,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, @@ -576,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; @@ -603,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(); } @@ -886,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 93395576c1..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; @@ -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 925427d4e6..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), @@ -227,7 +230,7 @@ impl MediaCache { self.insert_source(id, level, DecodedSource::new(img, Some(info))); } - pub(super) fn insert_source(&mut self, id: PhotoId, level: SourceLevel, img: DecodedSource) { + pub(crate) fn insert_source(&mut self, id: PhotoId, level: SourceLevel, img: DecodedSource) { let tick = lightcraft_preview::next_tick(); match level { SourceLevel::Thumb => { @@ -302,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() }; } @@ -342,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 @@ -360,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/session.rs b/crates/engine/src/media/session.rs index 5b6cb9c028..ac1b8145a9 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -42,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) @@ -53,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) @@ -62,7 +70,8 @@ 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); @@ -71,6 +80,10 @@ impl crate::Session { 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); @@ -104,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() @@ -112,15 +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); 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); @@ -134,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(), @@ -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, @@ -235,11 +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); 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); @@ -252,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) } @@ -361,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)) }) @@ -493,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. diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index c1ee14ca89..f13349f18c 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -1,4 +1,4 @@ -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 = 75; @@ -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 2ca0f5cab5..85089d231d 100644 --- a/crates/engine/src/media/thumbnail_hash_tests.rs +++ b/crates/engine/src/media/thumbnail_hash_tests.rs @@ -37,8 +37,8 @@ fn persistent_keys_name_the_process_the_settings_render_with() { 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), Some("view"), 1), - (crate::Session::variant_key(&p, &newer, 256), Some("variant"), 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"); @@ -69,8 +69,8 @@ fn v1_and_v2_photos_keep_the_render_cache_keys_they_had() { }; let keys = [ s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1 == before_v3(None, 256), - crate::Session::view_key(&p, true) == before_v3(Some("view"), 1), - crate::Session::variant_key(&p, &settings, 256) == before_v3(Some("variant"), 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"); @@ -142,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 @@ -166,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() }; @@ -204,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/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/tests.rs b/crates/engine/src/tests.rs index b5f08f6ae1..a22547ec4a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12,6 +12,8 @@ mod color; mod constrain_crop; mod crop_angle; mod crop_aspect; +mod dcp; +mod dcp_corpus; mod denoise; mod export; mod face_models; 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/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 18a9659618..e1c6dacd62 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/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/examples/thumb_request_bench.rs b/crates/ui-egui/examples/thumb_request_bench.rs index a4e869805c..ada42356de 100644 --- a/crates/ui-egui/examples/thumb_request_bench.rs +++ b/crates/ui-egui/examples/thumb_request_bench.rs @@ -168,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/lib.rs b/crates/ui-egui/src/lib.rs index a43eda66dc..00311afd33 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -547,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 ccfb85d0a7..730bde3df4 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -2039,16 +2039,24 @@ fn file_import_presets_command(app: &mut LightcraftApp, ctx: &egui::Context, id: Ok(paths) => 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/edit/sliders.rs b/crates/ui-egui/src/panels/edit/sliders.rs index b24fae8b8e..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); } }); }); diff --git a/crates/ui-egui/src/panels/profiles.rs b/crates/ui-egui/src/panels/profiles.rs index c95e8d7a76..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 { 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/thumbnail_tests.rs b/crates/ui-egui/src/render/thumbnail_tests.rs index 922a9b8a47..7a2cb1a6a9 100644 --- a/crates/ui-egui/src/render/thumbnail_tests.rs +++ b/crates/ui-egui/src/render/thumbnail_tests.rs @@ -83,7 +83,7 @@ fn each_render_request_and_how_it_ended_is_a_debug_line_with_its_file() { // 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()))); + 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); @@ -394,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(); @@ -441,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())) @@ -590,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); @@ -616,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); @@ -799,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| { @@ -1035,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/find_similar.rs b/crates/ui-egui/src/tests/find_similar.rs index 4ac537dc28..b75995a1ca 100644 --- a/crates/ui-egui/src/tests/find_similar.rs +++ b/crates/ui-egui/src/tests/find_similar.rs @@ -40,7 +40,7 @@ fn app_on_a_slow_drive(guard: Duration) -> (Headless, Drive) { 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, _| { + 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)) { @@ -195,7 +195,7 @@ fn a_search_that_cannot_start_leaves_no_row() { #[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.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(); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 8bf7d6d6ff..dd3c3c3911 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/parity-checklist.md b/docs/parity-checklist.md index ced72e47cf..2758969b26 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-05 · **Change:** minor (LRC-DEV-AUTOSYNC: white balance syncs on each photo's own scale, As Shot and Auto per photo; before: 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 +> **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 @@ -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) @@ -875,6 +875,8 @@ 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 (🟡) | 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/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/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}"); } } } From eaef01e986537152809f4973bd564b7175b1a46f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 5 Nov 2026 07:44:24 +0100 Subject: [PATCH 32/39] Light tests allow a level of 8-bit dither (#3779) Process V4's tests and the 8-bit dither landed separately, and each passed its own gate: a flat source now varies by a level, and a ramp can step back by one. The tests compared exact 8-bit values. Co-authored-by: Claude Opus 5.5 --- crates/pipeline/src/tests_light.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/pipeline/src/tests_light.rs b/crates/pipeline/src/tests_light.rs index 2b85a98043..c6ea984c49 100644 --- a/crates/pipeline/src/tests_light.rs +++ b/crates/pipeline/src/tests_light.rs @@ -38,7 +38,8 @@ fn check_luminance_cutoff(chroma: f32, pixel: [f32; 3], expected: [u8; 4]) { 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])); + // (8-bit output is dithered: a flat source varies by a level) + assert!(image.data.iter().all(|p| p.iter().zip(image.data[0]).all(|(a, b)| a.abs_diff(b) <= 1))); for (actual, expected) in image.data[0].into_iter().zip(expected) { assert!(actual.abs_diff(expected) <= 1, "chroma {chroma}: {:?}, expected {expected}", image.data[0]); } @@ -311,7 +312,8 @@ fn v3_sliders_move_a_grey_ramp_their_way() { ("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"); + // (within a level of 8-bit dither) + assert!(r.windows(2).all(|w| luma(w[1]) >= luma(w[0]) - 1), "{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)); From 61005f3dc119625608d357a1dbb57d4f67ce3ccb Mon Sep 17 00:00:00 2001 From: OneSlip Date: Thu, 5 Nov 2026 17:32:26 +1000 Subject: [PATCH 33/39] Culling: the loupe uses built previews; photos prepared ahead and in the background (#3077) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * PERF-CULL-0: ui.inspect reports how the loupe showed each photo it was stepped to perf.loupeSteps records, per step, the ms from the step to the first frame with anything of the photo, with a full-size picture (camera JPEG, cached or rendered) and with LightCraft's own render, measured on the frames the app draws, so culling benchmarks exclude the control channel's round trip. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 95f0343848fc0a238f80f07ceb292eaf6779aeaa) * PERF-CULL-1: browsing a folder shows its first photos within a second The Local view read and hashed every file of the folder before showing any of them (2,933 EOS R5 C CR3s: 30.6 s to the first photo). It now hands the files the library lacks straight to the import, ordered the way the view sorts them (file time for the date sorts), which adds them batch by batch: first photo 0.9 s, twelve thumbnails 1.4 s, the whole folder in the same ~34 s as before, in the background. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit b766558e7ef4f802919a144da53e444f70e0186b) * PERF-CULL-2: the loupe makes the next photos' camera previews ahead of the step Culling steps through photos, and each step waited for the next raw's embedded JPEG to be read and decoded (p50 187 ms, p95 332 ms on EOS R5 C CR3s) and then for a full raw develop. Now: - the loupe's stand-ins for the next five photos in the direction of travel and the one behind are made ahead (Slot::QuickAhead, priority just below the loupe's own render) and taken over at the step, so a step shows the camera JPEG at once (p50 0 ms); - a slot keeps its photo while the photo stays wanted, so photos that shift places as the user steps are not made twice; - decoded camera JPEGs stay in the memory LRU (never on disk), so going back shows them again without a decode; - while an arrow key is held (a photo left within 0.25 s), the raw develop waits until the photo has stayed 0.12 s, and a render queued for a photo already left is dropped, so the workers make the previews instead of renders nobody sees. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 0430b95636d2b6adce8887af7b9464687c95549e) * PERF-CULL-3: CR3 previews take the smallest embedded JPEG that covers the view; plain sRGB JPEGs decode straight to 8-bit Upstream's embedded_preview_covering (14e0d128) picks the smallest covering JPEG of a TIFF-based raw; this extends it to Canon CR3 and adds the 8-bit decode: - A CR3 keeps an 8192 px JPEG track, a 1620 px PRVW box and a 160 px THMB. embedded_preview_covering now picks among the three (cr3_boxes lists the boxes), so a grid thumbnail or a loupe up to 1620 px decodes the PRVW. Loader at 1280 px on 20 EOS R5 C CR3s: 168-322 ms -> 31 ms a photo. - lightcraft_codecs::decode_jpeg_srgb8_fit decodes a plain 8-bit sRGB JPEG (DCT-scaled) and box-averages it in linear light straight into 8-bit sRGB, without the float image the general path builds; anything with an ICC profile, an Adobe RGB declaration, CMYK or 12-bit takes the general path. 45 MP preview fitted to 2560 px: 182 -> 151 ms (min of 15, loaded machine). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit a67bb398c2f438cbe16f4db1431ae0270f1c8b04) * PERF-CULL-4: Camera preview label; thumbnails ahead of the step; 100 % shows the camera JPEG first - While the loupe shows a raw's embedded JPEG (or its thumbnail), a small 'Camera preview' label at the top right says so, with what that means on hover (widget loupe:cameraPreview; nine languages), so colour and tone are not judged on the camera's rendering. - The look-ahead also asks for the next photos' thumbnails (a small embedded JPEG each), so a held arrow key has something to show in full screen too, where no filmstrip asks for them (2400x1500 window, 40 held steps: camera JPEG on 36, nothing on 2; before 1 and 4). Stepping through a whole wedding keeps at most 600 thumbnails, those around the open photo. - Zoomed in on an unedited raw, its camera JPEG at full size (8192 px for an EOS R5 C) is drawn under the window render until that arrives: 100 % in ~0.9 s instead of ~5.6 s; released when not zoomed. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 9f212b1e16815c3c0ca33130319a7ef41fb05a26) * PERF-CULL-5: lightcraft-cli bench-cull and tools/cull-bench.py time culling a real shoot bench-cull FOLDER (headless) times reading the folder into the Local view, the first screen of grid thumbnails on the app's render threads, camera previews at 1280 / 2560 px and full size, a cold 2560 px loupe render, rating 50 photos in a row and importing N files in place / copying M, as 'name: X ms wall' lines (p50, p95, n) and JSON. Libraries are made under --work; nothing is written next to the photos. tools/cull-bench.py drives the running app over the control channel (browse, first photo, steps at rest, a held arrow key, 100 % zoom, rating) and reads the app's own frame timings (perf.loupeSteps). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit bd2eaac591b72f8258acae4389c67aa4d1da3b27) * PERF-CULL-5: bench-cull --files K samples a slow folder; e2e test; cull-bench usage Co-Authored-By: Claude Opus 5.5 (cherry picked from commit c32c9556924ccdee6f8c103864df51c3e170df98) * PERF-CULL: docs for culling speed (parity rows, gap 26, preview reads, opening a photo) Co-Authored-By: Claude Opus 5.5 (cherry picked from commit fb69b5975b51f882d82b2ca684e0f7ddc8373908) * PERF-CULL: the whole-file preview decodes a plain sRGB camera JPEG the quick path's way Upstream's quick-path test wants the bounded read and the whole file to give the same picture byte for byte; with the branch's straight-to-8-bit decode on the quick path only, a 49 px preview came out differently. Both paths now take it. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 0c8acab4c2f3e85d1c51fab5faf62b6e997d7c73) * PERF-THUMB-FIRST: CR3 thumbnails decode the 1620 px PRVW copy, and grid thumbnails from camera JPEGs are kept in the thumbnail cache A CR3 grid thumbnail decoded the full-size JPEG track (45 MP, ~150 ms each) whatever size was asked; it now takes the smallest embedded copy that covers the cell (PRVW, same shape), and the box search stops at mdat (was a scan of the whole file). The decoded camera JPEG of an unedited raw is written to the library's thumbnail cache, so a folder seen before fills from small files. Measured on 250 R5 C raws (loaded machine): first screen fills in 294 ms (was 553), on a second visit 53 ms (was 610). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 12162f966dd859b7e53ac65b5c4564a8e837b7eb) * PERF-CULL: cargo fmt Co-Authored-By: Claude Opus 5.5 * PERF-CULL: docs for culling speed (parity rows LR-IMP-LOCAL, LR-IMP-PREVIEW-READ, LR-VIEW-DETAIL; gap 26) Co-Authored-By: Claude Opus 5.5 * PERF-CULL: review fixes (bench work folder, 8-bit APP1 cap, size sort) - bench-cull makes its libraries in a new folder of the run's own under --work and never deletes what is already there (it removed lib-browse, lib-add and lib-copy under a folder the caller named). - The 8-bit sRGB JPEG path refuses more than 128 APP1 segments before its decoders walk them again, as the general decode does. - Browsing by file size keeps unreadable files last in both directions (they were sized 0, so first when ascending). - --files K in the CLI synopsis and help. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: the loupe uses built previews; photos are prepared ahead and in the background Built standard previews were never what the loupe showed: it rendered every photo again (~1.8 s on a raw), the rendered previews in memory were capped at 128 MB (~84 photos) whatever the budget, the disk cache was a fixed 2 GB (a wedding's previews pruned each other), the cache's writer skipped disk writes when it fell behind, and Build Previews with one photo open built only that photo though the menu said "Visible". - The loupe's render job takes a cached view render of the same settings that is at least as big as asked for, fitted down (no render). - Memory for rendered previews is a quarter of the cache share; the disk cache's automatic size makes room for every photo (about 1.5 MB each); Settings offers Automatic, 50 GB and 200 GB. - A build skips photos whose previews are there, writes each to disk before counting it, builds at least the loupe's size, and with one photo selected builds the view. - Prepare photos in the background (Settings > Performance), per mode (culling, library, editing), app-wide (kept in ui.json) or per library: photos ahead rendered for the loupe (a few at a time, 0 = off) and the whole view's previews built in the spare time once the user steps through photos: two lanes, waiting while the photo on screen renders, nearest first in the direction of travel, one cancellable row, replaced by a build that is asked for. Commands prefs.backgroundPrep / prefs.setBackgroundPrep; ui.inspect perf.previewCache. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: the bench work-folder test removes only a folder it made Co-Authored-By: Claude Opus 5.5 * PERF-CULL: browsing keeps the whole listing for the folder bookkeeping; cull-bench stops on small folders The browse worker queues only the files the library lacks, but the folder bookkeeping (browse times, records of files gone) needs every file listed: a subfolder of known photos only was not stamped as browsed. The known files now come along marked as already in the library. tools/cull-bench.py stops waiting at min(12, photos) thumbnails. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: review fixes (smart previews honour id, editing builds by the Library row, lenient prep settings) - library.smartPreviews with an explicit id works on that photo, not the whole view. - While editing, the whole view's background build follows the Library row (its switch and which photos); the Editing row's scope is for the photos kept ready ahead. - The app-wide and per-library preparation settings are read leniently: a value this build doesn't know is the defaults (app) or none (library), and the other settings are kept. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: cull-bench counts twelve thumbnails while the folder is still loading Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: a view change stops the background build for the old view The running background build was only re-aimed at the photo on screen; after another folder, filter or library it went on building photos no longer shown. It is now stopped when the view's signature changes (not counted as stopped by the user), and the view now shown is prepared. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: cull-bench picks the thumbnail threshold from the final photo count Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: the view signature covers every photo; the view-change test holds the build explicitly Co-Authored-By: Claude Opus 5.5 * PERF-CULL: cull-bench stops waiting for twelve thumbnails 30 s after the folder loaded Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: in the marked scope, marking a photo changes what the view's build prepares Co-Authored-By: Claude Opus 5.5 * PERF-CULL: cull-bench times only the thumbnails the browse adds Thumbnails already cached before library.browse no longer count towards the first-thumbnail and twelve-thumbnail times. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: count every thumbnail made, for the browse benchmark thumbTextures counts resident thumbnails, and evicting old ones can hide new ones. The renderer now also counts each grid thumbnail it stores (perf.thumbsMade, never lowered by eviction), and cull-bench times the browse from that. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: the marked-scope test waits for its builds before cleaning up Both preview builds finish before the test library is removed, and the removal is checked, so no worker writes into a folder being deleted. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: stand-ins made ahead keep their order, size and photo Review fixes for the loupe's stand-ins and the browse benchmark: - a stand-in still queued ahead moves to its new place in the order when the user steps; - one made ahead still shows when the loupe's own request failed; - one made ahead for a smaller loupe isn't taken over by a larger one; - quick and full-size camera-preview keys include the photo, so a virtual copy gets its own; - perf.thumbsMade counts photos given a thumbnail, not a render replacing a stand-in. Each has a test that fails without it. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: a late stand-in never takes another photo's place in the loupe A stand-in made ahead takes over after the loupe's own request failed only while the loupe still wants that photo and has no other request pending; the test covers stepping on before it arrives. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: a stand-in made ahead and no longer wanted is dropped when it arrives Freeing a look-ahead slot whose job is already running now also forgets its request, so the late result isn't kept as a hidden texture, unless the loupe is waiting for exactly that stand-in. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: a running stand-in the loupe waits for keeps its look-ahead slot When the next look-ahead no longer wants the photo the loupe has just stepped to, the slot whose job is still making that photo's stand-in stays reserved instead of going to a new photo, so the result still reaches the loupe. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: CodeRabbit round 10 (browse order ties, library skip, CR3 boxes after mdat, badge once, look-ahead crop key, cli test binary) - browse_order: import- and edit-date sorts queue new files by name (they tie on those keys); ties go by name in the view's direction, as the catalog breaks them. - Local browsing never lists the library's own folder (browse_files, as scan_with skips it). - CR3 PRVW/THMB search skips only the mdat payload: boxes after it (a moov holding THMB) are still found. - The camera-preview badge and the loupe timing are settled once, after the window renders (no double badge with the full-size camera JPEG). - The loupe look-ahead key includes the crop. - bench-cull CLI tests use binary() after upstream's test split. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: CodeRabbit round 11 (browse listing errors and library root, rating ties, every CR3 PRVW, checked CR3 box math, look-ahead view key, windows wait while settling) - browse_files: a folder that can't be listed is an error (the scan ends as failed, nothing is forgotten as gone), and the library's folder or one inside it lists nothing. - New photos tie on rating: queued by name in the view's direction. - Every valid CR3 PRVW/THMB is a candidate (the smallest covering one is picked); the box offsets use checked arithmetic. - The loupe look-ahead is keyed to the visible list's generation (a new sort, filter or source changes the neighbours). - While stepping fast, zoomed-in window renders wait like the frame, and a window drawn before the frame is timed as the render. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: CodeRabbit round 12 (loupe timing: the After window, over any stand-in) In a split view only the After side's window says the raw's render is on screen; and a window drawn over the camera JPEG counts as the render too (the source shown is a render only when it is "render" or "cached"). Co-Authored-By: Claude Opus 5.5 * PERF-CULL: CodeRabbit round 13 (loupe timing: the Before window when the Before is shown alone) Co-Authored-By: Claude Opus 5.5 * PERF-CULL: CodeRabbit round 14 (loupe timing: a Before window side by side with \ held is not the shown view) Co-Authored-By: Claude Opus 5.5 * PERF-CULL: CodeRabbit round 15 (the split-view timing test asserts its precondition) Co-Authored-By: Claude Opus 5.5 * PERF-CULL: CodeRabbit round 16 (side by side with \ held, each window stays in its pane) Co-Authored-By: Claude Opus 5.5 * PERF-CULL: a cancelled browse stops ordering its files; browsing hands back earlier probes Co-Authored-By: Claude Opus 5.5 * PERF-CULL: the web build runs the browse job in place as FnMut (it hands the probes back) Co-Authored-By: Claude Opus 5.5 * PERF-CULL: a scan hands the probes it took back however it ends (CodeRabbit, #3077 / #3080) - The browse worker sends a result on every path: the listing, or `Stopped` (the folder couldn't be listed, or another folder was chosen) with the probes `ScanInput::new` took from the session. A listing failure is never sent as an empty listing. - A scan stopped without waiting (its cross, or a browse replaced by another) keeps its channel until the worker ends, so the probes still come back; a finished scan's probes join the session's instead of replacing them. - A cancelled scan whose worker ended without a result is not reported as "Scan failed". Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: built previews are the ones on disk; stand-ins ahead follow the preparation settings (CodeRabbit, #3077) - A build counts a photo as built only when its previews are in the disk cache (when it has one): a loupe render kept only in memory, its deferred write skipped, is built again and written (`stored_dims`). - `DiskCache::put` and `PreviewCache::put_at` say whether the file was written; a view preview the cache folder can't take fails the photo instead of counting it as built. - The loupe's stand-ins ahead honour Settings > Performance for the mode: none for "Only the photo on screen" or no photos ahead (the queued ones are dropped), only marked photos in the marked scope. The settings are part of what the look-ahead was made for. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: a preview for a discarded cache fails the photo; cache file sizes are read from 4 KiB first (CodeRabbit, #3077 / #3080) - `PreviewCache::put_at` returns false for a job made before the cache was cleared or retired (nothing is kept), so a build that overlaps Discard Preview Cache counts that photo as failed, not built. The warning says which of the two happened. - `DiskCache::dims` reads a file's first 4 KiB, and up to 64 KiB only when the size marker isn't there. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: a photo another build renders counts once it is built; a write pruned away is not kept (CodeRabbit, #3077 / #3080) - A build that meets a photo another build is rendering waits for that render, then counts the photo as built only when its previews are there, else renders it itself (it was counted as shared at once). - `DiskCache::put` returns false when the pruning its own write starts removes that file (a picture bigger than the room pruning leaves). Co-Authored-By: Claude Opus 5.5 * PERF-CULL: put_memory holds the cache generation through its insertion (CodeRabbit, #3080) A clear can no longer finish between put_memory's look at the generation and its insertion. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: browsing skips the library's folder by any name it has (a symlink, a path through ..) (CodeRabbit, #3077) Co-Authored-By: Claude Opus 5.5 * PERF-CULL: rustfmt the library-folder check Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: cancelled builds stop before their test library is removed (CodeRabbit, #3077) Co-Authored-By: Claude Opus 5.5 * PERF-CULL: the library folder is skipped by its resolved path only; lib/../outside is browsed, an unresolvable folder reports its error (CodeRabbit, #3077) Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: the replaced background build is held by TestHold, not a 250 ms deadline (CodeRabbit, #3077) Co-Authored-By: Claude Opus 5.5 * PERF-CULL: a browsed folder has one spelling (. and .. taken out by name) for the view, its listing and the catalog's records; an unresolvable root inside the library is still skipped (CodeRabbit, #3055 / #3077 / #3080) Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: TestHold counts its holders: one test's release doesn't free a build another test holds (CodeRabbit, #3077 / #3080) Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: TestHold's release without the deprecated fetch_update Co-Authored-By: Claude Opus 5.5 * PERF-CULL: browsing resolves `..` the way the system does, and `.` is the current folder `lexical_path` took `..` out by name, which is wrong on POSIX when the folder before it is a symlink (`link/..` is the folder above where the link points). `browse_path` makes the root absolute first (so `.` and `a/..` name the current folder, not an empty path), resolves a link just before a `..` on POSIX, and keeps every other spelling as written (a mapped drive stays a drive letter, matching the catalog's records). Windows takes `..` out by name, as before. Tests: a folder link followed by `..` lists what the system lists there; `.` is the current folder. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: browsing resolves the folder on its worker, never on the window's thread `browse()` called `browse_path` (which may canonicalize a link) and `is_dir()` before starting the worker, so a link into a stalled network mount could freeze the window. The UI now spells the folder with `browse_spelling` (`.`/`..` by name, no disk access) and shows it as given; the worker resolves it with `browse_path`, checks it is a folder (else the scan ends as failed, with the usual toast), and sends the resolved spelling, which the view takes before the listing arrives. Tests: a browse whose resolution is held returns at once and waits, then reads the folder; a missing folder fails on the worker; `browse_spelling` matches `browse_path` without links. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: the browse worker resolves the path as given, not the view's spelling (CodeRabbit, #3055 / #3077 / #3080) On Unix `photos/link/../select` with `link` pointing at `real/day` is `real/select`; the spelling with `..` taken out by name read `photos/select`. The view keeps the spelling until the worker answers. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: bench-cull measures small folders and never writes its results among the photos (CodeRabbit, #3077) A folder with no more photos than the grid sample was reported with empty camera-preview and loupe timings: the samples now fall back to the photos it has. A --json path in the source folder is refused before the run. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: editing renders the loupe from its source; the loupe holds background work back only while its render is on the way (CodeRabbit, #3077) In Develop a cached view render left the source undecoded until the first slider draft. foreground() was renewed every loupe frame even with the render shown, so background builds mostly waited. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: loupeSteps.total, a step cursor that survives the 256-step list (CodeRabbit, #3077) tools/cull-bench.py sliced the list by its length, which stops growing at 256 steps, and reported no steps on repeated runs. Also documents perf.thumbsMade and perf.previewCache. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: the camera preview is located once when the fast decode declines (CodeRabbit, #3077) The general decode takes the stand-in JPEG the fast path already found instead of parsing the container again. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: the uncapped preview cache warns once per session when its drive runs low The automatic preview cache budget grows with the library and has no ceiling. When the library opens, and at most every five minutes while previews are built, the engine reads the free space of the drive holding the cache (fs4, MIT OR Apache-2.0, pure Rust over rustix / windows-sys); under 10 % or under 20 GB free it raises one alert per session. The desktop app shows it as a notice with the drive's free space and the cache's size and a button to Settings > Performance, where a size limit can be set. A drive that can't say its free space gives no alert (logged). library.info reports lowDiskSpace; the notice is in ui.inspect's notices like the others. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: the free-space read runs off the UI thread; a queued low-disk notice goes with its library; --work outside the source folder (CodeRabbit, #3077) - Session::check_disk_space reads the drive on a worker thread and takes the answer on a later call (take_disk_space_alert, library.info, the next check): a slow network share no longer holds up a library open or a UI frame. Test: a_slow_drive_does_not_hold_up_the_check. - The UI keeps the low-disk notice with the library generation it was raised for and drops it when another library opens. Test: a_queued_notice_goes_when_another_library_opens. - The real-drive test runs on native targets only (read is None on wasm32). - bench-cull refuses a --work folder inside the measured folder, also one not made yet, before anything is created. Test: the_work_folder_never_goes_in_the_source_folder. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: one free-space read at a time across library switches, the cache counted on its worker; a --json link into the source folder is refused (CodeRabbit, #3077/#3080) - A library opened while the drive's free-space read still runs keeps that read (marked stale) instead of starting a second worker beside it; its answer is dropped and the current library's drive is read once it has come. Switching libraries while a share hangs no longer piles up workers. Test: switching_libraries_while_a_drive_hangs_starts_no_second_read. - When the drive is low, the preview cache is counted on the read's worker and the count travels with the answer: taking it on the UI thread no longer scans a big cache on a slow share. DiskCache::known_size reads the count without touching the disk. Test: the_preview_cache_is_counted_off_the_ui_thread. - bench-cull: a --json path that exists is resolved itself (a link to a photo in the source folder is that photo), a link that points nowhere yet by the file writing through it would create, a loop of links is refused. Test: a_json_link_into_the_source_folder_is_refused. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: bench-cull --json replaces its file instead of writing into it, so a hard link to a photo can't overwrite the photo (CodeRabbit, #3077) The results go to a new file next to the destination, renamed over it; the temporary file is removed on error. Test: a_json_hard_link_to_a_photo_leaves_the_photo_alone (fails with the old write). Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: bench-cull refuses a --json entry in the source folder, also a link there to a file outside (CodeRabbit, #3080) Writing the results replaces the --json entry itself, so a link sitting in the source folder that points outside it would be replaced, removing that entry. check_outputs now checks where the entry sits (its folder resolved, the final link not followed) as well as where it resolves to. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: a frame without the loupe ends its step timing, so time away from Detail never counts (CodeRabbit, #3055) LoupeTiming::left was never called: a photo's record stayed open while the grid, Compare, Survey, Reference, People or the slideshow was up, so dwell / any / full / sharp ms counted time outside Detail. observe() marks the frame; finish_ui_pass ends the step when the loupe drew nothing. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: Build Standard-Sized Previews keeps 2560 px before a loupe was drawn (CodeRabbit, #3077) On Automatic with no loupe size known yet (a fresh session) the command left `edge` out, so the engine built its 2048 px minimum and a typical fit view rendered again. The loupe-aware engine size still applies once a loupe was drawn; a chosen limit is used as is. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: main's merge keeps one Russian "★ Favorites" and its browse test uses the scan's end channel Both sides had added the same key; main's new Auto Import browse test sends through the scan channel, which this branch carries as `ScanEnd`. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: stepping fast drops the queued Before render too; the thumbnail count is per photo across eviction (CodeRabbit, #3055) While an arrow is held the Before view's raw render waits like the loupe's own, and one still queued for a photo left behind is dropped. `thumbsMade` counts each photo once per library, so a thumbnail evicted and made again, or a library left and opened again, doesn't count twice. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: the free space is read every few minutes, not only while previews are built (CodeRabbit, #3080) Thumbnails and the loupe's previews fill the cache too, so a drive could run low after the library opened without the notice: the low-disk check now runs whatever fills the cache (still at most every five minutes). The engine gains two hidden test hooks (a reader and forgetting the last read). Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: a slow free-space read shows in the activity stack and an idle window wakes for the disk check (CodeRabbit, #3077) Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: background preparation advances on every logic pass, hidden ones too (CodeRabbit, #3077) Co-Authored-By: Claude Opus 5.5 * PERF-CULL: a photo the loupe opens on is never a fast step; only a step inside the loupe has a predecessor (CodeRabbit, #3077) Co-Authored-By: Claude Opus 5.5 * PERF-CULL: the cull benchmark rates one named photo and puts its rating back (CodeRabbit, #3077) Co-Authored-By: Claude Opus 5.5 * PERF-CULL: the cull benchmark refuses a full step history, says when thumbnails were in memory, fails on a lost key and ends a zoom that needs no region (CodeRabbit, #3055) Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: a forced build renders a photo another build was rendering itself (CodeRabbit, #3080) Co-Authored-By: Claude Opus 5.5 * PERF-CULL: the cull benchmark stops on a folder with no photos and times a zoom by the region that ended it (CodeRabbit, #3055/#3080) - browse: a folder that stays loaded with no supported photo ends the browse loop after 3 s instead of waiting 30 minutes, and the run stops with a clear message before the loupe section instead of failing on an empty selection; - zoom to 100 %: the time reported is the moment the loop ended on (the region's arrival, or the settled whole frame when no region is asked for), so a whole frame that settled before a region was requested no longer gives a too-short zoom time. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: the cull benchmark says no photos are visible, keeps an earlier result, and records an unfinished zoom as missing (CodeRabbit, #3055/#3077/#3080) - an empty selection after browsing means no photo is visible (a filter can hide them), not that the folder has none: say so and point at the filters; - LABEL.json is no longer overwritten: an existing one stops the run before it starts unless --overwrite is given (the final write opens with "x" then); - a zoom that did not finish within 60 s is written as null, not as a 60 s zoom time. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: a raw's preview pointer is read with checked bounds on its offset and size (FredApps, #3080) The JPEGInterchangeFormat pointer and the undefined-tag JPEGs were sliced with `as usize` casts of the file's own u64 numbers: safe on 64-bit (the slice is `get`, its end cut at the file's end), but an offset past 4 GiB would wrap to a small, wrong one on a 32-bit build (wasm32). `file_span` now converts with `try_from` and saturates the end. Test: `a_preview_pointer_past_the_end_of_the_file_finds_no_preview` (pointers past the end, lengths past it, u32::MAX for both; a real strip preview beside the lying pointer is still found; every truncation of the file is safe). Co-Authored-By: Claude Opus 5.5 * PERF-CULL: bench-cull refuses a --work or --json inside the photo folder (FredApps, #3055) Nothing is ever written next to the photos: a --work folder or a --json file inside FOLDER (the folder itself, a subfolder, or a path that goes there through `..`) is refused before anything is made. Paths are compared resolved (links followed as far as they exist). The cleanup already removes only what the run made (its own `bench-cull-run-…` folder's `lib-copy`), never --work. Test: `work_and_json_inside_the_photo_folder_are_refused`. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: a test that building previews writes nothing next to the photos (FredApps, #3077) `building_previews_writes_nothing_next_to_the_photos`: Build Previews and the background preparation while culling leave the shoot folder with the same files, byte for byte; previews go only to the library's own cache. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: cull-bench.py prints its usage on missing arguments and refuses a dangling LABEL.json link up front (CodeRabbit, #3055/#3077) - PORT / FOLDER missing (or PORT not a number), or an option with no value or an unreadable one, stop with the usage line instead of a traceback; - the early "LABEL.json exists" check uses `os.path.lexists`, so a dangling link there is refused before the run, not at the final exclusive write. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: a preview cut short by the end of the file is not taken (CodeRabbit, #3077) `file_span` keeps a span the file's end cuts short only while it still holds a JPEG end marker (an overstated length with the whole JPEG inside). A truncated JPEG passed the frame-header check, won as the largest preview and then failed to decode, so no preview was shown. Test: `a_preview_cut_short_by_the_end_of_the_file_is_not_taken`. Co-Authored-By: Claude Opus 5.5 * PERF-PREVIEW-PREP: the shoot-folder test waits for the background build to finish (CodeRabbit, #3077) `building_previews_writes_nothing_next_to_the_photos` used a 5 s capped poll and then went on; it now asserts `wait_finished` (30 s), so a late write by a slow build can't slip past the check. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: a cut-short preview must reach its own JPEG end marker; cull-bench refuses bad options up front (CodeRabbit, #3055/#3077/#3080) - raw: file_span keeps a span the file's end cuts short only when walking the JPEG's marker segments reaches its end marker inside it, and cuts it there. An FF D9 inside an APP payload no longer counts (it is skipped by the segment length), and bytes that don't start with FF D8 are refused without scanning the rest of the file. Tests: the cut-short test gains an APP1 payload holding FF D9 (taken before this fix) and a whole JPEG followed by other bytes; the_end_of_a_jpeg_is_its_own_end_marker covers stuffed bytes, restart markers, bad segment lengths and every truncation. - tools/cull-bench.py: an unknown option, an option where a value belongs (--label --overwrite), --steps/--hold-ms below 1, or a port outside 1-65535 stop with the usage line before the run. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: cull-bench refuses a run whose steps wouldn't fit the app's loupe history (CodeRabbit, #3055) The app keeps its last 256 loupe steps. A --steps that can't fit a run (1 + 11 + STEPS + 1) stops before the run, and each phase checks the room left before it starts, so a hold whose first steps were dropped is never reported as the whole hold. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: bench-cull refuses ".." in --json and --work (CodeRabbit, #3544) A ".." after a folder the run hasn't made yet can't be resolved by the source-folder check, and the run then makes that folder: --json NEW/../FOLDER/r.json would land in the source folder. Test: a_dot_dot_in_the_outputs_is_refused. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: a cut-short preview needs a scan before its end and the walks share a budget; cull-bench catches dropped steps and odd arguments (CodeRabbit, #3055/#3077/#3080) - raw: jpeg_end accepts an end marker only after a start of scan (an end with no image data before it is refused), and the walks of a file's pointers past its end share scan_budget, as scan_for_jpeg's do. Tests: a whole-looking JPEG with no scan is not taken; the_walks_to_a_jpegs_end_share_a_budget. - tools/cull-bench.py: the port must be a decimal number int() takes (isdecimal, guarded); a FOLDER that looks like an option stops with usage; --steps goes up to 254 (only the hold's STEPS + 1 must fit, with one to spare); each phase starts with room to spare, so a full history means other steps came in and the phase stops instead of reporting a shifted window. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: the camera JPEG goes only under the window render, and a stand-in decoded across a cache clear isn't kept (CodeRabbit, #3544) - ui-egui: zoomed in, the full-size camera JPEG is painted only where the window render will go (window_cover), so a window capped smaller than the view leaves the developed whole-frame render in the strips beside it instead of an unlabelled camera JPEG. Test: the_camera_jpeg_covers_only_where_the_window_goes. - engine/preview: QuickJob's camera-JPEG cache carries the cache generation it was made in and writes with put_deferred_at / the new put_memory_at, so a job decoding when Discard Preview Cache clears the cache can't put its picture back (as render jobs already do). Test: a_camera_jpeg_decoded_across_a_cache_clear_is_not_kept. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: a bad build request leaves the background build alone, and preparation settings that can't be saved aren't kept (CodeRabbit, #3544) - library.buildPreviews stops a running background build only after its own ids are known to be good, and a build whose thread can't start is marked finished instead of left "running". - prep_tick clears started_for when the background build fails to start, so the view retries. - set_prep_settings / clear_library_prep put the previous settings back when prefs.json can't be written. Tests: a_bad_build_request_leaves_the_background_build_running, a_prep_setting_that_cant_be_saved_is_not_kept. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: a background build that can't start waits 30 s before the view tries again Clearing `started_for` on a failed start made every tick call library.buildPreviews again while the cause lasted (CodeRabbit on #3080). The view now waits RETRY_AFTER first. Test `a_build_that_cant_start_waits_before_trying_again`. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: a build waiting to retry asks for a frame at its time; a build whose worker can't start leaves the background one running CodeRabbit on #3077/#3080: a background build that couldn't start retried only on the next input. The session now says how long until the retry (prep_retry_in) and the app asks for a frame then. CodeRabbit on #3544: a build asked for whose worker thread couldn't start cancelled the background preparation and left nothing running. The background build is now stopped only once the new one has started; otherwise it stays the session's build. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: a retry time that has passed asks for no more frames CodeRabbit on #3077 / #3080: once the retry deadline passed, prep_retry_in returned zero, so a view that couldn't be tried (grid, preparation off) asked for a frame at once on every pass and kept an idle window drawing. It returns None then. Co-Authored-By: Claude Opus 5.5 * PERF-CULL: CodeRabbit items from #3577 that live in #3077 and #3055 - disk space: a read whose thread can't start (or whose worker ends without answering) is tried again after 10 s, not after the 5-minute check interval; a hung read is polled every 5 s after its first 5 s instead of every 250 ms - the low-disk notice of the library before is not drawn in the frame after a library switch - library.smartPreviews reads its ids before stopping the background build - a forced build renders the grid thumbnail again instead of reading its cache - the loupe's look-ahead asks for its stand-ins again after a renderer reset - browse: a broken link before `..` is an error, not the link's parent folder - the probes of two stopped scans: the later scan's wins whichever ends first - camera JPEG fast path: a JPEG with an incomplete ICC sequence goes the general way; a CR3 without a JPEG track picks its box preview by size too - tests: bench-cull compares the source photos' bytes, the disk notice test waits for the open's read Co-Authored-By: Claude Opus 5.5 * PERF-CULL: CodeRabbit round 4 on #3077 and the #3583 items in its code - A background smart-preview request cancels the running build only once its worker started; a worker that can't start leaves the earlier build running and the session's (test hook). - The notice logic looks again at the next disk check (10 s after a read that couldn't start). - CR3 boxes: largest by pixels; every top-level mdat left out; whole-file fallback takes the first box of a kind; a copy without an end marker isn't chosen to cover a size; a test decodes the chosen copy. - The fitted JPEG decode reads a SEF file as the image before its trailer; its doc says a header that can't be read is Ok(None). - Settings: a saved cache size the list doesn't offer shows as its own option. - bench-cull rejects a second FOLDER; a browse through `..` reads again. - cull-bench.py: --size checked, baseline waits for renders, --skip-browse claims no folder, a short rest phase warns. Co-Authored-By: Claude Opus 5.5 * Format the quick-full draw call * Loupe stand-in choice moves to its own function * Render results: the newer-draft and display checks move to their own functions * Render results: a frame left on the GPU is shown by its own function * Format the frame's texture entry * Docs: one row each for the import and performance entries * Format the quick view's key --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- Cargo.lock | 11 + Cargo.toml | 2 + apps/lightcraft-cli/src/bench_cull.rs | 585 ++++++++++++++++ apps/lightcraft-cli/src/main.rs | 9 + apps/lightcraft-cli/tests/it/cli.rs | 69 ++ apps/lightcraft/src/main.rs | 1 + crates/codecs/src/jpeg.rs | 207 ++++++ crates/codecs/src/lib.rs | 15 + crates/codecs/tests/it/header.rs | 4 + crates/engine/Cargo.toml | 2 + crates/engine/src/cmd/library/specs.rs | 4 + crates/engine/src/cmd/previews.rs | 408 +++++++++-- crates/engine/src/disk_space.rs | 577 ++++++++++++++++ crates/engine/src/files/fs.rs | 6 + crates/engine/src/files/preview.rs | 23 +- crates/engine/src/import.rs | 4 +- crates/engine/src/import/job.rs | 2 + crates/engine/src/import/scan.rs | 181 ++++- crates/engine/src/lib.rs | 13 + crates/engine/src/library.rs | 45 +- crates/engine/src/media.rs | 9 +- crates/engine/src/media/cache.rs | 8 +- crates/engine/src/media/quick.rs | 43 +- crates/engine/src/media/render.rs | 107 ++- crates/engine/src/media/session.rs | 66 +- crates/engine/src/media/source.rs | 15 +- .../engine/src/media/thumbnail_hash_tests.rs | 101 ++- crates/engine/src/prep.rs | 532 +++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/import.rs | 209 ++++++ crates/engine/src/tests/lens_refresh.rs | 2 +- crates/engine/src/tests/preview_prep.rs | 635 ++++++++++++++++++ crates/preview/src/disk.rs | 63 +- crates/preview/src/lib.rs | 74 +- crates/preview/src/tests.rs | 60 ++ crates/raw/src/preview.rs | 220 +++++- crates/raw/src/preview/tests.rs | 350 ++++++++++ crates/ui-egui/locales/cs.json | 1 + crates/ui-egui/locales/de.json | 3 + crates/ui-egui/locales/es.json | 3 + crates/ui-egui/locales/fi.json | 1 + crates/ui-egui/locales/fr.json | 3 + crates/ui-egui/locales/id.json | 1 + crates/ui-egui/locales/it.json | 1 + crates/ui-egui/locales/ja.json | 3 + crates/ui-egui/locales/ka.json | 1 + crates/ui-egui/locales/pt-br.json | 3 + crates/ui-egui/locales/ru.json | 3 + crates/ui-egui/locales/sv.json | 1 + crates/ui-egui/locales/uk.json | 3 + crates/ui-egui/locales/vi.json | 1 + crates/ui-egui/locales/zh-hans.json | 3 + crates/ui-egui/locales/zh-hant.json | 3 + crates/ui-egui/src/app.rs | 44 ++ crates/ui-egui/src/app/frame.rs | 5 +- crates/ui-egui/src/control.rs | 19 +- crates/ui-egui/src/dialogs/import.rs | 5 +- crates/ui-egui/src/dialogs/import/scan.rs | 249 +++++-- crates/ui-egui/src/dialogs/settings.rs | 4 +- .../src/dialogs/settings/performance.rs | 131 +++- crates/ui-egui/src/headless/tests.rs | 140 ++++ crates/ui-egui/src/lib.rs | 23 + crates/ui-egui/src/loupe_timing.rs | 269 ++++++++ crates/ui-egui/src/menus/menubar.rs | 20 +- crates/ui-egui/src/panels/detail.rs | 305 ++++++++- crates/ui-egui/src/panels/detail/info.rs | 18 + .../ui-egui/src/panels/detail/look_ahead.rs | 119 ++++ crates/ui-egui/src/panels/detail/window.rs | 7 +- crates/ui-egui/src/panels/notices.rs | 128 +++- crates/ui-egui/src/render.rs | 337 ++++++++-- crates/ui-egui/src/render/thumbnail_tests.rs | 404 +++++++++++ crates/ui-egui/src/state/settings.rs | 16 + crates/ui-egui/src/tests.rs | 2 + crates/ui-egui/src/tests/disk_space.rs | 151 +++++ crates/ui-egui/src/tests/drop_import.rs | 5 +- crates/ui-egui/src/tests/lifecycle_037.rs | 40 ++ crates/ui-egui/src/tests/preview_limit.rs | 72 ++ crates/ui-egui/src/tests/scan_probes.rs | 204 ++++++ docs/control-protocol.md | 2 +- docs/gaps.md | 6 +- docs/gpu-pipeline.md | 5 + docs/parity-checklist.md | 22 +- docs/raw-preview-reads.md | 18 + tools/cull-bench.py | 336 +++++++++ 84 files changed, 7508 insertions(+), 295 deletions(-) create mode 100644 apps/lightcraft-cli/src/bench_cull.rs create mode 100644 crates/engine/src/disk_space.rs create mode 100644 crates/engine/src/prep.rs create mode 100644 crates/engine/src/tests/preview_prep.rs create mode 100644 crates/ui-egui/src/loupe_timing.rs create mode 100644 crates/ui-egui/src/panels/detail/look_ahead.rs create mode 100644 crates/ui-egui/src/tests/disk_space.rs create mode 100644 crates/ui-egui/src/tests/scan_probes.rs create mode 100644 tools/cull-bench.py diff --git a/Cargo.lock b/Cargo.lock index 1d0bb2bdc2..1b870d1c39 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2139,6 +2139,16 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" +[[package]] +name = "fs4" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5" +dependencies = [ + "rustix 1.1.5", + "windows-sys 0.61.2", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -3732,6 +3742,7 @@ dependencies = [ "ab_glyph", "chrono", "craft-docpath", + "fs4", "harfrust 0.13.3", "jxl-oxide", "libc", diff --git a/Cargo.toml b/Cargo.toml index 061507c999..25b742c1b7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,6 +58,8 @@ log = "0.4" # All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md). chrono = { version = "0.4.45", default-features = false, features = ["std"] } rayon = "1" +# free/total space of a drive (engine's low-disk alert); MIT OR Apache-2.0, pure Rust (rustix / windows-sys) +fs4 = { version = "1.1", default-features = false } winapi-util = "0.1" # lightcraft-catalog reads a file's volume serial number and file index with it on Windows proptest = "1" bytemuck = { version = "1", features = ["derive"] } diff --git a/apps/lightcraft-cli/src/bench_cull.rs b/apps/lightcraft-cli/src/bench_cull.rs new file mode 100644 index 0000000000..9107a94553 --- /dev/null +++ b/apps/lightcraft-cli/src/bench_cull.rs @@ -0,0 +1,585 @@ +//! `lightcraft-cli bench-cull FOLDER`: time what culling a shoot costs, headless, on real files. +//! +//! What a wedding photographer does most is open a folder of a few thousand raws, look at each +//! one, rate it and move on. This times the engine side of each step on the files themselves (the +//! desktop app's own frame timings come from `ui.inspect` → `perf.loupeSteps`, see +//! `tools/cull-bench.py`): +//! +//! - browse: reading the folder into the Local view (`library.browse`, the whole folder); +//! - grid thumbnails: the camera JPEG at 512 px for the first screen, on as many threads as the +//! app renders with; +//! - camera preview at loupe sizes (1280, 2560) and at full size (the 100 % view), one at a time; +//! - LightCraft's render of the loupe (2560 px) from a cold source; +//! - rating: `photo.rate` on many photos in a row, journal included; +//! - import: adding N files in place to a fresh library, and copying M of them into it (`--n 0`: +//! no import). +//! +//! `--files K` reads only the first K files (by name) of the folder, as browsing reads them: a +//! sample of a folder on a network share, where reading thousands of raws takes hours. +//! +//! Each number is printed as `name: X ms wall` (median, with p95 and n), the format +//! `cargo xtask bench` parses, and the lot as one JSON object with `--json FILE`. Nothing is +//! written next to the photos: every library is made in a new folder of the run's own under +//! `--work` (default: a folder in the system temp directory; nothing already there is deleted), +//! XMP auto-write stays off, and the source folder is only read. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Instant; + +use lightcraft_engine::Session; +use lightcraft_engine::catalog::PhotoId; +use serde_json::{Value, json}; + +const USAGE: &str = "lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]"; + +/// Threads the app renders thumbnails with (`Renderer::default`: cores − 1, at most 6). +fn render_threads() -> usize { + std::thread::available_parallelism().map(|n| n.get().saturating_sub(1)).unwrap_or(2).clamp(2, 6) +} + +/// Median, p95 and count of `ms` (milliseconds). +fn stats(ms: &[f64]) -> Value { + if ms.is_empty() { + return Value::Null; + } + let mut v = ms.to_vec(); + v.sort_by(f64::total_cmp); + let at = |q: f64| v.get(((v.len() - 1) as f64 * q).round() as usize).copied().unwrap_or(0.0); + json!({"p50": round(at(0.5)), "p95": round(at(0.95)), "max": round(at(1.0)), "n": v.len()}) +} + +fn round(x: f64) -> f64 { + (x * 10.0).round() / 10.0 +} + +fn ms_since(t: Instant) -> f64 { + t.elapsed().as_secs_f64() * 1000.0 +} + +/// Print one result line the way `xtask bench` parses it (`name: X ms wall`). +fn line(name: &str, s: &Value) { + if let Some(p50) = s.get("p50").and_then(Value::as_f64) { + println!("{name}: {p50:.1} ms wall (p95 {} ms, n {})", s["p95"], s["n"]); + } +} + +/// A new, empty folder `name` in this run's own folder; never deletes anything already there. +fn fresh_dir(root: &Path, name: &str) -> Result { + let d = root.join(name); + std::fs::create_dir(&d).map_err(|e| format!("{}: {e}", d.display()))?; + Ok(d) +} + +/// A folder of this run's own under `work`, which must not exist yet: a run never deletes or +/// reuses what is already under `--work`. +fn run_dir(work: &Path) -> Result { + std::fs::create_dir_all(work).map_err(|e| format!("{}: {e}", work.display()))?; + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + static RUNS: AtomicUsize = AtomicUsize::new(0); + let n = RUNS.fetch_add(1, Ordering::Relaxed); + let d = work.join(format!("bench-cull-run-{}-{stamp}-{n}", std::process::id())); + std::fs::create_dir(&d).map_err(|e| format!("{}: {e}", d.display()))?; + Ok(d) +} + +/// `take` items of `v` after the first `skip` (photos the stages before have read, so cold in the +/// file cache), or, when `v` has no more than `skip`, its first `take`: a small folder is measured +/// on photos already read rather than not at all. +fn sample_after(v: &[T], skip: usize, take: usize) -> &[T] { + let from = if v.len() > skip { skip } else { 0 }; + let rest = v.get(from..).unwrap_or_default(); + rest.get(..take.min(rest.len())).unwrap_or_default() +} + +/// Whether `path` names a file in `folder` (the source folder, which a run only reads), checked +/// twice: where its own entry sits (the folder holding it, the final link not followed: writing the +/// results replaces that entry, so a link to a file elsewhere that sits in the source folder, maybe +/// standing for a photo, would be replaced; CodeRabbit on #3080), and where it resolves to: a file +/// that is there by itself (a link to a photo there is the photo), a link that points nowhere yet +/// by where writing through it would create the file, and anything else by its nearest folder that +/// exists (a `--work` folder may not be there yet). +fn inside_source(path: &Path, folder: &Path) -> bool { + let Ok(folder) = std::fs::canonicalize(folder) else { return false }; + entry_inside(path, &folder) || resolves_inside(path, &folder, 0) +} + +/// Whether the folder holding `path`'s own entry (its nearest folder that exists, resolved) is in +/// `folder` (already resolved). The entry itself is not followed. +fn entry_inside(path: &Path, folder: &Path) -> bool { + let mut p = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")); + loop { + if let Ok(c) = std::fs::canonicalize(p) { + return c.starts_with(folder); + } + match p.parent() { + Some(up) if !up.as_os_str().is_empty() => p = up, + Some(_) => p = Path::new("."), + None => return false, + } + } +} + +/// [`inside_source`] for a `folder` already resolved; `hops`: links followed so far (a loop of +/// links counts as inside: refused). +fn resolves_inside(path: &Path, folder: &Path, hops: u32) -> bool { + if let Ok(c) = std::fs::canonicalize(path) { + return c.starts_with(folder); + } + if let Ok(target) = std::fs::read_link(path) { + if hops >= 40 { + return true; + } + let target = path.parent().map_or_else(|| target.clone(), |dir| dir.join(&target)); + return resolves_inside(&target, folder, hops + 1); + } + entry_inside(path, folder) +} + +/// Refuse `--json` or `--work` in the folder being measured: nothing is written next to the photos, +/// the results and the run's libraries included. Checked before anything is made. +fn check_outputs(folder: &Path, json: Option<&Path>, work: &Path) -> Result<(), String> { + // a `..` after a folder not made yet can't be resolved now, and the run makes that folder: + // `--json NEW/../FOLDER/r.json` would pass the checks below and land in the source folder + // (CodeRabbit on #3544) + for (name, p) in [("--json", json), ("--work", Some(work))] { + if let Some(p) = p.filter(|p| p.components().any(|c| c == std::path::Component::ParentDir)) { + return Err(format!("{}: {name} must not contain \"..\"; give the folder without it", p.display())); + } + } + if let Some(j) = json.filter(|j| inside_source(j, folder)) { + return Err(format!("{}: --json must not be in the folder being measured", j.display())); + } + if inside_source(&work.join("run"), folder) { + return Err(format!("{}: --work must not be in the folder being measured", work.display())); + } + Ok(()) +} + +fn library(dir: &Path) -> Result { + let mut s = Session::new().with_fs().with_system_clock(); + s.open_library(dir, false).map_err(|e| format!("{}: {e}", dir.display()))?; + // nothing is ever written next to the photos + s.execute("library.xmpPreferences", &json!({"autoWrite": false})).map_err(|e| e.to_string())?; + Ok(s) +} + +pub fn run(args: &[String]) -> Result<(), String> { + let mut folder = None; + let mut n = 2000usize; + let mut copy = 200usize; + let mut work = None; + let mut json_out = None; + let mut files = None; + let mut i = 0; + while i < args.len() { + let value = |i: usize| args.get(i + 1).cloned().ok_or_else(|| format!("{} needs a value\n{USAGE}", args[i])); + match args[i].as_str() { + "--n" => { + n = value(i)?.parse().map_err(|_| "--n needs a number".to_string())?; + i += 1; + } + "--copy" => { + copy = value(i)?.parse().map_err(|_| "--copy needs a number".to_string())?; + i += 1; + } + "--files" => { + files = Some(value(i)?.parse::().map_err(|_| "--files needs a number".to_string())?); + i += 1; + } + "--work" => { + work = Some(PathBuf::from(value(i)?)); + i += 1; + } + "--json" => { + json_out = Some(PathBuf::from(value(i)?)); + i += 1; + } + "-h" | "--help" => { + println!("{USAGE}"); + return Ok(()); + } + a if a.starts_with("--") => return Err(format!("unknown option {a}\n{USAGE}")), + // (a second folder would replace the first and be timed in its place: CodeRabbit on #3583) + a if folder.is_some() => return Err(format!("{a}: one FOLDER only\n{USAGE}")), + a => folder = Some(PathBuf::from(a)), + } + i += 1; + } + let folder = folder.ok_or_else(|| USAGE.to_string())?; + if !folder.is_dir() { + return Err(format!("{}: not a folder", folder.display())); + } + let work = work.unwrap_or_else(|| std::env::temp_dir().join(format!("lightcraft-bench-cull-{}", std::process::id()))); + check_outputs(&folder, json_out.as_deref(), &work)?; + let work = run_dir(&work)?; + let mut out = json!({"folder": folder.display().to_string(), "threads": render_threads()}); + + // --- browse: the whole folder into the Local view ------------------------------------------- + let mut s = library(&fresh_dir(&work, "lib-browse")?)?; + // `--files K`: only the first K files by name, read as browsing reads them (a sample of a slow + // network folder) + let t = Instant::now(); + let (photos, ids): (u64, Vec) = match files { + None => { + let r = s.execute("library.browse", &json!({"path": folder.display().to_string()})).map_err(|e| e.to_string())?; + (r["photos"].as_u64().unwrap_or(0), s.visible_cloned()) + } + Some(k) => { + let mut list: Vec = std::fs::read_dir(&folder) + .map_err(|e| format!("{}: {e}", folder.display()))? + .flatten() + .map(|e| e.path()) + .filter(|p| p.is_file() && lightcraft_engine::import::is_supported(p)) + .map(|p| p.display().to_string()) + .collect(); + list.sort(); + list.truncate(k); + let r = s.execute("library.import", &json!({"paths": list, "mode": "add", "local": true})).map_err(|e| e.to_string())?; + let ids: Vec = r["imported"].as_array().into_iter().flatten().filter_map(Value::as_u64).map(PhotoId).collect(); + (ids.len() as u64, ids) + } + }; + let browse_ms = ms_since(t); + let what = if files.is_some() { "first files" } else { "whole folder" }; + println!("browse {photos} photos ({what}): {browse_ms:.1} ms wall"); + out["browse"] = json!({"ms": round(browse_ms), "photos": photos, "perPhotoMs": round(browse_ms / photos.max(1) as f64)}); + let paths: Vec = ids + .iter() + .filter_map(|id| match &s.catalog.photo(*id)?.source { + lightcraft_engine::catalog::Source::File { path } => Some(path.clone()), + _ => None, + }) + .collect(); + if paths.is_empty() { + return Err(format!("{}: no photos", folder.display())); + } + let loader = s.media.preview_loader.clone().ok_or("no preview loader")?; + + // --- grid thumbnails: the first screen, in parallel ------------------------------------------ + let screen: Vec = paths.iter().take(48).cloned().collect(); + let next = Arc::new(AtomicUsize::new(0)); + let t = Instant::now(); + let per: Vec<(f64, f64)> = std::thread::scope(|sc| { + let workers: Vec<_> = (0..render_threads()) + .map(|_| { + let (next, loader, screen) = (next.clone(), loader.clone(), &screen); + sc.spawn(move || { + let mut done = Vec::new(); + while let Some(p) = screen.get(next.fetch_add(1, Ordering::Relaxed)) { + let a = Instant::now(); + let _ = loader(p, 512); + done.push((ms_since(a), ms_since(t))); + } + done + }) + }) + .collect(); + workers.into_iter().flat_map(|w| w.join().unwrap_or_default()).collect() + }); + let first = per.iter().map(|p| p.1).fold(f64::INFINITY, f64::min); + let all = per.iter().map(|p| p.1).fold(0.0, f64::max); + let each = stats(&per.iter().map(|p| p.0).collect::>()); + println!("grid: first thumbnail: {first:.1} ms wall"); + println!("grid: {} thumbnails: {all:.1} ms wall", per.len()); + line("grid: one 512 px thumbnail", &each); + out["thumbs"] = json!({"firstMs": round(first), "allMs": round(all), "count": per.len(), "each": each}); + + // --- camera previews at loupe sizes, one at a time (what a step costs without look-ahead) ----- + let sample = sample_after(&paths, 48, 20); + for edge in [1280usize, 2560, usize::MAX] { + let ms: Vec = sample + .iter() + .map(|p| { + let a = Instant::now(); + let _ = loader(p, edge); + ms_since(a) + }) + .collect(); + let name = if edge == usize::MAX { "camera preview full size (100 %)".to_string() } else { format!("camera preview {edge} px") }; + let st = stats(&ms); + line(&name, &st); + out[if edge == usize::MAX { "cameraFull".to_string() } else { format!("camera{edge}") }] = st; + } + + // --- LightCraft's loupe render (2560 px) from a cold source -------------------------------- + let ms: Vec = sample_after(&ids, 80, 5) + .iter() + .filter_map(|id| { + let job = s.loupe_job(*id, 2560, 1708, true)?; + let a = Instant::now(); + let r = job.run(); + let t = ms_since(a); + r.rendered.is_ok().then_some(t) + }) + .collect(); + let st = stats(&ms); + line("loupe render 2560 px (cold)", &st); + out["loupeRender"] = st; + + // --- rating: a culling pass of keypresses --------------------------------------------------- + let ms: Vec = ids + .iter() + .take(50) + .enumerate() + .filter_map(|(k, id)| { + // the key acts on the selected photo, as in the loupe + s.execute("library.select", &json!({"ids": [id.0], "active": id.0})).ok()?; + let a = Instant::now(); + s.execute("photo.rate", &json!({"rating": (k % 5) + 1})).ok()?; + Some(ms_since(a)) + }) + .collect(); + let st = stats(&ms); + line("rate one photo (journal written)", &st); + out["rate"] = st; + drop(s); + + // --- import: add in place, then copy ---------------------------------------------------------- + if n == 0 { + return finish(out, json_out); + } + let add: Vec = paths.iter().take(n).cloned().collect(); + let mut s = library(&fresh_dir(&work, "lib-add")?)?; + let t = Instant::now(); + let r = s.execute("library.import", &json!({"paths": add, "mode": "add"})).map_err(|e| e.to_string())?; + let add_ms = ms_since(t); + let added = r["imported"].as_array().map(Vec::len).unwrap_or(0); + println!("import {added} photos in place: {add_ms:.1} ms wall"); + out["importAdd"] = json!({"ms": round(add_ms), "photos": added, "perPhotoMs": round(add_ms / added.max(1) as f64)}); + drop(s); + if copy > 0 { + let some: Vec = paths.iter().take(copy).cloned().collect(); + let lib = fresh_dir(&work, "lib-copy")?; + let mut s = library(&lib)?; + let t = Instant::now(); + let r = s + .execute("library.import", &json!({"paths": some, "mode": "copy", "destination": lib.join("Originals").display().to_string()})) + .map_err(|e| e.to_string())?; + let copy_ms = ms_since(t); + let copied = r["imported"].as_array().map(Vec::len).unwrap_or(0); + println!("import {copied} photos by copying: {copy_ms:.1} ms wall"); + out["importCopy"] = json!({"ms": round(copy_ms), "photos": copied, "perPhotoMs": round(copy_ms / copied.max(1) as f64)}); + drop(s); + let _ = std::fs::remove_dir_all(&lib); + } + finish(out, json_out) +} + +fn finish(out: Value, json_out: Option) -> Result<(), String> { + if let Some(p) = json_out { + write_replacing(&p, serde_json::to_string_pretty(&out).unwrap_or_default().as_bytes())?; + } + println!("{}", serde_json::to_string(&out).unwrap_or_default()); + Ok(()) +} + +/// Write `bytes` to `path` through a new file next to it, renamed over `path`: an existing `path` +/// is replaced as a name, never written into. A hard link there shares its data with another file +/// (maybe a photo in the source folder, which [`inside_source`] can't tell), and writing into it +/// would overwrite that file too (CodeRabbit on #3077). The temporary file is removed on error. +fn write_replacing(path: &Path, bytes: &[u8]) -> Result<(), String> { + use std::io::Write; + let err = |e: std::io::Error| format!("{}: {e}", path.display()); + let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); + let name = path.file_name().ok_or_else(|| format!("{}: not a file name", path.display()))?; + static TEMPS: AtomicUsize = AtomicUsize::new(0); + let n = TEMPS.fetch_add(1, Ordering::Relaxed); + let mut tmp_name = std::ffi::OsString::from("."); + tmp_name.push(name); + tmp_name.push(format!(".{}-{n}.tmp", std::process::id())); + let tmp = dir.join(tmp_name); + let written = + std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp).and_then(|mut f| f.write_all(bytes).and_then(|()| f.sync_all())); + if let Err(e) = written.and_then(|()| std::fs::rename(&tmp, path)) { + let _ = std::fs::remove_file(&tmp); + return Err(err(e)); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_second_folder_is_an_error() { + let e = run(&["a".to_string(), "b".to_string()]).unwrap_err(); + assert!(e.starts_with("b: one FOLDER only"), "{e}"); + } + + /// `--work` may hold anything: a run makes a new folder of its own there and never deletes + /// what is already in it (it used to remove `lib-browse`, `lib-add` and `lib-copy` there). + #[test] + fn a_run_never_deletes_what_is_under_work() { + // a folder this test owns (made new), so the cleanup below removes nothing else + let work = run_dir(&std::env::temp_dir()).unwrap(); + let keep = work.join("lib-browse").join("keep.txt"); + std::fs::create_dir_all(keep.parent().unwrap()).unwrap(); + std::fs::write(&keep, b"mine").unwrap(); + let a = run_dir(&work).unwrap(); + let b = run_dir(&work).unwrap(); + assert_ne!(a, b); + fresh_dir(&a, "lib-browse").unwrap(); + assert!(fresh_dir(&a, "lib-browse").is_err(), "an existing folder is never reused"); + assert_eq!(std::fs::read(&keep).unwrap(), b"mine"); + let _ = std::fs::remove_dir_all(&work); + } + + /// A folder too small for the disjoint samples is measured on the photos it has (CodeRabbit on #3077). + #[test] + fn a_small_folder_is_sampled_from_its_start() { + let v: Vec = (0..100).collect(); + assert_eq!(sample_after(&v, 48, 20), &v[48..68]); + assert_eq!(sample_after(&v, 90, 20), &v[90..100]); + assert_eq!(sample_after(&v[..3], 48, 20), &v[..3]); + assert_eq!(sample_after(&v[..48], 48, 5), &v[..5]); + assert!(sample_after::(&[], 48, 20).is_empty()); + } + + /// A file link at `at` to `target`. + #[cfg(unix)] + fn link(target: &Path, at: &Path) -> std::io::Result<()> { + std::os::unix::fs::symlink(target, at) + } + + /// A file link at `at` to `target` (Windows: needs Developer Mode or the right to make links). + #[cfg(windows)] + fn link(target: &Path, at: &Path) -> std::io::Result<()> { + std::os::windows::fs::symlink_file(target, at) + } + + #[cfg(not(any(unix, windows)))] + fn link(_: &Path, _: &Path) -> std::io::Result<()> { + Err(std::io::Error::other("no file links here")) + } + + /// `--json` naming a link (made elsewhere) to a file in the source folder is refused: writing + /// the results would follow it and overwrite a photo (CodeRabbit on #3080). So is a link that + /// points to a file not made yet in the source folder, and a loop of links. + #[test] + fn a_json_link_into_the_source_folder_is_refused() { + let work = run_dir(&std::env::temp_dir()).unwrap(); + let src = fresh_dir(&work, "src").unwrap(); + let photo = src.join("a.jpg"); + std::fs::write(&photo, b"photo").unwrap(); + let to_photo = work.join("report.json"); + if let Err(e) = link(&photo, &to_photo) { + let _ = std::fs::remove_dir_all(&work); + lightcraft_testkit::skip!(System, "can't make a file link here ({e}); Windows needs Developer Mode"); + return; + } + assert!(inside_source(&to_photo, &src), "a link to a photo in the source folder"); + let e = check_outputs(&src, Some(&to_photo), &work.join("elsewhere")).unwrap_err(); + assert!(e.contains("--json"), "{e}"); + let to_new = work.join("new.json"); + link(&src.join("not-yet.json"), &to_new).unwrap(); + assert!(inside_source(&to_new, &src), "a link to a file not made yet in the source folder"); + let (x, y) = (work.join("x.json"), work.join("y.json")); + link(&y, &x).unwrap(); + link(&x, &y).unwrap(); + assert!(inside_source(&x, &src), "a loop of links"); + let to_elsewhere = work.join("fine.json"); + link(&work.join("out.json"), &to_elsewhere).unwrap(); + assert!(!inside_source(&to_elsewhere, &src), "a link to a file outside is fine"); + assert_eq!(std::fs::read(&photo).unwrap(), b"photo"); + let _ = std::fs::remove_dir_all(&work); + } + + /// `--json` naming a link that sits in the source folder and points to a file outside it is + /// refused: writing the results would replace the link itself, an entry of the source folder + /// (CodeRabbit on #3080). The link stays as it was. + #[test] + fn a_json_link_in_the_source_folder_to_a_file_outside_is_refused() { + let work = run_dir(&std::env::temp_dir()).unwrap(); + let src = fresh_dir(&work, "src").unwrap(); + let outside = work.join("out.json"); + std::fs::write(&outside, b"outside").unwrap(); + let in_src = src.join("a.jpg"); + if let Err(e) = link(&outside, &in_src) { + let _ = std::fs::remove_dir_all(&work); + lightcraft_testkit::skip!(System, "can't make a file link here ({e}); Windows needs Developer Mode"); + return; + } + assert!(inside_source(&in_src, &src), "a link in the source folder, wherever it points"); + let e = check_outputs(&src, Some(&in_src), &work.join("elsewhere")).unwrap_err(); + assert!(e.contains("--json"), "{e}"); + assert!(std::fs::symlink_metadata(&in_src).unwrap().file_type().is_symlink(), "the link stays"); + assert_eq!(std::fs::read_link(&in_src).unwrap(), outside); + assert_eq!(std::fs::read(&outside).unwrap(), b"outside"); + // a new file in the source folder (nothing there yet) is refused too + assert!(check_outputs(&src, Some(&src.join("new.json")), &work.join("elsewhere")).is_err()); + let _ = std::fs::remove_dir_all(&work); + } + + /// `--json` naming a hard link (made elsewhere) to a photo in the source folder passes + /// [`inside_source`] (a hard link has no target to resolve), so the results replace the link + /// instead of writing into it: the photo keeps its bytes (CodeRabbit on #3077). + #[test] + fn a_json_hard_link_to_a_photo_leaves_the_photo_alone() { + let work = run_dir(&std::env::temp_dir()).unwrap(); + let src = fresh_dir(&work, "src").unwrap(); + let photo = src.join("a.jpg"); + std::fs::write(&photo, b"photo").unwrap(); + let report = work.join("report.json"); + if let Err(e) = std::fs::hard_link(&photo, &report) { + let _ = std::fs::remove_dir_all(&work); + lightcraft_testkit::skip!(System, "can't make a hard link here ({e})"); + return; + } + finish(json!({"browse": 1}), Some(report.clone())).unwrap(); + assert_eq!(std::fs::read(&photo).unwrap(), b"photo", "the photo is unchanged"); + let written: Value = serde_json::from_slice(&std::fs::read(&report).unwrap()).unwrap(); + assert_eq!(written["browse"], 1); + let left: Vec<_> = std::fs::read_dir(&work).unwrap().flatten().map(|e| e.file_name()).collect(); + assert_eq!(left.len(), 2, "no temporary file is left: {left:?}"); + // a folder that isn't there: an error, nothing panics + assert!(write_replacing(&work.join("missing").join("r.json"), b"x").is_err()); + let _ = std::fs::remove_dir_all(&work); + } + + /// `--json` naming a file in the source folder is refused (CodeRabbit on #3077); elsewhere it is fine. + #[test] + fn the_results_never_go_in_the_source_folder() { + let work = run_dir(&std::env::temp_dir()).unwrap(); + let src = fresh_dir(&work, "src").unwrap(); + let sub = fresh_dir(&src, "sub").unwrap(); + assert!(inside_source(&src.join("a.png"), &src)); + assert!(inside_source(&sub.join("x.json"), &src)); + assert!(inside_source(&src.join("sub").join("..").join("a.png"), &src)); + assert!(!inside_source(&work.join("out.json"), &src)); + let _ = std::fs::remove_dir_all(&work); + } + + /// `--work` in the source folder is refused before anything is made there, also when it doesn't + /// exist yet (CodeRabbit on #3077); elsewhere it is fine. + #[test] + fn the_work_folder_never_goes_in_the_source_folder() { + let work = run_dir(&std::env::temp_dir()).unwrap(); + let src = fresh_dir(&work, "src").unwrap(); + let inside = src.join("out").join("deeper"); + let e = check_outputs(&src, None, &inside).unwrap_err(); + assert!(e.contains("--work"), "{e}"); + assert!(check_outputs(&src, None, &src).is_err(), "the source folder itself"); + assert!(!src.join("out").exists(), "nothing was made in the source folder"); + assert!(check_outputs(&src, None, &work.join("elsewhere")).is_ok()); + assert!(check_outputs(&src, Some(&src.join("r.json")), &work.join("elsewhere")).is_err()); + let _ = std::fs::remove_dir_all(&work); + } + + /// A `..` in `--json` or `--work` is refused: after a folder the run hasn't made yet it can't be + /// resolved now, and would lead into the source folder once the run makes it (CodeRabbit on #3544). + #[test] + fn a_dot_dot_in_the_outputs_is_refused() { + let work = run_dir(&std::env::temp_dir()).unwrap(); + let src = fresh_dir(&work, "src").unwrap(); + let sneaky = work.join("new").join("..").join("src").join("r.json"); + let e = check_outputs(&src, Some(&sneaky), &work.join("elsewhere")).unwrap_err(); + assert!(e.contains("--json") && e.contains(".."), "{e}"); + let e = check_outputs(&src, None, &work.join("new").join("..").join("src")).unwrap_err(); + assert!(e.contains("--work"), "{e}"); + assert!(!work.join("new").exists(), "nothing was made"); + let _ = std::fs::remove_dir_all(&work); + } +} diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rs index 7822bbed9a..d384229558 100644 --- a/apps/lightcraft-cli/src/main.rs +++ b/apps/lightcraft-cli/src/main.rs @@ -11,11 +11,13 @@ //! lightcraft-cli commands [--json] //! lightcraft-cli controls [--json] //! lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS/FILES… +//! lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE] //! ``` #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod alloc_release; +mod bench_cull; use std::io::Write; use std::path::Path; @@ -110,6 +112,12 @@ USAGE: model, written as .json to DIR (default: the profiles folder LightCraft reads, /camera-profiles, or $LIGHTCRAFT_CAMERA_PROFILES). Raws of a profiled model then take their colour from the profile and only their tone from their own JPEG. + lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE] + Time what culling a shoot costs on its own files: reading the folder (browse), the first + screen of grid thumbnails, camera previews at loupe sizes and full size, a loupe render, + rating, and importing N files in place (default 2000) and copying M (default 200). Libraries + are made in a new folder under DIR (default: the temp folder); nothing is written next to the + photos. --files K reads only the first K files by name (a sample of a slow network folder). lightcraft-cli --version | --help "; @@ -176,6 +184,7 @@ fn main() -> ExitCode { Some("controls") => controls(&args[1..]), Some("denoise-serve") => denoise_serve(&args[1..]), Some("calibrate") => calibrate(&args[1..]), + Some("bench-cull") => bench_cull::run(&args[1..]), Some("--version" | "-V" | "version") => { println!("lightcraft-cli {}", env!("CARGO_PKG_VERSION")); Ok(()) diff --git a/apps/lightcraft-cli/tests/it/cli.rs b/apps/lightcraft-cli/tests/it/cli.rs index 613197459c..2a052fc2d8 100644 --- a/apps/lightcraft-cli/tests/it/cli.rs +++ b/apps/lightcraft-cli/tests/it/cli.rs @@ -101,6 +101,75 @@ fn gradient_png(path: &std::path::Path) { std::fs::write(path, png).unwrap(); } +/// PERF-CULL-5: `bench-cull` times a folder end to end and writes nothing next to the photos. +#[test] +fn bench_cull_times_a_folder_and_leaves_it_untouched() { + let dir = tmp("bench-cull-src"); + std::fs::create_dir_all(&dir).unwrap(); + for (seed, name) in ["a.png", "b.png", "c.png"].iter().enumerate() { + // three different pictures (the same bytes would import as one photo) + let img = lightcraft_raster::Rgba8::from_fn(120, 80, |x, y| [(x * 2) as u8, (y * 3) as u8, (seed * 80) as u8, 255]); + let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &Default::default()).unwrap(); + std::fs::write(dir.join(name), png).unwrap(); + } + // every file's name and bytes: nothing added, and no photo written into (CodeRabbit on #3577) + let listing = |d: &std::path::Path| { + let mut v: Vec<(String, Vec)> = std::fs::read_dir(d) + .unwrap() + .map(|e| e.unwrap()) + .map(|e| (e.file_name().to_string_lossy().to_string(), std::fs::read(e.path()).unwrap())) + .collect(); + v.sort(); + v + }; + let before = listing(&dir); + let work = tmp("bench-cull-work"); + let json_out = tmp("bench-cull.json"); + let r = Command::new(binary()) + .arg("bench-cull") + .arg(&dir) + .args(["--n", "3", "--copy", "1", "--work"]) + .arg(&work) + .arg("--json") + .arg(&json_out) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&r.stdout); + assert!(r.status.success(), "{stdout}{}", String::from_utf8_lossy(&r.stderr)); + assert!(stdout.contains("browse 3 photos") && stdout.contains("ms wall"), "{stdout}"); + let v: Value = serde_json::from_str(&std::fs::read_to_string(&json_out).unwrap()).unwrap(); + assert_eq!(v["browse"]["photos"], 3); + assert_eq!(v["importAdd"]["photos"], 3); + assert_eq!(v["importCopy"]["photos"], 1); + assert_eq!(v["rate"]["n"], 3); + // a folder smaller than the samples is measured on the photos it has, not reported empty + for stage in ["camera1280", "camera2560", "cameraFull", "loupeRender"] { + assert_eq!(v[stage]["n"], 3, "{stage}: {}", v[stage]); + } + assert_eq!(listing(&dir), before, "nothing written next to the photos"); + // results asked for in the source folder: refused, the photo untouched + let photo = std::fs::read(dir.join("a.png")).unwrap(); + let r = Command::new(binary()) + .arg("bench-cull") + .arg(&dir) + .args(["--n", "0", "--work"]) + .arg(&work) + .arg("--json") + .arg(dir.join("a.png")) + .output() + .unwrap(); + assert!(!r.status.success() && String::from_utf8_lossy(&r.stderr).contains("--json"), "{}", String::from_utf8_lossy(&r.stderr)); + assert_eq!(std::fs::read(dir.join("a.png")).unwrap(), photo); + assert_eq!(listing(&dir), before); + // a sample of the folder, no import + let r = Command::new(binary()).arg("bench-cull").arg(&dir).args(["--files", "2", "--n", "0", "--work"]).arg(&work).output().unwrap(); + let stdout = String::from_utf8_lossy(&r.stdout); + assert!(r.status.success() && stdout.contains("browse 2 photos (first files)") && !stdout.contains("import"), "{stdout}"); + // a bad folder is an error, not a panic + let r = Command::new(binary()).args(["bench-cull", "/no/such/folder"]).output().unwrap(); + assert!(!r.status.success() && String::from_utf8_lossy(&r.stderr).contains("not a folder")); +} + #[test] fn calibrate_reads_raf_inputs_and_reports_bad_files() { let input = tmp("invalid.RAF"); diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 31ae7229f5..d5dcbc7360 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -371,6 +371,7 @@ fn main() -> eframe::Result { app.notices.extend(launch_notices); app.notices.extend(window_notice); app.gpu_notice = true; + app.disk_space_notice = true; // an empty library opens where Import is offered (a grid, with the sidebar); before // the snapshot below, so this alone isn't written to the settings file if problem.is_none() && files.is_empty() { diff --git a/crates/codecs/src/jpeg.rs b/crates/codecs/src/jpeg.rs index 89af1372bf..3e09ae1c4e 100644 --- a/crates/codecs/src/jpeg.rs +++ b/crates/codecs/src/jpeg.rs @@ -862,3 +862,210 @@ mod tests { } } } + +/// [`crate::decode_jpeg_srgb8_fit`]: a plain 8-bit sRGB JPEG decoded (DCT-scaled when that still +/// covers the box) and area-averaged in linear light straight into 8-bit sRGB, without the +/// float image the general path builds (for a 45 MP camera preview fitted to 2560 px that float +/// image and its conversions were half the time). `Ok(None)` for anything else. +pub(crate) fn srgb8_fit(bytes: &[u8], max_w: u32, max_h: u32) -> Result> { + // (a Samsung SEF trailer read as the file it stands for, as the general decode does: CodeRabbit on #3583) + let bytes = &*without_sef_trailer(bytes); + let Some(m) = parse_markers(bytes) else { return Ok(None) }; + let plain = matches!(m.components, 1 | 3) + && m.precision == 8 + && matches!(m.sof, 0xC0..=0xC2) + && m.icc.is_none() + && !m.icc_invalid + && m.adobe_transform.is_none(); + let summary = m.exif.as_deref().map(exif::summarize).unwrap_or_default(); + if !plain || summary.adobe_rgb_hint || max_w == 0 || max_h == 0 { + return Ok(None); + } + let budget = DecodeOptions::default(); + check_size(F, m.width as u64, m.height as u64, &budget)?; + // as in the general decode: the decoders below walk every APP1 again + if m.app1 > MAX_APP1 { + return Err(Error::Malformed(F, "too many APP1 markers".into())); + } + let scale_to = (m.width >= max_w.saturating_mul(2) || m.height >= max_h.saturating_mul(2)).then_some((max_w, max_h)); + let non_interleaved = matches!(m.sof, 0xC0 | 0xC1) && m.first_scan_components < m.components; + let raw = + if scale_to.is_some() || non_interleaved { decode_jpeg_decoder(bytes, &m, scale_to, &budget)? } else { decode_zune(bytes, &m, &budget)? }; + let Buf::U8(px) = &raw.buf else { return Ok(None) }; + let ch = match raw.model { + Model::Rgb => 3, + Model::Gray => 1, + Model::Cmyk => return Ok(None), + }; + let (w, h) = (raw.width, raw.height); + if w == 0 || h == 0 || px.len() < w.saturating_mul(h).saturating_mul(ch) { + return Err(Error::Malformed(F, "short output".into())); + } + // the size `lightcraft_raster::resample::fit` gives: within the box, aspect kept, never larger + let s = (max_w as f64 / w as f64).min(max_h as f64 / h as f64).min(1.0); + let tw = ((w as f64 * s).round() as usize).clamp(1, w); + let th = ((h as f64 * s).round() as usize).clamp(1, h); + let orientation = summary.orientation.filter(|o| (1..=8).contains(o)).unwrap_or(1); + Ok(Some((area_average_srgb8(px, w, h, ch, tw, th), orientation))) +} + +/// Source pixels and weights each output pixel along one axis covers: a box of the scale's width +/// (`n` source pixels onto `out`), partly covered pixels at its ends weighted by their share. +fn box_taps(n: usize, out: usize) -> Vec<(usize, Vec)> { + let scale = n as f64 / out as f64; + (0..out) + .map(|o| { + let (a, b) = (o as f64 * scale, ((o + 1) as f64 * scale).min(n as f64)); + let first = (a.floor() as usize).min(n - 1); + let last = ((b.ceil() as usize).max(first + 1)).min(n); + let ws: Vec = + (first..last).map(|j| ((b.min(j as f64 + 1.0) - a.max(j as f64)).max(0.0) / (b - a).max(f64::MIN_POSITIVE)) as f32).collect(); + (first, ws) + }) + .collect() +} + +/// `px` (`w × h`, `ch` = 1 or 3 interleaved 8-bit sRGB samples) averaged over boxes in linear +/// light into `tw × th` opaque 8-bit sRGB pixels. A copy when the size doesn't change. +fn area_average_srgb8(px: &[u8], w: usize, h: usize, ch: usize, tw: usize, th: usize) -> lightcraft_raster::Rgba8 { + use lightcraft_color::transfer::{decode_srgb8, encode_srgb8}; + let mut out = lightcraft_raster::Rgba8::new(tw, th); + let sample = |x: usize, y: usize, c: usize| px.get((y * w + x) * ch + if ch == 3 { c } else { 0 }).copied().unwrap_or(0); + if (tw, th) == (w, h) { + lightcraft_raster::par_rows(&mut out.data, tw, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + *o = [sample(x, y, 0), sample(x, y, 1), sample(x, y, 2), 255]; + } + }); + return out; + } + let lut: [f32; 256] = std::array::from_fn(|i| decode_srgb8(i as u8)); + let xs = box_taps(w, tw); + let ys = box_taps(h, th); + // one source row filtered across into linear RGB at the output width + let across = |sy: usize, buf: &mut Vec<[f32; 3]>| { + buf.clear(); + let Some(src) = px.get(sy * w * ch..(sy + 1) * w * ch) else { + buf.resize(tw, [0.0; 3]); + return; + }; + for (x0, wx) in &xs { + let mut a = [0f32; 3]; + if let Some(span) = src.get(x0 * ch..(x0 + wx.len()) * ch) { + for (p, &k) in span.chunks_exact(ch).zip(wx) { + match p { + [r, g, b] => { + a[0] += lut[*r as usize] * k; + a[1] += lut[*g as usize] * k; + a[2] += lut[*b as usize] * k; + } + [v] => { + let l = lut[*v as usize] * k; + a = [a[0] + l, a[1] + l, a[2] + l]; + } + _ => {} + } + } + } + buf.push(a); + } + }; + lightcraft_raster::par_rows(&mut out.data, tw, |y, row| { + let Some((y0, wy)) = ys.get(y) else { return }; + let mut acc = vec![[0f32; 3]; tw]; + let mut line = Vec::with_capacity(tw); + for (dy, &k) in wy.iter().enumerate() { + across(y0 + dy, &mut line); + for (a, l) in acc.iter_mut().zip(&line) { + a[0] += l[0] * k; + a[1] += l[1] * k; + a[2] += l[2] * k; + } + } + for (o, a) in row.iter_mut().zip(&acc) { + *o = [encode_srgb8(a[0]), encode_srgb8(a[1]), encode_srgb8(a[2]), 255]; + } + }); + out +} + +#[cfg(test)] +mod srgb8_fit_tests { + use super::*; + + fn jpeg(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 3]) -> Vec { + let data: Vec<[u8; 4]> = (0..w * h) + .map(|i| { + let [r, g, b] = f(i % w, i / w); + [r, g, b, 255] + }) + .collect(); + let img = lightcraft_raster::Rgba8 { width: w, height: h, data }; + crate::encode_jpeg(&crate::EncodeImage::rgba8(&img), 95, crate::ChromaSubsampling::S420, &crate::EncodeMeta::default()).unwrap() + } + + /// The fast path shows what the general decode shows for a plain sRGB JPEG, at the same size. + #[test] + fn matches_the_general_decode_within_a_few_levels() { + let b = jpeg(1203, 801, |x, y| [((x * 7) ^ (y * 3)) as u8, (x / 5 + y / 3) as u8, ((x * y) % 251) as u8]); + for (mw, mh) in [(300u32, 300u32), (640, 640), (1203, 801), (5000, 5000), (500, 120)] { + let (fast, o) = srgb8_fit(&b, mw, mh).unwrap().unwrap(); + let slow = crate::decode(&b, DecodeOptions::fit(mw, mh)).unwrap().to_srgb8(); + assert_eq!((fast.width, fast.height), (slow.width, slow.height), "box {mw}×{mh}"); + assert_eq!(o, 1); + let diff: Vec = + fast.data.iter().zip(&slow.data).flat_map(|(a, b)| (0..3).map(move |c| (a[c] as i32 - b[c] as i32).unsigned_abs())).collect(); + let mean = diff.iter().sum::() as f64 / diff.len() as f64; + assert!(mean < 3.0, "box {mw}×{mh}: mean difference {mean}"); + } + } + + /// Anything but plain 8-bit sRGB goes the general way; junk is an error or `None`, never a panic. + #[test] + fn declines_what_it_does_not_cover_and_never_panics() { + let b = jpeg(64, 48, |x, _| [x as u8, 0, 0]); + assert!(srgb8_fit(&b, 0, 10).unwrap().is_none()); + assert!(srgb8_fit(b"not a jpeg", 10, 10).unwrap().is_none()); + for cut in [0, 2, 20, b.len() / 2, b.len() - 3] { + let _ = srgb8_fit(&b[..cut], 32, 32); + } + // a 1-pixel-wide image into a box much smaller in one axis + let thin = jpeg(1, 300, |_, y| [y as u8, y as u8, y as u8]); + let (img, _) = srgb8_fit(&thin, 10, 10).unwrap().unwrap(); + assert_eq!((img.width, img.height), (1, 10)); + } + + /// An incomplete ICC_PROFILE sequence (chunk 1 of 2) is "has a profile we can't read", not + /// "plain sRGB": the general decode handles it, as the doc says (CodeRabbit on #3577). + #[test] + fn an_incomplete_icc_sequence_goes_the_general_way() { + let b = jpeg(16, 16, |x, y| [x as u8, y as u8, 0]); + let mut seg = vec![0xFF, 0xE2, 0, 0]; + seg.extend_from_slice(b"ICC_PROFILE"); + seg.extend_from_slice(&[1, 2]); + seg.extend_from_slice(&[0u8; 64]); + let len = u16::try_from(seg.len() - 2).unwrap(); + seg[2..4].copy_from_slice(&len.to_be_bytes()); + let mut with = b[..2].to_vec(); + with.extend_from_slice(&seg); + with.extend_from_slice(&b[2..]); + assert!(parse_markers(&with).unwrap().icc_invalid); + assert!(srgb8_fit(&b, 8, 8).unwrap().is_some()); + assert!(srgb8_fit(&with, 8, 8).unwrap().is_none()); + } + + /// The 8-bit path refuses an APP1 flood before its decoders walk it again, as the general one does. + #[test] + fn an_app1_flood_is_refused_by_the_8_bit_path_too() { + let b = jpeg(16, 16, |x, y| [x as u8, y as u8, 0]); + let mut flood = b[..2].to_vec(); + for _ in 0..200 { + flood.extend_from_slice(&[0xFF, 0xE1, 0x00, 0x02]); + } + flood.extend_from_slice(&b[2..]); + match srgb8_fit(&flood, 8, 8) { + Err(Error::Malformed(_, m)) => assert!(m.contains("APP1"), "{m}"), + other => panic!("unexpected: {other:?}"), + } + } +} diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index 8210f33f01..ad918ddd02 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -169,6 +169,21 @@ pub fn decode(bytes: &[u8], opts: DecodeOptions) -> Result { std::panic::catch_unwind(|| decode_unguarded(bytes, format, &opts)).unwrap_or_else(|_| Err(Error::Malformed(format, "decoder panicked".into()))) } +/// A JPEG for display, fast: fitted within `max_w × max_h` (never enlarged) as 8-bit sRGB with its +/// EXIF orientation (1..=8, not applied), the picture `decode(bytes, DecodeOptions::fit(..)) +/// .to_srgb8()` gives within a few levels, in about half the time for a large camera preview. +/// `Ok(None)` when the file is not a plain 8-bit sRGB JPEG (an ICC profile or an Adobe RGB EXIF +/// hint, CMYK, 12-bit, lossless or arithmetic coding) or its headers can't be read: use +/// [`decode`], which reports a malformed header as an error. Bad scan data is an error here, and +/// nothing is ever a panic. +pub fn decode_jpeg_srgb8_fit(bytes: &[u8], max_w: u32, max_h: u32) -> Result> { + if sniff(bytes) != Some(Format::Jpeg) { + return Ok(None); + } + std::panic::catch_unwind(|| jpeg::srgb8_fit(bytes, max_w, max_h)) + .unwrap_or_else(|_| Err(Error::Malformed(Format::Jpeg, "decoder panicked".into()))) +} + /// What a file's headers say about its image: enough to catalogue it without decoding pixels. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Header { diff --git a/crates/codecs/tests/it/header.rs b/crates/codecs/tests/it/header.rs index f6ce7d3216..7fec902228 100644 --- a/crates/codecs/tests/it/header.rs +++ b/crates/codecs/tests/it/header.rs @@ -208,6 +208,10 @@ fn samsung_sef_trailer_without_eoi() { assert_eq!(full.image.data, reference.image.data, "the same pixels as the file with its EOI"); let small = decode(&pano, DecodeOptions::fit(32, 32)).unwrap(); assert_eq!((small.source_width, small.source_height), (160, 96)); + // the fast display decode too, scaled (where the trailer after the scan used to fail it) + let (fit, _) = lightcraft_codecs::decode_jpeg_srgb8_fit(&pano, 32, 32).unwrap().unwrap(); + let (fit_ref, _) = lightcraft_codecs::decode_jpeg_srgb8_fit(&jpeg, 32, 32).unwrap().unwrap(); + assert_eq!((fit.width, fit.height, &fit.data), (fit_ref.width, fit_ref.height, &fit_ref.data)); // an FF D9 inside the SEF data is not the image's end let eoi_in_data = sef_file(scan, block, b"SEFH", 0x08E0, &[0xFF, 0xC0, 0, 0x11, 0xFF, 0xD9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], None); assert_eq!(read_header(&eoi_in_data).unwrap().width, 160); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0d40c73184..a01f28510b 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -49,6 +49,8 @@ lightcraft-segment = { workspace = true, optional = true } lightcraft-fetch = { workspace = true } # capture-time parsing for face recognition (native only) chrono = { workspace = true } +# free space of the drive holding the preview cache (the low-disk alert; pure Rust: rustix / windows-sys) +fs4 = { workspace = true } [features] # AI masks with SAM 3 (Object / Describe). Off for the web and CLI builds. diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index b99e97c054..4274e689c9 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -1367,6 +1367,8 @@ pub fn specs() -> Vec { ), // ---- persistence cmd!(query "library.info", "Library Info", [], None, "{}", always, |s, _| { + // the answer of a free-space read that ran on a worker (lowDiskSpace below) + s.poll_disk_space(); let photos = s.catalog.len(); let albums = s.catalog.albums().count(); let (rendered_n, rendered_bytes) = s.media.rendered.mem_usage(); @@ -1402,6 +1404,8 @@ pub fn specs() -> Vec { "lastError": lib.last_error, // settings files that were unreadable or damaged at open (kept, defaults used) "settingsWarnings": lib.settings_warnings, + // the drive holding the preview cache ran low this session (warned once) + "lowDiskSpace": s.disk_space_alert_raised(), // changes applied in memory whose write failed (retried by every save) "unsavedOps": s.unsaved().map_or(0, |u| u.0), "unsavedError": s.unsaved().map(|u| u.1), diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index 95aff90b79..e9c40232e9 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -31,6 +31,20 @@ pub struct PreviewBuild { pub what: &'static str, /// Why the whole build failed (e.g. the smart previews folder isn't there). pub error: std::sync::Mutex>, + /// Photos whose previews were there already (from an earlier build, the loupe or the photos + /// prepared ahead): counted as done, not rendered again (PERF-PREVIEW-REUSE). + pub skipped: AtomicUsize, + /// Photos left alone because another job was building them at that moment. + pub shared: AtomicUsize, + /// Started by the background preparation ([`crate::prep`]): it yields to the photo on screen, + /// and a build the user (or an import) asks for replaces it. + pub background: bool, + /// The photos in build order (ids), and where the user is among them: the next photo built + /// is the nearest one not built yet from there, in the direction of travel + /// ([`PreviewBuild::focus_on`]). + pub order: Vec, + pub focus: AtomicUsize, + pub backward: AtomicBool, /// Test-only: the gate this build's lanes wait at before a photo's first render (see /// [`test_gate`]). Captured by `build` on the calling thread; production builds never have one. #[cfg(test)] @@ -47,10 +61,38 @@ impl PreviewBuild { "cancelled": self.cancel.load(Ordering::Relaxed), "what": if self.what.is_empty() { "previews" } else { self.what }, "repaired": self.repaired.load(Ordering::Relaxed), + "skipped": self.skipped.load(Ordering::Relaxed), + "shared": self.shared.load(Ordering::Relaxed), + "background": self.background, "error": self.error(), }) } + pub fn running(&self) -> bool { + !self.finished.load(Ordering::Relaxed) + } + + /// The user is at photo `id`, moving `backward` or forward: build from there on. + pub fn focus_on(&self, id: lightcraft_catalog::PhotoId, backward: bool) { + if let Some(i) = self.order.iter().position(|p| *p == id.0) { + self.focus.store(i, Ordering::Relaxed); + self.backward.store(backward, Ordering::Relaxed); + } + } + + /// Index of the next photo to build in `queue` (`None`: none left): the first one still there + /// from the focus on in the direction of travel, then the rest the other way. + pub(crate) fn next_index(&self, queue: &[Option]) -> Option { + let n = queue.len(); + let at = self.focus.load(Ordering::Relaxed).min(n.saturating_sub(1)); + let there = |i: &usize| queue.get(*i).is_some_and(Option::is_some); + if self.backward.load(Ordering::Relaxed) { + (0..=at).rev().find(there).or_else(|| (at..n).find(there)) + } else { + (at..n).find(there).or_else(|| (0..at).rev().find(there)) + } + } + pub fn error(&self) -> Option { self.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone() } @@ -69,9 +111,93 @@ pub(crate) fn jobs_for(s: &mut Session, id: lightcraft_catalog::PhotoId, edge: O if e >= thumb { view.into_iter().chain(grid).collect() } else { grid.into_iter().chain(view).collect() } } +/// The previews the build of one photo would make are all there already, big enough: its view +/// render at least as large as asked for (`view_cache` of the view job) and its grid thumbnail +/// (`cache` of the thumbnail job), on disk when the cache has one: a render the loupe kept only in +/// memory (its deferred disk write skipped) is built again, and written. Only file headers are read. +pub(crate) fn already_built(jobs: &[RenderJob]) -> bool { + !jobs.is_empty() + && jobs.iter().all(|j| { + if let Some((cache, key)) = &j.view_cache { + let want = j.request.max_w.max(j.request.max_h) as f64; + cache.stored_dims(*key).is_some_and(|(w, h)| w.max(h) as f64 >= want * 0.99) + } else if let Some((cache, key)) = &j.cache { + cache.stored_dims(*key).is_some() + } else { + false + } + }) +} + +/// Photos some preview build is rendering right now, by (the cache they go to, photo id): two +/// builds (a background one being replaced, and the one replacing it) never render the same photo +/// at once. +static BUILDING: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Holds a photo in [`BUILDING`] while it is rendered. +struct Building((usize, u64)); + +impl Building { + /// `id` of `jobs` (the cache their results go to tells sessions apart). + fn take(id: u64, jobs: &[RenderJob]) -> Option { + let cache = jobs.iter().find_map(|j| j.view_cache.as_ref().or(j.cache.as_ref())).map_or(0, |(c, _)| Arc::as_ptr(c) as usize); + let id = (cache, id); + let mut b = BUILDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if b.contains(&id) { + return None; + } + b.push(id); + Some(Building(id)) + } + + /// [`Self::take`], waiting while another build renders the photo (a build asked for replacing the + /// background one may meet it on the same photo): the photo is not counted until that render is over, as + /// built when it made the previews, else rendered here. With whether it had to wait; `None` when `cancel` + /// was asked for meanwhile. (On the web, with one thread, a photo held is not waited for: `Some((None, true))`.) + fn wait(id: u64, jobs: &[RenderJob], cancel: &AtomicBool) -> Option<(Option, bool)> { + if let Some(b) = Self::take(id, jobs) { + return Some((Some(b), false)); + } + Self::wait_held(id, jobs, cancel) + } + + /// [`Self::wait`] for a photo another build holds. + #[cfg(not(target_arch = "wasm32"))] + fn wait_held(id: u64, jobs: &[RenderJob], cancel: &AtomicBool) -> Option<(Option, bool)> { + loop { + if cancel.load(Ordering::Relaxed) { + return None; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + if let Some(b) = Self::take(id, jobs) { + return Some((Some(b), true)); + } + } + } + + /// [`Self::wait`] for a photo another build holds: on the web, with one thread, it is not waited for. + #[cfg(target_arch = "wasm32")] + fn wait_held(_id: u64, _jobs: &[RenderJob], cancel: &AtomicBool) -> Option<(Option, bool)> { + (!cancel.load(Ordering::Relaxed)).then_some((None, true)) + } +} + +/// Tests: hold `id` of `jobs` as a build rendering it would, until the returned value is dropped. +#[cfg(test)] +pub(crate) fn hold_building(id: u64, jobs: &[RenderJob]) -> Option> { + Building::take(id, jobs).map(|b| Box::new(b) as Box) +} + +impl Drop for Building { + fn drop(&mut self) { + BUILDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner).retain(|x| *x != self.0); + } +} + /// The build's row in the activity stack (`what` as in [`PreviewBuild::what`]). fn task_for(s: &Session, state: &PreviewBuild) -> TaskGuard { let (kind, label) = match state.what { + "" if state.background => ("previews", "Preparing photos in the background"), "" => ("previews", "Building previews"), "smart previews" => ("smartPreviews", "Building smart previews"), _ => ("smartPreviews", "Discarding smart previews"), @@ -84,7 +210,8 @@ fn task_for(s: &Session, state: &PreviewBuild) -> TaskGuard { /// Render one photo's jobs in order. The source the first job decodes serves the ones after it /// (the grid thumbnail is made from the view's source instead of decoding the file again). /// `None` when `cancel` was asked for before a job started: that photo is not counted as done. -fn run_photo_cancellable(jobs: Vec, cancel: Option<&AtomicBool>) -> Option { +/// `force`: the grid thumbnail is rendered too, not taken from the cache it is written to. +fn run_photo_cancellable(jobs: Vec, cancel: Option<&AtomicBool>, force: bool) -> Option { let mut decoded: Option = None; let mut ok = true; for mut j in jobs { @@ -97,7 +224,33 @@ fn run_photo_cancellable(jobs: Vec, cancel: Option<&AtomicBool>) -> O { j.source = crate::media::SourceRef::Loaded(Box::new(src.clone())); } + // The view render is written to the disk cache here, before the photo counts as built, + // not left to the cache's writer (which skips writes when it falls behind): a built + // preview is on disk, for this session and the next. (Taken out of the job: it would only + // queue the write, and would serve a smaller cached view.) + // A preview that isn't kept fails the photo: it is not built (a full or unwritable cache folder, or the + // cache discarded while the photo rendered). + let keep = j.view_cache.take().map(|v| (v, j.cache_generation)); + // forced: the thumbnail job's cache is only written to, after the render (a job reads its cache first; + // CodeRabbit on #3577) + let rewrite = if force { j.cache.take().map(|c| (c, j.cache_generation)) } else { None }; let r = j.run(); + if let (Some(((cache, key), generation)), Ok(img)) = (rewrite, r.rendered.as_ref()) + && !cache.put_at(generation, key, Arc::new(img.image.clone())) + { + log::warn!("building previews: the grid thumbnail could not be kept"); + ok = false; + } + if let (Some(((cache, key), generation)), Ok(img)) = (keep, r.rendered.as_ref()) + && !cache.put_at(generation, key, Arc::new(img.image.clone())) + { + if cache.generation() == generation { + log::warn!("building previews: the view preview could not be written to the cache folder"); + } else { + log::warn!("building previews: the preview cache was discarded while the photo rendered"); + } + ok = false; + } ok &= r.rendered.is_ok(); if decoded.is_none() { decoded = r.loaded; @@ -109,7 +262,7 @@ fn run_photo_cancellable(jobs: Vec, cancel: Option<&AtomicBool>) -> O /// [`run_photo_cancellable`] for callers that render a photo without a cancel flag. #[cfg(test)] pub(crate) fn run_photo(jobs: Vec) -> bool { - run_photo_cancellable(jobs, None) == Some(true) + run_photo_cancellable(jobs, None, false) == Some(true) } /// How many photos render side by side: as many as an export batch for standard previews (each @@ -224,34 +377,83 @@ pub(crate) mod test_gate { pub(crate) fn take() -> Option> { NEXT_GATE.with(|g| g.borrow_mut().take()) } + + thread_local! { + /// The next build started on this thread fails to start its worker (a thread the system + /// won't give), taken by `build`. + static FAIL_SPAWN: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + /// Have the next build started on this thread fail to start its worker. + pub(crate) fn fail_next_spawn() { + FAIL_SPAWN.with(|f| f.set(true)); + } + + /// Whether this build's worker is to fail to start (once). + pub(crate) fn take_fail_spawn() -> bool { + FAIL_SPAWN.with(std::cell::Cell::take) + } } -fn run_all(jobs: Vec>, state: &PreviewBuild, task: &TaskGuard, lanes: usize) { +/// One photo's work in a build: its id and its render jobs ([`jobs_for`]). +type PhotoJobs = (u64, Vec); + +/// Build every photo of `jobs` on `lanes` threads. `force`: render even the photos whose previews +/// are there. `task`: the build's own row (`None`: another job's row shows it, e.g. the import's +/// Getting photos ready). +fn run_all(jobs: Vec, state: &PreviewBuild, task: Option<&TaskGuard>, lanes: usize, force: bool) { let total = jobs.len(); - let queue = std::sync::Mutex::new(jobs.into_iter()); + let queue = std::sync::Mutex::new(jobs.into_iter().map(Some).collect::>()); let work = || { loop { if state.cancel.load(Ordering::Relaxed) { break; } - let next = queue.lock().unwrap_or_else(std::sync::PoisonError::into_inner).next(); - let Some(photo_jobs) = next else { break }; + // the background preparation waits while the photo on screen is being made + if state.background && crate::prep::wait_for_foreground(&state.cancel) { + break; + } + let next = { + let mut q = queue.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + state.next_index(&q).and_then(|i| q.get_mut(i)).and_then(Option::take) + }; + let Some((id, photo_jobs)) = next else { break }; // A cancel accepted while this lane waited for the queue (or for another lane's // photo) stops before this photo's first render; a cancelled photo is not counted. if state.cancel.load(Ordering::Relaxed) { break; } - #[cfg(test)] - if let Some(gate) = &state.gate { - gate.enter(); - } - let outcome = crate::guard::catch("building previews", || run_photo_cancellable(photo_jobs, Some(&state.cancel))).unwrap_or(Some(false)); - let Some(ok) = outcome else { break }; - if !ok { - state.failed.fetch_add(1, Ordering::Relaxed); + if !force && already_built(&photo_jobs) { + state.skipped.fetch_add(1, Ordering::Relaxed); + } else if let Some((held, shared)) = Building::wait(id, &photo_jobs, &state.cancel) { + // another build was rendering this photo: what it made counts, if it made it (not + // for a forced build, which renders every photo itself) + if !force && shared && (held.is_none() || already_built(&photo_jobs)) { + state.shared.fetch_add(1, Ordering::Relaxed); + let done = state.done.fetch_add(1, Ordering::Relaxed).saturating_add(1); + if let Some(task) = task { + task.progress(done as u64, total as u64); + } + continue; + } + #[cfg(test)] + if let Some(gate) = &state.gate { + gate.enter(); + } + let outcome = + crate::guard::catch("building previews", || run_photo_cancellable(photo_jobs, Some(&state.cancel), force)).unwrap_or(Some(false)); + let Some(ok) = outcome else { break }; + if !ok { + state.failed.fetch_add(1, Ordering::Relaxed); + } + } else { + // cancelled while another build was rendering it: not counted + break; } let done = state.done.fetch_add(1, Ordering::Relaxed).saturating_add(1); - task.progress(done as u64, total as u64); + if let Some(task) = task { + task.progress(done as u64, total as u64); + } } }; #[cfg(not(target_arch = "wasm32"))] @@ -272,43 +474,99 @@ fn run_all(jobs: Vec>, state: &PreviewBuild, task: &TaskGuard, la state.finished.store(true, Ordering::Relaxed); } +/// The long edge a standard preview is built at: [`STANDARD_EDGE`], or what the loupe asks for +/// on this screen when that is more ([`Session::loupe_edge`]), so the loupe finds what was built. +pub fn standard_edge(s: &Session) -> usize { + STANDARD_EDGE.max(s.loupe_edge.min(8192)) +} + fn build(s: &mut Session, p: &Value) -> Result { const C: &str = "library.buildPreviews"; // tests: this invocation's gate, consumed here so an early error cannot attach it to a later build #[cfg(test)] let gate = test_gate::take(); let edge = match str_param(p, "size").unwrap_or("standard") { - "standard" => Some(p.get("edge").and_then(Value::as_u64).map_or(STANDARD_EDGE, |e| e.clamp(256, 8192) as usize)), + "standard" => Some(p.get("edge").and_then(Value::as_u64).map_or_else(|| standard_edge(s), |e| e.clamp(256, 8192) as usize)), "full" | "1:1" => None, other => return Err(bad(C, format!("unknown size `{other}` (standard|full)"))), }; - if s.preview_build.as_ref().is_some_and(|b| !b.finished.load(Ordering::Relaxed)) { - return Err(bad(C, "a preview build is already running")); + let background = p.get("background").and_then(Value::as_bool).unwrap_or(false); + let force = p.get("force").and_then(Value::as_bool).unwrap_or(false); + // (`row: false`: the job that asked shows the progress in its own row) + let row = p.get("row").and_then(Value::as_bool).unwrap_or(true); + // the background preparation gives way to a build that was asked for; nothing replaces a build + // that was asked for (it carries on, and the photos it built are skipped by the next). The + // background one is stopped only once this request is known to be good (below): a request + // with bad ids leaves it running (CodeRabbit on #3544) + let mut gives_way = None; + if let Some(b) = s.preview_build.as_ref().filter(|b| b.running()) { + if b.background && !background { + gives_way = Some(b.cancel.clone()); + } else { + return Err(bad(C, "a preview build is already running")); + } } - // explicit ids, else the selection, else everything in view - let ids = if p.get("ids").is_some() || p.get("id").is_some() || !s.selection.ids.is_empty() { s.targets(p)? } else { s.visible_cloned() }; - let jobs: Vec> = ids.iter().map(|id| jobs_for(s, *id, edge)).filter(|j| !j.is_empty()).collect(); + s.fit_disk_cache(); + // explicit ids, else the selected photos (more than one: as the menu says), else everything in + // view (a single photo selected is the one open, not a choice of photos: "Visible" in the menu) + let ids = if p.get("ids").is_some() || p.get("id").is_some() || (!background && s.selection.ids.len() > 1) { + s.targets(p)? + } else { + s.visible_cloned() + }; + let jobs: Vec = ids.iter().map(|id| (id.0, jobs_for(s, *id, edge))).filter(|j| !j.1.is_empty()).collect(); + // the background build stays the session's until this one has started (a worker that can't + // start leaves it running and in place: CodeRabbit on #3544) + let previous = s.preview_build.clone(); + let order = jobs.iter().map(|j| j.0).collect(); + #[cfg_attr(not(test), allow(unused_mut))] + let mut build_state = PreviewBuild { total: jobs.len(), background, order, ..Default::default() }; #[cfg(test)] - let state = Arc::new(PreviewBuild { total: jobs.len(), gate, ..Default::default() }); - #[cfg(not(test))] - let state = Arc::new(PreviewBuild { total: jobs.len(), ..Default::default() }); + { + build_state.gate = gate; + } + let state = Arc::new(build_state); + if let Some(at) = p.get("from").and_then(Value::as_u64) { + state.focus_on(lightcraft_catalog::PhotoId(at), p.get("backward").and_then(Value::as_bool).unwrap_or(false)); + } s.preview_build = Some(state.clone()); - let task = task_for(s, &state); - let lanes = lanes(jobs.len(), edge.is_none()); + let task = row.then(|| task_for(s, &state)); + // the background preparation leaves most of the machine to the photo on screen and the user + let lanes = if background { crate::prep::background_lanes() } else { lanes(jobs.len(), edge.is_none()) }; let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false) || cfg!(target_arch = "wasm32"); if wait { - run_all(jobs, &state, &task, lanes); + if let Some(cancel) = gives_way { + cancel.store(true, Ordering::Relaxed); + } + run_all(jobs, &state, task.as_ref(), lanes, force); return Ok(state.json()); } #[cfg(not(target_arch = "wasm32"))] { // the row stays while the worker runs (it is dropped with the closure, however that ends) let st = state.clone(); - std::thread::Builder::new() - .name("lc-build-previews".into()) - .spawn(move || run_all(jobs, &st, &task, lanes)) - .map_err(|e| bad(C, format!("could not start: {e}")))?; + #[cfg(test)] + let started = if test_gate::take_fail_spawn() { + drop(task); + Err(std::io::Error::other("no thread (test)")) + } else { + std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &st, task.as_ref(), lanes, force)) + }; + #[cfg(not(test))] + let started = std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &st, task.as_ref(), lanes, force)); + if let Err(e) = started { + // never started: not left "running", which would hold every later build back, and the + // build it was to replace carries on + state.finished.store(true, Ordering::Relaxed); + s.preview_build = previous; + return Err(bad(C, format!("could not start: {e}"))); + } + if let Some(cancel) = gives_way { + cancel.store(true, Ordering::Relaxed); + } } + #[cfg(target_arch = "wasm32")] + let _ = previous; Ok(state.json()) } @@ -476,10 +734,18 @@ fn smart(s: &mut Session, p: &Value) -> Result { let dir = s.media.smart_dir.clone().ok_or_else(|| bad(C, "smart previews need a library on disk"))?; let discard = p.get("discard").and_then(Value::as_bool).unwrap_or(false); let background = p.get("background").and_then(Value::as_bool).unwrap_or(false); - if background && s.preview_build.as_ref().is_some_and(|b| !b.finished.load(Ordering::Relaxed)) { - return Err(bad(C, "a preview build is already running")); + // (as Build Previews: the photos named, or the selected ones when more than one is, else + // everything in view; read first, so a request with bad ids stops nothing: CodeRabbit on #3577) + let ids = if p.get("ids").is_some() || p.get("id").is_some() || s.selection.ids.len() > 1 { s.targets(p)? } else { s.visible_cloned() }; + // (the background preparation gives way, as to Build Previews: once this one's worker has started) + let mut gives_way = None; + if background && let Some(b) = s.preview_build.as_ref().filter(|b| b.running()) { + if b.background { + gives_way = Some(b.cancel.clone()); + } else { + return Err(bad(C, "a preview build is already running")); + } } - let ids = if p.get("ids").is_some() || !s.selection.ids.is_empty() { s.targets(p)? } else { s.visible_cloned() }; let mut jobs: Vec = Vec::new(); for id in ids { let Some(ph) = s.catalog.photo(id).cloned() else { continue }; @@ -496,19 +762,35 @@ fn smart(s: &mut Session, p: &Value) -> Result { if background { let what = if discard { "discarding smart previews" } else { "smart previews" }; let state = Arc::new(PreviewBuild { total: jobs.len(), what, ..Default::default() }); - s.preview_build = Some(state.clone()); + let previous = s.preview_build.replace(state.clone()); let task = task_for(s, &state); let st = state.clone(); - std::thread::Builder::new() - .name("lc-smart-previews".into()) - .spawn(move || { - if let Err(e) = smart_run(&dir, custom, discard, jobs, Some((&st, &task))) { - log::warn!("{C}: {e}"); - *st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e); - } - st.finished.store(true, Ordering::Relaxed); - }) - .map_err(|e| bad(C, format!("could not start: {e}")))?; + let work = move || { + if let Err(e) = smart_run(&dir, custom, discard, jobs, Some((&st, &task))) { + log::warn!("{C}: {e}"); + *st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e); + } + st.finished.store(true, Ordering::Relaxed); + }; + #[cfg(test)] + let started = if test_gate::take_fail_spawn() { + drop(work); + Err(std::io::Error::other("no thread (test)")) + } else { + std::thread::Builder::new().name("lc-smart-previews".into()).spawn(work) + }; + #[cfg(not(test))] + let started = std::thread::Builder::new().name("lc-smart-previews".into()).spawn(work); + if let Err(e) = started { + // never started: not left "running", and the background build it was to replace carries on + // (CodeRabbit on #3077) + state.finished.store(true, Ordering::Relaxed); + s.preview_build = previous; + return Err(bad(C, format!("could not start: {e}"))); + } + if let Some(cancel) = gives_way { + cancel.store(true, Ordering::Relaxed); + } return Ok(state.json()); } let r = smart_run(&dir, custom, discard, jobs, None).map_err(|e| bad(C, e))?; @@ -647,7 +929,7 @@ pub fn specs() -> Vec { "Build Smart Previews", [], None, - "{ids?, discard?: bool, background?: bool} — build (or discard) the smart previews of the selected photos (else all in view): compact proxies in the library that keep photos editable and exportable (at proxy size) while their originals are offline; a damaged proxy (cut short) is rebuilt → {built, repaired, removed, failed}; with background (the app's menu) the files are read and written on a worker thread → {total, done, failed, repaired, running, what} like library.buildPreviews (progress: library.previewProgress, stop: library.cancelPreviews)", + "{ids?, discard?: bool, background?: bool} — build (or discard) the smart previews of the selected photos (when more than one is selected; else all in view): compact proxies in the library that keep photos editable and exportable (at proxy size) while their originals are offline; a damaged proxy (cut short) is rebuilt → {built, repaired, removed, failed}; with background (the app's menu) the files are read and written on a worker thread → {total, done, failed, repaired, running, what} like library.buildPreviews (progress: library.previewProgress, stop: library.cancelPreviews)", always, smart ), @@ -674,13 +956,43 @@ pub fn specs() -> Vec { "Build Previews", [], None, - "{size?: standard (2048 px, or `edge`) | full (1:1), ids?, wait?: bool} — render the grid thumbnail and loupe view of the selected photos (else all in view) into the preview cache, in the background unless `wait` → {total, done, failed, running}", + "{size?: standard (2048 px, or the loupe's size when bigger, or `edge`) | full (1:1), ids?, wait?: bool, force?: bool, from?: id, backward?: bool, background?: bool, row?: bool} — render the grid thumbnail and loupe view of the selected photos (when more than one is selected; else all in view) into the preview cache (memory and disk), in the background unless `wait`. Photos whose previews are there already (big enough) are skipped unless `force`; the photos nearest `from` go first. `background`: the background preparation's build (two lanes, waits while the photo on screen renders; a build asked for replaces it). `row: false`: no row of its own in the activity stack (the caller's row shows it) → {total, done, failed, skipped, shared, running}", always, build ), - cmd!(query "library.previewProgress", "Preview Build Progress", [], None, "{} → {total, done, failed, repaired, running, cancelled, what, error} | null", always, |s, _| { + cmd!(query "library.previewProgress", "Preview Build Progress", [], None, "{} → {total, done, failed, repaired, skipped, shared, background, running, cancelled, what, error} | null", always, |s, _| { Ok(s.preview_build.as_ref().map_or(Value::Null, |b| b.json())) }), + cmd!(query "prefs.backgroundPrep", "Background Preparation Settings", [], None, "{} → {app, library|null, settings (in use), own: bool (this library keeps its own), building} — what is prepared in the background per mode (culling | library: previews of every photo in view, ahead = photos ahead rendered for the loupe, eyeAhead = photos ahead whose eye focus strip is worked out, scope all|marked|onScreen; develop: ahead = photos kept decoded ready to edit, scope)", always, |s, _| { + Ok(s.prep_json()) + }), + cmd!( + "prefs.setBackgroundPrep", + "Set Background Preparation", + [], + None, + "{settings?: partial {culling?, library?, develop?}, library?: bool (this library's own settings; else the app-wide ones), reset?: bool (this library goes back to the app-wide settings)} → as prefs.backgroundPrep", + always, + |s, p| { + const C: &str = "prefs.setBackgroundPrep"; + let library = p.get("library").and_then(Value::as_bool).unwrap_or(false); + if p.get("reset").and_then(Value::as_bool).unwrap_or(false) { + s.clear_library_prep()?; + return Ok(s.prep_json()); + } + if library && s.library.is_none() { + return Err(bad(C, "no library is open")); + } + let base = if library { s.prep.library.unwrap_or(s.prep.app) } else { s.prep.app }; + let next = match p.get("settings") { + Some(patch) if patch.is_object() => base.patched(patch).map_err(|e| bad(C, e))?, + Some(_) => return Err(bad(C, "settings must be an object")), + None => base, + }; + s.set_prep_settings(next, library)?; + Ok(s.prep_json()) + } + ), cmd!("library.cancelPreviews", "Cancel Preview Build", [], None, "{}", always, |s, _| { if let Some(b) = &s.preview_build { b.cancel.store(true, Ordering::Relaxed); diff --git a/crates/engine/src/disk_space.rs b/crates/engine/src/disk_space.rs new file mode 100644 index 0000000000..eb7f29e967 --- /dev/null +++ b/crates/engine/src/disk_space.rs @@ -0,0 +1,577 @@ +//! A once-per-session alert when the drive holding the library's preview cache runs low. +//! +//! The automatic preview cache budget grows with the library and has no ceiling +//! ([`crate::media::default_disk_cache_bytes`]): a large library can fill its drive. Rather than cap +//! it, the session looks at the drive's free space when the library opens and, at most every +//! [`CHECK_EVERY`] while the app runs (thumbnails and previews fill the cache); when it is under [`LOW_FREE_PERCENT`] of the drive or +//! under [`LOW_FREE_BYTES`], it hands out one [`LowDiskAlert`] ([`crate::Session::take_disk_space_alert`]) +//! that the UI shows with a way to Settings ▸ Performance, where the cache can be given a limit. It is +//! not repeated until the next library open or app run. Reading the free space can fail (a network +//! share that doesn't say, the web build): then there is no alert, only a log line. +//! Natively the read runs on a worker thread and its answer is taken on a later call, so a slow +//! network share never holds up the UI thread that asks. + +use std::path::Path; + +/// The drive is low when less than this share of it (percent) is free… +pub const LOW_FREE_PERCENT: u64 = 10; +/// …or when less than this is free (20 GB), whichever comes first. +pub const LOW_FREE_BYTES: u64 = 20 << 30; +/// While a library is open, the free space is read at most this often (statvfs on the cache's +/// drive: cheap, but not something for every frame or every write). +pub const CHECK_EVERY: std::time::Duration = std::time::Duration::from_secs(5 * 60); +/// A read when the library opens that hasn't answered after this long shows in the activity stack. +const SHOW_ROW_AFTER: std::time::Duration = std::time::Duration::from_millis(200); +/// A read whose thread couldn't start (the system out of threads for a moment) is tried again this +/// soon, not after [`CHECK_EVERY`]. +pub const RETRY_AFTER: std::time::Duration = std::time::Duration::from_secs(10); + +/// What a read's worker answers: the drive's space and the cache's size when low (`None`: the drive +/// didn't say), or that the read couldn't start. +type Answer = Result, NotStarted>; + +/// A read's thread couldn't be started. +struct NotStarted; + +/// Space on one drive, in bytes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DiskSpace { + /// Free for this user (what can still be written). + pub available: u64, + /// The drive's size. + pub total: u64, +} + +impl DiskSpace { + /// Under [`LOW_FREE_PERCENT`] of the drive free, or under [`LOW_FREE_BYTES`]. A drive that + /// reports no size isn't judged by its share. + pub fn is_low(&self) -> bool { + let under_share = self.total > 0 && u128::from(self.available) * 100 < u128::from(self.total) * u128::from(LOW_FREE_PERCENT); + under_share || self.available < LOW_FREE_BYTES + } +} + +/// What the UI tells the user once: the drive's free space and size, and how big the preview +/// cache is now. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LowDiskAlert { + pub space: DiskSpace, + /// Bytes the preview cache takes on that drive. + pub cache_bytes: u64, +} + +/// The free space of the drive holding `dir` (or its parent when `dir` isn't there yet). `None` +/// (logged) when it can't be read. +pub fn read(dir: &Path) -> Option { + #[cfg(not(target_arch = "wasm32"))] + { + let probe = if dir.exists() { dir } else { dir.parent().unwrap_or(dir) }; + match fs4::statvfs(probe) { + Ok(s) => Some(DiskSpace { available: s.available_space(), total: s.total_space() }), + Err(e) => { + log::info!("disk space: can't read the free space of {}: {e}", probe.display()); + None + } + } + } + #[cfg(target_arch = "wasm32")] + { + let _ = dir; + None + } +} + +/// Reads the free space of a drive ([`read`]; a test can put a slow one in its place). +pub type Reader = std::sync::Arc Option + Send + Sync>; + +/// The session's state of the alert (reset when a library opens). +#[derive(Default)] +pub(crate) struct DiskAlertState { + /// The alert was handed out (or is waiting to be) this session: never again until reset. + pub(crate) raised: bool, + /// The alert waiting for the UI. + pub(crate) pending: Option, + /// When the free space was last read. + pub(crate) checked_at: Option, + /// The read running on a worker (natively): a network share can take its time to answer, and + /// the check runs on the UI thread. It answers with the drive's space and, when that is low, + /// the preview cache's size (counting the cache can mean reading every file's size: that too + /// stays off the UI thread). + probe: Option>, + /// The running read was started for the library open before this one: its answer is ignored, + /// and the drive is read again for the current library once it has come. Until then no second + /// read starts, so switching libraries while a drive hangs never piles up workers. + stale: bool, + /// In place of [`read`] (tests). + pub(crate) reader: Option, + /// Tests: the read's thread that fails to start (`"disk-space"`, `"disk-space-read"`). + pub(crate) fail_spawn: Option<&'static str>, +} + +/// Start a named thread; `fail` stands for a system that can't (tests). +#[cfg(not(target_arch = "wasm32"))] +fn spawn(name: &str, fail: bool, f: impl FnOnce() + Send + 'static) -> std::io::Result<()> { + if fail { + return Err(std::io::Error::other("no thread (test)")); + } + std::thread::Builder::new().name(name.into()).spawn(f).map(drop) +} + +impl DiskAlertState { + /// A fresh state for a newly opened library (the reader stays; a read still running is kept, + /// marked stale). + pub(crate) fn reset(&mut self) { + let probe = self.probe.take(); + let stale = probe.is_some(); + *self = DiskAlertState { reader: self.reader.take(), fail_spawn: self.fail_spawn, probe, stale, ..Default::default() }; + } +} + +impl crate::Session { + /// Read the free space of the drive holding the preview cache, at most every [`CHECK_EVERY`] + /// (`now`: whatever the last read, as when the library opens), and raise the alert if it is low + /// ([`Session::note_disk_space`](crate::Session::note_disk_space)). Nothing once the alert was + /// raised this session, without an on-disk library, or when the space can't be read. + /// The read itself runs on a worker (natively) and its answer is taken by a later call or + /// [`Session::poll_disk_space`]: a slow drive never holds up the caller. + pub fn check_disk_space(&mut self, now: bool) { + self.poll_disk_space(); + // (a read still running for an earlier library open starts this library's read when it answers) + if self.disk_alert.raised || self.disk_alert.probe.is_some() { + return; + } + let Some(dir) = self.library.as_ref().filter(|l| l.on_disk).map(crate::library::Library::thumbs_dir) else { return }; + let at = web_time::Instant::now(); + if !now && self.disk_alert.checked_at.is_some_and(|t| at.saturating_duration_since(t) < CHECK_EVERY) { + return; + } + self.disk_alert.checked_at = Some(at); + let reader = self.disk_alert.reader.clone(); + let rendered = self.media.rendered.clone(); + let read_now = move || { + let space = match reader { + Some(r) => r(&dir), + None => read(&dir), + }?; + // the cache is counted only when the alert will tell its size + let cache_bytes = if space.is_low() { rendered.disk().map_or(0, |d| d.size()) } else { 0 }; + Some((space, cache_bytes)) + }; + #[cfg(not(target_arch = "wasm32"))] + { + // a read when the library opens that takes more than a moment (a network share slow to + // answer, or the cache counted when the drive is low) shows in the activity stack; a quick + // one, and the quiet periodic ones every few minutes, don't + let activity = now.then(|| self.activity.clone()); + let fail = self.disk_alert.fail_spawn; + let (tx, rx) = std::sync::mpsc::channel(); + let started = spawn("disk-space", fail == Some("disk-space"), move || { + let answer = match activity { + None => Ok(read_now()), + Some(activity) => { + let (done, answered) = std::sync::mpsc::channel(); + let reading = spawn("disk-space-read", fail == Some("disk-space-read"), move || { + let _ = done.send(read_now()); + }); + match reading { + Err(e) => { + log::info!("disk space: can't start the free-space read: {e}"); + Err(NotStarted) + } + Ok(()) => match answered.recv_timeout(SHOW_ROW_AFTER) { + Ok(answer) => Ok(answer), + Err(_) => { + let _row = activity.start("cache", "Checking free disk space", crate::activity::Cancel::No); + Ok(answered.recv().ok().flatten()) + } + }, + } + } + }; + let _ = tx.send(answer); + }); + match started { + Ok(()) => self.disk_alert.probe = Some(rx), + Err(e) => { + log::info!("disk space: can't start the free-space read: {e}"); + self.retry_disk_space_soon(); + } + } + } + #[cfg(target_arch = "wasm32")] + if let Some((space, cache_bytes)) = read_now() { + self.raise_disk_alert(space, cache_bytes); + } + } + + /// Take the answer of the free-space read running on a worker, if it has come, and raise the + /// alert when the drive is low. An answer for an earlier library open is dropped and the drive + /// of the current one is read instead. Called by [`Session::check_disk_space`], + /// [`Session::take_disk_space_alert`] and `library.info`. + pub fn poll_disk_space(&mut self) { + let Some(rx) = self.disk_alert.probe.as_ref() else { return }; + let answer = match rx.try_recv() { + Ok(answer) => answer, + Err(std::sync::mpsc::TryRecvError::Empty) => return, + // (a worker that ended without answering: tried again soon too) + Err(std::sync::mpsc::TryRecvError::Disconnected) => Err(NotStarted), + }; + self.disk_alert.probe = None; + if std::mem::take(&mut self.disk_alert.stale) { + self.check_disk_space(true); + } else { + match answer { + Ok(Some((space, cache_bytes))) => { + self.raise_disk_alert(space, cache_bytes); + } + Ok(None) => {} + Err(NotStarted) => self.retry_disk_space_soon(), + } + } + } + + /// A read that couldn't start counts as made [`RETRY_AFTER`] less than [`CHECK_EVERY`] ago: the next check + /// reads the drive after [`RETRY_AFTER`] (CodeRabbit on #3577: it waited the whole five minutes). + fn retry_disk_space_soon(&mut self) { + let now = web_time::Instant::now(); + self.disk_alert.checked_at = Some(now.checked_sub(CHECK_EVERY.saturating_sub(RETRY_AFTER)).unwrap_or(now)); + } + + /// Raise the low-disk alert for `space` when it is low and the alert wasn't raised this session + /// yet (the numbers come from [`read`], or from a test). Returns whether it was raised now. + /// Counts the preview cache here, on the caller's thread: the session's own reads count it on + /// their worker. + pub fn note_disk_space(&mut self, space: DiskSpace) -> bool { + if self.disk_alert.raised || !space.is_low() { + return false; + } + let cache_bytes = self.media.rendered.disk().map_or(0, |d| d.size()); + self.raise_disk_alert(space, cache_bytes) + } + + /// [`Session::note_disk_space`] with the cache's size already counted. + fn raise_disk_alert(&mut self, space: DiskSpace, cache_bytes: u64) -> bool { + if self.disk_alert.raised || !space.is_low() { + return false; + } + log::warn!("disk space: {} of {} bytes free; the preview cache takes {cache_bytes} bytes", space.available, space.total); + self.disk_alert.raised = true; + self.disk_alert.pending = Some(LowDiskAlert { space, cache_bytes }); + true + } + + /// The low-disk alert not shown yet, if any (handed out once per session). + pub fn take_disk_space_alert(&mut self) -> Option { + self.poll_disk_space(); + self.disk_alert.pending.take() + } + + /// Read the drive's space with `reader` instead of asking the system (tests of the app). + #[doc(hidden)] + pub fn set_disk_space_reader(&mut self, reader: Option) { + self.disk_alert.reader = reader; + } + + /// Forget when the space was last read, as if [`CHECK_EVERY`] had passed (tests of the app). + #[doc(hidden)] + pub fn forget_disk_space_check(&mut self) { + self.disk_alert.checked_at = None; + } + + /// Whether a free-space read is running on its worker (its answer not taken yet). + pub fn disk_space_reading(&self) -> bool { + self.disk_alert.probe.is_some() + } + + /// How long until [`Session::check_disk_space`] reads the drive again (zero when it is due, `None` + /// when it won't: the alert was raised, a read runs, or nothing has been read yet). + pub fn disk_space_next_check_in(&self) -> Option { + let a = &self.disk_alert; + if a.raised || a.probe.is_some() { + return None; + } + Some(CHECK_EVERY.saturating_sub(a.checked_at?.elapsed())) + } + + /// How long the free-space read running on its worker has run (`Duration::MAX` for one started for the + /// library before), or `None` when none runs. + pub fn disk_space_read_running_for(&self) -> Option { + let a = &self.disk_alert; + a.probe.as_ref()?; + Some(a.checked_at.filter(|_| !a.stale).map_or(std::time::Duration::MAX, |t| t.elapsed())) + } + + /// Whether the low-disk alert was raised since the library opened (`library.info` → + /// `lowDiskSpace`). + pub fn disk_space_alert_raised(&self) -> bool { + self.disk_alert.raised + } +} + +#[cfg(test)] +mod tests { + use super::{DiskSpace, LOW_FREE_BYTES}; + use crate::Session; + + const GB: u64 = 1 << 30; + + #[test] + fn plenty_of_room_on_both_counts_raises_no_alert() { + let mut s = Session::new(); + assert!(!s.note_disk_space(DiskSpace { available: 200 * GB, total: 1000 * GB }), "20 % and 200 GB free"); + assert!(!s.note_disk_space(DiskSpace { available: 25 * GB, total: 100 * GB }), "25 % and 25 GB free"); + assert!(s.take_disk_space_alert().is_none()); + assert!(!s.disk_space_alert_raised()); + } + + #[test] + fn under_ten_percent_free_raises_the_alert() { + let mut s = Session::new(); + // 300 GB is far above 20 GB, but only 7.5 % of a 4 TB drive + let space = DiskSpace { available: 300 * GB, total: 4000 * GB }; + assert!(s.note_disk_space(space)); + let alert = s.take_disk_space_alert().expect("the alert is handed out"); + assert_eq!(alert.space, space); + assert!(s.disk_space_alert_raised()); + } + + #[test] + fn under_twenty_gb_free_raises_the_alert() { + let mut s = Session::new(); + // 15 % of a 100 GB drive is free, but that is under 20 GB + let space = DiskSpace { available: 15 * GB, total: 100 * GB }; + assert!(space.available < LOW_FREE_BYTES); + assert!(s.note_disk_space(space)); + assert_eq!(s.take_disk_space_alert().map(|a| a.space), Some(space)); + } + + #[test] + fn the_alert_is_raised_once_per_session() { + let mut s = Session::new(); + let low = DiskSpace { available: GB, total: 500 * GB }; + assert!(s.note_disk_space(low)); + assert!(s.take_disk_space_alert().is_some()); + assert!(s.take_disk_space_alert().is_none(), "handed out once"); + assert!(!s.note_disk_space(DiskSpace { available: GB / 2, ..low }), "lower still: not again this session"); + assert!(s.take_disk_space_alert().is_none()); + s.check_disk_space(true); + assert!(s.take_disk_space_alert().is_none(), "a check after the alert reads nothing"); + } + + #[test] + fn opening_a_library_starts_a_new_session_for_the_alert() { + let dir = std::env::temp_dir().join(format!("lc-disk-alert-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&dir, false).unwrap(); + // whatever this machine's drive holds, raise it by hand + let _ = s.take_disk_space_alert(); + let low = DiskSpace { available: GB, total: 500 * GB }; + if !s.disk_space_alert_raised() { + assert!(s.note_disk_space(low)); + } + assert!(!s.note_disk_space(low), "once per session"); + s.close_library().unwrap(); + s.open_library(&dir, false).unwrap(); + let _ = s.take_disk_space_alert(); + let raised_by_open = s.disk_space_alert_raised(); + assert!(raised_by_open || s.note_disk_space(low), "a new library open may warn again"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A drive that takes its time to answer (a network share) doesn't hold up the library open + /// or the checks on the UI thread: the read runs on a worker and its answer is taken later. + #[test] + fn a_slow_drive_does_not_hold_up_the_check() { + use std::sync::{Arc, Mutex, mpsc}; + let dir = std::env::temp_dir().join(format!("lc-disk-alert-slow-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (release, wait) = mpsc::channel::<()>(); + let wait = Mutex::new(wait); + let mut s = Session::new().with_fs(); + s.disk_alert.reader = Some(Arc::new(move |_: &std::path::Path| { + // answers once the test lets it (or after 10 s, so a broken test can't hang) + let _ = wait.lock().unwrap().recv_timeout(std::time::Duration::from_secs(10)); + Some(DiskSpace { available: GB, total: 500 * GB }) + })); + s.open_library(&dir, false).unwrap(); + assert!(s.take_disk_space_alert().is_none(), "the open didn't wait for the drive's answer"); + // the read the open started shows in the activity stack once it takes more than a moment + // (CodeRabbit on #3077) + let reading = |s: &Session| s.activity.list().iter().any(|t| t.kind == "cache" && t.label == "Checking free disk space"); + let until = web_time::Instant::now() + std::time::Duration::from_secs(10); + while !reading(&s) { + assert!(web_time::Instant::now() < until, "{:?}", s.activity.list()); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(s.disk_space_reading()); + s.check_disk_space(true); + assert!(s.take_disk_space_alert().is_none(), "nor does a check while the read runs"); + release.send(()).unwrap(); + let until = std::time::Instant::now() + std::time::Duration::from_secs(10); + let alert = loop { + if let Some(a) = s.take_disk_space_alert() { + break a; + } + assert!(std::time::Instant::now() < until, "the drive's answer was never taken"); + std::thread::sleep(std::time::Duration::from_millis(5)); + }; + assert_eq!(alert.space.available, GB); + assert!(s.disk_space_alert_raised()); + assert!(!reading(&s) && !s.disk_space_reading(), "the row goes with the read"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A drive that hangs while the user switches libraries: the read still running is kept, no + /// second worker starts beside it, its answer (for the old library) is dropped, and the current + /// library's drive is read once it has come. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn switching_libraries_while_a_drive_hangs_starts_no_second_read() { + use std::sync::{Arc, Mutex, mpsc}; + use std::time::{Duration, Instant}; + let root = std::env::temp_dir().join(format!("lc-disk-alert-switch-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let (a, b) = (root.join("a"), root.join("b")); + std::fs::create_dir_all(&a).unwrap(); + std::fs::create_dir_all(&b).unwrap(); + let (release, wait) = mpsc::channel::<()>(); + let (started_tx, started) = mpsc::channel::(); + let wait = Mutex::new(wait); + let started_tx = Mutex::new(started_tx); + let mut s = Session::new().with_fs(); + s.disk_alert.reader = Some(Arc::new(move |dir: &std::path::Path| { + let _ = started_tx.lock().unwrap().send(dir.to_path_buf()); + let _ = wait.lock().unwrap().recv_timeout(Duration::from_secs(10)); + Some(DiskSpace { available: GB, total: 500 * GB }) + })); + s.open_library(&a, false).unwrap(); + let first = started.recv_timeout(Duration::from_secs(10)).expect("the open reads the drive"); + assert!(first.starts_with(&a), "{first:?}"); + s.close_library().unwrap(); + s.open_library(&b, false).unwrap(); + s.check_disk_space(true); + assert!(started.recv_timeout(Duration::from_millis(300)).is_err(), "no second read beside the hanging one"); + release.send(()).unwrap(); + let until = Instant::now() + Duration::from_secs(10); + let second = loop { + assert!(s.take_disk_space_alert().is_none(), "the old library's answer is dropped"); + if let Ok(dir) = started.try_recv() { + break dir; + } + assert!(Instant::now() < until, "the current library's drive was never read"); + std::thread::sleep(Duration::from_millis(5)); + }; + assert!(second.starts_with(&b), "{second:?}"); + assert!(!s.disk_space_alert_raised()); + release.send(()).unwrap(); + let until = Instant::now() + Duration::from_secs(10); + while s.take_disk_space_alert().is_none() { + assert!(Instant::now() < until, "the current library's answer was never taken"); + std::thread::sleep(Duration::from_millis(5)); + } + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&root); + } + + /// When the drive is low, the preview cache is counted on the read's worker too: counting it can + /// mean reading the size of every file (a big cache on a slow share), never on the UI thread + /// that takes the answer. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_preview_cache_is_counted_off_the_ui_thread() { + use std::sync::{Arc, Mutex, mpsc}; + use std::time::{Duration, Instant}; + let dir = std::env::temp_dir().join(format!("lc-disk-alert-count-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (release, wait) = mpsc::channel::<()>(); + let wait = Mutex::new(wait); + let mut s = Session::new().with_fs(); + s.disk_alert.reader = Some(Arc::new(move |_: &std::path::Path| { + let _ = wait.lock().unwrap().recv_timeout(Duration::from_secs(10)); + Some(DiskSpace { available: GB, total: 500 * GB }) + })); + s.open_library(&dir, false).unwrap(); + let disk = || s.media.rendered.disk().map(lightcraft_preview::DiskCache::known_size); + assert_eq!(disk(), Some(None), "an on-disk library has a preview cache, not counted yet"); + release.send(()).unwrap(); + // no poll here: only the worker can count the cache + let until = Instant::now() + Duration::from_secs(10); + let counted = loop { + if let Some(Some(bytes)) = disk() { + break bytes; + } + assert!(Instant::now() < until, "the worker never counted the cache"); + std::thread::sleep(Duration::from_millis(5)); + }; + let until = Instant::now() + Duration::from_secs(10); + let alert = loop { + if let Some(a) = s.take_disk_space_alert() { + break a; + } + assert!(Instant::now() < until, "the drive's answer was never taken"); + std::thread::sleep(Duration::from_millis(5)); + }; + assert_eq!(alert.cache_bytes, counted); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_free_space_of_a_real_drive_is_read() { + let space = super::read(&std::env::temp_dir().join("lc-disk-alert-not-there")).expect("the temp folder's drive says its size"); + assert!(space.total > 0 && space.available <= space.total, "{space:?}"); + } + + /// A read whose thread can't start is tried again after [`super::RETRY_AFTER`], not after the five minutes + /// of [`super::CHECK_EVERY`] (CodeRabbit on #3577); for either of its two threads. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_read_that_could_not_start_is_tried_again_soon() { + use std::time::{Duration, Instant}; + for thread in ["disk-space", "disk-space-read"] { + let dir = std::env::temp_dir().join(format!("lc-disk-alert-nothread-{thread}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new().with_fs(); + s.disk_alert.reader = Some(std::sync::Arc::new(|_: &std::path::Path| Some(DiskSpace { available: GB, total: 500 * GB }))); + s.disk_alert.fail_spawn = Some(thread); + s.open_library(&dir, false).unwrap(); + let until = Instant::now() + Duration::from_secs(10); + while s.disk_space_reading() { + assert!(Instant::now() < until, "{thread}: the read never ended"); + s.poll_disk_space(); + std::thread::sleep(Duration::from_millis(5)); + } + let since = s.disk_alert.checked_at.expect("a check was made").elapsed(); + assert!( + since + super::RETRY_AFTER + Duration::from_secs(1) >= super::CHECK_EVERY, + "{thread}: next read in {:?}", + super::CHECK_EVERY.saturating_sub(since) + ); + // the thread can start again: the retry reads the drive and raises the alert + s.disk_alert.fail_spawn = None; + s.disk_alert.checked_at = s.disk_alert.checked_at.and_then(|t| t.checked_sub(super::RETRY_AFTER)); + s.check_disk_space(false); + let until = Instant::now() + Duration::from_secs(10); + while s.take_disk_space_alert().is_none() { + assert!(Instant::now() < until, "{thread}: the retry never read the drive"); + std::thread::sleep(Duration::from_millis(5)); + } + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } + } + + #[test] + fn a_drive_that_reports_no_size_is_judged_by_its_free_bytes() { + assert!(!DiskSpace { available: 50 * GB, total: 0 }.is_low()); + assert!(DiskSpace { available: 5 * GB, total: 0 }.is_low()); + } +} diff --git a/crates/engine/src/files/fs.rs b/crates/engine/src/files/fs.rs index 05784d542b..ce8347d701 100644 --- a/crates/engine/src/files/fs.rs +++ b/crates/engine/src/files/fs.rs @@ -37,6 +37,12 @@ pub(super) fn raf_preview_extent(prefix: &[u8]) -> Option { /// `adobe_rgb`: the container declares the preview Adobe RGB ([`PreviewRead::adobe_rgb`]), applied /// as [`decode_raw_preview`] applies it. `None` when the bytes are not a decodable image. pub(super) fn quick_image_srgb(header: &[u8], window: &[u8], adobe_rgb: bool, max_edge: usize) -> Option { + // a plain sRGB camera JPEG (nearly all of them) straight to 8-bit (PERF-CULL-3: 45 MP preview + // of an EOS R5 C fitted to 2560 px, 194 → ~110 ms); anything else takes the general decode + let edge = u32::try_from(max_edge).unwrap_or(u32::MAX); + if !adobe_rgb && let Ok(Some((image, orientation))) = lightcraft_codecs::decode_jpeg_srgb8_fit(window, edge, edge) { + return Some(image.oriented(preview_orientation(header, orientation))); + } let decoded = if adobe_rgb && window.starts_with(&[0xff, 0xd8]) { lightcraft_codecs::decode_jpeg_with_fallback(window, fit_box(max_edge), lightcraft_codecs::NamedSpace::AdobeRgb) } else { diff --git a/crates/engine/src/files/preview.rs b/crates/engine/src/files/preview.rs index 825167f5c1..85ee2c5fb8 100644 --- a/crates/engine/src/files/preview.rs +++ b/crates/engine/src/files/preview.rs @@ -33,7 +33,11 @@ pub(crate) fn decode_raw_preview( opts: lightcraft_codecs::DecodeOptions, covering: Option, ) -> Option { - let jpeg = stand_in_image(bytes, covering)?; + decode_stand_in(bytes, &stand_in_image(bytes, covering)?, opts) +} + +/// [`decode_raw_preview`] of the stand-in `jpeg` already found in the raw file `bytes` (by [`stand_in_image`]). +fn decode_stand_in(bytes: &[u8], jpeg: &[u8], opts: lightcraft_codecs::DecodeOptions) -> Option { // the colour space is a property of the JPEG; a TIFF stand-in (the file itself, or a Hasselblad RGB preview // wrapped as a TIFF) and a JPEG XL preview are read by their own decoders let is_jpeg = jpeg.starts_with(&[0xff, 0xd8]); @@ -43,9 +47,9 @@ pub(crate) fn decode_raw_preview( lightcraft_raw::PreviewColorSpace::Srgb => lightcraft_codecs::NamedSpace::Srgb, lightcraft_raw::PreviewColorSpace::AdobeRgb => lightcraft_codecs::NamedSpace::AdobeRgb, }; - lightcraft_codecs::decode_jpeg_with_fallback(&jpeg, opts, space).ok() + lightcraft_codecs::decode_jpeg_with_fallback(jpeg, opts, space).ok() } - None => lightcraft_codecs::decode(&jpeg, opts).ok(), + None => lightcraft_codecs::decode(jpeg, opts).ok(), } } @@ -80,7 +84,18 @@ pub fn load_embedded_preview(bytes: &[u8], max_edge: usize) -> Option<(Rgb32f, S /// loupe and grid show it until the raw itself has been developed ([`crate::media::QuickJob`]). The smallest /// embedded JPEG that covers `max_edge` is decoded, not the largest. pub fn embedded_preview_srgb(bytes: &[u8], max_edge: usize) -> Option { - let mut d = decode_raw_preview(bytes, fit_box(max_edge), Some(max_edge))?; + // a plain sRGB camera JPEG straight to 8-bit, as the quick path decodes it (PERF-CULL-3), so + // both paths give the same picture; anything else takes the general decode + let edge = u32::try_from(max_edge).unwrap_or(u32::MAX); + // (found once: the general decode below takes the same stand-in when the fast path declines) + let jpeg = stand_in_image(bytes, Some(max_edge))?; + if lightcraft_raw::embedded_preview_color_space(bytes) != Some(lightcraft_raw::PreviewColorSpace::AdobeRgb) + && matches!(jpeg, std::borrow::Cow::Owned(_)) + && let Ok(Some((image, orientation))) = lightcraft_codecs::decode_jpeg_srgb8_fit(&jpeg, edge, edge) + { + return Some(image.oriented(preview_orientation(bytes, orientation))); + } + let mut d = decode_stand_in(bytes, &jpeg, fit_box(max_edge))?; if d.image.width.max(d.image.height) > max_edge { d.image = fit(&d.image, max_edge, max_edge, Filter::Box); d.alpha = None; diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 6a6b6e6a70..b4ee766048 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -53,7 +53,9 @@ pub(crate) use files::{expand_noting, probe_all, probe_paths, probe_with}; use job::PreparedItem; pub use job::{ImportJob, Prepared, candidate_thumb_key, import, import_with}; pub(crate) use scan::scan_files; -pub use scan::{ScanInput, ScanOutput, ScanProgress, scan, scan_with}; +pub use scan::{ + ScanInput, ScanOutput, ScanProgress, browse_files, browse_order, browse_path, browse_queue, browse_queue_until, browse_spelling, scan, scan_with, +}; #[cfg(test)] use scan::{library_files, library_hashes}; pub use types::{ diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index ae635cb10d..e8ed759dd2 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -528,6 +528,8 @@ impl Session { key, cached: Vec::new(), embedded, + embedded_cache: None, + embedded_on_disk: false, minimum_embedded_edge, small: Some(Box::new(small)), }) diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index 57ee995f26..ad247c22c6 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -1,4 +1,4 @@ -use super::files::{Seen, expand, probe_all, reusable_probes}; +use super::files::{Seen, expand, is_supported, probe_all, reusable_probes}; use super::types::ImportCandidate; use super::{HashMap, Path, PathBuf, PhotoId, ProbeInfo, Session, Source}; @@ -98,6 +98,185 @@ impl ScanInput { pub(crate) fn library(&self) -> std::sync::Arc { std::sync::Arc::clone(&self.library) } + + /// The probes of earlier scans this input took from the session ([`ScanInput::new`]), to hand back with a + /// scan's output that probes nothing itself (browsing), so a later import doesn't read those files again. + pub fn take_probes(&mut self) -> HashMap { + std::mem::take(&mut self.cache) + } +} + +/// What browsing a folder (Local) has to read: the files of `files` the library has no photo at, +/// in the order the view will show them (see [`browse_order`]). Unlike [`scan_with`] nothing is +/// read, so the import that follows adds the photos batch by batch as it reads them, and the first +/// screen of a 3,000-raw wedding shows within a second instead of after every file was read +/// (measured on 2,933 EOS R5 C CR3s: 30.6 s to the first photo before). +pub fn browse_queue(input: &ScanInput, files: Vec, sort: &lightcraft_catalog::Sort) -> Vec { + browse_queue_until(input, files, sort, &std::sync::atomic::AtomicBool::new(false)).unwrap_or_default() +} + +/// [`browse_queue`] that stops reading the files' times or sizes once `cancel` is set (another folder was +/// chosen): `None` then. +pub fn browse_queue_until( + input: &ScanInput, + files: Vec, + sort: &lightcraft_catalog::Sort, + cancel: &std::sync::atomic::AtomicBool, +) -> Option> { + let known = library_files(&input.library, &files); + let mut files: Vec = files.into_iter().filter(|f| !known.contains_key(Path::new(f))).collect(); + browse_order_until(&mut files, sort, cancel).then_some(files) +} + +/// The files browsing `root` (Local) lists: the supported, non-hidden files in it, or below it +/// with `subfolders`, never inside the library's own folder (as [`scan_with`] skips it). +/// +/// A folder that can't be listed whole (gone, no access, a network share dropping out) is an +/// error, not an empty or partial listing: the browse bookkeeping would take the files missing +/// from it for files gone. (With `subfolders` the walk skips the folders below it that it can't +/// read, as the import's scan does.) +pub fn browse_files(input: &ScanInput, root: &str, subfolders: bool) -> std::io::Result> { + // one spelling for the folder, and so for its files: `lib/../outside` lists `outside`'s files as + // the catalog stores them, not as new photos under another name + let root_path = browse_path(Path::new(root))?; + let root = root_path.to_string_lossy().to_string(); + // the library's folder itself, or a folder inside it: nothing to browse + if input.skip.as_deref().is_some_and(|lib| inside(&root_path, lib)) { + return Ok(Vec::new()); + } + if subfolders { + // (the root itself must be there to be walked) + std::fs::read_dir(&root)?; + return Ok(expand(&[root], input.skip.as_deref())); + } + let mut v = Vec::new(); + for entry in std::fs::read_dir(&root)? { + let entry = entry?; + if crate::walk::is_hidden_entry(&entry) { + continue; + } + let f = entry.path(); + if f.is_file() && is_supported(&f) { + v.push(f.to_string_lossy().to_string()); + } + } + v.sort(); + Ok(v) +} + +/// The folder `path` names, as one spelling for the view, its listing and the catalog's records: +/// absolute (`.` is the current folder), with `.` and `..` taken out the way the system reads them. +/// Windows takes `..` out by name; elsewhere `link/..` is the folder above where the link points, +/// so a link before a `..` is resolved first. Everything else keeps its spelling (a mapped drive +/// stays a drive letter, a link not followed by `..` stays the link), as the records were made. +/// +/// It may read the disk (a link on a stalled network mount can block it): call it off the UI thread. +/// [`browse_spelling`] is the UI's spelling meanwhile. +pub fn browse_path(path: &Path) -> std::io::Result { + normalized(path, true) +} + +/// [`browse_path`] without reading the disk: `.` and `..` taken out by name. What the view shows +/// until the worker has resolved the folder; the same folder unless a link comes before a `..` +/// (not on Windows, which takes `..` out by name too). +pub fn browse_spelling(path: &Path) -> std::io::Result { + normalized(path, false) +} + +fn normalized(path: &Path, resolve_links: bool) -> std::io::Result { + use std::path::Component; + // (no disk access: the current folder is the process's) + let path = std::path::absolute(path)?; + let mut out = PathBuf::new(); + for c in path.components() { + match c { + Component::CurDir => {} + Component::ParentDir => { + // a link before `..` is left through where it points; a broken one is an error, not + // its parent folder by name (CodeRabbit on #3577) + #[cfg(not(windows))] + if resolve_links && std::fs::symlink_metadata(&out).is_ok_and(|m| m.file_type().is_symlink()) { + out = std::fs::canonicalize(&out)?; + } + #[cfg(windows)] + let _ = resolve_links; + // (above the root: still the root) + if matches!(out.components().next_back(), Some(Component::Normal(_))) { + out.pop(); + } + } + c => out.push(c.as_os_str()), + } + } + Ok(out) +} + +/// Whether `root` (a [`browse_path`]) is `lib` or a folder inside it: as written, or once both are +/// resolved (a symlink to the library names the same folder), as the recursive walk tells. A root +/// that can't be resolved (gone, or a network share that won't say) is compared as written when it +/// is there; one that isn't there is not inside, and listing it reports why. +fn inside(root: &Path, lib: &Path) -> bool { + let as_written = || root.starts_with(browse_path(lib).unwrap_or_else(|_| lib.to_path_buf())); + match std::fs::canonicalize(root) { + Ok(resolved) => as_written() || std::fs::canonicalize(lib).is_ok_and(|lib| resolved.starts_with(lib)), + Err(_) => root.exists() && as_written(), + } +} + +/// Order `files` the way a view sorted by `sort` will show them, as far as the file system can +/// tell before the files are read: by modification time for the capture date (a camera's file +/// time is its capture time, near enough to fill the first screen first), by name, or by size. +/// New photos share one import time and have no edit time, so the import- and edit-date sorts +/// show them by name. Ties go by name in the view's direction, as the catalog breaks them +/// ([`lightcraft_catalog::Sort::order`]); new photos tie on rating too. Random keeps the given order. Files whose +/// time or size can't be read go last. +pub fn browse_order(files: &mut [String], sort: &lightcraft_catalog::Sort) { + browse_order_until(files, sort, &std::sync::atomic::AtomicBool::new(false)); +} + +/// [`browse_order`] that stops reading the files' times or sizes once `cancel` is set: `false` then, and +/// `files` is left as it was. +fn browse_order_until(files: &mut [String], sort: &lightcraft_catalog::Sort, cancel: &std::sync::atomic::AtomicBool) -> bool { + use lightcraft_catalog::SortKey; + use lightcraft_catalog::query::cmp_name; + use std::cmp::Ordering; + use std::sync::atomic::Ordering::Relaxed; + let asc = sort.ascending; + let name = |f: &str| Path::new(f).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let directed = |o: Ordering| if asc { o } else { o.reverse() }; + // `key` per file (`None`: unreadable, last in either direction), then the name, in the view's direction + let by_key = |files: &mut [String], key: &dyn Fn(&str) -> Option| { + let mut keyed: Vec<(Option, String, String)> = Vec::with_capacity(files.len()); + for f in files.iter() { + if cancel.load(Relaxed) { + return false; + } + keyed.push((key(f), name(f), f.clone())); + } + keyed.sort_by(|a, b| match (a.0, b.0) { + (Some(x), Some(y)) => directed(x.cmp(&y).then_with(|| cmp_name(&a.1, &b.1))), + (Some(_), None) => Ordering::Less, + (None, Some(_)) => Ordering::Greater, + (None, None) => directed(cmp_name(&a.1, &b.1)), + }); + for (slot, (_, _, f)) in files.iter_mut().zip(keyed) { + *slot = f; + } + true + }; + match sort.key { + SortKey::CaptureDate => by_key(files, &|f| { + let t = std::fs::metadata(f).and_then(|m| m.modified()).ok()?; + // (nanoseconds since the epoch fit a u64 until 2554; earlier times count as the epoch) + Some(t.duration_since(std::time::UNIX_EPOCH).map_or(0, |d| u64::try_from(d.as_nanos()).unwrap_or(u64::MAX))) + }), + SortKey::ImportDate | SortKey::EditDate | SortKey::Rating | SortKey::FileName => { + files.sort_by(|a, b| directed(cmp_name(&name(a), &name(b)))); + !cancel.load(Relaxed) + } + SortKey::FileSize => by_key(files, &|f| std::fs::metadata(f).ok().map(|m| m.len())), + SortKey::Random => !cancel.load(Relaxed), + } } /// Find and probe what importing `paths` would add, marking duplicates (by path, or by content diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f71f9becd1..bade3892d3 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -28,6 +28,7 @@ pub mod crs_masks; pub mod demo; pub mod denoise; pub mod devices; +pub mod disk_space; pub mod display; pub mod doc_path; mod errors; @@ -61,6 +62,7 @@ mod model_download; pub mod open_path; pub mod originals; mod pdf; +pub mod prep; pub mod preset_import; pub mod preset_luminar; pub mod presets; @@ -398,10 +400,18 @@ pub struct Session { pub slideshow_export: Option>, /// The last (or running) Build Previews. pub preview_build: Option>, + /// Preparing photos in the background: settings (app-wide and this library's) and the build + /// it runs ([`prep`]). + pub prep: prep::PrepState, + /// The long edge (px) the loupe renders at on this screen, as the frontend last said + /// (0: not known). Standard previews are built at least this big, so the loupe can use them. + pub loupe_edge: usize, /// Develop defaults applied on import (persisted in prefs.json). pub import_defaults: import::ImportDefaults, /// Disk budget of the library's thumbnail cache in MB (0 = default; persisted in prefs.json). pub cache_mb: u32, + /// The once-per-session alert for a drive running low under the preview cache ([`disk_space`]). + pub(crate) disk_alert: disk_space::DiskAlertState, /// Slideshow playback settings (`slideshow.playback`; persisted in prefs.json). pub slideshow: slideshow::PlaybackSettings, /// Slideshow slide layout: Layout, Options and Backdrop (`slideshow.layout`; persisted in @@ -537,9 +547,12 @@ impl Session { folder_changes: None, activity: Default::default(), preview_build: None, + prep: Default::default(), + loupe_edge: 0, slideshow_export: None, import_defaults: import::ImportDefaults::default(), cache_mb: 0, + disk_alert: Default::default(), slideshow: slideshow::PlaybackSettings::default(), slide_layout: slide::SlideSettings::default(), slide_overlays: slide_overlay::OverlaySettings::default(), diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 23e333c4ca..8cd242face 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -258,6 +258,13 @@ impl Library { } } +/// [`PrefsFile`]'s `prep`, read leniently (see there). +fn lenient_prep<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result, D::Error> { + use serde::Deserialize; + let value = serde_json::Value::deserialize(d)?; + Ok(serde_json::from_value(value).ok()) +} + #[derive(Default, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] struct PrefsFile { @@ -295,6 +302,11 @@ struct PrefsFile { import: crate::import::ImportDefaults, /// Thumbnail disk cache budget (MB, 0 = default). cache_mb: u32, + /// This library's own background preparation settings (`None`: the app-wide ones). Read + /// leniently: a value a newer build wrote that this one doesn't know is `None`, and the rest of + /// the file is kept. + #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "lenient_prep")] + prep: Option, /// Folder for smart previews (default: `Smart Previews` in the library). smart_previews_dir: Option, /// Days after which untouched Local records of unbrowsed folders are forgotten (missing = @@ -585,6 +597,7 @@ impl Session { self.recent_keywords = prefs.recent_keywords; self.import_defaults = prefs.import; self.cache_mb = prefs.cache_mb; + self.prep.library = prefs.prep.map(crate::prep::PrepSettings::sanitized); self.slideshow = prefs.slideshow.sanitized(); self.slide_layout = prefs.slide_layout.sanitized(); self.slide_overlays = prefs.slide_overlays.sanitized(); @@ -688,6 +701,9 @@ impl Session { crate::cmd::previews::refresh_stale_smart_previews(self); } self.library_identity = std::sync::Arc::new(()); + // a library open is a new session for the low-disk alert: look at the drive now + self.disk_alert.reset(); + self.check_disk_space(true); Ok(()) } @@ -900,6 +916,7 @@ impl Session { recent_keywords: self.recent_keywords.clone(), import: self.import_defaults.clone(), cache_mb: self.cache_mb, + prep: self.prep.library, smart_previews_dir: self.smart_previews_dir.as_ref().map(|d| d.to_string_lossy().to_string()), forget_local_days: Some(self.forget_local_days), slideshow: self.slideshow.clone(), @@ -927,9 +944,23 @@ impl Session { new } - /// The thumbnail disk cache budget in bytes ([`Session::cache_mb`], else the default). + /// The thumbnail disk cache budget in bytes ([`Session::cache_mb`], else the default, which + /// grows with the library: [`crate::media::default_disk_cache_bytes`]). pub fn cache_bytes(&self) -> u64 { - if self.cache_mb == 0 { crate::media::DISK_CACHE_BYTES } else { u64::from(self.cache_mb) << 20 } + if self.cache_mb == 0 { crate::media::default_disk_cache_bytes(self.catalog.len()) } else { u64::from(self.cache_mb) << 20 } + } + + /// Bring the disk cache's budget up to date with the library (photos were added since it was + /// set): cheap, nothing is read or written. Called before previews are built, so it also + /// looks at the drive's free space when that is due ([`Session::check_disk_space`]). + pub fn fit_disk_cache(&mut self) { + let want = self.cache_bytes(); + if let Some(d) = self.media.rendered.disk() + && d.budget() != want + { + d.set_budget(want); + } + self.check_disk_space(false); } /// Change the thumbnail disk cache budget (MB, 0 = default) in place: the cached thumbnails @@ -991,6 +1022,16 @@ fn unlocked_warning(lock: Option<&LibraryLock>) -> Option { mod resolve_tests { use super::*; + /// A library's background preparation value this build doesn't know reads as none (the + /// app-wide settings apply) and keeps the rest of `prefs.json`. + #[test] + fn an_unknown_background_preparation_value_keeps_the_other_prefs() { + let v = serde_json::json!({"cacheMb": 77, "prep": {"culling": {"scope": "someday"}}}); + let read: PrefsFile = serde_json::from_value(v).unwrap(); + assert!(read.prep.is_none()); + assert_eq!(read.cache_mb, 77); + } + /// `--library /catalog.snap` failed with the OS's "File exists" (creating a folder over /// the file); it opens the library that file belongs to. #[test] diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index a4528795b1..9c6de8dd2c 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -35,14 +35,17 @@ mod settings_hash; mod source; pub use cache::DenoiseIndex; +#[cfg(test)] +pub(crate) use cache::rendered_budget; pub use quick::{QuickJob, QuickSource, content_key, source_info}; -pub use render::{RenderJob, RenderResult, ScreenFrame, develop, develop_reporting, fit_for_display}; +pub use render::{RenderJob, RenderResult, ScreenFrame, develop, develop_reporting, fit_cached, fit_for_display}; #[cfg(test)] use settings_hash::SETTINGS_HASH_ENTRIES; use settings_hash::SettingsHashes; pub use source::{ - DISK_CACHE_BYTES, DecodedSource, DenoiseSpec, FACE_EDGE_STEP, FileLoader, FileProbe, MakeProduct, PairLoader, PreviewLoader, ProbeInfo, - RENDER_CACHE_VERSION, ReducedLoader, SourceLevel, SourceRef, THUMB_SIZES, Twin, face_edge, thumb_bucket, + DISK_CACHE_BYTES, DISK_CACHE_PER_PHOTO, DecodedSource, DenoiseSpec, FACE_EDGE_STEP, FileLoader, FileProbe, MakeProduct, PairLoader, + PreviewLoader, ProbeInfo, RENDER_CACHE_VERSION, ReducedLoader, SourceLevel, SourceRef, THUMB_SIZES, Twin, default_disk_cache_bytes, face_edge, + thumb_bucket, }; pub struct MediaCache { diff --git a/crates/engine/src/media/cache.rs b/crates/engine/src/media/cache.rs index 234efb1485..036b4730a4 100644 --- a/crates/engine/src/media/cache.rs +++ b/crates/engine/src/media/cache.rs @@ -75,9 +75,11 @@ impl Default for MediaCache { } } -/// Memory for rendered previews out of the cache share. -fn rendered_budget(share: usize) -> usize { - RENDERED_MEM_BYTES.min(share / 4) +/// Memory for rendered previews out of the cache share: a quarter of it, so a big budget keeps +/// a whole shoot's previews (a 20 GB budget holds about 230 standard previews, or 1 500 loupe +/// renders at 1 200 px), and at least [`RENDERED_MEM_BYTES`] where the share allows. +pub(crate) fn rendered_budget(share: usize) -> usize { + (share / 4).max(RENDERED_MEM_BYTES.min(share / 2)) } impl MediaCache { diff --git a/crates/engine/src/media/quick.rs b/crates/engine/src/media/quick.rs index 335a118ca6..25c93e9f81 100644 --- a/crates/engine/src/media/quick.rs +++ b/crates/engine/src/media/quick.rs @@ -25,6 +25,15 @@ pub struct QuickJob { pub cached: Vec<(Arc, Hash128)>, /// Embedded preview of an unedited raw: (path, loader, max edge). pub embedded: Option<(String, PreviewLoader, usize)>, + /// Where a decoded [`Self::embedded`] preview is kept in memory, so stepping back to a photo + /// shows its camera JPEG again without reading and decoding it (culling goes back and forth): + /// the cache (memory only, never its disk), the key for this photo and edge, and the cache's + /// generation when the job was made (a Discard Preview Cache since then keeps the picture out). + pub embedded_cache: Option<(Arc, Hash128, u64)>, + /// Whether [`Self::embedded_cache`] keeps the decoded preview on disk too: a grid thumbnail, + /// so a folder seen before fills in from small files at once instead of every raw being read + /// and its camera JPEG decoded again (the loupe's large stand-ins stay in memory). + pub embedded_on_disk: bool, /// Import tiles need this many pixels when a render can provide them. `None` accepts any /// camera JPEG immediately (ordinary transient stand-ins and preview-only imports). /// An undersized JPEG remains the fallback if the render fails or is unavailable. @@ -79,13 +88,30 @@ impl QuickJob { } } let mut embedded_fallback = None; - if let Some((path, loader, edge)) = &self.embedded - && let Some(image) = loader(path, *edge) - { - if self.minimum_embedded_edge.is_none_or(|minimum| image.width.max(image.height) >= minimum) { - return done(rendered(image), Some(QuickSource::Embedded)); + if let Some((path, loader, edge)) = &self.embedded { + let kept = + self.embedded_cache.as_ref().and_then(|(cache, k, _)| if self.embedded_on_disk { cache.get(*k) } else { cache.get_memory(*k) }); + let image = match kept { + Some(img) => Some(Arc::unwrap_or_clone(img)), + None => { + let image = loader(path, *edge); + // written for the generation the job was made in: a cache cleared meanwhile stays clear + if let (Some(image), Some((cache, k, generation))) = (&image, &self.embedded_cache) { + if self.embedded_on_disk { + cache.put_deferred_at(*generation, *k, Arc::new(image.clone())); + } else { + cache.put_memory_at(*generation, *k, Arc::new(image.clone())); + } + } + image + } + }; + if let Some(image) = image { + if self.minimum_embedded_edge.is_none_or(|minimum| image.width.max(image.height) >= minimum) { + return done(rendered(image), Some(QuickSource::Embedded)); + } + embedded_fallback = Some(image); } - embedded_fallback = Some(image); } if let Some(job) = self.small { let r = job.run(); @@ -100,6 +126,11 @@ impl QuickJob { } } +/// The thumbnail cache's key for the camera JPEG standing for the thumbnail of cache key `k`. +pub(super) fn embedded_thumb_key(k: Hash128) -> Hash128 { + Hasher128::new().str("embedded-thumb").u64((k.0 >> 64) as u64).u64(k.0 as u64).finish() +} + /// What identifies a photo's pixels for caching: its content hash, else its source. /// Which decode of a photo a loaded source is: its file's content and, when it has one, its database lens profile /// ([`lens_key`]; the decode fits the starting colour through it). A job's source is kept only when this still diff --git a/crates/engine/src/media/render.rs b/crates/engine/src/media/render.rs index 56dc3b7cb9..bd8ee5292f 100644 --- a/crates/engine/src/media/render.rs +++ b/crates/engine/src/media/render.rs @@ -1,5 +1,5 @@ use super::quick::QuickSource; -use super::source::{DecodedSource, SourceLevel, SourceRef}; +use super::source::{DecodedSource, SourceLevel, SourceRef, VIEW_REUSE_SLACK}; use super::{ Arc, DevelopSettings, Hash128, Histogram, PhotoId, PreviewCache, Quality, RenderRequest, Rendered, Rgb32f, Rgba8, Source, SourceInfo, StageCache, }; @@ -241,8 +241,58 @@ impl RenderJob { r } + /// The view render kept for this job's photo and settings ([`Self::view_cache`]), fitted to the + /// size asked for, when it is at least that big, or unchanged when it covers the job's display + /// fit (else `None`: render). Only for what the cached + /// view is: a full-quality, 8-bit, whole-frame SDR render (the cache holds sRGB; a display + /// profile is applied to it like to any cached picture, [`crate::display::present`]). + pub fn cached_view(&self) -> Option { + let (cache, key) = self.view_cache.as_ref()?; + if self.request.quality != Quality::Full + || self.request.depth != lightcraft_pipeline::OutputDepth::U8 + || self.request.window.is_some() + || self.settings.hdr.enabled + || self.slide.is_some() + { + return None; + } + let img = cache.get_at(self.cache_generation, *key)?; + fit_cached(&img, self.request.max_w, self.request.max_h).or_else(|| { + // the loupe at rest asks for at least the preview level and shows the render shrunk to + // the drawn size (the display fit): a cached view that covers the drawn size is enough + let (fw, fh) = self.display_fit?; + let (w, h) = (img.width, img.height); + let s = (fw as f64 / w.max(1) as f64).min(fh as f64 / h.max(1) as f64); + (w > 0 && h > 0 && fw > 0 && fh > 0 && s <= 1.0 + VIEW_REUSE_SLACK).then(|| Arc::unwrap_or_clone(img)) + }) + } + /// The photo's render (without slide composition). fn run_photo(self) -> RenderResult { + // the loupe: a cached view render of these settings at least this big is the render (built + // previews and the photos prepared ahead are used, not rendered again; PERF-PREVIEW-REUSE) + if let Some(mut image) = self.cached_view() { + // as for a render: the histogram of the full picture, then the display fit + let histogram = Histogram::of_srgb8(&image); + if let Some((fw, fh)) = self.display_fit + && (image.width > fw.max(1) || image.height > fh.max(1)) + { + image = fit_for_display(&image, fw, fh); + } + 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, histogram, deep: None }), + gpu_fallback: None, + loaded: None, + quick: Some(QuickSource::Cached), + display: None, + frame: None, + }; + } if let Some((cache, key)) = &self.cache && let Some(img) = cache.get_at(self.cache_generation, *key) { @@ -395,6 +445,61 @@ impl RenderJob { } } +/// `img` fitted into `max_w × max_h` (its aspect kept), when it is big enough to need no +/// enlarging (within [`VIEW_REUSE_SLACK`]): as it is, or shrunk by averaging. +pub fn fit_cached(img: &Rgba8, max_w: usize, max_h: usize) -> Option { + let (w, h) = (img.width, img.height); + if w == 0 || h == 0 || max_w == 0 || max_h == 0 { + return None; + } + let s = (max_w as f64 / w as f64).min(max_h as f64 / h as f64); + if !s.is_finite() || s > 1.0 + VIEW_REUSE_SLACK { + return None; + } + let (nw, nh) = (((w as f64 * s).round() as usize).clamp(1, w), ((h as f64 * s).round() as usize).clamp(1, h)); + if nw == w && nh == h { + return Some(img.clone()); + } + Some(shrink_rgba(img, nw, nh)) +} + +/// `img` shrunk to `nw × nh` (no larger than it), each pixel the average of the ones it covers. +fn shrink_rgba(img: &Rgba8, nw: usize, nh: usize) -> Rgba8 { + let (w, h) = (img.width, img.height); + let (nw, nh) = (nw.clamp(1, w.max(1)), nh.clamp(1, h.max(1))); + // the source columns / rows each output column / row covers: [start, end) + let spans = |n: usize, of: usize| -> Vec<(usize, usize)> { + (0..n) + .map(|i| { + let a = i.saturating_mul(of) / n; + let b = (i.saturating_add(1).saturating_mul(of) / n).max(a.saturating_add(1)).min(of); + (a, b) + }) + .collect() + }; + let (xs, ys) = (spans(nw, w), spans(nh, h)); + let mut data = Vec::with_capacity(nw.saturating_mul(nh)); + let mut row = vec![[0u32; 4]; nw]; + for &(y0, y1) in &ys { + row.iter_mut().for_each(|r| *r = [0; 4]); + for y in y0..y1 { + let Some(line) = img.data.get(y * w..(y + 1) * w) else { continue }; + for (acc, &(x0, x1)) in row.iter_mut().zip(&xs) { + for px in line.get(x0..x1).unwrap_or(&[]) { + for (a, v) in acc.iter_mut().zip(px) { + *a += u32::from(*v); + } + } + } + } + for (acc, &(x0, x1)) in row.iter().zip(&xs) { + let n = (x1.saturating_sub(x0).saturating_mul(y1.saturating_sub(y0))).max(1) as u32; + data.push(acc.map(|a| ((a + n / 2) / n).min(255) as u8)); + } + } + Rgba8 { width: nw, height: nh, data } +} + /// Render `src`: on the GPU when `gpu` is set and a GPU is available (`lightcraft_gpu`), else on /// the CPU, reusing `stages` either way. Both produce the same image within 1–3 LSB (see /// `docs/gpu-pipeline.md`); `LIGHTCRAFT_GPU=0` or [`lightcraft_gpu::set_enabled`] forces the CPU. diff --git a/crates/engine/src/media/session.rs b/crates/engine/src/media/session.rs index ac1b8145a9..ed472972bd 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -1,4 +1,4 @@ -use super::quick::{QuickJob, content_key, source_info}; +use super::quick::{QuickJob, content_key, embedded_thumb_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}; @@ -264,12 +264,19 @@ impl crate::Session { Some(crate::face_tiles::PreviewCut { path, loader, want, min, rect, aspect, edge }) } - /// Size-independent cache key of a photo's view render (loupe) for its current settings, its lens profile - /// 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 { + /// Size-independent cache key of a photo's view render (loupe) for its current settings. The + /// denoised picture, camera profile and lens profile in use are part of it (as of the render's own + /// key, [`Self::variant_key`]): a view rendered before the photo's AI Denoise result was there is + /// not shown as the denoised one. + pub(crate) fn view_key(&self, p: &Photo, apply_crop: bool) -> Hash128 { + let salt = self.media.denoise_salt(p.id, &p.develop); + let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id); 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); with_process(&mut k, &p.develop).u64(crate::camera_profiles::cache_key()); + if salt != 0 { + k.u64(salt); + } if profile_salt != 0 { k.str("dcp").u64(profile_salt); } @@ -285,8 +292,7 @@ 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)?; - 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))); + job.view_cache = Some((self.media.rendered.clone(), self.view_key(p, apply_crop))); Some(job) } @@ -396,11 +402,49 @@ impl crate::Session { 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 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 cached = vec![(self.media.rendered.clone(), self.view_key(&p, apply_crop))]; + // (the photo too: a virtual copy shares the file and, unedited, the settings) + let h = + Hasher128::new().str(&content_key(&p)).str("quick").u64(p.develop.hash64()).u64(apply_crop as u64).u64(id.0).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)) }) + let embedded_cache = embedded.as_ref().map(|(_, _, edge)| { + let cache = self.media.rendered.clone(); + let generation = cache.generation(); + (cache, Hasher128::new().str(&content_key(&p)).str("embedded").u64(*edge as u64).finish(), generation) + }); + Some(QuickJob { + request_id: 0, + photo: id, + key, + cached, + embedded, + embedded_cache, + embedded_on_disk: false, + minimum_embedded_edge: None, + small: apply_crop.then(|| Box::new(small)), + }) + } + + /// The camera's embedded JPEG of an unedited raw at up to `max_edge` pixels (its full size for + /// a camera that stores one), for the loupe zoomed to 100 % while LightCraft renders the window + /// on screen: a focus check needs the pixels at once, and a 45 MP render of the window takes + /// seconds. Not kept in any cache (a full-size picture is 180 MB). `None` for other photos. + pub fn embedded_full_job(&mut self, id: PhotoId, max_edge: usize) -> Option { + let p = self.catalog.photo(id)?.clone(); + let (path, l) = self.embedded_of(&p)?; + let key = Hasher128::new().str(&content_key(&p)).str("embedded-full").u64(id.0).u64(max_edge as u64).finish().0 as u64; + Some(QuickJob { + request_id: 0, + photo: id, + key, + cached: Vec::new(), + embedded: Some((path, l, max_edge.max(1))), + embedded_cache: None, + embedded_on_disk: false, + minimum_embedded_edge: None, + small: None, + }) } /// A first grid thumbnail for an unedited raw: the cached render for `job` (the real @@ -419,6 +463,10 @@ impl crate::Session { key: job.key, cached: job.cache.clone().into_iter().collect(), embedded: Some((path, l, edge)), + // the camera JPEG is this thumbnail (an unedited raw): kept with the rendered ones, under + // a key of its own, so the folder's next visit reads it from the thumbnail cache + embedded_cache: job.cache.as_ref().map(|(c, k)| (c.clone(), embedded_thumb_key(*k), c.generation())), + embedded_on_disk: true, minimum_embedded_edge: None, small: Some(Box::new(job.clone())), }) diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index f13349f18c..faec08ca98 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -24,10 +24,23 @@ pub fn thumb_bucket(long_edge: usize) -> usize { /// Memory budgets. pub(super) const THUMB_SOURCE_BYTES: usize = 384 << 20; +/// The least memory kept for rendered previews (when the budget allows it). pub(super) const RENDERED_MEM_BYTES: usize = 128 << 20; -/// Disk budget for the thumbnail cache. +/// The smallest disk budget for the thumbnail and preview cache. pub const DISK_CACHE_BYTES: u64 = 2 << 30; +/// What one photo's previews take on disk, about: its standard preview (a 2048 px JPEG, ~1 MB) +/// and its grid thumbnails. The default disk budget grows by this per photo of the library, so +/// built previews of a whole wedding are not pruned while they are being made (PERF-PREVIEW-REUSE). +pub const DISK_CACHE_PER_PHOTO: u64 = 3 << 19; +/// The default disk budget for a library of `photos`: [`DISK_CACHE_BYTES`], or room for every +/// photo's previews ([`DISK_CACHE_PER_PHOTO`]) when that is more. +pub fn default_disk_cache_bytes(photos: usize) -> u64 { + DISK_CACHE_BYTES.max((photos as u64).saturating_mul(DISK_CACHE_PER_PHOTO)) +} +/// A cached view render this much smaller than asked for still serves the loupe (rounding: a +/// fit of the same frame into a box one pixel different). +pub(super) const VIEW_REUSE_SLACK: f64 = 0.01; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] diff --git a/crates/engine/src/media/thumbnail_hash_tests.rs b/crates/engine/src/media/thumbnail_hash_tests.rs index 85089d231d..6f9fcab339 100644 --- a/crates/engine/src/media/thumbnail_hash_tests.rs +++ b/crates/engine/src/media/thumbnail_hash_tests.rs @@ -6,6 +6,60 @@ fn session() -> crate::Session { s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); s } +/// PERF-CULL: an unedited raw's camera JPEG is read once for the loupe and kept in memory for a +/// step back; the full-size one (zoomed in) is made at the size asked for and kept nowhere; an +/// edited raw or another file has none. +#[test] +fn camera_previews_are_kept_for_a_revisit_and_full_size_ones_are_not() { + let reads = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let mut s = crate::Session::new(); + let r = reads.clone(); + s.media.preview_loader = Some(Arc::new(move |_: &str, edge: usize| { + r.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Some(Rgba8 { width: edge.min(64), height: 2, data: vec![[9, 8, 7, 255]; edge.min(64) * 2] }) + })); + let mut raw = Photo::new(PhotoId(1), Source::File { path: "a.cr3".into() }, "a.cr3", "CR3", 6000, 4000, "2026-01-01"); + raw.kind = MediaKind::Raw; + raw.develop = Arc::new(raw.camera_defaults()); + s.catalog.apply(Op::AddPhoto { photo: Box::new(raw) }).unwrap(); + let jpeg = Photo::new(PhotoId(2), Source::File { path: "b.jpg".into() }, "b.jpg", "JPEG", 600, 400, "2026-01-01"); + s.catalog.apply(Op::AddPhoto { photo: Box::new(jpeg) }).unwrap(); + for _ in 0..3 { + let q = s.quick_view_job(PhotoId(1), 48, true).unwrap(); + let r = q.run(); + assert_eq!(r.quick, Some(QuickSource::Embedded)); + } + assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 1, "read once, then from memory"); + let full = s.embedded_full_job(PhotoId(1), 8192).unwrap(); + assert!(full.embedded_cache.is_none() && full.cached.is_empty() && full.small.is_none()); + assert_eq!(full.embedded.as_ref().map(|e| e.2), Some(8192)); + assert_ne!(full.key, s.quick_view_job(PhotoId(1), 48, true).unwrap().key); + assert_eq!(full.run().quick, Some(QuickSource::Embedded)); + assert!(s.embedded_full_job(PhotoId(2), 8192).is_none(), "not a raw"); + let mut edited = (*s.catalog.photo(PhotoId(1)).unwrap().develop).clone(); + edited.light.exposure = 1.0; + s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(edited), label: "edit".into(), edited: None }).unwrap(); + assert!(s.embedded_full_job(PhotoId(1), 8192).is_none(), "an edit is shown rendered"); +} + +/// A virtual copy shares its master's file and, unedited, its settings; its loupe stand-ins +/// are its own all the same (CodeRabbit on #3080). +#[test] +fn a_virtual_copy_has_its_own_stand_in_keys() { + let mut s = crate::Session::new(); + s.media.preview_loader = Some(Arc::new(|_: &str, _: usize| None::)); + for id in [1, 2] { + let mut raw = Photo::new(PhotoId(id), Source::File { path: "a.cr3".into() }, "a.cr3", "CR3", 6000, 4000, "2026-01-01"); + raw.kind = MediaKind::Raw; + raw.develop = Arc::new(raw.camera_defaults()); + s.catalog.apply(Op::AddPhoto { photo: Box::new(raw) }).unwrap(); + } + let quick = |s: &mut crate::Session, id: u64| s.quick_view_job(PhotoId(id), 48, true).unwrap().key; + assert_ne!(quick(&mut s, 1), quick(&mut s, 2)); + let full = |s: &mut crate::Session, id: u64| s.embedded_full_job(PhotoId(id), 8192).unwrap().key; + assert_ne!(full(&mut s, 1), full(&mut s, 2)); +} + /// 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 @@ -37,7 +91,7 @@ fn persistent_keys_name_the_process_the_settings_render_with() { 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), + (s.view_key(&p, true), Some("view"), 1), (crate::Session::variant_key(&p, &newer, 256, 0), Some("variant"), 256), ]; for (key, kind, size) in keys { @@ -69,7 +123,7 @@ fn v1_and_v2_photos_keep_the_render_cache_keys_they_had() { }; 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), + s.view_key(&p, true) == before_v3(Some("view"), 1), crate::Session::variant_key(&p, &settings, 256, 0) == before_v3(Some("variant"), 256), ]; let old = process <= Process::V2; @@ -217,6 +271,8 @@ fn a_render_that_panics_fails_instead_of_never_answering() { key: 9, cached: Vec::new(), embedded: Some(("x.arw".into(), Arc::new(|_: &str, _: usize| -> Option { panic!("preview reader bug") }), 256)), + embedded_cache: None, + embedded_on_disk: false, minimum_embedded_edge: None, small: None, }; @@ -224,3 +280,44 @@ fn a_render_that_panics_fails_instead_of_never_answering() { assert_eq!((r.request_id, r.key), (7, 9)); assert_eq!(r.rendered.err().as_deref(), Some("the render failed unexpectedly: preview reader bug")); } + +/// CodeRabbit on #3544: a stand-in job decoding a camera JPEG when Discard Preview Cache clears the +/// cache doesn't put the picture back: it writes for the generation it was made in (memory and +/// disk alike), as render jobs do. +#[test] +fn a_camera_jpeg_decoded_across_a_cache_clear_is_not_kept() { + for on_disk in [false, true] { + let cache = Arc::new(PreviewCache::memory(64 << 20)); + let made_in = cache.generation(); + let key = Hash128(5); + let quick = QuickJob { + request_id: 1, + photo: PhotoId(1), + key: 2, + cached: Vec::new(), + embedded: Some(("x.arw".into(), Arc::new(|_: &str, _: usize| Some(Rgba8::new(16, 16))), 256)), + embedded_cache: Some((cache.clone(), key, made_in)), + embedded_on_disk: on_disk, + minimum_embedded_edge: None, + small: None, + }; + // the user discards the cache while the job is on its way + cache.clear(); + assert!(quick.run().rendered.is_ok(), "the stand-in is still shown"); + assert!(cache.get_memory(key).is_none(), "on disk {on_disk}: nothing kept in the cleared cache"); + // a job made after the clear keeps it as before + let quick = QuickJob { + request_id: 1, + photo: PhotoId(1), + key: 2, + cached: Vec::new(), + embedded: Some(("x.arw".into(), Arc::new(|_: &str, _: usize| Some(Rgba8::new(16, 16))), 256)), + embedded_cache: Some((cache.clone(), key, cache.generation())), + embedded_on_disk: on_disk, + minimum_embedded_edge: None, + small: None, + }; + assert!(quick.run().rendered.is_ok()); + assert!(cache.get_memory(key).is_some(), "on disk {on_disk}: kept when made after the clear"); + } +} diff --git a/crates/engine/src/prep.rs b/crates/engine/src/prep.rs new file mode 100644 index 0000000000..bb53d24418 --- /dev/null +++ b/crates/engine/src/prep.rs @@ -0,0 +1,532 @@ +//! Preparing photos in the background (PERF-PREVIEW-PREP, notes 47 and 48): while the user culls, +//! the photos ahead are made ready before they are reached, and with the machine otherwise idle +//! the previews of every photo in view are built, so stepping never waits for a render. +//! +//! What is prepared is set per mode, because each mode needs something else: +//! - **Culling** (a folder browsed before import, the Import tab): previews of every photo in the +//! folder, the next photos' loupe renders and their eye focus strips. +//! - **Library**: the same for the photos in the library's view. +//! - **Develop** (editing): the next photos decoded and kept ready to edit. +//! +//! Each mode has its own switch for the whole-view build, how many photos ahead to prepare (0 = +//! none) and which photos ([`Scope`]). The settings are app-wide (the desktop app keeps them in `ui.json`) +//! and a library can keep its own (its `prefs.json`): a timelapse library prepares nothing while a +//! wedding library prepares everything. +//! +//! The whole-view build is the preview build ([`crate::cmd::previews`]) in its background form: two +//! lanes, waiting whenever the photo on screen is being made ([`foreground`]), nearest photos to the +//! user first and re-aimed as they move ([`crate::cmd::previews::PreviewBuild::focus_on`]), photos +//! with previews skipped, one row in the activity stack that can be cancelled. It starts once the +//! user is culling (a few photos stepped through in the loupe), never just because a library was +//! opened (note 36: opening an old library to look at two photos must not start rebuilding). + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use lightcraft_catalog::PhotoId; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::Session; +use crate::cmd::previews::PreviewBuild; + +/// Which photos a mode prepares. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Scope { + /// Every photo in view (the folder, the collection, the filter). + #[default] + All, + /// Only picks, and photos with stars or a colour label. + Marked, + /// Only the photo on screen: nothing ahead, nothing in the background. + OnScreen, +} + +impl Scope { + pub fn parse(s: &str) -> Option { + match s { + "all" => Some(Scope::All), + "marked" => Some(Scope::Marked), + "onScreen" => Some(Scope::OnScreen), + _ => None, + } + } +} + +/// The most photos prepared ahead of the one on screen. +pub const MAX_AHEAD: u8 = 20; + +/// What one mode prepares. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct ModePrep { + /// Build the previews of every photo in scope in the background. + pub previews: bool, + /// Photos ahead (in the direction of travel) whose loupe render is made before they are reached (0 = none). + pub ahead: u8, + /// Photos ahead whose eye focus strip is worked out before they are reached (0 = only the one on + /// screen), for a frontend that shows one (the desktop app doesn't yet). + pub eye_ahead: u8, + pub scope: Scope, +} + +impl Default for ModePrep { + fn default() -> Self { + ModePrep { previews: true, ahead: 5, eye_ahead: 8, scope: Scope::All } + } +} + +/// Editing: what is kept ready for the next photos. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct DevelopPrep { + /// Photos ahead decoded and kept ready to edit (0 = none). + pub ahead: u8, + pub scope: Scope, +} + +impl Default for DevelopPrep { + fn default() -> Self { + DevelopPrep { ahead: 2, scope: Scope::All } + } +} + +/// The background preparation settings. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct PrepSettings { + pub culling: ModePrep, + pub library: ModePrep, + pub develop: DevelopPrep, +} + +impl PrepSettings { + /// Values from files or agents kept in range. + pub fn sanitized(mut self) -> Self { + for m in [&mut self.culling, &mut self.library] { + m.ahead = m.ahead.min(MAX_AHEAD); + m.eye_ahead = m.eye_ahead.min(MAX_AHEAD); + } + self.develop.ahead = self.develop.ahead.min(MAX_AHEAD); + self + } + + /// The settings of a browsing mode ([`Mode::Culling`] or [`Mode::Library`]; Develop prepares + /// views the way the Library does). + pub fn mode(&self, mode: Mode) -> ModePrep { + match mode { + Mode::Culling => self.culling, + Mode::Library | Mode::Develop => self.library, + } + } + + /// Photos ahead to render for the loupe in `mode` (0 when its scope is the photo on screen). + pub fn ahead(&self, mode: Mode) -> usize { + match mode { + Mode::Develop if self.develop.scope == Scope::OnScreen => 0, + Mode::Develop => usize::from(self.develop.ahead), + m => { + let p = self.mode(m); + if p.scope == Scope::OnScreen { 0 } else { usize::from(p.ahead) } + } + } + } + + /// Photos ahead whose eye focus strip is worked out in `mode`. + pub fn eye_ahead(&self, mode: Mode) -> usize { + let p = self.mode(mode); + if p.scope == Scope::OnScreen { 0 } else { usize::from(p.eye_ahead) } + } + + /// The scope that applies in `mode`. + pub fn scope(&self, mode: Mode) -> Scope { + match mode { + Mode::Develop => self.develop.scope, + m => self.mode(m).scope, + } + } + + /// Apply the fields of `patch` (a partial object, as `prefs.setBackgroundPrep` takes it). + pub fn patched(&self, patch: &Value) -> Result { + let mut v = serde_json::to_value(self).map_err(|e| e.to_string())?; + merge(&mut v, patch, 0); + let p: PrepSettings = serde_json::from_value(v).map_err(|e| format!("background preparation settings: {e}"))?; + Ok(p.sanitized()) + } +} + +/// `patch` merged into `into`, objects field by field (two levels deep: mode → field). +fn merge(into: &mut Value, patch: &Value, depth: usize) { + match (into, patch) { + (Value::Object(a), Value::Object(b)) if depth < 3 => { + for (k, v) in b { + match a.get_mut(k) { + Some(old) => merge(old, v, depth + 1), + None => { + a.insert(k.clone(), v.clone()); + } + } + } + } + (a, b) => *a = b.clone(), + } +} + +/// What the user is doing, as far as preparation goes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Mode { + Culling, + Library, + Develop, +} + +impl Mode { + pub fn parse(s: &str) -> Option { + match s { + "culling" => Some(Mode::Culling), + "library" => Some(Mode::Library), + "develop" => Some(Mode::Develop), + _ => None, + } + } + + /// The mode of what `s` shows when the frontend doesn't say: a folder browsed before import is + /// culling, anything else the library. + pub fn of(s: &Session) -> Mode { + if s.source == crate::LibrarySource::Folder { Mode::Culling } else { Mode::Library } + } +} + +/// Photos the user steps through in the loupe before the whole view is prepared: a library opened +/// to look at one photo starts nothing. +pub const STEPS_BEFORE_BUILD: usize = 3; +/// How long a view whose build couldn't start waits before trying again. +pub const RETRY_AFTER: std::time::Duration = std::time::Duration::from_secs(30); + +/// The background preparation's state in a session. +#[derive(Default)] +pub struct PrepState { + /// App-wide settings. + pub app: PrepSettings, + /// This library's own (`None`: it uses the app-wide ones). + pub library: Option, + /// The background build this preparation started. + build: Option>, + /// The view (its signature) whose build was started, or that the user stopped. + started_for: Option, + declined_for: Option, + /// A build that couldn't start: the view (its signature), and when it may try again (not on + /// every tick while the cause lasts; CodeRabbit on #3080). + pub retry_at: Option<(u64, web_time::Instant)>, + /// Tests: the next starts to fail, as a build thread that can't be spawned does. + #[cfg(test)] + pub(crate) fail_starts: usize, + /// The view the steps were counted in, the photo last seen, and the steps. + steps_in: Option, + last_at: Option, + steps: usize, +} + +impl std::fmt::Debug for PrepState { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PrepState").field("app", &self.app).field("library", &self.library).field("steps", &self.steps).finish() + } +} + +impl PrepState { + /// The settings in use. + pub fn settings(&self) -> PrepSettings { + self.library.unwrap_or(self.app) + } +} + +/// Until when (ms on [`clock_ms`]) the photo on screen is being made: background work waits. +static FOREGROUND_UNTIL: AtomicU64 = AtomicU64::new(0); + +/// How long a foreground signal holds background work back (ms): a little more than a frame +/// apart, so a frontend saying it every frame holds it back the whole time. +const FOREGROUND_HOLD_MS: u64 = 250; + +fn clock_ms() -> u64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + u64::try_from(START.get_or_init(web_time::Instant::now).elapsed().as_millis()).unwrap_or(u64::MAX) +} + +/// The frontend says the photo on screen is being made (a render it waits for is on its way): +/// background preparation waits until it has been quiet for a moment. +pub fn foreground() { + FOREGROUND_UNTIL.store(clock_ms().saturating_add(FOREGROUND_HOLD_MS), Ordering::Relaxed); +} + +/// Whether the photo on screen is being made now. +pub fn foreground_busy() -> bool { + #[cfg(test)] + if TEST_HOLD.load(Ordering::Relaxed) > 0 { + return true; + } + clock_ms() < FOREGROUND_UNTIL.load(Ordering::Relaxed) +} + +/// Tests: hold every background build at its foreground wait until released (a synchronization +/// point that doesn't depend on the hold's 250 ms). A count, not a switch: tests running side by +/// side each hold until their own release, and one test's release doesn't free another's build. +#[cfg(test)] +static TEST_HOLD: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Holds background builds while it lives (also when the test fails), whatever other holds do. +#[cfg(test)] +pub(crate) struct TestHold; + +#[cfg(test)] +impl TestHold { + pub(crate) fn new() -> Self { + TEST_HOLD.fetch_add(1, Ordering::Relaxed); + TestHold + } +} + +#[cfg(test)] +impl Drop for TestHold { + fn drop(&mut self) { + // (one release per hold made: never below 0) + TEST_HOLD.fetch_sub(1, Ordering::Relaxed); + } +} + +/// Wait while the photo on screen is being made. `true`: `cancel` was set meanwhile. +pub fn wait_for_foreground(cancel: &AtomicBool) -> bool { + #[cfg(not(target_arch = "wasm32"))] + while foreground_busy() { + if cancel.load(Ordering::Relaxed) { + return true; + } + std::thread::sleep(std::time::Duration::from_millis(30)); + } + cancel.load(Ordering::Relaxed) +} + +/// Photos the background build renders side by side: each render spreads over the cores already, +/// so two keep the machine busy while leaving room for the photo on screen. +pub fn background_lanes() -> usize { + let cores = std::thread::available_parallelism().map_or(2, |n| n.get()); + if cores >= 8 { 2 } else { 1 } +} + +/// A cheap identity of the photos a build prepares: a build is started once per view. `scope` +/// [`Scope::Marked`]: which of them are marked counts too (marking a photo changes the set). +fn signature(ids: &[PhotoId], s: &Session, scope: Scope) -> u64 { + let mut h = lightcraft_preview::Hasher128::new(); + h.u64(ids.len() as u64).u64(s.catalog.len() as u64); + // every id: a sort that moves photos in the middle is another view + for id in ids { + h.u64(id.0); + if scope == Scope::Marked { + h.u64(u64::from(marked(s, *id))); + } + } + h.finish().0 as u64 +} + +/// Whether `id` is a pick, or has stars or a colour label (the [`Scope::Marked`] photos). +pub fn marked(s: &Session, id: PhotoId) -> bool { + s.catalog.photo(id).is_some_and(|p| p.flag == lightcraft_catalog::Flag::Pick || p.rating > 0 || p.label.is_some()) +} + +impl Session { + /// How long until a view whose build couldn't start tries again ([`RETRY_AFTER`]), while one + /// waits: the app asks for a frame then, so the retry doesn't wait for the next input + /// (CodeRabbit on #3077/#3080). `None` once the time has come. + pub fn prep_retry_in(&self) -> Option { + // (a deadline that has passed asks for nothing: the pass at it tried again, or the view + // can't be tried now and a frame at once on every pass would keep an idle window drawing: + // CodeRabbit on #3077 / #3080) + let wait = self.prep.retry_at.map(|(_, at)| at.saturating_duration_since(web_time::Instant::now()))?; + (!wait.is_zero()).then_some(wait) + } + + /// The background preparation settings in use (this library's own, else the app-wide ones). + pub fn prep_settings(&self) -> PrepSettings { + self.prep.settings() + } + + /// Advance the background preparation (cheap; call every frame). `mode`: what the user is doing; + /// `at`: the photo in the loupe (`None` in the grid), `backward`: stepping back. + pub fn prep_tick(&mut self, mode: Mode, at: Option, backward: bool) { + let settings = self.prep.settings(); + let want = settings.mode(mode); + // the whole view's build follows its own row (Culling, or Library also while editing): its + // switch and its "which photos"; the Editing row's scope is for the photos kept ready ahead + let wanted = want.previews && want.scope != Scope::OnScreen; + // the running build: re-aimed at the user, stopped when switched off + if let Some(b) = self.prep.build.clone() { + if b.running() { + if !wanted { + b.cancel.store(true, Ordering::Relaxed); + } else if self.prep.started_for.is_some_and(|sig| sig != signature(&self.visible_cloned(), self, want.scope)) { + // another view (a folder, a filter, another library): this build's photos are + // not the ones shown; stopped, and the view now shown is prepared in its place + // (not counted as stopped by the user) + b.cancel.store(true, Ordering::Relaxed); + self.prep.started_for = None; + } else if let Some(id) = at { + b.focus_on(id, backward); + } + return; + } + self.prep.build = None; + let mine = self.preview_build.as_ref().is_some_and(|p| Arc::ptr_eq(p, &b)); + if b.cancel.load(Ordering::Relaxed) { + if mine && wanted { + // stopped from its row: not again for this view + self.prep.declined_for = self.prep.started_for; + } else { + // replaced by a build that was asked for, or switched off: may start again later + self.prep.started_for = None; + } + } + } + if !wanted { + return; + } + let Some(at) = at else { return }; + let ids = self.visible_cloned(); + let sig = signature(&ids, self, want.scope); + if self.prep.steps_in != Some(sig) { + self.prep.steps_in = Some(sig); + self.prep.steps = 0; + self.prep.last_at = None; + } + if self.prep.last_at != Some(at) { + self.prep.last_at = Some(at); + self.prep.steps = self.prep.steps.saturating_add(1); + } + let busy = self.preview_build.as_ref().is_some_and(|b| b.running()); + if busy + || self.prep.steps < STEPS_BEFORE_BUILD + || self.prep.started_for == Some(sig) + || self.prep.declined_for == Some(sig) + || self.prep.retry_at.is_some_and(|(view, at)| view == sig && web_time::Instant::now() < at) + || self.library.as_ref().is_none_or(|l| !l.on_disk) + { + return; + } + let ids: Vec = match want.scope { + Scope::Marked => ids.into_iter().filter(|id| marked(self, *id)).map(|id| id.0).collect(), + _ => ids.into_iter().map(|id| id.0).collect(), + }; + self.prep.started_for = Some(sig); + if ids.is_empty() { + return; + } + let p = json!({"ids": ids, "background": true, "from": at.0, "backward": backward}); + // (tests: a start made to fail, as a build thread that can't be spawned fails) + #[cfg(test)] + let fail = self.prep.fail_starts.checked_sub(1).map(|left| self.prep.fail_starts = left).is_some(); + #[cfg(not(test))] + let fail = false; + let started = if fail { + Err(crate::EngineError::Disabled("library.buildPreviews".into(), "test: the build couldn't start".into())) + } else { + self.execute("library.buildPreviews", &p) + }; + match started { + Ok(_) => { + self.prep.build = self.preview_build.clone(); + self.prep.retry_at = None; + } + Err(e) => { + // not started: this view tries again after a while (not on every tick) + self.prep.started_for = None; + self.prep.retry_at = web_time::Instant::now().checked_add(RETRY_AFTER).map(|at| (sig, at)); + log::info!("background preparation: {e}"); + } + } + } + + /// Change the background preparation settings: the app-wide ones, or (`library`) this library's + /// own. Saved at once. + pub fn set_prep_settings(&mut self, settings: PrepSettings, library: bool) -> crate::Result<()> { + let settings = settings.sanitized(); + if library { + let previous = self.prep.library; + self.prep.library = Some(settings); + self.save_library_prep(previous) + } else { + let previous = self.prep.app; + self.prep.app = settings; + let saved = self.save_prefs(); + if saved.is_err() { + self.prep.app = previous; + } + saved + } + } + + /// Back to the app-wide settings for this library. + pub fn clear_library_prep(&mut self) -> crate::Result<()> { + let previous = self.prep.library; + self.prep.library = None; + self.save_library_prep(previous) + } + + /// Save this library's preparation settings; when that fails, `previous` is put back, so the + /// session doesn't go on with settings the command reported as not changed (CodeRabbit on #3544). + fn save_library_prep(&mut self, previous: Option) -> crate::Result<()> { + let saved = self.save_prefs(); + if saved.is_err() { + self.prep.library = previous; + } + saved + } + + pub(crate) fn prep_json(&self) -> Value { + json!({ + "app": self.prep.app, + "library": self.prep.library, + "settings": self.prep.settings(), + "own": self.prep.library.is_some(), + "building": self.prep.build.as_ref().filter(|b| b.running()).map(|b| b.json()), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_patch_changes_only_what_it_names_and_is_kept_in_range() { + let p = PrepSettings::default().patched(&json!({"culling": {"ahead": 99}, "develop": {"scope": "onScreen"}})).unwrap(); + assert_eq!(p.culling.ahead, MAX_AHEAD); + assert_eq!(p.culling.eye_ahead, 8, "untouched"); + assert!(p.library.previews); + assert_eq!(p.develop.scope, Scope::OnScreen); + assert_eq!(p.ahead(Mode::Develop), 0); + assert!(PrepSettings::default().patched(&json!({"culling": {"scope": "sometimes"}})).is_err()); + } + + /// Tests side by side: one test's release doesn't free the build another test holds (CodeRabbit on #3077). + #[test] + fn one_tests_release_does_not_free_another_tests_hold() { + let a = TestHold::new(); + let b = TestHold::new(); + drop(a); + assert!(TEST_HOLD.load(Ordering::Relaxed) > 0 && foreground_busy(), "the other hold still holds"); + drop(b); + } + + #[test] + fn the_photo_on_screen_holds_background_work_back() { + let cancel = AtomicBool::new(false); + foreground(); + assert!(foreground_busy()); + let t = web_time::Instant::now(); + assert!(!wait_for_foreground(&cancel)); + assert!(t.elapsed().as_millis() >= 100, "waited for the foreground to go quiet"); + cancel.store(true, Ordering::Relaxed); + foreground(); + assert!(wait_for_foreground(&cancel), "a cancel ends the wait"); + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a22547ec4a..3393eca3fc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -44,6 +44,7 @@ mod organize; mod persist; mod prefs; mod presets_scale; +mod preview_prep; mod print; mod process; mod recheck; diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index e1c6dacd62..54f3382014 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -303,6 +303,149 @@ fn browsing_a_folder_lists_its_photos_without_adding_them() { let _ = std::fs::remove_dir_all(&dir); } +/// PERF-CULL-1: the Local view reads only what the library lacks, newest file first for the default +/// (newest capture first) sort, so the first screen is read first; other sorts follow their key. +#[test] +fn browsing_queues_unknown_files_in_the_order_the_view_shows_them() { + use lightcraft_catalog::{Sort, SortKey}; + let dir = temp_dir("browse-order"); + let set_time = |p: &Path, secs: u64| { + let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs); + std::fs::File::options().write(true).open(p).unwrap().set_modified(t).unwrap(); + }; + for (name, seed, secs) in [("a.png", 1u8, 300u64), ("b.png", 2, 100), ("c.png", 3, 200)] { + write_png(&dir.join(name), seed); + set_time(&dir.join(name), 1_700_000_000 + secs); + } + let mut s = Session::new().with_fs(); + let known = dir.join("b.png").to_string_lossy().to_string(); + s.execute("library.import", &json!({"paths": [known.clone()]})).unwrap(); + let files: Vec = ["a.png", "b.png", "c.png", "gone.png"].iter().map(|n| dir.join(n).to_string_lossy().to_string()).collect(); + let (input, _) = crate::import::ScanInput::new(&mut s, &[]); + let names = |v: Vec| v.iter().map(|f| Path::new(f).file_name().unwrap().to_string_lossy().to_string()).collect::>(); + // newest first, the file already in the library left out, an unreadable one last + let q = crate::import::browse_queue(&input, files.clone(), &Sort::default()); + assert_eq!(names(q), ["a.png", "c.png", "gone.png"]); + let q = crate::import::browse_queue(&input, files.clone(), &Sort { ascending: true, ..Sort::default() }); + assert_eq!(names(q), ["c.png", "a.png", "gone.png"]); + let q = crate::import::browse_queue(&input, files.clone(), &Sort { key: SortKey::FileName, ascending: false, ..Sort::default() }); + assert_eq!(names(q), ["gone.png", "c.png", "a.png"]); + // by size an unreadable file is last in both directions (it was sized 0, first when ascending) + for ascending in [true, false] { + let q = crate::import::browse_queue(&input, files.clone(), &Sort { key: SortKey::FileSize, ascending, ..Sort::default() }); + assert_eq!(names(q).last().map(String::as_str), Some("gone.png"), "ascending {ascending}"); + } + let q = crate::import::browse_queue(&input, files, &Sort { key: SortKey::Rating, ..Sort::default() }); + assert_eq!(names(q), ["gone.png", "c.png", "a.png"], "new photos tie on rating: by name, descending as the view"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Choosing another folder while a browse orders its files (`cancel` set) stops the ordering: no queue comes +/// back, and nothing more is read (CodeRabbit on #3055). Browsing hands back the probes of earlier scans it took. +#[test] +fn a_cancelled_browse_stops_ordering_and_keeps_earlier_probes() { + use lightcraft_catalog::{Sort, SortKey}; + use std::sync::atomic::AtomicBool; + let dir = temp_dir("browse-cancel"); + write_png(&dir.join("a.png"), 1); + write_png(&dir.join("b.png"), 2); + let files: Vec = ["a.png", "b.png"].iter().map(|n| dir.join(n).to_string_lossy().to_string()).collect(); + let mut s = Session::new().with_fs(); + s.import_probes.insert(files[0].clone(), crate::media::ProbeInfo { file_size: 1, ..Default::default() }); + let (mut input, _) = crate::import::ScanInput::new(&mut s, &[]); + for key in [SortKey::CaptureDate, SortKey::FileSize, SortKey::FileName, SortKey::Random] { + let sort = Sort { key, ..Sort::default() }; + assert_eq!(crate::import::browse_queue_until(&input, files.clone(), &sort, &AtomicBool::new(true)), None, "{key:?}"); + assert_eq!(crate::import::browse_queue_until(&input, files.clone(), &sort, &AtomicBool::new(false)).map(|q| q.len()), Some(2), "{key:?}"); + } + let probes = input.take_probes(); + assert!(probes.contains_key(&files[0]), "the earlier scan's probe comes back"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Browsing a folder with its subfolders lists nothing inside the library's own folder (the +/// import that follows would read it as photos), as the import's scan skips it. +#[test] +fn browsing_with_subfolders_skips_the_librarys_own_folder() { + let dir = temp_dir("browse-skip-lib"); + std::fs::create_dir_all(dir.join("lib")).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(dir.join("lib"), false).unwrap(); + write_png(&dir.join("a.png"), 1); + write_png(&dir.join("lib").join("inside.png"), 2); + let (input, _) = crate::import::ScanInput::new(&mut s, &[]); + let root = dir.to_string_lossy().to_string(); + let names = |v: Vec| v.iter().map(|f| Path::new(f).file_name().unwrap().to_string_lossy().to_string()).collect::>(); + assert_eq!(names(crate::import::browse_files(&input, &root, true).unwrap()), ["a.png"]); + assert_eq!(names(crate::import::browse_files(&input, &root, false).unwrap()), ["a.png"]); + // the library's folder chosen itself, with or without its subfolders + let lib = dir.join("lib").to_string_lossy().to_string(); + assert!(crate::import::browse_files(&input, &lib, false).unwrap().is_empty()); + assert!(crate::import::browse_files(&input, &lib, true).unwrap().is_empty()); + // the library's folder by another name: through `..`, or a symlink to it + std::fs::create_dir_all(dir.join("other")).unwrap(); + let around = dir.join("other").join("..").join("lib").to_string_lossy().to_string(); + assert!(crate::import::browse_files(&input, &around, false).unwrap().is_empty(), "{around}"); + assert!(crate::import::browse_files(&input, &around, true).unwrap().is_empty(), "{around}"); + #[cfg(unix)] + { + let alias = dir.join("alias"); + std::os::unix::fs::symlink(dir.join("lib"), &alias).unwrap(); + let alias = alias.to_string_lossy().to_string(); + assert!(crate::import::browse_files(&input, &alias, false).unwrap().is_empty(), "{alias}"); + assert!(crate::import::browse_files(&input, &alias, true).unwrap().is_empty(), "{alias}"); + } + // a folder next to the library named through it is outside it: browsed (CodeRabbit on #3077) + std::fs::create_dir_all(dir.join("outside")).unwrap(); + write_png(&dir.join("outside").join("next.png"), 3); + let next = dir.join("lib").join("..").join("outside").to_string_lossy().to_string(); + assert_eq!(names(crate::import::browse_files(&input, &next, false).unwrap()), ["next.png"], "{next}"); + assert_eq!(names(crate::import::browse_files(&input, &next, true).unwrap()), ["next.png"], "{next}"); + // under the folder's one spelling: the paths match the folder's own, so the catalog's records are found + // (CodeRabbit on #3055) + let direct = dir.join("outside").to_string_lossy().to_string(); + for sub in [false, true] { + assert_eq!(crate::import::browse_files(&input, &next, sub).unwrap(), crate::import::browse_files(&input, &direct, sub).unwrap()); + } + // a folder inside the library that isn't there is an error too, not an empty folder + let gone = dir.join("lib").join("not-there").to_string_lossy().to_string(); + assert!(crate::import::browse_files(&input, &gone, false).is_err(), "{gone}"); + // a folder that can't be listed is an error, not an empty folder (its photos aren't "gone") + let missing = dir.join("not-there").to_string_lossy().to_string(); + assert!(crate::import::browse_files(&input, &missing, false).is_err()); + assert!(crate::import::browse_files(&input, &missing, true).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Browsing's queue breaks ties the way the catalog does (by name, in the view's direction), and +/// the import- and edit-date sorts, where new photos tie, go by name rather than file time. +#[test] +fn browsing_breaks_ties_by_name_in_the_views_direction() { + use lightcraft_catalog::{Sort, SortKey}; + let dir = temp_dir("browse-ties"); + // names and file times run in opposite directions; x and y share a time and a size + for (name, secs) in [("x.png", 100u64), ("y.png", 100), ("z.png", 50)] { + write_png(&dir.join(name), 7); + let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000 + secs); + std::fs::File::options().write(true).open(dir.join(name)).unwrap().set_modified(t).unwrap(); + } + let files: Vec = ["y.png", "z.png", "x.png"].iter().map(|n| dir.join(n).to_string_lossy().to_string()).collect(); + let order = |key: SortKey, ascending: bool| { + let mut f = files.clone(); + crate::import::browse_order(&mut f, &Sort { key, ascending, ..Sort::default() }); + f.iter().map(|f| Path::new(f).file_name().unwrap().to_string_lossy().to_string()).collect::>() + }; + assert_eq!(order(SortKey::CaptureDate, false), ["y.png", "x.png", "z.png"]); + assert_eq!(order(SortKey::CaptureDate, true), ["z.png", "x.png", "y.png"]); + for key in [SortKey::ImportDate, SortKey::EditDate, SortKey::Rating] { + assert_eq!(order(key, true), ["x.png", "y.png", "z.png"], "{key:?}"); + assert_eq!(order(key, false), ["z.png", "y.png", "x.png"], "{key:?}"); + } + assert_eq!(order(SortKey::FileSize, true), ["x.png", "y.png", "z.png"]); + assert_eq!(order(SortKey::FileSize, false), ["z.png", "y.png", "x.png"]); + let _ = std::fs::remove_dir_all(&dir); +} + /// Photos a.png, b.png, c.png imported from `old`, then: a renamed into `moved`; b renamed, with /// an impostor (same name and size, other bytes) under its old name; c gone, with two impostors. fn renamed_and_ambiguous_scene(tag: &str) -> (std::path::PathBuf, Session) { @@ -2785,3 +2928,69 @@ fn a_file_arriving_beside_its_raws_stem_reads_its_own_sidecar() { assert_eq!(read(&s, "IMG_3.TIF"), 0, "the catalogued raw owns IMG_3.xmp"); let _ = std::fs::remove_dir_all(&src); } + +/// A folder's one spelling: `.` is the current folder, `.` and `..` are taken out, never above the +/// root (CodeRabbit on #3055 / #3080). +#[test] +fn a_browsed_folder_has_one_spelling() { + use crate::import::browse_path; + let root = std::env::temp_dir(); + assert_eq!(browse_path(&root.join("lib").join("..").join("outside")).unwrap(), root.join("outside")); + assert_eq!(browse_path(&root.join(".").join("a").join(".").join("b")).unwrap(), root.join("a").join("b")); + let top: PathBuf = root.ancestors().last().map(Path::to_path_buf).unwrap_or_default(); + assert_eq!(browse_path(&top.join("..").join("x")).unwrap(), top.join("x"), "never above the root"); + assert_eq!(browse_path(Path::new(".")).unwrap(), std::env::current_dir().unwrap(), "`.` is the current folder"); + assert_eq!(browse_path(Path::new("a/..")).unwrap(), std::env::current_dir().unwrap()); + // the UI's spelling, without the disk: the same where no link comes before a `..` + let by_name = crate::import::browse_spelling(&root.join("lib").join("..").join("outside")).unwrap(); + assert_eq!(by_name, root.join("outside")); + assert_eq!(crate::import::browse_spelling(Path::new(".")).unwrap(), std::env::current_dir().unwrap()); +} + +/// `link/..` is the folder the system reads (POSIX: above where the link points; Windows: the +/// folder holding the link): browsing it lists what the system lists there (CodeRabbit on #3055 / +/// #3077 / #3080). +#[test] +fn a_link_before_dotdot_names_the_folder_the_system_reads() { + let dir = temp_dir("browse-link-dotdot"); + std::fs::create_dir_all(dir.join("real").join("sub")).unwrap(); + write_png(&dir.join("real").join("in-real.png"), 1); + write_png(&dir.join("beside-link.png"), 2); + let link = dir.join("link"); + #[cfg(unix)] + let made = std::os::unix::fs::symlink(dir.join("real").join("sub"), &link); + #[cfg(windows)] + let made = std::os::windows::fs::symlink_dir(dir.join("real").join("sub"), &link); + if let Err(e) = made { + lightcraft_testkit::skip!(System, "can't make a folder link here: {e}"); + let _ = std::fs::remove_dir_all(&dir); + return; + } + let mut s = Session::new().with_fs(); + let (input, _) = crate::import::ScanInput::new(&mut s, &[]); + let through = link.join(".."); + let names = |v: Vec| v.iter().map(|f| Path::new(f).file_name().unwrap().to_string_lossy().to_string()).collect::>(); + let listed = names(crate::import::browse_files(&input, &through.to_string_lossy(), false).unwrap()); + let mut system: Vec = + std::fs::read_dir(&through).unwrap().flatten().map(|e| e.file_name().to_string_lossy().to_string()).filter(|n| n.ends_with(".png")).collect(); + system.sort(); + assert_eq!(listed, system, "{}", through.display()); + #[cfg(unix)] + assert_eq!(listed, ["in-real.png"]); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A broken link before `..` is an error, not the link's own folder by name: the system can't read +/// `broken/..` either (CodeRabbit on #3577). +#[cfg(unix)] +#[test] +fn a_broken_link_before_dotdot_is_an_error() { + let dir = temp_dir("browse-broken-link-dotdot"); + std::fs::create_dir_all(&dir).unwrap(); + let link = dir.join("broken"); + std::os::unix::fs::symlink(dir.join("nowhere"), &link).unwrap(); + assert!(crate::import::browse_path(&link.join("..")).is_err()); + // without reading the disk the spelling is still the folder by name + assert_eq!(crate::import::browse_spelling(&link.join("..")).unwrap(), dir); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/tests/lens_refresh.rs b/crates/engine/src/tests/lens_refresh.rs index 7678c93a3d..d3bf3a3574 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, 0), Session::view_key(&p, true, 0)) + (render, thumb, Session::variant_key(&p, &p.develop, 128, 0), s.view_key(&p, true)) }; 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/preview_prep.rs b/crates/engine/src/tests/preview_prep.rs new file mode 100644 index 0000000000..0981c2cf96 --- /dev/null +++ b/crates/engine/src/tests/preview_prep.rs @@ -0,0 +1,635 @@ +//! Previews are made once and used (notes 47–49): the loupe shows a built or prepared preview +//! instead of rendering the photo again, a build skips photos whose previews are there, built +//! previews are on disk when the build says it is done, the import's queue shows one row, and the +//! background preparation follows the user and gives way to a build that was asked for. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::Ordering; + +use lightcraft_catalog::PhotoId; +use serde_json::json; + +use crate::Session; +use crate::media::QuickSource; + +fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lc-preview-prep-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn png(p: &Path, seed: u8) { + let img = lightcraft_raster::Rgba8::from_fn(600, 400, |x, y| [(x % 251) as u8, (y % 241) as u8, seed, 255]); + let b = + crate::export::encode_image(&img, &crate::export::ExportOptions { format: crate::export::ExportFormat::Png, ..Default::default() }).unwrap(); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, b).unwrap(); +} + +/// A library on disk with `n` photos (600 × 400 PNGs) imported, in name order. +fn library(tag: &str, n: usize) -> (Session, PathBuf, Vec) { + let root = temp_dir(tag); + let paths: Vec = (0..n) + .map(|i| { + let p = root.join("shoot").join(format!("p{i:02}.png")); + png(&p, (i * 20) as u8); + p.to_string_lossy().to_string() + }) + .collect(); + let mut s = Session::new().with_fs(); + s.open_library(root.join("lib"), false).unwrap(); + s.execute("library.import", &json!({"paths": paths})).unwrap(); + let mut ids: Vec<(String, PhotoId)> = s.catalog.photos().map(|p| (p.file_name.clone(), p.id)).collect(); + ids.sort(); + (s, root, ids.into_iter().map(|(_, id)| id).collect()) +} + +fn ids_json(ids: &[PhotoId]) -> Vec { + ids.iter().map(|i| i.0).collect() +} + +/// FredApps on #3077: building previews (asked for, and the background preparation while culling) +/// writes only into the library's own cache, never next to the photos: the shoot folder holds the +/// same files afterwards, byte for byte. +#[test] +fn building_previews_writes_nothing_next_to_the_photos() { + let (mut s, root, ids) = library("prep-beside", 4); + let shoot = root.join("shoot"); + let listing = |dir: &std::path::Path| { + let mut v: Vec<(String, Vec)> = std::fs::read_dir(dir) + .unwrap() + .map(|e| e.unwrap().path()) + .map(|p| (p.file_name().unwrap().to_string_lossy().to_string(), std::fs::read(&p).unwrap())) + .collect(); + v.sort(); + v + }; + let before = listing(&shoot); + assert_eq!(before.len(), 4); + let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap(); + assert_eq!(r["done"], 4, "{r}"); + for id in &ids { + s.prep_tick(crate::prep::Mode::Library, Some(*id), false); + } + if let Some(b) = s.preview_build.clone() { + assert!(wait_finished(&b), "the background build stops (a late write would slip past the check)"); + } + assert_eq!(listing(&shoot), before, "nothing was written next to the photos"); + let _ = std::fs::remove_dir_all(&root); +} + +/// Note 47: a built preview at least as big as the loupe's size is what the loupe shows (fitted +/// down, no render); a smaller one is not (the photo renders). +#[test] +fn the_loupe_uses_a_built_preview_that_is_big_enough() { + let mut s = Session::with_demo(); + let id = s.active().unwrap(); + s.execute("library.buildPreviews", &json!({"ids": [id.0], "edge": 512, "wait": true})).unwrap(); + let r = s.loupe_job(id, 300, 300, true).unwrap().run(); + assert_eq!(r.quick, Some(QuickSource::Cached), "taken from the built preview"); + let img = r.rendered.unwrap().image; + assert_eq!(img.width.max(img.height), 300, "fitted to the loupe's size"); + // bigger than what was built: rendered + let r = s.loupe_job(id, 900, 900, true).unwrap().run(); + assert_eq!(r.quick, None, "a preview too small for the loupe is not used"); + assert!(r.rendered.is_ok()); + // a draft (a slider held) never comes from the cache + let r = s.loupe_job(id, 300, 300, true).unwrap().draft().run(); + assert_eq!(r.quick, None); +} + +/// Shrinking a cached view keeps its colour (an average of the pixels it covers) and its aspect, +/// and refuses to enlarge. +#[test] +fn a_cached_view_is_fitted_down_never_up() { + let img = lightcraft_raster::Rgba8::from_fn(400, 200, |x, _| if x % 2 == 0 { [200, 100, 0, 255] } else { [100, 50, 0, 255] }); + let f = crate::media::fit_cached(&img, 100, 100).unwrap(); + assert_eq!((f.width, f.height), (100, 50)); + assert!(f.data.iter().all(|p| p[0] == 150 && p[1] == 75), "averaged"); + assert!(crate::media::fit_cached(&img, 800, 800).is_none(), "never enlarged"); + assert_eq!(crate::media::fit_cached(&img, 401, 999).map(|f| f.width), Some(400), "a pixel short is the same size"); + assert!(crate::media::fit_cached(&img, 0, 10).is_none()); +} + +/// Note 47: the rendered previews in memory follow the memory budget (they were capped at +/// 128 MB, about 84 loupe renders, whatever the budget). +#[test] +fn the_memory_for_rendered_previews_grows_with_the_budget() { + let share = crate::memory::cache_share(20 << 30); + assert!(crate::media::rendered_budget(share) >= 2 << 30, "a 20 GB budget keeps gigabytes of previews"); + assert_eq!(crate::media::rendered_budget(256 << 20), 128 << 20, "a small budget keeps the old floor where it can"); + assert!(crate::media::rendered_budget(64 << 20) <= 32 << 20, "and never more than the share allows"); +} + +/// Note 47: the disk cache's default room grows with the library, so a wedding's previews are not +/// pruned while they are built (the fixed 2 GB held about 2 000 standard previews). +#[test] +fn the_disk_cache_default_grows_with_the_library() { + assert_eq!(crate::media::default_disk_cache_bytes(10), crate::media::DISK_CACHE_BYTES); + assert!(crate::media::default_disk_cache_bytes(4000) >= 4000 * (1 << 20)); + let (mut s, root, ids) = library("diskroom", 2); + assert_eq!(s.cache_bytes(), crate::media::DISK_CACHE_BYTES); + s.cache_mb = 700; + assert_eq!(s.cache_bytes(), 700 << 20, "a size the user chose is kept"); + assert_eq!(ids.len(), 2); + let _ = std::fs::remove_dir_all(root); +} + +/// Notes 47 and 49: a build skips photos whose previews are there (built before, or by the loupe), +/// renders those whose preview is too small, and its previews are on disk when it is done (they +/// were left to a writer that skips writes when it falls behind). +#[test] +fn a_build_skips_what_is_there_and_leaves_it_on_disk() { + let (mut s, root, ids) = library("skip", 4); + let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap(); + assert_eq!((r["done"].as_u64(), r["skipped"].as_u64(), r["failed"].as_u64()), (Some(4), Some(0), Some(0)), "{r}"); + // on disk now (no waiting for a writer), at the size built + for id in &ids { + let p = s.catalog.photo(*id).unwrap().clone(); + let key = s.view_key(&p, true); + let disk = s.media.rendered.disk().expect("a library has a disk cache"); + let (w, h) = disk.dims(key).expect("the view preview is on disk"); + assert_eq!(w.max(h), 300); + } + // again: nothing is rendered + let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap(); + assert_eq!((r["done"].as_u64(), r["skipped"].as_u64()), (Some(4), Some(4)), "{r}"); + // forced, or bigger: rendered + let r = s.execute("library.buildPreviews", &json!({"ids": [ids[0].0], "edge": 300, "wait": true, "force": true})).unwrap(); + assert_eq!(r["skipped"], 0, "{r}"); + let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 500, "wait": true})).unwrap(); + assert_eq!(r["skipped"], 0, "too small for what is asked: built again {r}"); + // a library opened again finds them on disk (memory is empty) + drop(s); + let mut s = Session::new().with_fs(); + s.open_library(root.join("lib"), false).unwrap(); + let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 500, "wait": true})).unwrap(); + assert_eq!(r["skipped"], 4, "{r}"); + let r = s.loupe_job(ids[1], 400, 400, true).unwrap().run(); + assert_eq!(r.quick, Some(QuickSource::Cached), "the loupe uses the preview built in the last session"); + let _ = std::fs::remove_dir_all(root); +} + +/// A forced build renders the grid thumbnail again too, not the one its cache holds (CodeRabbit on #3577: +/// the thumbnail job read its cache first, so `force` rebuilt only the view). +#[test] +fn a_forced_build_renders_the_thumbnail_again() { + let (mut s, root, ids) = library("force-thumb", 1); + let build = |s: &mut Session, force: bool| { + s.execute("library.buildPreviews", &json!({"ids": [ids[0].0], "edge": 300, "wait": true, "force": force})).unwrap() + }; + build(&mut s, false); + let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300)); + let thumb = jobs.iter().find(|j| j.view_cache.is_none() && j.cache.is_some()).expect("a thumbnail job"); + let ((cache, key), generation) = (thumb.cache.clone().unwrap(), thumb.cache_generation); + let stand_in = lightcraft_raster::Rgba8 { width: 1, height: 1, data: vec![[1, 2, 3, 255]] }; + assert!(cache.put_at(generation, key, std::sync::Arc::new(stand_in))); + let r = build(&mut s, false); + assert_eq!(r["skipped"], 1, "{r}"); + assert_eq!(cache.get_at(generation, key).map(|i| i.width), Some(1), "unforced: kept"); + let r = build(&mut s, true); + assert_eq!(r["failed"], 0, "{r}"); + assert!(cache.get_at(generation, key).is_some_and(|i| i.width > 1), "forced: rendered again"); + let _ = std::fs::remove_dir_all(root); +} + +/// Note 47: standard previews are built at least as big as the loupe on this screen asks for. +#[test] +fn standard_previews_are_as_big_as_the_loupe() { + let mut s = Session::with_demo(); + assert_eq!(crate::cmd::previews::standard_edge(&s), crate::cmd::previews::STANDARD_EDGE); + s.loupe_edge = 3000; + assert_eq!(crate::cmd::previews::standard_edge(&s), 3000); + s.loupe_edge = 1200; + assert_eq!(crate::cmd::previews::standard_edge(&s), crate::cmd::previews::STANDARD_EDGE); +} + +/// Note 48: a background build goes from where the user is, in the direction they step, and +/// follows them when they jump. +#[test] +fn the_background_build_starts_where_the_user_is() { + use crate::cmd::previews::PreviewBuild; + let b = PreviewBuild { order: (10..20).collect(), ..Default::default() }; + let mut queue: Vec> = (10..20).map(Some).collect(); + b.focus_on(PhotoId(14), false); + let mut took = Vec::new(); + for _ in 0..3 { + let i = b.next_index(&queue).unwrap(); + took.push(queue[i].take().unwrap()); + } + assert_eq!(took, vec![14, 15, 16], "forward from the photo on screen"); + b.focus_on(PhotoId(12), true); + let i = b.next_index(&queue).unwrap(); + assert_eq!(queue[i], Some(12), "jumped back: from there, backwards"); + queue[i] = None; + assert_eq!(b.next_index(&queue).map(|i| queue[i]), Some(Some(11))); + // the end reached: the rest the other way + b.focus_on(PhotoId(19), false); + for _ in 0..6 { + let i = b.next_index(&queue).unwrap(); + queue[i] = None; + } + assert!(b.next_index(&queue).is_none(), "all taken"); +} + +/// Note 49: the background preparation gives way to a build that is asked for (no error, no +/// two builds), and is not started again for a view the user stopped it in. +#[test] +fn a_build_asked_for_replaces_the_background_one() { + let (mut s, root, ids) = library("replace", 3); + // held back: the photo on screen is being made all along (held until released below, not for a + // deadline a slow test machine could pass before the build asked for comes) + let hold = crate::prep::TestHold::new(); + s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "background": true})).unwrap(); + let bg = s.preview_build.clone().unwrap(); + assert!(bg.background && bg.running()); + assert!(s.activity.list().iter().any(|t| t.label == "Preparing photos in the background"), "{:?}", s.activity.list()); + // a second background build is refused; one that is asked for replaces it + assert!(s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "background": true})).is_err()); + let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap(); + assert_eq!(r["done"], 3, "{r}"); + assert!(bg.cancel.load(Ordering::Relaxed), "the background build was stopped"); + drop(hold); + // its workers stop before their library is removed under them + assert!(wait_finished(&bg), "a cancelled build stops"); + drop(s); + std::fs::remove_dir_all(&root).unwrap(); +} + +/// Note 48: the background preparation starts once the user steps through photos in the loupe +/// (not when a library opens), builds the view's previews in one cancellable row, and a stop +/// from that row holds for the view. +#[test] +fn the_background_preparation_starts_when_culling_and_can_be_stopped() { + let (mut s, root, ids) = library("prep", 4); + let mode = crate::prep::Mode::Library; + s.prep_tick(mode, None, false); + s.prep_tick(mode, Some(ids[0]), false); + assert!(s.preview_build.is_none(), "opening and looking at one photo starts nothing"); + s.prep_tick(mode, Some(ids[1]), false); + s.prep_tick(mode, Some(ids[2]), false); + let b = s.preview_build.clone().expect("culling: the view is prepared"); + assert!(b.background); + assert_eq!(b.total, 4); + for _ in 0..600 { + s.prep_tick(mode, Some(ids[2]), false); + if !b.running() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + assert!(!b.running(), "built"); + assert_eq!(b.done.load(Ordering::Relaxed), 4); + s.prep_tick(mode, Some(ids[3]), false); + assert!(same_build(&s, &b), "not started again for the same view"); + // switched off: nothing starts in a new view either + s.execute("prefs.setBackgroundPrep", &json!({"settings": {"library": {"previews": false}}})).unwrap(); + let off = s.execute("prefs.backgroundPrep", &json!({})).unwrap(); + assert_eq!(off["settings"]["library"]["previews"], false, "{off}"); + assert_eq!(off["settings"]["culling"]["previews"], true, "each mode has its own"); + let _ = std::fs::remove_dir_all(root); +} + +/// While editing, the whole view's build follows the Library row (its switch and "which photos"); +/// the Editing row's scope is only for the photos kept ready ahead. +#[test] +fn editing_builds_the_view_by_the_library_rows_scope() { + let (mut s, root, ids) = library("prep-develop", 4); + s.execute("prefs.setBackgroundPrep", &json!({"settings": {"develop": {"scope": "onScreen"}, "library": {"scope": "marked"}}})).unwrap(); + s.execute("photo.rate", &json!({"ids": [ids[1].0], "rating": 3})).unwrap(); + let mode = crate::prep::Mode::Develop; + for id in &ids { + s.prep_tick(mode, Some(*id), false); + } + let b = s.preview_build.clone().expect("the Library row asks for the view while editing"); + assert_eq!(b.total, 1, "only the marked photos, as the Library row says"); + b.cancel.store(true, Ordering::Relaxed); + // its workers stop before their library is removed under them + assert!(wait_finished(&b), "a cancelled build stops"); + drop(s); + std::fs::remove_dir_all(&root).unwrap(); +} + +/// With "which photos" = marked, marking another photo changes what the view's build prepares: a +/// build for the newly marked set follows (it wasn't, as the view itself stayed the same). +#[test] +fn marking_a_photo_prepares_it_in_the_marked_scope() { + let (mut s, root, ids) = library("prep-marked", 4); + s.execute("prefs.setBackgroundPrep", &json!({"settings": {"library": {"scope": "marked"}}})).unwrap(); + s.execute("photo.rate", &json!({"ids": [ids[1].0], "rating": 3})).unwrap(); + let mode = crate::prep::Mode::Library; + let tick = |s: &mut Session, k: usize| s.prep_tick(mode, Some(ids[k % 3]), false); + for k in 0..3 { + tick(&mut s, k); + } + let first = s.preview_build.clone().expect("the marked photos are prepared"); + assert_eq!(first.total, 1); + s.execute("photo.rate", &json!({"ids": [ids[3].0], "rating": 2})).unwrap(); + let mut next = None; + for k in 0..600 { + tick(&mut s, k); + if let Some(b) = s.preview_build.clone().filter(|b| !std::sync::Arc::ptr_eq(b, &first)) { + next = Some(b); + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + let next = next.expect("a build for the newly marked set"); + assert_eq!(next.total, 2); + next.cancel.store(true, Ordering::Relaxed); + // both builds' workers stop before their library is removed under them + for b in [&first, &next] { + assert!(wait_finished(b), "a cancelled build stops"); + } + drop(s); + std::fs::remove_dir_all(&root).unwrap(); +} + +/// Waits (up to 30 s) for a build's workers to finish. +fn wait_finished(b: &crate::cmd::previews::PreviewBuild) -> bool { + for _ in 0..1500 { + if b.finished.load(Ordering::Relaxed) { + return true; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + false +} + +/// A background build started for one view is stopped when another view is shown (here the +/// library changes under it), not left building photos no longer shown; it doesn't count as +/// stopped by the user, so the view now shown is prepared. +#[test] +fn a_view_change_stops_the_background_build_for_the_old_view() { + let (mut s, root, ids) = library("prep-view", 6); + let mode = crate::prep::Mode::Library; + // the build's lanes wait at their foreground check until released below + let hold = crate::prep::TestHold::new(); + for id in &ids[..3] { + s.prep_tick(mode, Some(*id), false); + } + let b = s.preview_build.clone().expect("the view is prepared"); + assert!(b.running()); + s.catalog.apply(lightcraft_catalog::Op::RemovePhoto { id: ids[5] }).unwrap(); + s.prep_tick(mode, Some(ids[2]), false); + let stopped = b.cancel.load(Ordering::Relaxed); + drop(hold); + assert!(stopped, "the old view's build is stopped"); + // the user steps on in the view now shown + for k in 0..600 { + s.prep_tick(mode, Some(ids[k % 3]), false); + if s.preview_build.as_ref().is_some_and(|p| !std::sync::Arc::ptr_eq(p, &b)) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + let next = s.preview_build.clone().expect("a build for the view now shown"); + assert!(!std::sync::Arc::ptr_eq(&next, &b)); + assert_eq!(next.total, 5); + next.cancel.store(true, Ordering::Relaxed); + // both builds' workers stop before their library is removed under them + for b in [&b, &next] { + assert!(wait_finished(b), "a cancelled build stops"); + } + drop(s); + std::fs::remove_dir_all(&root).unwrap(); +} + +fn same_build(s: &Session, b: &std::sync::Arc) -> bool { + s.preview_build.as_ref().is_some_and(|p| std::sync::Arc::ptr_eq(p, b)) +} + +/// Note 48: a library keeps its own background settings (a timelapse library prepares nothing), +/// saved with it; the app-wide ones apply elsewhere. +#[test] +fn a_library_can_keep_its_own_background_settings() { + let (mut s, root, _ids) = library("own", 1); + let r = s.execute("prefs.setBackgroundPrep", &json!({"library": true, "settings": {"culling": {"previews": false, "ahead": 0}}})).unwrap(); + assert_eq!(r["own"], true, "{r}"); + assert_eq!(r["settings"]["culling"]["ahead"], 0); + assert_eq!(r["app"]["culling"]["ahead"], 5, "the app-wide ones are unchanged"); + drop(s); + let mut s = Session::new().with_fs(); + s.open_library(root.join("lib"), false).unwrap(); + assert_eq!(s.prep_settings().culling.ahead, 0, "kept with the library"); + assert_eq!(s.prep_settings().ahead(crate::prep::Mode::Culling), 0); + s.execute("prefs.setBackgroundPrep", &json!({"reset": true})).unwrap(); + assert_eq!(s.prep_settings().culling.ahead, 5, "back to the app-wide settings"); + assert!(s.execute("prefs.setBackgroundPrep", &json!({"settings": 3})).is_err()); + let _ = std::fs::remove_dir_all(root); +} + +/// Note 47: Build Previews with one photo open (selected) builds every photo in view, as its menu +/// item says ("Visible"); it built only the open photo, so culling after it found nothing built. +#[test] +fn build_previews_with_one_photo_open_builds_the_view() { + let mut s = Session::with_demo(); + let n = s.visible_cloned().len(); + assert!(n > 2); + let one = s.visible_cloned()[0]; + s.selection = crate::Selection::single(one); + let r = s.execute("library.buildPreviews", &json!({"edge": 256, "wait": true})).unwrap(); + assert_eq!(r["total"], n, "{r}"); + let two: Vec = s.visible_cloned().into_iter().take(2).collect(); + s.selection = crate::Selection { ids: two.clone(), active: two.first().copied() }; + let r = s.execute("library.buildPreviews", &json!({"edge": 256, "wait": true})).unwrap(); + assert_eq!(r["total"], 2, "a choice of photos is built alone {r}"); +} + +/// A view the loupe kept only in memory (its deferred disk write skipped when the writer fell behind) is not +/// counted as built: the build renders it and writes it to disk (CodeRabbit on #3077). +#[test] +fn a_preview_kept_only_in_memory_is_built_and_written() { + let (mut s, root, ids) = library("memonly", 1); + let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300)); + assert!(!jobs.is_empty()); + for j in &jobs { + let img = std::sync::Arc::new(lightcraft_raster::Rgba8::new(300, 200)); + if let Some((cache, key)) = &j.view_cache { + cache.put_memory(*key, img); + } else if let Some((cache, key)) = &j.cache { + cache.put_memory(*key, img); + } + } + assert!(!crate::cmd::previews::already_built(&jobs), "a copy only in memory is not a built preview"); + let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap(); + assert_eq!((r["skipped"].as_u64(), r["failed"].as_u64()), (Some(0), Some(0)), "{r}"); + let p = s.catalog.photo(ids[0]).unwrap().clone(); + let key = s.view_key(&p, true); + assert!(s.media.rendered.disk().and_then(|d| d.dims(key)).is_some(), "the view preview is on disk"); + let _ = std::fs::remove_dir_all(root); +} + +/// A view preview the cache folder can't take (full, or not writable) fails the photo instead of counting it +/// as built (CodeRabbit on #3077). +#[test] +fn a_preview_that_cannot_be_written_fails_the_build() { + let (mut s, root, ids) = library("unwritable", 2); + let dir = s.media.rendered.disk().expect("a library has a disk cache").dir().to_path_buf(); + let _ = std::fs::remove_dir_all(&dir); + // a file where the cache folder goes: nothing can be written under it + std::fs::write(&dir, b"not a folder").unwrap(); + let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap(); + assert_eq!(r["failed"].as_u64(), Some(2), "{r}"); + let _ = std::fs::remove_file(&dir); + let _ = std::fs::remove_dir_all(root); +} + +/// A photo whose preview cache is discarded while it renders is not counted as built: its preview isn't kept +/// (CodeRabbit on #3077). +#[test] +fn a_preview_rendered_for_a_discarded_cache_fails_the_photo() { + let (mut s, root, ids) = library("discarded", 1); + let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300)); + s.execute("library.clearPreviews", &json!({})).unwrap(); + assert!(!crate::cmd::previews::run_photo(jobs), "nothing was kept: the photo is not built"); + let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300)); + assert!(crate::cmd::previews::run_photo(jobs), "built for the cache as it is now"); + let _ = std::fs::remove_dir_all(root); +} + +/// A forced build renders a photo itself even when another build was rendering it and made its previews +/// (CodeRabbit on #3080): the other build's result is not taken as this one's. +#[test] +fn a_forced_build_renders_a_photo_another_build_was_rendering() { + let (mut s, root, ids) = library("forced-shared", 1); + s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap(); + let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300)); + let held = crate::cmd::previews::hold_building(ids[0].0, &jobs).expect("nobody renders it now"); + s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "force": true})).unwrap(); + let b = s.preview_build.clone().expect("the build"); + std::thread::sleep(std::time::Duration::from_millis(300)); + assert_eq!(b.done.load(Ordering::Relaxed), 0, "not counted while the other build holds it"); + drop(held); + assert!(wait_finished(&b)); + let counts = + (b.done.load(Ordering::Relaxed), b.failed.load(Ordering::Relaxed), b.shared.load(Ordering::Relaxed), b.skipped.load(Ordering::Relaxed)); + assert_eq!(counts, (1, 0, 0, 0), "rendered here, not taken from the other build"); + let _ = std::fs::remove_dir_all(root); +} + +/// A photo another build is rendering is not counted until that render is over: here the other build never +/// made its previews, so this build renders it (CodeRabbit on #3080). +#[test] +fn a_photo_another_build_is_rendering_is_counted_only_once_it_is_built() { + let (mut s, root, ids) = library("shared", 1); + let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300)); + let held = crate::cmd::previews::hold_building(ids[0].0, &jobs).expect("nobody renders it yet"); + s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300})).unwrap(); + let b = s.preview_build.clone().expect("the build"); + std::thread::sleep(std::time::Duration::from_millis(300)); + assert_eq!(b.done.load(Ordering::Relaxed), 0, "not counted while the other build holds it"); + drop(held); + assert!(wait_finished(&b)); + assert_eq!((b.done.load(Ordering::Relaxed), b.failed.load(Ordering::Relaxed), b.shared.load(Ordering::Relaxed)), (1, 0, 0)); + let p = s.catalog.photo(ids[0]).unwrap().clone(); + let key = s.view_key(&p, true); + assert!(s.media.rendered.disk().and_then(|d| d.dims(key)).is_some(), "rendered here, on disk"); + let _ = std::fs::remove_dir_all(root); +} + +/// CodeRabbit on #3544: a library preparation setting that can't be saved is not kept, nor is +/// going back to the app-wide settings: the session stays as the command's error says. +#[test] +fn a_prep_setting_that_cant_be_saved_is_not_kept() { + use crate::prep::PrepSettings; + let (mut s, root, _) = library("prep-unsaved", 1); + let mut own = PrepSettings::default(); + own.culling.ahead = 3; + s.set_prep_settings(own, true).unwrap(); + // prefs.json can't be written: a folder stands in its place + let prefs = root.join("lib").join("prefs.json"); + let _ = std::fs::remove_file(&prefs); + std::fs::create_dir_all(prefs.join("in-the-way")).unwrap(); + let mut other = own; + other.culling.ahead = 5; + assert!(s.set_prep_settings(other, true).is_err()); + assert_eq!(s.prep_json()["library"], json!(own), "the setting that couldn't be saved is not kept"); + assert!(s.clear_library_prep().is_err()); + assert_eq!(s.prep_json()["library"], json!(own), "nor going back to the app-wide settings"); + let _ = std::fs::remove_dir_all(&root); +} + +/// CodeRabbit on #3544: a build asked for with malformed ids fails without stopping the +/// background preparation that is running. +#[test] +fn a_bad_build_request_leaves_the_background_build_running() { + let _hold = crate::prep::TestHold::new(); + let (mut s, root, ids) = library("prep-bad-ids", 3); + s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "background": true})).unwrap(); + let b = s.preview_build.clone().expect("the background build"); + assert!(b.running()); + assert!(s.execute("library.buildPreviews", &json!({"ids": ["x"]})).is_err(), "ids that are not photo ids"); + assert!(!b.cancel.load(std::sync::atomic::Ordering::Relaxed), "the background build was not stopped"); + let _ = std::fs::remove_dir_all(&root); +} + +/// CodeRabbit on #3577: smart previews asked for in the background with malformed ids fail without +/// stopping the background preparation either. +#[test] +fn a_bad_smart_preview_request_leaves_the_background_build_running() { + let _hold = crate::prep::TestHold::new(); + let (mut s, root, ids) = library("prep-bad-smart-ids", 3); + s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "background": true})).unwrap(); + let b = s.preview_build.clone().expect("the background build"); + assert!(b.running()); + assert!(s.execute("library.smartPreviews", &json!({"ids": ["x"], "background": true})).is_err(), "ids that are not photo ids"); + assert!(!b.cancel.load(std::sync::atomic::Ordering::Relaxed), "the background build was not stopped"); + // a smart-preview worker that can't start: the background build carries on, and stays the session's + crate::cmd::previews::test_gate::fail_next_spawn(); + assert!(s.execute("library.smartPreviews", &json!({"ids": ids_json(&ids), "background": true})).is_err(), "the worker didn't start"); + assert!(!b.cancel.load(std::sync::atomic::Ordering::Relaxed), "the background build was not stopped"); + assert!(s.preview_build.as_ref().is_some_and(|now| std::sync::Arc::ptr_eq(now, &b)), "and is still the session's build"); + // (stopped and finished before its folder goes) + b.cancel.store(true, std::sync::atomic::Ordering::Relaxed); + drop(_hold); + let until = std::time::Instant::now() + std::time::Duration::from_secs(20); + while b.running() && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let _ = std::fs::remove_dir_all(&root); +} + +/// CodeRabbit on #3544: a build asked for whose worker can't start fails without stopping or +/// replacing the background preparation that is running. +#[test] +fn a_build_that_cant_start_leaves_the_background_build_running() { + let _hold = crate::prep::TestHold::new(); + let (mut s, root, ids) = library("prep-no-thread", 3); + s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "background": true})).unwrap(); + let b = s.preview_build.clone().expect("the background build"); + assert!(b.running()); + crate::cmd::previews::test_gate::fail_next_spawn(); + assert!(s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids)})).is_err(), "the worker didn't start"); + assert!(!b.cancel.load(std::sync::atomic::Ordering::Relaxed), "the background build was not stopped"); + assert!(s.preview_build.as_ref().is_some_and(|now| std::sync::Arc::ptr_eq(now, &b)), "and is still the session's build"); + let _ = std::fs::remove_dir_all(&root); +} + +/// CodeRabbit on #3080: a background build that can't start isn't tried again on every tick; the +/// view tries again once [`crate::prep::RETRY_AFTER`] has passed. +#[test] +fn a_build_that_cant_start_waits_before_trying_again() { + let (mut s, root, ids) = library("prep-retry", 3); + let mode = crate::prep::Mode::Library; + s.prep.fail_starts = 1; + for id in &ids { + s.prep_tick(mode, Some(*id), false); + } + assert!(s.preview_build.is_none(), "the start failed"); + assert!(s.prep.retry_at.is_some()); + // the app is told when to look again (a frame is asked for then) + assert!(s.prep_retry_in().is_some_and(|d| d <= crate::prep::RETRY_AFTER && d > crate::prep::RETRY_AFTER / 2)); + s.prep_tick(mode, Some(ids[2]), false); + assert!(s.preview_build.is_none(), "not tried again at once"); + // the wait is over: no more frames asked for it (CodeRabbit on #3077 / #3080) + s.prep.retry_at = s.prep.retry_at.map(|(view, _)| (view, web_time::Instant::now())); + assert_eq!(s.prep_retry_in(), None, "a deadline that has passed asks for no frame"); + s.prep_tick(mode, Some(ids[2]), false); + let b = s.preview_build.clone().expect("tried again"); + assert!(b.background && s.prep.retry_at.is_none()); + b.cancel.store(true, Ordering::Relaxed); + let _ = wait_finished(&b); + let _ = std::fs::remove_dir_all(&root); +} diff --git a/crates/preview/src/disk.rs b/crates/preview/src/disk.rs index ca82870483..a1395a04ca 100644 --- a/crates/preview/src/disk.rs +++ b/crates/preview/src/disk.rs @@ -172,15 +172,43 @@ impl DiskCache { } } - pub fn put(&self, key: Hash128, img: &Rgba8) { - let Some(bytes) = encode_jpeg(img) else { return }; + /// The size (width, height) of the picture kept under `key`, read from the start of its file + /// only (no decode, no hit counted, nothing written): to tell whether a preview is there and + /// big enough without loading it. + pub fn dims(&self, key: Hash128) -> Option<(usize, usize)> { + use std::io::Read; let p = self.path(key); - let Some(parent) = p.parent() else { return }; + if !p.parent().is_some_and(is_real_dir) { + return None; + } + let mut f = std::fs::File::open(&p).or_else(|_| std::fs::File::open(self.named(key, OLD_EXT))).ok()?; + // the size is normally in the first few KiB: more is read only when that is not enough + let mut head = Vec::new(); + for limit in [FIRST_HEADER_BYTES, HEADER_BYTES] { + let more = limit.saturating_sub(head.len() as u64); + (&mut f).take(more).read_to_end(&mut head).ok()?; + if let Some(dims) = jpeg_dims(&head) { + return Some(dims); + } + if (head.len() as u64) < limit { + // the whole file was read + break; + } + } + None + } + + /// Write `img` under `key`. Returns whether the file was written (a full or unwritable cache folder + /// gives `false`; the cache is unchanged then). + pub fn put(&self, key: Hash128, img: &Rgba8) -> bool { + let Some(bytes) = encode_jpeg(img) else { return false }; + let p = self.path(key); + let Some(parent) = p.parent() else { return false }; // a folder the cache makes for itself says that it is a cache; one that was there // already may hold somebody's files, and is not declared one let made = !self.dir.exists(); if std::fs::create_dir_all(parent).is_err() || !is_real_dir(parent) { - return; + return false; } if made { let _ = std::fs::write(self.dir.join(TAG), TAG_TEXT); @@ -197,7 +225,7 @@ impl DiskCache { let written = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp).and_then(|mut f| std::io::Write::write_all(&mut f, &bytes)); if written.is_err() || std::fs::rename(&tmp, &p).is_err() { let _ = std::fs::remove_file(&tmp); - return; + return false; } self.writes.fetch_add(1, Ordering::Relaxed); *used = used.saturating_sub(old_len).saturating_add(bytes.len() as u64); @@ -205,7 +233,10 @@ impl DiskCache { drop(total); if over { self.prune(); + // (a picture bigger than the room pruning leaves goes too: it was not kept) + return p.is_file(); } + true } /// All cache files (only names of the cache's own shape, see [`is_cache_file`]): @@ -374,6 +405,12 @@ impl DiskCache { *t.get_or_insert_with(|| self.scan().iter().map(|f| f.1).sum()) } + /// Bytes on disk when already known, without reading the folder (`None` until [`Self::size`], + /// a write or a prune has counted them). + pub fn known_size(&self) -> Option { + *self.total.lock().unwrap_or_else(|e| e.into_inner()) + } + pub fn clear(&self) { for (p, _, _) in self.scan() { let _ = std::fs::remove_file(p); @@ -432,6 +469,22 @@ pub fn encode_jpeg(img: &Rgba8) -> Option> { Some(out) } +/// How much of a cached file [`DiskCache::dims`] reads: the JPEG headers this cache writes come +/// first and are a few hundred bytes. +const HEADER_BYTES: u64 = 64 << 10; +/// What [`DiskCache::dims`] reads first, which holds the size of the JPEGs this cache writes. +const FIRST_HEADER_BYTES: u64 = 4 << 10; + +/// A JPEG's (width, height) from its headers (`None`: not a JPEG, or cut short before its frame header). +pub fn jpeg_dims(bytes: &[u8]) -> Option<(usize, usize)> { + use zune_core::bytestream::ZCursor; + let mut d = zune_jpeg::JpegDecoder::new(ZCursor::new(bytes)); + d.decode_headers().ok()?; + let info = d.info()?; + let (w, h) = (info.width as usize, info.height as usize); + (w > 0 && h > 0).then_some((w, h)) +} + /// Decode a cached thumbnail (see [`encode_jpeg`]). pub fn decode_jpeg(bytes: &[u8]) -> Option { use zune_core::bytestream::ZCursor; diff --git a/crates/preview/src/lib.rs b/crates/preview/src/lib.rs index 14bd50a1b3..3c5485ae8f 100644 --- a/crates/preview/src/lib.rs +++ b/crates/preview/src/lib.rs @@ -21,7 +21,7 @@ use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, RwLock}; -pub use disk::{DiskCache, decode_jpeg, encode_jpeg}; +pub use disk::{DiskCache, decode_jpeg, encode_jpeg, jpeg_dims}; pub use hash::{Hash128, Hasher128, hash_bytes}; use lightcraft_raster::Rgba8; pub use lru::{Lru, next_tick}; @@ -108,20 +108,80 @@ impl PreviewCache { Some(img) } - pub fn put(&self, key: Hash128, img: Arc) { - self.put_at(self.generation(), key, img); + /// The size of the image kept under `key` (memory, else disk: read from its file's header), without + /// loading it or changing what is kept. + pub fn dims(&self, key: Hash128) -> Option<(usize, usize)> { + if self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner).is_none() { + return None; + } + if let Some(v) = self.mem.lock().unwrap_or_else(|e| e.into_inner()).peek(&key) { + return Some((v.width, v.height)); + } + self.disk.as_ref()?.dims(key) } - pub fn put_at(&self, generation: u64, key: Hash128, img: Arc) { + /// The size of the image kept under `key` where it lasts: on disk when the cache has a disk (a copy only + /// in memory, whose deferred write may have been skipped, doesn't count), else in memory. Nothing is + /// loaded or changed. + pub fn stored_dims(&self, key: Hash128) -> Option<(usize, usize)> { + match &self.disk { + Some(d) if self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner).is_some() => d.dims(key), + Some(_) => None, + None => self.dims(key), + } + } + + /// The memory LRU's copy of `key`, without looking on disk. + pub fn get_memory(&self, key: Hash128) -> Option> { + if self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner).is_none() { + return None; + } + self.mem.lock().unwrap_or_else(|e| e.into_inner()).get(&key).cloned() + } + + /// Keep `img` in memory only (it is never written to disk): for pictures that are cheap + /// enough to make again, such as a raw's decoded camera JPEG, but worth keeping for a revisit. + pub fn put_memory(&self, key: Hash128, img: Arc) { + // (the guard is held through the insertion: a clear can't come between the look and the insertion) + let current = self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner); + if current.is_none() { + return; + } + let c = cost(&img); + self.mem.lock().unwrap_or_else(|e| e.into_inner()).insert(key, img, c); + drop(current); + } + + /// [`Self::put_memory`] for a job that captured `generation`: nothing is kept once the cache + /// was cleared (or retired) after that, so a job started before Discard Preview Cache can't + /// put its picture back. + pub fn put_memory_at(&self, generation: u64, key: Hash128, img: Arc) { + // (the guard is held through the insertion: a clear can't come between the look and the insertion) let current = self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner); if *current != Some(generation) { return; } - if let Some(d) = &self.disk { - d.put(key, &img); - } let c = cost(&img); self.mem.lock().unwrap_or_else(|e| e.into_inner()).insert(key, img, c); + drop(current); + } + + pub fn put(&self, key: Hash128, img: Arc) { + let _ = self.put_at(self.generation(), key, img); + } + + /// [`Self::put`] for a job of `generation`. Returns whether the image is kept where it lasts: `false` when + /// the cache was cleared or retired since the job was made (nothing is kept; see [`Self::generation`] to + /// tell), or when the disk cache could not write the file (the image is kept in memory all the same). + pub fn put_at(&self, generation: u64, key: Hash128, img: Arc) -> bool { + let current = self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner); + if *current != Some(generation) { + return false; + } + let written = self.disk.as_ref().is_none_or(|d| d.put(key, &img)); + let c = cost(&img); + self.mem.lock().unwrap_or_else(|e| e.into_inner()).insert(key, img, c); + written } /// Like [`Self::put`], but the disk write (a JPEG encode) happens on a background thread, so diff --git a/crates/preview/src/tests.rs b/crates/preview/src/tests.rs index 2f07e927fb..975c2ddf79 100644 --- a/crates/preview/src/tests.rs +++ b/crates/preview/src/tests.rs @@ -792,3 +792,63 @@ fn deferred_writes_are_bounded_and_drain_to_disk() { assert!(keys.iter().all(|k| cache.get(*k).is_some())); let _ = std::fs::remove_dir_all(&dir); } + +/// `put_at` says whether the image is kept where it lasts: not for a job made before the cache was cleared or +/// retired, nor when the disk cache can't write it (CodeRabbit on #3077). +#[test] +fn put_at_says_whether_the_image_was_kept() { + let dir = temp_dir("put-at-kept"); + let cache = PreviewCache::with_disk(1 << 20, &dir, 1 << 20); + let (key, img) = (hash_bytes(b"kept"), Arc::new(gradient(8, 8, 3))); + let old = cache.generation(); + assert!(cache.put_at(old, key, img.clone()), "kept"); + cache.clear(); + assert!(!cache.put_at(old, key, img.clone()), "a job from before the clear keeps nothing"); + assert!(cache.put_at(cache.generation(), key, img.clone())); + let generation = cache.generation(); + cache.retire(); + assert!(!cache.put_at(generation, key, img.clone()), "nor one for a retired cache"); + // a file where the cache folder goes: the write fails + let blocked = temp_dir("put-at-blocked"); + std::fs::write(&blocked, b"not a folder").unwrap(); + let cache = PreviewCache::with_disk(1 << 20, &blocked, 1 << 20); + assert!(!cache.put_at(cache.generation(), key, img.clone()), "not written"); + let memory = PreviewCache::memory(1 << 20); + assert!(memory.put_at(memory.generation(), key, img), "a memory-only cache keeps it"); + let _ = std::fs::remove_file(&blocked); + let _ = std::fs::remove_dir_all(&dir); +} + +/// `dims` reads a cached file's first few KiB, and further when its size marker comes later (CodeRabbit on #3080). +#[test] +fn dims_finds_a_size_marker_past_the_first_few_kib() { + let dir = temp_dir("dims-far"); + let d = DiskCache::new(&dir, 1 << 20); + let key = hash_bytes(b"far"); + assert!(d.put(key, &gradient(40, 30, 5))); + assert_eq!(d.dims(key), Some((40, 30))); + // the same picture with a 10 KiB application segment before its frame header + let file = files_under(&dir).into_iter().find(|f| f.ends_with(disk::EXT)).expect("the cached file"); + let path = dir.join(file); + let jpeg = std::fs::read(&path).unwrap(); + let mut padded = jpeg[..2].to_vec(); + let pad = 10 << 10; + padded.extend_from_slice(&[0xFF, 0xEF, ((pad + 2) >> 8) as u8, ((pad + 2) & 0xFF) as u8]); + padded.extend(std::iter::repeat_n(0u8, pad)); + padded.extend_from_slice(&jpeg[2..]); + std::fs::write(&path, padded).unwrap(); + assert_eq!(d.dims(key), Some((40, 30)), "found past the first read"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A picture bigger than the room pruning leaves is removed by the pruning its own write starts: `put` says it +/// was not kept (CodeRabbit on #3077). +#[test] +fn a_write_the_pruning_removes_is_not_reported_as_kept() { + let dir = temp_dir("pruned-away"); + let d = DiskCache::new(&dir, 64); + assert!(!d.put(hash_bytes(b"too big"), &gradient(64, 64, 9)), "pruned away at once"); + let roomy = DiskCache::new(&dir, 1 << 20); + assert!(roomy.put(hash_bytes(b"fits"), &gradient(64, 64, 9))); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rs index 2b16c441ad..d661439780 100644 --- a/crates/raw/src/preview.rs +++ b/crates/raw/src/preview.rs @@ -138,12 +138,68 @@ fn is_jxl(b: &[u8]) -> bool { b.starts_with(&[0xff, 0x0a]) || b.starts_with(&[0, 0, 0, 0x0c, b'J', b'X', b'L', b' ', 0x0d, 0x0a, 0x87, 0x0a]) } -fn candidates<'a>(data: &'a [u8], ifd: &Ifd, base: u64, out: &mut Vec<&'a [u8]>) { +/// The bytes a file's own (offset, length) pair names, cut at the file's end; `None` when the offset +/// lies past it. Both numbers come from the file: never cast them (a `u64` offset past 4 GiB would +/// wrap to a small, wrong one on a 32-bit build) nor add them unchecked. A span the file's end cuts +/// short is kept only when it is a JPEG whose own end marker is inside it, after its scan (an +/// overstated length with the whole JPEG inside), cut at that marker: a truncated JPEG passes the +/// frame-header check, would win as the largest preview and then fail to decode (CodeRabbit on +/// #3077). An `FF D9` inside an APP payload doesn't count, bytes that don't start a JPEG are refused +/// without a scan, and the walks share `budget` (bytes, as [`scan_with_budget`]'s do), so a file of +/// many such pointers stays linear. +fn file_span<'a>(data: &'a [u8], offset: u64, len: u64, budget: &mut usize) -> Option<&'a [u8]> { + let start = usize::try_from(offset).ok()?; + let wanted = usize::try_from(offset.saturating_add(len)).unwrap_or(usize::MAX); + let span = data.get(start..wanted.min(data.len()))?; + if wanted > data.len() { + return span.get(..jpeg_end(span, budget)?); + } + Some(span) +} + +/// Where the JPEG at the start of `s` ends (just past its end marker), walking its marker segments: +/// a segment's payload is skipped by its stated length (so an `FF D9` inside APP data isn't taken +/// for the end), entropy-coded bytes one at a time (stuffed `FF 00` and restart markers included). +/// `None` when `s` isn't a JPEG, ends first, reaches its end marker before a start of scan (no image +/// data), or the walk spends `budget` (one per step, shared by a file's walks). Each step moves +/// forward, so it ends within `s`. +fn jpeg_end(s: &[u8], budget: &mut usize) -> Option { + if !s.starts_with(&[0xff, 0xd8]) { + return None; + } + let (mut i, mut scanned) = (2usize, false); + loop { + *budget = budget.checked_sub(1)?; + match (s.get(i), s.get(i.checked_add(1)?)) { + (None, _) | (Some(&0xff), None) => return None, + (Some(&0xff), Some(&m)) => match m { + 0xd9 => return if scanned { i.checked_add(2) } else { None }, + // fill byte + 0xff => i += 1, + // stuffed zero, restart marker, TEM: no length follows + 0x00 | 0x01 | 0xd0..=0xd7 => i = i.checked_add(2)?, + _ => { + let (&hi, &lo) = (s.get(i.checked_add(2)?)?, s.get(i.checked_add(3)?)?); + let len = usize::from(u16::from_be_bytes([hi, lo])); + if len < 2 { + return None; + } + scanned |= m == 0xda; + i = i.checked_add(2)?.checked_add(len)?; + } + }, + // entropy-coded data + (Some(_), _) => i += 1, + } + } +} + +fn candidates<'a>(data: &'a [u8], ifd: &Ifd, base: u64, out: &mut Vec<&'a [u8]>, budget: &mut usize) { // whole JPEG files stored as an undefined-type tag value (e.g. Panasonic `JpgFromRaw` 0x002e) for e in &ifd.entries { if matches!(e.value, lightcraft_tiff::Value::Undefined(_)) && e.count() > 1024 - && let Some(s) = data.get(e.offset as usize..(e.offset.saturating_add(e.count() as u64) as usize).min(data.len())) + && let Some(s) = file_span(data, e.offset, e.count() as u64, budget) && s.starts_with(&[0xff, 0xd8]) { out.push(s); @@ -151,7 +207,7 @@ fn candidates<'a>(data: &'a [u8], ifd: &Ifd, base: u64, out: &mut Vec<&'a [u8]>) } if let (Some(off), Some(len)) = (ifd.u64(t::JPEG_INTERCHANGE_FORMAT), ifd.u64(t::JPEG_INTERCHANGE_FORMAT_LENGTH)) { let off = off.saturating_add(base); - if let Some(s) = data.get(off as usize..(off.saturating_add(len) as usize).min(data.len())) { + if let Some(s) = file_span(data, off, len, budget) { out.push(s); } } @@ -196,8 +252,12 @@ fn smallest_covering<'a>(found: &[&'a [u8]], largest: &[u8], min_edge: u32) -> O let (a, b) = (u64::from(w) * u64::from(bh), u64::from(h) * u64::from(bw)); w > 0 && h > 0 && c == bc && a.abs_diff(b) * 100 <= a }; + // (one cut short before its end marker would fail to decode, and nothing would try another: CodeRabbit + // on #3583) + let whole = |s: &[u8]| trim_eoi(s).ends_with(&[0xff, 0xd9]); found .iter() + .filter(|s| whole(s)) .filter_map(|&s| jpeg_frame(s).filter(|&f| like(f) && f.0.max(f.1) >= min_edge).map(|(w, h, _)| (s, w.max(h)))) .min_by_key(|&(_, long)| long) .map(|(s, _)| s) @@ -210,6 +270,20 @@ fn preview_covering(bytes: &[u8], min_edge: Option) -> Option> { } let format = crate::probe(bytes); if format == Some(crate::RawFormat::Cr3) { + // a Canon CR3 keeps its full-size JPEG beside a 1620 px `PRVW` (and a 160 px `THMB`): a + // thumbnail decodes the small copy, not 45 MP of JPEG (about 150 ms a photo, the grid's + // "popcorn" on a folder of R5 / R5 C raws) + // (without a JPEG track, the largest box is the picture's shape: the boxes alone may hold several) + if let Some(min) = min_edge { + let mut found = cr3_preview_box_list(bytes); + let full = cr3_full_jpeg(bytes); + found.extend(full); + if let Some(largest) = full.or_else(|| largest_by_pixels(&found)) + && let Some(j) = smallest_covering(&found, largest, min) + { + return Some(trim_eoi(j).to_vec()); + } + } return cr3_preview(bytes).map(|j| trim_eoi(j).to_vec()); } if matches!(format, Some(crate::RawFormat::Crw | crate::RawFormat::Mrw | crate::RawFormat::X3f)) { @@ -217,8 +291,10 @@ fn preview_covering(bytes: &[u8], min_edge: Option) -> Option> { } let tiff = Tiff::parse(bytes).ok()?; let mut found: Vec<&[u8]> = Vec::new(); + // the walks of pointers past the file's end share one budget (see file_span) + let mut budget = scan_budget(bytes.len()); for ifd in tiff.all_ifds() { - candidates(bytes, ifd, 0, &mut found); + candidates(bytes, ifd, 0, &mut found, &mut budget); } // maker-note preview IFDs (e.g. Nikon PreviewIFD 0x0011 holds JPEGInterchangeFormat relative to the note base) if let Some(exif) = tiff.exif() @@ -226,11 +302,11 @@ fn preview_covering(bytes: &[u8], min_edge: Option) -> Option> { { let make = tiff.find(t::MAKE).and_then(|e| e.value.as_str()).unwrap_or_default(); if let Some(mn) = makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make) { - candidates(bytes, &mn.ifd, mn.base, &mut found); + candidates(bytes, &mn.ifd, mn.base, &mut found, &mut budget); if let Some(off) = mn.ifd.u64(0x0011) && let Ok((pifd, _)) = lightcraft_tiff::parse_ifd_at(bytes, mn.base + off, mn.order, mn.base, false, &Default::default()) { - candidates(bytes, &pifd, mn.base, &mut found); + candidates(bytes, &pifd, mn.base, &mut found, &mut budget); } } } @@ -442,53 +518,123 @@ fn scan_with_budget(data: &[u8], budget: usize) -> (Option>, u64) { /// Canon CR3: the full-size JPEG track (see [`lightcraft_meta::cr3`]), else the `PRVW` / `THMB` boxes. fn cr3_preview(bytes: &[u8]) -> Option<&[u8]> { + cr3_full_jpeg(bytes).or_else(|| cr3_preview_boxes(bytes)) +} + +/// A CR3's full-size JPEG track, when it holds a DCT JPEG. +fn cr3_full_jpeg(bytes: &[u8]) -> Option<&[u8]> { let full = lightcraft_meta::cr3::parse_cr3(bytes) .and_then(|c| c.tracks.iter().find(|t| t.kind == lightcraft_meta::cr3::Cr3TrackKind::Jpeg).and_then(|t| t.data)); - if let Some(j) = full.and_then(|(at, len)| bytes.get(at..at.checked_add(len)?)).filter(|j| is_dct_jpeg(j)) { - return Some(j); - } - cr3_preview_boxes(bytes) + full.and_then(|(at, len)| bytes.get(at..at.checked_add(len)?)).filter(|j| is_dct_jpeg(j)) } -/// Canon CR3 (ISO base media file): the `PRVW` box (Laurent Clévy's CR3 notes; layout confirmed on a CC0 -/// sample) is `u32 size, "PRVW", u32 0, u16 ?, u16 width, u16 height, u16 ?, u32 jpeg length, JPEG`; the smaller -/// `THMB` box has the same shape. Returns the larger valid one. /// Marker-walk budget of the CR3 fallback: candidates can overlap (each claiming the rest of the file) and /// [`is_dct_jpeg`] walks each marker by marker, so walking every candidate would be quadratic in file size. /// The `THMB`/`PRVW` previews this finds are far below the cap together; once it is spent the scan stops. const CR3_MAX_WALK: usize = 8 << 20; +/// Canon CR3 (ISO base media file): the `PRVW` box (Laurent Clévy's CR3 notes; layout confirmed on a CC0 +/// sample) is `u32 size, "PRVW", u32 0, u16 ?, u16 width, u16 height, u16 ?, u32 jpeg length, JPEG`; the smaller +/// `THMB` box has the same shape. Returns the larger valid one. fn cr3_preview_boxes(bytes: &[u8]) -> Option<&[u8]> { - let mut best: Option<&[u8]> = None; + largest_by_pixels(&cr3_preview_box_list(bytes)) +} + +/// Of `found`, the JPEG with the longest edge in pixels (a smaller picture can take more bytes); the +/// first of equals. CodeRabbit on #3077. +fn largest_by_pixels<'a>(found: &[&'a [u8]]) -> Option<&'a [u8]> { + let long = |j: &[u8]| jpeg_frame(j).map_or(0, |(w, h, _)| w.max(h)); + found.iter().copied().rev().max_by_key(|j| long(j)) +} + +/// The valid JPEGs of a CR3's `PRVW` and `THMB` boxes, every one: a file may carry more than one +/// `PRVW`, and the smallest that covers a size is picked from them all. +fn cr3_preview_box_list(bytes: &[u8]) -> Vec<&[u8]> { + let mut out: Vec<&[u8]> = Vec::new(); let mut walked = 0usize; + // the boxes sit outside the media data: only the rest of the file is searched (the media data + // is most of the file, and a thumbnail is asked for every photo in view) + let file = bytes; + // (every top-level `mdat` is left out, not only the first: a PRVW-shaped JPEG in media data is not a + // preview; CodeRabbit on #3583) + let media = cr3_media_data(file); + let whole_file = media.is_empty(); + let mut regions: Vec<&[u8]> = Vec::new(); + let mut from = 0usize; + for (start, end) in media { + if start >= from { + regions.extend(file.get(from..start)); + } + from = from.max(end); + } + regions.extend(file.get(from..)); for tag in [b"PRVW", b"THMB"] { - let mut from = 0; - while let Some(i) = bytes.get(from..).and_then(|s| s.windows(4).position(|w| w == tag)).map(|p| p + from) { - from = i + 4; - let Some(start) = i.checked_sub(4) else { continue }; - let be32 = |at: usize| bytes.get(at..at + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize); - let (Some(size), Some(len)) = (be32(start), be32(start + 20)) else { continue }; - let j = start + 24; - // 32-bit box lengths can wrap `usize` on wasm32: check the sums, then slice with `get` - let (Some(end), Some(lim)) = (j.checked_add(len), start.checked_add(size.max(24))) else { continue }; - if len < 4 || end > lim { - continue; - } - let Some(jpeg) = bytes.get(j..end) else { continue }; - // One that doesn't fit the budget left is skipped; a smaller one later may still fit. - if walked + jpeg.len() > CR3_MAX_WALK { - continue; - } - walked += jpeg.len(); - if is_dct_jpeg(jpeg) { - if best.is_none_or(|b| b.len() < jpeg.len()) { - best = Some(jpeg); - } + // the whole file searched (its media data not found): the first valid box of a kind only, as + // the declared one comes before the media data and a later look-alike must not win + let mut taken = false; + for &bytes in ®ions { + if whole_file && taken { break; } + let mut from = 0; + while let Some(i) = bytes.get(from..).and_then(|s| s.windows(4).position(|w| w == tag)).map(|p| p + from) { + from = i + 4; + let Some(start) = i.checked_sub(4) else { continue }; + // (the sizes are the file's: checked, a 32-bit build must not wrap them) + let be32 = |at: usize| bytes.get(at..at.checked_add(4)?).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize); + let (Some(size), Some(len)) = (be32(start), start.checked_add(20).and_then(be32)) else { continue }; + let (Some(j), Some(box_end)) = (start.checked_add(24), start.checked_add(size.max(24))) else { continue }; + let Some(end) = j.checked_add(len).filter(|e| len >= 4 && *e <= box_end && *e <= bytes.len()) else { continue }; + let Some(jpeg) = bytes.get(j..end) else { continue }; + // One that doesn't fit the budget left is skipped; a smaller one later may still fit. + if walked.saturating_add(jpeg.len()) > CR3_MAX_WALK { + continue; + } + walked = walked.saturating_add(jpeg.len()); + if is_dct_jpeg(jpeg) { + out.push(jpeg); + taken = true; + if whole_file { + break; + } + // (past it: a tag inside its JPEG is not another box) + from = end; + } + } } } - best + out +} + +/// Where a CR3's top-level `mdat` boxes lie (`start..end` each, `end` clamped to the file, in file +/// order): the media data, most of the file. Empty when there is none, or the boxes stop making sense +/// before the first. The metadata and the small previews are in the other top-level boxes. +fn cr3_media_data(bytes: &[u8]) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + let _ = cr3_media_walk(bytes, &mut out); + out +} + +/// [`cr3_media_data`]'s walk of the top-level boxes; `None` where they stop making sense. +fn cr3_media_walk(bytes: &[u8], out: &mut Vec<(usize, usize)>) -> Option<()> { + let be32 = |at: usize| bytes.get(at..at.checked_add(4)?).map(|s| u64::from(u32::from_be_bytes([s[0], s[1], s[2], s[3]]))); + let be64 = |at: usize| bytes.get(at..at.checked_add(8)?).map(|s| u64::from_be_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]])); + let mut at = 0usize; + for _ in 0..64 { + let size = be32(at)?; + let len = match size { + // (a box running to the end of the file) + 0 => u64::try_from(bytes.len().saturating_sub(at)).unwrap_or(u64::MAX), + 1 => be64(at.checked_add(8)?)?, + n => n, + }; + let next = usize::try_from(len).ok().filter(|l| *l >= 8).and_then(|l| at.checked_add(l)); + if bytes.get(at.checked_add(4)?..at.checked_add(8)?) == Some(b"mdat".as_slice()) { + out.push((at, next.unwrap_or(bytes.len()).min(bytes.len()))); + } + at = next.filter(|n| *n < bytes.len())?; + } + None } /// Trim trailing garbage after the last EOI when a stored length over-reports. diff --git a/crates/raw/src/preview/tests.rs b/crates/raw/src/preview/tests.rs index aa2dc0da74..561d39645d 100644 --- a/crates/raw/src/preview/tests.rs +++ b/crates/raw/src/preview/tests.rs @@ -296,6 +296,98 @@ fn cr3_prefers_the_full_size_jpeg_track() { assert_eq!(embedded_preview(&file).unwrap(), small); } +/// A CR3 whose `PRVW` box holds `prvw` and whose JPEG track holds `big`. +fn cr3_with(prvw_jpeg: &[u8], big: &[u8]) -> Vec { + let bx = |kind: &[u8; 4], body: &[u8]| -> Vec { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; + let full = |kind: &[u8; 4], body: &[u8]| bx(kind, &[&[0u8; 4][..], body].concat()); + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + let mut prvw = b"\0\0\0\0\0\x01\x06T\x048\0\x01".to_vec(); + prvw.extend_from_slice(&(prvw_jpeg.len() as u32).to_be_bytes()); + prvw.extend_from_slice(prvw_jpeg); + file.extend(bx(b"PRVW", &prvw)); + let mut craw = vec![0u8; 82]; + craw.extend(bx(b"JPEG", &[0; 4])); + let at = 4096u64; + let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat()); + let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat()); + let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat()); + let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat())))); + file.extend(bx(b"moov", &trak)); + file.resize(at as usize, 0); + file.extend_from_slice(big); + file +} + +/// A CR3 thumbnail decodes the 1620 px `PRVW` copy, not the full-size JPEG (PERF-THUMB-FIRST: +/// 150 ms a photo for the full one); a size the copy can't cover, and the largest preview, are +/// still the full JPEG; a `PRVW` of another shape is never taken for the picture. +#[test] +fn cr3_thumbnails_take_the_smallest_copy_that_covers_them() { + let (prvw, big) = (sized_jpeg(1620, 1080, 3, 300), sized_jpeg(6000, 4000, 3, 3000)); + let file = cr3_with(&prvw, &big); + assert_eq!(embedded_preview_covering(&file, 512).unwrap(), prvw); + assert_eq!(embedded_preview_covering(&file, 1620).unwrap(), prvw); + assert_eq!(embedded_preview_covering(&file, 2000).unwrap(), big); + assert_eq!(embedded_preview(&file).unwrap(), big); + let letterboxed = cr3_with(&sized_jpeg(1620, 1215, 3, 300), &big); + assert_eq!(embedded_preview_covering(&letterboxed, 512).unwrap(), big, "another shape is not a copy"); + for n in (0..file.len()).step_by(13) { + let _ = embedded_preview_covering(&file[..n], 512); + } +} + +/// PERF-CULL-4: the smallest preview that covers the size asked for, of the largest one's shape; +/// the largest when none covers it. A CR3's 8192 px track, 1620 px `PRVW` and 160 px `THMB`. +#[test] +fn the_smallest_preview_covering_the_size_is_chosen() { + let bx = |kind: &[u8; 4], body: &[u8]| -> Vec { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; + let full = |kind: &[u8; 4], body: &[u8]| bx(kind, &[&[0u8; 4][..], body].concat()); + let boxed = |j: &[u8]| { + let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec(); + b.extend_from_slice(&(j.len() as u32).to_be_bytes()); + b.extend_from_slice(j); + b + }; + let (thmb, prvw, big) = (sized_jpeg(160, 107, 1, 50), sized_jpeg(1620, 1080, 1, 300), sized_jpeg(8192, 5464, 1, 3000)); + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"THMB", &boxed(&thmb))); + file.extend(bx(b"PRVW", &boxed(&prvw))); + let mut craw = vec![0u8; 82]; + craw.extend(bx(b"JPEG", &[0; 4])); + let at = 4096u64; + let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat()); + let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat()); + let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat()); + let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat())))); + file.extend(bx(b"moov", &trak)); + file.resize(at as usize, 0); + file.extend_from_slice(&big); + assert_eq!(embedded_preview(&file).unwrap(), big); + assert_eq!(embedded_preview_covering(&file, 512).unwrap(), prvw, "a grid thumbnail"); + assert_eq!(embedded_preview_covering(&file, 1620).unwrap(), prvw); + assert_eq!(embedded_preview_covering(&file, 100).unwrap(), thmb); + assert_eq!(embedded_preview_covering(&file, 2560).unwrap(), big, "a large loupe"); + assert_eq!(embedded_preview_covering(&file, u32::MAX).unwrap(), big); + // a smaller preview of another shape (letterboxed 16:9) is never a stand-in for the 3:2 one + let mut wide = file.clone(); + let p = wide.windows(4).position(|w| w == b"PRVW").unwrap(); + // the JPEG starts 20 bytes after the tag; its frame height 7 bytes into it + let height = p + 20 + 7; + wide[height..height + 2].copy_from_slice(&911u16.to_be_bytes()); + assert_eq!(embedded_preview_covering(&wide, 512).unwrap(), big); + // without the JPEG track the boxes are chosen from too: the smallest that covers, else the largest + // (CodeRabbit on #3577: a box-only CR3 always gave its largest box) + let boxes_only = &file[..file.windows(4).position(|w| w == b"moov").unwrap() - 4]; + assert_eq!(embedded_preview_covering(boxes_only, 100).unwrap(), thmb); + assert_eq!(embedded_preview_covering(boxes_only, 512).unwrap(), prvw); + assert_eq!(embedded_preview_covering(boxes_only, 2560).unwrap(), prvw, "none covers: the largest"); + assert_eq!(embedded_preview(boxes_only).unwrap(), prvw); + // damaged files never panic + for n in (0..file.len()).step_by(7) { + let _ = embedded_preview_covering(&file[..n], 512); + } +} + /// A minimal CR3 whose Canon box holds `CMT2` (EXIF ColorSpace `exif`) and `CMT3` (maker-note ColorSpace `note`). fn cr3_with_color_space(exif: Option, note: Option) -> Vec { let bx = |kind: &[u8; 4], body: &[u8]| -> Vec { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; @@ -502,3 +594,261 @@ fn scanned_containers_give_the_largest_colour_jpeg() { f.extend_from_slice(&mosaic); assert_eq!(embedded_preview(&f), None); } + +/// A CR3's `PRVW` / `THMB` boxes are searched outside the media data only, but before and after +/// it: a `moov` after the `mdat` (its Canon `uuid` holding the `THMB`) still gives its preview, and +/// bytes inside the media data that look like a preview box are never taken for one. +#[test] +fn cr3_preview_boxes_after_the_media_data_are_found() { + let bx = |kind: &[u8; 4], body: &[u8]| -> Vec { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; + let boxed = |j: &[u8]| { + let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec(); + b.extend_from_slice(&(j.len() as u32).to_be_bytes()); + b.extend_from_slice(j); + b + }; + let (thmb, in_media) = (sized_jpeg(160, 107, 1, 50), sized_jpeg(1620, 1080, 1, 300)); + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"mdat", &bx(b"PRVW", &boxed(&in_media)))); + file.extend(bx(b"moov", &bx(b"uuid", &[&[0x85u8; 16][..], &bx(b"THMB", &boxed(&thmb))].concat()))); + assert_eq!(embedded_preview(&file).unwrap(), thmb); + for n in (0..file.len()).step_by(5) { + let _ = embedded_preview(&file[..n]); + } +} + +/// Every valid `PRVW` of a CR3 is a candidate (CodeRabbit on #3055): with a small one first and +/// one that covers the size after it, a thumbnail takes the second, not the full-size track. +#[test] +fn a_cr3_with_two_prvw_boxes_offers_both() { + let bx = |kind: &[u8; 4], body: &[u8]| -> Vec { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; + let full = |kind: &[u8; 4], body: &[u8]| bx(kind, &[&[0u8; 4][..], body].concat()); + let boxed = |j: &[u8]| { + let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec(); + b.extend_from_slice(&(j.len() as u32).to_be_bytes()); + b.extend_from_slice(j); + b + }; + let (small, covering, big) = (sized_jpeg(300, 200, 1, 50), sized_jpeg(1620, 1080, 1, 300), sized_jpeg(8192, 5464, 1, 3000)); + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"PRVW", &boxed(&small))); + file.extend(bx(b"PRVW", &boxed(&covering))); + let mut craw = vec![0u8; 82]; + craw.extend(bx(b"JPEG", &[0; 4])); + let at = 4096u64; + let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat()); + let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat()); + let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat()); + let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat())))); + file.extend(bx(b"moov", &trak)); + // (the track in the media data, as a camera writes it, after a `free` box up to it) + let pad = at as usize - 16 - file.len(); + file.extend(bx(b"free", &vec![0u8; pad])); + file.extend(bx(b"mdat", &big)); + assert_eq!(embedded_preview_covering(&file, 1024).unwrap(), covering); + assert_eq!(embedded_preview_covering(&file, 200).unwrap(), small); +} + +/// A CR3 preview box claiming the largest sizes a file can give is skipped, never wrapped or +/// panicked on (CodeRabbit on #3080: on a 32-bit build the plain sums could overflow). +#[test] +fn a_cr3_preview_box_with_hostile_sizes_is_skipped() { + let mut file = b"\0\0\0\x18ftypcrx \0\0\0\x01crx isom".to_vec(); + file.extend_from_slice(&u32::MAX.to_be_bytes()); + file.extend_from_slice(b"PRVW\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01"); + file.extend_from_slice(&u32::MAX.to_be_bytes()); + file.extend_from_slice(&fake_jpeg(64)); + assert!(embedded_preview(&file).is_none()); + assert!(embedded_preview_covering(&file, 64).is_none()); +} + +/// A corrupt raw whose preview pointer (JPEGInterchangeFormat and its length) lies past the end +/// of the file, or whose length runs past it, finds no preview and never panics; a real preview +/// beside the lying pointer is still found (FredApps on #3080: the preview must be read with +/// bounds on its offset and size). +#[test] +fn a_preview_pointer_past_the_end_of_the_file_finds_no_preview() { + let real = sized_jpeg(640, 480, 3, 200); + let lying = |off: u32, len: u32, with_real: bool| { + let mut ifd = IfdBuilder::new(); + ifd.set(t::JPEG_INTERCHANGE_FORMAT, Value::Long(vec![off])); + ifd.set(t::JPEG_INTERCHANGE_FORMAT_LENGTH, Value::Long(vec![len])); + if with_real { + ifd.set(t::COMPRESSION, Value::Short(vec![6])); + ifd.set(t::IMAGE_WIDTH, Value::Long(vec![1])); + ifd.set(t::IMAGE_LENGTH, Value::Long(vec![1])); + ifd.set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![real.clone()] }); + } + TiffWriter::default().write(&[ifd]).unwrap() + }; + let short = lying(0, 0, false).len() as u32; + for (off, len) in [(u32::MAX, u32::MAX), (u32::MAX, 16), (short + 10, 4096), (8, u32::MAX), (short - 2, u32::MAX - 1)] { + let file = lying(off, len, false); + assert_eq!(embedded_preview(&file), None, "pointer {off:#x}+{len:#x} in a {} byte file", file.len()); + assert_eq!(embedded_preview_covering(&file, 64), None); + assert_eq!(embedded_preview_color_space(&file), None); + let with_real = lying(off, len, true); + assert_eq!(embedded_preview(&with_real).as_deref(), Some(&real[..]), "the strip preview beside pointer {off:#x}+{len:#x}"); + // and every truncation of the file (a raw cut short by a failed copy) is safe too + for n in 0..with_real.len() { + let _ = embedded_preview_covering(&with_real[..n], 64); + } + } +} + +/// A preview pointer whose length runs past the end of a file that cuts its JPEG short (no end +/// marker) finds no preview, so a smaller whole one wins; an overstated length whose JPEG is whole +/// inside the file still finds it (CodeRabbit on #3077). +#[test] +fn a_preview_cut_short_by_the_end_of_the_file_is_not_taken() { + let big = sized_jpeg(1600, 1200, 3, 4000); + let small = sized_jpeg(160, 120, 3, 100); + // the small JPEG as a strip, the big one pointed to at the end of the file + let with_tail = |tail: &[u8], declared: u32| { + let probe = { + let mut ifd = IfdBuilder::new(); + ifd.set(t::JPEG_INTERCHANGE_FORMAT, Value::Long(vec![0])); + ifd.set(t::JPEG_INTERCHANGE_FORMAT_LENGTH, Value::Long(vec![0])); + ifd.set(t::COMPRESSION, Value::Short(vec![6])); + ifd.set(t::IMAGE_WIDTH, Value::Long(vec![1])); + ifd.set(t::IMAGE_LENGTH, Value::Long(vec![1])); + ifd.set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![small.clone()] }); + ifd + }; + let at = TiffWriter::default().write(&[probe]).unwrap().len() as u32; + let mut ifd = IfdBuilder::new(); + ifd.set(t::JPEG_INTERCHANGE_FORMAT, Value::Long(vec![at])); + ifd.set(t::JPEG_INTERCHANGE_FORMAT_LENGTH, Value::Long(vec![declared])); + ifd.set(t::COMPRESSION, Value::Short(vec![6])); + ifd.set(t::IMAGE_WIDTH, Value::Long(vec![1])); + ifd.set(t::IMAGE_LENGTH, Value::Long(vec![1])); + ifd.set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![small.clone()] }); + let mut file = TiffWriter::default().write(&[ifd]).unwrap(); + assert_eq!(file.len() as u32, at, "the pointer lands right after the TIFF"); + file.extend_from_slice(tail); + file + }; + // the big one with a start of scan after its frame header (sized_jpeg has none), as a real JPEG + let mut big = big; + big.splice(21..21, [0xff, 0xda, 0x00, 0x02]); + let declared = big.len() as u32 + 64; + // cut short: half of the big JPEG, no end marker + let cut = with_tail(&big[..big.len() / 2], declared); + assert_eq!(embedded_preview(&cut).as_deref(), Some(&small[..]), "the truncated JPEG is not taken"); + // whole, its length overstated past the file's end: still the largest + let whole = with_tail(&big, declared); + assert_eq!(embedded_preview(&whole).as_deref(), Some(&big[..]), "a whole JPEG with an overstated length is kept"); + // an end marker inside an APP1 payload is not the JPEG's end: cut short, still not taken + let mut with_app = vec![0xff, 0xd8, 0xff, 0xe1, 0x00, 0x08, 0x12, 0xff, 0xd9, 0x34, 0x56, 0x78]; + with_app.extend_from_slice(&big[2..]); + let declared = with_app.len() as u32 + 64; + let cut = with_tail(&with_app[..with_app.len() / 2], declared); + assert_eq!(embedded_preview(&cut).as_deref(), Some(&small[..]), "an FF D9 in APP1 doesn't make a cut JPEG whole"); + // whole, with other bytes after it up to the file's end: kept, cut at its own end marker + let mut tail = with_app.clone(); + tail.extend_from_slice(&[0x11, 0xff, 0xd9, 0x22]); + let whole = with_tail(&tail, declared); + assert_eq!(embedded_preview(&whole).as_deref(), Some(&with_app[..]), "a whole JPEG is cut at its own end"); + // an end marker before any start of scan: no image data, not taken (CodeRabbit on #3080) + let unscanned = sized_jpeg(1600, 1200, 3, 4000); + let whole = with_tail(&unscanned, unscanned.len() as u32 + 64); + assert_eq!(embedded_preview(&whole).as_deref(), Some(&small[..]), "a JPEG without a scan is not taken"); +} + +/// The walk to a JPEG's end refuses what isn't one and never runs past the bytes it has. +#[test] +fn the_end_of_a_jpeg_is_its_own_end_marker() { + let jpeg_end = |s: &[u8]| super::jpeg_end(s, &mut (1usize << 20)); + assert_eq!(jpeg_end(&[0x12, 0x34, 0xff, 0xd9]), None, "not a JPEG"); + assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xd9]), None, "an end before any scan: no image data"); + // a stuffed zero and a restart marker in the scan data, then the end + assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xda, 0x00, 0x02, 0x55, 0xff, 0x00, 0xff, 0xd3, 0x66, 0xff, 0xd9]), Some(14)); + // a segment length of 0 or 1, or one running past the end + assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xe1, 0x00, 0x01, 0xff, 0xd9]), None); + assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xe1, 0xff, 0xff, 0xff, 0xd9]), None); + for n in 0..12 { + assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xe1, 0x00, 0x04, 0xff, 0xd9, 0x55, 0xff, 0xff, 0xff][..n]), None, "{n} bytes"); + } +} + +/// CodeRabbit on #3080: the walks to a JPEG's end share one budget, so a file of many pointers past +/// its end can't make each walk run the whole file: a walk that would overspend it gives up. +#[test] +fn the_walks_to_a_jpegs_end_share_a_budget() { + use super::jpeg_end; + let mut j = vec![0xff, 0xd8, 0xff, 0xda, 0x00, 0x02]; + j.extend(std::iter::repeat_n(0x55u8, 1000)); + j.extend_from_slice(&[0xff, 0xd9]); + let mut budget = 1500; + assert_eq!(jpeg_end(&j, &mut budget), Some(j.len()), "the first walk fits"); + assert!(budget < 1500 - 1000, "and is charged for its steps: {budget} left"); + assert_eq!(jpeg_end(&j, &mut budget), None, "the second would overspend what is left"); + assert_eq!(budget, 0); +} + +/// A CR3 without a JPEG track whose smaller `PRVW` (another shape) takes more bytes: the picture is +/// the box with the most pixels, not the most bytes (CodeRabbit on #3077). +#[test] +fn a_box_only_cr3_is_judged_by_pixels_not_bytes() { + let bx = |kind: &[u8; 4], body: &[u8]| -> Vec { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; + let boxed = |j: &[u8]| { + let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec(); + b.extend_from_slice(&(j.len() as u32).to_be_bytes()); + b.extend_from_slice(j); + b + }; + let (big, square) = (sized_jpeg(1620, 1080, 3, 300), sized_jpeg(800, 800, 3, 5000)); + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"PRVW", &boxed(&square))); + file.extend(bx(b"PRVW", &boxed(&big))); + // no media data found: the whole file is searched, and only its first box counts (a later look-alike could be + // in media data; CodeRabbit on #3583) + assert_eq!(embedded_preview(&file).unwrap(), square); + file.extend(bx(b"mdat", &[0u8; 16])); + assert_eq!(embedded_preview(&file).unwrap(), big); + assert_eq!(embedded_preview_covering(&file, 100).unwrap(), big, "the square is another picture's shape"); +} + +/// Every top-level `mdat` is media data, not only the first: a PRVW-shaped JPEG in a second one is +/// never the preview; and a `PRVW` cut short before its end marker isn't chosen to cover a size +/// (CodeRabbit on #3583). +#[test] +fn cr3_boxes_in_any_media_data_or_cut_short_are_not_previews() { + let bx = |kind: &[u8; 4], body: &[u8]| -> Vec { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; + let boxed = |j: &[u8]| { + let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec(); + b.extend_from_slice(&(j.len() as u32).to_be_bytes()); + b.extend_from_slice(j); + b + }; + let (real, fake) = (sized_jpeg(1620, 1080, 3, 300), sized_jpeg(3000, 2000, 3, 300)); + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"PRVW", &boxed(&real))); + file.extend(bx(b"mdat", &[0u8; 64])); + file.extend(bx(b"mdat", &bx(b"PRVW", &boxed(&fake)))); + assert_eq!(embedded_preview(&file).unwrap(), real, "the look-alike in the second mdat is media data"); + // a PRVW cut short (no end marker): the full-size track covers a thumbnail instead + let mut short = real.clone(); + short.truncate(real.len() - 2); + let big = sized_jpeg(6000, 4000, 3, 3000); + assert_eq!(embedded_preview_covering(&cr3_with(&short, &big), 512).unwrap(), big); + assert_eq!(embedded_preview_covering(&cr3_with(&real, &big), 512).unwrap(), real, "a whole one is still taken"); +} + +/// The copy a CR3 thumbnail is given decodes, whichever is chosen (CodeRabbit on #3583: the other CR3 fixtures have +/// no scan): real encoded JPEGs, the `PRVW` for a small size, the full-size track past it. +#[test] +fn the_cr3_copy_chosen_for_a_thumbnail_decodes() { + let encode = |w: u16, h: u16| { + let px: Vec = (0..usize::from(w) * usize::from(h)).flat_map(|i| [(i % 251) as u8, 90, 160]).collect(); + let mut j = Vec::new(); + jpeg_encoder::Encoder::new(&mut j, 85).encode(&px, w, h, jpeg_encoder::ColorType::Rgb).unwrap(); + j + }; + let file = cr3_with(&encode(96, 64), &encode(384, 256)); + for (min, want) in [(64u32, (96, 64)), (200, (384, 256))] { + let j = embedded_preview_covering(&file, min).unwrap(); + let (_, w, h, c) = crate::tiffraw::lossy_jpeg(&j, 3, 1 << 20).unwrap(); + assert_eq!(((w, h), c), (want, 3), "covering {min} px"); + } +} diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 0b142df5e6..a8d925d799 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -1245,6 +1245,7 @@ "Specific folder": "Konkrétní složka", "Same folder as original photo": "Stejná složka jako původní fotografie", "Tidying the thumbnail cache": "Úklid mezipaměti miniatur", + "Checking free disk space": "Kontrola volného místa na disku", "No masks yet. Choose a mask type above.": "Zatím žádné masky. Vyberte typ masky nahoře.", "No matching commands": "Žádné odpovídající příkazy", "No matching photos": "Žádné odpovídající fotografie", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 552ce68016..5a5b8e9a2b 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -2329,6 +2329,7 @@ "Specific folder": "Bestimmter Ordner", "Same folder as original photo": "Im selben Ordner wie das Originalfoto", "Tidying the thumbnail cache": "Miniaturcache wird aufgeräumt", + "Checking free disk space": "Freier Speicherplatz wird geprüft", "Reset all edits (Cmd+Shift+R)": "Alle Bearbeitungen zurücksetzen (⌘⇧R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Smart-Alben aktualisieren sich selbst: Ändere ihre Regeln oder verwende Foto → Foto löschen", "LightCraft stopped": "LightCraft wurde beendet", @@ -3459,6 +3460,8 @@ "The photos are imported once it ends": "Die Fotos werden danach importiert", "An import is running. Drop photos when it has finished": "Ein Import läuft. Lege die Fotos ab, wenn er fertig ist", "Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst", + "Camera preview": "Kameravorschau", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "Das eigene JPEG der Kamera, angezeigt, bis LightCraft die Raw-Datei gerendert hat. Farbe und Tonwerte am gerenderten Foto beurteilen.", "Profile: from the file (the camera's own correction)": "Profil: aus der Datei (Korrektur der Kamera)", "Downloading the lens database…": "Objektivdatenbank wird geladen…", "This file names no lens.": "Diese Datei nennt kein Objektiv.", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index b82a261256..ba1a5ec747 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2333,6 +2333,7 @@ "Specific folder": "Carpeta específica", "Same folder as original photo": "Misma carpeta que la foto original", "Tidying the thumbnail cache": "Ordenando la caché de miniaturas", + "Checking free disk space": "Comprobando el espacio libre en disco", "Reset all edits (Cmd+Shift+R)": "Restablecer todas las ediciones (Cmd+Mayús+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Los álbumes inteligentes se actualizan solos: cambie sus reglas o use Foto → Eliminar foto", "LightCraft stopped": "LightCraft se detuvo", @@ -2378,6 +2379,8 @@ "The photos are imported once it ends": "Las fotos se importarán después", "An import is running. Drop photos when it has finished": "Hay una importación en curso. Suelta las fotos cuando termine", "Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos", + "Camera preview": "Vista previa de la cámara", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "El JPEG propio de la cámara, mostrado hasta que LightCraft haya renderizado el RAW. Juzga el color y el tono en la foto renderizada.", "Profile: from the file (the camera's own correction)": "Perfil: del archivo (corrección de la propia cámara)", "Downloading the lens database…": "Descargando la base de datos de objetivos…", "This file names no lens.": "Este archivo no indica ningún objetivo.", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index df80342abe..b99329eb84 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2065,6 +2065,7 @@ "Thursday": "torstai", "Tick the box to accept the model's terms first": "Hyväksy ensin mallin ehdot valitsemalla ruutu", "Tidying the thumbnail cache": "Siivotaan pikkukuvien välimuistia", + "Checking free disk space": "Tarkistetaan vapaata levytilaa", "Time zone": "Aikavyöhyke", "Tint": "Värisävy", "Title": "Otsikko", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index e513e217de..2d1c623e17 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -2328,6 +2328,7 @@ "Specific folder": "Dossier spécifique", "Same folder as original photo": "Même dossier que la photo d’origine", "Tidying the thumbnail cache": "Rangement du cache des miniatures", + "Checking free disk space": "Vérification de l'espace disque libre", "Reset all edits (Cmd+Shift+R)": "Réinitialiser toutes les retouches (Cmd+Maj+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Les albums intelligents se mettent à jour d'eux-mêmes : modifiez leurs règles ou utilisez Photo → Supprimer la photo", "LightCraft stopped": "LightCraft s’est arrêté", @@ -2409,6 +2410,8 @@ "The photos are imported once a library is open": "Les photos seront importées dès qu'une bibliothèque sera ouverte", "Open a library first, then drop the presets again": "Ouvrez d'abord une bibliothèque, puis déposez à nouveau les préréglages", "This library couldn't be checked:": "Impossible de vérifier cette bibliothèque :", + "Camera preview": "Aperçu de l'appareil", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "Le JPEG de l'appareil photo, affiché jusqu'à ce que LightCraft ait rendu le fichier RAW. Jugez la couleur et les tons sur la photo rendue.", "Profile: from the file (the camera's own correction)": "Profil : du fichier (correction de l'appareil)", "Downloading the lens database…": "Téléchargement de la base de données d'objectifs…", "This file names no lens.": "Ce fichier n'indique aucun objectif.", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 7f5e56e1ce..8889444a08 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2062,6 +2062,7 @@ "Thursday": "Kamis", "Tick the box to accept the model's terms first": "Centang kotak untuk menyetujui ketentuan model terlebih dahulu", "Tidying the thumbnail cache": "Merapikan cache thumbnail", + "Checking free disk space": "Memeriksa ruang disk kosong", "Time zone": "Zona waktu", "Tint": "Rona", "Title": "Judul", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index c77a85b41f..b7a617a5af 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -937,6 +937,7 @@ "Specific folder": "Cartella specifica", "Same folder as original photo": "Stessa cartella della foto originale", "Tidying the thumbnail cache": "Riordino della cache delle miniature", + "Checking free disk space": "Controllo dello spazio libero su disco", "No masks yet. Choose a mask type above.": "Ancora nessuna maschera. Scegli un tipo di maschera qui sopra.", "No matching commands": "Nessun comando corrispondente", "No matching photos": "Nessuna foto corrispondente", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 72ed66ad20..a07bb9de25 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2331,6 +2331,7 @@ "Specific folder": "指定フォルダー", "Same folder as original photo": "元の写真と同じフォルダー", "Tidying the thumbnail cache": "サムネールキャッシュを整理中", + "Checking free disk space": "ディスクの空き容量を確認中", "Reset all edits (Cmd+Shift+R)": "すべての編集をリセット(⌘⇧R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "スマートアルバムは自動で更新されます。ルールを変更するか、写真 → 写真を削除を使ってください", "LightCraft stopped": "LightCraftが終了しました", @@ -2376,6 +2377,8 @@ "The photos are imported once it ends": "終わりしだい写真を読み込みます", "An import is running. Drop photos when it has finished": "読み込み中です。完了してから写真をドロップしてください", "Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください", + "Camera preview": "カメラのプレビュー", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "LightCraft が RAW を現像するまで表示される、カメラ自身の JPEG です。色とトーンは現像後の写真で判断してください。", "Profile: from the file (the camera's own correction)": "プロファイル: ファイル内(カメラ自身の補正)", "Downloading the lens database…": "レンズデータベースをダウンロード中…", "This file names no lens.": "このファイルにはレンズ名がありません。", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index e9d0ba8b05..b994b84144 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -2945,6 +2945,7 @@ "This row covers more than one disk: drop on a folder inside it": "ეს სტრიქონი ერთზე მეტ დისკს მოიცავს: ჩააგდეთ მის შიგნით მყოფ საქაღალდეზე", "This screen is off: turn it on under Titles to play it.": "ეს ეკრანი გამორთულია: დასაკრავად ჩართეთ „ტიტრებში“.", "Tidying the thumbnail cache": "ესკიზების ქეში სუფთავდება", + "Checking free disk space": "დისკზე თავისუფალი ადგილის შემოწმება", "Title text": "ტიტრის ტექსტი", "Titles": "ტიტრები", "Tokens: {file}, {name}, {title}, {caption}, {date}, {exposure}, {iso}, {focal}, {camera}, {lens}, {rating}, {creator}, {copyright}. Other text shows as typed.": "ტეგები: {file}, {name}, {title}, {caption}, {date}, {exposure}, {iso}, {focal}, {camera}, {lens}, {rating}, {creator}, {copyright}. სხვა ტექსტი ისე ჩანს, როგორც აკრიფეთ.", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 821bc56ff3..285b84f48d 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2171,6 +2171,7 @@ "Specific folder": "Pasta específica", "Same folder as original photo": "Mesma pasta da foto original", "Tidying the thumbnail cache": "Organizando o cache de miniaturas", + "Checking free disk space": "Verificando o espaço livre em disco", "Reset all edits (Cmd+Shift+R)": "Redefinir todas as edições (Cmd+Shift+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Álbuns inteligentes se atualizam sozinhos: altere as regras ou use Foto → Excluir foto", "LightCraft stopped": "O LightCraft parou", @@ -2222,6 +2223,8 @@ "The photos are imported once it ends": "As fotos serão importadas depois", "An import is running. Drop photos when it has finished": "Uma importação está em andamento. Solte as fotos quando ela terminar", "Finish Lightroom catalog import before adding photos": "Conclua a importação do catálogo do Lightroom antes de adicionar fotos", + "Camera preview": "Prévia da câmera", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "O JPEG da própria câmera, mostrado até o LightCraft renderizar o RAW. Avalie cor e tom na foto renderizada.", "Profile: from the file (the camera's own correction)": "Perfil: do arquivo (correção da própria câmera)", "Downloading the lens database…": "Baixando o banco de dados de lentes…", "This file names no lens.": "Este arquivo não indica nenhuma lente.", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index db51744bfa..79b8ced04d 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2539,6 +2539,7 @@ "Specific folder": "Указанная папка", "Same folder as original photo": "Та же папка, что и у оригинала", "Tidying the thumbnail cache": "Упорядочивание кэша миниатюр", + "Checking free disk space": "Проверка свободного места на диске", "Reset all edits (Cmd+Shift+R)": "Сбросить все правки (Cmd+Shift+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Смарт-альбомы обновляются сами: измените их правила или выберите Фото → Удалить фото", "LightCraft stopped": "LightCraft остановился", @@ -2584,6 +2585,8 @@ "The photos are imported once it ends": "Фото будут импортированы после этого", "An import is running. Drop photos when it has finished": "Импорт уже выполняется. Перетащите фото, когда он закончится", "Finish Lightroom catalog import before adding photos": "Завершите импорт каталога Lightroom, прежде чем добавлять фото", + "Camera preview": "Превью камеры", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "Собственный JPEG камеры, показанный, пока LightCraft не обработает RAW. Оценивайте цвет и тон по обработанному фото.", "Profile: from the file (the camera's own correction)": "Профиль: из файла (коррекция самой камеры)", "Downloading the lens database…": "Загружается база объективов…", "This file names no lens.": "В этом файле не указан объектив.", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 4c4267d523..1b35ecccde 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2242,6 +2242,7 @@ "Thursday": "Torsdag", "Tick the box to accept the model's terms first": "Markera rutan för att godkänna modellens villkor först", "Tidying the thumbnail cache": "Städar miniatyrcachen", + "Checking free disk space": "Kontrollerar ledigt diskutrymme", "Time zone": "Tidszon", "Tint": "Färgton", "Title": "Titel", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 085be4f7e4..7aafd1059a 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2329,6 +2329,7 @@ "Specific folder": "Вказана папка", "Same folder as original photo": "Та сама папка, що й оригінал", "Tidying the thumbnail cache": "Упорядкування кешу мініатюр", + "Checking free disk space": "Перевірка вільного місця на диску", "Reset all edits (Cmd+Shift+R)": "Скинути всі зміни (Cmd+Shift+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Розумні альбоми оновлюються самі: змініть їхні правила або виберіть Фото → Видалити фото", "LightCraft stopped": "LightCraft зупинився", @@ -2374,6 +2375,8 @@ "The photos are imported once it ends": "Фото буде імпортовано після цього", "An import is running. Drop photos when it has finished": "Імпорт уже виконується. Перетягніть фото, коли він завершиться", "Finish Lightroom catalog import before adding photos": "Завершіть імпорт каталогу Lightroom, перш ніж додавати фото", + "Camera preview": "Прев'ю камери", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "Власний JPEG камери, показаний, доки LightCraft не обробить RAW. Оцінюйте колір і тон за обробленим фото.", "Profile: from the file (the camera's own correction)": "Профіль: з файлу (корекція самої камери)", "Downloading the lens database…": "Завантажується база об'єктивів…", "This file names no lens.": "У цьому файлі не вказано об'єктив.", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index dd93d0485c..07a4ca85f1 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2568,6 +2568,7 @@ "Thumbnail size": "Kích thước ảnh thu nhỏ", "Import Thumbnail Size": "Kích thước ảnh thu nhỏ khi nhập", "Tidying the thumbnail cache": "Đang dọn dẹp bộ nhớ đệm ảnh thu nhỏ", + "Checking free disk space": "Đang kiểm tra dung lượng đĩa trống", "Title bar": "Thanh tiêu đề", "Title text": "Văn bản tiêu đề", "Titles": "Tiêu đề", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 5f138b6f9c..a199e84fe0 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2164,6 +2164,7 @@ "Specific folder": "指定文件夹", "Same folder as original photo": "与原始照片相同的文件夹", "Tidying the thumbnail cache": "正在整理缩略图缓存", + "Checking free disk space": "正在检查可用磁盘空间", "Reset all edits (Cmd+Shift+R)": "重置所有编辑 (Cmd+Shift+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "智能相册会自动更新:请更改其规则,或使用“照片 → 删除照片”", "LightCraft stopped": "LightCraft 已停止", @@ -2221,6 +2222,8 @@ "The photos are imported once it ends": "结束后即导入这些照片", "An import is running. Drop photos when it has finished": "正在导入。导入完成后再拖放照片", "Finish Lightroom catalog import before adding photos": "添加照片前,请先完成 Lightroom 目录的导入", + "Camera preview": "相机预览", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "相机自己的 JPEG,在 LightCraft 渲染出原始文件之前显示。请在渲染后的照片上判断颜色和影调。", "Profile: from the file (the camera's own correction)": "配置文件:来自文件(相机自身的校正)", "Downloading the lens database…": "正在下载镜头数据库…", "This file names no lens.": "此文件未注明镜头。", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 275accbeb0..d5cb5462cc 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2132,6 +2132,7 @@ "Specific folder": "指定資料夾", "Same folder as original photo": "與原始照片相同的資料夾", "Tidying the thumbnail cache": "正在整理縮圖快取", + "Checking free disk space": "正在檢查可用磁碟空間", "Reset all edits (Cmd+Shift+R)": "重設所有編輯(Cmd+Shift+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "智慧型相簿會自動更新:請變更其規則,或使用「照片 → 刪除照片」", "LightCraft stopped": "LightCraft 已停止", @@ -2177,6 +2178,8 @@ "The photos are imported once it ends": "結束後即匯入這些照片", "An import is running. Drop photos when it has finished": "正在匯入。匯入完成後再拖放照片", "Finish Lightroom catalog import before adding photos": "新增照片前,請先完成 Lightroom 目錄的匯入", + "Camera preview": "相機預覽", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "相機自己的 JPEG,在 LightCraft 算繪出原始檔之前顯示。請在算繪後的照片上判斷色彩與色調。", "Profile: from the file (the camera's own correction)": "設定檔:來自檔案(相機本身的校正)", "Downloading the lens database…": "正在下載鏡頭資料庫…", "This file names no lens.": "此檔案未註明鏡頭。", diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba91d2f71..34ffc3811b 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -65,6 +65,8 @@ impl LightcraftApp { #[cfg(test)] library_passes: vec![], #[cfg(test)] + prep_ticks: 0, + #[cfg(test)] missing_count_test_delay: None, shadow: None, synthetic: vec![], @@ -94,6 +96,9 @@ impl LightcraftApp { space_hand: None, brush_live: None, loupe_shown: None, + loupe_timing: Default::default(), + prep_synced: false, + look_ahead: Default::default(), region_view: None, region_before_view: None, size_hold: Default::default(), @@ -106,6 +111,7 @@ impl LightcraftApp { merge: merge::MergeState::default(), import: None, scan: None, + scans_stopping: Default::default(), waiting_import: Default::default(), sync: None, sync_owns_changes: false, @@ -123,6 +129,8 @@ impl LightcraftApp { window_is_fullscreen: false, gpu_applied: None, gpu_notice: false, + disk_space_notice: false, + disk_notice: None, memory_applied: None, display_applied: None, display_error: None, @@ -488,6 +496,41 @@ impl LightcraftApp { } } + /// The app-wide background preparation settings live with the app settings (`ui.json`): taken + /// into the session once, then a change made through `prefs.setBackgroundPrep` is saved with + /// them. Run at the start of every logic pass, before any command of that pass (also before + /// the fonts are ready and the window is drawn). + fn sync_prep_settings(&mut self) { + if !self.prep_synced { + self.session.prep.app = self.ui.settings.background_prep.sanitized(); + self.prep_synced = true; + } else if self.session.prep.app != self.ui.settings.background_prep { + self.ui.settings.background_prep = self.session.prep.app; + } + } + + /// Preparing photos in the background ([`lightcraft_engine::prep`]): the whole view's previews + /// once the user is culling in the loupe, built from the photo on screen in the direction of travel. + /// Advanced on every logic pass, the hidden ones too (a minimised window keeps preparing). + fn background_prep(&mut self, ctx: &egui::Context) { + #[cfg(test)] + { + self.prep_ticks += 1; + } + let mode = panels::detail::prep_mode(self); + let loupe = self.ui.fullscreen || self.ui.view == state::ViewMode::Detail; + let at = if loupe { self.session.active() } else { None }; + let backward = self.look_ahead.backward(); + self.session.prep_tick(mode, at, backward); + if self.session.preview_build.as_ref().is_some_and(|b| b.running()) { + ctx.request_repaint_after(std::time::Duration::from_millis(500)); + } + // a build that couldn't start tries again at its time, also when nothing else draws a frame + if let Some(wait) = self.session.prep_retry_in() { + ctx.request_repaint_after(wait); + } + } + /// AI masks: apply finished background requests (clicks, descriptions, detail passes) and /// show their errors; start a zoomed-in detail pass once the clicking stops /// (`ui.detail_due`); watch the model download. Never waits for the model. @@ -584,6 +627,7 @@ impl LightcraftApp { /// hidden, from `Context::run_logic`. It may read the refreshed viewport fields only: never /// `i.time`, events, keys or dropped files. pub fn logic(&mut self, ctx: &egui::Context) { + self.sync_prep_settings(); i18n::set_language(self.ui.language); // The fork's AccessKit root language and bidi runs follow the locale; presentation only. // Compare against the cached string: `Context::language()` allocates on every call, and diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 91eebe1cee..224a993484 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -44,7 +44,8 @@ impl LightcraftApp { /// monotonic app clock, so a hidden `run_logic` keeps it advancing and a second layout pass is /// a no-op rather than a duplicate. pub(super) fn logic_background(&mut self, ctx: &egui::Context) { - panels::notices::logic(self); + self.background_prep(ctx); + panels::notices::logic(self, ctx); // closing the window (or Quit) with changes only in memory: retry, else ask first if ctx.input(|i| i.viewport().close_requested()) && !panels::notices::may_close(self) { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); @@ -358,6 +359,8 @@ impl LightcraftApp { } self.widgets = std::mem::take(&mut self.next_widgets); self.widget_hits = std::mem::take(&mut self.next_widget_hits); + // a frame without the loupe (grid, Compare, Survey, slideshow…) ends the loupe's step timing + self.loupe_timing.end_frame(ctx.input(|i| i.time)); panels::notices::finish_ui_pass(self, ctx); panels::library_problem::finish_ui_pass(self, ctx); self.ui_passes = self.ui_passes.wrapping_add(1); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 3c6c2e1576..63403650b2 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(), "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())}, + "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(), "thumbsMade": app.renderer.thumbs_made, "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()), "loupeSteps": app.loupe_timing.to_json(), "previewCache": preview_cache_json(app)}, "loupe": app.loupe_shown.map(|(p, src)| json!({ "photo": p.0, "source": src, @@ -894,3 +894,20 @@ pub fn save_screenshot(app: &mut LightcraftApp, image: &egui::ColorImage, target } } } + +/// The preview cache's numbers for `ui.inspect` → `perf.previewCache`: what memory holds, and the +/// disk cache's hits, misses and writes this session (notes 47 and 48: are built previews used?). +fn preview_cache_json(app: &crate::LightcraftApp) -> serde_json::Value { + use std::sync::atomic::Ordering; + let (entries, bytes) = app.session.media.rendered.mem_usage(); + let disk = app.session.media.rendered.disk(); + serde_json::json!({ + "memEntries": entries, + "memBytes": bytes, + "diskHits": disk.map(|d| d.hits.load(Ordering::Relaxed)), + "diskMisses": disk.map(|d| d.misses.load(Ordering::Relaxed)), + "diskWrites": disk.map(|d| d.writes.load(Ordering::Relaxed)), + "diskBudget": disk.map(|d| d.budget()), + "loupeEdge": app.session.loupe_edge, + }) +} diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index e5bfab8817..c927608e01 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -34,11 +34,12 @@ pub(crate) use body::thumb_edge; use body::{DEFAULT_BELOW_GRID, badge_rect, dup_counts}; pub use body::{DEFAULT_FOLDER_TEMPLATE, body, example_destination, source_summary}; pub(crate) use body::{DIALOG_SIZE, THUMB_SIZE_DEFAULT, note_dialog_bottom, thumb_size}; +pub(crate) use scan::StoppingScans; #[cfg(not(target_arch = "wasm32"))] pub(crate) use scan::cards_seen; -pub use scan::{ScanTask, browse, open, poll_scan, running}; #[cfg(test)] -pub(crate) use scan::{stall_scan, stall_scan_of}; +pub(crate) use scan::{HELD_RESOLVES, ScanEnd, scan_by_hand, stall_scan, stall_scan_of}; +pub use scan::{ScanTask, browse, open, poll_scan, running}; pub(crate) use tags::{tag_field_width, tag_help, tag_toggle, unknown_tags_warning}; pub use task::{ImportTask, start, start_paths, tick}; diff --git a/crates/ui-egui/src/dialogs/import/scan.rs b/crates/ui-egui/src/dialogs/import/scan.rs index 67b1fa176b..c82f67123c 100644 --- a/crates/ui-egui/src/dialogs/import/scan.rs +++ b/crates/ui-egui/src/dialogs/import/scan.rs @@ -5,7 +5,7 @@ use super::{ImportDialog, LightcraftApp, Ordering, ScanInput, ScanOutput, ScanPr /// window must keep answering meanwhile). pub struct ScanTask { progress: std::sync::Arc, - rx: std::sync::mpsc::Receiver, + rx: std::sync::mpsc::Receiver, /// Open the review with "copy into the library" checked (a camera / card). pub copy: bool, /// Open the review with this album chosen (an album's context menu ▸ Import…). @@ -16,6 +16,91 @@ pub struct ScanTask { sources: Vec, /// The scan's row in the activity stack (its ✕ and `activity.cancel` set `progress.cancel`). guard: lightcraft_engine::activity::TaskGuard, + /// Browsing: the folder as the worker resolved it, once it has. The view shows it as given until then + /// (resolving reads the disk, which a stalled network mount can block: never on this thread). + resolved: Option>, +} + +/// What a scan's worker sends back. Every way it ends sends one, so the probes of earlier scans that +/// [`ScanInput::new`] took from the session always go back to it (a later import doesn't read those files again). +pub(crate) enum ScanEnd { + /// The scan finished. + Done(ScanOutput), + /// Browsing stopped without a listing: the folder couldn't be listed (`failed`), or another folder was + /// chosen. Never an empty listing, which the browse bookkeeping would take for every file gone. + Stopped { probes: std::collections::HashMap, failed: bool }, +} + +impl ScanEnd { + /// The probes this end hands back to the session. + fn into_probes(self) -> std::collections::HashMap { + match self { + ScanEnd::Done(out) => out.probes, + ScanEnd::Stopped { probes, .. } => probes, + } + } +} + +/// Scans stopped without waiting for their workers ([`stop_scan`]), in the order they were stopped, which is +/// the order they started (one scan runs at a time), and which of their probes went back to the session. +#[derive(Default)] +pub(crate) struct StoppingScans { + /// How many scans were stopped: each one's number. + stopped: u64, + /// Each stopped scan's number and channel, kept until its worker ends. + pending: Vec<(u64, std::sync::mpsc::Receiver)>, + /// The probes a stopped scan put back: by whom, and what they said (to tell they are still the ones there). + from: std::collections::HashMap, +} + +/// What tells two probes of one file apart: a file that changed but kept its size has another content hash. +type ProbeMark = (u64, Option, Option); + +fn mark(p: &lightcraft_engine::media::ProbeInfo) -> ProbeMark { + (p.file_size, p.content_hash.clone(), p.file_modified.clone()) +} + +/// Stop the running scan (if any) without waiting for its worker: the scan is closed at once, and its +/// channel is kept until the worker ends, so the probes it holds still come back ([`collect_stopped`]). +fn stop_scan(app: &mut LightcraftApp) { + if let Some(t) = app.scan.take() { + t.progress.cancel.store(true, Ordering::Relaxed); + let s = &mut app.scans_stopping; + s.stopped = s.stopped.saturating_add(1); + s.pending.push((s.stopped, t.rx)); + } +} + +/// The probes of stopped scans whose workers have ended go back to the session (called every frame). A probe +/// the session got since a scan started is newer than that scan's and stays, except one that a scan stopped +/// before it put back: a later scan read that file again, so its probe wins, whichever worker ends first +/// (an older probe of a file changed at the same size would hand the copy check a stale content hash). +fn collect_stopped(app: &mut LightcraftApp, ctx: &egui::Context) { + let probes = &mut app.session.import_probes; + let StoppingScans { pending, from, .. } = &mut app.scans_stopping; + pending.retain(|(seq, rx)| match rx.try_recv() { + Ok(end) => { + for (k, v) in end.into_probes() { + let replace = match probes.get(&k) { + None => true, + Some(have) => from.get(&k).is_some_and(|(by, m)| by < seq && *m == mark(have)), + }; + if replace { + from.insert(k.clone(), (*seq, mark(&v))); + probes.insert(k, v); + } + } + false + } + Err(std::sync::mpsc::TryRecvError::Empty) => true, + Err(std::sync::mpsc::TryRecvError::Disconnected) => false, + }); + if pending.is_empty() { + // no stopped scan left to compare with + from.clear(); + } else { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } } /// The activity row of a scan: the review's ("Scanning folder") or the Local view's ("Reading folder"). @@ -66,14 +151,14 @@ pub fn open(app: &mut LightcraftApp, paths: Vec) -> Result) -> Result) -> Result { - let dir = std::path::absolute(std::path::Path::new(path)).map_err(|e| e.to_string())?; - if !dir.is_dir() { - return Err(format!("{path}: not a folder")); - } + // one spelling for the view, the listing and the catalog's records: `a/lib/../outside` is `a/outside`. Taken out + // by name here, without reading the disk (a link on a stalled network mount would freeze the window): the worker + // resolves the folder, checks it is one, and the view takes its spelling when it says (see `poll_scan`) + let dir = lightcraft_engine::import::browse_spelling(std::path::Path::new(path)).map_err(|e| e.to_string())?; if app.scan.as_ref().is_some_and(|t| !t.browse) || app.import.as_ref().is_some_and(|t| !t.browse) { return Err("an import is running".into()); } let dir_s = dir.to_string_lossy().trim_end_matches(['/', '\\']).to_string(); let subfolders = subfolders.unwrap_or_else(|| app.session.browse.as_ref().is_some_and(|b| b.subfolders)); let running = app.scan.as_ref().is_some_and(|t| t.browse) || app.import.as_ref().is_some_and(|t| t.browse); - if running && app.session.browse.as_ref().is_some_and(|b| b.path == dir_s && b.subfolders == subfolders) { + // (a path through `..` can name another folder than its spelling, past a link: only the worker can tell, so it + // browses again; CodeRabbit on #3583) + let through_dotdot = std::path::Path::new(path).components().any(|c| c == std::path::Component::ParentDir); + if running && !through_dotdot && app.session.browse.as_ref().is_some_and(|b| b.path == dir_s && b.subfolders == subfolders) { // already reading this folder: clicking it again must not restart the progress app.session.source = lightcraft_engine::LibrarySource::Folder; app.session.keep_active_in_view(); return Ok(json!({"path": dir_s, "subfolders": subfolders, "scanning": true})); } - if let Some(t) = app.scan.take() { - t.progress.cancel.store(true, Ordering::Relaxed); - } + stop_scan(app); app.import = None; app.session.browse = Some(lightcraft_engine::Browse { path: dir_s.clone(), subfolders }); app.session.source = lightcraft_engine::LibrarySource::Folder; // the photos the library already knows from this folder show at once: keep or pick the active one app.session.keep_active_in_view(); - let (input, _) = ScanInput::new(&mut app.session, std::slice::from_ref(&dir_s)); + let (mut input, _) = ScanInput::new(&mut app.session, std::slice::from_ref(&dir_s)); let progress = std::sync::Arc::new(ScanProgress::default()); let (tx, rx) = std::sync::mpsc::channel(); let p = progress.clone(); - let root = dir_s.clone(); + // the worker resolves the path as given: on Unix `link/..` is the folder above where the link points, which the + // spelling (`..` taken out by name) can't tell + let given = path.to_owned(); + let sort = app.session.sort; + let (resolved_tx, resolved) = std::sync::mpsc::channel(); let job = move || { - let files: Vec = if subfolders { - lightcraft_engine::import::expand(&[root], None) - } else { - let mut v: Vec = std::fs::read_dir(&root) - .map(|rd| { - rd.flatten() - .filter(|e| !lightcraft_engine::walk::is_hidden_entry(e)) - .map(|e| e.path()) - .filter(|f| f.is_file() && lightcraft_engine::import::is_supported(f)) - .map(|f| f.to_string_lossy().to_string()) - .collect() - }) - .unwrap_or_default(); - v.sort(); - v + let root = match resolve_browse_root(&given) { + Ok(root) => root, + Err(e) => { + log::warn!("browse: can't read {given}: {e}"); + let _ = tx.send(ScanEnd::Stopped { probes: input.take_probes(), failed: true }); + return; + } }; - let _ = tx.send(scan_with(input, &files, &p)); + let _ = resolved_tx.send(root.clone()); + // (never the library's own folder, which the import would otherwise read as photos) + let files = match lightcraft_engine::import::browse_files(&input, &root, subfolders) { + Ok(files) => files, + Err(e) => { + // no listing is sent: the scan ends as failed, and no record is taken for a file gone + log::warn!("browse: can't list {root}: {e}"); + let _ = tx.send(ScanEnd::Stopped { probes: input.take_probes(), failed: true }); + return; + } + }; + // Nothing is read here: the import that follows reads the files and adds them batch by + // batch, first screen first, so the view fills while the rest is read (PERF-CULL-1). + // Another folder chosen meanwhile (`p.cancel`) stops the ordering, and no listing is sent. + let Some(queue) = lightcraft_engine::import::browse_queue_until(&input, files.clone(), &sort, &p.cancel) else { + let _ = tx.send(ScanEnd::Stopped { probes: input.take_probes(), failed: false }); + return; + }; + p.total.store(queue.len(), Ordering::Relaxed); + p.done.store(queue.len(), Ordering::Relaxed); + // the files the library knows come too, marked as such: the folder bookkeeping (browse + // times, records of files gone) needs the whole listing; only the queue is imported + let queued: std::collections::HashSet<&String> = queue.iter().collect(); + let known: Vec = files.iter().filter(|f| !queued.contains(f)).cloned().collect(); + let known = + known.into_iter().map(|path| lightcraft_engine::import::ImportCandidate { path, duplicate: Some("path".into()), ..Default::default() }); + let candidates = + queue.iter().cloned().map(|path| lightcraft_engine::import::ImportCandidate { path, ..Default::default() }).chain(known).collect(); + // the probes of earlier scans go back to the session with the result, for the import that follows + let _ = tx.send(ScanEnd::Done(lightcraft_engine::import::ScanOutput { candidates, probes: input.take_probes() })); }; #[cfg(not(target_arch = "wasm32"))] std::thread::spawn(job); + // the job takes the probes back out of `input`, so it is an FnMut where it runs in place #[cfg(target_arch = "wasm32")] - job(); + { + let mut job = job; + job(); + } let guard = scan_guard(app, &progress, true); - app.scan = Some(ScanTask { progress, rx, copy: false, album: None, browse: true, sources: Vec::new(), guard }); + app.scan = Some(ScanTask { progress, rx, copy: false, album: None, browse: true, sources: Vec::new(), guard, resolved: Some(resolved) }); app.renderer.forget_imports(); Ok(json!({"path": dir_s, "subfolders": subfolders, "scanning": true})) } +/// The browsed folder `given` (the path as `browse` received it, not its [`lightcraft_engine::import::browse_spelling`]) +/// as [`lightcraft_engine::import::browse_path`] resolves it, checked to be a folder: on the browse worker, as it reads the disk. +fn resolve_browse_root(given: &str) -> Result { + #[cfg(test)] + held_resolve(given); + let dir = lightcraft_engine::import::browse_path(std::path::Path::new(given)).map_err(|e| e.to_string())?; + if !dir.is_dir() { + return Err(format!("{given}: not a folder")); + } + Ok(dir.to_string_lossy().trim_end_matches(['/', '\\']).to_string()) +} + +/// Tests: browsed folders whose resolution waits (as on a stalled network mount) while they are listed here. +#[cfg(test)] +pub(crate) static HELD_RESOLVES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +#[cfg(test)] +fn held_resolve(given: &str) { + let held = || HELD_RESOLVES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).iter().any(|p| p == given); + let start = std::time::Instant::now(); + while held() && start.elapsed() < std::time::Duration::from_secs(30) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } +} + /// Collect a finished scan and open the review (called every frame). pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { show_pending_review(app, ctx); + collect_stopped(app, ctx); let Some(task) = app.scan.as_ref() else { return }; ctx.request_repaint_after(std::time::Duration::from_millis(100)); - let out = match task.rx.try_recv() { + // the worker resolved the browsed folder: the view takes its spelling (before its listing, sent after it) + if let Some(root) = task.resolved.as_ref().and_then(|r| r.try_recv().ok()) + && let Some(b) = app.session.browse.as_mut().filter(|b| b.path != root) + { + b.path = root; + app.session.keep_active_in_view(); + } + let Some(task) = app.scan.as_ref() else { return }; + let end = match task.rx.try_recv() { Ok(o) => o, Err(std::sync::mpsc::TryRecvError::Empty) => { if task.guard.is_cancelled() { // ✕: the worker stops at its next file; don't wait for it (a NAS read can take a while) - app.scan = None; + stop_scan(app); return; } let (total, done) = (task.progress.total.load(Ordering::Relaxed), task.progress.done.load(Ordering::Relaxed)); @@ -160,16 +309,32 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { return; } Err(_) => { + // a cancelled scan whose worker ended without a result was not a failure + let cancelled = task.guard.is_cancelled() || task.progress.cancel.load(Ordering::Relaxed); app.scan = None; - app.toast(ctx, crate::i18n::tr("Scan failed")); + if !cancelled { + app.toast(ctx, crate::i18n::tr("Scan failed")); + } return; } }; let Some(task) = app.scan.take() else { return }; - if task.progress.cancel.load(Ordering::Relaxed) { + let cancelled = task.progress.cancel.load(Ordering::Relaxed); + let out = match end { + ScanEnd::Done(out) => out, + ScanEnd::Stopped { probes, failed } => { + app.session.import_probes.extend(probes); + if failed && !cancelled { + app.toast(ctx, crate::i18n::tr("Scan failed")); + } + return; + } + }; + // the probes go back to the session however the scan ended (the ones of a scan stopped earlier may be there) + app.session.import_probes.extend(out.probes); + if cancelled { return; } - app.session.import_probes = out.probes; if task.browse { // the folder and the ones its photos are in count as browsed now, as `library.browse` records them, so // their untouched Local photos aren't forgotten while the folder is in use @@ -247,11 +412,17 @@ pub(crate) fn stall_scan(app: &mut LightcraftApp) -> Box { /// Tests: the same, for a Local folder browse scan (`browse`) instead of the review's scan. #[cfg(test)] pub(crate) fn stall_scan_of(app: &mut LightcraftApp, browse: bool) -> Box { + Box::new(scan_by_hand(app, browse)) +} + +/// Tests: a scan whose worker is the test: what it sends through the returned channel is the scan's end. +#[cfg(test)] +pub(crate) fn scan_by_hand(app: &mut LightcraftApp, browse: bool) -> std::sync::mpsc::Sender { let progress = std::sync::Arc::new(ScanProgress::default()); - let (tx, rx) = std::sync::mpsc::channel::(); + let (tx, rx) = std::sync::mpsc::channel::(); let guard = scan_guard(app, &progress, false); - app.scan = Some(ScanTask { progress, rx, copy: false, album: None, browse, sources: Vec::new(), guard }); - Box::new(tx) + app.scan = Some(ScanTask { progress, rx, copy: false, album: None, browse, sources: Vec::new(), guard, resolved: None }); + tx } /// Whether an import or any scan (the review's, or a Local folder browse) is running, or a finished scan's diff --git a/crates/ui-egui/src/dialogs/settings.rs b/crates/ui-egui/src/dialogs/settings.rs index 271b6e7c91..cada6c7fba 100644 --- a/crates/ui-egui/src/dialogs/settings.rs +++ b/crates/ui-egui/src/dialogs/settings.rs @@ -57,8 +57,8 @@ pub const TABS: &[(&str, &str)] = &[ ("denoise", "AI Denoise"), ]; -/// Thumbnail cache sizes offered (MB). -const CACHE_SIZES: [u32; 5] = [512, 1024, 2048, 4096, 8192]; +/// Preview cache sizes offered (MB; 0 = automatic: room for every photo of the library). +const CACHE_SIZES: [u32; 8] = [512, 1024, 2048, 4096, 8192, 51_200, 204_800, 0]; const LABEL_W: f32 = 150.0; diff --git a/crates/ui-egui/src/dialogs/settings/performance.rs b/crates/ui-egui/src/dialogs/settings/performance.rs index 370cf08bac..214dd38243 100644 --- a/crates/ui-egui/src/dialogs/settings/performance.rs +++ b/crates/ui-egui/src/dialogs/settings/performance.rs @@ -49,15 +49,30 @@ pub(super) fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &To let opts = [(0u32, auto.as_str()), (512, "512 MB"), (1024, "1 GB"), (2048, "2 GB"), (4096, "4 GB")]; choices(ui, "settingsMemory", &opts, &mut app.ui.settings.memory_mb); }); - heading(ui, t, crate::i18n::tr("Thumbnail cache")); - let cur = (app.session.cache_bytes() >> 20) as u32; + heading(ui, t, crate::i18n::tr("Preview cache")); + let cur = app.session.cache_mb; row(ui, t, crate::i18n::tr("Size limit"), |ui| { - let opts = [(512u32, "512 MB"), (1024, "1 GB"), (2048, "2 GB"), (4096, "4 GB"), (8192, "8 GB")]; - let mut v = if CACHE_SIZES.contains(&cur) { cur } else { 2048 }; + let gb = lightcraft_engine::media::default_disk_cache_bytes(app.session.catalog.len()).div_ceil(1 << 30); + let auto = format!("{} ({gb} GB)", crate::i18n::tr("Automatic")); + let custom = custom_cache_option(cur); + let mut opts = + vec![(512u32, "512 MB"), (1024, "1 GB"), (2048, "2 GB"), (4096, "4 GB"), (8192, "8 GB"), (51_200, "50 GB"), (204_800, "200 GB")]; + opts.extend(custom.as_ref().map(|(mb, l)| (*mb, l.as_str()))); + opts.push((0, auto.as_str())); + // (a saved size the list doesn't offer shows as its own option, not as Automatic: picking + // Automatic then changes it; CodeRabbit on #3583) + let mut v = if CACHE_SIZES.contains(&cur) || custom.is_some() { cur } else { 0 }; if choices(ui, "settingsCache", &opts, &mut v) { let _ = app.run("library.preferences", json!({"cacheMb": v})); } }); + hint( + ui, + t, + crate::i18n::tr( + "Grid thumbnails and the previews the loupe shows, kept on disk so photos open at once next time. Automatic makes room for every photo in this library (about 1.5 MB a photo). 50 GB: normal · 200 GB: better, for several weddings or large shoots.", + ), + ); let used = app.session.media.rendered.disk().map(|d| d.size()); row(ui, t, crate::i18n::tr("In use"), |ui| { ui.label( @@ -70,6 +85,7 @@ pub(super) fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &To let _ = app.run("library.clearPreviews", json!({})); } }); + background_prep(app, ui, t); heading(ui, t, crate::i18n::tr("Local folders")); row(ui, t, crate::i18n::tr("Forget unchanged photos"), |ui| { let opts = [(0u32, "Never"), (7, "After 7 days"), (30, "After 30 days"), (90, "After 90 days"), (365, "After a year")]; @@ -89,6 +105,92 @@ pub(super) fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &To smart_previews(app, ui, t); } +/// Settings ▸ Performance ▸ Prepare photos in the background (notes 47 and 48): per mode, what +/// is made ready before the user gets to it (`prefs.backgroundPrep`), app-wide or for this library. +fn background_prep(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + use lightcraft_engine::prep::{Mode, Scope}; + heading(ui, t, crate::i18n::tr("Prepare photos in the background")); + hint( + ui, + t, + crate::i18n::tr( + "While you go through photos in the loupe, the next ones are made ready before you reach them, and when the computer is otherwise idle the previews of every photo in view are built. The photo on screen always comes first; the work shows in the activity list, where it can be stopped.", + ), + ); + let own = app.session.prep.library.is_some(); + let lib_open = app.session.library.is_some(); + if lib_open { + let mut v = own; + if check(ui, "settings.prepOwn", &mut v, "Use different settings for this library") { + let r = if v { + let cur = app.session.prep_settings(); + app.run("prefs.setBackgroundPrep", json!({"library": true, "settings": cur})) + } else { + app.run("prefs.setBackgroundPrep", json!({"reset": true})) + }; + if let Err(e) = r { + log::warn!("background preparation: {e}"); + } + } + hint(ui, t, crate::i18n::tr("For example, a timelapse library can prepare nothing while a wedding library prepares everything.")); + } + let cur = app.session.prep_settings(); + let mut patch: Option = None; + let scopes = [(Scope::All, "Every photo"), (Scope::Marked, "Picks, rated and labelled"), (Scope::OnScreen, "Only the photo on screen")]; + for (mode, key, title) in [(Mode::Culling, "culling", "Culling (a folder before import)"), (Mode::Library, "library", "Library")] { + let m = cur.mode(mode); + ui.add_space(4.0); + ui.label(RichText::new(crate::i18n::tr(title)).font(t.semibold(12.0)).color(t.text)); + let mut previews = m.previews; + row(ui, t, crate::i18n::tr("Previews"), |ui| { + if check(ui, &format!("settings.prep.{key}.previews"), &mut previews, "Build previews for every photo in view") { + patch = Some(json!({key: {"previews": previews}})); + } + }); + hint(ui, t, crate::i18n::tr("Starts once you step through a few photos. Uses about 1.5 MB of disk a photo, and the computer's spare time.")); + let mut ahead = m.ahead; + row(ui, t, crate::i18n::tr("Photos ahead"), |ui| { + let opts = [(0u8, "Off"), (3, "3"), (5, "5"), (10, "10"), (20, "20")]; + if choices(ui, &format!("settingsPrepAhead-{key}"), &opts, &mut ahead) { + patch = Some(json!({key: {"ahead": ahead}})); + } + }); + let mut scope = m.scope; + row(ui, t, crate::i18n::tr("Which photos"), |ui| { + if choices(ui, &format!("settingsPrepScope-{key}"), &scopes, &mut scope) { + patch = Some(json!({key: {"scope": scope}})); + } + }); + } + ui.add_space(4.0); + ui.label(RichText::new(crate::i18n::tr("Editing")).font(t.semibold(12.0)).color(t.text)); + let mut ahead = cur.develop.ahead; + row(ui, t, crate::i18n::tr("Photos ahead"), |ui| { + let opts = [(0u8, "Off"), (1, "1"), (2, "2"), (3, "3"), (5, "5")]; + if choices(ui, "settingsPrepAhead-develop", &opts, &mut ahead) { + patch = Some(json!({"develop": {"ahead": ahead}})); + } + }); + hint( + ui, + t, + crate::i18n::tr( + "The next photos are opened and kept ready to edit, so the first slider move on them is quick. Uses memory: a few hundred MB a photo.", + ), + ); + let mut scope = cur.develop.scope; + row(ui, t, crate::i18n::tr("Which photos"), |ui| { + if choices(ui, "settingsPrepScope-develop", &scopes, &mut scope) { + patch = Some(json!({"develop": {"scope": scope}})); + } + }); + if let Some(patch) = patch + && let Err(e) = app.run("prefs.setBackgroundPrep", json!({"library": own, "settings": patch})) + { + log::warn!("background preparation: {e}"); + } +} + /// Where this library keeps its smart previews (the offline-editing proxies, which can be large): /// the effective folder, what is in it, and choosing another one. #[cfg(not(target_arch = "wasm32"))] @@ -193,3 +295,24 @@ fn smart_previews(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } hint(ui, t, crate::i18n::tr("Keep it on a drive with room: smart previews are about 1 MB per photo. The thumbnail cache stays in the library.")); } + +/// The cache size limit saved in the settings, as an option of its own when the list doesn't offer +/// it (set through `library.preferences`, or by an older version): its value and label. +fn custom_cache_option(cur: u32) -> Option<(u32, String)> { + if cur == 0 || CACHE_SIZES.contains(&cur) { + return None; + } + let label = if cur.is_multiple_of(1024) { format!("{} GB", cur / 1024) } else { format!("{cur} MB") }; + Some((cur, label)) +} + +#[cfg(test)] +mod tests { + #[test] + fn a_saved_cache_size_the_list_does_not_offer_is_an_option() { + assert_eq!(super::custom_cache_option(0), None, "Automatic"); + assert_eq!(super::custom_cache_option(51_200), None, "offered"); + assert_eq!(super::custom_cache_option(10_240), Some((10_240, "10 GB".to_string()))); + assert_eq!(super::custom_cache_option(3000), Some((3000, "3000 MB".to_string()))); + } +} diff --git a/crates/ui-egui/src/headless/tests.rs b/crates/ui-egui/src/headless/tests.rs index 7ba584faf0..43465fee78 100644 --- a/crates/ui-egui/src/headless/tests.rs +++ b/crates/ui-egui/src/headless/tests.rs @@ -527,6 +527,10 @@ fn demo_grid_snapshot_has_ui_pixels() { assert!(bright > 30, "no text in the top bar ({bright} bright px)"); // thumbnails arrived (photo textures were drawn) assert!(h.app.renderer.thumb_textures() > 0); + // and are counted for benchmarks, a count that eviction doesn't lower + let r = h.request("ui.inspect", json!({}), SETTLE); + let made = r["result"]["perf"]["thumbsMade"].as_u64().unwrap_or(0); + assert!(made >= h.app.renderer.thumb_textures() as u64, "{}", r["result"]["perf"]); } #[test] @@ -3416,6 +3420,15 @@ fn browsing_from_the_ui_records_the_folder() { assert_eq!(h.app.session.visible_cloned().len(), 1); assert!(h.app.session.catalog.last_browsed(&root).is_some(), "the browsed folder"); assert!(h.app.session.catalog.last_browsed(&day_s).is_some(), "the folder its photo is in"); + // browsed again: a subfolder with only photos the library knows (nothing to import) still + // counts as browsed + h.app.session.catalog.apply(lightcraft_catalog::Op::SetBrowsed { folder: day_s.clone(), at: None }).unwrap(); + assert!(h.app.session.catalog.last_browsed(&day_s).is_none()); + let r = h.request("engine.execute", json!({"command": "library.browse", "params": {"path": root, "subfolders": true}}), t); + assert_eq!(r["result"]["scanning"], true, "{r}"); + h.settle(SETTLE); + assert_eq!(h.app.session.visible_cloned().len(), 1); + assert!(h.app.session.catalog.last_browsed(&day_s).is_some(), "a folder of known photos only"); let _ = std::fs::remove_dir_all(&dir); } @@ -5057,6 +5070,133 @@ fn screenshot_request_is_answered_without_a_window() { assert_eq!(r["result"]["width"], 640, "{r}"); } +/// Note 47: stepping in the loupe to a photo whose preview was built shows that preview as the +/// photo (fitted to the loupe, no render), and standard previews are built at the loupe's size. +#[test] +fn the_loupe_shows_built_previews_without_rendering_again() { + use crate::render::Slot; + use lightcraft_engine::media::QuickSource; + let mut h = demo([1000.0, 700.0]); + let t = Duration::from_secs(10); + // nothing prepared ahead here: what the loupe shows comes from the build alone + h.request( + "engine.execute", + json!({"command": "prefs.setBackgroundPrep", "params": {"settings": {"library": {"ahead": 0, "previews": false}}}}), + t, + ); + h.request("ui.set", json!({"view": "detail", "right": "none"}), t); + h.settle(SETTLE); + let edge = h.app.session.loupe_edge; + assert!(edge > 100, "the loupe said its size: {edge}"); + let ids = h.app.session.visible_cloned(); + let all: Vec = ids.iter().map(|i| i.0).collect(); + let r = h.request("engine.execute", json!({"command": "library.buildPreviews", "params": {"wait": true, "edge": edge, "ids": all}}), t); + assert_eq!(r["result"]["done"], ids.len(), "{r}"); + let next = ids.get(1).copied().expect("a second photo"); + h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [next.0], "active": next.0}}), t); + assert!(h.step_until(SETTLE, |h| h.app.renderer.textures.get(&Slot::Main).is_some_and(|t| t.photo == next))); + let main = h.app.renderer.textures.get(&Slot::Main).unwrap(); + assert_eq!(main.quick, Some(QuickSource::Cached), "the built preview is the loupe's picture"); + let r = h.request("ui.inspect", json!({}), t); + assert!(r["result"]["perf"]["previewCache"]["memEntries"].as_u64().unwrap_or(0) > 0, "{}", r["result"]["perf"]["previewCache"]); +} + +/// Editing, the loupe renders the photo from its source even when a built preview of it is cached +/// (CodeRabbit on #3077): the cached view would show at once but leave the source undecoded, and +/// the first slider draft would wait for it. +#[test] +fn editing_renders_the_loupe_from_its_source_not_a_built_preview() { + use crate::render::Slot; + use lightcraft_engine::media::QuickSource; + let mut h = demo([1000.0, 700.0]); + let t = Duration::from_secs(10); + h.request( + "engine.execute", + json!({"command": "prefs.setBackgroundPrep", "params": {"settings": {"library": {"ahead": 0, "previews": false}, "develop": {"ahead": 0}}}}), + t, + ); + h.request("ui.set", json!({"view": "detail", "right": "none"}), t); + h.settle(SETTLE); + let edge = h.app.session.loupe_edge; + let ids = h.app.session.visible_cloned(); + let all: Vec = ids.iter().map(|i| i.0).collect(); + let r = h.request("engine.execute", json!({"command": "library.buildPreviews", "params": {"wait": true, "edge": edge, "ids": all}}), t); + assert_eq!(r["result"]["done"], ids.len(), "{r}"); + h.request("ui.set", json!({"right": "edit"}), t); + let next = ids.get(1).copied().expect("a second photo"); + h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [next.0], "active": next.0}}), t); + assert!(h.step_until(SETTLE, |h| h.app.renderer.textures.get(&Slot::Main).is_some_and(|t| t.photo == next))); + let main = h.app.renderer.textures.get(&Slot::Main).unwrap(); + assert_ne!(main.quick, Some(QuickSource::Cached), "rendered from the source while editing"); +} + +/// The loupe holds background preparation back only while its render is on the way (CodeRabbit on +/// #3077): once the photo is shown, the frames that follow don't renew the hold. +#[test] +fn a_shown_loupe_render_does_not_hold_background_preparation() { + use crate::render::Slot; + let mut h = demo([1000.0, 700.0]); + let t = Duration::from_secs(10); + h.request("ui.set", json!({"view": "detail", "right": "none"}), t); + let id = h.app.session.active().expect("an active photo"); + let signals = || crate::panels::detail::FOREGROUND_SIGNALS.with(std::cell::Cell::get); + let before = signals(); + assert!( + h.step_until(SETTLE, |h| h.app.renderer.textures.get(&Slot::Main).is_some_and(|t| t.photo == id) && !h.app.renderer.is_pending(Slot::Main)) + ); + assert!(signals() > before, "the hold was asked for while the render was on its way"); + let shown = signals(); + for _ in 0..10 { + h.step(); + } + assert_eq!(signals(), shown, "no hold while the render is on screen"); +} + +/// The app-wide background preparation settings are kept with the app settings (`ui.json`): +/// the saved ones reach the session at launch, and a change made through the command is saved. +#[test] +fn app_wide_preparation_settings_are_saved_with_the_app_settings() { + let mut h = demo([1000.0, 700.0]); + let t = Duration::from_secs(10); + let mut saved = lightcraft_engine::prep::PrepSettings::default(); + saved.library.ahead = 3; + // (as if read from ui.json before the first frame) + h.app.ui.settings.background_prep = saved; + h.app.prep_synced = false; + h.step(); + assert_eq!(h.app.session.prep.app, saved, "the saved settings reach the session"); + h.request("engine.execute", json!({"command": "prefs.setBackgroundPrep", "params": {"settings": {"library": {"ahead": 10}}}}), t); + h.step(); + assert_eq!(h.app.ui.settings.background_prep.library.ahead, 10, "a change is kept with the app settings"); + assert_eq!(h.app.session.prep.app.library.ahead, 10); +} + +/// Note 48: the loupe prepares as many photos ahead as the settings say, a few at a time, and +/// none when that is off. +#[test] +fn the_loupe_prepares_the_photos_ahead_the_settings_ask_for() { + let mut h = demo([1000.0, 700.0]); + let t = Duration::from_secs(10); + let n = h.app.session.visible_cloned().len(); + assert!(n >= 4, "the demo has photos to step through"); + h.request("engine.execute", json!({"command": "prefs.setBackgroundPrep", "params": {"settings": {"library": {"ahead": 3}}}}), t); + h.request("ui.set", json!({"view": "detail", "right": "none"}), t); + h.settle(SETTLE); + for _ in 0..40 { + h.step(); + } + h.settle(SETTLE); + // the first photo: three ahead (no photo behind it) + assert_eq!(h.app.renderer.prefetch_slots_asked(), 3.min(n - 1)); + h.app.renderer.forget_all(); + h.request("engine.execute", json!({"command": "prefs.setBackgroundPrep", "params": {"settings": {"library": {"ahead": 0}}}}), t); + for _ in 0..40 { + h.step(); + } + h.settle(SETTLE); + assert_eq!(h.app.renderer.prefetch_slots_asked(), 0, "off: nothing prepared ahead"); +} + /// A size typed in the Export dialog is the size exported: the pixel fields kept only multiples /// of 16, so 1080 became 1088 and 3000 became 3008 (issue #3300). #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 00311afd33..009238d2bb 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -33,6 +33,7 @@ pub mod icons; pub mod lens_db; pub mod lightroom_import; pub mod links; +pub mod loupe_timing; pub mod menus; mod missing_sweep; mod model_setup; @@ -223,6 +224,9 @@ pub struct LightcraftApp { /// effects (which the global shortcut guard also hides). #[cfg(test)] pub(crate) library_passes: Vec, + /// Test-only: how many times background preparation was advanced (once per logic pass). + #[cfg(test)] + pub(crate) prep_ticks: u32, /// Test-only: a delay for the sidebar's Missing Photos count worker (a slow disk). Kept here, /// not in `ui`, because `ui.set` rebuilds `ui` and would drop it. #[cfg(test)] @@ -289,6 +293,14 @@ pub struct LightcraftApp { /// What the loupe drew last frame: photo and source ("render", "cached", "embedded", "small", /// "thumb", "none"). pub loupe_shown: Option<(lightcraft_catalog::PhotoId, &'static str)>, + /// When each photo stepped to in the loupe first showed (`ui.inspect` → `perf.loupeSteps`). + pub loupe_timing: loupe_timing::LoupeTiming, + /// The app-wide background preparation settings were handed from the saved app settings to + /// the session ([`Self::background_prep`]). + prep_synced: bool, + /// The loupe's look-ahead: the photo it was made for, the direction of travel (+1 / -1), the + /// catalog revision and the edge, so it is worked out again only when one of them changes. + pub(crate) look_ahead: panels::detail::LookAhead, /// The window render the loupe asked for last, by job key (see [`region`]); kept for the few /// windows whose textures can be on screen, and for the inspector. pub region_view: Option, @@ -314,6 +326,9 @@ pub struct LightcraftApp { pub import: Option, /// A folder scan in progress (feeds the import review). pub scan: Option, + /// Scans stopped without waiting for their workers: each channel is kept until its worker ends, so + /// the probes it took from the session come back. + pub(crate) scans_stopping: import::StoppingScans, /// Files that waited for a library and wait for the running import or Synchronize Folder too. pub waiting_import: panels::library_problem::WaitingImport, /// A Synchronize Folder scan in progress (feeds its dialog). @@ -350,6 +365,14 @@ pub struct LightcraftApp { /// Say once, when the GPU device has been tried, that no graphics processor was found /// ([`panels::notices::gpu_notice`]). The desktop app sets it; headless sessions and tests don't. pub gpu_notice: bool, + /// Tell the user once per session when the drive holding the preview cache runs low + /// ([`panels::notices::disk_space_notice`]). The desktop app sets it; headless sessions and tests + /// don't (their drive is whatever the machine has). + pub disk_space_notice: bool, + /// The low-disk notice's text while it is queued in [`LightcraftApp::notices`]: it is shown with a + /// button to Settings ▸ Performance. With the library it was raised for + /// ([`lightcraft_engine::Session::library_generation`]): another library open drops it. + pub(crate) disk_notice: Option<(u64, String)>, /// The memory budget setting last applied (MB, 0 = automatic). memory_applied: Option, /// The display profile setting last applied (`app.displayProfile`). diff --git a/crates/ui-egui/src/loupe_timing.rs b/crates/ui-egui/src/loupe_timing.rs new file mode 100644 index 0000000000..e0df23768f --- /dev/null +++ b/crates/ui-egui/src/loupe_timing.rs @@ -0,0 +1,269 @@ +//! How long the loupe takes to show each photo it is stepped to, measured on the frames it draws. +//! +//! Culling is stepping through photos, so the number that matters is the time from the step (the +//! first frame that draws the new photo) to the first frame that shows something of it, to the +//! first frame with a full-size picture (the camera's embedded JPEG or a cached render) and to the +//! first frame with LightCraft's own render. `ui.inspect` → `perf.loupeSteps` reports the latest +//! steps; `perf-scratch`-style drivers turn them into medians and p95 without the control +//! channel's own round trip in the numbers. + +use std::collections::VecDeque; + +use lightcraft_catalog::PhotoId; +use serde_json::{Value, json}; + +/// Steps kept for `ui.inspect`. +const KEEP: usize = 256; + +/// A photo left sooner than this (s) after it was stepped to was skipped past: the user is +/// holding an arrow key or tapping through. +pub const FAST_STEP_SECS: f64 = 0.25; +/// While stepping fast, how long a photo has to stay before its render is started (s). Until then +/// the loupe shows its camera JPEG or thumbnail, and the workers make the next ones' instead of +/// starting a full raw develop that the next step throws away. +pub const SETTLE_SECS: f64 = 0.12; + +/// One photo's way onto the screen (times in ms since the frame it was stepped to). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct StepTiming { + pub photo: PhotoId, + /// First frame that drew anything of the photo (often the grid thumbnail, magnified). + pub any_ms: Option, + /// What that was. + pub any_source: &'static str, + /// First frame with a full-size stand-in or better: the camera's JPEG, a cached render, the render. + pub full_ms: Option, + pub full_source: &'static str, + /// First frame with LightCraft's own render of the photo (`render` or `cached`). + pub sharp_ms: Option, + /// How long the photo stayed in the loupe (ms): a step taken before `sharp_ms` was skipped past. + pub dwell_ms: f64, +} + +impl StepTiming { + fn to_json(self) -> Value { + json!({ + "photo": self.photo.0, + "anyMs": self.any_ms, + "anySource": self.any_source, + "fullMs": self.full_ms, + "fullSource": self.full_source, + "sharpMs": self.sharp_ms, + "dwellMs": self.dwell_ms, + }) + } +} + +/// The loupe's step timings. +#[derive(Debug, Default)] +pub struct LoupeTiming { + current: Option<(f64, StepTiming)>, + done: VecDeque, + /// Steps finished since the app started (never lowered when old ones leave `done`): a driver's + /// cursor for the steps made after it looked. + total: u64, + /// Whether the loupe drew a photo in the frame being drawn ([`LoupeTiming::end_frame`]). + drawn: bool, + /// How long the photo before the current one stayed (ms), when the loupe stepped to it from + /// that photo; `None` when the loupe opened on it (from the grid, or coming back to the loupe). + stepped_from: Option, +} + +/// Sources that show the photo at full size: the camera's JPEG, a cached or a fresh render. +fn full_size(source: &str) -> bool { + matches!(source, "embedded" | "cached" | "render" | "preview") +} + +impl LoupeTiming { + /// The loupe drew `photo` from `source` (what [`crate::panels::detail`] reports in + /// `loupe_shown`) in the frame that started at `now` (s). + pub fn observe(&mut self, photo: PhotoId, source: &'static str, now: f64) { + self.drawn = true; + if self.current.as_ref().is_none_or(|(_, t)| t.photo != photo) { + let stepped = self.current.is_some(); + self.finish(now); + self.stepped_from = if stepped { self.done.back().map(|t| t.dwell_ms) } else { None }; + let t = StepTiming { photo, any_ms: None, any_source: "none", full_ms: None, full_source: "none", sharp_ms: None, dwell_ms: 0.0 }; + self.current = Some((now, t)); + } + let Some((since, t)) = self.current.as_mut() else { return }; + let ms = ((now - *since) * 1000.0).max(0.0); + if !ms.is_finite() { + return; + } + t.dwell_ms = ms; + if source != "none" && t.any_ms.is_none() { + t.any_ms = Some(ms); + t.any_source = source; + } + if full_size(source) && t.full_ms.is_none() { + t.full_ms = Some(ms); + t.full_source = source; + } + if matches!(source, "render" | "cached") && t.sharp_ms.is_none() { + t.sharp_ms = Some(ms); + } + } + + /// Whether the user is stepping fast and `photo` (being drawn in the frame at `now`) has not + /// stayed [`SETTLE_SECS`] yet: the photo before it was left within [`FAST_STEP_SECS`]. + pub fn settling(&self, photo: PhotoId, now: f64) -> bool { + let (since, prev_dwell) = match &self.current { + // the first frame of a step: `observe` has not seen this photo yet + Some((since, t)) if t.photo != photo => (now, (now - since) * 1000.0), + // (a photo the loupe opened on, not stepped to, never settles: the step that ended by + // leaving the loupe is not its predecessor) + Some((since, _)) => (*since, self.stepped_from.unwrap_or(f64::INFINITY)), + None => return false, + }; + prev_dwell.is_finite() && prev_dwell < FAST_STEP_SECS * 1000.0 && now - since < SETTLE_SECS + } + + /// The loupe is not showing a photo any more (the grid is up). + pub fn left(&mut self, now: f64) { + self.finish(now); + } + + /// A frame (started at `now`) was drawn: when the loupe drew no photo in it (the grid, Compare, Survey, + /// Reference, People or the slideshow is up), the photo it showed was left then, so time away from the + /// loupe never counts as time on that photo. + pub fn end_frame(&mut self, now: f64) { + if !std::mem::take(&mut self.drawn) { + self.left(now); + } + } + + fn finish(&mut self, now: f64) { + if let Some((since, mut t)) = self.current.take() { + let dwell = (now - since) * 1000.0; + if dwell.is_finite() { + t.dwell_ms = dwell.max(t.dwell_ms); + } + if self.done.len() >= KEEP { + self.done.pop_front(); + } + self.done.push_back(t); + self.total = self.total.saturating_add(1); + } + } + + /// The finished steps, oldest first (the latest [`KEEP`]), how many have finished in all, and the photo on screen now. + pub fn to_json(&self) -> Value { + json!({ + "steps": self.done.iter().map(|t| t.to_json()).collect::>(), + "total": self.total, + "current": self.current.as_ref().map(|(_, t)| t.to_json()), + }) + } + + #[cfg(test)] + fn steps(&self) -> Vec { + self.done.iter().copied().collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_step_records_when_each_kind_of_picture_first_showed() { + let mut l = LoupeTiming::default(); + l.observe(PhotoId(1), "none", 10.0); + l.observe(PhotoId(1), "thumb", 10.016); + l.observe(PhotoId(1), "embedded", 10.040); + l.observe(PhotoId(1), "embedded", 10.056); + l.observe(PhotoId(1), "render", 11.0); + l.observe(PhotoId(2), "thumb", 12.0); + let s = l.steps(); + assert_eq!(s.len(), 1); + let t = s[0]; + assert_eq!(t.photo, PhotoId(1)); + assert_eq!((t.any_source, t.full_source), ("thumb", "embedded")); + assert!((t.any_ms.unwrap() - 16.0).abs() < 0.01); + assert!((t.full_ms.unwrap() - 40.0).abs() < 0.01); + assert!((t.sharp_ms.unwrap() - 1000.0).abs() < 0.01); + assert!((t.dwell_ms - 2000.0).abs() < 0.01); + assert_eq!(l.to_json()["current"]["photo"], 2); + } + + #[test] + fn stepping_fast_holds_the_render_back_until_the_photo_stays() { + let mut l = LoupeTiming::default(); + // the first photo opened: no step before it + assert!(!l.settling(PhotoId(1), 0.0)); + l.observe(PhotoId(1), "embedded", 0.0); + // a deliberate step (the photo before stayed 2 s): render at once + assert!(!l.settling(PhotoId(2), 2.0)); + l.observe(PhotoId(2), "embedded", 2.0); + // held arrow: the photo before stayed 33 ms + assert!(l.settling(PhotoId(3), 2.033)); + l.observe(PhotoId(3), "thumb", 2.033); + assert!(l.settling(PhotoId(3), 2.1)); + // …until this one has stayed long enough + assert!(!l.settling(PhotoId(3), 2.033 + SETTLE_SECS + 0.001)); + } + + /// Leaving the loupe soon after a step and coming back on another photo is not a fast step + /// (CodeRabbit on #3077): the photo the loupe opens on renders at once, on every frame. + #[test] + fn coming_back_to_the_loupe_on_another_photo_is_not_a_fast_step() { + let mut l = LoupeTiming::default(); + l.observe(PhotoId(1), "embedded", 0.0); + l.end_frame(0.0); + // the grid is up after 100 ms on the photo + l.end_frame(0.1); + assert!(!l.settling(PhotoId(2), 0.2), "the first frame back"); + l.observe(PhotoId(2), "thumb", 0.2); + l.end_frame(0.2); + assert!(!l.settling(PhotoId(2), 0.25), "nor the frames after it"); + // a fast step from there still settles + l.observe(PhotoId(2), "embedded", 0.25); + assert!(l.settling(PhotoId(3), 0.3)); + l.observe(PhotoId(3), "thumb", 0.3); + assert!(l.settling(PhotoId(3), 0.35)); + } + + /// A frame without the loupe finishes the photo it showed: coming back to it later starts a new step, and + /// neither counts the time away (CodeRabbit on #3055). + #[test] + fn leaving_the_loupe_finishes_its_photo() { + let mut l = LoupeTiming::default(); + l.observe(PhotoId(1), "embedded", 10.0); + l.end_frame(10.0); + l.observe(PhotoId(1), "embedded", 10.5); + l.end_frame(10.5); + assert!(l.steps().is_empty(), "frames that draw the loupe keep the step open"); + // the grid is up from 11 s to 60 s + l.end_frame(11.0); + l.end_frame(60.0); + let s = l.steps(); + assert_eq!(s.len(), 1); + assert!((s[0].dwell_ms - 1000.0).abs() < 0.01, "dwell ends when the loupe went: {}", s[0].dwell_ms); + // back in the loupe on the same photo: a new step, timed from its return + l.observe(PhotoId(1), "render", 60.0); + l.observe(PhotoId(1), "render", 60.2); + l.end_frame(60.2); + assert_eq!(l.steps().len(), 1); + assert_eq!(l.to_json()["current"]["sharpMs"], 0.0); + assert!((l.to_json()["current"]["dwellMs"].as_f64().unwrap() - 200.0).abs() < 0.01); + } + + #[test] + fn a_photo_stepped_past_has_no_sharp_time_and_the_list_is_bounded() { + let mut l = LoupeTiming::default(); + for i in 0..(KEEP as u64 + 10) { + l.observe(PhotoId(i), "thumb", i as f64 * 0.033); + } + l.left(1000.0); + let s = l.steps(); + assert_eq!(s.len(), KEEP); + // the count of steps goes on past the kept list: a driver's cursor (CodeRabbit on #3077) + assert_eq!(l.to_json()["total"], KEEP as u64 + 10); + assert!(s.iter().all(|t| t.sharp_ms.is_none() && t.full_ms.is_none())); + // a non-finite clock never poisons the record + l.observe(PhotoId(9999), "render", f64::NAN); + l.observe(PhotoId(9999), "render", f64::INFINITY); + assert!(l.to_json().is_object()); + } +} diff --git a/crates/ui-egui/src/menus/menubar.rs b/crates/ui-egui/src/menus/menubar.rs index 672c7cbccc..b73729a913 100644 --- a/crates/ui-egui/src/menus/menubar.rs +++ b/crates/ui-egui/src/menus/menubar.rs @@ -465,17 +465,31 @@ fn live_label(app: &LightcraftApp, id: &str, label: &str) -> String { } /// The parameterized submenus. +/// The params of Build Standard-Sized Previews: automatic builds as big as the loupe on this screen shows photos +/// (the engine's standard size, once a loupe has been drawn); before that, in a fresh session, the standard +/// 2560 px, not the engine's 2048 px minimum, so a typical fit view needn't render again; a chosen limit is used as is. +pub(crate) fn standard_build_params(settings: &crate::state::AppSettings, loupe_edge: usize) -> Value { + match settings.preview_limit { + 0 if loupe_edge == 0 => json!({"size": "standard", "edge": settings.standard_preview_edge()}), + 0 => json!({"size": "standard"}), + edge => json!({"size": "standard", "edge": edge}), + } +} + pub(crate) fn expanded(app: &LightcraftApp, name: &str) -> Option> { let active = app.session.active().and_then(|id| app.session.catalog.photo(id).cloned()); let has = active.is_some(); Some(match name { "Previews" => { - let running = app.session.preview_build.as_ref().is_some_and(|b| !b.finished.load(std::sync::atomic::Ordering::Relaxed)); + // (the background preparation's build gives way to one asked for here) + let running = app.session.preview_build.as_ref().is_some_and(|b| b.running() && !b.background); + let stoppable = app.session.preview_build.as_ref().is_some_and(|b| b.running()); + let standard = standard_build_params(&app.ui.settings, app.session.loupe_edge); let scope = if app.session.selection.ids.len() > 1 { "Selected" } else { "Visible" }; vec![ item( "library.buildPreviews", - json!({"size": "standard", "edge": app.ui.settings.standard_preview_edge()}), + standard, crate::i18n::tr_format!("Build Standard-Sized Previews ({scope})", scope = crate::i18n::tr(scope)), None, !running, @@ -489,7 +503,7 @@ pub(crate) fn expanded(app: &LightcraftApp, name: &str) -> Option> !running, None, ), - item("library.cancelPreviews", Value::Null, "Stop Building Previews", None, running, None), + item("library.cancelPreviews", Value::Null, "Stop Building Previews", None, stoppable, None), MenuNode::Separator, // (read and written on a worker thread: the originals may be on a slow drive) item( diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 3e321304d2..534949ab00 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -18,6 +18,7 @@ mod crop; mod filmstrip; mod geometry; mod info; +mod look_ahead; mod masks; mod retouch; mod window; @@ -41,11 +42,15 @@ use geometry::{animated_rect, middle_pan}; pub(crate) use geometry::{fit_rect, fit_texture_rect, focus_pan, navigate_gesture, output_px, pan_image, snap_fit_rect, texture_side}; #[cfg(test)] use info::RENDERING_AFTER_SECS; +use info::camera_preview_badge; use info::{ FILTER_PILL_HEIGHT, FILTER_PILL_INSET, brief_info, filter_pill, filter_pill_shown, info_overlay, info_overlay_extent, label_badge_rect, preview_only_pill, quick_name, }; pub(crate) use info::{draw_focus_point, failed_pill, loupe_pill, rendering_overdue}; +use look_ahead::BEHIND; +pub use look_ahead::LookAhead; +pub(crate) use look_ahead::{Prepare, look_ahead}; use masks::{RegionContext, RegionEdit, color_range_pick, mask_overlay, region_overlay}; use retouch::{eye_overlay, remove_overlay}; pub(crate) use window::overlay_supports_window; @@ -229,11 +234,12 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // one axis only. A box that matches the source to rounding is rendered at exactly its size. let short = |e: usize, a: f32| ((e as f32 / a).round() as usize).max(1); let (rw, rh) = if aspect >= 1.0 { (want, short(want, aspect)) } else { (short(want, 1.0 / aspect), want) }; + note_loupe_edge(app, sizes.canvas_long, !interacting && !split && !split_view); // hover and before renders are stand-ins: the preview size is plenty and keeps them cheap let se = app.ui.settings.stand_in_edge(want, texture_side); let (sw, sh) = if aspect >= 1.0 { (se, short(se, aspect)) } else { (short(se, 1.0 / aspect), se) }; let ask = LoupeAsk { id, with_crop: !crop_tool, interacting, fit_px, overlay }; - request_main(app, ui, &ask, [rw, rh], plan.window_edge.is_none()); + let settling = request_main_or_settle(app, ui, &ask, [rw, rh], plan.window_edge.is_none(), now); // hovering a preset or profile: the photo with that look, shown instead of the loupe render // once it is ready (nothing is committed) let hover_key = request_hover(app, &ask, [sw, sh]); @@ -242,8 +248,14 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } // until the loupe has this photo: show its cached render / embedded preview / a thumbnail request_stand_in(app, id, want, !crop_tool); + if !interacting { + // (what Settings ▸ Performance lets this mode prepare ahead) + let prepare = prepare_ahead(app); + look_ahead(app, id, want.max(8), !crop_tool, prepare); + } let show_before = app.ui.before_after == BeforeAfter::Original || ui.input(|i| i.key_down(egui::Key::Backslash)); - if split || show_before || split_view { + // (the Before render waits for a settled photo like the loupe's own) + if !settling && (split || show_before || split_view) { request_before(app, &ask, [sw, sh]); } // zoomed past what the whole-frame render holds: also render the part on screen, at no more @@ -263,13 +275,16 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { look, holding: navigating || app.size_hold.holding(now), }; - let window_views = if window_ctx.frame_edge.is_some() { + // (stepping fast: no window is asked for until the photo stays, as for the frame above) + let window_views = if window_ctx.frame_edge.is_some() && !settling { let mode = ViewMode { split, show_before, split_view }; window_views(mode, &Views { img_rect, target_rect, before_img, before_target, areas: &areas, main_area, canvas }) } else { Vec::new() }; let windows = request_windows(app, &window_ctx, window_views); + let single = hover_key.is_none() && !split && !show_before && !split_view && !interacting; + let camera_full = request_camera_full(app, &photo, single && !windows.is_empty(), native_long.min(texture_side)); let p = ui.painter_at(canvas); let draw = |slot: Slot, r: Rect, clip: Rect| draw_slot(app, &p, id, ppp, slot, r, clip); // soft proofing: a paper-white surround and the proof's name, as Lightroom shows it @@ -306,16 +321,21 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { none_message(app, &p, &t, canvas, id); } } - app.loupe_shown = Some((id, shown)); + // a wipe shows the Before whole-frame render on its side of the line… let line = crate::region::wipe_line(img_rect, canvas); draw_wipe_before(app, &p, id, img_rect, line); + let camera_full_drawn = camera_full && draw_camera_full(app, &p, id, img_rect, display_aspect, window_cover(&windows)); // …and the window renders go over the whole-frame ones, all of them, where they belong in the // frame (clipped to their pane, or their side of the line) - for (v, view) in &windows { - // (holding `\` in a wipe shows the Before everywhere: it is the Before view alone then) - let mode = if show_before { BeforeAfter::Original } else { app.ui.before_after }; - let clip = crate::region::window_clip(mode, v.before, v.visible, canvas, img_rect); - draw_window(&p.with_clip_rect(clip), app, &window_ctx, v, view); + let drawn = draw_windows(app, &p, &window_ctx, &windows, [canvas, img_rect], (show_before, split)); + let shown = shown_after_windows(shown, camera_full_drawn, drawn); + app.loupe_shown = Some((id, shown)); + app.loupe_timing.observe(id, shown, now); + // the camera's own JPEG is on screen, not LightCraft's rendering of the raw: say so (once), so + // colour and tone are not judged on it (PERF-CULL-4; Lightroom Classic badges its embedded + // previews). Not over a window render, which is LightCraft's own. + if camera_jpeg_shown(app, &photo, shown, drawn) { + camera_preview_badge(ui, canvas, img_rect.intersect(canvas)); } if let Some((bg, g)) = before_badge { paint_badge(&p, bg, g); @@ -462,21 +482,69 @@ fn prefetch_neighbours(app: &mut LightcraftApp, id: PhotoId, main_area: Rect, pp return; } let ids = app.session.visible_cloned(); - if let Some(i) = ids.iter().position(|p| *p == id) { - let next = ids.get(i + 1).copied(); - let prev = i.checked_sub(1).and_then(|j| ids.get(j)).copied(); - for (n, nid) in [next, prev].into_iter().enumerate() { - let Some(nid) = nid else { continue }; - let Some(np) = app.session.catalog.photo(nid).cloned() else { continue }; - let nf = Frame::with_lens(np.width.max(1) as usize, np.height.max(1) as usize, &np.develop, with_crop, np.embedded_lens.as_ref()); - let na = nf.aspect() as f32; - let nr = fit_rect(main_area, na, app.ui.zoom, output_px(&nf), ppp, app.ui.pan); - let nw = app.ui.settings.prefetch_edge(nr.width().max(nr.height()) * ppp, output_px(&nf).into_iter().max().unwrap_or(1), texture_side); - let (w, h) = if na >= 1.0 { (nw, (nw as f32 / na) as usize) } else { ((nw as f32 * na) as usize, nw) }; - if let Some(job) = app.session.loupe_job(nid, w.max(8), h.max(8), with_crop) { - app.renderer.prefetch(Slot::Prefetch(n as u8), job, PREFETCH_PRIORITY); - } + let mode = prep_mode(app); + let prep = app.session.prep_settings(); + let ahead = prep.ahead(mode); + // editing: the next photos are decoded and kept, ready for their edits (their view render is not + // what is wanted, and a cached one would leave the photo undecoded) + let develop = mode == lightcraft_engine::prep::Mode::Develop; + let Some(i) = ids.iter().position(|p| *p == id).filter(|_| ahead > 0) else { return }; + let mut targets = app.look_ahead.targets_n(&ids, i, ahead, BEHIND); + if prep.scope(mode) == lightcraft_engine::prep::Scope::Marked { + targets.retain(|t| lightcraft_engine::prep::marked(&app.session, *t)); + } + // a few at a time, nearest first (the pool keeps workers free for the photo the user goes to) + let mut room = PREFETCH_AT_ONCE.saturating_sub(app.renderer.prefetches_pending()); + let todo: Vec<(usize, PhotoId)> = targets.into_iter().filter_map(|nid| ids.iter().position(|p| *p == nid).map(|at| (at, nid))).collect(); + for (at, nid) in todo { + if room == 0 { + break; } + let n = prefetch_slot(at); + let Some(mut job) = neighbour_job(app, nid, main_area, ppp, texture_side, with_crop) else { continue }; + if develop { + job.view_cache = None; + } + // (asked for already, in this slot: queued, running or made) + if app.renderer.prefetch_asked(n, job.key) { + continue; + } + room -= 1; + app.renderer.prefetch(n, job, PREFETCH_PRIORITY); + } +} + +/// The render a neighbour is prepared with: its loupe render at the size it will be drawn at. +fn neighbour_job( + app: &mut LightcraftApp, + nid: PhotoId, + main_area: Rect, + ppp: f32, + texture_side: usize, + with_crop: bool, +) -> Option { + let np = app.session.catalog.photo(nid)?; + let nf = Frame::with_lens(np.width.max(1) as usize, np.height.max(1) as usize, &np.develop, with_crop, np.embedded_lens.as_ref()); + let na = nf.aspect() as f32; + let nr = fit_rect(main_area, na, app.ui.zoom, output_px(&nf), ppp, app.ui.pan); + let nw = app.ui.settings.prefetch_edge(nr.width().max(nr.height()) * ppp, output_px(&nf).into_iter().max().unwrap_or(1), texture_side); + let (w, h) = if na >= 1.0 { (nw, (nw as f32 / na) as usize) } else { ((nw as f32 * na) as usize, nw) }; + app.session.loupe_job(nid, w.max(8), h.max(8), with_crop) +} + +/// What Settings ▸ Performance lets the mode the user is in prepare ahead. +fn prepare_ahead(app: &LightcraftApp) -> Prepare { + let mode = prep_mode(app); + let prep = app.session.prep_settings(); + Prepare::of(prep.ahead(mode), prep.scope(mode)) +} + +/// The most the loupe shows a whole photo at (the canvas's long side; a photo of another shape than +/// this one may fill it), noted while it shows one view fitted (`single`): standard previews are +/// built at least this big. +fn note_loupe_edge(app: &mut LightcraftApp, canvas_long: f32, single: bool) { + if single && matches!(app.ui.zoom, Zoom::Fit) && canvas_long.is_finite() && canvas_long >= 1.0 { + app.session.loupe_edge = canvas_long.ceil() as usize; } } @@ -733,10 +801,138 @@ struct LoupeAsk { overlay: lightcraft_pipeline::Overlay, } +/// Stepping fast (an arrow held down): the render waits until the photo stays, the camera JPEG or +/// thumbnail shows meanwhile, and a render queued for a photo already left is dropped. Otherwise +/// the loupe's own render is requested. Whether the photo is still settling. +fn request_main_or_settle(app: &mut LightcraftApp, ui: &egui::Ui, a: &LoupeAsk, size: [usize; 2], whole_draft: bool, now: f64) -> bool { + let settling = !a.interacting && app.loupe_timing.settling(a.id, now); + if !settling { + request_main(app, ui, a, size, whole_draft); + return false; + } + drop_unsettled(&mut app.renderer, a.id); + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(crate::loupe_timing::SETTLE_SECS / 2.0)); + true +} + +/// While the photo settles: drop the raw renders still queued for a photo the user is stepping +/// past (one already running finishes). Its whole-frame render unless that is on screen already, +/// the zoomed-in windows (a region render decodes the raw as much as the frame) and the Before +/// view, which is a raw render too. +pub(crate) fn drop_unsettled(renderer: &mut crate::render::Renderer, photo: PhotoId) { + if renderer.textures.get(&Slot::Main).is_none_or(|t| t.photo != photo) { + renderer.drop_queued(Slot::Main); + } + for slot in [Slot::Region, Slot::RegionBefore, Slot::Before] { + renderer.drop_queued(slot); + } +} + +/// Zoomed in on an unedited raw (`zoomed`: one view, window renders up): its camera JPEG at full +/// size under the window render, so a focus check doesn't wait for the raw (PERF-CULL-5; Capture +/// One's Cull view shows the embedded JPEG at 100 % too). Released when the view is not zoomed any +/// more (180 MB). Whether it is wanted. +fn request_camera_full(app: &mut LightcraftApp, photo: &lightcraft_catalog::Photo, zoomed: bool, edge: usize) -> bool { + let wanted = zoomed && app.session.embedded_thumb_is_final(photo); + if wanted { + if let Some(q) = app.session.embedded_full_job(photo.id, edge) { + app.renderer.request_quick(Slot::QuickFull, q, 98); + } + } else if app.renderer.textures.contains_key(&Slot::QuickFull) || app.renderer.is_pending(Slot::QuickFull) { + app.renderer.forget(Slot::QuickFull); + } + wanted +} + +/// The camera JPEG at full size, magnified like the whole-frame render, until the window is +/// there: only where the window will go (`cover`, see [`window_cover`]). A window capped smaller +/// than the view leaves strips around it, and those keep the developed whole-frame render rather +/// than an unlabelled camera JPEG (CodeRabbit on #3544). Whether it was drawn. +fn draw_camera_full(app: &LightcraftApp, p: &egui::Painter, id: PhotoId, img_rect: Rect, display_aspect: f32, cover: Option) -> bool { + let Some(cover) = cover else { return false }; + let Some(tex) = app.renderer.textures.get(&Slot::QuickFull).filter(|t| t.photo == id) else { return false }; + if !crate::region::same_aspect(tex.size[0].max(1) as f32 / tex.size[1].max(1) as f32, display_aspect) { + return false; + } + p.with_clip_rect(p.clip_rect().intersect(cover)).image(tex.id(), img_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + true +} + +/// Where on screen the requested window renders go (each its window's share of its view's drawn +/// rect), joined: `None` without any. +fn window_cover(windows: &[(WindowView, crate::region::RegionView)]) -> Option { + windows + .iter() + .map(|(v, w)| { + let (fw, fh) = (w.full.0.max(1) as f32, w.full.1.max(1) as f32); + let at = v.img.min + vec2(w.window.x as f32 / fw * v.img.width(), w.window.y as f32 / fh * v.img.height()); + Rect::from_min_size(at, vec2(w.window.w as f32 / fw * v.img.width(), w.window.h as f32 / fh * v.img.height())) + }) + .reduce(|a, b| a.union(b)) +} + +/// Which window renders [`draw_windows`] drew. +#[derive(Clone, Copy)] +struct WindowsDrawn { + /// Any of them. + any: bool, + /// The window of the view shown whole: the After side's in a split view, the Before's when + /// the Before is shown alone; what the timing and the source shown are about. Holding `\` + /// side by side or top/bottom keeps both panes, and the After pane is still the one shown. + shown: bool, +} + +/// Draw the window renders over the whole-frame ones, each where it belongs in the frame +/// (clipped to its pane, or its side of the line). +fn draw_windows( + app: &LightcraftApp, + p: &egui::Painter, + ctx: &WindowCtx, + windows: &[(WindowView, crate::region::RegionView)], + [canvas, img_rect]: [Rect; 2], + (show_before, split): (bool, bool), +) -> WindowsDrawn { + let mut out = WindowsDrawn { any: false, shown: false }; + // (holding `\` in a wipe shows the Before everywhere: it is the Before view alone then; side by + // side or top/bottom, both panes stay, and each window stays in its own) + let before_alone = show_before && !split; + for (v, view) in windows { + let mode = if before_alone { BeforeAfter::Original } else { app.ui.before_after }; + let clip = crate::region::window_clip(mode, v.before, v.visible, canvas, img_rect); + let drawn = draw_window(&p.with_clip_rect(clip), app, ctx, v, view); + out.any |= drawn; + out.shown |= drawn && (!v.before || before_alone); + } + out +} + +/// What is on screen once the window renders are drawn: the camera JPEG at full size stands in +/// for the whole-frame render until a window covers it, and a window rendered over a stand-in +/// (thumbnail or camera JPEG) before the whole frame is the raw's own render. +fn shown_after_windows(shown: &'static str, camera_full_drawn: bool, drawn: WindowsDrawn) -> &'static str { + if camera_full_drawn && !drawn.any { + "embedded" + } else if drawn.shown && !matches!(shown, "render" | "cached") { + "render" + } else { + shown + } +} + +/// Whether the camera's own JPEG is what is on screen (not under a window render). +fn camera_jpeg_shown(app: &LightcraftApp, photo: &lightcraft_catalog::Photo, shown: &str, drawn: WindowsDrawn) -> bool { + !drawn.any && (shown == "embedded" || (shown == "thumb" && app.session.embedded_thumb_is_final(photo))) +} + /// Request the loupe's own render at `[rw, rh]` (drafts during drags). fn request_main(app: &mut LightcraftApp, ui: &egui::Ui, a: &LoupeAsk, [rw, rh]: [usize; 2], whole_draft: bool) { let (id, interacting, fit_px, overlay) = (a.id, a.interacting, a.fit_px, a.overlay); - if let Some(job) = app.session.loupe_job(id, rw.max(8), rh.max(8), a.with_crop) { + if let Some(mut job) = app.session.loupe_job(id, rw.max(8), rh.max(8), a.with_crop) { + // editing: the photo is rendered from its source, which stays decoded for the first slider + // draft (a cached view render would show at once but leave the source unread until then) + if prep_mode(app) == lightcraft_engine::prep::Mode::Develop { + job.view_cache = None; + } let job = if interacting { job.draft() } else { job }; // at rest the render is shrunk to exactly the size it is drawn at with a Lanczos filter on // the worker, so the window draws it texel for texel instead of shrinking it with 2-tap @@ -745,6 +941,11 @@ fn request_main(app: &mut LightcraftApp, ui: &egui::Ui, a: &LoupeAsk, [rw, rh]: let job = job.with_overlay(overlay).with_proof(app.ui.soft_proof.then_some(app.ui.proof)); let job = job.with_hidden_grading(app.ui.grading_hidden_for(id)); app.renderer.request(Slot::Main, job, 100); + // the photo on screen comes first: background preparation waits while it is being made + // (only then: this runs every loupe frame, and a render already shown asks for nothing) + if app.renderer.is_pending(Slot::Main) { + signal_foreground(); + } // a drag's draft that renders in a few ms (GPU) is drawn in this frame, not the next (zoomed // in, what changes on screen is the window's draft) #[cfg(not(target_arch = "wasm32"))] @@ -757,6 +958,19 @@ fn request_main(app: &mut LightcraftApp, ui: &egui::Ui, a: &LoupeAsk, [rw, rh]: } } +/// Tell background preparation the loupe is waiting for its render ([`lightcraft_engine::prep::foreground`]). +fn signal_foreground() { + #[cfg(test)] + FOREGROUND_SIGNALS.with(|n| n.set(n.get() + 1)); + lightcraft_engine::prep::foreground(); +} + +#[cfg(test)] +thread_local! { + /// Tests: how often this thread's loupe told background preparation to wait. + pub(crate) static FOREGROUND_SIGNALS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Hovering a preset or profile: the photo with that look, shown instead of the loupe render once /// it is ready (nothing is committed). The key of its render and the label to show. fn request_hover(app: &mut LightcraftApp, a: &LoupeAsk, [sw, sh]: [usize; 2]) -> Option<(u64, String)> { @@ -887,6 +1101,26 @@ fn request_stand_in(app: &mut LightcraftApp, id: PhotoId, edge: usize, with_crop /// Neighbour prefetch: below on-screen thumbnails, above background thumbnail refreshes. const PREFETCH_PRIORITY: u32 = 4; +/// Photos prepared ahead at once (each render spreads over the cores already): the others wait, +/// so the photo the user steps to next finds a worker free. +const PREFETCH_AT_ONCE: usize = 2; +/// Prepared-ahead slots, by the photo's place in the view: a step keeps the photos still ahead in +/// the slots they have (nothing is asked for twice), and the jump to another part of the shoot +/// replaces what was waiting. +const PREFETCH_SLOTS: usize = 32; + +fn prefetch_slot(at: usize) -> Slot { + Slot::Prefetch((at % PREFETCH_SLOTS) as u8) +} + +/// What the user is doing, for the background preparation: editing (a tool panel open), else +/// culling a folder or browsing the library. +pub fn prep_mode(app: &LightcraftApp) -> lightcraft_engine::prep::Mode { + match app.ui.right { + RightPanel::Edit | RightPanel::Crop | RightPanel::Remove | RightPanel::Masking | RightPanel::RedEye => lightcraft_engine::prep::Mode::Develop, + _ => lightcraft_engine::prep::Mode::of(&app.session), + } +} /// Targeted adjustment tool: dragging up/down on the photo raises/lowers the tone-curve region or /// the colour-mixer bands under the press point (`develop.targeted`, one call per whole step, all @@ -1075,6 +1309,29 @@ pub(crate) fn click_zoom_and_pan(app: &mut LightcraftApp, resp: &egui::Response, #[cfg(test)] mod tests { + /// The camera JPEG goes only where the window render will: a window of the left half of the + /// frame covers the left half of the drawn photo, not the strips beside it. + #[test] + fn the_camera_jpeg_covers_only_where_the_window_goes() { + use super::{WindowView, window_cover}; + use crate::region::RegionView; + use egui::{Rect, pos2}; + use lightcraft_pipeline::PixelWindow; + assert_eq!(window_cover(&[]), None, "no window: no camera JPEG"); + let img = Rect::from_min_max(pos2(100.0, 50.0), pos2(700.0, 450.0)); + let v = WindowView { slot: crate::render::Slot::Region, before: false, img, target: img, visible: img }; + let w = RegionView { + photo: lightcraft_catalog::PhotoId(1), + before: false, + key: 1, + full: (6000, 4000), + window: PixelWindow { x: 0, y: 1000, w: 3000, h: 2000 }, + settings: 0, + }; + let r = window_cover(&[(v, w)]).unwrap(); + assert_eq!(r, Rect::from_min_max(pos2(100.0, 150.0), pos2(400.0, 350.0)), "the window's share of the drawn rect"); + } + /// The rotation pointer's arc bulges away from the side of the crop box it is on, and follows /// a box that is itself rotated. #[test] diff --git a/crates/ui-egui/src/panels/detail/info.rs b/crates/ui-egui/src/panels/detail/info.rs index da5ae1bed6..99a0fc1108 100644 --- a/crates/ui-egui/src/panels/detail/info.rs +++ b/crates/ui-egui/src/panels/detail/info.rs @@ -201,6 +201,24 @@ pub(super) fn filter_pill(app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Re } } +/// A small "Camera preview" label at the top right of the photo while the loupe shows the camera's +/// embedded JPEG (widget `loupe:cameraPreview`), with what that means on hover. +pub(super) fn camera_preview_badge(ui: &egui::Ui, canvas: Rect, over: Rect) { + let t = Tokens::get(ui.ctx()); + let p = ui.painter_at(canvas); + let text = crate::i18n::tr("Camera preview"); + let g = p.layout_no_wrap(text.to_string(), t.font(11.5), Color32::from_gray(225)); + let size = vec2(g.size().x + 16.0, 18.0); + let over = if over.is_positive() { over } else { canvas }; + let r = Rect::from_min_size(pos2(over.right() - size.x - 8.0, over.top() + 8.0), size); + p.rect_filled(r, 9.0, Color32::from_black_alpha(165)); + p.galley(pos2(r.left() + 8.0, r.center().y - g.size().y / 2.0), g, Color32::from_gray(225)); + register(ui, "loupe:cameraPreview", r); + let tip = crate::i18n::tr("The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo."); + let resp = ui.interact(r, egui::Id::unique("camera-preview-badge"), Sense::hover()).on_hover_text(tip); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{text}: {tip}"))); +} + /// A raw shown from its embedded JPEG (issue #10): a pill at the canvas' top centre saying so; /// hovering it explains (registered as `notice:previewOnly:loupe`). pub(super) fn preview_only_pill(ui: &mut egui::Ui, canvas: Rect, reason: &str) { diff --git a/crates/ui-egui/src/panels/detail/look_ahead.rs b/crates/ui-egui/src/panels/detail/look_ahead.rs new file mode 100644 index 0000000000..839bf9fe92 --- /dev/null +++ b/crates/ui-egui/src/panels/detail/look_ahead.rs @@ -0,0 +1,119 @@ +//! The loupe's look-ahead: stand-ins and thumbnails for the photos it is likely to be stepped to +//! next (PERF-CULL-2). + +use super::{LightcraftApp, PhotoId}; + +/// How many photos ahead (in the direction of travel) the loupe makes its stand-in for, and how +/// many behind (a step back is common when culling). +const AHEAD: usize = 5; +pub(super) const BEHIND: usize = 1; +/// The look-ahead's priority: below the loupe's own render (100), above everything else. +const AHEAD_PRIORITY: u32 = 96; +/// Thumbnails the loupe keeps while stepping (as many as the grid keeps), and how many photos on +/// either side of the open one stay when it trims them. +const MAX_LOUPE_THUMBS: usize = 600; +const KEEP_AROUND: usize = 64; +/// The thumbnail size the look-ahead asks for (the filmstrip's at 2x). +const AHEAD_THUMB_EDGE: usize = 256; + +/// What [`look_ahead`] last worked out (see `LightcraftApp::look_ahead`). +#[derive(Debug, Default)] +pub struct LookAhead { + /// The last photo the loupe showed, for the direction of travel. + last: Option, + /// +1 forward (the default), -1 backward. + dir: i8, + /// (photo, direction, catalog revision, visible list generation, edge, crop, which photos) the + /// requests were made for: a new source, filter or sort changes the neighbours without an edit, + /// and a change of the preparation settings what may be made. + made_for: Option<(PhotoId, i8, u64, u64, usize, bool, Prepare, u64)>, +} + +/// Which photos the look-ahead may prepare, from Settings ▸ Performance for what the user is doing +/// ([`lightcraft_engine::prep::Mode`]): none when its "Photos ahead" is 0 or it prepares only the photo +/// on screen, else the photos of its "which photos". +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Prepare { + Nothing, + Photos(lightcraft_engine::prep::Scope), +} + +impl Prepare { + /// For `ahead` photos ahead (the mode's count, 0 for the photo on screen only) of `scope`. + pub(crate) fn of(ahead: usize, scope: lightcraft_engine::prep::Scope) -> Prepare { + if ahead == 0 || scope == lightcraft_engine::prep::Scope::OnScreen { Prepare::Nothing } else { Prepare::Photos(scope) } + } +} + +impl LookAhead { + /// The photos to prepare around `id` at position `i` of `ids`: [`AHEAD`] in the direction of + /// travel, nearest first, then [`BEHIND`] the other way, of those `prepare` allows. (The + /// stand-ins are cheap: as many as [`AHEAD`] whatever the mode's count, which is for the full + /// renders made ahead.) + fn targets(&self, app: &LightcraftApp, ids: &[PhotoId], i: usize, prepare: Prepare) -> Vec { + let Prepare::Photos(scope) = prepare else { return Vec::new() }; + let mut targets = self.targets_n(ids, i, AHEAD, BEHIND); + if scope == lightcraft_engine::prep::Scope::Marked { + targets.retain(|t| lightcraft_engine::prep::marked(&app.session, *t)); + } + targets + } + + /// `ahead` photos in the direction of travel from position `i` of `ids`, nearest first, then + /// `behind` the other way. + pub fn targets_n(&self, ids: &[PhotoId], i: usize, ahead: usize, behind: usize) -> Vec { + let dir: isize = if self.dir < 0 { -1 } else { 1 }; + let at = |k: isize| i.checked_add_signed(k).and_then(|j| ids.get(j)).copied(); + let cap = |n: usize| n.min(ids.len()) as isize; + let ahead = (1..=cap(ahead)).filter_map(|k| at(dir * k)); + let behind = (1..=cap(behind)).filter_map(|k| at(-dir * k)); + ahead.chain(behind).collect() + } + + /// Whether the user is stepping backwards. + pub fn backward(&self) -> bool { + self.dir < 0 + } +} + +/// Culling: make the loupe's stand-ins (the camera JPEG of an unedited raw, or a cached render) of +/// the next photos in the direction of travel, so that a step shows the next one at once instead +/// of after reading and decoding it (see [`Slot::QuickAhead`]). +/// Only the photos `prepare` allows (Settings ▸ Performance): none at all asks for nothing, and drops the +/// stand-ins still queued. +pub(crate) fn look_ahead(app: &mut LightcraftApp, id: PhotoId, edge: usize, crop: bool, prepare: Prepare) { + let rev = app.session.catalog.revision; + if app.look_ahead.last != Some(id) { + let ids = app.session.visible_cloned(); + let pos = |p: PhotoId| ids.iter().position(|q| *q == p); + if let (Some(prev), Some(i)) = (app.look_ahead.last, pos(id)) + && let Some(j) = pos(prev) + { + app.look_ahead.dir = if j > i { -1 } else { 1 }; + } + app.look_ahead.last = Some(id); + } + let (visible_gen, ids) = app.session.visible_shared(); + // (the renderer's epoch: a reset drops the stand-ins made, which are then asked for again) + let want = (id, app.look_ahead.dir, rev, visible_gen, edge, crop, prepare, app.renderer.epoch()); + if app.look_ahead.made_for == Some(want) { + return; + } + app.look_ahead.made_for = Some(want); + let Some(i) = ids.iter().position(|p| *p == id) else { return }; + let targets = app.look_ahead.targets(app, &ids, i, prepare); + // stepping through a whole wedding in the loupe would keep every thumbnail it ever drew: keep + // the ones around the photo (what the filmstrip can show) once there are many + if app.renderer.thumb_textures() > MAX_LOUPE_THUMBS { + let keep = ids.iter().skip(i.saturating_sub(KEEP_AROUND)).take(2 * KEEP_AROUND + 1).copied().collect(); + app.renderer.evict_thumbs(&keep, MAX_LOUPE_THUMBS); + } + // their thumbnails first (a small embedded JPEG each, a few ms): something to show at once + // even when a step outruns the full-size previews, and in full screen, where no filmstrip + // asks for them + for &nid in &targets { + crate::panels::grid::request_thumb(app, nid, AHEAD_THUMB_EDGE, AHEAD_PRIORITY + 2); + } + let jobs = targets.into_iter().filter_map(|nid| app.session.quick_view_job(nid, edge, crop)).collect(); + app.renderer.look_ahead(jobs, AHEAD_PRIORITY); +} diff --git a/crates/ui-egui/src/panels/detail/window.rs b/crates/ui-egui/src/panels/detail/window.rs index 3351fab289..5dbaa55f4a 100644 --- a/crates/ui-egui/src/panels/detail/window.rs +++ b/crates/ui-egui/src/panels/detail/window.rs @@ -110,13 +110,14 @@ pub(super) fn request_window(app: &mut LightcraftApp, c: &WindowCtx, v: &WindowV /// Draw `v`'s window texture over the whole-frame render, if it is the one asked for (or, in a /// drag, an earlier draft of it). -pub(super) fn draw_window(p: &egui::Painter, app: &LightcraftApp, c: &WindowCtx, v: &WindowView, wanted: &crate::region::RegionView) { - let Some(tex) = app.renderer.textures.get(&v.slot).filter(|t| t.photo == c.id) else { return }; +pub(super) fn draw_window(p: &egui::Painter, app: &LightcraftApp, c: &WindowCtx, v: &WindowView, wanted: &crate::region::RegionView) -> bool { + let Some(tex) = app.renderer.textures.get(&v.slot).filter(|t| t.photo == c.id) else { return false }; let Some(tile) = app.region_tiles.get(&(v.before, tex.key)).filter(|t| t.is_current(c.id, wanted.full, wanted.settings, c.interacting)) else { - return; + return false; }; 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.id(), dst, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + true } diff --git a/crates/ui-egui/src/panels/notices.rs b/crates/ui-egui/src/panels/notices.rs index cc01701932..7a95a423e0 100644 --- a/crates/ui-egui/src/panels/notices.rs +++ b/crates/ui-egui/src/panels/notices.rs @@ -1,6 +1,7 @@ //! Things the user must not miss (issue #103): settings files that were damaged or unreadable when //! the library opened (and host warnings such as a damaged `ui.json`), and quitting while changes -//! are only in memory or while tasks that would be cut short are running (issue #345). +//! are only in memory or while tasks that would be cut short are running (issue #345). Also, once +//! per session, that the drive holding the preview cache is running low ([`disk_space_notice`]). use egui::{Align2, RichText, vec2}; @@ -8,11 +9,35 @@ use crate::theme::Tokens; use crate::widgets::WidgetHit; use crate::{LightcraftApp, QuitPrompt}; -/// Collect the library's settings-file warnings (each is shown once), and the no-GPU notice once the GPU device has -/// been tried. -pub fn logic(app: &mut LightcraftApp) { +/// Collect the library's settings-file warnings (each is shown once), the no-GPU notice once the GPU device has +/// been tried, and the low-disk notice (once per session). +pub fn logic(app: &mut LightcraftApp, ctx: &egui::Context) { let new = app.session.take_library_warnings(); app.notices.extend(new); + // a low-disk notice still queued from the library that was open before is not this one's + if let Some((generation, text)) = app.disk_notice.as_ref() + && *generation != app.session.library_generation() + { + let text = text.clone(); + app.notices.retain(|n| *n != text); + app.disk_notice = None; + } + if app.disk_space_notice { + // the cache grows with every thumbnail and preview, not only while previews are built: the + // engine reads the free space at most every few minutes (a clock check otherwise) + app.session.check_disk_space(false); + // an idle window still takes the read's answer and makes the next check: a pass soon while + // the read runs, and one when the next check is due + if !app.session.disk_space_alert_raised() { + let s = &app.session; + ctx.request_repaint_after(disk_check_wait(s.disk_space_read_running_for(), s.disk_space_next_check_in())); + } + if let Some(alert) = app.session.take_disk_space_alert() { + let text = disk_space_notice(&alert); + app.disk_notice = Some((app.session.library_generation(), text.clone())); + app.notices.push(text); + } + } use lightcraft_engine::gpu; if app.gpu_notice && app.gpu_applied == Some(true) && gpu::ready() { app.gpu_notice = false; @@ -22,6 +47,18 @@ pub fn logic(app: &mut LightcraftApp) { } } +/// How soon the notice logic looks again for the free-space read: soon while a read runs, less often once it has +/// run for a while (a drive that hangs must not keep an idle window drawing four times a second for good), and +/// when the next check is due (`next_in`: sooner after a read that couldn't start) when none runs. +fn disk_check_wait(running_for: Option, next_in: Option) -> std::time::Duration { + use std::time::Duration; + match running_for { + Some(d) if d < Duration::from_secs(5) => Duration::from_millis(250), + Some(_) => Duration::from_secs(5), + None => next_in.unwrap_or(lightcraft_engine::disk_space::CHECK_EVERY), + } +} + /// What to tell the user when GPU rendering is on (`enabled`) but the GPU could not be used for `reason`: only when no /// graphics adapter was found at all ("no GPU adapter among …", e.g. no Vulkan loader on Linux), which makes every /// render much slower without saying so. Nothing when it was turned off (preference, `LIGHTCRAFT_GPU`), a software @@ -40,6 +77,34 @@ pub fn gpu_notice(reason: Option<&str>, enabled: bool) -> Option { Some(text) } +/// Bytes in plain words: "12.3 GB", "850 MB" (binary units, as the cache size choices). +fn size_words(bytes: u64) -> String { + const GB: f64 = (1u64 << 30) as f64; + const MB: f64 = (1u64 << 20) as f64; + let b = bytes as f64; + if b >= 100.0 * GB { + format!("{:.0} GB", b / GB) + } else if b >= GB { + format!("{:.1} GB", b / GB) + } else { + format!("{:.0} MB", b / MB) + } +} + +/// What to tell the user when the drive holding the preview cache runs low: its free space, the +/// cache's size, and where a limit can be set (the notice's button opens Settings ▸ Performance). +pub fn disk_space_notice(alert: &lightcraft_engine::disk_space::LowDiskAlert) -> String { + let free = size_words(alert.space.available); + let total = size_words(alert.space.total); + let cache = size_words(alert.cache_bytes); + crate::i18n::tr_format!( + "The drive with this library's previews is almost full: {free} free of {total}. The preview cache takes {cache} and grows as the library does. To keep it smaller, set a size limit in Settings → Performance.", + free = free, + total = total, + cache = cache + ) +} + /// The quit prompt's text while `count` cancellable tasks run (`names` lists them). fn tasks_message(count: usize, names: &str) -> String { if count == 1 { @@ -113,6 +178,7 @@ enum Choice { QuitAnyway, Cancel, Ok, + Settings, } /// The prompt (quit or settings notice) that owns input this frame, if any. @@ -597,11 +663,27 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { app.quit_confirmed = true; app.ui.quit = true; } - Some(Choice::Cancel | Choice::Ok) | None => app.quit_prompt = None, + Some(Choice::Cancel | Choice::Ok | Choice::Settings) | None => app.quit_prompt = None, } return; } if let Some(text) = app.notices.first().cloned() { + let disk = app.disk_notice.as_ref().filter(|(_, t)| *t == text).map(|(generation, _)| *generation); + if let Some(generation) = disk { + // another library opened since `logic` ran this frame: the notice is the previous library's, + // and the next `logic` takes it away + if generation != app.session.library_generation() { + return; + } + let buttons = [("noticeSettings", "Open Performance Settings", Choice::Settings), ("noticeOk", "OK", Choice::Ok)]; + let Some(i) = window(ctx, "settings-notice", "Drive almost full", &text, &buttons, &mut app.notice_input) else { return }; + app.notices.remove(0); + app.disk_notice = None; + if buttons.get(i).is_some_and(|(_, _, choice)| *choice == Choice::Settings) { + app.ui.dialog = Some(crate::state::Dialog::Settings { tab: "performance".into() }); + } + return; + } let buttons = [("noticeOk", "OK", Choice::Ok)]; if window(ctx, "settings-notice", "Settings file problem", &text, &buttons, &mut app.notice_input).is_some() { app.notices.remove(0); @@ -613,6 +695,42 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { mod tests { use super::{PromptKey, gpu_notice, prepare_ui_pass, prompt_allows_event, prompt_key}; + /// A library switch between `logic` and drawing leaves the previous library's low-disk notice queued for + /// that frame: it is not drawn, nor answered (CodeRabbit on #3577). + #[test] + fn a_low_disk_notice_of_the_library_before_is_not_drawn() { + let ctx = egui::Context::default(); + let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services::default()); + let text = "Drive almost full".to_string(); + app.notices.push(text.clone()); + app.disk_notice = Some((app.session.library_generation().wrapping_add(1), text)); + // the prompt's first button pressed, as Enter would + app.notice_input.activate = Some(0); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert_eq!(app.notices.len(), 1, "not answered"); + assert!(app.ui.dialog.is_none(), "Settings didn't open"); + // the current library's: drawn and answered + app.disk_notice = app.disk_notice.take().map(|(_, t)| (app.session.library_generation(), t)); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert!(app.notices.is_empty(), "answered"); + } + + /// The window wakes four times a second while a free-space read runs, then every few seconds once it hangs + /// (CodeRabbit on #3577: it asked for 250 ms passes for as long as the drive hung). + #[test] + fn a_hanging_free_space_read_is_looked_at_less_often() { + use lightcraft_engine::disk_space::{CHECK_EVERY, RETRY_AFTER}; + use std::time::Duration; + assert_eq!(super::disk_check_wait(Some(Duration::ZERO), None), Duration::from_millis(250)); + assert_eq!(super::disk_check_wait(Some(Duration::from_secs(60)), None), Duration::from_secs(5)); + assert_eq!(super::disk_check_wait(Some(Duration::MAX), None), Duration::from_secs(5)); + assert_eq!(super::disk_check_wait(None, None), CHECK_EVERY); + // after a read that couldn't start: at the retry, not five minutes on (CodeRabbit on #3077) + assert_eq!(super::disk_check_wait(None, Some(RETRY_AFTER)), RETRY_AFTER); + } + /// The prompt barrier keeps its own keys and pointer input, drops text/wheel input, and drops /// the start/move half of a new touch gesture while keeping End/Cancel to clear egui's private /// touch state. No prompt means everything survives. diff --git a/crates/ui-egui/src/render.rs b/crates/ui-egui/src/render.rs index 9237e43066..e8c3a90788 100644 --- a/crates/ui-egui/src/render.rs +++ b/crates/ui-egui/src/render.rs @@ -45,6 +45,13 @@ pub enum Slot { /// Background preparation of a neighbouring photo (no texture: its decoded source and view /// render are cached by the engine). 0 = next, 1 = previous. Prefetch(u8), + /// The loupe's stand-in for a photo the user is likely to step to next (the camera JPEG of an + /// unedited raw, or a cached render), made ahead in the direction of travel so a step shows it + /// at once: [`Renderer::request_quick`] takes the texture over into [`Slot::Preview`]. + QuickAhead(u8), + /// The loupe zoomed in on an unedited raw: its camera JPEG at full size, drawn under the window + /// render until that arrives (a focus check at 100 % without waiting for the raw). + QuickFull, /// A variant thumbnail (profile / preset browsers), by its job key ([`Session::variant_job`]). /// Kept in a bounded LRU ([`VARIANT_TEXTURES`]). Variant(u64), @@ -242,6 +249,11 @@ pub const MAX_VARIANT_TEXTURES: usize = 800; /// Priority of variant thumbnail jobs: below on-screen grid thumbnails and the loupe. const VARIANT_PRIORITY: u32 = 6; +/// The camera-preview edge a loupe stand-in is made at (0: one that doesn't depend on the size). +fn quick_edge(job: &QuickJob) -> usize { + job.embedded.as_ref().map_or(0, |e| e.2) +} + pub struct Renderer { #[cfg(test)] pub(crate) thumb_jobs_built: usize, @@ -283,6 +295,14 @@ pub struct Renderer { pub completed: u64, /// Finished jobs thrown away because a newer request for their slot had replaced them. pub discarded: u64, + /// Photos given a grid thumbnail since start (a render replacing a stand-in isn't counted again): + /// unlike [`Renderer::thumb_textures`] it never goes down when old thumbnails are evicted (for + /// benchmarks). + pub thumbs_made: u64, + /// The photos [`Self::thumbs_made`] counted, by library (a hash of its folder) and id: a + /// thumbnail made again after eviction, or after going to another library and back, is the + /// same photo (photo ids are a library's own). Never cleared. + thumbs_counted: std::collections::HashSet<(u64, PhotoId)>, /// Keep a CPU copy of every texture so the UI can be rasterized headlessly (set when the app /// is driven by the control channel). pub keep_pixels: bool, @@ -290,6 +310,10 @@ pub struct Renderer { stages: HashMap>, /// Slot → key of the last quick job requested for it (each is tried once). quick_tried: HashMap, + /// The camera-preview edge each loupe stand-in ([`Slot::Preview`], [`Slot::QuickAhead`]) was + /// asked for (0: one that doesn't depend on the size): a stand-in made ahead for a smaller loupe + /// isn't taken over by a larger one. + quick_edge: HashMap, /// Jobs that failed (unreadable or missing file…), by slot and job key, with the error and /// the photo: not requested again until the key changes (an edit, another size) — the grid /// asks every frame. @@ -327,6 +351,9 @@ pub struct Renderer { native_frames: HashMap, } +/// How many [`Slot::QuickAhead`] stand-ins the loupe keeps ready. +pub const AHEAD_SLOTS: u8 = 6; + /// After this long without renders the GPU renderer's pool of recycled buffers is freed. #[cfg(not(target_arch = "wasm32"))] const IDLE_TRIM: std::time::Duration = std::time::Duration::from_secs(3); @@ -395,9 +422,12 @@ impl Renderer { last_main_ms: 0.0, completed: 0, discarded: 0, + thumbs_made: 0, + thumbs_counted: Default::default(), keep_pixels: false, stages: HashMap::new(), quick_tried: HashMap::new(), + quick_edge: HashMap::new(), failed: HashMap::new(), catalog_rev: 0, prefetched: HashMap::new(), @@ -731,7 +761,9 @@ impl Renderer { } } - /// Request a stand-in for `slot` (once per job key). + /// Request a stand-in for `slot` (once per job key). The loupe's [`Slot::Preview`] takes over + /// a stand-in already made ahead for the same photo ([`Slot::QuickAhead`]) instead of making it + /// again: shown in this frame when it is ready, or as soon as that job finishes. pub fn request_quick(&mut self, slot: Slot, mut job: QuickJob, priority: u32) { if self.quick_tried.get(&slot) == Some(&job.key) { if self.pending.get(&slot).is_some_and(|p| p.0 == job.key && p.1 != priority) { @@ -758,6 +790,14 @@ impl Renderer { return; } self.quick_tried.insert(slot, job.key); + if matches!(slot, Slot::Preview | Slot::QuickAhead(_)) { + self.quick_edge.insert(slot, quick_edge(&job)); + } + if slot == Slot::Preview && self.take_ahead(job.photo, job.key, quick_edge(&job)) { + self.pending.remove(&slot); + self.requests.remove(&slot); + return; + } let source = job .small .as_ref() @@ -772,7 +812,84 @@ impl Renderer { ); let key = job.key; let display = self.display.clone(); - self.pool.submit(slot, key, priority, Box::new(move || Self::run_for(|| job.run(), &display))); + let background = matches!(slot, Slot::QuickAhead(_)); + self.pool.submit( + slot, + key, + priority, + Box::new(move || { + let run = || if background { lightcraft_engine::memory::in_background(|| job.run()) } else { job.run() }; + Self::run_for(run, &display) + }), + ); + } + + /// Whether the stand-in asked for in `slot` is at least `edge` pixels (see `quick_edge`). + fn ahead_covers(&self, slot: Slot, edge: usize) -> bool { + self.quick_edge.get(&slot).copied().unwrap_or(0) >= edge + } + + /// Move a [`Slot::QuickAhead`] texture of `photo` made for `key`, at least `edge` pixels, into + /// [`Slot::Preview`]. + fn take_ahead(&mut self, photo: PhotoId, key: u64, edge: usize) -> bool { + let Some(slot) = self + .textures + .iter() + .find(|(s, t)| matches!(s, Slot::QuickAhead(_)) && t.photo == photo && t.key == key && self.ahead_covers(**s, edge)) + .map(|(s, _)| *s) + else { + return false; + }; + let Some(tex) = self.textures.remove(&slot) else { return false }; + self.quick_tried.remove(&slot); + self.textures.insert(Slot::Preview, tex); + true + } + + /// Make the loupe's stand-ins for the photos it is likely to be stepped to next (see + /// [`Slot::QuickAhead`]), most likely first: `jobs[0]` gets `priority`, each next one less. + /// A slot keeps a photo for as long as the photo stays wanted (made or being made, it is not + /// made again when the user steps and the photos shift places); slots holding photos not + /// wanted any more are freed for the new ones, and their queued jobs dropped. + pub fn look_ahead(&mut self, jobs: Vec, priority: u32) { + let slots: Vec = (0..AHEAD_SLOTS).map(Slot::QuickAhead).collect(); + let held = |r: &Self, s: Slot| r.textures.get(&s).map(|t| t.key).or_else(|| r.quick_tried.get(&s).copied()); + // (a stand-in asked for at a smaller loupe size isn't kept for a larger one) + let wanted: HashMap = jobs.iter().map(|j| (j.key, quick_edge(j))).collect(); + let mut free = Vec::new(); + for &s in &slots { + let key = held(self, s); + if key.is_none_or(|k| wanted.get(&k).is_none_or(|&edge| !self.ahead_covers(s, edge))) { + self.textures.remove(&s); + // a job already running: its result is thrown away when it arrives (not left as a + // hidden stand-in), unless the loupe is waiting for just that one (a step to the + // photo): then the slot stays reserved for it until it arrives + let preview_edge = self.quick_edge.get(&Slot::Preview).copied().unwrap_or(0); + let loupe_waits = + key.is_some_and(|k| self.pending.get(&Slot::Preview).is_some_and(|p| p.0 == k)) && self.ahead_covers(s, preview_edge); + if !self.drop_queued(s) && loupe_waits { + continue; + } + self.quick_tried.remove(&s); + self.pending.remove(&s); + self.requests.remove(&s); + free.push(s); + } + } + let have: HashMap = slots.iter().filter_map(|&s| held(self, s).map(|k| (k, s))).collect(); + let mut free = free.into_iter(); + for (rank, job) in jobs.into_iter().enumerate() { + let priority = priority.saturating_sub(rank as u32); + if let Some(&s) = have.get(&job.key) { + // kept: a job still queued moves to its new place in the order + if self.quick_tried.get(&s) == Some(&job.key) { + self.request_quick(s, job, priority); + } + continue; + } + let Some(slot) = free.next() else { break }; + self.request_quick(slot, job, priority); + } } /// Render a slideshow title screen into `slot` (once per screen key, like [`Self::request`]): @@ -817,6 +934,21 @@ impl Renderer { ); } + /// Prepared-ahead jobs ([`Slot::Prefetch`]) queued or running. + pub fn prefetches_pending(&self) -> usize { + self.pending.keys().filter(|s| matches!(s, Slot::Prefetch(_))).count() + } + + /// Prepared-ahead slots asked for since the renderer last forgot everything. + pub fn prefetch_slots_asked(&self) -> usize { + self.prefetched.keys().filter(|s| matches!(s, Slot::Prefetch(_))).count() + } + + /// Whether `slot` was last asked for the job of `key` (queued, running or done). + pub fn prefetch_asked(&self, slot: Slot, key: u64) -> bool { + self.prefetched.get(&slot) == Some(&key) + } + /// Drop the slideshow slides other than `keep`: their textures and their requests that have /// not started (a slide that is no longer near is not worth rendering). pub fn release_slides(&mut self, keep: &[lightcraft_engine::slideshow::Item]) { @@ -869,6 +1001,11 @@ impl Renderer { self.textures.retain(|_, t| t.native.is_none()); } + /// Changes when [`Self::forget_all`] drops every texture and request: what was asked for before is gone. + pub fn epoch(&self) -> u64 { + self.epoch + } + pub fn is_pending(&self, slot: Slot) -> bool { self.pending.contains_key(&slot) } @@ -1132,6 +1269,89 @@ impl Renderer { finished } + /// The slot a finished job goes to. Made ahead for the photo the loupe is now waiting for, it is + /// the loupe's stand-in (the loupe's own request for it, if one was started, is dropped when it + /// arrives); also when the loupe's own request failed and it still wants that photo: the + /// stand-in made ahead still shows, but never over another photo's request. + fn stand_in_slot(&mut self, slot: Slot, r: &RenderResult) -> Slot { + let waiting = self.pending.get(&Slot::Preview).is_some_and(|p| p.0 == r.key); + let failed = !self.pending.contains_key(&Slot::Preview) + && self.quick_tried.get(&Slot::Preview) == Some(&r.key) + && self.failed.get(&Slot::Preview).is_some_and(|f| f.0 == r.key && f.3 == r.photo); + if !matches!(slot, Slot::QuickAhead(_)) + || r.rendered.is_err() + || !(waiting || failed) + || !self.ahead_covers(slot, self.quick_edge.get(&Slot::Preview).copied().unwrap_or(0)) + { + return slot; + } + self.pending.remove(&Slot::Preview); + self.requests.remove(&Slot::Preview); + self.quick_tried.remove(&slot); + Slot::Preview + } + + /// A superseded result an interactive view still takes: a draft newer than what it shows. + fn is_newer_draft(&self, slot: Slot, r: &RenderResult) -> bool { + slot.is_view() + && self.requests.contains_key(&slot) + && r.request_id >= self.epoch + && self.shown_ids.get(&slot).is_none_or(|shown| r.request_id > *shown) + && r.rendered.is_ok() + } + + /// Convert `r` to the display profile in use; whether that changed it. + fn convert_for_display(&self, r: &mut RenderResult) -> bool { + let Some(d) = &self.display else { return false }; + let before = r.display; + lightcraft_engine::display::present(r, d); + r.display != before + } + + /// Show a render that stayed on the GPU (`r.frame`) in `slot`; whether it could be. When it + /// can't, views come back as pixels from then on. + fn show_frame(&mut self, ctx: &egui::Context, slot: Slot, r: &RenderResult, look: Option<(u64, bool)>, ms: f64) -> bool { + let (Some(frame), Ok(rendered)) = (r.frame.as_ref(), r.rendered.as_ref()) else { return false }; + 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; + return false; + }; + 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; + } + true + } + /// 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); @@ -1152,12 +1372,7 @@ impl Renderer { // shows, and the source it decoded: a drag supersedes every request before it // finishes, and a source thrown away with them is decoded again for every tick. let (source, look) = if self.requests.get(&slot).map(|request| request.id) != Some(r.request_id) { - let newer_draft = slot.is_view() - && self.requests.contains_key(&slot) - && r.request_id >= self.epoch - && self.shown_ids.get(&slot).is_none_or(|shown| r.request_id > *shown) - && r.rendered.is_ok(); - if !newer_draft { + if !self.is_newer_draft(slot, &r) { self.discarded += 1; let replaced = self.requests.contains_key(&slot); self.decided(|| { @@ -1180,66 +1395,16 @@ impl Renderer { self.shown_ids.insert(slot, r.request_id); } // (results from an offload, which doesn't know the display profile: converted here) - if let Some(d) = &self.display { - let before = r.display; - lightcraft_engine::display::present(&mut r, d); - if r.display != before { - color = None; // converted after the worker made its texture pixels - } + if self.convert_for_display(&mut r) { + color = None; // converted after the worker made its texture pixels } if self.pending.get(&slot).is_some_and(|p| p.0 == r.key) { self.pending.remove(&slot); } + slot = self.stand_in_slot(slot, &r); // 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; + if r.frame.is_some() && r.rendered.is_ok() { + changed |= self.show_frame(ctx, slot, &r, look, ms); continue; } let rendered = match r.rendered { @@ -1259,7 +1424,7 @@ impl Renderer { x } Err(e) => { - if !matches!(slot, Slot::Prefetch(_)) { + if !matches!(slot, Slot::Prefetch(_) | Slot::QuickAhead(_)) { let message = render_failure_message(slot, r.photo, source.as_ref(), &e); #[cfg(test)] self.failure_messages.push(message.clone()); @@ -1291,6 +1456,11 @@ impl Renderer { slot = Slot::Thumb(id); } } + // (a photo's first thumbnail: not a render replacing its stand-in, nor one made again) + let first_thumb = match slot { + Slot::Thumb(id) | Slot::ThumbQuick(id) => self.thumbs_counted.insert((library_key(session), id)), + _ => false, + }; if let Slot::Thumb(id) = slot { self.textures.remove(&Slot::ThumbQuick(id)); } @@ -1332,7 +1502,11 @@ impl Renderer { ); } } - if slot == Slot::Main { + if first_thumb { + self.thumbs_made += 1; + } + // (a preview taken from the cache says nothing about how long a render takes) + if slot == Slot::Main && r.quick.is_none() { self.last_main_ms = ms; } changed = true; @@ -1413,6 +1587,29 @@ impl Renderer { .collect() } + /// Forget everything about `slot`: its texture, its queued job, and that its stand-in was asked + /// for (so asking again makes it again). + pub fn forget(&mut self, slot: Slot) { + self.drop_queued(slot); + self.pending.remove(&slot); + self.requests.remove(&slot); + self.quick_tried.remove(&slot); + self.release(slot); + } + + /// Drop `slot`'s job if it is still queued (a running one finishes). Returns whether one was. + pub fn drop_queued(&mut self, slot: Slot) -> bool { + let dropped = self.pool.reprioritize(|s, p| if *s == slot { None } else { Some(p) }); + let before = self.queue.len(); + self.queue.retain(|q| q.slot != slot); + let any = !dropped.is_empty() || self.queue.len() != before; + if any { + self.pending.remove(&slot); + self.requests.remove(&slot); + } + any + } + /// Drop the import review thumbnails (a new review, or the dialog closed). pub fn forget_imports(&mut self) { self.retain_imports(&Default::default()); @@ -1773,3 +1970,13 @@ mod color_image_tests { assert!(color_image(&img).pixels.is_empty()); } } + +/// Which library `session` has open, for [`Renderer::thumbs_made`]: a hash of its folder (the same +/// library opened again is the same), 0 with none. +fn library_key(session: &Session) -> u64 { + use std::hash::{Hash, Hasher}; + let Some(lib) = session.library.as_ref() else { return 0 }; + let mut h = std::collections::hash_map::DefaultHasher::new(); + lib.dir.hash(&mut h); + h.finish() +} diff --git a/crates/ui-egui/src/render/thumbnail_tests.rs b/crates/ui-egui/src/render/thumbnail_tests.rs index 7a2cb1a6a9..b2a87e6522 100644 --- a/crates/ui-egui/src/render/thumbnail_tests.rs +++ b/crates/ui-egui/src/render/thumbnail_tests.rs @@ -1541,3 +1541,407 @@ fn undo_to_embedded_thumb_rejects_late_full_render() { assert_eq!(quick.pixels.as_ref().unwrap().pixels, pixels_a); assert!(!app.renderer.is_pending(full_slot)); } + +/// PERF-CULL-2: the loupe's stand-ins made ahead are taken over at the step (no job, the texture +/// at once), a photo still wanted keeps its slot as the photos shift, and a step to a photo whose +/// stand-in is still being made shows it when it arrives. +#[test] +fn a_step_takes_over_the_camera_preview_made_ahead() { + let gate = Arc::new(std::sync::Mutex::new(())); + let mut s = Session::new(); + let g = gate.clone(); + s.media.preview_loader = Some(Arc::new(move |_: &str, _| { + drop(g.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); + Some(lightcraft_raster::Rgba8 { width: 4, height: 4, data: vec![[200, 100, 50, 255]; 16] }) + })); + let raw = |id: u64| { + let mut p = Photo::new(PhotoId(id), Source::File { path: format!("r{id}.cr3") }, &format!("r{id}.cr3"), "CR3", 6000, 4000, "2026-01-01"); + p.kind = lightcraft_catalog::MediaKind::Raw; + p.develop = Arc::new(p.camera_defaults()); + p + }; + let (mut app, _, ctx) = fixture_with(s, raw(1)); + for id in 2..=4 { + app.session.catalog.apply(Op::AddPhoto { photo: Box::new(raw(id)) }).unwrap(); + } + let job = |app: &mut crate::LightcraftApp, id: u64| app.session.quick_view_job(PhotoId(id), 64, true).unwrap(); + let wait = |app: &mut crate::LightcraftApp, done: &dyn Fn(&Renderer) -> bool| { + let t0 = std::time::Instant::now(); + while !done(&app.renderer) { + assert!(t0.elapsed() < std::time::Duration::from_secs(20), "the stand-ins never arrived"); + std::thread::sleep(std::time::Duration::from_millis(5)); + app.renderer.poll(&ctx, &mut app.session); + } + }; + let ahead_of = |r: &Renderer, id: u64| r.textures.iter().any(|(s, t)| matches!(s, Slot::QuickAhead(_)) && t.photo == PhotoId(id)); + let jobs = vec![job(&mut app, 2), job(&mut app, 3)]; + app.renderer.look_ahead(jobs, 96); + wait(&mut app, &|r| ahead_of(r, 2) && ahead_of(r, 3)); + // the step to photo 2: its stand-in is the loupe's at once, nothing is made again + let q = job(&mut app, 2); + app.renderer.request_quick(Slot::Preview, q, 110); + assert!(!app.renderer.is_pending(Slot::Preview)); + assert_eq!(app.renderer.textures.get(&Slot::Preview).map(|t| t.photo), Some(PhotoId(2))); + assert!(!ahead_of(&app.renderer, 2)); + // the next look-ahead (3 and 4): 3 keeps its slot and is not made again + let held = gate.lock().unwrap(); + let jobs = vec![job(&mut app, 3), job(&mut app, 4)]; + app.renderer.look_ahead(jobs, 96); + assert!(ahead_of(&app.renderer, 3), "a photo still wanted keeps what was made for it"); + let pending_ahead: Vec = app.renderer.pending.keys().copied().filter(|s| matches!(s, Slot::QuickAhead(_))).collect(); + assert_eq!(pending_ahead.len(), 1, "only photo 4 is being made: {pending_ahead:?}"); + // the step to photo 4 while its stand-in is still being made: shown when it arrives + let q = job(&mut app, 4); + app.renderer.request_quick(Slot::Preview, q, 110); + drop(held); + wait(&mut app, &|r| r.textures.get(&Slot::Preview).is_some_and(|t| t.photo == PhotoId(4)) && !r.is_pending(Slot::Preview)); + wait(&mut app, &|r| !r.pending.keys().any(|s| matches!(s, Slot::QuickAhead(_) | Slot::Preview))); + assert_eq!(app.renderer.textures.get(&Slot::Preview).map(|t| t.photo), Some(PhotoId(4))); +} + +/// A loupe with unedited raws 1..=n whose camera previews are read at once, on a renderer +/// that runs nothing until asked (`run_inline`). +fn raw_loupe(n: u64) -> (crate::LightcraftApp, egui::Context) { + let mut s = Session::new(); + s.media.preview_loader = Some(Arc::new(|_: &str, _| Some(lightcraft_raster::Rgba8 { width: 4, height: 4, data: vec![[200, 100, 50, 255]; 16] }))); + let raw = |id: u64| { + let mut p = Photo::new(PhotoId(id), Source::File { path: format!("r{id}.cr3") }, &format!("r{id}.cr3"), "CR3", 6000, 4000, "2026-01-01"); + p.kind = lightcraft_catalog::MediaKind::Raw; + p.develop = Arc::new(p.camera_defaults()); + p + }; + let (mut app, _, ctx) = fixture_with(s, raw(1)); + for id in 2..=n { + app.session.catalog.apply(Op::AddPhoto { photo: Box::new(raw(id)) }).unwrap(); + } + app.renderer.pool = JobPool::new(0); + (app, ctx) +} + +/// The look-ahead with every photo allowed (the default preparation settings). +const ALL: crate::panels::detail::Prepare = crate::panels::detail::Prepare::Photos(lightcraft_engine::prep::Scope::All); + +fn quick(app: &mut crate::LightcraftApp, id: u64, edge: usize) -> QuickJob { + app.session.quick_view_job(PhotoId(id), edge, true).unwrap() +} + +/// The loupe's stand-ins ahead follow Settings ▸ Performance: none when the mode prepares only the photo on +/// screen (or none ahead), and the ones still queued are dropped then; only marked photos in the marked scope +/// (CodeRabbit on #3077). +#[test] +fn the_look_ahead_prepares_only_what_the_preparation_settings_allow() { + use crate::panels::detail::{Prepare, look_ahead}; + use lightcraft_engine::prep::Scope; + let (mut app, _ctx) = raw_loupe(4); + app.session.sort.key = lightcraft_catalog::SortKey::FileName; + app.session.sort.ascending = true; + // (asked for: queued, running or made) + let ahead = |r: &Renderer| r.quick_tried.keys().filter(|s| matches!(s, Slot::QuickAhead(_))).count(); + look_ahead(&mut app, PhotoId(1), 64, true, Prepare::of(5, Scope::All)); + assert_eq!(ahead(&app.renderer), 3, "photos 2 to 4 are made ahead"); + // the photo on screen only: nothing ahead, and what was queued goes + look_ahead(&mut app, PhotoId(1), 64, true, Prepare::of(0, Scope::OnScreen)); + assert_eq!(ahead(&app.renderer), 0, "nothing is made ahead for the photo on screen only"); + look_ahead(&mut app, PhotoId(1), 64, true, Prepare::of(0, Scope::All)); + assert_eq!(ahead(&app.renderer), 0, "nor with no photos ahead"); + // picks, rated and labelled: only those + app.session.execute("library.select", &serde_json::json!({"ids": [3]})).unwrap(); + app.session.execute("photo.rate", &serde_json::json!({"rating": 2})).unwrap(); + look_ahead(&mut app, PhotoId(1), 64, true, Prepare::of(5, Scope::Marked)); + let k3 = quick(&mut app, 3, 64).key; + let queued: Vec = app.renderer.quick_tried.iter().filter(|(s, _)| matches!(s, Slot::QuickAhead(_))).map(|(_, k)| *k).collect(); + assert_eq!(queued, vec![k3], "only the rated photo is made ahead"); +} + +/// A renderer reset (`forget_all`: a library switch, a colour-management change) drops the stand-ins asked +/// for ahead; the same photo asks for them again (CodeRabbit on #3577: the look-ahead took them for made). +#[test] +fn the_look_ahead_asks_again_after_a_renderer_reset() { + use crate::panels::detail::look_ahead; + let (mut app, _ctx) = raw_loupe(4); + let ahead = |r: &Renderer| r.quick_tried.keys().filter(|s| matches!(s, Slot::QuickAhead(_))).count(); + look_ahead(&mut app, PhotoId(1), 64, true, ALL); + let asked = ahead(&app.renderer); + assert!(asked > 0); + app.renderer.forget_all(); + assert_eq!(ahead(&app.renderer), 0); + look_ahead(&mut app, PhotoId(1), 64, true, ALL); + assert_eq!(ahead(&app.renderer), asked, "asked for again"); +} + +/// A stand-in still queued ahead whose photo moves up in the order (the user stepped) is +/// queued at its new place, not left behind photos now further away (CodeRabbit on #3055). +#[test] +fn a_kept_ahead_job_moves_to_its_new_place_in_the_order() { + let (mut app, _ctx) = raw_loupe(3); + let jobs = vec![quick(&mut app, 2, 64), quick(&mut app, 3, 64)]; + let (k2, k3) = (jobs[0].key, jobs[1].key); + app.renderer.look_ahead(jobs, 96); + let priority_of = |r: &Renderer, key: u64| { + let slot = r.quick_tried.iter().find(|(s, k)| matches!(s, Slot::QuickAhead(_)) && **k == key).map(|(s, _)| *s).unwrap(); + r.pending[&slot].1 + }; + assert_eq!((priority_of(&app.renderer, k2), priority_of(&app.renderer, k3)), (96, 95)); + let jobs = vec![quick(&mut app, 3, 64), quick(&mut app, 2, 64)]; + app.renderer.look_ahead(jobs, 96); + assert_eq!((priority_of(&app.renderer, k3), priority_of(&app.renderer, k2)), (96, 95)); + assert_eq!(app.renderer.pool.queued(), 2, "nothing is queued twice"); +} + +/// A stand-in made ahead that is no longer wanted while it is being made is thrown away when it +/// arrives, not kept as a hidden texture (CodeRabbit on #3077); one the loupe waits for is kept. +#[test] +fn an_ahead_stand_in_no_longer_wanted_is_dropped_when_it_arrives() { + let gate = Arc::new(std::sync::Mutex::new(())); + let mut s = Session::new(); + let g = gate.clone(); + s.media.preview_loader = Some(Arc::new(move |_: &str, _| { + drop(g.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); + Some(lightcraft_raster::Rgba8 { width: 4, height: 4, data: vec![[200, 100, 50, 255]; 16] }) + })); + let raw = |id: u64| { + let mut p = Photo::new(PhotoId(id), Source::File { path: format!("r{id}.cr3") }, &format!("r{id}.cr3"), "CR3", 6000, 4000, "2026-01-01"); + p.kind = lightcraft_catalog::MediaKind::Raw; + p.develop = Arc::new(p.camera_defaults()); + p + }; + let (mut app, _, ctx) = fixture_with(s, raw(1)); + app.session.catalog.apply(Op::AddPhoto { photo: Box::new(raw(2)) }).unwrap(); + let wait = |app: &mut crate::LightcraftApp, done: &dyn Fn(&Renderer) -> bool, what: &str| { + let t0 = std::time::Instant::now(); + while !done(&app.renderer) { + assert!(t0.elapsed() < std::time::Duration::from_secs(20), "{what}"); + std::thread::sleep(std::time::Duration::from_millis(5)); + app.renderer.poll(&ctx, &mut app.session); + } + }; + let any_ahead = |r: &Renderer| r.textures.keys().any(|s| matches!(s, Slot::QuickAhead(_))); + let held = gate.lock().unwrap(); + let job = quick(&mut app, 2, 64); + app.renderer.look_ahead(vec![job], 96); + wait(&mut app, &|r| r.pool.queued() == 0, "the stand-in never started"); + // not wanted any more (the user went elsewhere) while it is being made + app.renderer.look_ahead(Vec::new(), 96); + assert!(!app.renderer.pending.keys().any(|s| matches!(s, Slot::QuickAhead(_)))); + let done = app.renderer.completed; + drop(held); + wait(&mut app, &|r| r.completed > done, "the stand-in never finished"); + assert!(!any_ahead(&app.renderer), "a stand-in nobody wants is left as a hidden texture"); + // the step to photo 2 while its stand-in is being made: the loupe takes it when it arrives + let held = gate.lock().unwrap(); + let job = quick(&mut app, 2, 32); + app.renderer.look_ahead(vec![job], 96); + wait(&mut app, &|r| r.pool.queued() == 0, "the stand-in never started"); + let job = quick(&mut app, 2, 32); + app.renderer.request_quick(Slot::Preview, job, 110); + app.renderer.look_ahead(Vec::new(), 96); + drop(held); + wait(&mut app, &|r| r.textures.get(&Slot::Preview).is_some_and(|t| t.photo == PhotoId(2)), "the loupe never got its stand-in"); +} + +/// The loupe waits for a stand-in made ahead that is still being made when the next look-ahead +/// brings new photos: its slot stays reserved, so the result still reaches the loupe (CodeRabbit +/// on #3055 and #3080). +#[test] +fn a_running_stand_in_the_loupe_waits_for_keeps_its_slot() { + // the first camera preview read (photo 2's, made ahead) waits for `first`, every later one + // for `later` + let first = Arc::new(std::sync::Mutex::new(())); + let later = Arc::new(std::sync::Mutex::new(())); + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let mut s = Session::new(); + let (f, l, c) = (first.clone(), later.clone(), calls.clone()); + s.media.preview_loader = Some(Arc::new(move |_: &str, _| { + let gate = if c.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 { &f } else { &l }; + drop(gate.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); + Some(lightcraft_raster::Rgba8 { width: 4, height: 4, data: vec![[200, 100, 50, 255]; 16] }) + })); + let raw = |id: u64| { + let mut p = Photo::new(PhotoId(id), Source::File { path: format!("r{id}.cr3") }, &format!("r{id}.cr3"), "CR3", 6000, 4000, "2026-01-01"); + p.kind = lightcraft_catalog::MediaKind::Raw; + p.develop = Arc::new(p.camera_defaults()); + p + }; + let (mut app, _, ctx) = fixture_with(s, raw(1)); + for id in 2..=3 { + app.session.catalog.apply(Op::AddPhoto { photo: Box::new(raw(id)) }).unwrap(); + } + app.renderer.pool = JobPool::new(4); + let wait = |app: &mut crate::LightcraftApp, done: &dyn Fn(&Renderer) -> bool, what: &str| { + let t0 = std::time::Instant::now(); + while !done(&app.renderer) { + assert!(t0.elapsed() < std::time::Duration::from_secs(20), "{what}"); + std::thread::sleep(std::time::Duration::from_millis(5)); + app.renderer.poll(&ctx, &mut app.session); + } + }; + let held_first = first.lock().unwrap(); + let held_later = later.lock().unwrap(); + let job = quick(&mut app, 2, 64); + app.renderer.look_ahead(vec![job], 96); + wait(&mut app, &|r| r.pool.queued() == 0, "photo 2's stand-in never started"); + wait(&mut app, &|_| calls.load(std::sync::atomic::Ordering::SeqCst) == 1, "photo 2's preview was never read"); + // the step to photo 2, then the next look-ahead, for photos 3 and 1 + let job = quick(&mut app, 2, 64); + app.renderer.request_quick(Slot::Preview, job, 110); + assert!(app.renderer.is_pending(Slot::Preview)); + let jobs = vec![quick(&mut app, 3, 64), quick(&mut app, 1, 64)]; + app.renderer.look_ahead(jobs, 96); + let done = app.renderer.completed; + drop(held_first); + wait(&mut app, &|r| r.completed > done, "photo 2's stand-in never finished"); + assert_eq!(app.renderer.textures.get(&Slot::Preview).map(|t| t.photo), Some(PhotoId(2)), "the loupe lost the stand-in it waited for"); + drop(held_later); + wait(&mut app, &|r| r.pool.queued() == 0 && !r.pending.keys().any(|s| matches!(s, Slot::QuickAhead(_))), "the look-ahead never finished"); +} + +/// The stand-in made ahead still shows when the loupe's own request for it failed first +/// (CodeRabbit on #3055). +#[test] +fn a_stand_in_made_ahead_shows_after_the_loupes_own_request_failed() { + let (mut app, ctx) = raw_loupe(2); + let job = quick(&mut app, 2, 64); + let key = job.key; + app.renderer.look_ahead(vec![job], 96); + let job = quick(&mut app, 2, 64); + app.renderer.request_quick(Slot::Preview, job, 110); + assert!(app.renderer.is_pending(Slot::Preview)); + // the loupe's request fails (its job never runs) + assert!(app.renderer.drop_queued(Slot::Preview)); + app.renderer.failed.insert(Slot::Preview, (key, "unreadable".into(), 0, PhotoId(2))); + assert_eq!(app.renderer.pool.run_inline(1), 1); + app.renderer.poll(&ctx, &mut app.session); + assert_eq!(app.renderer.textures.get(&Slot::Preview).map(|t| t.photo), Some(PhotoId(2))); + assert!(!app.renderer.failed.contains_key(&Slot::Preview)); + // the user has stepped on to photo 3 when photo 2's stand-in arrives: 3's request stays + let (mut app, ctx) = raw_loupe(3); + let job = quick(&mut app, 2, 64); + let key = job.key; + app.renderer.look_ahead(vec![job], 96); + let job = quick(&mut app, 2, 64); + app.renderer.request_quick(Slot::Preview, job, 110); + assert!(app.renderer.drop_queued(Slot::Preview)); + app.renderer.failed.insert(Slot::Preview, (key, "unreadable".into(), 0, PhotoId(2))); + let job = quick(&mut app, 3, 64); + let key3 = job.key; + // (queued behind the stand-in made ahead, so that one arrives first) + app.renderer.request_quick(Slot::Preview, job, 50); + let ahead = app.renderer.pool.run_inline(1); + assert_eq!(ahead, 1); + app.renderer.poll(&ctx, &mut app.session); + assert!(app.renderer.textures.get(&Slot::Preview).is_none_or(|t| t.photo != PhotoId(2)), "photo 2 took photo 3's place"); + assert_eq!(app.renderer.pending.get(&Slot::Preview).map(|p| p.0), Some(key3), "photo 3's request is kept"); +} + +/// A stand-in made ahead for a smaller loupe isn't taken over when the loupe has grown: the +/// larger one is made (CodeRabbit on #3077). +#[test] +fn a_stand_in_made_ahead_for_a_smaller_loupe_is_not_taken_over() { + let (mut app, ctx) = raw_loupe(2); + let small = quick(&mut app, 2, 32); + let large = quick(&mut app, 2, 64); + assert_eq!(small.key, large.key, "the same stand-in, at another size"); + app.renderer.look_ahead(vec![small], 96); + assert_eq!(app.renderer.pool.run_inline(1), 1); + app.renderer.poll(&ctx, &mut app.session); + assert!(app.renderer.textures.keys().any(|s| matches!(s, Slot::QuickAhead(_)))); + app.renderer.request_quick(Slot::Preview, large, 110); + assert!(app.renderer.is_pending(Slot::Preview), "the larger stand-in is made"); + assert!(!app.renderer.textures.contains_key(&Slot::Preview)); + // the same size is taken over at once + let (mut app, ctx) = raw_loupe(2); + let job = quick(&mut app, 2, 64); + app.renderer.look_ahead(vec![job], 96); + assert_eq!(app.renderer.pool.run_inline(1), 1); + app.renderer.poll(&ctx, &mut app.session); + let job = quick(&mut app, 2, 64); + app.renderer.request_quick(Slot::Preview, job, 110); + assert!(!app.renderer.is_pending(Slot::Preview)); + assert_eq!(app.renderer.textures.get(&Slot::Preview).map(|t| t.photo), Some(PhotoId(2))); +} + +/// The benchmark's thumbnail count is per photo: a render replacing a photo's stand-in isn't +/// counted again (CodeRabbit on #3055). +#[test] +fn a_thumbnail_replacing_its_stand_in_is_not_counted_again() { + 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, work, ctx) = fixture_with(s, raw); + app.renderer.pool = JobPool::new(0); + let id = PhotoId(1); + crate::panels::grid::request_thumb(&mut app, id, 384, 10); + assert_eq!(app.renderer.pool.run_inline(1), 1); + app.renderer.poll(&ctx, &mut app.session); + assert!(app.renderer.textures.contains_key(&Slot::ThumbQuick(id))); + assert_eq!(app.renderer.thumbs_made, 1); + let mut edited = (*app.session.catalog.photo(id).unwrap().develop).clone(); + edited.light.exposure += 0.5; + app.session.commit("Exposure", Op::SetDevelop { id, settings: Arc::new(edited), label: "Exposure".into(), edited: None }).unwrap(); + crate::panels::grid::request_thumb(&mut app, id, 384, 10); + let (slot, job) = take_job(&work); + assert_eq!(slot, Slot::Thumb(id)); + finish(&mut app, &work, &ctx, slot, job.run()); + assert!(app.renderer.textures.contains_key(&Slot::Thumb(id)), "the render replaced the stand-in"); + assert_eq!(app.renderer.thumbs_made, 1, "still one photo"); + // evicted and made again (scrolled away and back): the same photo (CodeRabbit on #3055) + app.renderer.evict_thumbs(&Default::default(), 0); + assert!(!app.renderer.textures.contains_key(&Slot::Thumb(id)), "evicted"); + crate::panels::grid::request_thumb(&mut app, id, 384, 10); + let (slot, job) = take_job(&work); + finish(&mut app, &work, &ctx, slot, job.run()); + assert!(app.renderer.textures.contains_key(&slot), "made again"); + assert_eq!(app.renderer.thumbs_made, 1, "an evicted photo made again is not counted again"); +} + +/// The loupe's look-ahead asks again when only the crop changes (its stand-ins' keys include the +/// crop), instead of keeping stand-ins the loupe can no longer use (CodeRabbit on #3077). +#[test] +fn the_look_ahead_asks_again_when_only_the_crop_changes() { + let (mut app, _ctx) = raw_loupe(3); + let ahead_keys = |r: &Renderer| r.quick_tried.iter().filter(|(s, _)| matches!(s, Slot::QuickAhead(_))).map(|(_, k)| *k).collect::>(); + crate::panels::detail::look_ahead(&mut app, PhotoId(1), 64, true, ALL); + let cropped = app.session.quick_view_job(PhotoId(2), 64, true).unwrap().key; + assert!(ahead_keys(&app.renderer).contains(&cropped)); + crate::panels::detail::look_ahead(&mut app, PhotoId(1), 64, false, ALL); + let uncropped = app.session.quick_view_job(PhotoId(2), 64, false).unwrap().key; + assert_ne!(cropped, uncropped); + assert!(ahead_keys(&app.renderer).contains(&uncropped), "the stand-ins are made again without the crop"); +} + +/// The loupe's look-ahead asks again when the view's order changes around the same photo (a new +/// sort, filter or source changes its neighbours without an edit; CodeRabbit on #3055). +#[test] +fn the_look_ahead_follows_a_new_order_around_the_same_photo() { + let (mut app, _ctx) = raw_loupe(5); + let ahead_keys = |r: &Renderer| r.quick_tried.iter().filter(|(s, _)| matches!(s, Slot::QuickAhead(_))).map(|(_, k)| *k).collect::>(); + app.session.sort.key = lightcraft_catalog::SortKey::FileName; + app.session.sort.ascending = true; + crate::panels::detail::look_ahead(&mut app, PhotoId(3), 64, true, ALL); + let one = quick(&mut app, 1, 64).key; + assert!(!ahead_keys(&app.renderer).contains(&one), "r1 is two behind: not prepared"); + // reversed: r1 is two ahead now + app.session.sort.ascending = false; + crate::panels::detail::look_ahead(&mut app, PhotoId(3), 64, true, ALL); + assert!(ahead_keys(&app.renderer).contains(&one), "the new neighbours are prepared"); +} + +/// Stepping fast (an arrow held down), the raw renders still queued for the photo left behind are +/// dropped, the Before view's too (CodeRabbit on #3055); the whole-frame render on screen stays. +#[test] +fn stepping_fast_drops_the_queued_before_render() { + let (mut app, _work, ctx) = fixture(); + app.renderer.set_offload(Box::new(Blocked)); + for slot in [Slot::Main, Slot::Before, Slot::Region, Slot::RegionBefore] { + let job = app.session.render_job(PhotoId(1), 64, 64, false, true).unwrap(); + app.renderer.request(slot, job, 100); + } + app.renderer.poll(&ctx, &mut app.session); + assert!(app.renderer.is_pending(Slot::Before), "queued behind the blocked worker"); + crate::panels::detail::drop_unsettled(&mut app.renderer, PhotoId(2)); + for slot in [Slot::Main, Slot::Before, Slot::Region, Slot::RegionBefore] { + assert!(!app.renderer.is_pending(slot), "{slot:?} still queued"); + } +} diff --git a/crates/ui-egui/src/state/settings.rs b/crates/ui-egui/src/state/settings.rs index b858b9a55f..0fae2ed8e7 100644 --- a/crates/ui-egui/src/state/settings.rs +++ b/crates/ui-egui/src/state/settings.rs @@ -166,6 +166,11 @@ pub struct AppSettings { /// View ▸ View Options ▸ Show message when loading or rendering photos: the loupe says /// "Rendering…" while the photo it shows is not the finished render. pub loupe_messages: bool, + /// Settings ▸ Performance ▸ Prepare photos in the background, app-wide (a library may keep its + /// own in its `prefs.json`): handed to the session at launch and kept in step with it. Read + /// leniently: a value this build doesn't know is the defaults, never the other settings lost. + #[serde(deserialize_with = "lenient")] + pub background_prep: lightcraft_engine::prep::PrepSettings, /// Shortcuts the user changed (Help ▸ Keyboard Shortcuts): command id → shortcut, `""` = none. pub keymap: crate::shortcuts::Keymap, /// Auto (follow the system), Dark or Light. @@ -238,6 +243,7 @@ impl Default for AppSettings { film_badges: true, grid_badges: GridBadges::Auto, loupe_messages: true, + background_prep: Default::default(), keymap: Default::default(), appearance_mode: AppearanceMode::Dark, dark_theme: DarkTheme::Charcoal, @@ -430,6 +436,16 @@ fn deserialize_favorite_themes<'de, D: serde::Deserializer<'de>>(d: D) -> Result mod loupe_info_tests { use super::*; + /// A background preparation value this build doesn't know (a newer build's scope) reads as the + /// defaults and keeps the rest of the settings. + #[test] + fn an_unknown_background_preparation_value_costs_nothing_else() { + let v = serde_json::json!({"filmNames": false, "backgroundPrep": {"culling": {"scope": "someday"}}}); + let read: AppSettings = serde_json::from_value(v).unwrap(); + assert_eq!(read.background_prep, lightcraft_engine::prep::PrepSettings::default()); + assert!(!read.film_names); + } + /// The lines chosen in View Options are saved with the app's settings; a settings file from /// before they existed, or with a line this build doesn't know, gets the default lines and /// keeps the rest of its settings. diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 4401d5d179..19717ef817 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -24,6 +24,7 @@ mod dialog_settings; mod dialog_settings_text; mod dialog_tab; mod dialogs; +mod disk_space; mod docking_acceptance; mod drop_import; mod edit_layout; @@ -80,6 +81,7 @@ mod recheck; mod rename_person; mod rules_editor; mod sam_setup; +mod scan_probes; mod scroll; mod slider_reset; mod slideshow; diff --git a/crates/ui-egui/src/tests/disk_space.rs b/crates/ui-egui/src/tests/disk_space.rs new file mode 100644 index 0000000000..c2434afedf --- /dev/null +++ b/crates/ui-egui/src/tests/disk_space.rs @@ -0,0 +1,151 @@ +//! The low-disk notice: once per session, when the drive holding the preview cache runs low, with a +//! button to Settings ▸ Performance (where the cache's size limit is). + +use std::time::Duration; + +use lightcraft_engine::disk_space::DiskSpace; +use serde_json::json; + +use crate::headless::Headless; +use crate::state::Dialog; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const GB: u64 = 1 << 30; + +fn has(h: &Headless, id: &str) -> bool { + h.app.widgets.iter().any(|(w, _)| w == id) +} + +#[test] +fn a_low_drive_is_told_once_with_a_way_to_the_performance_settings() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()); + app.disk_space_notice = true; + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + h.step(); + assert!(h.app.notices.is_empty(), "no notice before the drive is low"); + // 12 GB free of a 500 GB drive: under 20 GB and under 10 % + assert!(h.app.session.note_disk_space(DiskSpace { available: 12 * GB, total: 500 * GB })); + h.step(); + h.step(); + assert_eq!(h.app.notices.len(), 1, "{:?}", h.app.notices); + let text = h.app.notices[0].clone(); + assert!(text.contains("12.0 GB free of 500 GB") && text.contains("Settings → Performance"), "{text}"); + let inspect = h.request("ui.inspect", json!({}), T); + assert_eq!(inspect["result"]["notices"][0], text.as_str(), "{inspect}"); + assert!(has(&h, "button:noticeSettings") && has(&h, "button:noticeOk"), "the notice offers the settings"); + let r = h.request("ui.clickWidget", json!({"id": "button:noticeSettings"}), T); + assert_eq!(r["ok"], true, "{r}"); + assert!(h.app.notices.is_empty(), "the button dismisses the notice"); + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "performance".into() }), "and opens Settings ▸ Performance"); + // lower still, later in the same session: not again + assert!(!h.app.session.note_disk_space(DiskSpace { available: 2 * GB, total: 500 * GB })); + h.step(); + h.step(); + assert!(h.app.notices.is_empty(), "once per session"); +} + +#[test] +fn without_the_desktop_flag_no_notice_is_shown() { + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()), [1300.0, 900.0], 1.0); + assert!(h.app.session.note_disk_space(DiskSpace { available: GB, total: 500 * GB })); + h.step(); + assert!(h.app.notices.is_empty(), "headless sessions and tests don't show it"); +} + +/// A notice still queued when another library opens belongs to the library before: it goes, and +/// the new library's drive is judged on its own. +#[test] +fn a_queued_notice_goes_when_another_library_opens() { + let dir = std::env::temp_dir().join(format!("lc-disk-notice-switch-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo().with_fs(), Services::default()); + app.disk_space_notice = true; + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + h.step(); + assert!(h.app.session.note_disk_space(DiskSpace { available: GB, total: 500 * GB })); + h.step(); + assert_eq!(h.app.notices.len(), 1, "{:?}", h.app.notices); + // another library opens before the notice was answered + h.app.session.open_library(&dir, false).unwrap(); + h.step(); + h.step(); + assert!(h.app.notices.iter().all(|n| !n.contains("1.0 GB free of 500 GB")), "the previous library's notice is gone: {:?}", h.app.notices); + let _ = h.app.session.close_library(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The drive is read again every few minutes whatever is filling the cache, not only while +/// previews are built (CodeRabbit on #3080): thumbnails and the loupe's previews alone can take a +/// drive under the line after the library opened. +#[test] +fn a_drive_that_runs_low_without_a_preview_build_is_told() { + use std::sync::atomic::{AtomicBool, Ordering}; + let dir = std::env::temp_dir().join(format!("lc-disk-notice-later-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let low = std::sync::Arc::new(AtomicBool::new(false)); + let mut session = lightcraft_engine::Session::with_demo().with_fs(); + let l = low.clone(); + session.set_disk_space_reader(Some(std::sync::Arc::new(move |_: &std::path::Path| { + Some(DiskSpace { available: if l.load(Ordering::Relaxed) { GB } else { 400 * GB }, total: 500 * GB }) + }))); + let mut app = LightcraftApp::new(session, Services::default()); + app.disk_space_notice = true; + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + h.app.session.open_library(&dir, false).unwrap(); + // (the open's read answered: a pass before that would see no alert yet whatever the drive holds) + assert!(h.step_until(T, |h| !h.app.session.disk_space_reading() && h.app.session.preview_build.is_none())); + assert!(!h.app.session.disk_space_alert_raised()); + for _ in 0..5 { + h.step(); + } + assert!(h.app.notices.is_empty(), "plenty of space at open: {:?}", h.app.notices); + // later, the drive fills up while nothing builds previews + low.store(true, Ordering::Relaxed); + h.app.session.forget_disk_space_check(); + assert!(h.app.session.preview_build.as_ref().is_none_or(|b| !b.running())); + assert!(h.step_until(T, |h| !h.app.notices.is_empty()), "the low drive is told"); + assert!(h.app.notices[0].contains("1.0 GB free of 500 GB"), "{:?}", h.app.notices); + let _ = h.app.session.close_library(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// An idle window still takes the drive's answer and makes the next check (CodeRabbit on #3077): +/// while a read runs the notice logic asks for a pass soon, and otherwise for one when the next +/// check is due; once the alert was raised it asks for nothing. +#[test] +fn an_idle_window_wakes_for_the_disk_check() { + use std::sync::{Arc, Mutex, mpsc}; + let dir = std::env::temp_dir().join(format!("lc-disk-notice-idle-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (release, wait) = mpsc::channel::<()>(); + let wait = Mutex::new(wait); + let mut session = lightcraft_engine::Session::with_demo().with_fs(); + session.set_disk_space_reader(Some(Arc::new(move |_: &std::path::Path| { + let _ = wait.lock().unwrap().recv_timeout(Duration::from_secs(10)); + Some(DiskSpace { available: GB, total: 500 * GB }) + }))); + let mut app = LightcraftApp::new(session, Services::default()); + app.disk_space_notice = true; + app.session.open_library(&dir, false).unwrap(); + assert!(app.session.disk_space_reading()); + let ctx = egui::Context::default(); + let pass = |app: &mut LightcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |_| crate::panels::notices::logic(app, &ctx)); + out.textures_delta.clear(); + out.viewport_output.values().map(|v| v.repaint_delay).min().unwrap_or(Duration::MAX) + }; + assert!(pass(&mut app) <= Duration::from_millis(250), "a pass soon while the read runs"); + release.send(()).unwrap(); + let until = std::time::Instant::now() + T; + while app.notices.is_empty() { + assert!(std::time::Instant::now() < until, "the answer was never taken"); + pass(&mut app); + } + assert!(pass(&mut app) > Duration::from_secs(60), "raised: nothing more to wake for"); + let _ = app.session.close_library(); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/tests/drop_import.rs b/crates/ui-egui/src/tests/drop_import.rs index e5d427d65e..6136ccf93f 100644 --- a/crates/ui-egui/src/tests/drop_import.rs +++ b/crates/ui-egui/src/tests/drop_import.rs @@ -1193,13 +1193,12 @@ fn auto_import_waits_for_a_browse_that_starts_during_its_listing() { let dir = Scratch::new("auto-browse"); let mut h = app(&dir); second_auto_import_listing(&mut h, &dir); - let scan = crate::import::stall_scan_of(&mut h.app, true); + let tx = crate::import::scan_by_hand(&mut h.app, true); apply_auto_import_listing(&mut h); assert!(h.app.import.is_none(), "no Auto Import for the browse to replace"); // the browse finds one photo of its own and imports it - let Ok(tx) = scan.downcast::>() else { panic!("the stalled scan's sender") }; let found = ImportCandidate { path: dir.path("trip/a.png"), ..Default::default() }; - tx.send(ScanOutput { candidates: vec![found], probes: Default::default() }).unwrap(); + tx.send(crate::import::ScanEnd::Done(ScanOutput { candidates: vec![found], probes: Default::default() })).unwrap(); drop(tx); assert!(h.step_until(T, |h| h.app.import.is_some()), "the browse starts its import"); assert!(h.step_until(T, |h| h.app.import.is_none()), "and it ends"); diff --git a/crates/ui-egui/src/tests/lifecycle_037.rs b/crates/ui-egui/src/tests/lifecycle_037.rs index 7b51cb3feb..dbff222044 100644 --- a/crates/ui-egui/src/tests/lifecycle_037.rs +++ b/crates/ui-egui/src/tests/lifecycle_037.rs @@ -2332,3 +2332,43 @@ fn synthetic_modifier_ownership_follows_host_changes_across_frames() { assert_eq!(app.synthetic_mods, egui::Modifiers::NONE); assert!(!app.synthetic_mods_release); } + +/// Background preparation is advanced on every logic pass, the hidden ones too (CodeRabbit on +/// #3077): a minimised window keeps preparing the view's previews, and a shown frame ticks it once. +#[test] +fn background_preparation_advances_while_the_window_is_hidden() { + let mut app = app(); + let ctx = egui::Context::default(); + let hidden = viewport_raw(egui::vec2(800.0, 600.0), false); + let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx)); + let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx)); + assert_eq!(app.prep_ticks, 2, "each hidden pass advances it"); + let visible = viewport_raw(egui::vec2(800.0, 600.0), true); + let _ = ctx.run_logic(&visible, |ctx| app.logic(ctx)); + assert_eq!(app.prep_ticks, 3, "a shown pass advances it once"); +} +/// CodeRabbit on #3077/#3080: a background build that couldn't start asks for a frame at its retry +/// time, so the retry happens with no input and no other timed frame. +#[test] +fn a_build_waiting_to_retry_asks_for_a_frame_at_its_time() { + let mut app = app(); + let ctx = egui::Context::default(); + let delays = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let seen = delays.clone(); + ctx.set_request_repaint_callback(move |info| seen.lock().unwrap().push(info.delay)); + let wait = std::time::Duration::from_secs(7); + let hidden = viewport_raw(egui::vec2(800.0, 600.0), false); + // (the first passes ask for frames at once, which would hide a later request) + for _ in 0..3 { + let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx)); + } + delays.lock().unwrap().clear(); + app.session.prep.retry_at = Some((0, std::time::Instant::now() + wait)); + let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx)); + let got = delays.lock().unwrap().clone(); + assert!(got.iter().any(|d| *d > std::time::Duration::from_secs(6) && *d <= wait), "a frame at the retry time: {got:?}"); + app.session.prep.retry_at = None; + delays.lock().unwrap().clear(); + let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx)); + assert!(!delays.lock().unwrap().iter().any(|d| *d > std::time::Duration::from_secs(6) && *d <= wait), "none without a retry waiting"); +} diff --git a/crates/ui-egui/src/tests/preview_limit.rs b/crates/ui-egui/src/tests/preview_limit.rs index ce5a5aba42..ddd6c74790 100644 --- a/crates/ui-egui/src/tests/preview_limit.rs +++ b/crates/ui-egui/src/tests/preview_limit.rs @@ -1290,6 +1290,38 @@ mod in_the_loupe { assert!(window[0].1.right() >= canvas.right() - 0.5, "the Before window stops at the wipe line: {:?}", window[0].1); } + // Given Before and After side by side at 1:1 with `\` held, the After pane is still the view + // shown: a Before window drawn while the After pane shows a stand-in does not make the loupe + // say the render is on screen + #[test] + fn holding_backslash_side_by_side_the_before_window_is_not_the_shown_render() { + let (_fx, mut h, _) = detail_in([1800.0, 900.0]); + h.app.ui.before_after = crate::state::BeforeAfter::SideBySide; + h.request("engine.execute", json!({"command": "view.zoom100"}), T); + h.settle(SETTLE); + h.events.push(egui::Event::Key { + key: egui::Key::Backslash, + physical_key: Some(egui::Key::Backslash), + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }); + h.settle(SETTLE); + // (the key's own shortcut switches to the Before view; side by side is chosen again with the key down) + h.app.ui.before_after = crate::state::BeforeAfter::SideBySide; + h.settle(SETTLE); + assert!(h.app.renderer.textures.contains_key(&Slot::RegionBefore), "the Before window is rendered"); + // the After pane back to a stand-in: no whole-frame render and no window of its own + h.app.renderer.textures.remove(&Slot::Main); + h.app.renderer.textures.remove(&Slot::Region); + h.step(); + assert!(!drawn(&h, Slot::RegionBefore).is_empty(), "the Before window is painted"); + // (the step must not bring the After pane's render back, or the check below proves nothing) + assert!(!h.app.renderer.textures.contains_key(&Slot::Main), "the whole-frame render came back during the step"); + assert!(!h.app.renderer.textures.contains_key(&Slot::Region), "the After window came back during the step"); + assert_ne!(h.app.loupe_shown.map(|l| l.1), Some("render"), "the After pane shows a stand-in, not the render"); + } + // Given Before and After side by side at 1:1, each window is painted inside its own pane: its // margin (a window is wider than what its pane shows) does not spill into the neighbour #[test] @@ -1306,6 +1338,33 @@ mod in_the_loupe { assert!(after.iter().all(|(_, clip, _)| clip.left() >= canvas.center().x), "the After window spills into the Before pane: {after:?}"); } + // Given Before and After side by side at 1:1 with `\` held, both panes stay, so each window + // stays clipped to its own pane: the Before window's margin does not cover the After pane + #[test] + fn holding_backslash_side_by_side_keeps_each_window_in_its_pane() { + let (_fx, mut h, _) = detail_in([1800.0, 900.0]); + h.app.ui.before_after = crate::state::BeforeAfter::SideBySide; + h.request("engine.execute", json!({"command": "view.zoom100"}), T); + h.settle(SETTLE); + h.events.push(egui::Event::Key { + key: egui::Key::Backslash, + physical_key: Some(egui::Key::Backslash), + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }); + h.settle(SETTLE); + // (the key's own shortcut switches to the Before view; side by side is chosen again with the key down) + h.app.ui.before_after = crate::state::BeforeAfter::SideBySide; + h.settle(SETTLE); + h.step(); + let canvas = h.app.canvas_rect.unwrap(); + let (before, after) = (drawn(&h, Slot::RegionBefore), drawn(&h, Slot::Region)); + assert!(!before.is_empty() && !after.is_empty()); + assert!(before.iter().all(|(_, clip, _)| clip.right() <= canvas.center().x), "the Before window spills into the After pane: {before:?}"); + assert!(after.iter().all(|(_, clip, _)| clip.left() >= canvas.center().x), "the After window spills into the Before pane: {after:?}"); + } + // Given a Before and an After with the same look (an unedited photo), both windows are kept // apart: the job key is the same, and one tile must not replace the other #[test] @@ -1583,3 +1642,16 @@ mod in_the_loupe { assert_ne!(after.settings, before.settings); } } + +// Build Standard-Sized Previews on Automatic: the loupe's size once one was drawn (the engine's standard), the +// standard 2560 px in a fresh session, not the engine's 2048 px minimum a fit view would render again over +// (CodeRabbit on #3077); a chosen limit as is +#[test] +fn standard_build_keeps_the_standard_size_before_a_loupe_was_drawn() { + use crate::menubar::standard_build_params; + use serde_json::json; + assert_eq!(standard_build_params(&with_limit(0), 0), json!({"size": "standard", "edge": STANDARD_PREVIEW_EDGE})); + assert_eq!(standard_build_params(&with_limit(0), 2400), json!({"size": "standard"})); + assert_eq!(standard_build_params(&with_limit(3840), 0), json!({"size": "standard", "edge": 3840})); + assert_eq!(standard_build_params(&with_limit(3840), 2400), json!({"size": "standard", "edge": 3840})); +} diff --git a/crates/ui-egui/src/tests/scan_probes.rs b/crates/ui-egui/src/tests/scan_probes.rs new file mode 100644 index 0000000000..04c7ad10d0 --- /dev/null +++ b/crates/ui-egui/src/tests/scan_probes.rs @@ -0,0 +1,204 @@ +//! A scan takes the probes of earlier scans from the session (`ScanInput::new`) and hands them back +//! however it ends: finished, stopped by another folder or by ✕, or unable to list its folder, so a later +//! import doesn't read those files again. + +use std::time::Duration; + +use crate::LightcraftApp; +use crate::headless::Headless; +use crate::import::ScanEnd; + +const T: Duration = Duration::from_secs(10); +const KEPT: &str = "/nowhere/kept.cr3"; + +fn demo() -> Headless { + let services = crate::Services { png: None, ..Default::default() }; + Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1000.0, 700.0], 1.0) +} + +fn probes() -> std::collections::HashMap { + [(KEPT.to_string(), lightcraft_engine::media::ProbeInfo { file_size: 7, ..Default::default() })].into_iter().collect() +} + +fn kept(h: &Headless) -> bool { + h.app.session.import_probes.get(KEPT).is_some_and(|p| p.file_size == 7) +} + +fn failed_toast(h: &Headless) -> bool { + h.app.ui.toast.as_ref().is_some_and(|t| t.0.contains("Scan failed")) +} + +fn cancel_scan(h: &mut Headless) { + let id = h.app.session.activity.list().iter().find(|t| t.kind == "scan").map(|t| t.id).expect("the scan's row"); + h.app.session.activity.cancel(id).expect("the scan can be cancelled"); +} + +#[test] +fn a_browse_replaced_by_another_folder_hands_back_its_probes() { + let mut h = demo(); + let base = std::env::temp_dir().join(format!("lc-ui-scan-probes-{}", std::process::id())); + let (a, b) = (base.join("a"), base.join("b")); + std::fs::create_dir_all(&a).unwrap(); + std::fs::create_dir_all(&b).unwrap(); + h.app.session.import_probes = probes(); + crate::import::browse(&mut h.app, &a.to_string_lossy(), None).unwrap(); + assert!(h.app.session.import_probes.is_empty(), "the first browse took the probes"); + // another folder at once: the first browse is stopped (or its result left unread) + crate::import::browse(&mut h.app, &b.to_string_lossy(), None).unwrap(); + assert!(h.step_until(T, |h| h.app.scan.is_none() && kept(h)), "the first browse's probes came back"); + let _ = std::fs::remove_dir_all(&base); +} + +#[test] +fn a_browse_that_cannot_list_its_folder_hands_back_its_probes() { + let mut h = demo(); + let tx = crate::import::scan_by_hand(&mut h.app, true); + tx.send(ScanEnd::Stopped { probes: probes(), failed: true }).unwrap(); + h.step(); + assert!(h.app.scan.is_none()); + assert!(kept(&h), "the probes came back"); + assert!(failed_toast(&h), "the failure is reported: {:?}", h.app.ui.toast); +} + +#[test] +fn a_scan_closed_with_its_cross_hands_back_its_probes_when_the_worker_ends() { + let mut h = demo(); + let tx = crate::import::scan_by_hand(&mut h.app, false); + cancel_scan(&mut h); + h.step(); + assert!(h.app.scan.is_none(), "✕ closes the scan at once"); + // the worker ends later, with the probes it took + tx.send(ScanEnd::Done(lightcraft_engine::import::ScanOutput { candidates: Vec::new(), probes: probes() })).unwrap(); + assert!(h.step_until(T, kept), "the probes came back"); + assert!(h.app.ui.dialog.is_none(), "no review opened"); + assert!(!failed_toast(&h)); +} + +#[test] +fn a_cancelled_scan_whose_worker_ends_without_a_result_is_not_a_failure() { + let mut h = demo(); + let tx = crate::import::scan_by_hand(&mut h.app, true); + cancel_scan(&mut h); + drop(tx); + h.step(); + assert!(h.app.scan.is_none()); + assert!(!failed_toast(&h), "a cancelled scan says nothing: {:?}", h.app.ui.toast); +} + +/// Two stopped scans hand back a probe of one file: the later scan read it again, so its probe stays, +/// whichever worker ends first (CodeRabbit on #3577: the older one won when its worker ended first, +/// and its content hash is stale for a file changed at the same size). +#[test] +fn the_later_stopped_scans_probe_wins_whichever_worker_ends_first() { + let probe = |hash: &str| { + let p = lightcraft_engine::media::ProbeInfo { file_size: 7, content_hash: Some(hash.into()), ..Default::default() }; + [(KEPT.to_string(), p)].into_iter().collect() + }; + for later_ends_first in [false, true] { + let mut h = demo(); + let older = crate::import::scan_by_hand(&mut h.app, true); + cancel_scan(&mut h); + h.step(); + let newer = crate::import::scan_by_hand(&mut h.app, true); + cancel_scan(&mut h); + h.step(); + assert!(h.app.scan.is_none(), "both stopped"); + let a = ScanEnd::Stopped { probes: probe("older"), failed: false }; + let b = ScanEnd::Stopped { probes: probe("newer"), failed: false }; + if later_ends_first { + newer.send(b).unwrap(); + h.step(); + older.send(a).unwrap(); + } else { + older.send(a).unwrap(); + h.step(); + newer.send(b).unwrap(); + } + h.step(); + let hash = h.app.session.import_probes.get(KEPT).and_then(|p| p.content_hash.clone()); + assert_eq!(hash.as_deref(), Some("newer"), "later worker ends first: {later_ends_first}"); + } +} + +/// Browsing reads the disk only on its worker (CodeRabbit on #3077): a folder whose resolution is held (a link on +/// a stalled network mount) still lets `browse` return at once, the view shows the folder as given, and the scan +/// waits; once resolved, the folder is read. +#[test] +fn a_browse_whose_folder_resolves_slowly_returns_at_once_and_waits() { + let mut h = demo(); + let dir = std::env::temp_dir().join(format!("lc-ui-browse-held-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + // (spelled with `sub/..`: the worker is handed the path as given, not the view's spelling of it) + let given = dir.join("sub").join("..").to_string_lossy().to_string(); + let spelled = lightcraft_engine::import::browse_spelling(&dir).unwrap().to_string_lossy().trim_end_matches(['/', '\\']).to_string(); + crate::import::HELD_RESOLVES.lock().unwrap().push(given.clone()); + let start = std::time::Instant::now(); + let r = crate::import::browse(&mut h.app, &given, None).unwrap(); + assert!(start.elapsed() < Duration::from_secs(2), "returned after {:?}", start.elapsed()); + assert_eq!(r["scanning"], true, "{r}"); + assert_eq!(h.app.session.browse.as_ref().map(|b| b.path.clone()), Some(spelled), "shown as spelled meanwhile"); + for _ in 0..5 { + h.step(); + } + assert!(h.app.scan.is_some(), "still waiting for the folder"); + crate::import::HELD_RESOLVES.lock().unwrap().retain(|p| *p != given); + assert!(h.step_until(T, |h| h.app.scan.is_none()), "read once resolved"); + assert!(!failed_toast(&h), "{:?}", h.app.ui.toast); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A path that isn't a folder is found out by the worker, not by the window's thread: `browse` returns, and the scan +/// then ends as failed. +#[test] +fn a_browse_of_a_missing_folder_fails_on_its_worker() { + let mut h = demo(); + let gone = std::env::temp_dir().join(format!("lc-ui-browse-gone-{}", std::process::id())).join("not-there"); + assert!(crate::import::browse(&mut h.app, &gone.to_string_lossy(), None).is_ok()); + assert!(h.step_until(T, |h| h.app.scan.is_none())); + assert!(failed_toast(&h), "the failure is reported: {:?}", h.app.ui.toast); +} + +/// The worker resolves the path as given (CodeRabbit on #3055 / #3077 / #3080): on Unix `photos/link/../select`, with +/// `link` pointing at `real/day`, is `real/select`, not the `photos/select` that taking `..` out by name would read. +#[cfg(unix)] +#[test] +fn a_browse_through_a_link_and_dot_dot_reads_the_folder_the_system_names() { + let mut h = demo(); + let base = std::env::temp_dir().join(format!("lc-ui-browse-link-{}", std::process::id())); + let (day, real_select, photos) = (base.join("real/day"), base.join("real/select"), base.join("photos")); + for d in [&day, &real_select, &photos.join("select")] { + std::fs::create_dir_all(d).unwrap(); + } + std::os::unix::fs::symlink(&day, photos.join("link")).unwrap(); + let given = photos.join("link").join("..").join("select"); + crate::import::browse(&mut h.app, &given.to_string_lossy(), None).unwrap(); + assert!(h.step_until(T, |h| h.app.scan.is_none()), "the browse ended"); + assert!(!failed_toast(&h), "{:?}", h.app.ui.toast); + let want = std::fs::canonicalize(&real_select).unwrap(); + let shown = h.app.session.browse.as_ref().map(|b| std::fs::canonicalize(&b.path).unwrap()); + assert_eq!(shown, Some(want), "the folder the system names, not photos/select"); + let _ = std::fs::remove_dir_all(&base); +} + +/// Browsing a folder that is being read again keeps its progress, but not through `..` (CodeRabbit on #3583): past +/// a link, `x/link/../y` can be another folder than the `x/y` it is spelled as, so the worker reads it again. +#[test] +fn a_browse_through_dot_dot_reads_again_while_its_spelling_is_being_read() { + let mut h = demo(); + let dir = std::env::temp_dir().join(format!("lc-ui-browse-dotdot-{}", std::process::id())); + std::fs::create_dir_all(dir.join("sub")).unwrap(); + let plain = dir.to_string_lossy().to_string(); + crate::import::HELD_RESOLVES.lock().unwrap().push(plain.clone()); + let row = |h: &Headless| h.app.session.activity.list().iter().find(|t| t.kind == "scan").map(|t| t.id); + crate::import::browse(&mut h.app, &plain, None).unwrap(); + let first = row(&h); + assert!(first.is_some(), "the browse's row"); + crate::import::browse(&mut h.app, &plain, None).unwrap(); + assert_eq!(row(&h), first, "the same folder again: the same read"); + let given = dir.join("sub").join("..").to_string_lossy().to_string(); + crate::import::browse(&mut h.app, &given, None).unwrap(); + assert_ne!(row(&h), first, "through `..`: read again"); + crate::import::HELD_RESOLVES.lock().unwrap().retain(|p| *p != plain); + assert!(h.step_until(T, |h| h.app.scan.is_none()), "the browse ended"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 43ff7a7175..4f25582349 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, `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.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`, `loupeSteps` = how the loupe showed each photo it was stepped to, measured on the frames it drew: `{steps: [{photo, anyMs, anySource, fullMs, fullSource, sharpMs, dwellMs}], total, current}` — ms from the step to the first frame with anything of the photo, with a full-size picture (`embedded` camera JPEG, `cached` or `render`), and with LightCraft's own render; `dwellMs` is how long it stayed, the latest 256 steps; `total` counts every step finished since launch, a cursor that keeps rising when old steps leave the list; `thumbsMade` = photos given a grid thumbnail since launch (never lowered when old thumbnails are evicted, unlike `thumbTextures`); `previewCache` = the rendered-preview cache: `memEntries` / `memBytes` in memory, the disk cache's `diskHits`, `diskMisses`, `diskWrites` and `diskBudget` (bytes; all `null` without a library on disk), and `loupeEdge` (px, the loupe's longest edge, the size standard previews are built at)), 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, or once per session the drive holding the preview cache running low; OK = `button:noticeOk`, and the low-drive notice's `button:noticeSettings` opens Settings ▸ Performance), `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/gaps.md b/docs/gaps.md index 566786a5f0..e89a6162c0 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-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) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-05 · **Change:** minor (gap 26: culling uses built previews, background preparation per mode; before: Contrast and Blacks calibrated in process V4, #523; PERF-STEP-STALL: flags, ratings and edits never wait for the drive; 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 @@ -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**: 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) | +| 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); culling a wedding: first photos of a 2,933-raw folder in 0.9 s and camera JPEGs ready ahead of each step, but a full-size 45 MP camera JPEG still takes ~150 ms to decode (held-arrow stepping at a 2,560 px loupe can outrun it), the 100 % view of the raw itself still takes ~5 s to render (the camera JPEG is shown at 100 % meanwhile, ~0.9 s), and browsing or importing still reads and hashes every raw whole (~10 ms a file on SSD, ~1 s a 25 MB file from a NAS); the loupe uses built previews and photos are prepared ahead and the whole view in the background (face detection, AI masks and denoise are not yet part of that preparation) | 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,8 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | Gap 26: the loupe shows built previews (they were rendered again), photos ahead and the whole view are prepared in the background with settings per mode; gap not closed | +| 2026-10-27 | minor | Gap 26: culling speed measured and improved (progressive Local browse, camera previews made ahead, a CR3's smallest covering JPEG, camera JPEG first at 100 %); what is left listed; gap not closed | | 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) | diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index 6e063e6f90..a21ef36801 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -428,6 +428,11 @@ view shows a GPU-resident draft reads that texture back for the picture (`Screen - The next and previous photos in filmstrip order are prepared in the background once the current one is rendered (decoded source kept, view render cached): stepping through photos shows the developed image in ~50 ms. +- Culling (PERF-CULL): the stand-ins of the next five photos in the direction of travel and the one + behind are made ahead (`render::Slot::QuickAhead`) and taken over at the step, so a step shows + the camera JPEG at once; while an arrow key is held (a photo left within 0.25 s) the raw render + of a photo waits until it has stayed 0.12 s, and a render queued for a photo already left is + dropped. `ui.inspect` → `perf.loupeSteps` times each step on the frames drawn. ## Memory (M5.6) A view's stages keep an uploaded source only up to 96 MB (a Preview-level source); a bigger one (the original a zoom window is cut from) is kept once, outside the views' stages, for all views of the photo (the Before and After windows and every pan share it; the Before window of a Before/After waits at first open until the After's job has handed the original over, or each would decode and upload its own copy) and given back when the app idles with no zoom window on screen (a zoomed view keeps it for its next pan: a 64 MP original is 800 MB to upload again; issue #323: kept per view it counted against the stage budget on every tick of a drag, and not kept every new window uploaded 288 MB again). diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 2758969b26..fb535f1c43 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-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 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; before: LR-PROF-IMPORT: the user's own .dcp camera profiles import, checked on a real D750 profile against Lightroom; 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 @@ -52,10 +52,10 @@ cited here still exists. Formerly docs/parity.md. | X. Cross-cutting behaviours (BEHAV) | 23 | 6 | 1 | 1 | 8/8 (100%) | 7/10 (70%) | | 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** | 417 | 69 | 57 | 35 | 192/203 (95%) | 146/161 (91%) | +| Lightroom Classic extras | 41 | 26 | 21 | 8 | — | 24/27 (89%) | +| **Total** | 417 | 70 | 57 | 35 | 192/203 (95%) | 146/162 (90%) | -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. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.1%** of 544 in-scope rows — P0 97.3% of 203 · P1 94.1% of 162 · P2 56.7% of 178. ## Top gaps and shortcut notes @@ -78,11 +78,11 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-IMP-RAWDEFAULT | Raw defaults | P1 | ✅ | `cmd:library.preferences`, `crates/engine/src/import.rs`, `crates/ui-egui/src/dialogs/settings.rs` | LightCraft default / a preset / per camera (make + model); non-raw default too; the preset look counts as unedited and Reset returns to it | | LR-IMP-MIGRATE | Migrate other catalogs | OOS | 🚫 | | | | LR-IMP-PROFILES | Import profiles & presets | P1 | ✅ | `cmd:file.importPresets`, `cmd:preset.import`, `cmd:profile.import`, `crates/engine/src/preset_import.rs`, `crates/engine/src/preset_luminar.rs` | presets: .lcpreset, XMP, classic .lrtemplate (local adjustment templates become mask effects, LR-MASK-EFFECTS), photos carrying edits ("DNG presets"), Luminar looks (.lmp, .mplumpack collections; sliders with a counterpart), .zip bundles, folders (folder → group), drag & drop (an `.xmp` dropped together with its photo is that photo's sidecar and is not imported as a preset, issue #936); masks carried over; unmapped settings reported (fields that only describe the preset or photo, e.g. `Cluster`, `SortName`, `SupportsAmount2`, the as-shot white, empty Point Color slots, are not); profiles: .cube 3D LUTs (one toast reports both halves; a LUT that fails is named with its reason); a preset that names a profile (`crs:Look`) applies the imported profile of that name, imported before or after it, and Lightroom's basic profiles map to ours (`crates/engine/src/profile_refs.rs`, issue #1001); Adobe profile formats deliberately unsupported (so `.xmp` creative profiles' colour tables aren't read) | -| LR-IMP-LOCAL | Work on files in place | P0 | ✅ | `cmd:library.browse`, `cmd:photo.addToLibrary`, `cmd:library.import` (mode add), `cmd:local.addRoot`, `cmd:local.hide`, `cmd:local.restoreHidden`, `crates/engine/src/cmd/browse.rs`, `crates/ui-egui/src/panels/left.rs` (`local_section`), `crates/ui-egui/src/panels/grid.rs` (`folder_header`) | Local: browse Pictures / Desktop / Downloads / Home or any folder without adding it (breadcrumb, Include subfolders, Add N to My Photos); browsed photos stay out of All Photos, albums and counts (album commands skip them and the album menus say to Add to My Photos first, issue #684); folders picked with Browse Folder… (or Keep in Local / Add to Local on a folder row) stay listed across restarts, and browsing a folder inside a listed one highlights it inside that tree (opened down to it, siblings reachable) instead of adding a root; edits go to XMP sidecars; importing promotes them; right-click a top-level location → Remove from Local hides the shortcut only (nothing on disk or in the catalog changes), saved with the UI state, and “Show N hidden locations” (or Browse Folder… on it) brings it back, each on its own from the row's list when several are hidden, or all at once with Restore All (issue #2114); a folder is one location however its path is spelled (`/` or `\`, trailing separator, `.`/`..`, drive-letter case; `folder_key` in `crates/catalog/src/query.rs`); browsed photos nobody changed are forgotten once their folder has not been browsed for 30 days (Settings → Performance → Local folders, 0 = never; checked when the library opens, or `cmd:library.forgetLocal` with `dryRun`; files and sidecars stay, browsing again brings them back; see `crates/catalog/src/local.rs` for what counts as a change); browsing a folder again forgets at once the untouched records of its files that another app deleted or moved, so they no longer fail to load on every visit (issue #1392; changed ones stay, shown as missing); browsing a folder keeps the active photo when the folder shows it, else makes the folder's first photo active as it arrives, the same rule as albums and the other sources (`Session::keep_active_in_view`; issue #1447: before, a library photo stayed active, so Photo Grid marked nothing and Detail, the histogram and the info showed a photo the folder doesn't hold) | +| LR-IMP-LOCAL | Work on files in place | P0 | ✅ | `cmd:library.browse`, `cmd:photo.addToLibrary`, `cmd:library.import` (mode add), `cmd:local.addRoot`, `cmd:local.hide`, `cmd:local.restoreHidden`, `crates/engine/src/cmd/browse.rs`, `crates/ui-egui/src/panels/left.rs` (`local_section`), `crates/ui-egui/src/panels/grid.rs` (`folder_header`), `crates/engine/src/import.rs` (`browse_queue`) | Local: browse Pictures / Desktop / Downloads / Home or any folder without adding it (breadcrumb, Include subfolders, Add N to My Photos); the folder's photos join the view batch by batch while they are read, first screen first (`browse_queue`: newest file first for the default sort), so a 2,933-raw wedding folder shows its first photos in 0.9 s instead of after every file was read (30.6 s; the whole folder still takes ~30 s); browsed photos stay out of All Photos, albums and counts (album commands skip them and the album menus say to Add to My Photos first, issue #684); folders picked with Browse Folder… (or Keep in Local / Add to Local on a folder row) stay listed across restarts, and browsing a folder inside a listed one highlights it inside that tree (opened down to it, siblings reachable) instead of adding a root; edits go to XMP sidecars; importing promotes them; right-click a top-level location → Remove from Local hides the shortcut only (nothing on disk or in the catalog changes), saved with the UI state, and “Show N hidden locations” (or Browse Folder… on it) brings it back, each on its own from the row's list when several are hidden, or all at once with Restore All (issue #2114); a folder is one location however its path is spelled (`/` or `\`, trailing separator, `.`/`..`, drive-letter case; `folder_key` in `crates/catalog/src/query.rs`); browsed photos nobody changed are forgotten once their folder has not been browsed for 30 days (Settings → Performance → Local folders, 0 = never; checked when the library opens, or `cmd:library.forgetLocal` with `dryRun`; files and sidecars stay, browsing again brings them back; see `crates/catalog/src/local.rs` for what counts as a change); browsing a folder again forgets at once the untouched records of its files that another app deleted or moved, so they no longer fail to load on every visit (issue #1392; changed ones stay, shown as missing); browsing a folder keeps the active photo when the folder shows it, else makes the folder's first photo active as it arrives, the same rule as albums and the other sources (`Session::keep_active_in_view`; issue #1447: before, a library photo stayed active, so Photo Grid marked nothing and Detail, the histogram and the info showed a photo the folder doesn't hold) | | LR-IMP-SIDECAR-SPLIT | Separate XMP sidecar variants | P2 | ⬜ | `cmd:library.xmpPreferences` | sidecar naming option exists (stem/full), no split sidecars | +| LR-IMP-PREVIEW-READ | Preview reads the header, not the raw | P0 | ✅ | `crates/raw/src/preview.rs` (`bounded_preview`, `embedded_preview_from_range`, `embedded_preview_covering`), `crates/engine/src/files.rs` (`preview_window`), `docs/raw-preview-reads.md`, `crates/engine/src/files.rs` (`preview_window`, `planned_preview`), `crates/raw/src/sparse.rs` (`preview_plan`), `crates/raw/src/dng.rs` (`decode_reduced`), `crates/codecs/src/lib.rs` (`decode_jpeg_srgb8_fit`) | a grid thumbnail and a loupe preview of an unedited raw show the camera's embedded JPEG, which sits near the start of the file (a 24 MP Fuji RAF keeps its 5.6 MB JPEG in a 56 MB file), so the preview loader reads the header and that JPEG instead of the whole file: 56.5 MB → 5.9 MB and ~10 s → 0.96 s measured on one real RAF over a GVFS/SMB Wi-Fi share (byte-identical preview pixels; `LIGHTCRAFT_PROFILE=1` reports the bytes); the RAF pointer is read from its fixed header fields, a CR3's boxes and a TIFF raw whose preview tag sits past the prefix are read through `lightcraft_raw::sparse::preview_plan`, which names the ranges `embedded_preview` reads and nothing else; a cached render as stand-in, an edited photo and a raw without an embedded JPEG still render; the formats it cannot describe (CRW/MRW/X3F are found by scanning, NEF/ORF/PEF probe from samples) keep the whole-file path, and a lying pointer, a short read or a file that changes underneath us falls back to it rather than losing the preview. An unedited raw's **grid thumbnail is that camera JPEG itself**, so no sensor decode is scheduled behind it (`Session::embedded_thumb_is_final`, `grid::skips_the_real_render`): drawing a 512 px thumbnail used to decode the whole raw — 45 s a photo at 1.2 MB/s, 8.3 GB for a 149-raw folder — and the queue it built delayed the render the user was waiting for. Stand-ins and grid thumbnails decode the smallest embedded JPEG that covers the requested size and is a copy of the largest (aspect ratio within 1 %, same component count), not always the largest, on the whole-file and the plan route alike: an A7R VI's 1616 × 1080 JPEG (0.3 MB) instead of its 9984 × 6656 one (5.6 MB), mid-sized NEF / RW2 JPEGs, and a Canon CR3's 1620 px `PRVW` (or 160 px `THMB`) instead of its 8192 px JPEG track (`cr3_preview_box_list`; EOS R5 C at 1280 px: 168–322 → 31 ms a photo); a plain 8-bit sRGB camera JPEG decodes straight to 8-bit (`decode_jpeg_srgb8_fit`, no float image), and the decoded camera JPEG of an unedited raw is kept in the library's thumbnail cache, so a folder seen before fills from small files (250 R5 C raws: first screen 553 → 294 ms, second visit 610 → 53 ms); a DNG that keeps reduced-resolution copies of its LinearRaw image (Lightroom HDR/panorama merges) develops a thumbnail or preview from the smallest copy that covers it (512 px of a 23836 × 7078 pano: 38 s → 1.1 s) | | LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG (ICC APP2 sequences require unique complete chunks with consistent totals; malformed profiles use the existing unsupported-profile sRGB fallback; a Samsung panorama whose scan data runs into its SEF trailer with no end-of-image marker reads as the image before the trailer, while a JPEG cut short is still refused, issue #3350, `crates/codecs/src/jpeg.rs`), PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP (lossy wide-gamut JXL decodes to the right colours: jxl-oxide desaturated XYB rendered to P3/Rec. 2020, worked around in `crates/codecs/src/jxl.rs`); DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared primaries and transfer curve (linear, sRGB, BT.709 or a power; PQ / HLG stay preview-only) without clipping or gamut mapping, checked on one real file with 108 lossy tiles and on 2 Lightroom Classic 15.1 lossy LinearRaw DNGs (ILCE-7CM2) whose tiles declare Rec. 2100 primaries with the sRGB curve, which were preview-only before, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), CRW (CIFF, the 2000–2004 Canon bodies: clean-room-derived decode frozen in `craft-libs crates/crw/clean-room/02-crw-format.md`, `crates/raw/src/vendor/crw.rs`; EOS D30/D60/10D/300D, PowerShot G1 (10-bit GBRG) and G6 pixel-exact against a black-box reference on 28 of 29 corpus files incl. 18 private D60s; as-shot white balance from the ColorBalance record's ShotInfo-selected slot; black level from the darkest flat masked-border strip; rotation from ImageInfo; starting look fitted from the file's own embedded JPEG like CR2/CR3 (`camera_preview::file_local_look`), accepted on all 10 decodable public corpus files (holdout RMS 0.009–0.047), with the fitted matrix absorbing the white balance on the bodies without a ColorBalance record (D30, PowerShots); the PowerShot G5's anomalous entropy coding and the pre-CIFF compacts stay preview-only, and G2/G3/G4/Pro1/S-series decode unverified for lack of redistributable samples), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth but CFA and black unverified), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/vendor/kodak.rs`, checked on the one CC0 sample against its IFD0 thumbnail), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`, checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; an FFF has no colour matrix of its own and takes the camera's from the original 3FR header it embeds in tag `0xC51B`; neither carries a JPEG, so their uncompressed 8-bit RGB preview (1217 × 913 in the H4D-40 FFF, 218 × 218 in the CFV 3FR) is the embedded preview, handed on as a baseline TIFF, `crates/raw/src/vendor/hasselblad.rs`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Minolta / Konica Minolta MRW (the `\0MRM` block container: `PRD` sensor size, 12-bit packed or 16-bit-word storage and the RGGB / GBRG cell, `WBG` gains in cell order, the `TTW` TIFF for Exif and orientation, black 0 and white from the saturation plateau; `crates/raw/src/vendor/mrw.rs`, DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D checked on CC0 files against their previews), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (EOS R6 Mark III `ColorData` version 66: as-shot white balance and black level from the file, white level from the data, `docs/cr3.md`) (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8/RP, incl. RP 1.6× crop mode (`crates/raw/tests/it/cr3_corpus.rs`, `docs/cr3.md`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed ORF, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes, and the notices carry a Reload from Disk button; each flag is stamped with the app version that set it, and a library opened in another version rechecks its preview-only raws in the background, so a raw a newer release decodes is cleared without a manual Reload, issue #662, `library.recheckPreviewOnly`), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and the Kodak DCS Pro / DCS760C TIFFs (compression 65000): IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Sigma X3F (container recognised by magic, preview found by a structural JPEG scan), the Canon CRWs the decoder refuses (PowerShot G5, pre-CIFF compacts), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `crates/heif`, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate); folder discovery and file pickers include Sony SR2 and SRF, with the same extension list used by CLI/MCP: DSC-R1 SR2 decodes from sensor data; DSC-F828 SRF stays preview-only; transparency is flattened onto white, in linear light, where the working image is built (`to_working` in `crates/codecs/src/lib.rs`): renders, previews, exports and contact sheets no longer turn transparent areas black, issue #1212; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); the Hasselblad Lunar, a Sony NEX-7 under Make HASSELBLAD, decodes as an ARW: a HASSELBLAD file with Sony's raw coding (compression 32767 or tag `0x7010`) goes to the ARW reader, and the body for its `Tag2010` layout comes from the maker note's `SonyModelID`, checked on the CC0 4051 file, issue #1275; an uncompressed MOS, whose IFD0 is the 16-bit mosaic with no Make tag, is recognised by Leaf's data block `0x8606` instead of opening as a greyscale image of its mosaic, issue #1275), and any decode failure of a recognised raw, not only an unsupported variant Nikon 12-bit small RAW (D810 / D4S): packed Y0/Y1/Cb/Cr rows decode to linear RGB; header probes retain geometry without decoding pixels, and truncated strips are refused. Chroma gains are approximate. | | LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/it/corpus.rs`, `crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/evidence.tsv`, `docs/raw/coverage-sweep.tsv`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases and 4 pinned EOS R5 Mark II files (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; their white balance now comes from the encrypted `SR2SubIFD`'s `WB_RGGBLevels`, the gains the camera applied, which 14 bodies (DSLR-A450 … A700, NEX-3/5/C3, SLT-A33/A35/A55, ILCE-6001, UMC-R10C) had no other source for and which the maker-note estimate read before missed by up to 100 % on preset shots, issue #535, checked against ExifTool on 100 decoded ARWs from 87 Sony bodies; the encrypted SR2 black level is now read from its directory entry (the DSLR-A450/A500/A550/A700 read 354–975 instead of 512), checked on 126 ARWs from 97 Sony bodies, and downsized lossless M/S ARWs use their measured black level 1024 instead of 512, checked on 12 files from 4 bodies, issue #535, and on a fifth, the ILCE-7CM2 (issue #697: 0.5.0 rendered its lossless M file with that 512 pedestal, the darkest half of a dusk scene +11 L* and blue, the lamplight white; its darkest 0.1 % per channel sits at 1017/1020/1024, and with 1024 the render is within +3 L* of the camera JPEG; the body's compressed and uncompressed "M-size" files are Bayer at 4736×3132 with black 512, two public ones in the corpus); pre-2017 Sony bodies shot in the camera's 16:9 mode (ILCE-7SM2, DSLR-A580) now get the 16:9 crop of their camera JPEG instead of the whole 3:2 frame with padding columns, issue #535; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked; private Z 8 crop verified; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone); the D7100, whose data holds picture beyond the camera's frame, develops at Lightroom's frame (the camera JPEG's size) in full frame and 1.3x crop, so Lightroom crops line up (#1248).; CR2 white levels came from masked rows holding samples at 16383, so on the EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i), 1200D (Rebel T5) and 100D (Rebel SL1) clipped highlights sat at 81–98% of the range and were not treated as clipped, now taken from the active area only, issue #1272). Canon CRW verified pixel-exact on 6 bodies (D30, D60, 10D, 300D, G1, G6; 10 CC0 files in the corpus, `crates/raw/tests/it/corpus.rs`, plus 18 maintainer D60 files via the digest-pinned sample test of craft-crw in craft-libs (crates/crw/tests/samples.rs there); `craft-libs crates/crw/clean-room/03-verification.md`). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Pentax PEFs without area tags (KP, KF, K-3 Mark III, K-70, K-1, K-1 Mark II, K-S1, K-S2, 645Z) no longer keep their masked border: black, empty and saturated lines are trimmed against the maker-note BlackPoint, issue #1271, measured on 38 CC0 PEFs from 30 bodies.; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Canon PowerShot G9, which writes no `ColorData`, takes its as-shot white balance from the WBInfo row (`0x0029`) of the preset ShotInfo names, issue #1273, checked on 1 CC0 file against neutral areas of the camera JPEG (within 0.1 %).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Olympus E-10 (no ImageProcessing directory) takes its as-shot gains and its black level (`0x1012` in `0x102c` ValidBits units: 128 at 12 bits) from the main maker note, issue #1273: its render against the camera thumbnail goes from ΔE76 18.5 with a rejected fit to 11.5 with the fit accepted (measured by AlexChambers).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone), and the Nikon D90 likewise on 10 of 550 NEFs (42 filler columns on the right that developed as a pink band; green clips below red and blue).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Public raw.pixls.us coverage sweep (#1327): 30 more models verified on 40 CC0 files, with SHA-256 and FNV-1a sensor hashes pinned (`crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/coverage-sweep.tsv`; `docs/raw/coverage.py`: 515 → 545 verified rows). Render/reference luminance correlation is 0.6801 to 0.9998; eleven candidates excluded for identity, provenance or missing/mismatched reference images. Nikon D6 / Z 6 / Z 7 uncompressed and Z 8 HE variants remain preview-only. Own-matrix DNG tone differs from the camera JPEG (#1277); sensor verification is not colour calibration. | -| LR-IMP-PREVIEW-READ | Preview reads the header, not the raw | P0 | ✅ | `crates/raw/src/preview.rs` (`bounded_preview`, `embedded_preview_from_range`, `embedded_preview_covering`), `crates/engine/src/files.rs` (`preview_window`), `docs/raw-preview-reads.md`, `crates/engine/src/files.rs` (`preview_window`, `planned_preview`), `crates/raw/src/sparse.rs` (`preview_plan`), `crates/raw/src/dng.rs` (`decode_reduced`) | a grid thumbnail and a loupe preview of an unedited raw show the camera's embedded JPEG, which sits near the start of the file (a 24 MP Fuji RAF keeps its 5.6 MB JPEG in a 56 MB file), so the preview loader reads the header and that JPEG instead of the whole file: 56.5 MB → 5.9 MB and ~10 s → 0.96 s measured on one real RAF over a GVFS/SMB Wi-Fi share (byte-identical preview pixels; `LIGHTCRAFT_PROFILE=1` reports the bytes); the RAF pointer is read from its fixed header fields, a CR3's boxes and a TIFF raw whose preview tag sits past the prefix are read through `lightcraft_raw::sparse::preview_plan`, which names the ranges `embedded_preview` reads and nothing else; a cached render as stand-in, an edited photo and a raw without an embedded JPEG still render; the formats it cannot describe (CRW/MRW/X3F are found by scanning, NEF/ORF/PEF probe from samples) keep the whole-file path, and a lying pointer, a short read or a file that changes underneath us falls back to it rather than losing the preview. An unedited raw's **grid thumbnail is that camera JPEG itself**, so no sensor decode is scheduled behind it (`Session::embedded_thumb_is_final`, `grid::skips_the_real_render`): drawing a 512 px thumbnail used to decode the whole raw — 45 s a photo at 1.2 MB/s, 8.3 GB for a 149-raw folder — and the queue it built delayed the render the user was waiting for. Stand-ins and grid thumbnails decode the smallest embedded JPEG that covers the requested size and is a copy of the largest (aspect ratio within 1 %, same component count), not always the largest, on the whole-file and the plan route alike: an A7R VI's 1616 × 1080 JPEG (0.3 MB) instead of its 9984 × 6656 one (5.6 MB), and mid-sized NEF / RW2 JPEGs; a DNG that keeps reduced-resolution copies of its LinearRaw image (Lightroom HDR/panorama merges) develops a thumbnail or preview from the smallest copy that covers it (512 px of a 23836 × 7078 pano: 38 s → 1.1 s) | | LR-IMP-CULL-AT-IMPORT | Culling analysis at import | P2 | 🟡 | `cmd:photo.analyze` | run Assisted Culling on the imported photos (they're selected after an import); not automatic | | LR-IMP-MOVE | Move on import [Classic] | P1 | ✅ | `cmd:library.import` (`mode` move), `crates/engine/src/import_move.rs`, `crates/engine/src/tests/import_move.rs`, `crates/ui-egui/src/dialogs/import.rs` | Transfer ▸ Move with Copy's destination, folders (day / month / one folder / custom template), rename template and example destination; XMP sidecars (both namings) move along; each source is removed only after its destination is written (hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate, unchecked files keep their sources, taken names get -1, -2…, never overwritten; if the rename sequence runs out, later files are reported as failed and earlier completed moves remain catalogued; files already in the destination/library are added in place; sources that can't be removed (read-only card) are kept and reported (`kept`). Undo removes the photos from the library but leaves the moved files at the destination. No Copy as DNG while moving | | LR-IMP-DNG-CONVERT | Convert to DNG on import [Classic] | P2 | ✅ | `cmd:library.import` (`dng`), `crates/ui-egui/src/dialogs/import.rs` | copy imports: Raw files ▸ Copy as DNG (lossless; the card is untouched); the raw copy is removed only once its DNG is verified and on disk (issue #106) | @@ -125,7 +125,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). |---|---|---|---|---|---| | LR-VIEW-PHOTOGRID | Justified photo grid | P0 | ✅ | `cmd:view.photoGrid`, `cmd:library.groups`, `cmd:library.sort` (`group`), `crates/ui-egui/src/panels/grid.rs`, `crates/catalog/src/dates.rs` | grouped by capture / import / edit date (day headers “Wednesday, 30 September 2026 · 12 photos”, months or years when zoomed out, or a fixed day/month/year/none choice in the sort menu); sticky header; clicking a header selects its photos; stacks never split; scrolls to the active photo only when it changes (or the grid comes back on screen), never on its own; a mouse-wheel notch scrolls a third of the grid's height, in both grids, as in Lightroom Classic (`theme::WHEEL_STRIP_SHARE`; trackpads scroll the points they report); queued embedded thumbnail stand-ins follow viewport priority changes without another extraction (`crates/ui-egui/src/render.rs`, issue #348; full-app visual/timing verification pending); selected photos are ringed in the theme's colours (`Tokens::ring_active` / `ring_selected`, 3:1 or more against the grid in every theme): the active photo gets a 3 pt two-tone ring (a thin inner line against the photo, so it shows on a white photo too), the other selected photos a 1.5 pt ring; the empty view (an empty album or other source in a library with photos, or an empty Recently Deleted) names Import Photos' shortcut as the menu bar writes it and as bound (⌘⇧I on macOS, Ctrl+Shift+I elsewhere), and none when it is unbound | | LR-VIEW-SQUAREGRID | Square grid | P0 | ✅ | `cmd:view.squareGrid` | same date headers and selection rings as the photo grid | -| LR-VIEW-DETAIL | Single-photo view | P0 | ✅ | `cmd:view.detail`, `crates/ui-egui/src/panels/detail.rs` | a “Rendering…” pill at the bottom of the photo (widget `loupe:rendering`; above the Navigator when that is in the way) once a render has been on its way for 0.5 s with nothing new on screen: over a stand-in (the raw's embedded JPEG, a thumbnail), the previous render after an edit, or, zoomed in, the magnified frame waiting for its window; Before views watch their own renders. Always on (Lightroom Classic makes it a View Options choice). When the render fails behind a stand-in, a caution pill says “This photo can't be opened” (“Original offline · no smart preview” when that is why) with the reason on hover and for screen readers (widget `loupe:renderFailed`; `ui.inspect` → `loupe.failed`) | +| LR-VIEW-DETAIL | Single-photo view | P0 | ✅ | `cmd:view.detail`, `crates/ui-egui/src/panels/detail.rs` | a “Rendering…” pill at the bottom of the photo (widget `loupe:rendering`; above the Navigator when that is in the way) once a render has been on its way for 0.5 s with nothing new on screen: over a stand-in (the raw's embedded JPEG, a thumbnail), the previous render after an edit, or, zoomed in, the magnified frame waiting for its window; Before views watch their own renders. Always on (Lightroom Classic makes it a View Options choice). When the render fails behind a stand-in, a caution pill says “This photo can't be opened” (“Original offline · no smart preview” when that is why) with the reason on hover and for screen readers (widget `loupe:renderFailed`; `ui.inspect` → `loupe.failed`). While the camera's embedded JPEG is on screen a “Camera preview” label at the top right says so, with what that means on hover (widget `loupe:cameraPreview`), so colour isn't judged on it. Culling: the stand-ins of the next five photos in the direction of travel and the one behind are made ahead and taken over at the step (`render::Slot::QuickAhead`; EOS R5 C wedding: step to the camera JPEG p50 187 → 0 ms), decoded camera JPEGs stay in memory for a step back, zoomed in on an unedited raw the camera JPEG is shown at full size under the window render until that arrives (100 % in ~0.9 s instead of ~5.6 s, `render::Slot::QuickFull`), and while an arrow key is held the raw render waits until a photo stays 0.12 s (`crates/ui-egui/src/loupe_timing.rs`); `ui.inspect` → `perf.loupeSteps` times each step on the frames drawn | | LR-VIEW-EDIT | Edit view | P0 | ✅ | `cmd:panel.edit` | | | LR-VIEW-FULLSCREEN | Full-screen preview | P1 | ✅ | `cmd:view.fullScreenPreview`, `cmd:view.enterFullScreen` | photo on black, arrows step, Esc exits; ⇧⌘F window full screen | | LR-VIEW-FILMSTRIP | Filmstrip | P0 | ✅ | `cmd:view.filmstrip`, `crates/ui-egui/src/panels/detail.rs` | the photo context menu on right-click; the mouse wheel scrolls it sideways, a third of its width per notch as in Lightroom Classic (trackpads scroll the points they report); it follows the active photo only when that changes (centred if off screen), so a scrolled strip stays put; every selected photo has the selected background; selected photos with a loaded thumbnail also show a ring, the active one in the heavier two-tone ring and the others in the lighter one, in the theme's colours, as in the grid (a selected cell with no thumbnail, still loading or failed, has the background and no ring); a drag from a cell carries the selection (a photo outside it drags alone and replaces it; in Compare it drags alone and leaves the selection, the active photo and the pair as they are) to the same sidebar rows as a drag from the grid, and a click without movement works as before (it selects the photo; in Compare it goes to the active side, see LR-VIEW-COMPARE) | @@ -430,7 +430,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| | LR-PREF-GENERAL | General settings | P0 | ✅ | `cmd:app.settings`, `cmd:app.openLibrary`, `crates/ui-egui/src/dialogs/settings.rs`, `crates/ui-egui/src/panels/notices.rs` | General / Import / Performance / Display / Interface tabs; app settings in ui.json (written atomically, saved when the library changes and every few seconds), library settings in prefs.json; At launch: open the last library or ask (see LRC-LIB-CATALOG-SWITCH); a damaged settings file is kept as `.corrupt-