diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a90fad3905..a9d4d065a3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -85,3 +85,4 @@ jobs: AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} diff --git a/.gitignore b/.gitignore index 8c2047fe6b..c88ace5fa4 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,6 @@ plan/ # model weights are never committed (SAM 3: docs/ai-masks.md) *.safetensors *.safetensors.part + +# Python tools import their public operator family. +__pycache__/ diff --git a/Cargo.lock b/Cargo.lock index 4115a749a0..1d0bb2bdc2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1181,6 +1181,14 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-crw" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f3b62ec61f45534392376492fc5ad33047375205#f3b62ec61f45534392376492fc5ad33047375205" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-docpath" version = "0.1.0" @@ -1680,6 +1688,19 @@ dependencies = [ "winit", ] +[[package]] +name = "egui_extras" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +dependencies = [ + "ahash", + "egui", + "enum-map", + "itertools 0.15.0", + "log", + "profiling", +] + [[package]] name = "egui_glow" version = "0.37.0" @@ -1766,6 +1787,26 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "enum-map" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06" +dependencies = [ + "enum-map-derive", +] + +[[package]] +name = "enum-map-derive" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "enumflags2" version = "0.7.12" @@ -3724,6 +3765,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", + "unicode-normalization", "unicode-segmentation", "web-time", ] @@ -3754,6 +3796,13 @@ dependencies = [ "webpki-roots", ] +[[package]] +name = "lightcraft-film" +version = "0.18.0" +dependencies = [ + "libm", +] + [[package]] name = "lightcraft-geocode" version = "0.18.0" @@ -3902,6 +3951,8 @@ dependencies = [ name = "lightcraft-raw" version = "0.18.0" dependencies = [ + "chrono", + "craft-crw", "dhat", "jpeg-encoder", "jxl-oxide", @@ -3981,6 +4032,7 @@ dependencies = [ "craft-update", "craft-window", "egui", + "egui_extras", "egui_kittest", "lightcraft-catalog", "lightcraft-codecs", @@ -3998,6 +4050,7 @@ dependencies = [ "lightcraft-slideshow", "lightcraft-testkit", "log", + "pollster 1.0.1", "serde", "serde_json", "toml", @@ -4013,9 +4066,11 @@ dependencies = [ "egui", "js-sys", "lightcraft-codecs", + "lightcraft-color", "lightcraft-engine", "lightcraft-preview", "lightcraft-raster", + "lightcraft-raw", "lightcraft-ui-egui", "log", "serde", @@ -6598,6 +6653,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" version = "1.53.1" @@ -6804,6 +6865,15 @@ version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + [[package]] name = "unicode-properties" version = "0.1.4" @@ -8211,11 +8281,6 @@ name = "egui_demo_lib" version = "0.37.0" source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" -[[patch.unused]] -name = "egui_extras" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" - [[patch.unused]] name = "egui_inspection" version = "0.37.0" diff --git a/Cargo.toml b/Cargo.toml index eb363f491e..061507c999 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,8 @@ repository = "https://github.com/storytold/lightcraft" [workspace.dependencies] craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["serde"] } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } +# Canon CRW decoder shared with the other Craft apps +craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "f3b62ec61f45534392376492fc5ad33047375205" } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } @@ -28,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" } @@ -60,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/README.md b/README.md index e6ac8db59a..1b64265b3a 100644 --- a/README.md +++ b/README.md @@ -349,7 +349,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det casual use.** It's great for JPEG/DNG and most Sony / Panasonic / Fujifilm / Nikon / older-Canon raws on one machine; see [docs/raw-parity.md](docs/raw-parity.md) for your camera. - **The biggest gaps:** - - **camera colour calibration:** Sony, Nikon, Panasonic, Fujifilm and Canon CR3 raws have guarded estimates from their camera JPEGs, with built-in ILCA-99M2, ILCE-7CR, ILCE-7M4, ILCE-7RM5, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300 profiles; measured calibration is missing, and other raws or rejected fits retain a neutral matrix; + - **camera colour calibration:** Sony, Nikon, Panasonic, Fujifilm and Canon CR3 and CRW raws have guarded estimates from their camera JPEGs, with built-in Canon EOS D60, ILCA-99M2, ILCE-7CR, ILCE-7M4, ILCE-7RM5, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300 profiles; measured calibration covers one model so far (chart-measured matrices for the Canon EOS D60), and other raws or rejected fits retain a neutral matrix; - **compressed Olympus raws and unsupported CR3 variants:** these use embedded JPEG previews when present. Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md); - **AI quality and model setup:** Subject and Sky selection are classical heuristics; Object/Describe use an optional SAM 3 model. AI Denoise supports Bayer RAW with separately installed weights, while X-Trans and diff --git a/ROADMAP.md b/ROADMAP.md index 0571abfb99..471496ecd1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~14 points and ~340–600 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (gap 9: CI runs the tests on Linux x64 since #2667; macOS, Windows and the GPU equivalence tests still don't; the lens profile database priority links its tracking issue #329; Print: Japanese photo and postcard paper sizes — L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺; Minolta MRW decoded, 6 bodies verified; RAW: 83% of Adobe's models decode, 38% verified after the camera-coverage sweep #1327; German catalog 91% → 97%: interface strings and What's New lines translated) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (Canon CRW decoded clean-room, 6 bodies verified, 557 models verified; gap 9: CI runs the tests on Linux x64 since #2667; macOS, Windows and the GPU equivalence tests still don't; the lens profile database priority links its tracking issue #329; Print: Japanese photo and postcard paper sizes — L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺; Minolta MRW decoded, 6 bodies verified; RAW: 85% of Adobe's models decode, 39% verified after the camera-coverage sweep #1327; German catalog 91% → 97%: interface strings and What's New lines translated) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 One-page summary of how close LightCraft is to Adobe Lightroom. Agents: read this, then pick work from [docs/gaps.md](docs/gaps.md). The full assessment, method and evidence are in @@ -45,7 +45,7 @@ Hours are calibrated on this repo's PR history; see | Dimension | Ready | Breadth | Remaining | Doc | |---|---:|---:|---:|---| | Features | ~61% | ~77% (checklist 81.1%) | 600–1,100 h | [target-app-parity](docs/target-app-parity.md#features) | -| ↳ RAW cameras, colour, lens profiles | ~60% | 83% of 1,446 Adobe models decode, 38% verified | 255–480 h | [raw-parity](docs/raw-parity.md) | +| ↳ RAW cameras, colour, lens profiles | ~60% | 85% of 1,446 Adobe models decode, 39% verified | 255–480 h | [raw-parity](docs/raw-parity.md) | | UI/UX fidelity | ~70% | ~85% | 32–54 h | [ui-parity](docs/ui-parity.md) | | File formats (non-raw) | ~70% | ~85% | 30–55 h | [file-format-parity](docs/file-format-parity.md) | | Hardware | ~40% | ~50% | 40–80 h | [hardware-parity](docs/hardware-parity.md) | @@ -119,6 +119,12 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/ 六切 (203 × 254), 四切 (254 × 305) and 名刺 (55 × 91) — at their exact metric sizes. The Print dialog and `print.set` take their customary names, and names are matched case-, space- and punctuation-insensitively (`L判`, `l`, `L-size` are one paper). +- 2026-10-13: Canon CRW (the 2000–2004 CIFF bodies) decodes from sensor data: compression + derived clean-room against a black-box reference and frozen (`craft-libs crates/crw/clean-room/02-crw-format.md`); + EOS D30/D60/10D/300D and PowerShot G1/G6 verified pixel-exact on 28 of 29 corpus files (18 of + them the maintainer's D60 shots); as-shot white balance, black level, rotation and capture time + from the CIFF records; the PowerShot G5's anomalous coding stays preview-only. With the + camera-coverage sweep and MRW merged, 557 models verified; Canon bucket 95% → 98%. - 2026-10-14: Camera-coverage sweep verifies 30 more models on 40 CC0 files, with file and sensor hashes pinned (`docs/raw/coverage.py`: 515 → 545 verified). Eleven candidates excluded after rechecking identity, provenance and camera-image agreement. Phone and drone DNG tone differences remain tracked in #1277. @@ -194,6 +200,7 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/ | 2026-10-24 | patch | Alpha rationale: tests run in CI on Linux x64 (#2667) and FreeBSD nightly, not on macOS or Windows; ranked item 8 now reads "Tests in CI on macOS and Windows, and the GPU tests in CI"; percentages and hours unchanged | | 2026-10-22 | minor | Print: Japanese photo and postcard paper sizes (L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺) in the page setup, Print dialog and PDF output; headline numbers unchanged | | 2026-10-19 | minor | Indonesian interface (`id`): every plain and formats message, plus 69 command labels, locale, menu command and tests; What's New left in English; Localization ~55% → ~64% (mean of the 12 key languages), 8 of 12 present | +| 2026-10-13 | minor | Canon CRW decoded (clean-room): 6 bodies verified pixel-exact, G5 preview; 551 models verified after merging the coverage sweep | | 2026-10-12 | minor | Italian interface (`it`, #1192): 2,201 of 2,398 messages, locale, menu command and tests; headline numbers unchanged | | 2026-10-13 | minor | Sony ILCA-99M2 camera colour profile in the log; numbers unchanged | | 2026-10-14 | minor | Localization ~52% → ~55% (mean of the 12 key languages): de, es, fr, ja and uk catalogs filled | diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rs index dcb5280f61..7822bbed9a 100644 --- a/apps/lightcraft-cli/src/main.rs +++ b/apps/lightcraft-cli/src/main.rs @@ -106,7 +106,7 @@ USAGE: lightcraft-cli controls [--json] list every develop control id with its range lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS/FILES… Fit a colour profile per camera model from raw files and their embedded camera JPEGs - (Sony ARW, Nikon NEF, Fujifilm RAF): up to N files spread over the folders (default 300; 0 = all), pooled per + (Sony ARW, Nikon NEF, Fujifilm RAF, Canon CRW): up to N files spread over the folders (default 300; 0 = all), pooled per 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. @@ -196,26 +196,35 @@ fn main() -> ExitCode { } /// Raw files below `path` (or `path` itself), skipping hidden and NAS metadata folders. -fn raw_files(path: &Path, out: &mut Vec, depth: usize) { - let is_raw = - |p: &Path| p.extension().and_then(|e| e.to_str()).is_some_and(|e| ["arw", "nef", "nrw", "raf"].iter().any(|x| e.eq_ignore_ascii_case(x))); +/// +/// Folders go through the engine's bounded walk ([`lightcraft_engine::walk::files_in`]): it enters +/// a folder reached through a link once at most and stops at a depth and an entry budget. A +/// folder of links pointing back at their parents made the old recursive walk re-read the same +/// folders exponentially often before its depth limit cut it off (CWE-400). +fn raw_files(path: &Path, out: &mut Vec) { + let is_raw = |p: &Path| { + p.extension().and_then(|e| e.to_str()).is_some_and(|e| ["arw", "nef", "nrw", "raf", "crw"].iter().any(|x| e.eq_ignore_ascii_case(x))) + }; if path.is_file() { if is_raw(path) { out.push(path.to_path_buf()); } return; } - let Ok(entries) = std::fs::read_dir(path) else { return }; - if depth > 32 { - return; - } - for entry in entries.flatten() { - let name = entry.file_name(); - if name.to_string_lossy().starts_with(['.', '@']) { - continue; - } - raw_files(&entry.path(), out, depth + 1); + // (hidden entries are left out by the walk; `@eaDir` and other NAS metadata folders and files + // here, folders before they are listed so their entries do not use up the walk's budget) + let nas_metadata = |p: &Path| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with('@')); + let walked = lightcraft_engine::walk::files_in_entering( + path, + None, + lightcraft_engine::walk::Limits::default(), + |p| is_raw(p) && !nas_metadata(p) && p.is_file(), + |p| !nas_metadata(p), + ); + if walked.truncated { + eprintln!("calibrate: {} has more folders or entries than a walk looks at; the rest is left out", path.display()); } + out.extend(walked.files); } fn calibrate(args: &[String]) -> Result<(), String> { @@ -237,7 +246,7 @@ fn calibrate(args: &[String]) -> Result<(), String> { } let mut files = Vec::new(); for input in &inputs { - raw_files(Path::new(input), &mut files, 0); + raw_files(Path::new(input), &mut files); } files.sort(); files.dedup(); @@ -425,7 +434,7 @@ fn merge(args: &[String]) -> Result<(), String> { } i += 1; } - let mut s = Session::new().with_fs().with_default_denoise_models().with_system_clock(); + let mut s = file_session(); let paths = expand_paths(&files); let r = s.execute("library.import", &json!({"paths": paths})).map_err(|e| e.to_string())?; let mut ids: Vec = r["imported"].as_array().map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(); @@ -703,6 +712,12 @@ fn read_settings(p: &str) -> Result { } } +/// The session `render` and `merge` develop files in: with the lens database the desktop app downloaded, when it is +/// there (never fetched from here: scripts and tests stay offline). +fn file_session() -> Session { + Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_lens_database() +} + fn render(args: &[String]) -> Result<(), String> { let mut input = None; let mut output = None; @@ -741,7 +756,7 @@ fn render(args: &[String]) -> Result<(), String> { } let input = input.ok_or("render: missing input file")?; let output = output.ok_or("render: missing -o OUTPUT")?; - let mut s = Session::new().with_fs().with_default_denoise_models().with_system_clock(); + let mut s = file_session(); let abs = expand_paths(std::slice::from_ref(&input)); let r = s.execute("library.import", &json!({"paths": abs})).map_err(|e| e.to_string())?; let id = r["imported"][0].as_u64().ok_or_else(|| format!("{input}: not a readable photo"))?; @@ -836,15 +851,30 @@ fn snapshot(args: &[String]) -> Result<(), String> { let t0 = Instant::now(); let mut session = match &library { Some(dir) => { - let mut s = - Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_slide_templates(); + let mut s = Session::new() + .with_fs() + .with_default_denoise_models() + .with_system_clock() + .with_default_face_models() + .with_default_lens_database() + .with_default_slide_templates(); s.open_library(dir, false).map_err(|e| library_error(dir, e))?; s } - None if files.is_empty() => { - Session::with_demo().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_slide_templates() - } - None => Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_slide_templates(), + None if files.is_empty() => Session::with_demo() + .with_fs() + .with_default_denoise_models() + .with_system_clock() + .with_default_face_models() + .with_default_lens_database() + .with_default_slide_templates(), + None => Session::new() + .with_fs() + .with_default_denoise_models() + .with_system_clock() + .with_default_face_models() + .with_default_lens_database() + .with_default_slide_templates(), }; // Apply compute policy before imports or the first scripted query can discover an adapter. session.execute("app.gpu", &json!({"enabled": false})).map_err(|e| e.to_string())?; @@ -1069,6 +1099,47 @@ fn denoise_serve(_: &[String]) -> Result<(), String> { Err("denoise-serve: this build has no denoise support (build with the `denoise` feature)".into()) } +#[cfg(all(test, unix))] +mod raw_files_tests { + use super::raw_files; + + /// Links back to their own folders are entered once, not once per path that reaches them: a + /// handful of such links made the old walk list the same folders exponentially often. + #[test] + fn folder_links_back_up_are_walked_once() { + let dir = std::env::temp_dir().join(format!("lightcraft-cli-raw-files-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let a = dir.join("a"); + std::fs::create_dir_all(a.join("@eaDir")).unwrap(); + std::fs::write(a.join("one.NEF"), b"").unwrap(); + std::fs::write(a.join("@eaDir").join("thumb.nef"), b"").unwrap(); + std::fs::write(a.join("notes.txt"), b"").unwrap(); + for i in 0..8 { + std::os::unix::fs::symlink(&dir, a.join(format!("up{i}"))).unwrap(); + } + // a named pipe with a raw extension: not a file, so never opened (a read would block) + assert!(std::process::Command::new("mkfifo").arg(a.join("pipe.nef")).status().unwrap().success()); + let started = std::time::Instant::now(); + let mut files = Vec::new(); + raw_files(&dir, &mut files); + assert!(started.elapsed() < std::time::Duration::from_secs(10), "walk took {:?}", started.elapsed()); + assert_eq!(files, vec![a.join("one.NEF")]); + let _ = std::fs::remove_dir_all(&dir); + } +} + +#[cfg(test)] +mod tests { + /// `render` and `merge` read the lens database the desktop app downloaded, as the desktop does (the same raw + /// gets the same profile everywhere), but never fetch it. + #[test] + fn render_reads_the_downloaded_lens_database() { + let s = super::file_session(); + assert_eq!(lightcraft_engine::lens_profiles::host_dir(), lightcraft_engine::lensfun_download::default_dir()); + assert!(!s.lens_auto_download, "selecting it is not permission to download it"); + } +} + #[cfg(test)] mod import_target_tests { use super::{import_and_select, import_targets, json}; 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/backup.rs b/apps/lightcraft-web/src/backup.rs index 281a32296d..6a4dd205e5 100644 --- a/apps/lightcraft-web/src/backup.rs +++ b/apps/lightcraft-web/src/backup.rs @@ -233,6 +233,25 @@ pub fn parse_central(cd: &[u8]) -> Result, String> { Ok(out) } +/// What a restore writes, each storage key once, checked against the whole directory before any +/// payload is read: a backup names a file once, so a directory naming the same destination again +/// is damaged or altered, and its entries' bytes can't add up to more than the file holds (a +/// directory can point many entries at one stored range and have each read, checked and written). +pub fn restore_plan<'a>(entries: &'a [ZipEntry], dir: &str, file_len: u64) -> Result, String> { + let mut seen = std::collections::HashSet::new(); + let mut plan = Vec::new(); + let mut bytes = 0u64; + for e in entries { + let Some(key) = restore_key(&e.name, dir) else { continue }; + if !seen.insert(key.clone()) { + return Err(format!("{}: listed twice (damaged or altered backup)", e.name)); + } + bytes = bytes.checked_add(e.size).filter(|&b| b <= file_len).ok_or_else(|| format!("{}: entries larger than the backup itself", e.name))?; + plan.push((key, e)); + } + Ok(plan) +} + /// Offset of an entry's data from its local header's first 30 bytes. pub fn data_offset(entry: &ZipEntry, local: &[u8]) -> Result { if rd32(local, 0) != Some(LOCAL_SIG) { @@ -342,6 +361,23 @@ mod tests { assert!(!valid_library_dir("library-../x") && !valid_library_dir("originals") && !valid_library_dir("library-")); } + #[test] + fn restore_plan_refuses_repeated_and_oversized_entries() { + let entry = |name: &str, size: u64| ZipEntry { name: name.into(), crc: 0, size, header: 0, method: 0 }; + let ok = [entry("README.txt", 10), entry("library/catalog.log", 10), entry("originals/abc123/a.jpg", 100)]; + let plan = restore_plan(&ok, "d", 200).unwrap(); + assert_eq!(plan.iter().map(|(k, _)| k.as_str()).collect::>(), ["d/catalog.log", "originals/abc123"]); + // one stored range named 3 times would be read, checked and written 3 times + let twice = [entry("originals/abc123/a.jpg", 100), entry("originals/abc123/b.jpg", 100)]; + assert!(restore_plan(&twice, "d", 1000).unwrap_err().contains("twice")); + let twice = [entry("library/catalog.log", 10), entry("library/catalog.log", 10)]; + assert!(restore_plan(&twice, "d", 1000).is_err()); + // entries claiming more bytes than the file has + let big = [entry("library/catalog.log", 150), entry("originals/abc123/a.jpg", 100)]; + assert!(restore_plan(&big, "d", 200).is_err()); + assert!(restore_plan(&[entry("library/catalog.log", u64::MAX), entry("library/presets.json", 1)], "d", u64::MAX).is_err()); + } + #[test] fn size_limits_are_errors_not_panics() { let mut w = ZipWriter { offset: MAX_BYTES - 10, ..Default::default() }; diff --git a/apps/lightcraft-web/src/bench.rs b/apps/lightcraft-web/src/bench.rs index 484c0041f6..4864834c75 100644 --- a/apps/lightcraft-web/src/bench.rs +++ b/apps/lightcraft-web/src/bench.rs @@ -2,6 +2,9 @@ //! control exactly like a slider drag (begin interaction → N `develop.set` → end) and time each //! step from the command to the moment the new loupe texture is ready. Results go to the log //! (the browser console on the web) as one `lightcraft-bench {…json…}` line. +//! +//! The web host runs it only on the generated demo photos in an unsaved library (`?bench` implies `?store=memory`): it +//! commits edits to the photo it opens, which must never be one in the user's stored library. use lightcraft_ui_egui::LightcraftApp; use lightcraft_ui_egui::render::Slot; diff --git a/apps/lightcraft-web/src/lib.rs b/apps/lightcraft-web/src/lib.rs index 5d3c011589..6a6b83b728 100644 --- a/apps/lightcraft-web/src/lib.rs +++ b/apps/lightcraft-web/src/lib.rs @@ -11,7 +11,8 @@ //! - export downloads the file through the browser. //! //! `?bench` in the URL runs a scripted first-paint / slider-latency measurement and logs it to the -//! console (see [`bench`]); `?store=idb` forces the IndexedDB backend, `?store=memory` disables +//! console (see [`bench`]) on the generated demo photos in an unsaved library (it implies `?store=memory`, so it never edits +//! the library in browser storage); `?store=idb` forces the IndexedDB backend, `?store=memory` disables //! persistence and `?workers=0` renders on the main thread. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] diff --git a/apps/lightcraft-web/src/safety.rs b/apps/lightcraft-web/src/safety.rs index 137b525039..8bffc818d0 100644 --- a/apps/lightcraft-web/src/safety.rs +++ b/apps/lightcraft-web/src/safety.rs @@ -13,7 +13,7 @@ use wasm_bindgen_futures::JsFuture; use crate::backend::Backend; use crate::backup::{ - ACTIVE_LIBRARY, README, ZipWriter, data_offset, find_central, original_entry, parse_central, restore_key, restored_dir_name, tail_len, + ACTIVE_LIBRARY, README, ZipWriter, data_offset, find_central, original_entry, parse_central, restore_plan, restored_dir_name, tail_len, valid_hash, verify, verify_original, }; use crate::files::{Files, LIBRARY_FILES}; @@ -214,8 +214,7 @@ pub async fn restore(file: web_sys::File, backend: Backend) -> Result (FileLoader, FileProbe) { let s = self.clone(); - let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize| { + // (an imported camera profile is not applied on the web, as in the render worker: a raw keeps its own colour, + // whether it decodes in a worker or inline when workers are unavailable) + let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, _dcp: Option<&lightcraft_engine::media::DcpProfile>| { let bytes = s.get(path).ok_or_else(|| format!("{path}: the original is still loading from browser storage"))?; - load_bytes(&bytes, max_edge) + load_bytes_with(&bytes, max_edge, None) }); let s = self.clone(); let probe: FileProbe = Arc::new(move |path: &str| { @@ -237,6 +239,64 @@ mod tests { assert_eq!(out.image.width, 20); } + /// CodeRabbit on #1063: without web workers a render runs inline and handed the selected camera profile to this + /// loader, which applied it, so the picture differed from the worker's (which keeps the raw's own colour, the + /// documented web behaviour). The loader now ignores it. + #[test] + fn the_web_loader_keeps_a_raws_own_colour_with_a_camera_profile() { + use lightcraft_raw::*; + let (w, h) = (32usize, 24usize); + let raw = RawImage { + format: RawFormat::Dng, + width: w, + height: h, + cpp: 1, + data: RawData::U16((0..w * h).map(|i| 256 + ((i % w) * 300 + (i / w) * 200) as u16).collect()), + cfa: Cfa::bayer("RGGB"), + bits: 14, + black: BlackLevel::uniform(256.0), + white: vec![16000.0], + active_area: Rect::new(0, 0, w, h), + crop: Rect::new(0, 0, w, h), + orientation: Orientation::Normal, + color: ColorData { + illuminant: [21, 0], + color_matrix: [Some(lightcraft_color::Mat3([[0.9, 0.2, -0.15], [-0.3, 1.25, 0.08], [0.02, -0.12, 0.85]])), None], + as_shot_neutral: Some([0.5, 1.0, 0.7]), + ..Default::default() + }, + wb_multipliers: None, + linearized: false, + pixel_aspect: 1.0, + opcodes: OpcodeLists::default(), + metadata: Default::default(), + lens_metadata: Default::default(), + }; + let dng = write_dng(&raw, &DngWriteOptions::default()).unwrap(); + // our own numbers: a matrix that swaps the camera's red and blue + let swap = lightcraft_color::Mat3([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]).mul(&lightcraft_color::Mat3([ + [3.2406, -1.5372, -0.4986], + [-0.9689, 1.8758, 0.0415], + [0.0557, -0.2040, 1.0570], + ])); + let profile = dcp::DcpProfile { + name: "Swap".into(), + camera_model: "LightCraft Test Camera".into(), + color: ColorData { illuminant: [21, 0], color_matrix: [Some(swap), None], ..Default::default() }, + }; + assert_ne!( + load_bytes_with(&dng, 64, Some(&profile)).unwrap().0.data, + load_bytes_with(&dng, 64, None).unwrap().0.data, + "the profile changes a raw's colour where it is applied" + ); + let store = Originals::default(); + store.insert("h1", Arc::from(dng)); + let (loader, _) = store.hooks(); + let with = loader("web/h1/a.dng", 64, Some(&profile)).unwrap(); + let without = loader("web/h1/a.dng", 64, None).unwrap(); + assert_eq!(with.0.data, without.0.data, "the web loader leaves it out"); + } + #[test] fn download_names() { assert_eq!(download_name("dir/x-lightcraft.png"), "x-lightcraft.png"); diff --git a/apps/lightcraft-web/src/web.rs b/apps/lightcraft-web/src/web.rs index bd5215e4d4..b1eaa6b2bb 100644 --- a/apps/lightcraft-web/src/web.rs +++ b/apps/lightcraft-web/src/web.rs @@ -90,10 +90,13 @@ impl Options { }) .collect(); let get = |k: &str| params.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone()); + let bench = get("bench").is_some(); Options { - bench: get("bench").is_some(), - store: get("store").filter(|s| s == "idb" || s == "memory").unwrap_or_else(|| "opfs".into()), - workers: get("workers").and_then(|v| v.parse().ok()), + bench, + // the benchmark edits the first photo it finds: a link with `?bench` must never reach + // the library in browser storage, so it always runs on the demo photos in an unsaved library + store: if bench { "memory".into() } else { get("store").filter(|s| s == "idb" || s == "memory").unwrap_or_else(|| "opfs".into()) }, + workers: get("workers").and_then(|v| v.parse().ok()).map(|n: usize| n.min(crate::workers::MAX_WORKERS)), reset: get("reset").is_some(), } } @@ -496,6 +499,10 @@ impl WebApp { }); } } + // `?bench` never has storage (see `Options::from_url`): it measures the generated demo photos + if opts.bench && backend.is_none() && session.catalog.len() == 0 { + lightcraft_engine::demo::load(&mut session); + } if backend.is_some() { notice( "LightCraft in the browser is experimental. Your library is kept in this browser's storage: keep your original photos \ diff --git a/apps/lightcraft-web/src/workers.rs b/apps/lightcraft-web/src/workers.rs index a5e64886e3..56f7abea4a 100644 --- a/apps/lightcraft-web/src/workers.rs +++ b/apps/lightcraft-web/src/workers.rs @@ -207,6 +207,15 @@ impl Inner { } } +/// The most workers started, whatever `?workers=` asks: more than this brings nothing to a +/// render queue and a link can't make the page spawn workers (and their copies of the module) +/// without end. +pub const MAX_WORKERS: usize = 16; + +/// Worker constructions failing in a row after which the rest are not tried: a browser that +/// refused this many refuses the next ones too. +const MAX_FAILED_STARTS: usize = 3; + /// The main thread's handle on the render workers. #[derive(Clone)] pub struct Workers(Rc>); @@ -244,7 +253,12 @@ impl Workers { return w; } let mut slots = WorkerSlots::default(); - for attempt in 0..n { + let mut failed = 0; + for attempt in 0..n.min(MAX_WORKERS) { + if failed >= MAX_FAILED_STARTS { + log::warn!("render workers: {failed} failed to start in a row; not trying the rest"); + break; + } // The callbacks name their worker by its place in `workers`; a failed attempt takes none. let i = slots.peek(); let opts = web_sys::WorkerOptions::new(); @@ -254,6 +268,7 @@ impl Workers { Ok(x) => x, Err(e) => { log::warn!("render worker {attempt}: {e:?}"); + failed += 1; continue; } }; @@ -274,10 +289,12 @@ impl Workers { worker.set_onmessage(None); worker.set_onerror(None); worker.terminate(); + failed += 1; continue; } w.0.borrow_mut().workers.push(W { worker, ready: false, dead: false, busy: None }); slots.commit(); + failed = 0; } w } @@ -301,6 +318,7 @@ impl Workers { loaded: None, quick: None, display: None, + frame: None, }; g.done.push((b.slot, r, 0.0)); } @@ -392,6 +410,7 @@ impl Workers { loaded: None, quick: None, display: None, + frame: None, }, ms, )); @@ -446,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/logging.rs b/apps/lightcraft/src/logging.rs index dd174972de..70d06a8c48 100644 --- a/apps/lightcraft/src/logging.rs +++ b/apps/lightcraft/src/logging.rs @@ -167,7 +167,19 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> { /// One formatted log line: ` [] : \n`. pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String { let message = message.strip_suffix('\n').unwrap_or(message); - format!("{ts} {level:<5} [{thread}] {target}: {message}\n") + // A message can carry text from files and peers (a file name, a rejected value): it must not be able to start a + // record of its own. Later lines of a multi-line message (a panic report) are indented, so none begins like a + // record; other control characters (a bare CR, an escape sequence) are shown escaped. + let mut safe = String::with_capacity(message.len()); + for c in message.chars() { + match c { + '\n' => safe.push_str("\n "), + '\t' => safe.push(c), + c if c.is_control() => safe.extend(c.escape_default()), + c => safe.push(c), + } + } + format!("{ts} {level:<5} [{thread}] {target}: {safe}\n") } /// Where formatted lines go besides standard error: kept in memory until a file is attached, diff --git a/apps/lightcraft/src/logging/tests.rs b/apps/lightcraft/src/logging/tests.rs index b801c7d75d..c96707d824 100644 --- a/apps/lightcraft/src/logging/tests.rs +++ b/apps/lightcraft/src/logging/tests.rs @@ -167,7 +167,11 @@ fn a_line_carries_time_level_thread_target_and_message() { "2026-10-08T07:59:17.728Z INFO [main] lightcraft: library /photos: 12 photos\n" ); // A multi-line message keeps its lines; the record still ends in one newline. - assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n")); + // later lines are indented and control characters escaped, so a message cannot forge a record + assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\n b\n")); + let forged = format_line("t", log::Level::Info, "w", "x", "name\r\n2026-01-01T00:00:00Z ERROR [main] x: fake\u{1b}[2J"); + assert!(forged.lines().skip(1).all(|l| l.starts_with(' ')), "{forged:?}"); + assert!(!forged.contains('\r') && !forged.contains('\u{1b}'), "{forged:?}"); } #[test] @@ -357,7 +361,7 @@ fn a_panic_report_goes_to_the_file_and_never_deadlocks() { logger.record_panic("main", "while the sink is held"); } let text = read(&path); - assert!(text.contains(" ERROR [render] lightcraft: panicked at crates/x/src/lib.rs:3:5:\nboom\n"), "{text}"); + assert!(text.contains(" ERROR [render] lightcraft: panicked at crates/x/src/lib.rs:3:5:\n boom\n"), "{text}"); assert!(!text.contains("while the sink is held"), "{text}"); let _ = std::fs::remove_dir_all(&dir); } 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/session.rs b/apps/lightcraft/src/session.rs index 7d9db79bdb..ac46a43b5d 100644 --- a/apps/lightcraft/src/session.rs +++ b/apps/lightcraft/src/session.rs @@ -255,6 +255,10 @@ pub(crate) fn open_session(in_memory: bool, launch: &Launch, seed_demo: bool) -> Launch::Ask => (Session::new().with_fs().with_default_denoise_models().with_system_clock(), None), Launch::Open { dir, remembered, .. } => open_library_session(in_memory, dir.clone(), *remembered, seed_demo), }; + // lens profiles from the app's own lensfun copy, offered on the first launch (not for a throwaway session) + if !in_memory { + s = s.with_default_lens_database().with_lens_auto_download(); + } s.face_models_dir = lightcraft_engine::config::default_face_models_dir(); s.slide_templates_dir = lightcraft_engine::config::config_dir().map(|d| d.join(lightcraft_engine::slide_template::DIR_NAME)); // Control requests are answered on the UI thread: Add to Apple Photos must not wait there diff --git a/apps/lightcraft/src/tests.rs b/apps/lightcraft/src/tests.rs index 286838175e..ca90ebb5cc 100644 --- a/apps/lightcraft/src/tests.rs +++ b/apps/lightcraft/src/tests.rs @@ -5,6 +5,7 @@ fn desktop_clear_color_stays_opaque_with_a_modal_open() { let mut app = App( LightcraftApp::new(Session::new(), Services::default()), PrefsWriter::default(), + None, #[cfg(target_os = "macos")] None, ); @@ -566,6 +567,7 @@ fn on_exit_ends_the_process_on_macos() { let mut app = App( app, PrefsWriter::default(), + None, #[cfg(target_os = "macos")] None, ); @@ -598,6 +600,7 @@ fn on_exit_removes_the_lock_owner_note() { let mut app = App( LightcraftApp::new(session, Services::default()), PrefsWriter::default(), + None, #[cfg(target_os = "macos")] None, ); diff --git a/apps/lightcraft/src/window_gpu.rs b/apps/lightcraft/src/window_gpu.rs index e8caedf738..1b3e2d6809 100644 --- a/apps/lightcraft/src/window_gpu.rs +++ b/apps/lightcraft/src/window_gpu.rs @@ -154,6 +154,15 @@ pub fn base_options() -> WgpuConfiguration { n.instance_descriptor.backend_options = backend::backend_options(); // no indirect-call validation pipeline: Intel Metal fails to compile it and the window never opens (#250) n.instance_descriptor.flags = backend::instance_flags_from_env(n.instance_descriptor.flags); + // the GPU renderer may run on this device (`adopt_window_device`): it needs the adapter's + // buffer limits (a 24 MP photo is a 275 MiB buffer), not wgpu's defaults + let default = n.device_descriptor.clone(); + n.device_descriptor = std::sync::Arc::new(move |adapter| { + if adapter.get_info().backend == wgpu::Backend::Gl { + return default(adapter); + } + wgpu::DeviceDescriptor { label: Some("lightcraft window"), required_limits: adapter.limits(), ..Default::default() } + }); } c } @@ -192,7 +201,8 @@ fn probe(backends: Backends, compose_window: bool) -> Result io::Result<()> + Send + Sync>; + +static HOOKS: Mutex> = Mutex::new(Vec::new()); + +/// Run `hook` before every write and sync of the catalog log in `dir` (replacing an earlier one). +#[doc(hidden)] +pub fn install(dir: &Path, hook: Hook) { + let mut hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner); + hooks.retain(|(d, _)| d != dir); + hooks.push((dir.to_path_buf(), hook)); +} + +/// Remove the hook of `dir`. +#[doc(hidden)] +pub fn remove(dir: &Path) { + HOOKS.lock().unwrap_or_else(PoisonError::into_inner).retain(|(d, _)| d != dir); +} + +static ON_CALLER: Mutex> = Mutex::new(Vec::new()); + +/// Write the log in `dir` on the caller's thread, syncing before each append returns, as builds +/// before PERF-STEP-STALL did: a test's "before" (stores opened afterwards; the hooks run there too). +#[doc(hidden)] +pub fn write_on_caller(dir: &Path, on: bool) { + let mut dirs = ON_CALLER.lock().unwrap_or_else(PoisonError::into_inner); + dirs.retain(|d| d != dir); + if on { + dirs.push(dir.to_path_buf()); + } +} + +pub(crate) fn on_caller(dir: &Path) -> bool { + let dirs = ON_CALLER.lock().unwrap_or_else(PoisonError::into_inner); + !dirs.is_empty() && dirs.iter().any(|d| d == dir) +} + +pub(crate) fn check(dir: &Path, step: Step) -> io::Result<()> { + let hook = { + let hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner); + if hooks.is_empty() { + return Ok(()); + } + hooks.iter().find(|(d, _)| d == dir).map(|(_, h)| h.clone()) + }; + match hook { + Some(h) => h(step), + None => Ok(()), + } +} diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index 2600d794a4..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 @@ -52,6 +55,8 @@ //! | 7 | Kelvin white balance for raws whose camera has matrices (#730) | `Op::SetAsShotWb`, `WhiteBalance.scale` | //! | 8 | History cursor: Go to History Step adds no step | `Op::SetHistoryCursor`, `Photo.history_cursor` | //! | 9 | preview-only recheck | `Photo.preview_checked`, `Op::SetContent.preview_checked` | +//! | 10 | masks stay on the photo under lens corrections, Upright and Transform | `Mask.on_photo` (develop settings) | +//! | 11 | lens database profiles named in the Optics panel | `EmbeddedLens.source` | //! //! Rules: //! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a @@ -76,7 +81,7 @@ pub const LOG: &str = "catalog.log"; const FORMAT: &str = "lightcraft-catalog"; /// The catalog format this build writes (and the newest it reads). See the module docs → /// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added. -pub const VERSION: u32 = 9; +pub const VERSION: u32 = 11; /// When [`Journal::wants_snapshot`] says it's time to compact the log. #[derive(Clone, Copy, Debug)] @@ -193,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. @@ -381,6 +390,7 @@ impl Journal { pending: None, retry_at_records: 0, tail_dirty: false, + snapshot_due: false, }; let log = log.unwrap_or_default(); @@ -514,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. @@ -676,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); @@ -695,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 } @@ -704,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/keywords.rs b/crates/catalog/src/keywords.rs index d36ab11cd6..5fb095767b 100644 --- a/crates/catalog/src/keywords.rs +++ b/crates/catalog/src/keywords.rs @@ -87,6 +87,12 @@ pub fn from_file(flat: &[String], hierarchical: &[String]) -> Vec { /// The deepest a keyword list file may nest keywords: a file is input, so its nesting is bounded. pub const MAX_LEVELS: usize = 64; +/// The most bytes of full keyword paths a keyword list file may spell out. Every line names its +/// keyword by its whole path (`parent|child`), so a file of one long keyword with many short ones +/// inside it would otherwise grow into far more memory than its own size (CWE-400). Lightroom +/// Classic's own lists of tens of thousands of keywords come to a few MiB. +pub const MAX_LIST_PATH_BYTES: usize = 64 << 20; // 64 MiB + /// A keyword list as written by [`Catalog::keyword_list_text`]: the file's text, the keywords in /// it (paths), and what the format can't hold and so is left out (a keyword, with those inside it, /// as its path; a synonym as `path {synonym}`). @@ -114,6 +120,8 @@ pub fn parse_keyword_list(text: &str) -> Result> { let mut synonyms: std::collections::HashMap> = std::collections::HashMap::new(); // the keyword at each level above the line: its path and where it is in `out` let mut above: Vec<(String, usize)> = Vec::new(); + // bytes of full paths spelled out so far, checked against `MAX_LIST_PATH_BYTES` before each + let mut path_bytes = 0usize; for (i, line) in text.split('\n').enumerate() { let n = i + 1; if line.trim().is_empty() { @@ -162,6 +170,11 @@ pub fn parse_keyword_list(text: &str) -> Result> { return Err(bad(n, "“|” separates a keyword's levels: a name can't hold one")); } above.truncate(depth); + let parent_len = above.last().map_or(0, |(parent, _)| parent.len().saturating_add(1)); + path_bytes = path_bytes.saturating_add(parent_len.saturating_add(name.len())); + if path_bytes > MAX_LIST_PATH_BYTES { + return Err(bad(n, &format!("the keywords' full paths come to more than {} MiB", MAX_LIST_PATH_BYTES >> 20))); + } let path = match above.last() { Some((parent, _)) => format!("{parent}{SEP}{name}"), None => name.to_string(), @@ -189,6 +202,14 @@ pub fn closest<'a>(k: &str, from: &'a [String]) -> Option<&'a String> { from.iter().filter(|f| is_under(k, f)).max_by_key(|f| f.split(SEP).count()) } +/// Add each of `more` to `synonyms` that isn't there in any case, in order. One lowered set of +/// what is there, not a search of the growing list per synonym: an imported list can give a +/// keyword many synonyms, and the search was quadratic in them (CWE-407). +fn merge_synonyms(synonyms: &mut Vec, more: impl IntoIterator) { + let mut seen: std::collections::HashSet = synonyms.iter().map(|s| s.to_lowercase()).collect(); + synonyms.extend(more.into_iter().filter(|s| seen.insert(s.to_lowercase()))); +} + /// Keep the first of case-insensitively equal keywords. fn dedupe(v: &mut Vec) { let mut seen = std::collections::HashSet::new(); @@ -402,11 +423,7 @@ impl Catalog { Some(there) => { there.info.new_keywords_inside |= l.info.new_keywords_inside; there.info.keyword_shortcut |= l.info.keyword_shortcut; - for s in l.info.synonyms { - if !there.info.synonyms.iter().any(|x| same(x, &s)) { - there.info.synonyms.push(s); - } - } + merge_synonyms(&mut there.info.synonyms, l.info.synonyms); } None => { list.insert(path.to_lowercase(), ListedKeyword { path, info: l.info }); @@ -467,8 +484,11 @@ impl Catalog { let defaults = KeywordInfo::default(); let info = |path: &str| self.keyword_info(path).unwrap_or(&defaults); let mut out = ExportKeywords::default(); - let push = |v: &mut Vec, s: &str| { - if !s.is_empty() && !v.iter().any(|x| same(x, s)) { + // what each list holds, lowered: a search of the list per name was quadratic in a keyword's + // synonyms, which an imported list sets (CWE-407) + let (mut flat_seen, mut paths_seen) = (std::collections::HashSet::new(), std::collections::HashSet::new()); + let push = |v: &mut Vec, seen: &mut std::collections::HashSet, s: &str| { + if !s.is_empty() && seen.insert(s.to_lowercase()) { v.push(s.to_string()); } }; @@ -481,11 +501,11 @@ impl Catalog { let levels: Vec<&str> = path.split(SEP).collect(); let mut names = |at: usize, i: &KeywordInfo| { if let Some(name) = levels.get(at) { - push(&mut out.flat, name); + push(&mut out.flat, &mut flat_seen, name); } if i.export_synonyms { for s in &i.synonyms { - push(&mut out.flat, s.trim()); + push(&mut out.flat, &mut flat_seen, s.trim()); } } }; @@ -499,7 +519,7 @@ impl Catalog { } } } - push(&mut out.hierarchical, &path); + push(&mut out.hierarchical, &mut paths_seen, &path); } out } @@ -509,6 +529,13 @@ impl Catalog { /// keyword, a keyword left out of export in square brackets; by name. What the format can't hold /// is left out and named, so the file always reads back. pub fn keyword_list_text(&self) -> KeywordListFile { + self.keyword_list_text_within(MAX_LIST_PATH_BYTES) + } + + /// [`keyword_list_text`](Self::keyword_list_text) with the full paths written held to + /// `max_path_bytes` as [`parse_keyword_list`] holds them: a keyword past it is named + /// unwritable, with its subtree, so the file reads back. + fn keyword_list_text_within(&self, max_path_bytes: usize) -> KeywordListFile { // a name the list would read as something else, or not at all fn unwritable(name: &str) -> bool { name.trim().is_empty() @@ -519,14 +546,27 @@ impl Catalog { || (name.starts_with('[') && name.ends_with(']')) || (name.starts_with('{') && name.ends_with('}')) } - fn write(c: &Catalog, nodes: &[KeywordNode], depth: usize, file: &mut KeywordListFile) { + fn write( + c: &Catalog, + nodes: &[KeywordNode], + depth: usize, + file: &mut KeywordListFile, + path_bytes: &mut usize, + max_path_bytes: usize, + parent_len: usize, + ) { let tabs = "\t".repeat(depth); for n in nodes { // the keywords inside go with it: under its parent they'd be other keywords - if depth >= MAX_LEVELS || unwritable(&n.name) { + // (a line's full path is what the reader counts against its path budget) + // the path the reader rebuilds from the lines written: the parent as emitted, a + // separator, the name (a child's `n.path` can spell its parent in another case) + let emitted = if depth == 0 { n.name.len() } else { parent_len + SEP.len_utf8() + n.name.len() }; + if depth >= MAX_LEVELS || unwritable(&n.name) || path_bytes.saturating_add(emitted) > max_path_bytes { file.unwritable.push(n.path.clone()); continue; } + *path_bytes += emitted; let info = c.keyword_info(&n.path).cloned().unwrap_or_default(); if info.include_on_export { file.text.push_str(&format!("{tabs}{}\n", n.name)); @@ -536,19 +576,21 @@ impl Catalog { file.written.push(n.path.clone()); // the reader trims synonyms and takes one per spelling: an empty one, or another's // in a different case, is no loss; a line break or a “|” is - let mut synonyms: Vec<&str> = Vec::new(); + // (one lowered set, not a search of those written so far per synonym: quadratic + // in a keyword's synonyms, which an imported list sets — CWE-407) + let mut synonyms: std::collections::HashSet = std::collections::HashSet::new(); for s in info.synonyms.iter().map(|s| s.trim()) { - if s.is_empty() || synonyms.iter().any(|x| same(x, s)) { + if s.is_empty() || synonyms.contains(&s.to_lowercase()) { continue; } if s.chars().any(char::is_control) || s.contains(SEP) { file.unwritable.push(format!("{} {{{s}}}", n.path)); } else { - synonyms.push(s); + synonyms.insert(s.to_lowercase()); file.text.push_str(&format!("{tabs}\t{{{s}}}\n")); } } - write(c, &n.children, depth + 1, file); + write(c, &n.children, depth + 1, file, path_bytes, max_path_bytes, emitted); } } let mut file = KeywordListFile::default(); @@ -568,7 +610,7 @@ impl Catalog { } } } - write(self, &self.keyword_tree(), 0, &mut file); + write(self, &self.keyword_tree(), 0, &mut file, &mut 0, max_path_bytes, 0); file.unwritable.extend(over_deep); file } @@ -632,11 +674,7 @@ impl Catalog { // one the library has: the list's synonyms join its own (listed only if it gains some) let mut info_now = list.get(&key).map(|l| l.info.clone()).unwrap_or_default(); let before = info_now.synonyms.len(); - for s in &info.synonyms { - if !info_now.synonyms.iter().any(|x| same(x, s)) { - info_now.synonyms.push(s.clone()); - } - } + merge_synonyms(&mut info_now.synonyms, info.synonyms.iter().cloned()); if info_now.synonyms.len() > before { let path = list.get(&key).map_or(path, |l| l.path.clone()); list.insert(key, ListedKeyword { path, info: info_now }); diff --git a/crates/catalog/src/keywords/tests.rs b/crates/catalog/src/keywords/tests.rs index 6f50bd482e..6b9e505c0f 100644 --- a/crates/catalog/src/keywords/tests.rs +++ b/crates/catalog/src/keywords/tests.rs @@ -556,6 +556,17 @@ fn the_keyword_list_is_written_as_tab_indented_text() { assert_eq!(c.keyword_list_text().text, "beach\nEvents\n\tWeddings\n[Places]\n\tLisbon\n\t\t{Lisboa}\n"); } +/// The path budget the reader enforces holds for the writer too: a keyword past it, and its +/// subtree, is named unwritable instead of making a file `keyword.import` rejects. +#[test] +fn the_keyword_list_written_stays_within_the_path_budget() { + let (c, _) = lib(&[&["Places|Lisbon", "beach"], &["Events|Weddings"]]); + let file = c.keyword_list_text_within(17); + assert_eq!(file.text, "beach\nEvents\nPlaces\n"); + assert_eq!(file.unwritable, ["Events|Weddings", "Places|Lisbon"]); + assert_eq!(c.keyword_list_text().unwritable, Vec::::new()); +} + /// Reading a list gives each keyword's path and attributes: what was written comes back, and a /// file from elsewhere (Windows line ends, a byte-order mark, blank lines) reads too. #[test] @@ -765,3 +776,47 @@ fn keyword_tree_caps_a_keyword_at_the_list_depth() { let deepest = tree_paths(&c.keyword_tree()).iter().map(|(p, _)| p.split(SEP).count()).max().unwrap_or(0); assert_eq!(deepest, MAX_LEVELS); } + +/// A keyword list file spells each keyword's whole path, so one long keyword with many short ones +/// inside it expands into far more than its own size: past `MAX_LIST_PATH_BYTES` it is refused +/// with the line where that happened, instead of growing without bound (CWE-400). +#[test] +fn a_list_whose_paths_expand_past_the_budget_is_refused() { + let parent = "p".repeat(1 << 20); + let children = MAX_LIST_PATH_BYTES / parent.len() + 2; + let mut text = format!("{parent}\n"); + for i in 0..children { + text.push_str(&format!("\tc{i}\n")); + } + let err = parse_keyword_list(&text).unwrap_err().to_string(); + assert!(err.contains("full paths come to more than"), "{err}"); + // a list within the budget still reads + let ok = parse_keyword_list(&format!("{parent}\n\tchild\n")).unwrap(); + assert_eq!(ok.len(), 2); + assert_eq!(ok[1].0, format!("{parent}|child")); +} + +/// Many synonyms joining a keyword the library has, its export and its keyword list file each keep +/// every spelling once, in order, without a search of the growing list per synonym (CWE-407). +#[test] +fn many_synonyms_are_gathered_once_each_in_order() { + const N: usize = 40_000; + let mut c = Catalog::new(); + c.apply(Op::SetKeyword { path: "travel".into(), info: Some(with_synonyms(&["Trip"])) }).unwrap(); + let mut incoming: Vec = (0..N).map(|i| format!("syn{i}")).collect(); + incoming.push("TRIP".into()); + incoming.push("SYN7".into()); + let started = std::time::Instant::now(); + let (op, added, updated) = c.import_keywords_ops(&[("travel".into(), KeywordInfo { synonyms: incoming, ..KeywordInfo::default() })]); + c.apply(op).unwrap(); + assert_eq!((added, updated), (0, 1)); + let synonyms = c.keyword_info("travel").unwrap().synonyms.clone(); + assert_eq!(synonyms.len(), N + 1); + assert_eq!(synonyms[0], "Trip"); + assert_eq!(synonyms[8], "syn7"); + let exported = c.export_keywords(&["travel".into()]); + assert_eq!(exported.flat.len(), N + 2); + let file = c.keyword_list_text(); + assert_eq!(file.text.lines().count(), N + 2); + assert!(started.elapsed() < std::time::Duration::from_secs(20), "took {:?}", started.elapsed()); +} 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/model.rs b/crates/catalog/src/model.rs index ed1c190c59..5bd0371848 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -332,7 +332,9 @@ pub struct Analysis { /// file's white balance is edited relative to its as-shot look or in Kelvin depends on the camera: /// [`relative_wb_camera`]. pub fn relative_wb_format(format: &str) -> bool { - ["ARW", "NEF", "NRW", "RW2", "RWL", "RAW", "RAF", "CR3", "CR2", "PEF", "SRW", "ORF", "ERF", "MRW"].iter().any(|f| format.eq_ignore_ascii_case(f)) + ["ARW", "NEF", "NRW", "RW2", "RWL", "RAW", "RAF", "CR3", "CR2", "PEF", "SRW", "ORF", "ERF", "MRW", "CRW"] + .iter() + .any(|f| format.eq_ignore_ascii_case(f)) } /// Whether a raw of `format` shot on `camera` (Exif make and model, as [`Meta::camera`] keeps them) is developed diff --git a/crates/catalog/src/store.rs b/crates/catalog/src/store.rs index a79930f14a..3345ef884f 100644 --- a/crates/catalog/src/store.rs +++ b/crates/catalog/src/store.rs @@ -28,7 +28,9 @@ pub trait Store: Send { self.write_atomic(name, &buf)?; Ok(buf.len() as u64) } - /// Append and make durable (fsync) before returning. On an error, part of `data` may have + /// Append and make durable (fsync): before returning, or, natively, by the store's own log + /// thread right after ([`FsStore`]: a write that fails is returned by a later append, and a + /// read through the store sees every byte handed over). On an error, part of `data` may have /// been written (a full disk, a dropped network share): the journal cuts the file back to its /// previous length with [`Store::truncate`] before appending again. fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()>; @@ -43,12 +45,23 @@ pub trait Store: Send { fn background_writer(&self) -> Option> { None } + /// Wait until every append handed over is in the file and synced ([`FsStore`] writes them on a + /// thread of its own; the default has nothing to wait for). An error says why some aren't: they + /// are still held and retried, never dropped. + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + /// Records handed over by [`Store::append`] that can't be written yet (a write or sync on the + /// store's own thread failed: they are held and retried), and why. `None`: nothing held back. + fn unwritten(&self) -> Option<(usize, String)> { + None + } } /// Appends and truncates open the name's own file, so anything else at the name is the library's /// problem: a link planted there redirects the write outside the directory (CWE-59), and a device /// hangs the open. Refused with an error the open can show, before anything is written through. -fn check_regular_directory_entry(path: &Path) -> io::Result<()> { +pub(crate) fn check_regular_directory_entry(path: &Path) -> io::Result<()> { match std::fs::symlink_metadata(path) { Ok(md) if md.is_file() => Ok(()), Ok(md) => Err(io::Error::other(format!("{} is a {:?}, not a regular file", path.display(), md.file_type()))), @@ -60,15 +73,24 @@ fn check_regular_directory_entry(path: &Path) -> io::Result<()> { /// Files in a directory. pub struct FsStore { dir: PathBuf, - /// Open append handle (kept between appends; dropped on rewrite/truncate). + /// Open append handle (kept between appends; dropped on rewrite/truncate). Used when no thread + /// writes the log (the browser build, or one that couldn't start). appender: Option<(String, std::fs::File)>, + /// The thread that writes the log (natively; started by the first append). + #[cfg(not(target_arch = "wasm32"))] + log: Option, } impl FsStore { /// Use `dir` (created if missing). pub fn open(dir: impl AsRef) -> io::Result { std::fs::create_dir_all(dir.as_ref())?; - Ok(FsStore { dir: dir.as_ref().to_path_buf(), appender: None }) + Ok(FsStore { + dir: dir.as_ref().to_path_buf(), + appender: None, + #[cfg(not(target_arch = "wasm32"))] + log: None, + }) } pub fn dir(&self) -> &Path { &self.dir @@ -76,6 +98,21 @@ impl FsStore { fn path(&self, name: &str) -> PathBuf { self.dir.join(name) } + /// The log thread, when it writes `name`. + #[cfg(not(target_arch = "wasm32"))] + fn log_for(&self, name: &str) -> Option<&crate::log_writer::LogWriter> { + self.log.as_ref().filter(|w| w.name == name) + } + + /// Wait until the log thread has written and synced everything handed to it. + pub fn flush_log(&self) -> io::Result<()> { + #[cfg(not(target_arch = "wasm32"))] + if let Some(w) = &self.log { + return w.flush(); + } + Ok(()) + } + fn sync_dir(&self) { // Makes the rename durable on POSIX; opening a directory fails on Windows (where // `rename` is already journaled by NTFS), so errors are ignored. @@ -97,6 +134,11 @@ pub(crate) fn create_staging(tmp: &std::path::Path) -> io::Result impl Store for FsStore { fn read(&mut self, name: &str) -> io::Result>> { + #[cfg(not(target_arch = "wasm32"))] + if let Some(w) = self.log_for(name) { + // what was handed over, written or still held + return w.read(); + } match std::fs::read(self.path(name)) { Ok(b) => Ok(Some(b)), Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), @@ -106,6 +148,13 @@ impl Store for FsStore { fn write_atomic(&mut self, name: &str, data: &[u8]) -> io::Result<()> { use std::io::Write; + #[cfg(not(target_arch = "wasm32"))] + if let Some(w) = self.log_for(name) { + // (after the appends handed over before) + w.replace(data)?; + self.sync_dir(); + return Ok(()); + } if self.appender.as_ref().is_some_and(|(n, _)| n == name) { self.appender = None; } @@ -122,6 +171,15 @@ impl Store for FsStore { fn write_atomic_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn io::Write) -> io::Result<()>) -> io::Result { use std::io::Write; + #[cfg(not(target_arch = "wasm32"))] + if let Some(w) = self.log_for(name) { + // (the log is small: buffered, and replaced by its thread after the appends before) + let mut buf = Vec::new(); + fill(&mut buf)?; + w.replace(&buf)?; + self.sync_dir(); + return Ok(buf.len() as u64); + } if self.appender.as_ref().is_some_and(|(n, _)| n == name) { self.appender = None; } @@ -148,6 +206,23 @@ impl Store for FsStore { fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()> { use std::io::Write; + #[cfg(not(target_arch = "wasm32"))] + { + if self.log.is_none() && !crate::fault::on_caller(&self.dir) { + check_regular_directory_entry(&self.path(name))?; + if !self.path(name).exists() { + // created here, so the open's errors are this append's and its entry is durable + std::fs::OpenOptions::new().create(true).append(true).open(self.path(name))?; + self.sync_dir(); + } + self.appender = None; + self.log = crate::log_writer::LogWriter::start(self.dir.clone(), name); + } + // (another name than the log's is written here, as without a thread) + if let Some(w) = self.log_for(name) { + return w.append(data); + } + } if self.appender.as_ref().is_none_or(|(n, _)| n != name) { check_regular_directory_entry(&self.path(name))?; let existed = self.path(name).exists(); @@ -158,6 +233,12 @@ impl Store for FsStore { self.appender = Some((name.to_string(), f)); } let Some((_, f)) = self.appender.as_mut() else { return Err(io::Error::other("appender not open")) }; + #[cfg(not(target_arch = "wasm32"))] + let written = crate::fault::check(&self.dir, crate::fault::Step::Write) + .and_then(|()| f.write_all(data)) + .and_then(|()| crate::fault::check(&self.dir, crate::fault::Step::Sync)) + .and_then(|()| f.sync_data()); + #[cfg(target_arch = "wasm32")] let written = f.write_all(data).and_then(|()| f.sync_data()); if written.is_err() { // The handle may be dead (a network share that reconnected, a removed volume): the next @@ -169,6 +250,10 @@ impl Store for FsStore { } fn truncate(&mut self, name: &str, len: u64) -> io::Result<()> { + #[cfg(not(target_arch = "wasm32"))] + if let Some(w) = self.log_for(name) { + return w.truncate(len); + } if self.appender.as_ref().is_some_and(|(n, _)| n == name) { self.appender = None; } @@ -189,7 +274,16 @@ impl Store for FsStore { #[cfg(not(target_arch = "wasm32"))] fn background_writer(&self) -> Option> { - Some(Box::new(FsStore { dir: self.dir.clone(), appender: None })) + Some(Box::new(FsStore { dir: self.dir.clone(), appender: None, log: None })) + } + + fn flush(&mut self) -> io::Result<()> { + self.flush_log() + } + + #[cfg(not(target_arch = "wasm32"))] + fn unwritten(&self) -> Option<(usize, String)> { + self.log.as_ref().and_then(|w| w.unwritten()) } } @@ -256,13 +350,13 @@ impl Store for MemStore { } } +// (its one test plants a symlink, so the module is Unix-only: elsewhere `use super::*` would be unused) #[cfg(all(test, unix))] mod tests_staging { use super::*; /// A link planted at a staging name (`.tmp`) is removed, never followed: the file it points to keeps its /// bytes and the save still lands (issue #1502). - #[cfg(unix)] #[test] fn a_link_at_the_staging_name_is_never_written_through() { let dir = std::env::temp_dir().join(format!("lc-staging-link-{}", std::process::id())); diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rs index 6813d0a917..19817d78da 100644 --- a/crates/catalog/src/tests.rs +++ b/crates/catalog/src/tests.rs @@ -636,7 +636,8 @@ fn set_embedded_lens_is_undoable_and_journaled() { photo: Box::new(Photo::new(a, Source::File { path: "/x.rw2".into() }, "x.rw2", "RW2", 4000, 3000, "2026-10-06T00:00:00")), }) .unwrap(); - let lens = lightcraft_develop::EmbeddedLens { warp: Some(Default::default()), vignette: None, stages: Default::default() }; + let lens = + lightcraft_develop::EmbeddedLens { warp: Some(Default::default()), vignette: None, stages: Default::default(), source: Default::default() }; let op = Op::SetEmbeddedLens { id: a, lens: Some(Box::new(lens)) }; let op: Op = serde_json::from_str(&serde_json::to_string(&op).unwrap()).unwrap(); let inv = c.apply(op).unwrap(); 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_format_version.rs b/crates/catalog/src/tests_format_version.rs index e31d7fe0c4..ada4138307 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -238,8 +238,8 @@ fn op_variants_are_versioned() { Op::SetHistoryCursor { .. } => 8, } } - /// v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`. - const NEWEST_FIELDS: u32 = 9; + /// v11: `EmbeddedLens.source` (v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`). + const NEWEST_FIELDS: u32 = 11; let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None }); assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version"); } diff --git a/crates/catalog/src/tests_log_thread.rs b/crates/catalog/src/tests_log_thread.rs new file mode 100644 index 0000000000..9c78d61f69 --- /dev/null +++ b/crates/catalog/src/tests_log_thread.rs @@ -0,0 +1,232 @@ +//! PERF-STEP-STALL: the catalog log's own thread ([`crate::log_writer`]). Appends return at once +//! however slow the drive is; everything handed over is written in order; a write that fails is +//! held, reported and retried, never dropped, and the log never has a gap. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; + +use crate::fault::{self, Step}; +use crate::store::{FsStore, Store}; + +const LOG: &str = "catalog.log"; + +fn temp_dir(tag: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("lc-log-thread-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + d +} + +fn wait_until(what: &str, mut done: impl FnMut() -> bool) { + let t = Instant::now(); + while !done() { + assert!(t.elapsed() < Duration::from_secs(20), "{what}"); + std::thread::sleep(Duration::from_millis(10)); + } +} + +/// Appends are written by the thread in order; a read through the store sees every one; a cut +/// and a replace come after the appends before them; dropping the store writes what is left. +#[test] +fn appends_are_written_in_order_and_cuts_and_replaces_come_after_them() { + let dir = temp_dir("order"); + let mut store = FsStore::open(&dir).unwrap(); + let mut want = Vec::new(); + for i in 0..200u32 { + let line = format!("{i}\n"); + store.append(LOG, line.as_bytes()).unwrap(); + want.extend_from_slice(line.as_bytes()); + if i % 50 == 0 { + assert_eq!(store.read(LOG).unwrap().unwrap(), want, "all of it, through the store"); + } + } + store.flush().unwrap(); + assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), want, "all of it, in the file"); + store.truncate(LOG, 4).unwrap(); + assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n"); + // never longer than it is + store.truncate(LOG, 400).unwrap(); + assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n"); + store.append(LOG, b"x\n").unwrap(); + store.write_atomic(LOG, b"tail\n").unwrap(); + assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\n"); + store.append(LOG, b"more\n").unwrap(); + drop(store); + assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\nmore\n"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// (a) Each sync takes 300 ms: 100 appends still return at once, and a flush then finds all of +/// them in the file (before, each append waited for its own sync: 30 s for these). +#[test] +fn an_append_never_waits_for_a_slow_sync() { + let dir = temp_dir("slow"); + let mut store = FsStore::open(&dir).unwrap(); + store.append(LOG, b"first\n").unwrap(); + let syncs = Arc::new(AtomicUsize::new(0)); + let n = syncs.clone(); + fault::install( + &dir, + Arc::new(move |step| { + if step == Step::Sync { + n.fetch_add(1, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(300)); + } + Ok(()) + }), + ); + let mut want = b"first\n".to_vec(); + let mut slowest = Duration::ZERO; + for i in 0..100u32 { + let line = format!("{i}\n"); + let t = Instant::now(); + store.append(LOG, line.as_bytes()).unwrap(); + slowest = slowest.max(t.elapsed()); + want.extend_from_slice(line.as_bytes()); + std::thread::sleep(Duration::from_millis(2)); + } + assert!(slowest < Duration::from_millis(50), "an append waited {slowest:?}"); + store.flush().unwrap(); + assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), want); + // batched: far fewer syncs than appends + assert!(syncs.load(Ordering::SeqCst) < 50, "{} syncs", syncs.load(Ordering::SeqCst)); + fault::remove(&dir); + let _ = std::fs::remove_dir_all(&dir); +} + +/// (c) Writes fail for a while: what was handed over is held (reported, with the reason), later +/// appends are refused so the caller keeps them, and once writes work again the held bytes land, +/// in order, with no fragment of the failed attempts and no gap. +#[test] +fn a_failed_write_is_held_reported_and_retried() { + let dir = temp_dir("fail"); + let mut store = FsStore::open(&dir).unwrap(); + store.append(LOG, b"0\n").unwrap(); + store.flush().unwrap(); + let fail = Arc::new(AtomicBool::new(true)); + let f = fail.clone(); + fault::install(&dir, Arc::new(move |_| if f.load(Ordering::SeqCst) { Err(std::io::Error::other("disk full (test)")) } else { Ok(()) })); + // (one append: the log thread can fail the first before a second arrives, and then refuses it) + store.append(LOG, b"1\n2\n").unwrap(); + wait_until("the failure is published", || store.unwritten().is_some()); + let (held, why) = store.unwritten().unwrap(); + assert!(why.contains("disk full"), "{why}"); + assert!(held >= 1, "{held}"); + let refused = store.append(LOG, b"3\n"); + assert!(refused.is_err(), "refused while held"); + assert!(store.flush().is_err(), "a flush says it isn't written"); + // a read through the store still sees what was handed over + assert_eq!(store.read(LOG).unwrap().unwrap(), b"0\n1\n2\n"); + // a cut within what is held keeps it (the journal cuts back to its own length on an error) + store.truncate(LOG, 6).unwrap(); + assert_eq!(store.read(LOG).unwrap().unwrap(), b"0\n1\n2\n"); + // a fragment of a failed write left in the file is cut before the retry + { + use std::io::Write; + let mut file = std::fs::OpenOptions::new().append(true).open(dir.join(LOG)).unwrap(); + file.write_all(b"{\"seq\":").unwrap(); + } + fail.store(false, Ordering::SeqCst); + wait_until("retried on its own", || store.unwritten().is_none()); + store.append(LOG, b"3\n").unwrap(); + store.flush().unwrap(); + assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n2\n3\n"); + fault::remove(&dir); + let _ = std::fs::remove_dir_all(&dir); +} + +/// (b, c) Through the journal: ops appended while the drive is slow or failing all reopen, and a +/// journal over a log that failed has no gap (no damage on load). +#[test] +fn the_journal_reopens_every_op_after_a_slow_then_failing_drive() { + use crate::{Catalog, Journal, Op, Photo, PhotoId, Source}; + let dir = temp_dir("journal"); + let (mut j, mut c, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); + let fail = Arc::new(AtomicBool::new(false)); + let f = fail.clone(); + fault::install( + &dir, + Arc::new(move |step| { + if f.load(Ordering::SeqCst) { + return Err(std::io::Error::other("network share dropped (test)")); + } + if step == Step::Sync { + std::thread::sleep(Duration::from_millis(40)); + } + Ok(()) + }), + ); + let mut queued: Vec = Vec::new(); + for id in 1..=60u64 { + if id == 20 { + fail.store(true, Ordering::SeqCst); + } + if id == 40 { + fail.store(false, Ordering::SeqCst); + } + let p = Photo::new(PhotoId(id), Source::Demo { scene: 0 }, &format!("p{id}.jpg"), "JPEG", 4, 3, "2026-11-02"); + let op = Op::AddPhoto { photo: Box::new(p) }; + c.apply(op.clone()).unwrap(); + queued.push(op); + // as the engine does: a failed append keeps its ops queued for the next one + if j.append(&queued).is_ok() { + queued.clear(); + } + std::thread::sleep(Duration::from_millis(5)); + } + wait_until("everything written", || { + if !queued.is_empty() && j.append(&queued).is_ok() { + queued.clear(); + } + queued.is_empty() && j.unwritten().is_none() + }); + j.flush().unwrap(); + let expect = c.to_snapshot(); + drop(j); + fault::remove(&dir); + let (_, again, report): (_, Catalog, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); + assert!(report.damaged.is_none(), "{report:?}"); + assert_eq!(again.to_snapshot(), expect); + assert_eq!(again.len(), 60); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A sync that fails leaves the written bytes past the synced length in the file; a cut to exactly +/// that length removes them from the file too, so they never come back on the next open (review +/// of #3557). +#[test] +fn a_cut_to_the_synced_length_removes_bytes_a_failed_sync_left() { + let dir = temp_dir("cut-synced"); + let mut store = FsStore::open(&dir).unwrap(); + store + .append( + LOG, b"0 +", + ) + .unwrap(); + store.flush().unwrap(); + fault::install(&dir, Arc::new(|step| if step == Step::Sync { Err(std::io::Error::other("sync failed (test)")) } else { Ok(()) })); + store + .append( + LOG, b"1 +", + ) + .unwrap(); + wait_until("the failure is published", || store.unwritten().is_some()); + assert_eq!( + std::fs::read(dir.join(LOG)).unwrap(), + b"0 +1 +", + "written, not synced" + ); + store.truncate(LOG, 2).unwrap(); + fault::remove(&dir); + drop(store); + assert_eq!( + std::fs::read(dir.join(LOG)).unwrap(), + b"0 +" + ); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/catalog/src/tests_torn_append.rs b/crates/catalog/src/tests_torn_append.rs index 0b6cf05af3..f7cee57d23 100644 --- a/crates/catalog/src/tests_torn_append.rs +++ b/crates/catalog/src/tests_torn_append.rs @@ -88,6 +88,9 @@ fn partial_append_then_retry_loads_cleanly() { assert!(j.append(&batch).is_err(), "tear at {tear}"); // cut back to the last whole record assert_eq!(t.files.get(LOG).unwrap().len(), good_len, "tear at {tear}"); + // and a snapshot is due (records handed over before may be missing from a log written + // by a thread of its own: note 2 of 2026-10-25) + assert!(j.wants_snapshot(), "tear at {tear}"); j.append(&batch).unwrap(); let more = apply(&mut c, vec![Op::SetLabel { id, label: Some(ColorLabel::ALL[0]) }]); j.append(&more).unwrap(); diff --git a/crates/catalog/tests/path_fold_heap.rs b/crates/catalog/tests/path_fold_heap.rs index 4fc1c8ef14..9c41f3fcf2 100644 --- a/crates/catalog/tests/path_fold_heap.rs +++ b/crates/catalog/tests/path_fold_heap.rs @@ -55,5 +55,8 @@ fn a_file_path_rule_allocates_nothing_per_photo() { } let blocks = dhat::HeapStats::get().total_blocks - before; assert!(hits > 0, "the rules matched nothing: the test measures nothing"); - assert_eq!(blocks, 0, "{blocks} heap blocks for {} rule tests", 100 * rules.len() * photos.len()); + // dhat counts every thread, and the test harness's own thread can allocate a few blocks while this + // runs. An allocation per photo would be thousands, two per rule test. + let tests = 100 * rules.len() * photos.len(); + assert!(blocks < 64, "{blocks} heap blocks for {tests} rule tests"); } diff --git a/crates/denoise-core/src/product.rs b/crates/denoise-core/src/product.rs index c33b1d4c2a..09cf24245a 100644 --- a/crates/denoise-core/src/product.rs +++ b/crates/denoise-core/src/product.rs @@ -160,7 +160,10 @@ pub fn write(path: &Path, img: &Rgb32f, key: &str) -> Result<(), ProductError> { if let Some(dir) = path.parent() { std::fs::create_dir_all(dir)?; } - let mut f = std::io::BufWriter::new(std::fs::File::create(&tmp)?); + // a new temp file: an entry already under the name (a link planted in the cache folder + // would be written through) is removed, never opened + let _ = std::fs::remove_file(&tmp); + let mut f = std::io::BufWriter::new(std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?); f.write_all(MAGIC)?; f.write_all(&[VERSION, 0, 0, 0])?; f.write_all(&(header.len() as u32).to_le_bytes())?; @@ -459,6 +462,22 @@ mod tests { std::env::temp_dir().join(format!("lc-denoise-{name}-{}.lcdn", std::process::id())) } + #[cfg(unix)] + #[test] + fn a_link_planted_under_the_temp_name_is_not_written_through() { + let p = temp("planted"); + let victim = temp("victim"); + std::fs::write(&victim, b"keep").unwrap(); + let _ = std::fs::remove_file(p.with_extension("tmp")); + std::os::unix::fs::symlink(&victim, p.with_extension("tmp")).unwrap(); + write(&p, &picture(16, 4), "k").unwrap(); + assert_eq!(std::fs::read(&victim).unwrap(), b"keep"); + assert!(read_header_at(&p).is_ok()); + for f in [p, victim] { + let _ = std::fs::remove_file(f); + } + } + fn picture(w: usize, h: usize) -> Rgb32f { Rgb32f { width: w, diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index 739171abd9..201b33d5f0 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -84,17 +84,25 @@ pub enum Process { /// Highlights and Shadows keep the local contrast of the tones they move: their edge-aware base /// is taken of a fine median of log luminance (issue #632). V2, + /// Pixel-scale sharpening with working Radius and Detail controls. + V3, + /// V3, with Contrast and Blacks on a raw's camera look calibrated to Lightroom: the + /// camera curve keeps V2 Whites and fitted pointwise operators follow it + /// (`lightcraft_pipeline::light_v3`, `docs/light-v3.md`). + V4, } impl Process { /// Every process, oldest first. - pub const ALL: [Process; 2] = [Process::V1, Process::V2]; - pub const LATEST: Process = Process::V2; + pub const ALL: [Process; 4] = [Process::V1, Process::V2, Process::V3, Process::V4]; + pub const LATEST: Process = Process::V4; pub const fn version(self) -> ProcessVersion { match self { Process::V1 => ProcessVersion(1), Process::V2 => ProcessVersion(2), + Process::V3 => ProcessVersion(3), + Process::V4 => ProcessVersion(4), } } } @@ -699,11 +707,32 @@ impl Default for Optics { pub struct EmbeddedLens { pub warp: Option, pub vignette: Option, + /// Where the correction came from: the file itself, or a lens database looked up by the + /// lens named in the file (what the Optics panel says is loaded). + #[serde(skip_serializing_if = "LensSource::is_file")] + pub source: LensSource, /// A DNG 1.6 `WarpRectilinear2` chain (up to [`WARP_STAGES`] stages, in `OpcodeList3` order; each stage warps /// the result of the one before it). When any is set, `warp` is `None`: the chain holds every warp opcode. pub stages: [Option; WARP_STAGES], } +/// Where an [`EmbeddedLens`] came from. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum LensSource { + /// The file's own correction (DNG opcodes, a camera's correction a raw reader converts). + #[default] + File, + /// A profile from a lensfun-format lens database, matched by the lens named in the file. + Database, +} + +impl LensSource { + pub fn is_file(&self) -> bool { + *self == LensSource::File + } +} + /// Most warp stages an [`EmbeddedLens`] chain keeps. pub const WARP_STAGES: usize = 3; @@ -1054,15 +1083,35 @@ pub struct Mask { /// Refine Edges 0..100: the mask's edges snap to the photo's (guided filter). #[serde(skip_serializing_if = "is_zero")] pub refine: f64, + /// Where its coordinates (gradients, brush strokes, AI selections) live: `true`, on the photo as + /// shot (user orientation, before lens corrections, Upright and Transform), so the mask stays + /// on the same content whatever those do; `false`, a mask from before that, on the corrected + /// frame. Read as `false` when absent; [`Mask::default`] (every new mask) is `true`, and an + /// edit converts an old one (`lightcraft_pipeline::mask_space::attach`). + #[serde(default, skip_serializing_if = "is_false")] + pub on_photo: bool, } fn is_zero(v: &f64) -> bool { *v == 0.0 } +fn is_false(v: &bool) -> bool { + !*v +} + impl Default for Mask { fn default() -> Self { - Self { id: 0, name: "Mask 1".into(), visible: true, invert: false, components: Vec::new(), adjust: LocalAdjustments::default(), refine: 0.0 } + Self { + id: 0, + name: "Mask 1".into(), + visible: true, + invert: false, + components: Vec::new(), + adjust: LocalAdjustments::default(), + refine: 0.0, + on_photo: true, + } } } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0b203f7954..0d40c73184 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -40,6 +40,7 @@ log = { workspace = true } ab_glyph = { workspace = true } # Apply the font’s vertical substitutions and origins to Japanese watermarks. harfrust = { version = "0.13", default-features = false, features = ["std"] } +unicode-normalization = "0.1" unicode-segmentation = "1.13" lightcraft-segment = { workspace = true, optional = true } diff --git a/crates/engine/build.rs b/crates/engine/build.rs index 7f5aa77776..f2573f0197 100644 --- a/crates/engine/build.rs +++ b/crates/engine/build.rs @@ -65,6 +65,7 @@ fn craft_fonts(dir: &Path, required: bool) -> Result { let manifest = dir.join("fonts/manifest.txt"); println!("cargo::rerun-if-changed={}", manifest.display()); let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?; + let root = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?; let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32"); let mut out = String::new(); let mut has_japanese_ui = false; @@ -82,7 +83,17 @@ fn craft_fonts(dir: &Path, required: bool) -> Result { continue; } let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; - println!("cargo::rerun-if-changed={}", path.display()); + // a font is a file of the checkout: a manifest entry or a link reaching outside it would + // embed some other file of the build machine + if !path.starts_with(&root) || !path.is_file() { + return Err(format!("{file}: not a file inside {}", root.display())); + } + let shown = path.display().to_string(); + // one cargo instruction per line: a line break in the path would print a second one + if shown.contains(['\n', '\r']) { + return Err(format!("{file}: the path contains a line break")); + } + println!("cargo::rerun-if-changed={shown}"); let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); let _ = writeln!( out, 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/camera_preview/colour.rs b/crates/engine/src/camera_preview/colour.rs index 6befe7ce1a..742b37c48b 100644 --- a/crates/engine/src/camera_preview/colour.rs +++ b/crates/engine/src/camera_preview/colour.rs @@ -27,6 +27,7 @@ pub(crate) fn file_local_look(format: RawFormat) -> bool { | RawFormat::Pef | RawFormat::Srw | RawFormat::Orf + | RawFormat::Crw | RawFormat::Mrw | RawFormat::Erf ) diff --git a/crates/engine/src/camera_profiles.rs b/crates/engine/src/camera_profiles.rs index 9e6d2094ee..3c63773c1e 100644 --- a/crates/engine/src/camera_profiles.rs +++ b/crates/engine/src/camera_profiles.rs @@ -1,6 +1,6 @@ //! Camera colour profiles of our own, pooled from many photos of one camera model. //! -//! A raw file without colour matrices (Sony ARW, Nikon NEF, Fujifilm RAF) gets its look fitted to its own embedded camera +//! A raw file without colour matrices (Sony ARW, Nikon NEF, Fujifilm RAF, Canon CRW) gets its look fitted to its own embedded camera //! JPEG (`camera_preview`), but one photo shows too little of some colours: a lime shirt covering a //! few dozen proxy pixels next to a hillside of foliage at the same hue. `lightcraft-cli calibrate` //! pools the colour pairs of many photos per model and fits one matrix and hue/saturation/value @@ -25,6 +25,7 @@ const MAX_FILE: u64 = 4 << 20; /// Profiles built into LightCraft (`assets/camera-profiles/`, see `assets/ATTRIBUTION.md`): /// `(model, JSON)`. pub const BUNDLED: &[(&str, &str)] = &[ + ("Canon EOS D60", include_str!("../../../assets/camera-profiles/Canon_EOS_D60.json")), ("ILCA-99M2", include_str!("../../../assets/camera-profiles/ILCA-99M2.json")), ("ILCE-7CR", include_str!("../../../assets/camera-profiles/ILCE-7CR.json")), ("ILCE-7M4", include_str!("../../../assets/camera-profiles/ILCE-7M4.json")), @@ -115,9 +116,9 @@ pub fn save(profile: &CameraProfile, dir: &Path) -> Result { std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; let path = dir.join(file_name(&profile.model)); let json = serde_json::to_vec_pretty(profile).map_err(|e| e.to_string())?; - let tmp = path.with_extension("json.tmp"); - std::fs::write(&tmp, json).map_err(|e| format!("{}: {e}", tmp.display()))?; - std::fs::rename(&tmp, &path).map_err(|e| format!("{}: {e}", path.display()))?; + // a fresh temp file renamed over the profile: never a fixed `.tmp` name, which a planted link + // would have written through + lightcraft_catalog::safe_file::write_atomic(&path, &json).map_err(|e| format!("{}: {e}", path.display()))?; Ok(path) } @@ -295,6 +296,9 @@ mod tests { assert_eq!(bundled(model), Some(p)); } assert!(bundled("No Such Camera").is_none()); + // a model name with spaces is stored under its safe file name + assert!(bundled("Canon EOS D60").is_some_and(|p| p.files > 1000)); + assert_eq!(file_name("Canon EOS D60"), "Canon_EOS_D60.json"); } #[test] diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index daddc7f6ea..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; @@ -22,6 +23,7 @@ pub mod filters; mod focus; pub mod geocode; pub mod keywords; +pub mod lens_refresh; pub mod library; pub mod lut_profiles; pub mod manage; @@ -39,6 +41,7 @@ mod print; mod query; pub mod recheck; pub mod reload; +pub mod similar; mod slideshow; mod sync; mod xmp; @@ -152,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()); @@ -168,6 +172,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(browse::specs()); v.extend(missing::specs()); v.extend(recheck::specs()); + v.extend(lens_refresh::specs()); v.extend(sync::specs()); v.extend(metadata::specs()); v.extend(geocode::specs()); diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rs index 49f75181ca..0eb126c40f 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -433,6 +433,7 @@ fn move_to_folder(s: &mut Session, p: &Value) -> Result { } let mut plans: Vec = Vec::new(); let mut taken: std::collections::HashSet = std::collections::HashSet::new(); + let mut moving: std::collections::HashSet<&str> = std::collections::HashSet::new(); let mut clashes: Vec = Vec::new(); for id in ids { let ph = s.catalog.photo(id).ok_or_else(|| bad(C, format!("no photo {}", id.0)))?; @@ -442,7 +443,7 @@ fn move_to_folder(s: &mut Session, p: &Value) -> Result { let lightcraft_catalog::Source::File { path } = &ph.source else { return Err(bad(C, format!("{} has no file on disk", ph.file_name))); }; - if plans.iter().any(|pl| pl.from_path.as_deref() == Some(path.as_str())) { + if !moving.insert(path.as_str()) { continue; // a virtual copy of a photo already moving } let src = Path::new(path); @@ -521,7 +522,13 @@ pub(crate) fn move_folder(s: &mut Session, from: &str, to: &str) -> std::result: if !src.is_dir() { return Err(format!("{from} is not a folder")); } - if s.library.as_ref().is_some_and(|l| l.dir.starts_with(src) || src.starts_with(&l.dir)) { + // compared as the folders are on disk (a differently spelled or linked path to the library + // names the same folder), with the spelling as a fallback where that can't be told + let same_folder = |l: &Path| { + let (lib, chosen) = (l.canonicalize().unwrap_or_else(|_| l.to_path_buf()), src.canonicalize().unwrap_or_else(|_| src.to_path_buf())); + lib.starts_with(&chosen) || chosen.starts_with(&lib) || l.starts_with(src) || src.starts_with(l) + }; + if s.library.as_ref().is_some_and(|l| same_folder(&l.dir)) { return Err("the library's own folders can't be moved here".into()); } // Repairs retain their exact old paths, including those on surviving history entries. diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index 0871e43528..24b4165278 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -456,6 +456,7 @@ mod tests { warp: Some(lightcraft_develop::EmbeddedWarp { planes: [[1.0, -0.1, 0.03, 0.0, 0.0, 0.0]; 3], ..Default::default() }), vignette: None, stages: Default::default(), + source: Default::default(), } } fn old_rw2() -> lightcraft_catalog::Photo { diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 383ed890d9..c847852261 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -105,43 +105,6 @@ fn burst_params(p: &Value) -> Result<(f64, f32)> { Ok((num("burstGap", BURST_GAP, MAX_GAP)?, num("similarity", SAME, 1.0)? as f32)) } -/// Find Similar: photos that look like `id` (signatures from thumbnail-level sources, cached by -/// content), most similar first; the view is filtered to them. -fn find_similar(s: &mut Session, p: &Value) -> Result { - const C: &str = "library.findSimilar"; - let id = super::photo_id(p, C)?.or(s.active()).ok_or_else(|| super::bad(C, "no photo"))?; - let min = p.get("similarity").and_then(Value::as_f64).unwrap_or(0.8) as f32; - let all: Vec = s.catalog.photos().filter(|q| q.in_library()).map(|q| q.id).collect(); - let sig = |s: &mut Session, id: PhotoId| -> Option<[f32; 64]> { - let key = s.catalog.photo(id).map(|p| crate::media::content_key(p))?; - if let Some(v) = s.signatures.get(&key) { - return Some(*v); - } - let src = s.source_now(id, crate::media::SourceLevel::Thumb).ok()?; - let v = lightcraft_pipeline::cull::signature(&src); - s.signatures.insert(key, v); - Some(v) - }; - let me = sig(s, id).ok_or_else(|| super::bad(C, "can't read the photo"))?; - let mut hits: Vec<(PhotoId, f32)> = Vec::new(); - for q in all { - if let Some(v) = sig(s, q) { - let sim = lightcraft_pipeline::cull::similarity(&me, &v); - if sim >= min { - hits.push((q, sim.clamp(0.0, 1.0))); - } - } - } - hits.sort_by(|a, b| b.1.total_cmp(&a.1)); - if p.get("filter").and_then(Value::as_bool).unwrap_or(true) { - s.shelved_filter = None; - s.filter.only = hits.iter().map(|h| h.0).collect(); - // an empty `only` means "no constraint": no hits is its own state that shows no photos - s.filter.only_none = s.filter.only.is_empty(); - } - Ok(json!({"photos": hits.iter().map(|(i, v)| json!({"id": i.0, "similarity": (v * 1000.0).round() / 1000.0})).collect::>()})) -} - pub fn specs() -> Vec { vec![ cmd!( @@ -149,9 +112,9 @@ pub fn specs() -> Vec { "Find Similar Photos", ["Photo"], None, - "{id?, similarity?: 0..1 (0.8), filter?: bool (true)} — photos that look like the active one (composition and tones), most similar first; filters the view to them (Clear Filters to go back) → {photos: [{id, similarity}]}", - always, - find_similar + "{id?, similarity?: 0..1 (0.8), filter?: bool (true)} — photos that look like the active one (composition and tones), most similar first; filters the view to them (Clear Filters to go back) → {photos: [{id, similarity}]}. In the app the photos are read on a worker thread under an activity row: a control request is answered with this when the search ends, and from a menu the answer is {background: true, count}", + super::similar::no_search_running, + super::similar::run ), cmd!( "photo.analyze", diff --git a/crates/engine/src/cmd/dcp_profiles.rs b/crates/engine/src/cmd/dcp_profiles.rs new file mode 100644 index 0000000000..a7c6d4c02c --- /dev/null +++ b/crates/engine/src/cmd/dcp_profiles.rs @@ -0,0 +1,212 @@ +//! Imported camera profiles: the user's own DNG Camera Profiles (`.dcp`), chosen like any other +//! profile (`develop.profile {id: "dcp:…"}`). Unlike the built-in looks and LUT profiles, which +//! work on developed colour, a camera profile replaces the raw file's colour model when it is +//! decoded (its matrices and hue/saturation map; see [`lightcraft_raw::dcp`]), so the photo's +//! source is decoded again when it changes. Other photos (JPEG, TIFF…) ignore it. +//! +//! A library on disk keeps a copy of each file in its `Profiles/` folder; the list lives in the +//! library's prefs and the profiles are parsed again when the library opens. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use super::{CommandSpec, always, bad, cmd, str_param}; +use crate::media::LoadedCameraProfile; +use crate::{Result, Session}; + +/// Profile id prefix of imported camera profiles. +pub const DCP_PREFIX: &str = "dcp:"; +/// Profile browser group of imported camera profiles. +pub const DCP_GROUP: &str = "Camera Profiles"; + +/// One imported camera profile. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DcpEntry { + /// `dcp:`. + pub id: String, + /// `ProfileName`, else the file name. + pub name: String, + /// The camera it was made for (`UniqueCameraModel`). + #[serde(default)] + pub camera_model: String, + /// The `.dcp` file (the library's copy when there is a library on disk). + pub file: String, +} + +/// Is `id` an imported camera profile id? +pub fn is_dcp_id(id: &str) -> bool { + id.starts_with(DCP_PREFIX) +} + +fn profiles_dir(s: &Session) -> Option { + s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Profiles")) +} + +/// Parse every imported camera profile again and hand them to the decoder (missing or damaged +/// files are skipped: photos using them develop with the file's own colour, and the profile is not offered or +/// accepted by `develop.profile` until its file is back; the entry is kept). +/// +/// A library's own copies are found in `profiles`, the `Profiles/` folder of the library being opened (`None`: not on +/// disk), wherever the saved path points: a library moved or restored elsewhere keeps its profiles (the saved path is +/// updated). +pub fn register_all(s: &mut Session, profiles: Option<&Path>) { + if let Some(dir) = profiles { + for p in &mut s.dcp_profiles { + if let Some(here) = library_copy(dir, &p.file) { + p.file = here.to_string_lossy().to_string(); + } + } + } + let loaded: Vec<(String, LoadedCameraProfile)> = s + .dcp_profiles + .iter() + .filter_map(|p| { + lightcraft_raw::dcp::read_dcp(Path::new(&p.file)).ok().and_then(|b| LoadedCameraProfile::parse(&b).ok()).map(|d| (p.id.clone(), d)) + }) + .collect(); + s.media.camera_profiles = loaded.into_iter().collect(); +} + +/// The copy of saved profile file `file` in the open library's profiles folder `dir`, when it is there under the +/// same name and `file` is not already it. +fn library_copy(dir: &Path, file: &str) -> Option { + let saved = Path::new(file); + let here = dir.join(saved.file_name()?); + (here != saved && here.is_file()).then_some(here) +} + +/// `.dcp` files under `paths` (folders searched). +pub fn dcp_files(paths: &[String]) -> Vec { + let is_dcp = |f: &Path| f.extension().is_some_and(|x| x.eq_ignore_ascii_case("dcp")); + let mut out = Vec::new(); + for p in paths { + let path = Path::new(p); + if path.is_dir() { + out.extend(crate::walk::files_in(path, None, crate::walk::Limits::default(), is_dcp).files); + } else if is_dcp(path) { + out.push(path.to_path_buf()); + } + } + out +} + +/// Import the `.dcp` files under `paths` → (imported `[{id, name, cameraModel}]`, failed `[[file, error]]`). +/// A profile already imported (same name, camera and bytes) is not added twice. +pub fn import_files(s: &mut Session, paths: &[String]) -> Result<(Vec, Vec)> { + const C: &str = "profile.import"; + let dir = profiles_dir(s); + if let Some(d) = &dir { + std::fs::create_dir_all(d).map_err(|e| bad(C, format!("{}: {e}", d.display())))?; + } + let (mut imported, mut failed) = (Vec::new(), Vec::new()); + for f in dcp_files(paths) { + let shown = f.display().to_string(); + let bytes = match lightcraft_raw::dcp::read_dcp(&f) { + Ok(b) => b, + Err(e) => { + failed.push(json!([shown, e.to_string()])); + continue; + } + }; + let loaded = match LoadedCameraProfile::parse(&bytes) { + Ok(p) => p, + Err(e) => { + failed.push(json!([shown, e.to_string()])); + continue; + } + }; + let profile = loaded.profile.clone(); + let stem = f.file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "Camera Profile".into()); + let name = if profile.name.trim().is_empty() { stem.clone() } else { profile.name.trim().to_string() }; + // the same profile imported again: keep the one there is + let same = s.dcp_profiles.iter().find(|p| { + p.name == name && p.camera_model == profile.camera_model && lightcraft_raw::dcp::read_dcp(Path::new(&p.file)).is_ok_and(|b| b == bytes) + }); + if let Some(p) = same { + imported.push(json!({"id": p.id, "name": p.name, "cameraModel": p.camera_model, "existing": true})); + continue; + } + // (the file name keeps profiles with the same ProfileName apart, e.g. per-body copies) + let slug = crate::presets::slug(&format!("{}-{stem}", profile.camera_model)); + let mut id = format!("{DCP_PREFIX}{slug}"); + let mut n = 2; + while s.dcp_profiles.iter().any(|x| x.id == id) { + id = format!("{DCP_PREFIX}{slug}-{n}"); + n += 1; + } + let file = match &dir { + Some(d) => { + let to = d.join(format!("{}.dcp", id.trim_start_matches(DCP_PREFIX))); + // a copy that fails (disk full, no access) fails this file only: the profiles + // copied before it stay imported, and nothing half-written is left behind + if let Err(e) = std::fs::write(&to, &bytes) { + if to.is_file() { + let _ = std::fs::remove_file(&to); + } + failed.push(json!([shown, format!("{}: {e}", to.display())])); + continue; + } + to.to_string_lossy().to_string() + } + // no library on disk: remember the original (the in-memory session ends with the app) + None => f.to_string_lossy().to_string(), + }; + s.media.camera_profiles.insert(id.clone(), loaded); + s.dcp_profiles.push(DcpEntry { id: id.clone(), name: name.clone(), camera_model: profile.camera_model.clone(), file }); + imported.push(json!({"id": id, "name": name, "cameraModel": profile.camera_model})); + } + Ok((imported, failed)) +} + +fn delete(s: &mut Session, p: &Value) -> Result { + const C: &str = "profile.deleteCamera"; + let id = str_param(p, "id").ok_or_else(|| bad(C, "missing id"))?.to_string(); + let Some(i) = s.dcp_profiles.iter().position(|x| x.id == id) else { + return Err(bad(C, format!("no imported camera profile `{id}`"))); + }; + // the library's copy goes first; a file outside the library is the user's and stays. A copy that can't be + // removed (in use, no access) keeps the profile, so the library never holds a file it no longer lists. A path + // with `..` in it is never the library's copy (it could lead out of the profiles folder). + if let Some(d) = profiles_dir(s) + && let Some(entry) = s.dcp_profiles.get(i) + && Path::new(&entry.file).starts_with(&d) + && !Path::new(&entry.file).components().any(|c| c == std::path::Component::ParentDir) + { + match std::fs::remove_file(&entry.file) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(bad(C, format!("could not delete {}: {e}", entry.file))), + } + } + s.dcp_profiles.remove(i); + s.media.camera_profiles.remove(&id); + s.profile_favorites.retain(|f| f != &id); + s.profile_recent.retain(|f| f != &id); + s.save_prefs()?; + Ok(json!({"deleted": id})) +} + +pub fn specs() -> Vec { + vec![ + cmd!( + query "profiles.camera", + "Imported Camera Profiles", + [], + None, + "{} → {profiles: [{id, name, cameraModel, file}]}: the imported .dcp camera profiles (use with develop.profile)", + always, + |s, _| Ok(json!({"profiles": s.dcp_profiles})) + ), + cmd!( + "profile.deleteCamera", + "Delete Imported Camera Profile", + [], + None, + "{id: dcp:…} — photos using it develop with their file's own colour again", + always, + delete + ), + ] +} diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index df1089925d..292ad27795 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -557,9 +557,17 @@ pub fn specs() -> Vec { }), cmd!("develop.profile", "Set Profile", [], None, "{id: profile id (see profiles.list), amount?: 0..200}", has_active, |s, p| { let id = str_param(p, "id").ok_or_else(|| bad("develop.profile", "missing id"))?.to_string(); - if !crate::presets::PROFILES.iter().any(|x| x.id == id) && !s.lut_profiles.iter().any(|x| x.id == id) { + if !crate::presets::PROFILES.iter().any(|x| x.id == id) + && !s.lut_profiles.iter().any(|x| x.id == id) + && !s.dcp_profiles.iter().any(|x| x.id == id) + { return Err(bad("develop.profile", format!("unknown profile `{id}`"))); } + // an imported camera profile whose file is missing or damaged: choosing it would develop with the + // file's own colour without saying so + if crate::cmd::dcp_profiles::is_dcp_id(&id) && !s.media.camera_profiles.contains_key(&id) { + return Err(bad("develop.profile", format!("camera profile `{id}` can't be used: its file is missing or damaged"))); + } edit(s, "develop.profile", "Profile", |d| { d.profile.id = id.clone(); d.profile.amount = f64_or(p, "amount", d.profile.amount).clamp(0.0, 200.0); @@ -570,7 +578,7 @@ pub fn specs() -> Vec { }), cmd!("profile.favorite", "Favorite Profile", [], None, "{id, favorite?: bool} (toggles when omitted)", always, |s, p| { let id = str_param(p, "id").ok_or_else(|| bad("profile.favorite", "missing id"))?.to_string(); - if crate::presets::profile(&id).is_none() && !s.lut_profiles.iter().any(|x| x.id == id) { + if crate::presets::profile(&id).is_none() && !s.lut_profiles.iter().any(|x| x.id == id) && !s.dcp_profiles.iter().any(|x| x.id == id) { return Err(bad("profile.favorite", format!("unknown profile `{id}`"))); } let on = s.profile_favorites.contains(&id); diff --git a/crates/engine/src/cmd/geocode.rs b/crates/engine/src/cmd/geocode.rs index 63f8d8f173..d811f80209 100644 --- a/crates/engine/src/cmd/geocode.rs +++ b/crates/engine/src/cmd/geocode.rs @@ -47,6 +47,10 @@ pub struct PlaceNames { shared: Arc>, /// (cities file, its size, its modification time, the parsed names). cache: Option<(PathBuf, u64, Option, Arc)>, + /// (folder, server) a download goes to instead of `/geonames` and GeoNames. Only + /// tests set it: no command can, so a client never chooses where the files land (#2575). + #[cfg(not(target_arch = "wasm32"))] + download_to: Option<(PathBuf, String)>, } impl PlaceNames { @@ -188,10 +192,7 @@ mod download { use lightcraft_geocode::{GEONAMES_BASE, GEONAMES_ZIP}; - use super::{ - Cancel, DownloadOutcome, GEONAMES_ATTRIBUTION, GEONAMES_FILES, GeoNames, PoisonError, Result, Session, Value, bad, dataset_dir, json, - str_param, - }; + use super::{Cancel, DownloadOutcome, GEONAMES_ATTRIBUTION, GEONAMES_FILES, GeoNames, PoisonError, Result, Session, Value, bad, json}; use crate::activity::Unit; const MAX_ZIP: u64 = 64 * 1024 * 1024; @@ -218,7 +219,11 @@ mod download { return Err("the downloaded place list is empty".into()); } let _ = std::fs::remove_file(staging.join(GEONAMES_ZIP)); - let write = |name: &str, data: &[u8]| std::fs::write(dir.join(name), data).map_err(|e| format!("could not save {name}: {e}")); + // a temp file renamed over the old one: never half-written, and a link in its place is + // replaced, not written through (#2575); not synced, as a download can always be repeated + let write = |name: &str, data: &[u8]| { + lightcraft_catalog::safe_file::write_atomic_nosync(&dir.join(name), data).map_err(|e| format!("could not save {name}: {e}")) + }; for name in &GEONAMES_FILES[1..] { // optional: without them states stay blank and countries are ISO codes match get(name, base, &staging, cancel, task).and_then(|()| std::fs::read(staging.join(name)).map_err(|e| e.to_string())) { @@ -241,10 +246,21 @@ mod download { } /// `metadata.downloadPlaceNames`: starts a background download (shown in the activity stack, cancellable). + /// The files always go to `/geonames`, from GeoNames: a control or MCP client naming a + /// folder (`dataset`) or a server (`base`) could have written a server's bytes into any folder (#2575). pub(super) fn start(s: &mut Session, p: &Value) -> Result { const C: &str = "metadata.downloadPlaceNames"; - let dir = dataset_dir(p).ok_or_else(|| bad(C, "no settings folder: give `dataset`"))?; - let base = str_param(p, "base").unwrap_or(GEONAMES_BASE).to_string(); + if p.get("dataset").is_some() || p.get("base").is_some() { + return Err(bad(C, "the place names always download from GeoNames into the settings folder: `dataset` and `base` are not accepted")); + } + let target = s.place_names.download_to.clone(); + let (dir, base) = match target { + Some(t) => t, + None => ( + crate::config::config_dir().ok_or_else(|| bad(C, "no settings folder to save the place names in"))?.join("geonames"), + GEONAMES_BASE.to_string(), + ), + }; if !base_allowed(&base) { return Err(bad(C, "`base` must be an https:// address")); } @@ -309,7 +325,7 @@ pub fn specs() -> Vec { "Download Place Names (GeoNames)", ["Photo"], None, - "{dataset?: folder} → {started, path, attribution} — downloads the GeoNames cities list (CC-BY 4.0, ~3 MB, from download.geonames.org) in the background for Fill Location from GPS; no photo data is sent", + "{} → {started, path, attribution} — downloads the GeoNames cities list (CC-BY 4.0, ~3 MB, from download.geonames.org) in the background for Fill Location from GPS, always into `geonames` in the settings folder (a folder or server named by the caller is refused); no photo data is sent", always, download::start )); @@ -468,7 +484,8 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] fn download(s: &mut Session, base: &str, dir: &Path) -> DownloadOutcome { - s.execute("metadata.downloadPlaceNames", &json!({"dataset": dir, "base": base})).unwrap(); + s.place_names.download_to = Some((dir.to_path_buf(), base.to_string())); + s.execute("metadata.downloadPlaceNames", &json!({})).unwrap(); assert!(s.place_names.downloading() || s.place_names.lock().unreported.is_some()); let started = std::time::Instant::now(); loop { @@ -493,7 +510,8 @@ mod tests { let base = serve(); let dir = std::env::temp_dir().join(format!("lightcraft-geocode-dl-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); - assert!(s.execute("metadata.downloadPlaceNames", &json!({"dataset": dir, "base": "http://example.com/"})).is_err()); + s.place_names.download_to = Some((dir.clone(), "http://example.com/".into())); + assert!(s.execute("metadata.downloadPlaceNames", &json!({})).is_err(), "plain http to another machine"); for bad in ["missing", "garbage", "short"] { let o = download(&mut s, &format!("{base}/{bad}/"), &dir); @@ -516,6 +534,53 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Issue #2575: a control or MCP client named the folder (`dataset`) and the server (`base`), + /// so it could have a server's bytes written as `cities15000.txt`, `admin1CodesASCII.txt` and + /// `countryInfo.txt` into any folder. Both are refused now, before anything starts. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_client_cannot_choose_where_the_place_names_download_to() { + let mut s = Session::with_demo(); + let dir = std::env::temp_dir().join(format!("lightcraft-geocode-elsewhere-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for p in [json!({"dataset": dir}), json!({"base": "https://example.com/"}), json!({"dataset": dir, "base": "https://example.com/"})] { + let e = s.execute("metadata.downloadPlaceNames", &p).unwrap_err().to_string(); + assert!(e.contains("not accepted"), "{p}: {e}"); + } + assert!(!s.place_names.downloading() && s.activity.list().is_empty(), "nothing started"); + assert!(!dir.exists(), "nothing written"); + } + + /// The downloaded files replace what is there by renaming a complete temp file over it, so a + /// link planted under one of their names is replaced, not followed to the file it points at. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_download_replaces_a_planted_link_instead_of_writing_through_it() { + let mut s = Session::with_demo(); + let base = serve(); + let root = std::env::temp_dir().join(format!("lightcraft-geocode-link-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let dir = root.join("geonames"); + std::fs::create_dir_all(&dir).unwrap(); + let victim = root.join("victim.txt"); + std::fs::write(&victim, "keep me").unwrap(); + let link = dir.join("countryInfo.txt"); + #[cfg(unix)] + let linked = std::os::unix::fs::symlink(&victim, &link); + #[cfg(windows)] + let linked = std::os::windows::fs::symlink_file(&victim, &link); + if let Err(e) = linked { + lightcraft_testkit::skip!(System, "can't create a symbolic link here: {e}"); + let _ = std::fs::remove_dir_all(&root); + return; + } + assert_eq!(download(&mut s, &format!("{base}/good/"), &dir), DownloadOutcome::Done(2)); + assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep me", "the link's target is untouched"); + assert!(!std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link is now the downloaded file"); + assert!(std::fs::read_to_string(&link).unwrap().contains("France")); + let _ = std::fs::remove_dir_all(&root); + } + #[test] fn download_base_is_https_or_loopback_only() { assert!(download::base_allowed("https://download.geonames.org/export/dump/")); diff --git a/crates/engine/src/cmd/lens_refresh.rs b/crates/engine/src/cmd/lens_refresh.rs new file mode 100644 index 0000000000..350522b6c4 --- /dev/null +++ b/crates/engine/src/cmd/lens_refresh.rs @@ -0,0 +1,212 @@ +//! Lens profiles looked up again when the lens database appears or changes. A photo's lens data is +//! stored when it is imported ([`Photo::embedded_lens`]), so photos imported before the database was there say "no +//! profile" until something reads their file again. When the database arrives (downloaded on the user's request) or is updated, +//! and when "Enable Lens Corrections" is ticked on a photo without a profile, every library raw that has no profile +//! but whose lens the database knows by name is probed again and gets what Reload from Disk would give it: the +//! profile, and the correction switched on where its settings are still what import gave it (an edited photo keeps +//! its settings). +//! +//! Split like [`super::recheck`] so the app probes on a worker thread: [`missing`] lists what to probe (no +//! file-system calls), [`probe`] reads the files without the session, [`apply`] applies the results as LightCraft's +//! own bookkeeping (journaled, not an undo step). Agents and tests use `library.refreshLensProfiles`. + +use lightcraft_catalog::{Catalog, Op, Photo, PhotoId}; +use lightcraft_develop::LensSource; +use serde_json::{Value, json}; + +use super::{CommandSpec, always, bad, cmd}; +use crate::media::{FileProbe, ProbeInfo}; +use crate::{Result, Session}; + +/// A photo to probe again, and its file when listed (a result for a photo moved meanwhile is dropped). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Missing { + pub id: PhotoId, + pub path: String, +} + +/// Library raws with a file, no lens profile and a lens the database `db` knows by name (`ids`: only these; virtual +/// copies follow the photo they were copied from). With `again` (the database's files were replaced, or an agent +/// asked for every photo), also the raws whose profile came from the database (the new data may give another one, or +/// none) and the raws whose file named no lens when they were imported (a newer LightCraft may read their lens). +/// No file-system calls. +pub fn missing(cat: &Catalog, db: &lightcraft_lensdb::LensDb, ids: Option<&[PhotoId]>, again: bool) -> Vec { + // a photo and its virtual copies list the photo once, in library order + let mut seen = std::collections::HashSet::new(); + let from_database = |p: &Photo| p.embedded_lens.is_some_and(|l| l.source == LensSource::Database); + cat.photos() + .filter(|p| ids.is_none_or(|ids| ids.contains(&p.id) || p.copy_of.is_some_and(|c| ids.contains(&c)))) + .map(|p| p.copy_of.and_then(|c| cat.photo(c)).map_or(&**p, |orig| &**orig)) + .filter(|p| p.develops_raw()) + .filter(|p| { + let lens = p.meta.lens.trim(); + match &p.embedded_lens { + None if lens.is_empty() => again, + None => crate::lens_profiles::profile_name(db, &p.meta.camera, lens).is_some(), + Some(_) => again && from_database(p), + } + }) + .filter_map(|p| crate::cmd::missing::checked_path(p).map(|path| Missing { id: p.id, path: path.to_string() })) + .filter(|m| seen.insert(m.id)) + .collect() +} + +/// Probe each listed photo's file as Reload would. Doesn't touch the session. +pub fn probe(probe: &FileProbe, list: Vec) -> Vec<(Missing, std::result::Result)> { + let paths: Vec = list.iter().map(|x| x.path.clone()).collect(); + list.into_iter().zip(crate::import::probe_with(probe, &paths)).collect() +} + +/// Apply [`probe`]'s results: each photo and its virtual copies get the lens data their file gives now, in one batch +/// that is journaled but isn't an undo step: a profile found (or a different one from a replaced database), a +/// database profile the database no longer gives removed, and the lens's name where the catalog had none. Returns +/// the photos that gained or changed a profile. +pub fn apply(s: &mut Session, results: Vec<(Missing, std::result::Result)>) -> Result> { + let mut ops = Vec::new(); + let mut found = Vec::new(); + let mut changed = Vec::new(); + // each photo's virtual copies, gathered once for the whole batch (the catalog doesn't change until it's applied) + let mut copies: std::collections::HashMap> = std::collections::HashMap::new(); + for p in s.catalog.photos() { + if let Some(original) = p.copy_of { + copies.entry(original).or_default().push(p.id); + } + } + for (item, info) in results { + let Ok(info) = info else { continue }; + // the photo moved or left the library while its file was read: the result is stale, for its copies too + if s.catalog.photo(item.id).and_then(|p| crate::cmd::missing::checked_path(p)) != Some(item.path.as_str()) { + continue; + } + let family = std::iter::once(item.id).chain(copies.get(&item.id).into_iter().flatten().copied()); + for id in family { + let Some(p) = s.catalog.photo(id) else { continue }; + // nothing found for a photo without a database profile: a file's own correction is Reload's business + let from_database = p.embedded_lens.is_some_and(|l| l.source == LensSource::Database); + if info.embedded_lens.is_some() || from_database { + let mine = crate::cmd::convert::lens_ops(id, p, &info); + if !mine.is_empty() { + ops.extend(mine); + changed.push(id); + if info.embedded_lens.is_some() { + found.push(id); + } + } + } + let named = info.meta.lens.trim(); + if p.meta.lens.trim().is_empty() && !named.is_empty() { + let mut meta = p.meta.clone(); + meta.lens = named.to_string(); + ops.push(Op::SetMeta { id, meta: Box::new(meta) }); + } + } + } + if !ops.is_empty() { + s.apply_system(Op::Batch { ops })?; + } + for id in &changed { + s.media.forget(*id); + } + Ok(found) +} + +/// Why a photo has no lens profile, in words for the Optics panel: `None` when it has one. +pub fn no_profile_reason(p: &Photo) -> Option { + if p.embedded_lens.is_some() { + return None; + } + let lens = p.meta.lens.trim(); + Some(if lens.is_empty() { "This file names no lens.".to_string() } else { format!("No lens profile found for {lens}.") }) +} + +fn refresh(s: &mut Session, p: &Value) -> Result { + const C: &str = "library.refreshLensProfiles"; + let fp = super::recheck::file_probe(s).ok_or_else(|| bad(C, "this session has no file access"))?; + let ids: Option> = match p.get("ids") { + None | Some(Value::Null) => None, + Some(Value::Array(a)) => Some(a.iter().map(|v| v.as_u64().map(PhotoId).ok_or_else(|| bad(C, "ids are photo ids"))).collect::>()?), + Some(_) => return Err(bad(C, "ids is a list of photo ids")), + }; + let again = match p.get("all") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(C, "all is true or false")), + }; + let Some(db) = crate::lens_profiles::database() else { + return Ok(json!({"checked": 0, "found": [], "database": false})); + }; + let listed = missing(&s.catalog, &db, ids.as_deref(), again); + let n = listed.len(); + let found = apply(s, probe(&fp, listed))?; + Ok(json!({"checked": n, "found": found.iter().map(|i| i.0).collect::>(), "database": true})) +} + +fn download(s: &mut Session, _: &Value) -> Result { + const C: &str = "lens.downloadDatabase"; + let dir = crate::lensfun_download::default_dir().ok_or_else(|| bad(C, "this session has no data folder"))?; + start_download(s, &dir, crate::lensfun_download::mirrors(), crate::lensfun_download::FILES).map_err(|e| bad(C, e))?; + Ok(json!({"started": true, "dir": dir.to_string_lossy()})) +} + +/// Fetch the database into `dir` and select it, so this session reads it once it is in place (a session that +/// selected no database, e.g. a bare headless one, would otherwise download it and go on without it; the user's +/// `LIGHTCRAFT_LENSFUN_DIR` still wins). Until the download is whole the folder has no marker and isn't read. +pub fn start_download( + s: &mut Session, + dir: &std::path::Path, + mirrors: Vec, + files: &'static [crate::lensfun_download::Pin], +) -> std::result::Result<(), String> { + let activity = s.activity.clone(); + s.lensfun.start(dir, mirrors, files, &activity)?; + if crate::lens_profiles::host_dir().as_deref() != Some(dir) { + crate::lens_profiles::use_dir(Some(dir.to_path_buf())); + } + Ok(()) +} + +fn status(s: &mut Session, _: &Value) -> Result { + use crate::lensfun_download::State; + let state = match s.lensfun.state() { + State::Idle => json!({"state": "idle"}), + State::Running { bytes, total } => json!({"state": "running", "bytes": bytes, "total": total}), + State::Done { files } => json!({"state": "done", "files": files}), + State::Failed(e) => json!({"state": "failed", "error": e}), + State::Cancelled => json!({"state": "cancelled"}), + }; + let dir = crate::lens_profiles::dir(); + let lenses = crate::lens_profiles::database().map_or(0, |db| db.lenses.len()); + Ok(json!({"download": state, "dir": dir.map(|d| d.to_string_lossy().to_string()), "lenses": lenses})) +} + +pub fn specs() -> Vec { + vec![ + cmd!( + "library.refreshLensProfiles", + "Look Up Lens Profiles Again", + [], + None, + "{ids?: [photo ids], all?: bool} — library raws without a lens profile whose lens the lens database knows are read again and get their profile (the correction is switched on where the photo's settings are still as imported); with all, also raws whose profile came from the database (it may give another, or none) and raws whose file named no lens at import; the app does this by itself when the database arrives (all: when its files were replaced) and when Enable Lens Corrections is ticked; not an undo step → {checked, found: [ids], database: bool}", + always, + refresh + ), + cmd!( + "lens.downloadDatabase", + "Download the Lens Database", + [], + None, + "{} — fetch lensfun's lens database (CC BY-SA 3.0, pinned to one commit, checked file by file) into the app's data folder in the background, with an activity row, and read lens profiles from it once it is in place (unless LIGHTCRAFT_LENSFUN_DIR names another folder); the desktop app offers it on its first launch and in Settings. LIGHTCRAFT_LENSFUN_URL lists other places to fetch the same files from → {started, dir}", + always, + download + ), + cmd!( + "lens.databaseStatus", + "Lens Database Status", + [], + None, + "{} → {download: {state: idle|running|done|failed|cancelled, …}, dir, lenses (in the database in use)}", + always, + status + ), + ] +} diff --git a/crates/engine/src/cmd/library/selection.rs b/crates/engine/src/cmd/library/selection.rs index 964b2a8c85..40130adb9d 100644 --- a/crates/engine/src/cmd/library/selection.rs +++ b/crates/engine/src/cmd/library/selection.rs @@ -182,12 +182,17 @@ pub(super) fn rotate(s: &mut Session, p: &Value, cw: bool) -> Result { let targets = s.targets(p)?; let mut ops = Vec::new(); for id in targets { - if let Some(d) = s.develop_of(id) { - let mut d = (*d).clone(); + if let Some(before) = s.develop_of(id) { + let mut d = (*before).clone(); d.orientation = d.orientation.rotated(cw); // the crop lives in the oriented frame, so it turns with the image (else it keeps the old width and height and cuts the photo) let turn = lightcraft_geom::Orientation::Normal.rotated(cw); d.crop.geometry.rect = turn.map_norm_rect(d.crop.geometry.rect); + // and so do the masks: on the photo first (an old one), then turned with it + s.attach_masks(id, &before, &mut d); + for m in &mut d.masks { + lightcraft_pipeline::mask_space::turn(m, turn); + } d.crop.aspect = d.crop.aspect.map(|(w, h)| (h, w)); ops.extend(s.develop_op(id, d, "Rotate")); } diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index a2a842106a..b99e97c054 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -757,25 +757,29 @@ pub fn specs() -> Vec { } } // keywords are stored cleaned (`a | b ` is `a|b`), each once whatever its case - use lightcraft_catalog::keywords::{clean, same}; - let add = |m: &mut lightcraft_catalog::Meta, k: &str| { + use lightcraft_catalog::keywords::clean; + // (a set of the lower-cased keywords keeps this linear however many are supplied) + let mut seen: std::collections::HashSet = m.keywords.iter().map(|x| x.to_lowercase()).collect(); + let add = |m: &mut lightcraft_catalog::Meta, seen: &mut std::collections::HashSet, k: &str| { let k = clean(k); - if !k.is_empty() && !m.keywords.iter().any(|x| same(x, &k)) { + if !k.is_empty() && seen.insert(k.to_lowercase()) { m.keywords.push(k); } }; if let Some(k) = strs("keywords") { m.keywords.clear(); + seen.clear(); for k in k { - add(&mut m, &k); + add(&mut m, &mut seen, &k); } } for k in strs("addKeywords").unwrap_or_default() { - add(&mut m, &k); + add(&mut m, &mut seen, &k); } - for k in strs("removeKeywords").unwrap_or_default() { - let k = clean(&k); - m.keywords.retain(|x| !same(&clean(x), &k)); + let removed: std::collections::HashSet = + strs("removeKeywords").unwrap_or_default().iter().map(|k| clean(k).to_lowercase()).collect(); + if !removed.is_empty() { + m.keywords.retain(|x| !removed.contains(&clean(x).to_lowercase())); } ops.push(Op::SetMeta { id, meta: Box::new(m) }); } diff --git a/crates/engine/src/cmd/lut_profiles.rs b/crates/engine/src/cmd/lut_profiles.rs index b7a0d49928..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) @@ -120,7 +123,9 @@ fn import(s: &mut Session, p: &Value) -> Result { let file = match &dir { Some(d) => { let f = d.join(format!("{}.cube", id.trim_start_matches("lut:"))); - std::fs::write(&f, &text).map_err(|e| bad(C, format!("{}: {e}", f.display())))?; + // a new file renamed into place: an entry already under the name (a link planted + // in the Profiles folder) is replaced, never written through + lightcraft_catalog::safe_file::write_atomic(&f, text.as_bytes()).map_err(|e| bad(C, format!("{}: {e}", f.display())))?; f.to_string_lossy().to_string() } // no library on disk: the registered LUT is all this session needs (a copy would only @@ -131,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); @@ -144,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/masks.rs b/crates/engine/src/cmd/masks.rs index 5fc083f51f..171435e22b 100644 --- a/crates/engine/src/cmd/masks.rs +++ b/crates/engine/src/cmd/masks.rs @@ -464,6 +464,31 @@ pub fn specs() -> Vec { let exclude = bool_or(p, "exclude", false); let id = s.active().ok_or_else(|| bad(c, "no active photo"))?; let mid = mask_id(p, s.active_mask, c)?; + // an old mask (on the corrected frame, as the click then is) goes onto the photo + // first, and the click with it: the model works on the photo before lens + // corrections, Upright and Transform, and reads every click there + let mut at = at; + if let Some(cur) = s.develop_of(id).filter(|d| d.masks.iter().any(|m| m.id == mid && !m.on_photo)) { + if let Some(f) = s.mask_frame(id, &cur) { + // a click on the corrected frame's blank space is off the photo, not on + // its edge (a hair past it, from rounding, is on the edge) + const EDGE: f64 = 1e-6; + let n = f.for_mask(true).norm_to_mask(at); + let on = |v: f64| v.is_finite() && (-EDGE..=1.0 + EDGE).contains(&v); + if !(on(n.x) && on(n.y)) { + return Err(bad(c, "the point is outside the photo")); + } + at = Point::new(n.x.clamp(0.0, 1.0), n.y.clamp(0.0, 1.0)); + } + let mut on = (*cur).clone(); + s.attach_masks(id, &cur, &mut on); + s.apply_silent(lightcraft_catalog::Op::SetDevelop { + id, + settings: std::sync::Arc::new(on), + label: "Masks".into(), + edited: None, + })?; + } let d = s.develop_of(id).unwrap_or_default(); let m = d.masks.iter().find(|m| m.id == mid).ok_or_else(|| bad(c, format!("no mask {mid}")))?; let k = m diff --git a/crates/engine/src/cmd/missing.rs b/crates/engine/src/cmd/missing.rs index e5a17ab5db..17454cac26 100644 --- a/crates/engine/src/cmd/missing.rs +++ b/crates/engine/src/cmd/missing.rs @@ -163,7 +163,11 @@ fn stored_hash(p: &Photo) -> Option<&str> { /// The content hash of the file at `path` (as import computes it), if it can be read. Read in /// pieces: the file is whatever is on the disk, of any size. fn file_hash(path: &str) -> Option { - hash_reader(std::fs::File::open(path).ok()?) + use std::io::Read; + // the opened file must be regular (a FIFO or device would never end), and no more than its size at open is read + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok().filter(|m| m.is_file())?; + hash_reader(file.take(meta.len())) } /// The content hash of what `r` gives, read in pieces (the hash import computes of the whole). @@ -230,6 +234,9 @@ mod tests { std::fs::write(&f, b"pixels").unwrap(); assert_eq!(file_hash(f.to_str().unwrap()), Some(lightcraft_preview::hash_bytes(b"pixels").to_string())); assert_eq!(file_hash(dir.0.join("nope").to_str().unwrap()), None); + assert_eq!(file_hash(dir.0.to_str().unwrap()), None, "a folder has no content hash"); + #[cfg(unix)] + assert_eq!(file_hash("/dev/zero"), None, "a device never ends"); } } diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index dc1f2c864a..95aff90b79 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -360,8 +360,9 @@ struct SmartCounts { fn original_only(source: crate::media::SourceRef) -> Option { use crate::media::SourceRef; match source { + // (a smart preview keeps the file's own colour: an imported camera profile is applied when the original is read) SourceRef::File { path, max_edge, loader, denoise, .. } => { - Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, reduced: None }) + Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, camera_profile: None, reduced: None }) } SourceRef::Loaded(d) if d.info.is_some() && !d.from_proxy && !d.reduced => Some(SourceRef::Loaded(d)), _ => None, @@ -486,7 +487,9 @@ fn smart(s: &mut Session, p: &Value) -> Result { continue; } let path = crate::smart::sharded_file_path(&dir, &ph); - let source = (!discard).then(|| s.media.source_ref(&ph, crate::media::SourceLevel::Preview)); + // (a smart preview keeps the file's own colour: never built with the photo's imported camera profile, nor + // from a cached source developed with it) + let source = (!discard).then(|| s.media.source_ref_without_profile(&ph, crate::media::SourceLevel::Preview)); jobs.push((id, path, source, preview_fitted_look(&ph))); } let custom = s.smart_previews_dir.is_some(); @@ -720,8 +723,15 @@ mod tests { let mut jobs = jobs_for(&mut s, id, Some(512)); assert_eq!(jobs.len(), 2, "view and thumbnail"); assert!(jobs[0].view_cache.is_some(), "the view renders first"); - jobs[1].source = - SourceRef::File { path: "/nonexistent/photo.arw".into(), max_edge: 512, loader: None, fallback: None, denoise: None, reduced: None }; + jobs[1].source = SourceRef::File { + path: "/nonexistent/photo.arw".into(), + max_edge: 512, + loader: None, + fallback: None, + denoise: None, + camera_profile: None, + reduced: None, + }; assert!(run_photo(jobs), "the thumbnail rendered from the view's decoded source"); } diff --git a/crates/engine/src/cmd/similar.rs b/crates/engine/src/cmd/similar.rs new file mode 100644 index 0000000000..fd608ac2b7 --- /dev/null +++ b/crates/engine/src/cmd/similar.rs @@ -0,0 +1,399 @@ +//! Find Similar (`library.findSimilar`), split so the app can read the photos on a worker thread: the +//! first search reads a thumbnail-level source of every photo in the library, and in a large +//! library that froze the window for as long as it took (issue #3468). [`plan`] lists what is to be +//! read (no file-system calls), [`measure`] reads it without the session (cancellable, with +//! progress), [`keep`] adds what it found to the session's signatures and [`apply`] answers from +//! those. The command itself (the CLI, MCP without an app) does all of them at once. +//! +//! A search keeps no decoded source and learns nothing from one: it only looks, and in a large library +//! it would push out of memory what the grid and the loupe are showing. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Mutex, PoisonError}; + +use lightcraft_catalog::PhotoId; +use serde_json::{Value, json}; + +use super::bad; +use crate::media::{SourceLevel, SourceRef, content_key}; +use crate::{Result, Session}; + +const C: &str = "library.findSimilar"; + +/// The kind of the row in the activity stack that a search on a worker thread holds. +pub const KIND: &str = "similar"; + +/// A content key and that content's look-alike signature. +pub type Signature = (String, [f32; 64]); + +/// Whether a search can start (the command's `enabled`): one at a time, for what a second one would +/// read the first is reading. +pub fn no_search_running(s: &Session) -> std::result::Result<(), String> { + if s.activity.list().iter().any(|r| r.kind == KIND) { Err("a search for similar photos is already running".to_string()) } else { Ok(()) } +} + +/// What a search asks. +#[derive(Debug)] +pub struct Search { + id: PhotoId, + min: f32, + filter: bool, +} + +/// A content whose signature isn't known yet, and how to read it: from the first of its photos that +/// can be read (a copy that is offline gives way to the next). +struct Content { + key: String, + sources: Vec, +} + +/// What a search has to read: the searched photo first, as nothing can be compared without it. +pub struct Reads { + me: Option, + rest: Vec, +} + +impl Reads { + /// How many contents are to be read. + pub fn len(&self) -> usize { + self.rest.len().saturating_add(usize::from(self.me.is_some())) + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +/// The search `p` asks for and what it has to read, once for each content not known yet. No +/// file-system calls. +pub fn plan(s: &mut Session, p: &Value) -> Result<(Search, Reads)> { + let id = super::photo_id(p, C)?.or(s.active()).ok_or_else(|| bad(C, "no photo"))?; + let min = p.get("similarity").and_then(Value::as_f64).unwrap_or(0.8) as f32; + let filter = p.get("filter").and_then(Value::as_bool).unwrap_or(true); + let photo = s.catalog.photo(id).ok_or_else(|| bad(C, "can't read the photo"))?; + let my_key = content_key(photo); + let me = + (!s.signatures.contains_key(&my_key)).then(|| Content { sources: vec![s.media.source_ref(photo, SourceLevel::Thumb)], key: my_key.clone() }); + let mut rest: Vec = Vec::new(); + let mut at = std::collections::HashMap::new(); + for q in s.catalog.photos().filter(|q| q.in_library()) { + let key = content_key(q); + // (the searched photo's content is known by the time these are read, or the search has ended) + if key == my_key || s.signatures.contains_key(&key) { + continue; + } + let source = s.media.source_ref(q, SourceLevel::Thumb); + match at.get(&key).and_then(|i: &usize| rest.get_mut(*i)) { + Some(content) => content.sources.push(source), + None => { + at.insert(key.clone(), rest.len()); + rest.push(Content { key, sources: vec![source] }); + } + } + } + Ok((Search { id, min, filter }, Reads { me, rest })) +} + +/// `content`'s signature, or `None` when none of its photos can be read or `cancel` is set first. A +/// decoder's panic is that photo's failure, not the search's. +fn signature_of(content: &Content, cancel: &AtomicBool) -> Option<[f32; 64]> { + content.sources.iter().find_map(|source| { + if cancel.load(Ordering::Relaxed) { + return None; + } + crate::guard::catch("Find Similar", || { + crate::memory::in_background(|| source.load_source()).ok().map(|decoded| lightcraft_pipeline::cull::signature(&decoded.image)) + }) + .ok() + .flatten() + }) +} + +/// Read what [`plan`] listed, several photos at once. Doesn't touch the session. `progress(done)` is +/// called from the threads doing the reading; once `cancel` is set no further file is started, and +/// what was read until then comes back. A searched photo that can't be read ends it there. +pub fn measure(reads: Reads, cancel: &AtomicBool, progress: &(dyn Fn(usize) + Sync)) -> Vec { + let found = Mutex::new(Vec::with_capacity(reads.len().min(4096))); + let done = AtomicUsize::new(0); + let keep = |key: String, v: [f32; 64]| found.lock().unwrap_or_else(PoisonError::into_inner).push((key, v)); + if let Some(me) = reads.me { + let Some(v) = signature_of(&me, cancel) else { return Vec::new() }; + keep(me.key, v); + done.store(1, Ordering::Relaxed); + progress(1); + } + let lanes = crate::export::export_parallelism(reads.rest.len()); + let queue = Mutex::new(reads.rest.into_iter()); + let work = || { + while !cancel.load(Ordering::Relaxed) { + let next = queue.lock().unwrap_or_else(PoisonError::into_inner).next(); + let Some(content) = next else { break }; + if let Some(v) = signature_of(&content, cancel) { + keep(content.key, v); + } + progress(done.fetch_add(1, Ordering::Relaxed).saturating_add(1)); + } + }; + #[cfg(not(target_arch = "wasm32"))] + std::thread::scope(|sc| { + for k in 1..lanes.max(1) { + // a lane that can't start leaves its photos to the others (and to this thread) + if std::thread::Builder::new().name(format!("similar-{k}")).spawn_scoped(sc, work).is_err() { + break; + } + } + work(); + }); + #[cfg(target_arch = "wasm32")] + { + let _ = lanes; + work(); + } + found.into_inner().unwrap_or_else(PoisonError::into_inner) +} + +/// Add what [`measure`] found to the signatures, also when the search was stopped: they hold for the +/// contents they were read from, and the next search doesn't read those again. +pub fn keep(s: &mut Session, found: Vec) { + s.signatures.extend(found); +} + +/// Answer `search` from the signatures known now, most similar first, and filter the view to the +/// photos found. A photo with none (it can't be read, or came after the [`plan`]) isn't compared. +pub fn apply(s: &mut Session, search: &Search) -> Result { + let known = s.catalog.photo(search.id).and_then(|photo| s.signatures.get(&content_key(photo))); + let me = *known.ok_or_else(|| bad(C, "can't read the photo"))?; + let mut hits: Vec<(PhotoId, f32)> = Vec::new(); + for q in s.catalog.photos().filter(|q| q.in_library()) { + if let Some(v) = s.signatures.get(&content_key(q)) { + let sim = lightcraft_pipeline::cull::similarity(&me, v); + if sim >= search.min { + hits.push((q.id, sim.clamp(0.0, 1.0))); + } + } + } + hits.sort_by(|a, b| b.1.total_cmp(&a.1)); + if search.filter { + s.shelved_filter = None; + s.filter.only = hits.iter().map(|h| h.0).collect(); + // an empty `only` means "no constraint": no hits is its own state that shows no photos + s.filter.only_none = s.filter.only.is_empty(); + } + Ok(json!({"photos": hits.iter().map(|(i, v)| json!({"id": i.0, "similarity": (v * 1000.0).round() / 1000.0})).collect::>()})) +} + +/// Find Similar: photos that look like `id` (signatures from thumbnail-level sources, cached by +/// content), most similar first; the view is filtered to them. +pub(super) fn run(s: &mut Session, p: &Value) -> Result { + let (search, reads) = plan(s, p)?; + let found = measure(reads, &AtomicBool::new(false), &|_| {}); + keep(s, found); + apply(s, &search) +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::sync::Arc; + + use lightcraft_catalog::{Op, Photo, Source}; + use lightcraft_raster::Rgb32f; + + use super::*; + + /// Reads per file, the files that can't be read and the file whose decoder panics. + #[derive(Default)] + struct Files { + reads: Mutex>, + unreadable: Mutex>, + panics: Mutex>, + /// Set once this many reads have started. + cancel_after: Option<(usize, Arc)>, + } + + impl Files { + fn reads_of(&self, path: &str) -> usize { + self.reads.lock().unwrap().get(path).copied().unwrap_or(0) + } + fn reads(&self) -> usize { + self.reads.lock().unwrap().values().sum() + } + } + + /// A session of photos `/p/.jpg`, each with its content hash when it has one. Odd numbers + /// in a name mean a picture that gets brighter to the right, others one that does downwards. + fn session(photos: &[(&str, Option<&str>)], files: Files) -> (Session, Arc) { + let files = Arc::new(files); + let mut s = Session::new(); + for (i, (name, hash)) in photos.iter().enumerate() { + let source = Source::File { path: format!("/p/{name}.jpg") }; + let mut p = Photo::new(PhotoId(i as u64 + 1), source, &format!("{name}.jpg"), "JPEG", 64, 64, "2026-01-01T00:00:00"); + p.content_hash = hash.map(str::to_string); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + let seen = files.clone(); + s.media.file_loader = Some(Arc::new(move |path: &str, _, _| { + let started = { + let mut reads = seen.reads.lock().unwrap(); + *reads.entry(path.to_string()).or_default() += 1; + reads.values().sum::() + }; + if let Some((after, cancel)) = &seen.cancel_after + && started >= *after + { + cancel.store(true, Ordering::SeqCst); + } + if seen.panics.lock().unwrap().as_deref() == Some(path) { + panic!("a decoder fails on {path}"); + } + if seen.unreadable.lock().unwrap().iter().any(|f| f == path) { + return Err(format!("{path}: gone")); + } + let across = path.bytes().filter(u8::is_ascii_digit).any(|b| b % 2 == 1); + let image = Rgb32f::from_fn(64, 64, |x, y| { + let v = if across { x } else { y }; + [v as f32 / 64.0; 3] + }); + Ok((image, Default::default())) + })); + (s, files) + } + + fn ids(r: &Value) -> Vec { + r["photos"].as_array().unwrap().iter().map(|h| h["id"].as_u64().unwrap()).collect() + } + + /// A search on a worker thread holds a row of its kind: the command is off until the row goes. + #[test] + fn a_running_search_turns_the_command_off() { + let (mut s, files) = session(&[("a1", None), ("b2", None)], Files::default()); + let row = s.activity.start(KIND, "Find Similar Photos", crate::activity::Cancel::No); + let off = s.commands().into_iter().find(|c| c.id == C).is_some_and(|c| !c.enabled); + assert!(off, "the menu shows it off"); + assert!(matches!(s.execute(C, &json!({"id": 1})), Err(crate::EngineError::Disabled(..)))); + assert_eq!(files.reads(), 0); + drop(row); + assert!(s.execute(C, &json!({"id": 1})).is_ok()); + } + + #[test] + fn making_the_plan_reads_no_file() { + let (mut s, files) = session(&[("a1", None), ("b2", None), ("c1", None)], Files::default()); + let (_, reads) = plan(&mut s, &json!({"id": 1})).unwrap(); + assert_eq!(reads.len(), 3); + assert_eq!(files.reads(), 0); + } + + #[test] + fn the_command_reads_each_photo_and_finds_the_ones_alike() { + let names: Vec = (0..40).map(|i| format!("p{i}")).collect(); + let photos: Vec<(&str, Option<&str>)> = names.iter().map(|n| (n.as_str(), None)).collect(); + let (mut s, files) = session(&photos, Files::default()); + let r = s.execute("library.findSimilar", &json!({"id": 1})).unwrap(); + assert_eq!(files.reads(), 40, "each once"); + assert!(ids(&r).contains(&1) && ids(&r).len() < 40, "{r}"); + // known now: no file is read again + let again = s.execute("library.findSimilar", &json!({"id": 1})).unwrap(); + assert_eq!(files.reads(), 40); + assert_eq!(ids(&again), ids(&r)); + } + + #[test] + fn a_content_is_read_once_and_an_unreadable_copy_gives_way_to_the_next() { + let files = Files::default(); + files.unreadable.lock().unwrap().push("/p/copy2.jpg".into()); + let photos = [("me1", None), ("copy2", Some("h")), ("copy4", Some("h")), ("copy6", Some("h"))]; + let (mut s, files) = session(&photos, files); + let r = s.execute("library.findSimilar", &json!({"id": 1, "similarity": -1.0})).unwrap(); + assert_eq!(files.reads_of("/p/copy2.jpg"), 1); + assert_eq!(files.reads_of("/p/copy4.jpg"), 1, "the next copy stands in"); + assert_eq!(files.reads_of("/p/copy6.jpg"), 0, "its content is known by then"); + assert_eq!(ids(&r).len(), 4, "every copy is compared: {r}"); + } + + #[test] + fn a_searched_photo_that_cannot_be_read_ends_the_search_before_any_other_is_read() { + let files = Files::default(); + files.unreadable.lock().unwrap().push("/p/me1.jpg".into()); + let (mut s, files) = session(&[("me1", None), ("b2", None), ("c1", None)], files); + let e = s.execute("library.findSimilar", &json!({"id": 1})).unwrap_err(); + assert!(e.to_string().contains("can't read the photo"), "{e}"); + assert_eq!(files.reads(), 1, "only the searched photo"); + assert!(s.signatures.is_empty()); + assert_eq!(s.filter, Default::default(), "the view stays as it was"); + } + + #[test] + fn a_photo_nobody_has_is_refused_at_once() { + let (mut s, files) = session(&[("a1", None)], Files::default()); + assert!(matches!(plan(&mut s, &json!({"id": 99})), Err(crate::EngineError::BadParams { .. }))); + assert_eq!(files.reads(), 0); + } + + #[test] + fn a_photo_whose_decoder_panics_is_left_out_and_the_search_goes_on() { + let files = Files::default(); + *files.panics.lock().unwrap() = Some("/p/bad3.jpg".into()); + let (mut s, _) = session(&[("me1", None), ("bad3", None), ("ok1", None), ("ok5", None)], files); + let r = s.execute("library.findSimilar", &json!({"id": 1, "similarity": -1.0})).unwrap(); + assert_eq!(ids(&r).len(), 3, "{r}"); + assert!(!ids(&r).contains(&2), "{r}"); + } + + /// Stopped after some reads: what was read is kept, the view is left alone, and the next search + /// reads only the rest. + #[test] + fn a_stopped_search_keeps_what_it_read_and_the_next_reads_the_rest() { + let cancel = Arc::new(AtomicBool::new(false)); + let files = Files { cancel_after: Some((5, cancel.clone())), ..Default::default() }; + let names: Vec = (0..64).map(|i| format!("p{i}")).collect(); + let photos: Vec<(&str, Option<&str>)> = names.iter().map(|n| (n.as_str(), None)).collect(); + let (mut s, _) = session(&photos, files); + let (_, reads) = plan(&mut s, &json!({"id": 1})).unwrap(); + let found = measure(reads, &cancel, &|_| {}); + let read = found.len(); + assert!((1..64).contains(&read), "stopped along the way: {read}"); + keep(&mut s, found); + assert_eq!(s.filter, Default::default()); + let (_, rest) = plan(&mut s, &json!({"id": 1})).unwrap(); + assert_eq!(rest.len(), 64 - read); + } + + #[test] + fn a_stopped_search_reads_nothing_more() { + let (mut s, files) = session(&[("a1", None), ("b2", None), ("c1", None)], Files::default()); + let (_, reads) = plan(&mut s, &json!({"id": 1})).unwrap(); + assert!(measure(reads, &AtomicBool::new(true), &|_| {}).is_empty()); + assert_eq!(files.reads(), 0); + } + + /// What changed while the files were read: a photo deleted since isn't an answer, and one added + /// since has no signature to compare. + #[test] + fn photos_that_changed_during_the_search_are_answered_as_they_are_now() { + let (mut s, _) = session(&[("a1", None), ("b1", None), ("c1", None)], Files::default()); + let (search, reads) = plan(&mut s, &json!({"id": 1, "similarity": -1.0})).unwrap(); + let found = measure(reads, &AtomicBool::new(false), &|_| {}); + s.catalog.apply(Op::RemovePhoto { id: PhotoId(2) }).unwrap(); + let added = Photo::new(PhotoId(9), Source::File { path: "/p/new1.jpg".into() }, "new1.jpg", "JPEG", 64, 64, "2026-01-01T00:00:00"); + s.catalog.apply(Op::AddPhoto { photo: Box::new(added) }).unwrap(); + keep(&mut s, found); + let mut answer = ids(&apply(&mut s, &search).unwrap()); + answer.sort_unstable(); + assert_eq!(answer, [1, 3]); + } + + #[test] + fn progress_counts_every_content_read_or_not() { + let files = Files::default(); + files.unreadable.lock().unwrap().push("/p/b2.jpg".into()); + let (mut s, _) = session(&[("a1", None), ("b2", None), ("c1", None), ("d2", None)], files); + let (_, reads) = plan(&mut s, &json!({"id": 1})).unwrap(); + let top = AtomicUsize::new(0); + let found = measure(reads, &AtomicBool::new(false), &|done| { + top.fetch_max(done, Ordering::SeqCst); + }); + assert_eq!(top.load(Ordering::SeqCst), 4); + assert_eq!(found.len(), 3); + } +} diff --git a/crates/engine/src/config.rs b/crates/engine/src/config.rs index b3ded1fbd7..f7b762a6b3 100644 --- a/crates/engine/src/config.rs +++ b/crates/engine/src/config.rs @@ -146,6 +146,26 @@ impl Session { self } + /// Read lens profiles from the app's own copy of the lens database ([`crate::lensfun_download::default_dir`], + /// unless `LIGHTCRAFT_LENSFUN_DIR` names another) when it is there. Every host with a file system selects it + /// (desktop, CLI, headless MCP), so the same raw gets the same profile everywhere; it never fetches anything + /// ([`Self::with_lens_auto_download`] is that permission). + pub fn with_default_lens_database(self) -> Self { + let dir = crate::lensfun_download::default_dir(); + if let Some(d) = &dir { + crate::lensfun_download::recover(d); + } + crate::lens_profiles::use_dir(dir); + self + } + + /// Let the host offer the lens database at its start, and fetch it there once the user said yes + /// ([`crate::lensfun_download::fetch_on_start`] decides). Separate from selecting a database that is already there ([`Self::with_default_lens_database`]). + pub fn with_lens_auto_download(mut self) -> Self { + self.lens_auto_download = true; + self + } + /// Keep denoise models in the shared default folder ([`default_denoise_models_dir`]). pub fn with_default_denoise_models(mut self) -> Self { self.set_denoise_models_dir(default_denoise_models_dir()); diff --git a/crates/engine/src/denoise/gpu_tests.rs b/crates/engine/src/denoise/gpu_tests.rs index bb80cecdad..bff11cc20c 100644 --- a/crates/engine/src/denoise/gpu_tests.rs +++ b/crates/engine/src/denoise/gpu_tests.rs @@ -5,7 +5,8 @@ use lightcraft_denoise::manifest::{Domain, Gain}; fn folder(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("lc-engine-gpu-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); + // exclusive: a directory planted at this predictable name fails the test instead of receiving its files + std::fs::create_dir(&dir).unwrap(); dir } diff --git a/crates/engine/src/export/params.rs b/crates/engine/src/export/params.rs index 795d8f3672..34397fad3c 100644 --- a/crates/engine/src/export/params.rs +++ b/crates/engine/src/export/params.rs @@ -1,4 +1,5 @@ use super::options::{Conflict, DestinationMode, ExportFormat, HdrCurve, MetadataPolicy, Resize, ResizeMode, SharpenAmount, SharpenFor}; +use super::place::clean_subfolder; use super::prepare::DngCompression; use super::watermark::{Anchor, Watermark}; use super::{ExportOptions, JxlColour, JxlEffort, JxlOptions, OutputDepth, OutputSpace, TiffCompression}; @@ -429,7 +430,7 @@ impl ExportOptions { naming: s("naming").map_or(d.naming, str::to_string), start_number: u("startNumber").map_or(d.start_number, |v| v.min(999_999) as u32), destination_mode: s("destinationMode").and_then(DestinationMode::parse).unwrap_or(d.destination_mode), - subfolder: s("subfolder").map_or(d.subfolder, |v| v.trim().replace(['\\', ':', '\0'], "_")), + subfolder: s("subfolder").map_or(d.subfolder, clean_subfolder), conflict: s("conflict").and_then(Conflict::parse).unwrap_or(d.conflict), tiff_compression: match s("tiffCompression").map(str::to_ascii_lowercase).as_deref() { Some("none") => TiffCompression::None, diff --git a/crates/engine/src/export/place.rs b/crates/engine/src/export/place.rs index d223a3a791..c36f5e26bc 100644 --- a/crates/engine/src/export/place.rs +++ b/crates/engine/src/export/place.rs @@ -60,6 +60,14 @@ fn join_path(a: &str, b: &str) -> String { if a.is_empty() { b.to_string() } else { format!("{}/{b}", a.trim_end_matches('/')) } } +/// A subfolder that stays inside the destination folder (issue #2571): `\`, `:` and NUL become `_` +/// (so no drive, root or Windows separator), and empty, `.` and `..` parts are dropped; `a/b` still +/// nests. Applied where the folder is used, so presets and the Export dialog's field are covered too. +pub(super) fn clean_subfolder(s: &str) -> String { + let s = s.trim().replace(['\\', ':', '\0'], "_"); + s.split('/').map(str::trim).filter(|p| !p.is_empty() && *p != "." && *p != "..").collect::>().join("/") +} + impl<'a> Placer<'a> { pub(super) fn new( o: &'a ExportOptions, @@ -89,7 +97,8 @@ impl<'a> Placer<'a> { d.to_string() } }; - Ok(if self.o.subfolder.is_empty() { base } else { join_path(&base, &self.o.subfolder) }) + let sub = clean_subfolder(&self.o.subfolder); + Ok(if sub.is_empty() { base } else { join_path(&base, &sub) }) } /// Place photo `photo`'s export result (file `name`, its original in `source_dir`): write it diff --git a/crates/engine/src/export/tests.rs b/crates/engine/src/export/tests.rs index b8482a7df2..86600ddb57 100644 --- a/crates/engine/src/export/tests.rs +++ b/crates/engine/src/export/tests.rs @@ -912,6 +912,8 @@ fn ramp(depth: OutputDepth, space: OutputSpace) -> lightcraft_pipeline::Rendered fn distinct_levels(bytes: &[u8]) -> (usize, lightcraft_codecs::Decoded) { let d = lightcraft_codecs::decode(bytes, Default::default()).expect("decodes"); let mut v: Vec = (0..d.image.width).map(|x| d.image.get(x, 1)[1].to_bits()).collect(); + // sorted first: 8-bit output is dithered, so equal levels aren't all side by side + v.sort_unstable(); v.dedup(); (v.len(), d) } diff --git a/crates/engine/src/faces_index.rs b/crates/engine/src/faces_index.rs index 17bffbc193..5b23c58af4 100644 --- a/crates/engine/src/faces_index.rs +++ b/crates/engine/src/faces_index.rs @@ -214,9 +214,9 @@ impl Index { for (k, e) in &self.entries { buf.extend(self.record(k, e)); } - let part = path.with_extension("part"); - std::fs::write(&part, &buf)?; - std::fs::rename(&part, &path)?; + // a fresh temp file (never a `.part` entry left in the library, which could be a link + // to a file outside it) renamed over the cache + lightcraft_catalog::safe_file::write_atomic_nosync(&path, &buf)?; self.file_matches = true; self.rewrite = false; } @@ -367,9 +367,9 @@ impl Scanned { } else { let mut buf = self.header(); buf.extend(self.set.iter().flat_map(|id| id.to_le_bytes())); - let part = path.with_extension("part"); - std::fs::write(&part, &buf)?; - std::fs::rename(&part, &path)?; + // a fresh temp file (never a `.part` entry left in the library, which could be a link + // to a file outside it) renamed over the cache + lightcraft_catalog::safe_file::write_atomic_nosync(&path, &buf)?; self.file_matches = true; self.rewrite = false; } 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/probe.rs b/crates/engine/src/files/probe.rs index 12913bc6f3..41a0854f71 100644 --- a/crates/engine/src/files/probe.rs +++ b/crates/engine/src/files/probe.rs @@ -149,6 +149,13 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { } Err(Err(e)) => return Err(e), }; + // what the Exif reader can't see, the decoder may have read from the raw's own records (a CRW keeps make, + // model and capture time in CIFF records, no Exif): it fills the gaps, so the catalog knows the camera + let (meta, captured) = { + let mut m = m.clone(); + m.fill_missing(&raw.metadata); + meta_of(&m) + }; let (w, h) = raw.developed_size(); let (mut w, mut h) = (w.max(1) as u32, h.max(1) as u32); if raw.orientation.swaps_axes() { diff --git a/crates/engine/src/files/tests.rs b/crates/engine/src/files/tests.rs index 1b1b380dec..4fab917c82 100644 --- a/crates/engine/src/files/tests.rs +++ b/crates/engine/src/files/tests.rs @@ -44,6 +44,30 @@ fn psd_probe_reads_embedded_capture_time_gps_and_title() { use super::*; use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; +#[test] +fn crw_probes_name_their_camera_from_the_ciff_records() { + // no Exif in a CRW: the camera and capture time come from the decoder's records, and the catalog's camera + // string decides the white-balance scale (the D60 has chart-measured matrices, the 10D none) + let dir = std::env::var_os("LIGHTCRAFT_CORPUS") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus")) + .join("raw"); + for (name, camera, kelvin) in [("crw-canon-eos-d60.crw", "Canon Canon EOS D60", true), ("crw-canon-eos-10d-a.crw", "Canon Canon EOS 10D", false)] + { + let Ok(bytes) = std::fs::read(dir.join(name)) else { + lightcraft_testkit::skip!(Corpus, "{name} absent"); + continue; + }; + assert!(lightcraft_meta::extract(&bytes).model.is_none(), "{name}: no Exif to read"); + let info = probe_bytes(name, &bytes).unwrap(); + assert_eq!(info.meta.camera, camera, "{name}"); + assert!(info.captured.is_some(), "{name}"); + assert_eq!(lightcraft_catalog::relative_wb_camera(&info.format, &info.meta.camera), !kelvin, "{name}"); + let (t, _) = info.as_shot_wb.unwrap(); + assert_eq!(t != 6500.0, kelvin, "{name}: {t}"); + } +} + /// Which white-balance scale a raw gets (issue #730): a file with matrices of its own is absolute from them; a /// fitted-look file is absolute through its camera's measured matrices, which only read the as-shot /// multipliers as Kelvin; any other raw stays relative (6500 / 0 = as shot). The catalog's decision from the @@ -110,6 +134,17 @@ fn white_balance_scale_follows_the_files_matrices_then_the_cameras() { assert!(other.relative && other.scale_white.is_none()); let unknown = WbScaleOf::new(RawFormat::Nef, &ColorData::default(), mul, &lightcraft_meta::Metadata::default()); assert!(unknown.relative && unknown.as_shot(d65) == (6500.0, 0.0)); + // CRW: no matrices in the file. The EOS D60 has chart-measured matrices: Kelvin through them, its multipliers + // for the sun its D50 matrix was measured under reading as D50; another body stays relative, so its + // JPEG-fitted look applies + let d60 = WbScaleOf::new(RawFormat::Crw, &ColorData::default(), Some([2.362, 1.0, 1.298]), &meta("Canon", "Canon EOS D60")); + assert!(!d60.own_matrix && !d60.relative && d60.legacy_relative && d60.scale_white.is_some()); + let ((t, tint), (t50, tint50)) = (d60.as_shot(d65), xy_to_temp_tint(lightcraft_color::D50)); + assert!((t - t50).abs() < 50.0 && (tint - tint50).abs() < 2.0, "{t} {tint} vs D50 {t50} {tint50}"); + assert!(!lightcraft_catalog::relative_wb_camera("CRW", "Canon Canon EOS D60")); + let crw = WbScaleOf::new(RawFormat::Crw, &ColorData::default(), mul, &meta("Canon", "Canon EOS 10D")); + assert!(crw.relative && !crw.legacy_relative && crw.scale_white.is_none()); + assert!(lightcraft_catalog::relative_wb_camera("CRW", "Canon Canon EOS 10D")); // a file with matrices of its own (DNG): absolute from them, no matter whose camera let own = ColorData { illuminant: [21, 0], color_matrix: [Some(lightcraft_color::Mat3::IDENTITY), None], ..Default::default() }; let dng = WbScaleOf::new(RawFormat::Dng, &own, mul, &meta("SONY", "ILCE-7M3")); @@ -556,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)); @@ -1220,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/commit.rs b/crates/engine/src/import/commit.rs index a731488a00..df7cfe418a 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -9,6 +9,10 @@ use super::{HashMap, Op, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Sour pub(super) struct Plan { pub(super) slots: Vec, pub(super) transfers: Vec, + /// The content hashes and name families of [`Plan::transfers`], so each new file is checked against them in + /// constant time rather than by scanning the pending transfers. + pub(super) pending_hashes: std::collections::HashSet, + pub(super) pending_families: std::collections::HashSet<(String, String)>, } pub(super) enum Slot { @@ -26,9 +30,6 @@ pub(super) struct Transfer { pub(super) how: How, /// Copy as DNG. pub(super) dng: bool, - /// The folder (lowercase) and [`name_family`]: transfers of one family can take each other's - /// names, so they never run at the same time. - pub(super) family: (String, String), } pub(super) enum How { diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index 3269edb02a..ae635cb10d 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -329,7 +329,7 @@ impl ImportJob { // a copy of a file whose transfer is still pending: a duplicate only if that one succeeds if !opts.local && let Some(h) = &info.content_hash - && plan.transfers.iter().any(|t| t.info.content_hash.as_ref() == Some(h)) + && plan.pending_hashes.contains(h) { self.run_plan(&mut plan, &mut out, cancel); if cancel.load(Relaxed) { @@ -403,7 +403,7 @@ impl ImportJob { // into the same folder ends up with: that one goes first let as_named = name.as_deref().unwrap_or(if own.is_empty() { "photo" } else { own.as_str() }); let family = (dir.to_string_lossy().to_lowercase(), name_family(as_named)); - if plan.transfers.iter().any(|t| t.family == family) { + if plan.pending_families.contains(&family) { self.run_plan(&mut plan, &mut out, cancel); if cancel.load(Relaxed) { break; @@ -421,7 +421,10 @@ impl ImportJob { // Copy as DNG: the copied raw becomes a DNG (the copy is ours to replace) let dng = opts.convert_dng && mode == ImportMode::Copy && raw && !info.format.eq_ignore_ascii_case("DNG"); plan.slots.push(Slot::Transfer); - plan.transfers.push(Transfer { path, info, sidecar, dir, how, dng, family }); + // (transfers of one folder and name family can take each other's names, so they never run together) + plan.pending_families.insert(family); + plan.pending_hashes.extend(info.content_hash.clone()); + plan.transfers.push(Transfer { path, info, sidecar, dir, how, dng }); continue; } (ImportMode::Move, _) => { @@ -444,6 +447,8 @@ impl ImportJob { /// Run the transfers `plan` collected (on several threads) and append its items to `out` in /// file order. Transfers not started because `cancel` was set leave no item. fn run_plan(&mut self, plan: &mut Plan, out: &mut Prepared, cancel: &std::sync::atomic::AtomicBool) { + plan.pending_hashes.clear(); + plan.pending_families.clear(); let mut done = run_transfers(std::mem::take(&mut plan.transfers), self.file_bytes.as_ref(), cancel, &self.done).into_iter(); for slot in std::mem::take(&mut plan.slots) { let item = match slot { @@ -507,6 +512,7 @@ impl Session { stages: None, view_cache: None, display: None, + on_screen: false, slide: None, preview_cut: None, display_fit: None, diff --git a/crates/engine/src/import/job/tests.rs b/crates/engine/src/import/job/tests.rs index 82490915b7..08447ac02c 100644 --- a/crates/engine/src/import/job/tests.rs +++ b/crates/engine/src/import/job/tests.rs @@ -14,7 +14,7 @@ fn fixture(preview_edge: Option, renderable: bool, preview_only: bool) -> let mut session = Session::new(); let reads = Arc::new(AtomicUsize::new(0)); let count = reads.clone(); - session.media.file_loader = Some(Arc::new(move |_, edge| { + session.media.file_loader = Some(Arc::new(move |_, edge, _| { count.fetch_add(1, Ordering::SeqCst); if !renderable { return Err("synthetic raw cannot be rendered".into()); diff --git a/crates/engine/src/lens_profiles.rs b/crates/engine/src/lens_profiles.rs index 6e7f28120f..400afb6059 100644 --- a/crates/engine/src/lens_profiles.rs +++ b/crates/engine/src/lens_profiles.rs @@ -1,38 +1,153 @@ -//! Lens profile corrections from a lens database the user supplies ([`lightcraft_lensdb`]). +//! Lens profile corrections from a lens database ([`lightcraft_lensdb`]). //! //! When a raw carries no lens correction of its own (DNG opcodes, or a camera correction a raw reader converts, -//! [`crate::files::embedded_lens`]), the lens named in its EXIF is looked up in a lensfun-format database: the -//! directory in `LIGHTCRAFT_LENSFUN_DIR` (e.g. lensfun's `data/db`, CC-BY-SA, which is never bundled with the app). -//! The profile is converted to the same [`lightcraft_develop::EmbeddedLens`] form, so "Enable Profile Corrections", its -//! amount sliders, the GPU path and DNG export treat both alike. Without the variable nothing changes. -use std::path::PathBuf; -use std::sync::OnceLock; +//! [`crate::files::embedded_lens`]), the lens named in its EXIF is looked up in a lensfun-format database. The +//! database is lensfun's `data/db` (CC BY-SA 3.0): never bundled with the app, it is downloaded at run time into the +//! app's data folder ([`crate::lensfun_download`], which the desktop app offers on its first launch and Settings can start), or it is the +//! directory in `LIGHTCRAFT_LENSFUN_DIR` (which wins). The profile is converted to the same +//! [`lightcraft_develop::EmbeddedLens`] form (marked [`LensSource::Database`]), so "Enable Profile Corrections", its +//! amount sliders, the GPU path and DNG export treat both alike. Without a database nothing changes. +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, PoisonError, RwLock}; -use lightcraft_develop::EmbeddedLens; +use lightcraft_develop::{EmbeddedLens, LensSource}; use lightcraft_lensdb::{LensDb, Shot}; /// The environment variable naming the lens database directory. pub const ENV: &str = "LIGHTCRAFT_LENSFUN_DIR"; -/// The configured database, read once per process; `None` when none is configured or it holds no lenses. -pub fn database() -> Option<&'static LensDb> { - static DB: OnceLock> = OnceLock::new(); - DB.get_or_init(|| { - let dir = PathBuf::from(std::env::var_os(ENV)?); - match LensDb::load_dir(&dir) { - Ok((db, errors)) => { - for (file, e) in errors { - log::warn!("lens database: skipped {file}: {e}"); - } - (!db.lenses.is_empty()).then_some(db) - } - Err(e) => { - log::warn!("{e}"); - None +/// The database folder a host set up ([`use_dir`]), read when `LIGHTCRAFT_LENSFUN_DIR` is not set. +static HOST_DIR: RwLock> = RwLock::new(None); +/// The loaded database and the folder it was read from (`None` inside: nothing usable there). +static LOADED: RwLock>)>> = RwLock::new(None); +/// Bumped whenever the database in use changes ([`reload`]): photos looked up before may now find a profile. +static GENERATION: AtomicU64 = AtomicU64::new(0); +/// Bumped when the database's files were replaced ([`replaced`]): profiles found before may now be different. +static REPLACED: AtomicU64 = AtomicU64::new(0); + +/// Use `dir` (the app's downloaded lensfun data, [`crate::lensfun_download::default_dir`]) when +/// `LIGHTCRAFT_LENSFUN_DIR` is not set. Hosts with a file system call it; tests and sessions that don't stay +/// without a database. +pub fn use_dir(dir: Option) { + *HOST_DIR.write().unwrap_or_else(PoisonError::into_inner) = dir; + reload(); +} + +/// The database's files were replaced (a download put a new database in place): read it again, and photos whose +/// profile came from the old one are looked up again too ([`replacements`]). +pub fn replaced() { + REPLACED.fetch_add(1, Ordering::Relaxed); + reload(); +} + +/// Changes whenever the database's files were replaced ([`replaced`]); selecting a folder ([`use_dir`]) or reading +/// it again doesn't change it, so photos with a profile are not read again at every start. +pub fn replacements() -> u64 { + REPLACED.load(Ordering::Relaxed) +} + +/// The folder the host selected ([`use_dir`]), whatever `LIGHTCRAFT_LENSFUN_DIR` says. +pub fn host_dir() -> Option { + HOST_DIR.read().unwrap_or_else(PoisonError::into_inner).clone() +} + +/// Read the database again (after a download or an update): the next lookup sees the new data. +pub fn reload() { + // under the cache lock, so a load of the old files that finishes meanwhile can't be published ([`database`]) + let mut loaded = LOADED.write().unwrap_or_else(PoisonError::into_inner); + *loaded = None; + GENERATION.fetch_add(1, Ordering::Relaxed); +} + +/// Changes whenever the database in use may have changed. +pub fn generation() -> u64 { + GENERATION.load(Ordering::Relaxed) +} + +/// The folder the database is read from: `LIGHTCRAFT_LENSFUN_DIR`, else the host's ([`use_dir`]). +pub fn dir() -> Option { + source().map(|(d, _)| d) +} + +/// [`dir`], and whether it is the app's own downloaded folder (read only when whole, [`crate::lensfun_download::complete`]) +/// rather than the user's. +fn source() -> Option<(PathBuf, bool)> { + match std::env::var_os(ENV).filter(|v| !v.is_empty()) { + Some(d) => Some((PathBuf::from(d), false)), + None => HOST_DIR.read().unwrap_or_else(PoisonError::into_inner).clone().map(|d| (d, true)), + } +} + +/// The database in use, read once per folder (and again after [`reload`]); `None` when none is configured, the +/// folder is missing or it holds no lenses. +pub fn database() -> Option> { + let (dir, downloaded) = source()?; + if let Some((d, db)) = LOADED.read().unwrap_or_else(PoisonError::into_inner).as_ref() + && *d == dir + { + return db.clone(); + } + let generation = generation(); + // the app's own folder without its marker is a download that never finished: not read (the start fetches it) + let db = if downloaded && !crate::lensfun_download::complete(&dir) { + // info, not a warning: before the first download this is every user's state (logged once per reload) + log::info!("lens database: no finished download in {} yet; lens profiles are not applied", dir.display()); + None + } else { + load(&dir, downloaded) + }; + let mut loaded = LOADED.write().unwrap_or_else(PoisonError::into_inner); + // a reload while the files were read: they may be the old ones, so they aren't kept (the next call reads again) + if GENERATION.load(Ordering::Relaxed) == generation { + *loaded = Some((dir, db.clone())); + } + db +} + +fn load(dir: &Path, downloaded: bool) -> Option> { + let whose = if downloaded { "downloaded" } else { ENV }; + if !dir.is_dir() { + log::warn!("lens database: {} ({whose}) is missing or not a folder", dir.display()); + return None; + } + match LensDb::load_dir(dir) { + Ok((db, errors)) => { + for (file, e) in errors { + log::warn!("lens database: skipped {file}: {e}"); } + let (level, line) = summary(dir, whose, &db); + log::log!(level, "{line}"); + (!db.lenses.is_empty()).then(|| Arc::new(db)) } - }) - .as_ref() + Err(e) => { + log::warn!("{e}"); + None + } + } +} + +/// The log line for a database read from `dir`: where it is and how many lenses and cameras it has, so a user +/// setting up `LIGHTCRAFT_LENSFUN_DIR` can see whether it was found; a folder without lenses is a warning. +fn summary(dir: &Path, whose: &str, db: &LensDb) -> (log::Level, String) { + let (lenses, cameras) = (db.lenses.len(), db.cameras.len()); + if lenses == 0 { + ( + log::Level::Warn, + format!("lens database: no lenses in {} ({whose}): lenses 0, cameras {cameras}; lens profiles are not applied", dir.display()), + ) + } else { + (log::Level::Info, format!("lens database: read {} ({whose}): lenses {lenses}, cameras {cameras}", dir.display())) + } +} + +/// The database's name for the lens a photo's file calls `lens` (taken with `camera`, the make and model as the +/// library shows them): "Canon EF 70-200mm f/2.8L IS II USM". `None` without a database or a match. +pub fn profile_name(db: &LensDb, camera: &str, lens: &str) -> Option { + let cam = camera.split_once(' ').and_then(|(make, model)| db.find_camera(make, model).or_else(|| db.find_camera(make, camera))); + let p = db.find_lens(None, lens, cam)?; + let model = p.models.first()?; + Some(if model.to_lowercase().starts_with(&p.maker.to_lowercase()) || p.maker.is_empty() { model.clone() } else { format!("{} {model}", p.maker) }) } /// The database profile for a photo with metadata `m`, for its `w × h` (unoriented, default-cropped) image, @@ -49,10 +164,10 @@ pub fn lookup(db: &LensDb, m: &lightcraft_meta::Metadata, w: f64, h: f64, orient db.find_lens_named(m.lens_make.as_deref(), &name, camera)? } }; - let crop = frame_crop_factor(camera.map(|c| c.crop_factor), focal, m.focal_length_35mm); + let crop = frame_crop_factor(camera.and_then(|c| c.crop_factor), focal, m.focal_length_35mm); let shot = Shot { focal, aperture: m.f_number, distance: None, crop_factor: crop, width: w, height: h }; let corr = lens.correction(&shot)?; - Some(lightcraft_pipeline::optics::reorient_lens(&corr, orientation, w, h)) + Some(EmbeddedLens { source: LensSource::Database, ..lightcraft_pipeline::optics::reorient_lens(&corr, orientation, w, h) }) } /// The crop factor of the recorded frame, which scales the profile's radii: the body's (`camera`), else what the @@ -73,7 +188,7 @@ pub fn for_raw(raw: &lightcraft_raw::RawInfo, meta: impl FnOnce() -> lightcraft_ crate::files::embedded_lens(raw).or_else(|| { let db = database()?; let (w, h) = raw.developed_size(); - lookup(db, &meta(), w as f64, h as f64, raw.orientation) + lookup(&db, &meta(), w as f64, h as f64, raw.orientation) }) } @@ -102,11 +217,26 @@ mod tests { } } + /// The log says where the database was read from and what it holds, and warns when it holds no lenses (#2511). + #[test] + fn the_log_names_the_folder_and_what_it_holds() { + let dir = Path::new("/lensfun/db"); + let (level, line) = summary(dir, ENV, &LensDb::parse(DB).unwrap()); + assert_eq!(level, log::Level::Info); + assert!(line.contains("lenses 1, cameras 1") && line.contains("/lensfun/db") && line.contains(ENV), "{line}"); + let (level, line) = summary(dir, "downloaded", &LensDb::parse("").unwrap()); + assert_eq!(level, log::Level::Warn); + assert!(line.contains("no lenses") && line.contains("downloaded") && line.contains("lenses 0, cameras"), "{line}"); + } + #[test] fn exif_lens_is_found_and_converted() { let db = LensDb::parse(DB).unwrap(); let lens = lookup(&db, &meta(), 6000.0, 4000.0, Orientation::Normal).unwrap(); assert!(lens.warp.is_some() && lens.vignette.is_some()); + assert_eq!(lens.source, LensSource::Database, "the Optics panel says where it came from"); + assert_eq!(profile_name(&db, "Testcam TC-1", "18-55mm F3.5-5.6").as_deref(), Some("Testcam 18-55mm f/3.5-5.6")); + assert_eq!(profile_name(&db, "Testcam TC-1", "70-200mm F4"), None); let rotated = lookup(&db, &meta(), 6000.0, 4000.0, Orientation::Rotate90).unwrap(); assert_eq!(rotated.warp.unwrap().center, lightcraft_geom::Point::new(0.5, 0.5)); // no lens name, no focal length, an unknown lens: nothing @@ -164,7 +294,7 @@ mod tests { }; let at = |crop: f64, w: f64, h: f64| { let shot = Shot { focal: 70.0, aperture: Some(2.8), distance: None, crop_factor: Some(crop), width: w, height: h }; - db.lenses[0].correction(&shot).unwrap() + EmbeddedLens { source: LensSource::Database, ..db.lenses[0].correction(&shot).unwrap() } }; let aps_c = lookup(&db, &m(Some(105.0)), 5616.0, 3744.0, Orientation::Normal).unwrap(); assert_eq!(aps_c, at(1.5, 5616.0, 3744.0)); @@ -177,6 +307,34 @@ mod tests { assert_eq!(frame_crop_factor(Some(1.0), 0.0, Some(105.0)), Some(1.0), "a hostile focal length is ignored"); } + #[test] + fn unknown_camera_crop_uses_exif_equivalent_without_full_frame_assumption() { + for crop in [ + "", + "", + "bad", + "NaN", + "inf", + "0.049", + "21", + ] { + let xml = DB.replacen("1.5", crop, 1).replace("-0.03", "-0.003").replace("-0.4", "-0.04"); + let db = LensDb::parse(&xml).unwrap(); + // A below-1 crop exposes the old synthetic 1.0 body: the 10% crop-mode policy would keep it. + let m = lightcraft_meta::Metadata { focal_length_35mm: Some(17.1), ..meta() }; + let expected = db.lenses[0] + .correction(&Shot { focal: 18.0, aperture: Some(3.5), distance: None, crop_factor: Some(17.1 / 18.0), width: 6000.0, height: 4000.0 }) + .map(|lens| EmbeddedLens { source: LensSource::Database, ..lens }) + .unwrap(); + assert_eq!(lookup(&db, &m, 6000.0, 4000.0, Orientation::Normal).unwrap(), expected, "{crop}"); + let fallback = db.lenses[0] + .correction(&Shot { focal: 18.0, aperture: Some(3.5), distance: None, crop_factor: None, width: 6000.0, height: 4000.0 }) + .map(|lens| EmbeddedLens { source: LensSource::Database, ..lens }) + .unwrap(); + assert_eq!(lookup(&db, &meta(), 6000.0, 4000.0, Orientation::Normal).unwrap(), fallback, "no equivalent: {crop}"); + } + } + /// A synthetic grid recorded through the profile's barrel distortion comes out of the pipeline's geometry /// stage with straight lines. #[test] diff --git a/crates/engine/src/lensfun_download.rs b/crates/engine/src/lensfun_download.rs new file mode 100644 index 0000000000..c24b07f7a9 --- /dev/null +++ b/crates/engine/src/lensfun_download.rs @@ -0,0 +1,837 @@ +//! The lensfun lens database, downloaded on request: the desktop app offers it once on the first launch +//! ([`fetch_on_start`]: nothing is fetched without the user's click). +//! +//! lensfun's `data/db` (CC BY-SA 3.0, ) is data, never bundled with LightCraft and +//! never committed to its repository: the desktop app fetches it at run time, when the user chooses Download, into its data folder +//! ([`default_dir`]), with a row in the activity stack, and [`crate::lens_profiles`] reads it from there. The files are +//! pinned to one lensfun commit ([`COMMIT`]) by name, size and SHA-256 ([`FILES`]), so whatever mirror serves them +//! ([`URL_ENV`] lists others, e.g. a copy on LightCraft's own server), what arrives is exactly that commit's data or +//! it is thrown away. A new pin in a later build replaces the folder's files once ([`installed`] compares the pin). +//! +//! The transfer is [`lightcraft_fetch`] (pure-Rust HTTPS, resume, size and hash checks) on a background thread; the +//! files land in a staging folder beside the database folder, the marker is written there last, and only then does the +//! staged folder replace the database folder as a whole ([`publish`]): the previous complete database stays in use +//! until the new one is in place, and comes back if the swap fails. The loader reads the app's folder only when it has +//! the marker ([`complete`]), and [`installed`] also checks every pinned file is there, so a damaged folder is +//! downloaded again. Failure is a message, never a panic. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; + +use crate::activity::{Activity, Cancel, TaskHandle, Unit}; + +/// The lensfun commit the files are pinned to (2026-10-08). +pub const COMMIT: &str = "43f9e001ab66c4fcdd4f400463f13b72f94b2288"; +/// Where the files are fetched from by default: lensfun's repository at [`COMMIT`]. +pub const DEFAULT_MIRROR: &str = "https://raw.githubusercontent.com/lensfun/lensfun/43f9e001ab66c4fcdd4f400463f13b72f94b2288/data/db"; +/// Other places to fetch the same files from, tried first (base URLs separated by commas or spaces). +pub const URL_ENV: &str = "LIGHTCRAFT_LENSFUN_URL"; +/// The file written once every database file is in place: the pin it holds says which data the folder has. +pub const MARKER: &str = "SOURCE.txt"; +/// The suffix of the folder beside the database folder where files wait until all have arrived. +#[cfg(not(target_arch = "wasm32"))] +const STAGING: &str = "download"; +/// The suffix of the folder the previous database is moved to while the new one takes its place. +const PREVIOUS: &str = "previous"; +/// The suffix of the file that says a download into the folder is under way (another window or session of the +/// app may be the one downloading). +#[cfg(not(target_arch = "wasm32"))] +const LOCK: &str = "lock"; +/// Largest database file accepted (the biggest is under 1 MB). +#[cfg(not(target_arch = "wasm32"))] +const MAX_FILE: u64 = 8 << 20; + +/// The database files at [`COMMIT`]: name, size in bytes, SHA-256. +pub const FILES: &[(&str, u64, &str)] = &[ + ("6x6.xml", 29550, "ca13c2756b32d728675372695c072517a0e38af5eff2ecd3e17599dee7fc58b3"), + ("actioncams.xml", 17188, "79a5da0322574b95690464444c9d9ba1da0e1f827da44fd6bff120a0ec10e4b4"), + ("compact-canon.xml", 247046, "bae47e4b3a0f8852641038ae2dcca5b28ed7965e65ca795fd676f9de857c4670"), + ("compact-casio.xml", 6889, "ab35433879c4574ef8f97cd4e3d114d7ff8db4e7279da9d502fc9e911b51ee27"), + ("compact-fujifilm.xml", 67954, "58af9ebef2410c428ae2c5d01003d2247330d47d918823e63522b4d897a997d1"), + ("compact-kodak.xml", 2091, "377018ccd74f58e966b37a11e5a8689be4268153bebece9f1f2a0dbfa8234845"), + ("compact-konica-minolta.xml", 13349, "832a7473951ab625e10c48af6cf60f89b57280016d45729e2584cf9e41ad3cc7"), + ("compact-leica.xml", 9113, "8e4676679377576dc19e7900ce86fc69b0248ea1d4538aa22ee1ee09431a3be3"), + ("compact-nikon.xml", 40003, "5393bdb8223e13d21b85818e96571e97c035470b49b0452dfcedc2e1ff512d3b"), + ("compact-olympus.xml", 34454, "7637d469ad54a02ebce9492a9aa9424a2ff1ec07b0398158076f762fdc08389b"), + ("compact-panasonic.xml", 70621, "f191fc2a5d49fb50c06f4c399ee8c1a83a05f93a0efaecd352ec5c1479b8e60b"), + ("compact-pentax.xml", 6689, "596fae3edaadcf2d90ae930fc1bec42597ca0b2bd11842e686e1b915f3736390"), + ("compact-ricoh.xml", 18424, "46df96ebc367d5170cb6b7dfc3742093f0ad946264518fc5488573ba052f29d7"), + ("compact-samsung.xml", 13875, "36e3a778046d56385c387d48474cd32a89a5da94d99e640b5ce716ce747f898d"), + ("compact-sigma.xml", 2395, "0ddc265e3e580da05dcd4664d1b9c2464838d74dd02519c826520950c8f1759e"), + ("compact-sony.xml", 126229, "be146388b4f6f7bf0d73394e20386ce6ccef3559ab39f1268ba3c14aaef03207"), + ("contax.xml", 1696, "5eba12e6fd4913470afb6fe25fee47a263084b6cec830297273909872f47669a"), + ("generic.xml", 5416, "cd572d4110981546b2c4cd296c2ff16755b30063fa136d8b06ad2ca13ab4c59f"), + ("mil-canon.xml", 247994, "2de8e9467a6af6f83cc9da834d3d3b94d1aaf54519f60c68ac6bc02780a77516"), + ("mil-fujifilm.xml", 210586, "64586336153b948fe2325f6c46679149a4e3c114a70bee4bd1de88721cb4de72"), + ("mil-hasselblad.xml", 1048, "13e1fa55d36c2ed7d22964c21ce6c21d887bfe4506e840e425da1ce4157c3756"), + ("mil-leica.xml", 11663, "c691037e2e0743388473c2a0545e340462c412b7e3b57e451f4f9c89dde2388a"), + ("mil-nikon.xml", 178941, "dcae5ec2e505411a7f00b6b8dd03825e55620403b558b156be15e9ddfbeaf159"), + ("mil-olympus.xml", 147123, "989a3d88ef07a286efc2755df214792fdf71d60366932a1b369a77ad39cf2abb"), + ("mil-panasonic.xml", 299264, "eb5f01f33e65721f3900786d5970c7e220dd042aaa56968be33c009a358ff3c5"), + ("mil-pentax.xml", 1385, "675a94f52794868ad9f1d79e17b7128783c34b3db23e9eac346c5963812a16e5"), + ("mil-samsung.xml", 13007, "10130e9e125e0882a16fd3033cfed0175e9c14cb7d35e630cdb94736f27e5dc3"), + ("mil-samyang.xml", 25990, "ae3bf262f12facdc6f81b837cf6d36fdde2a930d2bfb0918d5abaa47fcfea3ab"), + ("mil-sigma.xml", 126080, "5f39b232efba5c208e5a98d8afe92cb2eee879213322d47827fcc6f0dc3a06f9"), + ("mil-sony.xml", 274541, "f9f7e5d7461ac58f76eb55dcc5b211f2e9a451402ddb4a9ecb12d1e4dc04f2b8"), + ("mil-tamron.xml", 106950, "2f0c9c4dfb9b0419ba0fac2e618bc251c2e71e068b6e09a23d7994b0ff62db0a"), + ("mil-tokina.xml", 1014, "addb27bd82b0d729644b9da1342f92401f63cc5945309ed17f38f4b7af1649e3"), + ("mil-zeiss.xml", 19171, "ef8a238904fc9ea6fdb6171863dfd70cd94814af19ecd8c31ee000ca1864589d"), + ("misc.xml", 176039, "2000a347d9dc37d908ea5b56c760de5b2b4ab475857959ae2e901c31339b01bb"), + ("om-system.xml", 35344, "a53a627e6ba79fbabb0fa7552ce2b6e56e206425d2eaf0e8ccdb6b8c40c20755"), + ("rf-leica.xml", 6712, "f93636e1980ad308d1873cc3ac078cdc77c0d529d777cd45c5c8d0e4781981e3"), + ("slr-canon.xml", 780353, "5244e6df8f2522f829c57e2073313ce31a624e9ed9605310fe43613b9d588c99"), + ("slr-hasselblad.xml", 642, "97602c467699904bf101179ea2fa24f05f3e1879250498a6ba306cd95a3b7a6b"), + ("slr-konica-minolta.xml", 47170, "5639ca94f121f609247c2c120b65830b3ef7784db6ecfa7e8eb3d29ff5046c1b"), + ("slr-leica.xml", 432, "c5e74cb511712e99ed60a066e85c842fea58f693c5039c3819485619f5293d0e"), + ("slr-nikon.xml", 550157, "5e591e8b1032203cce4c822f1da3d49524a78e7d71c594ea5a4533f2e57aacdf"), + ("slr-olympus.xml", 116602, "f7693b6779edd8ed10d7dc23113669255bfa4987cea7db0e843f7f5f2bbbe615"), + ("slr-panasonic.xml", 419, "cd79acb49d9ce5f2a4cecc572b3e117f03da380bed2dcbfd52327192d8ce2381"), + ("slr-pentax.xml", 209552, "2fba773e41a1cfb70f0c85efdab6d78944bf80ddf89bc2035ef6db39da352f29"), + ("slr-ricoh.xml", 2869, "c835798136a53535fdf4f81312ac9aad0ea3de3ef732c183d8cc4d2f432011d9"), + ("slr-samsung.xml", 1110, "dc0a29e424ff96e4316ddeb76126fa6f6c73a8836905a3e1f56f0c493826148f"), + ("slr-samyang.xml", 16811, "fb1585bea91f5f59e1fae8811dd76c92252ee5d52e3647df2aff4695048443b5"), + ("slr-schneider.xml", 5890, "de607cfe4ba6e7debc61e282ce39b72825c07601572e14af2bc9108ba67faf81"), + ("slr-sigma.xml", 444640, "f55f41c144fbb72e3c51d2dfef40e918930d37db1b4150bd02bd746406c036d2"), + ("slr-soligor.xml", 573, "1aba0aab19bce87ea86175b6551cb5306a512eb54be1698b89991b86008f6a04"), + ("slr-sony.xml", 88865, "e5ca7f532afe23ff380bf2f9e5458f687bed603355d73a254d85c4e692942fdc"), + ("slr-tamron.xml", 201992, "c62090789cebe6bbb663111c6e97beeb1111852bb735088e29cf8782df4bab45"), + ("slr-tokina.xml", 91977, "b1213eda81a613bc3976340398c6b8ce8b7dc29423476fc565d5f8e5cf612ecf"), + ("slr-ussr.xml", 19024, "1fd6acc8a8f40373379bea2899ffd96fc34b22d9b044d0474dabd4c89af44efb"), + ("slr-vivitar.xml", 2157, "c5c67e3fe38e8fa19044acadc7730047690435f66aac563f55ffe04997a88111"), + ("slr-zeiss.xml", 14957, "49aa211a41fd5fe391d26af5fa65bdf9428d60863ffff15d3916fa1c520dc101"), +]; + +/// The app's own copy of the database: `/lensfun`. +pub fn default_dir() -> Option { + crate::config::config_dir().map(|d| d.join("lensfun")) +} + +/// The folder holds the pinned data: [`MARKER`] names [`COMMIT`] and every pinned file is there at its pinned size +/// (a folder whose files went missing is downloaded again). +pub fn installed(dir: &Path) -> bool { + installed_with(dir, FILES) +} + +fn installed_with(dir: &Path, files: &[Pin]) -> bool { + std::fs::read_to_string(dir.join(MARKER)).is_ok_and(|s| s.contains(COMMIT)) + && files.iter().all(|(name, size, _)| std::fs::metadata(dir.join(name)).is_ok_and(|m| m.is_file() && m.len() == *size)) +} + +/// The folder holds a whole database, of this pin or an older one: its [`MARKER`], written last, is there. The app's +/// own folder is read only then ([`crate::lens_profiles::database`]). +pub fn complete(dir: &Path) -> bool { + dir.join(MARKER).is_file() +} + +/// `dir` with `suffix` added to its name: a folder beside it (`lensfun` → `lensfun.download`). +fn beside(dir: &Path, suffix: &str) -> PathBuf { + let mut name = dir.file_name().map(|n| n.to_os_string()).unwrap_or_default(); + name.push(format!(".{suffix}")); + dir.with_file_name(name) +} + +/// Put back the previous database when a swap ([`publish`]) was interrupted between its two moves (the app quit or +/// the machine stopped): `dir` is missing and the previous folder is whole. Best effort; says why it couldn't. Done +/// under the folder's download lock (`DirLock`) and skipped while a download, in this or another LightCraft, holds +/// it: that download is between its own two moves, not interrupted, and puts the folder right itself. +pub fn recover(dir: &Path) { + if !needs_recovery(dir) { + return; + } + #[cfg(not(target_arch = "wasm32"))] + let _lock = match DirLock::take(dir) { + Ok(lock) => lock, + Err(e) => { + log::warn!("lens database: the previous database is not put back now: {e}"); + return; + } + }; + recover_locked(dir); +} + +/// What a swap interrupted between its two moves leaves: no database folder, and a whole previous one. +fn needs_recovery(dir: &Path) -> bool { + !dir.exists() && complete(&beside(dir, PREVIOUS)) +} + +/// [`recover`] by a caller that already holds the folder's lock (a download). +fn recover_locked(dir: &Path) { + if needs_recovery(dir) + && let Err(e) = std::fs::rename(beside(dir, PREVIOUS), dir) + { + log::warn!("lens database: could not put back the previous database: {e}"); + } +} + +/// The user's answer to the first-launch offer of the database (the desktop app keeps it in its settings). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Offer { + /// Not asked yet: the first start asks. + #[default] + Ask, + /// Download was clicked (in the offer or in Settings): a start downloads the pinned database when it is missing + /// or from an older pin (an interrupted or failed download is tried again). + Accepted, + /// Not Now: nothing is downloaded and the start doesn't ask again (Settings can download it, or turn the offer + /// back on). + Declined, +} + +/// What a start does about the database ([`fetch_on_start`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Start { + Nothing, + /// Ask the user (once): download into this folder, or not now. + Ask(PathBuf), + /// Download into this folder (the user said yes before). + Fetch(PathBuf), +} + +/// The first-start policy, in one place: what a start does about the database. Nothing touches the network +/// without the user's click: the host must allow the question at all (`auto`, [`crate::Session::lens_auto_download`], +/// the desktop app only), a folder of the user's own (`LIGHTCRAFT_LENSFUN_DIR`) is never replaced, an installed +/// database needs nothing, and otherwise the user's answer (`offer`) decides: ask, download, or nothing. +pub fn fetch_on_start(auto: bool, offer: Offer) -> Start { + let own = std::env::var_os(crate::lens_profiles::ENV).is_some_and(|v| !v.is_empty()); + let dir = default_dir(); + if let Some(d) = dir.as_deref().filter(|_| auto && !own) { + recover(d); + } + let installed = dir.as_deref().is_some_and(installed); + decide(auto, own, dir, installed, offer) +} + +/// [`fetch_on_start`] without the file system: `own` (`LIGHTCRAFT_LENSFUN_DIR` is set), the app's folder `dir` and +/// whether it holds the pinned data. +pub fn decide(auto: bool, own: bool, dir: Option, installed: bool, offer: Offer) -> Start { + let Some(dir) = dir.filter(|_| auto && !own && !installed) else { return Start::Nothing }; + match offer { + Offer::Ask => Start::Ask(dir), + Offer::Accepted => Start::Fetch(dir), + Offer::Declined => Start::Nothing, + } +} + +/// The download's size in bytes: the pinned files' sizes added up (what the offer says). +pub fn download_size() -> u64 { + FILES.iter().map(|f| f.1).fold(0u64, u64::saturating_add) +} + +/// [`download_size`] in whole megabytes for people ("about 5 MB"), never 0. +pub fn download_megabytes() -> u64 { + (download_size().saturating_add(500_000) / 1_000_000).max(1) +} + +/// The mirrors to try, in order: [`URL_ENV`]'s, then lensfun's own ([`DEFAULT_MIRROR`]). +pub fn mirrors() -> Vec { + #[cfg(not(target_arch = "wasm32"))] + { + lightcraft_fetch::mirrors(std::env::var(URL_ENV).ok().as_deref(), None, &[DEFAULT_MIRROR]) + } + #[cfg(target_arch = "wasm32")] + { + Vec::new() + } +} + +/// Where the download stands. +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub enum State { + /// Not started this session. + #[default] + Idle, + Running { + bytes: u64, + total: u64, + }, + /// In place and loaded: `files` database files. + Done { + files: usize, + }, + Failed(String), + Cancelled, +} + +struct Shared { + state: Mutex, + cancel: Arc, + task: Option, +} + +impl Shared { + fn set(&self, s: State) { + if let (State::Running { bytes, total }, Some(task)) = (&s, &self.task) { + task.progress(*bytes, *total); + } + *self.state.lock().unwrap_or_else(PoisonError::into_inner) = s; + } + + fn get(&self) -> State { + self.state.lock().unwrap_or_else(PoisonError::into_inner).clone() + } +} + +/// The session's lens database download. +#[derive(Default)] +pub struct Download { + job: Option>, +} + +/// One pinned file: name, size in bytes, SHA-256. +pub type Pin = (&'static str, u64, &'static str); + +impl Download { + pub fn state(&self) -> State { + self.job.as_ref().map_or(State::Idle, |j| j.get()) + } + + pub fn running(&self) -> bool { + matches!(self.state(), State::Running { .. }) + } + + /// Fetch `files` from `mirrors` into `dir` on a background thread, shown in the activity stack until it ends + /// (its ✕ stops it). Started once at a time; when it ends the database is read again + /// ([`crate::lens_profiles::replaced`]). + pub fn start(&mut self, dir: &Path, mirrors: Vec, files: &'static [Pin], activity: &Activity) -> Result<(), String> { + if self.running() { + return Err("the lens database is already downloading".into()); + } + if mirrors.is_empty() { + return Err("no download location is configured for the lens database".into()); + } + let cancel = Arc::new(AtomicBool::new(false)); + let task = activity.start("download", "Downloading the lens database", Cancel::Flag(cancel.clone())); + task.set_unit(Unit::Bytes); + task.detail("lensfun (CC BY-SA 3.0)"); + let total = files.iter().map(|f| f.1).fold(0u64, u64::saturating_add); + task.progress(0, total); + let shared = Arc::new(Shared { state: Mutex::new(State::Running { bytes: 0, total }), cancel, task: Some(task.handle()) }); + let worker = shared.clone(); + let dir = dir.to_path_buf(); + std::thread::Builder::new() + .name("lens-database-download".into()) + .spawn(move || { + // the row goes when the thread ends, however it ends + let _task = task; + let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(&dir, &mirrors, files, &worker))); + if outcome.is_err() { + worker.set(State::Failed("the lens database download stopped unexpectedly".into())); + } + }) + .map_err(|e| format!("could not start the lens database download: {e}"))?; + self.job = Some(shared); + Ok(()) + } +} + +impl Drop for Download { + /// Quitting while it runs stops it (the staged files stay for the next try to resume). + fn drop(&mut self) { + if let Some(j) = &self.job { + j.cancel.store(true, Ordering::Relaxed); + } + } +} + +/// The whole job: fetch and check every file into the staging folder, then move them into `dir`, write the marker +/// and read the database again. Always ends in a final [`State`]. +fn run(dir: &Path, mirrors: &[String], files: &[Pin], shared: &Shared) { + match fetch_all(dir, mirrors, files, shared) { + Ok(n) => { + crate::lens_profiles::replaced(); + shared.set(State::Done { files: n }); + } + Err(e) if shared.cancel.load(Ordering::Relaxed) => { + log::info!("lens database download stopped: {e}"); + shared.set(State::Cancelled); + } + Err(e) => { + log::warn!("lens database download: {e}"); + shared.set(State::Failed(e)); + } + } +} + +/// Held while one download (or a [`recover`]) uses a folder's staging and previous folders, across sessions and +/// processes: an exclusive operating-system lock on a file beside the folder (`File::try_lock`: `flock` on Unix, +/// `LockFileEx` on Windows), held by the open file. The system lets go of it when the file closes, on drop or when the +/// process ends however it ends, so an app that crashed never leaves the folder locked and no age guess is needed. +/// The file itself stays (empty): removing it would let a second app lock a new file of the same name while the first +/// still holds the old one. Dropping it unlocks explicitly: a process another thread is spawning holds a copy of the +/// file until it execs, and on Unix the lock would last as long as that copy. +#[cfg(not(target_arch = "wasm32"))] +struct DirLock { + file: std::fs::File, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for DirLock { + fn drop(&mut self) { + let _ = self.file.unlock(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl DirLock { + fn take(dir: &Path) -> Result { + let path = beside(dir, LOCK); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|e| format!("could not create {}: {e}", parent.display()))?; + } + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(&path) + .map_err(|e| format!("could not create {}: {e}", path.display()))?; + match file.try_lock() { + Ok(()) => Ok(DirLock { file }), + Err(std::fs::TryLockError::WouldBlock) => Err("the lens database is already downloading (in another LightCraft window)".into()), + Err(std::fs::TryLockError::Error(e)) => Err(format!("could not lock {}: {e}", path.display())), + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn fetch_all(dir: &Path, mirrors: &[String], files: &[Pin], shared: &Shared) -> Result { + // (from before the recovery through the swap: another download of this folder would move the same folders) + let _lock = DirLock::take(dir)?; + recover_locked(dir); + let staging = beside(dir, STAGING); + std::fs::create_dir_all(&staging).map_err(|e| format!("could not create {}: {e}", staging.display()))?; + let specs: Vec> = + files.iter().map(|(name, size, sha)| lightcraft_fetch::FileSpec { name, size: Some(*size), sha256: Some(sha), max: MAX_FILE }).collect(); + let total = files.iter().map(|f| f.1).fold(0u64, u64::saturating_add); + lightcraft_fetch::download(&specs, mirrors, &staging, &lightcraft_fetch::Options::default(), &shared.cancel, &mut |p| { + shared.set(State::Running { bytes: p.done.min(total), total }); + }) + .map_err(|e| match e { + lightcraft_fetch::DownloadError::AllMirrorsFailed { errors, .. } => { + let detail: String = errors.join("; ").chars().take(300).collect(); + format!("could not download the lens database ({detail}): check the internet connection; LightCraft tries again next time it starts") + } + other => other.to_string(), + })?; + // every file is here and checked. The staged folder becomes the database: first without database files another + // pin left in it (a resumed older attempt), then with the marker, written last, then in place of the old folder + // as a whole + remove_stale(&staging, files, |p| std::fs::remove_file(p))?; + let readme = format!( + "lensfun lens database (data/db), commit {COMMIT} +from https://github.com/lensfun/lensfun, downloaded by LightCraft. + Licence: Creative Commons Attribution-ShareAlike 3.0 (https://creativecommons.org/licenses/by-sa/3.0/), by the lensfun contributors. + Data only, read by LightCraft at run time; not part of LightCraft. +" + ); + std::fs::write(staging.join(MARKER), readme).map_err(|e| format!("could not write {}: {e}", staging.join(MARKER).display()))?; + publish(&staging, dir, |from, to| std::fs::rename(from, to))?; + Ok(files.len()) +} + +/// Replace the database folder `dir` with the complete `staged` one, moving with `rename`: the old folder is moved +/// aside, the staged one takes its place, and the old one is removed. When the second move fails the old folder is +/// put back, so `dir` is always either the previous complete database or the new one, never a mix. +#[cfg(not(target_arch = "wasm32"))] +fn publish(staged: &Path, dir: &Path, rename: impl Fn(&Path, &Path) -> std::io::Result<()>) -> Result<(), String> { + let previous = beside(dir, PREVIOUS); + let had = dir.exists(); + // left by a swap that ended after its second move: `dir` is the database, so this copy can go. Without `dir` + // (a recovery that couldn't put it back) it may be the only whole database: kept until the new one is in place + if had && previous.exists() { + std::fs::remove_dir_all(&previous).map_err(|e| format!("could not remove {}: {e}", previous.display()))?; + } + if had { + rename(dir, &previous).map_err(|e| format!("could not move the old lens database aside ({}): {e}", dir.display()))?; + } + if let Err(e) = rename(staged, dir) { + if had && let Err(back) = rename(&previous, dir) { + // (the next start puts it back: [`recover`]) + log::warn!("lens database: could not put back the previous database yet: {back}"); + } + return Err(format!("could not move the new lens database into {}: {e}", dir.display())); + } + if previous.exists() + && let Err(e) = std::fs::remove_dir_all(&previous) + { + log::warn!("lens database: could not remove the previous database {}: {e}", previous.display()); + } + Ok(()) +} + +/// Remove the XML files in `dir` that are not among `files` (nothing else in the folder is touched) with `remove`: an +/// error names the first that could not be removed, or why the folder could not be listed. +#[cfg(not(target_arch = "wasm32"))] +fn remove_stale(dir: &Path, files: &[Pin], remove: impl Fn(&Path) -> std::io::Result<()>) -> Result<(), String> { + // a folder that can't be listed (or an entry that can't be read) may still hold an old file: an error, not success + let listing = |e: std::io::Error| format!("could not list the lens database folder {}: {e}", dir.display()); + for entry in std::fs::read_dir(dir).map_err(listing)? { + let entry = entry.map_err(listing)?; + let name = entry.file_name(); + let name = name.to_string_lossy(); + let xml = std::path::Path::new(&*name).extension().is_some_and(|e| e.eq_ignore_ascii_case("xml")); + if xml + && entry.path().is_file() + && !files.iter().any(|(pinned, _, _)| *pinned == name) + && let Err(e) = remove(&entry.path()) + { + return Err(format!("could not remove the old lens database file {name}: {e}")); + } + } + Ok(()) +} + +#[cfg(target_arch = "wasm32")] +fn fetch_all(_: &Path, _: &[String], _: &[Pin], _: &Shared) -> Result { + Err("the web build downloads no lens database".into()) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use std::io::{BufRead, BufReader, Write}; + use std::net::TcpListener; + use std::time::Duration; + + /// Two downloads into one folder (two windows, or two sessions of one app) never share its staging and previous + /// folders: the second is refused while the first holds the folder, however old the first's lock file is, and + /// may go once it ends; the file an app that quit mid-download leaves holds nothing (the system let go of it). + #[test] + fn one_download_at_a_time_holds_a_folder() { + let d = scratch("lock"); + let _ = std::fs::remove_file(beside(&d, LOCK)); + let first = DirLock::take(&d).unwrap(); + // (a download running for a week on a slow line: its lock file is old, and it still holds the folder) + let old = std::time::SystemTime::now() - Duration::from_secs(7 * 24 * 60 * 60); + std::fs::OpenOptions::new().write(true).open(beside(&d, LOCK)).unwrap().set_modified(old).unwrap(); + for _ in 0..3 { + let second = DirLock::take(&d); + assert!(second.as_ref().is_err_and(|e| e.contains("already downloading")), "{:?}", second.as_ref().err()); + } + drop(first); + drop(DirLock::take(&d).unwrap()); + // (what an app that quit mid-download leaves: the file, unlocked) + assert!(beside(&d, LOCK).exists()); + drop(DirLock::take(&d).unwrap()); + let _ = std::fs::remove_file(beside(&d, LOCK)); + } + + /// The start's recovery moves nothing while a download holds the folder: between that download's two moves the + /// folder is missing and the previous one whole, which is not an interrupted swap. + #[test] + fn recovery_leaves_a_folder_a_download_holds() { + let dir = scratch("recover-locked"); + std::fs::remove_dir_all(&dir).unwrap(); + let previous = beside(&dir, PREVIOUS); + std::fs::create_dir_all(&previous).unwrap(); + std::fs::write(previous.join(MARKER), "older").unwrap(); + let held = DirLock::take(&dir).unwrap(); + recover(&dir); + assert!(!dir.exists() && complete(&previous), "a download's swap is left alone"); + drop(held); + recover(&dir); + assert!(complete(&dir) && !previous.exists(), "an interrupted swap is put back"); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_file(beside(&dir, LOCK)); + } + + /// The lock holds across processes: while another process (another LightCraft) holds the folder, a download + /// here is refused; once that process is gone (killed, like a crash), the system has let go and it may start. + #[test] + fn another_process_holding_the_folder_refuses_a_download_here() { + let dir = scratch("lock-child"); + let ready = dir.join("child-locked"); + let exe = std::env::current_exe().unwrap(); + let mut child = std::process::Command::new(exe) + .args(["--exact", "lensfun_download::tests::lock_holder_child", "--ignored", "--test-threads=1"]) + .env("LC_LENSFUN_LOCK_CHILD_DIR", &dir) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .unwrap(); + let deadline = std::time::Instant::now() + Duration::from_secs(60); + while !ready.exists() { + assert!(child.try_wait().unwrap().is_none(), "the child exited before locking"); + assert!(std::time::Instant::now() < deadline, "the child never locked"); + std::thread::sleep(Duration::from_millis(20)); + } + let here = DirLock::take(&dir); + let refused = here.as_ref().is_err_and(|e| e.contains("already downloading")); + child.kill().unwrap(); + child.wait().unwrap(); + assert!(refused, "{:?}", here.as_ref().err()); + drop(DirLock::take(&dir).expect("the system let go of the dead process's lock")); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_file(beside(&dir, LOCK)); + } + + /// Run by [`another_process_holding_the_folder_refuses_a_download_here`] in a child process: take the folder's + /// lock, say so, and wait to be killed. + #[test] + #[ignore = "helper process for another_process_holding_the_folder_refuses_a_download_here"] + fn lock_holder_child() { + let Some(dir) = std::env::var_os("LC_LENSFUN_LOCK_CHILD_DIR") else { return }; + let dir = PathBuf::from(dir); + let _held = DirLock::take(&dir).unwrap(); + std::fs::write(dir.join("child-locked"), b"").unwrap(); + std::thread::sleep(Duration::from_secs(120)); + } + + /// A swap into a folder that is missing, with the previous database still beside it (a recovery that couldn't + /// put it back), keeps that previous database until the new one is in place: when the new one can't be moved + /// in, the previous one is still there for the next start to put back. + #[test] + fn a_failed_swap_keeps_the_only_whole_database() { + let dir = scratch("keep-previous"); + std::fs::remove_dir_all(&dir).unwrap(); + let previous = beside(&dir, PREVIOUS); + std::fs::create_dir_all(&previous).unwrap(); + std::fs::write(previous.join(MARKER), "older").unwrap(); + let staged = beside(&dir, STAGING); + std::fs::create_dir_all(&staged).unwrap(); + std::fs::write(staged.join(MARKER), COMMIT).unwrap(); + let err = publish(&staged, &dir, |_, _| Err(std::io::Error::other("in use"))).unwrap_err(); + assert!(err.contains("in use"), "{err}"); + assert!(complete(&previous), "the previous database is kept"); + recover(&dir); + assert_eq!(std::fs::read_to_string(dir.join(MARKER)).unwrap(), "older", "and the next start puts it back"); + // a swap that works into a missing folder removes the previous copy once the new one is in place + std::fs::remove_dir_all(&dir).unwrap(); + std::fs::create_dir_all(&previous).unwrap(); + std::fs::write(previous.join(MARKER), "older").unwrap(); + publish(&staged, &dir, |from, to| std::fs::rename(from, to)).unwrap(); + assert_eq!(std::fs::read_to_string(dir.join(MARKER)).unwrap(), COMMIT); + assert!(!previous.exists()); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_file(beside(&dir, LOCK)); + } + + fn scratch(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lc-lensfun-{name}-{}", std::process::id())); + for leftover in [d.clone(), beside(&d, STAGING), beside(&d, PREVIOUS)] { + let _ = std::fs::remove_dir_all(leftover); + } + std::fs::create_dir_all(&d).unwrap(); + d + } + + /// A local server answering `GET /db/` with that file's body (404 otherwise). + fn serve(files: Vec<(&'static str, Vec)>) -> String { + let l = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}/db", l.local_addr().unwrap()); + std::thread::spawn(move || { + for mut s in l.incoming().flatten() { + let mut r = BufReader::new(s.try_clone().unwrap()); + let mut first = String::new(); + let _ = r.read_line(&mut first); + loop { + let mut line = String::new(); + if r.read_line(&mut line).unwrap_or(0) == 0 || line.trim().is_empty() { + break; + } + } + let path = first.split_whitespace().nth(1).unwrap_or_default().to_string(); + match files.iter().find(|(n, _)| path == format!("/db/{n}")) { + Some((_, body)) => { + let _ = s.write_all(format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).as_bytes()); + let _ = s.write_all(body); + } + None => { + let _ = s.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + } + } + } + }); + base + } + + fn wait(what: &str, done: impl Fn() -> bool) { + let t = std::time::Instant::now(); + while !done() { + assert!(t.elapsed() < Duration::from_secs(20), "{what}"); + std::thread::sleep(Duration::from_millis(10)); + } + } + + const LENS: &str = r#"TestcamTestcam 50mm f/1.8T1 + "#; + const CAMERA: &str = + r#"TestcamTC-1T1"#; + + fn sha(s: &str) -> &'static str { + Box::leak(lightcraft_faces::hash::sha256_hex(s.as_bytes()).into_boxed_str()) + } + + fn pins() -> &'static [Pin] { + Box::leak(vec![("lenses.xml", LENS.len() as u64, sha(LENS)), ("cameras.xml", CAMERA.len() as u64, sha(CAMERA))].into_boxed_slice()) + } + + /// Every pinned file lands in the folder with the marker, the activity row shows the download until it ends, + /// and the database reads. + #[test] + fn downloads_checks_and_installs_the_pinned_files() { + let dir = scratch("ok"); + let base = serve(vec![("lenses.xml", LENS.as_bytes().to_vec()), ("cameras.xml", CAMERA.as_bytes().to_vec())]); + let activity = Activity::default(); + let mut d = Download::default(); + assert!(!installed_with(&dir, pins())); + // an older pin's database: replaced as a whole, so a file this pin doesn't list is not read beside the new ones + std::fs::write(dir.join("dropped.xml"), CAMERA).unwrap(); + std::fs::write(dir.join(MARKER), "older").unwrap(); + // a resumed older attempt left a file this pin doesn't list in the staging folder: not published + std::fs::create_dir_all(beside(&dir, STAGING)).unwrap(); + std::fs::write(beside(&dir, STAGING).join("old-staged.xml"), CAMERA).unwrap(); + d.start(&dir, vec![base], pins(), &activity).unwrap(); + let rows = activity.list(); + assert!(rows.iter().any(|r| r.kind == "download" && r.label == "Downloading the lens database" && r.cancellable), "{rows:?}"); + wait("the download never ended", || !d.running()); + assert_eq!(d.state(), State::Done { files: 2 }); + assert!(installed_with(&dir, pins()), "the marker names the pinned commit and every file is there"); + assert!(!beside(&dir, STAGING).exists() && !beside(&dir, PREVIOUS).exists(), "no staging or previous folder is left"); + let (db, errors) = lightcraft_lensdb::LensDb::load_dir(&dir).unwrap(); + assert!(errors.is_empty() && db.lenses.len() == 1 && db.cameras.len() == 1); + assert!(!dir.join("dropped.xml").exists() && !dir.join("old-staged.xml").exists(), "only this pin's files"); + wait("the row stayed", || activity.list().is_empty()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A file that is not the pinned one (another commit, a hostile mirror) is refused and nothing is installed: + /// the previous complete database stays as it was. + #[test] + fn a_file_that_is_not_the_pinned_one_installs_nothing() { + let dir = scratch("bad"); + std::fs::write(dir.join("cameras.xml"), "previous").unwrap(); + std::fs::write(dir.join(MARKER), "older").unwrap(); + let base = serve(vec![("lenses.xml", LENS.replace("0.01", "0.02").into_bytes()), ("cameras.xml", CAMERA.as_bytes().to_vec())]); + let mut d = Download::default(); + d.start(&dir, vec![base], pins(), &Activity::default()).unwrap(); + wait("the download never ended", || !d.running()); + assert!(matches!(d.state(), State::Failed(_)), "{:?}", d.state()); + assert!(!installed_with(&dir, pins()) && complete(&dir), "the previous database is still whole"); + assert_eq!(std::fs::read_to_string(dir.join("cameras.xml")).unwrap(), "previous", "nothing moved into place"); + // no mirror at all is an error, not a thread + assert!(Download::default().start(&dir, Vec::new(), pins(), &Activity::default()).is_err()); + let _ = std::fs::remove_dir_all(beside(&dir, STAGING)); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The new database replaces the old folder as a whole or not at all: when moving it into place fails, the + /// previous database is put back (and when even that fails, the next start puts it back). + #[test] + fn a_failed_swap_keeps_the_previous_database() { + let dir = scratch("swap"); + std::fs::write(dir.join("lenses.xml"), "old").unwrap(); + std::fs::write(dir.join(MARKER), "older").unwrap(); + let staged = beside(&dir, STAGING); + std::fs::create_dir_all(&staged).unwrap(); + std::fs::write(staged.join("lenses.xml"), "new").unwrap(); + std::fs::write(staged.join(MARKER), COMMIT).unwrap(); + let read = |d: &Path| std::fs::read_to_string(d.join("lenses.xml")).unwrap(); + // the staged folder can't be moved into place: the old one comes back + let calls = std::cell::Cell::new(0); + let second_fails = |from: &Path, to: &Path| { + calls.set(calls.get() + 1); + if calls.get() == 2 { Err(std::io::Error::other("in use")) } else { std::fs::rename(from, to) } + }; + let err = publish(&staged, &dir, second_fails).unwrap_err(); + assert!(err.contains("in use"), "{err}"); + assert_eq!(read(&dir), "old", "the previous database is in place"); + assert!(complete(&dir) && !beside(&dir, PREVIOUS).exists()); + // neither move back works either (the app stops here): the next start puts the previous database back + let calls = std::cell::Cell::new(0); + let all_but_first_fail = |from: &Path, to: &Path| { + calls.set(calls.get() + 1); + if calls.get() == 1 { std::fs::rename(from, to) } else { Err(std::io::Error::other("in use")) } + }; + assert!(publish(&staged, &dir, all_but_first_fail).is_err()); + assert!(!dir.exists() && complete(&beside(&dir, PREVIOUS))); + recover(&dir); + assert_eq!(read(&dir), "old"); + // and a swap that works leaves only the new database + publish(&staged, &dir, |from, to| std::fs::rename(from, to)).unwrap(); + assert_eq!(read(&dir), "new"); + assert!(!staged.exists() && !beside(&dir, PREVIOUS).exists()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A folder whose marker is there but whose database files went missing (or were cut short) is not installed, + /// so the start downloads it again. + #[test] + fn installed_needs_every_pinned_file() { + let dir = scratch("installed"); + std::fs::write(dir.join(MARKER), format!("commit {COMMIT}")).unwrap(); + assert!(complete(&dir) && !installed_with(&dir, pins()), "the marker alone is not a database"); + std::fs::write(dir.join("lenses.xml"), LENS).unwrap(); + std::fs::write(dir.join("cameras.xml"), CAMERA).unwrap(); + assert!(installed_with(&dir, pins())); + std::fs::write(dir.join("cameras.xml"), &CAMERA[..10]).unwrap(); + assert!(!installed_with(&dir, pins()), "a file cut short"); + std::fs::remove_file(dir.join("cameras.xml")).unwrap(); + assert!(!installed_with(&dir, pins()), "a file gone"); + std::fs::write(dir.join(MARKER), "an older commit").unwrap(); + std::fs::write(dir.join("cameras.xml"), CAMERA).unwrap(); + assert!(!installed_with(&dir, pins()) && complete(&dir), "an older pin: whole, but replaced"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// An old database file that can't be removed is an error (so no marker is written and the next start tries + /// again); the pinned files and other files are left alone. + #[test] + fn an_old_file_that_cannot_be_removed_is_an_error() { + let dir = scratch("stale"); + for name in ["lenses.xml", "old-lenses.xml", "notes.txt"] { + std::fs::write(dir.join(name), "x").unwrap(); + } + let failing = |_: &Path| Err(std::io::Error::other("in use")); + let err = remove_stale(&dir, pins(), failing).unwrap_err(); + assert!(err.contains("old-lenses.xml") && err.contains("in use"), "{err}"); + remove_stale(&dir, pins(), |p| std::fs::remove_file(p)).unwrap(); + assert!(!dir.join("old-lenses.xml").exists()); + assert!(dir.join("lenses.xml").exists() && dir.join("notes.txt").exists()); + // a folder that can't be listed is an error too, not "nothing stale" + let not_a_folder = dir.join("notes.txt"); + let err = remove_stale(¬_a_folder, pins(), |p| std::fs::remove_file(p)).unwrap_err(); + assert!(err.contains("could not list"), "{err}"); + let err = remove_stale(&dir.join("missing"), pins(), |p| std::fs::remove_file(p)).unwrap_err(); + assert!(err.contains("could not list"), "{err}"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The first start asks before anything is downloaded; Download (or Settings) means a start fetches a missing + /// database; Not Now means nothing, ever, on its own; an installed database, a folder of the user's own or a host + /// that may not ask (CLI, MCP) mean nothing whatever the answer. + #[test] + fn the_start_asks_once_and_downloads_only_after_a_yes() { + let dir = || Some(PathBuf::from("lensfun")); + assert_eq!(decide(true, false, dir(), false, Offer::Ask), Start::Ask(PathBuf::from("lensfun")), "the first start asks"); + assert_eq!(decide(true, false, dir(), false, Offer::Accepted), Start::Fetch(PathBuf::from("lensfun"))); + assert_eq!(decide(true, false, dir(), false, Offer::Declined), Start::Nothing, "Not Now: never asked again"); + for offer in [Offer::Ask, Offer::Accepted, Offer::Declined] { + assert_eq!(decide(true, false, dir(), true, offer), Start::Nothing, "installed: no question, no download"); + assert_eq!(decide(false, false, dir(), false, offer), Start::Nothing, "a headless host never asks or fetches"); + assert_eq!(decide(true, true, dir(), false, offer), Start::Nothing, "the user's own folder"); + assert_eq!(decide(true, false, None, false, offer), Start::Nothing, "no data folder"); + } + // the size the offer names comes from the pins + assert_eq!(download_size(), FILES.iter().map(|f| f.1).sum::()); + assert!((4..=8).contains(&download_megabytes()), "{}", download_megabytes()); + } + + /// The pinned list is lensfun's whole `data/db` at the commit: unique XML names, sane sizes, hex hashes. + #[test] + fn the_pins_are_well_formed() { + assert_eq!(FILES.len(), 56); + let mut names: Vec<&str> = FILES.iter().map(|f| f.0).collect(); + names.sort_unstable(); + names.dedup(); + assert_eq!(names.len(), FILES.len()); + for (name, size, sha) in FILES { + assert!(name.ends_with(".xml") && !name.contains(['/', '\\']), "{name}"); + assert!(*size > 0 && *size < MAX_FILE, "{name}"); + assert!(sha.len() == 64 && sha.bytes().all(|b| b.is_ascii_hexdigit()), "{name}"); + } + assert!(DEFAULT_MIRROR.contains(COMMIT)); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 163a102680..f71f9becd1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -46,6 +46,7 @@ pub mod guard; pub mod import; mod import_move; pub mod lens_profiles; +pub mod lensfun_download; pub mod library; mod lightroom_archive; pub mod lightroom_catalog; @@ -79,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; @@ -284,6 +286,11 @@ pub struct Session { pub face_models_dir: Option, /// Face model downloads started this session (the staged files wait in `/.downloads`). pub face_downloads: face_download::Downloads, + /// The lens database download ([`lensfun_download`]). + pub lensfun: lensfun_download::Download, + /// The host may offer the lens database at its start, and fetch it after the user's yes + /// ([`Session::with_lens_auto_download`]; when: [`lensfun_download::fetch_on_start`]). + pub lens_auto_download: bool, /// Reverse geocoding: the parsed place names and their download (`metadata.*PlaceNames`). pub place_names: cmd::geocode::PlaceNames, /// The user's own list of models to download (`catalog.json` in the models folder), as last read. @@ -353,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 @@ -476,6 +485,8 @@ impl Session { denoise: Default::default(), face_models_dir: None, face_downloads: Default::default(), + lensfun: Default::default(), + lens_auto_download: false, place_names: Default::default(), face_catalog: Default::default(), #[cfg(not(target_arch = "wasm32"))] @@ -510,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(), @@ -606,7 +618,8 @@ impl Session { } } if self.depth == 0 && self.library.is_some() { - // Make the command durable before reporting success. When the command's own records + // Make the command durable before reporting success (natively: handed to the catalog + // log's own thread, which syncs it right after and holds it until it can). When the command's own records // can't be appended, it fails with `NotSaved`: the change stays applied in memory and // queued, and the next save (any later command, or the frame loop) retries it. Other // persistence trouble (a failed compaction, an older queued change still unwritten by @@ -938,8 +951,9 @@ impl Session { i.crop_edited |= crop_edited; return self.apply_silent(Op::SetDevelop { id, settings, label: label.into(), edited: Some(now) }); } + let own_auto = self.own_auto_wb(id, &requested, label); let mut ops = vec![self.develop_op(id, (*settings).clone(), label).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?]; - ops.extend(self.auto_sync_ops(id, &requested, label)); + ops.extend(self.auto_sync_ops(id, &requested, label, &own_auto)); let op = if ops.len() == 1 { ops.remove(0) } else { Op::Batch { ops } }; self.commit(label, op) } @@ -980,13 +994,12 @@ impl Session { /// never spot removal or red eye (they belong to one photo's pixels), nor the rendering process /// (Sync doesn't carry it either), nor history / snapshot restores. Constrain Crop then fits each /// photo's own crop: the active photo's fitted crop is never copied over another's. - fn auto_sync_ops(&self, id: PhotoId, new: &DevelopSettings, label: &str) -> Vec { - if !self.auto_sync - || self.active() != Some(id) - || self.selection.ids.len() < 2 - || label.starts_with("History:") - || label.starts_with("Restore ") - { + /// + /// White balance goes on each photo as the active photo's mode or value on the photo's own + /// scale ([`sync_same`]): As Shot its own camera white, Auto its own (`own_auto`, worked out on + /// its pixels), a Temp or Tint the same number, only the slider that moved. + fn auto_sync_ops(&self, id: PhotoId, new: &DevelopSettings, label: &str, own_auto: &std::collections::HashMap) -> Vec { + if !self.auto_sync_applies(id, label) { return Vec::new(); } let Some(old) = self.develop_of(id) else { return Vec::new() }; @@ -1008,21 +1021,62 @@ 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)?; + let mut settings = settings; + // old masks (on the corrected frame) go onto the photo, from the frame they were drawn on: + // masks this edit kept, under the photo's settings before it (a geometry edit then moves + // the photo, not them); masks it brought in (paste, sync, a preset, a history step, a + // sidecar), under the settings they came with, where they render now. Kept masks also + // turn with an orientation change the edit makes (a sync or paste of the Crop group). + let before = match &self.interaction { + Some(i) if i.photo == id => Some(i.original.clone()), + _ => self.develop_of(id), + }; + let turn = before.as_ref().and_then(|b| orientation_change(b.orientation, settings.orientation)); + if settings.masks.iter().any(|m| !m.on_photo) || turn.is_some() { + let kept_frame = before.as_ref().and_then(|b| self.mask_frame(id, b)); + let new_frame = self.mask_frame(id, &settings); + for m in &mut settings.masks { + let kept = before.as_ref().is_some_and(|b| b.masks.contains(m)); + if let Some(f) = if kept { kept_frame.as_ref() } else { new_frame.as_ref() } { + lightcraft_pipeline::mask_space::attach(m, f); + } + if let (true, Some(t)) = (kept, turn) { + lightcraft_pipeline::mask_space::turn(m, t); + } + } + } let settings = Arc::new(settings); let step = lightcraft_catalog::HistoryStep { label: label.into(), settings: settings.clone() }; Some(Op::Batch { @@ -1030,11 +1084,45 @@ impl Session { }) } + /// Put the old masks of `d` (on the corrected frame, `Mask::on_photo` false) on photo `id` + /// before the warp, from the frame of `drawn` (the settings they were drawn under): they + /// render where they did and from then on stay on their content when lens corrections, + /// Upright or Transform change. + pub fn attach_masks(&self, id: PhotoId, drawn: &DevelopSettings, d: &mut DevelopSettings) { + if d.masks.iter().all(|m| m.on_photo) { + return; + } + let Some(frame) = self.mask_frame(id, drawn) else { return }; + for m in &mut d.masks { + lightcraft_pipeline::mask_space::attach(m, &frame); + } + } + + /// The uncropped frame of photo `id` under settings `d`, with its lens: where mask + /// coordinates go through its warp ([`lightcraft_pipeline::geometry::Frame::for_mask`]). + pub(crate) fn mask_frame(&self, id: PhotoId, d: &DevelopSettings) -> Option { + let p = self.catalog.photo(id)?; + Some(lightcraft_pipeline::geometry::Frame::with_lens( + p.width.max(1) as usize, + p.height.max(1) as usize, + &d.effective(), + false, + p.embedded_lens.as_ref(), + )) + } + pub fn begin_interaction(&mut self, label: &str) -> Result<()> { if self.interaction.is_some() { self.end_interaction()?; } let id = self.active().ok_or_else(|| EngineError::Other("no active photo".into()))?; + // old masks go onto the photo before a drag moves the frame under them (they then stay on + // their content while it does, not only once it ends) + if let Some(d) = self.develop_of(id).filter(|d| d.masks.iter().any(|m| !m.on_photo)) { + let mut on = (*d).clone(); + self.attach_masks(id, &d, &mut on); + self.apply_silent(Op::SetDevelop { id, settings: Arc::new(on), label: label.into(), edited: None })?; + } let original = self.develop_of(id).unwrap_or_default(); self.interaction = Some(Interaction { label: label.into(), photo: id, original, crop_edited: false }); Ok(()) @@ -1373,3 +1461,22 @@ mod tests; use tests::face_recognize as tests_face_recognize; #[cfg(test)] use tests::xmp as tests_xmp; + +/// The turn or flip that takes orientation `from` to `to` (`None` when they are the same): what the +/// masks, on the oriented photo, must follow ([`lightcraft_pipeline::mask_space::turn`]). +pub(crate) fn orientation_change(from: lightcraft_geom::Orientation, to: lightcraft_geom::Orientation) -> Option { + use lightcraft_geom::Orientation; + if from == to { + return None; + } + let inv = from.inverse(); + let probes = [(0.2, 0.3), (0.7, 0.1), (0.4, 0.9)]; + let close = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9; + (0..8u8).map(|k| Orientation::from_parts(k >= 4, k % 4)).find(|t| { + probes.iter().all(|&(x, y)| { + let (rx, ry) = inv.map(x, y, 1.0, 1.0); + let (tx, ty) = from.map(rx, ry, 1.0, 1.0); + close(t.map(tx, ty, 1.0, 1.0), to.map(rx, ry, 1.0, 1.0)) + }) + }) +} diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index caf51a0ab6..23e333c4ca 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -13,8 +13,12 @@ //! The files live in [`Store`]s: a directory ([`FsStore`]) natively, or any other implementation //! via [`Session::open_library_in`] (the browser build keeps them in OPFS or IndexedDB). //! -//! Every top-level [`Session::execute`] persists the ops it produced (fsynced) before returning, -//! so a crash loses at most the command in flight. When that write fails the command returns +//! Every top-level [`Session::execute`] persists the ops it produced before returning: fsynced +//! there, or natively handed to the catalog log's own thread, which writes and syncs them right +//! after (the UI thread never waits for the drive), so a crash or power cut loses at most the +//! batch in flight (what arrived during one sync). A write that thread +//! can't make is held and retried, counts as unsaved ([`Session::unsaved`]) and makes a snapshot +//! due. When that write fails the command returns //! [`EngineError::NotSaved`]: its change stays applied in memory and queued, and every later save //! retries the queue ([`Session::unsaved`] reports it meanwhile), so nothing is lost once the //! disk is writable again. The log is compacted into a snapshot when it @@ -134,6 +138,10 @@ pub struct Library { /// Why the last write of presets.json failed; `None` once it is written. While set, the preset /// changes exist only in memory and count as unsaved ([`Session::unsaved`], issue #2266). presets_error: Option, + /// Records the catalog log's own thread holds because writing them failed (it retries them), + /// and why; refreshed by every persist and every frame ([`Session::persist_if_dirty`]). While + /// set they count as unsaved ([`Session::unsaved`]), so quitting asks first. + log_held: Option<(usize, String)>, /// When the frame loop may retry a failed append ([`Session::persist_if_dirty`] backs off). retry_at: Option, /// What forgetting untouched Local records did when the library opened. @@ -277,6 +285,8 @@ struct PrefsFile { label_sets: Vec, /// Imported LUT profiles. lut_profiles: Vec, + /// Imported camera profiles (`.dcp`). + dcp_profiles: Vec, /// Keyword sets, the one in use, recent keywords. keyword_sets: Vec, keyword_set: Option, @@ -322,6 +332,8 @@ fn poll_compaction(lib: &mut Library) { log::error!("library: compaction: {e}"); lib.last_error = Some(format!("compaction: {e}")); } + // (never waits: the log's thread publishes what it holds) + lib.log_held = lib.journal.unwritten(); } /// How long the frame loop waits before retrying a failed append (commands retry at once). @@ -501,13 +513,24 @@ impl Session { /// Open `stores`; the new library takes `lock` once nothing can fail any more. fn open_stores(&mut self, stores: LibraryStores, seed_demo: bool, lock: &mut Option) -> Result<()> { let LibraryStores { dir, catalog, mut files, on_disk } = stores; - self.media.smart_dir = on_disk.then(|| crate::smart::dir(&dir)); - // the current library may be these same files: let its background snapshot land first - if let Some(old) = self.library.as_mut() - && let Err(e) = old.journal.wait() - { - log::error!("library: {e}"); + // the current library may be these same files: let its background snapshot land first, and + // what its log's thread was handed reach the file before the new journal reads it. When + // that can't be written, the open fails and the current library stays open with what its + // thread holds (retried): read now, the files would miss it (review of #3557). + if let Some(old) = self.library.as_mut() { + if let Err(e) = old.journal.wait() { + log::error!("library: {e}"); + } + if let Err(e) = old.journal.flush() { + old.log_held = old.journal.unwritten(); + // a snapshot that holds every op leaves nothing for the files to miss + if old.journal.snapshot_seq() < old.journal.seq() { + return Err(EngineError::NotSaved(format!("the open library's changes aren't on disk yet, so it stays open: {e}"))); + } + log::error!("library: {e} (every change is in its snapshot)"); + } } + self.media.smart_dir = on_disk.then(|| crate::smart::dir(&dir)); // Photo ids belong to one library; denoise work must not carry into the next. self.denoise.library_changed(); self.media.denoise.clear(); @@ -555,6 +578,8 @@ impl Session { self.label_sets = prefs.label_sets; self.lut_profiles = prefs.lut_profiles; crate::cmd::lut_profiles::register_all(self); + self.dcp_profiles = prefs.dcp_profiles; + crate::cmd::dcp_profiles::register_all(self, on_disk.then(|| dir.join("Profiles")).as_deref()); self.keyword_sets = prefs.keyword_sets; self.keyword_set = prefs.keyword_set; self.recent_keywords = prefs.recent_keywords; @@ -582,7 +607,11 @@ impl Session { self.presets.push(u); } } - let known = |id: &String| crate::presets::profile(id).is_some() || self.lut_profiles.iter().any(|p| &p.id == id); + let known = |id: &String| { + crate::presets::profile(id).is_some() + || self.lut_profiles.iter().any(|p| &p.id == id) + || self.dcp_profiles.iter().any(|p| &p.id == id) + }; self.profile_favorites = f.profile_favorites.into_iter().filter(known).collect(); self.profile_recent = f.profile_recent.into_iter().filter(known).take(crate::presets::RECENT_PROFILES).collect(); } @@ -631,6 +660,7 @@ impl Session { last_error: None, unsaved_error: None, presets_error: None, + log_held: None, retry_at: None, forgot_local: None, presets_saved, @@ -661,7 +691,7 @@ impl Session { Ok(()) } - /// Write pending ops to the log (fsynced), compact when due, and save changed presets. + /// Write pending ops to the log (fsynced, or handed to the log's own thread natively), compact when due, and save changed presets. /// Called after every top-level command; cheap when nothing changed. Fails (with /// [`EngineError::NotSaved`]) only when the queued ops couldn't be written; they stay queued. pub fn persist(&mut self) -> Result<()> { @@ -726,13 +756,40 @@ impl Session { pub fn persist_if_dirty(&mut self) { let backing_off = self.library.as_ref().and_then(|l| l.retry_at).is_some_and(|t| web_time::Instant::now() < t); let presets_unsaved = self.library.as_ref().is_some_and(|l| l.presets_error.is_some()); - if self.library.is_some() && (!self.pending_log.is_empty() || presets_unsaved) && !backing_off { + // records the log's thread can't write: a snapshot (a fresh file holding everything) is due + let log_held = self.library.as_ref().is_some_and(|l| l.log_held.is_some()); + if self.library.is_some() && (!self.pending_log.is_empty() || presets_unsaved || log_held) && !backing_off { let _ = self.persist(); } else if let Some(lib) = self.library.as_mut() { poll_compaction(lib); } } + /// Read again what the catalog log's own thread holds because writing it failed (never waits): + /// before a check of [`Session::unsaved`] that must be current, such as the quit prompt's. + pub fn refresh_unsaved(&mut self) { + if let Some(lib) = self.library.as_mut() { + lib.log_held = lib.journal.unwritten(); + } + } + + /// Every change applied is in the library's last snapshot (a closing snapshot landed), whatever + /// the catalog log's thread still holds or failed to reset. `false` without a library. + pub fn snapshot_holds_everything(&self) -> bool { + self.pending_log.is_empty() && self.library.as_ref().is_some_and(|l| l.journal.snapshot_seq() >= l.journal.seq()) + } + + /// Wait until what the catalog log's thread was handed is on disk, then read again what it + /// holds ([`Session::refresh_unsaved`]). Before the quit check: a change the thread accepted + /// but hasn't written yet is in no count of [`Session::unsaved`]. An error (a write failed, or + /// the drive took over a minute) means some changes may not be on disk yet. + pub fn flush_log(&mut self) -> Result<()> { + let Some(lib) = self.library.as_mut() else { return Ok(()) }; + let flushed = lib.journal.flush(); + lib.log_held = lib.journal.unwritten(); + Ok(flushed?) + } + /// Changes applied in memory but not yet written to disk because saving failed: the number of /// queued ops (plus one for presets.json) and why (`None` when everything is saved, or no library /// is open). Retried by every command and by [`Session::persist_if_dirty`]. @@ -740,8 +797,9 @@ impl Session { let lib = self.library.as_ref()?; let ops = lib.unsaved_error.as_deref().filter(|_| !self.pending_log.is_empty()); let presets = lib.presets_error.as_deref(); - let n = ops.map_or(0, |_| self.pending_log.len()) + usize::from(presets.is_some()); - ops.or(presets).map(|why| (n, why)) + let held = lib.log_held.as_ref().map(|(n, why)| (*n, why.as_str())); + let n = ops.map_or(0, |_| self.pending_log.len()) + held.map_or(0, |(n, _)| n) + usize::from(presets.is_some()); + ops.or(held.map(|(_, why)| why)).or(presets).map(|why| (n, why)) } /// Flush everything and write a snapshot (on quit). Ends an open interaction first. @@ -760,6 +818,8 @@ impl Session { let Some(lib) = self.library.as_mut() else { return Ok(()) }; let before = lib.journal.seq(); let snapshot = lib.journal.snapshot_with_unlogged(&self.catalog, unlogged); + // (a snapshot that landed holds what the log's thread held) + lib.log_held = lib.journal.unwritten(); if unlogged > 0 && lib.journal.seq() == before + unlogged { // the snapshot holds the queued ops: they are saved, never append them again log::info!("library: {unlogged} queued change(s) saved in the closing snapshot"); @@ -834,6 +894,7 @@ impl Session { mask_tool_effects: self.mask_tool_effects.clone(), label_sets: self.label_sets.clone(), lut_profiles: self.lut_profiles.clone(), + dcp_profiles: self.dcp_profiles.clone(), keyword_sets: self.keyword_sets.clone(), keyword_set: self.keyword_set.clone(), recent_keywords: self.recent_keywords.clone(), diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index c7bf8611b8..add37f904a 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -1139,7 +1139,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co number(&src.image, "fileHeight").max(0) as u32, &now, ); - if ["RAW", "DNG", "ARW", "CR2", "CR3", "NEF", "NRW", "RAF", "ORF", "RW2", "PEF"].contains(&p.format.to_uppercase().as_str()) { + if ["RAW", "DNG", "ARW", "CR2", "CR3", "CRW", "NEF", "NRW", "RAF", "ORF", "RW2", "PEF"].contains(&p.format.to_uppercase().as_str()) { p.kind = lightcraft_catalog::MediaKind::Raw; } p diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 7377e23f1b..a4528795b1 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -24,6 +24,7 @@ use lightcraft_develop::DevelopSettings; use lightcraft_pipeline::{Quality, RenderRequest, Rendered, SourceInfo, StageCache}; use lightcraft_preview::{Hash128, Hasher128, Lru, PreviewCache}; use lightcraft_raster::{Histogram, Rgb32f, Rgba8}; +pub use lightcraft_raw::dcp::DcpProfile; use serde::{Deserialize, Serialize}; mod cache; @@ -35,7 +36,7 @@ mod source; pub use cache::DenoiseIndex; pub use quick::{QuickJob, QuickSource, content_key, source_info}; -pub use render::{RenderJob, RenderResult, develop, develop_reporting, fit_for_display}; +pub use render::{RenderJob, RenderResult, ScreenFrame, develop, develop_reporting, fit_for_display}; #[cfg(test)] use settings_hash::SETTINGS_HASH_ENTRIES; use settings_hash::SettingsHashes; @@ -79,6 +80,26 @@ pub struct MediaCache { pub rendered: Arc, /// Which photos have a cached denoised picture, and how to read it. pub denoise: DenoiseIndex, + /// Imported camera profiles by id ([`crate::cmd::dcp_profiles`]), handed to the decoder of photos using them. + pub camera_profiles: std::collections::HashMap, +} + +/// An imported camera profile ready for the decoder, with a fingerprint of its file: decoded sources and cached renders +/// made with it carry the fingerprint, so a profile deleted, or replaced by another under the same id, never has +/// its old pictures stand in. +#[derive(Clone, Debug)] +pub struct LoadedCameraProfile { + pub profile: Arc, + /// Never 0 (0 is "no camera profile" in a render key). + pub fingerprint: u64, +} + +impl LoadedCameraProfile { + /// Parse a `.dcp` file's bytes. + pub fn parse(bytes: &[u8]) -> Result { + let profile = lightcraft_raw::dcp::parse_dcp(bytes)?; + Ok(LoadedCameraProfile { profile: Arc::new(profile), fingerprint: Hasher128::new().update(bytes).finish().0 as u64 | 1 }) + } } #[cfg(test)] diff --git a/crates/engine/src/media/cache.rs b/crates/engine/src/media/cache.rs index 238870c07a..234efb1485 100644 --- a/crates/engine/src/media/cache.rs +++ b/crates/engine/src/media/cache.rs @@ -1,6 +1,6 @@ use super::settings_hash::SettingsHashes; use super::source::{DecodedSource, DenoiseSpec, PairLoader, RENDERED_MEM_BYTES, SourceLevel, SourceRef, THUMB_SOURCE_BYTES}; -use super::{Arc, DevelopSettings, Hasher128, Lru, MediaCache, Photo, PhotoId, PreviewCache, Rgb32f, Source, SourceInfo}; +use super::{Arc, DcpProfile, DevelopSettings, HashMap, Hasher128, Lru, MediaCache, Photo, PhotoId, PreviewCache, Rgb32f, Source, SourceInfo}; /// The photos that have a cached denoised picture for the denoise model in use. Only memory: nothing here touches the /// file system, so it can be asked on the UI thread. @@ -70,6 +70,7 @@ impl Default for MediaCache { scenes: Vec::new(), rendered: Arc::new(PreviewCache::memory(rendered_budget(budget))), denoise: DenoiseIndex::default(), + camera_profiles: HashMap::new(), } } } @@ -202,14 +203,16 @@ impl MediaCache { } /// The facts of photo `id`'s cached sources: the decoder's when one has them, else `header` - /// (with a smart preview's stored camera tone curve). - pub(super) fn source_facts(&self, id: PhotoId, header: SourceInfo) -> SourceInfo { + /// (with a smart preview's stored camera tone curve). Only sources developed with `profile` (the photo's imported + /// camera profile tag, [`Self::camera_profile_of`], or none) count: one made with another profile has its facts. + pub(super) fn source_facts(&self, id: PhotoId, header: SourceInfo, profile: Option<&str>) -> SourceInfo { let cached = || { self.thumbs .peek(&id) .into_iter() .chain(self.previews.iter().filter(|e| e.0 == id).map(|e| &e.1)) .chain(self.full.iter().filter(|e| e.0 == id).map(|e| &e.1)) + .filter(|s| s.camera_profile.as_deref() == profile) }; match cached().find(|s| s.info.is_some()).or_else(|| cached().next()) { Some(s) => s.info_or(header), @@ -221,7 +224,13 @@ impl MediaCache { self.insert_source(id, level, DecodedSource::new(img, None)); } - pub(super) fn insert_source(&mut self, id: PhotoId, level: SourceLevel, img: DecodedSource) { + /// A decoded source with what the decoder reported about it (tests: photos of another as-shot white). + #[cfg(test)] + pub(crate) fn insert_with_info(&mut self, id: PhotoId, level: SourceLevel, img: Arc, info: lightcraft_pipeline::SourceInfo) { + self.insert_source(id, level, DecodedSource::new(img, Some(info))); + } + + pub(crate) fn insert_source(&mut self, id: PhotoId, level: SourceLevel, img: DecodedSource) { let tick = lightcraft_preview::next_tick(); match level { SourceLevel::Thumb => { @@ -296,24 +305,49 @@ impl MediaCache { self.source_ref_with(p, level, false) } + /// [`Self::source_ref`] without the photo's imported camera profile (keeping its denoised picture): a smart + /// preview keeps the file's own colour, and a cached source developed with the profile doesn't stand in for it. + #[cfg(not(target_arch = "wasm32"))] + pub fn source_ref_without_profile(&mut self, p: &Photo, level: SourceLevel) -> SourceRef { + self.source_ref_for(p, level, true, None) + } + fn source_ref_with(&mut self, p: &Photo, level: SourceLevel, cached: bool) -> SourceRef { - let mut r = self.source_ref_plain(p, level, cached); + let wanted = self.camera_profile_of(p); + self.source_ref_for(p, level, cached, wanted) + } + + /// [`Self::source_ref_with`] developed with camera profile `wanted` (none: the file's own colour). + fn source_ref_for(&mut self, p: &Photo, level: SourceLevel, cached: bool, wanted: Option<(String, Arc)>) -> SourceRef { + let mut r = self.source_ref_plain(p, level, cached, wanted); if let (SourceRef::File { denoise, .. }, Some((spec, loader))) = (&mut r, self.denoise.get(p.id)) { *denoise = Some((spec.clone(), loader.clone())); } r } - fn source_ref_plain(&mut self, p: &Photo, level: SourceLevel, cached: bool) -> SourceRef { - if cached && let Some(a) = self.get_source(p.id, level) { + /// Is photo `p`'s original known to be missing (cached answer only)? + fn original_offline(&self, p: &Photo) -> bool { + matches!(&p.source, Source::File { path } if self.availability.is_offline(path)) + } + + fn source_ref_plain(&mut self, p: &Photo, level: SourceLevel, cached: bool, wanted: Option<(String, Arc)>) -> SourceRef { + // (a source developed with another camera profile, or none, doesn't stand in; a smart preview + // has no camera profile, and decoding it again gives the same picture, so it stands in while the + // original is offline) + if cached + && let Some(a) = self.get_source(p.id, level) + && (a.camera_profile == wanted.as_ref().map(|(id, _)| id.clone()) || (a.from_proxy && self.original_offline(p))) + { return SourceRef::Loaded(Box::new(a)); } // a thumbnail of a photo whose preview is decoded (the one in the loupe) is cut from it; not - // with a denoised picture, which the thumbnail would lose + // with a denoised picture, which the thumbnail would lose, nor from one decoded with another camera profile if cached && level == SourceLevel::Thumb && self.denoise.spec(p.id).is_none() && let Some(big) = self.get_source(p.id, SourceLevel::Preview) + && (big.camera_profile == wanted.as_ref().map(|(tag, _)| tag.clone()) || (big.from_proxy && self.original_offline(p))) { return SourceRef::Fit { from: Box::new(big), max_edge: level.max_edge() }; } @@ -336,12 +370,36 @@ impl MediaCache { return SourceRef::Smart { path: sp }; } let mut r = self.origin_ref(&p.source, max_edge); - if let SourceRef::File { fallback, .. } = &mut r { + if let SourceRef::File { fallback, camera_profile, .. } = &mut r { *fallback = Some(sp); + *camera_profile = wanted; } return r; } - self.origin_ref(&p.source, max_edge) + let mut r = self.origin_ref(&p.source, max_edge); + if let SourceRef::File { camera_profile, .. } = &mut r { + *camera_profile = wanted; + } + r + } + + /// The imported camera profile photo `p` develops with, when its profile setting names one this library has: what a + /// source decoded with it is tagged with (its id and the file's fingerprint), and the profile. + pub fn camera_profile_of(&self, p: &Photo) -> Option<(String, Arc)> { + let id = &p.develop.profile.id; + if !crate::cmd::dcp_profiles::is_dcp_id(id) { + return None; + } + self.camera_profiles.get(id).map(|d| (format!("{id}#{:016x}", d.fingerprint), d.profile.clone())) + } + + /// What a render with profile `profile_id` adds to its cache keys: the imported camera profile's fingerprint, 0 + /// for any other profile and for a camera profile this library no longer has (it renders without it). + pub fn camera_profile_salt(&self, profile_id: &str) -> u64 { + if !crate::cmd::dcp_profiles::is_dcp_id(profile_id) { + return 0; + } + self.camera_profiles.get(profile_id).map_or(0, |d| d.fingerprint) } /// How to load `origin` at most `max_edge` pixels long, ignoring decoded sources in memory (a @@ -354,12 +412,26 @@ impl MediaCache { } match self.scenes.iter().find(|s| s.id == *scene) { Some(s) => SourceRef::Demo { scene: Box::new(s.clone()), max_edge }, - None => SourceRef::File { path: format!("demo:{scene}"), max_edge, loader: None, fallback: None, denoise: None, reduced: None }, + None => SourceRef::File { + path: format!("demo:{scene}"), + max_edge, + loader: None, + fallback: None, + denoise: None, + camera_profile: None, + reduced: None, + }, } } - Source::File { path } => { - SourceRef::File { path: path.clone(), max_edge, loader: self.file_loader.clone(), fallback: None, denoise: None, reduced: None } - } + Source::File { path } => SourceRef::File { + path: path.clone(), + max_edge, + loader: self.file_loader.clone(), + fallback: None, + denoise: None, + camera_profile: None, + reduced: None, + }, } } } diff --git a/crates/engine/src/media/quick.rs b/crates/engine/src/media/quick.rs index 21edb2bed4..335a118ca6 100644 --- a/crates/engine/src/media/quick.rs +++ b/crates/engine/src/media/quick.rs @@ -1,6 +1,6 @@ use super::render::{RenderJob, RenderResult}; use super::source::{PreviewLoader, SourceLevel}; -use super::{Arc, Deserialize, Hash128, Histogram, Photo, PhotoId, PreviewCache, Rendered, Rgba8, Serialize, Source, SourceInfo}; +use super::{Arc, Deserialize, Hash128, Hasher128, Histogram, Photo, PhotoId, PreviewCache, Rendered, Rgba8, Serialize, Source, SourceInfo}; /// Where a [`QuickJob`]'s stand-in image came from. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -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); @@ -99,6 +101,20 @@ impl QuickJob { } /// 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 +/// matches when the job finishes ([`super::Session::accept`]), so a decode started before a profile change never +/// returns to the cache after `cmd::lens_refresh` has dropped the photo's sources. +pub fn source_identity(p: &Photo) -> Hash128 { + let mut k = Hasher128::new(); + k.str(&content_key(p)); + let lens = lens_key(p); + if lens != 0 { + k.u64(lens); + } + k.finish() +} + pub fn content_key(p: &Photo) -> String { match (&p.content_hash, &p.source) { (Some(h), _) => h.clone(), @@ -107,6 +123,21 @@ pub fn content_key(p: &Photo) -> String { } } +/// What a photo's lens profile adds to its render and thumbnail keys: a database profile (0 without one), with the +/// correction on or off: a raw's starting colour is fitted through the profile's vignetting either way +/// (`camera_preview::starting_colour`), so the decoded picture depends on it. When a database update gives the +/// photo another profile, its cached renders and thumbnails no longer match. (The file's own correction changes only with the file, which the content +/// key covers, so it adds nothing and existing thumbnails stay valid.) +pub fn lens_key(p: &Photo) -> u64 { + match &p.embedded_lens { + Some(l) if l.source == lightcraft_develop::LensSource::Database => { + let k = Hasher128::new().str("lens").str(&format!("{l:?}")).finish(); + (k.0 as u64) ^ ((k.0 >> 64) as u64) | 1 + } + _ => 0, + } +} + pub fn source_info(p: &Photo) -> SourceInfo { // Procedural demo scenes are scene-referred HDR (like raw files): use the filmic tone map. // (They are drawn afresh at every size, so they have no original size.) 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 79cfa556c8..ac1b8145a9 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -1,5 +1,6 @@ use super::quick::{QuickJob, content_key, source_info}; use super::render::{RenderJob, RenderResult}; +use super::settings_hash::with_process; use super::source::{PreviewLoader, RENDER_CACHE_VERSION, SourceLevel, SourceRef, THUMB_SIZES, face_edge, source_edge_needed, thumb_bucket}; use super::{Arc, DevelopSettings, Hash128, Hasher128, MediaKind, Op, Photo, PhotoId, RenderRequest, Rendered, Rgb32f, Source, SourceInfo}; @@ -41,17 +42,26 @@ 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) // …and so is the file's content: a file changed on disk (Reload) renders afresh let content_key = content_key(&p); - let source_key = Hasher128::new().str(&content_key).finish(); - let content = source_key.0 as u64; + let content = Hasher128::new().str(&content_key).finish().0 as u64; + let source_key = super::quick::source_identity(&p); // 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) ^ ((max_h as u64) << 20) @@ -59,14 +69,25 @@ impl crate::Session { ^ (level as u64) << 60 ^ id.0.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ content.rotate_left(17) - ^ salt; + ^ salt + ^ profile_salt.rotate_left(29) + ^ lens.rotate_left(37); let cache = thumb_bucket.map(|b| { let mut k = Hasher128::new(); - k.str(&content_key).u64(settings_hash).u64(b as u64).u64(RENDER_CACHE_VERSION).u64(crate::camera_profiles::cache_key()); + k.str(&content_key).u64(settings_hash).u64(b as u64).u64(RENDER_CACHE_VERSION); + with_process(&mut k, &settings).u64(crate::camera_profiles::cache_key()); // (only a render that uses a denoised picture has it in its key, so every other thumbnail stays valid) if salt != 0 { k.u64(salt); } + // (likewise an imported camera profile's file: deleted or replaced, the thumbnail renders afresh) + if profile_salt != 0 { + k.str("dcp").u64(profile_salt); + } + // (likewise a database lens profile: thumbnails of every other photo keep their keys) + if lens != 0 { + k.u64(lens); + } (self.media.rendered.clone(), k.finish()) }); Some(RenderJob { @@ -85,6 +106,7 @@ impl crate::Session { stages: None, view_cache: None, display: None, + on_screen: false, slide: None, preview_cut: None, display_fit: None, @@ -95,21 +117,43 @@ 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()); - job.key = settings.hash64() ^ ((max_w as u64) << 40) ^ ((max_h as u64) << 20) ^ (apply_crop as u64) ^ (job.level as u64) << 60; + // (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() + ^ ((max_w as u64) << 40) + ^ ((max_h as u64) << 20) + ^ (apply_crop as u64) + ^ (job.level as u64) << 60 + ^ 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 { - Hasher128::new() - .str(&content_key(p)) - .str("variant") - .u64(settings.hash64()) - .u64(edge as u64) - .u64(RENDER_CACHE_VERSION) - .u64(crate::camera_profiles::cache_key()) - .finish() + /// `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); + } + k.finish() } /// A thumbnail of `id` rendered with `settings` instead of its own (profile and preset @@ -118,15 +162,17 @@ 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(), - source_key: Some(Hasher128::new().str(&content_key(&p)).finish()), + source_key: Some(super::quick::source_identity(&p)), photo: id, level, source, @@ -139,6 +185,7 @@ impl crate::Session { stages: None, view_cache: None, display: None, + on_screen: false, slide: None, preview_cut: None, display_fit: None, @@ -176,12 +223,12 @@ 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, cache_generation: self.media.rendered.generation(), - source_key: Some(Hasher128::new().str(&content_key(&p)).finish()), + source_key: Some(super::quick::source_identity(&p)), photo: id, level, source, @@ -194,6 +241,7 @@ impl crate::Session { stages: None, view_cache: None, display: None, + on_screen: false, slide: None, preview_cut, display_fit: None, @@ -216,16 +264,20 @@ 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. - fn view_key(p: &Photo, apply_crop: bool) -> Hash128 { - Hasher128::new() - .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()) - .finish() + /// 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 { + 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); + } + k.finish() } /// The loupe's render job: like [`Self::render_job`], and a full-quality result is kept as the @@ -233,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) } @@ -342,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)) }) @@ -374,7 +428,7 @@ impl crate::Session { /// has wrong is corrected too ([`Self::learn_as_shot_wb`]). pub fn accept(&mut self, r: &RenderResult) { if let Some(src) = &r.loaded - && r.source_key.is_none_or(|key| self.catalog.photo(r.photo).is_some_and(|p| Hasher128::new().str(&content_key(p)).finish() == key)) + && r.source_key.is_none_or(|key| self.catalog.photo(r.photo).is_some_and(|p| super::quick::source_identity(p) == key)) { if let Some(info) = &src.info { self.learn_as_shot_wb(r.photo, info); @@ -474,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. @@ -489,4 +545,37 @@ impl crate::Session { self.media.insert_source(id, level, r); Ok(image) } + + /// [`Session::source_now`] for several photos at once, each with the facts its decoder gave + /// ([`Session::source_info`], read before another photo can push it out of the cache): the + /// ones not in memory are decoded in parallel, so a selection costs about one decode per core, + /// not one after another. In the order of `ids`. Callers pass a few at a time (all of them are + /// held decoded until this returns). + pub(crate) fn sources_now(&mut self, ids: &[PhotoId], level: SourceLevel) -> Vec<(PhotoId, Result<(Arc, SourceInfo), String>)> { + use rayon::prelude::*; + let refs: Vec<(PhotoId, Option)> = + ids.iter().map(|&id| (id, self.catalog.photo(id).cloned().map(|p| self.media.source_ref(&p, level)))).collect(); + let loaded: Vec<(PhotoId, Result)> = + refs.into_par_iter().map(|(id, r)| (id, r.ok_or_else(|| "no such photo".to_string()).and_then(|r| r.load_source()))).collect(); + loaded + .into_iter() + .map(|(id, r)| { + let r = r.map(|r| { + let image = r.image.clone(); + if let Some(info) = &r.info { + self.learn_as_shot_wb(id, info); + } + // read before the insert: the cache's budget may evict this very entry, and + // the header facts alone lack the decoder's camera colour + let facts = match r.info { + Some(_) => r.info_or(self.catalog.photo(id).map(|p| source_info(p)).unwrap_or_default()), + None => self.source_info(id), + }; + self.media.insert_source(id, level, r); + (image, facts) + }); + (id, r) + }) + .collect() + } } diff --git a/crates/engine/src/media/settings_hash.rs b/crates/engine/src/media/settings_hash.rs index 802918fb90..39f76d52bb 100644 --- a/crates/engine/src/media/settings_hash.rs +++ b/crates/engine/src/media/settings_hash.rs @@ -1,4 +1,4 @@ -use super::{Arc, DevelopSettings, HashMap, PhotoId, VecDeque, Weak}; +use super::{Arc, DevelopSettings, HashMap, Hasher128, PhotoId, VecDeque, Weak}; pub(super) const SETTINGS_HASH_ENTRIES: usize = 1024; @@ -34,3 +34,18 @@ impl SettingsHashes { hash } } + +/// Add the rendering process `s` renders with in this build to persistent render key `h`, from +/// process V3 on: a process number from a newer LightCraft renders with an older build's latest +/// process, so the same settings (and settings hash) render differently in a build that knows that +/// process, and the keys must tell those renders apart. Builds before V3 (which have no process in +/// their keys) resolve every number above V2 to V2: naming V3 and later keeps this build's renders +/// of those numbers apart from theirs, and V1 and V2 keep the keys they always had, so their +/// cached renders stay valid (`docs/process-versions.md`). +pub(super) fn with_process<'a>(h: &'a mut Hasher128, s: &DevelopSettings) -> &'a mut Hasher128 { + let v = s.process.process().version().0; + if v >= lightcraft_develop::Process::V3.version().0 { + h.u64(u64::from(v)); + } + h +} diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index 3373e12b5c..f13349f18c 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -1,7 +1,7 @@ -use super::{Arc, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo}; +use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo}; /// Bump when the pipeline's output changes, to invalidate cached thumbnails. -pub const RENDER_CACHE_VERSION: u64 = 72; +pub const RENDER_CACHE_VERSION: u64 = 75; /// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache). pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512]; @@ -75,12 +75,14 @@ pub(super) fn source_edge_needed(p: &Photo, settings: &DevelopSettings, apply_cr } /// Decodes a file into a linear Rec.2020 image no larger than `max_edge` (set by the app). -pub type FileLoader = Arc Result<(Rgb32f, SourceInfo), String> + Send + Sync>; +/// The third argument is the photo's imported camera profile ([`crate::cmd::dcp_profiles`]): a raw file is developed +/// with its colour model. +pub type FileLoader = Arc) -> Result<(Rgb32f, SourceInfo), String> + Send + Sync>; /// [`FileLoader`] for a thumbnail: a raw file that keeps smaller copies of its raw image (Lightroom's merged DNGs) /// develops the smallest that covers `max_edge` (set by the app); the flag says it did. Never used for an export, /// which must render the full image. -pub type ReducedLoader = Arc Result<(Rgb32f, SourceInfo, bool), String> + Send + Sync>; +pub type ReducedLoader = Arc) -> Result<(Rgb32f, SourceInfo, bool), String> + Send + Sync>; /// A raw file's embedded (camera-rendered) preview as display sRGB, oriented, no larger than /// `max_edge` (set by the app). `None`: no usable preview. @@ -103,7 +105,8 @@ pub struct DenoiseSpec { /// Decodes a raw file once and develops it twice: as usual, and from the denoised picture in `spec` when that can be /// read (`None` when it cannot). Both are at most `max_edge` long and the same size. -pub type PairLoader = Arc Result<(Rgb32f, Option, SourceInfo), String> + Send + Sync>; +pub type PairLoader = + Arc) -> Result<(Rgb32f, Option, SourceInfo), String> + Send + Sync>; /// A photo's denoised picture next to its plain one, and the last mix of the two that was asked for. pub struct Twin { @@ -133,6 +136,9 @@ pub struct DecodedSource { pub camera_tone: Option, /// The same picture developed from the AI-denoised mosaic, when the photo has one cached. pub denoised: Option>, + /// The imported camera profile (`dcp:…` id) the raw file was developed with, if any: a cached source made with + /// another one (or none) doesn't stand in for it. + pub camera_profile: Option, /// These pixels came from the photo's smart preview (an offline original), not from its file. /// A refresh must never rebuild a proxy from itself: that would stamp its older look as current. pub from_proxy: bool, @@ -143,7 +149,7 @@ pub struct DecodedSource { impl DecodedSource { pub fn new(image: Arc, info: Option) -> Self { - DecodedSource { image, info, camera_tone: None, denoised: None, from_proxy: false, reduced: false } + DecodedSource { image, info, camera_tone: None, denoised: None, camera_profile: None, from_proxy: false, reduced: false } } /// The picture to develop for a Denoise `amount` (0 to 1, see [`DevelopSettings::denoise_amount`]): the plain one, @@ -183,14 +189,35 @@ impl DecodedSource { /// What to render these pixels against: the decoder's facts, else `header` (the catalog's) /// with any stored camera tone curve. The original's size comes from `header` either way: the /// decoder only sees the level it decoded. + /// + /// A lens profile from the lens database is the catalog's too ([`pinned_lens`]): the decoder looks the lens up in + /// the database in use when it reads the file, which may be newer than the one the photo's profile came from. pub fn info_or(&self, header: SourceInfo) -> SourceInfo { match &self.info { - Some(info) => SourceInfo { native_long: info.native_long.or(header.native_long), ..info.clone() }, + Some(info) => { + SourceInfo { native_long: info.native_long.or(header.native_long), lens: pinned_lens(info.lens, header.lens), ..info.clone() } + } None => SourceInfo { camera_tone: self.camera_tone.or(header.camera_tone), ..header }, } } } +/// The lens profile a render uses: the file's own correction as decoded (`decoded`, it is part of the file), else the +/// catalog's database profile (`catalog`, [`lightcraft_catalog::Photo::embedded_lens`]). A file correction the +/// catalog still holds but the decode no longer finds (the original was replaced) is not restored. A database profile +/// is never taken from the decode, so a cached render, a fresh decode and the Optics panel all use the one profile the photo holds, and a +/// change to it (a database update looked up again, `cmd::lens_refresh`) changes the render keys +/// ([`super::quick::lens_key`]). +pub(crate) fn pinned_lens( + decoded: Option, + catalog: Option, +) -> Option { + match decoded { + Some(l) if l.source == lightcraft_develop::LensSource::File => Some(l), + _ => catalog.filter(|c| c.source == lightcraft_develop::LensSource::Database), + } +} + #[derive(Clone)] pub enum SourceRef { Loaded(Box), @@ -214,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, }, @@ -241,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 @@ -260,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()); } @@ -269,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 3c23e9db95..85089d231d 100644 --- a/crates/engine/src/media/thumbnail_hash_tests.rs +++ b/crates/engine/src/media/thumbnail_hash_tests.rs @@ -6,6 +6,77 @@ fn session() -> crate::Session { s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); s } +/// Settings saved by a newer LightCraft (a process number this build doesn't know) render with +/// this build's latest process, and a build that resolved the number to an older process +/// cached other pixels under the same settings hash: the persistent keys (thumbnails, the +/// loupe's view render, variants) name the process the settings render with, so those are +/// never served (review of 5a7016c8: a catalog saved with a newer process kept main's V2 thumbnails). +#[test] +fn persistent_keys_name_the_process_the_settings_render_with() { + use lightcraft_develop::ProcessVersion; + let mut s = session(); + let newer = DevelopSettings { process: ProcessVersion(ProcessVersion::LATEST.0 + 1), ..DevelopSettings::default() }; + s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(newer.clone()), label: "newer".into(), edited: None }).unwrap(); + let p = s.catalog.photo(PhotoId(1)).unwrap().clone(); + let unnamed = |kind: Option<&str>, size: u64| { + let mut h = Hasher128::new(); + h.str(&content_key(&p)); + if let Some(k) = kind { + h.str(k); + } + h.u64(newer.hash64()).u64(size).u64(RENDER_CACHE_VERSION).u64(crate::camera_profiles::cache_key()).finish() + }; + let named = |kind: Option<&str>, size: u64, process: u64| { + let mut h = Hasher128::new(); + h.str(&content_key(&p)); + if let Some(k) = kind { + h.str(k); + } + h.u64(newer.hash64()).u64(size).u64(RENDER_CACHE_VERSION).u64(process).u64(crate::camera_profiles::cache_key()).finish() + }; + let resolved = u64::from(lightcraft_develop::Process::LATEST.version().0); + let keys = [ + (s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1, None, 256), + (crate::Session::view_key(&p, true, 0), Some("view"), 1), + (crate::Session::variant_key(&p, &newer, 256, 0), Some("variant"), 256), + ]; + for (key, kind, size) in keys { + assert_ne!(key, unnamed(kind, size), "old builds did not name their resolved process"); + assert_eq!(key, named(kind, size, resolved), "the key names the process used for rendering"); + assert_ne!(key, named(kind, size, u64::from(newer.process.0)), "the saved future number is not the resolved process"); + } +} + +/// Photos on V1 and V2 keep the persistent keys builds before process V3 gave them (no process +/// in them), so their cached thumbnails, view renders and variants stay valid after upgrading +/// (review of 26cd2df1: every V1/V2 photo rendered again, and offline ones without smart +/// previews lost their thumbnails); V3 and later name their process. +#[test] +fn v1_and_v2_photos_keep_the_render_cache_keys_they_had() { + use lightcraft_develop::Process; + let mut s = session(); + for process in [Process::V1, Process::V2, Process::V3] { + let settings = DevelopSettings { process: process.version(), ..DevelopSettings::default() }; + s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(settings.clone()), label: "p".into(), edited: None }).unwrap(); + let p = s.catalog.photo(PhotoId(1)).unwrap().clone(); + let before_v3 = |kind: Option<&str>, size: u64| { + let mut h = Hasher128::new(); + h.str(&content_key(&p)); + if let Some(k) = kind { + h.str(k); + } + h.u64(settings.hash64()).u64(size).u64(RENDER_CACHE_VERSION).u64(crate::camera_profiles::cache_key()).finish() + }; + let keys = [ + s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1 == before_v3(None, 256), + crate::Session::view_key(&p, true, 0) == before_v3(Some("view"), 1), + crate::Session::variant_key(&p, &settings, 256, 0) == before_v3(Some("variant"), 256), + ]; + let old = process <= Process::V2; + assert_eq!(keys, [old; 3], "{process:?}: thumbnail, view and variant keys"); + } +} + #[test] fn hashes_match_uncached_keys_and_are_not_recomputed_for_sizes_metadata_or_before() { let mut s = session(); @@ -21,6 +92,7 @@ fn hashes_match_uncached_keys_and_are_not_recomputed_for_sizes_metadata_or_befor .u64(settings) .u64(b as u64) .u64(RENDER_CACHE_VERSION) + .u64(u64::from(p.develop.process.process().version().0)) .u64(crate::camera_profiles::cache_key()) .finish(); let job = s.thumb_job(p.id, edge).unwrap(); @@ -70,7 +142,7 @@ fn hash_cache_is_bounded_weak_and_shared_settings_remain_independent() { #[test] fn source_from_before_content_reload_is_not_accepted() { let mut s = session(); - s.media.file_loader = Some(Arc::new(|_, _| Ok((Rgb32f::new(8, 8), SourceInfo::default())))); + s.media.file_loader = Some(Arc::new(|_, _, _| Ok((Rgb32f::new(8, 8), SourceInfo::default())))); let old = s.thumb_job(PhotoId(1), 256).unwrap().run(); assert!(old.loaded.is_some()); s.catalog @@ -88,13 +160,51 @@ fn source_from_before_content_reload_is_not_accepted() { s.accept(&old); assert_eq!(s.media.source_usage().0, 0); } +/// A decode that started before the photo's database lens profile changed (a lens database arriving, looked up again +/// by `cmd::lens_refresh`, which drops the photo's sources) never puts its source back in the cache: the source's +/// colour was fitted through the old profile. +#[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())))); + 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() }; + s.catalog.apply(Op::SetEmbeddedLens { id: PhotoId(1), lens: Some(Box::new(lens)) }).unwrap(); + s.media.forget(PhotoId(1)); + s.accept(&old); + assert_eq!(s.media.source_usage().0, 0, "the old decode is dropped"); + // a decode made with the new profile is kept + let new = s.thumb_job(PhotoId(1), 256).unwrap().run(); + s.accept(&new); + assert_ne!(s.media.source_usage().0, 0); +} +/// The loupe's hover preview (a preset or profile under the pointer) is cached by its key, so a database lens +/// profile looked up again gives it a new key and the hover renders afresh instead of showing the old correction. +#[test] +fn a_hover_preview_key_follows_the_lens_profile() { + let mut s = session(); + let settings = s.catalog.photo(PhotoId(1)).unwrap().develop.clone(); + let before = s.preview_job(PhotoId(1), 640, 480, true, &settings).unwrap().key; + let lens = lightcraft_develop::EmbeddedLens { source: lightcraft_develop::LensSource::Database, ..Default::default() }; + s.catalog.apply(Op::SetEmbeddedLens { id: PhotoId(1), lens: Some(Box::new(lens)) }).unwrap(); + let after = s.preview_job(PhotoId(1), 640, 480, true, &settings).unwrap().key; + assert_ne!(before, after); + // one database profile looked up again as another (a newer database): the key follows the profile's contents, + // not only whether there is one + let vignette = lightcraft_develop::EmbeddedVignette { k: [-0.3, 0.0, 0.0, 0.0, 0.0], radius: 1.0, ..Default::default() }; + let other = lightcraft_develop::EmbeddedLens { source: lightcraft_develop::LensSource::Database, vignette: Some(vignette), ..Default::default() }; + s.catalog.apply(Op::SetEmbeddedLens { id: PhotoId(1), lens: Some(Box::new(other)) }).unwrap(); + let again = s.preview_job(PhotoId(1), 640, 480, true, &settings).unwrap().key; + assert_ne!(after, again, "a different database profile"); +} /// A panic while rendering (here in the decoder) used to end the pool's worker thread without /// an answer, so the view that asked showed "Rendering…" forever. It is the job's failure now, /// for renders and for stand-ins, answering the request it came from. #[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/rename/fs.rs b/crates/engine/src/rename/fs.rs index 71de1a7843..30b6a3e30c 100644 --- a/crates/engine/src/rename/fs.rs +++ b/crates/engine/src/rename/fs.rs @@ -46,6 +46,9 @@ pub(crate) trait MoveFs { fn packet_version(&self, path: &Path) -> std::io::Result { use std::io::Read; let mut file = std::fs::File::open(path)?; + if !file.metadata()?.is_file() { + return Err(std::io::Error::other(format!("{} is not a regular file", path.display()))); + } let mut hash = lightcraft_preview::Hasher128::new(); let mut len = 0u64; let mut buffer = [0u8; 16 * 1024]; @@ -141,8 +144,14 @@ impl MoveFs for RealFs { .map(|k| b.with_file_name(format!(".{name}.lc-partial-{}-{k}", std::process::id()))) .find(|p| !self.exists(p)) .ok_or_else(|| std::io::Error::other(format!("no free temporary name beside {}", b.display())))?; + // a sidecar found beside the photo by its name is copied only when it is a plain file: a + // link there would have its target's contents copied into a new, readable file + let checked = std::fs::symlink_metadata(a)?; + if !checked.is_file() { + return Err(std::io::Error::other(format!("{} is not a regular file", a.display()))); + } let copied = (|| { - let mut from = std::fs::File::open(a)?; + let mut from = open_regular(a, &checked)?; let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(&partial)?; std::io::copy(&mut from, &mut f)?; f.sync_all() @@ -163,6 +172,33 @@ impl MoveFs for RealFs { } } +/// Opens `a` for reading and checks the open handle is the regular file `checked` (the +/// `symlink_metadata` of `a` taken before): the path check alone can be outrun by a swap for a +/// link, whose target the open would follow. +fn open_regular(a: &Path, checked: &std::fs::Metadata) -> std::io::Result { + let mut options = std::fs::OpenOptions::new(); + options.read(true); + // FILE_FLAG_OPEN_REPARSE_POINT: a symbolic link is opened itself, and then refused below + #[cfg(windows)] + std::os::windows::fs::OpenOptionsExt::custom_flags(&mut options, 0x0020_0000); + let file = options.open(a)?; + let opened = file.metadata()?; + #[cfg(unix)] + let same = { + use std::os::unix::fs::MetadataExt; + (opened.dev(), opened.ino()) == (checked.dev(), checked.ino()) + }; + #[cfg(not(unix))] + let same = { + let _ = checked; + true + }; + if !opened.is_file() || !same { + return Err(std::io::Error::other(format!("{} is not a regular file", a.display()))); + } + Ok(file) +} + /// Move `a` to `b` on another volume: copy (never replacing), compare the copy with the original /// byte for byte, and only then remove the original. A copy that doesn't match is removed. fn move_across_volumes(fs: &RealFs, a: &Path, b: &Path) -> std::io::Result<()> { @@ -240,3 +276,25 @@ pub(super) fn move_one(fs: &dyn MoveFs, a: &Path, b: &Path) -> std::io::Result<( Err(e2) => std::io::Error::other(format!("{e}; it could not be given its old name back either ({e2}): it is now {}", tmp.display())), }) } + +#[cfg(all(test, unix))] +mod open_regular_tests { + use super::open_regular; + + #[test] + fn a_link_swapped_in_after_the_check_is_not_followed() { + let dir = std::env::temp_dir().join(format!("lightcraft-open-regular-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (file, other, link) = (dir.join("a.xmp"), dir.join("secret"), dir.join("link.xmp")); + std::fs::write(&file, b"x").unwrap(); + std::fs::write(&other, b"secret").unwrap(); + let checked = std::fs::symlink_metadata(&file).unwrap(); + assert!(open_regular(&file, &checked).is_ok()); + // the name now holds a link to another file: the handle is not the one checked + std::fs::remove_file(&file).unwrap(); + std::os::unix::fs::symlink(&other, &link).unwrap(); + std::fs::rename(&link, &file).unwrap(); + assert!(open_regular(&file, &checked).is_err(), "the link's target must not be opened"); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/engine/src/rename/plan.rs b/crates/engine/src/rename/plan.rs index 4c9620bf13..924fc9a95e 100644 --- a/crates/engine/src/rename/plan.rs +++ b/crates/engine/src/rename/plan.rs @@ -27,7 +27,7 @@ pub fn plan_rename_photos(photos: &[std::sync::Arc], template: &str, star /// Plan renaming `photos`: `exists` says whether something answers to a path, `same_file` whether /// two spellings name one file (see [`MoveFs`]). -fn plan_rename_core( +pub(super) fn plan_rename_core( photos: &[std::sync::Arc], template: &str, start: usize, @@ -35,6 +35,9 @@ fn plan_rename_core( same_file: &dyn Fn(&Path, &Path) -> bool, ) -> Vec { let mut taken: HashSet = HashSet::new(); // lower-case target paths/names claimed in this batch + // Per first-choice target: how many leading suffixes are all claimed in this batch (`taken` only grows), so the + // next photo with the same first choice starts after them instead of rebuilding each one. + let mut claimed_prefix: std::collections::HashMap = std::collections::HashMap::new(); let mut out = Vec::new(); for (i, p) in photos.iter().enumerate() { let seq = start.saturating_add(i); @@ -53,7 +56,9 @@ fn plan_rename_core( let (to, to_path) = match &p.source { Source::File { path } => { let dir = Path::new(path).parent().map(Path::to_path_buf).unwrap_or_default(); - let mut k = 0; + let base = folded_path(&dir.join(&want).to_string_lossy()); + let mut k = claimed_prefix.get(&base).copied().unwrap_or(0); + let mut all_taken = true; loop { let name = candidate(k); let tp = dir.join(&name).to_string_lossy().to_string(); @@ -64,18 +69,25 @@ fn plan_rename_core( let same = from == to || (key == folded_path(path) && exists(to) && same_file(from, to)); // free: not claimed in this batch and not on disk (unless it is this very file). // A file this batch moves away still counts as taken: simple and safe. - if !taken.contains(&key) && (same || !exists(to)) { + let claimed = taken.contains(&key); + if !claimed && (same || !exists(to)) { taken.insert(key); + if all_taken { + claimed_prefix.insert(base, k + 1); + } break (name, Some(tp)); } + all_taken &= claimed; k += 1; } } Source::Demo { .. } => { - let mut k = 0; + let base = format!("demo:{}", want.to_lowercase()); + let mut k = claimed_prefix.get(&base).copied().unwrap_or(0); loop { let name = candidate(k); if taken.insert(format!("demo:{}", name.to_lowercase())) { + claimed_prefix.insert(base, k + 1); // (every candidate before it was claimed: nothing but `taken` rejects a demo name) break (name, None); } k += 1; diff --git a/crates/engine/src/rename/tests.rs b/crates/engine/src/rename/tests.rs index d8ef8de10d..fcad01d274 100644 --- a/crates/engine/src/rename/tests.rs +++ b/crates/engine/src/rename/tests.rs @@ -588,3 +588,37 @@ fn number_folder_and_metadata_tokens() { // a bare {seq} is padded to the caller's width assert_eq!(expand_tokens("{seq}|{seq:2}", &p, 7, 3), "007|07"); } + +/// Many photos wanting one name take its suffixes in order without each starting over at the bare name. +#[test] +fn photos_sharing_a_target_name_do_not_rescan_the_suffixes_already_claimed() { + let photos: Vec> = (0..300) + .map(|i| { + std::sync::Arc::new(Photo::new( + PhotoId(i + 1), + Source::File { path: format!("/lib/src{i}.jpg") }, + &format!("src{i}.jpg"), + "JPEG", + 0, + 0, + "2024-01-01T00:00:00Z", + )) + }) + .collect(); + let checks = std::cell::Cell::new(0usize); + let plans = plan::plan_rename_core( + &photos, + "same", + 1, + &|_| { + checks.set(checks.get() + 1); + false + }, + &|_, _| false, + ); + let mut names: Vec<&str> = plans.iter().map(|p| p.to.as_str()).collect(); + names.sort_unstable(); + names.dedup(); + assert_eq!(names.len(), 300); + assert!(checks.get() <= 3 * 300, "{} disk checks", checks.get()); +} diff --git a/crates/engine/src/segment.rs b/crates/engine/src/segment.rs index b69a6dca27..53ee4a5f83 100644 --- a/crates/engine/src/segment.rs +++ b/crates/engine/src/segment.rs @@ -376,12 +376,23 @@ fn clicks_of(include: &[Point], exclude: &[Point]) -> Vec { } impl Session { - /// The key and settings of photo `id` as the model sees it: its look without masks, uncropped. + /// The key and settings of photo `id` as the model sees it: its look without masks, uncropped + /// and unflipped, and without lens corrections, Upright and Transform. Mask coordinates + /// (clicks, stored selections) live on the photo before those (`Mask::on_photo`), so a + /// selection stays on its content when they change, and changing them doesn't ask again. #[cfg_attr(not(feature = "sam"), allow(dead_code))] - fn segment_key(&self, id: PhotoId) -> Option<(u64, lightcraft_develop::DevelopSettings)> { + pub(crate) fn segment_key(&self, id: PhotoId) -> Option<(u64, lightcraft_develop::DevelopSettings)> { let p = self.catalog.photo(id)?; let mut d = (*p.develop).clone(); d.masks.clear(); + // (the crop doesn't show in the uncropped input: it doesn't ask again either) + d.crop = Default::default(); + d.geometry = Default::default(); + d.optics.lens_profile = false; + d.optics.distortion = 0.0; + d.optics.remove_ca = false; + d.optics.ca_red = 0.0; + d.optics.ca_blue = 0.0; let content = crate::media::content_key(p); let mut h = mix(0xcbf2_9ce4_8422_2325, d.hash64()); h = mix(h, id.0); @@ -410,6 +421,13 @@ impl Session { region: Option<[f64; 4]>, ) -> Result { let dir = self.segmenter.model_dir()?; + // old masks go onto the photo first: the selection that comes back is in its coordinates + if let Some(cur) = self.develop_of(id).filter(|d| d.masks.iter().any(|m| !m.on_photo)) { + let mut on = (*cur).clone(); + self.attach_masks(id, &cur, &mut on); + self.apply_silent(lightcraft_catalog::Op::SetDevelop { id, settings: std::sync::Arc::new(on), label: "Masks".into(), edited: None }) + .map_err(|e| e.to_string())?; + } let (key, mut d) = self.segment_key(id).ok_or("no such photo")?; let p = self.catalog.photo(id).ok_or("no such photo")?.clone(); let missing = match &p.source { diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 9f3e518a49..252dd911a6 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -455,6 +455,11 @@ fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> { /// Copy `path` to a new `.bak-` (`-1`, `-2`… if taken; never overwriting). fn backup(path: &Path, stamp: &str) -> std::io::Result { use std::io::Write; + // only a plain file is copied aside: a link under the sidecar's name would have its target's + // contents copied into a new, readable file + if !std::fs::symlink_metadata(path)?.is_file() { + return Err(std::io::Error::other(format!("{} is not a regular file", path.display()))); + } let bytes = std::fs::read(path)?; let stamp: String = stamp.chars().filter(char::is_ascii_alphanumeric).collect(); let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); diff --git a/crates/engine/src/slide_title.rs b/crates/engine/src/slide_title.rs index 5885463b1c..0acda876d1 100644 --- a/crates/engine/src/slide_title.rs +++ b/crates/engine/src/slide_title.rs @@ -363,6 +363,7 @@ impl TitleCompose { quick: None, display: None, gpu_fallback: None, + frame: None, } } } diff --git a/crates/engine/src/slideshow_export.rs b/crates/engine/src/slideshow_export.rs index e91c1ed346..94a7bc7dd6 100644 --- a/crates/engine/src/slideshow_export.rs +++ b/crates/engine/src/slideshow_export.rs @@ -389,7 +389,10 @@ impl PartFile { let mut name = target.file_name().ok_or_else(|| format!("{}: not a file name", target.display()))?.to_os_string(); name.push(".part"); let part = target.with_file_name(name); - let f = std::fs::File::create(&part).map_err(|e| format!("{}: {e}", part.display()))?; + // an entry already under the staging name (a leftover, or a link planted to point the + // encoder's bytes at another file) is removed, never opened and written through + let _ = std::fs::remove_file(&part); + let f = std::fs::OpenOptions::new().write(true).create_new(true).open(&part).map_err(|e| format!("{}: {e}", part.display()))?; Ok((PartFile { part, target: target.to_path_buf(), done: false }, f)) } diff --git a/crates/engine/src/smart.rs b/crates/engine/src/smart.rs index b936830f83..77f78bd299 100644 --- a/crates/engine/src/smart.rs +++ b/crates/engine/src/smart.rs @@ -268,7 +268,15 @@ pub fn check_writable(dir: &Path) -> Result<(), String> { std::fs::create_dir(dir).map_err(|e| format!("can't create {}: {e}", dir.display()))?; } let probe = dir.join(format!(".lightcraft-write-test-{}", std::process::id())); - std::fs::write(&probe, b"x").map_err(|e| format!("{} is not writable (is the drive full or read-only?): {e}", dir.display()))?; + // the probe is a new entry of ours: an existing one (a link planted under the name would be + // written through) is removed first, never opened + let _ = std::fs::remove_file(&probe); + std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&probe) + .and_then(|mut f| std::io::Write::write_all(&mut f, b"x")) + .map_err(|e| format!("{} is not writable (is the drive full or read-only?): {e}", dir.display()))?; let _ = std::fs::remove_file(&probe); Ok(()) } @@ -494,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/smart/tests.rs b/crates/engine/src/smart/tests.rs index e4bbd548cd..b1eeefc221 100644 --- a/crates/engine/src/smart/tests.rs +++ b/crates/engine/src/smart/tests.rs @@ -18,6 +18,21 @@ fn writable_check_does_not_create_missing_parents() { let _ = std::fs::remove_dir_all(&base); } +#[cfg(unix)] +#[test] +fn writable_probe_never_writes_through_a_planted_link() { + let base = temp("probe-link"); + std::fs::create_dir_all(&base).unwrap(); + let victim = base.join("victim"); + std::fs::write(&victim, b"keep").unwrap(); + let probe = base.join(format!(".lightcraft-write-test-{}", std::process::id())); + std::os::unix::fs::symlink(&victim, &probe).unwrap(); + assert!(check_writable(&base).is_ok()); + assert_eq!(std::fs::read(&victim).unwrap(), b"keep"); + assert!(!probe.exists()); + let _ = std::fs::remove_dir_all(&base); +} + #[test] fn migrate_moves_leaves_or_discards() { let base = temp("migrate"); diff --git a/crates/engine/src/sync.rs b/crates/engine/src/sync.rs index 3e69a074e9..9bbbcbec18 100644 --- a/crates/engine/src/sync.rs +++ b/crates/engine/src/sync.rs @@ -334,8 +334,9 @@ fn match_moved( ) -> HashMap { // distinct missing files (a photo's virtual copies share its file), with what is known of them let mut files: Vec<(&str, Option<&Photo>)> = Vec::new(); + let mut seen_paths: std::collections::HashSet<&str> = std::collections::HashSet::new(); for m in missing { - if !files.iter().any(|(p, _)| *p == m.path) { + if seen_paths.insert(m.path.as_str()) { files.push((m.path.as_str(), labels.photo(PhotoId(m.id)).map(|p| &**p))); } } @@ -363,7 +364,8 @@ fn match_moved( } } let mut found: HashMap<(u64, u32, u32), Vec<&str>> = HashMap::new(); - for c in candidates.iter().filter(usable).filter(|c| !moved.values().any(|to| *to == c.path)) { + let taken: std::collections::HashSet<&str> = moved.values().map(String::as_str).collect(); + for c in candidates.iter().filter(usable).filter(|c| !taken.contains(c.path.as_str())) { if let Some(k) = key(c.file_size, c.width, c.height) { found.entry(k).or_default().push(c.path.as_str()); } 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 37b300dbfc..a22547ec4a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7,10 +7,13 @@ mod album_missing; mod album_order; mod album_remove; mod albums_local; +mod autosync_wb; mod color; mod constrain_crop; mod crop_angle; mod crop_aspect; +mod dcp; +mod dcp_corpus; mod denoise; mod export; mod face_models; @@ -29,10 +32,12 @@ mod ids_params; mod import; mod import_move; mod keyword_list; +mod lens_refresh; mod libops; mod library; mod lightroom_folder; mod mask_effects; +mod mask_geometry; mod merge; mod move_to_share; mod organize; @@ -47,6 +52,8 @@ mod settings_files; mod shelved_folder; mod slide; mod slideshow_export; +#[cfg(not(target_arch = "wasm32"))] +mod slow_drive; mod spots; mod sync; mod view_follow; diff --git a/crates/engine/src/tests/autosync_wb.rs b/crates/engine/src/tests/autosync_wb.rs new file mode 100644 index 0000000000..1d05ddebf0 --- /dev/null +++ b/crates/engine/src/tests/autosync_wb.rs @@ -0,0 +1,189 @@ +//! LRC-DEV-AUTOSYNC (N-A3, test notes 2026-10-24 note 18): Auto Sync sets every selected photo to +//! the active photo's value, and where white balance is a mode or another scale, each photo applies +//! it to itself. As Shot gives each photo its own camera white, Auto each photo's own from its +//! pixels, a light preset its numbers. A typed or dragged Temp is the same number on each photo of +//! the same scale (the same Kelvin on raws edited in Kelvin; an old relative-scale value converted +//! first, never read as Kelvin), moves a photo of another scale (a JPEG beside a raw) by as much as +//! the active photo, and leaves each photo's own tint. + +use lightcraft_catalog::PhotoId; +use lightcraft_develop::{WbMode, WbScale, WhiteBalance}; +use serde_json::json; + +use crate::Session; + +/// Give photo `id` a decoded raw source (thumbnail and preview) with as-shot white `(temp, tint)`; +/// `legacy`: a camera whose settings without a scale were written on the relative scale; `warm` +/// tints its pixels, so Auto finds another white on each photo. +fn raw_as_shot(s: &mut Session, id: PhotoId, temp: f64, tint: f64, legacy: bool, warm: f32) { + use crate::media::SourceLevel; + let mut img = lightcraft_raster::Rgb32f::new(48, 32); + for (i, px) in img.data.iter_mut().enumerate() { + let v = 0.1 + 0.6 * ((i % 48) as f32 / 48.0); + *px = [v * warm, v, v / warm]; + } + let img = std::sync::Arc::new(img); + let info = + lightcraft_pipeline::SourceInfo { raw: true, legacy_relative_wb: legacy, as_shot_temp: temp, as_shot_tint: tint, ..Default::default() }; + s.media.insert_with_info(id, SourceLevel::Thumb, img.clone(), info.clone()); + s.media.insert_with_info(id, SourceLevel::Preview, img, info); +} + +/// The white balance photo `id` renders with (Kelvin, tint). +fn wb(s: &Session, id: PhotoId) -> (f64, f64) { + lightcraft_pipeline::local::effective_wb(&s.source_info(id), &s.develop_of(id).unwrap()) +} + +fn close(x: (f64, f64), y: (f64, f64)) -> bool { + (x.0 - y.0).abs() < 1.0 && (x.1 - y.1).abs() < 0.5 +} + +/// Three demo photos (a active, b, c) selected, Auto Sync on, each a raw of another as-shot white; +/// c still holds an old relative-scale white (7000 there meant "a little warmer than as shot"). +fn three_raws() -> (Session, [PhotoId; 3]) { + let mut s = Session::with_demo(); + let ids: Vec = s.visible_cloned().into_iter().take(3).collect(); + let (a, b, c) = (ids[0], ids[1], ids[2]); + raw_as_shot(&mut s, a, 5200.0, 4.0, false, 1.0); + raw_as_shot(&mut s, b, 3300.0, -12.0, false, 1.4); + raw_as_shot(&mut s, c, 6100.0, 8.0, true, 0.7); + let mut d = (*s.develop_of(c).unwrap()).clone(); + d.wb = WhiteBalance { mode: WbMode::Custom, temp: 7000.0, tint: 0.0, scale: WbScale::Legacy }; + s.catalog.apply(lightcraft_catalog::Op::SetDevelop { id: c, settings: std::sync::Arc::new(d), label: "x".into(), edited: None }).unwrap(); + s.execute("library.select", &json!({"ids": [a.0, b.0, c.0], "active": a.0})).unwrap(); + s.execute("develop.autoSync", &json!({"on": true})).unwrap(); + (s, [a, b, c]) +} + +/// As Shot and Auto are modes: each photo gets its own camera white, or its own Auto white worked +/// out on its own pixels, never the active photo's numbers. A light preset gives its numbers. +#[test] +fn auto_sync_white_balance_modes_apply_to_each_photo() { + let (mut s, [a, b, c]) = three_raws(); + // As Shot: each photo's own camera white + s.execute("develop.wb", &json!({"mode": "asShot"})).unwrap(); + for (id, own) in [(a, (5200.0, 4.0)), (b, (3300.0, -12.0)), (c, (6100.0, 8.0))] { + assert!(close(wb(&s, id), own), "As Shot on photo {}: {:?}, its own is {own:?}", id.0, wb(&s, id)); + assert_eq!(s.develop_of(id).unwrap().wb.mode, WbMode::AsShot); + } + // a light preset: its numbers on every raw + s.execute("develop.wb", &json!({"mode": "tungsten"})).unwrap(); + for id in [a, b, c] { + assert!(close(wb(&s, id), (2850.0, 0.0)), "Tungsten on photo {}: {:?}", id.0, wb(&s, id)); + } + // Auto: each photo's own, from its own pixels + s.execute("develop.wb", &json!({"mode": "auto"})).unwrap(); + for id in [b, c] { + let src = s.source_now(id, crate::media::SourceLevel::Thumb).unwrap(); + let own = lightcraft_pipeline::auto::auto_wb(&src, &s.source_info(id)); + assert!(close(wb(&s, id), own), "Auto on photo {}: {:?}, its own Auto is {own:?}", id.0, wb(&s, id)); + assert_eq!(s.develop_of(id).unwrap().wb.mode, WbMode::Auto); + } + assert!(!close(wb(&s, a), wb(&s, b)), "not the active photo's Auto copied over: {:?}", wb(&s, a)); + // one undo step puts every photo back + s.execute("edit.undo", &json!({})).unwrap(); + for id in [a, b, c] { + assert!(close(wb(&s, id), (2850.0, 0.0)), "undo, photo {}: {:?}", id.0, wb(&s, id)); + } +} + +/// A Temp typed or dragged from As Shot: the same Kelvin on every raw, each keeping its own tint; +/// the photo holding an old relative-scale value gets the Kelvin too, never read on that scale. +#[test] +fn auto_sync_temp_is_the_same_kelvin_and_keeps_each_photos_tint() { + let (mut s, [a, b, c]) = three_raws(); + s.execute("develop.wb", &json!({"mode": "asShot"})).unwrap(); + // typed + s.execute("develop.set", &json!({"control": "wb.temp", "value": 5600.0})).unwrap(); + assert!(close(wb(&s, a), (5600.0, 4.0)), "a: {:?}", wb(&s, a)); + assert!(close(wb(&s, b), (5600.0, -12.0)), "b keeps its own tint: {:?}", wb(&s, b)); + assert!(close(wb(&s, c), (5600.0, 8.0)), "c keeps its own tint: {:?}", wb(&s, c)); + // a drag, synced on release + s.execute("develop.beginInteraction", &json!({"label": "Temp"})).unwrap(); + for v in [5000.0, 4600.0] { + s.execute("develop.set", &json!({"control": "wb.temp", "value": v})).unwrap(); + } + s.execute("develop.endInteraction", &json!({})).unwrap(); + assert!(close(wb(&s, b), (4600.0, -12.0)) && close(wb(&s, c), (4600.0, 8.0)), "b {:?} c {:?}", wb(&s, b), wb(&s, c)); + // a Tint move: the same tint on every photo, each keeping its Kelvin (all at 4600 here) + s.execute("develop.set", &json!({"control": "wb.tint", "value": 10.0})).unwrap(); + for id in [a, b, c] { + assert!(close(wb(&s, id), (4600.0, 10.0)), "photo {}: {:?}", id.0, wb(&s, id)); + } +} + +/// A photo still holding an old relative-scale value: a Temp synced from a photo in Kelvin reaches +/// it as Kelvin, never as a number on the relative scale (where 6500 is as shot), which turned +/// photos blue (test notes 2026-10-15). Main already got this right; the guard keeps it so. +#[test] +fn auto_sync_temp_never_lands_on_an_old_relative_scale() { + let (mut s, [_, _, c]) = three_raws(); + s.execute("develop.set", &json!({"control": "wb.temp", "value": 5600.0})).unwrap(); + assert!((wb(&s, c).0 - 5600.0).abs() < 1.0, "c renders at {:?}", wb(&s, c)); + assert_eq!(s.develop_of(c).unwrap().wb.scale, WbScale::Kelvin); +} + +/// A JPEG selected with a raw has no "same" Kelvin (its white balance is relative to its own +/// colours): it moves by as much as the raw did. Before, it got the raw's Kelvin number, read on +/// its own scale. +#[test] +fn auto_sync_temp_moves_a_jpeg_by_as_much_as_the_raw() { + let mut s = Session::with_demo(); + let ids: Vec = s.visible_cloned().into_iter().take(2).collect(); + let (a, b) = (ids[0], ids[1]); + raw_as_shot(&mut s, a, 5200.0, 4.0, false, 1.0); + // b: a JPEG (no raw white balance scale: 6500 / 0 = its own colours) + let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::filled(48, 32, [0.4, 0.4, 0.4])); + let info = lightcraft_pipeline::SourceInfo { raw: false, as_shot_temp: 6500.0, as_shot_tint: 0.0, ..Default::default() }; + s.media.insert_with_info(b, crate::media::SourceLevel::Thumb, img.clone(), info.clone()); + s.media.insert_with_info(b, crate::media::SourceLevel::Preview, img, info); + assert!(!s.source_info(b).raw); + s.execute("library.select", &json!({"ids": [a.0, b.0], "active": a.0})).unwrap(); + s.execute("develop.autoSync", &json!({"on": true})).unwrap(); + s.execute("develop.wb", &json!({"mode": "asShot"})).unwrap(); + let before = wb(&s, b); + s.execute("develop.set", &json!({"control": "wb.temp", "value": 5600.0})).unwrap(); + assert!(close(wb(&s, b), (before.0 + 400.0, before.1)), "the JPEG: {:?}, was {before:?}", wb(&s, b)); +} + +/// The other photos' pixels for Auto are read together (in parallel, review of #3571): in the +/// order asked, each photo its own, and a photo the library doesn't have is an error, not a panic. +#[test] +fn sources_for_auto_come_back_in_order_and_per_photo() { + let (mut s, [a, b, c]) = three_raws(); + let want: Vec<_> = [b, c, a].iter().map(|&x| s.source_now(x, crate::media::SourceLevel::Thumb).unwrap()).collect(); + let got = s.sources_now(&[b, PhotoId(u64::MAX), c, a], crate::media::SourceLevel::Thumb); + assert_eq!(got.iter().map(|(x, _)| *x).collect::>(), vec![b, PhotoId(u64::MAX), c, a]); + assert!(got[1].1.is_err()); + for (i, k) in [0, 2, 3].into_iter().enumerate() { + let (img, info) = got[k].1.as_ref().unwrap(); + assert!(std::sync::Arc::ptr_eq(img, &want[i]), "photo {k}"); + // the facts its decoder gave (the as-shot whites differ per photo here) + assert_eq!(info.as_shot_temp, s.source_info(got[k].0).as_shot_temp, "photo {k}"); + } + assert_eq!(got[0].1.as_ref().unwrap().1.as_shot_temp, 3300.0, "b's own"); +} + +/// Review of #3585: a light preset given a tint of its own on a JPEG (where the stored numbers are +/// what renders) carries that tint to the other photos, as a Custom white balance would, not the +/// preset's tint. +#[test] +fn a_preset_with_its_own_tint_on_a_jpeg_carries_that_tint() { + let mut s = Session::with_demo(); + let ids: Vec = s.visible_cloned().into_iter().take(2).collect(); + let (a, b) = (ids[0], ids[1]); + let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::filled(48, 32, [0.4, 0.4, 0.4])); + let info = lightcraft_pipeline::SourceInfo { raw: false, as_shot_temp: 6500.0, as_shot_tint: 0.0, ..Default::default() }; + for id in [a, b] { + s.media.insert_with_info(id, crate::media::SourceLevel::Thumb, img.clone(), info.clone()); + s.media.insert_with_info(id, crate::media::SourceLevel::Preview, img.clone(), info.clone()); + } + s.execute("library.select", &json!({"ids": [a.0, b.0], "active": a.0})).unwrap(); + s.execute("develop.autoSync", &json!({"on": true})).unwrap(); + s.execute("develop.wb", &json!({"mode": "daylight", "tint": 30.0})).unwrap(); + assert!(close(wb(&s, a), (6500.0, 30.0)), "a: {:?}", wb(&s, a)); + assert!(close(wb(&s, b), wb(&s, a)), "b renders a's numbers: {:?}", wb(&s, b)); + // a plain preset still gives the preset's numbers + s.execute("develop.wb", &json!({"mode": "shade"})).unwrap(); + assert!(close(wb(&s, b), (6500.0 * 7500.0 / 5500.0, 10.0)), "b: {:?}", wb(&s, b)); +} diff --git a/crates/engine/src/tests/dcp.rs b/crates/engine/src/tests/dcp.rs new file mode 100644 index 0000000000..87f926f591 --- /dev/null +++ b/crates/engine/src/tests/dcp.rs @@ -0,0 +1,563 @@ +//! Imported camera profiles (`.dcp`): import, choosing one for a raw photo, decoding with it, the +//! source cache, persistence and deletion. Profiles are built in memory (no profile file is committed). + +use std::path::PathBuf; + +use lightcraft_catalog::PhotoId; +use lightcraft_raw::dcp::{DcpProfile, write_dcp}; +use lightcraft_raw::{ColorData, Mat3}; +use serde_json::json; + +use crate::Session; +use crate::media::SourceRef; + +fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lc-dcp-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// A profile whose matrix swaps the camera's red and blue (our own numbers): photos developed with it +/// come out with red and blue exchanged, which is easy to see in a test. +fn swapping_profile(name: &str) -> DcpProfile { + let m = Mat3([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]); + let xyz_to_cam = m.mul(&Mat3([[3.2406, -1.5372, -0.4986], [-0.9689, 1.8758, 0.0415], [0.0557, -0.2040, 1.0570]])); + DcpProfile { + name: name.into(), + camera_model: "LightCraft Test Camera".into(), + color: ColorData { illuminant: [21, 0], color_matrix: [Some(xyz_to_cam), None], ..Default::default() }, + } +} + +fn mean_rgb(img: &lightcraft_raster::Rgb32f) -> [f32; 3] { + let n = img.data.len().max(1) as f32; + let s = img.data.iter().fold([0.0f32; 3], |a, p| [a[0] + p[0], a[1] + p[1], a[2] + p[2]]); + [s[0] / n, s[1] / n, s[2] / n] +} + +#[test] +fn a_camera_profile_replaces_the_raw_colour_model_when_decoding() { + let dng = crate::tests_xmp::synthetic_dng_with(None, Default::default()); + let (plain, plain_info) = crate::files::load_bytes(&dng, 64).unwrap(); + let p = swapping_profile("Swap"); + let (with, info) = crate::files::load_bytes_with(&dng, 64, Some(&p)).unwrap(); + let (a, b) = (mean_rgb(&plain), mean_rgb(&with)); + assert!((a[0] - b[0]).abs() > 1e-3 || (a[2] - b[2]).abs() > 1e-3, "the profile changes the colour: {a:?} vs {b:?}"); + // white balance at render time works from the profile's matrices + let tags = &info.camera_color.as_ref().expect("a matrix colour model").tags; + assert_eq!(tags.color_matrix, p.color.color_matrix); + assert_ne!(plain_info.camera_color.as_ref().map(|c| c.tags.color_matrix), Some(p.color.color_matrix)); +} + +#[test] +fn a_profile_without_a_tone_curve_keeps_the_photos_contrast() { + use lightcraft_raw::profile::ToneCurve; + // a DNG with a tone curve of its own (our numbers: 18 % grey → 30 %) + let plain = crate::tests_xmp::synthetic_dng_with(None, Default::default()); + let mut raw = lightcraft_raw::decode(&plain).unwrap(); + raw.color.profile.tone_curve = ToneCurve::from_tag(&[0.0, 0.0, 0.18, 0.3, 1.0, 1.0]); + let dng = lightcraft_raw::write_dng(&raw, &Default::default()).unwrap(); + // a chart-style profile (no curve) keeps the file's curve + let (_, info) = crate::files::load_bytes_with(&dng, 64, Some(&swapping_profile("Swap"))).unwrap(); + let tone = info.camera_tone.expect("the file's tone curve stays"); + assert!((tone.apply(0.18) - 0.3).abs() < 0.01, "{}", tone.apply(0.18)); + // a profile with a curve of its own uses that one (18 % → 45 %) + let mut curved = swapping_profile("Curved"); + curved.color.profile.tone_curve = ToneCurve::from_tag(&[0.0, 0.0, 0.18, 0.45, 1.0, 1.0]); + let (_, info) = crate::files::load_bytes_with(&dng, 64, Some(&curved)).unwrap(); + let tone = info.camera_tone.expect("the profile's tone curve"); + assert!((tone.apply(0.18) - 0.45).abs() < 0.01, "{}", tone.apply(0.18)); +} + +#[test] +fn import_choose_cache_persist_and_delete() { + let dir = temp_dir("session"); + let (lib, files) = (dir.join("lib"), dir.join("files")); + std::fs::create_dir_all(files.join("profiles")).unwrap(); + let raw = files.join("IMG_0001.dng"); + std::fs::write(&raw, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); + std::fs::write(files.join("profiles").join("Swap.dcp"), write_dcp(&swapping_profile("Swap")).unwrap()).unwrap(); + std::fs::write(files.join("profiles").join("Broken.dcp"), b"IIRC\x08\0\0\0junk").unwrap(); + let id; + let dcp_id; + { + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let r = s.execute("library.import", &json!({"paths": [raw.to_string_lossy()]})).unwrap(); + id = PhotoId(r["imported"][0].as_u64().unwrap()); + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + // a folder: the good profile comes in, the broken one is reported + let r = s.execute("profile.import", &json!({"paths": [files.join("profiles").to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"].as_array().unwrap().len(), 1, "{r}"); + assert_eq!(r["failed"].as_array().unwrap().len(), 1, "{r}"); + dcp_id = r["imported"][0]["id"].as_str().unwrap().to_string(); + assert!(dcp_id.starts_with("dcp:")); + assert_eq!(r["imported"][0]["cameraModel"], "LightCraft Test Camera"); + // importing it again adds nothing + let again = s.execute("profile.import", &json!({"paths": [files.join("profiles").join("Swap.dcp").to_string_lossy()]})).unwrap(); + assert_eq!(again["imported"][0]["existing"], true); + // a single .dcp file is a camera profile only, not also a LUT that "couldn't be read" + assert_eq!(again["failed"], json!([]), "{again}"); + assert_eq!(s.dcp_profiles.len(), 1); + // the library keeps its own copy + assert!(std::path::Path::new(&s.dcp_profiles[0].file).starts_with(&lib)); + // listed in the profile menu under Camera Profiles + let menu = s.profile_menu(); + let group = menu["groups"].as_array().unwrap().iter().find(|g| g["name"] == "Camera Profiles").expect("a Camera Profiles group"); + assert_eq!(group["profiles"][0]["id"], dcp_id.as_str()); + // develop the photo with it: a decode made without it doesn't stand in + let before = s.render_job(id, 48, 48, false, true).unwrap().run(); + let loaded = before.loaded.clone().expect("decoded from the file"); + assert!(loaded.camera_profile.is_none()); + s.media.insert(id, before.level, loaded.image.clone()); + assert!(matches!(s.render_job(id, 48, 48, false, true).unwrap().source, SourceRef::Loaded(_)), "cached while nothing changed"); + s.execute("develop.profile", &json!({"id": dcp_id})).unwrap(); + let job = s.render_job(id, 48, 48, false, true).unwrap(); + match &job.source { + SourceRef::File { camera_profile: Some((pid, _)), .. } => assert!(pid.starts_with(&format!("{dcp_id}#")), "{pid}"), + _ => panic!("the photo is decoded again with its camera profile"), + } + let after = job.run(); + assert_eq!( + after.loaded.as_ref().and_then(|l| l.camera_profile.clone()), + s.media.camera_profile_of(s.catalog.photo(id).unwrap()).map(|c| c.0) + ); + assert!(after.rendered.is_ok()); + assert_ne!(mean_rgb(&before.loaded.unwrap().image), mean_rgb(&after.loaded.unwrap().image)); + s.persist().unwrap(); + s.close_library().unwrap(); + } + // reopened: the profile is there and decodes again + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + assert_eq!(s.dcp_profiles.len(), 1); + assert!(s.media.camera_profiles.contains_key(&dcp_id)); + assert_eq!(s.catalog.photo(id).unwrap().develop.profile.id, dcp_id); + assert_eq!(s.profile_info(&dcp_id).map(|(_, g)| g), Some("Camera Profiles")); + // deleted: photos using it develop with their file's own colour, the library's copy goes + let file = s.dcp_profiles[0].file.clone(); + s.execute("profile.deleteImported", &json!({"id": dcp_id})).unwrap(); + assert!(s.dcp_profiles.is_empty() && !std::path::Path::new(&file).exists()); + let p = s.catalog.photo(id).unwrap().clone(); + assert!(s.media.camera_profile_of(&p).is_none()); + assert!(s.execute("develop.profile", &json!({"id": dcp_id})).is_err(), "no longer a known profile"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Hovering a camera profile (the loupe's preview, the browser's thumbnails) develops the photo with +/// it, and hovering a built-in profile while one is applied develops without it. Before, both used +/// the photo's own decode: a camera profile's colour never showed in a hover. +#[test] +fn hover_previews_and_browser_thumbnails_decode_with_the_hovered_camera_profile() { + let dir = temp_dir("hover"); + let (lib, files) = (dir.join("lib"), dir.join("files")); + std::fs::create_dir_all(&files).unwrap(); + let raw = files.join("IMG_0002.dng"); + std::fs::write(&raw, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); + let dcp_file = files.join("Swap.dcp"); + std::fs::write(&dcp_file, write_dcp(&swapping_profile("Swap")).unwrap()).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let r = s.execute("library.import", &json!({"paths": [raw.to_string_lossy()]})).unwrap(); + let id = PhotoId(r["imported"][0].as_u64().unwrap()); + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + let dcp_id = + s.execute("profile.import", &json!({"paths": [dcp_file.to_string_lossy()]})).unwrap()["imported"][0]["id"].as_str().unwrap().to_string(); + let mean = |j: crate::media::RenderJob| { + let img = j.run().rendered.unwrap().image; + let n = img.data.len().max(1) as f64; + img.data.iter().fold([0.0f64; 3], |a, p| [a[0] + f64::from(p[0]) / n, a[1] + f64::from(p[1]) / n, a[2] + f64::from(p[2]) / n]) + }; + let differ = |a: [f64; 3], b: [f64; 3]| a.iter().zip(b).any(|(x, y)| (x - y).abs() > 2.0); + let close = |a: [f64; 3], b: [f64; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.6); + let own = (*s.develop_of(id).unwrap()).clone(); + let mut hovered = own.clone(); + hovered.profile.id = dcp_id.clone(); + let builtin = mean(s.render_job(id, 64, 64, false, true).unwrap()); + let hover = mean(s.preview_job(id, 64, 64, true, &hovered).unwrap()); + assert!(differ(hover, builtin), "the hover shows the camera profile: {hover:?} vs {builtin:?}"); + // the browser's thumbnail too, under its own cache key + let (va, vb) = (s.variant_job(id, &own, 64).unwrap(), s.variant_job(id, &hovered, 64).unwrap()); + assert_ne!(va.cache.as_ref().unwrap().1, vb.cache.as_ref().unwrap().1); + assert!(matches!(&vb.source, SourceRef::File { camera_profile: Some(_), .. }), "decoded with the camera profile"); + assert!(differ(mean(va), mean(vb))); + // selected: the same picture as the hover; hovering the built-in profile then: without it + s.execute("develop.profile", &json!({"id": dcp_id})).unwrap(); + let selected = mean(s.render_job(id, 64, 64, false, true).unwrap()); + assert!(close(hover, selected), "{hover:?} vs {selected:?}"); + let back = mean(s.preview_job(id, 64, 64, true, &own).unwrap()); + assert!(close(back, builtin), "{back:?} vs {builtin:?}"); + // the profile's file replaced under the same id: the hover's key changes with it, so the old picture isn't + // taken for current (CodeRabbit on #1063) + let before = s.preview_job(id, 64, 64, true, &hovered).unwrap().key; + s.media.camera_profiles.get_mut(&dcp_id).unwrap().fingerprint ^= 0x10; + assert_ne!(s.preview_job(id, 64, 64, true, &hovered).unwrap().key, before); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A library with one raw photo and the `Swap` profile imported from `files//Swap.dcp` and selected for it. +fn library_with_profile(dir: &std::path::Path) -> (Session, PhotoId, String) { + let (lib, files) = (dir.join("lib"), dir.join("files")); + std::fs::create_dir_all(files.join("a")).unwrap(); + let raw = files.join("IMG_0003.dng"); + std::fs::write(&raw, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); + std::fs::write(files.join("a").join("Swap.dcp"), write_dcp(&swapping_profile("Swap")).unwrap()).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let r = s.execute("library.import", &json!({"paths": [raw.to_string_lossy()]})).unwrap(); + let id = PhotoId(r["imported"][0].as_u64().unwrap()); + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + let r = s.execute("profile.import", &json!({"paths": [files.join("a").join("Swap.dcp").to_string_lossy()]})).unwrap(); + let dcp_id = r["imported"][0]["id"].as_str().unwrap().to_string(); + s.execute("develop.profile", &json!({"id": dcp_id})).unwrap(); + (s, id, dcp_id) +} + +/// The thumbnail, browser-thumbnail and loupe cache keys of photo `id` (as it is now), and its source tag. +fn render_keys(s: &mut Session, id: PhotoId) -> [lightcraft_preview::Hash128; 3] { + let settings = (*s.develop_of(id).unwrap()).clone(); + [ + s.thumb_job(id, 256).unwrap().cache.unwrap().1, + s.variant_job(id, &settings, 64).unwrap().cache.unwrap().1, + s.loupe_job(id, 200, 200, true).unwrap().view_cache.unwrap().1, + ] +} + +/// A camera profile deleted, or replaced by a different file under the same id, never has renders or decoded +/// sources made with the old one stand in: before, the cache keys followed only the profile id, which the photo keeps. +#[test] +fn a_deleted_or_replaced_camera_profile_never_reuses_renders_made_with_it() { + let dir = temp_dir("replace"); + let (mut s, id, dcp_id) = library_with_profile(&dir); + let with = render_keys(&mut s, id); + let level = s.render_job(id, 48, 48, false, true).unwrap().level; + let old_tag = s.media.camera_profile_of(s.catalog.photo(id).unwrap()).map(|c| c.0); + assert!(old_tag.is_some()); + // deleted: the photo keeps the id, renders without the profile, under other keys + s.execute("profile.deleteImported", &json!({"id": dcp_id})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().develop.profile.id, dcp_id); + let without = render_keys(&mut s, id); + for (a, b) in with.iter().zip(&without) { + assert_ne!(a, b, "a render made with the deleted profile would stand in"); + } + // another profile under the same file name gets the same id back, and other keys again + let other_dir = dir.join("files").join("b"); + std::fs::create_dir_all(&other_dir).unwrap(); + let mut other = swapping_profile("Swap"); + other.color.color_matrix = [Some(Mat3([[3.2406, -1.5372, -0.4986], [-0.9689, 1.8758, 0.0415], [0.0557, -0.2040, 1.0570]])), None]; + std::fs::write(other_dir.join("Swap.dcp"), write_dcp(&other).unwrap()).unwrap(); + let r = s.execute("profile.import", &json!({"paths": [other_dir.join("Swap.dcp").to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"][0]["id"], dcp_id.as_str(), "{r}"); + let replaced = render_keys(&mut s, id); + for ((a, b), c) in with.iter().zip(&without).zip(&replaced) { + assert_ne!(a, c, "a render made with the replaced profile would stand in"); + assert_ne!(b, c); + } + // nor does a source decoded with the old file + let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::new(4, 4)); + s.media.insert_source(id, level, crate::media::DecodedSource { camera_profile: old_tag, ..crate::media::DecodedSource::new(img, None) }); + assert!(!matches!(s.render_job(id, 48, 48, false, true).unwrap().source, SourceRef::Loaded(_)), "decoded again with the new file"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A grid thumbnail is cut from the photo's decoded preview only when that preview was decoded with the camera profile +/// the photo uses now; before, one made with another profile (or none) was fitted and cached under the new key. +#[test] +fn a_thumbnail_is_not_cut_from_a_preview_decoded_with_another_camera_profile() { + let dir = temp_dir("fit"); + let (mut s, id, _) = library_with_profile(&dir); + let p = (**s.catalog.photo(id).unwrap()).clone(); + let tag = s.media.camera_profile_of(&p).map(|c| c.0); + let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::new(1600, 1000)); + let preview = |camera_profile| crate::media::DecodedSource { camera_profile, ..crate::media::DecodedSource::new(img.clone(), None) }; + use crate::media::SourceLevel; + s.media.insert_source(id, SourceLevel::Preview, preview(None)); + assert!(!matches!(s.media.source_ref(&p, SourceLevel::Thumb), SourceRef::Fit { .. }), "decoded without the profile"); + s.media.insert_source(id, SourceLevel::Preview, preview(tag)); + assert!(matches!(s.media.source_ref(&p, SourceLevel::Thumb), SourceRef::Fit { .. }), "decoded with it: still cut from it"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A library moved (or restored) elsewhere finds its camera profiles in its own `Profiles/` folder, and a camera +/// profile can be a favourite, which survives reopening like the recent list. +#[test] +fn a_moved_library_keeps_its_camera_profiles_and_their_favourites() { + let dir = temp_dir("moved"); + let (mut s, id, dcp_id) = library_with_profile(&dir); + assert_eq!(s.execute("profile.favorite", &json!({"id": dcp_id})).unwrap()["favorite"], true); + assert!(s.profile_recent.contains(&dcp_id)); + s.persist().unwrap(); + s.close_library().unwrap(); + drop(s); + let moved = dir.join("moved"); + std::fs::rename(dir.join("lib"), &moved).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&moved, false).unwrap(); + assert!(s.media.camera_profiles.contains_key(&dcp_id), "the profile is found in the moved library"); + assert!(std::path::Path::new(&s.dcp_profiles[0].file).starts_with(&moved), "{}", s.dcp_profiles[0].file); + assert!(s.media.camera_profile_of(s.catalog.photo(id).unwrap()).is_some()); + assert!(s.profile_favorites.contains(&dcp_id) && s.profile_recent.contains(&dcp_id)); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +fn distance(a: [f32; 3], b: [f32; 3]) -> f32 { + (0..3).map(|i| (a[i] - b[i]).abs()).sum() +} + +/// A smart preview keeps the file's own colour: Build Smart Previews never develops it with the photo's imported +/// camera profile, nor takes a cached source decoded with it. Before, only the stale-proxy refresh left the profile out. +#[test] +fn smart_previews_are_built_without_the_imported_camera_profile() { + use crate::media::{DecodedSource, SourceLevel}; + let dir = temp_dir("smart"); + let (mut s, id, _) = library_with_profile(&dir); + let p = (**s.catalog.photo(id).unwrap()).clone(); + s.execute("library.smartPreviews", &json!({"ids": [id.0], "discard": true})).unwrap(); + // a cached preview decoded with the profile (flat magenta, so it shows if the proxy is cut from it) + let tag = s.media.camera_profile_of(&p).map(|c| c.0); + let mut magenta = lightcraft_raster::Rgb32f::new(8, 8); + magenta.data.iter_mut().for_each(|px| *px = [1.0, 0.0, 1.0]); + s.media.insert_source(id, SourceLevel::Preview, DecodedSource { camera_profile: tag, ..DecodedSource::new(std::sync::Arc::new(magenta), None) }); + let r = s.execute("library.smartPreviews", &json!({"ids": [id.0]})).unwrap(); + assert_eq!((r["built"].as_u64(), r["repaired"].as_u64()), (Some(1), Some(0)), "{r}"); + let smart_dir = s.media.smart_dir.clone().unwrap(); + let proxy = crate::smart::load(&crate::smart::existing_file_path(&smart_dir, crate::smart::sharded_file_path(&smart_dir, &p))).unwrap(); + let got = mean_rgb(&proxy.image); + let dng = std::fs::read(dir.join("files").join("IMG_0003.dng")).unwrap(); + let edge = SourceLevel::Preview.max_edge(); + let plain = mean_rgb(&crate::files::load_bytes(&dng, edge).unwrap().0); + let with = mean_rgb(&crate::files::load_bytes_with(&dng, edge, Some(&swapping_profile("Swap"))).unwrap().0); + assert!(distance(got, plain) < distance(got, with), "the proxy has the file's own colour: {got:?}, plain {plain:?}, profiled {with:?}"); + // nor from the file developed with the profile + s.media.forget(id); + s.execute("library.smartPreviews", &json!({"ids": [id.0], "discard": true})).unwrap(); + s.execute("library.smartPreviews", &json!({"ids": [id.0]})).unwrap(); + let proxy = crate::smart::load(&crate::smart::existing_file_path(&smart_dir, crate::smart::sharded_file_path(&smart_dir, &p))).unwrap(); + let got = mean_rgb(&proxy.image); + assert!(distance(got, plain) < distance(got, with), "the proxy has the file's own colour: {got:?}, plain {plain:?}, profiled {with:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// While the original is offline, a cached smart preview stands in for a photo developed with an imported camera +/// profile: it has no profile and decoding it again gives the same picture. Before, it was decoded again for every +/// render. Once the original is back, the photo is decoded from it with its profile. +#[test] +fn a_cached_smart_preview_stands_in_while_the_original_is_offline() { + use crate::media::{DecodedSource, SourceLevel, SourceRef}; + let dir = temp_dir("proxy-offline"); + let (mut s, id, _) = library_with_profile(&dir); + let p = (**s.catalog.photo(id).unwrap()).clone(); + assert!(s.media.camera_profile_of(&p).is_some()); + let proxy = DecodedSource { from_proxy: true, ..DecodedSource::new(std::sync::Arc::new(lightcraft_raster::Rgb32f::new(8, 8)), None) }; + s.media.insert_source(id, SourceLevel::Preview, proxy); + let offline = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); + let probe_offline = offline.clone(); + s.media.availability.set_probe(std::sync::Arc::new(move |path: &str| { + !(path.ends_with("IMG_0003.dng") && probe_offline.load(std::sync::atomic::Ordering::Relaxed)) && std::path::Path::new(path).exists() + })); + assert!(matches!(s.media.source_ref(&p, SourceLevel::Preview), SourceRef::Loaded(a) if a.from_proxy), "the proxy stands in"); + assert!(matches!(s.media.source_ref(&p, SourceLevel::Thumb), SourceRef::Fit { .. }), "the thumbnail is cut from it"); + offline.store(false, std::sync::atomic::Ordering::Relaxed); + assert!(!matches!(s.media.source_ref(&p, SourceLevel::Preview), SourceRef::Loaded(_)), "the original is back: decoded with the profile"); + assert!(!matches!(s.media.source_ref(&p, SourceLevel::Thumb), SourceRef::Fit { .. })); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The decoder facts reported for a photo come from a cached source developed with the camera profile it uses now; +/// before, a thumbnail decoded with another profile (or none) answered first. +#[test] +fn source_facts_come_from_a_source_developed_with_the_current_camera_profile() { + use crate::media::{DecodedSource, SourceLevel}; + let dir = temp_dir("facts"); + let (mut s, id, _) = library_with_profile(&dir); + let tag = s.media.camera_profile_of(s.catalog.photo(id).unwrap()).map(|c| c.0); + let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::new(4, 4)); + let facts = |temp: f64, camera_profile| DecodedSource { + camera_profile, + ..DecodedSource::new(img.clone(), Some(lightcraft_pipeline::SourceInfo { as_shot_temp: temp, ..Default::default() })) + }; + s.media.insert_source(id, SourceLevel::Thumb, facts(3100.0, None)); + s.media.insert_source(id, SourceLevel::Preview, facts(6200.0, tag)); + assert_eq!(s.source_info(id).as_shot_temp, 6200.0); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The Before side (and its region renders) decodes with the Before settings' camera profile — here none, the +/// import defaults — not with the edit's: before, it reused or decoded a source developed with the edit's profile. +#[test] +fn the_before_side_decodes_with_its_own_camera_profile() { + use crate::media::{DecodedSource, SourceLevel}; + let dir = temp_dir("before"); + let (mut s, id, _) = library_with_profile(&dir); + let camera = |job: &crate::media::RenderJob| match &job.source { + SourceRef::File { camera_profile, .. } => camera_profile.as_ref().map(|c| c.0.clone()), + SourceRef::Loaded(a) => a.camera_profile.clone(), + _ => None, + }; + s.media.forget(id); + let after = s.render_job(id, 256, 256, false, true).unwrap(); + let tag = camera(&after); + assert!(tag.is_some(), "the edit develops with the imported profile"); + let before = s.render_job(id, 256, 256, true, true).unwrap(); + assert_eq!(camera(&before), None, "the Before side develops with the file's own colour"); + // nor does a cached source developed with the edit's profile stand in for it + for level in [SourceLevel::Thumb, SourceLevel::Preview, SourceLevel::Full] { + let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::new(4, 4)); + s.media.insert_source(id, level, DecodedSource { camera_profile: tag.clone(), ..DecodedSource::new(img, None) }); + } + let before = s.render_job(id, 256, 256, true, true).unwrap(); + assert!(!matches!(before.source, SourceRef::Loaded(_)), "the Before side is decoded afresh"); + assert_eq!(camera(&before), None); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A profile whose copy into the library fails is reported as failed on its own: the profiles imported with +/// it stay imported (and are saved), and the command does not fail. +#[test] +fn a_profile_that_cannot_be_copied_fails_on_its_own() { + let dir = temp_dir("copy-fails"); + let (lib, files) = (dir.join("lib"), dir.join("files")); + std::fs::create_dir_all(&files).unwrap(); + for name in ["A", "B"] { + std::fs::write(files.join(format!("{name}.dcp")), write_dcp(&swapping_profile(name)).unwrap()).unwrap(); + } + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + // a folder where B's copy goes: writing it fails + let blocked = lib.join("Profiles").join(format!("{}.dcp", crate::presets::slug("LightCraft Test Camera-B"))); + std::fs::create_dir_all(&blocked).unwrap(); + let r = s.execute("profile.import", &json!({"paths": [files.to_string_lossy()]})).unwrap(); + let imported: Vec<&str> = r["imported"].as_array().unwrap().iter().filter_map(|p| p["name"].as_str()).collect(); + assert_eq!(imported, ["A"], "{r}"); + let failed = r["failed"].as_array().unwrap(); + assert_eq!(failed.len(), 1, "{r}"); + assert!(failed[0][0].as_str().is_some_and(|f| f.ends_with("B.dcp")), "{r}"); + assert_eq!(s.dcp_profiles.iter().map(|p| p.name.as_str()).collect::>(), ["A"]); + assert!(blocked.is_dir(), "the folder in the way is left alone"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A file that is neither a `.cube`, a `.dcp` nor a `.zip` is reported as failed instead of being passed over. +#[test] +fn importing_an_unsupported_profile_file_reports_it() { + let dir = temp_dir("unsupported"); + let notes = dir.join("notes.txt"); + std::fs::write(¬es, "not a profile").unwrap(); + let mut s = Session::new(); + let r = s.execute("profile.import", &json!({"paths": [notes.to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(0), "{r}"); + assert_eq!(r["failed"], json!([["notes", "not a .cube, .dcp or .zip file"]]), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A library copy that can't be removed keeps its profile: the command fails and nothing is forgotten, so the +/// library never holds a profile file it no longer lists (CodeRabbit on #1063). +#[test] +fn a_profile_whose_copy_cannot_be_deleted_stays() { + let dir = temp_dir("delete-fails"); + let (mut s, _, dcp_id) = library_with_profile(&dir); + let file = s.dcp_profiles.iter().find(|p| p.id == dcp_id).map(|p| PathBuf::from(&p.file)).unwrap(); + // a folder in the copy's place: removing it as a file fails (as a file in use does) + std::fs::remove_file(&file).unwrap(); + std::fs::create_dir_all(&file).unwrap(); + let r = s.execute("profile.deleteCamera", &json!({"id": dcp_id})); + assert!(r.is_err(), "{r:?}"); + assert!(s.dcp_profiles.iter().any(|p| p.id == dcp_id), "the profile is still listed"); + // gone already: deleting just forgets it + std::fs::remove_dir_all(&file).unwrap(); + s.execute("profile.deleteCamera", &json!({"id": dcp_id})).unwrap(); + assert!(s.dcp_profiles.iter().all(|p| p.id != dcp_id)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A listed path that climbs out of the profiles folder with `..` is not the library's copy: deleting the profile +/// leaves that file alone (CodeRabbit on #1063). +#[test] +fn deleting_a_profile_never_follows_dot_dot_out_of_the_profiles_folder() { + let dir = temp_dir("delete-dotdot"); + let (mut s, _, dcp_id) = library_with_profile(&dir); + let entry = s.dcp_profiles.iter_mut().find(|p| p.id == dcp_id).unwrap(); + let profiles = PathBuf::from(&entry.file).parent().unwrap().to_path_buf(); + let outside = profiles.parent().unwrap().join("keep.txt"); + std::fs::write(&outside, b"the user's").unwrap(); + entry.file = profiles.join("..").join("keep.txt").to_string_lossy().into_owned(); + s.execute("profile.deleteCamera", &json!({"id": dcp_id})).unwrap(); + assert!(s.dcp_profiles.iter().all(|p| p.id != dcp_id), "forgotten"); + assert!(outside.exists(), "the file outside the profiles folder stays"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// CodeRabbit on #1063: a camera profile whose library copy is missing or damaged when the library opens stayed in the +/// profile browser and `develop.profile` accepted it, and the photo then silently developed with the raw's own +/// colour. It is no longer offered or accepted; its entry stays, and once the file is back it is offered again. +#[test] +fn a_damaged_camera_profile_is_not_offered_until_its_file_is_back() { + let dir = temp_dir("damaged"); + let (mut s, _id, dcp_id) = library_with_profile(&dir); + let file = std::path::PathBuf::from(&s.dcp_profiles[0].file); + s.persist().unwrap(); + s.close_library().unwrap(); + drop(s); + let good = std::fs::read(&file).unwrap(); + std::fs::write(&file, b"not a profile").unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(dir.join("lib"), false).unwrap(); + assert_eq!(s.dcp_profiles.len(), 1, "the entry stays"); + assert!(!s.imported_profiles().iter().any(|p| p.0 == dcp_id), "not offered"); + let menu = s.profile_menu().to_string(); + assert!(!menu.contains(&dcp_id), "not in the profile menu: {menu}"); + assert!(s.execute("develop.profile", &json!({"id": dcp_id})).is_err(), "not accepted"); + s.close_library().unwrap(); + drop(s); + std::fs::write(&file, good).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(dir.join("lib"), false).unwrap(); + assert!(s.imported_profiles().iter().any(|p| p.0 == dcp_id), "offered again"); + s.execute("develop.profile", &json!({"id": dcp_id})).unwrap(); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// CodeRabbit on #1063: a LUT profile group named like the camera profiles' ("Camera Profiles") that doesn't sort last +/// made the profile menu list that group twice, each with the same profiles. It is one group, last. +#[test] +fn a_lut_group_named_camera_profiles_joins_the_camera_profiles_group() { + let dir = temp_dir("group"); + let (mut s, _id, dcp_id) = library_with_profile(&dir); + for (id, group) in [("lut:a", crate::cmd::dcp_profiles::DCP_GROUP), ("lut:z", "Zebra")] { + s.lut_profiles.push(crate::cmd::lut_profiles::LutProfile { id: id.into(), name: id.into(), group: group.into(), file: String::new() }); + } + let menu = s.profile_menu(); + let groups: Vec<&str> = menu["groups"].as_array().unwrap().iter().filter_map(|g| g["name"].as_str()).collect(); + assert_eq!(groups.iter().filter(|g| **g == crate::cmd::dcp_profiles::DCP_GROUP).count(), 1, "{groups:?}"); + assert_eq!(groups.last(), Some(&crate::cmd::dcp_profiles::DCP_GROUP), "{groups:?}"); + let ids: Vec<&str> = menu["groups"] + .as_array() + .unwrap() + .iter() + .filter(|g| g["name"] == crate::cmd::dcp_profiles::DCP_GROUP) + .flat_map(|g| g["profiles"].as_array().unwrap().iter().filter_map(|p| p["id"].as_str())) + .collect(); + assert!(ids.contains(&"lut:a") && ids.contains(&dcp_id.as_str()), "{ids:?}"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A `.dcp` file larger than the parser accepts is refused while it is read, before the whole file is loaded into +/// memory (CodeRabbit on #1063): the import reports it as failed with its own reason. +#[test] +fn an_oversized_camera_profile_is_refused_while_it_is_read() { + let dir = temp_dir("oversized"); + let big = dir.join("Big.dcp"); + let mut bytes = write_dcp(&swapping_profile("Big")).unwrap(); + bytes.truncate(4); + std::fs::write(&big, &bytes).unwrap(); + std::fs::OpenOptions::new().write(true).open(&big).unwrap().set_len(lightcraft_raw::dcp::MAX_DCP_BYTES + 1).unwrap(); + let mut s = Session::new(); + let r = s.execute("profile.import", &json!({"paths": [big.to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"], json!([]), "{r}"); + assert_eq!(r["failed"][0][1], json!("the camera profile is larger than 64 MiB"), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/tests/dcp_corpus.rs b/crates/engine/src/tests/dcp_corpus.rs new file mode 100644 index 0000000000..48ed68467d --- /dev/null +++ b/crates/engine/src/tests/dcp_corpus.rs @@ -0,0 +1,243 @@ +//! A real camera profile end to end: the Nikon D750 ColorChecker DCP and chart NEFs dieli released +//! under CC0 (github.com/dieli/d750-lightcraft-colorchecker, pinned in `D750_COLORCHECKER`, +//! xtask/src/main.rs; `cargo xtask corpus --download`). Each chart is imported, developed with the +//! imported profile, white balanced on the second-lightest grey patch (as in the reference) and +//! exported as sRGB; the 24 patches are then compared in CIELAB (ΔE2000) with Lightroom Classic +//! 15.6's render of the same NEF with the same profile. +//! +//! The comparison is lenient on purpose: the profile is matrix-only, so the colour model is the same, +//! but Lightroom adds its own default tone curve and rendering, which LightCraft does not copy. The +//! test pins the measured agreement against regressions (see `MEAN_LIMIT`, `MAX_LIMIT`) and prints +//! every patch's ΔE. Missing files are reported as skipped. + +use std::path::{Path, PathBuf}; + +use lightcraft_catalog::PhotoId; +use serde_json::json; + +use crate::Session; +use crate::export::{ExportOptions, export_photo}; + +/// Upper bounds for the mean and the largest patch ΔE2000 against Lightroom. Measured when this test +/// was written (2026-10-22): daylight/flash mean 3.84, max 7.77 (patch 16, yellow); indoor mean 3.35, +/// max 5.24 (patch 13, blue). The grey row agrees within about 1-3; the colour patches come out less +/// saturated than Lightroom's (its own rendering on top of the profile), which is most of the rest. +const MEAN_LIMIT: f64 = 5.0; +const MAX_LIMIT: f64 = 10.0; + +fn set_dir() -> PathBuf { + std::env::var_os("LIGHTCRAFT_CORPUS") + .map(PathBuf::from) + .unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus")) + .join("d750-colorchecker") +} + +/// Patch centres (row-major, normalized x, y) in Lightroom's render of each chart, a crop around the +/// ColorChecker. Row 4 is the grey row, white to black. +fn reference_centres(chart: &str) -> Vec<(f64, f64)> { + let (xs, ys): (&[f64], &[f64]) = if chart.contains("indoor") { + (&[193.0, 361.0, 527.0, 692.0, 857.0, 1022.0], &[152.0, 318.0, 486.0, 660.0]) + } else { + (&[197.0, 378.0, 555.0, 731.0, 906.0, 1080.0], &[135.0, 312.0, 490.0, 668.0]) + }; + ys.iter().flat_map(|y| xs.iter().map(move |x| (x / 1200.0, y / 801.0))).collect() +} + +/// The same patches in the whole NEF frame (our export, uncropped), read off a 1200 × 802 render. +fn frame_centres(chart: &str) -> Vec<(f64, f64)> { + let (xs, ys): (&[f64], &[f64]) = if chart.contains("indoor") { + (&[468.0, 528.0, 587.0, 645.0, 704.0, 765.0], &[527.0, 585.0, 644.0, 705.0]) + } else { + (&[462.0, 512.0, 560.0, 609.0, 658.0, 706.0], &[381.0, 430.0, 479.0, 529.0]) + }; + ys.iter().flat_map(|y| xs.iter().map(move |x| (x / 1200.0, y / 802.0))).collect() +} + +/// Mean CIELAB (D50) of a box of half-width `radius` (a fraction of the image width) around each +/// centre, and the largest standard deviation of L* inside a box (a box on a patch edge shows up there). +fn patch_labs(bytes: &[u8], centres: &[(f64, f64)], radius: f64) -> (Vec<[f64; 3]>, f64) { + let d = lightcraft_codecs::decode(bytes, Default::default()).unwrap(); + let to_xyz = d.space.to_xyz_d50; + let (w, h) = (d.image.width, d.image.height); + let r = (w as f64 * radius).max(1.0) as isize; + let mut worst = 0.0f64; + let labs = centres + .iter() + .map(|&(x, y)| { + let (cx, cy) = ((x * w as f64) as isize, (y * h as f64) as isize); + let (mut acc, mut ls) = ([0.0f64; 3], Vec::new()); + for yy in (cy - r).max(0)..(cy + r).min(h as isize) { + for xx in (cx - r).max(0)..(cx + r).min(w as isize) { + let p = d.image.data[yy as usize * w + xx as usize]; + let rgb = [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])]; + for (a, v) in acc.iter_mut().zip(rgb) { + *a += v; + } + ls.push(lab(to_xyz.apply(rgb))[0]); + } + } + let n = ls.len().max(1) as f64; + let mean_l = ls.iter().sum::() / n; + worst = worst.max((ls.iter().map(|l| (l - mean_l).powi(2)).sum::() / n).sqrt()); + lab(to_xyz.apply(acc.map(|v| v / n))) + }) + .collect(); + (labs, worst) +} + +fn lab(xyz: [f64; 3]) -> [f64; 3] { + let white = [0.9642, 1.0, 0.8249]; + let f = |t: f64| if t > 216.0 / 24389.0 { t.cbrt() } else { (24389.0 / 27.0 * t + 16.0) / 116.0 }; + let [fx, fy, fz] = [f(xyz[0] / white[0]), f(xyz[1] / white[1]), f(xyz[2] / white[2])]; + [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)] +} + +/// CIEDE2000 (Sharma, Wu and Dalal 2005). +fn de2000(a: [f64; 3], b: [f64; 3]) -> f64 { + use std::f64::consts::PI; + let (l1, a1, b1, l2, a2, b2) = (a[0], a[1], a[2], b[0], b[1], b[2]); + let c_bar = ((a1 * a1 + b1 * b1).sqrt() + (a2 * a2 + b2 * b2).sqrt()) / 2.0; + let g = 0.5 * (1.0 - (c_bar.powi(7) / (c_bar.powi(7) + 25f64.powi(7))).sqrt()); + let (a1p, a2p) = ((1.0 + g) * a1, (1.0 + g) * a2); + let (c1p, c2p) = ((a1p * a1p + b1 * b1).sqrt(), (a2p * a2p + b2 * b2).sqrt()); + let hue = |b: f64, a: f64| if b == 0.0 && a == 0.0 { 0.0 } else { b.atan2(a).rem_euclid(2.0 * PI) }; + let (h1p, h2p) = (hue(b1, a1p), hue(b2, a2p)); + let dl = l2 - l1; + let dc = c2p - c1p; + let dh = if c1p * c2p == 0.0 { + 0.0 + } else { + let d = h2p - h1p; + if d.abs() <= PI { + d + } else if d > PI { + d - 2.0 * PI + } else { + d + 2.0 * PI + } + }; + let dhh = 2.0 * (c1p * c2p).sqrt() * (dh / 2.0).sin(); + let l_bar = (l1 + l2) / 2.0; + let cp_bar = (c1p + c2p) / 2.0; + let hp_bar = if c1p * c2p == 0.0 { + h1p + h2p + } else if (h1p - h2p).abs() <= PI { + (h1p + h2p) / 2.0 + } else if h1p + h2p < 2.0 * PI { + (h1p + h2p + 2.0 * PI) / 2.0 + } else { + (h1p + h2p - 2.0 * PI) / 2.0 + }; + let t = 1.0 - 0.17 * (hp_bar - PI / 6.0).cos() + 0.24 * (2.0 * hp_bar).cos() + 0.32 * (3.0 * hp_bar + PI / 30.0).cos() + - 0.20 * (4.0 * hp_bar - 63.0 * PI / 180.0).cos(); + let d_theta = 30.0 * (-(((hp_bar * 180.0 / PI) - 275.0) / 25.0).powi(2)).exp(); + let rc = 2.0 * (cp_bar.powi(7) / (cp_bar.powi(7) + 25f64.powi(7))).sqrt(); + let sl = 1.0 + 0.015 * (l_bar - 50.0).powi(2) / (20.0 + (l_bar - 50.0).powi(2)).sqrt(); + let sc = 1.0 + 0.045 * cp_bar; + let sh = 1.0 + 0.015 * cp_bar * t; + let rt = -(2.0 * d_theta * PI / 180.0).sin() * rc; + ((dl / sl).powi(2) + (dc / sc).powi(2) + (dhh / sh).powi(2) + rt * (dc / sc) * (dhh / sh)).sqrt() +} + +#[test] +fn de2000_matches_the_published_test_pairs() { + // Sharma, Wu and Dalal (2005), table 1: pairs 1, 7 and 17 + let cases = [ + ([50.0, 2.6772, -79.7751], [50.0, 0.0, -82.7485], 2.0425), + ([50.0, 0.0, 0.0], [50.0, -1.0, 2.0], 2.3669), + ([50.0, 2.5, 0.0], [73.0, 25.0, -18.0], 27.1492), + ]; + for (a, b, e) in cases { + assert!((de2000(a, b) - e).abs() < 1e-3, "{a:?} {b:?}: {} vs {e}", de2000(a, b)); + } +} + +#[test] +fn the_d750_profile_develops_its_charts_close_to_lightroom() { + let set = set_dir(); + let dcp = set.join("profiles/20261016_NikonD750_DualIllumination_ColorCheckerPassport.dcp"); + let charts = [("daylight_flash", "raw/chart-daylight_flash.NEF"), ("indoor", "raw/chart-indoor.NEF")]; + let mut needed = vec![dcp.clone()]; + for (name, raw) in charts { + needed.push(set.join(raw)); + needed.push(set.join(format!("images/{name}-lightroom.jpg"))); + } + if let Some(missing) = needed.iter().find(|p| !p.exists()) { + lightcraft_testkit::skip!(Corpus, "{} absent (cargo xtask corpus --download)", missing.display()); + return; + } + let lib = std::env::temp_dir().join(format!("lc-dcp-d750-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&lib); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let r = s.execute("profile.import", &json!({"paths": [dcp.to_string_lossy()]})).unwrap(); + let dcp_id = r["imported"][0]["id"].as_str().expect("the D750 profile imports").to_string(); + assert!(r["imported"][0]["cameraModel"].as_str().unwrap().contains("D750"), "{r}"); + let o = ExportOptions::from_json(&json!({"format": "png", "longEdge": 1200, "colorSpace": "srgb"})); + let mut report = String::new(); + let mut means = Vec::new(); + for (name, raw) in charts { + let r = s.execute("library.import", &json!({"paths": [set.join(raw).to_string_lossy()]})).unwrap(); + let id = PhotoId(r["imported"][0].as_u64().expect("the NEF imports")); + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + s.execute("develop.profile", &json!({"id": dcp_id})).unwrap(); + let centres = frame_centres(name); + let (reference, spread) = + patch_labs(&std::fs::read(set.join(format!("images/{name}-lightroom.jpg"))).unwrap(), &reference_centres(name), 0.02); + assert!(spread < 4.0, "{name}: every reference box lies inside its patch (L* spread {spread:.1})"); + // white balance on the second-lightest grey (patch 20), as the reference was made + let wb = s.execute("develop.wbPick", &json!({"x": centres[19].0, "y": centres[19].1})).unwrap(); + // exposure: the value whose grey row is closest to the reference's (golden-section search) + let render = |s: &mut Session, ev: f64| { + s.execute("develop.set", &json!({"control": "light.exposure", "value": ev})).unwrap(); + let e = export_photo(s, id, &o, 1).expect("the chart develops with the D750 profile"); + patch_labs(&e.bytes, ¢res, 0.006) + }; + let grey_de = |(labs, _): &(Vec<[f64; 3]>, f64)| (18..24).map(|i| de2000(labs[i], reference[i])).sum::() / 6.0; + let (mut lo, mut hi) = (-1.5f64, 1.5f64); + let phi = (5f64.sqrt() - 1.0) / 2.0; + let (mut m1, mut m2) = (hi - phi * (hi - lo), lo + phi * (hi - lo)); + let (mut f1, mut f2) = (grey_de(&render(&mut s, m1)), grey_de(&render(&mut s, m2))); + for _ in 0..8 { + if f1 < f2 { + (hi, m2, f2) = (m2, m1, f1); + m1 = hi - phi * (hi - lo); + f1 = grey_de(&render(&mut s, m1)); + } else { + (lo, m1, f1) = (m1, m2, f2); + m2 = lo + phi * (hi - lo); + f2 = grey_de(&render(&mut s, m2)); + } + } + let ev = (lo + hi) / 2.0; + let (ours, spread) = render(&mut s, ev); + assert!(spread < 4.0, "{name}: every box lies inside its patch (L* spread {spread:.1})"); + // LIGHTCRAFT_DCP_DUMP=: keep our renders, to check the patch boxes by eye + if let Some(dir) = std::env::var_os("LIGHTCRAFT_DCP_DUMP") { + s.execute("develop.set", &json!({"control": "light.exposure", "value": ev})).unwrap(); + let _ = std::fs::write(Path::new(&dir).join(format!("{name}.png")), export_photo(&mut s, id, &o, 1).unwrap().bytes); + } + let des: Vec = ours.iter().zip(&reference).map(|(a, b)| de2000(*a, *b)).collect(); + let mean = des.iter().sum::() / des.len() as f64; + let max = des.iter().cloned().fold(0.0, f64::max); + report += &format!("{name}: wb {} K / tint {}, exposure {ev:+.2}, mean ΔE2000 {mean:.2}, max {max:.2}\n", wb["temp"], wb["tint"]); + for (i, d) in des.iter().enumerate() { + report += &format!( + " patch {:2}: ΔE {d:5.2} ours L*a*b* {:6.1} {:6.1} {:6.1} Lightroom {:6.1} {:6.1} {:6.1}\n", + i + 1, + ours[i][0], + ours[i][1], + ours[i][2], + reference[i][0], + reference[i][1], + reference[i][2] + ); + } + means.push((name, mean, max)); + } + eprintln!("{report}"); + let _ = std::fs::remove_dir_all(&lib); + for (name, mean, max) in means { + assert!(mean < MEAN_LIMIT && max < MAX_LIMIT, "{name}: mean ΔE2000 {mean:.2}, max {max:.2}\n{report}"); + } +} diff --git a/crates/engine/src/tests/export.rs b/crates/engine/src/tests/export.rs index 27268e463a..531f1d652c 100644 --- a/crates/engine/src/tests/export.rs +++ b/crates/engine/src/tests/export.rs @@ -189,6 +189,40 @@ fn presets_conflicts_and_subfolders() { assert_eq!(written, ["out/Sub/LC01347.png"]); } +/// Issue #2571: a subfolder with `..`, a root or a drive wrote outside the chosen folder. It is +/// cleaned where the folder is used, so a preset or the Export dialog's field (which set it +/// without `from_json`) are covered as well as command parameters. +#[test] +fn a_subfolder_never_leaves_the_destination_folder() { + use crate::export::{Destination, export_batch}; + let mut s = Session::with_demo(); + let id = s.active().unwrap(); + let to = Destination { dir: "out".into(), exact: None }; + let written_to = |s: &mut Session, sub: &str| { + let o = ExportOptions { subfolder: sub.into(), naming: "x".into(), ..ExportOptions::from_json(&json!({"format": "png", "width": 16})) }; + let mut written: Vec = Vec::new(); + let mut write = |p: &str, _: &[u8]| { + written.push(p.to_string()); + Ok(()) + }; + export_batch(s, &[id], &o, &to, &mut write, &|_| false).unwrap(); + written + }; + for (sub, want) in [ + ("../../escaped", "out/escaped/x.png"), + ("..", "out/x.png"), + ("/etc", "out/etc/x.png"), + ("C:\\Windows", "out/C__Windows/x.png"), + ("a/./b/../c", "out/a/b/c/x.png"), + (" Client / Jobs ", "out/Client/Jobs/x.png"), + ] { + assert_eq!(written_to(&mut s, sub), [want], "{sub:?}"); + } + // command parameters get the same cleaning + let o = ExportOptions::from_json(&json!({"subfolder": "../up"})); + assert_eq!(o.subfolder, "up"); +} + #[test] fn prepared_exports_run_on_another_thread() { fn send(_: &T) {} diff --git a/crates/engine/src/tests/face_tiles.rs b/crates/engine/src/tests/face_tiles.rs index 9aa4b05e84..b166dcd859 100644 --- a/crates/engine/src/tests/face_tiles.rs +++ b/crates/engine/src/tests/face_tiles.rs @@ -91,9 +91,9 @@ fn count_loads(s: &mut Session) -> Loads { let loads = Loads::default(); let file = s.media.file_loader.clone().unwrap(); let n = loads.files.clone(); - s.media.file_loader = Some(Arc::new(move |p: &str, e: usize| { + s.media.file_loader = Some(Arc::new(move |p: &str, e: usize, dcp: Option<&crate::media::DcpProfile>| { n.fetch_add(1, Ordering::SeqCst); - file(p, e) + file(p, e, dcp) })); let preview = s.media.preview_loader.clone().unwrap(); let n = loads.previews.clone(); diff --git a/crates/engine/src/tests/folders.rs b/crates/engine/src/tests/folders.rs index 34017fc977..6877572768 100644 --- a/crates/engine/src/tests/folders.rs +++ b/crates/engine/src/tests/folders.rs @@ -701,3 +701,18 @@ fn a_destination_without_write_permission_reports_an_error_and_keeps_everything( } std::fs::set_permissions(dir.0.join("ro"), std::fs::Permissions::from_mode(0o755)).unwrap(); } + +#[cfg(unix)] +#[test] +fn the_library_folder_is_protected_however_its_path_is_spelled() { + let dir = Scratch::new("library-link"); + let lib = dir.0.join("library"); + let mut s = Session::new(); + s.open_library(&lib, true).unwrap(); + // a link to the library's folder names the same folder on disk + std::os::unix::fs::symlink(&lib, dir.0.join("alias")).unwrap(); + std::fs::create_dir_all(dir.0.join("elsewhere")).unwrap(); + let err = s.execute("folder.move", &json!({"path": dir.path("alias"), "into": dir.path("elsewhere")})).unwrap_err().to_string(); + assert!(err.contains("library's own folders"), "{err}"); + assert!(lib.is_dir() && !dir.0.join("elsewhere/alias").exists()); +} 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 new file mode 100644 index 0000000000..7678c93a3d --- /dev/null +++ b/crates/engine/src/tests/lens_refresh.rs @@ -0,0 +1,291 @@ +//! Lens profiles stay per lens. Presets, Copy / Paste and Sync carry "Enable Lens Corrections" and +//! its amounts, never a profile: each photo keeps the one found for its own lens. And photos imported before the lens +//! database was there get their profile when it arrives (`cmd::lens_refresh`). + +use std::sync::Arc; + +use lightcraft_catalog::{MediaKind, Op, Photo, PhotoId, Source}; +use lightcraft_develop::{EmbeddedLens, EmbeddedWarp, LensSource}; +use serde_json::json; + +use crate::Session; + +fn lens(k: f64) -> EmbeddedLens { + EmbeddedLens { + warp: Some(EmbeddedWarp { planes: [[1.0, k, 0.0, 0.0, 0.0, 0.0]; 3], radius: 0.6, ..Default::default() }), + source: LensSource::Database, + ..Default::default() + } +} + +fn lens_of(s: &Session, id: PhotoId) -> Option { + s.catalog.photo(id).and_then(|p| p.embedded_lens) +} + +/// Two demo photos "taken with different lenses". +fn two_lenses() -> (Session, PhotoId, PhotoId) { + let mut s = Session::with_demo(); + let ids: Vec = s.visible().iter().copied().take(2).collect(); + let (a, b) = (ids[0], ids[1]); + s.catalog.apply(Op::SetEmbeddedLens { id: a, lens: Some(Box::new(lens(-0.05))) }).unwrap(); + s.catalog.apply(Op::SetEmbeddedLens { id: b, lens: Some(Box::new(lens(0.03))) }).unwrap(); + s.execute("library.select", &json!({"ids": [a.0]})).unwrap(); + s.execute("develop.merge", &json!({"settings": {"optics": {"lens_profile": true}}, "label": "Lens Corrections"})).unwrap(); + s.execute("develop.set", &json!({"values": {"optics.profileDistortion": 60}})).unwrap(); + (s, a, b) +} + +fn carried(s: &Session, id: PhotoId) { + let d = s.develop_of(id).unwrap(); + assert!(d.optics.lens_profile, "the switch travels"); + assert_eq!(d.optics.profile_distortion, 60.0, "the amount travels"); +} + +#[test] +fn copy_paste_carries_the_switch_and_amounts_never_the_profile() { + let (mut s, a, b) = two_lenses(); + s.execute("develop.copy", &json!({})).unwrap(); + s.execute("develop.paste", &json!({"ids": [b.0]})).unwrap(); + carried(&s, b); + assert_eq!(lens_of(&s, b), Some(lens(0.03)), "b keeps its own lens's profile"); + assert_eq!(lens_of(&s, a), Some(lens(-0.05))); +} + +#[test] +fn sync_and_presets_keep_each_photos_own_profile() { + let (mut s, a, b) = two_lenses(); + s.execute("library.select", &json!({"ids": [a.0, b.0], "active": a.0})).unwrap(); + s.execute("develop.sync", &json!({})).unwrap(); + carried(&s, b); + assert_eq!(lens_of(&s, b), Some(lens(0.03))); + // a preset made on a's settings, applied to b + let pid = s.execute("preset.create", &json!({"name": "Optics", "groups": ["optics"]})).unwrap()["id"].as_str().unwrap().to_string(); + s.execute("library.select", &json!({"ids": [b.0]})).unwrap(); + s.execute("develop.merge", &json!({"settings": {"optics": {"lens_profile": false}}, "label": "Lens Corrections"})).unwrap(); + s.execute("preset.apply", &json!({"id": pid})).unwrap(); + carried(&s, b); + assert_eq!(lens_of(&s, b), Some(lens(0.03)), "a preset never brings another lens's profile"); + assert_eq!(lens_of(&s, a), Some(lens(-0.05))); +} + +/// A batch of results gives each probed photo's profile to that photo and to its own virtual copies, never to the +/// copies of a photo that wasn't probed. +#[test] +fn each_result_reaches_its_photos_virtual_copies_and_no_others() { + let mut s = Session::new(); + for p in [raw(1, "50mm F1.8", false), raw(2, "50mm F1.8", false), raw(3, "50mm F1.8", false)] { + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + for (id, of) in [(11, 1), (12, 1), (21, 2), (31, 3)] { + let mut copy = raw(id, "50mm F1.8", false); + copy.copy_of = Some(PhotoId(of)); + s.catalog.apply(Op::AddPhoto { photo: Box::new(copy) }).unwrap(); + } + let probed = [1, 2].map(|id| { + let m = crate::cmd::lens_refresh::Missing { id: PhotoId(id), path: format!("/photos/{id}.cr3") }; + (m, Ok(crate::media::ProbeInfo { embedded_lens: Some(lens(-0.01)), ..Default::default() })) + }); + let mut found = crate::cmd::lens_refresh::apply(&mut s, probed.into()).unwrap(); + found.sort(); + assert_eq!(found, [1, 2, 11, 12, 21].map(PhotoId), "each probed photo and its own copies"); + for id in [1, 2, 11, 12, 21] { + assert!(s.catalog.photo(PhotoId(id)).unwrap().embedded_lens.is_some(), "photo {id} gets the profile"); + } + for id in [3, 31] { + assert!(s.catalog.photo(PhotoId(id)).unwrap().embedded_lens.is_none(), "photo {id} wasn't probed: unchanged"); + } +} + +/// A raw in a library folder, as an older import left it: no lens data. +fn raw(id: u64, lens_name: &str, edited: bool) -> Photo { + let mut p = + Photo::new(PhotoId(id), Source::File { path: format!("/photos/{id}.cr3") }, &format!("{id}.cr3"), "CR3", 600, 400, "2026-10-01T00:00:00"); + p.kind = MediaKind::Raw; + p.meta.camera = "Testcam TC-1".into(); + p.meta.lens = lens_name.into(); + if edited { + let mut d = (*p.develop).clone(); + d.light.exposure = 0.5; + p.develop = Arc::new(d); + p.edited = Some("2026-10-02T00:00:00".into()); + } + p +} + +const DB: &str = r#" + TestcamTC-1T1 + TestcamTestcam 50mm f/1.8T1 + "#; + +/// When the database arrives, the library's raws whose lens it knows get their profile; untouched photos get the +/// correction switched on as import would, edited ones keep their settings; lenses it doesn't know are not probed. +#[test] +fn photos_get_their_profile_when_the_database_arrives() { + let mut s = Session::new(); + for p in [raw(1, "50mm F1.8", false), raw(2, "50mm F1.8", true), raw(3, "300mm F4", false), raw(4, "", false)] { + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + let db = lightcraft_lensdb::LensDb::parse(DB).unwrap(); + let listed = crate::cmd::lens_refresh::missing(&s.catalog, &db, None, false); + assert_eq!(listed.iter().map(|m| m.id.0).collect::>(), [1, 2], "only lenses the database knows"); + assert_eq!(crate::cmd::lens_refresh::missing(&s.catalog, &db, Some(&[PhotoId(2)]), false).len(), 1, "or only the photos asked for"); + // what the files give when read again + let results = listed.into_iter().map(|m| (m, Ok(crate::media::ProbeInfo { embedded_lens: Some(lens(-0.01)), ..Default::default() }))).collect(); + let found = crate::cmd::lens_refresh::apply(&mut s, results).unwrap(); + assert_eq!(found, [PhotoId(1), PhotoId(2)]); + let p = |id: u64| s.catalog.photo(PhotoId(id)).unwrap().clone(); + assert!(p(1).embedded_lens.is_some() && p(1).develop.optics.lens_profile, "untouched: on, as import would"); + assert!(p(2).embedded_lens.is_some() && !p(2).develop.optics.lens_profile, "edited: its settings stay"); + assert!(p(3).embedded_lens.is_none()); + assert!(s.undo.is_empty(), "bookkeeping, not an undo step"); + // the Optics panel's words + assert_eq!(crate::cmd::lens_refresh::no_profile_reason(&p(3)).as_deref(), Some("No lens profile found for 300mm F4.")); + assert_eq!(crate::cmd::lens_refresh::no_profile_reason(&p(4)).as_deref(), Some("This file names no lens.")); + assert_eq!(crate::cmd::lens_refresh::no_profile_reason(&p(1)), None); + // a result read from a file the photo no longer has (moved meanwhile) is dropped, for its virtual copies too + let mut copy = raw(5, "300mm F4", false); + copy.copy_of = Some(PhotoId(3)); + s.catalog.apply(Op::AddPhoto { photo: Box::new(copy) }).unwrap(); + let stale = crate::cmd::lens_refresh::Missing { id: PhotoId(3), path: "/elsewhere/3.cr3".into() }; + let ok = crate::media::ProbeInfo { embedded_lens: Some(lens(-0.01)), ..Default::default() }; + assert!(crate::cmd::lens_refresh::apply(&mut s, vec![(stale, Ok(ok))]).unwrap().is_empty()); + assert!(s.catalog.photo(PhotoId(3)).unwrap().embedded_lens.is_none(), "a stale probe changes nothing"); + assert!(s.catalog.photo(PhotoId(5)).unwrap().embedded_lens.is_none(), "nor the copies"); + // without file access the command says so instead of clearing anything + assert!(s.execute("library.refreshLensProfiles", &json!({})).is_err()); + assert!(s.execute("library.refreshLensProfiles", &json!({"ids": "x"})).is_err()); +} + +fn with_lens(mut p: Photo, l: Option, on: bool) -> Photo { + p.embedded_lens = l; + let mut d = (*p.develop).clone(); + d.optics.lens_profile = on; + p.develop = Arc::new(d); + p +} + +/// When the database's files were replaced, the photos whose profile came from the old database are read again +/// (they get the new profile, or lose one the database no longer gives), and so are the raws that named no lens when +/// they were imported. A profile from the file itself is left alone, and none of these are read at an ordinary start. +#[test] +fn a_replaced_database_looks_up_database_profiles_and_unnamed_photos_again() { + let mut s = Session::new(); + let file_lens = EmbeddedLens { source: LensSource::File, ..lens(-0.04) }; + for p in [ + with_lens(raw(1, "50mm F1.8", false), Some(lens(-0.01)), true), + with_lens(raw(2, "50mm F1.8", false), Some(file_lens), true), + raw(3, "", false), + with_lens(raw(4, "300mm F4", false), Some(lens(-0.02)), true), + ] { + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + let db = lightcraft_lensdb::LensDb::parse(DB).unwrap(); + let ids = |v: Vec| v.iter().map(|m| m.id.0).collect::>(); + assert!(crate::cmd::lens_refresh::missing(&s.catalog, &db, None, false).is_empty(), "an ordinary start reads none of them"); + let listed = crate::cmd::lens_refresh::missing(&s.catalog, &db, None, true); + assert_eq!(ids(listed.clone()), [1, 3, 4], "database profiles and unnamed raws, never the file's own correction"); + // what the files give with the new database: 1 another profile, 3 its lens (now read) and a profile, 4 nothing + let gives = |id: u64| match id { + 1 => crate::media::ProbeInfo { embedded_lens: Some(lens(-0.03)), ..Default::default() }, + 3 => { + let mut info = crate::media::ProbeInfo { embedded_lens: Some(lens(-0.01)), ..Default::default() }; + info.meta.lens = "50mm F1.8".into(); + info + } + _ => crate::media::ProbeInfo::default(), + }; + let results = listed.into_iter().map(|m| (m.clone(), Ok(gives(m.id.0)))).collect(); + let found = crate::cmd::lens_refresh::apply(&mut s, results).unwrap(); + assert_eq!(found, [PhotoId(1), PhotoId(3)]); + assert_eq!(lens_of(&s, PhotoId(1)), Some(lens(-0.03)), "the new database's profile"); + assert_eq!(lens_of(&s, PhotoId(2)), Some(file_lens), "the file's own correction stays"); + assert_eq!(lens_of(&s, PhotoId(3)), Some(lens(-0.01))); + assert_eq!(s.catalog.photo(PhotoId(3)).unwrap().meta.lens, "50mm F1.8", "the lens's name, read now"); + assert_eq!(lens_of(&s, PhotoId(4)), None, "a profile the database no longer gives is gone"); + assert!(s.undo.is_empty(), "bookkeeping, not an undo step"); +} + +/// Every render of a photo uses the one database profile the catalog holds for it: a fresh decode that looked the lens +/// up in a newer database doesn't override it (a cached preview and a fresh render agree), while the file's own +/// correction, part of the file, still comes from the decode. +#[test] +fn a_decode_never_overrides_the_photos_database_profile() { + use crate::media::DecodedSource; + let img = Arc::new(lightcraft_raster::Rgb32f::new(4, 4)); + let decoded = |l: EmbeddedLens| DecodedSource::new(img.clone(), Some(lightcraft_pipeline::SourceInfo { lens: Some(l), ..Default::default() })); + let header = |l: Option| lightcraft_pipeline::SourceInfo { lens: l, ..Default::default() }; + assert_eq!(decoded(lens(-0.05)).info_or(header(Some(lens(-0.01)))).lens, Some(lens(-0.01)), "the catalog's profile"); + assert_eq!(decoded(lens(-0.05)).info_or(header(None)).lens, None, "none until the photo is given one"); + let file_lens = EmbeddedLens { source: LensSource::File, ..lens(-0.04) }; + assert_eq!(decoded(file_lens).info_or(header(None)).lens, Some(file_lens), "the file's own correction"); + // the original was replaced by one without a correction: the decode finds none, and the catalog's old file + // correction isn't put back + let none = DecodedSource::new(img.clone(), Some(lightcraft_pipeline::SourceInfo { lens: None, ..Default::default() })); + assert_eq!(none.info_or(header(Some(file_lens))).lens, None, "no file correction the file no longer has"); + assert_eq!(none.info_or(header(Some(lens(-0.01)))).lens, Some(lens(-0.01)), "the database profile stays"); +} + +/// When a photo's database profile changes (a replaced database looked up again), its render key and its thumbnail +/// and variant cache keys change, so no cached render made with the old profile is shown. With the correction off +/// they change too: the decode fits the raw's starting colour through the profile's vignetting either way. +#[test] +fn a_new_database_profile_changes_the_render_and_cache_keys() { + let mut s = Session::new(); + s.catalog.apply(Op::AddPhoto { photo: Box::new(with_lens(raw(1, "50mm F1.8", false), Some(lens(-0.01)), true)) }).unwrap(); + let id = PhotoId(1); + let keys = |s: &mut Session| { + 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)) + }; + let before = keys(&mut s); + s.catalog.apply(Op::SetEmbeddedLens { id, lens: Some(Box::new(lens(-0.03))) }).unwrap(); + let after = keys(&mut s); + assert_ne!(before.0, after.0, "render key"); + assert_ne!(before.1, after.1, "thumbnail cache key"); + assert_ne!(before.2, after.2, "variant cache key"); + assert_ne!(before.3, after.3, "loupe view cache key"); + // correction off: the starting colour's fit still uses the profile, so the keys change as well + let off = with_lens((**s.catalog.photo(id).unwrap()).clone(), Some(lens(-0.03)), false); + s.catalog.apply(Op::SetDevelop { id, settings: off.develop.clone(), label: "Lens Corrections".into(), edited: None }).unwrap(); + let off_before = keys(&mut s); + s.catalog.apply(Op::SetEmbeddedLens { id, lens: Some(Box::new(lens(-0.05))) }).unwrap(); + let off_after = keys(&mut s); + assert_ne!(off_before.0, off_after.0, "render key, correction off"); + assert_ne!(off_before.1, off_after.1, "thumbnail cache key, correction off"); + assert_ne!(off_before.2, off_after.2, "variant cache key, correction off"); + assert_ne!(off_before.3, off_after.3, "loupe view cache key, correction off"); +} + +/// `lens.downloadDatabase` selects the folder it downloads into, so the session reads the database once it is in +/// place (a headless session would otherwise download it and go on without it); and the app's own folder is read +/// only when it is whole (its marker, written last, is there). +#[test] +fn the_downloaded_database_is_selected_and_read_only_when_whole() { + use crate::{lens_profiles, lensfun_download}; + if std::env::var_os(lens_profiles::ENV).is_some_and(|v| !v.is_empty()) { + lightcraft_testkit::skip!(Input, "LIGHTCRAFT_LENSFUN_DIR names the folder in use"); + return; + } + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + let root = std::env::temp_dir().join(format!("lc-lens-select-{}-{unique}", std::process::id())); + let dir = root.join("lensfun"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("lenses.xml"), DB).unwrap(); + let before = lens_profiles::host_dir(); + let mut s = Session::new(); + // nothing listens on port 1: the download fails at once, without the network + crate::cmd::lens_refresh::start_download(&mut s, &dir, vec!["http://127.0.0.1:1/db".into()], lensfun_download::FILES).unwrap(); + assert_eq!(lens_profiles::dir().as_deref(), Some(dir.as_path()), "the session reads the folder it downloads into"); + assert!(lens_profiles::database().is_none(), "no marker: a download that never finished is not read"); + std::fs::write(dir.join(lensfun_download::MARKER), "whole").unwrap(); + lens_profiles::reload(); + assert_eq!(lens_profiles::database().map(|db| db.lenses.len()), Some(1), "whole: read"); + let t0 = std::time::Instant::now(); + while s.lensfun.running() && t0.elapsed() < std::time::Duration::from_secs(60) { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + lens_profiles::use_dir(before); + let _ = std::fs::remove_dir_all(&root); +} 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/mask_geometry.rs b/crates/engine/src/tests/mask_geometry.rs new file mode 100644 index 0000000000..c2a1edef85 --- /dev/null +++ b/crates/engine/src/tests/mask_geometry.rs @@ -0,0 +1,315 @@ +//! Masks stay on the photo's content when its geometry changes: Rotate +//! Left / Right turns them with the photo, an old mask (on the corrected frame) goes onto the +//! photo at its next edit without moving, and the AI models see the photo the masks live on +//! (no lens corrections, Upright, Transform, crop or flips), so changing those leaves the AI +//! selections as they are. + +use lightcraft_develop::{DevelopSettings, Mask, MaskComponent, MaskOp, MaskShape}; +use lightcraft_geom::Point; +use serde_json::json; + +use crate::Session; + +fn active_dev(s: &Session) -> DevelopSettings { + (*s.develop_of(s.active().unwrap()).unwrap()).clone() +} + +fn radial_at(p: Point) -> Mask { + Mask { + id: 1, + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Radial { center: p, rx: 0.1, ry: 0.05, angle: 20.0, feather: 50.0, invert: false }, + }], + ..Default::default() + } +} + +fn centre(d: &DevelopSettings) -> (Point, f64) { + match &d.masks[0].components[0].shape { + MaskShape::Radial { center, angle, .. } => (*center, *angle), + other => panic!("{other:?}"), + } +} + +#[test] +fn rotating_the_photo_turns_its_masks_with_it() { + let mut s = Session::with_demo(); + let id = s.active().unwrap(); + let mut d = active_dev(&s); + let p = Point::new(0.2, 0.3); + d.masks = vec![radial_at(p)]; + s.set_develop(id, d, "Mask").unwrap(); + s.execute("photo.rotateRight", &json!({})).unwrap(); + let (c, a) = centre(&active_dev(&s)); + // a quarter turn clockwise: (x, y) → (1 − y, x), and the ellipse turns along + assert!((c.x - 0.7).abs() < 1e-9 && (c.y - 0.2).abs() < 1e-9, "{c:?}"); + assert_eq!(a, 110.0); + s.execute("photo.rotateLeft", &json!({})).unwrap(); + let (c, a) = centre(&active_dev(&s)); + assert!((c.x - p.x).abs() < 1e-9 && (c.y - p.y).abs() < 1e-9 && a == 20.0, "{c:?} {a}"); +} + +#[test] +fn an_old_mask_goes_onto_the_photo_at_its_next_edit_without_moving() { + let mut s = Session::with_demo(); + let id = s.active().unwrap(); + let mut d = active_dev(&s); + d.geometry.vertical = 30.0; + d.geometry.rotate = 5.0; + let p = Point::new(0.3, 0.4); + let mut m = radial_at(p); + m.on_photo = false; + d.masks = vec![m]; + // as a catalog from before keeps it + s.catalog.apply(lightcraft_catalog::Op::SetDevelop { id, settings: std::sync::Arc::new(d.clone()), label: "Old".into(), edited: None }).unwrap(); + assert!(!active_dev(&s).masks[0].on_photo); + d.light.exposure = 0.5; + s.set_develop(id, d.clone(), "Exposure").unwrap(); + let now = active_dev(&s); + assert!(now.masks[0].on_photo, "attached at the edit"); + let photo = s.catalog.photo(id).unwrap(); + let frame = lightcraft_pipeline::geometry::Frame::with_lens(photo.width as usize, photo.height as usize, &d, false, None); + let (c, _) = centre(&now); + let back = frame.for_mask(true).mask_to_norm(c); + assert!((back.x - p.x).abs() < 1e-6 && (back.y - p.y).abs() < 1e-6, "renders where it did: {back:?}"); + assert!((c.x - p.x).hypot(c.y - p.y) > 0.005, "its place on the photo differs from the corrected frame's: {c:?}"); + // a later Transform change leaves it on the photo where it is + let mut d = now.clone(); + d.geometry.vertical = -10.0; + s.set_develop(id, d, "Transform").unwrap(); + assert_eq!(centre(&active_dev(&s)).0, c); +} + +#[test] +fn the_ai_models_see_the_photo_the_masks_live_on() { + let mut s = Session::with_demo(); + let id = s.active().unwrap(); + let key = s.segment_key(id).unwrap().0; + let mut d = active_dev(&s); + d.geometry.vertical = 20.0; + d.optics.distortion = 30.0; + d.crop.geometry.angle = 5.0; + d.crop.flip_h = true; + s.set_develop(id, d.clone(), "Geometry").unwrap(); + assert_eq!(s.segment_key(id).unwrap().0, key, "geometry doesn't change what the models see: the AI masks stay valid"); + d.light.exposure = 1.0; + s.set_develop(id, d, "Exposure").unwrap(); + assert_ne!(s.segment_key(id).unwrap().0, key, "the look still does"); +} + +/// A mask saved before `Mask::on_photo` reads as an old mask (on the corrected frame), a new mask +/// is on the photo, and an old one is written as it was read. +#[test] +fn a_mask_saved_before_reads_as_an_old_mask() { + let old: Mask = serde_json::from_value(json!({"id": 3, "name": "Mask 3", "components": []})).unwrap(); + assert!(!old.on_photo); + assert!(Mask::default().on_photo); + let written = serde_json::to_value(&old).unwrap(); + assert!(written.get("on_photo").is_none(), "{written}"); + assert_eq!(serde_json::to_value(Mask::default()).unwrap()["on_photo"], json!(true)); +} + +/// Old masks an edit brings in (paste, sync, a preset, a history step, a sidecar) go onto the +/// photo from the settings they came with, where they render now, not from the photo's settings +/// before the edit (review of #3550). +#[test] +fn old_masks_an_edit_brings_in_go_onto_the_photo_from_the_settings_they_came_with() { + let mut s = Session::with_demo(); + let id = s.active().unwrap(); + // the photo now: no Transform + let before = active_dev(&s); + // what comes in: a Transform and an old mask drawn under it + let p = Point::new(0.3, 0.4); + let mut incoming = before.clone(); + incoming.geometry.vertical = 30.0; + incoming.geometry.rotate = 5.0; + let mut m = radial_at(p); + m.on_photo = false; + incoming.masks = vec![m]; + s.set_develop(id, incoming.clone(), "Paste Settings").unwrap(); + let now = active_dev(&s); + assert!(now.masks[0].on_photo); + let photo = s.catalog.photo(id).unwrap(); + let frame = lightcraft_pipeline::geometry::Frame::with_lens(photo.width as usize, photo.height as usize, &incoming, false, None); + let back = frame.for_mask(true).mask_to_norm(centre(&now).0); + assert!((back.x - p.x).abs() < 1e-6 && (back.y - p.y).abs() < 1e-6, "renders where it did under its own settings: {back:?}"); +} + +/// A click on an old Object mask goes onto the photo with the mask before the model reads it: the +/// stored clicks and the new one are then in the same coordinates (review of #3550). +#[test] +fn a_click_on_an_old_object_mask_goes_onto_the_photo_with_it() { + let mut s = Session::with_demo(); + let id = s.active().unwrap(); + let mut d = active_dev(&s); + d.geometry.vertical = 30.0; + d.geometry.rotate = 5.0; + let p = Point::new(0.3, 0.4); + d.masks = vec![Mask { + id: 1, + on_photo: false, + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Object { hint: vec![p], exclude: Vec::new(), seg: None, detail: Vec::new(), edge: 0.0 }, + }], + ..Default::default() + }]; + s.catalog.apply(lightcraft_catalog::Op::SetDevelop { id, settings: std::sync::Arc::new(d.clone()), label: "Old".into(), edited: None }).unwrap(); + s.active_mask = Some(1); + // (no model: the command fails at the model, after the mask went onto the photo) + s.segmenter.dir = Some(std::env::temp_dir().join("lightcraft-no-model-mask-geometry")); + let _ = s.execute("mask.objectPoint", &json!({"x": 0.6, "y": 0.5})); + let now = active_dev(&s); + assert!(now.masks[0].on_photo); + let photo = s.catalog.photo(id).unwrap(); + let frame = lightcraft_pipeline::geometry::Frame::with_lens(photo.width as usize, photo.height as usize, &d, false, None); + let MaskShape::Object { hint, .. } = &now.masks[0].components[0].shape else { panic!() }; + let want = frame.for_mask(true).norm_to_mask(p); + assert!((hint[0].x - want.x).abs() < 1e-9 && (hint[0].y - want.y).abs() < 1e-9, "{hint:?} vs {want:?}"); +} + +/// An old mask the photo keeps, when an edit both brings in a mask and changes the geometry (a +/// preset), goes onto the photo from the photo's settings before the edit, where it rendered; the +/// mask brought in, from the settings it came with (review of #3550). +#[test] +fn a_kept_old_mask_attaches_under_the_settings_before_an_edit_that_adds_one() { + let mut s = Session::with_demo(); + let id = s.active().unwrap(); + let mut d = active_dev(&s); + d.geometry.vertical = 30.0; + d.geometry.rotate = 5.0; + let p = Point::new(0.3, 0.4); + let mut kept = radial_at(p); + kept.on_photo = false; + d.masks = vec![kept]; + s.catalog.apply(lightcraft_catalog::Op::SetDevelop { id, settings: std::sync::Arc::new(d.clone()), label: "Old".into(), edited: None }).unwrap(); + // the preset: another Transform and a new old mask + let mut incoming = d.clone(); + incoming.geometry.vertical = -20.0; + incoming.geometry.rotate = 0.0; + let q = Point::new(0.6, 0.6); + let mut added = radial_at(q); + added.id = 2; + added.on_photo = false; + incoming.masks.push(added); + s.set_develop(id, incoming.clone(), "Preset").unwrap(); + let now = active_dev(&s); + assert!(now.masks.iter().all(|m| m.on_photo)); + let photo = s.catalog.photo(id).unwrap(); + let frame = |d: &DevelopSettings| lightcraft_pipeline::geometry::Frame::with_lens(photo.width as usize, photo.height as usize, d, false, None); + let at = |m: &Mask| match &m.components[0].shape { + MaskShape::Radial { center, .. } => *center, + other => panic!("{other:?}"), + }; + let back = frame(&d).for_mask(true).mask_to_norm(at(&now.masks[0])); + assert!((back.x - p.x).abs() < 1e-6 && (back.y - p.y).abs() < 1e-6, "the kept mask, from the frame it was drawn on: {back:?}"); + let back = frame(&incoming).for_mask(true).mask_to_norm(at(&now.masks[1])); + assert!((back.x - q.x).abs() < 1e-6 && (back.y - q.y).abs() < 1e-6, "the added mask, from its own: {back:?}"); +} + +/// A sync or paste of the Crop group without the Masks group turns the photo: its masks turn with +/// it, as Rotate does (review of #3550). +#[test] +fn masks_turn_with_an_orientation_a_sync_brings() { + let mut s = Session::with_demo(); + let id = s.active().unwrap(); + let mut d = active_dev(&s); + let p = Point::new(0.2, 0.3); + d.masks = vec![radial_at(p)]; + s.set_develop(id, d.clone(), "Mask").unwrap(); + let mut synced = d.clone(); + synced.orientation = d.orientation.rotated(true); + s.set_develop(id, synced, "Sync Settings").unwrap(); + let (c, a) = centre(&active_dev(&s)); + assert!((c.x - 0.7).abs() < 1e-9 && (c.y - 0.2).abs() < 1e-9 && a == 110.0, "{c:?} {a}"); + // Rotate itself still turns them once + s.execute("photo.rotateLeft", &json!({})).unwrap(); + let (c, a) = centre(&active_dev(&s)); + assert!((c.x - p.x).abs() < 1e-9 && (c.y - p.y).abs() < 1e-9 && a == 20.0, "{c:?} {a}"); +} + +/// The change between two orientations is the turn Rotate makes, and none between equal ones. +#[test] +fn the_change_between_orientations_is_the_turn_made() { + use lightcraft_geom::Orientation; + for k in 0..8u8 { + let o = Orientation::from_parts(k >= 4, k % 4); + assert_eq!(crate::orientation_change(o, o), None); + for cw in [true, false] { + assert_eq!(crate::orientation_change(o, o.rotated(cw)), Some(Orientation::Normal.rotated(cw)), "{o:?} {cw}"); + } + } +} + +/// An old Object mask with a Transform active, and a click. +fn old_object_mask() -> (Session, lightcraft_catalog::PhotoId, DevelopSettings, Point) { + let mut s = Session::with_demo(); + let id = s.active().unwrap(); + let mut d = active_dev(&s); + d.geometry.vertical = 30.0; + d.geometry.rotate = 5.0; + let p = Point::new(0.3, 0.4); + d.masks = vec![Mask { + id: 1, + on_photo: false, + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Object { hint: vec![p], exclude: Vec::new(), seg: None, detail: Vec::new(), edge: 0.0 }, + }], + ..Default::default() + }]; + s.catalog.apply(lightcraft_catalog::Op::SetDevelop { id, settings: std::sync::Arc::new(d.clone()), label: "Old".into(), edited: None }).unwrap(); + s.active_mask = Some(1); + (s, id, d, p) +} + +/// A click on an old Object mask that lands off the photo (the corrected frame's blank space) is +/// refused, not moved onto the photo's edge, and leaves the mask as it was (review of #3550). +#[test] +fn a_click_off_the_photo_on_an_old_object_mask_is_refused() { + let (mut s, id, d, _) = old_object_mask(); + let photo = s.catalog.photo(id).unwrap(); + let frame = lightcraft_pipeline::geometry::Frame::with_lens(photo.width as usize, photo.height as usize, &d, false, None); + let f = frame.for_mask(true); + let off = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.5, 0.0), (0.5, 1.0)] + .map(|(x, y)| Point::new(x, y)) + .into_iter() + .find(|p| { + let n = f.norm_to_mask(*p); + !(n.x.is_finite() && n.y.is_finite()) || n.x < -0.01 || n.x > 1.01 || n.y < -0.01 || n.y > 1.01 + }) + .expect("a corner of the transformed frame is off the photo"); + let e = s.execute("mask.objectPoint", &json!({"x": off.x, "y": off.y})).unwrap_err().to_string(); + assert!(e.contains("outside the photo"), "{e}"); + assert_eq!(active_dev(&s).masks, d.masks, "nothing changed"); +} + +/// The click on its way to the model is in the mask's coordinates with the stored ones (with a +/// model folder that looks installed; skipped where the build has no model support). +#[test] +fn a_pending_click_on_an_old_object_mask_is_in_the_masks_coordinates() { + if !crate::segment::Segmenter::AVAILABLE { + lightcraft_testkit::skip!(Model, "built without the segmentation model"); + return; + } + let (mut s, id, d, p) = old_object_mask(); + s.segmenter.background = true; + s.segmenter.dir = Some(super::segment::damaged_model("mask-geometry-pending")); + let r = s.execute("mask.objectPoint", &json!({"x": 0.6, "y": 0.5})).unwrap(); + assert_eq!(r["pending"], true); + let photo = s.catalog.photo(id).unwrap(); + let frame = lightcraft_pipeline::geometry::Frame::with_lens(photo.width as usize, photo.height as usize, &d, false, None); + let f = frame.for_mask(true); + let pending = s.segmenter.pending_clicks().expect("the click is pending").clone(); + assert_eq!(pending.hint.len(), 2); + for (got, want) in pending.hint.iter().zip([f.norm_to_mask(p), f.norm_to_mask(Point::new(0.6, 0.5))]) { + assert!((got.x - want.x).abs() < 1e-9 && (got.y - want.y).abs() < 1e-9, "{got:?} vs {want:?}"); + } +} diff --git a/crates/engine/src/tests/move_to_share.rs b/crates/engine/src/tests/move_to_share.rs index ed824b29d8..e7602818e4 100644 --- a/crates/engine/src/tests/move_to_share.rs +++ b/crates/engine/src/tests/move_to_share.rs @@ -254,6 +254,19 @@ fn other_device(here: &std::path::Path) -> Option { } } +#[cfg(unix)] +#[test] +fn a_link_is_not_copied_as_its_target() { + use crate::rename::MoveFs; + let dir = Scratch::new("copy-link"); + std::fs::create_dir_all(dir.0.join("local")).unwrap(); + std::fs::create_dir_all(dir.0.join("share")).unwrap(); + std::fs::write(dir.0.join("local/private.txt"), b"secret").unwrap(); + std::os::unix::fs::symlink(dir.0.join("local/private.txt"), dir.0.join("local/photo.xmp")).unwrap(); + assert!(crate::rename::RealFs.copy_no_replace(&dir.0.join("local/photo.xmp"), &dir.0.join("share/photo.xmp")).is_err()); + assert!(!dir.0.join("share/photo.xmp").exists()); +} + #[test] fn the_copy_across_volumes_is_whole_or_absent_and_never_replaces() { use crate::rename::MoveFs; diff --git a/crates/engine/src/tests/segment.rs b/crates/engine/src/tests/segment.rs index ceb2365fbe..b649dbdd7e 100644 --- a/crates/engine/src/tests/segment.rs +++ b/crates/engine/src/tests/segment.rs @@ -17,7 +17,7 @@ fn tmp(name: &str) -> std::path::PathBuf { } /// A folder that looks installed but holds no usable model. -fn damaged_model(name: &str) -> std::path::PathBuf { +pub(super) fn damaged_model(name: &str) -> std::path::PathBuf { let d = tmp(name); std::fs::create_dir_all(&d).unwrap(); std::fs::write(d.join("model.safetensors"), b"\x10\x00\x00\x00\x00\x00\x00\x00{not json at all}").unwrap(); diff --git a/crates/engine/src/tests/slow_drive.rs b/crates/engine/src/tests/slow_drive.rs new file mode 100644 index 0000000000..f9942986aa --- /dev/null +++ b/crates/engine/src/tests/slow_drive.rs @@ -0,0 +1,317 @@ +//! PERF-STEP-STALL: culling on a slow or failing drive. A flag or rating never waits for the drive +//! (the catalog log is written and synced by a thread of its own), and nothing made meanwhile is +//! lost: it is on disk once the save lands, after a clean quit, after a quit with no close, and, +//! when the drive fails, held, retried and reported as unsaved until it is written. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use lightcraft_catalog::fault::{self, Step}; +use lightcraft_catalog::{Flag, PhotoId}; +use serde_json::json; + +use crate::Session; + +fn temp_dir(tag: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("lc-engine-slow-drive-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + d +} + +fn open(dir: &std::path::Path) -> Session { + let mut s = Session::new(); + s.open_library(dir, true).unwrap(); + s +} + +fn ids(s: &Session) -> Vec { + let mut v: Vec = s.catalog.photos().map(|p| p.id).collect(); + v.sort(); + v +} + +/// Every sync of the log in `dir` takes `sync` (a busy disk: Windows makes a write wait for a sync +/// of the same file in flight); `fail` makes every write fail while it is set. +fn slow_drive(dir: &std::path::Path, sync: Duration, fail: Arc) { + fault::install( + dir, + Arc::new(move |step| { + if fail.load(Ordering::SeqCst) { + return Err(std::io::Error::other("the drive is gone (test)")); + } + if step == Step::Sync { + std::thread::sleep(sync); + } + Ok(()) + }), + ); +} + +/// The flag or rating each photo got, as `(id, flag, rating)`. +fn culled(s: &Session) -> Vec<(PhotoId, Flag, u8)> { + ids(s).into_iter().filter_map(|id| s.catalog.photo(id).map(|p| (id, p.flag, p.rating))).collect() +} + +/// Flag and rate every photo the way a photographer culls: pick / reject in turn, a rating on +/// every other one. Returns the slowest command, in ms. +fn cull(s: &mut Session, rounds: usize) -> f64 { + let all = ids(s); + let mut slowest = 0.0f64; + for k in 0..rounds { + for (i, id) in all.iter().enumerate() { + let flag = if (i + k) % 2 == 0 { "pick" } else { "reject" }; + let t = Instant::now(); + s.execute("photo.flag", &json!({"flag": flag, "ids": [id.0]})).unwrap(); + slowest = slowest.max(t.elapsed().as_secs_f64() * 1000.0); + if i % 2 == 0 { + let t = Instant::now(); + s.execute("photo.rate", &json!({"rating": ((i + k) % 5) as u8 + 1, "ids": [id.0]})).unwrap(); + slowest = slowest.max(t.elapsed().as_secs_f64() * 1000.0); + } + } + } + slowest +} + +/// (a) With every sync of the log taking 300 ms, a flag or rating returns long before one sync. +/// The same culling with the log written on the caller's thread (as before PERF-STEP-STALL) waits +/// for a sync on every key, which is what this test would see without the fix. +#[test] +fn a_flag_never_waits_for_a_slow_drive() { + let sync = Duration::from_millis(300); + let mut seen = Vec::new(); + for on_caller in [true, false] { + let dir = temp_dir(if on_caller { "wait-before" } else { "wait" }); + fault::write_on_caller(&dir, on_caller); + let mut s = open(&dir); + slow_drive(&dir, sync, Arc::new(AtomicBool::new(false))); + let t = Instant::now(); + let slowest = cull(&mut s, 1); + let total = t.elapsed().as_secs_f64() * 1000.0; + let n = s.library.as_ref().map_or(0, |l| l.journal().stats().appends); + eprintln!( + "{} drive syncing in 300 ms: slowest command {slowest:.1} ms, {total:.0} ms for the culling", + if on_caller { "before (log written on the caller):" } else { "after (log on its own thread):" } + ); + seen.push((slowest, total, n)); + drop(s); + fault::remove(&dir); + fault::write_on_caller(&dir, false); + let _ = std::fs::remove_dir_all(&dir); + } + let ((before, _, _), (after, _, _)) = (seen[0], seen[1]); + assert!(before >= 300.0, "the caller waited for its sync before: {before:.1} ms"); + // a debug build of the whole workspace's tests at once leaves room; one sync is 300 ms + assert!(after < 120.0, "a command waited for the drive: {after:.1} ms"); +} + +/// (b) Everything flagged and rated while slow saves are in flight is on disk once they land +/// (a flush), after a quit with no close (the process ends normally: the log's thread finishes), +/// and after a clean quit (`close_library`). +#[test] +fn every_change_made_during_a_slow_save_is_on_disk() { + for how in ["flush", "drop", "close"] { + let dir = temp_dir(&format!("kept-{how}")); + let mut s = open(&dir); + slow_drive(&dir, Duration::from_millis(150), Arc::new(AtomicBool::new(false))); + cull(&mut s, 3); + let want = culled(&s); + let expect = s.catalog.to_snapshot(); + match how { + "flush" => { + s.library.as_mut().unwrap().journal_mut().flush().unwrap(); + // a copy of the files taken now (the next crash) holds everything + let copy = temp_dir("kept-copy"); + std::fs::create_dir_all(©).unwrap(); + for f in [lightcraft_catalog::journal::SNAPSHOT, lightcraft_catalog::journal::LOG] { + if dir.join(f).exists() { + std::fs::copy(dir.join(f), copy.join(f)).unwrap(); + } + } + let (_, c, _) = lightcraft_catalog::Journal::open(Box::new(lightcraft_catalog::store::FsStore::open(©).unwrap())).unwrap(); + assert_eq!(c.to_snapshot(), expect, "{how}"); + let _ = std::fs::remove_dir_all(©); + } + "close" => s.close_library().unwrap(), + _ => {} + } + assert!(s.unsaved().is_none(), "{how}: {:?}", s.unsaved()); + drop(s); + fault::remove(&dir); + let again = open(&dir); + assert_eq!(culled(&again), want, "{how}"); + assert_eq!(again.catalog.to_snapshot(), expect, "{how}"); + drop(again); + let _ = std::fs::remove_dir_all(&dir); + } +} + +/// Wait (bounded) until `done` holds, calling the frame loop's save meanwhile. +fn frames_until(s: &mut Session, what: &str, mut done: impl FnMut(&Session) -> bool) { + let t = Instant::now(); + while !done(s) { + assert!(t.elapsed() < Duration::from_secs(20), "{what}: {:?}", s.unsaved()); + s.persist_if_dirty(); + std::thread::sleep(Duration::from_millis(20)); + } +} + +/// (c) A drive that fails: the flags handed over before the failure are held and retried, never +/// dropped; the failure is reported (`unsaved`, the quit prompt's source) and later flags fail +/// with `NotSaved` and stay queued; once the drive is back, all of it is written, in order, with +/// no gap in the log. +#[test] +fn a_failed_write_is_reported_and_retried_never_dropped() { + let dir = temp_dir("fail"); + let mut s = open(&dir); + let fail = Arc::new(AtomicBool::new(false)); + slow_drive(&dir, Duration::from_millis(5), fail.clone()); + let all = ids(&s); + fail.store(true, Ordering::SeqCst); + // handed over before the thread found out: accepted, then held + s.execute("photo.flag", &json!({"flag": "pick", "ids": [all[0].0]})).unwrap(); + // the quit check reads it at once, not as of the last frame (review of #3557) + let t = Instant::now(); + while s.library.as_ref().unwrap().journal().unwritten().is_none() { + assert!(t.elapsed() < Duration::from_secs(20), "the log thread never reported the failure"); + std::thread::sleep(Duration::from_millis(10)); + } + s.refresh_unsaved(); + assert!(s.unsaved().is_some(), "refreshed for the quit check"); + let (n, why) = s.unsaved().map(|(n, w)| (n, w.to_string())).unwrap(); + assert!(n >= 1 && why.contains("the drive is gone"), "{n} {why}"); + // later flags: refused with the reason, kept in memory and queued + let r = s.execute("photo.flag", &json!({"flag": "reject", "ids": [all[1].0]})); + assert!(matches!(r, Err(crate::EngineError::NotSaved(_))), "{r:?}"); + assert_eq!(s.catalog.photo(all[1]).unwrap().flag, Flag::Reject, "applied in memory"); + let _ = s.execute("photo.rate", &json!({"rating": 4, "ids": [all[2].0]})); + assert!(s.unsaved().is_some_and(|(n, _)| n >= 3), "{:?}", s.unsaved()); + // the drive is back: the held record and the queued ones are written by the frame loop + fail.store(false, Ordering::SeqCst); + frames_until(&mut s, "written once the drive is back", |s| s.unsaved().is_none() && s.pending_log.is_empty()); + let want = culled(&s); + let expect = s.catalog.to_snapshot(); + // a crash now: the files alone hold everything, and the log has no gap (no damage on load) + s.library.as_mut().unwrap().journal_mut().flush().unwrap(); + let copy = temp_dir("fail-copy"); + std::fs::create_dir_all(©).unwrap(); + for f in [lightcraft_catalog::journal::SNAPSHOT, lightcraft_catalog::journal::LOG] { + if dir.join(f).exists() { + std::fs::copy(dir.join(f), copy.join(f)).unwrap(); + } + } + let (_, c, report) = lightcraft_catalog::Journal::open(Box::new(lightcraft_catalog::store::FsStore::open(©).unwrap())).unwrap(); + assert!(report.damaged.is_none(), "{report:?}"); + assert_eq!(c.to_snapshot(), expect); + let _ = std::fs::remove_dir_all(©); + fault::remove(&dir); + drop(s); + assert_eq!(culled(&open(&dir)), want); + let _ = std::fs::remove_dir_all(&dir); +} + +/// (c) The drive stays broken for the log until the quit: the quit prompt is told (unsaved), and +/// the closing snapshot (a fresh file) saves the held flags, so they are there on the next open. +#[test] +fn a_log_that_stays_broken_is_saved_by_the_closing_snapshot() { + let dir = temp_dir("broken"); + let mut s = open(&dir); + let all = ids(&s); + let fail = Arc::new(AtomicBool::new(false)); + slow_drive(&dir, Duration::from_millis(5), fail.clone()); + fail.store(true, Ordering::SeqCst); + s.execute("photo.flag", &json!({"flag": "reject", "ids": [all[0].0]})).unwrap(); + frames_until(&mut s, "the failure is reported", |s| s.unsaved().is_some()); + let _ = s.execute("photo.flag", &json!({"flag": "pick", "ids": [all[1].0]})); + let want = culled(&s); + // (the snapshot itself is written by the store, which the hook leaves alone; the log's reset + // after it fails, so close reports it, but the snapshot holds everything) + let _ = s.close_library(); + // the snapshot holds them: the quit prompt must not say they would be lost (review of #3557) + assert!(s.unsaved().is_none(), "{:?}", s.unsaved()); + drop(s); + fault::remove(&dir); + let again = open(&dir); + assert!(again.library.as_ref().unwrap().report.damaged.is_none()); + assert_eq!(culled(&again), want); + drop(again); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The same library opened again in the same session (Settings, Libraries; a reopen after an +/// error): everything the old session's log thread was handed is in the files before the new one +/// reads them (review of #3557). +#[test] +fn reopening_the_same_library_reads_what_its_log_thread_was_handed() { + let dir = temp_dir("reopen"); + let mut s = open(&dir); + fault::install( + &dir, + Arc::new(|step| { + if step == Step::Write { + std::thread::sleep(Duration::from_millis(300)); + } + Ok(()) + }), + ); + let all = ids(&s); + s.execute("photo.flag", &json!({"flag": "reject", "ids": [all[0].0]})).unwrap(); + s.open_library(&dir, true).unwrap(); + fault::remove(&dir); + assert_eq!(s.catalog.photo(all[0]).unwrap().flag, Flag::Reject); + drop(s); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The same library opened again while its log's thread can't write what it was handed: the open +/// fails and the current library stays open with the change (held, retried), instead of a new +/// catalog read from files that miss it (review of #3557). Once the drive is back, the reopen +/// reads it. +#[test] +fn a_reopen_waits_for_what_the_log_thread_could_not_write() { + let dir = temp_dir("reopen-fail"); + let mut s = open(&dir); + let all = ids(&s); + let fail = Arc::new(AtomicBool::new(false)); + slow_drive(&dir, Duration::from_millis(5), fail.clone()); + fail.store(true, Ordering::SeqCst); + s.execute("photo.flag", &json!({"flag": "reject", "ids": [all[0].0]})).unwrap(); + let r = s.open_library(&dir, true); + assert!(matches!(r, Err(crate::EngineError::NotSaved(_))), "{r:?}"); + assert_eq!(s.catalog.photo(all[0]).unwrap().flag, Flag::Reject, "the open library keeps the change"); + assert!(s.unsaved().is_some(), "and says it isn't saved yet"); + fail.store(false, Ordering::SeqCst); + let t = Instant::now(); + while s.library.as_mut().unwrap().journal_mut().flush().is_err() { + assert!(t.elapsed() < Duration::from_secs(20), "never written"); + std::thread::sleep(Duration::from_millis(50)); + } + s.open_library(&dir, true).unwrap(); + fault::remove(&dir); + assert_eq!(s.catalog.photo(all[0]).unwrap().flag, Flag::Reject); + drop(s); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A reopen while the log still can't be written, but after a snapshot that holds every change +/// (the log's reset after it failed): nothing is missing from the files, so the open goes ahead +/// (review of #3557). +#[test] +fn a_reopen_after_a_snapshot_that_holds_everything_goes_ahead() { + let dir = temp_dir("reopen-snap"); + let mut s = open(&dir); + let all = ids(&s); + let fail = Arc::new(AtomicBool::new(false)); + slow_drive(&dir, Duration::from_millis(5), fail.clone()); + fail.store(true, Ordering::SeqCst); + s.execute("photo.flag", &json!({"flag": "reject", "ids": [all[0].0]})).unwrap(); + let _ = s.close_library(); + assert!(s.snapshot_holds_everything()); + s.open_library(&dir, true).unwrap(); + assert_eq!(s.catalog.photo(all[0]).unwrap().flag, Flag::Reject); + fault::remove(&dir); + drop(s); + assert_eq!(open(&dir).catalog.photo(all[0]).unwrap().flag, Flag::Reject); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/text.rs b/crates/engine/src/text.rs index 0e2e39c1ea..c3585c3b88 100644 --- a/crates/engine/src/text.rs +++ b/crates/engine/src/text.rs @@ -57,6 +57,19 @@ pub fn cell_glyphs(font: &FontRef<'_>, data: &harfrust::ShaperData, text: &str, Some(glyphs) } +/// NFC, except CJK compatibility ideographs, which NFC would swap for their unified forms. +fn compose(text: &str) -> String { + use unicode_normalization::UnicodeNormalization; + let compatibility = |c: char| matches!(c, '\u{F900}'..='\u{FAFF}' | '\u{2F800}'..='\u{2FA1F}'); + let mut out = String::with_capacity(text.len()); + for part in text.split_inclusive(compatibility) { + let kept = part.chars().next_back().filter(|&c| compatibility(c)); + out.extend(kept.and_then(|c| part.strip_suffix(c)).unwrap_or(part).nfc()); + out.extend(kept); + } + out +} + /// A string laid out at one size: its glyphs relative to the box's top-left corner and the box's /// size in pixels (lines are `px` apart; vertical text: columns `px` wide, right to left). pub struct TextLayout { @@ -79,6 +92,9 @@ impl TextLayout { Some((i, _)) => text.get(..i).unwrap_or(text), None => text, }; + // macOS file names are often decomposed (NFD); the layout below draws one glyph per char + let composed = compose(text); + let text = composed.as_str(); let fonts = faces(craft); let latin = fonts.first()?.clone(); let vertical_data: Vec<_> = if vertical { @@ -264,6 +280,48 @@ mod tests { } } + fn assert_draws_composed(text: &str, craft: &'static [CraftFont]) { + use unicode_normalization::UnicodeNormalization; + let nfc: String = text.nfc().collect(); + let nfd: String = text.nfd().collect(); + assert_ne!(nfc, nfd); + let (a, b) = (TextLayout::new(&nfc, 40.0, false, craft).unwrap(), TextLayout::new(&nfd, 40.0, false, craft).unwrap()); + let ids = |l: &TextLayout| l.glyphs.iter().map(|(face, g, _)| (*face, g.id.0)).collect::>(); + assert_eq!(ids(&b), ids(&a)); + assert_eq!(b.width, a.width); + assert!(a.glyphs.iter().all(|(_, g, _)| g.id.0 != 0)); + } + + #[test] + fn decomposed_vietnamese_draws_its_composed_letters() { + assert_draws_composed("HỌC ĐỂ ỨNG DỤNG", &[]); + } + + #[test] + fn decomposed_hangul_draws_whole_syllables() { + if !CRAFT_FONTS.iter().any(|font| font.covers("Hang")) { + lightcraft_testkit::skip!(Fonts, "built without a Hangul face from craft-fonts"); + return; + } + assert_draws_composed("제주도 바다 여행.jpg", CRAFT_FONTS); + } + + #[test] + fn compatibility_ideographs_keep_their_code_points() { + use unicode_normalization::UnicodeNormalization; + let nfd = |s: &str| s.nfd().collect::(); + let text = format!("\u{FA10}{} \u{2F800}{}\u{F900}", nfd("본 제주"), nfd("Ọ")); + assert_eq!(compose(&text), "\u{FA10}본 제주 \u{2F800}Ọ\u{F900}"); + } + + #[test] + fn already_composed_text_stays_as_it_is() { + for text in ["", "plain.jpg", "제주도 바다 여행.jpg", "HỌC ĐỂ ỨNG DỤNG"] { + assert!(unicode_normalization::is_nfc(text), "{text}"); + assert_eq!(compose(text), text); + } + } + #[test] fn bundled_thai_uses_its_glyphs() { assert_script_glyphs("Thai", "สวัสดีครับ"); diff --git a/crates/engine/src/walk.rs b/crates/engine/src/walk.rs index 98290130ea..db024f7098 100644 --- a/crates/engine/src/walk.rs +++ b/crates/engine/src/walk.rs @@ -95,17 +95,37 @@ pub type NoteFolder<'a> = &'a mut dyn FnMut(&Path, Vec<(std::ffi::OsString, Entr /// are left out, the folder `skip` (e.g. the library's own) is never entered, and the walk stops /// at `limits` (see [`Walked::truncated`]). Unreadable folders are skipped. pub fn files_in(root: &Path, skip: Option<&Path>, limits: Limits, keep: impl FnMut(&Path) -> bool) -> Walked { - walk(root, skip, limits, keep, None) + walk(root, skip, limits, keep, |_| true, None) +} + +/// [`files_in`], entering a folder below `root` only when `enter` accepts it: a folder it turns +/// down is neither listed nor counted against `limits` (e.g. a NAS's `@eaDir` thumbnail folders, +/// which can hold more entries than the photos beside them). +pub fn files_in_entering( + root: &Path, + skip: Option<&Path>, + limits: Limits, + keep: impl FnMut(&Path) -> bool, + enter: impl FnMut(&Path) -> bool, +) -> Walked { + walk(root, skip, limits, keep, enter, None) } /// [`files_in`], handing the listing of every folder it reads to `note`: who walks a folder to /// find its files has, with that, the answer to "is this name there" for everything in it, and /// need not ask the disk again (a round trip for each name on a network share). pub fn files_in_noting(root: &Path, skip: Option<&Path>, limits: Limits, keep: impl FnMut(&Path) -> bool, note: NoteFolder) -> Walked { - walk(root, skip, limits, keep, Some(note)) + walk(root, skip, limits, keep, |_| true, Some(note)) } -fn walk(root: &Path, skip: Option<&Path>, limits: Limits, mut keep: impl FnMut(&Path) -> bool, mut note: Option) -> Walked { +fn walk( + root: &Path, + skip: Option<&Path>, + limits: Limits, + mut keep: impl FnMut(&Path) -> bool, + mut enter: impl FnMut(&Path) -> bool, + mut note: Option, +) -> Walked { let mut out = Walked::default(); // canonical folders reached through a link, so a link loop is walked at most once let mut linked: HashSet = HashSet::new(); @@ -171,6 +191,11 @@ fn walk(root: &Path, skip: Option<&Path>, limits: Limits, mut keep: impl FnMut(& // a link (or a Windows junction): a folder is entered once, a file is a file match std::fs::metadata(&p) { Ok(m) if m.is_dir() => { + // (asked before the folder is marked as entered, so a folder turned down + // here can still be entered through another link to it) + if !enter(&p) { + continue; + } let Ok(c) = std::fs::canonicalize(&p) else { continue }; if !linked.insert(c) { continue; @@ -179,8 +204,13 @@ fn walk(root: &Path, skip: Option<&Path>, limits: Limits, mut keep: impl FnMut(& } _ => false, } + } else if ft.is_dir() { + if !enter(&p) { + continue; + } + true } else { - ft.is_dir() + false }; children.push((p, dir)); } @@ -343,6 +373,41 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// A folder `enter` turns down is not listed: its entries neither come back nor use up the + /// entry budget, so a sibling folder after it is still walked. + #[test] + fn folders_turned_down_are_not_listed_or_counted() { + let d = tmp("enter"); + std::fs::create_dir_all(d.join("@eaDir")).unwrap(); + std::fs::create_dir_all(d.join("z")).unwrap(); + for i in 0..20 { + std::fs::write(d.join("@eaDir").join(format!("{i:02}.jpg")), b"x").unwrap(); + } + std::fs::write(d.join("z/keep.jpg"), b"x").unwrap(); + let not_at = |p: &Path| !p.file_name().is_some_and(|n| n.to_string_lossy().starts_with('@')); + let w = files_in_entering(&d, None, Limits { max_depth: 8, max_entries: 5 }, |_| true, not_at); + assert_eq!((w.files, w.entries, w.truncated), (vec![d.join("z/keep.jpg")], 3, false)); + let _ = std::fs::remove_dir_all(&d); + } + + /// A link `enter` turns down does not use up its folder's one visit through a link: another + /// link to the same folder is still entered. + #[cfg(unix)] + #[test] + fn folder_turned_down_through_one_link_is_entered_through_another() { + let d = tmp("enter-link"); + std::fs::create_dir_all(d.join("real")).unwrap(); + std::fs::write(d.join("real/p.jpg"), b"x").unwrap(); + let root = d.join("root"); + std::fs::create_dir_all(&root).unwrap(); + std::os::unix::fs::symlink(d.join("real"), root.join("@meta")).unwrap(); + std::os::unix::fs::symlink(d.join("real"), root.join("photos")).unwrap(); + let not_at = |p: &Path| !p.file_name().is_some_and(|n| n.to_string_lossy().starts_with('@')); + let w = files_in_entering(&root, None, Limits::default(), |_| true, not_at); + assert_eq!(w.files, vec![root.join("photos/p.jpg")]); + let _ = std::fs::remove_dir_all(&d); + } + /// A link back up the tree (a loop) is followed at most once: the walk ends. #[cfg(unix)] #[test] diff --git a/crates/faces/src/matching.rs b/crates/faces/src/matching.rs index d4f1e5484d..f052cb4443 100644 --- a/crates/faces/src/matching.rs +++ b/crates/faces/src/matching.rs @@ -54,12 +54,16 @@ fn dot(a: &[f32], b: &[f32]) -> f32 { /// best first. Names are compared case-insensitively and shown as first seen. pub fn rank(query: &[f32], gallery: &[(&str, &[f32])]) -> Vec { let mut people: Vec<(String, String, Vec)> = Vec::new(); // (key, shown name, similarities) + let mut at: std::collections::HashMap = std::collections::HashMap::new(); // key -> index in `people` for (name, emb) in gallery { let Some(c) = cosine(query, emb) else { continue }; let key = name.to_lowercase(); - match people.iter_mut().find(|p| p.0 == key) { + match at.get(&key).and_then(|&i| people.get_mut(i)) { Some(p) => p.2.push(c), - None => people.push((key, (*name).to_string(), vec![c])), + None => { + at.insert(key.clone(), people.len()); + people.push((key, (*name).to_string(), vec![c])); + } } } let mut out: Vec = people diff --git a/crates/film/Cargo.toml b/crates/film/Cargo.toml new file mode 100644 index 0000000000..bf3d911b97 --- /dev/null +++ b/crates/film/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "lightcraft-film" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "LightCraft film-negative conversion: film base, levels in density space, film presets, colour and tone (L1)" + +[lints] +workspace = true + +[dependencies] +# Pure-Rust libm: the conversion's maths gives the same numbers on every target, the browser included. +libm = { workspace = true } diff --git a/crates/film/src/analysis.rs b/crates/film/src/analysis.rs new file mode 100644 index 0000000000..e2417033ea --- /dev/null +++ b/crates/film/src/analysis.rs @@ -0,0 +1,202 @@ +//! What the conversion needs to know about one negative, and how to measure it from pixels +//! without an allocator (a fixed-size histogram per channel). + +use crate::{RANGE_STOPS, color::Encoding, film}; + +/// Film base and levels, per channel. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Analysis { + /// The film base (unexposed film, the border) in linear light: scene black. + pub base: [f32; 3], + /// Relative exposure ([`film::exposure`]) that maps to black. + pub black: [f32; 3], + /// Relative exposure that maps to white. + pub white: [f32; 3], +} + +impl Analysis { + /// Levels from the base alone: the base is black and a scene [`RANGE_STOPS`] stops brighter + /// is white, on every channel. Needs nothing from the image, so it is identical on every band. + pub fn manual(base_linear: [f32; 3]) -> Self { + Self::from_base(base_linear, [crate::NEGATIVE_GAMMA; 3]) + } + + /// [`Analysis::manual`] for a film whose layers have the given density per log-exposure: a + /// steeper layer reaches the same scene brightness at a higher density, so its white point + /// sits further from the base. Relative exposures stay in the [`film::exposure`] convention. + pub fn from_base(base_linear: [f32; 3], gamma: [f32; 3]) -> Self { + let mut white = [0.0; 3]; + for (w, g) in white.iter_mut().zip(gamma) { + let g = if g.is_finite() && g > 0.05 { g } else { crate::NEGATIVE_GAMMA }; + *w = libm::exp2f(g / crate::NEGATIVE_GAMMA * RANGE_STOPS); + } + Self { base: base_linear, black: [1.0; 3], white } + } + + /// Levels from three scan values per channel in the host encoding: the film base, the + /// brightest value that still counts as exposed (black) and the darkest (white). `None` + /// when a channel has no range between black and white. + pub fn from_scan_values(base: [f32; 3], black: [f32; 3], white: [f32; 3], enc: Encoding) -> Option { + let mut a = Self { base: [0.0; 3], black: [0.0; 3], white: [0.0; 3] }; + for ch in 0..3 { + a.base[ch] = enc.decode(base[ch]); + a.black[ch] = film::exposure(enc.decode(black[ch]), a.base[ch]); + a.white[ch] = film::exposure(enc.decode(white[ch]), a.base[ch]); + if !a.white[ch].is_finite() || !a.black[ch].is_finite() || a.white[ch] <= a.black[ch] * 1.0001 { + return None; + } + } + Some(a) + } +} + +/// Bins per channel. +pub const BINS: usize = 1024; + +/// Per-channel histogram of scan values in the host encoding, 0..1. One pass over a band gives +/// the film base (a high quantile: the unexposed border is the brightest the scan gets) and the +/// black and white points (the quantiles the black and white clips leave). +#[derive(Clone, Copy, Debug)] +pub struct ValueHistogram { + bins: [[u32; BINS]; 3], + count: u32, +} + +impl Default for ValueHistogram { + fn default() -> Self { + Self::new() + } +} + +impl ValueHistogram { + pub const fn new() -> Self { + Self { bins: [[0; BINS]; 3], count: 0 } + } + + /// Account for one sample (host encoding, 0..1 per channel). + pub fn push(&mut self, rgb: [f32; 3]) { + for (bins, v) in self.bins.iter_mut().zip(rgb) { + if let Some(b) = bins.get_mut(bin(v)) { + *b = b.saturating_add(1); + } + } + self.count = self.count.saturating_add(1); + } + + pub fn count(&self) -> u32 { + self.count + } + + /// The value below which a fraction `q` (0..1) of channel `ch` lies. + pub fn quantile(&self, ch: usize, q: f32) -> Option { + self.bins.get(ch).and_then(|bins| quantile_bin(bins, self.count, q)).map(|b| b as f32 / (BINS - 1) as f32) + } + + /// The analysis of the pixels seen: the base at the `1 − base_clip` quantile, black at + /// `1 − black_clip`, white at `white_clip` (all fractions, 0..1), for samples in `enc`. + pub fn analysis(&self, base_clip: f32, black_clip: f32, white_clip: f32, enc: Encoding) -> Option { + let (mut base, mut black, mut white) = ([0.0; 3], [0.0; 3], [0.0; 3]); + for ch in 0..3 { + base[ch] = self.quantile(ch, 1.0 - base_clip.clamp(0.0, 0.5))?; + black[ch] = self.quantile(ch, 1.0 - black_clip.clamp(0.0, 0.5))?; + white[ch] = self.quantile(ch, white_clip.clamp(0.0, 0.5))?; + } + Analysis::from_scan_values(base, black, white, enc) + } +} + +/// The bin of a value in 0..1. +fn bin(v: f32) -> usize { + if v.is_finite() { (v.clamp(0.0, 1.0) * (BINS - 1) as f32) as usize } else { 0 } +} + +/// The first bin at which the cumulative count reaches `q` of `count` (`None` when empty). +fn quantile_bin(bins: &[u32; BINS], count: u32, q: f32) -> Option { + if count == 0 { + return None; + } + let target = libm::ceil(f64::from(q.clamp(0.0, 1.0)) * f64::from(count)).max(1.0) as u64; + let mut seen = 0u64; + for (i, n) in bins.iter().enumerate() { + seen += u64::from(*n); + if seen >= target { + return Some(i); + } + } + Some(BINS - 1) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::color; + + const BASE: [f32; 3] = [0.6, 0.35, 0.15]; + + #[test] + fn histogram_finds_base_and_levels_of_a_synthetic_negative() { + let mut h = ValueHistogram::new(); + assert_eq!(h.analysis(0.001, 0.0, 0.0, Encoding::Srgb), None); + // Scene exposures from 1 (black, at the base) to 2^5 (white), evenly on a log scale, + // plus a hot pixel brighter than the base. + for i in 0..=1000 { + let e = libm::exp2f(5.0 * i as f32 / 1000.0); + let mut rgb = [0.0; 3]; + for (v, b) in rgb.iter_mut().zip(BASE) { + *v = color::srgb_encode(film::transmittance(e, b)); + } + h.push(rgb); + } + h.push([1.0; 3]); + assert_eq!(h.count(), 1002); + let a = h.analysis(0.005, 0.0, 0.0, Encoding::Srgb).unwrap(); + for (ch, b) in BASE.iter().enumerate() { + // The clip takes the top 0.5 % of a 5-stop log ramp: 0.025 stops under the base. + assert!((a.base[ch] - b).abs() < 0.01, "{a:?}"); + assert!((a.black[ch] - 1.0).abs() < 0.03, "{a:?}"); + assert!((a.white[ch] - 32.0).abs() / 32.0 < 0.05, "{a:?}"); + } + let clipped = h.analysis(0.005, 0.1, 0.1, Encoding::Srgb).unwrap(); + assert!(clipped.black[0] > a.black[0] * 1.2 && clipped.white[0] < a.white[0] * 0.8, "{clipped:?}"); + // A flat band (all one value) has no range. + let mut flat = ValueHistogram::new(); + flat.push([0.3; 3]); + assert_eq!(flat.analysis(0.0, 0.0, 0.0, Encoding::Srgb), None); + } + + #[test] + fn a_steeper_layer_puts_white_further_from_the_base() { + let a = Analysis::from_base(BASE, [0.6, 0.6, 0.72]); + assert_eq!(a.white[0], a.white[1]); + assert!(a.white[2] > a.white[0] * 1.5, "{a:?}"); + assert_eq!(Analysis::from_base(BASE, [f32::NAN, 0.0, 0.6]).white, Analysis::manual(BASE).white); + } + + #[test] + fn scan_values_give_levels_in_linear_too() { + let a = Analysis::from_scan_values(BASE, BASE, [0.1, 0.1, 0.1], Encoding::Linear).unwrap(); + assert_eq!(a.base, BASE); + assert_eq!(a.black, [1.0; 3]); + assert!(a.white[0] > a.white[2], "the same scan value is further below a brighter base: {a:?}"); + assert_eq!(Analysis::from_scan_values(BASE, [0.1; 3], [0.1; 3], Encoding::Linear), None); + } + + #[test] + fn quantile_edges() { + let mut bins = [0u32; BINS]; + bins[10] = 5; + bins[500] = 5; + assert_eq!(quantile_bin(&bins, 10, 0.0), Some(10)); + assert_eq!(quantile_bin(&bins, 10, 0.5), Some(10)); + assert_eq!(quantile_bin(&bins, 10, 0.51), Some(500)); + assert_eq!(quantile_bin(&bins, 10, 1.0), Some(500)); + assert_eq!(quantile_bin(&bins, 0, 0.5), None); + assert_eq!(bin(f32::NAN), 0); + assert_eq!(bin(1.0), BINS - 1); + let mut h = ValueHistogram::new(); + h.push([f32::NAN, 2.0, -1.0]); + assert_eq!(h.quantile(0, 0.5), Some(0.0)); + assert_eq!(h.quantile(1, 0.5), Some(1.0)); + assert_eq!(h.quantile(3, 0.5), None); + } +} diff --git a/crates/film/src/color.rs b/crates/film/src/color.rs new file mode 100644 index 0000000000..ff8597e3c5 --- /dev/null +++ b/crates/film/src/color.rs @@ -0,0 +1,145 @@ +//! sRGB transfer functions and luminance, including the fused forms the conversion runs on +//! (one `powf` where the naive chain would need two: the host meters instructions per sample). + +/// How a host's samples are encoded. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Encoding { + /// Display-referred, sRGB transfer (8- and 16-bit documents). + Srgb, + /// Scene-linear (32-bit float documents). + Linear, +} + +impl Encoding { + /// The usual encoding of a document of `depth` bits per sample. + pub fn for_depth(depth: u32) -> Self { + if depth >= 32 { Self::Linear } else { Self::Srgb } + } + + pub fn parse(s: &str) -> Option { + match s { + "srgb" => Some(Self::Srgb), + "linear" => Some(Self::Linear), + _ => None, + } + } + + /// A sample in this encoding as linear light. + pub fn decode(self, v: f32) -> f32 { + match self { + Self::Srgb => srgb_decode(v), + Self::Linear => v, + } + } + + /// Three linear values as samples in this encoding. + pub fn encode3(self, rgb: [f32; 3]) -> [f32; 3] { + [self.encode(rgb[0]), self.encode(rgb[1]), self.encode(rgb[2])] + } + + /// Linear light as a sample in this encoding. + pub fn encode(self, v: f32) -> f32 { + match self { + Self::Srgb => srgb_encode(v), + Self::Linear => v, + } + } +} + +/// Below this encoded value the sRGB curve is linear. +const SRGB_KNEE_ENCODED: f32 = 0.04045; +/// Below this linear value the sRGB curve is linear. +const SRGB_KNEE_LINEAR: f32 = 0.003_130_8; + +/// sRGB-encoded 0..1 to linear light (non-finite input reads as 0). +pub fn srgb_decode(v: f32) -> f32 { + if !v.is_finite() { + return 0.0; + } + let v = v.clamp(0.0, 1.0); + if v <= SRGB_KNEE_ENCODED { v / 12.92 } else { libm::powf((v + 0.055) / 1.055, 2.4) } +} + +/// `srgb_decode(v)^e` in one `powf`, for `v` in 0..1 and finite `e`. +pub fn srgb_decode_pow(v: f32, e: f32) -> f32 { + if !v.is_finite() { + return 0.0; + } + let v = v.clamp(0.0, 1.0); + if v <= SRGB_KNEE_ENCODED { libm::powf(v / 12.92, e) } else { libm::powf((v + 0.055) / 1.055, 2.4 * e) } +} + +/// Linear light 0..1 to sRGB-encoded (clamped; non-finite input reads as 0). +pub fn srgb_encode(v: f32) -> f32 { + if !v.is_finite() { + return 0.0; + } + let v = v.clamp(0.0, 1.0); + if v <= SRGB_KNEE_LINEAR { v * 12.92 } else { 1.055 * libm::powf(v, 1.0 / 2.4) - 0.055 } +} + +/// `srgb_encode(v^e)` in one `powf`, for `v` in 0..1 and `e > 0`; `knee` is +/// [`encode_pow_knee`]`(e)`, the `v` below which `v^e` is in the curve's linear part. +pub fn srgb_encode_pow(v: f32, e: f32, knee: f32) -> f32 { + if !v.is_finite() { + return 0.0; + } + let v = v.clamp(0.0, 1.0); + if v <= knee { 12.92 * libm::powf(v, e) } else { 1.055 * libm::powf(v, e / 2.4) - 0.055 } +} + +/// The `v` below which `v^e` falls in the sRGB curve's linear part. +pub fn encode_pow_knee(e: f32) -> f32 { + if e.is_finite() && e > 0.0 { libm::powf(SRGB_KNEE_LINEAR, 1.0 / e) } else { SRGB_KNEE_LINEAR } +} + +/// Rec. 709 luminance of a linear RGB triple. +pub fn luminance(rgb: [f32; 3]) -> f32 { + 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn srgb_round_trips_and_pins_known_points() { + for v in [0.0, 0.001, 0.04045, 0.1, 0.5, 0.9, 1.0] { + assert!((srgb_decode(srgb_encode(v)) - v).abs() < 1e-6, "{v}"); + } + assert!((srgb_encode(0.18) - 0.4613).abs() < 1e-3); + assert!((srgb_decode(0.5) - 0.2140).abs() < 1e-3); + assert_eq!(srgb_encode(f32::NAN), 0.0); + assert_eq!(srgb_decode(2.0), 1.0); + } + + #[test] + fn fused_forms_match_the_chains() { + for v in [0.0f32, 0.001, 0.02, 0.04045, 0.1, 0.5, 0.9, 1.0] { + for e in [0.5, 1.0, 1.7, -1.6] { + // Negative exponents blow up at 0; callers clamp first, as the test does. + let v = if e < 0.0 { v.max(0.001) } else { v }; + let want = libm::powf(srgb_decode(v), e); + let got = srgb_decode_pow(v, e); + assert!((got - want).abs() / want.max(1.0) < 1e-4, "decode {v}^{e}: {got} vs {want}"); + } + for e in [0.5, 1.0, 2.0] { + let want = srgb_encode(libm::powf(v, e)); + let got = srgb_encode_pow(v, e, encode_pow_knee(e)); + assert!((got - want).abs() < 1e-5, "encode {v}^{e}: {got} vs {want}"); + } + } + assert_eq!(srgb_decode_pow(f32::NAN, 2.0), 0.0); + assert_eq!(srgb_encode_pow(f32::INFINITY, 1.0, encode_pow_knee(1.0)), 0.0); + assert_eq!(encode_pow_knee(f32::NAN), SRGB_KNEE_LINEAR); + } + + #[test] + fn depth_picks_encoding() { + assert_eq!(Encoding::for_depth(8), Encoding::Srgb); + assert_eq!(Encoding::for_depth(16), Encoding::Srgb); + assert_eq!(Encoding::for_depth(32), Encoding::Linear); + assert_eq!(Encoding::parse("linear"), Some(Encoding::Linear)); + assert_eq!(Encoding::parse("auto"), None); + } +} diff --git a/crates/film/src/film.rs b/crates/film/src/film.rs new file mode 100644 index 0000000000..bee1ecbc4d --- /dev/null +++ b/crates/film/src/film.rs @@ -0,0 +1,105 @@ +//! The negative's characteristic curve, straight-line approximation. +//! +//! Density `D = D_base + γ · log10(E)` for scene exposure `E` relative to the exposure that just +//! starts to darken the film; what the scanner sees is the transmittance `T = 10^−D`. So the +//! relative exposure that produced a scan value `t` with film base `t_base` is +//! `E = (t_base / t)^(1/γ)`: 1 at the base (scene black), growing as the negative gets denser. + +use crate::{NEGATIVE_GAMMA, color::Encoding}; + +/// Transmittance below which a sample reads as fully dense (avoids division by zero). +pub const MIN_TRANSMITTANCE: f32 = 1e-5; +/// The sRGB-encoded value of [`MIN_TRANSMITTANCE`] (in the curve's linear part). +const MIN_TRANSMITTANCE_SRGB: f32 = MIN_TRANSMITTANCE * 12.92; + +/// Relative scene exposure (≥ 1) behind a linear scan value `t` of a negative with film base +/// `t_base` (both linear light, 0..1). Values brighter than the base read as the base. +pub fn exposure(t: f32, t_base: f32) -> f32 { + let t_base = if t_base.is_finite() { t_base.max(MIN_TRANSMITTANCE) } else { MIN_TRANSMITTANCE }; + let t = if t.is_finite() { t.clamp(MIN_TRANSMITTANCE, t_base) } else { t_base }; + libm::powf(t_base / t, 1.0 / NEGATIVE_GAMMA) +} + +/// `t_base^(1/γ)`: the factor that turns `t^(−1/γ)` into [`exposure`]. +pub fn base_factor(t_base: f32) -> f32 { + let t_base = if t_base.is_finite() { t_base.max(MIN_TRANSMITTANCE) } else { MIN_TRANSMITTANCE }; + libm::powf(t_base, 1.0 / NEGATIVE_GAMMA) +} + +/// `factor · t^(−exponent)` for a scan value `v` in its host encoding: one `powf` per sample. +/// With `exponent = 1/γ` and `factor` the base's [`base_factor`] this is [`exposure`]; a +/// different exponent per channel normalises channels of unequal density range +/// ([`crate::Converter`]). Results below 1 read as 1 (brighter than the base); non-finite +/// input reads as the base. +pub fn exposure_encoded(v: f32, enc: Encoding, factor: f32, exponent: f32) -> f32 { + exposure_encoded_raw(v, enc, factor, exponent).max(1.0) +} + +/// [`exposure_encoded`] before its floor at 1: it keeps going below 1 past the base, so that a +/// table of it interpolates straight through the black point instead of across a corner. +pub fn exposure_encoded_raw(v: f32, enc: Encoding, factor: f32, exponent: f32) -> f32 { + if !v.is_finite() { + return 1.0; + } + let e = match enc { + Encoding::Srgb => factor * color::srgb_decode_pow(v.max(MIN_TRANSMITTANCE_SRGB), -exponent), + Encoding::Linear => factor * libm::powf(v.max(MIN_TRANSMITTANCE), -exponent), + }; + if e.is_finite() { e } else { 1.0 } +} + +use crate::color; + +/// The inverse: the linear scan value a relative exposure `e` (≥ 1) leaves on a negative with +/// film base `t_base`. Used to synthesise negatives in tests and to reason about levels. +pub fn transmittance(e: f32, t_base: f32) -> f32 { + transmittance_at(e, t_base, NEGATIVE_GAMMA) +} + +/// [`transmittance`] for a channel whose density grows by `gamma` per log-exposure: a scan of +/// colour film, whose channels spread apart ([`crate::SCAN_SPREAD`]). +pub fn transmittance_at(e: f32, t_base: f32, gamma: f32) -> f32 { + t_base * libm::powf(e.max(1.0), -gamma) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn base_is_unit_exposure_and_density_grows_with_exposure() { + assert_eq!(exposure(0.5, 0.5), 1.0); + assert_eq!(exposure(0.9, 0.5), 1.0, "brighter than the base clamps"); + let e1 = exposure(0.25, 0.5); + let e2 = exposure(0.125, 0.5); + assert!(e1 > 1.0 && e2 > e1); + // Halving the transmittance (0.3 density) is 0.5 log-exposure at γ 0.6: ×2^(1/0.6) ≈ 3.17. + assert!((e2 / e1 - 3.175).abs() < 0.01, "{e1} {e2}"); + } + + #[test] + fn transmittance_inverts_exposure() { + for e in [1.0, 2.0, 10.0, 64.0] { + let t = transmittance(e, 0.6); + assert!((exposure(t, 0.6) - e).abs() / e < 1e-4, "{e}"); + } + assert!(exposure(0.0, 0.6).is_finite()); + assert!(exposure(f32::NAN, f32::NAN).is_finite()); + } + + #[test] + fn encoded_form_matches_the_linear_one() { + let base = 0.6; + let k = base_factor(base); + for t in [0.6, 0.3, 0.1, 0.02, 0.001, 0.0] { + let want = exposure(t, base); + let lin = exposure_encoded(t, Encoding::Linear, k, 1.0 / NEGATIVE_GAMMA); + let srgb = exposure_encoded(color::srgb_encode(t), Encoding::Srgb, k, 1.0 / NEGATIVE_GAMMA); + assert!((lin - want).abs() / want < 1e-3, "linear {t}: {lin} vs {want}"); + assert!((srgb - want).abs() / want < 2e-3, "srgb {t}: {srgb} vs {want}"); + } + assert_eq!(exposure_encoded(0.9, Encoding::Linear, k, 1.0 / NEGATIVE_GAMMA), 1.0, "brighter than the base"); + assert_eq!(exposure_encoded(f32::NAN, Encoding::Srgb, k, 1.0 / NEGATIVE_GAMMA), 1.0); + assert!(exposure_encoded(0.0, Encoding::Srgb, f32::INFINITY, 1.0 / NEGATIVE_GAMMA).is_finite()); + } +} diff --git a/crates/film/src/lib.rs b/crates/film/src/lib.rs new file mode 100644 index 0000000000..3c76ab7a74 --- /dev/null +++ b/crates/film/src/lib.rs @@ -0,0 +1,718 @@ +//! Film-negative conversion: a scanned colour or black-and-white negative to a positive. +//! +//! Ported from Film Lab (github.com/smyrgeorge/film-lab, by the same author), whose PhotoCraft +//! plug-ins run the same maths. Hosts hand over RGB samples in 0..1 and say how they are encoded +//! ([`Encoding`]); this crate gives back the positive. Nothing in here knows a host's pixel layout; +//! [`measure`] analyses a whole scan once, so every render (a preview, a zoomed window, an export) +//! uses the same numbers. +//! +//! # The model +//! +//! A negative records scene exposure as density. In the straight part of its characteristic +//! curve, density grows by [`NEGATIVE_GAMMA`] per stop, so the light a scanner sees through the +//! film falls as the scene brightens. Reading that back: +//! +//! 1. **Film base.** The unexposed film (the border, orange on colour negative film) is the +//! brightest the scan gets and stands for scene black. Every channel is measured relative to +//! it, which also removes the orange mask ([`film::exposure`]). +//! 2. **Levels.** Each channel's density range between its black and white points is mapped onto +//! the same [`RANGE_STOPS`] of scene brightness, so channels of unequal range (a scan whose +//! blue runs much denser than its red) come out balanced, and black and white land on 0 and 1 +//! ([`Analysis`]: the base for black and the fixed range for white when only the base is +//! known, or scan values for black and white from an analysis of the image). +//! 3. **Colour** in linear light ([`look::Colour`]): exposure, white balance (sliders, a preset, +//! a neutral sample), the colour model, pre-saturation, mid-tone balance; black-and-white. +//! 4. **Tone** ([`tone::Curve`]): white and black points, brightness as a gamma, then in display +//! (sRGB-encoded) space a tone profile, contrast, lights / darks, fade / glow and soft ends. +//! 5. **Toning** ([`look::Toning`]): highlight and shadow colour balance and saturation on the +//! encoded result. +//! +//! The workflow this serves is the usual one for negatives: sample the film border, exclude +//! the border and sprocket holes from the evaluated area, convert, then edit. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod analysis; +pub mod color; +pub mod film; +pub mod look; +pub mod measure; +pub mod preset; +pub mod tone; + +pub use analysis::{Analysis, ValueHistogram}; +pub use color::Encoding; +pub use look::{Look, WbPreset}; +pub use measure::{MeasureOptions, Measurement}; +pub use preset::{PRESETS, Preset, SCAN_SPREAD, Sliders}; +pub use tone::Tone; + +/// The negative's contrast: density per log-exposure in the straight part of its characteristic +/// curve. Colour negative film sits near 0.6; the brightness and contrast controls absorb the +/// difference for other stocks. +pub const NEGATIVE_GAMMA: f32 = 0.6; + +/// Stops of scene brightness between the film base and the positive's white when only the base +/// is known (a density range of about 1.1 at [`NEGATIVE_GAMMA`], typical of a well-exposed +/// colour negative). +pub const RANGE_STOPS: f32 = 6.0; + +/// Stops the density range between the black and white points is rendered over by default +/// ([`Params::range`]). Fewer stops than the film's own [`RANGE_STOPS`] render mid-tones the way +/// a lab scan does: measured against a lab-converted reference, 3 matches its mid-tones; 6 is +/// the scene-linear rendition. +pub const DISPLAY_STOPS: f32 = 3.0; + +/// Channel indices in the RGB triples. +pub const RED: usize = 0; +pub const GREEN: usize = 1; +pub const BLUE: usize = 2; + +/// The user's edits. Slider ranges follow the Convert Negative panel: ±50 for the bipolar controls, +/// 0..100 for amounts, exposure in stops, pre-saturation 1..5. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Params { + /// Stops of scene brightness mapped between the black and white points (default + /// [`DISPLAY_STOPS`]); fewer stops render mid-tones brighter, as lab scans do, and + /// [`RANGE_STOPS`] is the scene-linear rendition. + pub range: f32, + /// Stops; positive brightens the whole positive. + pub exposure: f32, + /// Mid-tone gamma, −50..50; positive brightens mid-tones without moving black or white. + pub brightness: f32, + /// Added to the tone profile's contrast, −50..50. + pub contrast: f32, + pub tone: Tone, + /// −50..50; positive brightens the lighter tones. + pub lights: f32, + /// −50..50; positive brightens the darker tones. + pub darks: f32, + /// −50..50; moves the white point (positive brightens whites; clipped detail stays clipped). + pub whites: f32, + /// −50..50; moves the black point (positive lifts it for a faded look). + pub blacks: f32, + /// −100..100: positive lifts black for smoother shadows with no pure black; negative + /// expands the shadow tonality. + pub fade: f32, + /// −100..100: positive compresses the highlights into a soft shoulder; negative expands them. + pub glow: f32, + /// 0..100: tonal roll-off into white. + pub soft_highs: f32, + /// 0..100: tonal roll-off into black. + pub soft_lows: f32, + pub wb: WbPreset, + /// −50..50; positive is warmer. + pub temp: f32, + /// −50..50; positive is more magenta, negative more green. + pub tint: f32, + /// Per-channel mid-tone gammas (0.4..2.5, 1 = none): a colour balance that leaves black and + /// white alone, what an automatic neutral balance computes from the channel medians. + pub balance: [f32; 3], + /// 1..5, default 3: saturation before the tone curve, which also sets colour separation. + pub presat: f32, + /// −50..50: saturation after the tone curve. + pub saturation: f32, + pub look: Look, + /// Mid-tone colour balance, −50..50 each: red / cyan, green / magenta, blue / yellow. + pub mids_red: f32, + pub mids_green: f32, + pub mids_blue: f32, + /// Highlight toning balance, −50..50 each, and how far down it reaches (0..100). + pub highs_red: f32, + pub highs_green: f32, + pub highs_blue: f32, + pub highs_range: f32, + /// Shadow toning balance, −50..50 each, and how far up it reaches (0..100). + pub lows_red: f32, + pub lows_green: f32, + pub lows_blue: f32, + pub lows_range: f32, + /// Black-and-white film: the positive is the luminance (toning still colours it). + pub monochrome: bool, + /// Density per log-exposure of the red, green and blue channels of the scan, for levels + /// derived from a base alone ([`Analysis::from_base`]); a measured range makes it irrelevant. + /// A preset sets it to its [`Preset::scan_gamma`]. + pub film_gamma: [f32; 3], +} + +impl Default for Params { + fn default() -> Self { + Self { + range: DISPLAY_STOPS, + exposure: 0.0, + brightness: 0.0, + contrast: 0.0, + tone: Tone::LabStandard, + lights: 0.0, + darks: 0.0, + whites: 0.0, + blacks: 0.0, + fade: 0.0, + glow: 0.0, + soft_highs: 0.0, + soft_lows: 0.0, + wb: WbPreset::AsIs, + temp: 0.0, + tint: 0.0, + balance: [1.0; 3], + presat: 3.0, + saturation: 0.0, + look: Look::Neutral, + mids_red: 0.0, + mids_green: 0.0, + mids_blue: 0.0, + highs_red: 0.0, + highs_green: 0.0, + highs_blue: 0.0, + highs_range: 30.0, + lows_red: 0.0, + lows_green: 0.0, + lows_blue: 0.0, + lows_range: 30.0, + monochrome: false, + film_gamma: [NEGATIVE_GAMMA; 3], + } + } +} + +/// A conversion ready to run on pixels of one encoding: the analysis and the edits folded into +/// per-channel factors, one exponent, one colour pipeline and one tone curve. [`Converter::convert`] +/// is the exact path (two `powf` per channel, and an `expf` when the curve has contrast); +/// [`Converter::convert_with`] runs through [`Tables`] instead, with no transcendental call per +/// sample, for hosts that meter instructions. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Converter { + enc: Encoding, + /// Per channel, the normalised exposure `2^(u · RANGE_STOPS)` of a scan value `t` is + /// `factor · t^(−exponent)`, where `u` is the position of its density between the black and + /// white points (0..1): levels in density space folded into one `powf`. + factor: [f32; 3], + exponent: [f32; 3], + /// `gain / (2^RANGE_STOPS − 1)`: the normalised exposure to a positive, exposure folded in. + scale: f32, + colour: look::Colour, + monochrome: bool, + /// White point as a gain on the linear positive. + white_gain: f32, + /// Black point: lifted (positive) or crushed (negative), as a fraction of the range. + black_point: f32, + /// Exponent applied to the levelled positive per channel (brightness and balance). + gamma: [f32; 3], + /// [`color::encode_pow_knee`] of each `gamma`. + knee: [f32; 3], + curve: tone::Curve, + toning: look::Toning, +} + +impl Converter { + /// `neutral` is a scan sample (host encoding) of something that should come out grey, if the + /// user picked one with the colour picker. + pub fn new(a: &Analysis, p: &Params, enc: Encoding, neutral: Option<[f32; 3]>) -> Self { + let gain = libm::exp2f(finite(p.exposure, 0.0).clamp(-10.0, 10.0)); + let stops = finite(p.range, DISPLAY_STOPS).clamp(1.0, 10.0); + let scale = gain / (libm::exp2f(stops) - 1.0); + let mut factor = [0.0; 3]; + let mut exponent = [0.0; 3]; + for ch in 0..3 { + // Stops between the black and white points; the base-only default is RANGE_STOPS. + let black = if a.black[ch].is_finite() { a.black[ch].max(1.0) } else { 1.0 }; + let white = if a.white[ch].is_finite() { a.white[ch] } else { 0.0 }; + let range = libm::log2f(white) - libm::log2f(black); + let range = if range.is_finite() && range > 1e-3 { range } else { RANGE_STOPS }; + // 2^(u · S) = (E / black)^(S / range) = base^(S/(γ range)) · black^(−S/range) · t^(−S/(γ range)). + let e = stops / (NEGATIVE_GAMMA * range); + exponent[ch] = e; + let base = if a.base[ch].is_finite() { a.base[ch].max(film::MIN_TRANSMITTANCE) } else { film::MIN_TRANSMITTANCE }; + factor[ch] = libm::powf(base, e) * libm::powf(black, -stops / range); + } + let levelled = |neg: [f32; 3]| { + let mut out = [0.0; 3]; + for ch in 0..3 { + let e = film::exposure_encoded(neg[ch], enc, factor[ch], exponent[ch]); + out[ch] = ((e - 1.0) * scale).max(0.0); + } + out + }; + // Brightness, the profile's mid-tone gamma and the per-channel balance as one exponent per + // channel on the linear positive (a gamma in encoded space is close to the same gamma on + // the linear value, after encoding). + let brightness = libm::exp2f(-finite(p.brightness, 0.0).clamp(-50.0, 50.0) / 50.0) * p.tone.gamma(); + // The per-channel balance corrects a colour cast; a monochrome positive has none, and + // unequal gammas would tint it. + let balance = if p.monochrome { [1.0; 3] } else { p.balance }; + let mut gamma = [0.0; 3]; + let mut knee = [0.0; 3]; + for ch in 0..3 { + gamma[ch] = brightness * finite(balance[ch], 1.0).clamp(0.4, 2.5); + knee[ch] = color::encode_pow_knee(gamma[ch]); + } + Self { + enc, + factor, + exponent, + scale, + colour: look::Colour::new(p, neutral.map(levelled)), + monochrome: p.monochrome, + white_gain: libm::exp2f(finite(p.whites, 0.0).clamp(-50.0, 50.0) / 100.0), + black_point: finite(p.blacks, 0.0).clamp(-50.0, 50.0) / 100.0 * 0.2, + gamma, + knee, + curve: tone::Curve::new(p), + toning: look::Toning::new(p), + } + } + + pub fn encoding(&self) -> Encoding { + self.enc + } + + /// The levelled linear positive of channel `ch`'s scan value, exposure folded in, capped at + /// [`LEVELS_CAP`]. + fn levelled(&self, v: f32, ch: usize) -> f32 { + let e = film::exposure_encoded(v, self.enc, self.factor[ch], self.exponent[ch]); + ((e - 1.0) * self.scale).clamp(0.0, LEVELS_CAP) + } + + /// The white and black points on a linear positive, clamped to 0..1. + fn points(&self, v: f32) -> f32 { + let mut x = v * self.white_gain; + if self.black_point > 0.0 { + x = self.black_point + x * (1.0 - self.black_point); + } else if self.black_point < 0.0 { + x = (x + self.black_point) / (1.0 + self.black_point); + } + x.clamp(0.0, 1.0) + } + + /// The colour stage, monochrome and the points on a levelled positive. + fn graded(&self, mut p: [f32; 3]) -> [f32; 3] { + p = self.colour.apply(p); + if self.monochrome { + p = [color::luminance(p).max(0.0); 3]; + } + for v in &mut p { + *v = self.points(*v); + } + p + } + + /// One RGB sample of the negative, in the converter's encoding, as the linear positive before + /// the gammas and the tone curve: levels, exposure, colour, the white and black points. + fn positive(&self, neg: [f32; 3]) -> [f32; 3] { + let mut p = [0.0f32; 3]; + for (ch, (v, n)) in p.iter_mut().zip(neg).enumerate() { + *v = self.levelled(n, ch); + } + self.graded(p) + } + + /// Channel `ch` of a linear positive (after the points) as the sRGB-encoded sample before + /// toning: brightness (a gamma) and the tone curve, which act in sRGB-encoded space. + fn encoded(&self, p: f32, ch: usize) -> f32 { + self.curve.apply(color::srgb_encode_pow(p, self.gamma[ch], self.knee[ch])) + } + + /// The toning and the host's encoding on an sRGB-encoded positive. + fn finished(&self, mut out: [f32; 3]) -> [f32; 3] { + out = self.toning.apply(out); + match self.enc { + Encoding::Srgb => out, + Encoding::Linear => [color::srgb_decode(out[0]), color::srgb_decode(out[1]), color::srgb_decode(out[2])], + } + } + + /// One RGB sample of the negative, in the converter's encoding, as the positive in the same + /// encoding, 0..1: the exact path, two `powf` per channel. + pub fn convert(&self, neg: [f32; 3]) -> [f32; 3] { + let p = self.positive(neg); + if self.enc == Encoding::Linear && self.curve.is_identity() && self.toning.is_identity { + // Encoding and decoding again would cancel: a gamma on the linear value. + return [libm::powf(p[0], self.gamma[0]), libm::powf(p[1], self.gamma[1]), libm::powf(p[2], self.gamma[2])]; + } + self.finished([self.encoded(p[0], 0), self.encoded(p[1], 1), self.encoded(p[2], 2)]) + } + + /// Channel `ch` of a linear positive as the output table holds it: sRGB-encoded, or in the + /// host's encoding when `folded` (no toning to follow). + fn output_entry(&self, p: f32, ch: usize, folded: bool) -> f32 { + let out = self.encoded(p, ch); + if folded && self.enc == Encoding::Linear { color::srgb_decode(out) } else { out } + } + + /// Where a scan value sits in the levels table: as it is for an sRGB host, whose samples are + /// already spaced the way the levels curve bends; by its square root for a linear host, so + /// that the dense end (small values, the highlights) gets most of the entries. + fn levels_index(&self, v: f32) -> f32 { + match self.enc { + Encoding::Srgb => v, + Encoding::Linear => libm::sqrtf(v.max(0.0)), + } + } + + /// Fills `t` with this conversion's transfer functions, for [`Converter::convert_with`]. + pub fn tables(&self, t: &mut Tables) { + let step = 1.0 / (TABLE_SIZE - 1) as f32; + t.folded = self.toning.is_identity; + for (ch, (levels, output)) in t.levels.iter_mut().zip(t.output.iter_mut()).enumerate() { + // The scan value at which the relative exposure is 1: the black point. + let black = libm::powf(self.factor[ch], 1.0 / self.exponent[ch]); + t.black[ch] = self.levels_index(match self.enc { + Encoding::Srgb => color::srgb_encode(black), + Encoding::Linear => black, + }); + for (i, v) in levels.iter_mut().enumerate() { + let u = i as f32 * step; + let scan = match self.enc { + Encoding::Srgb => u, + Encoding::Linear => u * u, + }; + // Unfloored, so the entries run straight through the black point and an + // interpolation lands on it; `convert_with` floors the result. + let e = film::exposure_encoded_raw(scan, self.enc, self.factor[ch], self.exponent[ch]); + *v = ((e - 1.0) * self.scale).min(LEVELS_CAP); + } + for (i, v) in output.iter_mut().enumerate() { + *v = self.output_entry(i as f32 * step, ch, t.folded); + } + } + } + + /// [`Converter::convert`] through `t`, filled by [`Converter::tables`] for this converter: + /// the same positive to within the tables' interpolation (under a thousandth of the range) + /// with no transcendental call per sample, which is what counts under an interpreter. The + /// darkest inputs, where a steep gamma or a dense highlight outruns any table, take the + /// exact path: few pixels, so little cost. + pub fn convert_with(&self, t: &Tables, neg: [f32; 3]) -> [f32; 3] { + let index = match self.enc { + Encoding::Srgb => neg, + Encoding::Linear => [libm::sqrtf(neg[0].max(0.0)), libm::sqrtf(neg[1].max(0.0)), libm::sqrtf(neg[2].max(0.0))], + }; + let mut p = [0.0f32; 3]; + for (ch, (v, (table, (n, u)))) in p.iter_mut().zip(t.levels.iter().zip(neg.into_iter().zip(index))).enumerate() { + // At and past the black point (and for NaN) the positive is 0; the darkest inputs + // take the exact path; the rest interpolate. + *v = if u >= t.black[ch] || u.is_nan() { + 0.0 + } else if u < EXACT_BELOW { + self.levelled(n, ch) + } else { + lookup(table, u).max(0.0) + }; + } + p = self.graded(p); + let mut out = [0.0f32; 3]; + for (ch, (o, (table, v))) in out.iter_mut().zip(t.output.iter().zip(p)).enumerate() { + *o = if v < EXACT_BELOW { self.output_entry(v, ch, t.folded) } else { lookup(table, v) }; + } + if t.folded { out } else { self.finished(out) } + } +} + +/// Entries per channel in [`Tables`]. +pub const TABLE_SIZE: usize = 2048; + +/// Where the levelled positive stops: four stops over white, deep in what the white point clips. +/// Without it a scan value near zero puts a channel at 10⁸ and the colour stage's rounding +/// then zeroes the other two. +const LEVELS_CAP: f32 = 16.0; + +/// Inputs below this (the tables' first eight entries) take the exact path in +/// [`Converter::convert_with`]: a gamma of 0.2 or a highlight denser than the second entry +/// changes faster there than an interpolation can follow. +const EXACT_BELOW: f32 = 8.0 / (TABLE_SIZE - 1) as f32; + +/// The per-channel transfer functions of a [`Converter`] sampled over their input range, so that +/// a sample costs an interpolation per channel and stage instead of a `powf`. 48 KiB: keep one +/// in static memory and refill it per converter with [`Converter::tables`]. +pub struct Tables { + /// Host-encoded scan value (0..1; its square root for a linear host) → levelled linear + /// positive, exposure folded in, unfloored (negative past the black point). + levels: [[f32; TABLE_SIZE]; 3], + /// Linear positive after the colour stage and the points (0..1) → the output sample: the + /// brightness gamma and the tone curve, and the host's encoding when `folded`. + output: [[f32; TABLE_SIZE]; 3], + /// Where in `levels` each channel reaches its black point: at and past it the positive is + /// exactly 0, as on the exact path, rather than an interpolation's few millionths (which a + /// lifting gamma would make visible). + black: [f32; 3], + /// The toning (which mixes channels, so cannot be a table) is identity, and `output` ends + /// in the host's encoding; otherwise it ends sRGB-encoded for the toning to follow. + folded: bool, +} + +impl Tables { + pub const fn blank() -> Self { + Self { levels: [[0.0; TABLE_SIZE]; 3], output: [[0.0; TABLE_SIZE]; 3], black: [0.0; 3], folded: false } + } +} + +impl Default for Tables { + fn default() -> Self { + Self::blank() + } +} + +/// `table` at `x` (0..1, finite), linearly interpolated. +fn lookup(table: &[f32; TABLE_SIZE], x: f32) -> f32 { + let x = x.clamp(0.0, 1.0) * (TABLE_SIZE - 1) as f32; + let i = x as usize; + match (table.get(i), table.get(i + 1)) { + (Some(a), Some(b)) => a + (b - a) * (x - i as f32), + (Some(a), None) => *a, + _ => 0.0, + } +} + +/// `v`, or `fallback` when it is NaN or infinite. +pub(crate) fn finite(v: f32, fallback: f32) -> f32 { + if v.is_finite() { v } else { fallback } +} + +#[cfg(test)] +mod tests { + use super::*; + + const BASE: [f32; 3] = [0.6, 0.35, 0.15]; + + /// No edits and the scene-linear rendition: the film model's round trip. + fn neutral() -> Params { + Params { tone: Tone::Linear, range: RANGE_STOPS, ..Params::default() } + } + + /// The linear scan value a scene value `s` (0..1 of the positive's range) leaves, per channel. + fn negative(s: f32, ch: usize) -> f32 { + let white = libm::exp2f(RANGE_STOPS); + film::transmittance(1.0 + s * (white - 1.0), BASE[ch]) + } + + fn scan(s: f32, enc: Encoding) -> [f32; 3] { + [enc.encode(negative(s, 0)), enc.encode(negative(s, 1)), enc.encode(negative(s, 2))] + } + + fn convert(p: &Params, s: f32) -> [f32; 3] { + Converter::new(&Analysis::manual(BASE), p, Encoding::Srgb, None).convert(scan(s, Encoding::Srgb)) + } + + #[test] + fn manual_conversion_inverts_the_film_model_in_both_encodings() { + for enc in [Encoding::Srgb, Encoding::Linear] { + let c = Converter::new(&Analysis::manual(BASE), &neutral(), enc, None); + assert_eq!(c.encoding(), enc); + for s in [0.0, 0.01, 0.1, 0.18, 0.5, 0.9, 1.0] { + let out = c.convert(scan(s, enc)); + let want = enc.encode(s); + for v in out { + assert!((v - want).abs() < 2e-3, "{enc:?} scene {s}: got {out:?}, want {want}"); + } + } + } + } + + #[test] + fn base_is_black_and_brighter_than_base_stays_black() { + let c = Converter::new(&Analysis::manual(BASE), &neutral(), Encoding::Linear, None); + assert_eq!(c.convert(BASE), [0.0; 3]); + assert_eq!(c.convert([0.9, 0.9, 0.9]), [0.0; 3]); + // Nothing transmitted at all: the brightest possible scene tone. + assert!(c.convert([0.0; 3]).iter().all(|v| (v - 1.0).abs() < 1e-6)); + } + + #[test] + fn exposure_brightness_whites_and_blacks_move_tones_the_right_way() { + let base = convert(&neutral(), 0.18)[0]; + let up = convert(&Params { exposure: 1.0, ..neutral() }, 0.18)[0]; + let bright = convert(&Params { brightness: 25.0, ..neutral() }, 0.18)[0]; + let dark = convert(&Params { brightness: -25.0, ..neutral() }, 0.18)[0]; + assert!(up > base && bright > base && dark < base, "{base} {up} {bright} {dark}"); + assert!((color::srgb_decode(up) / color::srgb_decode(base) - 2.0).abs() < 0.02, "one stop doubles linear light"); + // Brightness is a gamma: black and white stay put. + assert_eq!(convert(&Params { brightness: 40.0, ..neutral() }, 0.0)[0], 0.0); + assert!((convert(&Params { brightness: 40.0, ..neutral() }, 1.0)[0] - 1.0).abs() < 1e-5); + // Whites scale towards white, blacks lift or crush the black point. + assert!(convert(&Params { whites: 50.0, ..neutral() }, 0.5)[0] > convert(&neutral(), 0.5)[0]); + assert!(convert(&Params { whites: 50.0, ..neutral() }, 0.0)[0] == 0.0); + assert!(convert(&Params { blacks: 50.0, ..neutral() }, 0.0)[0] > 0.05, "lifted black"); + assert!(convert(&Params { blacks: -50.0, ..neutral() }, 0.05)[0] == 0.0, "crushed black"); + assert!((convert(&Params { blacks: -50.0, ..neutral() }, 1.0)[0] - 1.0).abs() < 1e-5); + } + + #[test] + fn white_balance_presets_looks_and_monochrome() { + let warm = convert(&Params { temp: 50.0, ..neutral() }, 0.3); + assert!(warm[0] > warm[1] && warm[1] > warm[2], "{warm:?}"); + let magenta = convert(&Params { tint: 50.0, ..neutral() }, 0.3); + assert!(magenta[1] < magenta[0] && magenta[1] < magenta[2], "{magenta:?}"); + let preset = convert(&Params { wb: WbPreset::Warm, ..neutral() }, 0.3); + assert!(preset[0] > preset[2], "{preset:?}"); + let lab = convert(&Params { look: Look::LabWarm, ..neutral() }, 0.3); + assert!(lab[0] > lab[2], "{lab:?}"); + assert!(convert(&Params { tone: Tone::LinearDeep, ..neutral() }, 0.3)[0] < convert(&neutral(), 0.3)[0], "deep darkens mid-tones"); + let mono = convert(&Params { monochrome: true, temp: 50.0, ..neutral() }, 0.3); + assert!(mono[0] == mono[1] && mono[1] == mono[2], "{mono:?}"); + let toned = convert(&Params { monochrome: true, lows_blue: 50.0, lows_range: 100.0, ..neutral() }, 0.1); + assert!(toned[2] > toned[0], "toning colours a black-and-white positive: {toned:?}"); + let grey = convert(&Params { saturation: -50.0, temp: 50.0, ..neutral() }, 0.3); + assert!((grey[0] - grey[2]).abs() < 1e-5, "{grey:?}"); + } + + #[test] + fn unequal_channel_ranges_are_balanced_by_the_levels() { + // A scan whose blue runs twice as dense as its red for the same scene: with black and + // white points per channel, a scene grey still comes out grey at every tone. + let stops = [4.0f32, 6.0, 8.0]; + let scan = |s: f32| { + let mut v = [0.0; 3]; + for ch in 0..3 { + v[ch] = Encoding::Srgb.encode(film::transmittance(libm::exp2f(s * stops[ch]), BASE[ch])); + } + v + }; + let a = Analysis::from_scan_values( + [Encoding::Srgb.encode(BASE[0]), Encoding::Srgb.encode(BASE[1]), Encoding::Srgb.encode(BASE[2])], + scan(0.0), + scan(1.0), + Encoding::Srgb, + ) + .unwrap(); + let c = Converter::new(&a, &neutral(), Encoding::Srgb, None); + for s in [0.0, 0.2, 0.5, 0.8, 1.0] { + let out = c.convert(scan(s)); + assert!((out[0] - out[1]).abs() < 4e-3 && (out[1] - out[2]).abs() < 4e-3, "scene {s}: {out:?}"); + let want = color::srgb_encode((libm::exp2f(s * RANGE_STOPS) - 1.0) / (libm::exp2f(RANGE_STOPS) - 1.0)); + assert!((out[1] - want).abs() < 4e-3, "scene {s}: {out:?} vs {want}"); + } + } + + #[test] + fn range_and_balance_move_midtones_without_moving_the_ends() { + let wide = convert(&neutral(), 0.18)[0]; + let narrow = convert(&Params { range: 3.0, ..neutral() }, 0.18)[0]; + assert!(narrow > wide, "fewer stops between black and white render mid-tones brighter: {narrow} vs {wide}"); + assert_eq!(Params::default().range, DISPLAY_STOPS); + assert_eq!(convert(&Params { range: 3.0, ..neutral() }, 0.0)[0], 0.0); + assert!((convert(&Params { range: 3.0, ..neutral() }, 1.0)[0] - 1.0).abs() < 1e-5); + let balanced = convert(&Params { balance: [0.8, 1.0, 1.25], ..neutral() }, 0.3); + assert!(balanced[0] > balanced[1] && balanced[1] > balanced[2], "{balanced:?}"); + assert_eq!(convert(&Params { balance: [0.8, 1.0, 1.25], ..neutral() }, 0.0), [0.0; 3]); + assert!(convert(&Params { balance: [0.8, 1.0, 1.25], ..neutral() }, 1.0).iter().all(|v| (v - 1.0).abs() < 1e-5)); + } + + #[test] + fn neutral_sample_balances_the_positive() { + // A scene grey that the scan renders with a cast (a stronger red mask than the base says). + let a = Analysis::manual(BASE); + let cast = [0.8, 1.0, 1.0]; + let scan_of = + |s: f32| [Encoding::Srgb.encode(negative(s, 0) * cast[0]), Encoding::Srgb.encode(negative(s, 1)), Encoding::Srgb.encode(negative(s, 2))]; + let before = Converter::new(&a, &neutral(), Encoding::Srgb, None).convert(scan_of(0.4)); + assert!(before[0] > before[1] + 0.02, "the cast shows: {before:?}"); + let after = Converter::new(&a, &neutral(), Encoding::Srgb, Some(scan_of(0.4))).convert(scan_of(0.4)); + assert!((after[0] - after[1]).abs() < 2e-3 && (after[1] - after[2]).abs() < 2e-3, "{after:?}"); + } + + #[test] + fn a_balance_never_tints_a_monochrome_positive() { + let p = Params { monochrome: true, balance: [0.7, 1.0, 1.5], ..neutral() }; + for s in [0.05, 0.3, 0.7] { + let out = convert(&p, s); + assert!((out[0] - out[1]).abs() < 1e-6 && (out[1] - out[2]).abs() < 1e-6, "{out:?}"); + } + let colour = convert(&Params { balance: [0.7, 1.0, 1.5], ..neutral() }, 0.3); + assert!(colour[0] > colour[2] + 0.02, "the same balance does tint a colour positive: {colour:?}"); + } + + #[test] + fn tables_match_the_exact_conversion() { + let mut t = std::boxed::Box::new(Tables::blank()); + let cases = [ + Params::default(), + neutral(), + Params { + brightness: 20.0, + contrast: 25.0, + temp: 15.0, + tint: -10.0, + saturation: 20.0, + lows_blue: 30.0, + lows_range: 40.0, + ..Params::default() + }, + Params { monochrome: true, balance: [0.8, 1.0, 1.3], ..Params::default() }, + // The steepest gammas the sliders and a balance reach, and the hardest curve. + Params { brightness: 50.0, balance: [0.4, 1.0, 2.5], contrast: 50.0, ..Params::default() }, + Params { brightness: -50.0, balance: [2.5, 1.0, 0.4], whites: 30.0, blacks: -20.0, ..Params::default() }, + ]; + for enc in [Encoding::Srgb, Encoding::Linear] { + // The base alone, and a measurement whose blue highlight sits two entries from black. + let dense = [0.2, 0.1, if enc == Encoding::Linear { 0.001 } else { 0.03 }]; + let analyses = [Analysis::manual(BASE), Analysis::from_scan_values(enc.encode3(BASE), enc.encode3(BASE), dense, enc).unwrap()]; + for (p, a) in cases.iter().flat_map(|p| analyses.iter().map(move |a| (p, a))) { + let c = Converter::new(a, p, enc, None); + c.tables(&mut t); + // Compared as displayed: a linear host's output is sRGB-encoded first. + let shown = |v: f32| if enc == Encoding::Linear { color::srgb_encode(v) } else { v }; + let (mut worst, mut at) = (0.0f32, [0.0f32; 3]); + for i in 0..=255u32 { + for j in (0..=255u32).step_by(15) { + for k in (0..=255u32).step_by(15) { + let neg = [i as f32 / 255.0, j as f32 / 255.0, k as f32 / 255.0]; + // A hair above the black point no path is stable: a lifting gamma + // turns the rounding of a millionth into percents. + if (0..3).any(|ch| (0.0..1e-5).contains(&c.levelled(neg[ch], ch)) && c.levelled(neg[ch], ch) > 0.0) { + continue; + } + let exact = c.convert(neg); + let fast = c.convert_with(&t, neg); + for ch in 0..3 { + let d = (shown(exact[ch]) - shown(fast[ch])).abs(); + if d > worst { + (worst, at) = (d, neg); + } + } + } + } + } + let (exact, fast) = (c.convert(at), c.convert_with(&t, at)); + std::eprintln!( + "{enc:?}, brightness {}, contrast {}, white {:?}: the tables stray by {worst} at {at:?}: {exact:?} vs {fast:?}", + p.brightness, + p.contrast, + a.white + ); + assert!(worst < 1e-3, "{enc:?}: the tables stray by {worst} (an 8-bit level is 0.0039)"); + } + } + // Non-finite input is black, as on the exact path. + let c = Converter::new(&Analysis::manual(BASE), &Params::default(), Encoding::Srgb, None); + c.tables(&mut t); + let odd = [f32::NAN, 0.5, f32::INFINITY]; + assert!(c.convert_with(&t, odd).iter().zip(c.convert(odd)).all(|(a, b)| (a - b).abs() < 1e-3)); + } + + #[test] + fn tone_curves_reach_linear_documents_too() { + let strong = Params { tone: Tone::LabHard, range: RANGE_STOPS, ..Params::default() }; + let lin = Converter::new(&Analysis::manual(BASE), &strong, Encoding::Linear, None).convert(scan(0.05, Encoding::Linear))[0]; + let srgb = Converter::new(&Analysis::manual(BASE), &strong, Encoding::Srgb, None).convert(scan(0.05, Encoding::Srgb))[0]; + assert!((color::srgb_encode(lin) - srgb).abs() < 2e-3, "{lin} vs {srgb}"); + assert!(lin < 0.05, "a dark tone drops under a hard curve: {lin}"); + } + + #[test] + fn hostile_parameters_do_not_poison_the_output() { + let p = Params { + exposure: f32::NAN, + brightness: f32::INFINITY, + temp: -1e9, + saturation: f32::NEG_INFINITY, + presat: f32::NAN, + whites: 1e9, + ..Params::default() + }; + let out = convert(&p, 0.5); + assert!(out.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{out:?}"); + let c = Converter::new(&Analysis::manual([f32::NAN, 0.0, f32::INFINITY]), &Params::default(), Encoding::Srgb, Some([f32::NAN; 3])); + let out = c.convert([f32::NAN, -1.0, 2.0]); + assert!(out.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{out:?}"); + } +} diff --git a/crates/film/src/look.rs b/crates/film/src/look.rs new file mode 100644 index 0000000000..d36a4ba38e --- /dev/null +++ b/crates/film/src/look.rs @@ -0,0 +1,331 @@ +//! Colour: white-balance presets, the colour models (looks), mid-tone colour balance and +//! highlight / shadow toning. Everything here is a per-channel gain or a small matrix, so the +//! conversion stays within the host's instruction budget. + +use crate::{Params, color, finite}; + +/// White-balance presets: fixed temperature / tint offsets for film stocks whose balance a +/// neutral conversion tends to miss. `AsIs` leaves the sliders alone. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum WbPreset { + #[default] + AsIs, + /// A touch of warmth, what most colour negative film wants after an inversion. + Warm, + Cool, + /// Tungsten-balanced cine stock shot in daylight: a stronger warm correction. + TungstenFilm, +} + +impl WbPreset { + pub const ALL: [(WbPreset, &'static str); 4] = + [(WbPreset::AsIs, "as_is"), (WbPreset::Warm, "warm"), (WbPreset::Cool, "cool"), (WbPreset::TungstenFilm, "tungsten_film")]; + + pub fn parse(s: &str) -> Option { + Self::ALL.iter().find(|(_, name)| *name == s).map(|(t, _)| *t) + } + + /// (temperature, tint) offsets in slider units. + pub fn offsets(self) -> (f32, f32) { + match self { + Self::AsIs => (0.0, 0.0), + Self::Warm => (8.0, 2.0), + Self::Cool => (-8.0, -2.0), + Self::TungstenFilm => (18.0, 4.0), + } + } +} + +/// Colour models: how the positive's colours are rendered. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Look { + /// Colour accuracy over character. + #[default] + Neutral, + /// The rendering of a minilab scanner: teal blues, golden yellows, warm neutrals. + LabWarm, + /// The same family, less warm. + LabCool, + /// Print-like depth: denser shadows with a touch of green, lifted saturation. + Print, + /// Luminosity first: clean contrast, restrained colour. + Clean, +} + +impl Look { + pub const ALL: [(Look, &'static str); 5] = + [(Look::Neutral, "neutral"), (Look::LabWarm, "lab_warm"), (Look::LabCool, "lab_cool"), (Look::Print, "print"), (Look::Clean, "clean")]; + + pub fn parse(s: &str) -> Option { + Self::ALL.iter().find(|(_, name)| *name == s).map(|(t, _)| *t) + } + + pub fn name(self) -> &'static str { + Self::ALL.iter().find(|(t, _)| *t == self).map_or("neutral", |(_, name)| name) + } + + /// A row-major matrix on linear RGB (rows sum to 1, so neutrals stay neutral), plus + /// temperature / tint offsets, a saturation factor and a shadow tint (linear RGB gains + /// weighted towards black). + pub fn recipe(self) -> Recipe { + let identity = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]; + match self { + Self::Neutral => Recipe { matrix: identity, temp: 0.0, tint: 0.0, saturation: 1.0, shadow_tint: [1.0; 3] }, + Self::LabWarm => Recipe { + matrix: [[1.00, 0.06, -0.06], [0.02, 1.00, -0.02], [-0.08, 0.12, 0.96]], + temp: 5.0, + tint: 1.0, + saturation: 1.12, + shadow_tint: [1.0; 3], + }, + Self::LabCool => Recipe { + matrix: [[1.00, 0.03, -0.03], [0.0, 1.00, 0.0], [-0.06, 0.10, 0.96]], + temp: 0.0, + tint: 0.0, + saturation: 1.08, + shadow_tint: [1.0; 3], + }, + Self::Print => Recipe { matrix: identity, temp: 2.0, tint: -1.0, saturation: 1.1, shadow_tint: [0.97, 1.02, 0.98] }, + Self::Clean => Recipe { matrix: identity, temp: 0.0, tint: 0.0, saturation: 0.92, shadow_tint: [1.0; 3] }, + } + } +} + +/// What a [`Look`] does, see [`Look::recipe`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Recipe { + pub matrix: [[f32; 3]; 3], + pub temp: f32, + pub tint: f32, + pub saturation: f32, + pub shadow_tint: [f32; 3], +} + +/// Per-channel gains for a temperature / tint pair (slider units, −50..50 each; larger values +/// from presets are allowed), applied in linear light. +pub fn white_balance(temp: f32, tint: f32) -> [f32; 3] { + let t = finite(temp, 0.0).clamp(-100.0, 100.0) / 50.0; + let u = finite(tint, 0.0).clamp(-100.0, 100.0) / 50.0; + [(1.0 + 0.4 * t).max(0.05), (1.0 - 0.3 * u).max(0.05), (1.0 - 0.4 * t).max(0.05)] +} + +/// Gains that make the linear positive `sample` neutral (the colour picker on a grey card or a +/// white wall): each channel to the sample's luminance. `None` for a sample without colour. +pub fn neutralise(sample: [f32; 3]) -> Option<[f32; 3]> { + let y = color::luminance(sample); + if !y.is_finite() || y <= 1e-6 || sample.iter().any(|v| !v.is_finite() || *v <= 1e-6) { + return None; + } + Some([(y / sample[0]).clamp(0.2, 5.0), (y / sample[1]).clamp(0.2, 5.0), (y / sample[2]).clamp(0.2, 5.0)]) +} + +/// Weight of the highlights for toning: 0 below `1 − reach`, 1 at white (`reach` 0..1). +pub fn highs_weight(y: f32, reach: f32) -> f32 { + let reach = reach.clamp(0.05, 1.0); + smoothstep((y - (1.0 - reach)) / reach) +} + +/// Weight of the shadows for toning: 1 at black, 0 above `reach` (`reach` 0..1). +pub fn lows_weight(y: f32, reach: f32) -> f32 { + let reach = reach.clamp(0.05, 1.0); + smoothstep((reach - y) / reach) +} + +/// Weight of the mid-tones: 1 at middle grey, 0 at black and white. +pub fn mids_weight(y: f32) -> f32 { + let y = y.clamp(0.0, 1.0); + 4.0 * y * (1.0 - y) +} + +fn smoothstep(x: f32) -> f32 { + let x = finite(x, 0.0).clamp(0.0, 1.0); + x * x * (3.0 - 2.0 * x) +} + +/// The colour part of a conversion, folded from [`Params`]: everything in linear light. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Colour { + /// White balance (sliders, preset, look and neutral sample) as gains. + pub gains: [f32; 3], + pub matrix: [[f32; 3]; 3], + /// Saturation before the tone curve (pre-saturation and the look), as a chroma factor. + pub presat: f32, + /// Mid-tone balance gains at full weight (red/cyan, green/magenta, blue/yellow). + pub mids: [f32; 3], + pub shadow_tint: [f32; 3], + /// The matrix is not the identity. + mixes: bool, + /// The mid-tone balance or the shadow tint is not neutral, so the luminance weights are needed. + weighted: bool, + pub is_identity: bool, +} + +impl Colour { + /// `neutral` is a linear positive sample that should come out grey, if the user picked one. + pub fn new(p: &Params, neutral: Option<[f32; 3]>) -> Self { + let recipe = p.look.recipe(); + let (pt, pu) = p.wb.offsets(); + let mut gains = white_balance(finite(p.temp, 0.0) + pt + recipe.temp, finite(p.tint, 0.0) + pu + recipe.tint); + if let Some(n) = neutral.and_then(neutralise) { + for (g, k) in gains.iter_mut().zip(n) { + *g *= k; + } + } + let presat = (finite(p.presat, 3.0).clamp(1.0, 5.0) / 3.0 * recipe.saturation).max(0.0); + let mut mids = [1.0; 3]; + for (m, v) in mids.iter_mut().zip([p.mids_red, p.mids_green, p.mids_blue]) { + *m = 1.0 + finite(v, 0.0).clamp(-50.0, 50.0) / 50.0 * 0.25; + } + let mixes = recipe.matrix != Look::Neutral.recipe().matrix; + let weighted = mids != [1.0; 3] || recipe.shadow_tint != [1.0; 3]; + let is_identity = gains == [1.0; 3] && !mixes && (presat - 1.0).abs() < 1e-6 && !weighted; + Self { gains, matrix: recipe.matrix, presat, mids, shadow_tint: recipe.shadow_tint, mixes, weighted, is_identity } + } + + /// One linear positive sample (levelled, 0..1-ish) through the colour pipeline. + pub fn apply(&self, mut p: [f32; 3]) -> [f32; 3] { + if self.is_identity { + return p; + } + for (v, g) in p.iter_mut().zip(self.gains) { + *v *= g; + } + if self.mixes { + let m = &self.matrix; + p = [ + m[0][0] * p[0] + m[0][1] * p[1] + m[0][2] * p[2], + m[1][0] * p[0] + m[1][1] * p[1] + m[1][2] * p[2], + m[2][0] * p[0] + m[2][1] * p[1] + m[2][2] * p[2], + ]; + } + let y = color::luminance(p).max(0.0); + if !self.weighted { + for v in &mut p { + *v = (y + (*v - y) * self.presat).max(0.0); + } + return p; + } + // Perceptual weights from the luminance; a square root is one instruction. + let yl = libm::sqrtf(y); + let w_mid = mids_weight(yl); + let w_low = lows_weight(yl, 0.35); + for (ch, v) in p.iter_mut().enumerate() { + let mut x = y + (*v - y) * self.presat; + x *= 1.0 + (self.mids[ch] - 1.0) * w_mid; + x *= 1.0 + (self.shadow_tint[ch] - 1.0) * w_low; + *v = x.max(0.0); + } + p + } +} + +/// Highlight and shadow toning, applied to the encoded positive after the tone curve: a +/// red / cyan, green / magenta and blue / yellow balance for each end, with a `range` that +/// says how far from the end the toning reaches. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Toning { + highs: [f32; 3], + highs_reach: f32, + lows: [f32; 3], + lows_reach: f32, + /// Saturation after the curve, as a chroma factor. + saturation: f32, + pub is_identity: bool, +} + +impl Toning { + pub fn new(p: &Params) -> Self { + let slider = |v: f32| finite(v, 0.0).clamp(-50.0, 50.0) / 50.0 * 0.15; + let reach = |v: f32| 0.2 + finite(v, 30.0).clamp(0.0, 100.0) / 100.0 * 0.6; + let highs = [slider(p.highs_red), slider(p.highs_green), slider(p.highs_blue)]; + let lows = [slider(p.lows_red), slider(p.lows_green), slider(p.lows_blue)]; + let saturation = (1.0 + finite(p.saturation, 0.0).clamp(-50.0, 50.0) / 50.0).max(0.0); + let is_identity = highs == [0.0; 3] && lows == [0.0; 3] && (saturation - 1.0).abs() < 1e-6; + Self { highs, highs_reach: reach(p.highs_range), lows, lows_reach: reach(p.lows_range), saturation, is_identity } + } + + /// One encoded RGB sample (0..1) toned and saturated, 0..1. + pub fn apply(&self, mut c: [f32; 3]) -> [f32; 3] { + if self.is_identity { + return c; + } + let y = (c[0] + c[1] + c[2]) / 3.0; + let w_hi = highs_weight(y, self.highs_reach); + let w_lo = lows_weight(y, self.lows_reach); + for (ch, x) in c.iter_mut().enumerate() { + let v = y + (*x - y) * self.saturation; + *x = (v + self.highs[ch] * w_hi + self.lows[ch] * w_lo).clamp(0.0, 1.0); + } + c + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn presets_and_looks_parse_and_keep_neutrals_neutral() { + for (preset, name) in WbPreset::ALL { + assert_eq!(WbPreset::parse(name), Some(preset)); + } + for (look, name) in Look::ALL { + assert_eq!(Look::parse(name), Some(look)); + let m = look.recipe().matrix; + for row in m { + assert!((row.iter().sum::() - 1.0).abs() < 1e-6, "{name}: {row:?}"); + } + } + assert_eq!(Look::parse("frontier"), None); + let warm = Colour::new(&Params { look: Look::LabWarm, ..Params::default() }, None); + let grey = warm.apply([0.3, 0.3, 0.3]); + assert!(grey[0] > grey[2], "the warm lab look warms neutrals: {grey:?}"); + let neutral = Colour::new(&Params::default(), None); + assert!(neutral.is_identity); + assert_eq!(neutral.apply([0.2, 0.4, 0.6]), [0.2, 0.4, 0.6]); + } + + #[test] + fn toning_colours_the_ends_and_post_saturation_scales_chroma() { + let warm_highs = Toning::new(&Params { highs_blue: -50.0, highs_range: 10.0, ..Params::default() }); + assert!(!warm_highs.is_identity); + let hi = warm_highs.apply([0.95, 0.95, 0.95]); + assert!(hi[2] < hi[0] && hi[0] == 0.95, "yellow highlights: {hi:?}"); + assert_eq!(warm_highs.apply([0.3, 0.3, 0.3]), [0.3, 0.3, 0.3], "mid-tones untouched at a short range"); + let cool_lows = Toning::new(&Params { lows_blue: 50.0, lows_range: 100.0, ..Params::default() }); + let lo = cool_lows.apply([0.1, 0.1, 0.1]); + assert!(lo[2] > lo[0], "{lo:?}"); + assert_eq!(cool_lows.apply([1.0; 3]), [1.0; 3]); + let grey = Toning::new(&Params { saturation: -50.0, ..Params::default() }).apply([0.2, 0.5, 0.8]); + assert!((grey[0] - grey[2]).abs() < 1e-6, "{grey:?}"); + assert!(Toning::new(&Params::default()).is_identity); + } + + #[test] + fn neutral_sample_is_made_grey() { + let sample = [0.5, 0.4, 0.3]; + let c = Colour::new(&Params::default(), Some(sample)); + let out = c.apply(sample); + assert!((out[0] - out[1]).abs() < 1e-5 && (out[1] - out[2]).abs() < 1e-5, "{out:?}"); + assert_eq!(neutralise([0.0, 0.5, 0.5]), None); + assert_eq!(neutralise([f32::NAN; 3]), None); + } + + #[test] + fn presat_mids_and_toning_helpers() { + let vivid = Colour::new(&Params { presat: 5.0, ..Params::default() }, None).apply([0.6, 0.3, 0.3]); + let flat = Colour::new(&Params { presat: 1.0, ..Params::default() }, None).apply([0.6, 0.3, 0.3]); + assert!(vivid[0] - vivid[1] > 0.3 && flat[0] - flat[1] < 0.3, "{vivid:?} {flat:?}"); + let mids = Colour::new(&Params { mids_red: 50.0, ..Params::default() }, None); + let mid = mids.apply([0.2, 0.2, 0.2]); + assert!(mid[0] > mid[1], "{mid:?}"); + let black = mids.apply([0.0; 3]); + assert_eq!(black, [0.0; 3]); + assert_eq!(highs_weight(1.0, 0.5), 1.0); + assert_eq!(highs_weight(0.4, 0.5), 0.0); + assert_eq!(lows_weight(0.0, 0.3), 1.0); + assert_eq!(lows_weight(0.5, 0.3), 0.0); + assert_eq!(mids_weight(0.5), 1.0); + assert_eq!(white_balance(0.0, 0.0), [1.0; 3]); + } +} diff --git a/crates/film/src/measure.rs b/crates/film/src/measure.rs new file mode 100644 index 0000000000..b68136d579 --- /dev/null +++ b/crates/film/src/measure.rs @@ -0,0 +1,173 @@ +//! What belongs to the scan rather than the film, measured once on the whole image: the film base +//! and each channel's black and white point, and a mid-tone balance that makes the scene average +//! grey. A host stores the result with the photo's settings, so every render of it (a draft, a +//! zoomed window, a full-size export) converts with the same numbers. + +use crate::{Analysis, Converter, Encoding, Params, Tone, ValueHistogram, color}; + +/// How a scan is measured. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MeasureOptions { + /// Fraction of each edge left out (film holder, sprocket holes, the border itself), 0..0.45. + pub border: f32, + /// Share of the brightest samples that may lie above the film base (dust, hot pixels). + pub base_clip: f32, + /// Shares of samples allowed beyond black and white. + pub black_clip: f32, + pub white_clip: f32, + /// Bring each channel's median to the common one with a per-channel gamma (a grey scene + /// average). Off: the black and white points are neutral and the scene keeps its own colour. + pub neutral: bool, + /// At most this many pixels are sampled (a regular grid over the image). + pub max_samples: usize, +} + +impl Default for MeasureOptions { + fn default() -> Self { + Self { border: 0.08, base_clip: 0.001, black_clip: 0.003, white_clip: 0.003, neutral: true, max_samples: 1_000_000 } + } +} + +/// A measured scan: scan values in linear light, 0..1, per channel. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Measurement { + /// The film base: the unexposed film, scene black. + pub base: [f32; 3], + /// The brightest value that still counts as exposed (the positive's black). + pub black: [f32; 3], + /// The densest value (the positive's white). + pub white: [f32; 3], + /// Per-channel mid-tone gammas that neutralise the scene average (1 = none). + pub balance: [f32; 3], +} + +impl Measurement { + /// The levels of this measurement for linear samples; with a `base` picked from the border, + /// that base is black and the measured white point still applies. `None` when a channel has + /// no range left between black and white. + pub fn analysis(&self, base: Option<[f32; 3]>) -> Option { + match base { + Some(b) => Analysis::from_scan_values(b, b, self.white, Encoding::Linear), + None => Analysis::from_scan_values(self.base, self.black, self.white, Encoding::Linear), + } + } +} + +/// Measures a `w × h` scan of linear samples (row-major, 0..1 per channel). +pub fn measure(pixels: &[[f32; 3]], w: usize, h: usize, o: &MeasureOptions) -> Result { + if pixels.len() < w.saturating_mul(h) { + return Err("the image is smaller than its size says".into()); + } + let border = if o.border.is_finite() { o.border.clamp(0.0, 0.45) } else { 0.0 }; + let (bx, by) = ((w as f32 * border) as usize, (h as f32 * border) as usize); + let (x0, x1, y0, y1) = (bx, w.saturating_sub(bx), by, h.saturating_sub(by)); + if x1 <= x0 || y1 <= y0 { + return Err("the border leaves no pixels to measure".into()); + } + let area = (x1 - x0).saturating_mul(y1 - y0); + let step = (libm::ceil(libm::sqrt(area as f64 / o.max_samples.max(1) as f64)) as usize).max(1); + // The histogram is binned on the sRGB-encoded values, which spread the dense end (the + // highlights, near 0 in linear light) over many more bins than a linear scale would. + let mut hist = ValueHistogram::new(); + for y in (y0..y1).step_by(step) { + for x in (x0..x1).step_by(step) { + if let Some(p) = pixels.get(y * w + x) { + hist.push(Encoding::Srgb.encode3(*p)); + } + } + } + if hist.count() == 0 { + return Err("no pixels to measure".into()); + } + let q = |ch: usize, frac: f32| hist.quantile(ch, frac).map(color::srgb_decode).ok_or_else(|| "empty histogram".to_string()); + let mut m = Measurement { base: [0.0; 3], black: [0.0; 3], white: [0.0; 3], balance: [1.0; 3] }; + let mut median = [0.0; 3]; + for (ch, med) in median.iter_mut().enumerate() { + m.base[ch] = q(ch, 1.0 - o.base_clip.clamp(0.0, 0.5))?; + m.black[ch] = q(ch, 1.0 - o.black_clip.clamp(0.0, 0.5))?; + m.white[ch] = q(ch, o.white_clip.clamp(0.0, 0.5))?; + *med = q(ch, 0.5)?; + if m.white[ch] >= m.black[ch] { + return Err("the scan has no tonal range between black and white (a flat image, or the border leaves too little)".into()); + } + } + if o.neutral { + m.balance = neutral_balance(&m, median); + } + Ok(m) +} + +/// Per-channel gammas that bring each channel's median positive to the geometric mean of the +/// three: the scene averages grey, black and white stay put. +fn neutral_balance(m: &Measurement, median: [f32; 3]) -> [f32; 3] { + let Some(a) = m.analysis(None) else { return [1.0; 3] }; + let c = Converter::new(&a, &Params { tone: Tone::Linear, ..Params::default() }, Encoding::Linear, None); + let out = c.convert(median).map(|v| v.clamp(1e-3, 0.999)); + let target = (libm::logf(out[0]) + libm::logf(out[1]) + libm::logf(out[2])) / 3.0; + out.map(|v| { + let b = target / libm::logf(v); + if b.is_finite() { b.clamp(0.4, 2.5) } else { 1.0 } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{RANGE_STOPS, film}; + + const BASE: [f32; 3] = [0.6, 0.35, 0.15]; + + /// A synthetic negative: a log ramp of scene exposures across the width, with a cast in the + /// blue mid-tones the neutral balance should take out, framed by a border of film base. + fn scan(w: usize, h: usize) -> Vec<[f32; 3]> { + let mut px = Vec::with_capacity(w * h); + for y in 0..h { + for x in 0..w { + let inside = x >= w / 10 && x < w - w / 10 && y >= h / 10 && y < h - h / 10; + let s = x as f32 / (w - 1) as f32; + let e = libm::exp2f(s * RANGE_STOPS); + px.push(if inside { + [film::transmittance(e, BASE[0]), film::transmittance(e, BASE[1]), film::transmittance(e, BASE[2]) * 0.8] + } else { + BASE + }); + } + } + px + } + + #[test] + fn measures_base_levels_and_balance_of_a_synthetic_negative() { + let (w, h) = (300, 200); + let px = scan(w, h); + let m = measure(&px, w, h, &MeasureOptions { border: 0.12, ..MeasureOptions::default() }).unwrap(); + for ch in 0..3 { + assert!(m.white[ch] < m.black[ch] && m.black[ch] <= m.base[ch] * 1.01, "{m:?}"); + } + assert!(m.balance[2] != 1.0, "the blue cast gets a balance: {m:?}"); + // With the border in the measured area, the base is the border. + let framed = measure(&px, w, h, &MeasureOptions { border: 0.0, ..MeasureOptions::default() }).unwrap(); + for ch in 0..3 { + assert!((framed.base[ch] - BASE[ch]).abs() < 0.01, "{framed:?}"); + } + let a = m.analysis(None).unwrap(); + assert!(a.white.iter().zip(a.black).all(|(w, b)| *w > b)); + // A picked base is black; the measured white point stays. + let picked = m.analysis(Some(BASE)).unwrap(); + assert_eq!(picked.base, BASE); + assert_eq!(picked.black, [1.0; 3]); + } + + #[test] + fn bad_input_is_an_error_not_a_panic() { + assert!(measure(&[], 0, 0, &MeasureOptions::default()).is_err()); + assert!(measure(&[[0.5; 3]; 4], 10, 10, &MeasureOptions::default()).is_err(), "short buffer"); + assert!(measure(&[[0.5; 3]; 100], 10, 10, &MeasureOptions::default()).is_err(), "flat image"); + let px = scan(40, 30); + assert!(measure(&px, 40, 30, &MeasureOptions { border: f32::NAN, ..MeasureOptions::default() }).is_ok()); + // One sample has no range: an error too. + assert!(measure(&px, 40, 30, &MeasureOptions { max_samples: 0, ..MeasureOptions::default() }).is_err()); + let nan = vec![[f32::NAN, f32::INFINITY, -1.0]; 100]; + assert!(measure(&nan, 10, 10, &MeasureOptions::default()).is_err()); + } +} diff --git a/crates/film/src/preset.rs b/crates/film/src/preset.rs new file mode 100644 index 0000000000..740ec25824 --- /dev/null +++ b/crates/film/src/preset.rs @@ -0,0 +1,416 @@ +//! Presets: the character of a film stock as a conversion recipe. +//! +//! A preset carries what belongs to the *film*: the contrast of each colour layer (density per +//! log-exposure), the typical colour of its mask, a tone profile, a colour model, saturation, +//! a warmth offset and a touch of toning. It does not carry what belongs to the *scan* (the +//! actual film base and the black and white points), which is measured; the preset's mask +//! colour is only the fallback when nothing was measured. +//! +//! The recipes are starting points derived from the stocks' published characteristic curves +//! and the way they are known to render, named after the stock they take after. Names are +//! lower-case words and numbers, which a host that labels a choice from its value renders +//! capitalised (`portra 400` → "Portra 400"); [`Preset::parse`] accepts any spelling of them. + +use crate::{Look, NEGATIVE_GAMMA, Params, Tone, color, finite}; + +/// How much more density each channel of a scan of colour negative film spans than the layer's +/// own gamma gives, red, green, blue: a scan's blue runs far denser than its red (the orange +/// mask, the dyes' side absorptions, the scanner's or camera's channel sensitivities). Only the +/// levels derived from a base alone use it ([`Preset::scan_gamma`]); a measurement makes it +/// irrelevant. +/// +/// Provisional: fitted on three frames of one Kodak Ektar 100 strip photographed against +/// daylight, matching the colour of each frame's mean to the photographer's own positive (the +/// best fit per preset ran 0.62 to 0.78 for red and 1.30 to 1.52 for blue). Without it, those +/// frames came out strongly blue. More scans are needed to settle it. +pub const SCAN_SPREAD: [f32; 3] = [0.7, 1.0, 1.4]; + +/// One recipe. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Preset { + /// The parameter value and its menu entry, as shown ([`Preset::parse`] takes any spelling). + pub name: &'static str, + /// Density per log-exposure of the red, green and blue layers (as the film's data gives + /// it; a scan spreads them further, [`SCAN_SPREAD`]). + pub gamma: [f32; 3], + /// Typical mask colour of an unexposed, normally scanned frame, sRGB-encoded 0..1: the + /// fallback film base. + pub base: [f32; 3], + pub tone: Tone, + pub look: Look, + pub presat: f32, + /// Offsets added to the sliders. + pub contrast: f32, + pub temp: f32, + pub tint: f32, + pub saturation: f32, + /// Highlight and shadow toning (red, green, blue balance, −50..50) at the default range. + pub highs: [f32; 3], + pub lows: [f32; 3], + pub monochrome: bool, +} + +/// Every preset, in menu order. The first is the default. +/// +/// The film names are the trademarks of their makers (Eastman Kodak, FUJIFILM, CineStill), used +/// to say which stock a recipe takes after; the recipes are this project's own, built from the +/// stocks' published characteristics and the way they are known to render, and are starting +/// points to tune against your own scans. +pub const PRESETS: [Preset; 12] = [ + // A neutral lab scan: even layer contrast, neutral colour, the lab tone profile. + Preset { + name: "Standard", + gamma: [NEGATIVE_GAMMA; 3], + base: [0.80, 0.52, 0.36], + tone: Tone::LabStandard, + look: Look::Neutral, + presat: 3.0, + contrast: 0.0, + temp: 0.0, + tint: 0.0, + saturation: 0.0, + highs: [0.0; 3], + lows: [0.0; 3], + monochrome: false, + }, + // Kodak Portra 160: the gentlest of the family. Low contrast, pastel saturation, warm + // natural skin, soft warm highlights. + Preset { + name: "Portra 160", + gamma: [0.56, 0.58, 0.60], + base: [0.79, 0.53, 0.37], + tone: Tone::LabSoft, + look: Look::Neutral, + presat: 2.4, + contrast: -4.0, + temp: 4.0, + tint: 1.0, + saturation: -8.0, + highs: [3.0, 1.0, -4.0], + lows: [0.0, 0.0, 1.0], + monochrome: false, + }, + // Kodak Portra 400: the portrait standard. Moderate contrast, warm natural skin, muted but + // full colour, warm highlights, a touch of cool in the shadows. + Preset { + name: "Portra 400", + gamma: [0.58, 0.60, 0.63], + base: [0.79, 0.53, 0.37], + tone: Tone::LabSoft, + look: Look::Neutral, + presat: 2.8, + contrast: 0.0, + temp: 9.0, + tint: -2.0, + saturation: -2.0, + highs: [5.0, 1.0, -6.0], + lows: [-1.0, 1.0, 0.0], + monochrome: false, + }, + // Kodak Ektar 100: the saturated one. Steep layers, strong separation, vivid reds and + // blues, clean neutrals, contrast to match. + Preset { + name: "Ektar 100", + gamma: [0.63, 0.65, 0.69], + base: [0.78, 0.50, 0.33], + tone: Tone::LabStandard, + look: Look::Neutral, + presat: 4.0, + contrast: 10.0, + temp: 3.0, + tint: 1.0, + saturation: 14.0, + highs: [2.0, 0.0, -2.0], + lows: [0.0, 0.0, -3.0], + monochrome: false, + }, + // Kodak Gold 200: golden. Warm yellow highlights, warm neutrals, saturated reds and + // yellows, the minilab rendering. + Preset { + name: "Gold 200", + gamma: [0.60, 0.62, 0.66], + base: [0.82, 0.54, 0.35], + tone: Tone::LabStandard, + look: Look::LabWarm, + presat: 3.2, + contrast: 2.0, + temp: 12.0, + tint: 3.0, + saturation: 6.0, + highs: [8.0, 3.0, -10.0], + lows: [3.0, 0.0, -3.0], + monochrome: false, + }, + // Kodak ColorPlus 200: the everyday stock. Warm like Gold but softer and less saturated, + // warm shadows, a little faded: the look of old snapshots. + Preset { + name: "ColorPlus 200", + gamma: [0.58, 0.60, 0.63], + base: [0.83, 0.55, 0.36], + tone: Tone::LabSoft, + look: Look::LabWarm, + presat: 2.8, + contrast: -2.0, + temp: 10.0, + tint: 2.0, + saturation: -2.0, + highs: [6.0, 2.0, -8.0], + lows: [4.0, 1.0, -2.0], + monochrome: false, + }, + // Kodak UltraMax 400: the punchy consumer stock. Saturated, contrasty, warm, strong blues. + Preset { + name: "UltraMax 400", + gamma: [0.61, 0.63, 0.67], + base: [0.81, 0.53, 0.35], + tone: Tone::LabStandard, + look: Look::LabWarm, + presat: 3.5, + contrast: 6.0, + temp: 6.0, + tint: 2.0, + saturation: 10.0, + highs: [4.0, 2.0, -6.0], + lows: [1.0, 0.0, -1.0], + monochrome: false, + }, + // Fujifilm Superia X-TRA 400: Fuji's greens. Cooler than Kodak, a steeper green layer, + // vivid, teal shadows, a touch of magenta in skin. + Preset { + name: "Superia 400", + gamma: [0.60, 0.64, 0.66], + base: [0.76, 0.50, 0.34], + tone: Tone::LabStandard, + look: Look::LabCool, + presat: 3.4, + contrast: 6.0, + temp: -5.0, + tint: -5.0, + saturation: 8.0, + highs: [0.0, 3.0, -2.0], + lows: [-3.0, 2.0, 5.0], + monochrome: false, + }, + // Fujifilm C200: clean and cool. Soft contrast, restrained saturation, cool neutrals, a + // green-cyan lean in the shadows. + Preset { + name: "C200", + gamma: [0.58, 0.61, 0.63], + base: [0.77, 0.51, 0.35], + tone: Tone::LabSoft, + look: Look::LabCool, + presat: 2.8, + contrast: 0.0, + temp: -4.0, + tint: -3.0, + saturation: -4.0, + highs: [0.0, 2.0, 0.0], + lows: [-2.0, 2.0, 3.0], + monochrome: false, + }, + // Fujifilm Pro 400H: the pastel wedding stock. Flat layers, airy highlights, mint greens, + // cyan shadows, soft skin; made to be overexposed. + Preset { + name: "Pro 400H", + gamma: [0.55, 0.58, 0.60], + base: [0.78, 0.52, 0.36], + tone: Tone::LabSoft, + look: Look::Clean, + presat: 2.3, + contrast: -8.0, + temp: -3.0, + tint: -6.0, + saturation: -6.0, + highs: [-2.0, 2.0, 2.0], + lows: [-4.0, 3.0, 5.0], + monochrome: false, + }, + // CineStill 800T: tungsten cine stock shot in daylight. Low, cinematic contrast, muted + // colour, teal-blue shadows against warm orange highlights. (The halation it is known for + // is not a colour and is not modelled.) + Preset { + name: "CineStill 800", + gamma: [0.55, 0.57, 0.60], + base: [0.80, 0.52, 0.36], + tone: Tone::Cinematic, + look: Look::Clean, + presat: 2.6, + contrast: 0.0, + temp: -3.0, + tint: 2.0, + saturation: -8.0, + highs: [10.0, 2.0, -8.0], + lows: [-8.0, 0.0, 12.0], + monochrome: false, + }, + // Black-and-white: a paper-like straight line with some contrast, no colour. + Preset { + name: "Monochrome", + gamma: [0.65; 3], + base: [0.74; 3], + tone: Tone::Linear, + look: Look::Neutral, + presat: 3.0, + contrast: 15.0, + temp: 0.0, + tint: 0.0, + saturation: 0.0, + highs: [0.0; 3], + lows: [0.0; 3], + monochrome: true, + }, +]; + +/// The sliders a user sets on top of a preset. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Sliders { + pub exposure: f32, + pub brightness: f32, + pub contrast: f32, + pub temp: f32, + pub tint: f32, + pub saturation: f32, +} + +/// A preset name reduced to what [`Preset::parse`] compares: its letters and digits, lower-case. +fn name_key(s: &str) -> impl Iterator + '_ { + s.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()) +} + +impl Preset { + /// The preset with this name, spelled any way: case, spaces, hyphens and underscores do not + /// count (`portra 400`, `portra400` and `PORTRA_400` are the same preset). + pub fn parse(name: &str) -> Option<&'static Preset> { + PRESETS.iter().find(|p| name_key(p.name).eq(name_key(name))) + } + + pub fn default_preset() -> &'static Preset { + &PRESETS[0] + } + + /// The fallback film base in linear light. + pub fn base_linear(&self) -> [f32; 3] { + [color::srgb_decode(self.base[0]), color::srgb_decode(self.base[1]), color::srgb_decode(self.base[2])] + } + + /// Density per log-exposure of each channel as a scan sees it: [`Preset::gamma`] spread by + /// [`SCAN_SPREAD`] for colour film, as it is for black-and-white (no mask, one dye). + pub fn scan_gamma(&self) -> [f32; 3] { + if self.monochrome { + return self.gamma; + } + [self.gamma[0] * SCAN_SPREAD[0], self.gamma[1] * SCAN_SPREAD[1], self.gamma[2] * SCAN_SPREAD[2]] + } + + /// The conversion parameters for this preset with `s` on top. + pub fn params(&self, s: &Sliders) -> Params { + let d = Params::default(); + Params { + exposure: finite(s.exposure, 0.0), + brightness: finite(s.brightness, 0.0), + contrast: self.contrast + finite(s.contrast, 0.0), + tone: self.tone, + temp: self.temp + finite(s.temp, 0.0), + tint: self.tint + finite(s.tint, 0.0), + presat: self.presat, + saturation: self.saturation + finite(s.saturation, 0.0), + look: self.look, + highs_red: self.highs[0], + highs_green: self.highs[1], + highs_blue: self.highs[2], + lows_red: self.lows[0], + lows_green: self.lows[1], + lows_blue: self.lows[2], + monochrome: self.monochrome, + film_gamma: self.scan_gamma(), + ..d + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Analysis, Converter, Encoding, RANGE_STOPS, film}; + + #[test] + fn presets_parse_and_the_first_is_standard() { + assert_eq!(Preset::default_preset().name, "Standard"); + for p in &PRESETS { + assert_eq!(Preset::parse(p.name).map(|q| q.name), Some(p.name)); + assert!(p.gamma.iter().all(|g| (0.4..=0.8).contains(g)), "{}", p.name); + assert!(p.base.iter().all(|b| (0.3..=0.95).contains(b)), "{}", p.name); + } + assert!(Preset::parse("portra").is_none()); + } + + #[test] + fn names_parse_in_any_spelling() { + for (spelling, name) in [ + ("portra 400", "Portra 400"), + ("portra400", "Portra 400"), + ("PORTRA_400", "Portra 400"), + ("pro 400h", "Pro 400H"), + ("CineStill-800", "CineStill 800"), + ] { + assert_eq!(Preset::parse(spelling).map(|p| p.name), Some(name), "{spelling}"); + } + assert!(Preset::parse("kodachrome").is_none() && Preset::parse("").is_none()); + // A host shows a choice with a space exactly as written (PhotoCraft does), so the names + // are the menu's text: capitalised words and numbers, distinct however they are spelled. + for p in &PRESETS { + assert!(p.name.starts_with(|c: char| c.is_ascii_uppercase()), "{}", p.name); + assert!(p.name.chars().all(|c| c.is_ascii_alphanumeric() || c == ' '), "{}", p.name); + assert_eq!(PRESETS.iter().filter(|q| name_key(q.name).eq(name_key(p.name))).count(), 1, "{}", p.name); + } + } + + #[test] + fn every_preset_converts_a_ramp_monotonically_and_finitely() { + let white = libm::exp2f(RANGE_STOPS); + for preset in &PRESETS { + let base = preset.base_linear(); + let p = preset.params(&Sliders::default()); + let c = Converter::new(&Analysis::from_base(base, p.film_gamma), &p, Encoding::Srgb, None); + let mut last = [-1.0f32; 3]; + for i in 0..=40 { + let s = i as f32 / 40.0; + let e = 1.0 + s * (white - 1.0); + let scan = [ + color::srgb_encode(film::transmittance(e, base[0])), + color::srgb_encode(film::transmittance(e, base[1])), + color::srgb_encode(film::transmittance(e, base[2])), + ]; + let out = c.convert(scan); + assert!(out.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{}: {out:?}", preset.name); + let y = color::luminance(out); + assert!(y >= color::luminance(last) - 1e-3, "{} not monotonic at {s}: {out:?} after {last:?}", preset.name); + if preset.monochrome { + assert!((out[0] - out[1]).abs() < 1e-5 && (out[1] - out[2]).abs() < 1e-5, "{}: {out:?}", preset.name); + } + last = out; + } + assert!(color::luminance(last) > 0.9, "{} reaches white: {last:?}", preset.name); + } + } + + #[test] + fn sliders_add_to_the_preset() { + let golden = Preset::parse("gold 200").unwrap(); + let p = golden.params(&Sliders { temp: 10.0, contrast: -8.0, exposure: f32::NAN, ..Sliders::default() }); + assert_eq!(p.temp, golden.temp + 10.0); + assert_eq!(p.contrast, golden.contrast - 8.0); + assert_eq!(p.exposure, 0.0); + assert_eq!(p.look, Look::LabWarm); + assert_eq!(p.film_gamma, golden.scan_gamma()); + } + + #[test] + fn a_scan_spreads_colour_layers_but_not_black_and_white() { + let portra = Preset::parse("portra 400").unwrap(); + let g = portra.scan_gamma(); + assert!(g[0] < portra.gamma[0] && g[1] == portra.gamma[1] && g[2] > portra.gamma[2], "{g:?}"); + let mono = Preset::parse("monochrome").unwrap(); + assert_eq!(mono.scan_gamma(), mono.gamma); + } +} diff --git a/crates/film/src/tone.rs b/crates/film/src/tone.rs new file mode 100644 index 0000000000..8db6f0bef5 --- /dev/null +++ b/crates/film/src/tone.rs @@ -0,0 +1,331 @@ +//! Tone shaping in display (sRGB-encoded) space: the tone profiles, the tone sliders, and the +//! lab-scanner look of a lifted toe (fade) and a soft shoulder (glow). + +use crate::{Params, finite}; + +/// The tone profiles: three families, as lab-style negative conversion software offers them. +/// +/// - **Linear**: a flat, neutral start, a straight line between the black and white points; +/// `Deep` darkens the mid-tones, `Flat` lifts black and lowers white a little. +/// - **Cinematic**: smooth, low-contrast mid-tones and shadows with strong highlight +/// separation, the look of scanned cine film; `Flat` lifts the toe further, `Rich` adds +/// contrast. +/// - **Lab**: the contrast of a lab scanner, tones close to clipping. `Standard` is the +/// default; the others change the steepness on one side or both. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Tone { + Linear, + LinearDeep, + LinearFlat, + Cinematic, + CinematicFlat, + CinematicRich, + LabSoft, + #[default] + LabStandard, + LabHard, + LabHighlightSoft, + LabHighlightHard, + LabShadowSoft, + LabShadowHard, +} + +/// A profile's shape: logistic steepness on the shadow and highlight sides (0 = straight), +/// a black lift, a white ceiling and a mid-tone gamma. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Profile { + k_lo: f32, + k_hi: f32, + lift: f32, + ceiling: f32, + gamma: f32, +} + +impl Tone { + /// Every profile with its parameter name, in menu order. + pub const ALL: [(Tone, &'static str); 13] = [ + (Tone::Linear, "linear"), + (Tone::LinearDeep, "linear_deep"), + (Tone::LinearFlat, "linear_flat"), + (Tone::Cinematic, "cinematic"), + (Tone::CinematicFlat, "cinematic_flat"), + (Tone::CinematicRich, "cinematic_rich"), + (Tone::LabSoft, "lab_soft"), + (Tone::LabStandard, "lab_standard"), + (Tone::LabHard, "lab_hard"), + (Tone::LabHighlightSoft, "lab_highlight_soft"), + (Tone::LabHighlightHard, "lab_highlight_hard"), + (Tone::LabShadowSoft, "lab_shadow_soft"), + (Tone::LabShadowHard, "lab_shadow_hard"), + ]; + + pub fn parse(s: &str) -> Option { + Self::ALL.iter().find(|(_, name)| *name == s).map(|(t, _)| *t) + } + + pub fn name(self) -> &'static str { + Self::ALL.iter().find(|(t, _)| *t == self).map_or("linear", |(_, name)| name) + } + + /// The profile's mid-tone gamma (> 1 darkens), applied with brightness by the converter. + pub fn gamma(self) -> f32 { + self.profile().gamma + } + + fn profile(self) -> Profile { + let p = |k_lo, k_hi, lift, ceiling, gamma| Profile { k_lo, k_hi, lift, ceiling, gamma }; + match self { + Self::Linear => p(0.0, 0.0, 0.0, 1.0, 1.0), + Self::LinearDeep => p(0.0, 0.0, 0.0, 1.0, 1.15), + Self::LinearFlat => p(0.0, 0.0, 0.04, 0.97, 1.0), + Self::Cinematic => p(1.5, 3.5, 0.03, 1.0, 0.95), + Self::CinematicFlat => p(1.0, 2.5, 0.06, 0.98, 0.95), + Self::CinematicRich => p(2.5, 4.5, 0.0, 1.0, 1.05), + Self::LabSoft => p(2.5, 2.5, 0.0, 1.0, 1.0), + Self::LabStandard => p(4.0, 4.0, 0.0, 1.0, 1.0), + Self::LabHard => p(6.0, 6.0, 0.0, 1.0, 1.0), + Self::LabHighlightSoft => p(4.0, 2.0, 0.0, 1.0, 1.0), + Self::LabHighlightHard => p(4.0, 6.5, 0.0, 1.0, 1.0), + Self::LabShadowSoft => p(2.0, 4.0, 0.0, 1.0, 1.0), + Self::LabShadowHard => p(6.5, 4.0, 0.0, 1.0, 1.0), + } + } +} + +/// Steepness the contrast slider adds at ±50. +const CONTRAST_STEEPNESS: f32 = 4.0; +/// Steepest logistic allowed. +const MAX_STEEPNESS: f32 = 10.0; + +/// The folded tone curve of one conversion. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Curve { + /// Logistic steepness on the shadow and highlight sides; both ≤ 0 means "towards flat" + /// by `−k / MAX_STEEPNESS`. + k_lo: f32, + k_hi: f32, + lights: f32, + darks: f32, + /// Black lift (positive fade and the profile's lift) and shadow expansion (negative fade). + lift: f32, + expand_lows: f32, + ceiling: f32, + /// Highlight compression (positive glow) and expansion (negative glow). + glow: f32, + expand_highs: f32, + soft_highs: f32, + soft_lows: f32, +} + +impl Curve { + pub fn new(p: &Params) -> Self { + let prof = p.tone.profile(); + let contrast = finite(p.contrast, 0.0).clamp(-50.0, 50.0) / 50.0 * CONTRAST_STEEPNESS; + let fade = finite(p.fade, 0.0).clamp(-100.0, 100.0) / 100.0; + let glow = finite(p.glow, 0.0).clamp(-100.0, 100.0) / 100.0; + Self { + k_lo: (prof.k_lo + contrast).clamp(-MAX_STEEPNESS, MAX_STEEPNESS), + k_hi: (prof.k_hi + contrast).clamp(-MAX_STEEPNESS, MAX_STEEPNESS), + lights: finite(p.lights, 0.0).clamp(-50.0, 50.0) / 100.0, + darks: finite(p.darks, 0.0).clamp(-50.0, 50.0) / 100.0, + lift: prof.lift + fade.max(0.0) * 0.2, + expand_lows: (-fade).max(0.0) * 2.0, + ceiling: prof.ceiling, + glow: glow.max(0.0) * 2.0, + expand_highs: (-glow).max(0.0) * 2.0, + soft_highs: finite(p.soft_highs, 0.0).clamp(0.0, 100.0) / 100.0 * 2.0, + soft_lows: finite(p.soft_lows, 0.0).clamp(0.0, 100.0) / 100.0 * 2.0, + } + } + + /// True when the curve changes nothing, so a host can skip the encode / decode around it. + pub fn is_identity(&self) -> bool { + self.k_lo.abs() <= 1e-6 + && self.k_hi.abs() <= 1e-6 + && self.lights == 0.0 + && self.darks == 0.0 + && self.lift <= 0.0 + && self.expand_lows <= 0.0 + && self.ceiling >= 1.0 + && self.glow <= 0.0 + && self.expand_highs <= 0.0 + && self.soft_highs <= 0.0 + && self.soft_lows <= 0.0 + } + + /// `x` (sRGB-encoded, 0..1) through the curve, 0..1. + pub fn apply(&self, x: f32) -> f32 { + let mut y = finite(x, 0.0).clamp(0.0, 1.0); + // The contrast S: one symmetric logistic per side (each pinned at 0, ½ and 1), blended + // across the middle so the join is smooth and mid-grey stays where it is. + if (self.k_lo - self.k_hi).abs() <= 1e-6 { + y = s_curve(y, self.k_lo); + } else { + let w = smoothstep((y - 0.3) / 0.4); + y = s_curve(y, self.k_lo) * (1.0 - w) + s_curve(y, self.k_hi) * w; + } + // Bumps centred on the shadows (⅓) and highlights (⅔), zero at both ends. + y += self.darks * 3.0 * y * (1.0 - y) * (1.0 - y); + y += self.lights * 3.0 * y * y * (1.0 - y); + y = y.clamp(0.0, 1.0); + // Shadow and highlight tonality: expansion steepens an end, compression softens it. + if self.expand_lows > 0.0 { + y = remap(y, 0.0, 0.5, |t| compress_top(t, self.expand_lows)); + } + if self.expand_highs > 0.0 { + y = remap(y, 0.5, 1.0, |t| compress_bottom(t, self.expand_highs)); + } + if self.glow > 0.0 { + y = remap(y, 0.5, 1.0, |t| compress_top(t, self.glow)); + } + if self.soft_lows > 0.0 { + y = remap(y, 0.0, 0.3, |t| compress_bottom(t, self.soft_lows)); + } + if self.soft_highs > 0.0 { + y = remap(y, 0.7, 1.0, |t| compress_top(t, self.soft_highs)); + } + // Lift and ceiling last, so black and white land where the profile and fade say. + if self.lift > 0.0 || self.ceiling < 1.0 { + y = self.lift + y * (self.ceiling - self.lift); + } + y.clamp(0.0, 1.0) + } +} + +fn sigmoid(x: f32) -> f32 { + 1.0 / (1.0 + libm::expf(-x)) +} + +/// A symmetric contrast curve through (0, 0), (½, ½) and (1, 1): a logistic of steepness `k` +/// when `k > 0`, a pull towards flat when `k < 0`, identity at 0. +fn s_curve(y: f32, k: f32) -> f32 { + if k > 1e-6 { + let half = sigmoid(k * 0.5) - 0.5; + (0.5 + 0.5 * (sigmoid(k * (y - 0.5)) - 0.5) / half).clamp(0.0, 1.0) + } else if k < -1e-6 { + y + (0.5 - y) * (-k / MAX_STEEPNESS) + } else { + y + } +} + +fn smoothstep(x: f32) -> f32 { + let x = x.clamp(0.0, 1.0); + x * x * (3.0 - 2.0 * x) +} + +/// `t` in 0..1 with its slope reduced towards 1 (Reinhard with the white point kept at 1). +fn compress_top(t: f32, a: f32) -> f32 { + t * (1.0 + a) / (1.0 + a * t) +} + +/// `t` in 0..1 with its slope reduced towards 0. +fn compress_bottom(t: f32, a: f32) -> f32 { + 1.0 - compress_top(1.0 - t, a) +} + +/// `y` with `f` applied to the part of it inside `lo..hi` (unchanged outside). +fn remap(y: f32, lo: f32, hi: f32, f: impl Fn(f32) -> f32) -> f32 { + if y <= lo || y >= hi { + return y; + } + lo + f((y - lo) / (hi - lo)) * (hi - lo) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn curve(p: Params) -> Curve { + Curve::new(&p) + } + + fn linear() -> Params { + Params { tone: Tone::Linear, ..Params::default() } + } + + #[test] + fn names_round_trip_and_default_is_lab_standard() { + for (tone, name) in Tone::ALL { + assert_eq!(Tone::parse(name), Some(tone)); + assert_eq!(tone.name(), name); + } + assert_eq!(Tone::parse("lab"), None); + assert_eq!(Tone::default(), Tone::LabStandard); + assert_eq!(Params::default().tone, Tone::LabStandard); + } + + #[test] + fn linear_profile_is_identity_and_every_profile_is_monotonic_and_pinned() { + let c = curve(linear()); + assert!(c.is_identity()); + for x in [0.0, 0.25, 0.5, 0.75, 1.0] { + assert!((c.apply(x) - x).abs() < 1e-6); + } + for (tone, name) in Tone::ALL { + let c = curve(Params { tone, ..Params::default() }); + let mut last = -1.0; + for i in 0..=200 { + let y = c.apply(i as f32 / 200.0); + assert!(y >= last - 1e-5, "{name} not monotonic at {i}: {y} < {last}"); + last = y; + } + let lo = c.apply(0.0); + let hi = c.apply(1.0); + assert!((0.0..=0.07).contains(&lo) && (0.96..=1.0).contains(&hi), "{name}: ends {lo} {hi}"); + if tone != Tone::Linear && tone != Tone::LinearDeep { + assert!(!c.is_identity(), "{name}"); + } + } + } + + #[test] + fn lab_profiles_order_by_steepness_on_each_side() { + let at = |tone, x: f32| curve(Params { tone, ..Params::default() }).apply(x); + assert!(at(Tone::LabHard, 0.25) < at(Tone::LabStandard, 0.25) && at(Tone::LabStandard, 0.25) < at(Tone::LabSoft, 0.25)); + assert!(at(Tone::LabHard, 0.75) > at(Tone::LabStandard, 0.75) && at(Tone::LabStandard, 0.75) > at(Tone::LabSoft, 0.75)); + // Highlight-side variants leave the shadows where Standard has them, and mid-grey stays put. + assert!((at(Tone::LabHighlightHard, 0.15) - at(Tone::LabStandard, 0.15)).abs() < 1e-5); + assert!((at(Tone::LabHighlightSoft, 0.5) - 0.5).abs() < 1e-5 && (at(Tone::LabShadowHard, 0.5) - 0.5).abs() < 1e-5); + assert!(at(Tone::LabHighlightHard, 0.85) > at(Tone::LabStandard, 0.85)); + assert!(at(Tone::LabHighlightSoft, 0.85) < at(Tone::LabStandard, 0.85)); + assert!(at(Tone::LabShadowHard, 0.15) < at(Tone::LabStandard, 0.15)); + assert!(at(Tone::LabShadowSoft, 0.15) > at(Tone::LabStandard, 0.15)); + // Cinematic: flatter shadows than Lab Standard, a lifted toe, separated highlights. + assert!(at(Tone::Cinematic, 0.0) > 0.0 && at(Tone::Cinematic, 0.2) > at(Tone::LabStandard, 0.2)); + assert!(Tone::LinearDeep.gamma() > 1.0 && Tone::Cinematic.gamma() < 1.0 && Tone::LabStandard.gamma() == 1.0); + assert!(at(Tone::LinearFlat, 0.0) > 0.0 && at(Tone::LinearFlat, 1.0) < 1.0); + } + + #[test] + fn contrast_slider_adds_and_removes_steepness() { + let more = curve(Params { contrast: 30.0, ..Params::default() }).apply(0.25); + let standard = curve(Params::default()).apply(0.25); + let less = curve(Params { contrast: -50.0, ..linear() }).apply(0.25); + assert!(more < standard, "{more} {standard}"); + assert!(less > 0.25, "negative contrast on a straight line flattens: {less}"); + assert!(curve(Params { contrast: -50.0, ..linear() }).apply(0.0) > 0.0); + } + + #[test] + fn lights_darks_fade_glow_and_soft_ends_act_where_they_should() { + let lin = linear(); + let darks = curve(Params { darks: 50.0, ..lin }); + assert!(darks.apply(0.3) > 0.3 && (darks.apply(0.3) - 0.3) > (darks.apply(0.9) - 0.9), "darks lift the low end most"); + let lights = curve(Params { lights: -50.0, ..lin }); + assert!(lights.apply(0.7) < 0.7 && (0.7 - lights.apply(0.7)) > (0.1 - lights.apply(0.1)), "lights act on the high end"); + let fade = curve(Params { fade: 100.0, ..lin }); + assert!((fade.apply(0.0) - 0.2).abs() < 1e-6 && (fade.apply(1.0) - 1.0).abs() < 1e-6); + let unfade = curve(Params { fade: -100.0, ..lin }); + assert!(unfade.apply(0.1) > 0.1 && unfade.apply(0.0) == 0.0 && (unfade.apply(0.5) - 0.5).abs() < 1e-6, "negative fade steepens the shadows"); + let glow = curve(Params { glow: 100.0, ..lin }); + assert!(glow.apply(0.75) > 0.75 && (glow.apply(1.0) - 1.0).abs() < 1e-6 && (glow.apply(0.5) - 0.5).abs() < 1e-6); + assert!(glow.apply(0.99) - glow.apply(0.9) < 0.09, "the shoulder compresses the top"); + let unglow = curve(Params { glow: -100.0, ..lin }); + assert!(unglow.apply(0.75) < 0.75 && (unglow.apply(1.0) - 1.0).abs() < 1e-6, "negative glow expands the highlights"); + let soft = curve(Params { soft_highs: 100.0, soft_lows: 100.0, ..lin }); + assert!((soft.apply(0.5) - 0.5).abs() < 1e-6 && soft.apply(0.85) > 0.85 && soft.apply(0.15) < 0.15); + assert!(soft.apply(0.02) < 0.02 * 0.6 && (1.0 - soft.apply(0.98)) < 0.02 * 0.6, "flatter at both ends"); + assert!(curve(Params { fade: f32::NAN, glow: f32::INFINITY, darks: -1e9, ..lin }).apply(f32::NAN).is_finite()); + } +} diff --git a/crates/geocode/src/lib.rs b/crates/geocode/src/lib.rs index de0bea5c90..9346e13089 100644 --- a/crates/geocode/src/lib.rs +++ b/crates/geocode/src/lib.rs @@ -102,6 +102,24 @@ pub struct GeoNames { countries: HashMap, } +/// Most bytes of one dump file read into memory (the extracted `cities*.txt` is far below this). +const MAX_FILE_BYTES: u64 = 256 << 20; + +/// A regular file's text, at most [`MAX_FILE_BYTES`] of it (the opened file is checked, never its pathname). +fn read_text(path: &Path) -> std::io::Result { + use std::io::Read; + let file = std::fs::File::open(path)?; + if !file.metadata()?.is_file() { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a regular file")); + } + let mut bytes = Vec::new(); + file.take(MAX_FILE_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_FILE_BYTES { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "file too large")); + } + Ok(String::from_utf8_lossy(&bytes).into_owned()) +} + fn cell(p: LatLon) -> (i32, i32) { // valid positions only: |lat| ≤ 90, |lon| ≤ 180, so the casts are in range // longitude 180 is the same meridian as -180: key it as column -180, the wrap `reverse` probes @@ -121,7 +139,8 @@ impl GeoNames { if g.cities.len() >= MAX_PLACES { break; } - let f: Vec<&str> = line.split('\t').collect(); + // only the first 11 columns are used: a line of tabs must not build a field for each + let f: Vec<&str> = line.split('\t').take(11).collect(); // columns: 1 name, 4 latitude, 5 longitude, 8 country code, 10 admin1 code let (Some(name), Some(lat), Some(lon), Some(cc)) = (f.get(1), f.get(4), f.get(5), f.get(8)) else { continue }; let (Ok(lat), Ok(lon)) = (lat.trim().parse::(), lon.trim().parse::()) else { continue }; @@ -152,7 +171,7 @@ impl GeoNames { /// Load from a folder holding [`GEONAMES_FILES`] (the last two are optional: without them /// states stay blank and countries are ISO codes). pub fn load(dir: &Path) -> Result { - let read = |n: &str| std::fs::read(dir.join(n)).map(|b| String::from_utf8_lossy(&b).into_owned()); + let read = |n: &str| read_text(&dir.join(n)); let cities = read(GEONAMES_FILES[0]).map_err(|e| GeocodeError::Missing(format!("the place names aren't downloaded ({e})")))?; let g = GeoNames::parse(&cities, read(GEONAMES_FILES[1]).ok().as_deref(), read(GEONAMES_FILES[2]).ok().as_deref()); if g.is_empty() { @@ -262,6 +281,14 @@ mod tests { } } + #[test] + fn a_line_of_tabs_and_a_non_regular_file_are_handled() { + assert!(GeoNames::parse(&"\t".repeat(100_000), None, None).is_empty()); + assert!(read_text(&std::env::temp_dir()).is_err()); + #[cfg(unix)] + assert!(read_text(Path::new("/dev/zero")).is_err()); + } + #[test] fn high_latitude_cities_two_cells_away() { let city = |lat: f64, lon: f64| GeoNames::parse(&format!("1\tX\tX\t\t{lat}\t{lon}\tP\tP\tNO\t\t\n"), None, None); diff --git a/crates/geocode/src/unzip.rs b/crates/geocode/src/unzip.rs index d422297a7f..49d86bafde 100644 --- a/crates/geocode/src/unzip.rs +++ b/crates/geocode/src/unzip.rs @@ -62,7 +62,7 @@ pub fn extract(zip: &[u8], name: &str, max: usize) -> Result, GeocodeErr 0 if data.len() <= max => Ok(data.to_vec()), 0 => Err(GeocodeError::Invalid(format!("{name} is larger than {max} bytes"))), 8 => { - let decoded = miniz_oxide::inflate::decompress_to_vec_with_limit(data, max).map_err(|e| bad(&format!("deflate: {e:?}")))?; + let decoded = miniz_oxide::inflate::decompress_to_vec_with_limit(data, max).map_err(|e| bad(&format!("deflate: {:?}", e.status)))?; if decoded.len() != usize_ { return Err(bad("uncompressed size")); } diff --git a/crates/gpu/src/backend.rs b/crates/gpu/src/backend.rs index d970003e73..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; @@ -427,6 +688,8 @@ mod tests { let dir = std::env::temp_dir().join(format!("lc-gpu-marker-{}", std::process::id())); let m = dir.join("gpu-init.marker"); let _ = std::fs::remove_dir_all(&dir); + // exclusive: a directory planted at this predictable name fails the test instead of receiving the marker + std::fs::create_dir(&dir).unwrap(); // a local scope counter: other tests create real devices through the process-wide one let active = Mutex::new(0); let seen = with_marker_on(Some(m.clone()), &active, "device creation", || m.exists()); @@ -447,6 +710,8 @@ mod tests { let dir = std::env::temp_dir().join(format!("lc-gpu-global-{}", std::process::id())); let m = dir.join("gpu-init.marker"); let _ = std::fs::remove_dir_all(&dir); + // exclusive: a directory planted at this predictable name fails the test instead of receiving the marker + std::fs::create_dir(&dir).unwrap(); set_init_marker(Some(m.clone())); let seen = with_init_marker(Backends::DX12, || m.exists()); set_init_marker(None); @@ -501,6 +766,8 @@ mod tests { let dir = std::env::temp_dir().join(format!("lc-gpu-scopes-{}", std::process::id())); let m = dir.join("gpu-init.marker"); let _ = std::fs::remove_dir_all(&dir); + // exclusive: a directory planted at this predictable name fails the test instead of receiving the marker + std::fs::create_dir(&dir).unwrap(); let active = Mutex::new(0); arm(&m, &active, "device creation"); assert!(read_init_marker(&m).unwrap().contains("device creation")); @@ -524,6 +791,8 @@ mod tests { let dir = std::env::temp_dir().join(format!("lc-gpu-panic-{}", std::process::id())); let m = dir.join("gpu-init.marker"); let _ = std::fs::remove_dir_all(&dir); + // exclusive: a directory planted at this predictable name fails the test instead of receiving the marker + std::fs::create_dir(&dir).unwrap(); let active = Mutex::new(0); let r = std::panic::catch_unwind(|| with_marker_on(Some(m.clone()), &active, "kernel compilation", || panic!("compile"))); assert!(r.is_err()); diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index ea93008fed..2735116e39 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -30,7 +30,12 @@ const MODULES: &[Module] = &[ Module { src: include_str!("wgsl/blur.wgsl"), bindings: &[("src", false, "f32"), ("dst", true, "f32")], - entries: &["box_h", "box_v", "median_h", "median_v"], + entries: &["box_h", "box_v", "minmax", "median_h", "median_v"], + }, + Module { + src: include_str!("wgsl/gauss.wgsl"), + bindings: &[("src", false, "f32"), ("taps", false, "f32"), ("dst", true, "f32")], + entries: &["gauss_h", "gauss_v"], }, Module { src: include_str!("wgsl/resize.wgsl"), @@ -55,13 +60,26 @@ const MODULES: &[Module] = &[ "xguided_pre", "xguided_ab", "xguided_apply", + "fringe_lab", + "fringe_apply", ], }, + Module { + src: include_str!("wgsl/spot.wgsl"), + bindings: &[("img", true, "f32"), ("pts", false, "f32"), ("al", true, "f32"), ("sp", true, "f32"), ("df", true, "f32"), ("wt", true, "f32")], + entries: &["spot_prep", "spot_apply", "spot_score"], + }, + Module { src: include_str!("wgsl/hist.wgsl"), bindings: &[("px", false, "u32"), ("bins", true, "atomic")], entries: &["histogram"] }, Module { src: include_str!("wgsl/mask.wgsl"), bindings: &[("img", false, "f32"), ("log_l", false, "f32"), ("aux", false, "f32"), ("c", true, "f32"), ("alpha", true, "f32")], entries: &["shape", "combine", "finalize"], }, + Module { + src: include_str!("wgsl/present.wgsl"), + bindings: &[("px", false, "u32"), ("dst", true, "u32"), ("count", true, "atomic")], + entries: &["unwritten", "pad_rows"], + }, Module { src: include_str!("wgsl/geom.wgsl"), bindings: &[("src", false, "f32"), ("dst", true, "f32"), ("coverage", false, "u32")], @@ -337,6 +355,8 @@ pub struct Gpu { free: std::sync::Mutex>, /// Largest storage buffer the device accepts (bytes). pub max_buffer: u64, + /// The device is the window's (eframe's): renders can hand it textures to draw directly. + pub window: bool, } /// WGSL constants shared by every module (generated from the CPU pipeline's values). @@ -345,7 +365,15 @@ fn constants() -> String { use lightcraft_pipeline::tone::{CHROMA_N, LUT_MAX_EV, LUT_MIN_EV, LUT_N}; let mut s = String::new(); let [to_lms, from_lms, to_lab, from_lab] = lightcraft_color::perceptual::oklab_matrices(); - for (name, m) in [("OK_TO_LMS", to_lms), ("OK_FROM_LMS", from_lms), ("OK_TO_LAB", to_lab), ("OK_FROM_LAB", from_lab)] { + let (to_pro, from_pro) = lightcraft_pipeline::light_v3::prophoto_matrices(); + for (name, m) in [ + ("OK_TO_LMS", to_lms), + ("OK_FROM_LMS", from_lms), + ("OK_TO_LAB", to_lab), + ("OK_FROM_LAB", from_lab), + ("PRO_FROM_2020", to_pro), + ("PRO_TO_2020", from_pro), + ] { let rows: Vec = m.iter().map(|r| format!("vec3({:?}, {:?}, {:?})", r[0], r[1], r[2])).collect(); s += &format!("const {name} = array, 3>({});\n", rows.join(", ")); } @@ -360,10 +388,18 @@ fn constants() -> String { crate::params::CURVE_N ); s += &format!("const POINT_WORDS: u32 = {}u;\n", lightcraft_pipeline::colorops::POINT_WORDS); + let y = lightcraft_pipeline::light_v3::PRO_Y; + s += &format!("const PRO_Y = vec3({:?}, {:?}, {:?});\nconst LIGHT_N: u32 = {}u;\n", y[0], y[1], y[2], lightcraft_pipeline::light_v3::LUT_N); s += &format!("const EYE_WORDS: u32 = {}u;\n", lightcraft_pipeline::redeye::EYE_WORDS); use lightcraft_pipeline::masks::{AUTO_TOL_CHROMA, AUTO_TOL_EV}; s += &format!("const AUTO_TOL_EV: f32 = {AUTO_TOL_EV:?};\nconst AUTO_TOL_CHROMA: f32 = {AUTO_TOL_CHROMA:?};\n"); s += &format!("const SHADOW_TINT_K: f32 = {:?};\n", lightcraft_pipeline::colorops::SHADOW_TINT); + s += &format!("const GAMUT_WARN: f32 = {:?};\n", lightcraft_pipeline::finish::GAMUT_WARN); + s += &format!("const NCAND: u32 = {}u;\n", lightcraft_pipeline::spots::candidates(1.0).len()); + use lightcraft_pipeline::output::{PROOF_DEST_WARNING, PROOF_DISPLAY_WARNING}; + for (name, c) in [("PROOF_DEST", PROOF_DEST_WARNING), ("PROOF_DISP", PROOF_DISPLAY_WARNING)] { + s += &format!("const {name}_R: f32 = {:?};\nconst {name}_G: f32 = {:?};\nconst {name}_B: f32 = {:?};\n", c[0], c[1], c[2]); + } for (i, h) in GRAIN_HASH.iter().enumerate() { s += &format!("const GRAIN_H{i}: u32 = {h}u;\n"); } @@ -397,10 +433,8 @@ impl Gpu { // no indirect-call validation pipeline: Intel Metal fails to compile it (#250) desc.flags = crate::backend::instance_flags_from_env(desc.flags); let instance = wgpu::Instance::new(desc); - let adapter = pollster::block_on( - instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }), - ) - .map_err(|e| format!("no GPU adapter among {backends:?} ({e})"))?; + // the card LIGHTCRAFT_GPU_ADAPTER names, else the high-performance one + let adapter = crate::backend::pick_adapter(&instance, backends)?; let info = adapter.get_info(); if refuse_adapter(info.device_type, software_allowed()) { log::info!("gpu: only a software adapter ({}), using the CPU pipeline", info.name); @@ -414,17 +448,46 @@ impl Gpu { log::info!("gpu: {} has too few storage buffers per stage", info.name); return Err(format!("{} has too few storage buffers per shader stage ({} < 10)", info.name, limits.max_storage_buffers_per_shader_stage)); } - if let Some((binding, buffer)) = limits_override() { - limits.max_storage_buffer_binding_size = limits.max_storage_buffer_binding_size.min(binding); - limits.max_buffer_size = limits.max_buffer_size.min(buffer); - log::info!("gpu: LIGHTCRAFT_GPU_LIMITS: storage bindings ≤ {} MiB, buffers ≤ {} MiB", binding >> 20, buffer >> 20); - } + limits = capped(limits, limits_override()); let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("lightcraft"), required_limits: limits.clone(), ..Default::default() })) .map_err(|e| format!("{}: device creation failed ({e})", info.name))?; + Gpu::with_device(device, queue, info, limits, false) + } + + /// The renderer on the window's device ([`crate::adopt_window_device`]), within its limits + /// lowered by `LIGHTCRAFT_GPU_LIMITS` as a device of its own would be. + pub fn adopt(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo) -> Result { + Gpu::adopt_capped(device, queue, info, limits_override()) + } + + /// [`Gpu::adopt`] with the limits override given (`LIGHTCRAFT_GPU_LIMITS`, parsed). + fn adopt_capped(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo, cap: Option<(u64, u64)>) -> Result { + let limits = capped(device.limits(), cap); + Gpu::with_device(device, queue, info, limits, true) + } + + /// The renderer on an existing device: the window's (`window`, see [`crate::adopt_window_device`]) + /// or one [`Gpu::new`] created with `limits`. Builds the kernels (~0.4–2 s: not on the UI thread). + pub fn with_device(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo, limits: wgpu::Limits, window: bool) -> Result { + if limits.max_storage_buffers_per_shader_stage < 10 { + return Err(format!("{} has too few storage buffers per shader stage ({} < 10)", info.name, limits.max_storage_buffers_per_shader_stage)); + } + let started = std::time::Instant::now(); + let kernels = match build_kernels(&device) { + Ok(kernels) => kernels, + Err(e) => { + log::error!("gpu: kernels failed to build on {}: {e}", info.name); + return Err(format!("{}: kernels failed to build ({e})", info.name)); + } + }; + let build_ms = started.elapsed().as_millis(); + // Only a device the renderer keeps gets these: a window's device declined above keeps the + // window's own handler, so a later error of the window's can't stop the renderer's device + // (review of PR #1065). // Errors outside a render's error scopes (see `ErrorScopes`): log, and stop using the GPU. device.on_uncaptured_error(std::sync::Arc::new(|e| { log::error!("gpu: {e}"); @@ -437,15 +500,6 @@ impl Gpu { log::error!("gpu: device lost ({reason:?}): {msg}"); crate::mark_broken(&format!("device lost ({reason:?}): {msg}")); }); - let started = std::time::Instant::now(); - let kernels = match build_kernels(&device) { - Ok(kernels) => kernels, - Err(e) => { - log::error!("gpu: kernels failed to build on {}: {e}", info.name); - return Err(format!("{}: kernels failed to build ({e})", info.name)); - } - }; - let build_ms = started.elapsed().as_millis(); let dummy = device.create_buffer(&wgpu::BufferDescriptor { label: Some("dummy"), size: 16, @@ -453,8 +507,15 @@ impl Gpu { mapped_at_creation: false, }); let max_buffer = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size); - log::info!("gpu: {} ({:?}), {} kernels in {build_ms} ms, buffers ≤ {} MiB", info.name, info.backend, kernels.len(), max_buffer >> 20); - Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer }) + log::info!( + "gpu: {} ({:?}), {} kernels in {build_ms} ms, buffers ≤ {} MiB{}", + info.name, + info.backend, + kernels.len(), + max_buffer >> 20, + if window { ", the window's device" } else { "" } + ); + Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer, window }) } /// A buffer of `len` 32-bit values with undefined contents (a recycled one when possible). @@ -542,24 +603,7 @@ impl Gpu { /// second panic while a failed render unwinds aborts the process. A lost device is not polled /// again; a poll that panics counts as one and stops the GPU. pub(crate) fn poll(&self, t: wgpu::PollType) -> Result { - if DEVICE_LOST.load(Ordering::Relaxed) { - return Err("the device is lost".into()); - } - let polled = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - #[cfg(test)] - if SIMULATED_LOST_POLL.with(std::cell::Cell::get) { - panic!("Error in Device::poll: Validation Error\n\nCaused by:\n Parent device is lost (simulated)"); - } - self.device.poll(t) - })); - match polled { - Ok(r) => r.map_err(|e| e.to_string()), - Err(_) => { - DEVICE_LOST.store(true, Ordering::Relaxed); - crate::mark_broken("device lost: Device::poll failed"); - Err("the device is lost (Device::poll failed)".into()) - } - } + poll_device(&self.device, t) } /// Upload 32-bit values. @@ -771,6 +815,108 @@ fn limits_override() -> Option<(u64, u64)> { parse_limits(&std::env::var("LIGHTCRAFT_GPU_LIMITS").ok()?) } +/// `limits` lowered to `cap` ([`limits_override`]: storage binding bytes, buffer bytes). +fn capped(mut limits: wgpu::Limits, cap: Option<(u64, u64)>) -> wgpu::Limits { + if let Some((binding, buffer)) = cap { + limits.max_storage_buffer_binding_size = limits.max_storage_buffer_binding_size.min(binding); + limits.max_buffer_size = limits.max_buffer_size.min(buffer); + log::info!("gpu: LIGHTCRAFT_GPU_LIMITS: storage bindings ≤ {} MiB, buffers ≤ {} MiB", binding >> 20, buffer >> 20); + } + limits +} + +/// `device.poll` that never panics: see [`Gpu::poll`]. [`read_texture`] uses it too: its device +/// (the window's, when adopted) shares the device-lost flag. +fn poll_device(device: &wgpu::Device, t: wgpu::PollType) -> Result { + if DEVICE_LOST.load(Ordering::Relaxed) { + return Err("the device is lost".into()); + } + let polled = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + #[cfg(test)] + if SIMULATED_LOST_POLL.with(std::cell::Cell::get) { + panic!("Error in Device::poll: Validation Error\n\nCaused by:\n Parent device is lost (simulated)"); + } + device.poll(t) + })); + match polled { + Ok(r) => r.map_err(|e| e.to_string()), + Err(_) => { + DEVICE_LOST.store(true, Ordering::Relaxed); + crate::mark_broken("device lost: Device::poll failed"); + Err("the device is lost (Device::poll failed)".into()) + } + } +} + +/// See [`crate::read_texture`]. +pub(crate) fn read_texture( + device: &wgpu::Device, + queue: &wgpu::Queue, + texture: &wgpu::Texture, + width: usize, + height: usize, +) -> Result { + if DEVICE_LOST.load(Ordering::Relaxed) { + return Err("the device is lost".into()); + } + if width == 0 || height == 0 { + return Err("an empty texture".into()); + } + let (Ok(w32), Ok(h32)) = (u32::try_from(width), u32::try_from(height)) else { return Err("texture too large".into()) }; + if w32 > texture.width() || h32 > texture.height() || texture.format() != wgpu::TextureFormat::Rgba8Unorm { + return Err("not an 8-bit view texture of that size".into()); + } + // texture copies take rows of a multiple of 256 bytes + let stride = width.checked_mul(4).ok_or("texture too large")?.next_multiple_of(256); + let size = stride.checked_mul(height).ok_or("texture too large")?; + let (Ok(stride32), Ok(size64)) = (u32::try_from(stride), u64::try_from(size)) else { return Err("texture too large".into()) }; + let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); + let staging = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("view readback"), + size: size64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("view readback") }); + enc.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyBufferInfo { + buffer: &staging, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(stride32), rows_per_image: Some(h32) }, + }, + wgpu::Extent3d { width: w32, height: h32, depth_or_array_layers: 1 }, + ); + queue.submit([enc.finish()]); + if let Some(e) = pollster::block_on(scope.pop()) { + return Err(format!("texture copy failed: {e}")); + } + let slice = staging.slice(..); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |r| { + let _ = tx.send(r); + }); + // (the render path's wait: queued work ahead of the copy can take that long too) + let wait = READBACK_TIMEOUT; + poll_device(device, wgpu::PollType::Wait { submission_index: None, timeout: Some(wait) })?; + match rx.recv_timeout(wait) { + Ok(Ok(())) => {} + Ok(Err(e)) => return Err(format!("{e}")), + Err(e) => return Err(format!("map callback: {e}")), + } + let bytes = slice.get_mapped_range().map_err(|e| format!("{e:?}"))?; + let mut data = Vec::with_capacity(width * height); + for row in bytes.chunks(stride).take(height) { + let row = row.get(..width * 4).ok_or("short readback row")?; + data.extend(row.as_chunks::<4>().0.iter().copied()); + } + drop(bytes); + staging.unmap(); + if data.len() != width * height { + return Err("incomplete readback".into()); + } + Ok(lightcraft_raster::Rgba8 { width, height, data }) +} + fn parse_limits(v: &str) -> Option<(u64, u64)> { let v = v.trim().to_ascii_lowercase(); match v.as_str() { @@ -927,6 +1073,54 @@ mod tests { assert_eq!(super::parse_limits("17592186044416"), None); } + /// `LIGHTCRAFT_GPU_LIMITS` caps the window's device as it caps a device of its own (review of + /// PR #1065: adopting the window's device skipped it, so a 1024 × 1024 RGB float buffer — 12 MiB — + /// was taken under an 8 MiB cap). + #[test] + fn the_limits_override_caps_an_adopted_device() { + let big = wgpu::Limits { max_storage_buffer_binding_size: 1 << 30, max_buffer_size: 1 << 31, ..wgpu::Limits::default() }; + let c = super::capped(big.clone(), super::parse_limits("8")); + assert_eq!((c.max_storage_buffer_binding_size, c.max_buffer_size), (8 << 20, 16 << 20)); + let c = super::capped(big.clone(), None); + assert_eq!((c.max_storage_buffer_binding_size, c.max_buffer_size), (1 << 30, 1 << 31)); + + let _lock = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let Some((device, queue, info)) = test_device() else { + lightcraft_testkit::skip!(Gpu, "no GPU adapter"); + return; + }; + let full = device.limits().max_storage_buffer_binding_size.min(device.limits().max_buffer_size); + if full <= 12 << 20 { + lightcraft_testkit::skip!(Gpu, "the adapter's buffers are already ≤ 12 MiB"); + return; + } + let g = super::Gpu::adopt_capped(device, queue, info, super::parse_limits("8")).expect("kernels build"); + assert!(g.window); + assert_eq!(g.limit(), 8 << 20, "the cap applies to the adopted device"); + assert!(1024 * 1024 * 3 * 4 > g.limit(), "a 12 MiB buffer is over it"); + } + + /// A device as eframe makes the window's (the adapter's own limits). + fn test_device() -> Option<(wgpu::Device, wgpu::Queue, wgpu::AdapterInfo)> { + let backends = crate::backend::compute_backends()?; + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = backends; + desc.backend_options = crate::backend::backend_options(); + let instance = wgpu::Instance::new(desc); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; + let info = adapter.get_info(); + if info.device_type == wgpu::DeviceType::Cpu { + return None; + } + let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + label: Some("test window"), + required_limits: adapter.limits(), + ..Default::default() + })) + .ok()?; + Some((device, queue, info)) + } + /// Issue #2936: the kernels are built on several threads; every entry point of every module has one. #[test] fn every_entry_point_has_a_kernel() { @@ -1009,6 +1203,42 @@ mod tests { } } + /// Review of PR #1065: a view readback (headless screenshot) whose poll finds the device lost + /// returns an error instead of panicking, stops the GPU, and doesn't poll the device again. + #[test] + fn a_view_readback_on_a_lost_device_fails_without_a_panic() { + if run_child("lost_readback_child").is_none() { + lightcraft_testkit::skip!(Gpu, "no GPU device"); + } + } + + #[test] + #[ignore = "run in its own process by a_view_readback_on_a_lost_device_fails_without_a_panic"] + fn lost_readback_child() { + let Some(g) = crate::device() else { + println!("CHILD: no GPU"); + return; + }; + let texture = g.device.create_texture(&wgpu::TextureDescriptor { + label: Some("view"), + size: wgpu::Extent3d { width: 8, height: 8, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }); + assert!(super::read_texture(&g.device, &g.queue, &texture, 8, 8).is_ok(), "a live device reads back"); + super::SIMULATED_LOST_POLL.with(|c| c.set(true)); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| super::read_texture(&g.device, &g.queue, &texture, 8, 8))); + assert!(matches!(r, Ok(Err(_))), "the lost device fails the readback without a panic"); + assert!(!crate::available(), "the GPU is not used again"); + super::SIMULATED_LOST_POLL.with(|c| c.set(false)); + assert!(super::read_texture(&g.device, &g.queue, &texture, 8, 8).is_err(), "a lost device is not polled again"); + println!("CHILD: survived"); + } + /// A Metal device really lost (its command buffers exhausted) is never polled again. #[test] fn a_really_lost_device_is_not_polled_again() { diff --git a/crates/gpu/src/faces.rs b/crates/gpu/src/faces.rs index 9192677867..e85b1bd98b 100644 --- a/crates/gpu/src/faces.rs +++ b/crates/gpu/src/faces.rs @@ -107,20 +107,7 @@ fn make_device(backends: wgpu::Backends) -> Result { desc.backend_options = crate::backend::backend_options(); desc.flags = crate::backend::instance_flags_from_env(desc.flags); let instance = wgpu::Instance::new(desc); - let wanted = std::env::var("LIGHTCRAFT_GPU_ADAPTER").ok().map(|s| s.trim().to_lowercase()).filter(|s| !s.is_empty()); - let adapter = match &wanted { - Some(w) => pollster::block_on(instance.enumerate_adapters(backends)) - .into_iter() - .find(|a| { - let i = a.get_info(); - i.device_type != wgpu::DeviceType::Cpu && i.name.to_lowercase().contains(w.as_str()) - }) - .ok_or_else(|| format!("no GPU adapter named like `{w}`"))?, - None => pollster::block_on( - instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }), - ) - .map_err(|e| format!("no GPU adapter among {backends:?} ({e})"))?, - }; + let adapter = crate::backend::pick_adapter(&instance, backends)?; let info = adapter.get_info(); if info.device_type == wgpu::DeviceType::Cpu { return Err(format!("software adapter ({}) skipped: the CPU is faster", info.name)); diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 51a8aa45bc..8863b45a04 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -45,7 +45,14 @@ mod params; mod render; #[cfg(not(target_arch = "wasm32"))] -pub use render::GpuStages; +pub use render::{DisplayFrame, GpuStages, Output}; +/// The wgpu the renderer is built on (the same crate eframe uses: hosts hand over its device). +#[cfg(not(target_arch = "wasm32"))] +pub use wgpu; + +/// Unit tests that create the device or swap the crash sentinel's path take turns. +#[cfg(test)] +pub(crate) static DEVICE_TEST_LOCK: Mutex<()> = Mutex::new(()); static ENABLED: AtomicBool = AtomicBool::new(true); /// Set when a GPU render failed: the process stays on the CPU from then on. @@ -277,6 +284,21 @@ fn env_disabled() -> bool { #[cfg(not(target_arch = "wasm32"))] static GPU: std::sync::OnceLock> = std::sync::OnceLock::new(); +/// Set while [`adopt_window_device`] is about to run or running: [`device`] and [`warm_up`] then +/// don't create a device of their own (review of PR #1065: the settings' warm-up raced the +/// adoption thread and could win, so the window's device went unused). +#[cfg(not(target_arch = "wasm32"))] +static WINDOW_PENDING: AtomicBool = AtomicBool::new(false); + +/// Announce (before spawning it) that [`adopt_window_device`] will run, or withdraw that when it +/// can't (`false`). Until it has finished, renders take the CPU path and [`warm_up`] does nothing. +pub fn set_window_device_pending(pending: bool) { + #[cfg(not(target_arch = "wasm32"))] + WINDOW_PENDING.store(pending, Ordering::Release); + #[cfg(target_arch = "wasm32")] + let _ = pending; +} + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn device() -> Option<&'static ctx::Gpu> { // turned off (preference, environment): don't even load the driver (issue #136) @@ -286,6 +308,11 @@ pub(crate) fn device() -> Option<&'static ctx::Gpu> { if let Some(g) = GPU.get() { return g.as_ref().ok(); } + // the window's device is being adopted: render on the CPU until it is, rather than create a + // device of our own first (which would leave the window's unused) + if WINDOW_PENDING.load(Ordering::Acquire) { + return None; + } // creating the device is a long call into the driver: not once the process is ending let _work = exit::enter()?; GPU.get_or_init(|| { @@ -313,7 +340,7 @@ pub(crate) fn existing_device() -> Option<&'static ctx::Gpu> { /// while GPU rendering is turned off. Repeated calls start one thread at most. pub fn warm_up() { #[cfg(not(target_arch = "wasm32"))] - if !env_disabled() && ENABLED.load(Ordering::SeqCst) && GPU.get().is_none() { + if !env_disabled() && ENABLED.load(Ordering::SeqCst) && GPU.get().is_none() && !WINDOW_PENDING.load(Ordering::Acquire) { static STARTED: AtomicBool = AtomicBool::new(false); if STARTED.swap(true, Ordering::SeqCst) { return; @@ -328,8 +355,9 @@ pub fn warm_up() { // again. Released first, then the preference read again: a call made while this // thread still held the flag (turned back on meanwhile) returned without starting // one, so this thread tries again itself rather than leave "starting" for good. + // The window's device being adopted meanwhile: that creates the device, not this. STARTED.store(false, Ordering::SeqCst); - if !ENABLED.load(Ordering::SeqCst) || STARTED.swap(true, Ordering::SeqCst) { + if WINDOW_PENDING.load(Ordering::Acquire) || !ENABLED.load(Ordering::SeqCst) || STARTED.swap(true, Ordering::SeqCst) { break; } } @@ -492,6 +520,114 @@ pub fn try_render( stages: Option<&StageCache>, ) -> Result { #[cfg(not(target_arch = "wasm32"))] + { + match run(src, info, s, req, stages, false)? { + render::Output::Image(r) => Ok(r), + // (not asked for) + render::Output::Display { .. } => Err(Fallback::NotTried), + } + } + #[cfg(target_arch = "wasm32")] + { + let _ = (src, info, s, req, stages); + Err(Fallback::NotTried) + } +} + +/// [`render`] for the window: when the device is the window's ([`adopt_window_device`]) and the +/// render allows it, the result stays on the device as a texture to draw ([`Output::Display`]); +/// otherwise pixels as from [`render`]. `None`: render on the CPU instead. +#[cfg(not(target_arch = "wasm32"))] +pub fn render_display(src: &Arc, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest, stages: Option<&StageCache>) -> Option { + run(src, info, s, req, stages, true).ok() +} + +/// Whether renders run on the window's device (and so can be handed over as textures). +pub fn on_window_device() -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + existing_device().is_some_and(|g| g.window) + } + #[cfg(target_arch = "wasm32")] + { + false + } +} + +/// Render on the window's device (eframe's) instead of a device of its own, so finished views can +/// be drawn without reading them back ([`render_display`]). Builds the kernels on it (~0.4–2 s: +/// call it off the UI thread), in place of [`warm_up`]. When that fails, or the window's device +/// doesn't suit (a software adapter, too few storage buffers), a device of its own is created as +/// before; `Err` says why the window's wasn't used. Does nothing once a device exists. +#[cfg(not(target_arch = "wasm32"))] +pub fn adopt_window_device(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo) -> Result<(), String> { + /// Whatever the outcome, renders may create or use a device again afterwards. + struct Done; + impl Drop for Done { + fn drop(&mut self) { + WINDOW_PENDING.store(false, Ordering::Release); + } + } + let _done = Done; + if env_disabled() || !ENABLED.load(Ordering::Relaxed) { + return Err("GPU rendering is off".into()); + } + let _work = exit::enter().ok_or("LightCraft is closing")?; + let mut declined = None; + let g = GPU.get_or_init(|| { + let adopted = if info.device_type == wgpu::DeviceType::Cpu { + Err(format!("software adapter ({}) skipped: the CPU pipeline is faster", info.name)) + } else if !backend::may_adopt_window_device(&info.name) { + // (the photos render on the card LIGHTCRAFT_GPU_ADAPTER names, on a device of its own) + Err(format!("LIGHTCRAFT_GPU_ADAPTER names another card than the window's ({})", info.name)) + } else { + // (building the kernels is a long call into the driver: the crash sentinel covers it) + backend::with_init_marker(wgpu::Backends::from(info.backend), || { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ctx::Gpu::adopt(device, queue, info))) + .unwrap_or_else(|_| Err("kernel setup panicked".into())) + }) + }; + adopted.or_else(|e| { + log::warn!("gpu: not rendering on the window's device ({e}); creating one"); + declined = Some(e); + let Some(backends) = backend::compute_backends() else { return Err("disabled by LIGHTCRAFT_GPU_BACKEND=off".into()) }; + backend::with_init_marker(backends, || { + std::panic::catch_unwind(|| ctx::Gpu::new(backends)).unwrap_or_else(|_| Err("device creation panicked".into())) + }) + }) + }); + match (g, declined) { + (Ok(g), None) if g.window => Ok(()), + (_, Some(e)) => Err(e), + (Ok(_), None) => Err("a device of its own was created first".into()), + (Err(e), None) => Err(e.clone()), + } +} + +/// The pixels of a texture on `device` (a [`DisplayFrame`]'s, or any `Rgba8Unorm` texture with +/// `COPY_SRC`): for a headless screenshot of a view drawn straight from the GPU, and for tests. The +/// app never needs them to draw. Waits for the GPU (at most a minute); `Err` when the copy or +/// the wait fails. +#[cfg(not(target_arch = "wasm32"))] +pub fn read_texture( + device: &wgpu::Device, + queue: &wgpu::Queue, + texture: &wgpu::Texture, + width: usize, + height: usize, +) -> Result { + ctx::read_texture(device, queue, texture, width, height) +} + +#[cfg(not(target_arch = "wasm32"))] +fn run( + src: &Arc, + info: &SourceInfo, + s: &DevelopSettings, + req: &RenderRequest, + stages: Option<&StageCache>, + display: bool, +) -> Result { { // sections switched off with their eye render as if at their defaults (issue #316) let effective = s.effective(); @@ -501,6 +637,10 @@ pub fn try_render( return Err(Fallback::NotTried); } let s = &*lightcraft_pipeline::settings_for(s, req); + // content-aware Fill spots (`spots::fill_box`) have no GPU kernel: the CPU renders the photo + if s.spots.iter().any(|sp| sp.mode == lightcraft_develop::SpotMode::Fill) { + return Err(Fallback::NotTried); + } // in flight until this returns; not tried once the process is ending (issue #620) let _work = exit::enter().ok_or(Fallback::NotTried)?; let gpu = device().ok_or(Fallback::NotTried)?; @@ -512,7 +652,7 @@ pub fn try_render( let (r, scoped) = { let _scope = ctx::RenderScope::new(gpu); let errors = ctx::ErrorScopes::push(gpu); - let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| render::render(gpu, src, info, s, req, ext.as_deref(), fault))); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| render::render(gpu, src, info, s, req, ext.as_deref(), fault, display))); (r, errors.pop()) }; // An error the device raised explains the readback failures that follow it; a buffer @@ -533,7 +673,8 @@ pub fn try_render( e.clear(); } let what = match &r { - Some(r) => format!("{}×{}", r.image.width, r.image.height), + Some(Output::Image(r)) => format!("{}×{}", r.image.width, r.image.height), + Some(Output::Display { frame, .. }) => format!("{}×{}", frame.width, frame.height), None => "GPU render".into(), }; let reason = match f.kind { @@ -568,11 +709,6 @@ pub fn try_render( record_fallback(reason.clone()); Err(Fallback::Failed(reason)) } - #[cfg(target_arch = "wasm32")] - { - let _ = (src, info, s, req, stages); - Err(Fallback::NotTried) - } } /// Tests: parse and validate a WGSL module with naga, as wgpu does before it hands a shader to the driver. Needs no diff --git a/crates/gpu/src/nn.rs b/crates/gpu/src/nn.rs index 235ba9be68..334a663919 100644 --- a/crates/gpu/src/nn.rs +++ b/crates/gpu/src/nn.rs @@ -4,7 +4,8 @@ //! The runner has a device of its own, so a denoise job and the interactive renders are separate contexts that the //! driver time-slices, and a failure of one never takes the other down. It respects the same switches as GPU rendering //! (`LIGHTCRAFT_GPU`, `LIGHTCRAFT_GPU_BACKEND`, the GPU preference) and the same crash sentinel around device creation. -//! `LIGHTCRAFT_GPU_ADAPTER` picks an adapter by (part of) its name, e.g. to try another card. +//! `LIGHTCRAFT_GPU_ADAPTER` picks an adapter by (part of) its name, e.g. to try another card (`backend::pick_adapter`, +//! shared with the render device). //! //! Every failure is an `Err` (never a panic), and a device that errs or is lost stops being used: callers then run the //! CPU runner. The kernels (`wgsl/nn_conv.wgsl`, `wgsl/nn_pool.wgsl`) are tested against the plain-loop reference @@ -89,23 +90,7 @@ fn make_device(backends: wgpu::Backends) -> Result { // no indirect-call validation pipeline: Intel Metal fails to compile it (#250) desc.flags = crate::backend::instance_flags_from_env(desc.flags); let instance = wgpu::Instance::new(desc); - let wanted = std::env::var("LIGHTCRAFT_GPU_ADAPTER").ok().map(|s| s.trim().to_lowercase()).filter(|s| !s.is_empty()); - let adapter = match &wanted { - Some(w) => { - let all = pollster::block_on(instance.enumerate_adapters(backends)); - let names: Vec = all.iter().map(|a| a.get_info().name).collect(); - all.into_iter() - .find(|a| { - let i = a.get_info(); - i.device_type != wgpu::DeviceType::Cpu && i.name.to_lowercase().contains(w.as_str()) - }) - .ok_or_else(|| format!("no GPU adapter named like `{w}` (found: {})", names.join(", ")))? - } - None => pollster::block_on( - instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }), - ) - .map_err(|e| format!("no GPU adapter among {backends:?} ({e})"))?, - }; + let adapter = crate::backend::pick_adapter(&instance, backends)?; let info = adapter.get_info(); if info.device_type == wgpu::DeviceType::Cpu { return Err(format!("software adapter ({}) skipped: the CPU is faster", info.name)); @@ -968,6 +953,9 @@ mod tests { /// The runner, or `None` (with a note) on a machine with no usable GPU. fn gpu(net: &Net, tile: usize) -> Option { + // creating the device and building the kernels arms the crash sentinel: take turns with + // the tests that set its path (`backend::tests`) + let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); match runner(net, tile) { Ok(r) => Some(r), Err(e) => { @@ -1087,7 +1075,10 @@ mod tests { let net = onnx::read(std::path::Path::new(&model)).unwrap(); let tile = 512usize; let started = Instant::now(); - let g = runner(&net, tile).unwrap(); + let g = { + let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + runner(&net, tile).unwrap() + }; println!("{}: set up in {:.2} s, {:.0} MB per tile in flight", g.adapter(), started.elapsed().as_secs_f64(), g.bytes_per_tile() as f64 / 1e6); println!("kernels: {}", g.build_report()); let manifest = DenoiserManifest { diff --git a/crates/gpu/src/params.rs b/crates/gpu/src/params.rs index b46b7cc1ac..8c8624a23c 100644 --- a/crates/gpu/src/params.rs +++ b/crates/gpu/src/params.rs @@ -28,6 +28,11 @@ const FIELDS: &[(&str, usize)] = &[ ("DEHAZE", 1), ("SHARPEN", 1), ("SHARPEN_MASK", 1), + ("SHARPEN_LIMIT", 1), + ("SHARPEN_GAIN", 1), + ("SHARPEN_V3", 1), + ("SHP_OFF", 1), + ("HAS_SHP", 1), ("HAS_CLAR", 1), ("HAS_TEX", 1), ("HAS_DARK", 1), @@ -73,6 +78,13 @@ const FIELDS: &[(&str, usize)] = &[ ("OUT_Y", 3), ("OUT_TRC", 1), ("OUT_GAMMA", 1), + // a LUT profile: its table in `aux` at LUT_OFF (size³ rgb, red fastest), amount and domain + ("LUT", 1), + ("LUT_OFF", 1), + ("LUT_N", 1), + ("LUT_AMT", 1), + ("LUT_MIN", 3), + ("LUT_MAX", 3), // soft proofing (matrix proofs; `ProofParams`): working → proof RGB, its luma, proof → output, warnings ("PROOF", 1), ("PROOF_M", 9), @@ -82,6 +94,13 @@ const FIELDS: &[(&str, usize)] = &[ ("PROOF_DISP_WARN", 1), // first row of a band dispatch (the kernel runs over rows Y0.., see `render`) ("Y0", 1), + // process V4's calibrated Contrast, Blacks (`FinishParams::light`): the number of active + // operators (0 = none), each one's mode (`light_v3::Mode::code`) and mix weight, and the offset + // of their tables in `aux` (LIGHT_N entries each, in order) + ("LIGHT_OPS", 1), + ("LIGHT_MODE", 2), + ("LIGHT_W", 2), + ("LIGHT_OFF", 1), ]; /// `(name, index)` of every field (for the WGSL constants). @@ -140,13 +159,15 @@ impl Block { pub struct Present { pub clarity: bool, pub texture: bool, + /// The sharpening blur plane (after the texture plane in `tex` when both are present). + pub sharpen: bool, pub dark: bool, /// The blurred chromaticity follows the mask planes in the `masks` buffer. pub chroma: bool, } /// The `finish` kernel's parameter block and auxiliary table (tone LUT | chroma curve | sRGB LUT | curve LUTs | -/// mask terms) for `fp` with `masks` (their local adjustments' terms). +/// mask terms | light operator tables) for `fp` with `masks` (their local adjustments' terms). pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present) -> (Vec, Vec) { let mut aux: Vec = fp.tone.lut().to_vec(); aux.extend_from_slice(fp.tone.chroma_lut()); @@ -163,8 +184,28 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr for m in masks { aux.extend_from_slice(m); } + let light_off = aux.len(); + let light = fp.light.as_ref().map_or(&[][..], |l| &l.ops[..]); + let light = &light[..light.len().min(2)]; + for op in light { + aux.extend_from_slice(&op.lut[..]); + } + let lut_off = aux.len(); + if let Some((l, _)) = &fp.lut { + aux.extend(l.data.iter().flatten()); + } let mut p = Block::new(); + p.u("LIGHT_OPS", light.len() as u32); + p.u("LIGHT_OFF", light_off as u32); + if let Some(i) = index("LIGHT_MODE") { + for (k, op) in light.iter().enumerate() { + if let Some(slot) = p.0.get_mut(i + k) { + *slot = op.mode.code(); + } + } + } + p.fs("LIGHT_W", &light.iter().map(|op| op.weight).collect::>()); p.u("W", fp.w as u32); p.u("H", fp.h as u32); p.u("NMASK", masks.len() as u32); @@ -184,6 +225,11 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr p.f("DEHAZE", fp.dehaze); p.f("SHARPEN", fp.sharpen); p.f("SHARPEN_MASK", fp.sharpen_mask); + p.f("SHARPEN_LIMIT", fp.sharpen_limit); + p.f("SHARPEN_GAIN", fp.sharpen_gain); + p.b("SHARPEN_V3", fp.pixel_sharpen); + p.u("SHP_OFF", if present.texture { (fp.w * fp.h) as u32 } else { 0 }); + p.b("HAS_SHP", present.sharpen); p.b("HAS_CLAR", present.clarity); p.b("HAS_TEX", present.texture); p.b("HAS_DARK", present.dark); @@ -211,6 +257,7 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr } p.f("SKIN", ops.skin); p.fs("BANDH", lightcraft_pipeline::colorops::band_hues()); + p.fs("VIG_VIEW", &fp.view); if let Some(v) = &fp.vig { p.b("VIG", true); @@ -220,7 +267,6 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr p.f("VIG_ASPECT_MIX", v.aspect_mix); p.f("VIG_POWER", v.power); p.f("VIG_HL", v.highlights); - p.fs("VIG_VIEW", &fp.view); p.u( "VIG_STYLE", match v.style { @@ -240,6 +286,14 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr let (trc, gamma) = fp.out_trc.code(); p.u("OUT_TRC", trc); p.f("OUT_GAMMA", gamma); + if let Some((l, amount)) = &fp.lut { + p.b("LUT", true); + p.u("LUT_OFF", lut_off as u32); + p.u("LUT_N", l.size as u32); + p.f("LUT_AMT", *amount); + p.fs("LUT_MIN", &l.domain_min); + p.fs("LUT_MAX", &l.domain_max); + } if let Some(pp) = fp.proof.as_ref().filter(|pp| pp.table.is_none()) { p.b("PROOF", true); p.fs("PROOF_M", pp.to_proof.as_flattened()); diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 9d6172d9c3..701cc3c5de 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -44,6 +44,7 @@ struct Planes { base: Option<(local::BaseKey, Arc)>, clarity: Option<(u32, Arc)>, texture: Option<(u32, Arc)>, + sharpen: Option<(local::SharpenKey, Arc)>, dark: Option<(u32, Arc, f32)>, chroma: Option<(u32, Arc)>, } @@ -105,6 +106,7 @@ impl GpuStages { p.base.iter().for_each(|(_, b)| add(b)); p.clarity.iter().for_each(|(_, b)| add(b)); p.texture.iter().for_each(|(_, b)| add(b)); + p.sharpen.iter().for_each(|(_, b)| add(b)); p.dark.iter().for_each(|(_, b, _)| add(b)); } if let Some((_, b)) = &*self.source.lock().unwrap_or_else(|e| e.into_inner()) { @@ -213,6 +215,20 @@ impl<'a> Cx<'a> { enc.copy_buffer_to_buffer(src.raw(), 0, dst.raw(), (offset * 4) as u64, (src.len * 4) as u64); } + /// Copy `w × h` texels from `b` (rows of `stride` 32-bit texels, a multiple of 64) into + /// `texture` (recorded). + pub fn copy_to_texture(&mut self, b: &Buf, stride: usize, texture: &wgpu::Texture, w: usize, h: usize) { + let enc = self.enc.get_or_insert_with(|| self.gpu.encoder()); + enc.copy_buffer_to_texture( + wgpu::TexelCopyBufferInfo { + buffer: b.raw(), + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some((stride * 4) as u32), rows_per_image: Some(h as u32) }, + }, + wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 }, + ); + } + pub fn read_rgb(&mut self, b: &Buf, w: usize, h: usize) -> Rgb32f { Rgb32f { width: w, height: h, data: self.read(b, w * h * 3) } } @@ -263,6 +279,18 @@ pub(crate) fn gaussian(cx: &mut Cx<'_>, src: &Buf, w: usize, h: usize, nc: usize if last == 0 { a } else { b } } +/// Exact Gaussian (`lightcraft_raster::blur::gaussian_taps`) of a one-channel plane. +pub(crate) fn gaussian_fir(cx: &mut Cx<'_>, src: &Buf, w: usize, h: usize, sigma: f32) -> Buf { + let taps = lightcraft_raster::blur::gauss_taps(sigma); + let taps_buf = cx.gpu.upload(&taps); + let r = (taps.len() / 2) as u32; + let (tmp, out) = (cx.gpu.buffer(w * h), cx.gpu.buffer(w * h)); + let p = [w as u32, h as u32, r]; + cx.run("gauss_h", &p, &[Some(src), Some(&taps_buf), Some(&tmp)], groups2(w, h, [16, 16])); + cx.run("gauss_v", &p, &[Some(&tmp), Some(&taps_buf), Some(&out)], groups2(w, h, [16, 16])); + out +} + /// Resample taps of `lightcraft_raster::resample::resize`, packed for the `resize_*` kernels. fn taps(src: usize, dst: usize, filter: Filter) -> Vec { let w = lightcraft_raster::resample::weights(src, dst, filter); @@ -579,8 +607,34 @@ pub(crate) fn profiling() -> bool { *ON.get_or_init(|| std::env::var_os("LIGHTCRAFT_PROFILE").is_some()) } -/// Render on `gpu`, reusing `stages` (if given). `None` (or a result the caller discards) when the -/// render failed: the reason is recorded with [`crate::ctx::fail`]. +/// A finished render on the window's device, ready to draw: an `Rgba8Unorm` texture (the 8-bit +/// output, sRGB-curve encoded, as egui's own textures) that never went through host memory. +#[derive(Clone, Debug)] +pub struct DisplayFrame { + pub texture: wgpu::Texture, + pub width: usize, + pub height: usize, +} + +/// What a render produced: pixels in host memory, or (asked for with `display` and possible) a +/// texture on the window's device plus the histogram. +pub enum Output { + Image(Rendered), + Display { frame: DisplayFrame, histogram: Histogram }, +} + +/// Whether a render of this plan can end in a texture instead of a readback: the device is the +/// window's, nothing is drawn over the image on the CPU (overlays) or cut from it (a window that +/// spots grew), and the texture fits the device. +fn can_display(gpu: &Gpu, plan: &Plan<'_>, req: &RenderRequest) -> bool { + let max = gpu.device.limits().max_texture_dimension_2d as usize; + gpu.window && req.overlay == lightcraft_pipeline::Overlay::None && plan.keep.is_none() && plan.w <= max && plan.h <= max && plan.w * plan.h > 0 +} + +/// Render on `gpu`, reusing `stages` (if given); with `display`, into a texture when +/// [`can_display`]. `None` (or a result the caller discards) when the render failed: the reason is +/// recorded with [`crate::ctx::fail`]. +#[allow(clippy::too_many_arguments)] pub fn render( gpu: &Gpu, src: &Arc, @@ -589,7 +643,8 @@ pub fn render( req: &RenderRequest, stages: Option<&GpuStages>, fault: Option, -) -> Option { + display: bool, +) -> Option { let mut t = profiling().then(std::time::Instant::now); // Each stage is submitted on its own; under `LIGHTCRAFT_PROFILE` also waited for, so the // timings are real. @@ -692,9 +747,22 @@ pub fn render( let present = Present { clarity: prep.clarity.is_some(), texture: prep.texture.is_some(), + sharpen: prep.sharpen.is_some(), dark: prep.dark.is_some(), chroma: masks.is_some() && prep.chroma.is_some(), }; + // the finish kernel's `tex` binding: the texture plane, then the sharpening plane (one binding + // for both keeps the kernel within the storage-buffer count every supported device has) + let tex_buf: Option> = match (&prep.texture, &prep.sharpen) { + (Some(t), Some(sh)) => { + let both = cx.gpu.buffer(2 * n); + cx.copy_into(t, &both, 0); + cx.copy_into(sh, &both, n); + Some(Arc::new(both)) + } + (Some(b), None) | (None, Some(b)) => Some(b.clone()), + (None, None) => None, + }; let (p, aux) = finish_block(&fp, &terms, &present); let aux = gpu.upload(&aux); // cleared, so that work which never ran cannot pass for an image (see the check below) @@ -717,7 +785,7 @@ pub fn render( Some(&prep.log_l), Some(&prep.base), prep.clarity.as_deref(), - prep.texture.as_deref(), + tex_buf.as_deref(), prep.dark.as_deref(), masks.as_ref(), Some(&aux), @@ -726,6 +794,9 @@ pub fn render( groups2(w, rows.min(h - y0), [16, 16]), ); } + if display && can_display(gpu, &plan, req) { + return to_texture(&mut cx, &out, w, h).map(|(frame, histogram)| Output::Display { frame, histogram }); + } // the alpha a mask overlay shows: copied out before the readback below submits let overlay_mask = req.overlay.mask(s).map(|m| { let list = s.masks.iter().filter(|m| m.visible && !m.components.is_empty()); @@ -769,10 +840,8 @@ pub fn render( fail(FailKind::Fatal, format!("the GPU returned an incomplete image ({unwritten} of {n} pixels unwritten)")); return None; } - let histogram = match plan.keep { - Some(k) => Histogram::of_srgb8(&image.crop(k.x, k.y, k.w, k.h)), - None => Histogram::of_srgb8(&image), - }; + let region = plan.keep.map_or((0, 0, w, h), |k| (k.x, k.y, k.w, k.h)); + let histogram = histogram(&mut cx, &out, w, region); lap("histogram", &mut t, &mut cx); // An entirely black result (upstream work that did not run would give that too): redo it on // the CPU, which costs time only for the rare photo that really is black. @@ -794,8 +863,9 @@ pub fn render( let overlay_mask = overlay_mask.or_else(|| { req.overlay.reads_detail().then(|| { let l = host.log_l.get_or_insert_with(|| Arc::new(cx.read_plane(&prep.log_l, w, h))).clone(); - let tex = prep.texture.as_deref().map(|b| cx.read_plane(b, w, h)); - lightcraft_pipeline::visualize::sharpen_plane(req.overlay, &plan.settings, &l, tex.as_ref(), plan.px_per_long) + let band = if local::pixel_sharpen(&plan.settings) { &prep.sharpen } else { &prep.texture }; + let blur = band.as_deref().map(|b| cx.read_plane(b, w, h)); + lightcraft_pipeline::visualize::sharpen_plane(req.overlay, &plan.settings, &l, blur.as_ref(), plan.px_per_long, plan.native_long as f64) })? }); lightcraft_pipeline::visualize::apply(&mut image, req.overlay, &plan, overlay_mask.as_ref(), all_overlay_alphas.as_deref()); @@ -803,7 +873,53 @@ pub fn render( if let Some(k) = plan.keep { image = image.crop(k.x, k.y, k.w, k.h); } - Some(Rendered { image, histogram, deep: None }) + Some(Output::Image(Rendered { image, histogram, deep: None })) +} + +/// The finished output `out` (`w × h` packed RGBA8) as a texture on the device, with its +/// histogram; the same checks as a readback (every pixel written, not entirely black), done on +/// the device: only the histogram and a pixel count come back. +fn to_texture(cx: &mut Cx<'_>, out: &Buf, w: usize, h: usize) -> Option<(DisplayFrame, Histogram)> { + let n = w * h; + let unwritten = cx.zeroed(1); + cx.run("unwritten", &[n as u32], &[Some(out), None, Some(&unwritten)], groups1(n)); + let histogram = histogram(cx, out, w, (0, 0, w, h)); + let left = cx.read::(&unwritten, 1).first().copied().unwrap_or(0); + if crate::ctx::failed() { + return None; + } + if left > 0 { + fail(FailKind::Fatal, format!("the GPU returned an incomplete image ({left} of {n} pixels unwritten)")); + return None; + } + if n >= 4096 && [&histogram.r, &histogram.g, &histogram.b].iter().all(|c| c.first() == Some(&histogram.total)) { + fail(FailKind::Blank, "the GPU result is entirely black; rendering it on the CPU to be sure".into()); + return None; + } + // texture copies take rows of a multiple of 256 bytes: pad them unless they already are + let stride = w.next_multiple_of(64); + let padded = (stride != w).then(|| { + let b = cx.gpu.buffer(stride * h); + cx.run("pad_rows", &[w as u32, h as u32, stride as u32], &[Some(out), Some(&b), None], groups2(w, h, [16, 16])); + b + }); + let texture = cx.gpu.device.create_texture(&wgpu::TextureDescriptor { + label: Some("lightcraft view"), + size: wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + // (COPY_SRC: a screenshot or a test can read it back) + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + cx.copy_to_texture(padded.as_ref().unwrap_or(out), stride, &texture, w, h); + cx.flush(); + if crate::ctx::failed() { + return None; + } + Some((DisplayFrame { texture, width: w, height: h }, histogram)) } /// Pixels whose alpha is not 255 (cheap: no early exit, so it vectorizes). @@ -816,8 +932,9 @@ fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, ho let (w, h) = (plan.w, plan.h); let n = w * h; let s = &*plan.settings; - let img = if lightcraft_pipeline::lin_needs_cpu(s, info) { - // defringe / spot removal / local tone mapping: CPU + let img = if lightcraft_pipeline::local_tone::enabled(info, s) { + // the camera's local tone mapping (ProRAW gain table, off by default): the whole + // scene-linear stage on the CPU let mut img = match host.sampled.take() { Some(i) => i, None => cx.read_rgb(sampled, w, h), @@ -825,11 +942,14 @@ fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, ho lightcraft_pipeline::lin_cpu(&mut img, info, plan); cx.gpu.upload(rgb_words(&img)) } else { + // `lin_cpu`'s order: white balance, defringe, spots, red eye let m = local::wb_matrix_for(info, s); let mut p = vec![m.is_some() as u32]; p.extend(m.unwrap_or_default().iter().flatten().map(|v| v.to_bits())); let out = cx.gpu.buffer(n * 3); map(cx, "wb_k", n, &p, [Some(sampled), None, None], &out); + let out = defringe(cx, out, plan); + let out = spots(cx, out, plan); if plan.eyes.is_empty() { out } else { @@ -843,6 +963,96 @@ fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, ho denoise(cx, img, plan) } +/// Defringe (`optics::defringe`) of the white-balanced image. +fn defringe(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf { + use lightcraft_pipeline::optics; + let Some(dp) = optics::defringe_params(&plan.settings, plan.px_per_long / optics::DEFRINGE_REF_LONG) else { return img }; + let (w, h) = (plan.w, plan.h); + let n = w * h; + let lab = cx.gpu.buffer(n * 3); + map(cx, "fringe_lab", n, &[], [Some(&img), None, None], &lab); + // the lightness channel, then its min and max around each pixel + let l = cx.gpu.buffer(n); + map(cx, "subsample", n, &[3], [Some(&lab), None, None], &l); + // (a radius past the image reads the same pixels as one at its size) + let r = dp.radius.min(w.max(h)) as u32; + let filtered = |cx: &mut Cx<'_>, max: u32| { + let tmp = cx.gpu.buffer(n); + cx.run("minmax", &[w as u32, h as u32, r, 0, max], &[Some(&l), Some(&tmp)], groups2(w, h, [16, 16])); + let out = cx.gpu.buffer(n); + cx.run("minmax", &[w as u32, h as u32, r, 1, max], &[Some(&tmp), Some(&out)], groups2(w, h, [16, 16])); + out + }; + let (lo, hi) = (filtered(cx, 0), filtered(cx, 1)); + // the kernel writes only the pixels it changes + let out = cx.copy(&img); + let p = [dp.purple.0, dp.purple.1, dp.green.0, dp.green.1, dp.purple_strength, dp.green_strength].map(f32::to_bits); + map(cx, "fringe_apply", n, &p, [Some(&lab), Some(&lo), Some(&hi)], &out); + out +} + +/// Spot removal (`spots::apply`), spot by spot on `img` in place: each spot reads the image as +/// the earlier ones left it. +fn spots(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf { + use lightcraft_pipeline::spots; + let (w, h) = (plan.w, plan.h); + for spot in &plan.settings.spots { + let Some(l) = spots::layout(spot, &plan.frame, w, h, plan.px_per_long) else { continue }; + let Some(&first) = l.pts.first() else { continue }; + let offset = match l.offset { + Some(o) => o, + None => auto_source(cx, &img, w, h, first, l.r), + }; + let pts = cx.gpu.upload(&l.pts.iter().flat_map(|p| [p.0, p.1]).collect::>()); + let nb = l.bw * l.bh; + let (al, sp, df, wt) = (cx.gpu.buffer(nb), cx.gpu.buffer(3 * nb), cx.gpu.buffer(3 * nb), cx.gpu.buffer(nb)); + let mut p = vec![w as u32, h as u32, l.bx as u32, l.by as u32, l.bw as u32, l.bh as u32, l.pts.len() as u32]; + p.extend([l.r, l.inner, l.opacity, offset.0, offset.1].map(f32::to_bits)); + p.push(l.heal as u32); + let groups = groups2(l.bw, l.bh, [16, 16]); + cx.run("spot_prep", &p, &[Some(&img), Some(&pts), Some(&al), Some(&sp), Some(&df), Some(&wt)], groups); + // Heal: the tone correction is the masked difference's normalized blur + let blurred = l.heal.then(|| { + let sigma = (l.r * 0.6).max(1.0); + (gaussian(cx, &df, l.bw, l.bh, 3, sigma), gaussian(cx, &wt, l.bw, l.bh, 1, sigma)) + }); + let (bd, bm) = blurred.as_ref().map_or((&df, &wt), |(d, m)| (d, m)); + cx.run("spot_apply", &p, &[Some(&img), Some(&pts), Some(&al), Some(&sp), Some(bd), Some(bm)], groups); + } + img +} + +/// `spots::auto_source` on the device: every candidate scored at once, the 48 scores read back. +fn auto_source(cx: &mut Cx<'_>, img: &Buf, w: usize, h: usize, target: (f32, f32), r: f32) -> (f32, f32) { + use lightcraft_pipeline::spots; + let cands = spots::candidates(r); + let mut data: Vec = cands.iter().flat_map(|d| [d.0, d.1]).collect(); + data.extend(spots::ring_dirs().iter().flat_map(|d| [d.0, d.1])); + let pts = cx.gpu.upload(&data); + let [around, within] = spots::score_radii(r); + let mut p = vec![w as u32, h as u32]; + p.extend([target.0, target.1].iter().chain(&around).chain(&within).map(|v| v.to_bits())); + let scores = cx.gpu.buffer(cands.len()); + cx.run("spot_score", &p, &[Some(img), Some(&pts), Some(&scores), None, None, None], [cands.len().div_ceil(64) as u32, 1, 1]); + let scores: Vec = cx.read(&scores, cands.len()); + spots::rank(&cands, &scores).first().copied().unwrap_or_else(|| spots::fallback_source(r)) +} + +/// The output's histogram (`Histogram::of_srgb8` of the `region` x, y, w, h of the `w`-wide +/// packed RGBA8 `out`, on the same sampling grid), counted on the device. +fn histogram(cx: &mut Cx<'_>, out: &Buf, w: usize, region: (usize, usize, usize, usize)) -> Histogram { + let (x0, y0, rw, rh) = region; + let step = (((rw * rh) as f64 / 1_000_000.0).sqrt().ceil() as usize).max(1); + let (nx, ny) = (rw.div_ceil(step), rh.div_ceil(step)); + let bins = cx.zeroed(4 * Histogram::BINS + 1); + let p = [w, x0, y0, nx, ny, step].map(|v| v as u32); + cx.run("histogram", &p, &[Some(out), Some(&bins)], groups2(nx, ny, [16, 16])); + let v: Vec = cx.read(&bins, 4 * Histogram::BINS + 1); + let part = |k: usize| v.get(k * Histogram::BINS..(k + 1) * Histogram::BINS).map_or_else(|| vec![0; Histogram::BINS], <[u32]>::to_vec); + // (SDR bins: an HDR edit's histogram is made after the render, `media::develop`) + Histogram { r: part(0), g: part(1), b: part(2), luma: part(3), total: v.get(4 * Histogram::BINS).copied().unwrap_or(0), hdr: None } +} + /// Noise reduction (`local::denoise`). fn denoise(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf { let (w, h) = (plan.w, plan.h); @@ -874,6 +1084,7 @@ struct Prep { base: Arc, clarity: Option>, texture: Option>, + sharpen: Option>, dark: Option>, /// Blurred chromaticity (local Moiré / Noise). chroma: Option>, @@ -884,7 +1095,7 @@ struct Prep { fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, planes: &mut Planes) -> Prep { let (w, h) = (plan.w, plan.h); let n = w * h; - let sig = local::plane_sigmas(&plan.settings, plan.px_per_long, req.quality); + let sig = local::plane_sigmas(&plan.settings, plan.px_per_long, plan.native_long as f64, req.quality); let log_l = match &planes.log_l { Some(b) => b.clone(), None => { @@ -904,6 +1115,7 @@ fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, pla }; let clarity = sig.clarity.map(|sg| plane_at(&mut planes.clarity, sg.to_bits(), || guided_fast(cx, &log_l, w, h, sg, local::CLARITY_EPS))); let texture = sig.texture.map(|sg| plane_at(&mut planes.texture, sg.to_bits(), || gaussian(cx, &log_l, w, h, 1, sg))); + let sharpen = sig.sharpen.map(|sg| plane_at(&mut planes.sharpen, local::sharpen_key(&plan.settings, sg), || gaussian_fir(cx, &log_l, w, h, sg))); let (dark, air) = match sig.dark { None => (None, 1.0), Some(sg) => match &planes.dark { @@ -931,7 +1143,7 @@ fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, pla gaussian(cx, &ch, w, h, 3, sg) }) }); - Prep { log_l, base, clarity, texture, dark, chroma, air } + Prep { log_l, base, clarity, texture, sharpen, dark, chroma, air } } /// Most brush dabs the mask kernel evaluates per pixel (more: the CPU rasterizes the brush). @@ -958,8 +1170,18 @@ fn brush_aux(dabs: &[&lightcraft_pipeline::masks::BrushDabs], erase: bool) -> Ve aux } -/// Cross guided filter (`masks::guided_cross`) of `p` steered by `guide`, max-combined with `p`. -fn guided_cross_max(cx: &mut Cx<'_>, guide: &Buf, p: &Buf, w: usize, h: usize, sigma: f32, eps: f32) -> Buf { +/// How [`guided_cross`] combines the filtered plane with its input. +#[derive(Clone, Copy)] +enum Combine { + /// The larger of the two (Auto Mask strokes). + Max, + /// The input moved towards the filtered plane by this much (Refine Edges). + Mix(f32), +} + +/// Cross guided filter (`masks::guided_cross`) of `p` steered by `guide`, combined with `p`. +#[allow(clippy::too_many_arguments)] +fn guided_cross(cx: &mut Cx<'_>, guide: &Buf, p: &Buf, w: usize, h: usize, sigma: f32, eps: f32, how: Combine) -> Buf { let n = w * h; let (m0, m1) = (cx.gpu.buffer(2 * n), cx.gpu.buffer(2 * n)); map(cx, "xguided_pre", n, &[0], [Some(guide), Some(p), None], &m0); @@ -969,7 +1191,11 @@ fn guided_cross_max(cx: &mut Cx<'_>, guide: &Buf, p: &Buf, w: usize, h: usize, s map(cx, "xguided_ab", n, &[eps.to_bits()], [Some(&b0), Some(&b1), None], &ab); let ab = gaussian(cx, &ab, w, h, 2, sigma); let q = cx.gpu.buffer(n); - map(cx, "xguided_apply", n, &[], [Some(guide), Some(&ab), Some(p)], &q); + let mode = match how { + Combine::Max => [0, 0], + Combine::Mix(k) => [1, k.to_bits()], + }; + map(cx, "xguided_apply", n, &mode, [Some(guide), Some(&ab), Some(p)], &q); q } @@ -997,6 +1223,11 @@ fn masks(cx: &mut Cx<'_>, lin: &Buf, prep: &Prep, plan: &Plan<'_>, host: &mut Ho } let comp_plane = cx.gpu.buffer(n); for (mi, m) in list.iter().enumerate() { + // its coordinates on the photo before the warp (`masks::evaluate_one`): through a lens or + // perspective warp the kernels' affine positions don't hold, so its shapes run on the CPU + let mframe = plan.frame.for_mask(m.on_photo); + let frame = &*mframe; + let warped = frame.mask_warp().is_some(); let mut first = true; for comp in &m.components { let op = match comp.op { @@ -1012,6 +1243,7 @@ fn masks(cx: &mut Cx<'_>, lin: &Buf, prep: &Prep, plan: &Plan<'_>, host: &mut Ho let mut aux: Vec = Vec::new(); let mut own: Option = None; let kind = match &comp.shape { + MaskShape::Linear { .. } | MaskShape::Radial { .. } if warped => None, MaskShape::Linear { start, end } => { let (a, b) = (frame.norm_to_long(*start), frame.norm_to_long(*end)); let d = b - a; @@ -1068,7 +1300,7 @@ fn masks(cx: &mut Cx<'_>, lin: &Buf, prep: &Prep, plan: &Plan<'_>, host: &mut Ho cx.run("shape", &q, &[Some(lin), Some(&prep.log_l), Some(&aux), Some(&stroke), Some(&brush)], groups2(w, h, [16, 16])); let refined = d.auto.then(|| { let (sigma, eps) = lightcraft_pipeline::masks::auto_refine(d.r); - guided_cross_max(cx, &prep.log_l, &stroke, w, h, sigma, eps) + guided_cross(cx, &prep.log_l, &stroke, w, h, sigma, eps, Combine::Max) }); let op = if d.erase { 2 } else { 1 }; cx.run( @@ -1114,6 +1346,15 @@ fn masks(cx: &mut Cx<'_>, lin: &Buf, prep: &Prep, plan: &Plan<'_>, host: &mut Ho let k = [n as u32, 0, mi as u32, op]; cx.run("combine", &k, &[None, None, None, Some(cbuf), Some(&alpha)], groups1(n)); } + if m.refine > 0.0 { + // Refine Edges (`masks::evaluate_one`): the combined alpha follows the photo's edges, + // before the mask's invert and amount + let k = (m.refine / 100.0).clamp(0.0, 1.0) as f32; + let sigma = (0.04 * frame.output_long(w, h) as f32 * k).max(1.0); + let plane = cx.slice(&alpha, mi * n, n); + let refined = guided_cross(cx, &prep.log_l, &plane, w, h, sigma, 0.02, Combine::Mix(k.sqrt())); + cx.copy_into(&refined, &alpha, mi * n); + } let amt = (m.adjust.amount / 100.0) as f32; cx.run( "finalize", @@ -1141,6 +1382,7 @@ mod tests { }), vignette: None, stages: Default::default(), + source: Default::default(), }; let mut s = DevelopSettings::default(); s.optics.lens_profile = true; @@ -1202,6 +1444,8 @@ mod tests { /// workgroup, windows wider than the image, and 1, 2 (as two planes) and 3 channels. #[test] fn gaussian_matches_cpu() { + // (creating the device writes the crash sentinel another test swaps out) + let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); use lightcraft_raster::blur; let Some(gpu) = crate::device() else { return }; let _scope = crate::ctx::RenderScope::new(gpu); @@ -1229,6 +1473,8 @@ mod tests { #[test] #[ignore] fn bench_kernels() { + // (creating the device writes the crash sentinel another test swaps out) + let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let Some(gpu) = crate::device() else { return }; let _scope = crate::ctx::RenderScope::new(gpu); let (w, h) = (6000, 4000); @@ -1266,6 +1512,31 @@ mod tests { time("guided sigma=1.75", &mut |cx| drop(guided(cx, &src, w, h, 1.75, 0.01))); } + /// The device scores Remove's candidate sources like the CPU and picks the same one. + #[test] + fn auto_source_picks_the_cpu_candidate() { + // (creating the device writes the crash sentinel another test swaps out) + let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(gpu) = crate::device() else { + let why = crate::unavailable_reason().unwrap_or_default(); + assert!(!why.contains("kernels failed to build"), "{why}"); + return; + }; + let _scope = crate::ctx::RenderScope::new(gpu); + let img = lightcraft_scenes::demo_library()[3].render(640, 427); + let buf = gpu.upload(rgb_words(&img)); + let mut differ = Vec::new(); + for (tx, ty, r) in [(25.6, 213.0, 19.2), (320.0, 192.0, 19.2), (100.0, 50.0, 12.0), (600.0, 400.0, 25.0), (320.0, 213.0, 6.0)] { + let mut cx = Cx::new(gpu); + let g = auto_source(&mut cx, &buf, img.width, img.height, (tx, ty), r); + let c = lightcraft_pipeline::spots::auto_source(&img, (tx, ty), r); + if g != c { + differ.push(((tx, ty, r), g, c)); + } + } + assert!(differ.is_empty(), "(target, gpu, cpu): {differ:?}"); + } + #[test] fn orient_map_matches_image_oriented() { use Orientation::*; diff --git a/crates/gpu/src/wgsl/blur.wgsl b/crates/gpu/src/wgsl/blur.wgsl index 375fb6d550..756457ade4 100644 --- a/crates/gpu/src/wgsl/blur.wgsl +++ b/crates/gpu/src/wgsl/blur.wgsl @@ -75,6 +75,43 @@ fn box_v(@builtin(global_invocation_id) g: vec3) { } } +// Square min (P[4] = 0) or max (1) filter of radius r, one axis at a time (`optics::min_filter`): +// clamped to the image, single channel. P: w, h, r, axis (0 horizontal, 1 vertical), max. +@compute @workgroup_size(16, 16) +fn minmax(@builtin(global_invocation_id) g: vec3) { + let w = pu(0u); + let h = pu(1u); + if (g.x >= w || g.y >= h) { + return; + } + let r = pu(2u); + let vertical = pu(3u) != 0u; + let is_max = pu(4u) != 0u; + let i = g.y * w + g.x; + var v = src[i]; + var lo = 0u; + var hi = 0u; + if (vertical) { + lo = g.y - min(g.y, r); + hi = min(g.y + r, h - 1u); + } else { + lo = g.x - min(g.x, r); + hi = min(g.x + r, w - 1u); + } + for (var k = lo; k <= hi; k++) { + var j = g.y * w + k; + if (vertical) { + j = k * w + g.x; + } + if (is_max) { + v = max(v, src[j]); + } else { + v = min(v, src[j]); + } + } + dst[i] = v; +} + // Separable median of a single-channel plane (`lightcraft_pipeline::local::median_hv`): 2r+1 // taps (r ≤ 24, clamped edges) along a row (median_h) or a column (median_v), one thread per // pixel. The median is a selection, so the result matches the CPU's bit for bit. diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl index 767ff44c99..9e589f4ca9 100644 --- a/crates/gpu/src/wgsl/finish.wgsl +++ b/crates/gpu/src/wgsl/finish.wgsl @@ -1,7 +1,7 @@ // The per-pixel stage: a straight port of `lightcraft_pipeline::finish` (keep in step with it). // Bindings: img (rgb, pre-exposure), log_l, base, clar, tex, dark, masks (NMASK planes, then the // blurred chromaticity when HAS_CHROMA), aux -// (tone LUT | chroma curve | sRGB LUT | curve LUTs | mask terms), out (packed RGBA8). +// (tone LUT | chroma curve | sRGB LUT | curve LUTs | mask terms | light operator tables), out (packed RGBA8). fn tone_apply(y: f32) -> f32 { if (y <= 0.0) { @@ -47,6 +47,56 @@ fn curve(ch: u32, x: f32) -> f32 { return aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * t; } +// Process V4's calibrated Contrast, Blacks (`lightcraft_pipeline::light_v3`): operator `k`'s +// table (linear output over encoded v) at v (`Operator::eval`). +fn light_eval(k: u32, v: f32) -> f32 { + let o = pu(F_LIGHT_OFF) + k * LIGHT_N; + let f = clamp(v, 0.0, 1.0) * f32(LIGHT_N - 1u); + let i = min(u32(f), LIGHT_N - 2u); + let t = f - f32(i); + return aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * t; +} + +// `Operator::channel`: one linear value; above 1 unchanged, below 0 shifted by F(0). +fn light_channel(k: u32, x: f32) -> f32 { + if (x > 1.0) { + return x; + } + if (x < 0.0) { + return aux[pu(F_LIGHT_OFF) + k * LIGHT_N] + x; + } + return light_eval(k, encode_srgb(x)); +} + +// `Operator::luminance`: scaled by F of the ProPhoto luminance over it. +fn light_lum(k: u32, p: vec3) -> vec3 { + let y = PRO_Y.x * p.x + PRO_Y.y * p.y + PRO_Y.z * p.z; + if (!(y > 1e-6) || y > 1.0) { + return p; + } + return p * (light_channel(k, y) / y); +} + +// `LightOps::apply`: linear Rec.2020 → ProPhoto, the operators in order, back. +fn light_ops(d: vec3) -> vec3 { + var p = mul3(PRO_FROM_2020, d); + let n = min(pu(F_LIGHT_OPS), 2u); + for (var k = 0u; k < n; k++) { + let mode = pu(F_LIGHT_MODE + k); + if (mode == 0u) { + p = vec3(light_channel(k, p.x), light_channel(k, p.y), light_channel(k, p.z)); + } else if (mode == 1u) { + p = light_lum(k, p); + } else { + let a = vec3(light_channel(k, p.x), light_channel(k, p.y), light_channel(k, p.z)); + let b = light_lum(k, p); + let w = pf(F_LIGHT_W + k); + p = vec3(w * a.x + (1.0 - w) * b.x, w * a.y + (1.0 - w) * b.y, w * a.z + (1.0 - w) * b.z); + } + } + return mul3(PRO_TO_2020, p); +} + fn band_weights(h: f32) -> array { var w: array; for (var i = 0u; i < 8u; i++) { @@ -230,8 +280,69 @@ fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { return a + (b - a) * v; } -fn enc8(v: f32) -> u32 { - return u32(clamp(v, 0.0, 1.0) * 255.0 + 0.5); +// The 3×3 matrix at parameter `o` (row-major). +fn mat_at(o: u32) -> array, 3> { + return array, 3>( + vec3(pf(o), pf(o + 1u), pf(o + 2u)), + vec3(pf(o + 3u), pf(o + 4u), pf(o + 5u)), + vec3(pf(o + 6u), pf(o + 7u), pf(o + 8u)), + ); +} + +// `finish::out_of_gamut`: needed real desaturation, and isn't a neutral clipping at white/black. +fn out_of_gamut(r: vec3, t: f32) -> bool { + let lo = min(r.x, min(r.y, r.z)); + let hi = max(r.x, max(r.y, r.z)); + return t < GAMUT_WARN && (hi - lo) > 0.02 * max(abs(hi), 1e-3) && hi - lo > 1e-3 && (lo < -1e-3 || (hi > 1.0 && lo < 1.0)); +} + +// `Lut3d::apply` (trilinear) on the LUT profile's table in `aux` (red fastest). +fn lut_at(r: u32, g: u32, b: u32) -> vec3 { + let n = pu(F_LUT_N); + let o = pu(F_LUT_OFF) + 3u * (r + n * (g + n * b)); + return vec3(aux[o], aux[o + 1u], aux[o + 2u]); +} + +fn lut_apply(c: vec3) -> vec3 { + let n = pu(F_LUT_N); + let s = f32(n - 1u); + var idx = vec3(0u); + var fr = vec3(0.0); + for (var k = 0u; k < 3u; k++) { + let lo = pf(F_LUT_MIN + k); + let span = max(pf(F_LUT_MAX + k) - lo, 1e-6); + let x = clamp((c[k] - lo) / span, 0.0, 1.0) * s; + let i = min(u32(floor(x)), n - 2u); + idx[k] = i; + fr[k] = x - f32(i); + } + let r = idx.x; + let g = idx.y; + let b = idx.z; + let c00 = mix(lut_at(r, g, b), lut_at(r + 1u, g, b), fr.x); + let c10 = mix(lut_at(r, g + 1u, b), lut_at(r + 1u, g + 1u, b), fr.x); + let c01 = mix(lut_at(r, g, b + 1u), lut_at(r + 1u, g, b + 1u), fr.x); + let c11 = mix(lut_at(r, g + 1u, b + 1u), lut_at(r + 1u, g + 1u, b + 1u), fr.x); + return mix(mix(c00, c10, fr.y), mix(c01, c11, fr.y), fr.z); +} + +const BAYER_8X8 = array( + 0.0, 32.0, 8.0, 40.0, 2.0, 34.0, 10.0, 42.0, + 48.0, 16.0, 56.0, 24.0, 50.0, 18.0, 58.0, 26.0, + 12.0, 44.0, 4.0, 36.0, 14.0, 46.0, 6.0, 38.0, + 60.0, 28.0, 52.0, 20.0, 62.0, 30.0, 54.0, 22.0, + 3.0, 35.0, 11.0, 43.0, 1.0, 33.0, 9.0, 41.0, + 51.0, 19.0, 59.0, 27.0, 49.0, 17.0, 57.0, 25.0, + 15.0, 47.0, 7.0, 39.0, 13.0, 45.0, 5.0, 37.0, + 63.0, 31.0, 55.0, 23.0, 61.0, 29.0, 53.0, 21.0, +); + +fn enc8(v: f32, d: f32) -> u32 { + let y = clamp(v, 0.0, 1.0) * 255.0; + if (y >= 254.9) { + return 255u; + } + return u32(clamp(y + d, 0.0, 255.0)); } // sRGB-curve-encoded value → the output space's own curve (`OutputTrc`: 0 sRGB, 1 gamma, 2 Rec.709). @@ -254,15 +365,6 @@ fn out_encode(v: f32) -> f32 { return 1.099 * pow(l, 0.45) - 0.099; } -// The 3×3 matrix stored row by row from field `o`. -fn mat_at(o: u32) -> array, 3> { - return array, 3>( - vec3(pf(o), pf(o + 1u), pf(o + 2u)), - vec3(pf(o + 3u), pf(o + 4u), pf(o + 5u)), - vec3(pf(o + 6u), pf(o + 7u), pf(o + 8u)), - ); -} - // `finish::gamut_map` (SDR): the chroma scale that brings `r` into 0..1 towards its luminance (1: in gamut) ... fn gamut_scale(r: vec3, luma: vec3) -> f32 { let yy = clamp(dot(luma, r), 0.0, 1.0); @@ -287,13 +389,6 @@ fn gamut_apply(r: vec3, luma: vec3, tg: f32) -> vec3 { return r; } -// `finish::out_of_gamut`: `r` needed desaturating by `t` to fit and isn't just a neutral beyond white or below black. -fn out_of_gamut(r: vec3, t: f32) -> bool { - let lo = min(r.x, min(r.y, r.z)); - let hi = max(r.x, max(r.y, r.z)); - return t < 0.995 && (hi - lo) > 0.02 * max(abs(hi), 1e-3) && hi - lo > 1e-3 && (lo < -1e-3 || (hi > 1.0 && lo < 1.0)); -} - @compute @workgroup_size(16, 16) fn main(@builtin(global_invocation_id) gid: vec3) { let w = pu(F_W); @@ -423,19 +518,28 @@ fn main(@builtin(global_invocation_id) gid: vec3) { delta += cl * 0.85 * det * (0.35 + 0.65 * mid); } let tx = pf(F_TEX) + lt[8]; - let sp = lt[13] * 0.6 + pf(F_SHARPEN); - if ((tx != 0.0 || sp != 0.0) && pu(F_HAS_TEX) != 0u) { + if (tx != 0.0 && pu(F_HAS_TEX) != 0u) { let det = l_pre - tex[i]; let tame = 1.0 - 0.6 * sstep(0.4, 1.6, abs(det)); delta += tx * 1.1 * clamp(det, -1.0, 1.0) * tame; - if (sp != 0.0) { - let sm = pf(F_SHARPEN_MASK); - var mk = 1.0; - if (sm > 0.0) { - mk = sstep(sm * 0.25, sm * 0.25 + 0.15, abs(det)); - } - delta += sp * 1.3 * clamp(det, -0.8, 0.8) * mk; + } + let sp = lt[13] * 0.6 + pf(F_SHARPEN); + if (pu(F_SHARPEN_V3) != 0u && sp != 0.0 && pu(F_HAS_SHP) != 0u) { + let det = l_pre - tex[pu(F_SHP_OFF) + i]; + let sm = pf(F_SHARPEN_MASK); + var mk = 1.0; + if (sm > 0.0) { + mk = sstep(sm * 0.1, sm * 0.1 + 0.06, abs(det)); } + delta += sp * pf(F_SHARPEN_GAIN) * 7.0 * mk * det / (1.0 + abs(det) / pf(F_SHARPEN_LIMIT)); + } else if (pu(F_SHARPEN_V3) == 0u && sp != 0.0 && pu(F_HAS_TEX) != 0u) { + let det = l_pre - tex[i]; + let sm = pf(F_SHARPEN_MASK); + var mk = 1.0; + if (sm > 0.0) { + mk = sstep(sm * 0.25, sm * 0.25 + 0.15, abs(det)); + } + delta += sp * 1.3 * clamp(det, -0.8, 0.8) * mk; } // local Noise: smooth (or, negative, boost) small-amplitude detail, keep edges if (l_noise != 0.0 && pu(F_HAS_TEX) != 0u) { @@ -468,6 +572,11 @@ fn main(@builtin(global_invocation_id) gid: vec3) { d = d + (o - d) * t; } + // --- process V4: calibrated Contrast, Blacks + if (pu(F_LIGHT_OPS) != 0u) { + d = light_ops(d); + } + // --- colour d = color_ops(d, lt[11], lt[12]); if (tint_on) { @@ -558,11 +667,18 @@ fn main(@builtin(global_invocation_id) gid: vec3) { let k = pf(F_GRAIN_AMT) * g * (0.35 + 2.6 * lum * (1.0 - lum)); e = e + k; } + if (pu(F_LUT) != 0u) { + let m = lut_apply(clamp(e, vec3(0.0), vec3(1.0))); + e = e + (m - e) * pf(F_LUT_AMT); + } if (warn == 1u) { - e = vec3(1.0, 0.0, 0.0); + e = vec3(PROOF_DEST_R, PROOF_DEST_G, PROOF_DEST_B); } else if (warn == 2u) { - e = vec3(0.0, 0.25, 1.0); + e = vec3(PROOF_DISP_R, PROOF_DISP_G, PROOF_DISP_B); } e = vec3(out_encode(e.x), out_encode(e.y), out_encode(e.z)); - out[i] = enc8(e.x) | (enc8(e.y) << 8u) | (enc8(e.z) << 16u) | (255u << 24u); + let abs_x = u32(pf(F_VIG_VIEW)) + x; + let abs_y = u32(pf(F_VIG_VIEW + 1u)) + y; + let dither = (BAYER_8X8[(abs_y & 7u) * 8u + (abs_x & 7u)] + 0.5) / 64.0; + out[i] = enc8(e.x, dither) | (enc8(e.y, dither) << 8u) | (enc8(e.z, dither) << 16u) | (255u << 24u); } diff --git a/crates/gpu/src/wgsl/gauss.wgsl b/crates/gpu/src/wgsl/gauss.wgsl new file mode 100644 index 0000000000..a3ad4e7234 --- /dev/null +++ b/crates/gpu/src/wgsl/gauss.wgsl @@ -0,0 +1,36 @@ +// Exact separable Gaussian with explicit taps over a one-channel plane (clamped edges); mirrors +// `lightcraft_raster::blur::gaussian_taps` (same taps, same accumulation order). +// P: w, h, r (taps has 2r+1 entries). Bindings: src, taps, dst. + +@compute @workgroup_size(16, 16) +fn gauss_h(@builtin(global_invocation_id) g: vec3) { + let w = pu(0u); + let h = pu(1u); + let r = i32(pu(2u)); + if (g.x >= w || g.y >= h) { + return; + } + let last = i32(w) - 1; + let row = g.y * w; + var acc = 0.0; + for (var k = 0; k <= 2 * r; k++) { + acc += src[row + u32(clamp(i32(g.x) + k - r, 0, last))] * taps[u32(k)]; + } + dst[row + g.x] = acc; +} + +@compute @workgroup_size(16, 16) +fn gauss_v(@builtin(global_invocation_id) g: vec3) { + let w = pu(0u); + let h = pu(1u); + let r = i32(pu(2u)); + if (g.x >= w || g.y >= h) { + return; + } + let last = i32(h) - 1; + var acc = 0.0; + for (var k = 0; k <= 2 * r; k++) { + acc += src[u32(clamp(i32(g.y) + k - r, 0, last)) * w + g.x] * taps[u32(k)]; + } + dst[g.y * w + g.x] = acc; +} diff --git a/crates/gpu/src/wgsl/hist.wgsl b/crates/gpu/src/wgsl/hist.wgsl new file mode 100644 index 0000000000..19d0a1a8e2 --- /dev/null +++ b/crates/gpu/src/wgsl/hist.wgsl @@ -0,0 +1,24 @@ +// The histogram (`Histogram::of_srgb8`) of a region of the packed RGBA8 output, on the same +// sampling grid: every STEP-th pixel of every STEP-th row. Bindings: px (packed RGBA8), bins +// (r | g | b | luma, 256 each, then the total; cleared beforehand). +// P: W (image width), X0, Y0 (region origin), NX, NY (sampled columns / rows), STEP. + +@compute @workgroup_size(16, 16) +fn histogram(@builtin(global_invocation_id) g: vec3) { + if (g.x >= pu(3u) || g.y >= pu(4u)) { + return; + } + let step = pu(5u); + let x = pu(1u) + g.x * step; + let y = pu(2u) + g.y * step; + let p = px[y * pu(0u) + x]; + let r = p & 255u; + let gg = (p >> 8u) & 255u; + let b = (p >> 16u) & 255u; + atomicAdd(&bins[r], 1u); + atomicAdd(&bins[256u + gg], 1u); + atomicAdd(&bins[512u + b], 1u); + let l = min((r * 54u + gg * 183u + b * 19u) >> 8u, 255u); + atomicAdd(&bins[768u + l], 1u); + atomicAdd(&bins[1024u], 1u); +} diff --git a/crates/gpu/src/wgsl/map.wgsl b/crates/gpu/src/wgsl/map.wgsl index fc8eebecfe..9b84b8d89d 100644 --- a/crates/gpu/src/wgsl/map.wgsl +++ b/crates/gpu/src/wgsl/map.wgsl @@ -105,14 +105,20 @@ fn xguided_ab(@builtin(global_invocation_id) g: vec3, @builtin(num_workgrou dst[2u * i + 1u] = mp - k * mi; } -// `max(p, clamp(a·guide + b, 0, 1))` (a: guide, b: blurred coefficients, c: the input p). +// q = clamp(a·guide + b, 0, 1) (a: guide, b: blurred coefficients, c: the input p), then +// P[1] = 0: max(p, q) (Auto Mask strokes); 1: p + (q − p)·P[2] (Refine Edges). @compute @workgroup_size(256) fn xguided_apply(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { let i = lin_index(g, nw); if (i >= pu(0u)) { return; } - dst[i] = max(c[i], clamp(b[2u * i] * a[i] + b[2u * i + 1u], 0.0, 1.0)); + let q = clamp(b[2u * i] * a[i] + b[2u * i + 1u], 0.0, 1.0); + if (pu(1u) == 0u) { + dst[i] = max(c[i], q); + } else { + dst[i] = c[i] + (q - c[i]) * pf(2u); + } } // White balance: 3×3 matrix (P[1] = has matrix, P[2..11] row-major), clamped at 0. @@ -226,3 +232,53 @@ fn redeye_k(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups } put_rgb(i, c); } + +// Defringe, first step (`optics::defringe`): OkLab of the clamped colour (a: image) → dst +// (lightness, a, b interleaved). +@compute @workgroup_size(256) +fn fringe_lab(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + put_rgb(i, oklab(max(rgb_a(i), vec3(0.0)))); +} + +// `optics::hue_weight`: membership of hue h (deg) in [lo, hi] with 8° shoulders. +fn hue_weight(h: f32, lo: f32, hi: f32) -> f32 { + let mid = (lo + hi) / 2.0; + let half = (hi - lo) / 2.0; + var d = abs(h - mid) % 360.0; + if (d > 180.0) { + d = 360.0 - d; + } + return 1.0 - sstep(half, half + 8.0, d); +} + +// Defringe, last step: desaturate fringe colours at edges (a: OkLab, b / c: lightness min / max +// around each pixel; dst: the image, written only where it changes, so it starts as a copy). +// P[1..7] = purple lo, hi, green lo, hi, purple strength, green strength. +@compute @workgroup_size(256) +fn fringe_apply(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + let edge = sstep(0.08, 0.25, c[i] - b[i]); + if (edge <= 0.0) { + return; + } + let lab = rgb_a(i); + let ch = sqrt(lab.y * lab.y + lab.z * lab.z); + let chroma_w = sstep(0.015, 0.05, ch); + if (chroma_w <= 0.0) { + return; + } + let hue = rem_euclid(degrees(atan2(lab.z, lab.y)), 360.0); + let k = max(pf(5u) * hue_weight(hue, pf(1u), pf(2u)), pf(6u) * hue_weight(hue, pf(3u), pf(4u))) * edge * chroma_w; + if (k <= 0.0) { + return; + } + let f = 1.0 - min(k, 1.0); + put_rgb(i, max(oklab_inv(vec3(lab.x, lab.y * f, lab.z * f)), vec3(0.0))); +} diff --git a/crates/gpu/src/wgsl/present.wgsl b/crates/gpu/src/wgsl/present.wgsl new file mode 100644 index 0000000000..6d586c7fad --- /dev/null +++ b/crates/gpu/src/wgsl/present.wgsl @@ -0,0 +1,24 @@ +// Handing a finished render to the window without a readback (`render::present`). +// Bindings: px (packed RGBA8 output), dst (packed RGBA8, padded rows), count (one atomic word). + +// Pixels whose alpha is not 255: work that never ran (the readback's `unwritten`). P[0] = pixels. +@compute @workgroup_size(256) +fn unwritten(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + if ((px[i] >> 24u) != 255u) { + atomicAdd(&count[0], 1u); + } +} + +// Rows of P[0] pixels (P[1] rows) re-laid at a stride of P[2] pixels (texture copies take rows of a +// multiple of 256 bytes). +@compute @workgroup_size(16, 16) +fn pad_rows(@builtin(global_invocation_id) g: vec3) { + if (g.x >= pu(0u) || g.y >= pu(1u)) { + return; + } + dst[g.y * pu(2u) + g.x] = px[g.y * pu(0u) + g.x]; +} diff --git a/crates/gpu/src/wgsl/spot.wgsl b/crates/gpu/src/wgsl/spot.wgsl new file mode 100644 index 0000000000..8151d1d5e9 --- /dev/null +++ b/crates/gpu/src/wgsl/spot.wgsl @@ -0,0 +1,177 @@ +// Spot removal (`lightcraft_pipeline::spots::apply`), one spot at a time, on the image in place. +// Bindings: img (rgb, read-write), pts (f32 data: see each kernel), al / sp / df / wt (work buffers +// over the spot's box: alpha, source patch, masked difference, weights). +// +// Parameters of spot_prep / spot_apply: W, H, BX, BY, BW, BH, NPTS, R, INNER, OPACITY, OFFX, OFFY, +// HEAL. `pts`: the stroke's points (x, y; output pixels). + +// `f32::MAX` exactly ("doesn't fit", as the CPU's score; a decimal literal may round below it, +// and naga can't evaluate bitcast in a const). +fn f32_max() -> f32 { + return bitcast(0x7f7fffffu); +} + +// `Rgb32f::get_clamped`. +fn px_at(x: i32, y: i32) -> vec3 { + let w = i32(pu(0u)); + let h = i32(pu(1u)); + let i = u32(clamp(y, 0, h - 1) * w + clamp(x, 0, w - 1)); + return vec3(img[3u * i], img[3u * i + 1u], img[3u * i + 2u]); +} + +// `Rgb32f::sample_bilinear` (pixel centres at +0.5). +fn bilinear(x: f32, y: f32) -> vec3 { + let fx = x - 0.5; + let fy = y - 0.5; + let x0 = floor(fx); + let y0 = floor(fy); + let tx = fx - x0; + let ty = fy - y0; + let ix = i32(x0); + let iy = i32(y0); + let a = px_at(ix, iy); + let b = px_at(ix + 1, iy); + let c = px_at(ix, iy + 1); + let d = px_at(ix + 1, iy + 1); + let top = a + (b - a) * tx; + let bot = c + (d - c) * tx; + return top + (bot - top) * ty; +} + +// `spots::smooth`, defined for e1 ≤ e0 as the step at e1 (no feather). +fn spot_smooth(e0: f32, e1: f32, x: f32) -> f32 { + if (e1 <= e0) { + return select(0.0, 1.0, x >= e1); + } + return sstep(e0, e1, x); +} + +// Alpha, source patch and (Heal) the difference outside the stroke, over the box. +@compute @workgroup_size(16, 16) +fn spot_prep(@builtin(global_invocation_id) gid: vec3) { + let bw = pu(4u); + let bh = pu(5u); + if (gid.x >= bw || gid.y >= bh) { + return; + } + let i = gid.y * bw + gid.x; + let gx = pu(2u) + gid.x; + let gy = pu(3u) + gid.y; + let px = f32(gx) + 0.5; + let py = f32(gy) + 0.5; + var d = f32_max(); + for (var k = 0u; k < pu(6u); k++) { + let ex = px - pts[2u * k]; + let ey = py - pts[2u * k + 1u]; + d = min(d, sqrt(ex * ex + ey * ey)); + } + let alpha = (1.0 - spot_smooth(pf(8u), pf(7u), d)) * pf(9u); + al[i] = alpha; + let s = bilinear(px + pf(10u), py + pf(11u)); + sp[3u * i] = s.x; + sp[3u * i + 1u] = s.y; + sp[3u * i + 2u] = s.z; + let gi = gy * pu(0u) + gx; + let t = vec3(img[3u * gi], img[3u * gi + 1u], img[3u * gi + 2u]); + let outside = select(0.0, 1.0, alpha < 0.02); + let m = (t - s) * outside; + df[3u * i] = m.x; + df[3u * i + 1u] = m.y; + df[3u * i + 2u] = m.z; + wt[i] = outside; +} + +// Blend the (healed) patch into the image (df, wt: the blurred difference and weights). +@compute @workgroup_size(16, 16) +fn spot_apply(@builtin(global_invocation_id) gid: vec3) { + let bw = pu(4u); + let bh = pu(5u); + if (gid.x >= bw || gid.y >= bh) { + return; + } + let i = gid.y * bw + gid.x; + let a = al[i]; + if (a <= 0.0) { + return; + } + var v = vec3(sp[3u * i], sp[3u * i + 1u], sp[3u * i + 2u]); + if (pu(12u) != 0u) { + let m = max(wt[i], 1e-4); + v = v + vec3(df[3u * i] / m, df[3u * i + 1u] / m, df[3u * i + 2u] / m); + } + let gi = (pu(3u) + gid.y) * pu(0u) + pu(2u) + gid.x; + let t = vec3(img[3u * gi], img[3u * gi + 1u], img[3u * gi + 2u]); + let o = max(t + (v - t) * a, vec3(0.0)); + img[3u * gi] = o.x; + img[3u * gi + 1u] = o.y; + img[3u * gi + 2u] = o.z; +} + +// `spots::ring_stats`: sample k (spoke-major, 3 radii each) of the rings around c, or a NaN-free +// flag in .w = 0 when it falls outside the image. +fn ring_sample(c: vec2, k: u32, radii: u32) -> vec4 { + let spoke = k / 3u; + let rr = pf(radii + k % 3u); + let o = 2u * NCAND + 2u * spoke; + let x = c.x + pts[o] * rr; + let y = c.y + pts[o + 1u] * rr; + if (x < 0.0 || y < 0.0 || x >= f32(pu(0u)) || y >= f32(pu(1u))) { + return vec4(0.0); + } + return vec4(bilinear(x, y), 1.0); +} + +fn ring_fits(c: vec2, radii: u32) -> bool { + for (var k = 0u; k < 72u; k++) { + if (ring_sample(c, k, radii).w == 0.0) { + return false; + } + } + return true; +} + +fn sq(v: f32) -> f32 { + return sqrt(max(v, 0.0)); +} + +// `spots::score` of every candidate source (one invocation each) into `al`. +// Parameters: W, H, TX, TY, then the surroundings' radii (3) and the inside's (3). +// `pts`: NCAND candidate offsets (x, y), then the 24 spoke directions (cos, sin). +@compute @workgroup_size(64) +fn spot_score(@builtin(global_invocation_id) gid: vec3) { + let j = gid.x; + if (j >= NCAND) { + return; + } + let tgt = vec2(pf(2u), pf(3u)); + let src = tgt + vec2(pts[2u * j], pts[2u * j + 1u]); + if (!ring_fits(tgt, 4u) || !ring_fits(src, 4u)) { + al[j] = f32_max(); + return; + } + var s = 0.0; + for (var k = 0u; k < 72u; k++) { + let p = ring_sample(tgt, k, 4u).xyz; + let q = ring_sample(src, k, 4u).xyz; + for (var c = 0u; c < 3u; c++) { + let u = sq(p[c]); + let v = sq(q[c]); + s += (u - v) * (u - v); + } + } + if (ring_fits(src, 7u)) { + var mean_a = 0.0; + for (var k = 0u; k < 72u; k++) { + mean_a += sq(ring_sample(tgt, k, 4u).y); + } + mean_a = mean_a / 72.0; + var var_ = 0.0; + for (var k = 0u; k < 72u; k++) { + let e = sq(ring_sample(src, k, 7u).y) - mean_a; + var_ += e * e; + } + var_ = var_ / 72.0; + s += var_ * 72.0 * 0.5; + } + al[j] = s; +} diff --git a/crates/gpu/tests/display.rs b/crates/gpu/tests/display.rs new file mode 100644 index 0000000000..525743b9fb --- /dev/null +++ b/crates/gpu/tests/display.rs @@ -0,0 +1,80 @@ +//! Renders handed to the window as textures (`render_display` on an adopted device): the texture +//! holds exactly the pixels a readback render returns, the histogram matches, and what can't be a +//! texture (overlays, a window grown by spots) comes back as pixels. Own process: adopting a +//! device is once per process. Skips (passes with a note) without an adapter. + +use std::sync::Arc; + +use lightcraft_develop::{DevelopSettings, Spot}; +use lightcraft_geom::Point; +use lightcraft_gpu::{Output, wgpu}; +use lightcraft_pipeline::{Overlay, PixelWindow, Quality, RenderRequest, SourceInfo, StageCache}; + +/// A device made the way eframe makes the window's (adapter limits, the window's backends). +fn window_device() -> Option<(wgpu::Device, wgpu::Queue, wgpu::AdapterInfo)> { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = lightcraft_gpu::backend::window_backends(); + desc.backend_options = lightcraft_gpu::backend::backend_options(); + let instance = wgpu::Instance::new(desc); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; + let info = adapter.get_info(); + let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + label: Some("test window"), + required_limits: adapter.limits(), + ..Default::default() + })) + .ok()?; + Some((device, queue, info)) +} + +#[test] +fn display_renders_match_readback_renders() { + // switched off for the process (`LIGHTCRAFT_GPU=0`): there is no device to adopt + if let Some(reason) = lightcraft_gpu::env_off_reason() { + lightcraft_testkit::skip!(Gpu, "{reason}"); + return; + } + let Some((device, queue, info)) = window_device() else { + lightcraft_testkit::skip!(Gpu, "no GPU adapter"); + return; + }; + if info.device_type == wgpu::DeviceType::Cpu { + lightcraft_testkit::skip!(Gpu, "software adapter"); + return; + } + lightcraft_gpu::adopt_window_device(device.clone(), queue.clone(), info).expect("adopted"); + assert!(lightcraft_gpu::on_window_device()); + let raw = SourceInfo { raw: true, ..Default::default() }; + let mut s = DevelopSettings::default(); + s.light.exposure = 0.5; + s.light.highlights = -40.0; + s.effects.clarity = 20.0; + s.detail.nr_luminance = 20.0; + s.grain.amount = 20.0; + // widths that are and aren't a multiple of 64 texels (row padding), draft and full quality + for (w, h, quality) in [(640, 427, Quality::Full), (1000, 667, Quality::Draft), (1024, 683, Quality::Full)] { + let src = Arc::new(lightcraft_scenes::demo_library()[0].render(w, h)); + let req = RenderRequest { quality, ..RenderRequest::fit(w, h) }; + let stages = StageCache::default(); + let pixels = lightcraft_gpu::render(&src, &raw, &s, &req, Some(&stages)).expect("gpu render"); + match lightcraft_gpu::render_display(&src, &raw, &s, &req, Some(&stages)).expect("display render") { + Output::Display { frame, histogram } => { + assert_eq!((frame.width, frame.height), (pixels.image.width, pixels.image.height)); + let shown = lightcraft_gpu::read_texture(&device, &queue, &frame.texture, frame.width, frame.height).expect("readback"); + assert!(shown.data == pixels.image.data, "{w}×{h}: the texture holds the readback's pixels"); + assert_eq!(histogram, pixels.histogram); + } + Output::Image(_) => panic!("{w}×{h}: expected a texture"), + } + } + // overlays are drawn on the CPU, and a window that spots grew is cut there: pixels + let src = Arc::new(lightcraft_scenes::demo_library()[0].render(3000, 2000)); + let req = RenderRequest { overlay: Overlay::Spots(50), ..RenderRequest::fit(800, 800) }; + assert!(matches!(lightcraft_gpu::render_display(&src, &raw, &s, &req, None), Some(Output::Image(_))), "overlay"); + s.spots = vec![Spot { points: vec![Point::new(0.5, 0.5)], size: 0.02, source_offset: Some(Point::new(0.15, 0.0)), ..Default::default() }]; + let req = RenderRequest { window: Some(PixelWindow { x: 1200, y: 800, w: 500, h: 400 }), ..RenderRequest::fit(3000, 2000) }; + match lightcraft_gpu::render_display(&src, &raw, &s, &req, None) { + Some(Output::Image(r)) => assert_eq!((r.image.width, r.image.height), (500, 400)), + _ => panic!("a grown window comes back as pixels"), + } +} diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 6a1a8464c4..7a21768de1 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -20,11 +20,58 @@ const MAX_LSB: u8 = 3; fn gpu() -> bool { let ok = lightcraft_gpu::available(); if !ok { + let why = lightcraft_gpu::unavailable_reason().unwrap_or_default(); + // no adapter (CI) skips; an adapter whose kernels don't build is a bug in them + assert!(!why.contains("kernels failed to build"), "{why}"); lightcraft_testkit::skip!(Gpu, "no GPU adapter"); } + // which card the comparisons ran on (`LIGHTCRAFT_GPU_ADAPTER` picks one on a machine with two) + static NAMED: std::sync::Once = std::sync::Once::new(); + NAMED.call_once(|| eprintln!("GPU equivalence tests on {}", lightcraft_gpu::adapter_name().unwrap_or_default())); ok } +fn check_v3_luminance_cutoff(chroma: f32, pixel: [f32; 3], expected: [u8; 4]) { + if !gpu() { + return; + } + // These uniform nonnegative sources expose cancellation after camera chroma scaling + // and Contrast, just below the positive Blacks luminance cutoff. + let curve = lightcraft_pipeline::tone::CameraTone::new(std::array::from_fn(|i| { + let x = (i + 1) as f32 / 33.0; + [x, x] + })) + .unwrap() + .with_chroma([chroma; 8]) + .unwrap(); + let info = SourceInfo { raw: true, camera_tone: Some(curve), ..Default::default() }; + let src = Arc::new(Rgb32f::filled(64, 64, pixel)); + let mut s = DevelopSettings { process: Process::V4.version(), ..Default::default() }; + s.light.contrast = 100.0; + s.light.blacks = 80.0; + let req = RenderRequest::fit(64, 64); + let cpu = render(&src, &info, &s, &req).image; + let gpu = lightcraft_gpu::try_render(&src, &info, &s, &req, None).expect("GPU render without CPU fallback").image; + for image in [&cpu, &gpu] { + assert!(image.data.iter().all(|p| *p == image.data[0])); + for (actual, expected) in image.data[0].into_iter().zip(expected) { + assert!(actual.abs_diff(expected) <= 1, "chroma {chroma}: {:?}, expected {expected}", image.data[0]); + } + } + let (_, max, _) = diff(&cpu, &gpu); + assert!(max <= 1, "chroma {chroma}: CPU {:?}, GPU {:?}", cpu.data[0], gpu.data[0]); +} + +#[test] +fn v3_luminance_cutoff_chroma_2() { + check_v3_luminance_cutoff(2.0, [0.023_433_316, 0.000_071_107_73, 0.005_175_675], [27, 0, 8, 255]); +} + +#[test] +fn v3_luminance_cutoff_chroma_4() { + check_v3_luminance_cutoff(4.0, [0.035_338_085, 0.000_048_468_723, 0.010_193_758], [47, 0, 19, 255]); +} + #[test] fn camera_tone_and_relative_wb() { if !gpu() { @@ -236,6 +283,33 @@ fn cases() -> Vec<(&'static str, Edit)> { s.effects.clarity = -60.0; s.effects.texture = -40.0; }), + ("sharpen radius 2.5 detail 100", |s| { + s.detail.sharpen_amount = 100.0; + s.detail.sharpen_radius = 2.5; + s.detail.sharpen_detail = 100.0; + }), + ("sharpen radius 0.6 detail 0", |s| { + s.detail.sharpen_amount = 80.0; + s.detail.sharpen_radius = 0.6; + s.detail.sharpen_detail = 0.0; + }), + ("sharpen + texture + masking", |s| { + s.detail.sharpen_amount = 70.0; + s.detail.sharpen_masking = 30.0; + s.effects.texture = 40.0; + }), + ("local sharpness", |s| { + s.masks = vec![Mask { + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Linear { start: Point::new(0.5, 0.0), end: Point::new(0.5, 0.6) }, + }], + adjust: lightcraft_develop::LocalAdjustments { sharpness: 80.0, ..Default::default() }, + ..Default::default() + }]; + }), ("sharpen masking", |s| { s.detail.sharpen_amount = 90.0; s.detail.sharpen_masking = 60.0; @@ -417,7 +491,7 @@ fn cases() -> Vec<(&'static str, Edit)> { s.calibration.blue_sat = 60.0; s.calibration.blue_hue = 25.0; }), - ("spots + defringe (cpu stage)", |s| { + ("spots + defringe", |s| { s.spots = vec![Spot { points: vec![Point::new(0.3, 0.3)], size: 0.03, source_offset: Some(Point::new(0.1, 0.0)), ..Default::default() }]; s.optics.defringe_purple_amount = 5.0; }), @@ -582,6 +656,7 @@ fn embedded_lens_perspective_edges_match() { }), vignette: Some(EmbeddedVignette { k: [0.4, -0.1, 0.02, 0.0, 0.0], center: Point::new(0.5, 0.5), radius: 0.6 }), stages: Default::default(), + source: Default::default(), }; let info = SourceInfo { lens: Some(lens), ..raw }; let mut s = DevelopSettings::default(); @@ -615,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. @@ -647,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"); @@ -657,6 +793,30 @@ fn highlights_shadows_base_matches_on_every_process() { } } +#[test] +fn sharpening_matches_each_process_and_reduced_source() { + if !gpu() { + return; + } + let src = scene(0, 256, 192); + let info = SourceInfo { raw: true, native_long: Some(1024), ..Default::default() }; + let req = RenderRequest::fit(128, 128); + let cache = StageCache::default(); + for process in [Process::V1, Process::V2, Process::V3, Process::V2, Process::V3] { + let mut s = DevelopSettings { process: process.version(), ..Default::default() }; + s.detail.sharpen_amount = 80.0; + s.detail.sharpen_radius = 2.0; + s.detail.sharpen_detail = 75.0; + for nr in [0.0, 50.0, 20.0] { + s.detail.nr_luminance = nr; + check(&format!("{process:?} sharpening NR {nr}"), &src, &info, &s, &req); + let warm = lightcraft_gpu::render(&src, &info, &s, &req, Some(&cache)).expect("gpu"); + let fresh = lightcraft_gpu::render(&src, &info, &s, &req, None).expect("gpu"); + assert_eq!(warm.image, fresh.image, "{process:?} NR {nr}"); + } + } +} + #[test] fn overlays_match() { if !gpu() { @@ -796,7 +956,7 @@ fn red_eye_matches() { spots: vec![Spot { points: vec![Point::new(0.1, 0.2)], size: 0.02, source_offset: Some(Point::new(0.05, 0.0)), ..Default::default() }], ..Default::default() }; - check("red eye + spot (cpu stage)", &src, &info, &s, &RenderRequest::fit(600, 600)); + check("red eye + spot", &src, &info, &s, &RenderRequest::fit(600, 600)); } fn saturated(s: &mut DevelopSettings) { @@ -955,6 +1115,89 @@ fn windows_of_a_big_photo_share_one_uploaded_source() { assert_eq!(lightcraft_gpu::source_uploads() - start, 2); } +/// A non-trivial 3D LUT (cross-process look: lifted blacks, warm highlights, swapped-ish blues). +fn look_lut(n: usize, domain_max: f32) -> lightcraft_pipeline::lut::Lut3d { + let mut data = Vec::with_capacity(n * n * n); + for b in 0..n { + for g in 0..n { + for r in 0..n { + let c = [r, g, b].map(|v| v as f32 / (n - 1) as f32 * domain_max); + data.push([ + (0.06 + 0.9 * c[0].powf(0.9) + 0.05 * c[2]).min(1.0), + (0.04 + 0.92 * c[1] * (1.0 - 0.1 * c[2])).min(1.0), + (0.1 + 0.6 * c[2] + 0.2 * c[0] * c[1]).min(1.0), + ]); + } + } + } + lightcraft_pipeline::lut::Lut3d { size: n, data, domain_min: [0.0; 3], domain_max: [domain_max; 3], title: None } +} + +/// LUT profiles render on the GPU (the table is applied after grain, blended by the amount). +#[test] +fn lut_profiles_match() { + if !gpu() { + return; + } + let src = scene(1, 900, 600); + let raw = SourceInfo { raw: true, ..Default::default() }; + lightcraft_pipeline::lut::register("lut:gpu-test-17", look_lut(17, 1.0)); + lightcraft_pipeline::lut::register("lut:gpu-test-domain", look_lut(9, 1.2)); + for (id, amount) in [("lut:gpu-test-17", 100.0), ("lut:gpu-test-17", 160.0), ("lut:gpu-test-domain", 60.0)] { + for (name, edit) in [("default", (|_| {}) as Edit), ("saturated + curves + grain", saturated as Edit)] { + let mut s = DevelopSettings::default(); + edit(&mut s); + s.profile.id = id.into(); + s.profile.amount = amount; + check(&format!("{id} {amount} {name}"), &src, &raw, &s, &RenderRequest::fit(640, 640)); + } + } +} + +/// Refine Edges on a mask is the cross guided filter on the device, blended by √refine. +#[test] +fn refine_edges_match() { + if !gpu() { + return; + } + let src = scene(0, 900, 600); + let raw = SourceInfo { raw: true, ..Default::default() }; + for refine in [15.0, 60.0, 100.0] { + let mut s = DevelopSettings::default(); + typical(&mut s); + s.masks = vec![ + Mask { + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Radial { center: Point::new(0.45, 0.55), rx: 0.3, ry: 0.2, angle: 10.0, feather: 30.0, invert: false }, + }], + adjust: lightcraft_develop::LocalAdjustments { exposure: 0.9, saturation: -30.0, ..Default::default() }, + refine, + ..Default::default() + }, + Mask { + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Linear { start: Point::new(0.5, 0.0), end: Point::new(0.5, 0.5) }, + }], + adjust: lightcraft_develop::LocalAdjustments { exposure: -0.7, amount: 70.0, ..Default::default() }, + refine: refine / 2.0, + invert: true, + ..Default::default() + }, + ]; + check(&format!("refine edges {refine}"), &src, &raw, &s, &RenderRequest::fit(640, 640)); + let gpu = |s: &DevelopSettings| lightcraft_gpu::render(&src, &raw, s, &RenderRequest::fit(640, 640), None).expect("gpu render").image; + let unrefined = DevelopSettings { masks: s.masks.iter().map(|m| Mask { refine: 0.0, ..m.clone() }).collect(), ..s.clone() }; + // (a light refine barely moves a soft radial edge; a strong one visibly does) + assert!(refine < 50.0 || diff(&gpu(&s), &gpu(&unrefined)).1 > 3, "refine {refine} changes the mask"); + } +} + #[test] fn soft_proofs_match() { if !gpu() { @@ -1005,3 +1248,96 @@ fn soft_proofs_match() { }; assert!(lightcraft_gpu::render(&src, &raw, &DevelopSettings::default(), &req, None).is_none(), "declined: the CPU renders it"); } + +/// Spot removal on the device: Clone, Heal and Remove (automatic source, scored on the device), +/// brushed strokes, overlapping spots (each reads what the earlier ones left), feather 0 and +/// spots cut by the image edge. +#[test] +fn spots_match() { + if !gpu() { + return; + } + use lightcraft_develop::SpotMode; + let src = scene(3, 900, 600); + let raw = SourceInfo { raw: true, ..Default::default() }; + let spot = |mode, pts: &[(f64, f64)], size, feather, off: Option<(f64, f64)>| Spot { + mode, + points: pts.iter().map(|p| Point::new(p.0, p.1)).collect(), + size, + feather, + opacity: 100.0, + source_offset: off.map(|o| Point::new(o.0, o.1)), + }; + let sets: Vec<(&str, Vec)> = vec![ + ("clone", vec![spot(SpotMode::Clone, &[(0.3, 0.4)], 0.04, 40.0, Some((0.15, 0.05)))]), + ("heal", vec![spot(SpotMode::Heal, &[(0.6, 0.5)], 0.05, 60.0, Some((-0.12, 0.1)))]), + ("remove (auto source)", vec![spot(SpotMode::Remove, &[(0.5, 0.45)], 0.03, 50.0, None)]), + ("remove near the edge (auto)", vec![spot(SpotMode::Remove, &[(0.04, 0.5)], 0.03, 50.0, None)]), + ("brushed heal stroke", vec![spot(SpotMode::Heal, &[(0.2, 0.7), (0.3, 0.72), (0.4, 0.69)], 0.02, 30.0, Some((0.0, -0.15)))]), + ("feather 0, half opacity", vec![Spot { opacity: 50.0, ..spot(SpotMode::Clone, &[(0.7, 0.3)], 0.04, 0.0, Some((-0.2, 0.0))) }]), + ("cut by the edge", vec![spot(SpotMode::Heal, &[(0.99, 0.02)], 0.05, 50.0, Some((-0.2, 0.2)))]), + ( + "overlapping, auto after manual", + vec![ + spot(SpotMode::Clone, &[(0.45, 0.5)], 0.04, 50.0, Some((0.1, 0.0))), + spot(SpotMode::Remove, &[(0.47, 0.52)], 0.04, 50.0, None), + spot(SpotMode::Heal, &[(0.5, 0.5)], 0.03, 70.0, Some((0.0, 0.12))), + ], + ), + ]; + for (name, spots) in sets { + let mut s = DevelopSettings::default(); + typical(&mut s); + s.spots = spots; + check(&format!("spots: {name}"), &src, &raw, &s, &RenderRequest::fit(640, 640)); + } +} + +/// Defringe on the device: purple and green at several amounts and hue ranges, at preview and +/// full size (its filter radius follows the output size). +#[test] +fn defringe_matches() { + if !gpu() { + return; + } + let src = scene(1, 1800, 1200); + let raw = SourceInfo { raw: true, ..Default::default() }; + for (purple, green, hue) in [(4.0, 0.0, (30.0, 70.0)), (0.0, 10.0, (20.0, 80.0)), (20.0, 15.0, (0.0, 100.0))] { + let mut s = DevelopSettings::default(); + typical(&mut s); + s.color.saturation = 40.0; + s.optics.defringe_purple_amount = purple; + s.optics.defringe_green_amount = green; + s.optics.defringe_purple_hue_lo = hue.0; + s.optics.defringe_purple_hue_hi = hue.1; + s.optics.defringe_green_hue_lo = hue.0; + s.optics.defringe_green_hue_hi = hue.1; + for edge in [640, 1800] { + check(&format!("defringe {purple}/{green} {hue:?} @{edge}"), &src, &raw, &s, &RenderRequest::fit(edge, edge)); + } + } +} + +/// The histogram counted on the device is exactly the CPU's count of the image the GPU returned, +/// for whole frames (small and over 1 MP, where it samples) and for windows cut back after spots. +#[test] +fn device_histogram_is_exact() { + if !gpu() { + return; + } + let raw = SourceInfo { raw: true, ..Default::default() }; + let mut s = DevelopSettings::default(); + typical(&mut s); + for (w, h) in [(640, 427), (2400, 1600)] { + let src = scene(0, w, h); + let r = lightcraft_gpu::render(&src, &raw, &s, &RenderRequest::fit(w, h), None).expect("gpu render"); + assert_eq!(r.histogram, lightcraft_raster::Histogram::of_srgb8(&r.image), "{w}x{h}"); + } + // a window with a spot reading from outside it: the render grows, the histogram is of the cut + let src = scene(0, 3000, 2000); + s.spots = vec![Spot { points: vec![Point::new(0.5, 0.5)], size: 0.02, source_offset: Some(Point::new(0.15, 0.0)), ..Default::default() }]; + let req = RenderRequest { window: Some(lightcraft_pipeline::PixelWindow { x: 1200, y: 800, w: 500, h: 400 }), ..RenderRequest::fit(3000, 2000) }; + let r = lightcraft_gpu::render(&src, &raw, &s, &req, None).expect("gpu render"); + assert_eq!((r.image.width, r.image.height), (500, 400)); + assert_eq!(r.histogram, lightcraft_raster::Histogram::of_srgb8(&r.image), "window"); +} diff --git a/crates/gpu/tests/it/main.rs b/crates/gpu/tests/it/main.rs index d26d1efc94..1803370213 100644 --- a/crates/gpu/tests/it/main.rs +++ b/crates/gpu/tests/it/main.rs @@ -1,9 +1,11 @@ //! The integration tests, one module per file, linked into one test binary. //! Binaries of their own: `tests/shutdown.rs` and `tests/shutdown_first.rs` close the GPU for the whole -//! process, and `tests/memory.rs` checks the process's device-memory counters, which renders on other test -//! threads would change. +//! process, `tests/memory.rs` checks the process's device-memory counters, which renders on other test +//! threads would change, and `tests/display.rs` and `tests/window_pending.rs` adopt (or wait for) the +//! window's device, once per process. mod equivalence; mod fallback; #[cfg(not(target_arch = "wasm32"))] mod gpu_probe; +mod thumbs_bench; diff --git a/crates/gpu/tests/it/thumbs_bench.rs b/crates/gpu/tests/it/thumbs_bench.rs new file mode 100644 index 0000000000..e3ee63c284 --- /dev/null +++ b/crates/gpu/tests/it/thumbs_bench.rs @@ -0,0 +1,72 @@ +//! Thumbnail throughput, CPU vs GPU: `cargo test --release -p lightcraft-gpu --test it thumbs_bench -- --ignored --nocapture`. +//! Six threads (the app's render workers) each render thumbnails of 512 px sources at 256 px with +//! settings like a typical preset (noise reduction, sharpening, clarity, grading, a gradient mask). + +use std::sync::Arc; +use std::time::Instant; + +use lightcraft_develop::{DevelopSettings, Mask, MaskComponent, MaskOp, MaskShape}; +use lightcraft_geom::Point; +use lightcraft_pipeline::{RenderRequest, SourceInfo}; + +fn preset_like() -> DevelopSettings { + let mut s = DevelopSettings::default(); + s.light.exposure = 0.4; + s.light.contrast = 20.0; + s.light.highlights = -60.0; + s.light.shadows = 50.0; + s.effects.clarity = 15.0; + s.detail.nr_luminance = 16.0; + s.detail.sharpen_amount = 60.0; + s.color.vibrance = 15.0; + s.grading.shadows.hue = 220.0; + s.grading.shadows.sat = 30.0; + s.masks = vec![Mask { + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Linear { start: Point::new(0.5, 0.0), end: Point::new(0.5, 0.5) }, + }], + adjust: lightcraft_develop::LocalAdjustments { exposure: -0.6, ..Default::default() }, + ..Default::default() + }]; + s +} + +#[test] +#[ignore] +fn thumbnail_throughput() { + if !lightcraft_gpu::available() { + eprintln!("skipped: no GPU ({:?})", lightcraft_gpu::unavailable_reason()); + return; + } + let lib = lightcraft_scenes::demo_library(); + let sources: Vec> = (0..12).map(|i| Arc::new(lib[i % lib.len()].render(512, 341))).collect(); + let info = SourceInfo { raw: true, ..Default::default() }; + let s = preset_like(); + let req = RenderRequest::fit(256, 256); + let per_thread = 40; + for gpu in [false, true, false, true] { + let t = Instant::now(); + std::thread::scope(|sc| { + for k in 0..6 { + let (sources, info, s) = (&sources, &info, &s); + sc.spawn(move || { + for i in 0..per_thread { + let src = &sources[(k * per_thread + i) % sources.len()]; + let r = if gpu { + lightcraft_gpu::render(src, info, s, &req, None) + } else { + Some(lightcraft_pipeline::render(src, info, s, &req)) + }; + assert!(r.is_some()); + } + }); + } + }); + let n = 6 * per_thread; + let ms = t.elapsed().as_secs_f64() * 1e3; + eprintln!("{}: {n} thumbnails in {ms:.0} ms ({:.2} ms each)", if gpu { "gpu" } else { "cpu" }, ms / n as f64); + } +} diff --git a/crates/gpu/tests/mask_geometry.rs b/crates/gpu/tests/mask_geometry.rs new file mode 100644 index 0000000000..1cbd741a0e --- /dev/null +++ b/crates/gpu/tests/mask_geometry.rs @@ -0,0 +1,151 @@ +//! On the GPU, masks stay on the image content under every geometry change: +//! a mask drawn around a mark still brightens that mark after Straighten, a crop, a flip, a quarter +//! turn or a lens / perspective warp, rendered fresh or through the view's stage cache. (The CPU +//! side is `lightcraft-pipeline`'s `tests_mask_geometry`.) + +use std::sync::Arc; + +use lightcraft_develop::{BrushStroke, DevelopSettings, LocalAdjustments, Mask, MaskComponent, MaskOp, MaskShape, SegMask}; +use lightcraft_geom::{CropGeometry, Point, Rect}; +use lightcraft_pipeline::{RenderRequest, SourceInfo, StageCache}; +use lightcraft_raster::{Rgb32f, Rgba8}; + +const W: usize = 240; +const H: usize = 160; +const MARK: (f64, f64) = (0.3, 0.32); + +fn gpu() -> bool { + let ok = lightcraft_gpu::available(); + if !ok { + lightcraft_testkit::skip!(Gpu, "no GPU adapter"); + } + ok +} + +fn marked(mark: bool) -> Rgb32f { + let (mx, my) = (MARK.0 * W as f64, MARK.1 * H as f64); + Rgb32f::from_fn(W, H, |x, y| { + let d = ((x as f64 + 0.5 - mx).powi(2) + (y as f64 + 0.5 - my).powi(2)).sqrt(); + if d < 2.5 && mark { [0.9; 3] } else { [0.05; 3] } + }) +} + +fn with_mask(shape: MaskShape) -> DevelopSettings { + let mut s = DevelopSettings::default(); + s.masks.push(Mask { + id: 1, + components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape }], + adjust: LocalAdjustments { exposure: 2.0, ..Default::default() }, + ..Default::default() + }); + s +} + +fn shapes() -> Vec<(&'static str, MaskShape)> { + let l = W.max(H) as f64; + const SIDE: usize = 64; + let logits: Vec = (0..SIDE * SIDE) + .map(|i| { + let (x, y) = ((i % SIDE) as f64 + 0.5, (i / SIDE) as f64 + 0.5); + let (dx, dy) = ((x / SIDE as f64 - MARK.0) * W as f64, (y / SIDE as f64 - MARK.1) * H as f64); + if (dx * dx + dy * dy).sqrt() < 10.0 { 8.0 } else { -8.0 } + }) + .collect(); + vec![ + ("radial", MaskShape::Radial { center: Point::new(MARK.0, MARK.1), rx: 12.0 / l, ry: 12.0 / l, angle: 0.0, feather: 40.0, invert: false }), + ( + "brush", + MaskShape::Brush { + strokes: vec![BrushStroke { + points: vec![Point::new(MARK.0 - 0.005, MARK.1), Point::new(MARK.0 + 0.005, MARK.1)], + size: 8.0 / l, + ..Default::default() + }], + }, + ), + ( + "object", + MaskShape::Object { + hint: vec![Point::new(MARK.0, MARK.1)], + exclude: Vec::new(), + seg: Some(SegMask::from_logits(SIDE, &logits)), + detail: Vec::new(), + edge: 0.0, + }, + ), + ] +} + +fn geometries() -> Vec<(&'static str, Box)> { + vec![ + ("straighten", Box::new(|s: &mut DevelopSettings| s.crop.geometry = CropGeometry { rect: Rect::new(0.08, 0.1, 0.92, 0.9), angle: 7.0 })), + ("crop", Box::new(|s: &mut DevelopSettings| s.crop.geometry.rect = Rect::new(0.1, 0.15, 0.7, 0.8))), + ("flip", Box::new(|s: &mut DevelopSettings| s.crop.flip_h = true)), + ( + "perspective", + Box::new(|s: &mut DevelopSettings| { + s.geometry.vertical = 25.0; + s.geometry.rotate = 4.0; + }), + ), + ("distortion", Box::new(|s: &mut DevelopSettings| s.optics.distortion = 40.0)), + ( + // Rotate Right: the photo and its masks turn together (`photo.rotateRight`) + "quarter turn", + Box::new(|s: &mut DevelopSettings| { + let turn = lightcraft_geom::Orientation::Normal.rotated(true); + s.orientation = s.orientation.rotated(true); + for m in &mut s.masks { + lightcraft_pipeline::mask_space::turn(m, turn); + } + }), + ), + ] +} + +fn luma(img: &Rgba8, i: usize) -> f64 { + let p = img.data[i]; + (p[0] as f64 + p[1] as f64 + p[2] as f64) / 3.0 +} + +fn centroid(w: usize, weights: impl Iterator) -> (f64, f64) { + let (mut sx, mut sy, mut n) = (0.0, 0.0, 0.0); + for (i, v) in weights.enumerate() { + sx += v * ((i % w) as f64 + 0.5); + sy += v * ((i / w) as f64 + 0.5); + n += v; + } + assert!(n > 0.0, "nothing found"); + (sx / n, sy / n) +} + +fn on_gpu(src: &Arc, s: &DevelopSettings, cache: Option<&StageCache>) -> Rgba8 { + let req = RenderRequest::fit(W, H); + lightcraft_gpu::try_render(src, &SourceInfo::default(), s, &req, cache).map(|r| r.image).unwrap_or_else(|e| panic!("GPU render failed: {e:?}")) +} + +#[test] +fn masks_stay_on_the_content_under_every_geometry_change_on_the_gpu() { + if !gpu() { + return; + } + let src = Arc::new(marked(true)); + for (name, shape) in shapes() { + for (what, change) in geometries() { + let mut s = with_mask(shape.clone()); + let cache = StageCache::default(); + on_gpu(&src, &s, Some(&cache)); + change(&mut s); + let unmasked = DevelopSettings { masks: Vec::new(), ..s.clone() }; + let plain = on_gpu(&src, &unmasked, None); + // (where the marked photo differs from an unmarked one: a warp leaves light blank canvas) + let bare = on_gpu(&Arc::new(marked(false)), &unmasked, None); + let mark = centroid(plain.width, (0..plain.data.len()).map(|i| (luma(&plain, i) - luma(&bare, i)).max(0.0))); + for (how, m) in [("fresh", on_gpu(&src, &s, None)), ("cached", on_gpu(&src, &s, Some(&cache)))] { + let at = centroid(m.width, (0..m.data.len()).map(|i| (luma(&m, i) - luma(&plain, i)).max(0.0))); + let d = ((at.0 - mark.0).powi(2) + (at.1 - mark.1).powi(2)).sqrt(); + assert!(d < 2.0, "{name} after {what} ({how}): the mask's effect is at {at:?}, the mark at {mark:?}"); + } + } + } +} 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/lensdb/src/lib.rs b/crates/lensdb/src/lib.rs index cf6b2ec145..d03d950407 100644 --- a/crates/lensdb/src/lib.rs +++ b/crates/lensdb/src/lib.rs @@ -30,6 +30,11 @@ pub use model::{Distortion, Tca, Vignetting}; const MAX_FILE_BYTES: u64 = 16 << 20; /// Most files read from one directory. const MAX_FILES: usize = 2000; +/// Most bytes of lens names that profiles may copy per parsed document (each calibration owns a copy): a real +/// database copies about a megabyte. +const MAX_PROFILE_COPY_BYTES: usize = 32 << 20; +/// What one copied name costs besides its bytes: the `String` slot in its `Vec` and the allocator's header and rounding. +const NAME_ALLOCATION: usize = std::mem::size_of::() + 32; /// Largest radial error (half-diagonal units) accepted when converting a distortion to the DNG polynomial. pub const MAX_WARP_ERROR: f64 = 0.001; /// Largest relative error accepted when converting vignetting to the DNG polynomial. @@ -60,7 +65,8 @@ pub struct Camera { pub maker: String, pub model: String, pub mount: String, - pub crop_factor: f64, + /// Sensor crop relative to 35 mm; missing or invalid XML remains unknown. + pub crop_factor: Option, } /// One calibrated vignetting point. @@ -80,8 +86,8 @@ pub struct Profile { /// Every name the lens goes by (EXIF variants, translations). pub models: Vec, pub mounts: Vec, - /// Crop factor of the camera the calibration was made on. - pub crop_factor: f64, + /// Crop factor of the calibration frame; missing or invalid XML remains unknown. + pub crop_factor: Option, /// Long / short side of the calibration frame. pub aspect_ratio: f64, /// False for fisheye and other non-rectilinear projections: distortion is then not applied. @@ -144,7 +150,8 @@ impl LensDb { let root = xml::parse(xml)?; let Some(top) = root.kid("lensdatabase") else { return Err(Error::Xml("no element".into())) }; let cameras = top.kids("camera").filter_map(camera).collect(); - let lenses = top.kids("lens").flat_map(lens).collect(); + let mut budget = MAX_PROFILE_COPY_BYTES; + let lenses = top.kids("lens").flat_map(|n| lens(n, &mut budget)).collect(); Ok(LensDb { cameras, lenses }) } @@ -205,7 +212,7 @@ impl LensDb { { score *= 0.8; } - if score >= 0.6 && best.is_none_or(|(s, _)| score > s) { + if score >= 0.6 && best.is_none_or(|(s, b)| score > s || (score == s && b.crop_factor.is_none() && lens.crop_factor.is_some())) { best = Some((score, lens)); } } @@ -244,7 +251,7 @@ impl LensDb { continue; } let score = focals.iter().filter(|f| (lo..=hi).contains(*f)).count() as f64 / focals.len() as f64; - if score > 0.0 && best.is_none_or(|(s, _)| score > s) { + if score > 0.0 && best.is_none_or(|(s, b)| score > s || (score == s && b.crop_factor.is_none() && p.crop_factor.is_some())) { best = Some((score, p)); } } @@ -272,11 +279,26 @@ fn exif_focal_range(exif: &[String]) -> Option<(f64, f64)> { } fn read_capped(path: &Path) -> Result { - let len = std::fs::metadata(path).map_err(|e| Error::Io(e.to_string()))?.len(); - if len > MAX_FILE_BYTES { + use std::io::Read; + let io = |e: std::io::Error| Error::Io(e.to_string()); + // the pathname is checked before opening (opening a FIFO for reading blocks until a writer appears), then the + // opened file again: a link or FIFO swapped in after the pathname check is refused too + if !std::fs::metadata(path).map_err(io)?.is_file() { + return Err(Error::Io(format!("{}: not a regular file", path.display()))); + } + let file = std::fs::File::open(path).map_err(io)?; + let meta = file.metadata().map_err(io)?; + if !meta.is_file() { + return Err(Error::Io(format!("{}: not a regular file", path.display()))); + } + if meta.len() > MAX_FILE_BYTES { + return Err(Error::TooLarge); + } + let mut bytes = Vec::new(); + file.take(MAX_FILE_BYTES + 1).read_to_end(&mut bytes).map_err(io)?; + if bytes.len() as u64 > MAX_FILE_BYTES { return Err(Error::TooLarge); } - let bytes = std::fs::read(path).map_err(|e| Error::Io(e.to_string()))?; Ok(String::from_utf8_lossy(&bytes).into_owned()) } @@ -327,7 +349,9 @@ fn maker_matches(a: &[String], b: &[String]) -> bool { } /// How well a database name matches the EXIF name, 0..1. Every number in the database name (focal lengths, -/// apertures) must appear in the EXIF name; the maker's words are ignored on both sides (EXIF often omits them). +/// apertures) must appear in the EXIF name and vice versa; the maker's words are ignored on both sides (EXIF +/// often omits them). Extra EXIF words only lower the score; they name a different lens only when they mark +/// a teleconverter, a different optical system than the bare lens. fn name_score(db: &[String], exif: &[String], maker: &[String]) -> f64 { let db: Vec<&String> = db.iter().filter(|t| !maker.contains(t)).collect(); let exif: Vec<&String> = exif.iter().filter(|t| !maker.contains(t)).collect(); @@ -337,16 +361,33 @@ fn name_score(db: &[String], exif: &[String], maker: &[String]) -> f64 { if db.iter().any(|t| is_number(t) && !exif.contains(t)) || exif.iter().any(|t| is_number(t) && !db.contains(t)) { return 0.0; } + // A teleconverter combo is a different optical system from the bare lens: + // reject it whichever side carries the marker, independent of which tokens + // the names drop or add. + let db_tc = db.iter().any(|t| is_teleconverter_marker(t.as_str())); + let exif_tc = exif.iter().any(|t| is_teleconverter_marker(t.as_str())); + if db_tc != exif_tc { + return 0.0; + } let common = db.iter().filter(|t| exif.contains(t)).count() as f64; common / db.len().max(exif.len()) as f64 } +/// Teleconverter markers in a lens name. A name carrying one names a different +/// optical system than the bare lens, so a match whose sides disagree on the +/// marker is rejected before scoring. Converter factors such as `1.4x` +/// tokenise into a number the base profile lacks, so the numeric check above +/// already rejects them. +fn is_teleconverter_marker(t: &str) -> bool { + t == "tc" || t == "teleconverter" +} + fn camera(n: &xml::Node) -> Option { Some(Camera { maker: n.kid_text("maker")?.to_string(), model: n.kid_text("model")?.to_string(), mount: n.kid_text("mount").unwrap_or_default().to_string(), - crop_factor: crop_of(n.kid_text("cropfactor")).unwrap_or(1.0), + crop_factor: crop_of(n.kid_text("cropfactor")), }) } @@ -369,60 +410,80 @@ fn positive(v: Option) -> Option { } /// One `` element → one profile per `` (newer files give each its own crop factor and aspect). -fn lens(n: &xml::Node) -> Vec { +fn lens(n: &xml::Node, copy_budget: &mut usize) -> Vec { let Some(maker) = n.kid_text("maker") else { return Vec::new() }; let models: Vec = n.kids("model").map(|m| m.text.trim().to_string()).filter(|m| !m.is_empty()).collect(); if models.is_empty() { return Vec::new(); } - let crop = crop_of(n.kid_text("cropfactor")).unwrap_or(1.0); + let crop = crop_of(n.kid_text("cropfactor")); let aspect = aspect_of(n.kid_text("aspect-ratio")).unwrap_or(1.5); let rectilinear = n.kid_text("type").is_none_or(|t| t.eq_ignore_ascii_case("rectilinear")); let mounts = n.kids("mount").map(|m| m.text.trim().to_string()).filter(|m| !m.is_empty()).collect::>(); - n.kids("calibration") - .map(|cal| { - let mut p = Profile { - maker: maker.to_string(), - models: models.clone(), - mounts: mounts.clone(), - crop_factor: crop_of(cal.attr("cropfactor")).unwrap_or(crop), - aspect_ratio: aspect_of(cal.attr("aspect-ratio")).unwrap_or(aspect), - rectilinear, - distortion: Vec::new(), - tca: Vec::new(), - vignetting: Vec::new(), - }; - for c in &cal.children { - let Some(focal) = positive(c.num("focal")) else { continue }; - let k = |name: &str| c.num(name).unwrap_or(0.0); - match (c.name.as_str(), c.attr("model")) { - ("distortion", Some("poly3")) => p.distortion.push((focal, Distortion::Poly3 { k1: k("k1") })), - ("distortion", Some("poly5")) => p.distortion.push((focal, Distortion::Poly5 { k1: k("k1"), k2: k("k2") })), - ("distortion", Some("ptlens")) => p.distortion.push((focal, Distortion::PtLens { a: k("a"), b: k("b"), c: k("c") })), - ("tca", Some("linear")) => { - let one = |name: &str| c.num(name).unwrap_or(1.0); - p.tca.push((focal, Tca::Linear { kr: one("kr"), kb: one("kb") })); - } - ("tca", Some("poly3")) => { - let one = |name: &str| c.num(name).unwrap_or(1.0); - p.tca.push((focal, Tca::Poly3 { vr: one("vr"), vb: one("vb"), cr: k("cr"), cb: k("cb"), br: k("br"), bb: k("bb") })); - } - ("vignetting", Some("pa")) => { - let (Some(aperture), distance) = (positive(c.num("aperture")), positive(c.num("distance")).unwrap_or(1000.0)) else { - continue; - }; - let model = Vignetting { k1: k("k1"), k2: k("k2"), k3: k("k3") }; - p.vignetting.push(VignettingPoint { focal, aperture, distance, model }); - } - _ => {} + // every kept calibration owns a copy of the lens's names, charged to the document's shared copy budget (the + // strings' own allocations count, not only their bytes): when it can't cover another copy, the rest are left out + let meta_bytes = std::mem::size_of::() + + NAME_ALLOCATION + + maker.len() + + models.iter().chain(&mounts).map(|m| m.len() + NAME_ALLOCATION).sum::(); + let mut out = Vec::new(); + for cal in n.kids("calibration") { + if *copy_budget < meta_bytes { + break; + } + let mut p = Profile { + maker: String::new(), + models: Vec::new(), + mounts: Vec::new(), + // Only an omitted override inherits; an explicit invalid value remains unknown. + crop_factor: match cal.attr("cropfactor") { + Some(value) => crop_of(Some(value)), + None => crop, + }, + aspect_ratio: aspect_of(cal.attr("aspect-ratio")).unwrap_or(aspect), + rectilinear, + distortion: Vec::new(), + tca: Vec::new(), + vignetting: Vec::new(), + }; + for c in &cal.children { + let Some(focal) = positive(c.num("focal")) else { continue }; + let k = |name: &str| c.num(name).unwrap_or(0.0); + match (c.name.as_str(), c.attr("model")) { + ("distortion", Some("poly3")) => p.distortion.push((focal, Distortion::Poly3 { k1: k("k1") })), + ("distortion", Some("poly5")) => p.distortion.push((focal, Distortion::Poly5 { k1: k("k1"), k2: k("k2") })), + ("distortion", Some("ptlens")) => p.distortion.push((focal, Distortion::PtLens { a: k("a"), b: k("b"), c: k("c") })), + ("tca", Some("linear")) => { + let one = |name: &str| c.num(name).unwrap_or(1.0); + p.tca.push((focal, Tca::Linear { kr: one("kr"), kb: one("kb") })); } + ("tca", Some("poly3")) => { + let one = |name: &str| c.num(name).unwrap_or(1.0); + p.tca.push((focal, Tca::Poly3 { vr: one("vr"), vb: one("vb"), cr: k("cr"), cb: k("cb"), br: k("br"), bb: k("bb") })); + } + ("vignetting", Some("pa")) => { + let (Some(aperture), distance) = (positive(c.num("aperture")), positive(c.num("distance")).unwrap_or(1000.0)) else { + continue; + }; + let model = Vignetting { k1: k("k1"), k2: k("k2"), k3: k("k3") }; + p.vignetting.push(VignettingPoint { focal, aperture, distance, model }); + } + _ => {} } - p.distortion.sort_by(|a, b| a.0.total_cmp(&b.0)); - p.tca.sort_by(|a, b| a.0.total_cmp(&b.0)); - p - }) - .filter(|p| !p.distortion.is_empty() || !p.tca.is_empty() || !p.vignetting.is_empty()) - .collect() + } + // a calibration with nothing to apply is dropped before its names are copied or charged + if p.distortion.is_empty() && p.tca.is_empty() && p.vignetting.is_empty() { + continue; + } + *copy_budget -= meta_bytes; + p.maker = maker.to_string(); + p.models = models.clone(); + p.mounts = mounts.clone(); + p.distortion.sort_by(|a, b| a.0.total_cmp(&b.0)); + p.tca.sort_by(|a, b| a.0.total_cmp(&b.0)); + out.push(p); + } + out } /// Linear interpolation weights in a sorted key list: the bracketing indices and the weight of the upper one. @@ -514,14 +575,16 @@ impl Profile { /// The correction for `shot`, as the DNG opcode polynomials the pipeline applies, centred on the image. /// Distortion and TCA are combined per plane (R, G, B); a model the polynomial can't follow closely /// ([`MAX_WARP_ERROR`], [`MAX_VIGNETTE_ERROR`]) or that would fold the image is left out. + /// An unknown or invalid calibration crop factor cannot be converted. pub fn correction(&self, shot: &Shot) -> Option { let (w, h) = (shot.width, shot.height); if !(w >= 2.0 && h >= 2.0 && w.is_finite() && h.is_finite() && shot.focal.is_finite() && shot.focal > 0.0) { return None; } - let cam = shot.crop_factor.filter(|c| c.is_finite() && *c > 0.0).unwrap_or(self.crop_factor); + let calibration_crop = self.crop_factor.filter(|c| c.is_finite() && (0.05..=20.0).contains(c))?; + let cam = shot.crop_factor.filter(|c| c.is_finite() && *c > 0.0).unwrap_or(calibration_crop); // DNG radius (1 = image half diagonal) → lensfun radii - let to_vig = self.crop_factor / cam; + let to_vig = calibration_crop / cam; let to_dist = to_vig * (1.0 + self.aspect_ratio * self.aspect_ratio).sqrt(); let center = Point::new(0.5, 0.5); let radius = w.hypot(h) / 2.0 / w.max(h); diff --git a/crates/lensdb/src/tests.rs b/crates/lensdb/src/tests.rs index 71c9a4a0eb..2fe7d9f06a 100644 --- a/crates/lensdb/src/tests.rs +++ b/crates/lensdb/src/tests.rs @@ -36,6 +36,7 @@ const DB: &str = r#" Testcam Testcam 50mm f/1.8 Other Mount + 1 @@ -44,6 +45,7 @@ const DB: &str = r#" Fishco Fishco 8mm f/3.5 Fisheye equisolid + 1 @@ -101,8 +103,8 @@ fn malformed_documents_are_errors_not_panics() { #[test] fn finds_cameras_by_exif_strings() { let db = db(); - assert_eq!(db.find_camera("TESTCAM CORPORATION", "TC-1").unwrap().crop_factor, 1.5); - assert_eq!(db.find_camera("Testcam", "tc-ff").unwrap().crop_factor, 1.0); + assert_eq!(db.find_camera("TESTCAM CORPORATION", "TC-1").unwrap().crop_factor, Some(1.5)); + assert_eq!(db.find_camera("Testcam", "tc-ff").unwrap().crop_factor, Some(1.0)); assert!(db.find_camera("Testcam", "TC-2").is_none()); assert!(db.find_camera("Other", "TC-1").is_none()); } @@ -232,7 +234,8 @@ fn fisheyes_get_no_rectilinear_warp_and_bad_shots_none() { #[test] fn load_dir_reads_xml_files_and_reports_bad_ones() { let dir = std::env::temp_dir().join(format!("lensdb-test-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + // exclusive: an existing (possibly planted) entry fails the test instead of being written through + std::fs::create_dir(&dir).unwrap(); std::fs::write(dir.join("a.xml"), DB).unwrap(); std::fs::write(dir.join("b.xml"), " String { + format!( + r#"TestTest 50mm{parent} + + "# + ) +} + +#[test] +fn tied_lens_matches_prefer_a_known_calibration_crop() { + let name = spec_name([50.0, 50.0, 1.8, 1.8]); + for (parent, unknown, known) in [ + ("", "", r#"cropfactor="1""#), + ("bad", "", r#"cropfactor="1""#), + ("1", r#"cropfactor="bad""#, ""), + ("1", r#"cropfactor="bad""#, r#"cropfactor="1""#), + ] { + let calibration = |attributes: &str| format!(r#""#); + for (first, second) in [(unknown, known), (known, unknown)] { + let xml = format!( + "Test{name}{parent}{}{}", + calibration(first), + calibration(second), + ); + let db = LensDb::parse(&xml).unwrap(); + assert_eq!(db.lenses.len(), 2); + assert_eq!(db.lenses.iter().filter(|p| p.crop_factor.is_none()).count(), 1); + for profile in [db.find_lens(None, &name, None), db.find_lens_named(None, &name, None)] { + let profile = profile.unwrap(); + assert_eq!(profile.crop_factor, Some(1.0), "{parent}: {first}, {second}"); + assert!(profile.correction(&shot(50.0)).is_some()); + } + } + } +} + +#[test] +fn a_higher_lens_score_still_wins_with_unknown_crop() { + let mut db = db(); + let camera = db.cameras[0].clone(); + let mut unknown = db.lenses[0].clone(); + unknown.crop_factor = None; + let mut known = unknown.clone(); + known.crop_factor = Some(1.0); + known.mounts = vec!["Other Mount".into()]; + let name = unknown.models[0].clone(); + for lenses in [vec![unknown.clone(), known.clone()], vec![known, unknown]] { + db.lenses = lenses; + for profile in [db.find_lens(None, &name, Some(&camera)), db.find_lens_named(None, &name, Some(&camera))] { + assert_eq!(profile.unwrap().crop_factor, None, "the better mount match outranks crop availability"); + } + } +} + +#[test] +fn unknown_calibration_crop_is_not_assumed_full_frame() { + for parent in [ + "", + "", + "bad", + "NaN", + "inf", + "0", + "-1", + "0.049", + "21", + ] { + let db = LensDb::parse(&crop_xml(parent, "")).unwrap(); + assert_eq!(db.lenses[0].crop_factor, None, "{parent}"); + assert!(db.lenses[0].correction(&shot(50.0)).is_none(), "unknown calibration crop: {parent}"); + } +} + +#[test] +fn invalid_calibration_override_does_not_inherit_parent_crop() { + for value in ["", "bad", "NaN", "inf", "0", "-1", "0.049", "21"] { + let db = LensDb::parse(&crop_xml("1.5", &format!(r#"cropfactor="{value}""#))).unwrap(); + assert_eq!(db.lenses[0].crop_factor, None, "{value}"); + assert!(db.lenses[0].correction(&shot(50.0)).is_none(), "invalid calibration override: {value}"); + } +} + +#[test] +fn calibration_crop_inherits_only_when_omitted_and_accepts_valid_overrides() { + let inherited = LensDb::parse(&crop_xml("1.5", "")).unwrap(); + assert_eq!(inherited.lenses[0].crop_factor, Some(1.5)); + assert!(inherited.lenses[0].correction(&shot(50.0)).is_some()); + for parent in ["", "bad", "1.5"] { + for value in ["0.05", "1", "2", "20"] { + let db = LensDb::parse(&crop_xml(parent, &format!(r#"cropfactor="{value}""#))).unwrap(); + assert_eq!(db.lenses[0].crop_factor, value.parse().ok()); + // With no shot crop the valid calibration supplies the scale, even at the range boundaries. + assert!(db.lenses[0].correction(&Shot { crop_factor: None, ..shot(50.0) }).is_some()); + } + } +} + +#[test] +fn camera_crop_preserves_unknown_and_explicit_full_frame() { + for (crop, expected) in [ + ("", None), + ("bad", None), + ("NaN", None), + ("inf", None), + ("0", None), + ("-1", None), + ("0.049", None), + ("21", None), + ("0.05", Some(0.05)), + ("1", Some(1.0)), + ("20", Some(20.0)), + ] { + let xml = format!(r#"TestBody{crop}"#); + let db = LensDb::parse(&xml).unwrap(); + assert_eq!(db.cameras[0].crop_factor, expected, "{crop}"); + } + let db = LensDb::parse("TestBody").unwrap(); + assert_eq!(db.cameras[0].crop_factor, None); +} + +#[test] +fn direct_profile_api_rejects_invalid_calibration_and_preserves_shot_fallback() { + let mut profile = db().lenses[0].clone(); + for crop in [None, Some(f64::NAN), Some(f64::INFINITY), Some(0.0), Some(-1.0), Some(0.049), Some(21.0)] { + profile.crop_factor = crop; + assert!(profile.correction(&shot(24.0)).is_none(), "{crop:?}"); + } + profile.crop_factor = Some(1.0); + let expected = profile.correction(&shot(24.0)).unwrap(); + for crop in [None, Some(f64::NAN), Some(f64::INFINITY), Some(0.0), Some(-1.0)] { + assert_eq!(profile.correction(&Shot { crop_factor: crop, ..shot(24.0) }).unwrap(), expected); + } +} + #[test] fn built_in_lens_matches_by_camera_mount_and_focal_range() { let xml = r#" @@ -319,6 +456,42 @@ fn built_in_lens_matches_by_camera_mount_and_focal_range() { assert_eq!(exif_focal_range(&tokens(&huge)), Some((6.0, 6.0))); } +#[test] +fn tied_built_in_lens_matches_prefer_a_known_calibration_crop() { + let mut db = db(); + let cam = db.cameras[0].clone(); + let mut unknown = db.lenses[0].clone(); + unknown.models = vec!["Testcam Compact".into()]; + unknown.crop_factor = None; + let mut known = unknown.clone(); + known.crop_factor = Some(1.5); + for lenses in [vec![unknown.clone(), known.clone()], vec![known, unknown]] { + db.lenses = lenses; + let lens = db.find_lens(None, "24-70 mm f/2.8", Some(&cam)).unwrap(); + assert_eq!(lens.crop_factor, Some(1.5), "an exact focal-range score tie prefers the known crop in either order"); + assert!(lens.correction(&shot(24.0)).is_some()); + } +} + +#[test] +fn a_higher_built_in_lens_score_still_wins_with_unknown_crop() { + let mut db = db(); + let cam = db.cameras[0].clone(); + let mut unknown = db.lenses[0].clone(); + unknown.models = vec!["Testcam Compact".into()]; + unknown.crop_factor = None; + unknown.tca.clear(); + unknown.vignetting.clear(); + let mut known = unknown.clone(); + known.crop_factor = Some(1.5); + known.distortion[1].0 = 100.0; + for lenses in [vec![unknown.clone(), known.clone()], vec![known, unknown]] { + db.lenses = lenses; + let lens = db.find_lens(None, "24-70 mm f/2.8", Some(&cam)).unwrap(); + assert_eq!(lens.crop_factor, None, "the higher focal-range score remains the primary criterion in either order"); + } +} + /// A hand-edited or corrupt database may carry any number: infinities, NaN, enormous or negative /// coefficients, absurd crop factors and aspect ratios. Whatever loads must give corrections that /// are `None` or entirely finite, for any shot including nonsense ones; names of any shape find @@ -333,10 +506,10 @@ fn hostile_numbers_give_finite_corrections_or_none() { r#"MM 1{v}{v}"# ), format!( - r#"MM 1"# + r#"MM 1"# ), format!( - r#"MM 1"# + r#"MM 11"# ), ] { let Ok(db) = LensDb::parse(&format!("{xml}")) else { continue }; @@ -371,3 +544,95 @@ fn hostile_numbers_give_finite_corrections_or_none() { assert!(db.find_camera("", "").is_none()); assert!(db.find_lens(None, " ", None).is_none()); } + +#[test] +fn calibrations_past_the_shared_copy_budget_are_left_out() { + let name = "x".repeat(400_000); + let cal = ""; + let xml = format!("M{name}{}", cal.repeat(2000)); + let db = LensDb::parse(&xml).unwrap(); + assert!(!db.lenses.is_empty()); + assert!(db.lenses.len() * 400_000 <= MAX_PROFILE_COPY_BYTES); +} + +/// Unusable calibrations (nothing to apply) are not copied or charged, so they can't use up the +/// budget a later usable one of the same lens needs. +#[test] +fn unusable_calibrations_do_not_spend_the_copy_budget() { + let name = "x".repeat(8 << 20); + let empty = ""; + let good = ""; + let xml = format!("M{name}{}{good}", empty.repeat(4)); + let db = LensDb::parse(&xml).unwrap(); + assert_eq!(db.lenses.len(), 1, "the usable calibration after the empty ones is kept"); +} + +/// Many tiny names cost their allocations, not only their bytes. +#[test] +fn many_tiny_names_are_charged_their_allocations() { + let models = "a".repeat(400_000); + let good = ""; + let xml = format!("M{models}{good}{good}{good}{good}"); + let db = LensDb::parse(&xml).unwrap(); + let names: usize = db.lenses.iter().map(|p| p.models.len()).sum(); + assert!(db.lenses.len() < 4 && names * std::mem::size_of::() <= MAX_PROFILE_COPY_BYTES, "{} profiles", db.lenses.len()); +} + +#[cfg(unix)] +#[test] +fn load_dir_refuses_a_non_regular_xml_entry() { + let dir = std::env::temp_dir().join(format!("lensdb-test-dev-{}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + std::os::unix::fs::symlink("/dev/zero", dir.join("z.xml")).unwrap(); + let (db, errs) = LensDb::load_dir(&dir).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(db.is_empty()); + assert_eq!(errs.len(), 1, "{errs:?}"); +} + +/// A FIFO named `*.xml` is refused without opening it: opening a FIFO for reading blocks until a writer appears. +#[cfg(unix)] +#[test] +fn load_dir_refuses_a_fifo_without_blocking() { + let dir = std::env::temp_dir().join(format!("lensdb-test-fifo-{}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let fifo = dir.join("f.xml"); + let made = std::process::Command::new("mkfifo").arg(&fifo).status().is_ok_and(|s| s.success()); + if !made { + std::fs::remove_dir_all(&dir).unwrap(); + return; + } + let (db, errs) = LensDb::load_dir(&dir).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(db.is_empty()); + assert_eq!(errs.len(), 1, "{errs:?}"); +} + +#[test] +fn teleconverter_combo_does_not_inherit_base_profile() { + // The database has only the bare 400 mm profile. A teleconverter combo is a + // different optical system, so find_lens must not return the base profile -- + // not even when the converter is a digit-free suffix such as "Z TC". + let xml = r#" + + + Nikon + NIKKOR Z 400mm f/4.5 VR S + Z + + + + +"#; + let db = LensDb::parse(xml).unwrap(); + assert!(db.find_lens(Some("Nikon"), "NIKKOR Z 400mm f/4.5 VR S", None).is_some(), "the base profile matches its own name"); + // A digit-free teleconverter suffix must not inherit the 400 mm profile: + // name_score finds every base-profile number token present and would score 0.78. + assert!(db.find_lens(Some("Nikon"), "NIKKOR Z 400mm f/4.5 VR S Z TC", None).is_none(), "teleconverter combos do not inherit the base profile"); + // A converter factor ("1.4") is a numeric token the base profile lacks, so the + // combo matches nothing either. + assert!( + db.find_lens(Some("Nikon"), "NIKKOR Z 400mm f/4.5 VR S Z TC-1.4x", None).is_none(), + "teleconverter combos do not inherit the base profile", + ); +} diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 94b1d26062..11de914173 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -29,7 +29,9 @@ impl Drop for Headless { impl Default for Headless { fn default() -> Self { - let session = Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models(); + // the lens database the desktop app downloaded, when it is there (a headless session never fetches it) + let session = + Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_lens_database(); Self::new(session.with_default_sam3_model().with_default_slide_templates()) } } @@ -203,6 +205,15 @@ pub fn write_image(path: &Path, img: &Rgba8, quality: u8) -> Result<(), String> mod tests { use super::*; + /// A headless session reads the lens database the desktop app downloaded, as the desktop does (the same raw gets + /// the same profile everywhere), but never fetches it by itself. + #[test] + fn a_headless_session_reads_the_downloaded_lens_database() { + let h = Headless::default(); + assert_eq!(lightcraft_engine::lens_profiles::host_dir(), lightcraft_engine::lensfun_download::default_dir()); + assert!(!h.session.lens_auto_download, "selecting it is not permission to download it"); + } + #[test] fn folder_discovery_matches_engine_extensions() { let dir = std::env::temp_dir().join(format!("lc-mcp-discovery-{}", std::process::id())); diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index aa194252e9..5a9c51b8cf 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -29,6 +29,31 @@ pub fn sharpen_mask_weight(masking: f32, det: f32) -> f32 { if masking > 0.0 { smooth(masking * 0.25, masking * 0.25 + 0.15, det.abs()) } else { 1.0 } } +/// Masking weight for the V3 pixel-scale sharpening band, also used by its Alt-drag preview. +#[inline] +pub fn pixel_sharpen_mask_weight(masking: f32, det: f32) -> f32 { + if masking > 0.0 { smooth(masking * 0.1, masking * 0.1 + 0.06, det.abs()) } else { 1.0 } +} + +/// Gain of the sharpening detail term (per unit of `Amount / 150`), in stops of luminance per stop of detail. +pub const SHARPEN_GAIN: f32 = 7.0; + +/// Soft-clip limit (stops) of the sharpening detail term for Detail `0..=100`: 0.03 stops (large +/// edge detail is flattened so halos stay small) up to 1.5 stops (practically linear). +pub fn sharpen_limit(detail: f64) -> f32 { + let d = (detail / 100.0).clamp(0.0, 1.0) as f32; + 0.03 * 50f32.powf(d) +} + +/// The sharpening boost (stops) for pixel-scale detail `det` (log luminance minus its blur at the +/// sharpen radius): linear for small detail, soft-clipped at `limit`, and gated by the Masking edge +/// mask (`mask` = Masking / 100) so flat areas and noise can be left alone. +#[inline] +pub fn sharpen_term(det: f32, limit: f32, mask: f32) -> f32 { + let m = pixel_sharpen_mask_weight(mask, det); + SHARPEN_GAIN * m * det / (1.0 + det.abs() / limit) +} + /// Parametric region curve (encoded domain) composed with the master point curve. fn curve_luts(c: &ToneCurve) -> Option<[Lut1; 3]> { let parametric = c.highlights != 0.0 || c.lights != 0.0 || c.darks != 0.0 || c.shadows != 0.0; @@ -155,6 +180,9 @@ pub struct FinishParams { /// A LUT profile and its amount (0..2), applied to the display-encoded colour. pub lut: Option<(std::sync::Arc, f32)>, pub tone: ToneMap, + /// Process V4's calibrated Contrast and Blacks on the camera-look path, applied after + /// the tone map (`None`: another process or path, or both at 0; see [`crate::light_v3`]). + pub light: Option, pub ops: ColorOps, /// Calibration: primaries matrix (row-major, linear Rec.2020) and shadows tint (−1..1). pub calib: Option<[[f32; 3]; 3]>, @@ -169,7 +197,7 @@ pub struct FinishParams { pub to_out: [[f32; 3]; 3], pub out_luma: [f32; 3], pub out_trc: OutputTrc, - /// Soft proofing (CPU only; the GPU path declines proof renders). + /// Soft proofing (the GPU kernel reads the same parameters). pub proof: Option, pub hl: f32, pub sh: f32, @@ -178,6 +206,12 @@ pub struct FinishParams { pub dehaze: f32, pub sharpen: f32, pub sharpen_mask: f32, + /// V1/V2 retain their texture-band sharpening; V3 uses the pixel-scale plane. + pub pixel_sharpen: bool, + /// Soft-clip limit (stops) of the sharpening detail term: small damps halos (Detail 0), large keeps all (100). + pub sharpen_limit: f32, + /// Response compensation for a sharpening radius below one output pixel. + pub sharpen_gain: f32, /// Airlight after and before exposure, exposure gain and EV (see [`crate::Prepared`]). pub air: f32, pub air_pre: f32, @@ -240,6 +274,7 @@ impl FinishParams { calib: if calibration { crate::colorops::calibration_matrix(&s.calibration) } else { None }, shadow_tint: if calibration { (s.calibration.shadows_tint / 100.0) as f32 } else { 0.0 }, tone: base_tone(s, info, peak), + light: crate::light_v3::LightOps::new(s, info), lut: crate::lut::get(&s.profile.id).map(|l| (l, (s.profile.amount / 100.0).clamp(0.0, 2.0) as f32)), ops: ColorOps::new(s), curves: curve_luts(&s.curve), @@ -256,6 +291,13 @@ impl FinishParams { dehaze, sharpen: (s.detail.sharpen_amount / 150.0) as f32, sharpen_mask: (s.detail.sharpen_masking / 100.0) as f32, + pixel_sharpen: crate::local::pixel_sharpen(s), + sharpen_limit: sharpen_limit(s.detail.sharpen_detail), + sharpen_gain: crate::local::sharpen_gain(crate::local::sharpen_sigma_raw( + s, + px_per_long, + info.native_long.unwrap_or(0).max(frame.ow.max(frame.oh) as usize).max(1) as f64, + )), air: air_pre * gain, air_pre, gain, @@ -285,6 +327,8 @@ impl FinishParams { /// rendering process. This is where a new tone model branches: a retuned default tone curve (issue /// #146) is a new [`Process`] with its own arm here, and V1's arm stays as it is, so photos edited /// under V1 keep their look (`docs/process-versions.md`). CPU and GPU both take it from here. +/// From V4 the camera curve keeps V2 Whites; its Contrast and Blacks are the +/// calibrated operators that follow the tone map ([`crate::light_v3`], [`FinishParams::light`]). /// `peak` is the HDR render's peak relative to SDR white ([`lightcraft_develop::Hdr::peak`]); at 1.0 (SDR) /// every arm is the SDR tone map. An HDR render keeps the camera's look through the midtones and /// lifts its highlights past white ([`ToneMap::camera_hdr`]), so it matches the SDR render below them. @@ -292,14 +336,21 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap { let l = &s.light; match s.process.process() { // V2 changes the Highlights/Shadows base (`local::tone_base`), not the tone map - Process::V1 | Process::V2 => match info.camera_tone.as_ref().filter(|_| info.raw) { + Process::V1 | Process::V2 | Process::V3 => match info.camera_tone.as_ref().filter(|_| info.raw) { Some(curve) => ToneMap::camera_hdr(curve, l.contrast, l.whites, l.blacks, peak), None if info.raw => ToneMap::hdr(l.contrast, l.whites, l.blacks, peak), None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak), }, + // Keep V2 Whites in the camera curve; calibrated Contrast and Blacks follow it. + Process::V4 => match info.camera_tone.as_ref().filter(|_| info.raw) { + Some(curve) => ToneMap::camera_hdr(curve, 0.0, l.whites, 0.0, peak), + None if info.raw => ToneMap::hdr(l.contrast, l.whites, l.blacks, peak), + None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak), + }, } } +/// Finish the prepared pipeline stages into an 8-bit RGBA image in `space` (or `display`). pub(crate) fn finish( p: &Prepared, s: &DevelopSettings, @@ -317,11 +368,14 @@ pub(crate) fn finish( fp.for_display(d, proof); } let trc = fp.out_trc; - let data = finish_with(p, &fp, false, |e| match trc { - OutputTrc::Srgb => [enc(e[0]), enc(e[1]), enc(e[2]), 255], - t => { - let x = e.map(|v| enc(t.encode(lightcraft_color::transfer::srgb_to_linear(v.clamp(0.0, 1.0))))); - [x[0], x[1], x[2], 255] + let data = finish_with(p, &fp, false, |x, y, e| { + let d = bayer_dither_offset(x, y); + match trc { + OutputTrc::Srgb => [enc(e[0], d), enc(e[1], d), enc(e[2], d), 255], + t => { + let c = e.map(|v| enc(t.encode(lightcraft_color::transfer::srgb_to_linear(v.clamp(0.0, 1.0))), d)); + [c[0], c[1], c[2], 255] + } } }); Rgba8 { width: w, height: h, data } @@ -345,18 +399,18 @@ pub(crate) fn finish_deep( let trc = fp.out_trc; let samples = match depth { OutputDepth::F32Linear => { - let v = finish_with(p, &fp, true, |e| e.map(|v| srgb_to_linear(v.clamp(0.0, 1.0)))); + let v = finish_with(p, &fp, true, |_x, _y, e| e.map(|v| srgb_to_linear(v.clamp(0.0, 1.0)))); DeepSamples::F32(v.into_flattened()) } OutputDepth::F32Hdr => { // the sRGB curve extended past 1 (it is unbounded), so values up to `peak` survive let peak = fp.peak; - let v = finish_with(p, &fp, true, |e| e.map(|v| srgb_to_linear(v.max(0.0)).clamp(0.0, peak))); + let v = finish_with(p, &fp, true, |_x, _y, e| e.map(|v| srgb_to_linear(v.max(0.0)).clamp(0.0, peak))); DeepSamples::F32(v.into_flattened()) } _ => { let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16; - let v = finish_with(p, &fp, true, |e| match trc { + let v = finish_with(p, &fp, true, |_x, _y, e| match trc { OutputTrc::Srgb => e.map(q), t => e.map(|v| q(t.encode(srgb_to_linear(v.clamp(0.0, 1.0))))), }); @@ -373,19 +427,21 @@ pub(crate) fn finish_with( p: &Prepared, fp: &FinishParams, exact: bool, - store: impl Fn([f32; 3]) -> T + Sync + Send, + store: impl Fn(usize, usize, [f32; 3]) -> T + Sync + Send, ) -> Vec { let (w, h) = (p.img.width, p.img.height); let p_lut = fp.lut.clone(); - let FinishParams { curves, vig, to_out, out_luma, grain, .. } = fp; + let FinishParams { light, curves, vig, to_out, out_luma, grain, .. } = fp; let terms: Vec<[f32; MASK_TERMS]> = p.masks.iter().map(|m| mask_terms(&m.adjust)).collect(); let out_to_norm = fp.out_to_norm; let long = fp.ow.max(fp.oh); let [vx, vy, vw, vh] = fp.view; + let (vx_u, vy_u) = (vx.round() as usize, vy.round() as usize); // the vignette belongs to the whole output frame, not to the window being drawn let aspect = vw / vh; let srgb = srgb_lut(); + let preview_light = if exact { None } else { light.as_ref().and_then(|lo| crate::light_v3::PreviewOps::new(lo, &|v| encode_srgb(srgb, v))) }; let peak = fp.peak; let hdr = peak > 1.0; let mut out = vec![T::default(); w * h]; @@ -428,6 +484,9 @@ pub(crate) fn finish_with( d = d.map(|v| v + (o - v) * t); } + // --- process V4: calibrated Contrast, Blacks (ProPhoto with the sRGB transfer) + d = apply_light(d, light.as_ref(), preview_light.as_ref(), exact, srgb); + // --- colour d = fp.ops.apply(d, l_sat, l_hue); if let Some((dir, amt)) = local.tint { @@ -549,12 +608,29 @@ pub(crate) fn finish_with( } None => e, }; - *px = store(warn.unwrap_or(e)); + *px = store(vx_u + x, vy_u + y, warn.unwrap_or(e)); } }); out } +#[inline] +fn apply_light( + color: [f32; 3], + light: Option<&crate::light_v3::LightOps>, + preview: Option<&crate::light_v3::PreviewOps>, + exact: bool, + srgb: &[f32; SRGB_LUT_N + 1], +) -> [f32; 3] { + if let Some(lo) = preview { + lo.apply(color) + } else if let Some(lo) = light { + if exact { lo.apply(color, &linear_to_srgb) } else { lo.apply(color, &|v| encode_srgb(srgb, v)) } + } else { + color + } +} + struct PixelLocalTerms { values: [f32; MASK_SUMS], tint: Option<([f32; 3], f32)>, @@ -662,17 +738,26 @@ fn local_tone_delta(p: &Prepared, fp: &FinishParams, index: usize, base: f32, l1 delta += clarity * 0.85 * detail * (0.35 + 0.65 * midtone); } let texture = fp.tex + l_tex; - let sharpen = l_sharp * 0.6 + fp.sharpen; - if (texture != 0.0 || sharpen != 0.0) + if texture != 0.0 && let Some(blur) = &p.texture_blur { let detail = p.log_l.data[index] - blur.data[index]; let tame = 1.0 - 0.6 * smooth(0.4, 1.6, detail.abs()); delta += texture * 1.1 * detail.clamp(-1.0, 1.0) * tame; - if sharpen != 0.0 { - let mask = sharpen_mask_weight(fp.sharpen_mask, detail); - delta += sharpen * 1.3 * detail.clamp(-0.8, 0.8) * mask; + } + let sharpen = l_sharp * 0.6 + fp.sharpen; + if fp.pixel_sharpen { + if sharpen != 0.0 + && let Some(blur) = &p.sharpen_blur + { + delta += sharpen * fp.sharpen_gain * sharpen_term(p.log_l.data[index] - blur.data[index], fp.sharpen_limit, fp.sharpen_mask); } + } else if sharpen != 0.0 + && let Some(blur) = &p.texture_blur + { + let detail = p.log_l.data[index] - blur.data[index]; + let mask = sharpen_mask_weight(fp.sharpen_mask, detail); + delta += sharpen * 1.3 * detail.clamp(-0.8, 0.8) * mask; } if l_noise != 0.0 && let Some(blur) = &p.texture_blur @@ -685,7 +770,7 @@ fn local_tone_delta(p: &Prepared, fp: &FinishParams, index: usize, base: f32, l1 /// A colour needing more desaturation than this (scale < `GAMUT_WARN`) to fit is out of gamut for /// the gamut warnings (tolerates rounding at the gamut boundary). -const GAMUT_WARN: f32 = 0.995; +pub const GAMUT_WARN: f32 = 0.995; /// For the gamut warnings: `r` needed desaturating by `t` to fit, and isn't simply a neutral /// beyond white or below black (that's clipping, which the clipping warnings show). @@ -770,17 +855,42 @@ pub fn srgb_lut() -> &'static [f32; SRGB_LUT_N + 1] { /// Linear → sRGB-encoded (clamped to 0..1) by an interpolated table: within 2e-5 of the exact /// curve (≪ one 8-bit or 10-bit step), several times faster than `powf`. #[inline] -fn encode_srgb(lut: &[f32; SRGB_LUT_N + 1], v: f32) -> f32 { +pub(crate) fn encode_srgb(lut: &[f32; SRGB_LUT_N + 1], v: f32) -> f32 { let f = v.clamp(0.0, 1.0) * SRGB_LUT_N as f32; let i = (f as usize).min(SRGB_LUT_N - 1); let t = f - i as f32; lut[i] + (lut[i + 1] - lut[i]) * t } +#[rustfmt::skip] +const BAYER_8X8: [u8; 64] = [ + 0, 32, 8, 40, 2, 34, 10, 42, + 48, 16, 56, 24, 50, 18, 58, 26, + 12, 44, 4, 36, 14, 46, 6, 38, + 60, 28, 52, 20, 62, 30, 54, 22, + 3, 35, 11, 43, 1, 33, 9, 41, + 51, 19, 59, 27, 49, 17, 57, 25, + 15, 47, 7, 39, 13, 45, 5, 37, + 63, 31, 55, 23, 61, 29, 53, 21, +]; + +/// Returns the ordered Bayer 8×8 dither threshold offset in `0..1` for pixel `(x, y)`. #[inline] -fn enc(v: f32) -> u8 { - // `v` is already sRGB-encoded; round to 8 bits. - (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8 +fn bayer_dither_offset(x: usize, y: usize) -> f32 { + let idx = (y & 7) * 8 + (x & 7); + (BAYER_8X8[idx] as f32 + 0.5) / 64.0 +} + +/// Quantizes display-curve-encoded value `v` (0..1) to 8-bit integer with 8×8 ordered Bayer dithering. +#[inline] +fn enc(v: f32, dither: f32) -> u8 { + let y = v.clamp(0.0, 1.0) * 255.0; + // Guard against floating point rounding error (e.g. sRGB <-> Rec.2020 matrix conversion) + // where numerical white (1.0) evaluates to ~254.95. + if y >= 254.9 { + return 255; + } + (y + dither).clamp(0.0, 255.0) as u8 } #[cfg(test)] @@ -822,4 +932,62 @@ mod tests { assert_eq!(encode_srgb(lut, -1.0), 0.0); assert!((encode_srgb(lut, 2.0) - 1.0).abs() < 1e-6); } + + /// Verifies 8x8 Bayer dithering preserves endpoints, exact 8-bit quantization steps, and fractional levels. + #[test] + fn bayer_dithering_preserves_extremes_and_dithers_smoothly() { + for y in 0..8 { + for x in 0..8 { + let d = bayer_dither_offset(x, y); + // Zero is strictly 0 across all dither offsets + assert_eq!(enc(0.0, d), 0); + // One is strictly 255 across all dither offsets + assert_eq!(enc(1.0, d), 255); + // Exact 8-bit quantization steps have zero spatial noise + for k in 0..=255 { + assert_eq!(enc(k as f32 / 255.0, d), k); + } + } + } + + // Fractional level: 128.5 / 255.0 should dither equally between 128 and 129 + let v = 128.5 / 255.0; + let mut sum = 0u32; + let mut count_128 = 0; + let mut count_129 = 0; + for y in 0..8 { + for x in 0..8 { + let val = enc(v, bayer_dither_offset(x, y)); + sum += val as u32; + if val == 128 { + count_128 += 1; + } else if val == 129 { + count_129 += 1; + } + } + } + assert_eq!(count_128, 32); + assert_eq!(count_129, 32); + assert_eq!(sum, 32 * 128 + 32 * 129); + + // Fractional highlight level: 254.5 / 255.0 should dither equally between 254 and 255 + let v = 254.5 / 255.0; + let mut sum_hl = 0u32; + let mut count_254 = 0; + let mut count_255 = 0; + for y in 0..8 { + for x in 0..8 { + let val = enc(v, bayer_dither_offset(x, y)); + sum_hl += val as u32; + if val == 254 { + count_254 += 1; + } else if val == 255 { + count_255 += 1; + } + } + } + assert_eq!(count_254, 32); + assert_eq!(count_255, 32); + assert_eq!(sum_hl, 32 * 254 + 32 * 255); + } } diff --git a/crates/pipeline/src/geometry.rs b/crates/pipeline/src/geometry.rs index 641d50216b..1b4f5687f2 100644 --- a/crates/pipeline/src/geometry.rs +++ b/crates/pipeline/src/geometry.rs @@ -33,6 +33,10 @@ pub struct Frame { pub warp: Option, /// Set when this frame draws only a window of a larger output (see [`Frame::window`]). pub view: Option, + /// Mask coordinates are on the photo before the warp ([`Frame::for_mask`], + /// `lightcraft_develop::Mask::on_photo`); otherwise they are normalized coordinates of this + /// frame's transformed image, like spots and the crop. + pub masks_on_photo: bool, } /// Where a windowed [`Frame`]'s pixels sit in the full output: its offset and the full output's @@ -77,16 +81,34 @@ impl Frame { flip_v: s.crop.flip_v, warp: (!warp.is_identity()).then_some(warp), view: None, + masks_on_photo: false, }; - if apply_crop && s.geometry.constrain_crop { - f.constrain_to_image(); + if apply_crop { + f.constrain_to_image(s.geometry.constrain_crop); } f } - /// "Constrain Crop": shrink the crop about its centre until it contains no area outside the warped source. - fn constrain_to_image(&mut self) { - let Some(wp) = self.warp.as_ref().filter(|w| w.moves_pixels()) else { return }; + /// Shrink the crop about its centre until it contains no area outside the warped source. Lens + /// corrections (profile, embedded camera warp, manual distortion, lateral CA) always do this, as + /// a corrected lens never shows the blank past the photo's edge (issue #2361); perspective only + /// with "Constrain Crop" (`with_persp`), so a keystone fix can keep its corners. + pub(crate) fn constrain_to_image(&mut self, with_persp: bool) { + let Some(full) = self.warp.as_ref().filter(|w| w.moves_pixels()) else { return }; + let optics; + let wp = if with_persp || full.persp == Homography::IDENTITY { + full + } else { + let mut o = full.clone(); + o.persp = Homography::IDENTITY; + o.persp_inv = Homography::IDENTITY; + optics = o; + &optics + }; + if !wp.moves_pixels() { + return; + } + let planes: &[usize] = if wp.per_channel() { &[0, 1, 2] } else { &[1] }; let a = self.crop.output_to_source(self.ow, self.oh, 1.0, 1.0); let (w, h) = (self.ow, self.oh); let fits = |t: f64| { @@ -94,8 +116,10 @@ impl Frame { let u = i as f64 / 48.0; [(u, 0.0), (u, 1.0), (0.0, u), (1.0, u)].iter().all(|&(x, y)| { let p = Point::new(0.5 + t * (x - 0.5), 0.5 + t * (y - 0.5)); - let s = wp.to_source(a.apply(p), 1); - s.x >= -1e-6 * w && s.y >= -1e-6 * h && s.x <= w * (1.0 + 1e-6) && s.y <= h * (1.0 + 1e-6) + planes.iter().all(|&ch| { + let s = wp.to_source(a.apply(p), ch); + s.x >= -1e-6 * w && s.y >= -1e-6 * h && s.x <= w * (1.0 + 1e-6) && s.y <= h * (1.0 + 1e-6) + }) }) }) }; @@ -223,6 +247,61 @@ impl Frame { self.out_to_norm(out_w, out_h).inverse().unwrap_or(Affine::IDENTITY) } + /// This frame for evaluating mask `m`: whether its coordinates are on the photo before the + /// warp ([`lightcraft_develop::Mask::on_photo`]). + pub fn for_mask(&self, on_photo: bool) -> std::borrow::Cow<'_, Frame> { + if self.masks_on_photo == on_photo { + std::borrow::Cow::Borrowed(self) + } else { + std::borrow::Cow::Owned(Frame { masks_on_photo: on_photo, ..self.clone() }) + } + } + + /// The warp mask coordinates go through: the lens / perspective warp when masks are on the + /// photo and the warp moves pixels, else none (mask coordinates are then this frame's + /// normalized coordinates). + pub fn mask_warp(&self) -> Option<&Warp> { + self.warp.as_ref().filter(|w| self.masks_on_photo && w.moves_pixels()) + } + + /// Output pixel → mask coordinates (see [`Frame::masks_on_photo`]). + pub fn out_to_mask(&self, out_w: usize, out_h: usize) -> MaskMap { + MaskMap { + o2t: self.out_to_oriented(out_w, out_h), + to_norm: self.out_to_norm(out_w, out_h), + ow: self.ow, + oh: self.oh, + warp: self.mask_warp().cloned(), + } + } + + /// Mask coordinates → output pixel (the inverse of [`Frame::out_to_mask`]); `None` for a + /// point the warp can't invert (far outside a strong one), which has no place in the output. + pub fn mask_to_out(&self, out_w: usize, out_h: usize) -> impl Fn(Point) -> Option + use<> { + let to_out = self.norm_to_out(out_w, out_h); + let (warp, ow, oh) = (self.mask_warp().cloned(), self.ow, self.oh); + move |n: Point| match &warp { + Some(w) => w.from_source(Point::new(n.x * ow, n.y * oh)).map(|t| to_out.apply(Point::new(t.x / ow, t.y / oh))), + None => Some(to_out.apply(n)), + } + } + + /// Normalized coordinates of this frame's transformed image → mask coordinates. + pub fn norm_to_mask(&self, n: Point) -> Point { + match self.mask_warp() { + Some(w) => { + let s = w.to_source(Point::new(n.x * self.ow, n.y * self.oh), 1); + Point::new(s.x / self.ow, s.y / self.oh) + } + None => n, + } + } + + /// Mask coordinates → normalized coordinates of this frame's transformed image. + pub fn mask_to_norm(&self, n: Point) -> Point { + mask_to_norm(self.mask_warp(), self.ow, self.oh, n) + } + /// Convert normalized oriented coordinates to "long-edge units" (isotropic), used by mask shapes. pub fn norm_to_long(&self, p: Point) -> Point { let l = self.ow.max(self.oh); @@ -287,6 +366,40 @@ impl Frame { } } +/// Mask coordinates `n` (on the photo before `warp`, normalized to `ow × oh`) → normalized +/// transformed coordinates. A point the warp can't invert (far outside a strong one) stays put. +fn mask_to_norm(warp: Option<&Warp>, ow: f64, oh: f64, n: Point) -> Point { + match warp.and_then(|w| w.from_source(Point::new(n.x * ow, n.y * oh))) { + Some(t) => Point::new(t.x / ow, t.y / oh), + None => n, + } +} + +/// Output pixel → mask coordinates of a frame ([`Frame::out_to_mask`]). +#[derive(Clone, Debug)] +pub struct MaskMap { + /// Output px → transformed px, and → normalized transformed coordinates. + o2t: Affine, + to_norm: Affine, + ow: f64, + oh: f64, + warp: Option, +} + +impl MaskMap { + /// The mask coordinates at output position `p` (px; pixel centres at `x + 0.5`). + #[inline] + pub fn apply(&self, p: Point) -> Point { + match &self.warp { + Some(w) => { + let s = w.to_source(self.o2t.apply(p), 1); + Point::new(s.x / self.ow, s.y / self.oh) + } + None => self.to_norm.apply(p), + } + } +} + /// How a render resamples its source (see [`Frame::sample_plan`]). #[derive(Clone, Debug)] pub struct SamplePlan { diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index d56e8fe82d..5969447657 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -31,9 +31,14 @@ 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; +pub mod mask_space; pub mod masks; pub mod optics; pub mod output; @@ -226,6 +231,8 @@ pub(crate) struct Prepared { pub base: Arc, pub clarity_blur: Option>, pub texture_blur: Option>, + /// Log luminance blurred at the sharpen radius (the pixel-scale band sharpening boosts). + pub sharpen_blur: Option>, pub dark: Option>, /// Blurred chromaticity (`rgb / Y`) for local Moiré / Noise. pub chroma_blur: Option>, @@ -252,6 +259,10 @@ pub fn frame_for(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, apply_cro let mut frame = geometry::Frame::with_lens(src.width, src.height, s, apply_crop, info.lens.as_ref()); if s.optics.remove_ca && s.section_enabled("optics") { frame.add_lateral_ca(optics::estimate_lateral_ca(src)); + if apply_crop { + // The estimated CA moves the colour planes too: keep the crop inside every one of them. + frame.constrain_to_image(s.geometry.constrain_crop); + } } frame } @@ -324,7 +335,7 @@ impl StageCache { } let pl = &e.planes; let planes = pl.log_l.iter().chain(pl.base.iter().map(|x| &x.1)).chain(pl.clarity.iter().map(|x| &x.1)); - for p in planes.chain(pl.texture.iter().map(|x| &x.1)).chain(pl.dark.iter().map(|x| &x.1)) { + for p in planes.chain(pl.texture.iter().map(|x| &x.1)).chain(pl.sharpen.iter().map(|x| &x.1)).chain(pl.dark.iter().map(|x| &x.1)) { add(Arc::as_ptr(p) as usize, size(p)); } } @@ -384,6 +395,8 @@ pub struct Plan<'a> { pub px_per_long: f64, /// Long edge of the source buffer (px). pub src_long: usize, + /// Long edge of the original photo, shared by sharpening and noise reduction. + pub native_long: usize, /// Output pixels per pixel of the original photo ([`SourceInfo::native_long`], else the source /// buffer), at most 1: the scale of noise reduction, whose radii are in the original's pixels. pub detail_scale: f32, @@ -473,7 +486,23 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R [d.nr_luminance, d.nr_detail, d.nr_color, d.nr_color_detail, d.nr_color_smoothness].map(f64::to_bits), detail_scale.to_bits(), )); - Plan { settings, frame, w, h, px_per_long, src_long, detail_scale, geo, lin_key, pre_nr_key, eyes, fixed_air, keep, mattes: info.mattes.clone() } + Plan { + settings, + frame, + w, + h, + px_per_long, + src_long, + native_long, + detail_scale, + geo, + lin_key, + pre_nr_key, + eyes, + fixed_air, + keep, + mattes: info.mattes.clone(), + } } /// Whether the scene-linear stage needs work only the CPU does (defringe, spot removal). @@ -606,7 +635,7 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende Some(p) if req.quality == Quality::Draft && p.pre_nr == plan.pre_nr_key => p.for_other_nr(), _ => local::Planes { key: lin_key, pre_nr: plan.pre_nr_key, ..Default::default() }, }; - let mut prep = local::prepare(lin.clone(), s, frame, px_per_long, req.quality, &mut planes, plan.mattes.as_deref()); + let mut prep = local::prepare(lin.clone(), s, frame, px_per_long, plan.native_long as f64, req.quality, &mut planes, plan.mattes.as_deref()); if let Some(a) = plan.fixed_air { prep.air = a; } @@ -684,7 +713,8 @@ pub fn color_range_sample(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, /// (the one the render evaluated, or for a hidden mask a fresh evaluation). fn overlay_alpha(o: Overlay, plan: &Plan<'_>, prep: &Prepared) -> Option { if o.reads_detail() { - return visualize::sharpen_plane(o, &plan.settings, &prep.log_l, prep.texture_blur.as_deref(), plan.px_per_long); + let band = if local::pixel_sharpen(&plan.settings) { &prep.sharpen_blur } else { &prep.texture_blur }; + return visualize::sharpen_plane(o, &plan.settings, &prep.log_l, band.as_deref(), plan.px_per_long, plan.native_long as f64); } let m = o.mask(&plan.settings)?; if let Some(e) = prep.masks.iter().find(|e| e.id == m.id) { @@ -752,10 +782,18 @@ mod tests_geometry; #[cfg(test)] mod tests_hdr; #[cfg(test)] +mod tests_legacy; +#[cfg(test)] +mod tests_light; +#[cfg(test)] mod tests_local; #[cfg(test)] +mod tests_mask_geometry; +#[cfg(test)] mod tests_nr_scale; #[cfg(test)] +mod tests_sharpen; +#[cfg(test)] mod tests_tone; #[cfg(test)] mod tests_window; diff --git a/crates/pipeline/src/light_v3.rs b/crates/pipeline/src/light_v3.rs new file mode 100644 index 0000000000..43f836101a --- /dev/null +++ b/crates/pipeline/src/light_v3.rs @@ -0,0 +1,439 @@ +//! Process V4's Contrast and Blacks on the camera-look path (a raw with its camera's tone +//! curve): pointwise operators fitted to how Lightroom's sliders move a photo's tones, applied +//! after the camera curve with V2 Whites. Method, operator family and the fitted constants' provenance: +//! `docs/light-v3.md`; the constants are in [`crate::light_v3_params`] (generated). +//! +//! Each slider is an operator `F_a` on encoded values `v` (linear ProPhoto RGB, D50, Bradford from +//! the D65 working space, through the sRGB transfer curve), anchored at `F_0` = identity: +//! +//! - `a > 0`: `F_a(v) = v + s(a)·D₊(v)`; `a < 0`: `F_a(v) = max(0, v − s(a)·D₋(v))`, with `D` piecewise +//! linear on 12 fixed knots (`D(1) = 0`, and for Contrast `D(0) = 0`) and the amount law +//! `s(t) = ((1 − e^(−t/τ)) / (1 − e^(−1/τ)))^q`, `t = |a|/100`, one `(τ, q)` per sign; +//! - applied per channel ([`Mode::PerChannel`]), to the encoded ProPhoto luminance with linear RGB +//! scaled by the luminance ratio ([`Mode::Luminance`]), or a blend of the two in linear light +//! ([`Mode::Mix`], one weight per sign). +//! +//! The functions here port `Family.curve`, `Family.apply`, `Family.law` of +//! `fit_pointwise.py` (the fitting tool) exactly; [`Fit::unpack`] is its `Family.unpack`. Each +//! active operator is tabulated once per render ([`LUT_N`] entries over `v` in 0..1, interpolated +//! linearly). High-bit-depth CPU exports and the GPU read these tables ([`LightOps`]); 8-bit CPU +//! renders compose per-channel operations over linear input ([`PreviewOps`]). Luminance operations +//! retain the original evaluation, including any preceding per-channel operation. + +use lightcraft_color::{Mat3, PROPHOTO, REC2020}; +use lightcraft_develop::{DevelopSettings, Process}; + +use crate::SourceInfo; +use crate::light_v3_params as fitted; + +/// Entries of an operator's table over encoded `v` in 0..=1. +pub const LUT_N: usize = 1024; + +/// Linear ProPhoto RGB luminance (the Y row of ProPhoto → XYZ D50), as the fit computes it. +pub const PRO_Y: [f32; 3] = [0.288_040_2, 0.711_874_1, 0.000_085_7]; + +/// How an operator is applied to a pixel. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// To each encoded ProPhoto channel. + PerChannel, + /// To the encoded ProPhoto luminance; linear RGB is scaled by the luminance ratio. + Luminance, + /// `w·PerChannel + (1 − w)·Luminance` in linear light, with a weight per sign. + Mix, +} + +impl Mode { + /// The GPU kernel's code (`LIGHT_MODE` in `crates/gpu/src/params.rs`). + pub fn code(self) -> u32 { + match self { + Mode::PerChannel => 0, + Mode::Luminance => 1, + Mode::Mix => 2, + } + } +} + +/// One slider's fitted parameters, laid out as `fit_pointwise.py`'s `Family`: 11 values of `D₊` at +/// the knots but the last (`D(1) = 0`), 11 of `D₋`, then `ln τ₊, ln q₊, ln τ₋, ln q₋`, then two mix +/// logits (positive, negative amounts) in [`Mode::Mix`]. +#[derive(Clone, Copy, Debug)] +pub struct Fit { + pub mode: Mode, + /// Contrast moves tones both ways around a pivot: its shapes are anchored at black too (`D(0) = 0`). + pub signed: bool, + pub params: &'static [f64], +} + +const KNOTS_N: usize = fitted::KNOTS.len(); + +/// A [`Fit`] unpacked (`Family.unpack`). +#[derive(Clone, Copy, Debug)] +pub struct Unpacked { + pub d_pos: [f64; KNOTS_N], + pub d_neg: [f64; KNOTS_N], + /// `(τ, q)` of the amount law, positive and negative amounts. + pub law_pos: (f64, f64), + pub law_neg: (f64, f64), + /// Mix weights of the per-channel result for positive and negative amounts (1 outside [`Mode::Mix`]). + pub weights: (f64, f64), +} + +fn sigmoid(x: f64) -> f64 { + 1.0 / (1.0 + (-x).exp()) +} + +impl Fit { + /// The parameters unpacked; `None` when their number doesn't fit the layout. + pub fn unpack(&self) -> Option { + let n = KNOTS_N - 1; + let p = self.params; + let mix = self.mode == Mode::Mix; + let len = 2 * n + 4 + if mix { 2 } else { 0 }; + if p.len() != len { + return None; + } + // D(1) = 0 is appended (the last knot stays 0) + let shape = |off: usize| -> Option<[f64; KNOTS_N]> { + let mut d = [0.0; KNOTS_N]; + for (k, slot) in d.iter_mut().take(n).enumerate() { + *slot = *p.get(off + k)?; + } + Some(d) + }; + let (mut d_pos, mut d_neg) = (shape(0)?, shape(n)?); + if self.signed { + d_pos[0] = 0.0; + d_neg[0] = 0.0; + } + let at = |i: usize| p.get(i).copied(); + let i = 2 * n; + let law_pos = (at(i)?.exp(), at(i + 1)?.exp()); + let law_neg = (at(i + 2)?.exp(), at(i + 3)?.exp()); + let weights = if mix { (sigmoid(at(i + 4)?), sigmoid(at(i + 5)?)) } else { (1.0, 1.0) }; + Some(Unpacked { d_pos, d_neg, law_pos, law_neg, weights }) + } +} + +/// The amount law `s(t)` (`Family.law`): 1 at `|a| = 100`, linear as `τ` grows, saturating as it +/// shrinks. +pub fn law((tau, q): (f64, f64), a: f64) -> f64 { + let t = (a.abs() / 100.0).min(1.0); + let tau = tau.clamp(1e-3, 1e3); + ((1.0 - (-t / tau).exp()) / (1.0 - (-1.0 / tau).exp())).powf(q) +} + +/// `numpy.interp(v, KNOTS, d)`: piecewise linear, constant beyond the ends. +fn interp(v: f64, d: &[f64; KNOTS_N]) -> f64 { + let k = &fitted::KNOTS; + if v <= k[0] { + return d[0]; + } + for i in 1..KNOTS_N { + if v <= k[i] { + let t = (v - k[i - 1]) / (k[i] - k[i - 1]); + return d[i - 1] + t * (d[i] - d[i - 1]); + } + } + d[KNOTS_N - 1] +} + +impl Unpacked { + /// `F_a(v)` on an encoded value (`Family.curve`). + pub fn curve(&self, a: f64, v: f64) -> f64 { + if a == 0.0 { + return v; + } + if a > 0.0 { + return v + law(self.law_pos, a) * interp(v, &self.d_pos); + } + (v - law(self.law_neg, a) * interp(v, &self.d_neg)).max(0.0) + } +} + +/// One slider's operator at one amount, tabulated: `lut[i]` is the *linear* value of +/// `F_a(i / (LUT_N − 1))` (decoded with the sRGB curve), made non-decreasing (see [`Operator::new`]). +#[derive(Clone, Debug)] +pub struct Operator { + pub mode: Mode, + /// Weight of the per-channel result ([`Mode::Mix`]; 1 for per channel, 0 for luminance). + pub weight: f32, + pub lut: Box<[f32; LUT_N]>, +} + +impl Operator { + /// `fit` at `amount` (-100..100); `None` at 0 (the identity) or for parameters that do not unpack. + /// + /// The table is the running maximum of `F_a`: where a fitted shape folds back (a `D` rising + /// faster than 1), it is flat instead, so no two tones swap. None of the shipped fits folds. + /// The fitting tool inverts `F` the same way. + pub fn new(fit: &Fit, amount: f64) -> Option { + let a = if amount.is_finite() { amount.clamp(-100.0, 100.0) } else { 0.0 }; + if a == 0.0 { + return None; + } + let u = fit.unpack()?; + let weight = match fit.mode { + Mode::PerChannel => 1.0, + Mode::Luminance => 0.0, + Mode::Mix => (if a > 0.0 { u.weights.0 } else { u.weights.1 }) as f32, + }; + let mut lut = Box::new([0.0f32; LUT_N]); + let mut top = 0.0f64; + for (i, slot) in lut.iter_mut().enumerate() { + let v = i as f64 / (LUT_N - 1) as f64; + top = top.max(u.curve(a, v)); + *slot = srgb_decode(top) as f32; + } + // The negative Blacks fit rounds to exactly 1 in f32. Avoid calculating a luminance + // result that contributes nothing, on both CPU and GPU. + let mode = if weight == 1.0 { + Mode::PerChannel + } else if weight == 0.0 { + Mode::Luminance + } else { + Mode::Mix + }; + Some(Operator { mode, weight, lut }) + } + + /// The table at encoded `v` (clamped to 0..=1), interpolated: linear output. + #[inline] + pub fn eval(&self, v: f32) -> f32 { + let f = v.clamp(0.0, 1.0) * (LUT_N - 1) as f32; + let i = (f as usize).min(LUT_N - 2); + let t = f - i as f32; + self.lut[i] + (self.lut[i + 1] - self.lut[i]) * t + } + + /// One linear value through the operator: values above 1 (HDR renders) pass unchanged, which + /// is continuous because `F_a(1) = 1`; values below 0 (outside ProPhoto's gamut) keep their + /// distance below the image of 0, `F_a(0) + x` (continuous and increasing). This is the + /// per-channel domain: on luminance ([`Self::apply`]) a component above 1 is scaled with its + /// pixel unless the pixel's luminance is above 1. + #[inline] + pub fn channel(&self, x: f32, encode: &impl Fn(f32) -> f32) -> f32 { + if x > 1.0 { + x + } else if x < 0.0 { + self.lut[0] + x + } else { + self.eval(encode(x)) + } + } + + /// The luminance mode: linear ProPhoto `p` scaled by `F` of its luminance over its luminance + /// (unchanged when the luminance is at most 1e-6, or above 1). + #[inline] + fn luminance(&self, p: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] { + let y = PRO_Y[0] * p[0] + PRO_Y[1] * p[1] + PRO_Y[2] * p[2]; + if y.is_nan() || y <= 1e-6 || y > 1.0 { + return p; + } + let r = self.channel(y, encode) / y; + p.map(|c| c * r) + } + + /// The operator on a linear ProPhoto pixel (`Family.apply`). Per channel, each component goes + /// through [`Self::channel`] (one above 1 passes unchanged). On luminance, the pixel is scaled + /// by `F(Y) / Y` as a whole, components above 1 included, and passes unchanged only when `Y` + /// itself is above 1 (or at most 1e-6). Mix blends the two results in linear light, so an HDR + /// component of a pixel with `Y ≤ 1` moves by the luminance part's share. + #[inline] + pub fn apply(&self, p: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] { + match self.mode { + Mode::PerChannel => p.map(|c| self.channel(c, encode)), + Mode::Luminance => self.luminance(p, encode), + Mode::Mix => { + let (a, b) = (p.map(|c| self.channel(c, encode)), self.luminance(p, encode)); + let w = self.weight; + std::array::from_fn(|k| w * a[k] + (1.0 - w) * b[k]) + } + } + } +} + +/// sRGB decoding in f64 (the tables are built in f64, like the fit). +fn srgb_decode(e: f64) -> f64 { + if e <= 0.04045 { e / 12.92 } else { ((e + 0.055) / 1.055).powf(2.4) } +} + +/// Linear Rec.2020 (the working space) → linear ProPhoto RGB (D50, Bradford), and back. +pub fn prophoto_matrices() -> ([[f32; 3]; 3], [[f32; 3]; 3]) { + let to = REC2020.to_space(&PROPHOTO); + let from = to.inverse().unwrap_or(Mat3::IDENTITY); + (to.to_f32(), from.to_f32()) +} + +/// The active operators of a render, in order (Contrast, Blacks), and the conversions to +/// and from the space they work in. Applied after the tone map, chroma scaling and highlight +/// desaturation, before the colour stage (`finish::finish_with`, the GPU's `finish.wgsl`). +#[derive(Clone, Debug)] +pub struct LightOps { + pub ops: Vec, + pub to_pro: [[f32; 3]; 3], + pub from_pro: [[f32; 3]; 3], +} + +/// The fits of Contrast and Blacks, in the order they apply. +pub const FITS: [&Fit; 2] = [&fitted::CONTRAST, &fitted::BLACKS]; + +/// Whether `s` renders `info` with the V4 operators: process V4 and a raw with its camera's tone +/// curve (other sources keep the tone map's own Contrast and Blacks). +pub fn applies(s: &DevelopSettings, info: &SourceInfo) -> bool { + let camera_look = info.raw && info.camera_tone.is_some(); + match s.process.process() { + Process::V1 | Process::V2 | Process::V3 => false, + Process::V4 => camera_look, + } +} + +impl LightOps { + /// The operators of `s` for `info` (see [`applies`]); `None` when they don't apply or every + /// slider is at 0. + pub fn new(s: &DevelopSettings, info: &SourceInfo) -> Option { + if !applies(s, info) { + return None; + } + let l = &s.light; + let ops: Vec = FITS.iter().zip([l.contrast, l.blacks]).filter_map(|(f, a)| Operator::new(f, a)).collect(); + if ops.is_empty() { + return None; + } + let (to_pro, from_pro) = prophoto_matrices(); + Some(LightOps { ops, to_pro, from_pro }) + } + + /// The operators on a linear Rec.2020 pixel; `encode`: linear → sRGB-encoded on 0..1 (the + /// exact curve or the shared table, as the render encodes). + #[inline] + pub fn apply(&self, d: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] { + let mut p = mul3(&self.to_pro, d); + for op in &self.ops { + p = op.apply(p, encode); + } + mul3(&self.from_pro, p) + } +} + +/// Number of intervals over linear input for 8-bit CPU renders. Deep exports retain [`LightOps`] +/// with the exact sRGB encoder; this approximation is not used for U16 or F32 samples. +const PREVIEW_INTERVALS: usize = 16_384; + +/// An operator with its sRGB encoding and decoding included in one linear-input table. +struct LinearOperator { + black: f32, + white: f32, + // Each linear interval stores [intercept, slope], so a lookup needs no integer-to-float + // conversion or subtraction of neighbouring samples in the pixel loop. + segments: Box<[[f32; 2]; PREVIEW_INTERVALS]>, +} + +impl LinearOperator { + fn new(channel: impl Fn(f32) -> f32) -> Self { + let black = channel(0.0); + let mut previous = black; + let mut segments = Box::new([[0.0; 2]; PREVIEW_INTERVALS]); + for (i, segment) in segments.iter_mut().enumerate() { + let next = channel((i + 1) as f32 / PREVIEW_INTERVALS as f32); + let slope = (next - previous) * PREVIEW_INTERVALS as f32; + let intercept = (previous as f64 - slope as f64 * (i as f64 / PREVIEW_INTERVALS as f64)) as f32; + *segment = [intercept, slope]; + previous = next; + } + Self { black, white: previous, segments } + } + + #[inline(always)] + fn channel(&self, x: f32) -> f32 { + if x >= 1.0 { + if x == 1.0 { self.white } else { x } + } else if x < 0.0 { + self.black + x + } else { + let f = x * PREVIEW_INTERVALS as f32; + let i = (f as u32).min(PREVIEW_INTERVALS as u32 - 1) as usize; + let [intercept, slope] = self.segments[i]; + intercept + slope * x + } + } +} + +/// CPU preview tables for per-channel operations, built once per render. Luminance operations +/// use [`LightOps`] instead, so interpolation cannot change a nearly cancelling luminance sum. +pub(crate) struct PreviewOps { + ops: PreviewOperators, + to_pro: [[f32; 4]; 3], + from_pro: [[f32; 4]; 3], +} + +enum PreviewOperators { + PerChannel(LinearOperator), + Separate(Vec), +} + +impl PreviewOps { + pub(crate) fn new(exact: &LightOps, encode: &impl Fn(f32) -> f32) -> Option { + let ops = &exact.ops; + // Small per-channel errors can cross the luminance cutoff at 1e-6, or be amplified + // by F(Y) / Y. Keep every preceding operation exact too, including Contrast. + if ops.iter().any(|o| o.mode != Mode::PerChannel) { + return None; + } + // A preceding black lift could carry a negative input across zero. Only fuse when + // preceding operators fix zero, so the composed negative extension remains F(0) + x. + // Contrast fixes zero and negative Blacks is per channel, so their usual pair fuses. + let fuse = ops.iter().take(ops.len().saturating_sub(1)).all(|o| o.lut[0] == 0.0); + let ops = if fuse { + PreviewOperators::PerChannel(LinearOperator::new(|x| ops.iter().fold(x, |x, o| o.channel(x, encode)))) + } else { + PreviewOperators::Separate(ops.iter().map(|o| LinearOperator::new(|x| o.channel(x, encode))).collect()) + }; + let columns = |m: [[f32; 3]; 3]| std::array::from_fn(|i| [m[0][i], m[1][i], m[2][i], 0.0]); + Some(Self { ops, to_pro: columns(exact.to_pro), from_pro: columns(exact.from_pro) }) + } + + // Keep the single-table path in the finish loop. An out-of-line call per pixel saves + // little code here but adds register spills to this otherwise small operation. + #[inline(always)] + pub(crate) fn apply(&self, d: [f32; 3]) -> [f32; 3] { + let mut p = mul_preview(&self.to_pro, d); + match &self.ops { + PreviewOperators::PerChannel(op) => p = [op.channel(p[0]), op.channel(p[1]), op.channel(p[2])], + PreviewOperators::Separate(ops) => { + for op in ops { + p = p.map(|c| op.channel(c)); + } + } + } + mul_preview(&self.from_pro, p) + } +} + +/// Padded columns let the compiler multiply the RGB rows together in vector registers. +/// The fourth lane is unused; each RGB row keeps the same arithmetic order as `mul3`. +#[inline(always)] +fn mul_preview(m: &[[f32; 4]; 3], d: [f32; 3]) -> [f32; 3] { + let out: [f32; 4] = std::array::from_fn(|i| m[0][i] * d[0] + m[1][i] * d[1] + m[2][i] * d[2]); + [out[0], out[1], out[2]] +} + +#[inline] +fn mul3(m: &[[f32; 3]; 3], d: [f32; 3]) -> [f32; 3] { + [ + m[0][0] * d[0] + m[0][1] * d[1] + m[0][2] * d[2], + m[1][0] * d[0] + m[1][1] * d[1] + m[1][2] * d[2], + m[2][0] * d[0] + m[2][1] * d[1] + m[2][2] * d[2], + ] +} + +/// `fit_pointwise.py`'s own values for one fit at one amount (generated into +/// [`crate::light_v3_params`]; the tests check the port against them). +#[cfg(test)] +pub struct Reference { + pub amount: f64, + /// `Family.curve` at `light_v3_params::REF_V`. + pub curve: &'static [f64], + /// `Family.apply` on `light_v3_params::REF_PIX` (encoded ProPhoto), where the curve increases. + pub apply: Option<&'static [[f64; 3]]>, +} diff --git a/crates/pipeline/src/light_v3_params.rs b/crates/pipeline/src/light_v3_params.rs new file mode 100644 index 0000000000..07ce6dd0cd --- /dev/null +++ b/crates/pipeline/src/light_v3_params.rs @@ -0,0 +1,315 @@ +//! Fitted constants of process V4's Contrast and Blacks ([`crate::light_v3`]). +//! +//! GENERATED by `tools/light_v3_constants.py rust` from the committed fits named below: do not edit by hand, +//! regenerate (the script must reproduce this file byte for byte). +//! +//! The values are fitted to black-box Lightroom exports of one person's Sony ILCE-7CR photos (the exports' +//! pixels only: no Lightroom code, tables or files), each slider against the same photo's Neutral or another +//! amount exported in the same batch, on the tune photos; the check photos were held out. The exports are +//! private; errors are published only with at least three contributing photos. These are our operator family's +//! parameters (`docs/light-v3.md`), not Lightroom's. +//! +//! - Contrast: `tools/light_v3_fits/contrast.json` (fitted as `v2-contrast-pc.json`), mode `pc`; 155 tune pairs on 20 photos, 61 check pairs on 6 photos; +//! sha256 `2f04d078f1866ccb05fc279b493ccab545adbe2ac178b12df9ebc524c79c2ce1`. +//! - Blacks: `tools/light_v3_fits/blacks.json` (fitted as `v2-blacks-mix.json`), mode `mix`; 148 tune pairs on 19 photos, 60 check pairs on 6 photos; +//! sha256 `b8ee89df8f632d9559649fcba917607ade1511ecaa2041f481dd5b73a318c090`. + +use crate::light_v3::{Fit, Mode}; +#[cfg(test)] +use crate::light_v3::Reference; + +/// The family's knots: the displacement shapes are piecewise linear on them. +pub const KNOTS: [f64; 12] = [0.0, 0.02, 0.05, 0.09, 0.14, 0.2, 0.28, 0.38, 0.5, 0.65, 0.82, 1.0]; + +/// `tools/light_v3_fits/contrast.json`. +pub const CONTRAST: Fit = Fit { + mode: Mode::PerChannel, + signed: true, + params: &[ + 9.797174393178826e-18, -0.017053489024880908, -0.04260284838408044, -0.07195939270312468, -0.09738651081071477, + -0.1088504066519633, -0.10140378035603768, -0.06947815571389163, -0.007856500339789655, 0.08463087858854193, 0.1098534938016389, + 0.30583740028604467, -0.05850866310699469, -0.07854274245013221, -0.09074476735486797, -0.0906596002773617, -0.08429179542961336, + -0.07428102082426319, -0.05004459522573259, -0.00906946010144, 0.056653920573147026, 0.09818533983265328, 0.3070552562874873, + 0.10657448975892592, -0.13962415708911588, 0.37724097657204825, + ], +}; + +/// `tools/light_v3_fits/blacks.json`. +pub const BLACKS: Fit = Fit { + mode: Mode::Mix, + signed: false, + params: &[ + 0.0016748697345088984, 0.032126630862752484, 0.07188512588294256, 0.09530584096821723, 0.12925288090794965, 0.12680972925019743, + 0.10913227308994669, 0.10024857312175768, 0.0835198499581404, 0.05136152009684992, 0.02045048232256003, 0.00011845423640374467, + 0.2706623236742467, 0.42355931120492346, 0.37893058797626605, 0.22045052169596244, 0.20955478047682013, 0.2107908996685734, + 0.16685612159796198, 0.13055496600268582, 0.08667135921560576, 0.03499725744978859, 14.344979966519135, 0.1199976090379452, + 6.829791928600096, 0.5956122696562978, 0.6007994346537187, 22.053184691621333, + ], +}; + +/// Where the reference values are taken: encoded values and pixels (encoded ProPhoto). +#[cfg(test)] +pub const REF_V: [f64; 16] = [ + 0.0, 0.004, 0.012, 0.03, 0.07, 0.11, 0.17, 0.25, 0.33, 0.45, 0.58, 0.7, 0.81, 0.9, 0.97, 1.0, +]; +#[cfg(test)] +pub const REF_PIX: [[f64; 3]; 6] = [ + [0.02, 0.05, 0.01], [0.3, 0.25, 0.2], [0.55, 0.5, 0.62], [0.9, 0.85, 0.7], [0.15, 0.4, 0.35], [0.75, 0.97, 0.99], +]; + +/// The family's own `curve` at [`REF_V`] and `apply` on [`REF_PIX`] for `tools/light_v3_fits/contrast.json` (12 significant +/// digits). +#[cfg(test)] +pub const CONTRAST_REFERENCE: &[Reference] = &[ + Reference { + amount: -100.0, + curve: &[ + 0.0, 0.0157017326214, 0.0471051978642, 0.0951866895547, 0.154643754903, 0.200710700524, 0.257475697853, 0.328035061301, + 0.392162808025, 0.47614243307, 0.554016990408, 0.631130956115, 0.71425768483, 0.845452588982, 0.953635776695, 1.0, + ], + apply: Some(&[ + [0.078508663107, 0.12854274245, 0.0392543315535], [0.369433735705, 0.328035061301, 0.28429179543], + [0.537161666543, 0.509069460101, 0.576490755562], [0.845452588982, 0.768178883473, 0.631130956115], + [0.239598299469, 0.443215406038, 0.407315522905], [0.668915832804, 0.953635776695, 0.984545258898], + ]), + }, + Reference { + amount: -63.0, + curve: &[ + 0.0, 0.0117558826379, 0.0352676479138, 0.0732055944278, 0.126101694535, 0.170122852746, 0.227978700093, 0.301721466955, + 0.371201372402, 0.467327147126, 0.562778518405, 0.654353749223, 0.746542204136, 0.86384609598, 0.959153828794, 1.0, + ], + apply: Some(&[ + [0.0587794131897, 0.102057956904, 0.0293897065949], [0.346020527272, 0.301721466955, 0.255868416571], + [0.541490780829, 0.506011218203, 0.591162168506], [0.86384609598, 0.79576914397, 0.654353749223], + [0.209385555774, 0.428643076049, 0.387988602489], [0.696257592365, 0.959153828794, 0.986384609598], + ]), + }, + Reference { + amount: -25.0, + curve: &[ + 0.0, 0.00669797632024, 0.0200939289607, 0.0450295815589, 0.0895156438599, 0.130914451725, 0.19016858264, 0.267991929431, + 0.344332389013, 0.456027454879, 0.574009302137, 0.684121407008, 0.787925448518, 0.887423433092, 0.966227029927, 1.0, + ], + apply: Some(&[ + [0.0334898816012, 0.0681089814742, 0.0167449408006], [0.316008789537, 0.267991929431, 0.219434495337], + [0.547039966578, 0.502091073979, 0.609968416216], [0.887423433092, 0.831135149637, 0.684121407008], + [0.170657974176, 0.409963835778, 0.363214788663], [0.73130506224, 0.966227029927, 0.988742343309], + ]), + }, + Reference { + amount: -4.0, + curve: &[ + 0.0, 0.0042211975466, 0.0126635926398, 0.0312322222928, 0.0716000186917, 0.111714702007, 0.171653550835, 0.251475094729, + 0.331175061939, 0.450494169731, 0.579508843847, 0.698698170259, 0.808190185513, 0.898968891712, 0.969690667514, 1.0, + ], + apply: Some(&[ + [0.021105987733, 0.0514846914124, 0.0105529938665], [0.301312504095, 0.251475094729, 0.201593365611], + [0.549757317317, 0.500171439768, 0.619177545887], [0.898968891712, 0.848453337568, 0.698698170259], + [0.151693674318, 0.400816899693, 0.351083433835], [0.748467268102, 0.969690667514, 0.989896889171], + ]), + }, + Reference { + amount: -1.0, + curve: &[ + 0.0, 0.00403003956988, 0.0120901187096, 0.0301673410408, 0.0702172893598, 0.110232863843, 0.170224559253, 0.250200324153, + 0.330159578421, 0.450067110356, 0.5799332989, 0.699823205971, 0.809754219477, 0.899859971098, 0.96995799133, 1.0, + ], + apply: Some(&[ + [0.0201501978494, 0.0502016274236, 0.0100750989247], [0.300178243652, 0.250200324153, 0.200216385843], + [0.549967042657, 0.500023282251, 0.619888307225], [0.899859971098, 0.849789956648, 0.699823205971], + [0.150230008193, 0.400110938461, 0.350147134934], [0.749791848474, 0.96995799133, 0.98998599711], + ]), + }, + Reference { + amount: 1.0, + curve: &[ + 0.0, 0.00397028327185, 0.0119108498156, 0.0297772142058, 0.0695009210477, 0.109284415638, 0.169101549483, 0.249092158771, + 0.329255569926, 0.449707840731, 0.580361320706, 0.700802007104, 0.810944204495, 0.900531739739, 0.970159521922, 1.0, + ], + apply: Some(&[ + [0.0198514163593, 0.0496288098987, 0.00992570817964], [0.29917212145, 0.249092158771, 0.199051608167], + [0.550200155898, 0.499931547883, 0.620576207118], [0.900531739739, 0.850797609609, 0.700802007104], + [0.149134843694, 0.399484133579, 0.349311202243], [0.750866642282, 0.970159521922, 0.990053173974], + ]), + }, + Reference { + amount: 4.0, + curve: &[ + 0.0, 0.00386276829016, 0.0115883048705, 0.0289711762573, 0.067695255762, 0.106695434805, 0.165850959769, 0.245807593504, + 0.326562225444, 0.44865080988, 0.581668577311, 0.70370366501, 0.814360331887, 0.902455571598, 0.970736671479, 1.0, + ], + apply: Some(&[ + [0.0193138414508, 0.0482858458702, 0.0096569207254], [0.296176860778, 0.245807593504, 0.195620331007], + [0.550924318987, 0.499683888448, 0.622660921742], [0.902455571598, 0.853683357397, 0.70370366501], + [0.146004712278, 0.397617731312, 0.34681913522], [0.754002149954, 0.970736671479, 0.99024555716], + ]), + }, + Reference { + amount: 25.0, + curve: &[ + 0.0, 0.00303130723309, 0.00909392169928, 0.0227377271685, 0.0537312449465, 0.0866736973109, 0.140712707247, 0.220406592954, + 0.305733397543, 0.440476321314, 0.591778172653, 0.726143473036, 0.840778760722, 0.917333416951, 0.975200025085, 1.0, + ], + apply: Some(&[ + [0.0151565361655, 0.0379001091744, 0.00757826808274], [0.273013181027, 0.220406592954, 0.169084742294], + [0.556524593466, 0.497768628155, 0.638782944901], [0.917333416951, 0.876000125426, 0.726143473036], + [0.121798017215, 0.383184014474, 0.327546875221], [0.778250421984, 0.975200025085, 0.991733341695], + ]), + }, + Reference { + amount: 63.0, + curve: &[ + 0.0, 0.00166203669924, 0.00498611009773, 0.0124723297827, 0.0307349682338, 0.0537014072028, 0.0993144142548, 0.178575600043, + 0.271431971089, 0.427014372342, 0.608426903093, 0.763097901214, 0.884285279574, 0.941834618872, 0.982550385662, 1.0, + ], + apply: Some(&[ + [0.00831018349621, 0.0207966223556, 0.00415509174811], [0.234866663076, 0.178575600043, 0.125385281671], + [0.56574726332, 0.494614530364, 0.665333089458], [0.941834618872, 0.912751928309, 0.763097901214], + [0.0819338359776, 0.35941421432, 0.295808843098], [0.818183073196, 0.982550385662, 0.994183461887], + ]), + }, + Reference { + amount: 100.0, + curve: &[ + 0.0, 0.000589302195024, 0.00176790658507, 0.00443005785539, 0.0127188794564, 0.0278697600538, 0.0668815412687, 0.145803734783, + 0.244559031965, 0.416467809921, 0.621470101755, 0.792049294828, 0.918369810554, 0.961029718779, 0.988308915634, 1.0, + ], + apply: Some(&[ + [0.00294651097512, 0.00739715161592, 0.00147325548756], [0.204981344572, 0.145803734783, 0.091149593348], + [0.57297262597, 0.49214349966, 0.686133402803], [0.961029718779, 0.941544578168, 0.792049294828], + [0.0507028398824, 0.340792120182, 0.270944156893], [0.849467711067, 0.988308915634, 0.996102971878], + ]), + }, +]; + +/// The family's own `curve` at [`REF_V`] and `apply` on [`REF_PIX`] for `tools/light_v3_fits/blacks.json` (12 significant +/// digits). +#[cfg(test)] +pub const BLACKS_REFERENCE: &[Reference] = &[ + Reference { + amount: -100.0, + curve: &[ + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0396726450283, 0.141176489367, 0.304319552499, 0.472849624284, 0.62852690601, + 0.771963089505, 0.880557079195, 0.964167123758, 1.0, + ], + apply: Some(&[ + [0.0, 0.0, 0.0], [0.0979960559384, 0.0396726450312, 8.67909201708e-12], [0.434072902922, 0.369445033999, 0.524551919414], + [0.880557079192, 0.820835618793, 0.628526906024], [1.62784132506e-11, 0.239194070991, 0.169963444981], + [0.693725171247, 0.964167123755, 0.988055707915], + ]), + }, + Reference { + amount: -63.0, + curve: &[ + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0769799089595, 0.159002658298, 0.248306215942, 0.386971900482, 0.533641791607, 0.669077433807, + 0.793543473258, 0.891588093197, 0.967476427959, 1.0, + ], + apply: Some(&[ + [0.0, 0.0, 0.0], [0.212603750827, 0.159002658299, 0.109336909762], [0.49984457601, 0.443515883354, 0.578704745728], + [0.891588093196, 0.837382139795, 0.669077433813], [0.0554085751144, 0.330427917606, 0.27210785935], + [0.72565290629, 0.967476427958, 0.989158809318], + ]), + }, + Reference { + amount: -25.0, + curve: &[ + 0.0, 0.0, 0.0, 0.0039713718625, 0.0375281504298, 0.0844641752827, 0.152600319953, 0.232978681132, 0.314718938796, + 0.438210409673, 0.571328561555, 0.694215843567, 0.806921758549, 0.898426528234, 0.96952795847, 1.0, + ], + apply: Some(&[ + [1.38361828441e-12, 0.0157222994288, 6.91809142207e-13], [0.28365227602, 0.232978681132, 0.183041203846], + [0.540618281274, 0.489434480805, 0.612275601929], [0.898426528233, 0.84763979235, 0.694215843568], + [0.132306397362, 0.386986338539, 0.335430047312], [0.745445804924, 0.96952795847, 0.989842652823], + ]), + }, + Reference { + amount: -4.0, + curve: &[ + 0.0, 0.00384203333958, 0.0115267901451, 0.029063081396, 0.0688311531515, 0.109080820198, 0.169373686394, 0.249387305769, + 0.329449947556, 0.449575625482, 0.579687865532, 0.699791795259, 0.809889196554, 0.899943361788, 0.969983008536, 1.0, + ], + apply: Some(&[ + [0.0192115469507, 0.0487661502866, 0.00960560094376], [0.299411552286, 0.249387305769, 0.199389556317], + [0.549662298498, 0.499619686776, 0.61972195491], [0.899943361788, 0.849915042681, 0.699791795259], + [0.149363106446, 0.399531564189, 0.349475544402], [0.749836068575, 0.969983008536, 0.989994336179], + ]), + }, + Reference { + amount: -1.0, + curve: &[ + 0.0, 0.00398722513591, 0.0119617312187, 0.0299242307978, 0.0699054746135, 0.109925665346, 0.169949349621, 0.249950451029, + 0.32995551691, 0.449965680563, 0.579974757487, 0.69998316235, 0.809991039255, 0.899995419632, 0.96999862589, 1.0, + ], + apply: Some(&[ + [0.0199362373015, 0.0499002177906, 0.009968104698], [0.29995241186, 0.249950451029, 0.199950633032], + [0.549972689865, 0.499969243828, 0.619977514317], [0.899995419632, 0.849993129448, 0.69998316235], + [0.149948494014, 0.399962117299, 0.349957586943], [0.749986742762, 0.96999862589, 0.989999541963], + ]), + }, + Reference { + amount: 1.0, + curve: &[ + 9.31612027339e-06, 0.00404319245864, 0.0121109451354, 0.0302524139772, 0.0704649827756, 0.11060564863, 0.170712147943, + 0.250643898657, 0.330582319062, 0.450503332955, 0.580369162543, 0.700235118441, 0.810123865526, 0.900063195347, 0.970018958604, + 1.0, + ], + apply: Some(&[ + [0.0201752429349, 0.0503888012921, 0.0100906298252], [0.300630744288, 0.250626419466, 0.200631616538], + [0.550429399642, 0.500454032729, 0.620394920846], [0.90007223641, 0.850090998192, 0.700176696162], + [0.150565756988, 0.400578185286, 0.350572708933], [0.750135238759, 0.970032675648, 0.990024911688], + ]), + }, + Reference { + amount: 4.0, + curve: &[ + 4.44679248931e-05, 0.00420616726172, 0.0125295659354, 0.0312048283459, 0.0722194667453, 0.112890896317, 0.17339924135, + 0.253073472246, 0.332779539074, 0.452402520726, 0.581762095353, 0.701122272887, 0.810591237848, 0.900301645519, 0.970090493656, + 1.0, + ], + apply: Some(&[ + [0.0208391227968, 0.0518558616479, 0.0104339209625], [0.303010755867, 0.252990062923, 0.203015330491], + [0.55204964314, 0.502167204295, 0.621885228625], [0.900344802502, 0.850434355079, 0.700843514096], + [0.152703002383, 0.402759872928, 0.352733667786], [0.750645594216, 0.970155972394, 0.990118916658], + ]), + }, + Reference { + amount: 25.0, + curve: &[ + 0.000351031037929, 0.00562749010759, 0.0161804082469, 0.0395109485272, 0.0875205323187, 0.132820816064, 0.19683370592, + 0.274262075537, 0.351941758888, 0.468965565542, 0.593910029809, 0.708859253437, 0.814667248041, 0.902381198134, 0.97071435944, + 1.0, + ], + apply: Some(&[ + [0.0268094892594, 0.0646518089884, 0.0135180994291], [0.323771669718, 0.273605097162, 0.223833590382], + [0.566181459749, 0.517108276593, 0.63489439536], [0.902722015601, 0.853428836176, 0.7066658074], + [0.171494494367, 0.421790810113, 0.371579649929], [0.755101084946, 0.971231540587, 0.990939254456], + ]), + }, + Reference { + amount: 63.0, + curve: &[ + 0.000995014140305, 0.00861319796625, 0.0238495656181, 0.0569592350811, 0.11966278055, 0.174686686427, 0.246061413214, + 0.31877200482, 0.392194957135, 0.503758795817, 0.619428639797, 0.725111974413, 0.823229536124, 0.906749619145, 0.972024885744, + 1.0, + ], + apply: Some(&[ + [0.0404539765541, 0.0915381262658, 0.0205483468996], [0.367405560588, 0.316916949778, 0.267702217691], + [0.595875558955, 0.54849590131, 0.662288333975], [0.907716480454, 0.859719346711, 0.718935705489], + [0.211650252506, 0.461789763271, 0.411168543529], [0.764487032294, 0.973492582642, 0.992665468794], + ]), + }, + Reference { + amount: 100.0, + curve: &[ + 0.00167486973451, 0.0117652219602, 0.0319459264115, 0.0753794625361, 0.153595483426, 0.218884656944, 0.298031305079, + 0.36576131915, 0.434690423106, 0.540490151276, 0.646368740699, 0.742270038399, 0.832268778662, 0.911361379068, 0.97340841372, + 1.0, + ], + apply: Some(&[ + [0.055421940602, 0.119927912612, 0.0288346946948], [0.413495225374, 0.362648809539, 0.314154311953], + [0.627234264731, 0.5816340005, 0.691296631565], [0.912990263469, 0.866360468302, 0.731944464499], + [0.254705410536, 0.504042777472, 0.452962701964], [0.774433618221, 0.975881980047, 0.994492187831], + ]), + }, +]; diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index 6d09cf7557..22c17571f9 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -4,7 +4,7 @@ use lightcraft_color::cct::{temp_tint_to_xy, wb_matrix, xy_to_temp_tint}; use lightcraft_color::{REC2020, luminance_2020}; use lightcraft_develop::{DevelopSettings, Process}; -use lightcraft_raster::blur::gaussian; +use lightcraft_raster::blur::{gauss_taps, gaussian, gaussian_taps}; use std::sync::Arc; use lightcraft_raster::{Plane, Rgb32f, par_join}; @@ -371,11 +371,11 @@ pub fn base_detail_radius(px_per_long: f64) -> usize { } /// Median radius (px) of the highlights/shadows base of `s`'s rendering process at `px_per_long`: -/// 0 (no median) under V1, [`base_detail_radius`] from V2. +/// 0 (no median) under V1, [`base_detail_radius`] from V2 (later processes keep V2's base). pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize { match s.process.process() { Process::V1 => 0, - Process::V2 => base_detail_radius(px_per_long), + Process::V2 | Process::V3 | Process::V4 => base_detail_radius(px_per_long), } } @@ -521,6 +521,8 @@ pub(crate) struct Planes { pub base: Option<(BaseKey, Arc)>, pub clarity: Option<(u32, Arc)>, pub texture: Option<(u32, Arc)>, + /// Sharpening blur (exact Gaussian at the sharpen radius). + pub sharpen: Option<(SharpenKey, Arc)>, /// Dark channel and its airlight. pub dark: Option<(u32, Arc, f32)>, /// Blurred chromaticity (local Moiré / Noise). @@ -532,7 +534,7 @@ impl Planes { /// enough for a draft: the wide blurs (base, clarity, dehaze, chromaticity). Its `key` matches /// no image, so only another draft takes them. pub fn for_other_nr(self) -> Planes { - Planes { key: 0, pre_nr: self.pre_nr, log_l: None, texture: None, ..self } + Planes { key: 0, pre_nr: self.pre_nr, log_l: None, texture: None, sharpen: None, ..self } } } @@ -541,6 +543,16 @@ impl Planes { /// processes, so a photo moved to another one (Update to Current Process, undo) recomputes it. pub type BaseKey = (u32, Process, usize); +pub type SharpenKey = (u32, Process); + +pub fn sharpen_key(s: &DevelopSettings, sigma: f32) -> SharpenKey { + (sigma.to_bits(), s.process.process()) +} + +pub fn pixel_sharpen(s: &DevelopSettings) -> bool { + s.process.process() >= Process::V3 +} + /// The [`BaseKey`] of a base at `sigma` for `s` (`detail`: [`PlaneSigmas::base_detail`]). pub fn base_key(s: &DevelopSettings, sigma: f32, detail: usize) -> BaseKey { (sigma.to_bits(), s.process.process(), detail) @@ -584,6 +596,8 @@ pub struct PlaneSigmas { pub clarity: Option, /// Texture / sharpening band (Gaussian). pub texture: Option, + /// Sharpening blur (exact Gaussian, see [`sharpen_sigma`]). + pub sharpen: Option, /// Dehaze dark channel (Gaussian). pub dark: Option, /// Chromaticity blur for local Moiré / colour noise (Gaussian). @@ -595,7 +609,45 @@ pub fn texture_sigma(px_per_long: f64) -> f32 { (0.0018 * px_per_long as f32).max(0.6) } -pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, q: Quality) -> PlaneSigmas { +/// Sharpening blur radius in output pixels before clamping: Radius (source pixels) times the +/// output pixels per original pixel (`native_long` = the original photo's long edge), so a preview and +/// an export show the same detail at the same displayed scale. +pub fn sharpen_sigma_raw(s: &DevelopSettings, px_per_long: f64, native_long: f64) -> f32 { + let r = s.detail.sharpen_radius; + let radius = if r.is_finite() { r.clamp(0.1, 10.0) } else { 1.0 }; + (radius * px_per_long / native_long.max(1.0)) as f32 +} + +/// Smallest and largest sigma (px) of the sharpening blur. The largest is the most the Gaussian taps +/// support (CPU and GPU share them), so an enlarging export keeps every Radius step distinct. +pub const SHARPEN_SIGMA_MIN: f32 = 0.5; +pub const SHARPEN_SIGMA_MAX: f32 = lightcraft_raster::blur::GAUSS_SIGMA_MAX; + +/// The sharpening blur's sigma for a raw value of [`sharpen_sigma_raw`]. +pub fn sharpen_sigma(raw: f32) -> f32 { + raw.clamp(SHARPEN_SIGMA_MIN, SHARPEN_SIGMA_MAX) +} + +/// Match the continuous Gaussian's Nyquist response below half a pixel, using a representable +/// FIR blur. Blend the correction out between half and one pixel: no jump at the floor, and +/// full-pixel sharpening (including Radius 1 at native size) is unchanged. +pub fn sharpen_gain(raw: f32) -> f32 { + if !raw.is_finite() || raw <= 0.0 { + return 0.0; + } + if raw >= 1.0 { + return 1.0; + } + let taps = gauss_taps(sharpen_sigma(raw)); + let radius = taps.len() / 2; + let response = taps.iter().enumerate().map(|(i, &t)| if (i + radius).is_multiple_of(2) { t } else { -t }).sum::(); + let desired = -(-0.5 * std::f32::consts::PI.powi(2) * raw * raw).exp_m1(); + let ratio = desired / (1.0 - response).max(1e-6); + let blend = ((1.0 - raw) / 0.5).clamp(0.0, 1.0); + 1.0 + (ratio - 1.0) * blend +} + +pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, native_long: f64, q: Quality) -> PlaneSigmas { let ppl = px_per_long as f32; // A hidden mask, or one with no components, does not change the picture. Its sliders must // not pick the tone base Clarity reads (#1214). @@ -614,16 +666,19 @@ pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, q: Quality) -> PlaneS let clarity = (s.effects.clarity != 0.0 || local_any(|a| a.clarity)).then(|| (0.012 * ppl).max(1.0)); // local Noise and Defringe read the fine detail band too let texture = (s.effects.texture != 0.0 - || s.detail.sharpen_amount != 0.0 || local_any(|a| a.texture) - || local_any(|a| a.sharpness) || local_any(|a| a.noise) + || (!pixel_sharpen(s) && (s.detail.sharpen_amount != 0.0 || local_any(|a| a.sharpness))) || s.masks.iter().filter(live).any(|m| m.adjust.defringe > 0.0)) .then(|| texture_sigma(px_per_long)); let dark = (s.effects.dehaze != 0.0 || local_any(|a| a.dehaze)).then(|| (0.02 * ppl).max(1.0)); let chroma = (local_any(|a| a.moire) || s.masks.iter().filter(live).any(|m| m.adjust.noise > 0.0)).then(|| (CHROMA_SIGMA * ppl).max(1.0)); let base_detail = if base.is_some() { tone_base_detail(s, px_per_long) } else { 0 }; - PlaneSigmas { base, base_detail, clarity, texture, dark, chroma } + // V1/V2 keep their texture-band sharpening; only V3 requests the pixel-scale plane. + let sharpen_raw = sharpen_sigma_raw(s, px_per_long, native_long); + let sharpen = (pixel_sharpen(s) && sharpen_gain(sharpen_raw) > 0.0 && (s.detail.sharpen_amount != 0.0 || local_any(|a| a.sharpness))) + .then(|| sharpen_sigma(sharpen_raw)); + PlaneSigmas { base, base_detail, clarity, texture, sharpen, dark, chroma } } /// The spatial planes the per-pixel stage needs for `img` (white-balanced, before exposure), @@ -635,15 +690,23 @@ pub(crate) fn prepare( s: &DevelopSettings, frame: &Frame, px_per_long: f64, + native_long: f64, q: Quality, planes: &mut Planes, mattes: Option<&masks::Mattes>, ) -> Prepared { let log_l = planes.log_l.get_or_insert_with(|| Arc::new(timed("log_l", || img.map(log_lum)))).clone(); - let PlaneSigmas { base: base_sigma, base_detail, clarity: clarity_sigma, texture: texture_sigma, dark: dark_sigma, chroma: chroma_sigma } = - plane_sigmas(s, px_per_long, q); + let PlaneSigmas { + base: base_sigma, + base_detail, + clarity: clarity_sigma, + texture: texture_sigma, + sharpen: sharpen_sigma_px, + dark: dark_sigma, + chroma: chroma_sigma, + } = plane_sigmas(s, px_per_long, native_long, q); - let Planes { base: sb, clarity: sc, texture: st, dark: sd, chroma: sch, .. } = planes; + let Planes { base: sb, clarity: sc, texture: st, sharpen: ss, dark: sd, chroma: sch, .. } = planes; let chroma_blur = chroma_sigma.map(|sg| match sch { Some((k, c)) if *k == sg.to_bits() => c.clone(), _ => { @@ -653,14 +716,22 @@ pub(crate) fn prepare( } }); let l = &log_l; - let (base, (clarity_blur, (texture_blur, dark))) = par_join( + let (base, (clarity_blur, ((texture_blur, sharpen_blur), dark))) = par_join( || base_sigma.map(|sg| plane_at(sb, base_key(s, sg, base_detail), || timed("base", || tone_base(l, sg, base_detail)))), || { par_join( || clarity_sigma.map(|sg| plane_at(sc, sg.to_bits(), || timed("clarity", || guided_fast(l, sg, CLARITY_EPS)))), || { par_join( - || texture_sigma.map(|sg| plane_at(st, sg.to_bits(), || timed("texture", || gaussian(l, sg)))), + || { + par_join( + || texture_sigma.map(|sg| plane_at(st, sg.to_bits(), || timed("texture", || gaussian(l, sg)))), + || { + sharpen_sigma_px + .map(|sg| plane_at(ss, sharpen_key(s, sg), || timed("sharpen", || gaussian_taps(l, &gauss_taps(sg))))) + }, + ) + }, || { dark_sigma.map(|sg| match sd { Some((k, d, air)) if *k == sg.to_bits() => (d.clone(), *air), @@ -684,7 +755,7 @@ pub(crate) fn prepare( }; let ev = s.light.exposure as f32; let masks = timed("masks", || masks::evaluate(&s.masks, frame, img.width, img.height, &img, &log_l, ev, mattes)); - Prepared { img, log_l, base, clarity_blur, texture_blur, dark, chroma_blur, air, masks, px_per_long } + Prepared { img, log_l, base, clarity_blur, texture_blur, sharpen_blur, dark, chroma_blur, air, masks, px_per_long } } /// The airlight of the whole output frame, estimated on a small render of it (`proxy_w` px wide): @@ -814,17 +885,17 @@ mod tests { adjust: lightcraft_develop::LocalAdjustments { highlights: 40.0, ..Default::default() }, ..Default::default() }); - assert!(plane_sigmas(&s, 2000.0, Quality::Full).base.is_none()); + assert!(plane_sigmas(&s, 2000.0, 2000.0, Quality::Full).base.is_none()); s.masks[0].visible = true; s.masks[0].components.clear(); - assert!(plane_sigmas(&s, 2000.0, Quality::Full).base.is_none()); + assert!(plane_sigmas(&s, 2000.0, 2000.0, Quality::Full).base.is_none()); s.masks[0].components.push(MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: MaskShape::Linear { start: Point::new(0.0, 0.0), end: Point::new(1.0, 0.0) }, }); - assert!(plane_sigmas(&s, 2000.0, Quality::Full).base.is_some()); + assert!(plane_sigmas(&s, 2000.0, 2000.0, Quality::Full).base.is_some()); } #[test] diff --git a/crates/pipeline/src/lut.rs b/crates/pipeline/src/lut.rs index 00f6ea1852..971599cbbf 100644 --- a/crates/pipeline/src/lut.rs +++ b/crates/pipeline/src/lut.rs @@ -1,7 +1,7 @@ //! 3D LUT profiles: `.cube` files (the plain-text Cube LUT format: `LUT_3D_SIZE`, optional //! `DOMAIN_MIN` / `DOMAIN_MAX`, then size³ "r g b" lines with red changing fastest), applied to //! the display-encoded output colour and blended by the profile amount. Profiles are registered -//! here by id (`lut:…`) and found by the finishing stage; LUT profiles render on the CPU. +//! here by id (`lut:…`) and found by the finishing stage (CPU loop and GPU kernel alike). use std::collections::HashMap; use std::sync::{Arc, OnceLock, RwLock}; @@ -110,7 +110,7 @@ pub fn unregister(id: &str) { registry().write().unwrap_or_else(|e| e.into_inner()).remove(id); } -/// Profile ids that render with a LUT (and so on the CPU). +/// Profile ids that render with a LUT. pub fn is_lut_profile(id: &str) -> bool { id.starts_with("lut:") } diff --git a/crates/pipeline/src/mask_space.rs b/crates/pipeline/src/mask_space.rs new file mode 100644 index 0000000000..36b998ab5e --- /dev/null +++ b/crates/pipeline/src/mask_space.rs @@ -0,0 +1,473 @@ +//! Moving a mask's coordinates between frames: [`attach`] puts an old mask's coordinates (on the +//! corrected frame) on the photo before the warp ([`lightcraft_develop::Mask::on_photo`]), and +//! [`turn`] follows a quarter turn or flip of the photo (Rotate Left / Right). Gradients, brush +//! strokes and clicks move point by point; stored AI segmentations are resampled. + +use lightcraft_develop::{Mask, MaskShape, SegMask}; +use lightcraft_geom::{Orientation, Point}; + +use crate::geometry::Frame; +use crate::masks::SegGrid; + +/// Put mask `m`, drawn on the corrected (transformed) image of `frame`, on the photo before the +/// warp: it then renders where it did under `frame` and stays on that content whatever lens +/// corrections, Upright or Transform do later. A mask already on the photo is left alone. +/// +/// Points move exactly; a gradient's shape (a radial's radii and angle, a linear's direction and +/// width) goes through the warp's local linear part at the gradient, so it covers the same region +/// as long as the warp is close to linear across it (lens and perspective warps are smooth). +pub fn attach(m: &mut Mask, frame: &Frame) { + if m.on_photo { + return; + } + m.on_photo = true; + let f = frame.for_mask(true); + if f.mask_warp().is_none() { + // without a warp both are the same coordinates + return; + } + let fwd = |p: Point| f.norm_to_mask(p); + let back = |p: Point| f.mask_to_norm(p); + let l = f.ow.max(f.oh).max(1e-9); + let (sx, sy) = (f.ow / l, f.oh / l); + for c in &mut m.components { + match &mut c.shape { + MaskShape::Linear { start, end } => (*start, *end) = attach_linear(*start, *end, &fwd, sx, sy), + MaskShape::Radial { center, rx, ry, angle, .. } => { + let mid = *center; + *center = fwd(mid); + if let Some(j) = jacobian(&fwd, mid, sx, sy) + && let Some((nrx, nry, na)) = attach_ellipse(j, *rx, *ry, *angle) + { + (*rx, *ry, *angle) = (nrx, nry, na); + } + } + _ => {} + } + } + remap(m, &fwd, &back, 0.0, false); +} + +/// The local linear part of `f` (normalized → normalized) at `p`, in long-edge units (isotropic; +/// `sx`, `sy` are the frame's sides over its long side): `[a, b, c, d]` takes `(dx, dy)` to +/// `(a dx + b dy, c dx + d dy)`. `None` where `f` isn't finite or collapses. +fn jacobian(f: &dyn Fn(Point) -> Point, p: Point, sx: f64, sy: f64) -> Option<[f64; 4]> { + const H: f64 = 1e-4; + let (o, px, py) = (f(p), f(Point::new(p.x + H, p.y)), f(Point::new(p.x, p.y + H))); + let j = [(px.x - o.x) / H, (py.x - o.x) * sx / (H * sy), (px.y - o.y) * sy / (H * sx), (py.y - o.y) / H]; + let det = j[0] * j[3] - j[1] * j[2]; + (j.iter().all(|v| v.is_finite()) && det.is_finite() && det.abs() > 1e-9).then_some(j) +} + +/// A linear gradient from `start` to `end` (normalized, on the corrected frame) on the photo: +/// its start moves through `f`, and its direction and length follow the local linear part, so +/// its bands (lines at right angles to it) land on the same content. The end moves through `f` +/// alone where that part isn't defined. +fn attach_linear(start: Point, end: Point, f: &dyn Fn(Point) -> Point, sx: f64, sy: f64) -> (Point, Point) { + let (a, plain_end) = (f(start), f(end)); + let mid = Point::new((start.x + end.x) / 2.0, (start.y + end.y) / 2.0); + let Some([ja, jb, jc, jd]) = jacobian(f, mid, sx, sy) else { return (a, plain_end) }; + // the bands are level sets of (p - start)·d / |d|²: through J they keep that form with the + // normal J^-T d, and the same |d|² sets the length + let d = ((end.x - start.x) * sx, (end.y - start.y) * sy); + let det = ja * jd - jb * jc; + let n = ((jd * d.0 - jc * d.1) / det, (-jb * d.0 + ja * d.1) / det); + let (dd, nn) = (d.0 * d.0 + d.1 * d.1, n.0 * n.0 + n.1 * n.1); + if !(dd.is_finite() && nn.is_finite()) || nn < 1e-18 { + return (a, plain_end); + } + let k = dd / nn; + let e = Point::new(a.x + n.0 * k / sx, a.y + n.1 * k / sy); + if e.x.is_finite() && e.y.is_finite() { (a, e) } else { (a, plain_end) } +} + +/// An ellipse of radii `rx`, `ry` (long-edge units) turned by `angle` degrees, through the linear +/// map `j` (long-edge units): the radii and angle of the ellipse it becomes, `rx` staying the +/// radius along the image of the old `rx` axis. `None` when the result isn't usable. +fn attach_ellipse(j: [f64; 4], rx: f64, ry: f64, angle: f64) -> Option<(f64, f64, f64)> { + let (s, c) = angle.to_radians().sin_cos(); + // M = J · R(angle) · diag(rx, ry): its columns are the images of the two semi-axes + let m = [(j[0] * c + j[1] * s) * rx, (j[1] * c - j[0] * s) * ry, (j[2] * c + j[3] * s) * rx, (j[3] * c - j[2] * s) * ry]; + // the new ellipse's axes: eigenvectors of M Mᵀ, its radii the square roots of the eigenvalues + let (p, q, r) = (m[0] * m[0] + m[1] * m[1], m[0] * m[2] + m[1] * m[3], m[2] * m[2] + m[3] * m[3]); + let (half, det) = ((p + r) / 2.0, p * r - q * q); + let root = (half * half - det).max(0.0).sqrt(); + let (l1, l2) = (half + root, (half - root).max(0.0)); + let v1 = if q.abs() > 1e-15 * (p.abs() + r.abs()) { + let (x, y) = (q, l1 - p); + let n = x.hypot(y); + (x / n, y / n) + } else if p >= r { + (1.0, 0.0) + } else { + (0.0, 1.0) + }; + let v2 = (-v1.1, v1.0); + // the old rx axis, mapped + let a = (m[0], m[2]); + let along1 = (a.0 * v1.0 + a.1 * v1.1).abs() >= (a.0 * v2.0 + a.1 * v2.1).abs(); + let (axis, nrx, nry) = if along1 { (v1, l1.sqrt(), l2.sqrt()) } else { (v2, l2.sqrt(), l1.sqrt()) }; + // (pointing the way the old axis went) + let axis = if axis.0 * a.0 + axis.1 * a.1 < 0.0 { (-axis.0, -axis.1) } else { axis }; + let na = axis.1.atan2(axis.0).to_degrees(); + (nrx.is_finite() && nry.is_finite() && na.is_finite() && nrx > 0.0 && nry > 0.0).then_some((nrx, nry, na)) +} + +/// Follow `turn` (the change of the user orientation, e.g. a quarter turn clockwise): mask +/// coordinates are on the oriented photo, so they turn with it. Radial angles turn by the same +/// quarter turns; sizes (long-edge units) don't change. +pub fn turn(m: &mut Mask, turn: Orientation) { + if turn == Orientation::Normal { + return; + } + let fwd = |p: Point| { + let (x, y) = turn.map(p.x, p.y, 1.0, 1.0); + Point::new(x, y) + }; + let inv = turn.inverse(); + let back = |p: Point| { + let (x, y) = inv.map(p.x, p.y, 1.0, 1.0); + Point::new(x, y) + }; + let (flip, quarters) = turn.to_parts(); + // a radial's angle is clockwise on screen: a quarter turn clockwise adds 90°; a mirror negates it first + let delta = 90.0 * quarters as f64; + if flip { + for c in &mut m.components { + if let MaskShape::Radial { angle, .. } = &mut c.shape { + *angle = -*angle; + } + } + } + remap(m, &fwd, &back, delta, true); +} + +/// Move every place `m` stores: `fwd` maps an old point to the new frame, `back` a new point to +/// the old one (for resampling segmentations); radial angles change by `delta` degrees. With +/// `gradients` false, linear and radial gradients are left to the caller. +fn remap(m: &mut Mask, fwd: &dyn Fn(Point) -> Point, back: &dyn Fn(Point) -> Point, delta: f64, gradients: bool) { + for c in &mut m.components { + match &mut c.shape { + MaskShape::Linear { start, end } if gradients => { + *start = fwd(*start); + *end = fwd(*end); + } + MaskShape::Radial { center, angle, .. } if gradients => { + *center = fwd(*center); + if delta != 0.0 { + // (kept within −180..180°) + *angle = (*angle + delta + 180.0).rem_euclid(360.0) - 180.0; + } + } + MaskShape::Linear { .. } | MaskShape::Radial { .. } => {} + MaskShape::Brush { strokes } => { + for s in strokes { + s.points.iter_mut().for_each(|p| *p = fwd(*p)); + } + } + MaskShape::Object { hint, exclude, seg, detail, .. } => { + hint.iter_mut().chain(exclude.iter_mut()).for_each(|p| *p = fwd(*p)); + remap_segs(seg, detail, fwd, back); + } + MaskShape::Prompt { seg, detail, .. } => remap_segs(seg, detail, fwd, back), + // computed from the photo at each render (its mattes follow the warp), or colours, + // tones and depths, which have no place (a colour range's samples are colours) + MaskShape::Subject + | MaskShape::Sky + | MaskShape::Background + | MaskShape::People { .. } + | MaskShape::Landscape { .. } + | MaskShape::ColorRange { .. } + | MaskShape::LuminanceRange { .. } + | MaskShape::DepthRange { .. } => {} + } + } +} + +/// A stored selection and its zoomed-in passes, resampled onto the new frame. Where a pass's new +/// box reaches past what it covered, it takes the whole-photo selection there (what the render +/// showed), not a copy of its own edge. +fn remap_segs(seg: &mut Option, detail: &mut [SegMask], fwd: &dyn Fn(Point) -> Point, back: &dyn Fn(Point) -> Point) { + let coarse = seg.as_ref().and_then(SegGrid::new); + for d in detail.iter_mut() { + if let Some(m) = moved(d, fwd, back, coarse.as_ref()) { + *d = m; + } + } + if let Some(s) = seg.as_ref() + && let Some(m) = moved(s, fwd, back, None) + { + *seg = Some(m); + } +} + +/// Points along each edge of a box [`map_rect`] maps: a lens warp bends an edge between its ends, +/// most where it crosses the centre lines. +const RECT_EDGE_SAMPLES: usize = 16; + +/// The box around `r` mapped by `f` (points along its edges), inside 0..1. +fn map_rect(r: [f64; 4], f: &dyn Fn(Point) -> Point) -> [f64; 4] { + let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for i in 0..=RECT_EDGE_SAMPLES { + let t = i as f64 / RECT_EDGE_SAMPLES as f64; + let (x, y) = (r[0] + t * (r[2] - r[0]), r[1] + t * (r[3] - r[1])); + for q in [(x, r[1]), (x, r[3]), (r[0], y), (r[2], y)] { + let p = f(Point::new(q.0, q.1)); + if p.x.is_finite() && p.y.is_finite() { + (x0, y0, x1, y1) = (x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y)); + } + } + } + if x0 > x1 || y0 > y1 { + return r; + } + [x0.clamp(0.0, 1.0), y0.clamp(0.0, 1.0), x1.clamp(0.0, 1.0), y1.clamp(0.0, 1.0)] +} + +/// Segmentation `s` resampled onto the new frame: a grid of the same side over the mapped box +/// (the whole image for a whole-image one), each cell taking the old logit at its centre mapped +/// back. A cell whose centre maps back outside what `s` covered takes `outside`'s logit there +/// (for a zoomed-in pass: the whole-photo selection), else selects nothing. `None` when the data +/// is damaged (it is kept as it is). +fn moved(s: &SegMask, fwd: &dyn Fn(Point) -> Point, back: &dyn Fn(Point) -> Point, outside: Option<&SegGrid>) -> Option { + let old = SegGrid::new(s)?; + let side = s.side as usize; + let rect = match s.rect { + None => None, + Some(r) => Some(map_rect(r, fwd)).filter(|b| b[2] > b[0] && b[3] > b[1]), + }; + let b = rect.unwrap_or([0.0, 0.0, 1.0, 1.0]); + let logits: Vec = (0..side * side) + .map(|i| { + let (x, y) = ((i % side) as f64 + 0.5, (i / side) as f64 + 0.5); + let n = Point::new(b[0] + x / side as f64 * (b[2] - b[0]), b[1] + y / side as f64 * (b[3] - b[1])); + let o = back(n); + if old.contains(o) { old.logit(o) } else { outside.map_or(-16.0, |g| g.logit(o)) } + }) + .collect(); + Some(match rect { + Some(r) => SegMask::from_logits_in(side, &logits, r), + None => SegMask::from_logits(side, &logits), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use lightcraft_develop::{BrushStroke, DevelopSettings, MaskComponent, MaskOp}; + + fn comp(shape: MaskShape) -> MaskComponent { + MaskComponent { name: None, op: MaskOp::Add, invert: false, shape } + } + + fn mask(shape: MaskShape) -> Mask { + Mask { components: vec![comp(shape)], ..Default::default() } + } + + fn seg_at(p: Point) -> SegMask { + const SIDE: usize = 32; + let l: Vec = (0..SIDE * SIDE) + .map(|i| { + let (x, y) = (((i % SIDE) as f64 + 0.5) / SIDE as f64, ((i / SIDE) as f64 + 0.5) / SIDE as f64); + if (x - p.x).hypot(y - p.y) < 0.08 { 8.0 } else { -8.0 } + }) + .collect(); + SegMask::from_logits(SIDE, &l) + } + + fn object_at(p: Point) -> MaskShape { + MaskShape::Object { hint: vec![p], exclude: Vec::new(), seg: Some(seg_at(p)), detail: Vec::new(), edge: 0.0 } + } + + /// The centre of what `s` selects (sampled on a fine grid). + fn centre_of(s: &SegMask) -> Point { + let g = SegGrid::new(s).unwrap(); + let (mut sx, mut sy, mut n) = (0.0, 0.0, 0.0); + for i in 0..200 * 200 { + let p = Point::new(((i % 200) as f64 + 0.5) / 200.0, ((i / 200) as f64 + 0.5) / 200.0); + if g.contains(p) && g.logit(p) > 0.0 { + (sx, sy, n) = (sx + p.x, sy + p.y, n + 1.0); + } + } + assert!(n > 0.0, "nothing selected"); + Point::new(sx / n, sy / n) + } + + fn seg_of(m: &Mask, i: usize) -> &SegMask { + match &m.components[i].shape { + MaskShape::Object { seg: Some(s), .. } => s, + other => panic!("{other:?}"), + } + } + + #[test] + fn a_quarter_turn_turns_every_place_a_mask_keeps() { + let p = Point::new(0.2, 0.3); + let mut m = mask(MaskShape::Radial { center: p, rx: 0.1, ry: 0.05, angle: 10.0, feather: 50.0, invert: false }); + m.components.push(comp(MaskShape::Brush { strokes: vec![BrushStroke { points: vec![p], ..Default::default() }] })); + m.components.push(comp(object_at(p))); + turn(&mut m, Orientation::Rotate90); + // a quarter turn clockwise: (x, y) → (1 − y, x) + let want = Point::new(0.7, 0.2); + let MaskShape::Radial { center, angle, .. } = &m.components[0].shape else { panic!() }; + assert!((center.x - want.x).abs() < 1e-9 && (center.y - want.y).abs() < 1e-9, "{center:?}"); + assert_eq!(*angle, 100.0); + let MaskShape::Brush { strokes } = &m.components[1].shape else { panic!() }; + assert!((strokes[0].points[0].x - want.x).abs() < 1e-9); + let MaskShape::Object { hint, .. } = &m.components[2].shape else { panic!() }; + assert!((hint[0].x - want.x).abs() < 1e-9 && (hint[0].y - want.y).abs() < 1e-9, "{hint:?}"); + let c = centre_of(seg_of(&m, 2)); + assert!((c.x - want.x).abs() < 0.04 && (c.y - want.y).abs() < 0.04, "{c:?}"); + // and back + turn(&mut m, Orientation::Rotate270); + let MaskShape::Radial { center, angle, .. } = &m.components[0].shape else { panic!() }; + assert!((center.x - p.x).abs() < 1e-9 && (center.y - p.y).abs() < 1e-9 && *angle == 10.0); + } + + #[test] + fn attaching_an_old_mask_keeps_where_it_renders() { + let mut s = DevelopSettings::default(); + s.geometry.vertical = 30.0; + s.geometry.rotate = 5.0; + let frame = Frame::new(300, 200, &s, false); + let p = Point::new(0.3, 0.4); + let mut m = mask(MaskShape::Linear { start: p, end: Point::new(0.6, 0.4) }); + m.components.push(comp(object_at(p))); + m.on_photo = false; + attach(&mut m, &frame); + assert!(m.on_photo); + let on = frame.for_mask(true); + let MaskShape::Linear { start, .. } = &m.components[0].shape else { panic!() }; + let back = on.mask_to_norm(*start); + assert!((back.x - p.x).abs() < 1e-6 && (back.y - p.y).abs() < 1e-6, "{back:?}"); + assert!((start.x - p.x).hypot(start.y - p.y) > 0.005, "the warp moved it on the photo: {start:?}"); + let c = on.mask_to_norm(centre_of(seg_of(&m, 1))); + assert!((c.x - p.x).abs() < 0.04 && (c.y - p.y).abs() < 0.04, "{c:?}"); + // attaching again changes nothing + let before = m.clone(); + attach(&mut m, &frame); + assert_eq!(m, before); + } + + #[test] + fn damaged_or_hostile_masks_move_without_a_panic() { + let mut m = + mask(MaskShape::Radial { center: Point::new(f64::NAN, f64::INFINITY), rx: 0.1, ry: 0.1, angle: f64::NAN, feather: 0.0, invert: false }); + m.components.push(comp(MaskShape::Object { + hint: vec![Point::new(1e300, -1e300)], + exclude: Vec::new(), + seg: Some(SegMask { side: 1024, data: "not base64".into(), rect: Some([f64::NAN, 0.0, 2.0, -1.0]) }), + detail: vec![SegMask { side: 0, data: String::new(), rect: None }], + edge: 0.0, + })); + m.on_photo = false; + let mut s = DevelopSettings::default(); + s.geometry.vertical = 80.0; + s.optics.distortion = 100.0; + attach(&mut m, &Frame::new(300, 200, &s, false)); + for o in [Orientation::Rotate90, Orientation::FlipH, Orientation::Rotate180] { + turn(&mut m, o); + } + assert!(m.on_photo); + } + + /// A Transform and lens warp strong enough to bend shapes across a gradient. + fn warped() -> DevelopSettings { + let mut s = DevelopSettings::default(); + s.geometry.vertical = 40.0; + s.geometry.horizontal = -25.0; + s.geometry.rotate = 8.0; + s.optics.distortion = 60.0; + s + } + + /// The mean and largest difference between mask `a` and `b` rendered under `s`. + fn alpha_diff(a: &Mask, b: &Mask, s: &DevelopSettings) -> (f32, f32) { + let frame = Frame::new(300, 200, s, true); + let (w, h) = frame.fit(300, 200); + let img = lightcraft_raster::Rgb32f::new(w, h); + let log_l = lightcraft_raster::Plane::new(w, h); + let pa = crate::masks::evaluate_one(a, &frame, w, h, &img, &log_l, 0.0, None); + let pb = crate::masks::evaluate_one(b, &frame, w, h, &img, &log_l, 0.0, None); + let d: Vec = pa.data.iter().zip(&pb.data).map(|(x, y)| (x - y).abs()).collect(); + (d.iter().sum::() / d.len().max(1) as f32, d.iter().copied().fold(0.0, f32::max)) + } + + /// An old gradient keeps its region when it goes onto the photo: its shape goes through the + /// warp's local linear part, not only its centre or ends (review of #3550). + #[test] + fn attaching_an_old_gradient_keeps_its_region() { + let s = warped(); + let frame = Frame::new(300, 200, &s, false); + for shape in [ + MaskShape::Radial { center: Point::new(0.3, 0.35), rx: 0.18, ry: 0.07, angle: 30.0, feather: 30.0, invert: false }, + MaskShape::Linear { start: Point::new(0.2, 0.25), end: Point::new(0.45, 0.6) }, + ] { + let mut old = mask(shape.clone()); + old.on_photo = false; + let mut on = old.clone(); + attach(&mut on, &frame); + // what moving the points alone would give + let mut naive = old.clone(); + naive.on_photo = true; + remap(&mut naive, &|p| frame.for_mask(true).norm_to_mask(p), &|p| frame.for_mask(true).mask_to_norm(p), 0.0, true); + let (mean, max) = alpha_diff(&old, &on, &s); + let (naive_mean, naive_max) = alpha_diff(&old, &naive, &s); + // (the warp isn't linear across the whole gradient: a little is left at its far edge) + assert!(mean < 0.01, "{shape:?}: mean {mean}, max {max}"); + assert!(naive_mean > 1.5 * mean && naive_max > 2.0 * max, "{shape:?}: points alone {naive_mean} / {naive_max} vs {mean} / {max}"); + } + } + + /// Where a zoomed-in pass's new box reaches past what it covered (a turned box's corners), it + /// takes the whole-photo selection: neither a copy of its own edge (a negative whole-photo + /// selection) nor a fixed "unselected" (a positive one) (review of #3550). + #[test] + fn a_moved_detail_pass_takes_the_whole_selection_past_its_own_area() { + const SIDE: usize = 16; + let mut s = DevelopSettings::default(); + s.geometry.rotate = 20.0; + let frame = Frame::new(300, 200, &s, false); + for whole in [8.0f32, -8.0] { + let detail = SegMask::from_logits_in(SIDE, &[8.0; SIDE * SIDE], [0.4, 0.4, 0.6, 0.6]); + let coarse = SegMask::from_logits(SIDE, &[whole; SIDE * SIDE]); + let mut m = + mask(MaskShape::Object { hint: vec![Point::new(0.5, 0.5)], exclude: Vec::new(), seg: Some(coarse), detail: vec![detail], edge: 0.0 }); + m.on_photo = false; + attach(&mut m, &frame); + let MaskShape::Object { detail, .. } = &m.components[0].shape else { panic!() }; + let g = SegGrid::new(&detail[0]).unwrap(); + let b = detail[0].bounds().unwrap(); + // a corner of the new box is outside the turned patch: the whole-photo selection's sign + let inset = |t: f64| Point::new(b[0] + t * (b[2] - b[0]), b[1] + t * (b[3] - b[1])); + let corner = g.logit(inset(0.03)); + assert!((corner > 0.0) == (whole > 0.0), "whole {whole}: corner {corner}"); + assert!(g.logit(inset(0.5)) > 0.0, "whole {whole}: the patch itself stays selected"); + } + } + + /// The box around a mapped rectangle holds the whole bent edge, also off the centre lines + /// (review of #3550). + #[test] + fn a_mapped_box_holds_its_bent_edges() { + let mut s = DevelopSettings::default(); + s.optics.distortion = -80.0; + let f = Frame::new(300, 200, &s, false).for_mask(true).into_owned(); + let fwd = |p: Point| f.norm_to_mask(p); + let r = [0.2, 0.1, 0.9, 0.4]; + let b = map_rect(r, &fwd); + let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for i in 0..=2000 { + let t = i as f64 / 2000.0; + let (x, y) = (r[0] + t * (r[2] - r[0]), r[1] + t * (r[3] - r[1])); + for q in [(x, r[1]), (x, r[3]), (r[0], y), (r[2], y)] { + let p = fwd(Point::new(q.0, q.1)); + (x0, y0, x1, y1) = (x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y)); + } + } + let want = [x0.clamp(0.0, 1.0), y0.clamp(0.0, 1.0), x1.clamp(0.0, 1.0), y1.clamp(0.0, 1.0)]; + for k in 0..4 { + assert!((b[k] - want[k]).abs() < 5e-4, "{b:?} vs {want:?}"); + } + } +} diff --git a/crates/pipeline/src/masks.rs b/crates/pipeline/src/masks.rs index ca182ea81d..097e080a7e 100644 --- a/crates/pipeline/src/masks.rs +++ b/crates/pipeline/src/masks.rs @@ -152,6 +152,8 @@ pub fn evaluate(masks: &[Mask], frame: &Frame, w: usize, h: usize, img: &Rgb32f, /// scaled by its amount. #[allow(clippy::too_many_arguments)] pub fn evaluate_one(m: &Mask, frame: &Frame, w: usize, h: usize, img: &Rgb32f, log_l: &Plane, ev: f32, mattes: Option<&Mattes>) -> Plane { + // its coordinates on the photo before the warp, or (an old mask) on the corrected frame + let frame = &*frame.for_mask(m.on_photo); let mut alpha = Plane::new(w, h); let mut first = true; for comp in &m.components { @@ -195,7 +197,7 @@ pub fn evaluate_one(m: &Mask, frame: &Frame, w: usize, h: usize, img: &Rgb32f, l /// Per-pixel positions in long-edge units for output pixel centres. fn for_each_pos(frame: &Frame, w: usize, h: usize, out: &mut Plane, f: impl Fn(Point, usize) -> f32 + Sync + Send) { - let m = frame.out_to_norm(w, h); + let m = frame.out_to_mask(w, h); let (ow, oh, l) = (frame.ow, frame.oh, frame.ow.max(frame.oh)); for_rows(&mut out.data, w, |y, row| { for (x, v) in row.iter_mut().enumerate() { @@ -266,7 +268,7 @@ pub fn shape_alpha(shape: &MaskShape, frame: &Frame, w: usize, h: usize, img: &R MaskShape::Sky => { // Classical sky heuristic until the segmenter lands (M12): bright, smooth, blue-ish or // unsaturated, and connected to the top of the frame. - let m = frame.out_to_norm(w, h); + let m = frame.out_to_mask(w, h); for (i, v) in out.data.iter_mut().enumerate() { let (x, y) = (i % w, i / w); let n = m.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5)); @@ -293,7 +295,7 @@ pub fn shape_alpha(shape: &MaskShape, frame: &Frame, w: usize, h: usize, img: &R MaskShape::Prompt { .. } => {} MaskShape::Subject | MaskShape::Object { .. } | MaskShape::People { .. } => { // Saliency heuristic: centre-weighted local contrast (replaced by the segmenter in M12). - let m = frame.out_to_norm(w, h); + let m = frame.out_to_mask(w, h); let blur = lightcraft_raster::blur::gaussian(log_l, 0.03 * frame_px(frame, w)); for (i, v) in out.data.iter_mut().enumerate() { let (x, y) = (i % w, i / w); @@ -315,24 +317,24 @@ pub fn shape_alpha(shape: &MaskShape, frame: &Frame, w: usize, h: usize, img: &R } /// A decoded [`SegMask`]: its logits and the normalized rectangle they cover. -struct SegGrid { +pub struct SegGrid { logits: Vec, side: usize, r: [f64; 4], } impl SegGrid { - fn new(seg: &SegMask) -> Option { + pub fn new(seg: &SegMask) -> Option { Some(SegGrid { logits: seg.logits()?, side: seg.side as usize, r: seg.bounds()? }) } - fn contains(&self, n: Point) -> bool { + pub fn contains(&self, n: Point) -> bool { n.x >= self.r[0] && n.x <= self.r[2] && n.y >= self.r[1] && n.y <= self.r[3] } /// The bilinearly sampled logit at normalized image point `n` (cell centres at /// `(i + 0.5) / side` of the rectangle). - fn logit(&self, n: Point) -> f32 { + pub fn logit(&self, n: Point) -> f32 { let side = self.side; let at = |x: usize, y: usize| self.logits.get(y.min(side - 1) * side + x.min(side - 1)).copied().unwrap_or(-16.0); let u = (n.x - self.r[0]) / (self.r[2] - self.r[0]); @@ -385,7 +387,7 @@ fn sample_seg(seg: Option<&SegMask>, detail: &[SegMask], gain: f32, frame: &Fram if coarse.is_none() && patches.is_empty() { return; } - let m = frame.out_to_norm(w, h); + let m = frame.out_to_mask(w, h); for_rows(&mut out.data, w, |y, row| { for (x, v) in row.iter_mut().enumerate() { let n = m.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5)); @@ -571,7 +573,7 @@ pub fn brush_dabs(s: &BrushStroke, frame: &Frame, w: usize, h: usize) -> BrushDa /// Ask for one more than the threshold to tell "at it" from "past it": a result shorter than /// `max` is the whole stroke. pub fn brush_dabs_within(s: &BrushStroke, frame: &Frame, w: usize, h: usize, max: usize) -> BrushDabs { - let to_out = frame.norm_to_out(w, h); + let to_out = frame.mask_to_out(w, h); let ppl = frame.px_per_long(w); let r = (s.size * ppl).max(0.5); let hard = r * (1.0 - (s.feather / 100.0).clamp(0.0, 1.0)); @@ -588,7 +590,8 @@ pub fn brush_dabs_within(s: &BrushStroke, frame: &Frame, w: usize, h: usize, max if emitted >= max { break; } - let q = to_out.apply(*p); + // (a point the warp can't place lays no dab, rather than one at its unwarped place) + let Some(q) = to_out(*p) else { continue }; let before = dabs.len(); if push_dabs_within(&mut dabs, &mut emitted, prev, q, r, max) { let pq = s.pressure_at(i); diff --git a/crates/pipeline/src/optics.rs b/crates/pipeline/src/optics.rs index b0d7cc7f91..883be6730f 100644 --- a/crates/pipeline/src/optics.rs +++ b/crates/pipeline/src/optics.rs @@ -201,6 +201,39 @@ impl Warp { self.corrected_to_source(self.to_corrected(p), ch) } + /// Source px → transformed px (green plane): the inverse of [`Warp::to_source`], by Newton's + /// method on it (the warps are smooth and close to the identity, so a few steps reach a + /// hundredth of a pixel). `None` when it doesn't converge (a point far outside a strong warp). + pub fn from_source(&self, s: Point) -> Option { + if !(s.x.is_finite() && s.y.is_finite()) { + return None; + } + let f = |p: Point| self.to_source(p, 1); + // start from where the perspective alone puts it (the lens part moves pixels little) + let mut t = self.from_corrected(s); + let h = 1e-3 * self.w.max(self.h).max(1.0); + for _ in 0..24 { + let v = f(t); + let (ex, ey) = (v.x - s.x, v.y - s.y); + if !(ex.is_finite() && ey.is_finite()) { + return None; + } + if ex.abs() < 1e-4 && ey.abs() < 1e-4 { + return Some(t); + } + let (dx, dy) = (f(Point::new(t.x + h, t.y)), f(Point::new(t.x, t.y + h))); + let (a, c) = ((dx.x - v.x) / h, (dx.y - v.y) / h); + let (b, d) = ((dy.x - v.x) / h, (dy.y - v.y) / h); + let det = a * d - b * c; + if !det.is_finite() || det.abs() < 1e-12 { + return None; + } + t = Point::new(t.x - (d * ex - b * ey) / det, t.y - (a * ey - c * ex) / det); + } + let v = f(t); + ((v.x - s.x).abs() < 1e-2 && (v.y - s.y).abs() < 1e-2).then_some(t) + } + /// Vignetting compensation gain at source position `src` (px). pub fn gain(&self, src: Point) -> f32 { let mut g = 1.0; @@ -375,7 +408,7 @@ pub fn reorient_lens(lens: &EmbeddedLens, o: Orientation, w: f64, h: f64) -> Emb EmbeddedWarpStage { planes, center: map_pt(st.center), radius: st.radius * long_ratio, reciprocal: st.reciprocal } }) }); - EmbeddedLens { warp, vignette, stages } + EmbeddedLens { warp, vignette, stages, source: lens.source } } // ------------------------------------------------------------------------------------------ lateral CA @@ -570,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 a875ffb7fc..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 @@ -161,17 +191,18 @@ pub fn window_for_reads_checked( win: crate::PixelWindow, ) -> Option { let spots = &s.spots; - let autos: Vec<&lightcraft_develop::BrushStroke> = s + // (with whether its mask's coordinates are on the photo before the warp) + let autos: Vec<(bool, &lightcraft_develop::BrushStroke)> = s .masks .iter() .filter(|m| m.visible) - .flat_map(|m| &m.components) - .filter_map(|c| match &c.shape { - lightcraft_develop::MaskShape::Brush { strokes } => Some(strokes), + .flat_map(|m| m.components.iter().map(move |c| (m.on_photo, c))) + .filter_map(|(on, c)| match &c.shape { + lightcraft_develop::MaskShape::Brush { strokes } => Some(strokes.iter().map(move |st| (on, st))), _ => None, }) .flatten() - .filter(|st| st.auto_mask) + .filter(|(_, st)| st.auto_mask) .collect(); if spots.is_empty() && autos.is_empty() { return Some(win); @@ -205,10 +236,10 @@ pub fn window_for_reads_checked( // Auto Mask strokes weigh each dab by its similarity to the pixel under the dab's centre and // refine the stroke over a couple of radii: each dab matters to pixels within 2.5 radii let mut dab_boxes: Vec<[f64; 4]> = Vec::new(); - for st in autos { + for (on_photo, st) in autos { // One more than the window takes, so a stroke past it is still recognised as past it // without the other 1.8 million dabs being built first (#1520). - let dabs = crate::masks::brush_dabs_within(st, frame, full_w, full_h, MAX_DABS_CONSIDERED + 1); + let dabs = crate::masks::brush_dabs_within(st, &frame.for_mask(on_photo), full_w, full_h, MAX_DABS_CONSIDERED + 1); let r = dabs.r; if dabs.dabs.len() > MAX_DABS_CONSIDERED { continue; @@ -258,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. @@ -274,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]; @@ -326,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); @@ -335,7 +408,6 @@ pub fn apply(img: &mut Rgb32f, spots: &[Spot], frame: &Frame, ppl: f64) { if fill { fill_box(&mut src, &tgt, &alpha, bw, bh); } - let heal = matches!(spot.mode, SpotMode::Remove | SpotMode::Heal); let low = if heal { // Tone correction from the spot's *surroundings* only: normalized convolution of // (target − source) over pixels outside the stroke (a membrane-like interpolation). diff --git a/crates/pipeline/src/tests.rs b/crates/pipeline/src/tests.rs index 5c5f1b95c1..cee4ec1ffb 100644 --- a/crates/pipeline/src/tests.rs +++ b/crates/pipeline/src/tests.rs @@ -287,12 +287,16 @@ fn drafts_keep_wide_planes_across_a_noise_reduction_change_and_full_renders_do_n let full = RenderRequest { quality: Quality::Full, ..draft }; let mut s = typical_edits(); s.effects.clarity = 60.0; + s.detail.sharpen_amount = 80.0; render_cached(&src, &info, &s, &draft, &cache); let clarity_plane = |c: &StageCache| c.entries.lock().unwrap().first().and_then(|e| e.planes.clarity.clone()).unwrap().1; + let sharpen_plane = |c: &StageCache| c.entries.lock().unwrap().first().and_then(|e| e.planes.sharpen.clone()).unwrap().1; let first = clarity_plane(&cache); + let first_sharpen = sharpen_plane(&cache); s.detail.nr_luminance = 50.0; render_cached(&src, &info, &s, &draft, &cache); assert!(Arc::ptr_eq(&first, &clarity_plane(&cache)), "a draft redid the clarity plane for a noise-reduction change"); + assert!(!Arc::ptr_eq(&first_sharpen, &sharpen_plane(&cache)), "a draft reused the old sharpening plane after noise reduction changed"); for v in [10.0, 45.0, 80.0] { s.detail.nr_luminance = v; s.detail.nr_color = v / 2.0; diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index d88b6cf5dd..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:?}"); @@ -260,6 +289,26 @@ fn constrain_crop_removes_blank_areas() { assert!(blank_fraction(&c) < 0.002, "constrained: {}", blank_fraction(&c)); } +/// Issue #2361: lens corrections never show the blank past the photo's edge, with or without +/// Constrain Crop, in every colour plane; perspective alone still needs Constrain Crop. +#[test] +fn lens_corrections_leave_no_blank_corners() { + let src = Rgb32f::from_fn(300, 200, |x, y| [0.05 + 0.002 * x as f32, 0.1 + 0.002 * y as f32, 0.3]); + for (distortion, ca) in [(-80.0, 0.0), (80.0, 0.0), (-40.0, 100.0), (0.0, -100.0)] { + let mut s = DevelopSettings::default(); + s.optics.distortion = distortion; + s.optics.ca_red = ca; + s.optics.ca_blue = -ca; + let r = render(&src, &SourceInfo::default(), &s, &RenderRequest::fit(300, 300)).image; + assert!(blank_fraction(&r) < 0.002, "distortion {distortion}, CA {ca}: {}", blank_fraction(&r)); + } + let mut s = DevelopSettings::default(); + s.optics.distortion = -60.0; + s.geometry.vertical = -60.0; + let r = render(&src, &SourceInfo::default(), &s, &RenderRequest::fit(300, 300)).image; + assert!(blank_fraction(&r) > 0.03, "the keystone keeps its corners: {}", blank_fraction(&r)); +} + #[test] fn transforms_preview_matches_export() { let src = lightcraft_scenes::demo_library()[4].render(960, 640); 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..c6ea984c49 --- /dev/null +++ b/crates/pipeline/src/tests_light.rs @@ -0,0 +1,516 @@ +//! 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; + // (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]); + } +} + +#[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); + // (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)); + match (id, v > 0.0) { + ("light.contrast", true) => assert!(dark < 0 && light > 0, "{id} {v}: {dark} {light}"), + ("light.contrast", false) => assert!(dark > 0 && light < 0, "{id} {v}: {dark} {light}"), + ("light.whites", true) => assert!(light > 0, "{id} {v}: {dark} {light}"), + ("light.whites", false) => assert!(light < 0, "{id} {v}: {dark} {light}"), + (_, true) => assert!(dark > 0, "{id} {v}: {dark} {light}"), + (_, false) => assert!(dark < 0, "{id} {v}: {dark} {light}"), + } + } +} + +/// V4 with Contrast, Whites and Blacks at 0 is the Neutral camera look exactly (V2's at 0), +/// whatever the other sliders; other sources render under V4 as under V2. +#[test] +fn v3_at_zero_is_the_neutral_camera_look_and_other_paths_are_v2() { + let reqs = [RenderRequest::fit(480, 480), RenderRequest { depth: OutputDepth::U16, ..RenderRequest::fit(320, 320) }]; + let mut typical = DevelopSettings::for_raw(5200.0, 4.0); + for (id, v) in [("light.exposure", 0.4), ("light.highlights", -60.0), ("light.shadows", 30.0), ("effects.clarity", 20.0)] { + controls::set(&mut typical, id, v); + } + let mut hdr = typical.clone(); + hdr.hdr.enabled = true; + let hdr_req = RenderRequest { depth: OutputDepth::F32Hdr, ..RenderRequest::fit(240, 240) }; + for src in scenes() { + for s in [DevelopSettings::for_raw(5200.0, 4.0), typical.clone()] { + for req in &reqs { + assert_eq!( + render_hash(&src, &camera_look(), &on(Process::V4, &s), req), + render_hash(&src, &camera_look(), &on(Process::V3, &s), req) + ); + } + } + assert_eq!( + render_hash(&src, &camera_look(), &on(Process::V4, &hdr), &hdr_req), + render_hash(&src, &camera_look(), &on(Process::V3, &hdr), &hdr_req) + ); + let mut edited = typical.clone(); + for (id, v) in [("light.contrast", 30.0), ("light.whites", 25.0), ("light.blacks", -20.0)] { + controls::set(&mut edited, id, v); + } + for info in [SourceInfo::default(), SourceInfo { raw: true, ..Default::default() }] { + for req in &reqs { + assert_eq!(render_hash(&src, &info, &on(Process::V4, &edited), req), render_hash(&src, &info, &on(Process::V3, &edited), req)); + } + } + // and on the camera look the sliders do something + assert_ne!( + render_hash(&src, &camera_look(), &on(Process::V4, &edited), &reqs[0]), + render_hash(&src, &camera_look(), &on(Process::V4, &typical), &reqs[0]) + ); + } + let info = camera_look(); + assert!(LightOps::new(&on(Process::V4, &typical), &info).is_none(), "nothing to apply at 0"); + assert!( + LightOps::new( + &on(Process::V3, &DevelopSettings { light: lightcraft_develop::Light { contrast: 50.0, ..Default::default() }, ..typical.clone() }), + &info + ) + .is_none() + ); +} + +/// Cached renders (a view's stage cache) render as uncached ones do, whole or as a window. +#[test] +fn calibrated_operators_match_in_cached_and_windowed_renders() { + let src = std::sync::Arc::new(lightcraft_scenes::demo_library()[3].render(1200, 800)); + let info = camera_look(); + let mut s = DevelopSettings::default(); + s.light.contrast = 40.0; + s.light.blacks = -60.0; + s.light.whites = 80.0; + let cache = StageCache::default(); + let req = RenderRequest::fit(1200, 1200); + for _ in 0..2 { + assert!(render_cached(&src, &info, &s, &req, &cache).image == render(&src, &info, &s, &req).image); + } + let win = PixelWindow { x: 300, y: 200, w: 400, h: 300 }; + let wreq = RenderRequest { window: Some(win), ..req }; + let (f, w) = (render(&src, &info, &s, &req).image, render_cached(&src, &info, &s, &wreq, &cache).image); + assert!(window_diff(&f, &w, win) <= 1, "the window is the frame's pixels"); +} + +/// Largest channel difference between window `win` of `full` and the window render `w`. +fn window_diff(full: &Rgba8, w: &Rgba8, win: PixelWindow) -> u8 { + let mut max = 0; + for y in 0..win.h { + for x in 0..win.w { + let (a, b) = (full.get(win.x + x, win.y + y), w.get(x, y)); + for k in 0..3 { + max = max.max(a[k].abs_diff(b[k])); + } + } + } + max +} + +/// HDR values follow the mode (review of 5a7016c8): per channel a component above 1 passes +/// unchanged; on luminance a pixel whose luminance is at most 1 is scaled as a whole, components +/// above 1 included, and one whose luminance is above 1 passes; Mix blends the two. Both are +/// continuous where a component or the luminance crosses 1. +#[test] +fn hdr_components_follow_the_operators_mode() { + let enc = &linear_to_srgb; + let lum = |p: [f32; 3]| light_v3::PRO_Y[0] * p[0] + light_v3::PRO_Y[1] * p[1] + light_v3::PRO_Y[2] * p[2]; + for (name, fit, _) in fits() { + for a in [-100.0, -40.0, 40.0, 100.0] { + let op = Operator::new(fit, a).unwrap(); + for p in [[1.2f32, 0.2, 0.05], [3.0, 1.5, 0.8], [0.4, 1.1, 0.02]] { + let pc = p.map(|c| op.channel(c, enc)); + assert!(p.iter().zip(&pc).all(|(c, o)| *c <= 1.0 || o == c), "{name} {a}: per channel {p:?} -> {pc:?}"); + let y = lum(p); + let l = if y > 1.0 { p } else { p.map(|c| c * op.channel(y, enc) / y) }; + let want: [f32; 3] = match op.mode { + Mode::PerChannel => pc, + Mode::Luminance => l, + Mode::Mix => std::array::from_fn(|k| op.weight * pc[k] + (1.0 - op.weight) * l[k]), + }; + let got = op.apply(p, enc); + assert!(got.iter().all(|v| v.is_finite())); + assert!(got.iter().zip(&want).all(|(g, w)| (g - w).abs() < 1e-6), "{name} {a} ({:?}): {p:?} -> {got:?}, want {want:?}", op.mode); + } + // continuous where a component crosses 1, and where the luminance does + let (lo, hi) = (op.apply([0.9999, 0.3, 0.1], enc), op.apply([1.0001, 0.3, 0.1], enc)); + assert!(lo.iter().zip(&hi).all(|(a, b)| (a - b).abs() < 2e-3), "{name} {a}: {lo:?} | {hi:?}"); + let (lo, hi) = (op.apply([0.9999; 3], enc), op.apply([1.0001; 3], enc)); + assert!(lo.iter().zip(&hi).all(|(a, b)| (a - b).abs() < 2e-3), "{name} {a}: {lo:?} | {hi:?}"); + } + } +} + +/// Whites keeps the V2 tone curve for both signs, including HDR and render windows. +#[test] +fn whites_is_byte_identical_to_v2() { + let src = scenes().remove(0); + let info = camera_look(); + let reqs = [ + RenderRequest::fit(480, 480), + RenderRequest { depth: OutputDepth::U16, ..RenderRequest::fit(320, 320) }, + RenderRequest { depth: OutputDepth::F32Hdr, ..RenderRequest::fit(240, 240) }, + RenderRequest { window: Some(PixelWindow { x: 80, y: 60, w: 160, h: 120 }), ..RenderRequest::fit(480, 480) }, + ]; + for amount in [-100.0, -50.0, -1.0, 0.0, 1.0, 50.0, 100.0] { + for hdr in [false, true] { + let mut s = DevelopSettings::for_raw(5200.0, 4.0); + s.light.whites = amount; + s.light.exposure = 0.35; + s.light.highlights = -30.0; + s.light.shadows = 20.0; + s.hdr.enabled = hdr; + s.hdr.max_ev = 2.0; + for req in &reqs { + assert_eq!( + render_hash(&src, &info, &on(Process::V4, &s), req), + render_hash(&src, &info, &on(Process::V3, &s), req), + "Whites {amount}, HDR {hdr}, {req:?}" + ); + } + } + } +} + +#[test] +fn invalid_amounts_are_skipped_and_finite_amounts_are_bounded() { + for fit in FITS { + for a in [0.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(Operator::new(fit, a).is_none()); + } + for (a, endpoint) in [(-101.0, -100.0), (101.0, 100.0)] { + assert_eq!(Operator::new(fit, a).unwrap().lut, Operator::new(fit, endpoint).unwrap().lut); + } + } +} + +#[test] +fn section_bypass_and_local_adjustments_keep_v2_behavior() { + let src = scenes().remove(0); + let info = camera_look(); + let req = RenderRequest::fit(480, 480); + let mut s = DevelopSettings::default(); + s.light.contrast = 70.0; + s.light.blacks = -50.0; + s.disabled_sections.push("light".into()); + assert_eq!(render_hash(&src, &info, &on(Process::V4, &s), &req), render_hash(&src, &info, &on(Process::V3, &s), &req)); + s.light = Default::default(); + s.disabled_sections.clear(); + s.masks = vec![lightcraft_develop::Mask { + components: vec![lightcraft_develop::MaskComponent { + name: None, + op: lightcraft_develop::MaskOp::Add, + invert: false, + shape: lightcraft_develop::MaskShape::Linear { start: lightcraft_geom::Point::new(0.2, 0.0), end: lightcraft_geom::Point::new(0.8, 1.0) }, + }], + adjust: lightcraft_develop::LocalAdjustments { contrast: 40.0, whites: 60.0, blacks: -30.0, ..Default::default() }, + ..Default::default() + }]; + assert_eq!(render_hash(&src, &info, &on(Process::V4, &s), &req), render_hash(&src, &info, &on(Process::V3, &s), &req)); +} diff --git a/crates/pipeline/src/tests_mask_geometry.rs b/crates/pipeline/src/tests_mask_geometry.rs new file mode 100644 index 0000000000..08b084cf89 --- /dev/null +++ b/crates/pipeline/src/tests_mask_geometry.rs @@ -0,0 +1,221 @@ +//! Masks stay on the image content under every geometry change: a mask +//! drawn around a mark in the photo still brightens that mark after Straighten, a crop, a flip or +//! a lens / perspective warp, rendered fresh or through a view's stage cache. + +use std::sync::Arc; + +use lightcraft_develop::{BrushStroke, DevelopSettings, LocalAdjustments, Mask, MaskComponent, MaskOp, MaskShape, SegMask}; +use lightcraft_geom::{CropGeometry, Point, Rect}; +use lightcraft_raster::{Rgb32f, Rgba8}; + +use crate::{RenderRequest, SourceInfo, StageCache, render, render_cached}; + +const W: usize = 240; +const H: usize = 160; +/// Where the mark sits, normalized. +const MARK: (f64, f64) = (0.3, 0.32); + +/// Mid grey with a small bright mark at [`MARK`]. +fn marked(mark: bool) -> Rgb32f { + let (mx, my) = (MARK.0 * W as f64, MARK.1 * H as f64); + Rgb32f::from_fn(W, H, |x, y| { + let d = ((x as f64 + 0.5 - mx).powi(2) + (y as f64 + 0.5 - my).powi(2)).sqrt(); + if d < 2.5 && mark { [0.9; 3] } else { [0.05; 3] } + }) +} + +fn with_mask(shape: MaskShape) -> DevelopSettings { + let mut s = DevelopSettings::default(); + s.masks.push(Mask { + id: 1, + components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape }], + adjust: LocalAdjustments { exposure: 2.0, ..Default::default() }, + ..Default::default() + }); + s +} + +fn radial() -> MaskShape { + let l = W.max(H) as f64; + // (radii in long-edge units) + MaskShape::Radial { center: Point::new(MARK.0, MARK.1), rx: 12.0 / l, ry: 12.0 / l, angle: 0.0, feather: 40.0, invert: false } +} + +/// An AI object selection (a stored segmentation) covering the mark. +fn subject() -> MaskShape { + const SIDE: usize = 64; + let logits: Vec = (0..SIDE * SIDE) + .map(|i| { + let (x, y) = ((i % SIDE) as f64 + 0.5, (i / SIDE) as f64 + 0.5); + let (dx, dy) = ((x / SIDE as f64 - MARK.0) * W as f64, (y / SIDE as f64 - MARK.1) * H as f64); + if (dx * dx + dy * dy).sqrt() < 10.0 { 8.0 } else { -8.0 } + }) + .collect(); + MaskShape::Object { + hint: vec![Point::new(MARK.0, MARK.1)], + exclude: Vec::new(), + seg: Some(SegMask::from_logits(SIDE, &logits)), + detail: Vec::new(), + edge: 0.0, + } +} + +fn luma(img: &Rgba8, i: usize) -> f64 { + let p = img.data[i]; + (p[0] as f64 + p[1] as f64 + p[2] as f64) / 3.0 +} + +/// The mark's centre in a render with `s` (where the marked photo differs from an unmarked one: +/// a warp leaves light blank canvas around the photo). +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| 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) { + let (mut sx, mut sy, mut n) = (0.0, 0.0, 0.0); + for (i, v) in weights.enumerate() { + sx += v * ((i % w) as f64 + 0.5); + sy += v * ((i / w) as f64 + 0.5); + n += v; + } + assert!(n > 0.0, "nothing found"); + (sx / n, sy / n) +} + +/// 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| above_dither(luma(masked, i) - luma(plain, i)))) +} + +/// The geometry changes a user makes after drawing a mask. +pub(crate) fn geometries() -> Vec<(&'static str, Box)> { + vec![ + ("straighten", Box::new(|s: &mut DevelopSettings| s.crop.geometry = CropGeometry { rect: Rect::new(0.08, 0.1, 0.92, 0.9), angle: 7.0 })), + ( + "straighten the other way", + Box::new(|s: &mut DevelopSettings| s.crop.geometry = CropGeometry { rect: Rect::new(0.08, 0.1, 0.92, 0.9), angle: -9.0 }), + ), + ("crop", Box::new(|s: &mut DevelopSettings| s.crop.geometry.rect = Rect::new(0.1, 0.15, 0.7, 0.8))), + ("flip", Box::new(|s: &mut DevelopSettings| s.crop.flip_h = true)), + ("flip vertical", Box::new(|s: &mut DevelopSettings| s.crop.flip_v = true)), + ( + "perspective", + Box::new(|s: &mut DevelopSettings| { + s.geometry.vertical = 25.0; + s.geometry.rotate = 4.0; + }), + ), + ("distortion", Box::new(|s: &mut DevelopSettings| s.optics.distortion = 40.0)), + ( + // Rotate Right: the photo and its masks turn together (`photo.rotateRight`) + "quarter turn", + Box::new(|s: &mut DevelopSettings| { + let turn = lightcraft_geom::Orientation::Normal.rotated(true); + s.orientation = s.orientation.rotated(true); + for m in &mut s.masks { + crate::mask_space::turn(m, turn); + } + }), + ), + ] +} + +fn check(name: &str, shape: MaskShape) { + let src = Arc::new(marked(true)); + let req = RenderRequest::fit(W, H); + let info = SourceInfo::default(); + for (what, change) in geometries() { + let mut s = with_mask(shape.clone()); + // a view that rendered the photo before the change (its stage cache holds the mask) + let cache = StageCache::default(); + render_cached(&src, &info, &s, &req, &cache); + change(&mut s); + let plain = DevelopSettings { masks: Vec::new(), ..s.clone() }; + let p = render(&src, &info, &plain, &req).image; + let mark = mark_at(&plain); + for (how, m) in [("fresh", render(&src, &info, &s, &req).image), ("cached", render_cached(&src, &info, &s, &req, &cache).image)] { + let at = mask_at(&m, &p); + let d = ((at.0 - mark.0).powi(2) + (at.1 - mark.1).powi(2)).sqrt(); + assert!(d < 2.0, "{name} after {what} ({how}): the mask's effect is at {at:?}, the mark at {mark:?}"); + } + } +} + +#[test] +fn a_drawn_mask_stays_on_the_content_under_every_geometry_change() { + check("radial", radial()); +} + +fn brush() -> MaskShape { + let l = W.max(H) as f64; + MaskShape::Brush { + strokes: vec![BrushStroke { + points: vec![Point::new(MARK.0 - 0.005, MARK.1), Point::new(MARK.0 + 0.005, MARK.1)], + size: 8.0 / l, + ..Default::default() + }], + } +} + +#[test] +fn a_brushed_mask_stays_on_the_content_under_every_geometry_change() { + check("brush", brush()); +} + +/// A mask from before masks were on the photo keeps its place on the corrected frame: an old edit +/// renders as it did. +#[test] +fn an_old_mask_stays_where_it_was_drawn_on_the_corrected_frame() { + let src = Arc::new(marked(true)); + let req = RenderRequest::fit(W, H); + let info = SourceInfo::default(); + let mut s = with_mask(radial()); + s.masks[0].on_photo = false; + s.geometry.vertical = 25.0; + s.geometry.rotate = 6.0; + let unmasked = DevelopSettings { masks: Vec::new(), ..s.clone() }; + let plain = render(&src, &info, &unmasked, &req).image; + let at = mask_at(&render(&src, &info, &s, &req).image, &plain); + let frame = crate::geometry::Frame::new(W, H, &s, true); + let (w, h) = frame.fit(W, H); + let want = frame.norm_to_out(w, h).apply(Point::new(MARK.0, MARK.1)); + assert!((at.0 - want.x).hypot(at.1 - want.y) < 2.0, "{at:?} vs {want:?}"); + let mark = mark_at(&unmasked); + assert!((at.0 - mark.0).hypot(at.1 - mark.1) > 3.0, "and not on the mark, which the warp moved: {at:?} vs {mark:?}"); +} + +#[test] +fn an_ai_mask_stays_on_the_content_under_every_geometry_change() { + check("object", subject()); +} + +/// A brush point the warp can't place lays no dab, rather than one at its unwarped place, which +/// can be far from the stroke (review of #3550). +#[test] +fn a_brush_point_the_warp_cannot_place_lays_no_dab() { + let mut s = DevelopSettings::default(); + s.geometry.vertical = -100.0; + s.geometry.horizontal = -100.0; + s.optics.distortion = 100.0; + s.geometry.scale = 70.0; + let frame = crate::geometry::Frame::new(1000, 1500, &s, true).for_mask(true).into_owned(); + let (w, h) = frame.fit(1000, 1500); + let warp = frame.mask_warp().cloned().expect("a warp"); + // a point on the photo the inverse can't reach (found by search, so the test doesn't depend on + // the solver's exact limits) + let lost = (0..200 * 200) + .map(|i| Point::new((i % 200) as f64 / 199.0, (i / 200) as f64 / 199.0)) + .find(|p| warp.from_source(Point::new(p.x * frame.ow, p.y * frame.oh)).is_none()); + let lost = lost.expect("these settings leave points the inverse can't reach"); + let stroke = BrushStroke { points: vec![lost], size: 0.01, ..Default::default() }; + let dabs = crate::masks::brush_dabs_within(&stroke, &frame, w, h, 1000); + assert!(dabs.dabs.is_empty(), "{lost:?} laid {:?}", dabs.dabs); +} 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/preview/src/disk.rs b/crates/preview/src/disk.rs index 7510ffa383..ca82870483 100644 --- a/crates/preview/src/disk.rs +++ b/crates/preview/src/disk.rs @@ -191,7 +191,11 @@ impl DiskCache { let used = total.get_or_insert_with(|| self.scan().iter().map(|f| f.1).sum()); let old_len = std::fs::metadata(&p).map_or(0, |m| m.len()); let tmp = p.with_extension(format!("tmp{:?}", std::thread::current().id()).replace(['(', ')'], "")); - if std::fs::write(&tmp, &bytes).is_err() || std::fs::rename(&tmp, &p).is_err() { + // a new temp file: an entry already under the name (a link planted in the cache would be + // written through) is removed, never opened + let _ = std::fs::remove_file(&tmp); + 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; } diff --git a/crates/raster/src/blur.rs b/crates/raster/src/blur.rs index 36e3a64cf2..9fefea9ca2 100644 --- a/crates/raster/src/blur.rs +++ b/crates/raster/src/blur.rs @@ -126,8 +126,67 @@ pub fn gaussian(img: &Image, sigma: f32) -> Image { a } +/// Largest sigma [`gauss_taps`] makes taps for (larger ones are clamped to it). The GPU blur reads +/// the same taps, so it is the limit of both paths. +pub const GAUSS_SIGMA_MAX: f32 = 64.0; + +/// Normalized Gaussian taps `[w(-r) .. w(r)]` for `sigma`, `r = ceil(3 sigma)`. +/// +/// An exact kernel, unlike the three-box approximation of [`gaussian`], which cannot represent +/// a sigma under about 0.8 px (its boxes collapse to the identity): sharpening needs those. +pub fn gauss_taps(sigma: f32) -> Vec { + let sigma = if sigma.is_nan() { 0.05 } else { sigma.clamp(0.05, GAUSS_SIGMA_MAX) }; + let r = (3.0 * sigma).ceil() as i32; + let k = -0.5 / (sigma * sigma); + let mut t: Vec = (-r..=r).map(|i| ((i * i) as f32 * k).exp()).collect(); + let sum: f32 = t.iter().sum(); + t.iter_mut().for_each(|v| *v /= sum); + t +} + +/// Separable blur with odd-length symmetric `taps` (clamped edges), see [`gauss_taps`]. +pub fn gaussian_taps(img: &Image, taps: &[f32]) -> Image { + let (w, h) = (img.width, img.height); + if w == 0 || h == 0 || taps.len() < 3 { + return img.clone(); + } + let r = (taps.len() / 2) as isize; + let mut a = Image::::new(w, h); + par_rows(&mut a.data, w, |y, row| { + let src = &img.data[y * w..(y + 1) * w]; + for (x, o) in row.iter_mut().enumerate() { + let mut acc = T::zero(); + for (k, t) in taps.iter().enumerate() { + let xi = (x as isize + k as isize - r).clamp(0, w as isize - 1) as usize; + acc = acc.madd(src[xi], *t); + } + *o = acc; + } + }); + let mut b = Image::::new(w, h); + par_rows(&mut b.data, w, |y, row| { + for (k, t) in taps.iter().enumerate() { + let yi = (y as isize + k as isize - r).clamp(0, h as isize - 1) as usize; + for (o, v) in row.iter_mut().zip(&a.data[yi * w..(yi + 1) * w]) { + *o = o.madd(*v, *t); + } + } + }); + b +} + #[cfg(test)] mod tests { + #[test] + fn fir_gaussian_has_bounded_finite_taps_for_hostile_sigmas() { + for sigma in [f32::NAN, f32::NEG_INFINITY, f32::INFINITY, f32::MAX, -5.0, 0.0, 0.1, 4.0] { + let taps = super::gauss_taps(sigma); + assert!(taps.len() <= 385 && taps.len() % 2 == 1); + assert!(taps.iter().all(|v| v.is_finite() && *v >= 0.0)); + assert!((taps.iter().sum::() - 1.0).abs() < 1e-5); + } + } + /// The box radii of the formula as it was, for the check below. fn box_radii_before(sigma: f32) -> [usize; 3] { let n = 3.0f32; diff --git a/crates/raster/src/resample.rs b/crates/raster/src/resample.rs index afe0c10d76..4664dfa4b3 100644 --- a/crates/raster/src/resample.rs +++ b/crates/raster/src/resample.rs @@ -115,12 +115,22 @@ impl Pixel for [f32; 4] { } } -/// Resize to `w × h` (separable; horizontal pass then vertical pass). +/// Resize to `w × h` (separable; horizontal pass then vertical pass, or the other way round when +/// that intermediate would be far larger: widening a tall, narrow strip kept every source row at +/// the new width, gigabytes from a small source). pub fn resize(img: &Image, w: usize, h: usize, filter: Filter) -> Image { let (w, h) = (w.max(1), h.max(1)); if img.width == w && img.height == h { return img.clone(); } + if w.saturating_mul(img.height) > img.width.saturating_mul(h).saturating_mul(4) { + return horizontal(&vertical(img, h, filter), w, filter); + } + vertical(&horizontal(img, w, filter), h, filter) +} + +/// Each row resampled to `w` wide. +fn horizontal(img: &Image, w: usize, filter: Filter) -> Image { let wx = weights(img.width, w, filter); let mut tmp = Image::::new(w, img.height); par_rows(&mut tmp.data, w, |y, row| { @@ -134,12 +144,18 @@ pub fn resize(img: &Image, w: usize, h: usize, filter: Filter) -> I *o = acc; } }); + tmp +} + +/// Each column resampled to `h` tall. +fn vertical(img: &Image, h: usize, filter: Filter) -> Image { + let w = img.width; let wy = weights(img.height, h, filter); let mut out = Image::::new(w, h); par_rows(&mut out.data, w, |y, row| { let (lo, ws) = &wy[y]; for (k, wt) in ws.iter().enumerate() { - let src = tmp.row(lo + k); + let src = img.row(lo + k); for (o, s) in row.iter_mut().zip(src) { *o = o.madd(*s, *wt); } @@ -178,6 +194,16 @@ pub fn half(img: &Image) -> Image { mod tests { use super::*; + #[test] + fn widening_a_tall_strip_resamples_its_columns_first() { + // 1 × 400 000 to 4000 × 8: horizontal-first kept 400 000 rows of 4000 (25 GB of RGBA f32) + let mut strip = Image::<[f32; 4]>::new(1, 400_000); + strip.data.iter_mut().for_each(|p| *p = [0.25, 0.5, 0.75, 1.0]); + let out = resize(&strip, 4000, 8, Filter::Mitchell); + assert_eq!((out.width, out.height), (4000, 8)); + assert!(out.data.iter().all(|p| (p[1] - 0.5).abs() < 1e-3), "a flat strip stays flat"); + } + #[test] fn constant_image_stays_constant() { let img = Image::::filled(37, 21, 0.42); diff --git a/crates/raw/Cargo.toml b/crates/raw/Cargo.toml index 3cb2003b26..50ecfc3719 100644 --- a/crates/raw/Cargo.toml +++ b/crates/raw/Cargo.toml @@ -15,6 +15,8 @@ lightcraft-raster = { workspace = true } lightcraft-color = { workspace = true } lightcraft-geom = { workspace = true } serde = { workspace = true } +chrono = { workspace = true } +craft-crw = { workspace = true } thiserror = { workspace = true } rayon = { workspace = true } miniz_oxide = { workspace = true } diff --git a/crates/raw/src/chart_table.rs b/crates/raw/src/chart_table.rs new file mode 100644 index 0000000000..bb87ec73e2 --- /dev/null +++ b/crates/raw/src/chart_table.rs @@ -0,0 +1,21 @@ +// Camera colour matrices fitted to our own photographs of a ColorChecker Classic (post-November-2014 formulation), +// for cameras with no published spectral sensitivities. Kept by hand: each row's capture, fit and checks are in +// clean-room/crw/10-chart-calibration.md (scripts local-only). Reference colours: X-Rite's published L*a*b* (D50) for +// the chart, as packaged by colour-science (BSD-3-Clause). No number comes from Adobe or from a GPL raw decoder. +use super::Camera; +use lightcraft_color::Mat3; + +#[rustfmt::skip] +pub(super) const CAMERAS: &[Camera] = &[ + // Canon EOS D60 (CRW), the maintainer's body, ISO 100. Matrix 1: one ~2,900 K tungsten bulb, 11 frames, filed as + // Standard Illuminant A; matrix 2: direct afternoon sun, ~4,850 K, 20 frames, filed as D50 (both temperatures from + // the camera's own white-balance presets). Fitted on chromaticity with neutral held at D50 (the sunlit chart was + // unevenly lit): CIEDE2000 mean 2.42 / 1.70 on the 24 patches, 2.74 / 1.97 leaving each patch out. + Camera { + make: "Canon", + model: "EOS D60", + illuminant: [17, 23], + color_matrix: [Mat3([[0.950961, -0.345297, 0.112165], [-0.545579, 1.400621, 0.558365], [-0.123107, 0.222004, 1.026236]]), Mat3([[0.609694, -0.127035, -0.045387], [-0.461201, 1.16644, 0.337283], [-0.115992, 0.229363, 0.791647]])], + forward_matrix: [Mat3([[0.763921, 0.183562, 0.016813], [0.268545, 0.944022, -0.212567], [0.100742, -0.431647, 1.15601]]), Mat3([[0.757277, 0.190573, 0.016446], [0.291782, 1.009128, -0.300909], [0.026419, -0.264451, 1.063137]])], + }, +]; 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 17152e80f9..e8052c3bbb 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -15,7 +15,8 @@ //! //! Formats: DNG (uncompressed, lossless JPEG, lossy JPEG (Smart Previews), Deflate incl. floating point, JPEG XL (DNG 1.7, //! `jxl` feature, on by default), tiled/stripped, CFA and LinearRaw), -//! Canon CR2 / CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW), Nikon NEF/NRW (uncompressed, Huffman lossless / lossy compressed), Sony ARW (uncompressed, ARW2, lossless), Fujifilm RAF (uncompressed Bayer +//! Canon CR2 / CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW) / CRW (the CIFF bodies of 2000–2004; clean-room-derived +//! compression, `vendor::crw`; the PowerShot G5's anomalous coding is refused), Nikon NEF/NRW (uncompressed, Huffman lossless / lossy compressed), Sony ARW (uncompressed, ARW2, lossless), Fujifilm RAF (uncompressed Bayer //! and X-Trans, lossless and lossy compressed), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format: compressed 4 and 6, the prefix-coded strips of 8, //! packed 2/5/7, the 16-bit words of the oldest bodies), Pentax PEF (uncompressed, Huffman), Olympus ORF (uncompressed: 16-bit words, 12-bit XZ-2 words, 12-bit 16-byte blocks of the E-300/E-330/E-500). //! [`embedded_preview`] covers these containers' JPEG previews. Variants we can't decode yet (compressed ORF, CR3 unverified marker families / C-RAW configurations) return [`RawError::Unsupported`]; each vendor module documents its sources @@ -27,6 +28,7 @@ mod binned; pub mod color; +pub mod dcp; pub mod demosaic; mod dng; pub mod dngwrite; @@ -140,6 +142,7 @@ impl RawFormat { RawFormat::Dng | RawFormat::Cr2 | RawFormat::Cr3 + | RawFormat::Crw | RawFormat::Nef | RawFormat::Nrw | RawFormat::Arw @@ -413,6 +416,7 @@ fn decode_with(bytes: &[u8], mode: Mode) -> Result { RawFormat::Dng => dng::decode(bytes, mode).map(lift_clipped), RawFormat::Cr2 => vendor::cr2::decode(bytes, mode), RawFormat::Cr3 => vendor::cr3::decode(bytes, mode), + RawFormat::Crw => vendor::crw::decode(bytes, mode), RawFormat::Nef | RawFormat::Nrw => vendor::nef::decode(bytes, mode), RawFormat::Arw => vendor::arw::decode(bytes, mode), RawFormat::Raf => vendor::raf::decode(bytes, mode), diff --git a/crates/raw/src/opcodes.rs b/crates/raw/src/opcodes.rs index 4d3e463b0e..2f5d51fae0 100644 --- a/crates/raw/src/opcodes.rs +++ b/crates/raw/src/opcodes.rs @@ -566,8 +566,45 @@ const MAX_BAD_PIXELS: usize = 1 << 22; /// Apply a list to an interleaved `w × h × cpp` buffer. `cfa` (when the data is a mosaic) is used by the /// bad-pixel opcodes. `scale` is the value of 1.0 in the buffer: 65535 for list 1 (raw 16-bit values), 1 for /// lists 2 and 3 (normalised values). +/// Whole-image passes one opcode list may cost, all its ops together (a real DNG's list is a +/// handful of gain maps and tables). Ops past it, in list order, are left out: a list repeating a +/// full-image polynomial thousands of times was billions of evaluations on an ordinary raw. +const MAX_LIST_PASSES: usize = 32; + +/// Sample visits `op` costs on a `w × h × cpp` buffer (coefficient evaluations for a polynomial). +fn op_cost(op: &Opcode, w: usize, h: usize, cpp: usize) -> usize { + let visits = |a: &Area| { + let rows = (a.bottom as usize).min(h).saturating_sub(a.top as usize).div_ceil(a.row_pitch.max(1) as usize); + let cols = (a.right as usize).min(w).saturating_sub(a.left as usize).div_ceil(a.col_pitch.max(1) as usize); + let planes = (a.plane as usize).saturating_add(a.planes.max(1) as usize).min(cpp).saturating_sub(a.plane as usize); + rows.saturating_mul(cols).saturating_mul(planes) + }; + match op { + Opcode::MapPolynomial { area, coefficients } => visits(area).saturating_mul(coefficients.len().max(1)), + Opcode::MapTable { area, .. } + | Opcode::GainMap { area, .. } + | Opcode::DeltaPerRow { area, .. } + | Opcode::DeltaPerColumn { area, .. } + | Opcode::ScalePerRow { area, .. } + | Opcode::ScalePerColumn { area, .. } => visits(area), + // `apply_list` does nothing for these, so they spend none of the budget + Opcode::Unknown { .. } + | Opcode::TrimBounds { .. } + | Opcode::WarpFisheye { .. } + | Opcode::WarpRectilinear { .. } + | Opcode::WarpRectilinear2 { .. } => 0, + _ => w.saturating_mul(h).saturating_mul(cpp), + } +} + pub fn apply_list(list: &[Opcode], buf: &mut [f32], w: usize, h: usize, cpp: usize, cfa: Option<&Cfa>, scale: f32) { + let mut budget = w.saturating_mul(h).saturating_mul(cpp).max(1).saturating_mul(MAX_LIST_PASSES); for op in list { + let cost = op_cost(op, w, h, cpp); + if cost > budget { + continue; + } + budget -= cost; match op { Opcode::MapTable { area, table } => { let n = table.len(); diff --git a/crates/raw/src/opcodes/tests.rs b/crates/raw/src/opcodes/tests.rs index d1be999e98..48840ff23a 100644 --- a/crates/raw/src/opcodes/tests.rs +++ b/crates/raw/src/opcodes/tests.rs @@ -456,3 +456,30 @@ fn cropped_lens_corrections_correct_the_crop_like_the_whole() { assert!(warps[0].cropped(w, h, crate::Rect::new(30, 0, 70, 50)).is_none()); assert!(warps[0].cropped(w, h, crate::Rect::new(usize::MAX, 0, 70, 50)).is_none()); } + +/// Ten thousand full-image polynomials (a few hundred KB of opcode data): the list is held to +/// `MAX_LIST_PASSES` passes of work, the first ones applied and the rest left out. +#[test] +fn a_list_repeating_full_image_work_stops_at_its_budget() { + let (w, h) = (64usize, 48usize); + let a = Area { top: 0, left: 0, bottom: h as u32, right: w as u32, plane: 0, planes: 1, row_pitch: 1, col_pitch: 1 }; + // v + 0.001 each, two coefficients: each costs two passes + let list = vec![Opcode::MapPolynomial { area: a, coefficients: vec![0.001, 1.0] }; 10_000]; + let mut buf = vec![0.0f32; w * h]; + apply_list(&list, &mut buf, w, h, 1, None, 1.0); + let applied = (buf[0] / 0.001).round() as usize; + assert_eq!(applied, MAX_LIST_PASSES / 2, "{}", buf[0]); + assert!(buf.iter().all(|v| *v == buf[0])); +} + +/// Opcodes `apply_list` does nothing for spend none of the budget: a later real one still runs. +#[test] +fn ops_that_apply_nothing_cost_no_budget() { + let (w, h) = (8usize, 8usize); + let a = Area { top: 0, left: 0, bottom: h as u32, right: w as u32, plane: 0, planes: 1, row_pitch: 1, col_pitch: 1 }; + let mut list = vec![Opcode::Unknown { id: 9999, flags: 0, params: Vec::new() }; 4 * MAX_LIST_PASSES]; + list.push(Opcode::MapPolynomial { area: a, coefficients: vec![0.5, 1.0] }); + let mut buf = vec![0.0f32; w * h]; + apply_list(&list, &mut buf, w, h, 1, None, 1.0); + assert_eq!(buf[0], 0.5); +} diff --git a/crates/raw/src/preview/tests.rs b/crates/raw/src/preview/tests.rs index 7eb9b8dc16..aa2dc0da74 100644 --- a/crates/raw/src/preview/tests.rs +++ b/crates/raw/src/preview/tests.rs @@ -485,8 +485,8 @@ fn scanned_containers_give_the_largest_colour_jpeg() { f.extend_from_slice(part); f.extend_from_slice(&[0u8; 7]); } - // MRW decodes; its preview is still found by the scan - assert!(crate::probe(&f).is_some_and(|p| !p.is_supported() || p == crate::RawFormat::Mrw), "{head:?}"); + // CRW and MRW decode; their previews are still found by the scan, the others stay preview-only containers + assert!(crate::probe(&f).is_some_and(|p| !p.is_supported() || p == crate::RawFormat::Crw || p == crate::RawFormat::Mrw), "{head:?}"); assert_eq!(embedded_preview(&f).as_deref(), Some(&big[..]), "{head:?}"); for n in (0..f.len()).step_by(11) { let _ = embedded_preview(&f[..n]); diff --git a/crates/raw/src/sparse.rs b/crates/raw/src/sparse.rs index 8a404a25ea..893ba79b20 100644 --- a/crates/raw/src/sparse.rs +++ b/crates/raw/src/sparse.rs @@ -121,7 +121,8 @@ impl Ranges { /// The parts of `[start, end)` not covered. pub fn gaps(&self, start: u64, end: u64) -> Ranges { - let mut out = Ranges::new(); + // the gaps come in order, apart from each other: pushed, not merged in one by one + let mut out = Vec::new(); let mut at = start; for &(a, b) in &self.0 { if b <= at { @@ -131,24 +132,20 @@ impl Ranges { break; } if a > at { - out.insert(at, a); + out.push((at, a)); } at = at.max(b); } if at < end { - out.insert(at, end); + out.push((at, end)); } - out + Ranges(out) } /// These ranges without the ones in `other`. pub fn minus(&self, other: &Ranges) -> Ranges { let mut out = Ranges::new(); - for &(a, b) in &self.0 { - for &(x, y) in other.gaps(a, b).spans() { - out.insert(x, y); - } - } + out.extend(self.0.iter().flat_map(|&(a, b)| other.gaps(a, b).0)); out } } @@ -201,12 +198,17 @@ fn plan(bytes: &[u8], loaded: &Ranges, preview: bool) -> HeaderPlan { struct Want<'a> { len: u64, loaded: &'a Ranges, - need: Ranges, + /// What is missing, as found; merged once into the plan (merging each find into the ranges so + /// far was a copy of them per find: quadratic over a file of many out-of-line values). + need: Vec<(u64, u64)>, + /// `need` is merged when it reaches this long, so repeated finds of one gap stay bounded by + /// the distinct gaps (merging when it doubles keeps the cost linear). + compact_at: usize, } impl<'a> Want<'a> { fn new(bytes: &[u8], loaded: &'a Ranges) -> Self { - Self { len: bytes.len() as u64, loaded, need: Ranges::new() } + Self { len: bytes.len() as u64, loaded, need: Vec::new(), compact_at: 64 } } /// Whether `[start, end)` (clipped to the file) is loaded; asks for what isn't. @@ -215,15 +217,21 @@ impl<'a> Want<'a> { if self.loaded.contains(start, end) { return true; } - for &(a, b) in self.loaded.gaps(start, end).spans() { - self.need.insert(a, b); + self.need.extend(self.loaded.gaps(start, end).0); + if self.need.len() >= self.compact_at { + let mut merged = Ranges::new(); + merged.extend(std::mem::take(&mut self.need)); + self.need = merged.spans().to_vec(); + self.compact_at = (self.need.len() * 2).max(64); } false } /// `Need` when something is missing. fn into_plan(self) -> Option { - (!self.need.is_empty()).then_some(HeaderPlan::Need(self.need)) + let mut need = Ranges::new(); + need.extend(self.need); + (!need.is_empty()).then_some(HeaderPlan::Need(need)) } } @@ -559,6 +567,35 @@ mod tests { assert_eq!(r.total(), 20); } + #[test] + fn a_plan_of_many_missing_values_is_gathered_in_one_merge() { + // 200 000 loaded spans with a byte missing between each: every gap wanted once + let mut loaded = Ranges::new(); + loaded.extend((0..20_000u64).map(|i| (i * 4, i * 4 + 3))); + let bytes = vec![0u8; 80_000]; + let mut w = Want::new(&bytes, &loaded); + for i in 0..20_000u64 { + assert!(!w.want(i * 4 + 2, i * 4 + 4)); + } + let Some(HeaderPlan::Need(need)) = w.into_plan() else { panic!("a plan") }; + assert_eq!(need.spans().len(), 20_000); + assert_eq!(need.total(), 20_000); + assert_eq!(loaded.gaps(0, 12).spans(), &[(3, 4), (7, 8), (11, 12)]); + } + + #[test] + fn repeated_wants_of_one_gap_keep_the_buffer_bounded() { + let loaded = Ranges::new(); + let bytes = vec![0u8; 1000]; + let mut w = Want::new(&bytes, &loaded); + for _ in 0..100_000 { + assert!(!w.want(10, 20)); + assert!(w.need.len() <= 64); + } + let Some(HeaderPlan::Need(need)) = w.into_plan() else { panic!("a plan") }; + assert_eq!(need.spans(), &[(10, 20)]); + } + #[test] fn hostile_input_never_panics_and_ends() { let mut loaded = Ranges::new(); diff --git a/crates/raw/src/spectral.rs b/crates/raw/src/spectral.rs index 3a3e74262a..6c4e7c46ce 100644 --- a/crates/raw/src/spectral.rs +++ b/crates/raw/src/spectral.rs @@ -1,28 +1,34 @@ -//! Camera colour matrices from measured spectral sensitivities, for raws that carry no colour matrix. +//! Measured camera colour matrices, for raws that carry no colour matrix. //! -//! [`find`] looks a camera up by its Exif make and model in a table generated by -//! `tools/spectral_camera_table.py` from rawtoaces-data (Academy Software Foundation, Apache-2.0): per model, DNG -//! `ColorMatrix1/2` and `ForwardMatrix1/2` for Standard Illuminant A and D65, fitted to the camera's measured spectral -//! sensitivities. [`Camera::fill`] writes them into a file's [`ColorData`], and [`crate::color`]'s DNG model does the -//! rest. Other names of a covered camera (Rebel T3i for EOS 600D) come from rawtoaces-data's alias list, and other -//! bodies built on a covered camera's sensor from [`SAME_SENSOR`]. No number +//! [`find`] looks a camera up by its Exif make and model in two tables, per model DNG `ColorMatrix1/2` and +//! `ForwardMatrix1/2` for two calibration illuminants: +//! - generated by `tools/spectral_camera_table.py` from rawtoaces-data (Academy Software Foundation, Apache-2.0), +//! fitted to the camera's measured spectral sensitivities, for Standard Illuminant A and D65. Other names of a +//! covered camera (Rebel T3i for EOS 600D) come from rawtoaces-data's alias list, and other bodies built on a +//! covered camera's sensor from [`SAME_SENSOR`]; +//! - `chart_table.rs`: fitted to our own photographs of a ColorChecker Classic under two lights, for cameras with no +//! published sensitivities (`clean-room/crw/10-chart-calibration.md`). +//! +//! [`Camera::fill`] writes them into a file's [`ColorData`], and [`crate::color`]'s DNG model does the rest. No number //! comes from Adobe or from a GPL raw decoder. Which colour a raw starts from is the engine's choice //! (`docs/camera-preview-colour.md`). use crate::ColorData; use lightcraft_color::{Mat3, Xy}; +#[path = "chart_table.rs"] +mod chart; #[path = "spectral_table.rs"] mod table; -/// DNG `CalibrationIlluminant` codes of the two matrices: Standard Illuminant A, D65. -const ILLUMINANTS: [u16; 2] = [17, 21]; - /// One camera's colour matrices. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Camera { pub make: &'static str, pub model: &'static str, - /// XYZ → camera under Standard Illuminant A and D65 (`ColorMatrix1/2`). + /// DNG `CalibrationIlluminant` codes of the two matrices: Standard Illuminant A (17) and D65 (21) for the spectral + /// table, A and D50 (23) for a chart-measured camera. + pub illuminant: [u16; 2], + /// XYZ → camera under the two illuminants (`ColorMatrix1/2`). pub color_matrix: [Mat3; 2], /// White-balanced camera → XYZ D50 (`ForwardMatrix1/2`). pub forward_matrix: [Mat3; 2], @@ -34,7 +40,7 @@ impl Camera { if crate::color::has_matrix(color) { return false; } - color.illuminant = ILLUMINANTS; + color.illuminant = self.illuminant; color.color_matrix = self.color_matrix.map(Some); color.forward_matrix = self.forward_matrix.map(Some); true @@ -88,7 +94,7 @@ pub fn find(make: Option<&str>, model: &str) -> Option<&'static Camera> { }; match table::ALIASES.iter().chain(SAME_SENSOR).find(|(m, alias, _)| same(m, alias)) { Some((m, _, target)) => table::CAMERAS.iter().find(|c| brand(c.make) == brand(m) && c.model == *target), - None => table::CAMERAS.iter().find(|c| same(c.make, c.model)), + None => cameras().find(|c| same(c.make, c.model)), } } @@ -120,9 +126,9 @@ pub fn as_shot_white_through(camera: &Camera, color: &ColorData, wb_multipliers: Some(crate::color::as_shot_white_of(&c, wb_multipliers)) } -/// Every camera in the table. -pub fn cameras() -> &'static [Camera] { - table::CAMERAS +/// Every camera in the tables: the spectral one, then the chart-measured one. +pub fn cameras() -> impl Iterator { + table::CAMERAS.iter().chain(chart::CAMERAS) } #[cfg(test)] @@ -240,7 +246,7 @@ mod tests { #[test] fn every_row_is_a_usable_dng_profile() { - assert_eq!(cameras().len(), 52); + assert_eq!(cameras().count(), 53); for c in cameras() { assert_eq!(find(Some(c.make), c.model), Some(c), "{} {}", c.make, c.model); for m in c.color_matrix.iter().chain(&c.forward_matrix) { @@ -253,7 +259,36 @@ mod tests { let d50 = lightcraft_color::D50.to_xyz(); assert!((0..3).all(|i| (w[i] - d50[i]).abs() < 1e-4), "{} {w:?}", c.model); } + assert!(c.illuminant.iter().all(|&i| crate::color::illuminant_temperature(i).is_some()), "{}", c.model); } + assert!(table::CAMERAS.iter().all(|c| c.illuminant == [17, 21])); + } + + #[test] + fn the_chart_measured_eos_d60_reads_its_presets_in_kelvin() { + // Exif "Canon" / "Canon EOS D60" (CRW), and the catalog's joined string; not the Nikon D60 + let c = find(Some("Canon"), "Canon EOS D60").unwrap(); + assert_eq!((c.model, c.illuminant), ("EOS D60", [17, 23])); + assert_eq!(find_camera("Canon Canon EOS D60"), Some(c)); + assert_eq!(find(Some("NIKON CORPORATION"), "NIKON D60"), None); + // the camera's own white-balance presets (ColorBalance multipliers of a D60 file), which the fit never saw, + // land near the temperatures Canon names for them, on the locus + let kelvin = |r: f32, b: f32| { + let xy = as_shot_white_through(c, &ColorData::default(), Some([r, 1.0, b])).unwrap(); + lightcraft_color::cct::xy_to_temp_tint(xy) + }; + let (tungsten, tint) = kelvin(1.568, 1.918); + assert!((2900.0..3500.0).contains(&tungsten) && tint.abs() < 15.0, "Tungsten {tungsten} {tint}"); + let (daylight, tint) = kelvin(2.541, 1.219); + assert!((4800.0..5800.0).contains(&daylight) && tint.abs() < 15.0, "Daylight {daylight} {tint}"); + let (cloudy, _) = kelvin(2.799, 1.131); + let (flash, _) = kelvin(2.911, 1.103); + eprintln!("EOS D60 presets: Tungsten {tungsten:.0} K, Daylight {daylight:.0} K, Cloudy {cloudy:.0} K, Flash {flash:.0} K"); + assert!(cloudy > daylight + 300.0 && flash > daylight + 300.0, "{daylight} {cloudy} {flash}"); + // the two calibration lights read as the illuminants they were filed under + let (bulb, _) = kelvin(1.353, 2.213); + let (sun, _) = kelvin(2.362, 1.298); + assert!((bulb - 2856.0).abs() < 30.0 && (sun - 5003.0).abs() < 50.0, "{bulb} {sun}"); } #[test] diff --git a/crates/raw/src/spectral_table.rs b/crates/raw/src/spectral_table.rs index e8703e471f..f4ce3f8829 100644 --- a/crates/raw/src/spectral_table.rs +++ b/crates/raw/src/spectral_table.rs @@ -9,312 +9,364 @@ pub(super) const CAMERAS: &[Camera] = &[ Camera { make: "ARRI", model: "D21", + illuminant: [17, 21], color_matrix: [Mat3([[0.933065, -0.03997, 0.042177], [-0.321253, 0.916394, 0.250116], [-0.047929, 0.258088, 0.770888]]), Mat3([[0.841118, 0.11685, -0.05716], [-0.416513, 1.06087, 0.169491], [-0.121062, 0.361236, 0.692345]])], forward_matrix: [Mat3([[0.913988, -0.102353, 0.152661], [0.315506, 0.849769, -0.165276], [-0.134707, -0.698389, 1.6582]]), Mat3([[1.01361, -0.108757, 0.059444], [0.405694, 0.811177, -0.216871], [-0.027612, -0.326433, 1.17915]])], }, Camera { make: "Arashi Vision", model: "Insta360 X5", + illuminant: [17, 21], color_matrix: [Mat3([[1.0899, -0.436896, 0.023525], [-0.482767, 1.39879, 0.369626], [-0.056659, 0.169421, 0.72407]]), Mat3([[0.700283, -0.158934, -0.077847], [-0.543955, 1.30291, 0.196622], [-0.148964, 0.25165, 0.516509]])], forward_matrix: [Mat3([[0.710808, 0.160362, 0.093126], [0.231838, 0.891164, -0.123002], [0.020454, -0.498248, 1.3029]]), Mat3([[0.706099, 0.209581, 0.048616], [0.287186, 0.8971, -0.184286], [0.044158, -0.279999, 1.06095]])], }, Camera { make: "Canon", model: "Digital Rebel XTi", + illuminant: [17, 21], color_matrix: [Mat3([[0.984721, -0.317618, -0.03823], [-0.536205, 1.41139, 0.499196], [-0.019493, 0.0898, 0.993219]]), Mat3([[0.654378, -0.152128, -0.077165], [-0.504141, 1.17532, 0.279049], [-0.071499, 0.132862, 0.672873]])], forward_matrix: [Mat3([[0.735947, 0.130604, 0.097745], [0.271991, 0.870186, -0.142177], [-0.013289, -0.229681, 1.06808]]), Mat3([[0.693623, 0.247958, 0.022715], [0.295094, 0.978904, -0.273998], [0.00951, -0.117049, 0.932644]])], }, Camera { make: "Canon", model: "EOS-1D X Mark II", + illuminant: [17, 21], color_matrix: [Mat3([[0.841821, -0.109388, -0.029826], [-0.469467, 1.34341, 0.484215], [-0.074495, 0.204633, 0.843881]]), Mat3([[0.559829, 0.012974, -0.076841], [-0.474068, 1.17573, 0.252424], [-0.137973, 0.263217, 0.557436]])], forward_matrix: [Mat3([[0.867342, -0.069209, 0.166163], [0.282942, 0.879178, -0.162119], [0.042308, -0.560464, 1.34326]]), Mat3([[0.866644, -0.0379, 0.135551], [0.340507, 0.913959, -0.254466], [0.035971, -0.324047, 1.11318]])], }, Camera { make: "Canon", model: "EOS-1Ds Mark III", + illuminant: [17, 21], color_matrix: [Mat3([[0.933464, -0.245919, -0.026807], [-0.571496, 1.49286, 0.379177], [-0.048229, 0.100118, 0.927528]]), Mat3([[0.623037, -0.073582, -0.085177], [-0.54689, 1.28786, 0.213006], [-0.105037, 0.156191, 0.659429]])], forward_matrix: [Mat3([[0.785005, 0.07525, 0.10404], [0.285685, 0.799015, -0.084701], [0.044611, -0.231741, 1.01223]]), Mat3([[0.764142, 0.106772, 0.093381], [0.318478, 0.835999, -0.154477], [0.03106, -0.128764, 0.922809]])], }, Camera { make: "Canon", model: "EOS-1Ds Mark II", + illuminant: [17, 21], color_matrix: [Mat3([[0.945891, -0.245875, -0.023592], [-0.58518, 1.49586, 0.412994], [-0.049647, 0.124624, 1.04996]]), Mat3([[0.633076, -0.080316, -0.073882], [-0.552992, 1.27833, 0.227086], [-0.10768, 0.180208, 0.730732]])], forward_matrix: [Mat3([[0.78531, 0.073316, 0.10567], [0.29637, 0.804671, -0.101041], [0.021036, -0.254656, 1.05872]]), Mat3([[0.780605, 0.119757, 0.063934], [0.332784, 0.851961, -0.184745], [0.021321, -0.137163, 0.940946]])], }, Camera { make: "Canon", model: "EOS 100D", + illuminant: [17, 21], color_matrix: [Mat3([[0.823379, -0.153284, -0.011827], [-0.451822, 1.34611, 0.422153], [-0.063154, 0.17914, 0.866791]]), Mat3([[0.537713, -0.001778, -0.071702], [-0.479729, 1.20511, 0.230384], [-0.135862, 0.245077, 0.608091]])], forward_matrix: [Mat3([[0.839709, -0.013024, 0.137611], [0.260264, 0.869968, -0.130232], [0.040567, -0.473274, 1.25781]]), Mat3([[0.852444, -0.005311, 0.117164], [0.33135, 0.880249, -0.211599], [0.038232, -0.260159, 1.04703]])], }, Camera { make: "Canon", model: "EOS 200D", + illuminant: [17, 21], color_matrix: [Mat3([[0.882798, -0.11491, -0.016841], [-0.443662, 1.31235, 0.491834], [-0.062151, 0.206192, 0.798346]]), Mat3([[0.570466, 0.029473, -0.079371], [-0.461712, 1.15876, 0.257222], [-0.118587, 0.24972, 0.538517]])], forward_matrix: [Mat3([[0.867592, -0.074026, 0.17073], [0.27684, 0.904905, -0.181745], [0.007997, -0.615366, 1.43247]]), Mat3([[0.884048, -0.067045, 0.147293], [0.347584, 0.917256, -0.26484], [0.021454, -0.322825, 1.12647]])], }, Camera { make: "Canon", model: "EOS 200D II", + illuminant: [17, 21], color_matrix: [Mat3([[0.820814, -0.08112, -0.025232], [-0.449049, 1.31524, 0.500348], [-0.063522, 0.20839, 0.807016]]), Mat3([[0.534782, 0.039491, -0.075304], [-0.461016, 1.15287, 0.26203], [-0.117011, 0.248633, 0.539767]])], forward_matrix: [Mat3([[0.879874, -0.096427, 0.180849], [0.283378, 0.900453, -0.183831], [0.006798, -0.61219, 1.4305]]), Mat3([[0.897644, -0.089573, 0.156225], [0.354938, 0.914467, -0.269405], [0.020307, -0.323555, 1.12835]])], }, Camera { make: "Canon", model: "EOS 5DS", + illuminant: [17, 21], color_matrix: [Mat3([[0.784071, -0.14278, -0.018109], [-0.493528, 1.36672, 0.49299], [-0.067845, 0.178082, 0.792129]]), Mat3([[0.501948, -0.005161, -0.069927], [-0.500698, 1.19504, 0.25793], [-0.125608, 0.228657, 0.525639]])], forward_matrix: [Mat3([[0.838414, -0.019978, 0.145859], [0.285256, 0.874752, -0.160008], [0.038705, -0.507361, 1.29376]]), Mat3([[0.840997, -0.003166, 0.126464], [0.342942, 0.904091, -0.247033], [0.034419, -0.289165, 1.07985]])], }, Camera { make: "Canon", model: "EOS 5D", + illuminant: [17, 21], color_matrix: [Mat3([[0.961758, -0.26807, -0.006664], [-0.565407, 1.47679, 0.405541], [-0.067833, 0.12912, 0.951998]]), Mat3([[0.616895, -0.064661, -0.085183], [-0.554321, 1.28625, 0.22097], [-0.137616, 0.197613, 0.656267]])], forward_matrix: [Mat3([[0.79062, 0.078103, 0.095573], [0.287453, 0.812941, -0.100394], [0.068474, -0.279714, 1.03635]]), Mat3([[0.77434, 0.091394, 0.098562], [0.324069, 0.841224, -0.165293], [0.044245, -0.169979, 0.950838]])], }, Camera { make: "Canon", model: "EOS 5D Mark III", + illuminant: [17, 21], color_matrix: [Mat3([[0.798227, -0.156522, -0.024001], [-0.479014, 1.37953, 0.412187], [-0.067815, 0.178094, 0.795854]]), Mat3([[0.536462, -0.020759, -0.074508], [-0.493492, 1.22724, 0.222071], [-0.136505, 0.242956, 0.547031]])], forward_matrix: [Mat3([[0.829015, -0.007278, 0.142558], [0.266702, 0.857593, -0.124295], [0.048011, -0.488746, 1.26584]]), Mat3([[0.818929, 0.023372, 0.121994], [0.319742, 0.879191, -0.198933], [0.040465, -0.281513, 1.06615]])], }, Camera { make: "Canon", model: "EOS 5D Mark II", + illuminant: [17, 21], color_matrix: [Mat3([[0.765281, -0.126067, -0.028016], [-0.539891, 1.44802, 0.407637], [-0.058008, 0.128461, 0.861097]]), Mat3([[0.508976, -0.002163, -0.072663], [-0.524812, 1.25489, 0.224018], [-0.11344, 0.183978, 0.599963]])], forward_matrix: [Mat3([[0.84396, -0.009524, 0.12986], [0.296711, 0.799464, -0.096175], [0.052873, -0.321603, 1.09383]]), Mat3([[0.8407, 0.001511, 0.122085], [0.343565, 0.82753, -0.171095], [0.035331, -0.182192, 0.971966]])], }, Camera { make: "Canon", model: "EOS 5D Mark IV", + illuminant: [17, 21], color_matrix: [Mat3([[0.763394, -0.085035, -0.016567], [-0.442907, 1.31347, 0.486351], [-0.080725, 0.247335, 0.884784]]), Mat3([[0.49672, 0.034424, -0.068025], [-0.461551, 1.16055, 0.255439], [-0.154521, 0.307914, 0.579555]])], forward_matrix: [Mat3([[0.880649, -0.094084, 0.177732], [0.27666, 0.906137, -0.182797], [0.024429, -0.659213, 1.45989]]), Mat3([[0.898336, -0.087734, 0.153694], [0.347611, 0.924078, -0.271689], [0.035769, -0.378779, 1.16812]])], }, Camera { make: "Canon", model: "EOS 600D", + illuminant: [17, 21], color_matrix: [Mat3([[0.800214, -0.150575, -0.010842], [-0.462694, 1.36091, 0.41413], [-0.054076, 0.17327, 0.853835]]), Mat3([[0.528239, -0.007001, -0.067784], [-0.485979, 1.21691, 0.225002], [-0.13144, 0.244539, 0.592949]])], forward_matrix: [Mat3([[0.836952, -0.011114, 0.138458], [0.267123, 0.859868, -0.12699], [0.017395, -0.463764, 1.27147]]), Mat3([[0.849461, 0.005947, 0.108888], [0.332065, 0.875561, -0.207627], [0.033552, -0.262503, 1.05405]])], }, Camera { make: "Canon", model: "EOS M", + illuminant: [17, 21], color_matrix: [Mat3([[0.858133, -0.188655, -0.015316], [-0.477476, 1.37657, 0.415737], [-0.066593, 0.173487, 0.870331]]), Mat3([[0.559337, -0.024286, -0.076489], [-0.498439, 1.22646, 0.227107], [-0.13663, 0.237788, 0.612213]])], forward_matrix: [Mat3([[0.818185, 0.015661, 0.130449], [0.263684, 0.85776, -0.121444], [0.046738, -0.442459, 1.22083]]), Mat3([[0.820106, 0.031315, 0.112875], [0.32549, 0.874009, -0.199499], [0.03847, -0.243276, 1.02991]])], }, Camera { make: "Canon", model: "EOS R10", + illuminant: [17, 21], color_matrix: [Mat3([[0.900395, -0.120204, -0.023257], [-0.450784, 1.32079, 0.490112], [-0.060508, 0.207987, 0.757971]]), Mat3([[0.586274, 0.022629, -0.081629], [-0.465757, 1.16444, 0.255537], [-0.114546, 0.247787, 0.505639]])], forward_matrix: [Mat3([[0.860416, -0.07424, 0.178119], [0.279245, 0.90614, -0.185385], [-0.005252, -0.64772, 1.47808]]), Mat3([[0.874599, -0.057155, 0.146852], [0.346428, 0.920831, -0.267259], [0.018292, -0.341711, 1.14852]])], }, Camera { make: "Canon", model: "EOS R5", + illuminant: [17, 21], color_matrix: [Mat3([[0.906792, -0.181028, -0.039982], [-0.497007, 1.37995, 0.46653], [-0.056558, 0.135904, 0.790883]]), Mat3([[0.599617, -0.03146, -0.086837], [-0.500836, 1.20715, 0.246929], [-0.122485, 0.204473, 0.529195]])], forward_matrix: [Mat3([[0.825544, 0.000874, 0.137878], [0.27921, 0.851443, -0.130653], [0.053855, -0.393303, 1.16455]]), Mat3([[0.80269, 0.040879, 0.120727], [0.321664, 0.899552, -0.221215], [0.039913, -0.245426, 1.03062]])], }, Camera { make: "Canon", model: "EOS R5m2", + illuminant: [17, 21], color_matrix: [Mat3([[0.925997, -0.201878, -0.03247], [-0.514263, 1.39694, 0.472057], [-0.067213, 0.159605, 0.932813]]), Mat3([[0.603973, -0.037874, -0.08705], [-0.520173, 1.22523, 0.247204], [-0.147012, 0.240988, 0.619754]])], forward_matrix: [Mat3([[0.816853, 0.016859, 0.130583], [0.284699, 0.847793, -0.132492], [0.049678, -0.384186, 1.15961]]), Mat3([[0.796684, 0.049994, 0.117618], [0.326624, 0.8894, -0.216024], [0.040655, -0.243309, 1.02776]])], }, Camera { make: "Canon", model: "EOS R6", + illuminant: [17, 21], color_matrix: [Mat3([[0.887235, -0.176902, -0.018642], [-0.462429, 1.33965, 0.473061], [-0.070097, 0.19962, 0.862666]]), Mat3([[0.571385, -0.014759, -0.079163], [-0.485367, 1.18708, 0.251862], [-0.145333, 0.265796, 0.580543]])], forward_matrix: [Mat3([[0.830203, -0.011614, 0.145706], [0.268315, 0.891706, -0.16002], [0.03391, -0.533608, 1.3248]]), Mat3([[0.829826, 0.011021, 0.123449], [0.329107, 0.920067, -0.249174], [0.037653, -0.307101, 1.09455]])], }, Camera { make: "Canon", model: "EOS R6m2", + illuminant: [17, 21], color_matrix: [Mat3([[0.904651, -0.185945, -0.032292], [-0.490303, 1.37329, 0.46456], [-0.076482, 0.19622, 0.939437]]), Mat3([[0.595351, -0.032062, -0.086354], [-0.499687, 1.20659, 0.246445], [-0.151602, 0.266204, 0.633694]])], forward_matrix: [Mat3([[0.822515, -0.0028, 0.14458], [0.275534, 0.86495, -0.140483], [0.04532, -0.468236, 1.24802]]), Mat3([[0.80207, 0.038555, 0.123671], [0.322259, 0.905003, -0.227262], [0.03728, -0.271382, 1.05921]])], }, Camera { make: "Canon", model: "EOS RP", + illuminant: [17, 21], color_matrix: [Mat3([[0.843269, -0.158656, -0.026198], [-0.497933, 1.37758, 0.476056], [-0.070882, 0.179269, 0.839769]]), Mat3([[0.548578, -0.014251, -0.077893], [-0.504763, 1.20691, 0.250579], [-0.139008, 0.243991, 0.560854]])], forward_matrix: [Mat3([[0.836529, -0.017241, 0.145008], [0.285362, 0.860694, -0.146057], [0.049163, -0.481077, 1.25702]]), Mat3([[0.825922, 0.011858, 0.126516], [0.334357, 0.898585, -0.232942], [0.038621, -0.283664, 1.07015]])], }, Camera { make: "Canon", model: "EOS R", + illuminant: [17, 21], color_matrix: [Mat3([[0.732886, -0.080769, -0.010303], [-0.454757, 1.32829, 0.481287], [-0.083062, 0.251827, 0.895746]]), Mat3([[0.473635, 0.038459, -0.063761], [-0.474141, 1.17757, 0.250797], [-0.157456, 0.313293, 0.589901]])], forward_matrix: [Mat3([[0.884185, -0.093978, 0.174089], [0.284166, 0.893986, -0.178152], [0.023242, -0.654769, 1.45663]]), Mat3([[0.908841, -0.095987, 0.151442], [0.356864, 0.902145, -0.259009], [0.034581, -0.371735, 1.16226]])], }, Camera { make: "Canon", model: "PowerShot S90", + illuminant: [17, 21], color_matrix: [Mat3([[1.37542, -0.592063, 0.037432], [-0.219062, 1.12456, 0.326212], [-0.021707, 0.09788, 0.58587]]), Mat3([[0.90732, -0.244506, -0.087152], [-0.314903, 1.06475, 0.215416], [-0.11223, 0.179775, 0.439924]])], forward_matrix: [Mat3([[0.67794, 0.203129, 0.083227], [0.105177, 1.01192, -0.1171], [0.055684, -0.464622, 1.23404]]), Mat3([[0.655349, 0.321862, -0.012915], [0.180096, 1.10102, -0.281111], [0.064028, -0.26917, 1.03025]])], }, Camera { make: "Fujifilm", model: "GFX 100", + illuminant: [17, 21], color_matrix: [Mat3([[1.37208, -0.633889, 0.081365], [-0.430548, 1.32101, 0.427017], [-0.039908, 0.114944, 0.782345]]), Mat3([[0.834968, -0.233255, -0.07589], [-0.475844, 1.18948, 0.241344], [-0.126239, 0.194812, 0.541708]])], forward_matrix: [Mat3([[0.673446, 0.25104, 0.039809], [0.200798, 0.950696, -0.151494], [0.031013, -0.340478, 1.13457]]), Mat3([[0.679917, 0.304542, -0.020163], [0.261808, 1.00662, -0.268426], [0.044444, -0.214012, 0.994673]])], }, Camera { make: "Fujifilm", model: "X-T3", + illuminant: [17, 21], color_matrix: [Mat3([[1.29933, -0.598524, 0.075033], [-0.403354, 1.28265, 0.450876], [-0.037817, 0.112326, 0.810909]]), Mat3([[0.785701, -0.221043, -0.071522], [-0.456611, 1.15627, 0.255052], [-0.124341, 0.191243, 0.562458]])], forward_matrix: [Mat3([[0.671025, 0.255703, 0.037568], [0.190434, 0.97306, -0.163493], [0.03182, -0.334086, 1.12737]]), Mat3([[0.676828, 0.316449, -0.028982], [0.256753, 1.03712, -0.293871], [0.04319, -0.207191, 0.989106]])], }, Camera { make: "Fujifilm", model: "X-T4", + illuminant: [17, 21], color_matrix: [Mat3([[1.27406, -0.587718, 0.074639], [-0.371617, 1.24808, 0.450058], [-0.038746, 0.113215, 0.780014]]), Mat3([[0.771728, -0.215706, -0.070731], [-0.439625, 1.14183, 0.253491], [-0.125229, 0.192512, 0.542394]])], forward_matrix: [Mat3([[0.668116, 0.258486, 0.037694], [0.175163, 0.992049, -0.167213], [0.040145, -0.355105, 1.14006]]), Mat3([[0.675162, 0.317733, -0.028599], [0.248581, 1.05006, -0.298641], [0.04702, -0.219918, 0.998002]])], }, Camera { make: "Hasselblad", model: "L1D-20c", + illuminant: [17, 21], color_matrix: [Mat3([[0.697908, -0.225515, 0.018865], [-0.403519, 1.29608, 0.413637], [-0.048508, 0.167167, 0.74727]]), Mat3([[0.466971, -0.076456, -0.040872], [-0.471572, 1.21777, 0.21163], [-0.133006, 0.246905, 0.516655]])], forward_matrix: [Mat3([[0.754419, 0.110524, 0.099352], [0.21061, 0.943846, -0.154456], [0.016488, -0.523808, 1.33242]]), Mat3([[0.780313, 0.168783, 0.0152], [0.295267, 0.942833, -0.2381], [0.041, -0.301041, 1.08515]])], }, Camera { make: "Hasselblad", model: "L2D-20c", + illuminant: [17, 21], color_matrix: [Mat3([[0.787283, -0.249155, 0.044752], [-0.415734, 1.29586, 0.451949], [-0.060535, 0.144901, 0.709626]]), Mat3([[0.506449, -0.071884, -0.038243], [-0.435817, 1.14056, 0.251334], [-0.129637, 0.209508, 0.474062]])], forward_matrix: [Mat3([[0.776836, 0.120396, 0.067064], [0.218196, 0.951802, -0.169998], [0.071832, -0.4598, 1.21307]]), Mat3([[0.807201, 0.167509, -0.010414], [0.291699, 1.01528, -0.306978], [0.062694, -0.296911, 1.05932]])], }, Camera { make: "Nikon", model: "D200", + illuminant: [17, 21], color_matrix: [Mat3([[1.37569, -0.560621, 0.01677], [-0.606594, 1.52996, 0.38327], [-0.024329, 0.069398, 0.99135]]), Mat3([[0.898945, -0.249527, -0.086342], [-0.568281, 1.29839, 0.222009], [-0.098369, 0.139456, 0.687094]])], forward_matrix: [Mat3([[0.708545, 0.18748, 0.068271], [0.274935, 0.818921, -0.093855], [0.012224, -0.169279, 0.98216]]), Mat3([[0.685079, 0.274473, 0.004744], [0.294469, 0.898619, -0.193087], [0.026107, -0.10149, 0.900488]])], }, Camera { make: "Nikon", model: "D3300", + illuminant: [17, 21], color_matrix: [Mat3([[1.01047, -0.365965, 0.032301], [-0.473579, 1.3513, 0.474736], [-0.075188, 0.164522, 1.02012]]), Mat3([[0.644589, -0.136221, -0.056505], [-0.47509, 1.16499, 0.26318], [-0.15352, 0.237111, 0.681108]])], forward_matrix: [Mat3([[0.738138, 0.162349, 0.063809], [0.234836, 0.925124, -0.15996], [0.059989, -0.351996, 1.11711]]), Mat3([[0.742449, 0.23561, -0.013763], [0.290358, 1.00587, -0.29623], [0.04507, -0.217376, 0.99741]])], }, Camera { make: "Nikon", model: "D5100", + illuminant: [17, 21], color_matrix: [Mat3([[1.34772, -0.48474, 0.012024], [-0.466856, 1.29899, 0.44042], [-0.076248, 0.161652, 0.981853]]), Mat3([[0.929942, -0.213704, -0.081538], [-0.481178, 1.17186, 0.262186], [-0.14942, 0.233631, 0.699016]])], forward_matrix: [Mat3([[0.732398, 0.159354, 0.072543], [0.240376, 0.912366, -0.152741], [0.06111, -0.349037, 1.11303]]), Mat3([[0.727572, 0.254229, -0.017505], [0.287762, 1.00467, -0.292432], [0.040205, -0.206009, 0.990908]])], }, Camera { make: "Nikon", model: "D5300", + illuminant: [17, 21], color_matrix: [Mat3([[0.943297, -0.302977, 0.012055], [-0.489398, 1.36679, 0.480036], [-0.079912, 0.172098, 1.02217]]), Mat3([[0.613661, -0.114638, -0.052652], [-0.475392, 1.16153, 0.266621], [-0.147109, 0.232899, 0.680179]])], forward_matrix: [Mat3([[0.75961, 0.127618, 0.077067], [0.24786, 0.911605, -0.159465], [0.062139, -0.362458, 1.12542]]), Mat3([[0.765013, 0.208344, -0.009061], [0.301196, 0.998195, -0.299391], [0.042143, -0.217084, 1.00005]])], }, Camera { make: "Nikon", model: "D7000", + illuminant: [17, 21], color_matrix: [Mat3([[1.0579, -0.370378, 0.024968], [-0.50908, 1.38998, 0.475636], [-0.075079, 0.158561, 1.00866]]), Mat3([[0.675661, -0.143226, -0.053077], [-0.488456, 1.16985, 0.270384], [-0.137868, 0.21334, 0.681191]])], forward_matrix: [Mat3([[0.744976, 0.150244, 0.069076], [0.251735, 0.900835, -0.15257], [0.058406, -0.336086, 1.10278]]), Mat3([[0.755556, 0.237153, -0.028413], [0.304411, 0.998446, -0.302857], [0.039148, -0.192875, 0.978832]])], }, Camera { make: "Nikon", model: "D700", + illuminant: [17, 21], color_matrix: [Mat3([[1.25876, -0.491229, 0.017162], [-0.619342, 1.54791, 0.372191], [-0.050936, 0.098145, 1.01122]]), Mat3([[0.835285, -0.217528, -0.074624], [-0.583051, 1.32613, 0.209425], [-0.121368, 0.168895, 0.708639]])], forward_matrix: [Mat3([[0.722062, 0.17127, 0.070964], [0.279306, 0.809472, -0.088779], [0.042476, -0.200528, 0.983157]]), Mat3([[0.707886, 0.252255, 0.004155], [0.304416, 0.875438, -0.179854], [0.032977, -0.118624, 0.910752]])], }, Camera { make: "Nikon", model: "D70", + illuminant: [17, 21], color_matrix: [Mat3([[0.95752, -0.326533, -0.000865], [-0.654123, 1.5628, 0.437699], [-0.01723, 0.05324, 0.899754]]), Mat3([[0.621434, -0.137207, -0.067353], [-0.59081, 1.28888, 0.250406], [-0.066923, 0.098053, 0.633702]])], forward_matrix: [Mat3([[0.74958, 0.134109, 0.080606], [0.313007, 0.787492, -0.100498], [0.005453, -0.15183, 0.971482]]), Mat3([[0.722318, 0.215673, 0.026305], [0.326263, 0.879351, -0.205614], [0.017282, -0.077471, 0.885294]])], }, Camera { make: "Nikon", model: "D800E", + illuminant: [17, 21], color_matrix: [Mat3([[0.981723, -0.320813, 0.025417], [-0.500428, 1.37669, 0.486261], [-0.07946, 0.169419, 1.04548]]), Mat3([[0.629114, -0.117451, -0.046422], [-0.483155, 1.16337, 0.27171], [-0.147278, 0.230496, 0.696276]])], forward_matrix: [Mat3([[0.760723, 0.133423, 0.07015], [0.25382, 0.906695, -0.160515], [0.059962, -0.34837, 1.11351]]), Mat3([[0.780492, 0.212338, -0.028534], [0.311949, 0.998057, -0.310006], [0.041771, -0.208304, 0.991637]])], }, Camera { make: "Nikon", model: "D810", + illuminant: [17, 21], color_matrix: [Mat3([[0.983274, -0.318832, 0.030267], [-0.51358, 1.39278, 0.481653], [-0.076666, 0.176366, 1.07197]]), Mat3([[0.625688, -0.110113, -0.045912], [-0.497828, 1.18171, 0.267671], [-0.149244, 0.239807, 0.71615]])], forward_matrix: [Mat3([[0.763991, 0.129679, 0.070625], [0.262526, 0.897486, -0.160012], [0.045849, -0.35404, 1.13329]]), Mat3([[0.791151, 0.196615, -0.023471], [0.322368, 0.977225, -0.299593], [0.038389, -0.209045, 0.995761]])], }, Camera { make: "Nikon", model: "D850", + illuminant: [17, 21], color_matrix: [Mat3([[1.17359, -0.461087, -0.011934], [-0.607581, 1.52285, 0.4063], [-0.096127, 0.196063, 1.00005]]), Mat3([[0.773836, -0.196466, -0.097677], [-0.609077, 1.35526, 0.205388], [-0.190117, 0.290252, 0.676129]])], forward_matrix: [Mat3([[0.713588, 0.158895, 0.091813], [0.273041, 0.838318, -0.111359], [0.055293, -0.367196, 1.13701]]), Mat3([[0.669707, 0.227388, 0.0672], [0.291703, 0.871502, -0.163205], [0.042827, -0.229884, 1.01216]])], }, Camera { make: "Nikon", model: "Z f", + illuminant: [17, 21], color_matrix: [Mat3([[1.16951, -0.415422, 0.033906], [-0.516721, 1.41065, 0.441119], [-0.080466, 0.180954, 1.07672]]), Mat3([[0.749962, -0.151755, -0.063228], [-0.504317, 1.20913, 0.248149], [-0.162888, 0.256933, 0.729432]])], forward_matrix: [Mat3([[0.744024, 0.151119, 0.069153], [0.253649, 0.888649, -0.142297], [0.049891, -0.351314, 1.12653]]), Mat3([[0.756117, 0.216534, -0.008355], [0.304737, 0.961046, -0.265784], [0.041615, -0.212408, 0.995897]])], }, Camera { make: "Panasonic", model: "DC-GX9", + illuminant: [17, 21], color_matrix: [Mat3([[0.820911, -0.254983, 0.035979], [-0.372553, 1.25333, 0.438192], [-0.054294, 0.146795, 0.747319]]), Mat3([[0.534195, -0.07728, -0.038219], [-0.400358, 1.10647, 0.251688], [-0.12982, 0.216241, 0.50214]])], forward_matrix: [Mat3([[0.772645, 0.116685, 0.074966], [0.196365, 0.972505, -0.16887], [0.06062, -0.463162, 1.22765]]), Mat3([[0.805529, 0.178696, -0.01993], [0.275218, 1.04725, -0.322465], [0.060973, -0.29745, 1.06158]])], }, Camera { make: "Sony", model: "DSC-RX100M4", + illuminant: [17, 21], color_matrix: [Mat3([[0.783848, -0.284096, 0.031033], [-0.411895, 1.30629, 0.410807], [-0.047532, 0.165091, 0.725564]]), Mat3([[0.507376, -0.094837, -0.042497], [-0.488786, 1.23246, 0.213166], [-0.137082, 0.247475, 0.503834]])], forward_matrix: [Mat3([[0.733625, 0.143965, 0.086705], [0.210364, 0.945779, -0.156144], [0.012886, -0.528963, 1.34118]]), Mat3([[0.767183, 0.193058, 0.004054], [0.296288, 0.94455, -0.240838], [0.043397, -0.304922, 1.08663]])], }, Camera { make: "Sony", model: "ILCE-6400", + illuminant: [17, 21], color_matrix: [Mat3([[0.686447, -0.204525, 0.026311], [-0.43013, 1.31387, 0.445779], [-0.061279, 0.132669, 0.791917]]), Mat3([[0.44557, -0.064452, -0.027734], [-0.437513, 1.13079, 0.261784], [-0.122323, 0.190304, 0.552427]])], forward_matrix: [Mat3([[0.782555, 0.106676, 0.075064], [0.224677, 0.924591, -0.149268], [0.078407, -0.377222, 1.12392]]), Mat3([[0.821757, 0.17479, -0.032251], [0.30346, 1.00862, -0.31208], [0.052261, -0.224433, 0.997277]])], }, Camera { make: "Sony", model: "ILCE-7CM2", + illuminant: [17, 21], color_matrix: [Mat3([[0.758033, -0.221503, 0.036455], [-0.492549, 1.36195, 0.503357], [-0.065665, 0.148645, 0.906293]]), Mat3([[0.482991, -0.070139, -0.027429], [-0.478804, 1.14702, 0.282926], [-0.119226, 0.194381, 0.616628]])], forward_matrix: [Mat3([[0.788283, 0.10759, 0.068422], [0.261923, 0.909809, -0.171732], [0.053026, -0.362705, 1.13478]]), Mat3([[0.83437, 0.173346, -0.043421], [0.336938, 0.996333, -0.333271], [0.037073, -0.203664, 0.991696]])], }, Camera { make: "Sony", model: "ILCE-7M3", + illuminant: [17, 21], color_matrix: [Mat3([[0.759047, -0.22787, 0.042531], [-0.502563, 1.37732, 0.491076], [-0.066877, 0.150947, 0.900094]]), Mat3([[0.482867, -0.070899, -0.024574], [-0.489531, 1.16667, 0.274244], [-0.123988, 0.201218, 0.610148]])], forward_matrix: [Mat3([[0.787201, 0.113043, 0.064052], [0.265374, 0.902211, -0.167585], [0.052744, -0.364541, 1.1369]]), Mat3([[0.840001, 0.174345, -0.05005], [0.340881, 0.981246, -0.322127], [0.039232, -0.209817, 0.995689]])], }, Camera { make: "Sony", model: "ILCE-7M4", + illuminant: [17, 21], color_matrix: [Mat3([[0.763892, -0.227658, 0.033049], [-0.512687, 1.38412, 0.503225], [-0.063774, 0.141899, 0.91715]]), Mat3([[0.485445, -0.074907, -0.026973], [-0.491937, 1.15934, 0.283071], [-0.115422, 0.185993, 0.622862]])], forward_matrix: [Mat3([[0.784064, 0.112194, 0.068037], [0.2698, 0.896428, -0.166229], [0.050008, -0.338826, 1.11392]]), Mat3([[0.830062, 0.181159, -0.046925], [0.341401, 0.985843, -0.327244], [0.034749, -0.188826, 0.979182]])], }, Camera { make: "Sony", model: "ILCE-7RM2", + illuminant: [17, 21], color_matrix: [Mat3([[0.775308, -0.25358, 0.026979], [-0.524545, 1.40154, 0.490876], [-0.060608, 0.132591, 0.920838]]), Mat3([[0.492753, -0.089554, -0.036484], [-0.505928, 1.18284, 0.273705], [-0.116121, 0.182519, 0.626106]])], forward_matrix: [Mat3([[0.76369, 0.133034, 0.067571], [0.267238, 0.888036, -0.155274], [0.048003, -0.313698, 1.0908]]), Mat3([[0.787687, 0.201628, -0.025019], [0.326839, 0.971594, -0.298433], [0.034173, -0.177854, 0.968786]])], }, Camera { make: "Sony", model: "ILCE-7RM3", + illuminant: [17, 21], color_matrix: [Mat3([[0.742519, -0.22996, 0.032883], [-0.500197, 1.37662, 0.485744], [-0.063378, 0.142467, 0.898759]]), Mat3([[0.473388, -0.075142, -0.031025], [-0.487453, 1.16732, 0.271829], [-0.119917, 0.192619, 0.610537]])], forward_matrix: [Mat3([[0.776802, 0.119664, 0.06783], [0.260471, 0.900308, -0.160779], [0.051869, -0.347156, 1.12039]]), Mat3([[0.813753, 0.181916, -0.031373], [0.32902, 0.979656, -0.308676], [0.037764, -0.198487, 0.985828]])], }, Camera { make: "Sony", model: "ILCE-7RM4", + illuminant: [17, 21], color_matrix: [Mat3([[0.732028, -0.220808, 0.020118], [-0.501296, 1.37502, 0.49365], [-0.061615, 0.13838, 0.885461]]), Mat3([[0.472151, -0.07908, -0.031322], [-0.483014, 1.15528, 0.279019], [-0.111192, 0.18072, 0.604588]])], forward_matrix: [Mat3([[0.775623, 0.114594, 0.074079], [0.260863, 0.901608, -0.162471], [0.050735, -0.342927, 1.1173]]), Mat3([[0.806038, 0.193021, -0.034763], [0.32686, 0.992356, -0.319216], [0.033831, -0.189102, 0.980375]])], }, Camera { make: "Sony", model: "ILCE-7SM2", + illuminant: [17, 21], color_matrix: [Mat3([[0.615775, -0.137144, 0.06099], [-0.408209, 1.28402, 0.462018], [-0.084205, 0.196387, 0.85663]]), Mat3([[0.395982, -0.016098, -0.005517], [-0.420931, 1.11058, 0.265879], [-0.162165, 0.267589, 0.576945]])], forward_matrix: [Mat3([[0.854583, 0.041834, 0.067878], [0.234125, 0.948414, -0.182539], [0.097857, -0.530195, 1.25744]]), Mat3([[0.948357, 0.092307, -0.076369], [0.33668, 1.02973, -0.366408], [0.073834, -0.330955, 1.08223]])], }, Camera { make: "Sony", model: "ILCE-7SM3", + illuminant: [17, 21], color_matrix: [Mat3([[0.749715, -0.228299, 0.030188], [-0.512062, 1.38442, 0.500457], [-0.072776, 0.169469, 0.933545]]), Mat3([[0.476058, -0.07383, -0.031403], [-0.495874, 1.16904, 0.277606], [-0.134473, 0.222664, 0.625349]])], forward_matrix: [Mat3([[0.779691, 0.113899, 0.070706], [0.268632, 0.905927, -0.174559], [0.04639, -0.390929, 1.16964]]), Mat3([[0.816745, 0.179015, -0.031464], [0.334824, 0.988848, -0.323672], [0.037938, -0.229363, 1.01653]])], }, Camera { make: "Sony", model: "ILCE-9", + illuminant: [17, 21], color_matrix: [Mat3([[0.747492, -0.216385, 0.049086], [-0.499768, 1.37142, 0.499037], [-0.071324, 0.164705, 0.951496]]), Mat3([[0.473639, -0.063703, -0.016557], [-0.488372, 1.1591, 0.280181], [-0.129154, 0.213406, 0.651]])], forward_matrix: [Mat3([[0.796409, 0.106147, 0.061739], [0.26822, 0.906732, -0.174952], [0.050574, -0.378333, 1.15286]]), Mat3([[0.868551, 0.167059, -0.071314], [0.354491, 0.985971, -0.340462], [0.037779, -0.211149, 0.998474]])], }, diff --git a/crates/raw/src/tests.rs b/crates/raw/src/tests.rs index 865099cc92..e58991ccc8 100644 --- a/crates/raw/src/tests.rs +++ b/crates/raw/src/tests.rs @@ -258,9 +258,12 @@ fn private_containers_are_recognised_by_their_magic() { assert_eq!(probe(b"II\x1a\0\0\0HEAPCCDR\0\0"), Some(RawFormat::Crw)); assert_eq!(probe(b"\0MRM\0\x01\0\0"), Some(RawFormat::Mrw)); assert_eq!(probe(b"FOVb\x02\0\x02\0"), Some(RawFormat::X3f)); - for f in [RawFormat::Crw, RawFormat::X3f] { - assert!(!f.is_supported()); + for f in [RawFormat::Crw, RawFormat::Mrw] { + assert!(f.is_supported()); } + assert!(!RawFormat::X3f.is_supported()); + // a CRW signature with no heap behind it is corrupt, not a panic + assert!(matches!(decode(b"II\x1a\0\0\0HEAPCCDR\0\0"), Err(RawError::Corrupt(_)))); assert!(matches!(decode(b"FOVb\x02\0\x02\0"), Err(RawError::Unsupported(w)) if w.contains("X3f"))); // too short for the CIFF signature assert_eq!(probe(b"II\x1a\0\0\0HEAP"), None); diff --git a/crates/raw/src/tiffraw.rs b/crates/raw/src/tiffraw.rs index 75186d2d3b..deb64ea595 100644 --- a/crates/raw/src/tiffraw.rs +++ b/crates/raw/src/tiffraw.rs @@ -63,8 +63,20 @@ pub fn check_image(data: &[u8], info: &ImageInfo) -> Result { return Err(RawError::Limit("image data chunks far larger than the image")); } // Plausibility bound before allocating: no supported coding stores more than ~2000 samples per byte - // (Deflate of constant data is the extreme), so tiny files cannot trigger huge allocations. - let available: u64 = chunks.iter().map(|c| chunk_bytes(data, c).map_or(0, |s| s.len() as u64)).sum(); + // (Deflate of constant data is the extreme), so tiny files cannot trigger huge allocations. The + // bytes are counted once however many chunks point at them: a grid of tiles sharing one small + // payload holds that payload's samples, not the grid's. + let mut spans: Vec<(u64, u64)> = + chunks.iter().filter_map(|c| Some((c.offset, c.offset.checked_add(chunk_bytes(data, c)?.len() as u64)?))).collect(); + spans.sort_unstable(); + let (mut available, mut end) = (0u64, 0u64); + for (a, b) in spans { + let a = a.max(end); + if b > a { + available = available.saturating_add(b - a); + end = b; + } + } if available.saturating_mul(2048) < total as u64 { return Err(RawError::Corrupt(format!("{available} bytes of image data cannot hold {total} samples"))); } @@ -429,6 +441,30 @@ mod lossy_tests { use super::*; use lightcraft_tiff::image::Layout; + /// 65 536 tiles all pointing at the same 256 bytes: the image's samples can't come from them, + /// and nothing of its size is allocated to find that out. + #[test] + fn tiles_sharing_one_payload_count_its_bytes_once() { + let file = vec![0u8; 8 + 256]; + let info = ImageInfo { + width: 4096, + height: 4096, + bits_per_sample: vec![8], + samples_per_pixel: 1, + compression: comp::NONE, + photometric: 34892, + planar: 1, + predictor: 1, + sample_format: 1, + new_subfile_type: 0, + layout: Layout::Tiles { tile_width: 16, tile_height: 16 }, + offsets: vec![8; 65_536], + byte_counts: vec![256; 65_536], + }; + let err = check_image(&file, &info).unwrap_err().to_string(); + assert!(err.contains("cannot hold"), "{err}"); + } + /// A lossy-DNG-style image: two 16×8 tiles, each a baseline JPEG, the right one cut short /// by the image edge. #[test] diff --git a/crates/raw/src/vendor.rs b/crates/raw/src/vendor.rs index 1610f20ee5..a44262a2c4 100644 --- a/crates/raw/src/vendor.rs +++ b/crates/raw/src/vendor.rs @@ -9,6 +9,7 @@ mod arw_lens; pub(crate) mod arw_lens_rm6; pub mod cr2; pub mod cr3; +pub mod crw; pub mod crx; pub(crate) mod crx_wavelet; pub mod erf; diff --git a/crates/raw/src/vendor/arw.rs b/crates/raw/src/vendor/arw.rs index b1a9983caa..ba1c556d7a 100644 --- a/crates/raw/src/vendor/arw.rs +++ b/crates/raw/src/vendor/arw.rs @@ -790,7 +790,8 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { let rm6: Vec = if linear_rgb || !super::arw_lens::is_3_2(crop) { Vec::new() } else { - super::arw_lens_rm6::lens_opcodes(raw, &model, Rect::new(0, 0, w, h), reference) + let lens = metadata.lens_model.as_deref(); + super::arw_lens_rm6::lens_opcodes(raw, &model, lens, metadata.focal_length, Rect::new(0, 0, w, h), reference) }; if !rm6.is_empty() && let Some(record) = sony_lens.as_mut() diff --git a/crates/raw/src/vendor/arw_lens.rs b/crates/raw/src/vendor/arw_lens.rs index 473f5d9ffd..4cebf221ec 100644 --- a/crates/raw/src/vendor/arw_lens.rs +++ b/crates/raw/src/vendor/arw_lens.rs @@ -1,6 +1,6 @@ //! Sony's in-file lens-correction records (shading, lateral chromatic aberration, distortion): bounded decoding of //! the raw image IFD's fields and their encrypted `SR2SubIFD` copies into [`SonyLensCorrections`], and validated -//! ILCE-7RM4A and ILCE-7CR distortion tables into DNG warps for the shared optics pipeline. +//! ILCE-7RM4A, ILCE-7M3 and ILCE-7CR distortion tables into DNG warps for the shared optics pipeline. //! //! Tag identity/layout: https://exiftool.org/TagNames/EXIF.html (`0x7031` to `0x7037`, signed shorts) and //! https://exiftool.org/TagNames/Sony.html#SR2SubIFD (`0x797d`, `0x7980`, `0x7982`). The `SR2SubIFD` setting tags @@ -34,9 +34,9 @@ const DISTORTION: Tags = Tags { setting: (0x7036, 0x7981), table: (0x7037, 0x798 /// TIFF field types. const SHORT: u16 = 3; const SSHORT: u16 = 8; -/// Models using the validated A7R IVA conversion. The A7CR uses a separate conversion. +/// Models using the validated A7R IVA conversion (ILCE-7RM4A, ILCE-7M3). The A7CR uses a separate conversion. /// ILCE-7RM4 and ILCE-7RM4A are distinct models, not interchangeable aliases. -const DISTORTION_MODELS: &[&str] = &["ILCE-7RM4A"]; +const DISTORTION_MODELS: &[&str] = &["ILCE-7RM4A", "ILCE-7M3"]; /// Most directory entries scanned: a classic TIFF directory's largest count, also bounding a BigTIFF one. const MAX_ENTRIES: usize = 1 << 16; const SAMPLES: usize = 1024; @@ -1397,6 +1397,47 @@ mod tests { } } + // ILCE-7M3 raw-IFD tables (FE 16-35mm F4 ZA OSS at 16 and 35 mm, FE 28-70mm F3.5-5.6 OSS at 70 mm) and the + // geometry of the camera's own JPEG of the same exposure (Lens Comp. Distortion: Auto): checkerboard corners of + // that JPEG matched with the uncorrected raw and fitted with the warp's polynomial over the 6000×4000 frame (rms + // 0.11–0.25 px). See docs/sony-lens-corrections.md. + const A7M3: [([i16; 16], [f64; 4]); 3] = [ + ( + [32, 2, -38, -83, -138, -199, -270, -336, -402, -462, -519, -568, -611, -643, -670, -690], + [1.0247000859, -0.1092847508, 0.1061422243, -0.0397989678], + ), + ([2, 2, 4, 9, 18, 29, 45, 65, 92, 124, 164, 210, 264, 329, 403, 489], [0.9708150714, 0.0157256288, 0.0175613359, -0.004107544]), + ([4, 7, 18, 40, 68, 108, 155, 212, 280, 359, 453, 557, 679, 819, 978, 1161], [0.9342002611, 0.0560486347, 0.0076184603, 0.0021497933]), + ]; + + #[test] + fn ilce_7m3_matches_the_cameras_own_jpeg_geometry() { + let frame = Rect::new(0, 0, 6000, 4000); + let evaluate = |k: &[f64], r: f64| r * (k[0] + r * r * (k[1] + r * r * (k[2] + r * r * k[3]))); + for (values, reference) in A7M3 { + let Opcode::WarpRectilinear { planes, center } = distortion("ILCE-7M3", &values, frame, frame).unwrap() else { panic!("warp") }; + assert_eq!(center, [0.5, 0.5]); + // The camera fills its frame with its own zoom; compare the shape over the measured radii (to 0.97). + let radii: Vec = (1..=97).map(|i| i as f64 / 100.0).collect(); + let (ours, camera): (Vec, Vec) = radii.iter().map(|&r| (evaluate(&planes[0], r), evaluate(&reference, r))).unzip(); + let worst = |ours: &[f64]| { + let zoom = ours.iter().zip(&camera).map(|(a, b)| a * b).sum::() / ours.iter().map(|a| a * a).sum::(); + ours.iter().zip(&camera).map(|(a, b)| (a * zoom - b).abs()).fold(0.0, f64::max) + }; + // 0.0008 of the half diagonal is 2.9 px on the 6000 px frame (measured: 0.4–2.4 px); uncorrected is 10×+ off. + let (corrected, uncorrected) = (worst(&ours), worst(&radii)); + assert!(corrected < 0.0008 && uncorrected > 10.0 * corrected, "{values:?}: {corrected} vs {uncorrected}"); + } + // Sony's crop and the default crop agree on this body (12, 12, 6000×4000 of 6048×4024), so the warp sits on + // the image centre. + let Opcode::WarpRectilinear { center, .. } = + distortion("ILCE-7M3", &A7M3[0].0, Rect::new(0, 0, 6048, 4024), Rect::new(12, 12, 6000, 4000)).unwrap() + else { + panic!("warp") + }; + assert!((center[0] * 6047.0 - 3011.5).abs() < 1e-9 && (center[1] * 4023.0 - 2011.5).abs() < 1e-9, "{center:?}"); + } + #[test] fn barrel_framing_and_offset_crop_keep_the_same_geometry() { let crop = Rect::new(32, 20, 9504, 6336); @@ -1427,14 +1468,16 @@ mod tests { #[test] fn refuses_unvalidated_models_even_with_a_valid_table() { assert!(distortion("ILCE-7RM4A", &TELE, AREA, AREA).is_some()); - for model in ["", "ILCE-7M3", "ILCE-7M4", "ILCE-7RM4", "ILCE-7RM5", "ILCE-9M2", "DSC-RX100M3", "ILCE-7RM4A unknown", "ILCE-7CR"] { + assert!(distortion("ILCE-7M3", &TELE, AREA, AREA).is_some()); + for model in ["", "ILCE-7M4", "ILCE-7RM4", "ILCE-7RM5", "ILCE-9M2", "DSC-RX100M3", "ILCE-7RM4A unknown", "ILCE-7CR", "ILCE-7M3 ", "ILCE-7SM3"] + { assert!(distortion(model, &TELE, AREA, AREA).is_none(), "{model}"); } } #[test] fn header_and_full_decode_preserve_correction_through_dng() { - for (model, expected) in [("ILCE-7RM4A", 1), ("ILCE-7RM4", 0), ("ILCE-7M3", 0), ("", 0)] { + for (model, expected) in [("ILCE-7RM4A", 1), ("ILCE-7RM4", 0), ("ILCE-7M3", 1), ("ILCE-7M4", 0), ("", 0)] { for (height, expected) in [(20, expected), (16, 0)] { for order in [ByteOrder::Little, ByteOrder::Big] { let mut raw = IfdBuilder::new(); diff --git a/crates/raw/src/vendor/arw_lens_rm6.rs b/crates/raw/src/vendor/arw_lens_rm6.rs index 1130abc6d7..5a215ef7a2 100644 --- a/crates/raw/src/vendor/arw_lens_rm6.rs +++ b/crates/raw/src/vendor/arw_lens_rm6.rs @@ -62,6 +62,32 @@ const FULL_FRAME_CROP: &[(&str, (f64, f64))] = &[("ILCE-7RM6", (9984.0, 6656.0)) /// The verified APS-C bodies (Exif `Model`): their knots span the file's own default crop, the last knot at its corner. /// Measured on the ILCE-6700 (docs/sony-ilce7rm6-lens-corrections.md → ILCE-6700). const APSC_BODIES: &[&str] = &["ILCE-6700"]; + +/// A lens whose tables follow its body's convention with another knot spacing and unit, at the focal lengths up to +/// `max_focal_mm`; measured like the body, against the camera JPEG. +struct LensException { + /// Exif `Model` of the body. + body: &'static str, + /// Exif `LensModel`, as the body records it. + lens: &'static str, + max_focal_mm: f64, + knot_spacing: f64, + unit: f64, +} + +/// The measured lens exceptions (docs/sony-ilce7rm6-lens-corrections.md → ILCE-6700). +const LENS_EXCEPTIONS: &[LensException] = &[ + // Sigma 10-18 mm F2.8 DC DN at its wide end: 97 photos at 10 mm and 2 at 10.4-10.5 mm. The body's rule leaves + // 1.36-1.38 px there; from 11.7 mm on the body's rule fits better. `lens` is the only LensModel in 336 files of + // this lens (native E-mount, no adapter); the 116 measured copies carry body firmware "ILCE-6700 v2.00" + LensException { body: "ILCE-6700", lens: "10-18mm F2.8 DC DN | Contemporary 023", max_focal_mm: 10.5, knot_spacing: 416.0, unit: 14250.0 }, +]; + +/// The exception for the body `model` with the lens `lens` at `focal_mm`, if one is measured. +fn lens_exception(model: &str, lens: Option<&str>, focal_mm: Option) -> Option<&'static LensException> { + let (lens, focal) = (lens?.trim(), focal_mm.filter(|f| f.is_finite() && *f > 0.0)?); + LENS_EXCEPTIONS.iter().find(|e| e.body == model.trim() && e.lens == lens && focal <= e.max_focal_mm) +} /// The distortion table's value of 1 (relative radius); a global least-squares fit over the 34 photos gives 15000.7. const DISTORTION_UNIT: f64 = 15000.0; /// The CA table's value of 1 (relative to the green source radius). Provisional: the median best unit of the 20 @@ -179,18 +205,19 @@ fn fill_zoom(source: &dyn Fn(f64) -> f64, x: f64, y: f64) -> Option { /// worse than 0.25 px at a 1440 px long edge at one of the fit samples within the crop (a padded active area, as in /// lossless files, reaches radii that are never shown). pub(crate) fn warp_opcode(t: &LensTables, knot_spacing: f64, active: Rect, crop: Rect, lateral_ca: bool) -> Option { - gated_warp_opcode(t, knot_spacing, active, crop, lateral_ca, FIT_ERROR_PX_AT_1440) + gated_warp_opcode(t, knot_spacing, DISTORTION_UNIT, active, crop, lateral_ca, FIT_ERROR_PX_AT_1440) } -/// [`warp_opcode`] with the fit gate `fit_error_px` (px at a 1440 px long edge) instead of 0.25 px. -fn gated_warp_opcode(t: &LensTables, knot_spacing: f64, active: Rect, crop: Rect, lateral_ca: bool, fit_error_px: f64) -> Option { +/// [`warp_opcode`] with the distortion unit `unit` instead of 15000 and the fit gate `fit_error_px` (px at a 1440 px +/// long edge) instead of 0.25 px. +fn gated_warp_opcode(t: &LensTables, knot_spacing: f64, unit: f64, active: Rect, crop: Rect, lateral_ca: bool, fit_error_px: f64) -> Option { let v = t.distortion.as_deref().filter(|v| v.iter().any(|&x| x != 0.0))?; let (aw, ah) = (active.width as f64, active.height as f64); if aw < 2.0 || ah < 2.0 || crop.width == 0 || crop.height == 0 { return None; } let (cw, ch) = (crop.width as f64, crop.height as f64); - let source = |r: f64| r * (1.0 + interpolate(v, knot_spacing, r) / DISTORTION_UNIT); + let source = |r: f64| r * (1.0 + interpolate(v, knot_spacing, r) / unit); let z = fill_zoom(&source, cw / 2.0, ch / 2.0)?; // DNG's normalisation: pixel-index units, radius 1 = the farthest active-area corner let (cx, cy) = (crop.x as f64 + (cw - 1.0) / 2.0, crop.y as f64 + (ch - 1.0) / 2.0); @@ -226,12 +253,16 @@ fn gated_warp_opcode(t: &LensTables, knot_spacing: f64, active: Rect, crop: Rect /// R and B by 0.84 × the table. Over the 43 verified photos with enough corner detail, the render's corner R/G and B/G /// CA went from rms 0.032 / max 0.125 px (off) to 0.052 / 0.219 px (on) at a 1440 px long edge; only the 16–35 mm /// improved. Follow-up: warp the CFA colour planes before demosaic, then turn the planes on here. -pub(crate) fn lens_opcodes(raw: &Ifd, model: &str, active: Rect, crop: Rect) -> Vec { +/// +/// `lens` (Exif `LensModel`) and `focal_mm` (Exif `FocalLength`) select a measured lens exception's spacing and unit. +pub(crate) fn lens_opcodes(raw: &Ifd, model: &str, lens: Option<&str>, focal_mm: Option, active: Rect, crop: Rect) -> Vec { let tables = read_tables(raw); let knots = tables.distortion.as_ref().map_or(0, Vec::len); let Some(spacing) = knot_spacing(model, knots, crop) else { return Vec::new() }; - let op = if APSC_BODIES.contains(&model.trim()) { - gated_warp_opcode(&tables, spacing, active, crop, false, APSC_FIT_ERROR_PX_AT_1440) + let op = if let Some(e) = lens_exception(model, lens, focal_mm) { + gated_warp_opcode(&tables, e.knot_spacing, e.unit, active, crop, false, APSC_FIT_ERROR_PX_AT_1440) + } else if APSC_BODIES.contains(&model.trim()) { + gated_warp_opcode(&tables, spacing, DISTORTION_UNIT, active, crop, false, APSC_FIT_ERROR_PX_AT_1440) } else { warp_opcode(&tables, spacing, active, crop, false) }; @@ -372,7 +403,7 @@ mod tests { let t = read_tables(&ifd); assert!(t.distortion.is_none(), "{what}"); assert!(warp_opcode(&t, knots(), FF_ACTIVE, FF_CROP, false).is_none(), "{what}"); - assert!(lens_opcodes(&ifd, "ILCE-7RM6", FF_ACTIVE, FF_CROP).is_empty(), "{what}"); + assert!(lens_opcodes(&ifd, "ILCE-7RM6", None, None, FF_ACTIVE, FF_CROP).is_empty(), "{what}"); } // not an integer array, or absent for value in [Value::Ascii("16 0 2 7".into()), Value::Double(vec![2.0, 0.0, 1.0])] { @@ -406,7 +437,7 @@ mod tests { let mut table = vec![v; 17]; table[0] = 16; let ifd = ifd(vec![(DISTORTION_PARAMS, Value::SLong8(table))]); - assert!(lens_opcodes(&ifd, "ILCE-7RM6", FF_ACTIVE, FF_CROP).is_empty(), "{v}"); + assert!(lens_opcodes(&ifd, "ILCE-7RM6", None, None, FF_ACTIVE, FF_CROP).is_empty(), "{v}"); } // degenerate geometry let ff = tables_with_distortion(&values(&FF_DISTORTION)); @@ -455,7 +486,7 @@ mod tests { let t = read_tables(&ifd); assert!(t.ca.is_some() && t.distortion.is_none()); assert!(warp_opcode(&t, knots(), FF_ACTIVE, FF_CROP, true).is_none()); - assert!(lens_opcodes(&ifd, "ILCE-7RM6", FF_ACTIVE, FF_CROP).is_empty()); + assert!(lens_opcodes(&ifd, "ILCE-7RM6", None, None, FF_ACTIVE, FF_CROP).is_empty()); // an all-zero distortion table counts as absent let zero = LensTables { ca: t.ca, ..tables_with_distortion(&[0.0; 16]) }; assert!(warp_opcode(&zero, knots(), FF_ACTIVE, FF_CROP, true).is_none()); @@ -509,7 +540,7 @@ mod tests { let ifd = sony_lens_ifd(&FF_DISTORTION, &FF_VIGNETTING, &FF_HQ_CA, [1, 2, 1]); let with_ca = warp_opcode(&read_tables(&ifd), knots(), FF_ACTIVE, FF_CROP, true); assert!(matches!(with_ca, Some(Opcode::WarpRectilinear { ref planes, .. }) if planes.len() == 3), "{with_ca:?}"); - let ops = lens_opcodes(&ifd, "ILCE-7RM6", FF_ACTIVE, FF_CROP); + let ops = lens_opcodes(&ifd, "ILCE-7RM6", None, None, FF_ACTIVE, FF_CROP); let [Opcode::WarpRectilinear { planes, .. }] = ops.as_slice() else { panic!("{ops:?}") }; assert_eq!(planes.len(), 1); let green = warp_opcode(&tables_with_distortion(&values(&FF_DISTORTION)), knots(), FF_ACTIVE, FF_CROP, false); @@ -578,12 +609,12 @@ mod tests { let square = Rect { width: A6700_CROP.height, ..A6700_CROP }; assert_eq!(knot_spacing("ILCE-6700", 11, square), None); let ifd = sony_lens_ifd(&A6700_DISTORTION, &APSC_VIGNETTING, &APSC_CA, [1, 2, 1]); - let ops = lens_opcodes(&ifd, "ILCE-6700", A6700_CROP, A6700_CROP); - let gated = gated_warp_opcode(&read_tables(&ifd), s, A6700_CROP, A6700_CROP, false, APSC_FIT_ERROR_PX_AT_1440); + let ops = lens_opcodes(&ifd, "ILCE-6700", None, None, A6700_CROP, A6700_CROP); + let gated = gated_warp_opcode(&read_tables(&ifd), s, DISTORTION_UNIT, A6700_CROP, A6700_CROP, false, APSC_FIT_ERROR_PX_AT_1440); assert_eq!(ops, gated.into_iter().collect::>()); assert_eq!(ops.len(), 1); // other APS-C bodies stay unverified - assert!(lens_opcodes(&ifd, "ILCE-6600", A6700_CROP, A6700_CROP).is_empty()); + assert!(lens_opcodes(&ifd, "ILCE-6600", None, None, A6700_CROP, A6700_CROP).is_empty()); } /// The APS-C fit gate: a table the polynomial fits within 0.44 px is applied on the ILCE-6700, while the @@ -594,17 +625,46 @@ mod tests { let t = read_tables(&ifd); let s = knot_spacing("ILCE-6700", 11, A6700_DECODED_CROP).unwrap(); assert_eq!(warp_opcode(&t, s, A6700_ACTIVE, A6700_DECODED_CROP, false), None); - let ops = lens_opcodes(&ifd, "ILCE-6700", A6700_ACTIVE, A6700_DECODED_CROP); + let ops = lens_opcodes(&ifd, "ILCE-6700", None, None, A6700_ACTIVE, A6700_DECODED_CROP); assert!(matches!(ops.as_slice(), [Opcode::WarpRectilinear { planes, .. }] if planes.len() == 1), "{ops:?}"); } + const SIGMA_10_18: &str = "10-18mm F2.8 DC DN | Contemporary 023"; + + /// The Sigma 10-18 mm exception: its spacing and unit at 10-10.5 mm, the body's rule from 11.7 mm (and without a + /// lens or focal length, on another body or another lens). + #[test] + fn lens_exception_applies_only_to_its_lens_body_and_focal_range() { + let ifd = sony_lens_ifd(&A6700_DISTORTION, &APSC_VIGNETTING, &APSC_CA, [1, 2, 1]); + let t = read_tables(&ifd); + let geometry = (A6700_ACTIVE, A6700_DECODED_CROP); + let exception = gated_warp_opcode(&t, 416.0, 14250.0, geometry.0, geometry.1, false, APSC_FIT_ERROR_PX_AT_1440); + let body = lens_opcodes(&ifd, "ILCE-6700", None, None, geometry.0, geometry.1); + assert!(exception.is_some() && body.len() == 1); + assert_ne!(body.first(), exception.as_ref()); + for focal in [10.0, 10.5] { + let ops = lens_opcodes(&ifd, "ILCE-6700", Some(SIGMA_10_18), Some(focal), geometry.0, geometry.1); + assert_eq!(ops.first(), exception.as_ref(), "{focal} mm"); + } + for (lens, focal) in [(Some(SIGMA_10_18), Some(11.7)), (Some(SIGMA_10_18), None), (None, Some(10.0)), (Some("E 10-20mm F4 PZ G"), Some(10.0))] + { + let ops = lens_opcodes(&ifd, "ILCE-6700", lens, focal, geometry.0, geometry.1); + assert_eq!(ops, body, "{lens:?} {focal:?}"); + } + // hostile focal lengths fall back to the body's rule + for focal in [f64::NAN, f64::INFINITY, -10.0, 0.0] { + assert_eq!(lens_opcodes(&ifd, "ILCE-6700", Some(SIGMA_10_18), Some(focal), geometry.0, geometry.1), body); + } + assert_eq!(lens_exception("ILCE-6600", Some(SIGMA_10_18), Some(10.0)).map(|e| e.unit), None); + } + #[test] fn unknown_model_gets_no_opcodes() { let ifd = sony_lens_ifd(&FF_DISTORTION, &FF_VIGNETTING, &FF_CA, [0, 2, 1]); - assert!(lens_opcodes(&ifd, "ILCE-7M4", FF_ACTIVE, FF_CROP).is_empty()); - assert!(lens_opcodes(&ifd, "", FF_ACTIVE, FF_CROP).is_empty()); + assert!(lens_opcodes(&ifd, "ILCE-7M4", None, None, FF_ACTIVE, FF_CROP).is_empty()); + assert!(lens_opcodes(&ifd, "", None, None, FF_ACTIVE, FF_CROP).is_empty()); // the camera's in-camera flag (0 = off here) doesn't matter: the table is applied - let ops = lens_opcodes(&ifd, " ILCE-7RM6 ", FF_ACTIVE, FF_CROP); + let ops = lens_opcodes(&ifd, " ILCE-7RM6 ", None, None, FF_ACTIVE, FF_CROP); assert_eq!(ops, warp_opcode(&read_tables(&ifd), knots(), FF_ACTIVE, FF_CROP, false).into_iter().collect::>()); assert_eq!(ops.len(), 1); } diff --git a/crates/raw/src/vendor/crw.rs b/crates/raw/src/vendor/crw.rs new file mode 100644 index 0000000000..d48e1f229b --- /dev/null +++ b/crates/raw/src/vendor/crw.rs @@ -0,0 +1,255 @@ +//! Canon CRW (CIFF heap) raw decoding through the shared `craft-crw` crate (craft-libs, +//! `crates/crw`): the bodies before the CR2 era (EOS D30/D60/10D/300D, PowerShot G-series). +//! +//! The decoder, its frozen code tables and its clean-room record live in +//! craft-libs (`crates/crw/clean-room/`: the frozen format `02-crw-format.md`, the verification +//! `03-verification.md`, 28 of 29 corpus files and 1,516 EOS D60 files sample-exact against a +//! black-box reference). This module maps its output onto [`RawImage`]: CFA phase, black and white +//! levels, active area, orientation, as-shot white balance and the make, model and capture-time +//! records (a CRW carries no Exif block, so this is where the catalog learns the camera). +//! +//! Known gaps (documented in the freeze): the PowerShot G5's entropy coding diverges from the +//! model and is refused (its embedded JPEG is shown instead); PowerShot bodies without CC0 samples +//! (G2/G3/Pro1/S-series) decode through the same model unverified. Colour matrices for these +//! bodies are LightCraft's own (`chart_table`, the EOS D60); the file carries none. + +use crate::{BlackLevel, Cfa, ColorData, Metadata, Mode, OpcodeLists, Orientation, RawData, RawError, RawFormat, RawImage, Rect, Result}; +use lightcraft_meta::DateTime; + +fn map_err(e: craft_crw::Error) -> RawError { + match e { + craft_crw::Error::NotCrw => RawError::NotRaw, + craft_crw::Error::Corrupt(why) => RawError::Corrupt(format!("CRW: {why}")), + craft_crw::Error::Unsupported(why) => RawError::Unsupported(format!("CRW: {why}")), + craft_crw::Error::LimitExceeded(what) => RawError::Limit(what), + } +} + +pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { + // the crate's own cap (2²³ samples; the largest CRW frame is 7.4 million): its decode holds + // about three `u16` buffers of the declared size, so the raw crate's general `MAX_SAMPLES` + // (2³⁰) would let a malformed file ask for gigabytes. No sample may be filled after the + // entropy stream ends (the crate allows one 64-sample block by default): every corpus file + // ends exactly on its frame, so a shorter stream is a truncated file and is `Corrupt`. + let mut limits = craft_crw::Limits::default(); + limits.max_stream_end_fill = 0; + let full = mode == Mode::Full; + let (h, samples, black, white) = if full { + let img = craft_crw::decode(bytes, &limits).map_err(map_err)?; + let black = BlackLevel { repeat_rows: 2, repeat_cols: 2, values: img.black.values.to_vec(), delta_h: vec![], delta_v: vec![] }; + (img.header, img.samples, black, img.white) + } else { + let h = craft_crw::header(bytes, &limits).map_err(map_err)?; + let white = ((1u32 << h.bits.clamp(1, 16)) - 1) as f32; + (h, Vec::new(), BlackLevel::uniform(0.0), white) + }; + let active = Rect::new(h.active_area.x, h.active_area.y, h.active_area.width, h.active_area.height); + let orientation = Orientation::from_exif(h.exif_orientation as _); + let metadata = Metadata { + make: h.make, + model: h.model, + capture_time: h.capture_unix.and_then(datetime_from_unix), + width: Some(active.width as u32), + height: Some(active.height as u32), + orientation: Some(orientation), + ..Metadata::default() + }; + let img = RawImage { + format: RawFormat::Crw, + width: h.width, + height: h.height, + cpp: 1, + data: RawData::U16(samples), + cfa: Some(Cfa::bayer_static(h.cfa.name())), + bits: h.bits, + black, + white: vec![white], + active_area: active, + crop: Rect::new(0, 0, active.width, active.height), + orientation, + color: ColorData::default(), + wb_multipliers: h.wb_multipliers, + linearized: false, + pixel_aspect: 1.0, + opcodes: OpcodeLists::default(), + metadata, + lens_metadata: Default::default(), + }; + img.validate_for(mode)?; + Ok(img) +} + +/// Civil date-time from the TimeStamp record's Unix seconds (the camera's local clock, no UTC +/// offset; inverse of [`DateTime::unix_seconds`]). Before 1970 or after 2200 is a garbage clock, +/// not a capture time. +fn datetime_from_unix(t: i64) -> Option { + use chrono::{Datelike, Timelike}; + let c = chrono::DateTime::from_timestamp(t, 0)?.naive_utc(); + let dt = DateTime { + year: u16::try_from(c.year()).ok()?, + month: u8::try_from(c.month()).ok()?, + day: u8::try_from(c.day()).ok()?, + hour: u8::try_from(c.hour()).ok()?, + minute: u8::try_from(c.minute()).ok()?, + second: u8::try_from(c.second()).ok()?, + millis: 0, + offset_minutes: None, + }; + ((1970..=2200).contains(&dt.year)).then_some(dt) +} + +#[cfg(test)] +mod tests { + use super::*; + + const W: usize = 48; + const H: usize = 20; + + /// A CIFF file with the records the decoder reads and a pseudo-random payload: enough for the + /// header path; the entropy data decodes or is refused, never panics. + fn synthetic_crw(model: &str) -> Vec { + synthetic_crw_sized(model, W, H) + } + + fn synthetic_crw_sized(model: &str, w: usize, h: usize) -> Vec { + let payload: Vec = (0..514 + 256).map(|i| (i * 41 % 253) as u8).collect(); + synthetic_crw_with_payload(model, w, h, payload) + } + + fn synthetic_crw_with_payload(model: &str, w: usize, h: usize, payload: Vec) -> Vec { + let le16 = |v: u16| v.to_le_bytes(); + let le32 = |v: u32| v.to_le_bytes(); + let heap = |records: &[(u16, Vec)]| -> Vec { + let mut b = Vec::new(); + let mut entries = Vec::new(); + for (tc, v) in records { + entries.push((*tc, v.len() as u32, b.len() as u32)); + b.extend_from_slice(v); + if b.len() % 2 == 1 { + b.push(0); + } + } + let tbl = b.len() as u32; + b.extend_from_slice(&le16(entries.len() as u16)); + for (tc, l, off) in entries { + b.extend_from_slice(&le16(tc)); + b.extend_from_slice(&le32(l)); + b.extend_from_slice(&le32(off)); + } + b.extend_from_slice(&le32(tbl)); + b + }; + let sensor: Vec = [34u16, w as u16, h as u16, 0, 0, 2, 2, w as u16 - 3, h as u16 - 3].iter().flat_map(|&v| le16(v)).collect(); + let dtable: Vec = [0u32, 0, 514, 0].iter().flat_map(|&v| le32(v)).collect(); + let image_info: Vec = [w as u32, h as u32, 0, 270, 12, 12, 0].iter().flat_map(|&v| le32(v)).collect(); + let mut color_balance: Vec = vec![66]; + color_balance.extend([2000u16, 800, 800, 960]); + color_balance.extend((0..7).flat_map(|_| [1500u16, 900, 900, 1500])); + let color_balance: Vec = color_balance.iter().flat_map(|&v| le16(v)).collect(); + let mut make_model = b"Canon\0".to_vec(); + make_model.extend_from_slice(model.as_bytes()); + make_model.push(0); + let props = heap(&[ + (0x1031, sensor), + (0x1835, dtable), + (0x080a, make_model), + (0x1810, image_info), + (0x180e, [1083410638u32, 0, 0].iter().flat_map(|&v| le32(v)).collect()), + (0x10a9, color_balance), + ]); + let root = heap(&[(0x2005, payload), (0x300a, props)]); + let mut f = b"II".to_vec(); + f.extend_from_slice(&le32(26)); + f.extend_from_slice(b"HEAPCCDR"); + f.extend_from_slice(&le32(0x0001_0002)); + f.extend_from_slice(&[0; 8]); + f.extend_from_slice(&root); + f + } + + #[test] + fn header_mode_maps_the_records_onto_raw_image() { + let f = synthetic_crw("Canon EOS D60"); + let img = decode(&f, Mode::Header).expect("header decodes"); + assert_eq!((img.format, img.width, img.height, img.bits, img.cpp), (RawFormat::Crw, W, H, 10, 1)); + assert_eq!(img.data.len(), 0); + assert_eq!(img.active_area, Rect::new(2, 2, W - 4, H - 4)); + assert_eq!(img.crop, Rect::new(0, 0, W - 4, H - 4)); + assert_eq!(img.cfa.as_ref().map(|c| c.name()).as_deref(), Some("RGGB")); + assert_eq!(img.orientation, Orientation::from_exif(8)); + assert_eq!(img.metadata.make.as_deref(), Some("Canon")); + assert_eq!(img.metadata.model.as_deref(), Some("Canon EOS D60")); + assert_eq!(img.metadata.orientation, Some(Orientation::from_exif(8))); + assert_eq!(img.metadata.capture_time.map(|t| t.unix_seconds()), Some(1083410638)); + let wb = img.wb_multipliers.expect("ColorBalance slot 0"); + assert!((wb[0] - 2.5).abs() < 1e-3 && wb[1] == 1.0 && (wb[2] - 1.2).abs() < 1e-3, "{wb:?}"); + assert_eq!(img.white, vec![1023.0]); + assert_eq!(img.black, BlackLevel::uniform(0.0)); + // the entropy data is pseudo-random: decodes or errors, never panics + let _ = decode(&f, Mode::Full); + let g1 = decode(&synthetic_crw("Canon PowerShot G1"), Mode::Header).expect("header decodes"); + assert_eq!(g1.cfa.as_ref().map(|c| c.name()).as_deref(), Some("GBRG")); + } + + #[test] + fn errors_map_onto_raw_error() { + assert!(matches!(decode(b"II*\0\x08\0\0\0", Mode::Full), Err(RawError::NotRaw))); + assert!(matches!(decode(b"II HEAPCCDR ", Mode::Full), Err(RawError::Corrupt(w)) if w.starts_with("CRW: "))); + let Err(RawError::Unsupported(why)) = decode(&synthetic_crw("Canon PowerShot G5"), Mode::Header) else { panic!("expected Unsupported") }; + assert!(why.contains("PowerShot G5"), "{why}"); + assert_eq!(map_err(craft_crw::Error::LimitExceeded("image too large")), RawError::Limit("image too large")); + } + + /// A file declaring more samples than any CRW camera has is refused before anything is + /// allocated: 4096 × 4096 (16.8 million) passed when the adapter raised the crate's cap of 2²³ + /// to the raw crate's 2³⁰. + #[test] + fn an_oversized_crw_is_refused_by_the_crates_own_limit() { + let f = synthetic_crw_sized("Canon EOS D60", 4096, 4096); + for mode in [Mode::Header, Mode::Full] { + assert_eq!(decode(&f, mode).err(), Some(RawError::Limit("image too large")), "{mode:?}"); + } + // the largest real frame (the 10D's 3152 × 2068) is within it + assert!(decode(&synthetic_crw_sized("Canon EOS D60", 3152, 2068), Mode::Header).is_ok()); + } + + /// A stream cut short is `Corrupt`, not a smeared image: the crate once filled every sample + /// after the entropy stream ended with its predictor value and returned success, so a CRW + /// truncated just past its header rendered and exported as a flat frame. + #[test] + fn a_truncated_entropy_stream_is_corrupt() { + // the 514-byte header and two bytes of entropy: almost all of the 960-sample frame unread + let f = synthetic_crw_with_payload("Canon EOS D60", W, H, vec![0; 516]); + let Err(RawError::Corrupt(why)) = decode(&f, Mode::Full) else { panic!("a truncated stream must be refused") }; + assert!(why.starts_with("CRW: ") && why.contains("before the frame does"), "{why}"); + // the header alone still reads, so the library can list the file and show its preview + assert!(decode(&f, Mode::Header).is_ok()); + } + + /// A stream that ends a few samples short is `Corrupt` too: the crate's default limit fills up + /// to one 64-sample block silently, and no real CRW fills any. + #[test] + fn a_stream_a_few_samples_short_is_corrupt() { + // an all-zero entropy stream of 842 bytes decodes the 960-sample frame exactly + let payload = |len: usize| vec![0u8; 514 + len]; + let whole = synthetic_crw_with_payload("Canon EOS D60", W, H, payload(842)); + assert!(decode(&whole, Mode::Full).is_ok()); + // six bytes fewer leave 10 samples unread, within the crate's default of 64 + let short = synthetic_crw_with_payload("Canon EOS D60", W, H, payload(836)); + let filled = craft_crw::decode(&short, &craft_crw::Limits::default()).map(|i| i.stream_end_fill); + assert_eq!(filled, Ok(10)); + let Err(RawError::Corrupt(why)) = decode(&short, Mode::Full) else { panic!("a stream 10 samples short must be refused") }; + assert!(why.contains("10 samples before the frame does"), "{why}"); + } + + #[test] + fn unix_datetime_inverse_matches_unix_seconds() { + for t in [0i64, 1, 86399, 86400, 951867295, 1083410638, 1600000000, 4102444799] { + let dt = datetime_from_unix(t).expect("in range"); + assert_eq!(dt.unix_seconds(), t, "{t}"); + } + // Before 1970 or after 2200 is a garbage clock, not a capture time. + assert!(datetime_from_unix(-1).is_none()); + assert!(datetime_from_unix(i64::MAX).is_none()); + } +} diff --git a/crates/raw/src/vendor/orf.rs b/crates/raw/src/vendor/orf.rs index 172f83013b..ee1d1f48d2 100644 --- a/crates/raw/src/vendor/orf.rs +++ b/crates/raw/src/vendor/orf.rs @@ -230,6 +230,11 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { (RawData::U16(d), 12) } else if total * 8 >= (n as u64) * 12 && total * 8 < (n as u64) * 13 && chunks.len() == 1 { let src = chunk_bytes(bytes, &chunks[0]).ok_or_else(|| RawError::Corrupt("ORF strip outside file".into()))?; + // the strip as it is in the file (clipped at its end), not as its tag states it: one too short + // for the samples is a truncated file, refused before they are allocated + if (src.len() as u64).saturating_mul(8) < (n as u64).saturating_mul(12) { + return Err(RawError::Corrupt("ORF strip shorter than its samples".into())); + } // the depth is fixed here, so a header-only probe needs the samples only when the file doesn't state its // colour-filter layout let d = if mode == Mode::Full || stated.is_none() { 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/raw/tests/it/corpus.rs b/crates/raw/tests/it/corpus.rs index 85792c79a7..c2d4a80f45 100644 --- a/crates/raw/tests/it/corpus.rs +++ b/crates/raw/tests/it/corpus.rs @@ -17,10 +17,11 @@ fn corpus_root() -> PathBuf { /// Variants known not to decode yet (see the crate docs): matched against the lower-case file name. const KNOWN_UNSUPPORTED: &[&str] = &[ - "cr3-", // Unverified CRX coding variants; exact supported cases live in cr3_corpus.rs. - "orf-olympus-em", // Olympus compressed ORF - "-he.nef", // Nikon High Efficiency (HE / HE★) NEF, issue #193 - "sraw", // Canon sRAW / mRAW + "cr3-", // Unverified CRX coding variants; exact supported cases live in cr3_corpus.rs. + "orf-olympus-em", // Olympus compressed ORF + "-he.nef", // Nikon High Efficiency (HE / HE★) NEF, issue #193 + "sraw", // Canon sRAW / mRAW + "crw-canon-powershot-g5.crw", // Canon PowerShot G5 CRW: entropy coding anomaly (craft-libs crates/crw/clean-room/02-crw-format.md §4) ]; #[test] @@ -1069,8 +1070,8 @@ fn sony_embedded_distortion_is_limited_to_validated_models() { for (name, model, expected) in [ ("arw-sony-a7rm4a-compressed.arw", "ILCE-7RM4A", 1), ("arw-sony-a9m2-compressed.arw", "ILCE-9M2", 0), - ("arw-sony-a7m3-compressed.arw", "ILCE-7M3", 0), - ("arw-sony-a7m3-uncompressed.arw", "ILCE-7M3", 0), + ("arw-sony-a7m3-compressed.arw", "ILCE-7M3", 1), + ("arw-sony-a7m3-uncompressed.arw", "ILCE-7M3", 1), ("arw-sony-a7m4-14bit.arw", "ILCE-7M4", 0), ("arw-sony-a7m4-lossless-l.arw", "ILCE-7M4", 0), ("arw-sony-a7m4-lossless-m.arw", "ILCE-7M4", 0), @@ -1227,7 +1228,7 @@ fn a_sony_fixture_that_differs_from_its_pin_fails() { /// Sony's lens-correction records (`lightcraft_raw::lens_metadata`, `crates/raw/src/vendor/arw_lens.rs`) on the public /// samples: shading, CA and distortion decoded from the raw IFD with their settings, equal to their `SR2SubIFD` copies, -/// the same from header and full decode, and nothing applied beyond the validated ILCE-7RM4A distortion. Expected +/// the same from header and full decode, and nothing applied beyond the validated ILCE-7RM4A and ILCE-7M3 distortion. Expected /// tables and settings: what ExifTool, run as a black-box tool, prints for these files. Every file is checked against /// its pinned SHA-256 before it is decoded; absent files are skipped. #[test] @@ -1351,13 +1352,13 @@ fn sony_lens_records_of_the_public_samples() { eprintln!("{name}: shading, CA and distortion decoded; distortion {status:?}"); checked += 1; } - // every Sony corpus file: only the ILCE-7RM4A's distortion is ever applied, and an applied status is an opcode + // every Sony corpus file: only the ILCE-7RM4A's and ILCE-7M3's distortion is ever applied, and an applied status is an opcode for (name, _) in SONY_SAMPLES { let Some(bytes) = pinned_sony(&root, name) else { continue }; let info = probe_info(&bytes).unwrap_or_else(|e| panic!("{name}: {e}")); let Some(s) = &info.lens_metadata.sony else { continue }; let applied = s.distortion.status == SonyLensStatus::Applied; - assert_eq!(applied, info.metadata.model.as_deref() == Some("ILCE-7RM4A"), "{name}"); + assert_eq!(applied, matches!(info.metadata.model.as_deref(), Some("ILCE-7RM4A" | "ILCE-7M3")), "{name}"); assert_eq!(info.opcodes.list3.len(), usize::from(applied), "{name}"); assert!(![s.shading.status, s.chromatic_aberration.status].contains(&SonyLensStatus::Applied), "{name}"); checked += 1; diff --git a/crates/raw/tests/it/crw_corpus.rs b/crates/raw/tests/it/crw_corpus.rs new file mode 100644 index 0000000000..9de297a71e --- /dev/null +++ b/crates/raw/tests/it/crw_corpus.rs @@ -0,0 +1,71 @@ +//! Canon CRW through the shared craft-crw decoder, on the CC0 corpus files (URLs and SHA-256 in +//! `xtask/src/raw_samples.rs`; downloaded into the gitignored corpus/raw by `cargo xtask corpus --download`). +//! +//! The FNV-1a hashes over the decoded u16 samples (row-major, little-endian, masked borders +//! included) were computed from LightCraft's earlier in-tree clean-room CRW decoder (commit +//! dd02f12f, branch `clean-room-crw-format-decode`) before it moved to craft-libs: the shared +//! decoder reproduces it bit for bit on all ten files, six bodies. Black and white levels are not +//! pinned: craft-crw changed both on purpose (border padding no longer lowers the black level; the +//! white level follows these bodies' low-ISO clip near 4000), so they are only checked for sanity. + +use lightcraft_raw::{RawData, RawError, decode}; +use std::path::{Path, PathBuf}; + +fn corpus() -> PathBuf { + std::env::var_os("LIGHTCRAFT_CORPUS").map(PathBuf::from).unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus")) +} + +fn fnv1a(samples: &[u16]) -> u64 { + samples.iter().flat_map(|v| v.to_le_bytes()).fold(0xcbf2_9ce4_8422_2325u64, |h, byte| (h ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3)) +} + +/// (file, sensor width × height, FNV-1a of the samples from the earlier in-tree decoder) +const CASES: &[(&str, (usize, usize), u64)] = &[ + ("crw-canon-eos-10d-a.crw", (3152, 2068), 0xb8a6_7781_fa37_b1df), + ("crw-canon-eos-10d-b.crw", (3152, 2068), 0xeeea_3c68_2fb5_62ae), + ("crw-canon-eos-10d-c.crw", (3152, 2068), 0x060d_d320_55aa_d79e), + ("crw-canon-eos-300d-a.crw", (3152, 2068), 0xa9a0_5cc0_ca19_01bd), + ("crw-canon-eos-300d-b.crw", (3152, 2068), 0xf0c3_98e8_be78_58cc), + ("crw-canon-eos-d30.crw", (2224, 1456), 0x1394_ca5c_1cb8_816d), + ("crw-canon-eos-d60.crw", (3152, 2068), 0x63e2_4897_3fe4_1cef), + ("crw-canon-eos-digital-rebel.crw", (3152, 2068), 0x0db1_b751_a769_aa32), + ("crw-canon-powershot-g1.crw", (2144, 1560), 0x29e5_4008_46b7_a54b), + ("crw-canon-powershot-g6.crw", (3160, 2344), 0xa7fa_be95_3036_5b64), +]; + +#[test] +fn crw_samples_match_the_earlier_in_tree_decoder() { + let mut seen = 0; + for &(name, sensor, hash) in CASES { + let path = corpus().join("raw").join(name); + let Ok(bytes) = std::fs::read(&path) else { continue }; + let raw = decode(&bytes).unwrap_or_else(|e| panic!("{name}: {e}")); + raw.validate().unwrap(); + assert_eq!((raw.width, raw.height, raw.cpp), (sensor.0, sensor.1, 1), "{name}: sensor size"); + let RawData::U16(samples) = &raw.data else { panic!("{name}: integer sensor data expected") }; + assert_eq!(fnv1a(samples), hash, "{name}: sensor samples differ from the earlier decoder"); + assert!(raw.white_at(0) > raw.black.mean() && raw.black.mean() > 0.0, "{name}: invalid black/white levels"); + seen += 1; + } + if seen == 0 { + lightcraft_testkit::skip!(Corpus, "no CRW files in {}", corpus().join("raw").display()); + } +} + +/// A real CRW damaged two ways is an error, never a panic or a silently smeared frame. +#[test] +fn a_damaged_real_crw_is_an_error() { + let path = corpus().join("raw").join("crw-canon-eos-d60.crw"); + let Ok(bytes) = std::fs::read(&path) else { + lightcraft_testkit::skip!(Corpus, "{} absent", path.display()); + return; + }; + // cut in half: the CIFF heap's record table sits at the end, so the file no longer parses + let cut = &bytes[..bytes.len() / 2]; + assert!(matches!(decode(cut), Err(RawError::Corrupt(_) | RawError::NotRaw)), "{:?}", decode(cut).err()); + // the length kept but a run of the sensor data overwritten with an invalid code + let mut garbled = bytes.clone(); + let mid = garbled.len() / 2; + garbled[mid..mid + 4096].fill(0xff); + assert!(matches!(decode(&garbled), Err(RawError::Corrupt(_))), "{:?}", decode(&garbled).err()); +} diff --git a/crates/raw/tests/it/main.rs b/crates/raw/tests/it/main.rs index 8834ed0f0c..88840b2cae 100644 --- a/crates/raw/tests/it/main.rs +++ b/crates/raw/tests/it/main.rs @@ -7,6 +7,7 @@ mod corpus; mod coverage_sweep_corpus; mod cr3_corpus; mod cr3_variants; +mod crw_corpus; mod crx_properties; mod dng; mod lossy_dng; diff --git a/crates/raw/tests/it/vendor_robust.rs b/crates/raw/tests/it/vendor_robust.rs index cb79c87da9..446c1fb60a 100644 --- a/crates/raw/tests/it/vendor_robust.rs +++ b/crates/raw/tests/it/vendor_robust.rs @@ -1,4 +1,4 @@ -//! Malformed vendor raw files (NEF, ARW, PEF, ORF, RW2 of every raw format, CR2, RAF) must decode to an error, never panic. +//! Malformed vendor raw files (NEF, ARW, PEF, ORF, RW2 of every raw format, CR2, RAF, CRW) must decode to an error, never panic. use lightcraft_tiff::tags as t; use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; @@ -226,8 +226,48 @@ fn raf() -> Vec { raf_file(W, H, 16, strip, Some(layout), b"\xff\xd8\xff\xd9") } +/// A Canon CRW: CIFF header, a raw-data payload of pseudo-random bytes, and a nested properties +/// heap with the records the decoder reads. +fn crw() -> Vec { + let le16 = |v: u16| v.to_le_bytes(); + let le32 = |v: u32| v.to_le_bytes(); + let heap = |records: &[(u16, Vec)]| -> Vec { + let mut b = Vec::new(); + let mut entries = Vec::new(); + for (tc, v) in records { + entries.push((*tc, v.len() as u32, b.len() as u32)); + b.extend_from_slice(v); + if b.len() % 2 == 1 { + b.push(0); + } + } + let tbl = b.len() as u32; + b.extend_from_slice(&le16(entries.len() as u16)); + for (tc, l, off) in entries { + b.extend_from_slice(&le16(tc)); + b.extend_from_slice(&le32(l)); + b.extend_from_slice(&le32(off)); + } + b.extend_from_slice(&le32(tbl)); + b + }; + let sensor: Vec = [34u16, W as u16, H as u16, 0, 0, 2, 2, W as u16 - 3, H as u16 - 3].iter().flat_map(|&v| le16(v)).collect(); + let dtable: Vec = [0u32, 0, 514, 0].iter().flat_map(|&v| le32(v)).collect(); + let props = heap(&[(0x1031, sensor), (0x1835, dtable), (0x080a, b"Canon\0Canon EOS D60\0".to_vec())]); + let payload: Vec = (0..514 + 256).map(|i| (i * 41 % 253) as u8).collect(); + let root = heap(&[(0x2005, payload), (0x300a, props)]); + let mut f = b"II".to_vec(); + f.extend_from_slice(&le32(26)); + f.extend_from_slice(b"HEAPCCDR"); + f.extend_from_slice(&le32(0x0001_0002)); + f.extend_from_slice(&[0; 8]); + f.extend_from_slice(&root); + f +} + fn samples() -> Vec> { vec![ + crw(), cfa_tiff("NIKON CORPORATION", 1, 12, ByteOrder::Big), cfa_tiff("NIKON CORPORATION", 34713, 14, ByteOrder::Big), cfa_tiff("SONY", 32767, 12, ByteOrder::Little), @@ -283,7 +323,7 @@ proptest! { #![proptest_config(ProptestConfig { cases: 2000, .. ProptestConfig::default() })] #[test] - fn mutated_vendor_files_never_panic(kind in 0usize..18, flips in proptest::collection::vec((any::(), any::()), 1..16), cut in any::()) { + fn mutated_vendor_files_never_panic(kind in 0usize..19, flips in proptest::collection::vec((any::(), any::()), 1..16), cut in any::()) { let mut data = samples().swap_remove(kind); let n = data.len(); for (i, v) in flips { diff --git a/crates/segment/src/mask.rs b/crates/segment/src/mask.rs index af349a2625..d884659aab 100644 --- a/crates/segment/src/mask.rs +++ b/crates/segment/src/mask.rs @@ -34,6 +34,31 @@ pub fn preprocess(rgb: &[u8], w: usize, h: usize, side: usize) -> Result w.saturating_mul(4) { + let mut t = vec![0u8; n]; + for y in 0..h { + for x in 0..w { + if let (Some(d), Some(s)) = (t.get_mut((x * h + y) * 3..(x * h + y) * 3 + 3), rgb.get((y * w + x) * 3..(y * w + x) * 3 + 3)) { + d.copy_from_slice(s); + } + } + } + let o = preprocess(&t, h, w, side)?; + let mut out = vec![0f32; o.len()]; + for c in 0..3 { + for oy in 0..side { + for ox in 0..side { + if let (Some(d), Some(v)) = (out.get_mut((c * side + oy) * side + ox), o.get((c * side + ox) * side + oy)) { + *d = *v; + } + } + } + } + return Ok(out); + } let (wx, wy) = (weights(w, side), weights(h, side)); // horizontal pass: h rows × side columns × 3 let mut tmp = vec![0f32; h * side * 3]; @@ -117,6 +142,19 @@ mod tests { #[test] fn short_buffers_are_errors() { assert!(preprocess(&[0; 5], 2, 2, 4).is_err()); + // a strip 1 pixel wide and 200 000 tall: resampled transposed, so the intermediate is + // side × 1 rather than 200 000 × side; it equals the resample of its transposed twin + let h = 200_000usize; + let strip: Vec = (0..h * 3).map(|i| (i / 3 % 251) as u8).collect(); + let a = preprocess(&strip, 1, h, 8).unwrap(); + let b = preprocess(&strip, h, 1, 8).unwrap(); + for c in 0..3 { + for y in 0..8 { + for x in 0..8 { + assert_eq!(a[(c * 8 + y) * 8 + x], b[(c * 8 + x) * 8 + y]); + } + } + } assert!(preprocess(&[], 0, 0, 4).is_err()); } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 8e7b77f42f..83a18de446 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -24,6 +24,7 @@ lightcraft-engine = { workspace = true } lightcraft-slideshow = { workspace = true } lightcraft-preview = { workspace = true } egui = { workspace = true } +egui_extras = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } log = { workspace = true } @@ -41,6 +42,8 @@ lightcraft-denoise = { workspace = true, features = ["runtime"] } lightcraft-codecs = { workspace = true } lightcraft-faces = { workspace = true } lightcraft-merge = { workspace = true } +# a device for the GPU-resident view test (`render.rs`) +pollster = { workspace = true } [build-dependencies] serde_json = { workspace = true } diff --git a/crates/ui-egui/examples/thumb_request_bench.rs b/crates/ui-egui/examples/thumb_request_bench.rs index 34fe5fc883..ada42356de 100644 --- a/crates/ui-egui/examples/thumb_request_bench.rs +++ b/crates/ui-egui/examples/thumb_request_bench.rs @@ -113,7 +113,18 @@ fn micro(points: usize, pending: bool) { let key = app.session.thumb_job(id, 384).unwrap().key; app.renderer.textures.insert( Slot::Thumb(id), - Tex { look: None, key, photo: id, tex: texture.clone(), size: [1, 1], histogram: None, ms: 0.0, quick: None, pixels: None }, + Tex { + look: None, + key, + photo: id, + tex: texture.clone(), + size: [1, 1], + histogram: None, + ms: 0.0, + quick: None, + pixels: None, + native: None, + }, ); } request_thumb(&mut app, id, 384, 10); @@ -157,7 +168,7 @@ fn verify_texture(h: &Headless, id: PhotoId) { let edge = tex.size[0].max(tex.size[1]); assert!([128, 256, 384, 512].contains(&edge), "thumbnail must use a supported size bucket"); let Source::File { path } = &p.source else { unreachable!() }; - let (source, info) = h.app.session.media.file_loader.as_ref().unwrap()(path, 512).unwrap(); + let (source, info) = h.app.session.media.file_loader.as_ref().unwrap()(path, 512, None).unwrap(); println!("decode,path={path},raw={},preview_only={:?}", info.raw, p.preview_only); if std::env::var_os("REQUIRE_RAW").is_some() { assert!(p.preview_only.is_none(), "embedded-preview fallback does not validate RAW decoding"); diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index e0ec9f1baa..e65ad627ef 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -313,6 +313,9 @@ "Added {n} photo{}": "Přidáno fotografií: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Kam má jít katalog Lightroomu „{catalog}“?", "Merge into the open library “{library}” ({count} photo{})": "Sloučit s otevřenou knihovnou „{library}“ (fotografie: {count}{:.0})", + "Profile: {} (lens database)": "Profil: {} (databáze objektivů)", + "No lens profile found for {}.": "Pro {} nebyl nalezen profil objektivu.", + "{n} photos got their lens profile": "Profil objektivu získaly fotky: {n}", "Photo: {name}": "Fotografie: {name}", "Panel layout could not be restored: {error}": "Rozložení panelů se nepodařilo obnovit: {error}", "Panel move was not applied: {error}": "Přesun panelu nebyl použit: {error}", diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 6a056bbfb9..0b142df5e6 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2428,6 +2428,25 @@ "The photos are imported once it ends": "Fotky se naimportují potom", "An import is running. Drop photos when it has finished": "Import už běží. Fotky přetáhněte, až skončí", "Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky", + "Profile: from the file (the camera's own correction)": "Profil: ze souboru (vlastní korekce fotoaparátu)", + "Downloading the lens database…": "Stahuje se databáze objektivů…", + "This file names no lens.": "Tento soubor neuvádí žádný objektiv.", + "1 photo got its lens profile": "1 fotka získala profil objektivu", + "Looking up lens profiles": "Hledání profilů objektivů", + "Downloading the lens database": "Stahování databáze objektivů", + "The lens database could not be downloaded. LightCraft tries again the next time it starts.": "Databázi objektivů se nepodařilo stáhnout. LightCraft to zkusí znovu při příštím spuštění.", + "Lens Profiles": "Profily objektivů", + "Download lens profiles?": "Stáhnout profily objektivů?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft umí opravit zkreslení a vinětaci mnoha objektivů pomocí otevřené databáze objektivů (lensfun, asi {size} MB).", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "Nic se nestáhne, dokud nezvolíte Stáhnout. Později ji můžete stáhnout v Nastavení.", + "Lens profiles": "Profily objektivů", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "Profily objektivů se čtou ze složky, kterou určuje LIGHTCRAFT_LENSFUN_DIR.", + "The lens database is installed.": "Databáze objektivů je nainstalována.", + "The lens database is not installed (about {size} MB).": "Databáze objektivů není nainstalována (asi {size} MB).", + "Lens database": "Databáze objektivů", + "Download Lens Database": "Stáhnout databázi objektivů", + "Offer the lens database download when LightCraft starts": "Nabídnout stažení databáze objektivů při spuštění LightCraftu", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "Otevřená databáze objektivů lensfun (CC BY-SA 3.0) opravuje zkreslení a vinětaci mnoha objektivů. Stáhne se jen, když to zvolíte.", "Import Thumbnail Size": "Velikost miniatur při importu", "Face recognition is on": "Rozpoznávání obličejů je zapnuto", "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "Rozpoznávání obličejů je vypnuto. Zapněte je, abyste dostávali návrhy jmen a viděli podobné obličeje pohromadě.", diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 782886be84..70ced17114 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -313,6 +313,9 @@ "Added {n} photo{}": "{n} Foto{} hinzugefügt", "Where should the Lightroom catalog “{catalog}” go?": "Wohin soll der Lightroom-Katalog „{catalog}“?", "Merge into the open library “{library}” ({count} photo{})": "Mit der geöffneten Bibliothek „{library}“ zusammenführen ({count} Foto{})", + "Profile: {} (lens database)": "Profil: {} (Objektivdatenbank)", + "No lens profile found for {}.": "Kein Objektivprofil für {} gefunden.", + "{n} photos got their lens profile": "{n} Fotos haben ihr Objektivprofil erhalten", "Photo: {name}": "Foto: {name}", "Panel layout could not be restored: {error}": "Die Bereichsanordnung konnte nicht wiederhergestellt werden: {error}", "Panel move was not applied: {error}": "Das Verschieben des Bereichs wurde nicht ausgeführt: {error}", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 405c54a464..552ce68016 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3459,6 +3459,25 @@ "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", + "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.", + "1 photo got its lens profile": "1 Foto hat sein Objektivprofil erhalten", + "Looking up lens profiles": "Objektivprofile werden gesucht", + "Downloading the lens database": "Objektivdatenbank wird geladen", + "The lens database could not be downloaded. LightCraft tries again the next time it starts.": "Die Objektivdatenbank konnte nicht geladen werden. LightCraft versucht es beim nächsten Start erneut.", + "Lens Profiles": "Objektivprofile", + "Download lens profiles?": "Objektivprofile laden?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft kann Verzeichnung und Vignettierung für viele Objektive mit der offenen Objektivdatenbank korrigieren (lensfun, etwa {size} MB).", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "Nichts wird geladen, bevor Sie „Laden“ wählen. Sie können sie später in den Einstellungen laden.", + "Lens profiles": "Objektivprofile", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "Objektivprofile werden aus dem Ordner gelesen, den LIGHTCRAFT_LENSFUN_DIR nennt.", + "The lens database is installed.": "Die Objektivdatenbank ist installiert.", + "The lens database is not installed (about {size} MB).": "Die Objektivdatenbank ist nicht installiert (etwa {size} MB).", + "Lens database": "Objektivdatenbank", + "Download Lens Database": "Objektivdatenbank laden", + "Offer the lens database download when LightCraft starts": "Beim Start von LightCraft anbieten, die Objektivdatenbank zu laden", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "Die offene Objektivdatenbank von lensfun (CC BY-SA 3.0) korrigiert Verzeichnung und Vignettierung für viele Objektive. Sie wird nur geladen, wenn Sie es wählen.", "Import Thumbnail Size": "Vorschaubildgröße beim Import", "Face recognition is on": "Gesichtserkennung ist eingeschaltet", "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "Gesichtserkennung ist ausgeschaltet. Schalte sie ein, um Namensvorschläge zu erhalten und ähnliche Gesichter zusammen zu sehen.", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 41ae09d66e..7b697e946b 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -313,6 +313,9 @@ "Added {n} photo{}": "{n} foto{0} añadida{0}", "Where should the Lightroom catalog “{catalog}” go?": "¿Dónde debe ir el catálogo de Lightroom “{catalog}”?", "Merge into the open library “{library}” ({count} photo{})": "Combinar con la biblioteca abierta “{library}” ({count} foto{})", + "Profile: {} (lens database)": "Perfil: {} (base de datos de objetivos)", + "No lens profile found for {}.": "No se encontró un perfil de objetivo para {}.", + "{n} photos got their lens profile": "{n} fotos recibieron su perfil de objetivo", "Photo: {name}": "Foto: {name}", "Panel layout could not be restored: {error}": "No se pudo restablecer la disposición de paneles: {error}", "Panel move was not applied: {error}": "No se aplicó el movimiento del panel: {error}", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index e43ae8c49b..b82a261256 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2378,6 +2378,25 @@ "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", + "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.", + "1 photo got its lens profile": "1 foto recibió su perfil de objetivo", + "Looking up lens profiles": "Buscando perfiles de objetivo", + "Downloading the lens database": "Descargando la base de datos de objetivos", + "The lens database could not be downloaded. LightCraft tries again the next time it starts.": "No se pudo descargar la base de datos de objetivos. LightCraft lo intentará de nuevo la próxima vez que se inicie.", + "Lens Profiles": "Perfiles de objetivo", + "Download lens profiles?": "¿Descargar perfiles de objetivo?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft puede corregir la distorsión y el viñeteado de muchos objetivos con la base de datos abierta de objetivos (lensfun, unos {size} MB).", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "No se descarga nada hasta que elija Descargar. Puede descargarla más tarde desde Ajustes.", + "Lens profiles": "Perfiles de objetivo", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "Los perfiles de objetivo se leen de la carpeta que indica LIGHTCRAFT_LENSFUN_DIR.", + "The lens database is installed.": "La base de datos de objetivos está instalada.", + "The lens database is not installed (about {size} MB).": "La base de datos de objetivos no está instalada (unos {size} MB).", + "Lens database": "Base de datos de objetivos", + "Download Lens Database": "Descargar base de datos de objetivos", + "Offer the lens database download when LightCraft starts": "Ofrecer la descarga de la base de datos de objetivos al iniciar LightCraft", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "La base de datos abierta de objetivos de lensfun (CC BY-SA 3.0) corrige la distorsión y el viñeteado de muchos objetivos. Solo se descarga si usted lo elige.", "Thumbnail size": "Tamaño de las miniaturas", "Import Thumbnail Size": "Tamaño de las miniaturas de importación", "Face recognition is on": "El reconocimiento facial está activado", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index ff7e03c066..df80342abe 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2346,6 +2346,18 @@ "Dropped Files": "Pudotetut tiedostot", "Finish Lightroom catalog import before adding photos": "Viimeistele Lightroom-luettelon tuonti ennen kuvien lisäämistä", "Import dropped files without review": "Tuo pudotetut tiedostot ilman tarkistusta", + "Lens Profiles": "Objektiiviprofiilit", + "Download lens profiles?": "Ladataanko objektiiviprofiilit?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft voi korjata monien objektiivien vääristymän ja vinjetoinnin avoimen objektiivitietokannan avulla (lensfun, noin {size} Mt).", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "Mitään ei ladata, ennen kuin valitset Lataa. Voit ladata sen myöhemmin asetuksista.", + "Lens profiles": "Objektiiviprofiilit", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "Objektiiviprofiilit luetaan kansiosta, jonka LIGHTCRAFT_LENSFUN_DIR nimeää.", + "The lens database is installed.": "Objektiivitietokanta on asennettu.", + "The lens database is not installed (about {size} MB).": "Objektiivitietokantaa ei ole asennettu (noin {size} Mt).", + "Lens database": "Objektiivitietokanta", + "Download Lens Database": "Lataa objektiivitietokanta", + "Offer the lens database download when LightCraft starts": "Tarjoa objektiivitietokannan latausta, kun LightCraft käynnistyy", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "lensfunin avoin objektiivitietokanta (CC BY-SA 3.0) korjaa monien objektiivien vääristymän ja vinjetoinnin. Se ladataan vain, jos valitset niin.", "Import Thumbnail Size": "Tuonnin pienoiskuvien koko", "Face recognition is on": "Kasvojentunnistus on päällä", "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "Kasvojentunnistus on pois päältä. Ota se käyttöön, niin saat nimiehdotuksia ja näet samannäköiset kasvot yhdessä.", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index fc46d653c6..3aa2166971 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -313,6 +313,9 @@ "Added {n} photo{}": "{n} photo{} ajoutée(s)", "Where should the Lightroom catalog “{catalog}” go?": "Où importer le catalogue Lightroom « {catalog} » ?", "Merge into the open library “{library}” ({count} photo{})": "Fusionner avec la bibliothèque ouverte « {library} » ({count} photo{})", + "Profile: {} (lens database)": "Profil : {} (base de données d'objectifs)", + "No lens profile found for {}.": "Aucun profil d'objectif trouvé pour {}.", + "{n} photos got their lens profile": "{n} photos ont reçu leur profil d'objectif", "Photo: {name}": "Photo : {name}", "Panel layout could not be restored: {error}": "La disposition des panneaux n'a pas pu être restaurée : {error}", "Panel move was not applied: {error}": "Le déplacement du panneau n'a pas été appliqué : {error}", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index e032cf52f3..e513e217de 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -2409,6 +2409,25 @@ "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 :", + "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.", + "1 photo got its lens profile": "1 photo a reçu son profil d'objectif", + "Looking up lens profiles": "Recherche des profils d'objectif", + "Downloading the lens database": "Téléchargement de la base de données d'objectifs", + "The lens database could not be downloaded. LightCraft tries again the next time it starts.": "La base de données d’objectifs n’a pas pu être téléchargée. LightCraft réessaiera au prochain démarrage.", + "Lens Profiles": "Profils d’objectif", + "Download lens profiles?": "Télécharger les profils d’objectif ?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft peut corriger la distorsion et le vignetage de nombreux objectifs grâce à la base d’objectifs ouverte (lensfun, environ {size} Mo).", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "Rien n’est téléchargé tant que vous ne choisissez pas Télécharger. Vous pourrez la télécharger plus tard dans les Réglages.", + "Lens profiles": "Profils d’objectif", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "Les profils d’objectif sont lus dans le dossier indiqué par LIGHTCRAFT_LENSFUN_DIR.", + "The lens database is installed.": "La base d’objectifs est installée.", + "The lens database is not installed (about {size} MB).": "La base d’objectifs n’est pas installée (environ {size} Mo).", + "Lens database": "Base d’objectifs", + "Download Lens Database": "Télécharger la base d’objectifs", + "Offer the lens database download when LightCraft starts": "Proposer le téléchargement de la base d’objectifs au démarrage de LightCraft", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "La base d’objectifs ouverte de lensfun (CC BY-SA 3.0) corrige la distorsion et le vignetage de nombreux objectifs. Elle n’est téléchargée que si vous le choisissez.", "Face recognition is on": "La reconnaissance des visages est activée", "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "La reconnaissance des visages est désactivée. Activez-la pour obtenir des suggestions de noms et voir ensemble les visages qui se ressemblent.", "Turn on": "Activer", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 1c70f26344..7f5e56e1ce 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2359,6 +2359,18 @@ "Dropped Files": "File yang dijatuhkan", "Finish Lightroom catalog import before adding photos": "Selesaikan impor katalog Lightroom sebelum menambahkan foto", "Import dropped files without review": "Impor file yang dijatuhkan tanpa tinjauan", + "Lens Profiles": "Profil lensa", + "Download lens profiles?": "Unduh profil lensa?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft dapat mengoreksi distorsi dan vinyet untuk banyak lensa menggunakan basis data lensa terbuka (lensfun, sekitar {size} MB).", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "Tidak ada yang diunduh sampai Anda memilih Unduh. Anda dapat mengunduhnya nanti dari Pengaturan.", + "Lens profiles": "Profil lensa", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "Profil lensa dibaca dari folder yang disebut LIGHTCRAFT_LENSFUN_DIR.", + "The lens database is installed.": "Basis data lensa sudah terpasang.", + "The lens database is not installed (about {size} MB).": "Basis data lensa belum terpasang (sekitar {size} MB).", + "Lens database": "Basis data lensa", + "Download Lens Database": "Unduh Basis Data Lensa", + "Offer the lens database download when LightCraft starts": "Tawarkan unduhan basis data lensa saat LightCraft dimulai", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "Basis data lensa terbuka lensfun (CC BY-SA 3.0) mengoreksi distorsi dan vinyet untuk banyak lensa. Basis data ini hanya diunduh jika Anda memilihnya.", "Thumbnail size": "Ukuran gambar mini", "Import Thumbnail Size": "Ukuran Gambar Mini Impor", "Face recognition is on": "Pengenalan wajah aktif", diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 4437aa644d..729c27a0f1 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -313,6 +313,9 @@ "Added {n} photo{}": "Foto aggiunte: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Dove importare il catalogo Lightroom “{catalog}”?", "Merge into the open library “{library}” ({count} photo{})": "Unisci alla libreria aperta “{library}” (foto: {count}{:.0})", + "Profile: {} (lens database)": "Profilo: {} (database degli obiettivi)", + "No lens profile found for {}.": "Nessun profilo obiettivo trovato per {}.", + "{n} photos got their lens profile": "{n} foto hanno ricevuto il profilo dell'obiettivo", "Photo: {name}": "Foto: {name}", "Panel layout could not be restored: {error}": "Non è stato possibile ripristinare la disposizione dei pannelli: {error}", "Panel move was not applied: {error}": "Lo spostamento del pannello non è stato applicato: {error}", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index a0d39d0610..c77a85b41f 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2422,6 +2422,25 @@ "The photos are imported once it ends": "Le foto verranno importate dopo", "An import is running. Drop photos when it has finished": "Un'importazione è in corso. Trascina le foto quando è finita", "Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto", + "Profile: from the file (the camera's own correction)": "Profilo: dal file (correzione della fotocamera)", + "Downloading the lens database…": "Download del database degli obiettivi…", + "This file names no lens.": "Questo file non indica alcun obiettivo.", + "1 photo got its lens profile": "1 foto ha ricevuto il profilo dell'obiettivo", + "Looking up lens profiles": "Ricerca dei profili degli obiettivi", + "Downloading the lens database": "Download del database degli obiettivi", + "The lens database could not be downloaded. LightCraft tries again the next time it starts.": "Impossibile scaricare il database degli obiettivi. LightCraft riproverà al prossimo avvio.", + "Lens Profiles": "Profili obiettivo", + "Download lens profiles?": "Scaricare i profili degli obiettivi?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft può correggere distorsione e vignettatura per molti obiettivi usando il database aperto degli obiettivi (lensfun, circa {size} MB).", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "Non viene scaricato nulla finché non scegli Scarica. Puoi scaricarlo più tardi dalle Impostazioni.", + "Lens profiles": "Profili obiettivo", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "I profili obiettivo vengono letti dalla cartella indicata da LIGHTCRAFT_LENSFUN_DIR.", + "The lens database is installed.": "Il database degli obiettivi è installato.", + "The lens database is not installed (about {size} MB).": "Il database degli obiettivi non è installato (circa {size} MB).", + "Lens database": "Database obiettivi", + "Download Lens Database": "Scarica database obiettivi", + "Offer the lens database download when LightCraft starts": "Offri il download del database obiettivi all’avvio di LightCraft", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "Il database aperto degli obiettivi di lensfun (CC BY-SA 3.0) corregge distorsione e vignettatura per molti obiettivi. Viene scaricato solo se lo scegli.", "A slide stays up for its duration, its fade in included. A fade of 0 cuts.": "Una diapositiva resta visibile per la sua durata, dissolvenza d'ingresso compresa. Con una dissolvenza di 0 il passaggio è netto.", "Add a cell": "Aggiungi una cella", "cells": "celle", diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 2fb625ff6a..b25ef53978 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -313,6 +313,9 @@ "Added {n} photo{}": "{n}枚を追加しました{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Lightroom カタログ「{catalog}」をどこに読み込みますか?", "Merge into the open library “{library}” ({count} photo{})": "開いているライブラリ「{library}」に統合(写真{count}枚){:.0}", + "Profile: {} (lens database)": "プロファイル: {}(レンズデータベース)", + "No lens profile found for {}.": "{} のレンズプロファイルが見つかりません。", + "{n} photos got their lens profile": "{n} 枚の写真にレンズプロファイルが適用されました", "Photo: {name}": "写真: {name}", "Panel layout could not be restored: {error}": "パネル配置を復元できませんでした:{error}", "Panel move was not applied: {error}": "パネルの移動は適用されませんでした:{error}", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 5f80d7896b..72ed66ad20 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2376,6 +2376,25 @@ "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 カタログの読み込みを完了してください", + "Profile: from the file (the camera's own correction)": "プロファイル: ファイル内(カメラ自身の補正)", + "Downloading the lens database…": "レンズデータベースをダウンロード中…", + "This file names no lens.": "このファイルにはレンズ名がありません。", + "1 photo got its lens profile": "1 枚の写真にレンズプロファイルが適用されました", + "Looking up lens profiles": "レンズプロファイルを検索中", + "Downloading the lens database": "レンズデータベースをダウンロード中", + "The lens database could not be downloaded. LightCraft tries again the next time it starts.": "レンズデータベースをダウンロードできませんでした。LightCraft は次回の起動時に再試行します。", + "Lens Profiles": "レンズプロファイル", + "Download lens profiles?": "レンズプロファイルをダウンロードしますか?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft はオープンなレンズデータベース(lensfun、約 {size} MB)を使って、多くのレンズの歪曲収差と周辺減光を補正できます。", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "「ダウンロード」を選ぶまで何もダウンロードしません。あとで設定からダウンロードすることもできます。", + "Lens profiles": "レンズプロファイル", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "レンズプロファイルは LIGHTCRAFT_LENSFUN_DIR が指定するフォルダーから読み込まれます。", + "The lens database is installed.": "レンズデータベースはインストール済みです。", + "The lens database is not installed (about {size} MB).": "レンズデータベースはインストールされていません(約 {size} MB)。", + "Lens database": "レンズデータベース", + "Download Lens Database": "レンズデータベースをダウンロード", + "Offer the lens database download when LightCraft starts": "LightCraft の起動時にレンズデータベースのダウンロードを提案する", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "lensfun のオープンなレンズデータベース(CC BY-SA 3.0)は多くのレンズの歪曲収差と周辺減光を補正します。選んだときにだけダウンロードされます。", "Thumbnail size": "サムネイルのサイズ", "Import Thumbnail Size": "読み込みサムネイルのサイズ", "Face recognition is on": "顔認識をオンにしました", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 329662ac1b..612178c0e8 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -316,6 +316,9 @@ "Added {n} photo{}": "დაემატა ფოტო: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "სად გადავიტანოთ Lightroom-ის კატალოგი „{catalog}“?", "Merge into the open library “{library}” ({count} photo{})": "გაერთიანება ღია ბიბლიოთეკასთან „{library}“ (ფოტოები: {count}){:.0}", + "Profile: {} (lens database)": "პროფილი: {} (ობიექტივების ბაზა)", + "No lens profile found for {}.": "{}-ისთვის ობიექტივის პროფილი ვერ მოიძებნა.", + "{n} photos got their lens profile": "ობიექტივის პროფილი მიიღო {n} ფოტომ", "Photo: {name}": "ფოტო: {name}", "Panel layout could not be restored: {error}": "პანელების განლაგების აღდგენა ვერ მოხერხდა: {error}", "Panel move was not applied: {error}": "პანელის გადატანა არ შესრულდა: {error}", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 0ea7d3d805..e9d0ba8b05 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -2753,6 +2753,25 @@ "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-ის კატალოგის იმპორტი", + "Profile: from the file (the camera's own correction)": "პროფილი: ფაილიდან (კამერის საკუთარი კორექცია)", + "Downloading the lens database…": "ობიექტივების ბაზა იტვირთება…", + "This file names no lens.": "ამ ფაილში ობიექტივი არ არის მითითებული.", + "1 photo got its lens profile": "1 ფოტომ მიიღო ობიექტივის პროფილი", + "Looking up lens profiles": "ობიექტივის პროფილების ძიება", + "Downloading the lens database": "ობიექტივების ბაზის ჩამოტვირთვა", + "The lens database could not be downloaded. LightCraft tries again the next time it starts.": "ობიექტივების მონაცემთა ბაზის ჩამოტვირთვა ვერ მოხერხდა. LightCraft კვლავ სცდის შემდეგ გაშვებისას.", + "Lens Profiles": "ობიექტივის პროფილები", + "Download lens profiles?": "ჩამოვტვირთო ობიექტივის პროფილები?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft-ს შეუძლია მრავალი ობიექტივის დისტორსიისა და ვინეტირების გასწორება ობიექტივების ღია ბაზით (lensfun, დაახლოებით {size} მბ).", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "არაფერი ჩამოიტვირთება, სანამ „ჩამოტვირთვას“ არ აირჩევთ. მოგვიანებით მისი ჩამოტვირთვა პარამეტრებიდანაც შეგიძლიათ.", + "Lens profiles": "ობიექტივის პროფილები", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "ობიექტივის პროფილები იკითხება საქაღალდიდან, რომელსაც LIGHTCRAFT_LENSFUN_DIR ასახელებს.", + "The lens database is installed.": "ობიექტივების ბაზა დაყენებულია.", + "The lens database is not installed (about {size} MB).": "ობიექტივების ბაზა არ არის დაყენებული (დაახლოებით {size} მბ).", + "Lens database": "ობიექტივების ბაზა", + "Download Lens Database": "ობიექტივების ბაზის ჩამოტვირთვა", + "Offer the lens database download when LightCraft starts": "LightCraft-ის გაშვებისას ობიექტივების ბაზის ჩამოტვირთვის შეთავაზება", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "lensfun-ის ობიექტივების ღია ბაზა (CC BY-SA 3.0) ასწორებს მრავალი ობიექტივის დისტორსიასა და ვინეტირებას. ის მხოლოდ თქვენი არჩევით ჩამოიტვირთება.", "(not in the library)": "(ბიბლიოთეკაში არ არის)", "1 raw can now be developed from its raw data": "1 RAW ფაილის დამუშავება ახლა მისი RAW მონაცემებიდან შეიძლება", "150 dpi · sRGB · current edits · fit without cropping": "150 dpi · sRGB · მიმდინარე ცვლილებები · ჩატევა ჩამოჭრის გარეშე", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 3f0fd43a22..e5d3e8d068 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -313,6 +313,9 @@ "Inside: {names}": "Wewnątrz: {names}", "Where should the Lightroom catalog “{catalog}” go?": "Dokąd zaimportować katalog Lightroom „{catalog}”?", "Merge into the open library “{library}” ({count} photo{})": "Scal z otwartą biblioteką „{library}” (zdjęcia: {count}){:.0}", + "Profile: {} (lens database)": "Profil: {} (baza obiektywów)", + "No lens profile found for {}.": "Nie znaleziono profilu obiektywu dla {}.", + "{n} photos got their lens profile": "Profil obiektywu otrzymały zdjęcia: {n}", "Photo: {name}": "Zdjęcie: {name}", "Panel layout could not be restored: {error}": "Nie udało się przywrócić układu paneli: {error}", "Panel move was not applied: {error}": "Przeniesienie panelu nie zostało zastosowane: {error}", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index bb3729a5b6..6d1eeb7dad 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2304,6 +2304,25 @@ "The photos are imported once it ends": "Zdjęcia zostaną zaimportowane potem", "An import is running. Drop photos when it has finished": "Import jest w toku. Upuść zdjęcia, gdy się zakończy", "Finish Lightroom catalog import before adding photos": "Zakończ import katalogu Lightrooma, zanim dodasz zdjęcia", + "Profile: from the file (the camera's own correction)": "Profil: z pliku (korekcja aparatu)", + "Downloading the lens database…": "Pobieranie bazy obiektywów…", + "This file names no lens.": "Ten plik nie podaje obiektywu.", + "1 photo got its lens profile": "1 zdjęcie otrzymało profil obiektywu", + "Looking up lens profiles": "Wyszukiwanie profili obiektywów", + "Downloading the lens database": "Pobieranie bazy obiektywów", + "The lens database could not be downloaded. LightCraft tries again the next time it starts.": "Nie udało się pobrać bazy obiektywów. LightCraft spróbuje ponownie przy następnym uruchomieniu.", + "Lens Profiles": "Profile obiektywów", + "Download lens profiles?": "Pobrać profile obiektywów?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft może korygować dystorsję i winietowanie wielu obiektywów, korzystając z otwartej bazy obiektywów (lensfun, około {size} MB).", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "Nic nie zostanie pobrane, dopóki nie wybierzesz Pobierz. Możesz ją pobrać później w Ustawieniach.", + "Lens profiles": "Profile obiektywów", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "Profile obiektywów są odczytywane z folderu wskazanego przez LIGHTCRAFT_LENSFUN_DIR.", + "The lens database is installed.": "Baza obiektywów jest zainstalowana.", + "The lens database is not installed (about {size} MB).": "Baza obiektywów nie jest zainstalowana (około {size} MB).", + "Lens database": "Baza obiektywów", + "Download Lens Database": "Pobierz bazę obiektywów", + "Offer the lens database download when LightCraft starts": "Proponuj pobranie bazy obiektywów przy uruchomieniu LightCraft", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "Otwarta baza obiektywów lensfun (CC BY-SA 3.0) koryguje dystorsję i winietowanie wielu obiektywów. Jest pobierana tylko wtedy, gdy to wybierzesz.", "Thumbnail size": "Rozmiar miniatur", "Import Thumbnail Size": "Rozmiar miniatur importu", "Face recognition is on": "Rozpoznawanie twarzy jest włączone", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index c26b2e281e..83d5a37518 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -313,6 +313,9 @@ "Added {n} photo{}": "{n} foto{0} adicionada{0}", "Where should the Lightroom catalog “{catalog}” go?": "Para onde vai o catálogo do Lightroom “{catalog}”?", "Merge into the open library “{library}” ({count} photo{})": "Mesclar na biblioteca aberta “{library}” ({count} foto{})", + "Profile: {} (lens database)": "Perfil: {} (banco de dados de lentes)", + "No lens profile found for {}.": "Nenhum perfil de lente encontrado para {}.", + "{n} photos got their lens profile": "{n} fotos receberam o perfil da lente", "Photo: {name}": "Foto: {name}", "Panel layout could not be restored: {error}": "Não foi possível restaurar a disposição dos painéis: {error}", "Panel move was not applied: {error}": "A movimentação do painel não foi aplicada: {error}", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index a0884dc56a..821bc56ff3 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2222,6 +2222,25 @@ "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", + "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.", + "1 photo got its lens profile": "1 foto recebeu o perfil da lente", + "Looking up lens profiles": "Procurando perfis de lente", + "Downloading the lens database": "Baixando o banco de dados de lentes", + "The lens database could not be downloaded. LightCraft tries again the next time it starts.": "Não foi possível baixar o banco de dados de lentes. O LightCraft tentará novamente na próxima vez que for aberto.", + "Lens Profiles": "Perfis de lente", + "Download lens profiles?": "Baixar perfis de lente?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "O LightCraft pode corrigir distorção e vinheta de muitas lentes usando o banco de dados aberto de lentes (lensfun, cerca de {size} MB).", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "Nada é baixado até você escolher Baixar. Você pode baixá-lo depois em Configurações.", + "Lens profiles": "Perfis de lente", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "Os perfis de lente são lidos da pasta indicada por LIGHTCRAFT_LENSFUN_DIR.", + "The lens database is installed.": "O banco de dados de lentes está instalado.", + "The lens database is not installed (about {size} MB).": "O banco de dados de lentes não está instalado (cerca de {size} MB).", + "Lens database": "Banco de dados de lentes", + "Download Lens Database": "Baixar banco de dados de lentes", + "Offer the lens database download when LightCraft starts": "Oferecer o download do banco de dados de lentes ao iniciar o LightCraft", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "O banco de dados aberto de lentes do lensfun (CC BY-SA 3.0) corrige distorção e vinheta de muitas lentes. Ele só é baixado quando você escolhe.", "Thumbnail size": "Tamanho das miniaturas", "Import Thumbnail Size": "Tamanho das miniaturas de importação", "Face recognition is on": "O reconhecimento facial está ativado", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 4be240ec5b..02f8126d96 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -313,6 +313,9 @@ "Added {n} photo{}": "Добавлено фото: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Куда импортировать каталог Lightroom «{catalog}»?", "Merge into the open library “{library}” ({count} photo{})": "Объединить с открытой библиотекой «{library}» (фото: {count}){:.0}", + "Profile: {} (lens database)": "Профиль: {} (база объективов)", + "No lens profile found for {}.": "Профиль объектива для {} не найден.", + "{n} photos got their lens profile": "Профиль объектива получили фото: {n}", "Photo: {name}": "Фото: {name}", "Panel layout could not be restored: {error}": "Не удалось восстановить расположение панелей: {error}", "Panel move was not applied: {error}": "Перемещение панели не применено: {error}", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 598893c3bc..db51744bfa 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2584,6 +2584,25 @@ "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, прежде чем добавлять фото", + "Profile: from the file (the camera's own correction)": "Профиль: из файла (коррекция самой камеры)", + "Downloading the lens database…": "Загружается база объективов…", + "This file names no lens.": "В этом файле не указан объектив.", + "1 photo got its lens profile": "1 фото получило профиль объектива", + "Looking up lens profiles": "Поиск профилей объективов", + "Downloading the lens database": "Загрузка базы объективов", + "The lens database could not be downloaded. LightCraft tries again the next time it starts.": "Не удалось загрузить базу данных объективов. LightCraft попробует снова при следующем запуске.", + "Lens Profiles": "Профили объективов", + "Download lens profiles?": "Загрузить профили объективов?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft может исправлять дисторсию и виньетирование для многих объективов с помощью открытой базы объективов (lensfun, около {size} МБ).", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "Ничего не загружается, пока вы не выберете «Загрузить». Загрузить её можно и позже в настройках.", + "Lens profiles": "Профили объективов", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "Профили объективов читаются из папки, указанной в LIGHTCRAFT_LENSFUN_DIR.", + "The lens database is installed.": "База объективов установлена.", + "The lens database is not installed (about {size} MB).": "База объективов не установлена (около {size} МБ).", + "Lens database": "База объективов", + "Download Lens Database": "Загрузить базу объективов", + "Offer the lens database download when LightCraft starts": "Предлагать загрузку базы объективов при запуске LightCraft", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "Открытая база объективов lensfun (CC BY-SA 3.0) исправляет дисторсию и виньетирование для многих объективов. Она загружается, только если вы это выберете.", "★ Favorites": "★ Избранное", "Import Thumbnail Size": "Размер миниатюр при импорте", "Face recognition is on": "Распознавание лиц включено", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index f229b9547c..4c4267d523 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2443,6 +2443,18 @@ "Dropped Files": "Släppta filer", "Finish Lightroom catalog import before adding photos": "Slutför importen av Lightroom-katalogen innan du lägger till foton", "Import dropped files without review": "Importera släppta filer utan granskning", + "Lens Profiles": "Objektivprofiler", + "Download lens profiles?": "Hämta objektivprofiler?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft kan korrigera distorsion och vinjettering för många objektiv med den öppna objektivdatabasen (lensfun, cirka {size} MB).", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "Inget hämtas förrän du väljer Hämta. Du kan hämta den senare i Inställningar.", + "Lens profiles": "Objektivprofiler", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "Objektivprofiler läses från mappen som LIGHTCRAFT_LENSFUN_DIR anger.", + "The lens database is installed.": "Objektivdatabasen är installerad.", + "The lens database is not installed (about {size} MB).": "Objektivdatabasen är inte installerad (cirka {size} MB).", + "Lens database": "Objektivdatabas", + "Download Lens Database": "Hämta objektivdatabas", + "Offer the lens database download when LightCraft starts": "Erbjud att hämta objektivdatabasen när LightCraft startar", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "lensfuns öppna objektivdatabas (CC BY-SA 3.0) korrigerar distorsion och vinjettering för många objektiv. Den hämtas bara när du väljer det.", "Import Thumbnail Size": "Miniatyrstorlek vid import", "Click to type a value, drag to change it": "Klicka för att ange ett värde, dra för att ändra det", "Face recognition is on": "Ansiktsigenkänning är på", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index e87bd03749..1bdab6dc34 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -313,6 +313,9 @@ "Added {n} photo{}": "Додано фото: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Куди імпортувати каталог Lightroom «{catalog}»?", "Merge into the open library “{library}” ({count} photo{})": "Об’єднати з відкритою бібліотекою «{library}» (фото: {count}){:.0}", + "Profile: {} (lens database)": "Профіль: {} (база об'єктивів)", + "No lens profile found for {}.": "Профіль об'єктива для {} не знайдено.", + "{n} photos got their lens profile": "Профіль об'єктива отримали фото: {n}", "Photo: {name}": "Фото: {name}", "Panel layout could not be restored: {error}": "Не вдалося відновити розташування панелей: {error}", "Panel move was not applied: {error}": "Переміщення панелі не застосовано: {error}", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index a4efe34a60..085be4f7e4 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2374,6 +2374,25 @@ "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, перш ніж додавати фото", + "Profile: from the file (the camera's own correction)": "Профіль: з файлу (корекція самої камери)", + "Downloading the lens database…": "Завантажується база об'єктивів…", + "This file names no lens.": "У цьому файлі не вказано об'єктив.", + "1 photo got its lens profile": "1 фото отримало профіль об'єктива", + "Looking up lens profiles": "Пошук профілів об'єктивів", + "Downloading the lens database": "Завантаження бази об'єктивів", + "The lens database could not be downloaded. LightCraft tries again the next time it starts.": "Не вдалося завантажити базу даних об’єктивів. LightCraft спробує знову під час наступного запуску.", + "Lens Profiles": "Профілі об’єктивів", + "Download lens profiles?": "Завантажити профілі об’єктивів?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft може виправляти дисторсію та віньєтування для багатьох об’єктивів за допомогою відкритої бази об’єктивів (lensfun, близько {size} МБ).", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "Нічого не завантажується, доки ви не виберете «Завантажити». Завантажити її можна й пізніше в налаштуваннях.", + "Lens profiles": "Профілі об’єктивів", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "Профілі об’єктивів читаються з теки, яку вказує LIGHTCRAFT_LENSFUN_DIR.", + "The lens database is installed.": "Базу об’єктивів установлено.", + "The lens database is not installed (about {size} MB).": "Базу об’єктивів не встановлено (близько {size} МБ).", + "Lens database": "База об’єктивів", + "Download Lens Database": "Завантажити базу об’єктивів", + "Offer the lens database download when LightCraft starts": "Пропонувати завантажити базу об’єктивів під час запуску LightCraft", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "Відкрита база об’єктивів lensfun (CC BY-SA 3.0) виправляє дисторсію та віньєтування для багатьох об’єктивів. Вона завантажується, лише якщо ви це виберете.", "Thumbnail size": "Розмір мініатюр", "Import Thumbnail Size": "Розмір мініатюр імпорту", "Face recognition is on": "Розпізнавання облич увімкнено", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index c1610e428f..dd93d0485c 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2253,6 +2253,18 @@ "Dropped Files": "Tệp đã thả", "Finish Lightroom catalog import before adding photos": "Hoàn tất nhập danh mục Lightroom trước khi thêm ảnh", "Import dropped files without review": "Nhập các tệp đã thả mà không xem lại", + "Lens Profiles": "Hồ sơ ống kính", + "Download lens profiles?": "Tải hồ sơ ống kính?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft có thể sửa méo hình và tối góc cho nhiều ống kính bằng cơ sở dữ liệu ống kính mở (lensfun, khoảng {size} MB).", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "Không có gì được tải xuống cho đến khi bạn chọn Tải xuống. Bạn có thể tải sau trong Cài đặt.", + "Lens profiles": "Hồ sơ ống kính", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "Hồ sơ ống kính được đọc từ thư mục mà LIGHTCRAFT_LENSFUN_DIR chỉ định.", + "The lens database is installed.": "Cơ sở dữ liệu ống kính đã được cài đặt.", + "The lens database is not installed (about {size} MB).": "Cơ sở dữ liệu ống kính chưa được cài đặt (khoảng {size} MB).", + "Lens database": "Cơ sở dữ liệu ống kính", + "Download Lens Database": "Tải cơ sở dữ liệu ống kính", + "Offer the lens database download when LightCraft starts": "Đề nghị tải cơ sở dữ liệu ống kính khi LightCraft khởi động", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "Cơ sở dữ liệu ống kính mở của lensfun (CC BY-SA 3.0) sửa méo hình và tối góc cho nhiều ống kính. Nó chỉ được tải khi bạn chọn.", "(not in the library)": "(không có trong thư viện)", "1 raw can now be developed from its raw data": "Hiện có thể xử lý 1 tệp RAW từ dữ liệu thô", "150 dpi · sRGB · current edits · fit without cropping": "150 dpi · sRGB · chỉnh sửa hiện tại · vừa khung không cắt xén", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 0a8b94115f..900d30b428 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -313,6 +313,9 @@ "Added {n} photo{}": "已添加 {n} 张照片{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Lightroom 目录“{catalog}”要导入到哪里?", "Merge into the open library “{library}” ({count} photo{})": "合并到当前打开的图库“{library}”({count} 张照片){:.0}", + "Profile: {} (lens database)": "配置文件:{}(镜头数据库)", + "No lens profile found for {}.": "未找到 {} 的镜头配置文件。", + "{n} photos got their lens profile": "{n} 张照片获得了镜头配置文件", "Photo: {name}": "照片:{name}", "Panel layout could not be restored: {error}": "无法恢复面板布局:{error}", "Panel move was not applied: {error}": "面板移动未应用:{error}", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index ea867f35e6..5f138b6f9c 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2221,6 +2221,25 @@ "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 目录的导入", + "Profile: from the file (the camera's own correction)": "配置文件:来自文件(相机自身的校正)", + "Downloading the lens database…": "正在下载镜头数据库…", + "This file names no lens.": "此文件未注明镜头。", + "1 photo got its lens profile": "1 张照片获得了镜头配置文件", + "Looking up lens profiles": "正在查找镜头配置文件", + "Downloading the lens database": "正在下载镜头数据库", + "The lens database could not be downloaded. LightCraft tries again the next time it starts.": "无法下载镜头数据库。LightCraft 会在下次启动时重试。", + "Lens Profiles": "镜头配置文件", + "Download lens profiles?": "下载镜头配置文件?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft 可以使用开放的镜头数据库(lensfun,约 {size} MB)校正许多镜头的畸变和暗角。", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "在您选择“下载”之前不会下载任何内容。您也可以稍后在设置中下载。", + "Lens profiles": "镜头配置文件", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "镜头配置文件从 LIGHTCRAFT_LENSFUN_DIR 指定的文件夹读取。", + "The lens database is installed.": "镜头数据库已安装。", + "The lens database is not installed (about {size} MB).": "镜头数据库未安装(约 {size} MB)。", + "Lens database": "镜头数据库", + "Download Lens Database": "下载镜头数据库", + "Offer the lens database download when LightCraft starts": "LightCraft 启动时提示下载镜头数据库", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "lensfun 的开放镜头数据库(CC BY-SA 3.0)可校正许多镜头的畸变和暗角。只有在您选择时才会下载。", "Thumbnail size": "缩略图大小", "Import Thumbnail Size": "导入缩略图大小", "\"saved in memory but not written to disk\", the top bar shows a warning, and LightCraft keeps retrying until the": "“已保存在内存中但未写入磁盘”,顶栏会显示警告,LightCraft 会持续重试,直到", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 178cd55a03..a451e955d5 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -313,6 +313,9 @@ "Added {n} photo{}": "已加入 {n} 張照片{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Lightroom 目錄「{catalog}」要匯入到哪裡?", "Merge into the open library “{library}” ({count} photo{})": "合併到目前開啟的照片庫「{library}」({count} 張照片){:.0}", + "Profile: {} (lens database)": "設定檔:{}(鏡頭資料庫)", + "No lens profile found for {}.": "找不到 {} 的鏡頭設定檔。", + "{n} photos got their lens profile": "{n} 張照片取得了鏡頭設定檔", "Photo: {name}": "照片:{name}", "Panel layout could not be restored: {error}": "無法還原面板配置:{error}", "Panel move was not applied: {error}": "面板移動未套用:{error}", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 90b3670ec3..275accbeb0 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2177,6 +2177,25 @@ "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 目錄的匯入", + "Profile: from the file (the camera's own correction)": "設定檔:來自檔案(相機本身的校正)", + "Downloading the lens database…": "正在下載鏡頭資料庫…", + "This file names no lens.": "此檔案未註明鏡頭。", + "1 photo got its lens profile": "1 張照片取得了鏡頭設定檔", + "Looking up lens profiles": "正在查找鏡頭設定檔", + "Downloading the lens database": "正在下載鏡頭資料庫", + "The lens database could not be downloaded. LightCraft tries again the next time it starts.": "無法下載鏡頭資料庫。LightCraft 會在下次啟動時重試。", + "Lens Profiles": "鏡頭描述檔", + "Download lens profiles?": "下載鏡頭描述檔?", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft 可以使用開放的鏡頭資料庫(lensfun,約 {size} MB)校正許多鏡頭的變形與暗角。", + "Nothing is downloaded until you choose Download. You can download it later from Settings.": "在您選擇「下載」之前不會下載任何內容。您也可以稍後在設定中下載。", + "Lens profiles": "鏡頭描述檔", + "Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.": "鏡頭描述檔從 LIGHTCRAFT_LENSFUN_DIR 指定的資料夾讀取。", + "The lens database is installed.": "鏡頭資料庫已安裝。", + "The lens database is not installed (about {size} MB).": "鏡頭資料庫未安裝(約 {size} MB)。", + "Lens database": "鏡頭資料庫", + "Download Lens Database": "下載鏡頭資料庫", + "Offer the lens database download when LightCraft starts": "LightCraft 啟動時提示下載鏡頭資料庫", + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "lensfun 的開放鏡頭資料庫(CC BY-SA 3.0)可校正許多鏡頭的變形與暗角。只有在您選擇時才會下載。", "Thumbnail size": "縮圖大小", "Import Thumbnail Size": "匯入縮圖大小", "\"saved in memory but not written to disk\", the top bar shows a warning, and LightCraft keeps retrying until the": "「已儲存在記憶體中但尚未寫入磁碟」,頂端列會顯示警告,LightCraft 會持續重試,直到", diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index a757af1aef..43e430e3c7 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -70,6 +70,8 @@ impl LightcraftApp { lightroom_import::tick(self, ctx); recheck::tick(self); tasks::poll(self, ctx); + // after the poll: a lookup that just finished is cleared, so photos queued meanwhile are looked up now + crate::lens_db::tick(self); updates_ui::tick(self, ctx); self.preview_build_status(ctx); self.save_status(ctx); @@ -305,6 +307,10 @@ impl LightcraftApp { if self.shown_library == Some(generation) { return; } + // (the first library shown takes the place of none: nothing was searching another one) + if self.shown_library.is_some() { + crate::find_similar::library_changed(self); + } self.shown_library = Some(generation); if let Some(l) = self.session.library.as_ref().filter(|l| l.on_disk) { let path = l.dir.to_string_lossy().into_owned(); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index a7b70e3143..3c6c2e1576 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -133,7 +133,7 @@ pub fn inspect(app: &LightcraftApp, ctx: &egui::Context) -> Value { "selection": app.session.selection.ids.iter().map(|p| p.0).collect::>(), "activeMask": app.session.active_mask, "widgetCount": app.widgets.len(), - "perf": {"viewFollowed": app.session.view_followed, "viewWorkedOut": app.session.view_worked_out, "frameMs": app.perf.frame_ms, "logicMs": app.perf.logic_ms, "updateMs": app.perf.update_ms, "maxUpdateMs": app.perf.max_update_ms, "fps": app.perf.fps, "lastRenderMs": app.renderer.last_main_ms, "renderQueue": app.renderer.queued(), "rendersInFlight": app.renderer.in_flight(), "pendingSlots": app.renderer.pending_slots(), "mergeRunning": app.merge.busy(), "lastMerge": app.merge.last_result, "rendersDone": app.renderer.completed, "thumbTextures": app.renderer.thumb_textures(), "variantTextures": app.renderer.variant_textures(), "gpu": (lightcraft_engine::gpu::ready() && lightcraft_engine::gpu::available()).then(lightcraft_engine::gpu::adapter_name).flatten(), "gpuReason": lightcraft_engine::gpu::unavailable_reason(), "gpuFallback": lightcraft_engine::gpu::last_fallback()}, + "perf": {"viewFollowed": app.session.view_followed, "viewWorkedOut": app.session.view_worked_out, "frameMs": app.perf.frame_ms, "logicMs": app.perf.logic_ms, "updateMs": app.perf.update_ms, "maxUpdateMs": app.perf.max_update_ms, "fps": app.perf.fps, "lastRenderMs": app.renderer.last_main_ms, "renderQueue": app.renderer.queued(), "rendersInFlight": app.renderer.in_flight(), "pendingSlots": app.renderer.pending_slots(), "mergeRunning": app.merge.busy(), "lastMerge": app.merge.last_result, "rendersDone": app.renderer.completed, "thumbTextures": app.renderer.thumb_textures(), "variantTextures": app.renderer.variant_textures(), "gpu": (lightcraft_engine::gpu::ready() && lightcraft_engine::gpu::available()).then(lightcraft_engine::gpu::adapter_name).flatten(), "gpuReason": lightcraft_engine::gpu::unavailable_reason(), "gpuFallback": lightcraft_engine::gpu::last_fallback(), "gpuWindowDevice": lightcraft_engine::gpu::on_window_device(), "screenTextures": app.renderer.has_screen_textures(), "mainOnGpu": app.renderer.textures.get(&crate::render::Slot::Main).is_some_and(|t| t.native.is_some())}, "loupe": app.loupe_shown.map(|(p, src)| json!({ "photo": p.0, "source": src, @@ -345,6 +345,12 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest ctx.request_repaint(); return started; } + if id == "library.findSimilar" { + // reads every photo: on a worker thread, answered when it is done + let started = crate::find_similar::ask(app, ¶ms, req.reply.clone()); + ctx.request_repaint(); + return started; + } let r = app.run(id, params); ctx.request_repaint(); wrap(r) @@ -445,6 +451,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest | crate::state::Dialog::SmartRules { .. } | crate::state::Dialog::SaveEffect { .. } | crate::state::Dialog::CaptureTime { .. } + | crate::state::Dialog::LensDatabase { .. } | crate::state::Dialog::TextPrompt { .. } )) || (r.is_ok() && crate::panels::dialogs::keeps_open(app, &d)) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 07f050aa7a..03a1ef5478 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -158,6 +158,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { Dialog::FaceModel { .. } => 460.0, Dialog::LightroomCatalog { .. } => 440.0, Dialog::LightroomDestination { .. } => 480.0, + Dialog::LensDatabase { .. } => 440.0, Dialog::ManageEffects { .. } => 560.0, _ => 380.0, }) @@ -320,6 +321,7 @@ fn dialog_title(app: &LightcraftApp, dlg: &Dialog) -> String { Dialog::MovePhotos { .. } => "Move Photos", Dialog::LightroomCatalog { .. } => "Lightroom Classic Catalog", Dialog::LightroomDestination { .. } => "Import Lightroom Catalog", + Dialog::LensDatabase { .. } => "Lens Profiles", Dialog::SaveEffect { .. } => "New Effect Preset", Dialog::ManageEffects { .. } => "Manage Effect Presets", Dialog::DeleteEffects { names } if names.len() == 1 => "Delete Effect Preset", @@ -369,7 +371,7 @@ impl SamState { fn cancel_label(dlg: &Dialog, sam: &SamState) -> &'static str { match dlg { Dialog::SamModel { .. } if sam.running || sam.installed || sam.by_hand => "Close", - Dialog::SamModel { .. } => "Not Now", + Dialog::SamModel { .. } | Dialog::LensDatabase { .. } => "Not Now", Dialog::LightroomResult { .. } => "Close", _ => "Cancel", } @@ -446,6 +448,7 @@ fn fixed_ok_label(app: &LightcraftApp, dlg: &Dialog, informational: bool) -> &'s Dialog::RemoveFolder { .. } => "Remove", Dialog::LightroomCatalog { .. } => "Import Lightroom Catalog…", d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::ok_label(d), + Dialog::LensDatabase { .. } => "Download", Dialog::SynchronizeFolder { .. } if informational => "Close", Dialog::SynchronizeFolder { .. } => "Synchronize", Dialog::RenamePerson { from, to, .. } if person_rename_plan(&app.session.catalog, from, to).needs_merge => "Merge", @@ -554,7 +557,8 @@ fn confirmed(app: &mut LightcraftApp, ctx: &egui::Context, dlg: &mut Dialog) -> match confirm_dialog(app, dlg) { // the import review stays open on an error (e.g. an unusable folder template), and so // does Export (e.g. no folder chosen) so the choices aren't lost, and Edit Capture Time - // (a time that isn't a date, or a shift it refuses) + // (a time that isn't a date, or a shift it refuses), and the lens database offer (a download that can't + // start: Download again or Not Now) Err(e) if matches!( dlg, @@ -571,6 +575,7 @@ fn confirmed(app: &mut LightcraftApp, ctx: &egui::Context, dlg: &mut Dialog) -> | Dialog::SynchronizeFolder { .. } | Dialog::SaveEffect { .. } | Dialog::CaptureTime { .. } + | Dialog::LensDatabase { .. } ) => { app.toast(ctx, e) @@ -1863,7 +1868,7 @@ fn remove_folder_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { /// The body of the About dialog. fn about_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { let Dialog::About = dlg else { return }; - ui.set_min_width(680.0); + ui.set_min_width(820.0); let tab_id = egui::Id::unique("about_tab"); let mut tab = ui.data_mut(|d| d.get_temp::(tab_id)).unwrap_or(0); ui.horizontal(|ui| { @@ -1989,6 +1994,7 @@ fn dialog_content(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, body_m d @ Dialog::SynchronizeFolder { .. } => crate::sync::body(app, ui, d), Dialog::LightroomCatalog { .. } => lightroom_catalog_body(app, ui, t, dlg), d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::body(app, ui, d), + Dialog::LensDatabase { .. } => crate::lens_db::offer(ui), Dialog::RemoveFolder { .. } => remove_folder_body(ui, t, dlg), Dialog::About => about_body(app, ui, t, dlg), Dialog::Shortcuts => crate::panels::keymap::body(app, ui, t), diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 707c0dbec6..5f8e2c0445 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -238,6 +238,9 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result crate::lightroom_destination::confirm(app, d), + Dialog::LensDatabase { dir, mirrors } => { + crate::lens_db::download(app, std::path::Path::new(dir), mirrors.clone()).map(|()| json!({"downloading": true})) + } Dialog::SaveEffect { name, group, fields, amount, brush } => { crate::panels::mask_effects::save_confirm(app, name, group, fields, *amount, *brush) } diff --git a/crates/ui-egui/src/dialogs/credits.rs b/crates/ui-egui/src/dialogs/credits.rs index 12f857705a..049bf1eedb 100644 --- a/crates/ui-egui/src/dialogs/credits.rs +++ b/crates/ui-egui/src/dialogs/credits.rs @@ -271,12 +271,17 @@ pub fn contributors_ui(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.label(RichText::new(crate::i18n::tr_format!("{} contributors · {} commits", list.len(), group(TOTAL_COMMITS))).small().color(t.text_dim)); ui.separator(); let list_h = crate::panels::dialogs::list_height(ui, LIST_HEIGHT); - egui::ScrollArea::both().id_salt("credits_scroll").max_height(list_h).auto_shrink([false, true]).show(ui, |ui| { - if list.is_empty() { - ui.label(crate::i18n::tr("No contributor data was built into this copy.")); - } else if v.table { - table(app, ui, &list, &mut v); - } else { + if list.is_empty() { + ui.label(crate::i18n::tr("No contributor data was built into this copy.")); + } else if v.table { + // The table scrolls vertically itself, under a fixed header; it only scrolls sideways + // once its columns are dragged wider than the dialog. + ui.allocate_ui(egui::vec2(ui.available_width(), list_h), |ui| { + ui.set_max_height(list_h); + egui::ScrollArea::horizontal().id_salt("credits_scroll").auto_shrink([false, false]).show(ui, |ui| table(app, ui, &list, &mut v)); + }); + } else { + egui::ScrollArea::vertical().id_salt("credits_scroll").max_height(list_h).auto_shrink([false, true]).show(ui, |ui| { ui.horizontal_wrapped(|ui| { for (i, c) in list.iter().enumerate() { if i > 0 { @@ -285,49 +290,153 @@ pub fn contributors_ui(app: &mut LightcraftApp, ui: &mut egui::Ui) { name_link(app, ui, c, v.names); } }); - } - }); + }); + } ui.data_mut(|d| d.insert_temp(id, v)); } -fn table(app: &mut LightcraftApp, ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) { - egui::Grid::new("credits_table").striped(true).num_columns(SortKey::ALL.len()).show(ui, |ui| { - for k in SortKey::ALL { - let text = RichText::new(crate::i18n::tr(k.label().1)).strong(); - let header = if v.key == k { - crate::widgets::arrow_button( - ui, - text, - if v.ascending { crate::icons::Icon::ChevronUp } else { crate::icons::Icon::ChevronDown }, - false, - ) +/// How the contributor table's spare width is shared out: all of it to Name. +const CONTRIBUTOR_GROW: [f32; 10] = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; + +/// How the model table's spare width is shared out: to Company and Model, the text columns. +const MODEL_GROW: [f32; 6] = [1.0, 2.0, 0.0, 0.0, 0.0, 0.0]; + +/// The narrowest a column can be dragged. +const MIN_COLUMN: f32 = 28.0; + +/// The width a column needs for its header and its widest cell. +fn natural(ui: &egui::Ui, header: RichText, cells: impl Iterator) -> f32 { + let measure = |text: egui::WidgetText| text.into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Body).size().x; + let widest = cells.map(|c| measure(c.into())).fold(measure(header.into()), f32::max); + widest + 2.0 * ui.spacing().button_padding.x +} + +/// Opening column widths: each column's natural width, with the spare room shared out by `grow`, +/// so the columns fill `room` exactly. When there is too little room, only the growing columns +/// give way, each in proportion to its width above [`MIN_COLUMN`], and none goes below that. +fn fit_widths(natural: &[f32], grow: &[f32], room: f32) -> Vec { + let spare = room - natural.iter().sum::(); + let weight = grow.iter().sum::(); + let slack = |w: f32| (w - MIN_COLUMN).max(0.0); + let flexible: f32 = natural.iter().zip(grow).filter(|(_, g)| **g > 0.0).map(|(w, _)| slack(*w)).sum(); + natural + .iter() + .zip(grow) + .map(|(w, g)| { + if *g > 0.0 && spare >= 0.0 { + w + spare * g / weight + } else if *g > 0.0 && flexible > 0.0 { + w - (-spare).min(flexible) * slack(*w) / flexible } else { - ui.button(text) - }; - if header.on_hover_text(crate::i18n::tr(k.label().0)).clicked() { - if v.key == k { - v.ascending = !v.ascending; - } else { - v.key = k; - v.ascending = k.default_ascending(); - } + *w } - } - ui.end_row(); - for c in list { - name_link(app, ui, c, v.names); - ui.label(group(c.prs)); - ui.label(group(c.commits)); - ui.label(group(c.lines_added)); - ui.label(group(c.lines_deleted)); - ui.label(signed(c.lines_delta())); - ui.label(group(c.binary_added)); - ui.label(group(c.binary_deleted)); - ui.label(day(c.first_commit)); - ui.label(day(c.last_commit)); - ui.end_row(); - } - }); + }) + .collect() +} + +/// A striped table whose columns open at [`fit_widths`], so it fills the width and nothing scrolls +/// sideways. Every column, the last included, can be dragged wider or narrower at its right edge: +/// only a table dragged wider than the window scrolls sideways. Text too long for its column is +/// clipped. When a column's natural width or the window changes, the columns go back to a new fit, +/// dropping any dragged widths. +fn fitted_table<'a>(ui: &'a mut egui::Ui, id: &str, natural: &[f32], grow: &[f32]) -> egui_extras::TableBuilder<'a> { + // Every cell is followed by the item gap, and the vertical scrollbar keeps its margins. + let s = ui.spacing(); + let gaps = s.item_spacing.x * natural.len() as f32; + let bar = s.scroll.bar_width + s.scroll.bar_inner_margin + s.scroll.bar_outer_margin; + let widths = fit_widths(natural, grow, (ui.available_width() - gaps - bar).max(0.0)); + // The table keeps its own column widths, so a change in what they were fitted to has to clear + // them. A longer name can leave the fit itself unchanged, and scrolling can nudge the available + // width, so this compares the natural widths and the clip rect, which scrolling never moves. + let fit = egui::Id::unique(("credits_fit", id)); + let measured = (natural.to_vec(), ui.clip_rect().width()); + let refit = ui.data_mut(|d| d.get_temp::<(Vec, f32)>(fit)).as_ref() != Some(&measured); + ui.data_mut(|d| d.insert_temp(fit, measured)); + let mut t = + egui_extras::TableBuilder::new(ui).id_salt(id).striped(true).resizable(true).auto_shrink([false, false]).max_scroll_height(f32::INFINITY); + if refit { + t.reset(); + } + for w in widths { + t = t.column(egui_extras::Column::initial(w).at_least(MIN_COLUMN).clip(true)); + } + t +} + +/// Add a cell's widget right-aligned (counts, dates) or left-aligned (names), vertically centred. +fn aligned(ui: &mut egui::Ui, right: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + let layout = if right { egui::Layout::right_to_left(egui::Align::Center) } else { egui::Layout::left_to_right(egui::Align::Center) }; + ui.with_layout(layout, add).inner +} + +fn row_height(ui: &egui::Ui) -> f32 { + ui.text_style_height(&egui::TextStyle::Body) + 6.0 +} + +/// One contributor's table cells after the name, in `SortKey::ALL` order. +fn cells(c: &Contributor) -> [String; 9] { + [ + group(c.prs), + group(c.commits), + group(c.lines_added), + group(c.lines_deleted), + signed(c.lines_delta()), + group(c.binary_added), + group(c.binary_deleted), + day(c.first_commit).to_string(), + day(c.last_commit).to_string(), + ] +} + +/// A contributor-table header. The sorted column is highlighted; its direction shows on the +/// toolbar's sort-order button, so no arrow widens the column. +fn header_text(k: SortKey) -> RichText { + RichText::new(crate::i18n::tr(k.label().1)).strong() +} + +fn table(app: &mut LightcraftApp, ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) { + let h = row_height(ui); + let rows: Vec<[String; 9]> = list.iter().map(|c| cells(c)).collect(); + let widths: Vec = SortKey::ALL + .iter() + .enumerate() + .map(|(i, &k)| match i.checked_sub(1) { + None => natural(ui, header_text(k), list.iter().map(|c| c.name(v.names))), + Some(col) => natural(ui, header_text(k), rows.iter().filter_map(|r| r.get(col).cloned())), + }) + .collect(); + fitted_table(ui, "credits_table", &widths, &CONTRIBUTOR_GROW) + .header(h + 4.0, |mut header| { + for k in SortKey::ALL { + header.col(|ui| { + let r = aligned(ui, k != SortKey::Name, |ui| ui.selectable_label(v.key == k, header_text(k))) + .on_hover_text(crate::i18n::tr(k.label().0)); + + if r.clicked() { + if v.key == k { + v.ascending = !v.ascending; + } else { + v.key = k; + v.ascending = k.default_ascending(); + } + } + }); + } + }) + .body(|mut body| { + for (c, cells) in list.iter().zip(rows) { + body.row(h, |mut row| { + row.col(|ui| { + aligned(ui, false, |ui| name_link(app, ui, c, v.names)); + }); + for text in cells { + row.col(|ui| { + aligned(ui, true, |ui| ui.label(text)); + }); + } + }); + } + }); } /// About ▸ Models: AI models credited in Co-Authored-By trailers. @@ -337,22 +446,51 @@ pub fn models_ui(ui: &mut egui::Ui) { return; } let assisted: u64 = MODELS.iter().map(|m| m.commits).max().unwrap_or(0).max(1); + let h = row_height(ui); let list_h = crate::panels::dialogs::list_height(ui, LIST_HEIGHT); - egui::ScrollArea::both().id_salt("credits_models_scroll").max_height(list_h).auto_shrink([false, true]).show(ui, |ui| { - egui::Grid::new("credits_models").striped(true).num_columns(6).show(ui, |ui| { - for h in ["Company", "Model", "Version", "Commits", "% of all commits", "Lines +/−"] { - ui.label(RichText::new(crate::i18n::tr(h)).strong()); - } - ui.end_row(); - for m in MODELS { - ui.label(m.company); - ui.label(m.model); - ui.label(m.version); - ui.label(group(m.commits)); - ui.label(format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64)); - ui.label(format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted))); - ui.end_row(); - } + let titles = ["Company", "Model", "Version", "Commits", "% of all commits", "Lines +/−"]; + // Company, Model and Version read as text; the counts line up on the right. + let right = [false, false, false, true, true, true]; + let rows: Vec<[String; 6]> = MODELS + .iter() + .map(|m| { + [ + m.company.to_string(), + m.model.to_string(), + m.version.to_string(), + group(m.commits), + format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64), + format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted)), + ] + }) + .collect(); + let widths: Vec = titles + .iter() + .enumerate() + .map(|(i, title)| natural(ui, RichText::new(crate::i18n::tr(title)).strong(), rows.iter().filter_map(|r| r.get(i).cloned()))) + .collect(); + ui.allocate_ui(egui::vec2(ui.available_width(), list_h), |ui| { + ui.set_max_height(list_h); + egui::ScrollArea::horizontal().id_salt("credits_models_scroll").auto_shrink([false, false]).show(ui, |ui| { + fitted_table(ui, "credits_models", &widths, &MODEL_GROW) + .header(h + 4.0, |mut header| { + for (title, r) in titles.into_iter().zip(right) { + header.col(|ui| { + aligned(ui, r, |ui| ui.label(RichText::new(crate::i18n::tr(title)).strong())); + }); + } + }) + .body(|mut body| { + for cells in rows { + body.row(h, |mut row| { + for (text, r) in cells.into_iter().zip(right) { + row.col(|ui| { + aligned(ui, r, |ui| ui.label(text)); + }); + } + }); + } + }); }); }); } @@ -442,4 +580,131 @@ mod tests { assert_eq!(day("2026-10-07T18:45:23Z"), "2026-10-07"); assert_eq!(day(""), "—"); } + + #[test] + fn columns_fill_the_room_and_spare_width_goes_to_growing_columns() { + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 300.0), [200.0, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 2.0, 0.0], 230.0), [110.0, 60.0, 60.0]); + let w = fit_widths(&[123.0, 45.5, 67.25], &[1.0, 0.0, 2.0], 512.0); + assert!((w.iter().sum::() - 512.0).abs() < 0.01, "a fitted table neither scrolls nor leaves a gap: {w:?}"); + } + + #[test] + fn too_little_room_shrinks_only_growing_columns() { + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 150.0), [50.0, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 0.0), [MIN_COLUMN, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0], &[0.0, 0.0], 50.0), [100.0, 40.0]); + } + + #[test] + fn a_column_at_the_minimum_leaves_the_shortfall_to_the_others() { + let w = fit_widths(&[100.0, 300.0, 50.0], &[1.0, 1.0, 0.0], 140.0); + assert!((w.iter().sum::() - 140.0).abs() < 0.01, "the columns still fit the room: {w:?}"); + assert!(w.iter().all(|c| *c >= MIN_COLUMN), "no column goes below the minimum: {w:?}"); + assert_eq!(fit_widths(&[100.0, 300.0, 50.0], &[1.0, 1.0, 0.0], 0.0), [MIN_COLUMN, MIN_COLUMN, 50.0]); + } + + const WINDOW: f32 = 640.5; + const NATURAL: [f32; 3] = [120.0, 80.0, 80.0]; + const GROW: [f32; 3] = [1.0, 0.0, 0.0]; + + /// One frame of a table long enough to scroll; the rects of its header cells. + fn table_frame(ctx: &egui::Context, width: f32, natural: &[f32], events: Vec) -> Vec { + scrolled_frame(ctx, width, natural, 0.0, events) + } + + /// [`table_frame`], scrolled `offset` points sideways. + fn scrolled_frame(ctx: &egui::Context, width: f32, natural: &[f32], offset: f32, events: Vec) -> Vec { + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 300.0))); + let raw = egui::RawInput { screen_rect, events, ..Default::default() }; + let mut cells = Vec::new(); + let out = ctx.run_ui(raw, |ui| { + cells.clear(); + egui::ScrollArea::horizontal().auto_shrink([false, false]).horizontal_scroll_offset(offset).show(ui, |ui| { + fitted_table(ui, "test", natural, &GROW) + .header(20.0, |mut header| { + for _ in natural { + header.col(|ui| cells.push(ui.max_rect())); + } + }) + .body(|mut body| { + for _ in 0..40 { + body.row(20.0, |mut row| { + for _ in natural { + row.col(|ui| { + ui.label("x"); + }); + } + }); + } + }); + }); + }); + out.drop_without_applying_deltas(); + cells + } + + /// A new context with the table open and settled, and the rects of its header cells. + fn opened_table() -> (egui::Context, Vec) { + let ctx = egui::Context::default(); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let cells = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + (ctx, cells) + } + + /// Drags a column's right edge, which runs midway through the gap after `cell`, then lets go. + fn drag_edge(ctx: &egui::Context, cell: egui::Rect, by: f32) { + use egui::{Event, Modifiers, PointerButton}; + let start = egui::pos2(cell.right() + 4.0, cell.center().y); + let halfway = start + egui::vec2(by / 2.0, 0.0); + let end = start + egui::vec2(by, 0.0); + let moved = Event::PointerMoved; + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + for event in [moved(start), button(start, true), moved(halfway), moved(end), button(end, false)] { + table_frame(ctx, WINDOW, &NATURAL, vec![event]); + } + } + + #[test] + fn every_column_can_be_dragged_at_its_right_edge_and_stays_there() { + let (_, opened) = opened_table(); + for (dragged, cell) in opened.iter().enumerate() { + let (ctx, _) = opened_table(); + drag_edge(&ctx, *cell, -30.0); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let after = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + for (column, (was, now)) in opened.iter().zip(&after).enumerate() { + let want = if column == dragged { was.width() - 30.0 } else { was.width() }; + assert!((now.width() - want).abs() < 1.0, "dragging column {dragged}: column {column} is {now:?}, was {was:?}"); + } + } + } + + #[test] + fn a_changed_fit_replaces_the_column_widths() { + let (ctx, opened) = opened_table(); + drag_edge(&ctx, opened[0], -30.0); + let longer_name = table_frame(&ctx, WINDOW, &[200.0, 80.0, 80.0], Vec::new()); + assert!((longer_name[0].width() - opened[0].width()).abs() < 1.0, "a longer name drops a dragged width: {longer_name:?}"); + let wider = table_frame(&ctx, WINDOW, &[120.0, 200.0, 80.0], Vec::new()); + let widths: Vec = wider.iter().map(|c| c.width().round()).collect(); + assert!(widths.ends_with(&[200.0, 80.0]), "a longer cell widens its column: {widths:?}"); + assert!(wider[2].right() < WINDOW, "the table still fits the window: {wider:?}"); + let narrower = table_frame(&ctx, 400.0, &NATURAL, Vec::new()); + assert!(narrower[2].right() < 400.0, "a narrower window refits the table: {narrower:?}"); + } + + #[test] + fn scrolling_sideways_keeps_dragged_widths() { + let (ctx, opened) = opened_table(); + drag_edge(&ctx, opened[0], 100.0); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let dragged = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + assert!((dragged[0].width() - opened[0].width() - 100.0).abs() < 1.0, "the drag took: {dragged:?}"); + for offset in [13.3, 27.77, 41.1, 0.6] { + scrolled_frame(&ctx, WINDOW, &NATURAL, offset, Vec::new()); + let scrolled = scrolled_frame(&ctx, WINDOW, &NATURAL, offset, Vec::new()); + assert!((scrolled[0].width() - dragged[0].width()).abs() < 1.0, "scrolled {offset}: {scrolled:?}"); + } + } } diff --git a/crates/ui-egui/src/dialogs/import/body.rs b/crates/ui-egui/src/dialogs/import/body.rs index 0a4b9fb97f..61e0bfb1bd 100644 --- a/crates/ui-egui/src/dialogs/import/body.rs +++ b/crates/ui-egui/src/dialogs/import/body.rs @@ -450,7 +450,7 @@ fn candidate_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDial let s = ((img.width() - 8.0) / tw as f32).min((img.height() - 8.0) / th as f32); let fit = Rect::from_center_size(img.center(), vec2(tw as f32 * s, th as f32 * s)); let tint = if ok { Color32::WHITE } else { Color32::from_gray(110) }; - p.image(tex.tex.id(), fit, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), tint); + p.image(tex.id(), fit, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), tint); } let on = d.checked.get(i).copied().unwrap_or(false) && ok; if on { diff --git a/crates/ui-egui/src/dialogs/print_view.rs b/crates/ui-egui/src/dialogs/print_view.rs index c9af1d776d..3161aa96f7 100644 --- a/crates/ui-egui/src/dialogs/print_view.rs +++ b/crates/ui-egui/src/dialogs/print_view.rs @@ -883,7 +883,7 @@ fn paint_cell( let px = (shown.width().max(shown.height()) * 2.0).clamp(64.0, 1024.0) as usize; crate::panels::grid::request_thumb(app, id, px, 10); } - app.renderer.thumb(id).map(|tex| tex.tex.id()) + app.renderer.thumb(id).map(|tex| tex.id()) }); match tex { Some(id) => { diff --git a/crates/ui-egui/src/dialogs/settings/general.rs b/crates/ui-egui/src/dialogs/settings/general.rs index c4fb8b754e..1231e9d3b7 100644 --- a/crates/ui-egui/src/dialogs/settings/general.rs +++ b/crates/ui-egui/src/dialogs/settings/general.rs @@ -109,6 +109,50 @@ pub(super) fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens "To hand this editor the original file itself instead (the raw, without a copy: DxO PhotoLab, for example), right-click a photo → Edit In → Open Original in Other Editor (RAW, no copy).", ), ); + #[cfg(not(target_arch = "wasm32"))] + lens_profiles(app, ui, t); +} + +/// Lens profiles: whether the lens database is here, a button that downloads it (nothing is fetched without a +/// click: the first launch offers it once, [`crate::lens_db`]), and the startup offer turned back on or off. +#[cfg(not(target_arch = "wasm32"))] +fn lens_profiles(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + use lightcraft_engine::lensfun_download::{self, Offer}; + heading(ui, t, crate::i18n::tr("Lens profiles")); + let running = app.session.lensfun.running(); + // (the user's own folder, LIGHTCRAFT_LENSFUN_DIR, is read instead and never replaced) + let own = std::env::var_os(lightcraft_engine::lens_profiles::ENV).is_some_and(|v| !v.is_empty()); + let installed = lensfun_download::default_dir().is_some_and(|d| lensfun_download::installed(&d)); + let status = if own { + crate::i18n::tr("Lens profiles are read from the folder LIGHTCRAFT_LENSFUN_DIR names.").to_string() + } else if running { + crate::i18n::tr("Downloading the lens database…").to_string() + } else if installed { + crate::i18n::tr("The lens database is installed.").to_string() + } else { + crate::i18n::tr_format!("The lens database is not installed (about {size} MB).", size = lensfun_download::download_megabytes()) + }; + row(ui, t, crate::i18n::tr("Lens database"), |ui| { + ui.label(RichText::new(status).color(t.text)); + let r = ui.add_enabled(!own && !running && !installed, egui::Button::new(crate::i18n::tr("Download Lens Database"))); + register(ui, "button:settingsLensDatabase", r.rect); + if r.clicked() + && let Err(e) = crate::lens_db::download_default(app) + { + app.toast(ui.ctx(), e); + } + }); + let mut offer = app.ui.settings.lens_database != Offer::Declined; + if check(ui, "settings.lensDatabaseOffer", &mut offer, "Offer the lens database download when LightCraft starts") { + app.ui.settings.lens_database = if offer { Offer::Ask } else { Offer::Declined }; + } + hint( + ui, + t, + crate::i18n::tr( + "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.", + ), + ); } /// The file Edit In hands an editor: format, colour space and bit depth (`button:{id}Format-…`). diff --git a/crates/ui-egui/src/dialogs/settings/slide_layout.rs b/crates/ui-egui/src/dialogs/settings/slide_layout.rs index c78d3df4d9..d9595d2de9 100644 --- a/crates/ui-egui/src/dialogs/settings/slide_layout.rs +++ b/crates/ui-egui/src/dialogs/settings/slide_layout.rs @@ -258,7 +258,7 @@ pub fn preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, max_h: f3 return; }; let drawn = crate::panels::detail::fit_texture_rect(rect, tex.size); - p.image(tex.tex.id(), drawn, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), drawn, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); if s.show_guides { // the margins, as lines across the slide (where the image cell's edges are) let aspect = app.session.slide_photo_aspect(id).unwrap_or(1.5); @@ -302,7 +302,7 @@ fn title_preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, rect: R match app.renderer.textures.get(&Slot::SlidePreview).filter(|tex| tex.photo == lightcraft_catalog::PhotoId(0)) { Some(tex) => { let drawn = crate::panels::detail::fit_texture_rect(rect, tex.size); - p.image(tex.tex.id(), drawn, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), drawn, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } None => { let c = look.titles.screen(title).color; diff --git a/crates/ui-egui/src/find_similar.rs b/crates/ui-egui/src/find_similar.rs new file mode 100644 index 0000000000..d96424317c --- /dev/null +++ b/crates/ui-egui/src/find_similar.rs @@ -0,0 +1,110 @@ +//! Find Similar Photos in the app. The first search reads every photo of the library, which on the +//! UI thread left the window not responding for as long as that took: hours in a library of tens of +//! thousands of raws (issue #3468). The photos are read on a worker thread instead, under a row in +//! the activity stack that counts them and can stop. What was read before a stop is kept, so the +//! next search goes on from there. +//! +//! From a menu the command answers at once and says how it ended in a toast. A request from the +//! control channel (an agent, `mcp --connect`) gets the same `{photos}` as ever, when the search +//! ends; one that gave up waiting can ask again and is answered from what was read. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::Sender; + +use lightcraft_engine::cmd::similar; +use serde_json::{Value, json}; + +use crate::LightcraftApp; +use crate::control::{self, Outcome}; + +/// The activity stack's label (the menu item's name, already translated). +pub const LABEL: &str = "Find Similar Photos"; + +/// How a search ended. +enum End { + /// The command's answer. + Found(Value), + /// Nothing was asked of the view any more: why. + Dropped(&'static str), + Failed(String), +} + +/// Start a search for `p`: `end` runs on the UI thread when it is over. How many contents it has to +/// read, or why it can't start. +fn start(app: &mut LightcraftApp, p: &Value, end: impl FnOnce(&mut LightcraftApp, &egui::Context, End) + Send + 'static) -> Result { + similar::no_search_running(&app.session).map_err(|why| format!("library.findSimilar: {why}"))?; + let (search, reads) = similar::plan(&mut app.session, p).map_err(|e| e.to_string())?; + let count = reads.len(); + let library = app.session.library_generation(); + let cancel = Arc::new(AtomicBool::new(false)); + let (flag, stopped) = (cancel.clone(), cancel.clone()); + let work = move |task: lightcraft_engine::activity::TaskHandle| { + let total = count as u64; + task.progress(0, total); + lightcraft_engine::guard::catch(LABEL, || similar::measure(reads, &flag, &|done| task.progress(done as u64, total))) + }; + let done = move |app: &mut LightcraftApp, ctx: &egui::Context, found: Result, String>| { + let ended = match found { + _ if app.session.library_generation() != library => End::Dropped("another library was opened before the search ended"), + Err(e) => End::Failed(e), + Ok(found) => { + similar::keep(&mut app.session, found); + if stopped.load(Ordering::Relaxed) { + End::Dropped("the search was stopped") + } else { + match app.session.execute_fn("library.findSimilar", |s| similar::apply(s, &search)) { + Ok(answer) => End::Found(answer), + Err(e) => End::Failed(e.to_string()), + } + } + } + }; + end(app, ctx, ended); + }; + crate::tasks::spawn_tracked(app, LABEL, similar::KIND, cancel, work, done)?; + Ok(count) +} + +/// `library.findSimilar` from a menu: start reading → `{background: true, count}`. The grid shows +/// what it found, and a toast says how many. +pub fn command(app: &mut LightcraftApp, p: &Value) -> Result { + let count = start(app, p, |app, ctx, end| match end { + End::Found(answer) => { + let n = answer["photos"].as_array().map_or(0, Vec::len); + app.ui.view = crate::state::ViewMode::PhotoGrid; + app.toast(ctx, crate::i18n::tr_format!("{n} similar photo{} · View ▸ Clear Filters to see all", if n == 1 { "" } else { "s" }, n = n)); + } + // (whoever stopped it knows; a search of another library has nothing to say about this one) + End::Dropped(_) => {} + End::Failed(e) => app.toast(ctx, e), + })?; + Ok(json!({"background": true, "count": count})) +} + +/// `library.findSimilar` from the control channel: `reply` gets the command's answer when the search +/// ends, and the view stays where the agent left it. +pub fn ask(app: &mut LightcraftApp, p: &Value, reply: Sender) -> Outcome { + let started = start(app, p, move |_, _, end| { + let answer = match end { + End::Found(answer) => control::success(answer), + End::Dropped(why) => control::failure(format!("library.findSimilar: {why}")), + End::Failed(e) => control::failure(e), + }; + // (a caller that gave up has no one to send to; what was read stays known for its next request) + let _ = reply.send(answer); + }); + match started { + Ok(_) => Outcome::Later, + Err(e) => Outcome::Done(control::failure(e)), + } +} + +/// Another library was opened: stop a search of the one before, which has nothing left to find (it +/// could go on reading for hours). Its row goes when the photo being read is done. +pub fn library_changed(app: &LightcraftApp) { + for row in app.session.activity.list().into_iter().filter(|r| r.kind == similar::KIND) { + // (a row that has just ended can't be stopped: nothing to do) + let _ = app.session.activity.cancel(row.id); + } +} diff --git a/crates/ui-egui/src/lens_db.rs b/crates/ui-egui/src/lens_db.rs new file mode 100644 index 0000000000..67933e7041 --- /dev/null +++ b/crates/ui-egui/src/lens_db.rs @@ -0,0 +1,259 @@ +//! The lens database on request: the first launch offers lensfun's database once (its size, Download / Not Now, +//! [`offer`]), Settings ▸ General can download it any time ([`download_default`]), and nothing is fetched without +//! that click (`lightcraft_engine::lensfun_download::fetch_on_start` decides; an activity row while it runs). +//! Whenever the database in use changes +//! (it arrived, a newer pin replaced it) or Enable Lens Corrections is ticked on a photo without a profile, the +//! library's raws that have none are looked up again on a worker thread (`lightcraft_engine::cmd::lens_refresh`); +//! when its files were replaced, so are those whose profile came from the database and those that named no lens. + +use lightcraft_engine::cmd::{lens_refresh, recheck}; +use lightcraft_engine::{lens_profiles, lensfun_download}; + +use crate::LightcraftApp; + +/// The activity stack's label while files are read for their lens. +pub const LABEL: &str = "Looking up lens profiles"; + +/// Called every frame. +pub fn tick(app: &mut LightcraftApp) { + start_download(app); + refresh(app); +} + +/// Once per run, what the start policy says ([`lensfun_download::fetch_on_start`]): offer the database, fetch it +/// (the user said yes before), or nothing. The offer waits for the window to be free (another dialog, the library +/// chooser). +fn start_download(app: &mut LightcraftApp) { + if app.ui.lens_download_checked { + return; + } + if !app.session.lens_auto_download { + app.ui.lens_download_checked = true; + return; + } + if app.ui.dialog.is_some() || crate::panels::library_problem::blocks_dialog_input(app) { + return; + } + app.ui.lens_download_checked = true; + let start = lensfun_download::fetch_on_start(app.session.lens_auto_download, app.ui.settings.lens_database); + begin(app, start, lensfun_download::mirrors()); +} + +/// Act on the start policy's answer, fetching from `mirrors`. The offer counts as answered once it is shown: closing +/// it any way but Download (Not Now, Esc) is "not now", and the next start doesn't ask again. +pub(crate) fn begin(app: &mut LightcraftApp, start: lensfun_download::Start, mirrors: Vec) { + match start { + lensfun_download::Start::Nothing => {} + lensfun_download::Start::Ask(dir) => { + app.ui.settings.lens_database = lensfun_download::Offer::Declined; + app.ui.dialog = Some(crate::state::Dialog::LensDatabase { dir: dir.to_string_lossy().into_owned(), mirrors }); + } + lensfun_download::Start::Fetch(dir) => { + if let Err(e) = download(app, &dir, mirrors) { + log::warn!("lens database: {e}"); + } + } + } +} + +/// Download the database into `dir` from `mirrors` (the offer's Download, Settings' button): remembered as the +/// user's yes, shown in the activity stack, and read once it is in place. +pub(crate) fn download(app: &mut LightcraftApp, dir: &std::path::Path, mirrors: Vec) -> Result<(), String> { + lens_refresh::start_download(&mut app.session, dir, mirrors, lensfun_download::FILES)?; + // a yes only once it started: a download that couldn't start isn't fetched again at the next start + app.ui.settings.lens_database = lensfun_download::Offer::Accepted; + Ok(()) +} + +/// Settings' Download Lens Database: into the app's own folder, from the usual mirrors. +pub fn download_default(app: &mut LightcraftApp) -> Result<(), String> { + let dir = lensfun_download::default_dir().ok_or("this computer has no folder for LightCraft's data")?; + download(app, &dir, lensfun_download::mirrors()) +} + +/// The offer's window: what the database does, its size, and that Settings has it later. +pub fn offer(ui: &mut egui::Ui) { + let t = crate::theme::Tokens::get(ui.ctx()); + ui.label(egui::RichText::new(crate::i18n::tr("Download lens profiles?")).strong()); + ui.add_space(4.0); + ui.add( + egui::Label::new(crate::i18n::tr_format!( + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).", + size = lensfun_download::download_megabytes() + )) + .wrap(), + ); + ui.add_space(4.0); + ui.add( + egui::Label::new( + egui::RichText::new(crate::i18n::tr("Nothing is downloaded until you choose Download. You can download it later from Settings.")) + .color(t.text_dim), + ) + .wrap(), + ); +} + +/// After Enable Lens Corrections was ticked on photo `id`: the photos to look up again, those of `id` and the +/// selection that now have corrections on and no profile. With Auto Sync off only `id` was changed, so the other +/// selected photos are left alone unless their corrections were already on. +pub fn to_look_up(session: &lightcraft_engine::Session, id: lightcraft_catalog::PhotoId) -> Vec { + let mut out: Vec = Vec::new(); + let mut seen = std::collections::HashSet::new(); + for t in std::iter::once(id).chain(session.selection.ids.iter().copied()) { + if seen.insert(t) && session.catalog.photo(t).is_some_and(|p| p.embedded_lens.is_none() && p.develop.optics.lens_profile) { + out.push(t); + } + } + out +} + +/// What a lookup's results belong to: the library, the lens database in use and how often its files were replaced. +/// Results for another key are stale. +pub(crate) fn lookup_key(app: &LightcraftApp) -> (u64, u64, u64) { + (app.session.library_generation(), lens_profiles::generation(), lens_profiles::replacements()) +} + +/// Whether this lookup also reads the photos that have a database profile or no lens name +/// ([`lens_refresh::missing`]'s `again`): only when the database's files were replaced since the last lookup, not at +/// every start or library switch. +pub(crate) fn look_up_again(last: Option<(u64, u64, u64)>, key: (u64, u64, u64)) -> bool { + last.map_or(key.2 > 0, |last| last.2 != key.2) +} + +/// Look the library's raws up again when the database changed, the library changed, or photos asked for it. +fn refresh(app: &mut LightcraftApp) { + let key = lookup_key(app); + let asked = std::mem::take(&mut app.ui.lens_lookup_ids); + if app.ui.lens_refreshed == Some(key) && asked.is_empty() { + return; + } + // (a lookup already under way finishes first; what was asked meanwhile waits for the next frame) + if app.tasks.is_running(LABEL) { + app.ui.lens_lookup_ids.extend(asked); + return; + } + let ids = (app.ui.lens_refreshed == Some(key)).then_some(asked); + let again = ids.is_none() && look_up_again(app.ui.lens_refreshed, key); + app.ui.lens_refreshed = Some(key); + let Some(probe) = recheck::file_probe(&app.session) else { return }; + let Some(db) = lens_profiles::database() else { return }; + let listed = lens_refresh::missing(&app.session.catalog, &db, ids.as_deref(), again); + if listed.is_empty() { + return; + } + let work = move || lens_refresh::probe(&probe, listed); + let done = move |app: &mut LightcraftApp, ctx: &egui::Context, results| { + // another library, or a database reloaded while the files were read (the probe may have used either): the + // next frame looks them up again with the database in use now (asked for here: an idle window draws none) + if lookup_key(app) != key { + ctx.request_repaint(); + return; + } + match lens_refresh::apply(&mut app.session, results) { + Ok(found) if found.len() == 1 => app.toast(ctx, crate::i18n::tr("1 photo got its lens profile")), + Ok(found) if found.len() > 1 => app.toast(ctx, crate::i18n::tr_format!("{n} photos got their lens profile", n = found.len())), + Ok(_) => {} + Err(e) => log::warn!("lens profile lookup: {e}"), + } + }; + if let Err(e) = crate::tasks::spawn(app, LABEL, Some("lensLookup"), work, done) { + log::warn!("{e}"); + } +} + +/// The database's name for a lens, remembered per lens and database (the panel asks every frame; a search scores +/// every lens in the database). +fn database_name(camera: &str, lens: &str) -> Option { + type Key = (String, String, u64); + thread_local! { + static LAST: std::cell::RefCell)>> = const { std::cell::RefCell::new(None) }; + } + let key = (camera.to_string(), lens.to_string(), lens_profiles::generation()); + LAST.with(|last| { + if let Some((k, name)) = last.borrow().as_ref() + && *k == key + { + return name.clone(); + } + let name = lens_profiles::database().and_then(|db| lens_profiles::profile_name(&db, camera, lens)); + *last.borrow_mut() = Some((key, name.clone())); + name + }) +} + +/// What the Optics panel says about photo `p`'s lens profile: which one is loaded and from where, or why there is +/// none. +pub fn readout(app: &LightcraftApp, p: &lightcraft_catalog::Photo) -> String { + use lightcraft_develop::LensSource; + match p.embedded_lens.map(|l| l.source) { + Some(LensSource::File) => crate::i18n::tr("Profile: from the file (the camera's own correction)").to_string(), + Some(LensSource::Database) => { + let name = database_name(&p.meta.camera, &p.meta.lens).unwrap_or_else(|| p.meta.lens.trim().to_string()); + crate::i18n::tr_format!("Profile: {} (lens database)", name) + } + None if app.session.lensfun.running() => crate::i18n::tr("Downloading the lens database…").to_string(), + None if matches!(app.session.lensfun.state(), lensfun_download::State::Failed(_)) && lens_profiles::database().is_none() => { + crate::i18n::tr("The lens database could not be downloaded. LightCraft tries again the next time it starts.").to_string() + } + None => match lens_refresh::no_profile_reason(p) { + Some(r) if p.meta.lens.trim().is_empty() => crate::i18n::tr(&r).to_string(), + Some(_) => crate::i18n::tr_format!("No lens profile found for {}.", p.meta.lens.trim()), + None => String::new(), + }, + } +} + +#[cfg(test)] +mod tests { + use crate::{LightcraftApp, Services}; + use lightcraft_develop::{EmbeddedLens, LensSource}; + + /// The Optics panel says which profile is loaded and from where, or why there is none. + #[test] + fn the_optics_readout_names_the_profile_or_the_lens_without_one() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let id = app.session.active().expect("a photo"); + let mut p = (**app.session.catalog.photo(id).expect("the photo")).clone(); + p.meta.lens = "EF35mm f/1.4L II USM".into(); + p.embedded_lens = None; + assert_eq!(super::readout(&app, &p), "No lens profile found for EF35mm f/1.4L II USM."); + p.meta.lens.clear(); + assert_eq!(super::readout(&app, &p), "This file names no lens."); + p.embedded_lens = Some(EmbeddedLens::default()); + assert_eq!(super::readout(&app, &p), "Profile: from the file (the camera's own correction)"); + p.meta.lens = "EF70-200mm f/2.8L IS II USM".into(); + p.embedded_lens = Some(EmbeddedLens { source: LensSource::Database, ..Default::default() }); + // the database's name for it, or the file's own without a database (LIGHTCRAFT_LENSFUN_DIR may be set) + let r = super::readout(&app, &p); + assert!(r.starts_with("Profile: ") && r.contains("70-200mm f/2.8L IS II USM") && r.ends_with(" (lens database)"), "{r}"); + } + + /// A first-run download that failed says so, instead of "no profile" for every lens. + #[test] + fn a_failed_download_is_named_in_the_optics_readout() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let id = app.session.active().expect("a photo"); + let mut p = (**app.session.catalog.photo(id).expect("the photo")).clone(); + p.meta.lens = "EF35mm f/1.4L II USM".into(); + p.embedded_lens = None; + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + let root = std::env::temp_dir().join(format!("lc-lens-db-failed-{}-{unique}", std::process::id())); + // (the download stages its files beside the database folder: both live in this test's own folder) + let dir = root.join("lensfun"); + // nothing listens on port 1: the download fails at once, without the network + let activity = app.session.activity.clone(); + app.session + .lensfun + .start(&dir, vec!["http://127.0.0.1:1/db".into()], lightcraft_engine::lensfun_download::FILES, &activity) + .expect("started"); + let t0 = std::time::Instant::now(); + while app.session.lensfun.running() && t0.elapsed() < std::time::Duration::from_secs(60) { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + assert!(matches!(app.session.lensfun.state(), lightcraft_engine::lensfun_download::State::Failed(_)), "{:?}", app.session.lensfun.state()); + if lightcraft_engine::lens_profiles::database().is_none() { + assert_eq!(super::readout(&app, &p), "The lens database could not be downloaded. LightCraft tries again the next time it starts."); + } + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7a67d87109..00311afd33 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -24,11 +24,13 @@ pub mod dialogs; pub mod docking; mod drop_overlay; pub mod export_task; +mod find_similar; mod focus_scan; mod frame_rate; pub mod headless; pub mod i18n; pub mod icons; +pub mod lens_db; pub mod lightroom_import; pub mod links; pub mod menus; @@ -545,7 +547,7 @@ pub fn is_model_file(path: &str) -> bool { /// Files dropped on the window that are presets rather than photos. pub fn is_preset_file(path: &str) -> bool { let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); - ["lcpreset", "lrtemplate", "xmp", "zip", "cube", "lmp", "mplumpack", "lceffect"].contains(&ext.as_str()) + ["lcpreset", "lrtemplate", "xmp", "zip", "cube", "dcp", "lmp", "mplumpack", "lceffect"].contains(&ext.as_str()) } /// Splits dropped files into presets and everything else. An `.xmp` dropped next to a photo with the same diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index ec9835a39f..730bde3df4 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -158,6 +158,10 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option paths, Err(answer) => return answer, }; + // .cube LUTs (and those inside zips / folders) become profiles, .dcp files camera profiles let lut_paths: Vec<&String> = paths .iter() .filter(|p| { let l = p.to_ascii_lowercase(); - l.ends_with(".cube") || l.ends_with(".zip") || std::path::Path::new(p.as_str()).is_dir() + l.ends_with(".cube") || l.ends_with(".dcp") || l.ends_with(".zip") || std::path::Path::new(p.as_str()).is_dir() }) .collect(); let mut news = ImportNews::default(); let profiles = if lut_paths.is_empty() { Value::Null } else { import_luts(app, &lut_paths, &mut news) }; - let preset_paths: Vec<&String> = paths.iter().filter(|p| !p.to_ascii_lowercase().ends_with(".cube")).collect(); + // (.dcp camera profiles went to profile.import above) + let preset_paths: Vec<&String> = paths + .iter() + .filter(|p| { + let l = p.to_ascii_lowercase(); + !l.ends_with(".cube") && !l.ends_with(".dcp") + }) + .collect(); let r = import_preset_files(app, &preset_paths, &mut news); toast_import_news(app, ctx, &news); r.map(|mut v| { diff --git a/crates/ui-egui/src/panels/compare.rs b/crates/ui-egui/src/panels/compare.rs index b7034f3a6d..d3f11733b8 100644 --- a/crates/ui-egui/src/panels/compare.rs +++ b/crates/ui-egui/src/panels/compare.rs @@ -277,14 +277,14 @@ fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slo if let Some(tex) = app.renderer.textures.get(&slot).filter(|x| x.photo == id) { let texture_aspect = tex.size[0].max(1) as f32 / tex.size[1].max(1) as f32; display = super::detail::fit_rect(img_area, texture_aspect, zoom, native, ppp, app.ui.pan); - p.image(tex.tex.id(), display, uv, Color32::WHITE); + p.image(tex.id(), display, uv, Color32::WHITE); if let Some(i) = window { draw_window(&p, app, i, id, photo.develop.hash64(), display); } } else if let Some(tex) = app.renderer.textures.get(&Slot::Thumb(id)) { let texture_aspect = tex.size[0].max(1) as f32 / tex.size[1].max(1) as f32; display = super::detail::fit_rect(img_area, texture_aspect, zoom, native, ppp, app.ui.pan); - p.image(tex.tex.id(), display, uv, Color32::WHITE); + p.image(tex.id(), display, uv, Color32::WHITE); } else { p.rect_filled(img.intersect(img_area), 0.0, t.skeleton); } @@ -452,7 +452,7 @@ fn draw_window(p: &egui::Painter, app: &LightcraftApp, pane: u8, id: PhotoId, lo let (fw, fh) = (tile.full.0.max(1) as f32, tile.full.1.max(1) as f32); let at = display.min + vec2(tile.window.x as f32 / fw * display.width(), tile.window.y as f32 / fh * display.height()); let dst = Rect::from_min_size(at, vec2(tile.window.w as f32 / fw * display.width(), tile.window.h as f32 / fh * display.height())); - p.image(tex.tex.id(), dst, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), dst, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } /// Per frame, before the central view is shown: Compare and Reference keep two photos' originals @@ -581,8 +581,9 @@ pub fn show_survey(app: &mut LightcraftApp, ui: &mut egui::Ui) { let _ = app.run("library.select", json!({"ids": [id.0]})); app.ui.view = ViewMode::Detail; } - // remove from the survey (deselect) on hover - if resp.hovered() && photos.len() > 1 { + // remove from the survey (deselect) on hover; the × stays while the pointer is on it, where + // the tile has lost its hover to the × (tied to `hovered()`, it vanished before a click landed) + if resp.contains_pointer() && photos.len() > 1 { let xr = Rect::from_min_size(pos2(img.right() - 26.0, img.top() + 6.0), vec2(20.0, 20.0)); let xresp = ui.interact(xr, egui::Id::unique(("survey-x", id.0)), Sense::click()).on_hover_text(crate::i18n::tr("Remove from survey")); crate::widgets::announce(&xresp, crate::i18n::tr("Remove from survey")); diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 116c35b08e..3e321304d2 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -442,7 +442,7 @@ fn draw_wipe_before(app: &LightcraftApp, p: &egui::Painter, id: PhotoId, img_rec let before_rect = fit_texture_rect(img_rect, tex.size); let u = ((line.x - before_rect.left()) / before_rect.width().max(1.0)).clamp(0.0, 1.0); let left = Rect::from_min_max(before_rect.min, pos2(before_rect.left() + u * before_rect.width(), before_rect.bottom())); - p.image(tex.tex.id(), left, Rect::from_min_max(pos2(0.0, 0.0), pos2(u, 1.0)), Color32::WHITE); + p.image(tex.id(), left, Rect::from_min_max(pos2(0.0, 0.0), pos2(u, 1.0)), Color32::WHITE); } if app.ui.before_after == BeforeAfter::SplitTopBottom && let Some(tex) = app.renderer.textures.get(&Slot::Before).filter(|t| t.photo == id) @@ -450,7 +450,7 @@ fn draw_wipe_before(app: &LightcraftApp, p: &egui::Painter, id: PhotoId, img_rec let before_rect = fit_texture_rect(img_rect, tex.size); let v = ((line.y - before_rect.top()) / before_rect.height().max(1.0)).clamp(0.0, 1.0); let top = Rect::from_min_max(before_rect.min, pos2(before_rect.right(), before_rect.top() + v * before_rect.height())); - p.image(tex.tex.id(), top, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, v)), Color32::WHITE); + p.image(tex.id(), top, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, v)), Color32::WHITE); } } @@ -795,14 +795,14 @@ fn draw_slot(app: &LightcraftApp, p: &egui::Painter, id: PhotoId, ppp: f32, slot return "none"; }; let image_rect = snap_fit_rect(fit_texture_rect(r, tex.size), tex.size, ppp); - p.with_clip_rect(clip).image(tex.tex.id(), image_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.with_clip_rect(clip).image(tex.id(), image_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); what } /// The hovered look's render over the photo, with its label. fn draw_hover(p: &egui::Painter, t: &Tokens, tex: &crate::render::Tex, label: &str, [img_rect, canvas]: [Rect; 2], badge_top_inset: f32) { let hover_rect = fit_texture_rect(img_rect, tex.size); - p.image(tex.tex.id(), hover_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), hover_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); let g = p.layout_no_wrap(label.to_string(), t.font(12.0), Color32::WHITE); let bg = label_badge_rect(hover_rect, canvas, g.size(), badge_top_inset); paint_badge(p, bg, g); diff --git a/crates/ui-egui/src/panels/detail/filmstrip.rs b/crates/ui-egui/src/panels/detail/filmstrip.rs index 52e9c8b25a..268d021b20 100644 --- a/crates/ui-egui/src/panels/detail/filmstrip.rs +++ b/crates/ui-egui/src/panels/detail/filmstrip.rs @@ -17,7 +17,7 @@ pub(super) fn navigator(app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Rect let p = ui.painter_at(canvas); p.rect_filled(frame.expand(5.0), 4.0, Color32::from_black_alpha(190)); match tex { - Some(t) => p.image(t.tex.id(), frame, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE), + Some(t) => p.image(t.id(), frame, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE), None => p.rect_filled(frame, 0.0, Tokens::get(ui.ctx()).skeleton), }; // the visible part of the photo, in normalized image coordinates @@ -131,7 +131,7 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { let [tw, th] = tex.size; let s = (img_area.width() / tw as f32).min(img_area.height() / th as f32); let fr = Rect::from_center_size(img_area.center(), vec2(tw as f32 * s, th as f32 * s)); - p.image(tex.tex.id(), fr, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), fr, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); crate::panels::grid::selection_ring(p, &t, fr, state); if app.ui.settings.film_badges && let Some(ph) = app.session.catalog.photo(*id) diff --git a/crates/ui-egui/src/panels/detail/geometry.rs b/crates/ui-egui/src/panels/detail/geometry.rs index d679010f17..b02c5eb9c1 100644 --- a/crates/ui-egui/src/panels/detail/geometry.rs +++ b/crates/ui-egui/src/panels/detail/geometry.rs @@ -3,12 +3,17 @@ use super::info::label_badge_rect; use super::{Affine, Frame, LightcraftApp, PhotoId, Point, Pos2, Rect, Zoom, json, pos2, vec2}; /// Screen ↔ normalized-image mapping for the displayed frame. -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct CanvasMap { pub(super) rect: Rect, to_norm: Affine, from_norm: Affine, k: f32, + /// The frame's lens / perspective warp (with the oriented size it works in), when it moves + /// pixels: a mask on the photo (`Mask::on_photo`) has its coordinates before it. + warp: Option>, + /// Whether `norm` / `screen` speak a mask's coordinates on the photo ([`CanvasMap::for_mask`]). + on_photo: bool, } impl CanvasMap { @@ -16,12 +21,47 @@ impl CanvasMap { let k = 8.0f32; let (w, h) = ((rect.width() * k).round().max(1.0) as usize, (rect.height() * k).round().max(1.0) as usize); let to_norm = frame.out_to_norm(w, h); - CanvasMap { rect, to_norm, from_norm: to_norm.inverse().unwrap_or(Affine::IDENTITY), k } + let warp = frame.warp.as_ref().filter(|w| w.moves_pixels()).map(|w| std::sync::Arc::new((w.clone(), frame.ow, frame.oh))); + CanvasMap { rect, to_norm, from_norm: to_norm.inverse().unwrap_or(Affine::IDENTITY), k, warp, on_photo: false } + } + /// The mapping for a mask's coordinates: on the photo before lens corrections, Upright and + /// Transform (`on_photo`, every mask made now), or an old mask's on the corrected frame. + pub(crate) fn for_mask(&self, on_photo: bool) -> CanvasMap { + CanvasMap { on_photo, ..self.clone() } + } + /// Whether `norm` / `screen` go through a lens or perspective warp (a mask's coordinates on a + /// warped photo). + pub(crate) fn warped(&self) -> bool { + self.on_photo && self.warp.is_some() + } + /// [`Self::for_mask`] for the mask `id` of `d` (none, or a new mask: on the photo). + pub(crate) fn for_mask_id(&self, d: &lightcraft_develop::DevelopSettings, id: Option) -> CanvasMap { + self.for_mask(id.and_then(|id| d.masks.iter().find(|m| m.id == id)).is_none_or(|m| m.on_photo)) } pub fn norm(&self, p: Pos2) -> Point { - self.to_norm.apply(Point::new(((p.x - self.rect.left()) * self.k) as f64, ((p.y - self.rect.top()) * self.k) as f64)) + let n = self.to_norm.apply(Point::new(((p.x - self.rect.left()) * self.k) as f64, ((p.y - self.rect.top()) * self.k) as f64)); + match self.warp.as_deref().filter(|_| self.on_photo) { + Some((w, ow, oh)) => { + let s = w.to_source(Point::new(n.x * ow, n.y * oh), 1); + Point::new(s.x / ow, s.y / oh) + } + None => n, + } } pub fn screen(&self, n: Point) -> Pos2 { + self.try_screen(n).unwrap_or_else(|| self.place(n)) + } + /// [`Self::screen`], or `None` where the warp can't be undone at `n` (a point a strong + /// warp folds away), for drawing that must not join such a point to its neighbours. + pub(crate) fn try_screen(&self, n: Point) -> Option { + let n = match self.warp.as_deref().filter(|_| self.on_photo) { + Some((w, ow, oh)) => w.from_source(Point::new(n.x * ow, n.y * oh)).map(|t| Point::new(t.x / ow, t.y / oh))?, + None => n, + }; + Some(self.place(n)) + } + /// A point on the displayed frame (normalized) on screen. + fn place(&self, n: Point) -> Pos2 { let q = self.from_norm.apply(n); pos2(self.rect.left() + q.x as f32 / self.k, self.rect.top() + q.y as f32 / self.k) } @@ -383,3 +423,96 @@ mod snap_tests { assert_eq!((bad.width(), bad.height()), (1088.0, 720.0)); } } + +#[cfg(test)] +mod mask_map_tests { + use super::*; + use lightcraft_develop::DevelopSettings; + + fn close(a: Point, b: Point) -> bool { + (a.x - b.x).abs() < 1e-4 && (a.y - b.y).abs() < 1e-4 + } + + /// Under a perspective warp, a mask's on-screen place goes into its coordinates on the photo + /// (`Mask::on_photo`) and back: the point clicked is the point the render puts the mask on, and + /// its handle draws where it was clicked. + #[test] + fn a_mask_drawn_on_a_warped_photo_lands_on_the_content_under_the_pointer() { + let mut d = DevelopSettings::default(); + d.geometry.vertical = 30.0; + d.geometry.rotate = 5.0; + let frame = Frame::new(400, 300, &d, true); + let m = CanvasMap::new(&frame, Rect::from_min_size(pos2(100.0, 50.0), vec2(400.0, 300.0))); + let q = pos2(220.0, 140.0); + let on = m.for_mask(true).norm(q); + let plain = m.for_mask(false).norm(q); + assert!(!close(on, plain), "the warp moves the photo under the frame: {on:?} {plain:?}"); + // the render maps the mask's coordinates through the warp to the same frame point + assert!(close(frame.for_mask(true).mask_to_norm(on), plain)); + assert!((m.for_mask(true).screen(on) - q).length() < 0.01, "and its handle draws there"); + // a new mask (no id) and a mask of today are on the photo; an old one isn't + let mut d = d.clone(); + d.masks.push(lightcraft_develop::Mask { id: 7, on_photo: false, ..Default::default() }); + assert!(close(m.for_mask_id(&d, None).norm(q), on)); + assert!(close(m.for_mask_id(&d, Some(7)).norm(q), plain)); + } + + /// A linear gradient's guides on a warped photo follow its bands through the warp: every + /// point drawn is on the band through the gradient's start or end (review of #3550). + #[test] + fn a_linear_gradients_guides_follow_the_warp() { + let mut d = DevelopSettings::default(); + d.geometry.vertical = 35.0; + d.optics.distortion = 50.0; + let frame = Frame::new(400, 300, &d, true); + let m = CanvasMap::new(&frame, Rect::from_min_size(pos2(100.0, 50.0), vec2(400.0, 300.0))).for_mask(true); + assert!(m.warped()); + let (start, end) = (Point::new(0.3, 0.3), Point::new(0.5, 0.6)); + // (long-edge units: the frame is 400 × 300) + let (sx, sy) = (1.0, 0.75); + let dd = ((end.x - start.x) * sx, (end.y - start.y) * sy); + let t = |q: Point| ((q.x - start.x) * sx * dd.0 + (q.y - start.y) * sy * dd.1) / (dd.0 * dd.0 + dd.1 * dd.1); + for (at, want) in [(start, 0.0), (end, 1.0)] { + let guide: Vec = super::super::masks::linear_guide(&m, start, end, at).concat(); + assert!(guide.len() > 2, "drawn in steps"); + let inside: Vec<&Pos2> = guide.iter().filter(|g| m.rect.expand(-2.0).contains(**g)).collect(); + assert!(inside.len() > 2, "the guide crosses the canvas: {}", inside.len()); + for g in inside { + let got = t(m.norm(*g)); + assert!((got - want).abs() < 1e-3, "{g:?}: band {got}, want {want}"); + } + } + } + + /// A guide is cut where a sample can't go through the warp, so no line joins a warped point + /// to an unwarped one (review of #3550). + #[test] + fn a_guide_breaks_where_the_warp_cant_be_undone() { + let (a, b, c) = (pos2(1.0, 1.0), pos2(2.0, 2.0), pos2(3.0, 3.0)); + let runs = super::super::masks::runs([Some(a), Some(b), None, Some(c), None, None, Some(a), Some(b)]); + assert_eq!(runs, vec![vec![a, b], vec![a, b]], "single points are dropped, the rest split"); + assert!(super::super::masks::runs([None, Some(a), None]).is_empty()); + // a chord far longer than the usual step (across a fold) cuts the run too + let line: Vec = (0..10).map(|i| pos2(i as f32, 0.0)).chain((0..10).map(|i| pos2(200.0 + i as f32, 0.0))).collect(); + let cut = super::super::masks::split_jumps(vec![line]); + assert_eq!(cut.len(), 2, "{cut:?}"); + assert!(cut.iter().all(|r| r.len() == 10)); + } + + /// A guide through an end far off the photo still crosses the canvas (review of #3550). + #[test] + fn a_guide_through_an_end_off_the_photo_still_crosses_it() { + let mut d = DevelopSettings::default(); + d.geometry.vertical = 35.0; + d.optics.distortion = 50.0; + let frame = Frame::new(400, 300, &d, true); + let m = CanvasMap::new(&frame, Rect::from_min_size(pos2(100.0, 50.0), vec2(400.0, 300.0))).for_mask(true); + // a gradient drawn off the photo's right side (start and end both there): its guides are + // horizontal and cross the photo from 2.5 photo widths away + let (start, end) = (Point::new(3.5, 0.4), Point::new(3.5, 0.6)); + for at in [start, end] { + let guide: Vec = super::super::masks::linear_guide(&m, start, end, at).concat(); + assert!(guide.iter().filter(|g| m.rect.expand(-2.0).contains(**g)).count() > 2, "{at:?}: the guide crosses the canvas"); + } + } +} diff --git a/crates/ui-egui/src/panels/detail/masks.rs b/crates/ui-egui/src/panels/detail/masks.rs index d8e789b7a0..2150d513b8 100644 --- a/crates/ui-egui/src/panels/detail/masks.rs +++ b/crates/ui-egui/src/panels/detail/masks.rs @@ -324,6 +324,8 @@ pub(super) fn mask_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &eg } for m in &d.masks { let sel = Some(m.id) == active; + // (its coordinates on the photo, or an old mask's on the corrected frame) + let map = &map.for_mask(m.on_photo); // Ctrl+Shift+O (`mask_overlay_all`) shows every visible mask's region; outline each one // too, not just the selected mask. Handles and the rotation grip stay on the selected // mask so nothing else becomes draggable. The component check keeps this in step with the @@ -416,11 +418,11 @@ fn component_outline( } MaskShape::Linear { start, end } => { let (a, b) = (map.screen(*start), map.screen(*end)); - let dir = (b - a).normalized(); - let perp = vec2(-dir.y, dir.x) * 3000.0; let (a1, a2): (u8, u8) = if sel { (230, 110) } else { (170, 80) }; - for (q, alpha) in [(a, a1), (b, a2)] { - p.line_segment([q - perp, q + perp], Stroke::new(1.0, Color32::from_white_alpha(alpha))); + for (at, alpha) in [(*start, a1), (*end, a2)] { + for run in linear_guide(map, *start, *end, at) { + p.add(egui::Shape::line(run, Stroke::new(1.0, Color32::from_white_alpha(alpha)))); + } } if sel { for (i, q) in [a, b].iter().enumerate() { @@ -434,11 +436,96 @@ fn component_outline( } } +/// A linear gradient's guide through `at` (its start or end): the line at right angles to it, as +/// screen points. In a mask's coordinates on the photo, a lens or perspective warp bends and +/// turns it on screen, so it is drawn through the warp in steps; else it is a straight line. +pub(super) fn linear_guide(map: &CanvasMap, start: Point, end: Point, at: Point) -> Vec> { + let (a, b) = (map.screen(start), map.screen(end)); + if !map.warped() { + let dir = (b - a).normalized(); + let perp = vec2(-dir.y, dir.x) * 3000.0; + let q = map.screen(at); + return vec![vec![q - perp, q + perp]]; + } + // in long-edge units the perpendicular is a right angle; it spans the whole photo + let l = frame_long_norm(map); + let d = ((end.x - start.x) / l.0, (end.y - start.y) / l.1); + let n = d.0.hypot(d.1); + if !(n.is_finite() && n > 1e-12) { + return Vec::new(); + } + let perp = (-d.1 / n * l.0, d.0 / n * l.1); + // from where the line enters the photo to where it leaves it (with a margin), measured from + // `at`, so a guide whose end lies off the photo still reaches it + let pp = perp.0 * perp.0 + perp.1 * perp.1; + let ts = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)].map(|(x, y)| ((x - at.x) * perp.0 + (y - at.y) * perp.1) / pp); + let (lo, hi) = ts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), t| (lo.min(*t), hi.max(*t))); + let pad = 0.1 * (hi - lo); + let (lo, hi) = (lo - pad, hi + pad); + if !(lo.is_finite() && hi.is_finite() && hi > lo) { + return Vec::new(); + } + // 48 steps across about a photo's width, at most 256 + let steps = ((hi - lo) * 16.0).ceil().clamp(48.0, 256.0) as usize; + split_jumps(runs((0..=steps).map(|i| { + let t = lo + (hi - lo) * i as f64 / steps as f64; + map.try_screen(Point::new(at.x + perp.0 * t, at.y + perp.1 * t)) + }))) +} + +/// `runs` cut again where a step is far longer than the run's usual one: a strong warp can fold +/// the line, and a chord across the fold isn't part of it. +pub(super) fn split_jumps(runs: Vec>) -> Vec> { + let mut out = Vec::new(); + for run in runs { + let mut steps: Vec = run.windows(2).filter_map(|w| Some(w.first()?.distance(*w.get(1)?))).collect(); + steps.sort_by(f32::total_cmp); + let usual = steps.get(steps.len() / 2).copied().unwrap_or(0.0); + let limit = (8.0 * usual).max(2.0); + let mut cur: Vec = Vec::new(); + for q in run { + if cur.last().is_some_and(|p: &Pos2| p.distance(q) > limit) { + if cur.len() >= 2 { + out.push(std::mem::take(&mut cur)); + } + cur.clear(); + } + cur.push(q); + } + if cur.len() >= 2 { + out.push(cur); + } + } + out +} + +/// The unbroken runs (two points or more) of a sampled line whose missing samples (`None`) cut it. +pub(super) fn runs(samples: impl IntoIterator>) -> Vec> { + let mut out: Vec> = Vec::new(); + let mut cur: Vec = Vec::new(); + for s in samples { + match s { + Some(q) => cur.push(q), + None => { + if cur.len() >= 2 { + out.push(std::mem::take(&mut cur)); + } + cur.clear(); + } + } + } + if cur.len() >= 2 { + out.push(cur); + } + out +} + /// Object selections (SAM 3) of the selected mask: each click, green to include, red to exclude /// (clicks still on their way to the model included). fn object_marks(app: &LightcraftApp, p: &egui::Painter, map: &CanvasMap, d: &DevelopSettings, active: Option) { let pending = app.session.segmenter.pending_clicks().cloned(); for m in d.masks.iter().filter(|m| Some(m.id) == active) { + let map = &map.for_mask(m.on_photo); for (k, c) in m.components.iter().enumerate() { if let MaskShape::Object { hint, exclude, .. } = &c.shape { let (hint, exclude) = match pending.as_ref().filter(|q| (q.mask, q.comp) == (m.id, k)) { @@ -503,7 +590,8 @@ fn object_tool( if own_pin_at(grips, app.session.active_mask, q) { return; } - let n = map.norm(q); + // (a click goes into the selected mask, or a new one: in its coordinates) + let n = map.for_mask_id(d, app.session.active_mask).norm(q); let exclude = ui.input(|i| i.modifiers.alt); match app.run_typed("mask.objectPoint", json!({"x": n.x, "y": n.y, "exclude": exclude})) { Ok(_) => { @@ -527,6 +615,8 @@ fn brush_tool( d: &DevelopSettings, ) { let active = app.session.active_mask; + // the stroke goes into the selected mask (or a new one): in its coordinates + let map = &map.for_mask_id(d, active); let long = (map.rect.width().max(map.rect.height())) as f64; let r = (app.ui.brush_size as f64 * long) as f32; if let Some(h) = resp.hover_pos() { @@ -635,6 +725,7 @@ fn grip_gestures( let m = d.masks.iter().find(|m| Some(m.id) == active)?; // Handles take precedence; otherwise grab the selected radial component under // the press, including components after the first in compound masks. + let map = &map.for_mask(m.on_photo); let at = map.norm(q); if let Some(ci) = m.components.iter().position(|c| radial_body_contains(&c.shape, at, map)) { return Some((m.id, ci, 0)); @@ -643,18 +734,25 @@ fn grip_gestures( matches!(m.components.first()?.shape, MaskShape::Linear { .. }).then_some((m.id, 0, 0)) }); if let Some((mask, comp, handle)) = grip - && let Some(original_shape) = d.masks.iter().find(|m| m.id == mask).and_then(|m| m.components.get(comp)).map(|c| c.shape.clone()) + && d.masks.iter().find(|m| m.id == mask).and_then(|m| m.components.get(comp)).is_some() { if Some(mask) != active { let _ = app.run("mask.select", json!({"id": mask})); } let _ = app.run("develop.beginInteraction", json!({"label": "Edit Mask"})); - app.gesture = Some(Gesture::MaskHandle { mask, comp, handle, original_shape }); + // (read after it begins: an old mask is on the photo from then on, in its coordinates) + if let Some(original_shape) = current_shape(app, mask, comp) + .or_else(|| d.masks.iter().find(|m| m.id == mask).and_then(|m| m.components.get(comp)).map(|c| c.shape.clone())) + { + app.gesture = Some(Gesture::MaskHandle { mask, comp, handle, original_shape }); + } } } if resp.dragged() && let (Some(Gesture::MaskHandle { mask, comp, handle, original_shape }), Some(q)) = (app.gesture.clone(), resp.interact_pointer_pos()) { + // (the live flag: the drag's first frame began the interaction, which put an old mask on the photo) + let map = ¤t_on_photo(app, mask).map_or_else(|| map.for_mask_id(d, Some(mask)), |on| map.for_mask(on)); let n = map.norm(q); let press_origin = ui.input(|i| i.pointer.press_origin()).unwrap_or(q); let n0 = map.norm(press_origin); @@ -692,6 +790,7 @@ fn mask_keys(app: &mut LightcraftApp, ui: &mut egui::Ui, map: &CanvasMap, d: &De for &(mid, ci, handle, q) in grips { let Some(m) = d.masks.iter().find(|m| m.id == mid) else { continue }; let Some(shape) = m.components.get(ci).map(|c| &c.shape) else { continue }; + let map = &map.for_mask(m.on_photo); let at = map.norm(q); let mask_name = if m.name.trim().is_empty() { format!("{} {mid}", crate::i18n::tr("Mask")) } else { m.name.clone() }; let name = mask_handle_name(&mask_name, shape, handle); @@ -703,17 +802,37 @@ fn mask_keys(app: &mut LightcraftApp, ui: &mut egui::Ui, map: &CanvasMap, d: &De if app.session.active_mask != Some(mid) { let _ = app.run("mask.select", json!({"id": mid})); } - let to = Point::new(at.x + dx, at.y + dy); - let new_shape = moved_shape(shape, handle, Point::new(dx, dy), to, map, false); let _ = app.run("develop.beginInteraction", json!({"label": "Edit Mask"})); + // (read after it begins: an old mask is on the photo from then on, in its coordinates) + let (shape, map) = match (current_shape(app, mid, ci), current_on_photo(app, mid)) { + (Some(s), Some(on)) => (s, map.for_mask(on)), + _ => (shape.clone(), map.clone()), + }; + let at = map.norm(q); + let to = Point::new(at.x + dx, at.y + dy); + let new_shape = moved_shape(&shape, handle, Point::new(dx, dy), to, &map, false); let _ = app.run("mask.update", json!({"id": mid, "component": ci, "shape": new_shape})); let _ = app.run("develop.endInteraction", json!({})); } } +/// The shape of component `comp` of mask `mask` of the active photo as the session has it now. +fn current_shape(app: &LightcraftApp, mask: u32, comp: usize) -> Option { + let d = app.session.develop_of(app.session.active()?)?; + d.masks.iter().find(|m| m.id == mask)?.components.get(comp).map(|c| c.shape.clone()) +} + +/// Whether mask `mask` of the active photo is on the photo now (`Mask::on_photo`). +fn current_on_photo(app: &LightcraftApp, mask: u32) -> Option { + let d = app.session.develop_of(app.session.active()?)?; + d.masks.iter().find(|m| m.id == mask).map(|m| m.on_photo) +} + /// Long-edge units → normalized units for x and y. fn frame_long_norm(map: &CanvasMap) -> (f64, f64) { - // derive from the mapping: 1 normalized unit in x and y in screen points + // derive from the mapping: 1 normalized unit in x and y in screen points (of the frame's + // proportions, which a lens or perspective warp doesn't change) + let map = map.for_mask(false); let o = map.screen(Point::new(0.0, 0.0)); let x = map.screen(Point::new(1.0, 0.0)).distance(o) as f64; let y = map.screen(Point::new(0.0, 1.0)).distance(o) as f64; diff --git a/crates/ui-egui/src/panels/detail/window.rs b/crates/ui-egui/src/panels/detail/window.rs index c9b78b5429..3351fab289 100644 --- a/crates/ui-egui/src/panels/detail/window.rs +++ b/crates/ui-egui/src/panels/detail/window.rs @@ -118,5 +118,5 @@ pub(super) fn draw_window(p: &egui::Painter, app: &LightcraftApp, c: &WindowCtx, let (fw, fh) = (tile.full.0 as f32, tile.full.1 as f32); let at = v.img.min + vec2(tile.window.x as f32 / fw * v.img.width(), tile.window.y as f32 / fh * v.img.height()); let dst = Rect::from_min_size(at, vec2(tile.window.w as f32 / fw * v.img.width(), tile.window.h as f32 / fh * v.img.height())); - p.image(tex.tex.id(), dst, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), dst, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index 31b1303bf5..632bad5cbb 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -19,6 +19,7 @@ use crate::widgets::{BAND_COLORS, SliderOut, divider, flyout_row, hex, register, mod curve; mod grading; +mod hdr_flow; mod histogram; mod mixer; mod sliders; @@ -152,7 +153,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { divider(ui); section(app, ui, &d, "light", "Light", |app, ui, d| { - hdr_row(app, ui, d); + hdr_row(app, ui, d, id); for c in ["light.exposure", "light.contrast", "light.highlights", "light.shadows", "light.whites", "light.blacks"] { control(app, ui, d, c, true); } @@ -318,12 +319,20 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { } let mut lp = d.optics.lens_profile; if ui.checkbox(&mut lp, crate::i18n::tr("Enable Lens Corrections")).changed() { - let _ = app.run("develop.merge", json!({"settings": {"optics": {"lens_profile": lp}}, "label": "Lens Corrections"})); + let ok = app.run("develop.merge", json!({"settings": {"optics": {"lens_profile": lp}}, "label": "Lens Corrections"})).is_ok(); + // ticked on photos without a profile: look their lenses up again (a database that arrived + // since they were imported may know them now) + if ok && lp { + let without = crate::lens_db::to_look_up(&app.session, id); + app.ui.lens_lookup_ids.extend(without); + } } - if lp && !has_lens { - ui.label( - egui::RichText::new(crate::i18n::tr("No lens data embedded in this file.")).size(11.0).color(Tokens::get(ui.ctx()).text_dim), - ); + if lp && let Some(p) = app.session.catalog.photo(id).cloned() { + let text = crate::lens_db::readout(app, &p); + if !text.is_empty() { + let r = ui.label(egui::RichText::new(text).size(11.0).color(Tokens::get(ui.ctx()).text_dim)); + crate::widgets::register(ui, "optics:lensProfile", r.rect); + } } }); if d.optics.lens_profile { diff --git a/crates/ui-egui/src/panels/edit/hdr_flow.rs b/crates/ui-egui/src/panels/edit/hdr_flow.rs new file mode 100644 index 0000000000..a9ddb7233a --- /dev/null +++ b/crates/ui-egui/src/panels/edit/hdr_flow.rs @@ -0,0 +1,319 @@ +//! The Edit panel's flow between SDR and HDR: pressing HDR moves the histogram and the HDR settings +//! to their new layout instead of swapping it in one frame. + +use lightcraft_raster::HdrBins; + +use super::{Color32, Histogram, Mesh, PhotoId, Pos2, Rect, Stroke, Vertex, hex, pos2, vec2}; + +/// How long the histogram and the HDR settings take to flow between their SDR and HDR layouts. +const FLOW_SECS: f32 = 0.45; + +pub(super) fn hdr_histogram_key(id: PhotoId) -> egui::Id { + egui::Id::unique(("hdrHistogram", id)) +} + +/// The photo's last SDR histogram, kept to draw the way back from the HDR layout and into it. +pub(super) fn sdr_histogram_key(id: PhotoId) -> egui::Id { + egui::Id::unique(("sdrHistogram", id)) +} + +/// The histogram on its way between its layouts this frame. Entering HDR squeezes the SDR curve into +/// the HDR histogram's SDR section while the HDR section opens beside it (and the legend row slides +/// open under the plot); leaving stretches it back. The last histogram of each kind is kept so both +/// ends can be drawn on the way. +pub(super) struct LayoutFlow { + /// 0 (the SDR layout) to 1 (the HDR layout), eased. + pub morph: f32, + bins: Option, + sdr: Option, + hdr: Option, +} + +impl LayoutFlow { + /// The flow towards the layout of `hist`, the histogram shown this frame. + pub fn of(ctx: &egui::Context, id: PhotoId, hist: Option<&Histogram>) -> Self { + let showing_hdr = hist.is_some_and(|h| h.hdr.is_some()); + let morph = + egui::emath::easing::cubic_in_out(ctx.animate_bool_with_time(egui::Id::unique(("histogramHdrLayout", id)), showing_hdr, FLOW_SECS)); + let hdr = if showing_hdr { + hist.cloned() + } else if morph > 0.0 { + ctx.data(|d| d.get_temp::(hdr_histogram_key(id))) + } else { + None + }; + let sdr = if !showing_hdr { + hist.cloned() + } else if morph < 1.0 { + ctx.data(|d| d.get_temp::(sdr_histogram_key(id))) + } else { + None + }; + let bins = hdr.as_ref().and_then(|h| h.hdr); + Self { morph: if bins.is_some() { morph } else { 0.0 }, bins, sdr, hdr } + } + + /// The HDR section's bins, while any of it is showing. + pub fn hdr_bins(&self) -> Option { + self.bins.filter(|_| self.morph > 0.0) + } + + /// The histogram being left, drawn alone mid-way when there is none of the new kind yet. + pub fn leaving(&self) -> Option { + self.hdr.clone().filter(|_| self.morph > 0.0) + } + + /// The first HDR bin: where the HDR histogram's SDR section ends. + fn from(&self) -> f32 { + self.bins.map_or(255.0, |b| b.from as f32) + } + + /// SDR white across `plot`: its right edge in SDR, the HDR layout's split in HDR. + pub fn sdr_white_x(&self, plot: Rect) -> f32 { + plot.left() + plot.width() * sdr_white_at(self.from(), self.morph) + } + + /// The curve, one through both layouts: the SDR section's heights morph from the SDR histogram's + /// to the HDR histogram's SDR bins as it narrows to SDR white, and the HDR bins fill the rest. + /// `shown` decides greyscale, whose three channels coincide: one neutral line is drawn. + pub fn paint_curve(&self, p: &egui::Painter, plot: Rect, shown: &Histogram) { + let sdr = self.sdr.as_ref().map(histogram_heights); + let hdr = self.hdr.as_ref().filter(|_| self.bins.is_some()).map(histogram_heights); + let pts = morph_curve(sdr.as_ref(), hdr.as_ref(), self.from(), self.morph); + let to = |x: f32, v: f32| pos2(plot.left() + plot.width() * x, plot.bottom() - plot.height() * v); + // luminance fill + let mut mesh = Mesh::default(); + for (i, (x, hs)) in pts.iter().enumerate() { + let top = to(*x, hs[0]); + mesh.vertices.push(Vertex { pos: top, uv: Pos2::ZERO, color: Color32::from_gray(120).gamma_multiply(0.35) }); + mesh.vertices.push(Vertex { pos: pos2(top.x, plot.bottom()), uv: Pos2::ZERO, color: Color32::from_gray(120).gamma_multiply(0.35) }); + if i > 0 { + let k = (i as u32) * 2; + mesh.indices.extend([k - 2, k - 1, k, k - 1, k + 1, k]); + } + } + p.add(mesh); + let line = |j: usize, c: Color32| egui::Shape::line(pts.iter().map(|(x, hs)| to(*x, hs[j])).collect(), Stroke::new(1.5, c)); + if is_greyscale(shown) { + p.add(line(2, Color32::from_gray(200))); + } else { + for (j, c) in [(1, hex("#df3939")), (2, hex("#44b072")), (3, hex("#3b6fe0"))] { + p.add(line(j, c)); + } + } + } +} + +/// SDR white across the plot (0..1), `morph` of the way to the HDR layout where it sits at bin `from`. +fn sdr_white_at(from: f32, morph: f32) -> f32 { + 1.0 + (from / 255.0 - 1.0) * morph +} + +/// A histogram's display heights per bin for luma, R, G and B: smoothed over 5 bins, then +/// square-root scaled against the R/G/B peak (the end bins left out) and capped at 1. +fn histogram_heights(h: &Histogram) -> [Vec; 4] { + let smooth = |v: &[u32]| -> Vec { + (0..256) + .map(|i: usize| { + let (a, b) = (i.saturating_sub(2), (i + 3).min(v.len())); + let w = v.get(a..b).unwrap_or_default(); + w.iter().map(|x| *x as f32).sum::() / w.len().max(1) as f32 + }) + .collect() + }; + let [l, r, g, b] = [smooth(&h.luma), smooth(&h.r), smooth(&h.g), smooth(&h.b)]; + let peak = [&r, &g, &b].iter().flat_map(|v| v.iter().skip(2).take(252)).fold(1.0f32, |a, b| a.max(*b)); + [l, r, g, b].map(|v| v.into_iter().map(|x| (x / peak).sqrt().min(1.0)).collect()) +} + +/// `v` at fractional bin `x`, linearly interpolated (clamped to its ends). +fn sample(v: &[f32], x: f32) -> f32 { + let x = x.clamp(0.0, v.len().saturating_sub(1) as f32); + let i = x.floor() as usize; + let (a, b) = (v.get(i).copied().unwrap_or(0.0), v.get(i + 1).or(v.get(i)).copied().unwrap_or(0.0)); + a + (b - a) * (x - i as f32) +} + +/// A greyscale image's histogram: its three channels coincide. +fn is_greyscale(h: &Histogram) -> bool { + let spread: f32 = h.r.iter().zip(&h.g).zip(&h.b).map(|((r, g), b)| (*r as f32 - *g as f32).abs() + (*g as f32 - *b as f32).abs()).sum(); + spread / (h.g.iter().map(|x| *x as f32).sum::().max(1.0)) < 0.02 +} + +/// The histogram curve `morph` of the way from the SDR layout (0) to the HDR one (1), as +/// (x across the plot 0..1, heights for luma, R, G, B). Left of SDR white ([`sdr_white_at`]), the SDR +/// histogram's heights morph into the HDR histogram's SDR bins (`0..from`); right of it, the HDR +/// bins fill what has opened. Either histogram may be missing: the other is drawn alone. +fn morph_curve(sdr: Option<&[Vec; 4]>, hdr: Option<&[Vec; 4]>, from: f32, morph: f32) -> Vec<(f32, [f32; 4])> { + let x0 = sdr_white_at(from, morph); + let mut pts: Vec<(f32, [f32; 4])> = (0..=255) + .map(|k| { + let u = k as f32 / 255.0; + let hs = std::array::from_fn(|j| match (sdr, hdr) { + (Some(s), Some(c)) => { + let (a, z) = (sample(&s[j], u * 255.0), sample(&c[j], u * from)); + a + (z - a) * morph + } + (Some(s), None) => sample(&s[j], u * 255.0), + (None, Some(c)) => sample(&c[j], u * from), + (None, None) => 0.0, + }); + (x0 * u, hs) + }) + .collect(); + if let Some(c) = hdr.filter(|_| morph > 0.0) { + let n = (255.0 - from).max(1.0) as usize; + pts.extend((1..=n).map(|k| { + let u = k as f32 / n as f32; + (x0 + (1.0 - x0) * u, std::array::from_fn(|j| sample(&c[j], from + u * (255.0 - from)))) + })); + } + pts +} + +/// `body` as a drawer sliding open (`open`) or shut over [`FLOW_SECS`], eased like the histogram: its +/// height grows from 0 to its full height, the rows below move with its edge, and the content slides +/// down from under the row above (clipped there: nothing past the edge is drawn or clickable). Fully +/// shut, `body` doesn't run. +pub(super) fn drawer(ui: &mut egui::Ui, id: egui::Id, open: bool, body: impl FnOnce(&mut egui::Ui)) { + let t = egui::emath::easing::cubic_in_out(ui.ctx().animate_bool_with_time(id, open, FLOW_SECS)); + if t <= 0.0 { + return; + } + // the height measured last frame (0 before the first: that frame draws nothing and measures) + let full = ui.ctx().data(|d| d.get_temp::(id)).unwrap_or(0.0); + let avail = ui.available_rect_before_wrap(); + let top = avail.top(); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(avail.translate(vec2(0.0, -full * (1.0 - t)))).layout(*ui.layout())); + if t < 1.0 { + child.shrink_clip_rect(Rect::from_min_max(pos2(avail.left(), top), pos2(avail.right(), top + full * t))); + } + body(&mut child); + let measured = child.min_rect().height(); + ui.ctx().data_mut(|d| d.insert_temp(id, measured)); + ui.advance_cursor_after_rect(Rect::from_min_size(pos2(avail.left(), top), vec2(child.min_rect().width(), measured * t))); + // the spacing after it grows with it too, so nothing below jumps when it starts or ends + ui.add_space(-ui.spacing().item_spacing.y * (1.0 - t)); +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::Sense; + + /// The whole panel, frame by frame: the HDR button's layout change moves the histogram's height + /// and the sliders below in small steps, both ways, and ends at the same layout it left. + #[test] + fn pressing_hdr_moves_the_panel_instead_of_swapping_its_layout() { + use crate::headless::Headless; + use crate::{LightcraftApp, Services}; + use serde_json::json; + use std::time::{Duration, Instant}; + + let widget = |h: &Headless, id: &str| h.app.widgets.iter().rev().find(|(w, _)| w == id).map(|(_, r)| *r); + // (the histogram's height, the Exposure slider's top) at each frame until both reach `end` + let run = |h: &mut Headless, on: bool, end: Option| { + h.app.run("develop.hdr", json!({"enabled": on})).expect("develop.hdr"); + let (t0, mut trail) = (Instant::now(), Vec::new()); + let mut still = 0; + while t0.elapsed() < Duration::from_secs(120) && still < 60 { + h.step(); + std::thread::sleep(Duration::from_millis(1)); + let at = |id| widget(h, id).unwrap_or_else(|| panic!("no widget {id}")); + let now = (at("histogram").height(), at("slider:light.exposure").top()); + still = if trail.last() == Some(&now) && end.is_none_or(|e| now.0 == e) { still + 1 } else { 0 }; + trail.push(now); + } + trail + }; + let moved = |v: &[f32]| -> (usize, f32) { + let (lo, hi) = (v.iter().copied().fold(f32::MAX, f32::min), v.iter().copied().fold(f32::MIN, f32::max)); + let steps = v.iter().filter(|x| **x > lo && **x < hi).count(); + (steps, v.windows(2).map(|w| (w[1] - w[0]).abs()).fold(0.0, f32::max) / (hi - lo).max(1.0)) + }; + + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1400.0, 1000.0], 1.0); + let r = h.request("ui.set", json!({"view": "detail", "right": "edit", "openSections": ["light"]}), Duration::from_secs(20)); + assert_eq!(r["ok"], true, "{r}"); + h.settle(Duration::from_secs(120)); + let (sdr_h, sdr_y) = (widget(&h, "histogram").expect("histogram").height(), widget(&h, "slider:light.exposure").expect("exposure").top()); + + let on = run(&mut h, true, Some(sdr_h + 26.0)); + let off = run(&mut h, false, Some(sdr_h)); + for (name, trail) in [("on", &on), ("off", &off)] { + let heights: Vec = trail.iter().map(|t| t.0).collect(); + let tops: Vec = trail.iter().map(|t| t.1).collect(); + let (h_steps, h_jump) = moved(&heights); + let (y_steps, y_jump) = moved(&tops); + assert!(h_steps >= 4 && h_jump < 0.5, "{name}: the histogram's height jumped: {heights:?}"); + assert!(y_steps >= 4 && y_jump < 0.5, "{name}: the sliders jumped: {tops:?}"); + } + assert_eq!(on.last().map(|t| t.0), Some(sdr_h + 26.0), "the legend row opened"); + assert_eq!(off.last().copied(), Some((sdr_h, sdr_y)), "back where it started"); + } + + #[test] + fn the_hdr_settings_slide_open_and_shut() { + let ctx = egui::Context::default(); + let id = egui::Id::unique("drawer"); + // the height the drawer takes in the layout at each frame + let frame = |time: f64, open: bool| { + let mut height = 0.0; + let input = egui::RawInput { time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + let top = ui.cursor().top(); + drawer(ui, id, open, |ui| { + ui.allocate_exact_size(vec2(100.0, 40.0), Sense::hover()); + }); + height = ui.cursor().top() - top; + }); + out.textures_delta.clear(); + height + }; + // shut from the start: nothing; opened: it grows a little each frame up to its height + assert_eq!(frame(0.0, false), 0.0); + let opening: Vec = (1..=15).map(|k| frame(k as f64 * 0.05, true)).collect(); + assert!(opening.windows(2).all(|w| w[1] >= w[0]), "{opening:?}"); + assert!(opening.iter().filter(|h| **h > 0.0 && **h < 40.0).count() >= 4, "{opening:?}"); + assert!(opening[0] < 3.0, "no jump as it starts: {opening:?}"); + let spaced = 40.0 + ctx.global_style().spacing.item_spacing.y; + assert_eq!(opening.last(), Some(&spaced)); + // and shrinks back the same way + let closing: Vec = (16..=30).map(|k| frame(k as f64 * 0.05, false)).collect(); + assert!(closing.windows(2).all(|w| w[1] <= w[0]), "{closing:?}"); + assert!(closing.iter().filter(|h| **h > 0.0 && **h < 40.0).count() >= 4, "{closing:?}"); + assert_eq!(closing.last(), Some(&0.0)); + } + + #[test] + fn the_histogram_flows_between_its_sdr_and_hdr_layouts() { + let flat = |v: f32| -> [Vec; 4] { std::array::from_fn(|_| vec![v; 256]) }; + let (sdr, hdr) = (flat(0.2), flat(0.6)); + let from = 128.0; + let x_of = |pts: &[(f32, [f32; 4])]| pts.iter().map(|p| p.0).collect::>(); + // SDR: the SDR histogram across the whole plot, no HDR section + let pts = morph_curve(Some(&sdr), Some(&hdr), from, 0.0); + assert_eq!(pts.len(), 256); + assert!(pts.iter().all(|p| (p.1[0] - 0.2).abs() < 1e-6)); + assert_eq!(pts.last().map(|p| p.0), Some(1.0)); + // half way: the SDR section squeezed half way to SDR white, its heights half morphed, + // the HDR section opened beside it, joined without a gap + let pts = morph_curve(Some(&sdr), Some(&hdr), from, 0.5); + let x0 = sdr_white_at(from, 0.5); + assert!((pts[255].0 - x0).abs() < 1e-6); + assert!((pts[100].1[2] - 0.4).abs() < 1e-6); + assert!((pts[256].1[2] - 0.6).abs() < 1e-6 && pts[256].0 > x0); + let xs = x_of(&pts); + assert!(xs.windows(2).all(|w| w[1] > w[0] && w[1] - w[0] < 0.02), "one continuous curve"); + assert_eq!(xs.last(), Some(&1.0)); + // HDR: the HDR histogram alone, SDR white at its bin + let pts = morph_curve(Some(&sdr), Some(&hdr), from, 1.0); + assert!((pts[255].0 - from / 255.0).abs() < 1e-6); + assert!(pts.iter().all(|p| (p.1[0] - 0.6).abs() < 1e-6)); + // a missing end draws the other alone + assert!(morph_curve(None, Some(&hdr), from, 0.3).iter().all(|p| (p.1[1] - 0.6).abs() < 1e-6)); + assert_eq!(morph_curve(Some(&sdr), None, from, 0.0).len(), 256); + assert_eq!((sample(&[0.0, 1.0], 0.25), sample(&[0.0, 1.0], 9.0), sample(&[], 1.0)), (0.25, 1.0, 0.0)); + } +} diff --git a/crates/ui-egui/src/panels/edit/histogram.rs b/crates/ui-egui/src/panels/edit/histogram.rs index df21b1d798..875053ce8f 100644 --- a/crates/ui-egui/src/panels/edit/histogram.rs +++ b/crates/ui-egui/src/panels/edit/histogram.rs @@ -1,8 +1,9 @@ +use super::hdr_flow::{LayoutFlow, hdr_histogram_key, sdr_histogram_key}; #[cfg(test)] use super::sliders::reset_tip; use super::{ - Align2, Color32, Histogram, Icon, LightcraftApp, Mesh, PhotoId, Pos2, Rect, RichText, RightPanel, Sense, Slot, Stroke, Tokens, Vertex, divider, - hex, json, paint, pos2, register, vec2, + Align2, Color32, Histogram, Icon, LightcraftApp, PhotoId, Rect, RichText, RightPanel, Sense, Slot, Stroke, Tokens, divider, json, paint, pos2, + register, vec2, }; // ------------------------------------------------------------------------------ histogram @@ -20,16 +21,21 @@ pub(super) fn preview_histogram(app: &LightcraftApp, id: PhotoId) -> Option) -> Option { - let key = egui::Id::unique(("hdrHistogram", id)); + let (hdr_key, sdr_key) = (hdr_histogram_key(id), sdr_histogram_key(id)); match hist { Some(h) if h.hdr.is_some() => { - ctx.data_mut(|d| d.insert_temp(key, h.clone())); - Some(h) + ctx.data_mut(|d| d.insert_temp(hdr_key, h.clone())); + if hdr_edit { Some(h) } else { ctx.data(|d| d.get_temp::(sdr_key)) } } - h if hdr_edit => ctx.data(|d| d.get_temp::(key)).or(h), - h => h, + Some(h) => { + ctx.data_mut(|d| d.insert_temp(sdr_key, h.clone())); + if hdr_edit { ctx.data(|d| d.get_temp::(hdr_key)).or(Some(h)) } else { Some(h) } + } + None if hdr_edit => ctx.data(|d| d.get_temp::(hdr_key)), + None => None, } } @@ -62,10 +68,12 @@ pub(crate) fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) // rendered it) let hist = live.or_else(|| preview_histogram(app, id)); let hist = steady_hdr_histogram(ui.ctx(), id, hdr_edit, hist); + // the SDR ⇄ HDR layout change flows instead of cutting + let flow = LayoutFlow::of(ui.ctx(), id, hist.as_ref()); // an HDR edit's histogram (`pipeline::hdr_histogram`) gets a colour bar and an SDR / HDR label // row under the plot - let hdr = hist.as_ref().and_then(|h| h.hdr); - let legend = if hdr.is_some() { 26.0 } else { 0.0 }; + let hdr = flow.hdr_bins(); + let legend = 26.0 * flow.morph; let (r, resp) = ui.allocate_exact_size(vec2(w, 118.0 + legend), Sense::click_and_drag()); crate::widgets::announce(&resp, crate::i18n::tr("Histogram")); register(ui, "histogram", r); @@ -79,10 +87,11 @@ pub(crate) fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) if let Some(a) = &zone { crate::panels::histogram::paint_zone(p, plot, a, &t); } + let x0 = flow.sdr_white_x(plot); if let Some(b) = hdr { // white for SDR, then one band per stop above SDR white: white too, or (Visualize HDR - // range on) in its colours - let x0 = plot.left() + plot.width() * b.from as f32 / 255.0; + // range on) in its colours; the row is revealed as it opens + let p = &p.with_clip_rect(Rect::from_min_max(pos2(r.left(), plot.bottom()), pos2(r.right(), plot.bottom() + legend))); let bar = |a: f32, z: f32, c: Color32| p.rect_filled(Rect::from_min_max(pos2(a, plot.bottom() + 2.0), pos2(z, plot.bottom() + 7.0)), 0.0, c); let white = Color32::from_rgb(228, 228, 230); bar(plot.left(), x0 - 1.0, white); @@ -104,18 +113,10 @@ pub(crate) fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) )); } let clipping = hist.as_ref().map(|h| h.clipping()); - if let Some(h) = hist { - let smooth = |v: &[u32]| -> Vec { - (0..256) - .map(|i| { - let (a, b) = (i.max(2) - 2, (i + 3).min(256)); - v[a..b].iter().map(|x| *x as f32).sum::() / (b - a) as f32 - }) - .collect() - }; - // HDR: SDR on the left half, a solid line at SDR white and dashed ones between the stops - if let Some(b) = h.hdr { - let x0 = plot.left() + plot.width() * b.from as f32 / 255.0; + // mid-way with no histogram of the new kind yet, the one being left is drawn alone + if let Some(h) = hist.or_else(|| flow.leaving()) { + // HDR: SDR on the left, a solid line at SDR white and dashed ones between the stops + if let Some(b) = hdr { let stops = b.stops.round().max(1.0) as usize; for k in 1..stops { let x = x0 + (plot.right() - x0) * k as f32 / stops as f32; @@ -134,34 +135,7 @@ pub(crate) fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) p.line_segment([pos2(x, plot.top()), pos2(x, plot.bottom())], Stroke::new(1.0, Color32::from_rgb(230, 150, 60))); } } - let chans = [(smooth(&h.r), hex("#df3939")), (smooth(&h.g), hex("#44b072")), (smooth(&h.b), hex("#3b6fe0"))]; - let peak = chans.iter().flat_map(|(v, _)| v.iter().skip(2).take(252)).fold(1.0f32, |a, b| a.max(*b)); - let to = |i: usize, v: f32| pos2(plot.left() + plot.width() * i as f32 / 255.0, plot.bottom() - plot.height() * (v / peak).sqrt().min(1.0)); - // luminance fill - let lum = smooth(&h.luma); - let mut mesh = Mesh::default(); - for i in 0..256 { - let top = to(i, lum[i]); - mesh.vertices.push(Vertex { pos: top, uv: Pos2::ZERO, color: Color32::from_gray(120).gamma_multiply(0.35) }); - mesh.vertices.push(Vertex { pos: pos2(top.x, plot.bottom()), uv: Pos2::ZERO, color: Color32::from_gray(120).gamma_multiply(0.35) }); - if i > 0 { - let k = (i as u32) * 2; - mesh.indices.extend([k - 2, k - 1, k, k - 1, k + 1, k]); - } - } - p.add(mesh); - // greyscale images: the three channels coincide — draw one neutral line - let spread: f32 = (0..256).map(|i| (chans[0].0[i] - chans[1].0[i]).abs() + (chans[1].0[i] - chans[2].0[i]).abs()).sum(); - let total: f32 = chans[1].0.iter().sum::().max(1.0); - if spread / total < 0.02 { - let pts: Vec = (0..256).map(|i| to(i, chans[1].0[i])).collect(); - p.add(egui::Shape::line(pts, Stroke::new(1.5, Color32::from_gray(200)))); - } else { - for (v, c) in &chans { - let pts: Vec = (0..256).map(|i| to(i, v[i])).collect(); - p.add(egui::Shape::line(pts, Stroke::new(1.5, *c))); - } - } + flow.paint_curve(p, plot, &h); } let mut clicked = resp.clicked(); // both buttons keep clear of the panel's right edge, where its floating scroll bar widens when @@ -363,6 +337,10 @@ mod tests { assert_eq!(steady_hdr_histogram(&ctx, id, true, Some(sdr.clone())), Some(hdr(4.0))); // HDR turned off: the SDR histogram at once; other photos keep their own assert_eq!(steady_hdr_histogram(&ctx, id, false, Some(sdr.clone())), Some(sdr.clone())); + // an SDR edit never shows an HDR histogram (a stale thumbnail's): its last SDR one instead, + // or none yet + assert_eq!(steady_hdr_histogram(&ctx, id, false, Some(hdr(4.0))), Some(sdr.clone())); + assert_eq!(steady_hdr_histogram(&ctx, PhotoId(9), false, Some(hdr(4.0))), None); assert_eq!(steady_hdr_histogram(&ctx, PhotoId(8), true, Some(sdr.clone())), Some(sdr)); } diff --git a/crates/ui-egui/src/panels/edit/sliders.rs b/crates/ui-egui/src/panels/edit/sliders.rs index 78a402087e..2a6a3a13eb 100644 --- a/crates/ui-egui/src/panels/edit/sliders.rs +++ b/crates/ui-egui/src/panels/edit/sliders.rs @@ -116,17 +116,21 @@ fn profile_menu_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSett crate::menu_level::set_anchor(ui.ctx(), 2, r.response.rect); } } - // imported LUT profile groups - let mut lut_groups: Vec = app.session.lut_profiles.iter().map(|p| p.group.clone()).collect(); - lut_groups.sort_unstable(); - lut_groups.dedup(); + // imported profile groups: LUT folders, then camera profiles + let imported = app.session.imported_profiles(); + let mut lut_groups: Vec = Vec::new(); + for (_, _, g) in &imported { + if !lut_groups.contains(g) { + lut_groups.push(g.clone()); + } + } for g in &lut_groups { // a folder's name as it is, and its own widget id even when it matches a built-in group let r = crate::widgets::menu_button(ui, g.as_str(), |ui| { crate::menu_level::level(ui, 2, Some(below), |ui| { ui.set_min_width(170.0); - for p in app.session.lut_profiles.iter().filter(|p| &p.group == g) { - item(ui, "group", &p.id, &p.name, &mut pick); + for (id, name, _) in imported.iter().filter(|p| &p.2 == g) { + item(ui, "group", id, name, &mut pick); } }); }); @@ -214,13 +218,14 @@ pub(super) fn section( // ------------------------------------------------------------------------------ HDR -/// The Light panel's HDR row: the HDR switch and Visualize HDR, then (HDR on) the headroom limit. /// The Light panel's HDR settings while HDR editing is on (the switch itself is the HDR button -/// next to B&W): Visualize HDR range and the headroom limit. -pub(super) fn hdr_row(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) { - if !d.hdr.enabled { - return; - } +/// next to B&W): Visualize HDR range and the headroom limit. They slide open and shut with the +/// histogram's change of layout; another photo shows its own at once. +pub(super) fn hdr_row(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings, id: PhotoId) { + super::hdr_flow::drawer(ui, egui::Id::unique(("hdrSettings", id)), d.hdr.enabled, |ui| hdr_settings(app, ui, d)); +} + +fn hdr_settings(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) { egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 4, bottom: 4 }).show(ui, |ui| { let mut v = app.ui.hdr_visualize; let r = ui.checkbox(&mut v, "Visualize HDR"); diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index 29579a01fb..db4dfa1b83 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -806,15 +806,15 @@ fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, square } else { r }; - paint_cell_thumbnail(app, p, &t, id, img_rect, ThumbFlags { square, state, onscreen, ppp }); + let photo_rect = paint_cell_thumbnail(app, p, &t, id, img_rect, ThumbFlags { square, state, onscreen, ppp }); // labels and badges paint_cell_caption(app, p, &t, &photo, r, square); - paint_cell_badges(app, p, &t, &photo, img_rect, BadgeFlags { square, selected, hovered: resp.hovered() }); + paint_cell_badges(app, p, &t, &photo, photo_rect, BadgeFlags { square, selected, hovered: resp.hovered() }); if let Some(name) = &photo.copy_name { paint_copy_tag(p, &t, name, img_rect, square); } if let Some(why) = &photo.preview_only { - paint_preview_pill(ui, p, &t, id, why, img_rect); + paint_preview_pill(ui, p, &t, id, why, photo_rect); } if photo.flag == Flag::Reject { p.rect_filled(img_rect, 0.0, Color32::from_black_alpha(110)); @@ -838,7 +838,7 @@ pub(crate) fn cell_description(app: &LightcraftApp, photo: &lightcraft_catalog:: spoken } -fn paint_cell_thumbnail(app: &mut LightcraftApp, p: &egui::Painter, t: &Tokens, id: PhotoId, img_rect: Rect, flags: ThumbFlags) { +fn paint_cell_thumbnail(app: &mut LightcraftApp, p: &egui::Painter, t: &Tokens, id: PhotoId, img_rect: Rect, flags: ThumbFlags) -> Rect { let ThumbFlags { square, state, onscreen, ppp } = flags; let size = thumb_px(img_rect.width().max(img_rect.height()), ppp); request_thumb(app, id, size, if onscreen { 10 } else { 5 }); @@ -846,8 +846,9 @@ 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 { let ph = img_rect.shrink(if square { 20.0 } else { 0.0 }); p.rect_filled(ph, 0.0, t.skeleton); @@ -857,6 +858,7 @@ fn paint_cell_thumbnail(app: &mut LightcraftApp, p: &egui::Painter, t: &Tokens, // unreadable / missing file p.text(ph.center(), Align2::CENTER_CENTER, "!", t.semibold(18.0), t.text); } + ph } } @@ -890,14 +892,22 @@ fn paint_cell_caption(app: &LightcraftApp, p: &egui::Painter, t: &Tokens, photo: } } -fn paint_cell_badges(app: &LightcraftApp, p: &egui::Painter, t: &Tokens, photo: &lightcraft_catalog::Photo, img_rect: Rect, flags: BadgeFlags) { +/// The 24-pixel band the badges sit in, on the photo itself: a portrait's fitted rect is +/// narrower than the cell's image area and a landscape's is shorter, so a band sized from +/// the image area sticks out past the photo and crosses its selection frame (#3601). A photo +/// shorter than the band keeps its own top edge. +fn photo_badge_bar(photo_rect: Rect) -> Rect { + Rect::from_min_max(pos2(photo_rect.left(), (photo_rect.bottom() - 24.0).max(photo_rect.top())), photo_rect.right_bottom()) +} + +fn paint_cell_badges(app: &LightcraftApp, p: &egui::Painter, t: &Tokens, photo: &lightcraft_catalog::Photo, photo_rect: Rect, flags: BadgeFlags) { let BadgeFlags { square, selected, hovered } = flags; let show_badges = match app.ui.settings.grid_badges { crate::state::GridBadges::Auto => hovered || selected || photo.rating > 0 || photo.flag != Flag::None || photo.label.is_some(), crate::state::GridBadges::Always => true, crate::state::GridBadges::Never => false, }; - let badge_bar = Rect::from_min_max(pos2(img_rect.left(), img_rect.bottom() - 24.0), img_rect.right_bottom()); + let badge_bar = photo_badge_bar(photo_rect); if !square && photo.label.is_some() { // Justified photos fill the whole cell, so the label shows as a translucent tinted footer // over the photo's bottom edge (opaque, it would hide 24 px of every labelled photo). @@ -944,11 +954,11 @@ fn paint_copy_tag(p: &egui::Painter, t: &Tokens, name: &str, img_rect: Rect, squ p.galley(pos2(br.left() + 22.0, br.center().y - g.size().y / 2.0), g, Color32::WHITE); } -fn paint_preview_pill(ui: &egui::Ui, p: &egui::Painter, t: &Tokens, id: PhotoId, why: &str, img_rect: Rect) { - // a raw shown from its embedded JPEG: a small amber "Preview" pill at the image's bottom +fn paint_preview_pill(ui: &egui::Ui, p: &egui::Painter, t: &Tokens, id: PhotoId, why: &str, photo_rect: Rect) { + // a raw shown from its embedded JPEG: a small amber "Preview" pill at the photo's bottom // left, above the badge bar (always shown: it changes what editing does) let g = p.layout_no_wrap(crate::i18n::tr("Preview").into(), t.semibold(9.5), Color32::WHITE); - let at = pos2(img_rect.left() + 6.0, img_rect.bottom() - 30.0 - 16.0); + let at = pos2(photo_rect.left() + 6.0, photo_rect.bottom() - 30.0 - 16.0); let br = Rect::from_min_size(at, vec2(g.size().x + 24.0, 16.0)); p.rect_filled(br, 8.0, Color32::from_black_alpha(170)); paint(p, Rect::from_center_size(pos2(br.left() + 9.0, br.center().y), vec2(12.0, 12.0)), Icon::Info, t.caution); @@ -1315,18 +1325,11 @@ fn context_menu_open_and_edit(app: &mut LightcraftApp, ui: &mut egui::Ui, id: Ph } }); }); - if ui.button(crate::i18n::tr("Find Similar Photos")).clicked() { - match app.run("library.findSimilar", json!({"id": id.0})) { - Ok(r) => { - let n = r["photos"].as_array().map_or(0, Vec::len); - app.ui.view = crate::state::ViewMode::PhotoGrid; - app.toast( - ui.ctx(), - crate::i18n::tr_format!("{n} similar photo{} · View ▸ Clear Filters to see all", if n == 1 { "" } else { "s" }, n = n), - ); - } - Err(e) => app.toast(ui.ctx(), e), - } + let can_search = lightcraft_engine::cmd::similar::no_search_running(&app.session).is_ok(); + if ui.add_enabled(can_search, egui::Button::new(crate::i18n::tr("Find Similar Photos"))).clicked() + && let Err(e) = app.run("library.findSimilar", json!({"id": id.0})) + { + app.toast(ui.ctx(), e); } let live = super::compare::live(app, id); let set_reference = ui @@ -1662,4 +1665,27 @@ mod tests { assert_eq!(resolve_group(GroupBy::None, 220.0), GroupBy::None); assert_eq!(resolve_group(GroupBy::Year, 400.0), GroupBy::Year); } + + /// The badge band sits on the photo itself — a portrait's fitted rect is narrower than the + /// cell's image area, a landscape's is shorter — so it never sticks out past the photo or + /// crosses its selection frame (#3601). + #[test] + fn the_badge_band_stays_on_the_photo() { + let cell = Rect::from_min_size(pos2(10.0, 24.0), vec2(180.0, 180.0)); + // A photo that fills the image area: the band is the usual 24 px footer + let full = photo_badge_bar(cell); + assert!((full.height() - 24.0).abs() < 0.01, "{full:?}"); + assert!((full.bottom() - cell.bottom()).abs() < 0.01); + assert!((full.left() - cell.left()).abs() < 0.01 && (full.right() - cell.right()).abs() < 0.01); + // A portrait photo fitted inside it: the band is no wider than the photo + let portrait = Rect::from_min_size(pos2(cell.left() + 55.0, cell.top()), vec2(70.0, 180.0)); + let bar = photo_badge_bar(portrait); + assert!(bar.left() >= portrait.left() && bar.right() <= portrait.right(), "{bar:?}"); + assert!((bar.height() - 24.0).abs() < 0.01); + // A landscape photo shorter than the band: its own top edge, never a negative rect + let wide = Rect::from_min_size(pos2(cell.left(), cell.top() + 80.0), vec2(180.0, 20.0)); + let bar = photo_badge_bar(wide); + assert!((bar.top() - wide.top()).abs() < 0.01, "{bar:?}"); + assert!(bar.bottom() <= wide.bottom() + 0.01); + } } diff --git a/crates/ui-egui/src/panels/notices.rs b/crates/ui-egui/src/panels/notices.rs index cec974aa64..cc01701932 100644 --- a/crates/ui-egui/src/panels/notices.rs +++ b/crates/ui-egui/src/panels/notices.rs @@ -76,21 +76,34 @@ pub fn may_close(app: &mut LightcraftApp) -> bool { app.quit_prompt = Some(QuitPrompt::Tasks(tasks_message(names.len(), &names.join(", ")))); return false; } - if app.session.unsaved().is_none() { + // what the catalog log's thread was handed is written first, and what it holds read now: a + // change it accepted but hasn't written yet must not pass for saved (review of #3557) + let flushed = app.session.flush_log(); + if flushed.is_ok() && app.session.unsaved().is_none() { return true; } let _ = app.session.persist(); - if app.session.unsaved().is_some() - && let Err(e) = app.session.close_library() - { - log::error!("quit: library not saved: {e}"); + // a snapshot of everything in memory saves what the log couldn't take + let mut closed = Ok(()); + if flushed.is_err() || app.session.unsaved().is_some() { + closed = app.session.close_library(); + if let Err(e) = &closed { + log::error!("quit: library not saved: {e}"); + } } - match app.session.unsaved() { - None => true, - Some((n, e)) => { + match (app.session.unsaved(), flushed, closed) { + (None, Ok(()), _) | (None, _, Ok(())) => true, + (Some((n, e)), _, _) => { app.quit_prompt = Some(QuitPrompt::Unsaved(unsaved_message(n, e))); false } + // the snapshot landed; only the log's reset after it failed + (None, Err(_), Err(_)) if app.session.snapshot_holds_everything() => true, + // the log's thread didn't finish and the snapshot failed: changes may be lost + (None, Err(_), Err(e)) => { + app.quit_prompt = Some(QuitPrompt::Unsaved(unsaved_message(1, &e.to_string()))); + false + } } } diff --git a/crates/ui-egui/src/panels/people.rs b/crates/ui-egui/src/panels/people.rs index 18403d75df..da10075ca9 100644 --- a/crates/ui-egui/src/panels/people.rs +++ b/crates/ui-egui/src/panels/people.rs @@ -175,7 +175,7 @@ fn card(app: &mut LightcraftApp, ui: &mut egui::Ui, person: &Person, r: Rect, ed if let Some(job) = app.session.face_job(person.photo, view, (edge * ppp).ceil() as usize) && let Some(tex) = app.renderer.variant(job) { - p.image(tex.tex.id(), face, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), face, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } // how many photos they are in, on the picture let g = p.layout_no_wrap(badge_count(person.count), t.font(11.5), Color32::WHITE); diff --git a/crates/ui-egui/src/panels/person.rs b/crates/ui-egui/src/panels/person.rs index 0b6b946aa1..1063de935c 100644 --- a/crates/ui-egui/src/panels/person.rs +++ b/crates/ui-egui/src/panels/person.rs @@ -327,7 +327,7 @@ fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, spec: &TileSpec) -> Hit { if let Some(job) = app.session.face_job(lightcraft_catalog::PhotoId(f.photo), f.rect, (r.width() * ppp).ceil() as usize) && let Some(tex) = app.renderer.variant(job) { - p.image(tex.tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } if hovered { p.rect_stroke(r, 3.0, Stroke::new(1.5, Color32::WHITE), StrokeKind::Outside); diff --git a/crates/ui-egui/src/panels/presets.rs b/crates/ui-egui/src/panels/presets.rs index 6d35a50274..277c62b26b 100644 --- a/crates/ui-egui/src/panels/presets.rs +++ b/crates/ui-egui/src/panels/presets.rs @@ -228,7 +228,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if let Some(job) = app.session.variant_job(id, s, THUMB_EDGE) && let Some(tex) = app.renderer.variant(job) { - ui.painter().image(tex.tex.id(), tr, cover_uv(tr, tex.size), Color32::WHITE); + ui.painter().image(tex.id(), tr, cover_uv(tr, tex.size), Color32::WHITE); } text_x = tr.right() + 10.0; } diff --git a/crates/ui-egui/src/panels/profiles.rs b/crates/ui-egui/src/panels/profiles.rs index cf9a6c50cd..4757e9c504 100644 --- a/crates/ui-egui/src/panels/profiles.rs +++ b/crates/ui-egui/src/panels/profiles.rs @@ -62,12 +62,16 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { PROFILES.iter().filter(|p| p.group == g).map(|p| (p.id.to_string(), p.name.to_string(), p.group.to_string())).collect(), )); } - // imported LUT profile groups - let mut lut_groups: Vec = app.session.lut_profiles.iter().map(|p| p.group.clone()).collect(); - lut_groups.sort_unstable(); - lut_groups.dedup(); + // imported profile groups: LUT folders, then camera profiles + let imported = app.session.imported_profiles(); + let mut lut_groups: Vec = Vec::new(); + for (_, _, g) in &imported { + if !lut_groups.contains(g) { + lut_groups.push(g.clone()); + } + } for g in &lut_groups { - let profiles = app.session.lut_profiles.iter().filter(|p| &p.group == g).map(|p| (p.id.clone(), p.name.clone(), p.group.clone())).collect(); + let profiles = imported.iter().filter(|p| &p.2 == g).cloned().collect(); sections.push((g.as_str(), "", true, profiles)); } for (title, tag, imported, list) in sections { @@ -163,7 +167,7 @@ fn cell_ui( if let Some(job) = app.session.variant_job(id, &s, THUMB_EDGE) && let Some(tex) = app.renderer.variant(job) { - painter.image(tex.tex.id(), thumb, cover_uv(thumb, tex.size), Color32::WHITE); + painter.image(tex.id(), thumb, cover_uv(thumb, tex.size), Color32::WHITE); } let applied = d.profile.id == p_id; if applied { diff --git a/crates/ui-egui/src/panels/right/history.rs b/crates/ui-egui/src/panels/right/history.rs index d434075adc..86cdf1b19f 100644 --- a/crates/ui-egui/src/panels/right/history.rs +++ b/crates/ui-egui/src/panels/right/history.rs @@ -42,7 +42,7 @@ pub(super) fn versions(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) if let Some(job) = app.session.variant_job(id, &v.settings, 160) && let Some(tex) = app.renderer.variant(job) { - ui.painter().image(tex.tex.id(), tr, crate::panels::presets::cover_uv(tr, tex.size), egui::Color32::WHITE); + ui.painter().image(tex.id(), tr, crate::panels::presets::cover_uv(tr, tex.size), egui::Color32::WHITE); } let x = tr.right() + 10.0; ui.painter().with_clip_rect(r.with_max_x(r.right() - 24.0)).text( diff --git a/crates/ui-egui/src/panels/second.rs b/crates/ui-egui/src/panels/second.rs index 57fc5756a4..710079bef0 100644 --- a/crates/ui-egui/src/panels/second.rs +++ b/crates/ui-egui/src/panels/second.rs @@ -55,9 +55,10 @@ fn body(app: &mut LightcraftApp, ui: &mut egui::Ui) { let mine = |s: Slot| app.renderer.textures.get(&s).filter(|t| t.photo == id); let tex = mine(Slot::Second).or_else(|| mine(Slot::Main)).or_else(|| app.renderer.thumb(id)); if let Some(t) = tex { - let [tw, th] = t.tex.size(); + // (the frame's size: a GPU-resident render's `tex` is only a placeholder) + let [tw, th] = t.size.map(|n| n.max(1)); let s = (area.width() / tw as f32).min(area.height() / th as f32); let r = Rect::from_center_size(area.center(), vec2(tw as f32 * s, th as f32 * s)); - ui.painter().image(t.tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + ui.painter().image(t.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } } diff --git a/crates/ui-egui/src/panels/slideshow.rs b/crates/ui-egui/src/panels/slideshow.rs index cfe0ce6e68..8b0ade6cf3 100644 --- a/crates/ui-egui/src/panels/slideshow.rs +++ b/crates/ui-egui/src/panels/slideshow.rs @@ -328,7 +328,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let draw = |id: Item, alpha: f32| -> Option { let t = texture(app, id)?; let r = rect_of(t); - p.image(t.tex.id(), r, full_uv(), Color32::WHITE.gamma_multiply(alpha.clamp(0.0, 1.0))); + p.image(t.id(), r, full_uv(), Color32::WHITE.gamma_multiply(alpha.clamp(0.0, 1.0))); Some(r) }; let k = frame.progress.clamp(0.0, 1.0); @@ -352,13 +352,13 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let r = rect_of(t); match new_rect { Some(n) => { - p.with_clip_rect(n.intersect(canvas)).image(t.tex.id(), r, full_uv(), Color32::WHITE); + p.with_clip_rect(n.intersect(canvas)).image(t.id(), r, full_uv(), Color32::WHITE); for band in outside(r, n) { - p.with_clip_rect(band).image(t.tex.id(), r, full_uv(), Color32::WHITE.gamma_multiply(1.0 - k)); + p.with_clip_rect(band).image(t.id(), r, full_uv(), Color32::WHITE.gamma_multiply(1.0 - k)); } } None => { - p.image(t.tex.id(), r, full_uv(), Color32::WHITE.gamma_multiply(1.0 - k)); + p.image(t.id(), r, full_uv(), Color32::WHITE.gamma_multiply(1.0 - k)); } } } diff --git a/crates/ui-egui/src/panels/unnamed.rs b/crates/ui-egui/src/panels/unnamed.rs index 7f42437b2e..71f1a2803d 100644 --- a/crates/ui-egui/src/panels/unnamed.rs +++ b/crates/ui-egui/src/panels/unnamed.rs @@ -243,7 +243,7 @@ pub fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, list: &Unnamed, i: usize if let Some(job) = app.session.face_job(lightcraft_catalog::PhotoId(f.photo), f.view, (r.width() * ppp).ceil() as usize) && let Some(tex) = app.renderer.variant(job) { - p.image(tex.tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } if selected { p.rect_filled(r, 3.0, Color32::from_rgba_unmultiplied(70, 130, 255, 55)); diff --git a/crates/ui-egui/src/pick.rs b/crates/ui-egui/src/pick.rs index b9d58cee6c..c7e8e742db 100644 --- a/crates/ui-egui/src/pick.rs +++ b/crates/ui-egui/src/pick.rs @@ -58,7 +58,7 @@ impl PickRequest { } /// What File ▸ Import Profiles & Presets… opens. -pub const PRESET_EXTENSIONS: &[&str] = &["lcpreset", "xmp", "lrtemplate", "zip", "dng", "lmp", "mplumpack", "cube", "lceffect"]; +pub const PRESET_EXTENSIONS: &[&str] = &["lcpreset", "xmp", "lrtemplate", "zip", "dng", "lmp", "mplumpack", "cube", "dcp", "lceffect"]; /// What Import Point Curve Presets… opens. pub const CURVE_PRESET_EXTENSIONS: &[&str] = &["lccurve", "json"]; diff --git a/crates/ui-egui/src/render.rs b/crates/ui-egui/src/render.rs index fd2bc1706f..9237e43066 100644 --- a/crates/ui-egui/src/render.rs +++ b/crates/ui-egui/src/render.rs @@ -93,6 +93,44 @@ pub struct Tex { pub quick: Option, /// CPU copy of the pixels (only with [`Renderer::keep_pixels`]; for headless screenshots). pub pixels: Option>, + /// Showing a render that stayed on the GPU ([`ScreenTextures`]): drawn by this id instead of `tex`. + pub native: Option, +} + +impl Tex { + /// Draw this slot from the GPU-resident texture `id` from now on. On the switch from pixels, the egui texture + /// (never drawn while `native` is set) drops its full-size image for a 1 × 1 placeholder, so a view slot on the + /// GPU path doesn't keep a second copy of the picture until it is released (review of PR #1065). + fn show_native(&mut self, id: egui::TextureId) { + if self.native.is_none() { + self.tex.set(egui::ColorImage::filled([1, 1], egui::Color32::BLACK), egui::TextureOptions::LINEAR); + } + self.native = Some(id); + self.pixels = None; + } + + /// The texture to draw. + pub fn id(&self) -> egui::TextureId { + self.native.unwrap_or_else(|| egui::TextureHandle::id(&self.tex)) + } +} + +/// Draws renders that stayed on the GPU ([`lightcraft_engine::media::ScreenFrame`]): the window's +/// renderer registers their textures. Installed by a host whose GPU renderer runs on the window's +/// device (the desktop app); without one, every render comes back as pixels. +pub trait ScreenTextures { + /// Show `frame` under `id` (one this returned before, updated in place) or a new id; `None` + /// when it can't be shown. + fn show(&mut self, frame: &lightcraft_engine::media::ScreenFrame, id: Option) -> Option; + /// Release `id` (and the texture it shows). + fn free(&mut self, id: egui::TextureId); + /// The pixels `frame` holds, read back from the GPU: only for a headless screenshot of a view + /// that shows it ([`Renderer::cpu_textures`]). `None` when they can't be read (the view is + /// then left out of the picture). + fn read(&self, frame: &lightcraft_engine::media::ScreenFrame) -> Option { + let _ = frame; + None + } } /// Runs render jobs outside this thread's job pool (the browser build: Web Workers, each with its @@ -214,6 +252,9 @@ pub struct Renderer { offload_looks: HashMap, #[cfg(test)] failure_messages: Vec, + /// The render decisions [`Self::decided`] logged. + #[cfg(test)] + decisions: Vec, /// Request id of the pixels each interactive view (loupe, before, hover) shows: a draft that /// finishes after a newer request was made still replaces older pixels, so a long slider drag /// keeps updating the loupe instead of waiting for the drag to pause. @@ -276,6 +317,14 @@ pub struct Renderer { /// Since when nothing has been pending, and whether the GPU pool was trimmed since. #[cfg(not(target_arch = "wasm32"))] idle: Option<(std::time::Instant, bool)>, + /// Draws GPU-resident renders; with it, interactive drafts of views stay on the GPU. + screen: Option>, + /// The texture id each view slot shows GPU-resident renders under (one per slot, reused). + natives: HashMap, + /// The GPU-resident render each of those shows, kept with [`Self::keep_pixels`]: a headless + /// screenshot reads it back ([`Self::cpu_textures`]) instead of finding no pixels (a white + /// photo, review of PR #1065). + native_frames: HashMap, } /// After this long without renders the GPU renderer's pool of recycled buffers is freed. @@ -329,6 +378,8 @@ impl Renderer { offload_looks: HashMap::new(), #[cfg(test)] failure_messages: Vec::new(), + #[cfg(test)] + decisions: Vec::new(), shown_ids: HashMap::new(), epoch: 0, preview_generation: None, @@ -360,6 +411,9 @@ impl Renderer { display: None, #[cfg(not(target_arch = "wasm32"))] idle: None, + screen: None, + natives: HashMap::new(), + native_frames: HashMap::new(), } } } @@ -521,7 +575,23 @@ impl Renderer { /// `job` as [`Self::request`] would run it for `slot` (its key included): views render for /// the display profile in use. pub fn job_for(&self, slot: Slot, job: RenderJob) -> RenderJob { - if Self::renders_for_display(slot) { job.with_display(self.display.clone()) } else { job } + if !Self::renders_for_display(slot) { + return job; + } + let job = job.with_display(self.display.clone()); + // a drag's drafts are only drawn: they may stay on the GPU when the window can show them + if self.screen.is_some() && job.request.quality == lightcraft_pipeline::Quality::Draft { job.on_screen() } else { job } + } + + /// Show GPU-resident renders through `screen` from now on (the desktop app, once its GPU + /// renderer runs on the window's device). + pub fn set_screen_textures(&mut self, screen: Box) { + self.screen = Some(screen); + } + + /// Whether GPU-resident renders can be shown. + pub fn has_screen_textures(&self) -> bool { + self.screen.is_some() } /// The display profile in use (id). @@ -567,6 +637,19 @@ impl Renderer { pub fn release(&mut self, slot: Slot) { self.textures.remove(&slot); self.stages.remove(&slot); + // and its GPU-resident texture, which can be window-sized (review of PR #1065) + self.free_native(slot); + } + + /// Let go of `slot`'s GPU-resident texture: its registration with the window, and the frame + /// kept for headless screenshots. + fn free_native(&mut self, slot: Slot) { + self.native_frames.remove(&slot); + if let Some(id) = self.natives.remove(&slot) + && let Some(screen) = self.screen.as_mut() + { + screen.free(id); + } } /// Run jobs through `offload` from now on (instead of the job pool / inline). @@ -597,6 +680,7 @@ impl Renderer { if !self.request_needed(slot, job.key, priority) { return; } + self.note_request(slot, job.key, priority, "requested", || render_subject(slot, job.photo, Some(&job.origin))); self.pending.insert(slot, (job.key, priority)); job.request_id = lightcraft_preview::next_tick(); self.requests.insert( @@ -664,18 +748,24 @@ impl Renderer { }); if queued && let Some(p) = self.pending.get_mut(&slot) { p.1 = priority; + if logs_decisions() { + let source = self.requests.get(&slot).and_then(|r| r.source.as_ref()); + let line = format!("{}: still waiting, moved to priority {priority}", render_subject(slot, job.photo, source)); + self.decided(|| line); + } } } return; } self.quick_tried.insert(slot, job.key); - self.pending.insert(slot, (job.key, priority)); - job.request_id = lightcraft_preview::next_tick(); let source = job .small .as_ref() .map(|job| job.origin.clone()) .or_else(|| job.embedded.as_ref().map(|(path, _, _)| lightcraft_catalog::Source::File { path: path.clone() })); + self.note_request(slot, job.key, priority, "stand-in requested", || render_subject(slot, job.photo, source.as_ref())); + self.pending.insert(slot, (job.key, priority)); + job.request_id = lightcraft_preview::next_tick(); self.requests.insert( slot, Requested { look: job.small.as_ref().map(|j| (geometry_look(&j.settings), j.request.apply_crop)), id: job.request_id, source }, @@ -696,6 +786,7 @@ impl Renderer { if !self.request_needed(slot, key, priority) { return; } + self.note_request(slot, key, priority, "title screen requested", || format!("render {slot:?}")); self.pending.insert(slot, (key, priority)); let request_id = lightcraft_preview::next_tick(); self.requests.insert(slot, Requested { look: None, id: request_id, source: None }); @@ -710,6 +801,7 @@ impl Renderer { return; } self.prefetched.insert(slot, job.key); + self.note_request(slot, job.key, priority, "prefetch requested", || render_subject(slot, job.photo, Some(&job.origin))); self.pending.insert(slot, (job.key, priority)); job.request_id = lightcraft_preview::next_tick(); self.requests.insert( @@ -732,6 +824,7 @@ impl Renderer { return; } let gone = |s: &Slot| matches!(s, Slot::Slide(id) if !keep.contains(id)); + self.abandon_pending(gone, "no longer near the slide shown"); self.textures.retain(|s, _| !gone(s)); let _ = self.pool.reprioritize(|s, p| if gone(s) { None } else { Some(p) }); self.queue.retain(|q| !gone(&q.slot)); @@ -745,6 +838,7 @@ impl Renderer { /// Is a request for `slot` queued or running? /// Drop every texture and cached stage (another library was opened: photo ids changed meaning). pub fn forget_all(&mut self) { + self.abandon_pending(|_| true, "the renderer started over (another library, or the previews were cleared)"); self.requests.clear(); self.offload_looks.clear(); self.shown_ids.clear(); @@ -759,6 +853,20 @@ impl Renderer { self.prefetched.clear(); self.pending.clear(); self.queue.clear(); + self.free_natives(); + } + + /// Release every GPU-resident texture shown. + fn free_natives(&mut self) { + if let Some(screen) = self.screen.as_mut() { + for (_, id) in self.natives.drain() { + screen.free(id); + } + } + self.natives.clear(); + self.native_frames.clear(); + // a view drawn from a freed texture would show nothing: it is rendered again, as pixels + self.textures.retain(|_, t| t.native.is_none()); } pub fn is_pending(&self, slot: Slot) -> bool { @@ -1008,8 +1116,9 @@ impl Renderer { } } - /// Turn finished jobs into textures. Returns true if anything changed. - fn collect(&mut self, ctx: &egui::Context, session: &mut Session, inline_ms: f64) -> bool { + /// The jobs the pool and the offload finished: (slot, result, texture pixels, look, ms). + #[allow(clippy::type_complexity)] + fn take_finished(&mut self, inline_ms: f64) -> Vec<(Slot, RenderResult, Option>, Option<(u64, bool)>, f64)> { let mut finished = Vec::new(); while let Some(done) = self.pool.try_recv() { finished.push((done.slot, done.result.result, done.result.color, done.result.look, if done.ms > 0.0 { done.ms } else { inline_ms })); @@ -1020,12 +1129,22 @@ impl Renderer { (slot, r, None, look, ms) })); } + finished + } + + /// Turn finished jobs into textures. Returns true if anything changed. + fn collect(&mut self, ctx: &egui::Context, session: &mut Session, inline_ms: f64) -> bool { + let finished = self.take_finished(inline_ms); self.dispatch(); let mut changed = false; for (mut slot, mut r, mut color, completed_look, ms) in finished { self.completed += 1; // made for another display profile than the one in use: obsolete if r.display.is_some_and(|id| Some(id) != self.display_id()) { + self.decided(|| { + let source = session.catalog.photo(r.photo).map(|p| &p.source); + format!("{}: abandoned, made for another display profile", render_subject(slot, r.photo, source)) + }); continue; } // Ignore obsolete pixels, failures and decoded sources, even for the same render key; @@ -1040,6 +1159,12 @@ impl Renderer { && r.rendered.is_ok(); if !newer_draft { self.discarded += 1; + let replaced = self.requests.contains_key(&slot); + self.decided(|| { + let why = if replaced { "a newer request replaced it" } else { "no longer wanted when it finished" }; + let source = session.catalog.photo(r.photo).map(|p| &p.source); + format!("{}: abandoned, {why}", render_subject(slot, r.photo, source)) + }); continue; } session.accept(&r); @@ -1065,9 +1190,72 @@ impl Renderer { if self.pending.get(&slot).is_some_and(|p| p.0 == r.key) { self.pending.remove(&slot); } + // a render that stayed on the GPU: drawn from its texture + if let (Some(frame), Ok(rendered)) = (r.frame.as_ref(), r.rendered.as_ref()) { + self.failed.remove(&slot); + let shown = self.screen.as_mut().and_then(|s| s.show(frame, self.natives.get(&slot).copied())); + let Some(id) = shown else { + // can't be shown: from now on views come back as pixels + log::warn!("render {slot:?}: a GPU-resident render can't be shown; rendering pixels"); + self.free_natives(); + self.screen = None; + continue; + }; + self.natives.insert(slot, id); + if self.keep_pixels { + self.native_frames.insert(slot, frame.clone()); + } + let (size, histogram) = ([frame.width, frame.height], rendered.histogram.clone()); + match self.textures.get_mut(&slot) { + Some(t) => { + t.show_native(id); + t.look = look; + t.key = r.key; + t.photo = r.photo; + t.size = size; + t.histogram = Some(histogram); + t.ms = ms; + t.quick = None; + } + None => { + // (`tex` is never drawn while `native` is set) + let blank = egui::ColorImage::filled([1, 1], egui::Color32::BLACK); + let tex = ctx.load_texture(format!("{slot:?}"), blank, egui::TextureOptions::LINEAR); + let t = Tex { + look, + key: r.key, + photo: r.photo, + tex, + size, + histogram: Some(histogram), + ms, + quick: None, + pixels: None, + native: Some(id), + }; + self.textures.insert(slot, t); + } + } + if slot == Slot::Main { + self.last_main_ms = ms; + } + changed = true; + continue; + } let rendered = match r.rendered { Ok(x) => { self.failed.remove(&slot); + // (a stand-in that comes back after the thumbnail itself is thrown away below) + let unused = matches!(slot, Slot::ThumbQuick(id) if self.textures.contains_key(&Slot::Thumb(id))); + self.decided(|| { + let source = source.as_ref().or_else(|| session.catalog.photo(r.photo).map(|p| &p.source)); + let subject = render_subject(slot, r.photo, source); + if unused { + format!("{subject}: abandoned, the thumbnail itself came first") + } else { + format!("{subject}: produced in {ms:.0} ms") + } + }); x } Err(e) => { @@ -1077,6 +1265,9 @@ impl Renderer { self.failure_messages.push(message.clone()); log::warn!("{message}"); self.failed.insert(slot, (r.key, e, self.catalog_rev, r.photo)); + } else { + // (a prefetch only prepares: its failure is no warning, but the trace says how it ended) + self.decided(|| format!("{}: prefetch failed: {e}", render_subject(slot, r.photo, source.as_ref()))); } continue; } @@ -1107,9 +1298,12 @@ impl Renderer { let color = color.unwrap_or_else(|| Arc::new(color_image(img))); let pixels = self.keep_pixels.then(|| color.clone()); let name = format!("{slot:?}"); + // pixels again: the slot's GPU-resident texture is let go + self.free_native(slot); match self.textures.get_mut(&slot) { Some(t) => { t.tex.set(color, egui::TextureOptions::LINEAR); + t.native = None; t.pixels = pixels; t.look = look; t.key = r.key; @@ -1133,6 +1327,7 @@ impl Renderer { ms, quick: r.quick, pixels, + native: None, }, ); } @@ -1202,9 +1397,20 @@ impl Renderer { }) } - /// CPU copies of the current textures by id (see [`Self::keep_pixels`]). + /// CPU copies of the current textures by id (see [`Self::keep_pixels`]); a view drawn straight + /// from the GPU is read back from it (only here: drawing it never does). pub fn cpu_textures(&self) -> HashMap { - self.textures.values().filter_map(|t| Some((t.tex.id(), crate::softpaint::CpuTexture::linear(t.pixels.clone()?)))).collect() + self.textures + .iter() + .filter_map(|(slot, t)| { + let pixels = match (&t.pixels, t.native, self.native_frames.get(slot), self.screen.as_ref()) { + (Some(p), ..) => p.clone(), + (None, Some(_), Some(frame), Some(screen)) => Arc::new(screen.read(frame)?), + _ => return None, + }; + Some((t.id(), crate::softpaint::CpuTexture::linear(pixels))) + }) + .collect() } /// Drop the import review thumbnails (a new review, or the dialog closed). @@ -1235,19 +1441,24 @@ impl Renderer { }); for s in dropped { self.pending.remove(&s); - self.requests.remove(&s); + let request = self.requests.remove(&s); self.quick_tried.remove(&s); + self.decided(|| abandoned_line(s, request.as_ref(), "scrolled out of view before it started")); } + let mut gone = Vec::new(); let requests = &mut self.requests; let pending = &mut self.pending; self.queue.retain(|q| match q.slot { Slot::Thumb(id) if !keep.contains(&id) && q.priority <= 10 => { pending.remove(&q.slot); - requests.remove(&q.slot); + gone.push((q.slot, requests.remove(&q.slot))); false } _ => true, }); + for (s, request) in gone { + self.decided(|| abandoned_line(s, request.as_ref(), "scrolled out of view before it started")); + } let thumbs = self.thumb_textures(); if thumbs <= max { return; @@ -1255,15 +1466,91 @@ impl Renderer { self.textures.retain(|s, _| !matches!(s, Slot::Thumb(id) | Slot::ThumbQuick(id) if !keep.contains(id))); self.quick_tried.retain(|s, _| !matches!(s, Slot::ThumbQuick(id) if !keep.contains(id))); } + + /// Log a render decision at debug level: each request, and how it ended when it ended without + /// a picture or a failure (failures stay warnings). One "requested" line per request tells a + /// file asked for 37 times from one asked once and failing inside (issue #2682). `line` is only + /// built when the log takes debug lines (`LIGHTCRAFT_LOG=debug`, or + /// `RUST_LOG=lightcraft_ui_egui::render=debug`), so the grid's requests cost nothing more otherwise. + fn decided(&mut self, line: impl FnOnce() -> String) { + if !logs_decisions() { + return; + } + let line = line(); + log::debug!("{line}"); + #[cfg(test)] + self.decisions.push(line); + } + + /// Log a new request for `slot`, and first what becomes of the one it replaces while that one + /// still waits: a queue holds one job per slot, so a newer render drops it, and the same render + /// is only moved to the new priority. One already running says so when its result comes back. + fn note_request(&mut self, slot: Slot, key: u64, priority: u32, what: &str, subject: impl FnOnce() -> String) { + if !logs_decisions() { + return; + } + let waiting = self.pending.get(&slot).map(|p| p.0).filter(|_| self.is_queued(slot)); + if waiting == Some(key) { + let line = format!("{}: still waiting, moved to priority {priority}", subject()); + self.decided(|| line); + return; + } + if waiting.is_some() { + let line = abandoned_line(slot, self.requests.get(&slot), "a newer request replaced it before it started"); + self.decided(|| line); + } + let again = if self.failed.get(&slot).is_some_and(|f| f.0 == key) { " again after a failure" } else { "" }; + let line = format!("{}: {what}{again}", subject()); + self.decided(|| line); + } + + /// Log each request in `which` that still waits in a queue as abandoned (`why`), before they are + /// dropped. One already running says so once, when its result comes back unclaimed. + fn abandon_pending(&mut self, which: impl Fn(&Slot) -> bool, why: &str) { + if !logs_decisions() { + return; + } + let mut slots: Vec = self.pending.keys().copied().filter(|s| which(s) && self.is_queued(*s)).collect(); + slots.sort_by_key(|s| format!("{s:?}")); + for s in slots { + let line = abandoned_line(s, self.requests.get(&s), why); + self.decided(|| line); + } + } } -/// Include the source identity in diagnostics for every catalog-backed render slot (#1890). -/// Debug-format paths so whitespace/control characters cannot forge another log entry. -fn render_failure_message(slot: Slot, photo: PhotoId, source: Option<&lightcraft_catalog::Source>, error: &str) -> String { +/// Whether render decisions are logged ([`Renderer::decided`]): the log takes debug lines from this +/// module, or a test is looking. +fn logs_decisions() -> bool { + cfg!(test) || log::log_enabled!(log::Level::Debug) +} + +/// How the log names a render: its slot, its photo and that photo's source, for every +/// catalog-backed render slot (#1890). Debug-format paths so whitespace/control characters cannot +/// forge another log entry. +fn render_subject(slot: Slot, photo: PhotoId, source: Option<&lightcraft_catalog::Source>) -> String { match source { - Some(lightcraft_catalog::Source::File { path }) => format!("render {slot:?}, {photo:?}, file {path:?}: {error}"), - Some(lightcraft_catalog::Source::Demo { scene }) => format!("render {slot:?}, {photo:?}, demo scene {scene}: {error}"), - None => format!("render {slot:?}, {photo:?}, source unavailable: {error}"), + Some(lightcraft_catalog::Source::File { path }) => format!("render {slot:?}, {photo:?}, file {path:?}"), + Some(lightcraft_catalog::Source::Demo { scene }) => format!("render {slot:?}, {photo:?}, demo scene {scene}"), + None => format!("render {slot:?}, {photo:?}, source unavailable"), + } +} + +/// Include the source identity in diagnostics ([`render_subject`]). +fn render_failure_message(slot: Slot, photo: PhotoId, source: Option<&lightcraft_catalog::Source>, error: &str) -> String { + format!("{}: {error}", render_subject(slot, photo, source)) +} + +/// The log line for a request dropped before its result came back, named by the source it was +/// requested from. A grid slot names its photo; a view or slide slot shows whichever photo is open, +/// so its file names it. +fn abandoned_line(slot: Slot, request: Option<&Requested>, why: &str) -> String { + let source = request.and_then(|r| r.source.as_ref()); + match (slot, source) { + (Slot::Thumb(id) | Slot::ThumbQuick(id), _) => format!("{}: abandoned, {why}", render_subject(slot, id, source)), + (_, Some(lightcraft_catalog::Source::File { path })) => format!("render {slot:?}, file {path:?}: abandoned, {why}"), + (_, Some(lightcraft_catalog::Source::Demo { scene })) => format!("render {slot:?}, demo scene {scene}: abandoned, {why}"), + (_, None) => format!("render {slot:?}: abandoned, {why}"), } } @@ -1286,7 +1573,7 @@ mod stage_budget_tests { let tex = ctx.load_texture("window", egui::ColorImage::new([1, 1], vec![egui::Color32::BLACK]), Default::default()); r.textures.insert( Slot::Region, - Tex { look: None, key: 1, photo: PhotoId(1), tex, size: [1, 1], histogram: None, ms: 0.0, quick: None, pixels: None }, + Tex { look: None, key: 1, photo: PhotoId(1), tex, native: None, size: [1, 1], histogram: None, ms: 0.0, quick: None, pixels: None }, ); let long_ago = std::time::Instant::now().checked_sub(IDLE_TRIM * 2).unwrap(); r.idle = Some((long_ago, false)); @@ -1298,6 +1585,59 @@ mod stage_budget_tests { assert_eq!(r.idle, Some((long_ago, true)), "trimmed once the window is gone"); } + // Given views drawn from GPU-resident frames, freeing those frames (the screen can't show one any more) drops + // the views that point at them, so they are rendered again as pixels; a view held as pixels stays + #[test] + fn freeing_gpu_frames_drops_the_views_drawn_from_them() { + let ctx = egui::Context::default(); + let mut r = Renderer::default(); + let tex = |name: &str| ctx.load_texture(name, egui::ColorImage::new([1, 1], vec![egui::Color32::BLACK]), Default::default()); + let view = |tex, native| Tex { + look: None, + key: 1, + photo: PhotoId(1), + tex, + native, + size: [64, 48], + histogram: None, + ms: 0.0, + quick: None, + pixels: None, + }; + r.textures.insert(Slot::Before, view(tex("before"), Some(egui::TextureId::User(7)))); + r.textures.insert(Slot::Compare(0), view(tex("compare"), Some(egui::TextureId::User(8)))); + r.textures.insert(Slot::Main, view(tex("main"), None)); + r.free_natives(); + assert!(!r.textures.contains_key(&Slot::Before), "its frame is gone"); + assert!(!r.textures.contains_key(&Slot::Compare(0)), "its frame is gone"); + assert!(r.textures.contains_key(&Slot::Main), "pixels stay"); + } + + /// A view slot switching from pixels to a GPU-resident texture lets go of its pixel image (it is never drawn + /// while the native texture is set): before, the full-size image stayed in egui's texture manager. + #[test] + fn a_view_switching_to_a_gpu_texture_drops_its_pixel_image() { + let ctx = egui::Context::default(); + let image = egui::ColorImage::new([64, 48], vec![egui::Color32::GRAY; 64 * 48]); + let mut t = Tex { + look: None, + key: 1, + photo: PhotoId(1), + tex: ctx.load_texture("main", image, Default::default()), + native: None, + size: [64, 48], + histogram: None, + ms: 0.0, + quick: None, + pixels: Some(std::sync::Arc::new(egui::ColorImage::new([1, 1], vec![egui::Color32::BLACK]))), + }; + t.show_native(egui::TextureId::User(7)); + assert_eq!(t.tex.size(), [1, 1], "the pixel image is released"); + assert_eq!((t.native, t.pixels.is_none()), (Some(egui::TextureId::User(7)), true)); + t.show_native(egui::TextureId::User(8)); + assert_eq!((t.native, t.tex.size()), (Some(egui::TextureId::User(8)), [1, 1])); + } + // Given stage caches within the budget, nothing is cleared #[test] fn nothing_is_trimmed_within_the_budget() { @@ -1418,6 +1758,7 @@ mod color_image_tests { loaded: None, quick: None, display: None, + frame: None, }; let histogram = Histogram::of_srgb8(&image); let ok = Renderer::run_for(|| result(Ok(lightcraft_pipeline::Rendered { image: image.clone(), histogram, deep: None })), &None); diff --git a/crates/ui-egui/src/render/thumbnail_tests.rs b/crates/ui-egui/src/render/thumbnail_tests.rs index 769f9378b2..7a2cb1a6a9 100644 --- a/crates/ui-egui/src/render/thumbnail_tests.rs +++ b/crates/ui-egui/src/render/thumbnail_tests.rs @@ -23,6 +23,129 @@ fn render_failure_paths_are_escaped_and_missing_sources_still_identified() { assert!(render_failure_message(Slot::Main, PhotoId(42), Some(&demo), "decode failed").contains("demo scene 7")); } +/// Issue #2682: the log could not tell a file asked for 37 times from one asked once and failing +/// inside. At debug level every request is a line naming its file, and so is how it ended when it +/// drew nothing (a failure stays the warning it was). +#[test] +fn each_render_request_and_how_it_ended_is_a_debug_line_with_its_file() { + let ends = + |lines: &[String]| -> Vec { lines.iter().map(|l| l.rsplit_once(": ").map_or(l.clone(), |(_, end)| end.to_string())).collect() }; + let (mut app, work, ctx) = fixture(); + let slot = Slot::Thumb(PhotoId(1)); + let job = |app: &mut crate::LightcraftApp, edge| app.session.render_job(PhotoId(1), edge, edge, false, true).unwrap(); + // asked once, drawn + let j = job(&mut app, 64); + app.renderer.request(slot, j, 10); + let (_, j) = take_job(&work); + finish(&mut app, &work, &ctx, slot, j.run()); + // asked twice: the first answer comes after the second request and is dropped + let (a, b) = (job(&mut app, 128), job(&mut app, 160)); + app.renderer.request(slot, a, 10); + app.renderer.request(slot, b, 10); + let (_, b) = take_job(&work); + let (_, a) = take_job(&work); + finish(&mut app, &work, &ctx, slot, a.run()); + finish(&mut app, &work, &ctx, slot, b.run()); + // a stand-in that comes back after the thumbnail itself is not used + let quick = Slot::ThumbQuick(PhotoId(1)); + let mut j = job(&mut app, 64); + j.request_id = lightcraft_preview::next_tick(); + app.renderer.requests.insert(quick, Requested { look: None, id: j.request_id, source: Some(j.origin.clone()) }); + finish(&mut app, &work, &ctx, quick, j.run()); + // a render still running when everything is forgotten says so once, when it comes back + let j = job(&mut app, 200); + app.renderer.request(slot, j, 10); + let (_, j) = take_job(&work); + app.renderer.forget_all(); + finish(&mut app, &work, &ctx, slot, j.run()); + assert_eq!( + ends(&app.renderer.decisions), + [ + "requested", + "produced in 0 ms", + "requested", + "requested", + "abandoned, a newer request replaced it", + "produced in 0 ms", + "abandoned, the thumbnail itself came first", + "requested", + "abandoned, no longer wanted when it finished" + ] + ); + let named = |app: &crate::LightcraftApp| { + assert!( + app.renderer.decisions.iter().all(|l| l.starts_with("render Thumb") && l.contains(", PhotoId(1), file \"audit.jpg\": ")), + "{:?}", + app.renderer.decisions + ); + }; + named(&app); + + // a file that fails asks nothing while its failure stands, and says so when it is asked again + let (mut app, work, ctx) = fixture(); + app.session.media.file_loader = Some(Arc::new(|_, _, _| Err("simulated decode failure".into()))); + let j = job(&mut app, 64); + app.renderer.request(slot, j, 10); + let (_, j) = take_job(&work); + finish(&mut app, &work, &ctx, slot, j.run()); + assert_eq!(app.renderer.failure_messages.len(), 1, "the failure is the warning it was"); + let j = job(&mut app, 64); + app.renderer.request(slot, j, 10); + app.session.catalog.apply(Op::SetRating { id: PhotoId(1), rating: 3 }).unwrap(); + app.renderer.poll(&ctx, &mut app.session); + let j = job(&mut app, 64); + app.renderer.request(slot, j, 10); + assert_eq!(ends(&app.renderer.decisions), ["requested", "requested again after a failure"]); + named(&app); + + // requests that end before they run: the same render moved to another priority, a newer render + // in its place, scrolled out of view, everything forgotten + let (mut app, _, _) = fixture(); + app.renderer.set_offload(Box::new(Blocked)); + let j = job(&mut app, 64); + app.renderer.request(slot, j, 5); + let j = job(&mut app, 64); + app.renderer.request(slot, j, 10); + let j = job(&mut app, 128); + app.renderer.request(slot, j, 10); + app.renderer.evict_thumbs(&Default::default(), 0); + let j = job(&mut app, 64); + app.renderer.request(slot, j, 5); + app.renderer.forget_all(); + assert_eq!( + ends(&app.renderer.decisions), + [ + "requested", + "still waiting, moved to priority 10", + "abandoned, a newer request replaced it before it started", + "requested", + "abandoned, scrolled out of view before it started", + "requested", + "abandoned, the renderer started over (another library, or the previews were cleared)" + ] + ); + named(&app); + + // a stand-in still waiting that the grid moves up while it scrolls says so + let mut s = Session::new(); + s.media.preview_loader = Some(Arc::new(|_, _| Some(lightcraft_raster::Rgba8 { width: 4, height: 4, data: vec![[200, 100, 50, 255]; 16] }))); + let mut raw = (*photo()).clone(); + raw.kind = lightcraft_catalog::MediaKind::Raw; + raw.develop = Arc::new(raw.camera_defaults()); + let (mut app, _, _) = fixture_with(s, raw); + app.renderer.pool = JobPool::new(0); // nothing starts until run_inline + crate::panels::grid::request_thumb(&mut app, PhotoId(1), 384, 5); + crate::panels::grid::request_thumb(&mut app, PhotoId(1), 384, 10); + assert_eq!(ends(&app.renderer.decisions), ["stand-in requested", "still waiting, moved to priority 11"]); + named(&app); + // a view shows whichever photo is open: its file names it + let main = Requested { look: None, id: 1, source: Some(Source::File { path: "trip/IMG_1.nef".into() }) }; + assert_eq!( + abandoned_line(Slot::Main, Some(&main), "a newer request replaced it"), + "render Main, file \"trip/IMG_1.nef\": abandoned, a newer request replaced it" + ); +} + struct Blocked; impl RenderOffload for Blocked { fn try_start(&mut self, _: Slot, job: RenderJob) -> Option { @@ -206,6 +329,7 @@ fn larger_texture_for_another_key_does_not_count_as_current() { ms: 0.0, quick: None, pixels: None, + native: None, }; let mut r = Renderer::default(); // A completed larger bucket: the remembered request is bucket 512, key 77. @@ -270,7 +394,7 @@ fn a_failed_thumbnail_is_retried_only_when_its_photo_changes() { #[test] fn a_fast_draft_is_drawn_in_the_frame_that_asked_for_it() { let mut s = Session::new(); - s.media.file_loader = Some(Arc::new(|_, _| Ok((lightcraft_raster::Rgb32f::new(8, 8), Default::default())))); + s.media.file_loader = Some(Arc::new(|_, _, _| Ok((lightcraft_raster::Rgb32f::new(8, 8), Default::default())))); s.catalog.apply(Op::AddPhoto { photo: Box::new((*photo()).clone()) }).unwrap(); let mut r = Renderer::with_worker_threads(1); let ctx = egui::Context::default(); @@ -317,7 +441,7 @@ fn raw_quick_fixture() -> (crate::LightcraftApp, std::rc::Rc (crate::LightcraftApp, std::rc::Rc>, egui::Context) { - s.media.file_loader = Some(Arc::new(|_, _| { + s.media.file_loader = Some(Arc::new(|_, _, _| { let mut image = lightcraft_raster::Rgb32f::new(8, 8); image.data.fill([0.3, 0.2, 0.1]); Ok((image, Default::default())) @@ -344,6 +468,117 @@ fn request(app: &mut crate::LightcraftApp) { crate::panels::grid::request_thumb(app, PhotoId(1), 256, 10); } +/// Draws GPU-resident renders under one fixed id, and reads them back from the test's device. +#[cfg(not(target_arch = "wasm32"))] +struct TestScreen(lightcraft_engine::gpu::wgpu::Device, lightcraft_engine::gpu::wgpu::Queue, std::sync::Arc>>); +#[cfg(not(target_arch = "wasm32"))] +impl ScreenTextures for TestScreen { + fn show(&mut self, _: &lightcraft_engine::media::ScreenFrame, _: Option) -> Option { + Some(egui::TextureId::User(7)) + } + fn free(&mut self, id: egui::TextureId) { + self.2.lock().unwrap().push(id); + } + fn read(&self, frame: &lightcraft_engine::media::ScreenFrame) -> Option { + let img = lightcraft_engine::gpu::read_texture(&self.0, &self.1, &frame.texture, frame.width, frame.height).ok()?; + Some(color_image(&img)) + } +} + +/// A headless screenshot (driven by the control channel: `keep_pixels`) of a view drawn straight +/// from the GPU has its pixels. Before, a mid-drag `ui.screenshot {"headless": true}` showed the +/// photo as a white rectangle: the GPU-resident draft left no CPU copy (review of PR #1065). +/// The test fixture with a small GPU texture (5 × 3 known texels) and a [`TestScreen`] that +/// records the ids it frees; `None` without a GPU adapter. +#[cfg(not(target_arch = "wasm32"))] +#[allow(clippy::type_complexity)] +fn gpu_drawn_fixture( + freed: std::sync::Arc>>, +) -> Option<(crate::LightcraftApp, std::rc::Rc>, egui::Context, lightcraft_engine::media::ScreenFrame)> { + use lightcraft_engine::gpu::wgpu; + let device = (|| { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = lightcraft_engine::gpu::backend::window_backends(); + desc.backend_options = lightcraft_engine::gpu::backend::backend_options(); + let instance = wgpu::Instance::new(desc); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; + pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("test window"), ..Default::default() })).ok() + })(); + let (device, queue) = device?; + let (w, h) = (5usize, 3usize); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let texels: Vec = (0..w * h).flat_map(|i| [i as u8 * 10, 100, 200, 255]).collect(); + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + &texels, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w as u32 * 4), rows_per_image: Some(h as u32) }, + wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 }, + ); + let (mut app, work, ctx) = fixture(); + app.renderer.set_screen_textures(Box::new(TestScreen(device, queue, freed))); + Some((app, work, ctx, lightcraft_engine::media::ScreenFrame { texture, width: w, height: h })) +} + +/// A headless screenshot (driven by the control channel: `keep_pixels`) of a view drawn straight +/// from the GPU has its pixels. Before, a mid-drag `ui.screenshot {"headless": true}` showed the +/// photo as a white rectangle: the GPU-resident draft left no CPU copy (review of PR #1065). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_headless_screenshot_reads_back_a_view_drawn_from_the_gpu() { + let Some((mut app, work, ctx, frame)) = gpu_drawn_fixture(Default::default()) else { + lightcraft_testkit::skip!(Gpu, "no GPU adapter"); + return; + }; + let (w, h) = (frame.width, frame.height); + assert!(app.renderer.keep_pixels); + let job = app.session.render_job(PhotoId(1), 64, 64, false, true).unwrap().draft(); + app.renderer.request(Slot::Main, job, 100); + let (slot, job) = take_job(&work); + let mut result = job.run(); + result.frame = Some(frame); + finish(&mut app, &work, &ctx, slot, result); + let t = app.renderer.textures.get(&Slot::Main).unwrap(); + assert_eq!(t.id(), egui::TextureId::User(7), "the draft is drawn from the GPU"); + assert!(t.pixels.is_none()); + let cpu = app.renderer.cpu_textures(); + let shot = cpu.get(&egui::TextureId::User(7)).expect("the headless screenshot has the view's pixels"); + assert_eq!(shot.image.size, [w, h]); + assert_eq!(shot.image.pixels[4], egui::Color32::from_rgb(40, 100, 200)); +} + +/// Releasing a slot (a zoomed loupe leaving its window, a Compare region) lets go of its +/// GPU-resident texture too, which can be window-sized (review of PR #1065: it was kept until +/// the slot was drawn from the GPU again). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn releasing_a_slot_frees_its_gpu_texture() { + let freed = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let Some((mut app, work, ctx, frame)) = gpu_drawn_fixture(freed.clone()) else { + lightcraft_testkit::skip!(Gpu, "no GPU adapter"); + return; + }; + let job = app.session.render_job(PhotoId(1), 64, 64, false, true).unwrap().draft(); + app.renderer.request(Slot::Main, job, 100); + let (slot, job) = take_job(&work); + let mut result = job.run(); + result.frame = Some(frame); + finish(&mut app, &work, &ctx, slot, result); + assert_eq!(app.renderer.textures.get(&Slot::Main).map(|t| t.id()), Some(egui::TextureId::User(7))); + assert!(freed.lock().unwrap().is_empty()); + app.renderer.release(Slot::Main); + assert_eq!(*freed.lock().unwrap(), vec![egui::TextureId::User(7)], "the window's texture is freed"); + assert!(app.renderer.natives.is_empty() && app.renderer.native_frames.is_empty()); +} + fn relink_destination() -> std::path::PathBuf { let path = std::env::temp_dir().join(format!("lc-render-relinked-{}-{}.nef", std::process::id(), lightcraft_preview::next_tick())); std::fs::write(&path, b"replacement source").unwrap(); @@ -355,7 +590,7 @@ fn completed_failure_keeps_requested_source_after_relink() { let replacement = relink_destination(); for slot in [Slot::Thumb(PhotoId(1)), Slot::Main, Slot::Before, Slot::Compare(1), Slot::Region] { let (mut app, work, ctx) = fixture(); - app.session.media.file_loader = Some(Arc::new(|_, _| Err("simulated decode failure".into()))); + app.session.media.file_loader = Some(Arc::new(|_, _, _| Err("simulated decode failure".into()))); let job = app.session.render_job(PhotoId(1), 64, 64, false, true).unwrap(); app.renderer.request(slot, job, 100); let (submitted, job) = take_job(&work); @@ -381,7 +616,7 @@ fn completed_failure_keeps_requested_source_after_relink() { fn superseded_failure_does_not_take_the_new_requests_source() { let replacement = relink_destination(); let (mut app, work, ctx) = fixture(); - app.session.media.file_loader = Some(Arc::new(|_, _| Err("simulated decode failure".into()))); + app.session.media.file_loader = Some(Arc::new(|_, _, _| Err("simulated decode failure".into()))); let slot = Slot::Main; let old_job = app.session.render_job(PhotoId(1), 64, 64, false, true).unwrap(); app.renderer.request(slot, old_job, 100); @@ -564,7 +799,7 @@ fn resizing_the_disk_cache_keeps_textures_and_skips_rebuilds() { #[test] fn a_panicking_render_is_a_failure_not_a_dead_worker() { let (mut app, _, ctx) = fixture_with(Session::new(), (*photo()).clone()); - app.session.media.file_loader = Some(Arc::new(|_, _| panic!("decoder bug"))); + app.session.media.file_loader = Some(Arc::new(|_, _, _| panic!("decoder bug"))); app.renderer.offload = None; // the real job pool let slot = Slot::Thumb(PhotoId(1)); let ask = |app: &mut crate::LightcraftApp| { @@ -800,7 +1035,7 @@ fn library_reset_rejects_old_job_even_when_photo_id_and_key_are_reused() { let photo = app.session.catalog.photo(PhotoId(1)).unwrap().as_ref().clone(); app.session = lightcraft_engine::Session::new(); app.session.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); - app.session.media.file_loader = Some(Arc::new(|_, _| { + app.session.media.file_loader = Some(Arc::new(|_, _, _| { let mut image = lightcraft_raster::Rgb32f::new(8, 8); image.data.fill([0.1, 0.2, 0.9]); Ok((image, Default::default())) diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 161fad09b9..6f4b42723f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -358,6 +358,16 @@ pub struct UiState { /// (`crate::recheck`). #[serde(skip)] pub rechecked_library: Option, + /// The first-run lens database download was considered this run (`crate::lens_db`). + #[serde(skip)] + pub lens_download_checked: bool, + /// The library, lens database generation and database replacement count whose raws were last looked up for a + /// lens profile (`crate::lens_db::lookup_key`). + #[serde(skip)] + pub lens_refreshed: Option<(u64, u64, u64)>, + /// Photos to look up for a lens profile on the next frame (Enable Lens Corrections ticked without one). + #[serde(skip)] + pub lens_lookup_ids: Vec, #[serde(skip)] pub status: String, #[serde(skip)] @@ -508,6 +518,9 @@ impl Default for UiState { #[cfg(test)] find_missing_test_delay: None, rechecked_library: None, + lens_download_checked: false, + lens_refreshed: None, + lens_lookup_ids: Vec::new(), status: String::new(), dialog: None, print: Default::default(), diff --git a/crates/ui-egui/src/state/dialog.rs b/crates/ui-egui/src/state/dialog.rs index 7f9226b6e4..30a2c08ffa 100644 --- a/crates/ui-egui/src/state/dialog.rs +++ b/crates/ui-egui/src/state/dialog.rs @@ -246,6 +246,12 @@ pub enum Dialog { #[serde(default)] error: Option, }, + /// The first launch offers the lens database (`crate::lens_db`): its size, Download or Not Now. `dir`: where it + /// goes; `mirrors`: where it comes from. + LensDatabase { + dir: String, + mirrors: Vec, + }, /// Open Library was given a Lightroom Classic catalog (issue #891): offer File ▸ Import /// Lightroom Catalog… with `catalog` (the `.lrcat` found; `None`: ask for it) instead. /// `folder`: what was chosen. diff --git a/crates/ui-egui/src/state/settings.rs b/crates/ui-egui/src/state/settings.rs index ffd2a0f8d0..b858b9a55f 100644 --- a/crates/ui-egui/src/state/settings.rs +++ b/crates/ui-egui/src/state/settings.rs @@ -195,6 +195,10 @@ pub struct AppSettings { /// gets a new one, or always merge (issue #2672; the window's "Don't ask again" picks that). #[serde(deserialize_with = "lenient")] pub lightroom_import: LightroomImport, + /// The answer to the first-launch offer of the lens database (Download / Not Now; Settings ▸ General ▸ Lens + /// profiles changes it). A value this version doesn't read asks again. + #[serde(deserialize_with = "lenient")] + pub lens_database: lightcraft_engine::lensfun_download::Offer, } /// Where File ▸ Import Lightroom Catalog… puts a catalog (Settings ▸ General ▸ Library). Saved as @@ -245,6 +249,7 @@ impl Default for AppSettings { zoom_to_focus: true, loupe_info: LoupeInfo::default(), lightroom_import: LightroomImport::Ask, + lens_database: Default::default(), } } } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 09e7703d77..4401d5d179 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -31,6 +31,7 @@ mod empty_library; mod error_kinds; mod filmstrip; mod filmstrip_drag; +mod find_similar; mod focus_point; mod folder_drop; mod grading; @@ -49,6 +50,8 @@ mod keywording; mod labels; mod launch_library; mod layout_image; +mod lens_lookup; +mod lens_offer; mod library_problem; mod lifecycle_037; mod lightroom_destination; diff --git a/crates/ui-egui/src/tests/compare.rs b/crates/ui-egui/src/tests/compare.rs index f570df33a8..0baffa06b6 100644 --- a/crates/ui-egui/src/tests/compare.rs +++ b/crates/ui-egui/src/tests/compare.rs @@ -405,6 +405,39 @@ fn survey_command_click_takes_the_photo_out() { assert_eq!((sel(&h), active(&h)), (vec![a], Some(a)), "the last photo stays in the survey"); } +/// Hover photo `id`'s survey tile, as a person does, so its × appears; then click the × in its corner. +fn click_x(h: &mut Headless, id: u64) { + let name = format!("cull:{id}"); + let tile = h.app.widgets.iter().find(|(w, _)| *w == name).map(|(_, r)| *r).expect("the tile is laid out"); + h.app.synthetic.push(egui::Event::PointerMoved(tile.center())); + h.settle(SETTLE); + click_with(h, egui::pos2(tile.right() - 16.0, tile.top() + 16.0), egui::Modifiers::NONE); +} + +/// The × in a survey tile's corner takes the photo out of the survey. It shows while the pointer is +/// over the tile, and it must stay while the pointer is on the × itself (#1639, #3614): the tile +/// loses its hover to the ×, and an × tied to that hover vanished before the click landed. +#[test] +fn survey_x_takes_the_photo_out() { + let mut h = demo(); + let [a, b, c] = survey_of_three(&mut h); + click_x(&mut h, c); + let sel: Vec = h.app.session.selection.ids.iter().map(|p| p.0).collect(); + let active = h.app.session.selection.active.map(|p| p.0); + assert_eq!((sel, active), (vec![a, b], Some(b)), "the photo whose × was clicked left the survey; the active one stays active"); +} + +/// The × on the active survey photo takes it out too, and the last remaining photo becomes active, +/// as a ⌘/Ctrl-click on it does. +#[test] +fn survey_x_on_the_active_photo_activates_the_last_one() { + let mut h = demo(); + let [a, b, c] = survey_of_three(&mut h); + click_x(&mut h, b); + let sel: Vec = h.app.session.selection.ids.iter().map(|p| p.0).collect(); + assert_eq!((sel, h.app.session.selection.active.map(|p| p.0)), (vec![a, c], Some(c))); +} + /// ⌘/Ctrl-click on the active survey photo while others remain: it leaves, and the last /// remaining photo becomes active, so the keys still act on a photo on screen. #[test] diff --git a/crates/ui-egui/src/tests/find_similar.rs b/crates/ui-egui/src/tests/find_similar.rs new file mode 100644 index 0000000000..b75995a1ca --- /dev/null +++ b/crates/ui-egui/src/tests/find_similar.rs @@ -0,0 +1,301 @@ +//! Find Similar Photos reads every photo of the library the first time, which left the window not +//! responding for as long as that took (issue #3468): the photos are read on a worker thread under a +//! row of the activity stack. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::mpsc::Receiver; +use std::time::{Duration, Instant}; + +use lightcraft_catalog::{Op, Photo, PhotoId, Source}; +use lightcraft_raster::Rgb32f; +use serde_json::{Value, json}; + +use crate::find_similar::LABEL; +use crate::headless::Headless; +use crate::state::ViewMode; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(60); +const PHOTOS: u64 = 12; +/// How long a read waits for a drive that isn't opened, and how long the frames may take while it does. +const GUARD: Duration = Duration::from_secs(20); +const FRAMES: Duration = Duration::from_secs(15); + +/// The photos' files: a read waits for `open` (a slow drive), at most `guard`, and is counted, as +/// are the reads made on the UI thread. +struct Drive { + open: Arc, + reads: Arc, + on_ui: Arc, +} + +fn app_on_a_slow_drive(guard: Duration) -> (Headless, Drive) { + let mut app = LightcraftApp::new(lightcraft_engine::Session::new(), Services { png: None, ..Default::default() }); + for i in 0..PHOTOS { + let path = format!("/drive/IMG_{i:04}.arw"); + let p = Photo::new(PhotoId(i + 1), Source::File { path }, &format!("IMG_{i:04}.arw"), "ARW", 64, 64, "2026-01-01T00:00:00"); + app.session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + let drive = Drive { open: Arc::new(AtomicBool::new(false)), reads: Arc::new(AtomicUsize::new(0)), on_ui: Arc::new(AtomicUsize::new(0)) }; + let (ui, open, reads, on_ui) = (std::thread::current().id(), drive.open.clone(), drive.reads.clone(), drive.on_ui.clone()); + let deadline = Instant::now() + guard; + app.session.media.file_loader = Some(Arc::new(move |path: &str, _, _| { + // (the grid reads the photos for its thumbnails too, on threads of its own) + let thread = std::thread::current(); + if thread.name().is_some_and(|n| n.starts_with("similar-") || n.contains(LABEL)) { + reads.fetch_add(1, Ordering::SeqCst); + } + if thread.id() == ui { + on_ui.fetch_add(1, Ordering::SeqCst); + } + // (a hang guard: the read goes on after it, so a regression fails the test instead of hanging it) + while !open.load(Ordering::SeqCst) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(1)); + } + // even photos get brighter to the right, odd ones downwards + let across = path.bytes().rfind(u8::is_ascii_digit).is_some_and(|d| d % 2 == 0); + let image = Rgb32f::from_fn(64, 64, |x, y| { + let v = if across { x } else { y }; + [v as f32 / 64.0; 3] + }); + Ok((image, Default::default())) + })); + (Headless::new(app, [1200.0, 800.0], 1.0), drive) +} + +fn rows(h: &Headless) -> Vec { + h.app.session.activity.list().into_iter().filter(|r| r.kind == "similar").collect() +} + +/// The row's wait is over once the task has gone. +fn until_done(h: &mut Headless) { + assert!(h.step_until(T, |h| h.app.tasks.is_empty()), "the search never ended"); +} + +fn ask(h: &mut Headless) -> Receiver { + h.send("engine.execute", json!({"command": "library.findSimilar", "params": {"id": 1}})).unwrap() +} + +fn answer(h: &mut Headless, rx: &Receiver) -> Value { + let t0 = Instant::now(); + loop { + h.step(); + if let Ok(v) = rx.try_recv() { + return v; + } + assert!(t0.elapsed() < T, "never answered"); + std::thread::sleep(Duration::from_millis(1)); + } +} + +/// The issue's report: from the menu, the command answers at once while the files are read, the +/// window takes its frames, the row counts and can stop, and the grid shows what was found. +#[test] +fn a_search_from_the_menu_reads_off_the_ui_thread_and_the_window_goes_on() { + let (mut h, drive) = app_on_a_slow_drive(GUARD); + h.app.ui.view = ViewMode::Detail; + let t0 = Instant::now(); + let r = h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); + assert_eq!(r, json!({"background": true, "count": PHOTOS})); + for _ in 0..3 { + h.step(); + } + // nothing has been read yet: the command and the frames waited for none of it + assert!(t0.elapsed() < FRAMES, "the window waited for the files: {:?}", t0.elapsed()); + assert_eq!(h.app.session.filter, Default::default(), "no answer before the files are read"); + let row = &rows(&h)[0]; + assert_eq!(row.label, LABEL); + assert_eq!(row.total, PHOTOS); + assert!(row.cancellable, "the row can stop the search"); + + drive.open.store(true, Ordering::SeqCst); + until_done(&mut h); + assert_eq!(drive.on_ui.load(Ordering::SeqCst), 0, "a file was read on the UI thread"); + assert_eq!(drive.reads.load(Ordering::SeqCst), PHOTOS as usize); + assert!(rows(&h).is_empty(), "the row goes with the search"); + let shown = h.app.session.filter.only.len(); + assert_eq!(shown, PHOTOS as usize / 2, "the photos alike are shown"); + assert_eq!(h.app.ui.view, ViewMode::PhotoGrid); + let toast = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(toast.starts_with(&format!("{shown} similar photos")), "{toast}"); +} + +/// One search at a time: the menu row is off while one runs and on again after it, and a second +/// request is refused without touching the first. +#[test] +fn a_second_search_waits_for_the_first() { + // what the menu bar draws the row from + let row_is_on = |h: &Headless| crate::menus::menu_entries(&h.app).into_iter().find(|e| e.id == "library.findSimilar").is_some_and(|e| e.enabled); + let (mut h, drive) = app_on_a_slow_drive(GUARD); + assert!(row_is_on(&h)); + h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); + assert!(!row_is_on(&h), "the row is off while one runs"); + let e = h.app.run("library.findSimilar", json!({"id": 2})).unwrap_err(); + assert!(e.contains("already running"), "{e}"); + assert_eq!(rows(&h).len(), 1); + drive.open.store(true, Ordering::SeqCst); + until_done(&mut h); + assert!(row_is_on(&h)); + assert!(h.app.session.filter.only.contains(&PhotoId(1)), "the first search answered"); +} + +/// ✕ on the row: the view stays as it was, nothing is said, and the next search doesn't read again +/// what was read. +#[test] +fn stopping_leaves_the_view_alone_and_the_next_search_reads_only_the_rest() { + let (mut h, drive) = app_on_a_slow_drive(GUARD); + h.app.ui.view = ViewMode::Detail; + h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); + // stopped while the searched photo is being read: that one read is all it does + assert!(h.step_until(T, |_| drive.reads.load(Ordering::SeqCst) == 1), "the first read never started"); + h.app.session.activity.cancel(rows(&h)[0].id).unwrap(); + drive.open.store(true, Ordering::SeqCst); + until_done(&mut h); + assert!(rows(&h).is_empty()); + assert_eq!(h.app.session.filter, Default::default()); + assert_eq!(h.app.ui.view, ViewMode::Detail); + assert!(h.app.ui.toast.is_none(), "{:?}", h.app.ui.toast); + assert_eq!(drive.reads.load(Ordering::SeqCst), 1); + + let r = h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); + assert_eq!(r["count"], PHOTOS - 1, "what was read isn't read again"); + until_done(&mut h); + assert_eq!(drive.reads.load(Ordering::SeqCst), PHOTOS as usize); + assert_eq!(h.app.session.filter.only.len(), PHOTOS as usize / 2); +} + +/// Nothing to read: the answer comes on the next frames, with no photo read. +#[test] +fn a_search_of_what_is_known_reads_nothing() { + let (mut h, drive) = app_on_a_slow_drive(Duration::ZERO); + drive.open.store(true, Ordering::SeqCst); + h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); + until_done(&mut h); + let reads = drive.reads.load(Ordering::SeqCst); + let r = h.app.run("library.findSimilar", json!({"id": 2})).unwrap(); + assert_eq!(r["count"], 0); + until_done(&mut h); + assert_eq!(drive.reads.load(Ordering::SeqCst), reads); + assert!(h.app.session.filter.only.contains(&PhotoId(2))); +} + +/// A refusal comes at once and starts nothing (no photo active, a photo the library doesn't have). +#[test] +fn a_search_that_cannot_start_leaves_no_row() { + let (mut h, drive) = app_on_a_slow_drive(Duration::ZERO); + assert!(h.app.run("library.findSimilar", json!({"id": 999})).is_err()); + assert!(h.app.run("library.findSimilar", json!({"id": "x"})).is_err()); + assert!(h.app.tasks.is_empty()); + assert!(rows(&h).is_empty()); + assert_eq!(drive.reads.load(Ordering::SeqCst), 0); +} + +/// A searched photo that can't be read says so where the person is. +#[test] +fn a_photo_that_cannot_be_read_says_so() { + let (mut h, _) = app_on_a_slow_drive(Duration::ZERO); + h.app.session.media.file_loader = Some(Arc::new(|path: &str, _, _| Err(format!("{path}: gone")))); + h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); + until_done(&mut h); + let toast = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(toast.contains("can't read the photo"), "{toast}"); + assert_eq!(h.app.session.filter, Default::default()); +} + +/// A control request is answered when the search ends, with the command's `{photos}`, and the window +/// takes its frames meanwhile. An agent's view isn't switched for it. +#[test] +fn a_control_request_is_answered_when_the_search_ends() { + let (mut h, drive) = app_on_a_slow_drive(GUARD); + h.app.ui.view = ViewMode::Detail; + let t0 = Instant::now(); + let rx = ask(&mut h); + for _ in 0..3 { + h.step(); + } + assert!(t0.elapsed() < FRAMES, "the frames waited for the files: {:?}", t0.elapsed()); + assert!(rx.try_recv().is_err(), "no answer before the files are read"); + assert_eq!(rows(&h).len(), 1); + drive.open.store(true, Ordering::SeqCst); + let reply = answer(&mut h, &rx); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(reply["result"]["photos"][0]["id"], 1, "{reply}"); + assert_eq!(reply["result"]["photos"].as_array().unwrap().len(), PHOTOS as usize / 2, "{reply}"); + assert_eq!(drive.on_ui.load(Ordering::SeqCst), 0); + assert_eq!(h.app.ui.view, ViewMode::Detail); + assert!(h.app.ui.toast.is_none(), "{:?}", h.app.ui.toast); +} + +/// `activity.cancel` stops the search; the request is told so. +#[test] +fn stopping_answers_the_request_with_an_error() { + let (mut h, drive) = app_on_a_slow_drive(GUARD); + let rx = ask(&mut h); + for _ in 0..3 { + h.step(); + } + let id = rows(&h)[0].id; + let r = h.request("engine.execute", json!({"command": "activity.cancel", "params": {"id": id}}), T); + assert_eq!(r["ok"], true, "{r}"); + drive.open.store(true, Ordering::SeqCst); + let reply = answer(&mut h, &rx); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().is_some_and(|e| e.contains("stopped")), "{reply}"); + assert_eq!(h.app.session.filter, Default::default()); +} + +/// A request that comes while a search runs is refused at once, not left to wait. +#[test] +fn a_second_request_is_refused_at_once() { + let (mut h, drive) = app_on_a_slow_drive(GUARD); + let first = ask(&mut h); + for _ in 0..3 { + h.step(); + } + let second = ask(&mut h); + let refused = answer(&mut h, &second); + assert_eq!(refused["ok"], false, "{refused}"); + assert!(refused["error"].as_str().is_some_and(|e| e.contains("already running")), "{refused}"); + drive.open.store(true, Ordering::SeqCst); + assert_eq!(answer(&mut h, &first)["ok"], true); +} + +/// A caller whose request timed out asks again: what was read stays known, so it isn't read again. +#[test] +fn a_request_nobody_waits_for_any_more_leaves_what_it_read() { + let (mut h, drive) = app_on_a_slow_drive(Duration::ZERO); + drive.open.store(true, Ordering::SeqCst); + drop(ask(&mut h)); + // (a frame takes the request and starts the search) + h.step(); + until_done(&mut h); + let reads = drive.reads.load(Ordering::SeqCst); + assert_eq!(reads, PHOTOS as usize); + let rx = ask(&mut h); + assert_eq!(answer(&mut h, &rx)["ok"], true); + assert_eq!(drive.reads.load(Ordering::SeqCst), reads); +} + +/// Another library was opened: the search stops, and neither its answer nor what it read reaches the +/// new library. +#[test] +fn another_library_stops_the_search_and_gets_nothing_from_it() { + let (mut h, drive) = app_on_a_slow_drive(GUARD); + let rx = ask(&mut h); + for _ in 0..3 { + h.step(); + } + let dir = std::env::temp_dir().join(format!("lc-ui-similar-other-{}", std::process::id())); + h.app.session.open_library(&dir, false).unwrap(); + h.step(); + drive.open.store(true, Ordering::SeqCst); + let reply = answer(&mut h, &rx); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().is_some_and(|e| e.contains("another library")), "{reply}"); + let read = drive.reads.load(Ordering::SeqCst); + assert!(read < PHOTOS as usize, "it stopped reading: {read}"); + assert!(h.app.session.signatures.is_empty()); + assert_eq!(h.app.session.filter, Default::default()); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/ui-egui/src/tests/lens_lookup.rs b/crates/ui-egui/src/tests/lens_lookup.rs new file mode 100644 index 0000000000..d2c9c10155 --- /dev/null +++ b/crates/ui-egui/src/tests/lens_lookup.rs @@ -0,0 +1,50 @@ +//! Enable Lens Corrections looks up again only the photos it switched on (and selected photos that already had +//! corrections on): with Auto Sync off the other selected photos are left alone. + +use lightcraft_engine::Session; +use serde_json::json; + +#[test] +fn ticking_lens_corrections_looks_up_only_the_photos_it_changed() { + let mut s = Session::with_demo(); + s.execute("library.selectAll", &json!({})).unwrap(); + let active = s.selection.active.unwrap(); + assert!(s.selection.ids.len() > 2); + let lp = |s: &Session| s.selection.ids.iter().filter(|id| s.catalog.photo(**id).unwrap().develop.optics.lens_profile).count(); + assert_eq!(lp(&s), 0); + // Auto Sync off: only the active photo is changed, so only it is looked up + s.execute("develop.merge", &json!({"settings": {"optics": {"lens_profile": true}}})).unwrap(); + assert_eq!(crate::lens_db::to_look_up(&s, active), vec![active]); + // Auto Sync on: every selected photo now has corrections on, and each is looked up once + let mut s = Session::with_demo(); + s.execute("library.selectAll", &json!({})).unwrap(); + let active = s.selection.active.unwrap(); + s.auto_sync = true; + s.execute("develop.merge", &json!({"settings": {"optics": {"lens_profile": true}}})).unwrap(); + assert_eq!(lp(&s), s.selection.ids.len()); + let ids = crate::lens_db::to_look_up(&s, active); + assert_eq!(ids.len(), s.selection.ids.len()); + assert_eq!(ids.first(), Some(&active)); +} + +/// A lookup's results are dropped when the lens database was reloaded while the files were read (the probe may have +/// used the old one); the next frame looks the photos up again. +#[test] +fn a_database_reloaded_during_a_lookup_makes_its_results_stale() { + let app = crate::LightcraftApp::new(Session::with_demo(), crate::Services { png: None, ..Default::default() }); + let key = crate::lens_db::lookup_key(&app); + assert_eq!(crate::lens_db::lookup_key(&app), key); + lightcraft_engine::lens_profiles::reload(); + assert_ne!(crate::lens_db::lookup_key(&app), key); +} + +/// Photos that have a database profile (or named no lens) are read again only when the database's files were +/// replaced, never at every start, library switch or folder selection: a big library isn't read at each launch. +#[test] +fn photos_with_a_profile_are_read_again_only_when_the_database_was_replaced() { + use crate::lens_db::look_up_again; + assert!(!look_up_again(None, (1, 1, 0)), "a start with the database already there"); + assert!(!look_up_again(Some((1, 1, 0)), (2, 2, 0)), "another library, or the folder selected again"); + assert!(look_up_again(Some((1, 1, 0)), (1, 2, 1)), "a download replaced it"); + assert!(look_up_again(None, (1, 2, 1)), "replaced before the first lookup"); +} diff --git a/crates/ui-egui/src/tests/lens_offer.rs b/crates/ui-egui/src/tests/lens_offer.rs new file mode 100644 index 0000000000..3e6d51ae96 --- /dev/null +++ b/crates/ui-egui/src/tests/lens_offer.rs @@ -0,0 +1,145 @@ +//! The lens database is offered once, on the first launch, and downloaded only after a click: Download in the offer +//! or in Settings. Not Now downloads nothing and the next start doesn't ask; an installed database and headless +//! hosts (CLI, MCP) never ask (`crate::lens_db`, `lightcraft_engine::lensfun_download::fetch_on_start`). + +use lightcraft_engine::lensfun_download::{self, Offer, Start}; +use lightcraft_engine::{Session, lens_profiles}; + +use crate::state::Dialog; +use crate::{LightcraftApp, Services}; + +/// A desktop-like app (allowed to ask) and a folder of this test's own for the database. +fn desktop(name: &str) -> (LightcraftApp, std::path::PathBuf) { + let mut session = Session::with_demo(); + session.lens_auto_download = true; + let app = LightcraftApp::new(session, Services { png: None, ..Default::default() }); + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + let root = std::env::temp_dir().join(format!("lc-lens-offer-{name}-{}-{unique}", std::process::id())); + (app, root) +} + +/// Nothing listens on port 1: a download started in a test fails at once, without the network. +fn offline() -> Vec { + vec!["http://127.0.0.1:1/db".into()] +} + +fn wait_idle(app: &LightcraftApp) { + let t0 = std::time::Instant::now(); + while app.session.lensfun.running() && t0.elapsed() < std::time::Duration::from_secs(60) { + std::thread::sleep(std::time::Duration::from_millis(20)); + } +} + +/// The first start shows the offer and fetches nothing; Download starts the download (an activity row) and is +/// remembered as the user's yes. +#[test] +fn the_first_start_offers_the_database_and_fetches_nothing_until_download() { + let (mut app, root) = desktop("first"); + let dir = root.join("lensfun"); + let before = lens_profiles::host_dir(); + crate::lens_db::begin(&mut app, lensfun_download::decide(true, false, Some(dir.clone()), false, Offer::Ask), offline()); + let Some(dlg @ Dialog::LensDatabase { .. }) = app.ui.dialog.clone() else { panic!("no offer: {:?}", app.ui.dialog) }; + assert_eq!(app.session.lensfun.state(), lensfun_download::State::Idle, "nothing fetched while it asks"); + assert!(app.session.activity.list().is_empty()); + crate::panels::dialogs::confirm_dialog(&mut app, &dlg).expect("Download"); + assert_ne!(app.session.lensfun.state(), lensfun_download::State::Idle, "Download starts it"); + assert_eq!(app.ui.settings.lens_database, Offer::Accepted); + wait_idle(&app); + lens_profiles::use_dir(before); + let _ = std::fs::remove_dir_all(&root); +} + +/// Not Now (or Esc: closing the offer any way but Download) downloads nothing, is saved with the settings, and the +/// next start doesn't ask. +#[test] +fn not_now_is_remembered_and_the_next_start_does_not_ask() { + let (mut app, root) = desktop("notnow"); + crate::lens_db::begin(&mut app, Start::Ask(root.join("lensfun")), offline()); + assert!(matches!(app.ui.dialog, Some(Dialog::LensDatabase { .. }))); + app.ui.dialog = None; // Not Now + assert_eq!(app.session.lensfun.state(), lensfun_download::State::Idle, "nothing fetched"); + assert_eq!(app.ui.settings.lens_database, Offer::Declined); + // saved and read back with the app's settings + let saved = serde_json::to_value(&app.ui.settings).expect("settings save"); + let read: crate::state::AppSettings = serde_json::from_value(saved).expect("settings read"); + assert_eq!(read.lens_database, Offer::Declined); + assert_eq!(lensfun_download::decide(true, false, Some(root.join("lensfun")), false, read.lens_database), Start::Nothing, "not asked again"); + // a damaged value asks again instead of failing to read the settings + let mut damaged = serde_json::to_value(&app.ui.settings).expect("settings save"); + damaged["lensDatabase"] = serde_json::json!(42); + let read: crate::state::AppSettings = serde_json::from_value(damaged).expect("a bad value doesn't spoil the settings"); + assert_eq!(read.lens_database, Offer::Ask); +} + +/// Settings' Download Lens Database downloads it (after a Not Now, too) and remembers the yes. +#[test] +fn the_settings_button_downloads_the_database() { + let (mut app, root) = desktop("settings"); + let before = lens_profiles::host_dir(); + app.ui.settings.lens_database = Offer::Declined; + crate::lens_db::download(&mut app, &root.join("lensfun"), offline()).expect("started"); + assert_ne!(app.session.lensfun.state(), lensfun_download::State::Idle, "the download ran"); + assert_eq!(app.ui.settings.lens_database, Offer::Accepted); + assert_eq!(lens_profiles::host_dir(), Some(root.join("lensfun")), "and is read once it is in place"); + wait_idle(&app); + lens_profiles::use_dir(before); + let _ = std::fs::remove_dir_all(&root); +} + +/// An installed database means no offer and no download. +#[test] +fn an_installed_database_is_not_offered() { + let (mut app, root) = desktop("installed"); + for offer in [Offer::Ask, Offer::Accepted, Offer::Declined] { + crate::lens_db::begin(&mut app, lensfun_download::decide(true, false, Some(root.join("lensfun")), true, offer), offline()); + assert!(app.ui.dialog.is_none(), "{offer:?}"); + assert_eq!(app.session.lensfun.state(), lensfun_download::State::Idle); + } +} + +/// A headless app (CLI snapshot, MCP) never shows the offer and never fetches, whatever the settings say. +#[test] +fn a_headless_app_never_offers_or_fetches() { + let mut app = LightcraftApp::new(Session::with_demo(), Services { png: None, ..Default::default() }); + assert!(!app.session.lens_auto_download); + for offer in [Offer::Ask, Offer::Accepted] { + app.ui.settings.lens_database = offer; + app.ui.lens_download_checked = false; + crate::lens_db::tick(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.lensfun.state(), lensfun_download::State::Idle); + } +} + +/// A download that can't start keeps the offer open with a toast saying why (Download again or Not Now), from its +/// Download button and from `ui.dialog.confirm`, and isn't remembered as a yes. +#[test] +fn a_download_that_cannot_start_keeps_the_offer_open_and_says_why() { + use crate::headless::Headless; + let t = std::time::Duration::from_secs(20); + let app = LightcraftApp::new(Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + h.step(); + let root = std::env::temp_dir().join(format!("lc-lens-offer-fail-{}", std::process::id())); + // no place to download from: the start is refused + let refused = Dialog::LensDatabase { dir: root.join("lensfun").to_string_lossy().into_owned(), mirrors: Vec::new() }; + let offer_open = |h: &Headless| matches!(h.app.ui.dialog, Some(Dialog::LensDatabase { .. })); + + h.app.ui.settings.lens_database = Offer::Declined; + h.app.ui.dialog = Some(refused.clone()); + h.settle(std::time::Duration::from_secs(10)); + let r = h.request("ui.clickWidget", serde_json::json!({"id": "button:dialogOk"}), t); + assert_eq!(r["ok"], true, "{r}"); + let toast = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(toast.contains("no download location"), "Download says why it didn't start: {toast:?}"); + assert!(offer_open(&h), "the offer stays open: {:?}", h.app.ui.dialog); + assert_eq!(h.app.session.lensfun.state(), lensfun_download::State::Idle); + assert_eq!(h.app.ui.settings.lens_database, Offer::Declined, "a start that failed isn't a yes"); + + // the control channel's confirm keeps it open too + let r = h.request("ui.dialog.confirm", serde_json::json!({}), t); + assert_eq!(r["ok"], false, "{r}"); + assert!(offer_open(&h), "the offer stays open after ui.dialog.confirm: {:?}", h.app.ui.dialog); + assert_eq!(h.request("ui.dialog.cancel", serde_json::json!({}), t)["ok"], true); + assert!(h.app.ui.dialog.is_none(), "Not Now still closes it"); +} diff --git a/crates/ui-egui/src/tests/lifecycle_037.rs b/crates/ui-egui/src/tests/lifecycle_037.rs index d994b93001..7b51cb3feb 100644 --- a/crates/ui-egui/src/tests/lifecycle_037.rs +++ b/crates/ui-egui/src/tests/lifecycle_037.rs @@ -609,7 +609,7 @@ fn hidden_slideshow_pauses_and_keeps_its_remaining_time() { let tex = ctx.load_texture(format!("slide-{}", id.0), egui::ColorImage::filled([2, 2], egui::Color32::WHITE), Default::default()); app.renderer.textures.insert( Slot::Slide(Item::Photo(id)), - Tex { look: None, key: 0, photo: id, tex, size: [2, 2], histogram: None, ms: 0.0, quick: None, pixels: None }, + Tex { look: None, key: 0, photo: id, tex, native: None, size: [2, 2], histogram: None, ms: 0.0, quick: None, pixels: None }, ); } let first = app.ui.slideshow.as_ref().unwrap().play.current(); diff --git a/crates/ui-egui/src/tests/preview_limit.rs b/crates/ui-egui/src/tests/preview_limit.rs index 1b8c37212f..ce5a5aba42 100644 --- a/crates/ui-egui/src/tests/preview_limit.rs +++ b/crates/ui-egui/src/tests/preview_limit.rs @@ -588,7 +588,7 @@ mod in_the_loupe { // Given soft proofing against an output-device profile (rendered on the CPU even with a GPU), a // drag drafts small (#330); proofs into an output space run on the GPU like any render #[test] - fn a_soft_proofed_drag_drafts_small() { + fn a_drag_soft_proofed_to_a_device_profile_drafts_small() { // the GPU device up front (the loupe never waits for it): with one, this is the case where // the GPU is there and the render still goes to the CPU let _ = lightcraft_engine::gpu::available(); @@ -601,6 +601,24 @@ mod in_the_loupe { assert!(main <= small, "the draft is {main} px, a small one at most {small}"); } + // Given soft proofing into a colour space (the GPU renders it), a drag drafts as it does + // without the proof: at full size where the GPU draws the view (review of PR #1065: it + // drafted small, as if the proof went to the CPU) + #[test] + fn a_drag_soft_proofed_into_a_colour_space_drafts_full_size_on_the_gpu() { + let gpu = lightcraft_engine::gpu::available(); + let (_fx, mut h, _) = detail(); + assert_eq!(h.app.ui.proof.profile, 0, "a colour space, no device profile"); + h.app.ui.soft_proof = true; + h.settle(SETTLE); + let (main, small) = drag_exposure(&mut h); + if !gpu { + lightcraft_testkit::skip!(Gpu, "no GPU: every drag drafts small"); + return; + } + assert!(main > small, "the draft is {main} px, a small one would be at most {small}"); + } + fn tile(h: &Headless, slot: Slot) -> Option<(usize, usize)> { h.app.renderer.textures.get(&slot).map(|t| (t.size[0], t.size[1])) } @@ -1211,7 +1229,7 @@ mod in_the_loupe { .iter() .enumerate() .filter_map(|(i, c)| match &c.shape { - egui::epaint::Shape::Mesh(m) if m.texture_id == tex.tex.id() => Some((i, c.clip_rect, m.calc_bounds())), + egui::epaint::Shape::Mesh(m) if m.texture_id == tex.id() => Some((i, c.clip_rect, m.calc_bounds())), _ => None, }) .collect() diff --git a/crates/ui-egui/src/tests/quit_unsaved.rs b/crates/ui-egui/src/tests/quit_unsaved.rs index f703c24a67..bdfb3550a9 100644 --- a/crates/ui-egui/src/tests/quit_unsaved.rs +++ b/crates/ui-egui/src/tests/quit_unsaved.rs @@ -164,3 +164,51 @@ fn damaged_settings_file_is_shown() { h.step(); assert!(!has(&h, "button:noticeOk")); } + +/// A change the catalog log's thread accepted but hadn't written yet (a drive that takes a moment, +/// then fails) is not taken for saved: the quit check waits for the thread, finds the failure and +/// saves everything with the closing snapshot before the window may close (review of #3557). It +/// used to read only the failure the thread had already reported, and close with the change in +/// no file. +#[test] +fn quitting_waits_for_what_the_log_thread_has_not_written_yet() { + use lightcraft_catalog::fault::{self, Step}; + let dir = std::env::temp_dir().join(format!("lc-ui-quit-log-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = lightcraft_engine::Session::new(); + s.open_library(&dir, true).unwrap(); + let id = s.catalog.photos().map(|p| p.id).min().unwrap(); + fault::install( + &dir, + Arc::new(|step| { + if step == Step::Write { + std::thread::sleep(Duration::from_millis(400)); + return Err(std::io::Error::other("the drive is gone (test)")); + } + Ok(()) + }), + ); + let app = LightcraftApp::new(s, Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + let r = h.request("engine.execute", json!({"command": "photo.flag", "params": {"flag": "reject", "ids": [id.0]}}), T); + assert_eq!(r["ok"], true, "{r}"); + let closes = crate::panels::notices::may_close(&mut h.app); + let prompt = h.app.quit_prompt.as_ref().map(|p| p.text().to_string()); + // the files alone, as the next start reads them, hold the change + let copy = dir.with_extension("copy"); + let _ = std::fs::remove_dir_all(©); + std::fs::create_dir_all(©).unwrap(); + for f in [lightcraft_catalog::journal::SNAPSHOT, lightcraft_catalog::journal::LOG] { + if dir.join(f).exists() { + std::fs::copy(dir.join(f), copy.join(f)).unwrap(); + } + } + let (_, c, _) = lightcraft_catalog::Journal::open(Box::new(lightcraft_catalog::store::FsStore::open(©).unwrap())).unwrap(); + let saved = c.photo(id).map(|p| p.flag); + fault::remove(&dir); + drop(h); + let _ = std::fs::remove_dir_all(©); + let _ = std::fs::remove_dir_all(&dir); + assert!(!closes || saved == Some(lightcraft_catalog::Flag::Reject), "closed with the flag in no file: {saved:?}"); + assert!(closes, "the closing snapshot saved it, so the window may close: {:?} {saved:?}", prompt); +} diff --git a/crates/ui-egui/src/tests/zoom.rs b/crates/ui-egui/src/tests/zoom.rs index ebe3ecd22f..518bd477af 100644 --- a/crates/ui-egui/src/tests/zoom.rs +++ b/crates/ui-egui/src/tests/zoom.rs @@ -70,7 +70,18 @@ fn a_pending_crop_or_rotation_does_not_reuse_the_old_textures_aspect() { let tex = h.view.ctx.load_texture("old loupe", egui::ColorImage::filled([4, 3], egui::Color32::BLACK), Default::default()); h.app.renderer.textures.insert( Slot::Main, - Tex { look: Some((old_look, true)), key: 0, photo: id, tex, size: [64, 48], histogram: None, ms: 0.0, quick: None, pixels: None }, + Tex { + look: Some((old_look, true)), + key: 0, + photo: id, + tex, + native: None, + size: [64, 48], + histogram: None, + ms: 0.0, + quick: None, + pixels: None, + }, ); edit(&mut h, |d| d.crop.geometry.rect = lightcraft_geom::Rect::new(0.25, 0.2, 0.75, 0.2 + 1.0 / 3.0)); for (rotate, expected) in [(false, egui::vec2(32.0, 16.0)), (true, egui::vec2(16.0, 32.0))] { diff --git a/docs/background-tasks.md b/docs/background-tasks.md index 0c9281dfc2..6f2b003477 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -61,6 +61,7 @@ guard.detail(&file_name); | Face scan, AI Denoise | `crates/engine/src/cmd/face_recognize.rs`, `crates/engine/src/denoise.rs` | a continuous job with no ✕, kept in session state | | Find Missing Photos | `crates/ui-egui/src/tasks.rs` | a generic background task with a row (`kind: Some(..)`) | | Reload from Disk | `crates/ui-egui/src/reload.rs`, `crates/engine/src/cmd/reload.rs` | a command split into plan / probe / apply so the app reads the files on a worker thread (`tasks::spawn_tracked`: progress and `Cancel::Flag`); the result is committed through `Session::execute_fn` (undo step, save, XMP auto-write), and dropped for a photo a later-started reload has already updated; `wait: true` runs it in place | +| Find Similar Photos | `crates/ui-egui/src/find_similar.rs`, `crates/engine/src/cmd/similar.rs` | a command split into plan / measure / apply, whose reads are kept when it is stopped; a control request is answered when it ends (`Outcome::Later`) | | Reading focus points | `crates/engine/src/focus_scan.rs` | a worker paced by the UI's per-frame pump (`focus.pump {pace}`); `Cancel::Flag`; commits in batches without undo steps | ## Testing diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index be50d23f87..41f9af0c1f 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -1,6 +1,6 @@ -# Sony ARW, Nikon NEF, Panasonic RW2, Fujifilm RAF, Canon CR3/CR2, Pentax PEF, Samsung SRW, Olympus ORF, Epson ERF and Minolta MRW starting look +# Sony ARW, Nikon NEF, Panasonic RW2, Fujifilm RAF, Canon CR3/CR2/CRW, Pentax PEF, Samsung SRW, Olympus ORF, Epson ERF and Minolta MRW starting look -ARW, NEF, RW2, RAF, CR3, CR2, PEF, SRW, ORF, ERF and MRW decoding supply sensor data and camera white-balance multipliers, but currently no measured camera colour matrix. Treating camera RGB as linear sRGB produces a dark, muted default rendering. The loader now estimates a file-local starting look from that file's embedded camera JPEG, only when a usable camera matrix is absent. All output pixels still come from the RAW sensor data; there is no JPEG replacement or uniform saturation boost. +ARW, NEF, RW2, RAF, CR3, CR2, CRW, PEF, SRW, ORF, ERF and MRW decoding supply sensor data and camera white-balance multipliers (CRW only on the D60/10D/300D; on the other CRW bodies the fitted matrix absorbs the white balance), but currently no measured camera colour matrix — with one exception: the Canon EOS D60, whose matrices we measured on a ColorChecker (`crates/raw/src/chart_table.rs`). They give a D60 CRW its colour when its JPEG look cannot be fitted, and its white balance in Kelvin (below); an accepted fit still wins. Treating camera RGB as linear sRGB produces a dark, muted default rendering. The loader now estimates a file-local starting look from that file's embedded camera JPEG, only when a usable camera matrix is absent. All output pixels still come from the RAW sensor data; there is no JPEG replacement or uniform saturation boost. ## Colour and tone are separate @@ -48,7 +48,7 @@ Previously `SourceRef::load()` discarded the decoder's `SourceInfo`, and render Vendor RGB WB multipliers alone do **not** identify an absolute illuminant without camera calibration. The generic model inferred approximately 6829 K / −127 tint for one Sony sample; changing only temperature retained that spurious tint and caused a pink cast. Uncalibrated ARWs, NEFs, RW2s and RAFs keep the file's vendor WB at decode and expose **relative** WB controls around the as-shot look. 6500/0 is the internal neutral reference of that relative scale, not a claim about the capture's measured Kelvin temperature. Presets, picker/auto and manual controls use this reference consistently. Switching from As Shot to Custom first resolves both controls; changing one cannot inherit stale catalog tint. Reset restores the current as-shot reference. Old As Shot numbers in a catalog do not mark an otherwise unchanged photo as edited; Custom WB remains an edit. -**Kelvin through the camera's measured matrices (issue #730).** A raw of a camera in `lightcraft_raw::spectral` (52 bodies: ILCE-7M3, ILCE-7M4, ILCE-7RM3, D850, EOS 5D Mark III…) edits white balance in Kelvin like a DNG, whichever look it got: the matrices read its as-shot multipliers as a temperature and tint (`spectral::as_shot_white_through`, the DNG `AsShotNeutral` reading with the model's `ColorMatrix1/2`) and the Temp slider runs 2000–50000 K with As Shot at that reading. The matrices do nothing else: the colour look stays the file's JPEG fit (or the profile, or the spectral fallback), and the picture is adapted from the as-shot white to the chosen one with Bradford, as every fitted look is — not re-developed in camera space as a DNG is. That keeps one adaptation model per camera whether or not a photo's fit was accepted, and it is what makes the upgrade exact: white balance written on the relative scale before this (no `scale` in the settings' `wb`, `WbScale::Legacy`) renders as the composition of the two Bradford adaptations, which is again one Bradford adaptation (`lightcraft_pipeline::local::legacy_white`), so existing edits are pixel-identical; they are converted to Custom Kelvin values the first time they are edited (`normalize_wb`). The decision is one function on both sides — `lightcraft_catalog::relative_wb_camera(format, camera)` from the catalog's camera string and `files::WbScaleOf` from the file — and a test keeps them in step. A photo imported before this keeps the relative scale's 6500 / 0 as its recorded as-shot white until its file is next decoded for display or reloaded (`Op::SetAsShotWb`, bookkeeping); only the readout waits, not the look. Raws of cameras without measured matrices stay relative, unless their own white-balance presets give the scale (next). +**Kelvin through the camera's measured matrices (issue #730).** A raw of a camera in `lightcraft_raw::spectral` (52 bodies with spectral matrices: ILCE-7M3, ILCE-7M4, ILCE-7RM3, D850, EOS 5D Mark III…, and the Canon EOS D60, whose matrices we measured on a ColorChecker under tungsten and sun, `chart_table.rs`, `clean-room/crw/10-chart-calibration.md`) edits white balance in Kelvin like a DNG, whichever look it got: the matrices read its as-shot multipliers as a temperature and tint (`spectral::as_shot_white_through`, the DNG `AsShotNeutral` reading with the model's `ColorMatrix1/2`) and the Temp slider runs 2000–50000 K with As Shot at that reading. The matrices do nothing else: the colour look stays the file's JPEG fit (or the profile, or the spectral fallback), and the picture is adapted from the as-shot white to the chosen one with Bradford, as every fitted look is — not re-developed in camera space as a DNG is. That keeps one adaptation model per camera whether or not a photo's fit was accepted, and it is what makes the upgrade exact: white balance written on the relative scale before this (no `scale` in the settings' `wb`, `WbScale::Legacy`) renders as the composition of the two Bradford adaptations, which is again one Bradford adaptation (`lightcraft_pipeline::local::legacy_white`), so existing edits are pixel-identical; they are converted to Custom Kelvin values the first time they are edited (`normalize_wb`). The decision is one function on both sides — `lightcraft_catalog::relative_wb_camera(format, camera)` from the catalog's camera string and `files::WbScaleOf` from the file — and a test keeps them in step. A photo imported before this keeps the relative scale's 6500 / 0 as its recorded as-shot white until its file is next decoded for display or reloaded (`Op::SetAsShotWb`, bookkeeping); only the readout waits, not the look. Raws of cameras without measured matrices stay relative, unless their own white-balance presets give the scale (next). **Kelvin through the camera's white-balance presets.** Sony ARWs store, in the encrypted `SR2SubIFD`, the multipliers of every white-balance preset, five of them at a stated temperature (2500, 3200, 4500, 6000 and 8500 K). For a camera without measured matrices whose files carry them (`lightcraft_raw::kelvin_presets`: Sony ILCA-99M2, ILCA-77M2, SLT-A33, DSC-RX10, ILCE-3500, ILCE-7S) they take the matrices' place in everything above: the as-shot multipliers are placed on the curve through the five presets (mired linear along it, in log red/green and blue/green), an offset from the curve is the tint, and the decision, the Bradford adaptation, the pixel-identical upgrade and `Op::SetAsShotWb` are the same. The scale is Sony's own: files shot on the Kelvin setting read back what the dial said (ILCA-77M2 3400 K → 3396 K and 5200 K → 5193 K, SLT-A33 4700 K → 4708 K, the public ILCE-3500 sample's 5600 K → 5594 K; with the colour filter one step towards magenta, the SLT-A33's 3400 K reads 3473 K / +11), and the Shade preset reads 7493 K on the public ILCE-7S sample. Off the curve, two constants come from the 14 Sony bodies that have both measured matrices and presets: the tint is the offset scaled by the locus's own spacing (the matrices give 0.90–1.04 of it), and the isotherms lean against the curve's normal (`ISOTHERM_TILT` 0.74, measured 0.59–0.84). On 150 ILCE-7SM2 photos read both ways, the presets' temperature tracks the matrices' to ±4 mired around Sony's 8 % higher scale, and the tint to −9 ± 4. A listed camera whose file has no presets keeps the Kelvin scale with As Shot at D65, as a covered camera without multipliers does. Bodies with measured matrices keep reading through them. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9c086e5c6f..43ff7a7175 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -89,7 +89,7 @@ filmstrip is visible. | `engine.commands` | — | Engine + UI commands: id, label, menu, shortcut, params doc, enabled | | `ui.menu.list` | — | Menu entries (flat: id, label, menu path, shortcut, enabled) | | `ui.menu.tree` | — | The menu bar as shown (File … Help): items `{id, params?, label, shortcut?, enabled, checked?}`, separators, submenus — the model behind the native macOS menu bar and the in-window menus | -| `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why — see `docs/gpu-pipeline.md`), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file; OK = `button:noticeOk`), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight as the activity stack in the top-left corner shows it, same shape as `activity.list`; a row appears once its task is 0.5 s old, ids `activity:row:`, ✕ = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | +| `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why, `gpuWindowDevice` / `screenTextures` / `mainOnGpu` = renders run on the window's device / can be drawn from the GPU / the loupe shows one now — see `docs/gpu-pipeline.md`), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file; OK = `button:noticeOk`), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight as the activity stack in the top-left corner shows it, same shape as `activity.list`; a row appears once its task is 0.5 s old, ids `activity:row:`, ✕ = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | | `ui.widgets` | `{filter?}` | On-screen widgets `{id, rect: [x, y, w, h]}` (screen points) | | `ui.clickWidget` / `ui.dragWidget` / `ui.hoverWidget` | `{id, count?, button?, fx?, fy?}` (`button: "right"` right-clicks; `count` is capped at 16) / `{id, toX?, toY?, dx?, dy?, steps?}` (steps are capped at 1000) / `{id, fx?, fy?}` | Real egui input on a widget (hover: the pointer rests on it, e.g. for preset/profile previews). `fx`/`fy` are fractions of the registered rect and may lie outside `[0,1]`; the resulting point must still be inside egui's clipped interaction rect, and a non-finite fraction or resolved point is rejected before any input is queued. Geometry comes from the latest completed layout; if the widget moves before the first event or before a press, or its latest clipped rect no longer contains the point, the request fails with an error instead of clicking another widget or retargeting. A target below an ordinary modal dialog may succeed as a no-op or a backdrop click, because egui routes that input to the dialog; a target covered by a non-modal overlay fails. The blocking library-problem/launch-list window is explicit: its dim takes the modal layer, but a background target fails instead of reporting a no-op success, and only that window's own controls (`button:library…`) pass. Its creation frame is shielded and redrawn with empty input like a prompt's, so background text/pointer input cannot act while the new modal areas settle. A quit prompt or settings notice is a real egui modal scope with a foreground backdrop. Only its own buttons (`button:quit…`, `button:noticeOk`) accept a `ui.clickWidget`; background targets fail, and background keystrokes, text/clipboard input, wheel/zoom input and AccessKit actions are dropped before panels see them. The prompt itself takes Tab/Shift+Tab, Enter/Space on the focused button, and Escape/Enter for the safe default Cancel; AccessKit Focus/Click works when targeted at a prompt button. Its first creation frame (including a Tasks→Unsaved or notice→next-notice transition) is shielded and redrawn with empty input, so a press/release in that frame, or a held press from before it, cannot act underneath it; a synthetic drag already in progress is canceled. Once settled, raw `ui.click`/`ui.drag`/`ui.pointer` and backdrop clicks are still delivered to the prompt backdrop as no-ops, and the prompt's own button clicks work normally. The area/layer check cannot see a different widget covering the point in the same layer. A `ui.clickWidget` whose widget disappears before its release also fails, after canceling the pointer press without a click or drag (the same rules apply when a click spans several host frames) | | `ui.move` / `ui.click` / `ui.drag` | `{x, y, count?, button?}` / `{x, y, toX, toY, steps?}` | Raw pointer input, screen points (the same click and step caps apply). In every pointer and scroll gesture a number other than `count` and `steps` must lie between −1,000,000 and 1,000,000, or the request is refused and queues nothing | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 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/gaps.md b/docs/gaps.md index 0e650528d1..566786a5f0 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps: where LightCraft falls short of Lightroom -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-29 · **Change:** minor (LR-LIB-VIRTUALCOPY: default number exhaustion is validated before copy creation; 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: 551 models verified; 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: 551 models verified; 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: 551 models verified; 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: 551 models verified; 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: 551 models verified; 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: 551 models verified; 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: 551 models verified; 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 @@ -15,16 +15,16 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | # | Gap | Evidence | User impact | Hours | Doc | |---:|---|---|---|---:|---| -| 1 B | **Camera colour is estimated, not measured** (LR-PROF-CAMERACOLOR). Raws start from a per-file fit to the camera JPEG, 9 bundled profiles or 52 spectral matrices (plus same-sensor bodies, e.g. the X-T30 through the X-T3); 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); 0 chart-calibrated models 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) | +| 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) | | 7 | **Nikon High Efficiency NEF** (HE / HE★ on Z 8, Z 9, Z 6III, Z f, Z50II, Z5II when set to HE) | named and preview only (#193); needs a pure-Rust JPEG XS decoder | +1.1 points (only shots taken in HE; lossless works on the same bodies); low gain per hour (~0.04), so not a beta blocker | 20–40 | [raw-parity](raw-parity.md) | -| 8 B | **No lens profile database** (LR-EDIT-OPTICS-PROFILE): only DNG opcodes, RW2 in-file distortion, Sony ILCE-7RM4A, full-frame ILCE-7CR distortion (Auto only) and ILCE-7RM6 and ILCE-6700 distortion (`docs/sony-ilce7rm6-lens-corrections.md`) and Nikon Z 6II / Z 8 / Z f distortion (`docs/nikon-lens-corrections.md`); tracked in #329 | Adobe ships 3,635 lens profiles; we never use them | distortion / vignetting correction is a default step for many | 40–80 + calibration shots | [raw-parity](raw-parity.md#lens-profiles) | +| 8 B | **Lens profiles: lensfun only, no picker, no own calibration** (LR-EDIT-OPTICS-PROFILE): the desktop app offers lensfun's database (CC BY-SA 3.0, pinned, never bundled) once on the first launch and downloads it on that click or from Settings, then looks every raw up by its lens ([lens-profiles.md](lens-profiles.md)), but those profiles are not validated against Lightroom, there is no profile picker (in the file / lens database / own calibration) and no calibration wizard; in-file corrections: DNG opcodes, RW2 in-file distortion, Sony ILCE-7RM4A, ILCE-7M3, full-frame ILCE-7CR distortion (Auto only) and ILCE-7RM6 and ILCE-6700 distortion (`docs/sony-ilce7rm6-lens-corrections.md`) and Nikon Z 6II / Z 8 / Z f distortion (`docs/nikon-lens-corrections.md`); tracked in #329 | Adobe ships 3,635 lens profiles; we never use them | distortion / vignetting correction is a default step for many | 40–80 + calibration shots | [raw-parity](raw-parity.md#lens-profiles) | | 9 B | **Tests don't run in CI on macOS or Windows, and no CI job runs the GPU equivalence tests**: the CI gate (`ci.yml`, #2667) runs `cargo xtask ci`, which includes `cargo test`, on Linux x64 for every push to `main` and every pull request; FreeBSD runs `cargo test` nightly, on pushes to `release` and on PRs that change its workflow or `packaging/freebsd/`; the macOS and Windows jobs build packages | `.github/workflows/` (ci, freebsd, packaging-lint, release, sonarcloud, windows-arm64); the gate's runner has Mesa software Vulkan drivers installed, but `Gpu::new` refuses software adapters (`crates/gpu/src/ctx.rs`), so the CPU ↔ GPU equivalence tests skip; the linux-riscv64 release job added in 0.6.0 (#844) runs only `lightcraft-cli --version` under QEMU; #1148 (open, not merged; #2667 names it superseded) has the macOS and Windows test legs and a `LIGHTCRAFT_GPU_ALLOW_SOFTWARE` opt-in that runs the GPU tests on lavapipe, Metal and WARP | a regression that only shows on macOS or Windows, or only on a GPU, reaches users; `cargo xtask ci` runs only on Linux in CI | 6–12 | [target-app-parity](target-app-parity.md#by-dimension) | -| 10 B | **Per-model verification thin, plus cheap per-body decode fixes**: 551 of 1,446 Adobe models verified (38%), ~85% of photographers on a verified body; Nikon 5 bodies verified, Canon 34, Leica 14 (the Q3 by a recorded check of 38 private DNGs). Cheap fixes: Z 6II packed 14-bit NEF (#769, PR #671), Sony A100 regression (#702); F828 SRF now discovered and imported as preview-only, sensor decoding still missing, DSLR-A200…A390 / A850 12-bit ARW (#535) | measured: [raw/coverage.tsv](raw/coverage.tsv) | per-body bugs (levels, crops, WB) surface only from users | 25–45 | [raw-parity](raw-parity.md#by-maker-measured) | +| 10 B | **Per-model verification thin, plus cheap per-body decode fixes**: 557 of 1,446 Adobe models verified (39%), ~86% of photographers on a verified body; Nikon 5 bodies verified, Canon 34, Leica 14 (the Q3 by a recorded check of 38 private DNGs). Cheap fixes: Z 6II packed 14-bit NEF (#769, PR #671), Sony A100 regression (#702); F828 SRF now discovered and imported as preview-only, sensor decoding still missing, DSLR-A200…A390 / A850 12-bit ARW (#535) | measured: [raw/coverage.tsv](raw/coverage.tsv) | per-body bugs (levels, crops, WB) surface only from users | 25–45 | [raw-parity](raw-parity.md#by-maker-measured) | | 11 | **Enhance: Raw Details, Super Resolution; AI denoise without shippable weights or X-Trans** | ENH rows 0%; denoise Bayer only, RawNIND weights GPL and opt-in | Fujifilm users get no AI denoise; nobody gets it out of the box | 30–60 + model decision | [raw-parity](raw-parity.md#demosaic-levels-crops-and-lens-metadata) | | 12 | **Content-aware / generative remove, detect distractions, reflections removal** | REM rows 75%; patch synthesis missing | cleanup work goes back to Photoshop | 25–45 (+ generative model) | [target-app-parity](target-app-parity.md#ai) | | 13 | **Lightroom catalog migration is one-way and approximate**: unsupported Adobe profiles / AI settings archived, history kept as data; main-file pages read on demand up to 16 GiB, with dense-table and WAL bounds retained (#798); offline record counts and destination are now shown in a lasting import result; catalog VIDEO records match the Videos filter, with older classification repaired on reimport; before an import the app asks whether the catalog merges into the open library or goes into a new library (opt-out in Settings, #2672) | lightroom-catalog-import.md | switching users lose some looks | 8–12 | [file-format-parity](file-format-parity.md) | @@ -34,13 +34,13 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 17 | **Tethered capture** | ⬜ | studio photographers | 25–45 + cameras | [hardware-parity](hardware-parity.md) | | 18 | **Video**: playback, trim, global edits, export | VID rows 0% | users who mix stills and clips | 25–45 | [target-app-parity](target-app-parity.md#features) | | 19 | **Plug-in ecosystem**: no Lightroom SDK equivalent (export / publish plug-ins, metadata plug-ins) | ⬜ | pro workflows built on plug-ins (LR/Enfuse, Jeffrey's exporters, Negative Lab Pro) | 40–80 + owner decision | [target-app-parity](target-app-parity.md#by-dimension) | -| 20 | **Long-tail raw formats**: compressed SRW, ARQ pixel shift, IIQ, Hasselblad compression, X3F, CRW, ERF, KDC, DCR, MEF, GPR, old FinePix (MRW decodes since 2026-10-18) | raw-parity.md | small user share each | 40–80 | [raw-parity](raw-parity.md) | +| 20 | **Long-tail raw formats**: compressed SRW, ARQ pixel shift, IIQ, Hasselblad compression, X3F, KDC, DCR, GPR, old FinePix (MRW decodes since 2026-10-18; ERF and MEF since 2026-10-12; CRW since 2026-10-13, the PowerShot G5 anomaly and pre-CIFF compacts remain preview) | raw-parity.md | small user share each | 35–75 | [raw-parity](raw-parity.md) | | 21 | **Localization**: 10 of 16 shipped languages partial (de, es, fr, ja, uk now 97–99% of catalog messages and id every message but What's New, awaiting native review; pt-BR, ru, zh-hans, zh-hant 74–92%), lower-layer errors English; Hindi, Arabic, Korean, Vietnamese absent; no RTL or complex shaping; exports add Thai glyphs only (#2052), with horizontal mark positioning still incomplete and Arabic fallback deferred until joining and bidi exist | measured from catalogs | non-English users see mixed English | 40–70 (shipped to full); 135–239 (four 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) | | 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,9 @@ 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 | | 2026-10-24 | minor | Gap 8: lens profile work is tracked in #329; hours unchanged | | 2026-10-25 | patch | Import Copy and Move report rename-sequence exhaustion per file without losing earlier transfers; no ranked gap or readiness changes | @@ -98,6 +101,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-25 | patch | LR-META-EXIF-FULL rejects extra clock components rather than projecting a plausible prefix; valid DateTimeDigitized, IFD0 DateTime and XMP fallbacks remain available, raw tag values stay visible, and the status / feature counts do not change | | 2026-10-25 | patch | JPEG ICC APP2 chunks are validated as a complete, uniquely numbered sequence before colour conversion; ranked gaps and readiness counts unchanged | | 2026-10-29 | minor | Gap 5: Object / Describe masks are enlarged along the photo's edges, so a raised Exposure no longer outlines the subject (#3272); the gap (heuristic Subject / Sky / People, no model mirror) and its hours are unchanged | +| 2026-10-13 | minor | Gap 20: Canon CRW decoded (clean-room derivation; EOS and G1/G6 verified pixel-exact; G5 preview) — removed from the long-tail list; hours 40–80 → 35–75 after merging main (MRW) | | 2026-10-24 | minor | Gap 28: ⌘⌥⇧C / ⌘⌥⇧V (Ctrl+Alt+Shift+C / V on Windows and Linux) copy and paste metadata; no key leaves the entry; hours unchanged | | 2026-10-24 | minor | Gap 30 shrinks: the Info panel's Show Metadata For (Target Photo / Selected Photos, `view.infoSelectedPhotos`) shows the selected photos' shared values and marks fields that differ as Mixed; the All Metadata dialog remains; 1–3 h (was 4–8) | | 2026-10-24 | patch | Typed GPS input now validates the complete coordinate expression, rejecting unknown text, wrong-axis or conflicting hemispheres, and invalid DMS minutes/seconds before changing metadata; ranked gaps, estimates and readiness counts unchanged | @@ -125,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) | @@ -176,3 +181,4 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-14 | minor | Gap 10: 515 of 1,446 models verified (36%), ~84% of photographers on a verified body (integration batch 36) | | 2026-10-24 | patch | LR-META-XMP: sidecar keywords are written as names in `dc:subject` and paths in `lr:hierarchicalSubject`, so other DAMs can search them; ranked gaps and estimates unchanged | | 2026-10-20 | minor | Opt-in Windows DirectComposition preference added; VRR hardware verification pending; parity counts unchanged | +| 2026-10-25 | minor | Gap 1: first chart-calibrated model, the Canon EOS D60 (ColorChecker Classic under tungsten and sun, `crates/raw/src/chart_table.rs`); the gap stays open, hours unchanged | diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index a35218c46d..6e063e6f90 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -8,6 +8,11 @@ CPU fast guided-filter allocation measurements and reproduction commands are doc [guided-filter-memory.md](guided-filter-memory.md). That optimization retains the full-size base and does not change the GPU's coefficient buffers. +Process V4's camera-look Contrast and Blacks share the CPU's generated lookup tables and +ProPhoto matrices. `finish.wgsl::light_ops` applies them after V2's Whites tone curve and +before the colour stage. Full frames and render windows use the same pointwise operators; +see [calibrated Light operators](light-v3.md) for HDR rules and limits. + Warped geometry uses a CPU-computed coverage bit mask for the source boundary. The CPU reference evaluates that boundary in double precision; GPU float rounding otherwise can turn a blank edge pixel into a photo pixel. The mask @@ -49,6 +54,21 @@ Overrides (read once at launch): - `LIGHTCRAFT_GPU=0`: GPU rendering off for the process (the window is unaffected). - Both `LIGHTCRAFT_GPU=0` and `LIGHTCRAFT_GPU_BACKEND=off` also keep AI Denoise, the face models and the AI mask model (SAM 3 on Metal) on the CPU. +- `LIGHTCRAFT_GPU_ADAPTER=` (any case, e.g. `4070`, `radeon`, `"rtx 4070 super"`): + the graphics card for GPU rendering, AI Denoise and the face models, on a machine with more than one + (`backend::pick_adapter`). Of the hardware cards whose name contains it, the one whose whole name it + is wins, then dedicated before built-in before virtual cards, then wgpu's order + (`backend::choose_named_adapter`); the log says which when several match (`… matches 2 graphics + cards (…): using …`). Software renderers (WARP, llvmpipe) never: a name that matches only one is + logged as such. A name that matches no card is logged + (`gpu: LIGHTCRAFT_GPU_ADAPTER=… names none of the graphics cards (…); using the default choice`) and + the default high-performance card is used. Each line is logged once, though the render device, AI + Denoise and the face models each ask. Each of those makes its own wgpu instance and device, so + devices on different cards share no buffer, pipeline or queue. The window keeps the card wgpu picks for it by power preference, and + rendering runs on a device of its own on the chosen card (the photo is copied to the window's card). + Rendering shares the window's device when the variable is unset or names the window's card + (`backend::may_adopt_window_device`). The log's `gpu: LIGHTCRAFT_GPU_ADAPTER=…: using …` line names the card + used. Handy to keep test runs or a long export off the card the screens hang on. - `LIGHTCRAFT_GPU_ALLOW_SOFTWARE=1`: accept a software adapter (llvmpipe / lavapipe, WARP), which is otherwise refused because the CPU pipeline is faster. For running the GPU tests on a machine without a GPU (below); the app never sets it. @@ -152,7 +172,18 @@ walks the drive. ## Where it is used - `lightcraft_engine::media::develop` (called by every `RenderJob`): loupe / before / compare views, `render_now` (CLI, MCP, control channel renders) and exports render on the GPU when one is - available; grid/filmstrip thumbnails (many small jobs in parallel) stay on the CPU. + available. Thumbnails (grid, filmstrip, preset and profile previews, faces) render on the GPU + once the device is ready (`lightcraft_gpu::ready()`) and on the CPU until then, so they never + wait for device creation at startup. Six workers rendering 256 px thumbnails: 3.6 ms each on an + RTX 5070 vs 4.3–5.2 ms on 32 CPU threads (`crates/gpu/tests/it/thumbs_bench.rs`), and the cores stay + free for raw decoding. +- 8-bit renders take the GPU path with LUT profiles (the `.cube` table rides in the kernel's + `aux` buffer, trilinear like `Lut3d::apply`, after grain), masks with Refine Edges (the cross + guided filter of Auto Mask, blended by √refine before the mask's invert and amount) and soft + proofs into a colour space (proof-space gamut mapping and both gamut warnings, into an output + space or a display). These render on the CPU: high-bit-depth exports and Visualize HDR (both + need float output), soft proofs to an output device's profile (a printer or paper profile), and + photos with a content-aware Fill spot (no GPU kernel for it). - Anything the GPU path cannot do returns `None` and the CPU renders instead: no adapter (CI machines, software-only adapters), `LIGHTCRAFT_GPU=0` or `LIGHTCRAFT_GPU_BACKEND=off` (whole process; see [Backends](#backends-environment-variables-and-troubleshooting-issue-136)), the `app.gpu {enabled}` @@ -178,10 +209,17 @@ walks the drive. (log luminance, dark channel, guided-filter steps, white balance, luminance / colour NR, airlight sampling), `mask` (linear / radial / luminance / colour range / brush shapes, combine, finalize), `finish` (the whole per-pixel stage) — each mirrors a named CPU function. +- Defringe (`fringe_lab`, a separable lightness `minmax` filter, `fringe_apply`; parameters from + `optics::defringe_params`) and spot removal (`spot` module, spot by spot in place: `spot_prep`, + the Heal tone correction as two device Gaussians, `spot_apply`; Remove's 48 candidate sources are + scored by `spot_score` and only the scores are read back; layout and candidates from + `spots::{layout, candidates, ring_dirs, score_radii, rank}`) run on the device in `lin_cpu`'s + order. The histogram is counted on the device (`hist`, atomics, the same sampling grid as + `Histogram::of_srgb8`, so it is exact). - Soft proofing against an output space (`RenderRequest::proof`, with its destination and display gamut warnings) runs in `finish`; a proof against an output-device profile (its 3D table) renders on the CPU. -- Per-stage hybrid: defringe and spot removal (rare, CPU-only for now) download the resampled image, - run on the CPU and upload; heuristic mask shapes (Sky, Subject, Background, …) and brushes of more +- Per-stage hybrid: the camera's local tone mapping (ProRAW gain tables, off by default) runs the + scene-linear stage on the CPU and uploads; heuristic mask shapes (Sky, Subject, Background, …) and brushes of more than 4096 dabs are evaluated on the CPU and uploaded; sources over the buffer limit are resampled on the CPU. - Stage cache: `GpuStages` mirrors `StageCache` (same keys: source identity + `geo`, `lin_key`, @@ -247,7 +285,8 @@ thread. A render's *own* reason comes from `lightcraft_gpu::try_render` (`Err(Fa passes on as `RenderResult::gpu_fallback`; an export carries it as `Exported::gpu_fallback`, and each file of an `app.export` batch result has `gpuFallback` when its render fell back (issue #675). **Reproducing a smaller GPU:** `LIGHTCRAFT_GPU_LIMITS=webgpu` (or `downlevel`) creates the device -with 128 MiB storage bindings / 256 MiB buffers, `LIGHTCRAFT_GPU_LIMITS=` with n MiB / 2n MiB. +with 128 MiB storage bindings / 256 MiB buffers, `LIGHTCRAFT_GPU_LIMITS=` with n MiB / 2n MiB; +the window's device, when adopted, is capped the same way. Tests inject failures with `lightcraft_gpu::inject_fault` (`crates/gpu/tests/it/fallback.rs`, `export_falls_back_to_the_cpu_when_gpu_work_is_lost`). The fault is thread-local, and so are its consequences: a simulated fatal failure stops GPU use on the injecting thread only (`available()` @@ -348,6 +387,38 @@ most likely the largest kernel (`finish.wgsl`) alone (not timed per kernel). wgp opens its own; a refused kernel still means no GPU. The `gpu:` info log line gives the kernel count and build time. +## Drawing renders straight from the GPU +The desktop app creates the window's wgpu device with the adapter's limits and hands it to the GPU +renderer (`lightcraft_gpu::adopt_window_device`, on a background thread at startup: the kernels +build there; the crash sentinel covers it), so rendering and drawing share one device. A slider +drag's drafts of the views (Detail, Before, the zoomed window, hover, Compare, the second window) +are then marked `RenderJob::on_screen`: the render ends in an `Rgba8Unorm` texture +(`lightcraft_gpu::render_display` → `Output::Display`) that egui-wgpu draws as a native texture +(`ScreenTextures` in `ui-egui`, implemented by the app) - no readback, no conversion to egui's +pixels, no re-upload. The per-render checks run on the device instead: every pixel written (an +atomic count), not entirely black (the device histogram). Rows are re-laid at a 256-byte stride +for the texture copy when the width needs it. + +Renders that need pixels keep the readback: the settled full-quality render after a drag (the cached +view preview, overlays, screenshots), thumbnails, exports, overlays (Visualize Spots, mask +overlays), windows that spots grew (cut on the CPU), a monitor profile (corrected on the CPU), and +anything the GPU path declines. A device that doesn't suit (software adapter, too few storage +buffers, kernels that don't build there) makes the renderer create a device of its own, as before. +A headless `ui.screenshot` (the control channel keeps CPU copies of what is drawn) taken while a +view shows a GPU-resident draft reads that texture back for the picture (`ScreenTextures::read`, +`lightcraft_gpu::read_texture`); drawing never does. + +- `LIGHTCRAFT_GPU_WINDOW=0`: never adopt the window's device (a device of its own, renders read + back) - to compare, or for a driver that misbehaves with compute and drawing on one device. +- `ui.inspect` → `perf.gpuWindowDevice` (renders run on the window's device), `perf.screenTextures` + (the UI can draw GPU-resident renders), `perf.mainOnGpu` (the loupe shows one now). +- Measured (RTX 5070, DX12, a 45 MP CR3, 90 exposure steps of a drag at 30 Hz): the loupe's draft + render 1.69 ms median from the texture vs 2.05 ms with the readback; the UI thread unchanged + within noise (~1 ms). The difference grows with the loupe's size (4K/5K displays, zoom). +- With the renderer on the window's device, errors the device raises outside a render (the window's + own included) are logged and stop GPU rendering (CPU from then on) instead of wgpu's default + panic. + ## Opening a photo (M5.4) - The loupe shows a stand-in at once (`media::QuickJob`): the photo's cached view render for its current settings, else (raws with their import look) the embedded camera JPEG, else a @@ -389,10 +460,8 @@ A view's stages keep an uploaded source only up to 96 MB (a Preview-level source 2.5–2.6 GB → 0.91–0.96 GB, heap peak 930 → ~600 MB; stepping median ~13 ms (unchanged). ## Open items -- Keep the loupe texture on the GPU (render into an `egui-wgpu` texture on eframe's device instead of - reading back); share the device with eframe. - WebGPU in the browser build (async init, single device per canvas). -- Defringe and spot removal kernels; Sky/Subject heuristics (replaced by the segmenter in M12). +- Sky/Subject heuristics (replaced by the segmenter in M12); the ProRAW local tone map. - Tiling for sources / outputs beyond the buffer limit (24 MP+ on WebGPU-default limits, 60 MP+ on most desktop adapters; these render on the CPU now): tile with overlap equal to the largest filter radius, with global values (airlight) from a first pass. @@ -400,4 +469,3 @@ A view's stages keep an uploaded source only up to 96 MB (a Preview-level source faster path for exports. - Large-radius blurs at full size (dehaze dark channel at 24 MP) dominate the export: a summed-area table or a downsampled dark channel would cut them further. -- GPU histogram (atomics) to skip the CPU pass over the readback. diff --git a/docs/lens-profiles.md b/docs/lens-profiles.md index 13d1b2b7a7..4e72251b14 100644 --- a/docs/lens-profiles.md +++ b/docs/lens-profiles.md @@ -1,23 +1,63 @@ # Lens profiles from a lens database Raws that carry no lens correction of their own (DNG `OpcodeList3`, or a camera correction a raw reader converts, -see [sony-lens-corrections.md](sony-lens-corrections.md) and [nikon-lens-corrections.md](nikon-lens-corrections.md)) can be corrected from a **lens database in the lensfun -XML format** that you supply. The app does not ship any lens database: lensfun's data is licensed CC-BY-SA 3.0 and -stays a separate download. Adobe LCP profiles are never used. +see [sony-lens-corrections.md](sony-lens-corrections.md) and [nikon-lens-corrections.md](nikon-lens-corrections.md)) are corrected from a **lens database in the lensfun +XML format**. The app does not ship any lens database: lensfun's data is licensed CC BY-SA 3.0 and is downloaded at +run time, never bundled and never committed. Adobe LCP profiles are never used. -## Setup +## Setup: one click -1. Get the lensfun database (the `data/db/*.xml` files of , or the copy a Linux - distribution installs under `/usr/share/lensfun/version_1/`). -2. Point `LIGHTCRAFT_LENSFUN_DIR` at that directory and start the app (or the CLI). +1. Nothing is downloaded without the user's click. On the first launch the desktop app asks once: "Download lens + profiles? LightCraft can correct distortion and vignetting for many lenses using the open lens database + (lensfun, about N MB)", with **Download** and **Not Now** (N is the pinned files' sizes added up). Not Now (or + Esc) downloads nothing and the app doesn't ask again; Settings ▸ General ▸ Lens profiles has **Download Lens + Database** and a switch that turns the offer back on. The answer is kept with the app's settings (`ui.json`, + `lensDatabase`: `ask` / `accepted` / `declined`; a value it can't read asks again), and + `lensfun_download::fetch_on_start` is the one place that decides. After a yes, a start that finds the database + missing or from an older pin downloads it again (an interrupted download resumes). + Download fetches lensfun's `data/db` (56 XML files, about 5 MB) into the app's data folder + (`/lensfun`, beside the face and denoise models; see `crates/engine/src/config.rs`), with a row in + the activity stack (its ✕ stops it). The files are pinned to one lensfun commit by name, + size and SHA-256 (`crates/engine/src/lensfun_download.rs`); a file that differs is thrown away. A later build with + a newer pin replaces them once. The files are staged in `/lensfun.download`, `SOURCE.txt` (the commit + and the licence) is written there last, and the staged folder then replaces the old one as a whole: until it is + in place the previous complete database is used, and if the swap fails it is put back. The app's folder is read + only when it has `SOURCE.txt`, and a folder whose pinned files are missing or cut short is downloaded again. + The CLI (`render`, `merge`, `snapshot`) and the headless MCP server read this folder too, but never ask and never + fetch on their own; `lens.downloadDatabase` fetches it on request from any of them. +2. By default the files come from lensfun's GitHub repository at the pinned commit. `LIGHTCRAFT_LENSFUN_URL` lists + other places serving the same files (base URLs, tried first), e.g. a copy on LightCraft's own server. +3. `LIGHTCRAFT_LENSFUN_DIR` points at a database of your own instead (lensfun's `data/db`, or a Linux + distribution's `/usr/share/lensfun/version_1/`); then the app doesn't offer the download, and that folder is read + even after `lens.downloadDatabase` fetches the app's own copy. -Files are read once per process. Invalid files are skipped with a warning in the log. Without the variable nothing -changes. +When the database arrives (or changes), every library raw without a profile whose lens it knows is read again in the +background and gets its profile; a photo still as imported gets the correction switched on, as import would, and an +edited one keeps its settings. When a download replaced the database's files, the raws whose profile came from the +old database are read again too (they get the new profile, or lose one it no longer gives), and so are raws whose +file named no lens at import. Ticking **Enable Lens Corrections** on a photo without a profile looks it up again +too. `library.refreshLensProfiles` (`all: true` for the wider pass), `lens.downloadDatabase` (which also selects the +downloaded folder) and `lens.databaseStatus` do the same for agents. + +A database profile is pinned to the photo: every render (fresh decode, cached preview, thumbnail, export) uses the +profile the catalog holds, never one a decode looked up in a newer database, and the profile is part of the render +and thumbnail cache keys, so a changed profile never shows an old cached render. A file's own correction comes from +the file as before. + +The Optics panel says which profile is loaded: "Profile: from the file", "Profile: (lens database)", or +"No lens profile found for ". A profile is never copied between photos: presets, Copy / Paste, Sync and Auto +Sync carry Enable Lens Corrections and its amounts, and each photo keeps the profile of its own lens +(`crates/engine/src/tests/lens_refresh.rs`). + +Files are read once per folder and again after a download. Invalid files are skipped with a warning in the log. +Each read logs the folder, whether it is the download or `LIGHTCRAFT_LENSFUN_DIR`, and how many lenses and cameras +it holds; a folder that is missing or holds no lenses is logged as a warning (#2511). The app's own folder before a +download has finished is not read, and says so at info level, since that is the state before the first download. ## What is applied The lens is identified from EXIF: camera make / model (for the mount and crop factor; the 35 mm equivalent focal -length is used when the camera isn't listed) and the lens model string. Lens names match on their words; every +length is used when the camera isn't listed or its crop factor is unknown) and the lens model string. Lens names match on their words; every number (focal lengths, apertures) in the database name must appear in the EXIF name, and the lens maker must agree when the file names one. @@ -44,11 +84,17 @@ half diagonal, or that would fold the image, is not applied. Normalisation follows lensfun's documentation: distortion and TCA radii are 1 at half the shorter side of the calibration frame (its `cropfactor` and `aspect-ratio`), vignetting radii 1 at its corner; the optical centre is -the image centre (lensfun's `
` offsets are not read). +the image centre (lensfun's `
` offsets are not read). Missing or invalid crop factors remain unknown; +only finite values from 0.05 through 20 are accepted. A calibration inherits the lens's crop factor only when its +`cropfactor` attribute is omitted; an explicit invalid override remains unknown. Profiles with an unknown +calibration crop factor are not applied. An explicit crop factor of 1 still means full frame. +On exact lookup-score ties, both named and built-in fixed-lens matching prefer a known calibration crop; a higher +match score still wins even when its crop is unknown. ## Limits - Only raws: rendered images (JPEG, HEIF, TIFF) are often already corrected in camera. - The focus distance is not read from maker notes yet: vignetting uses the farthest calibrated distance. -- No manual make / model picker yet; matching is automatic. +- No manual make / model picker and no choice between sources (in the file, lens database, an own calibration) + yet; matching is automatic, the file's own correction wins. - Not yet validated against real photos and another renderer; the tests use synthetic profiles and grids. 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 46aabad737..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-10-30 · **Change:** minor (LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; LR-LIB-ALBUM: album commands leave out photos the library no longer has and record nothing when they add nothing; LR-BEHAV-DRAGDROP: a right-click on a text field while photos are carried from the grid opens no Cut / Copy / Paste menu; LR-BEHAV-DRAGDROP: a right-click while photos are carried from the grid opens no context menu; LR-LIB-VIRTUALCOPY: default numbering is preflighted across the requested batch and explicit names bypass suffix allocation; LR-BEHAV-DRAGDROP: only the primary button drags photos out of the grid and drops them; KEYC-RATING: deleting a keyword while Enable Filters has the filter put aside no longer leaves an empty one there; LR-BEHAV-DRAGDROP: a drop's destination is named with its parent when another folder or album has the same name; LR-VIEW-FILMSTRIP: photos drag from the filmstrip to the same sidebar targets as from the grid; LRC-LIB-LIBFOLDERS: a deep row's count follows its name in a narrow panel; LR-FILT-FLAG / LRC-LIB-FILTERBAR: the flag toggles combine, Picked + Unflagged, #2588; LR-VIEW-PHOTOGRID, LR-VIEW-FILMSTRIP, LR-VIEW-COMPARE, LR-VIEW-SURVEY, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: the active photo's selection ring shows on light themes and in Compare, Survey and the face tiles, and needs a loaded thumbnail; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-LOCATION: Info GPS text is fully validated before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in point fields; malformed references error; CDATA stays literal; LR-BEHAV-ACCESS: the Thumbnail size control is a slider to screen readers; LR-BEHAV-ACCESS: the Detail photo is named with its file name; LR-VIEW-PHOTOGRID: the grid's empty-view message names its shortcut as this platform writes it and as it is bound; LR-BEHAV-ACCESS: the grid's date headers are named as they read; LR-BEHAV-ACCESS: the sidebar's disclosure triangles name their row; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K Set Keyword Shortcut and ⇧K; KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K Edit Keywords; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-FOLDERS: Local's built-in places (Pictures, Desktop, Downloads, Home) offer no Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; LRC-LIB-CATALOG-SWITCH: a library's catalog.snap or folder given at launch opens that library; LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the dialog makes a new preview each time it opens, also after a failed one, #2708; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-MISSING: `library.missing` from the control channel checks the files on a worker thread instead of the UI thread; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-CROP-AUTO: Auto straighten reads the vertical vanishing point and the horizon; LR-META-EXIF-FULL: reject extra EXIF clock components so invalid capture-time candidates fall through to valid metadata; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-XMP / LRC-MAP-TRACKLOG: malformed ISO times are not projected or matched; LR-IMP-FORMATS: JPEG ICC APP2 chunk validation; LR-BEHAV-TITLEBAR: a dialog leaves the title bar undimmed, as a macOS sheet does; LR-BEHAV-ACCESS: the bars are toolbars and the panels landmarks for screen readers; LR-BEHAV-ACCESS: every dialog and prompt is exposed as a dialog (a modal one, an alert dialog for the prompts); LR-BEHAV-ACCESS: icon-only buttons are named by their label, with the shortcut as the description; MENU-HELP-HELP: on macOS the Help menu is registered with the application only once the menu bar is installed (muda ignores the call before), so AppKit knows which menu is Help; LR-BEHAV-ACCESS: a slider's value field is named ` value`, with how to use it as its description; MENU-BAR: every shortcut the app shows on macOS lists its modifiers ⌃⌥⇧⌘, as the menu bar does; MENU-BAR: on macOS two menu rows that run the same command each get their own native row and label (File ▸ Export… and File ▸ Export with Preset ▸ Custom…; File ▸ New Album… and Photo ▸ Add to Album ▸ New Album…); LR-BEHAV-DIALOGS: a one-line prompt that is refused stays open and says why, and a New Folder on Disk says it was made; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-VIEW-HISTOGRAM: the shadow and highlight clipping buttons take their tile and chevron from the theme, so the chevron reads in every theme; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MASK-BRUSH: extreme brush segments skip the intermediate dabs; LR-MASK-BRUSH: with the mask overlay hidden, the stroke being painted no longer tints the photo) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (LR-PROF-IMPORT: the user's own .dcp camera profiles import, checked on a real D750 profile against Lightroom; before: LRC-DEV-AUTOSYNC: white balance syncs on each photo's own scale, As Shot and Auto per photo; LR-LIB-FLAG: a flag or rating never waits for the drive, PERF-STEP-STALL; LRC-LIB-VISUALSEARCH: Find Similar Photos reads the photos on a worker thread, so a large library no longer freezes the window; LR-MASK-LINEAR: masks stay on the photo's content under lens corrections, Upright, Transform and Rotate; LR-IMP-FORMATS: the Canon CRW decoder is the shared craft-libs crate `craft-crw`; LR-PROF-CAMERACOLOR: chart-measured matrices for the Canon EOS D60, its white balance in Kelvin; CRW imports name their camera; LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; LR-LIB-ALBUM: album commands leave out photos the library no longer has and record nothing when they add nothing; LR-BEHAV-DRAGDROP: a right-click on a text field while photos are carried from the grid opens no Cut / Copy / Paste menu; LR-BEHAV-DRAGDROP: a right-click while photos are carried from the grid opens no context menu; LR-LIB-VIRTUALCOPY: default numbering is preflighted across the requested batch and explicit names bypass suffix allocation; LR-BEHAV-DRAGDROP: only the primary button drags photos out of the grid and drops them; KEYC-RATING: deleting a keyword while Enable Filters has the filter put aside no longer leaves an empty one there; LR-BEHAV-DRAGDROP: a drop's destination is named with its parent when another folder or album has the same name; LR-VIEW-FILMSTRIP: photos drag from the filmstrip to the same sidebar targets as from the grid; LRC-LIB-LIBFOLDERS: a deep row's count follows its name in a narrow panel; LR-FILT-FLAG / LRC-LIB-FILTERBAR: the flag toggles combine, Picked + Unflagged, #2588; LR-VIEW-PHOTOGRID, LR-VIEW-FILMSTRIP, LR-VIEW-COMPARE, LR-VIEW-SURVEY, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: the active photo's selection ring shows on light themes and in Compare, Survey and the face tiles, and needs a loaded thumbnail; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-LOCATION: Info GPS text is fully validated before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in point fields; malformed references error; CDATA stays literal; LR-BEHAV-ACCESS: the Thumbnail size control is a slider to screen readers; LR-BEHAV-ACCESS: the Detail photo is named with its file name; LR-VIEW-PHOTOGRID: the grid's empty-view message names its shortcut as this platform writes it and as it is bound; LR-BEHAV-ACCESS: the grid's date headers are named as they read; LR-BEHAV-ACCESS: the sidebar's disclosure triangles name their row; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K Set Keyword Shortcut and ⇧K; KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K Edit Keywords; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-FOLDERS: Local's built-in places (Pictures, Desktop, Downloads, Home) offer no Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; LRC-LIB-CATALOG-SWITCH: a library's catalog.snap or folder given at launch opens that library; LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the dialog makes a new preview each time it opens, also after a failed one, #2708; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-MISSING: `library.missing` from the control channel checks the files on a worker thread instead of the UI thread; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-CROP-AUTO: Auto straighten reads the vertical vanishing point and the horizon; LR-META-EXIF-FULL: reject extra EXIF clock components so invalid capture-time candidates fall through to valid metadata; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-XMP / LRC-MAP-TRACKLOG: malformed ISO times are not projected or matched; LR-IMP-FORMATS: JPEG ICC APP2 chunk validation; LR-BEHAV-TITLEBAR: a dialog leaves the title bar undimmed, as a macOS sheet does; LR-BEHAV-ACCESS: the bars are toolbars and the panels landmarks for screen readers; LR-BEHAV-ACCESS: every dialog and prompt is exposed as a dialog (a modal one, an alert dialog for the prompts); LR-BEHAV-ACCESS: icon-only buttons are named by their label, with the shortcut as the description; MENU-HELP-HELP: on macOS the Help menu is registered with the application only once the menu bar is installed (muda ignores the call before), so AppKit knows which menu is Help; LR-BEHAV-ACCESS: a slider's value field is named ` value`, with how to use it as its description; MENU-BAR: every shortcut the app shows on macOS lists its modifiers ⌃⌥⇧⌘, as the menu bar does; MENU-BAR: on macOS two menu rows that run the same command each get their own native row and label (File ▸ Export… and File ▸ Export with Preset ▸ Custom…; File ▸ New Album… and Photo ▸ Add to Album ▸ New Album…); LR-BEHAV-DIALOGS: a one-line prompt that is refused stays open and says why, and a New Folder on Disk says it was made; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-VIEW-HISTOGRAM: the shadow and highlight clipping buttons take their tile and chevron from the theme, so the chevron reads in every theme; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MASK-BRUSH: extreme brush segments skip the intermediate dabs; LR-MASK-BRUSH: with the mask overlay hidden, the stroke being painted no longer tints the photo) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -31,7 +31,7 @@ cited here still exists. Formerly docs/parity.md. | C. Views & navigation (VIEW) | 16 | 1 | 1 | 0 | 9/9 (100%) | 4/4 (100%) | | D. Search & filter (FILT) | 11 | 1 | 1 | 0 | 4/4 (100%) | 4/4 (100%) | | E. Metadata (META) | 5 | 1 | 0 | 0 | 2/2 (100%) | 2/2 (100%) | -| F. Edit panel — global adjustments (EDIT) | 43 | 3 | 3 | 1 | 27/28 (96%) | 13/14 (93%) | +| F. Edit panel — global adjustments (EDIT) | 40 | 6 | 3 | 1 | 24/28 (86%) | 13/14 (93%) | | G. Profiles (PROF) | 7 | 1 | 3 | 0 | 3/4 (75%) | 3/3 (100%) | | H. Crop & rotate (CROP) | 10 | 1 | 0 | 1 | 8/8 (100%) | 2/3 (67%) | | I. Remove / healing (REM) | 8 | 1 | 2 | 2 | 4/4 (100%) | 2/3 (67%) | @@ -53,9 +53,9 @@ cited here still exists. Formerly docs/parity.md. | Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 78 | 4 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | | Lightroom Classic extras | 41 | 25 | 21 | 8 | — | 24/26 (92%) | -| **Total** | 420 | 66 | 57 | 35 | 195/203 (96%) | 146/161 (91%) | +| **Total** | 417 | 69 | 57 | 35 | 192/203 (95%) | 146/161 (91%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.4%** of 543 in-scope rows — P0 98.0% of 203 · P1 94.4% of 161 · P2 56.7% of 178. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.1%** of 543 in-scope rows — P0 97.3% of 203 · P1 94.4% of 161 · P2 56.7% of 178. ## Top gaps and shortcut notes @@ -80,8 +80,8 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | 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-SIDECAR-SPLIT | Separate XMP sidecar variants | P2 | ⬜ | `cmd:library.xmpPreferences` | sidecar naming option exists (stem/full), no split sidecars | -| 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), 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 Canon CRW and Sigma X3F (containers recognised by magic, preview found by a structural JPEG scan), 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). 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-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 | @@ -101,7 +101,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-OFFLINE | Keep album offline | P2 | 🚫 | | not applicable: local-first library | | LR-LIB-TARGET | Target album | P2 | ✅ | `cmd:album.setTarget`, `cmd:album.toggleTarget` | see LRC-LIB-COLLECTIONS | | LR-LIB-RATING | Star ratings | P0 | ✅ | `cmd:photo.rate` (`advance`), `cmd:photo.decreaseRating`, `cmd:photo.increaseRating`, `crates/ui-egui/src/shortcuts.rs`, `crates/ui-egui/src/widgets/rating.rs` | one shared star row in the bottom bar, Info panel and filter bar (hover previews, ←/→ on a focused star) and one painter for badges (grid cells, filmstrip, Compare caption); menu rows with star text (Photo ▸ Set Rating, Select By Rating, the grid context menu) are separate menu items, unchanged; 0 clears; 1–5 set; Shift+0–5 applies and advances once, including with Auto Advance. A rating, flag or label that takes the active photo out of the view (filter bar, Picks, smart album) makes the photo after it active (the one before at the end), and Shift / Auto Advance doesn't step past it (#2312). Default grid brackets adjust each photo by one, clamped to 0–5; one batch undo and AutoWrite. Batch grid and undo/redo regressions; macOS native ownership corrected (PR #261) | -| LR-LIB-FLAG | Pick / reject flags | P0 | ✅ | `cmd:photo.pick`, `cmd:photo.reject`, `cmd:photo.unflag`, `cmd:photo.flag` | P pick, X reject, U clear; Shift+P picks and advances in both grids (Presets elsewhere); Shift+X/U and legacy Shift+Z advance; no flag cycle; rejection does not delete the file; a pick shows as a filled flag on thumbnails, in Compare, in the loupe and on the Pick button, a reject outlined (#1013) | +| LR-LIB-FLAG | Pick / reject flags | P0 | ✅ | `cmd:photo.pick`, `cmd:photo.reject`, `cmd:photo.unflag`, `cmd:photo.flag` | P pick, X reject, U clear; a flag or rating never waits for the drive: the catalog log is written and synced by a thread of its own, a failed write is held, retried and counted as unsaved (`crates/catalog/src/log_writer.rs`, PERF-STEP-STALL); Shift+P picks and advances in both grids (Presets elsewhere); Shift+X/U and legacy Shift+Z advance; no flag cycle; rejection does not delete the file; a pick shows as a filled flag on thumbnails, in Compare, in the loupe and on the Pick button, a reject outlined (#1013) | | LR-LIB-LABEL | Colour labels | P1 | ✅ | `cmd:photo.label`, `cmd:photo.clearLabel`, `cmd:label.setNames`, `cmd:label.names`, `cmd:dialog.labelNames`, keys 6–9 in `crates/ui-egui/src/shortcuts.rs` | Photo menu and grid context menu (coloured, named), Info-panel swatches, label dot plus translucent colour on square-grid/filmstrip surrounds and photo-grid footers (photo pixels unchanged); colour-label toasts have pale matching backgrounds; setting/clearing through keys (including Shift), menus or Info swatches shows the same bottom toast as ratings, with the colour/custom name; editable label names (undoable, journaled); no purple key (as in Lightroom), Clear Color Label (`photo.clearLabel`) has no key until one is given in Help → Keyboard Shortcuts, no custom extra labels | | LR-LIB-KEYWORD | Keywords | P0 | ✅ | `cmd:panel.keywords`, `cmd:photo.setMeta` (`addKeywords`/`removeKeywords`), `cmd:keyword.list`, `cmd:keyword.rename`, `cmd:keyword.delete`, `cmd:keyword.merge`, `cmd:keyword.suggest`, `crates/catalog/src/keywords.rs`, `crates/ui-egui/src/panels/left.rs` | left-panel keyword tree with counts (click filters, children included; context menu rename / merge / delete / add / remove); library-wide ops are one undo step and replay from the op log; suggestions (co-occurring / most used / completions) in the Keywords panel; keywords reorganize by drag and drop in the Keyword List (LRC-LIB-KEYWORDS) | | LR-LIB-PEOPLE | People / faces | P2 | 🟡 | `cmd:faces.detect`, `cmd:view.people`, `cmd:view.faceBoxes`, `cmd:photo.removeRegion`, `cmd:photo.setRegion`, `cmd:library.filter`, `crates/ui-egui/src/panels/people.rs`, `crates/catalog/src/query.rs` (`people`), `crates/engine/src/media.rs` (`face_job`), `crates/meta/src/xmp.rs` | MVP: named face regions read from XMP (MWG-RS, read-only, see `docs/xmp-interop.md`; clipped to the photo; Lightroom's `Rotation` of ±π/2 and π handled, mirrored orientations taken as written; boxes follow Rotate Left/Right and flips; a sidecar stating `mwg-rs:Regions`, even empty, replaces the photo's on re-read, one without leaves them) become cards in the People view (View ▸ People, or the People button in the toolbar): a close-up of the person's largest face, name and photo count; a click filters the grid (`person` in `library.filter`, `person:` search token, filter chip). Face boxes in the loupe can be switched off (View ▸ Face Boxes, toolbar) resized with eight drag handles and removed with the × shown on hover (catalog-only and undoable, one undo step per drag; the sidecar is never rewritten for either); no moving a box by dragging it yet. Photo ▸ Detect Faces (`cmd:faces.detect`) finds faces with the YuNet detector (pure Rust, about 200 ms a photo, matches OpenCV's own YuNet on a 45-photo test set; the 232 KB model is a one-time download offered in the same step, never part of LightCraft) and adds them as unnamed boxes; names are suggested from the faces already named (recognition models are opt-in downloads, run on the CPU in a background thread; a face is named only when you confirm it); a person's page shows their cropped faces and the unnamed faces that look like them (LRC-LIB-PEOPLE), with a user-triggered ↑ action or targeted A key to name all shown suggestions at or above one score in one undo step; with recognition on, a background scan finds faces in photos that have none and embeds every face (one to three worker threads, raws through their embedded preview); an Unnamed faces section orders faces by likeness and names a selected group at once; no separated clusters, no manual tagging, no writing regions back | @@ -139,7 +139,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-VIEW-SLIDESHOW | Slideshow | P2 | ✅ | `cmd:view.slideshow` | View ▸ Slideshow (⌥⌘↩): the photos in view full screen from the selected one, played with the library's playback settings (see LRC-SS-PLAYBACK: fades, random order, repeat, previews prepared ahead; `interval` / any setting overrides one run); Space pauses, ←/→ step (a cut), Esc ends; playback controls on pointer movement | | LR-VIEW-SECONDWINDOW | Second display window [Classic] | P2 | ✅ | `cmd:view.secondWindow`, `crates/ui-egui/src/panels/second.rs` | Window ▸ Second Window (⌘F11): the active photo fitted in its own native window with its own render (a floating panel where there are no native windows); loupe view only (no grid / compare / survey there) | | LR-VIEW-CLIPPING | Clipping indicators | P0 | ✅ | `cmd:view.clipping` | | -| LR-VIEW-HISTOGRAM | Histogram | P0 | ✅ | `cmd:view.histogram`, `crates/ui-egui/src/panels/edit/histogram.rs`, `crates/ui-egui/src/panels/right.rs`, `crates/pipeline/src/lib.rs` (`hdr_histogram`) | stays at the top of the Edit panel while its sliders scroll under it (issue #2679, `the_histogram_stays_in_view_while_the_sliders_scroll`); HDR edits: SDR on the left half, the HDR range (0 to 5 stops above SDR white, a fixed scale) on the right with the headroom limit marked; colour bar (white, or Visualize HDR range's colours when that is on) and SDR / HDR labels; the plot's five tonal zones also drag to adjust their Basic control (LRC-DEV-HISTOGRAM-DRAG); it follows slider drags of an HDR edit live (a small render beside the drafts, `Slot::HdrHistogram`) and never drops to the SDR layout mid-drag; an edit with HDR switched off keeps its SDR histogram while it is dragged (#2819); the shadow and highlight clipping buttons at its top corners are the theme's raised fill with a chevron that stands 3:1 on it in every theme and state | +| LR-VIEW-HISTOGRAM | Histogram | P0 | ✅ | `cmd:view.histogram`, `crates/ui-egui/src/panels/edit/histogram.rs`, `crates/ui-egui/src/panels/right.rs`, `crates/pipeline/src/lib.rs` (`hdr_histogram`) | stays at the top of the Edit panel while its sliders scroll under it (issue #2679, `the_histogram_stays_in_view_while_the_sliders_scroll`); HDR edits: SDR on the left half, the HDR range (0 to 5 stops above SDR white, a fixed scale) on the right with the headroom limit marked; colour bar (white, or Visualize HDR range's colours when that is on) and SDR / HDR labels; the plot's five tonal zones also drag to adjust their Basic control (LRC-DEV-HISTOGRAM-DRAG); it follows slider drags of an HDR edit live (a small render beside the drafts, `Slot::HdrHistogram`) and never drops to the SDR layout mid-drag; an edit with HDR switched off keeps its SDR histogram while it is dragged (#2819); turning HDR on or off flows between the layouts (`crates/ui-egui/src/panels/edit/hdr_flow.rs`: the SDR curve squeezes into the HDR layout's SDR section as the HDR section and legend open, and stretches back); the shadow and highlight clipping buttons at its top corners are the theme's raised fill with a chevron that stands 3:1 on it in every theme and state | | LR-VIEW-HDR-DISPLAY | HDR display output | P2 | ⬜ | |, `apps/lightcraft/src/hdr_display.rs` (`choose`, `preferred_hdr_format`) | SDR/HDR decision (platform, surface format, OS headroom, `LIGHTCRAFT_HDR_DISPLAY=0`) is unit-tested and logged at start; always SDR today because eframe configures an 8-bit surface; no OS headroom query yet; | ## D. Search & filter (FILT) @@ -177,13 +177,13 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). |---|---|---|---|---|---| | LR-EDIT-AUTO | Auto settings | P0 | ✅ | `cmd:develop.auto`, `crates/pipeline/src/auto.rs` | a Lightroom-like recipe calibrated black-box on Lightroom's Auto results for 24 Sony raws: Exposure from the scene's scene-linear log-average luminance (Lightroom's observed slope, -0.41 EV per EV), Highlights -66 and Shadows +52 (Lightroom's average Auto values), Contrast +68 and Vibrance +30 fitted on our scales. Held out one photo at a time: on the 16 photos whose start Sony's DRO doesn't brighten, a median dE76 of 6.4 from Lightroom's Auto results against 8.3 unedited; on all 24, 7.7 against 7.9 (issues #318, #209). Calibrated on Sony files only; Whites and Blacks stay 0 | | LR-EDIT-BW | Black & white | P0 | ✅ | `cmd:develop.treatment` | | -| LR-EDIT-HDR-MODE | HDR editing | P2 | ✅ | `cmd:develop.hdr`, `ctl:hdr.maxEv`, `crates/ui-egui/src/panels/edit.rs` (`hdr_row`) | HDR button next to B&W in the Edit panel header, as Lightroom (Visualize HDR and the headroom limit in the Light panel while it's on); see Q. HDR | +| LR-EDIT-HDR-MODE | HDR editing | P2 | ✅ | `cmd:develop.hdr`, `ctl:hdr.maxEv`, `crates/ui-egui/src/panels/edit.rs` (`hdr_row`) | HDR button next to B&W in the Edit panel header, as Lightroom (Visualize HDR and the headroom limit in the Light panel while it's on, sliding open and shut with the histogram's layout change); see Q. HDR | | LR-EDIT-LIGHT-EXPOSURE | Exposure | P0 | ✅ | `ctl:light.exposure` | Alt/Option-drag shows highlight clipping (black, clipped channels in colour) | -| LR-EDIT-LIGHT-CONTRAST | Contrast | P0 | ✅ | `ctl:light.contrast` | | +| LR-EDIT-LIGHT-CONTRAST | Contrast | P0 | 🟡 | `ctl:light.contrast` | From process V4, global Contrast on the camera-look path is fitted per channel in ProPhoto with the sRGB transfer. Check response error 0.136 to 0.038 stops on six held-out Sony photos. Other sources and local adjustments retain V2; broader parity remains unverified (`docs/light-v3.md`). | | LR-EDIT-LIGHT-HIGHLIGHTS | Highlights | P0 | ✅ | `ctl:light.highlights`, `crates/raw/src/highlight.rs` | sensor-clipped highlights stay neutral when Highlights (or Exposure, Whites) darkens them: fully clipped content is rebuilt to the neutral of the colour model applied after it, partly clipped content takes its colour from reliable unclipped content nearby (not from dark objects, lens fringes or another surface beside it) and white where there is none, and pale partly clipped content (a white sky) turns white on its way to clipping (#523); binned previews and thumbnails decide clipping per sample before averaging (`develop_binned_masked`, `highlight::reconstruct_masked`), so a block with one clipped specular sample keeps its mean instead of jumping to the clip level, which reconstruction turned into green speckles at 500 px (#548) From process V2 the Highlights/Shadows base is the edge-aware filter of the 0.15 %-of-long-edge median of log luminance: twigs and fine texture take their surroundings' shift, so bright areas keep their local contrast as with Exposure (V1's base kept ~0.6 of it at −100, #632); region edges stay sharp. Alt/Option-drag shows highlight clipping | | LR-EDIT-LIGHT-SHADOWS | Shadows | P0 | ✅ | `ctl:light.shadows` | From process V2, the same base as Highlights: dark areas keep their local contrast when lifted (#632). Alt/Option-drag shows shadow clipping (white, clipped channels in colour) | -| LR-EDIT-LIGHT-WHITES | Whites | P0 | ✅ | `ctl:light.whites`, `crates/pipeline/src/visualize.rs` | Alt/Option-drag shows highlight clipping (black, clipped channels in colour) | -| LR-EDIT-LIGHT-BLACKS | Blacks | P0 | ✅ | `ctl:light.blacks`, `crates/pipeline/src/visualize.rs` | Alt/Option-drag shows shadow clipping (white, clipped channels in colour) | +| LR-EDIT-LIGHT-WHITES | Whites | P0 | 🟡 | `ctl:light.whites`, `crates/pipeline/src/visualize.rs` | V4 preserves V2 Whites for both signs. Calibration is a planned follow-up; measured V2 check response error is 0.075 stops on the Sony test photos (`docs/light-v3.md`). Alt/Option-drag shows highlight clipping (black, clipped channels in colour) | +| LR-EDIT-LIGHT-BLACKS | Blacks | P0 | 🟡 | `ctl:light.blacks`, `crates/pipeline/src/visualize.rs` | From process V4, global Blacks on the camera-look path uses a fitted per-channel/luminance mix. Check response error 0.424 to 0.077 stops on six held-out Sony photos; deepest tones still differ. Other sources and local adjustments retain V2 (`docs/light-v3.md`). Alt/Option-drag shows shadow clipping (white, clipped channels in colour) | | LR-EDIT-LIGHT-CURVE-PARAM | Parametric curve | P0 | ✅ | `ctl:curve.highlights`, `ctl:curve.lights`, `ctl:curve.darks`, `ctl:curve.shadows`, `ctl:curve.split*`, `crates/pipeline/src/curve.rs` | the graph draws the renderer's own curve model; dragging the line moves the region under the pointer (one undo step) | | LR-EDIT-LIGHT-CURVE-POINT | Point curve | P0 | ✅ | `cmd:develop.curve`, `cmd:curve.reset`, `cmd:curve.presets`, `cmd:curve.applyPreset`, `cmd:curve.savePreset`, `cmd:curve.deletePreset`, `cmd:curve.importPresets`, `cmd:curve.exportPresets`, `cmd:file.importCurvePresets`, `cmd:file.exportCurvePresets`, `crates/engine/src/cmd/curves.rs`, `crates/ui-egui/src/panels/edit.rs` | click to add a point; drag a point in both axes (between its neighbours, input / output readout, one undo step per drag; ⌥-drag moves it a tenth as far for fine adjustment, issue #1363); drag empty space to add and drag; double-click removes; reset: double-click a channel selector (that channel), the Reset button under the graph (every curve incl. parametric) or right-click the graph (channel / all); Point Curve preset dropdown: own Linear / Medium Contrast / Strong Contrast, user presets (save the current point curves, delete by right-click; saved with the library), import / export as `.lccurve` JSON | | LR-EDIT-LIGHT-CURVE-RGB | Per-channel curves | P0 | ✅ | `cmd:develop.curve` (`channel`) | | @@ -204,7 +204,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-EFFECTS-DEHAZE | Dehaze | P0 | ✅ | `ctl:effects.dehaze` | | | LR-EDIT-EFFECTS-VIGNETTE | Post-crop vignette | P0 | ✅ | `ctl:vignette.*`, `crates/pipeline/src/finish.rs`, `crates/ui-egui/src/panels/edit.rs` | style picker (Highlight / Color / Paint) in the Effects section | | LR-EDIT-EFFECTS-GRAIN | Grain | P1 | ✅ | `ctl:grain.*` | | -| LR-EDIT-DETAIL-SHARPEN | Sharpening | P0 | 🟡 | `ctl:detail.sharpenAmount`, `ctl:detail.sharpenRadius`, `ctl:detail.sharpenDetail`, `ctl:detail.sharpenMasking`, `crates/pipeline/src/visualize.rs` | Amount and Masking work; Radius and Detail are stored (XMP round trip) but do not change the render yet (the band is a fixed 0.18 % of the long edge). Alt/Option-drag previews: Amount greyscale, Radius / Detail the detail band sharpening amplifies, Masking the mask (white = sharpened) | +| LR-EDIT-DETAIL-SHARPEN | Sharpening | P0 | ✅ | `ctl:detail.sharpenAmount`, `ctl:detail.sharpenRadius`, `ctl:detail.sharpenDetail`, `ctl:detail.sharpenMasking`, `crates/pipeline/src/visualize.rs` | Process V3: pixel-scale sharpening, working Radius and Detail, original-photo scale in previews and exports; V1/V2 preserve the previous rendering (`crates/pipeline/src/tests_sharpen.rs`). Alt/Option-drag previews: Amount greyscale, Radius / Detail the detail band sharpening amplifies, Masking the mask (white = sharpened) | | LR-EDIT-DETAIL-NR | Luminance noise reduction | P0 | ✅ | `ctl:detail.nrLuminance`, `ctl:detail.nrDetail`, `ctl:detail.nrContrast` | radii in the original's pixels, so grid, loupe and smaller exports look like the full-size render scaled down (`local::nr_params`, `Plan::detail_scale`, #960). Alt/Option-drag on Luminance, Detail and Contrast shows the photo in greyscale | | LR-EDIT-DETAIL-CNR | Colour noise reduction | P0 | ✅ | `ctl:detail.nrColor`, `ctl:detail.nrColorDetail`, `ctl:detail.nrColorSmoothness` | preview-size independent like luminance NR (#960) | | LR-EDIT-DETAIL-DENOISE | AI denoise | P2 | 🟡 | cmd:denoise.toggle, cmd:denoise.models.install, cmd:denoise.queue, ctl:enhance.denoise, `crates/denoise/`, `docs/denoise.md` | non-destructive Bayer RAW, opt-in weights, pure-Rust CPU/GPU; GPU convolution uses independently written shared scalars (Metal equivalence regression, issue #479); tiles can also run on another computer's graphics card (`lightcraft-cli denoise-serve`, `crates/denoise/src/remote.rs`); X-Trans/linear RGB, model policy and Lightroom fidelity remain; closing the model setup without installing turns the switch back off (#922) | @@ -212,7 +212,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-DETAIL-SUPERRES | Super resolution | P2 | ⬜ | | | | LR-EDIT-DETAIL-AISHARPEN | AI sharpen | OOS | 🚫 | | | | LR-EDIT-OPTICS-CA | Remove chromatic aberration | P1 | ✅ | `crates/ui-egui/src/panels/edit.rs` (checkbox), `ctl:optics.caRed`, `ctl:optics.caBlue` | | -| LR-EDIT-OPTICS-PROFILE | Lens profile corrections | P1 | 🟡 | `ctl:optics.profileDistortion`, `ctl:optics.profileVignetting`, `crates/pipeline/src/optics.rs`, `crates/raw/src/vendor/rw2.rs`, `crates/raw/src/vendor/raf_lens.rs`, `crates/engine/src/crs.rs` | uses corrections embedded in the file: DNG `WarpRectilinear` / `WarpRectilinear2` (opcode 14, DNG 1.6: degree-14 radial polynomial, valid-radius clamp, reciprocal option, applied in list order with the spec's skip rule for a `WarpRectilinear` after an optional one, so Pixel DNGs' two-stage warp is corrected; up to 3 chained stages, sampled on the CPU because the polynomials need `f64`; issue #635) / `FixVignetteRadial`, and the camera's own distortion correction in Panasonic / Leica RW2 / RWL files (tag `0x0119`, read as the equivalent `WarpRectilinear`; on 79 photos from 13 bodies and 11 lenses the corrected render lines up with the camera JPEG within 0.75 px at 1440 px at the corners, from up to 13 % of the half diagonal uncorrected; issue #256); an imported preset's `LensProfileEnable=0` leaves them on, as Lightroom applies built-in corrections regardless (inferred); Sony ILCE-7RM4A Bayer ARW raw-IFD distortion tables (`0x7037`, 16-sample layout, native 3:2 framing) use the same warp path, enabled for the independently validated ILCE-7RM4A with FE 24–105 and FE 200–600 lenses, and ILCE-7CR full-frame Bayer 3:2 files with correction Auto or forced Auto (a separate corrected-radius conversion validated against camera JPEGs with FE 24-50mm, FE 16-25mm and FE 50mm lenses); A7CR Off, APS-C, aspect crops and lossless M/S remain uncorrected; ILCE-7RM6 verified against the camera JPEG on 54 photos with three lenses (`docs/sony-ilce7rm6-lens-corrections.md`); other Sony models remain uncorrected (see `docs/sony-lens-corrections.md`); Nikon NEF distortion from NikonNEFInfo (`0xc7d5`: polynomial, frame-filling zoom and the optical-centre offset left by in-body stabilisation; `crates/raw/src/vendor/nef_lens.rs`, `docs/nikon-lens-corrections.md`) for the Z 6II, Z 8 and Z f, full-frame image area only: F-mount lenses on the FTZ match the camera JPEG within 0.2 px median, Z lenses within 0.5–1.5 px except the 24-70 f/4's wide end, where the camera applies a further correction that is not in the readable data (7 px median at 24 mm, from 16 px / 106 px p95 uncorrected); Fujifilm RAF raw-IFD tables (`0xf00b` distortion, `0xf010` vignetting; `crates/raw/src/vendor/raf_lens.rs`, `docs/fuji-lens-corrections.md`) become a `WarpRectilinear` with the camera's frame-filling zoom and a `FixVignetteRadial` gain for 59 body models with sample files checked against the camera JPEG (the table indexed by the source radius with last knot at the corner; on 67 body/lens combinations the corrected render's radial shape error against the camera JPEG falls from a median of 0.72 % to 0.05 % of the half diagonal, largest 0.42 %, and the vignetting gain of the JPEG tracks the table at a median correlation of 0.987); files whose table scale is not the recorded image's half diagonal (X-T30 III, X-M5, X-T5 crops; X-S20 supported) and six unmatched bodies stay uncorrected; Fujifilm's lateral CA table (`0xf00f`) is real but is not applied, because our demosaic already registers the planes and the stored shift over-corrects; vignetting and lateral CA data of Olympus raws not read yet; Sony ARW shading, lateral CA and distortion tables (raw IFD `0x7031`–`0x7037`, with the encrypted `SR2SubIFD` copies as a checked fallback) are decoded with their camera settings, provenance and framing evidence for every body that records them (`crates/raw/src/lens_metadata.rs`), but only the ILCE-7RM4A, ILCE-7RM6 and ILCE-7CR use the separate distortion conversions above; Sony shading and CA semantics are not validated beyond the ILCE-7RM6's (lateral CA off) (`docs/sony-lens-corrections.md`); Reload from Disk reads the file's lens data for photos catalogued without it and turns the correction on for those still at import settings (issue #314); lens-profile database: a lensfun-format XML database in `LIGHTCRAFT_LENSFUN_DIR` (none is bundled) supplies distortion (poly3 / poly5 / PTLens), TCA and vignetting for lenses it lists (`crates/lensdb`, `crates/engine/src/lens_profiles.rs`, `docs/lens-profiles.md`); raws that name no lens model (Nikon DSLRs: maker-note lens specification only) look it up by a name built from the specification (`24-70mm f/2.8`) and take only a profile named exactly that; no settings switch or bundled database yet | +| LR-EDIT-OPTICS-PROFILE | Lens profile corrections | P1 | 🟡 | `ctl:optics.profileDistortion`, `ctl:optics.profileVignetting`, `crates/pipeline/src/optics.rs`, `crates/raw/src/vendor/rw2.rs`, `crates/raw/src/vendor/raf_lens.rs`, `crates/engine/src/crs.rs` | uses corrections embedded in the file: DNG `WarpRectilinear` / `WarpRectilinear2` (opcode 14, DNG 1.6: degree-14 radial polynomial, valid-radius clamp, reciprocal option, applied in list order with the spec's skip rule for a `WarpRectilinear` after an optional one, so Pixel DNGs' two-stage warp is corrected; up to 3 chained stages, sampled on the CPU because the polynomials need `f64`; issue #635) / `FixVignetteRadial`, and the camera's own distortion correction in Panasonic / Leica RW2 / RWL files (tag `0x0119`, read as the equivalent `WarpRectilinear`; on 79 photos from 13 bodies and 11 lenses the corrected render lines up with the camera JPEG within 0.75 px at 1440 px at the corners, from up to 13 % of the half diagonal uncorrected; issue #256); an imported preset's `LensProfileEnable=0` leaves them on, as Lightroom applies built-in corrections regardless (inferred); Sony ILCE-7RM4A Bayer ARW raw-IFD distortion tables (`0x7037`, 16-sample layout, native 3:2 framing) use the same warp path, enabled for the independently validated ILCE-7RM4A with FE 24–105 and FE 200–600 lenses, ILCE-7M3 (FE 16–35 F4 ZA, FE 28–70, FE 50 F1.8; 26 shots within 0.06–0.44 px median of the camera JPEG at 6000 px, from up to 26 px uncorrected), and ILCE-7CR full-frame Bayer 3:2 files with correction Auto or forced Auto (a separate corrected-radius conversion validated against camera JPEGs with FE 24-50mm, FE 16-25mm and FE 50mm lenses); A7CR Off, APS-C, aspect crops and lossless M/S remain uncorrected; ILCE-7RM6 verified against the camera JPEG on 54 photos with three lenses (`docs/sony-ilce7rm6-lens-corrections.md`); other Sony models remain uncorrected (see `docs/sony-lens-corrections.md`); Nikon NEF distortion from NikonNEFInfo (`0xc7d5`: polynomial, frame-filling zoom and the optical-centre offset left by in-body stabilisation; `crates/raw/src/vendor/nef_lens.rs`, `docs/nikon-lens-corrections.md`) for the Z 6II, Z 8 and Z f, full-frame image area only: F-mount lenses on the FTZ match the camera JPEG within 0.2 px median, Z lenses within 0.5–1.5 px except the 24-70 f/4's wide end, where the camera applies a further correction that is not in the readable data (7 px median at 24 mm, from 16 px / 106 px p95 uncorrected); Fujifilm RAF raw-IFD tables (`0xf00b` distortion, `0xf010` vignetting; `crates/raw/src/vendor/raf_lens.rs`, `docs/fuji-lens-corrections.md`) become a `WarpRectilinear` with the camera's frame-filling zoom and a `FixVignetteRadial` gain for 59 body models with sample files checked against the camera JPEG (the table indexed by the source radius with last knot at the corner; on 67 body/lens combinations the corrected render's radial shape error against the camera JPEG falls from a median of 0.72 % to 0.05 % of the half diagonal, largest 0.42 %, and the vignetting gain of the JPEG tracks the table at a median correlation of 0.987); files whose table scale is not the recorded image's half diagonal (X-T30 III, X-M5, X-T5 crops; X-S20 supported) and six unmatched bodies stay uncorrected; Fujifilm's lateral CA table (`0xf00f`) is real but is not applied, because our demosaic already registers the planes and the stored shift over-corrects; vignetting and lateral CA data of Olympus raws not read yet; Sony ARW shading, lateral CA and distortion tables (raw IFD `0x7031`–`0x7037`, with the encrypted `SR2SubIFD` copies as a checked fallback) are decoded with their camera settings, provenance and framing evidence for every body that records them (`crates/raw/src/lens_metadata.rs`), but only the ILCE-7RM4A, ILCE-7M3, ILCE-7RM6 and ILCE-7CR use the separate distortion conversions above; Sony shading and CA semantics are not validated beyond the ILCE-7RM6's (lateral CA off) (`docs/sony-lens-corrections.md`); Reload from Disk reads the file's lens data for photos catalogued without it and turns the correction on for those still at import settings (issue #314); lens-profile database: a lensfun-format XML database in `LIGHTCRAFT_LENSFUN_DIR` (none is bundled) supplies distortion (poly3 / poly5 / PTLens), TCA and vignetting for lenses it lists (`crates/lensdb`, `crates/engine/src/lens_profiles.rs`, `docs/lens-profiles.md`); raws that name no lens model (Nikon DSLRs: maker-note lens specification only) look it up by a name built from the specification (`24-70mm f/2.8`) and take only a profile named exactly that; lens database: the desktop app offers lensfun's `data/db` once on the first launch (Download / Not Now with its size; Settings ▸ General ▸ Lens profiles downloads it later; nothing is fetched without that click; CC BY-SA 3.0, pinned by commit, size and SHA-256, never bundled; `cmd:lens.downloadDatabase`, `crates/engine/src/lensfun_download.rs`) and downloads it with an activity row, and when it arrives every library raw whose lens it knows is looked up again in the background (`cmd:library.refreshLensProfiles`, `crates/engine/src/cmd/lens_refresh.rs`), as is a photo whose Enable Lens Corrections is ticked; the Optics panel names the loaded profile and its source, or says "No lens profile found for " (`crates/ui-egui/src/lens_db.rs`); presets, Copy / Paste and Sync carry only the switch and amounts, never a profile (`crates/engine/src/tests/lens_refresh.rs`); no source picker or own calibration yet | ) | LR-EDIT-OPTICS-DEFRINGE | Defringe | P1 | ✅ | `ctl:optics.defringe*` | no fringe eyedropper | | LR-EDIT-OPTICS-MANUAL | Manual distortion / vignetting | P1 | ✅ | `ctl:optics.distortion`, `ctl:optics.vignetting`, `ctl:optics.vignettingMidpoint` | | @@ -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); 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) @@ -297,7 +297,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-MASK-PEOPLE | People parts | P2 | ⬜ | | shape exists (no UI): uses the photo's person / skin / hair / teeth / glasses mattes when it carries them (DNG semantic masks), else the subject heuristic | | LR-MASK-LANDSCAPE | Landscape classes | P2 | ⬜ | | shape exists, evaluates empty | | LR-MASK-BRUSH | Brush mask | P0 | 🟡 | `cmd:tool.brush`, `cmd:mask.brushStroke` (`autoMask`), `crates/pipeline/src/masks.rs`, `crates/ui-egui/src/brush_live.rs` | size/feather/flow/density/erase; Create New Mask starts a separate brush in paint mode; the stroke shows while the button is held with the committed stroke's dab spacing, feather and flow, so fast strokes have no gaps (#517); with the mask overlay hidden (O / the eye, or after a mask slider hid it) or a colour overlay at opacity 0 it is not tinted while painting either, so dodging and burning is judged on the photo, and its effect shows once the stroke is committed (#2549); coverage builds up by passes, not hold time (holding the brush still adds nothing, live or committed, #518); oversized path segments skip intermediate dabs instead of allocating a million samples; Auto Mask: dabs weighted by similarity to the colour under the dab centre, refined by a guided filter on luminance (CPU + GPU); ⇧-click draws a straight stroke from where the last stroke ended (`connect`), tapering size, feather and flow from that stroke's values when they changed; no A/B brushes; pen pressure (Brush ▸ Pen Pressure, on by default; `pressure` per point in `mask.brushStroke`) scales each dab's size (a tenth to all of it) and flow, live and committed alike, where winit reports a pen force (Windows; not macOS / Linux tablets yet); no tilt | -| LR-MASK-LINEAR | Linear gradient | P0 | ✅ | `cmd:tool.linear`, `cmd:mask.update` | | +| LR-MASK-LINEAR | Linear gradient | P0 | ✅ | `cmd:tool.linear`, `cmd:mask.update`, `crates/pipeline/src/mask_space.rs` | gradients, brushes and AI selections stay on the photo's content when lens corrections, Upright, Transform or Rotate Left / Right change (`Mask.on_photo`; CPU and GPU) | | LR-MASK-RADIAL | Radial gradient | P0 | ✅ | `cmd:tool.radial`, `cmd:mask.update`, `crates/ui-egui/src/panels/detail.rs` | drag the selected ellipse's body or centre pin to move; edge grips resize, outer grip rotates; rotated and compound radial components, hidden pins, outside hit rejection and one-step undo tested | | LR-MASK-COLORRANGE | Colour range | P1 | ✅ | `cmd:mask.add` (`colorRange`), `cmd:mask.sampleColor`, `cmd:mask.update`, `crates/pipeline/src/lib.rs` (`color_range_sample`) | Color tile → click the photo to sample (⇧-click adds, up to 5; samples taken in the space the mask compares in, respecting section eyes and the requested HDR/SDR rendition), Pick button, Refine slider; at most 64 samples (`MAX_COLOR_RANGE_SAMPLES`, render cost is pixels × samples) however the mask arrives: `mask.add` / `mask.update`, a sidecar's `lc:settings`, a preset, `develop.merge`, `render --settings` or the catalog and history keep the first 64 (issue #2556) | | LR-MASK-LUMRANGE | Luminance range | P1 | ✅ | `cmd:mask.add` (`luminanceRange`), `cmd:mask.update`, `crates/ui-egui/src/panels/masking.rs` (`range_controls`) | range bar with two handles (the pressed endpoint stays selected through fast/crossing drags; one undo step per drag), Smoothness, Show Luminance Map (B&W photo with the range tinted) | @@ -399,7 +399,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EXP-HDR | HDR output | P2 | 🟡 | `cmd:app.export`, `crates/ui-egui/src/dialogs.rs` | HDR output checkbox in the export dialog: gain map JPEG, PQ or HLG AVIF, PQ PNG, PQ JPEG XL, float TIFF; no HDR presets yet | | LR-EXP-SHARPEN | Output sharpening | P1 | ✅ | `cmd:app.export` (`sharpen`, `sharpenAmount`) | | | LR-EXP-METADATA | Metadata policy | P1 | ✅ | `cmd:app.export` (`metadata`, `removeLocation`) | Original export is refused when Remove Location Info is on and the source embeds GPS or a nonblank sublocation, city, state or country; rendered exports and XMP sidecars remove those modeled fields | -| LR-EXP-WATERMARK | Watermark | P1 | 🟡 | `cmd:app.export` (`watermark`: text, or `{text, vertical, size, opacity, anchor, insetX, insetY, inset, rotation, color, shadow, image, imageWidth}`), `crates/engine/src/export.rs` (`Watermark`, `WATERMARK_PARAMS`) | text uses Inter SemiBold, the existing Mincho-first CJK chain, then Thai faces from `CRAFT_FONTS_DIR`, shared with contact-sheet captions and slideshow overlays (#2052, partial). Horizontal Thai mark positioning remains incomplete. Arabic export fallback is deferred until joining and bidi reordering exist; UI font fallback is unchanged. Text (`size` = height as a fraction of the short edge, 0.005..0.5, default 0.035; `color` sRGB `[r,g,b]`; `shadow`; Japanese vertical glyph forms and origins, tested by `biz_ud_vertical_watermarks_place_punctuation_at_the_top_right`; extended grapheme cells keep decomposed dakuten/handakuten and Latin accents together, tested by `vertical_watermarks_keep_combining_marks_in_one_cell` and `upright_watermark_cell_retains_multiple_glyphs` (see `docs/vertical-watermarks.md`)) or a graphic with transparency (EXIF orientation applied before sizing; oversized graphics fit the rotated image bounds without stretching, tested by `graphic_watermark_honours_exif_orientation` and `graphic_watermark_keeps_aspect_when_fitted_and_rotated`; `image` path, `imageWidth` = fraction of the photo's width, 0.01..1, converted to the output colour space); `anchor` (nine positions), `insetX` / `insetY` (margins from the side and from the top/bottom edges, each a fraction of the short edge, 0..0.4; the Export dialog's Horizontal and Vertical inset sliders, as in Lightroom Classic; the older single `inset` still reads as both; tested by `watermark_insets_are_horizontal_and_vertical`), `rotation` (0, 90, 180 or 270 degrees clockwise, the Export dialog's Rotate row, as Lightroom Classic's rotate buttons; sized before it is turned, placed and inset by the turned box; tested by `watermark_rotation_turns_the_text_in_its_corner` and `graphic_watermark_is_placed_scaled_and_blended`), `opacity` 0..1. Unknown keys and out-of-range values are errors (issue #183). The Export dialog previews it on the first exported photo's thumbnail (`draw_watermark_preview` scales the 6 px minimum text size to the preview so it matches the file), tested by `watermark_preview_scales_the_minimum_text_size` and `export_dialog_previews_the_watermark` | +| LR-EXP-WATERMARK | Watermark | P1 | 🟡 | `cmd:app.export` (`watermark`: text, or `{text, vertical, size, opacity, anchor, insetX, insetY, inset, rotation, color, shadow, image, imageWidth}`), `crates/engine/src/export.rs` (`Watermark`, `WATERMARK_PARAMS`) | text uses Inter SemiBold, the existing Mincho-first CJK chain, then Thai faces from `CRAFT_FONTS_DIR`, shared with contact-sheet captions and slideshow overlays (#2052, partial). Decomposed (NFD) text, as macOS often writes file names, is composed to NFC first, so Hangul syllables and Vietnamese letters draw whole instead of as loose jamo and marks; CJK compatibility ideographs keep their code points (issue #3480, #3277; `decomposed_hangul_draws_whole_syllables`, `decomposed_vietnamese_draws_its_composed_letters`, `compatibility_ideographs_keep_their_code_points`). Horizontal Thai mark positioning remains incomplete. Arabic export fallback is deferred until joining and bidi reordering exist; UI font fallback is unchanged. Text (`size` = height as a fraction of the short edge, 0.005..0.5, default 0.035; `color` sRGB `[r,g,b]`; `shadow`; Japanese vertical glyph forms and origins, tested by `biz_ud_vertical_watermarks_place_punctuation_at_the_top_right`; extended grapheme cells keep decomposed dakuten/handakuten and Latin accents together, tested by `vertical_watermarks_keep_combining_marks_in_one_cell` and `upright_watermark_cell_retains_multiple_glyphs` (see `docs/vertical-watermarks.md`)) or a graphic with transparency (EXIF orientation applied before sizing; oversized graphics fit the rotated image bounds without stretching, tested by `graphic_watermark_honours_exif_orientation` and `graphic_watermark_keeps_aspect_when_fitted_and_rotated`; `image` path, `imageWidth` = fraction of the photo's width, 0.01..1, converted to the output colour space); `anchor` (nine positions), `insetX` / `insetY` (margins from the side and from the top/bottom edges, each a fraction of the short edge, 0..0.4; the Export dialog's Horizontal and Vertical inset sliders, as in Lightroom Classic; the older single `inset` still reads as both; tested by `watermark_insets_are_horizontal_and_vertical`), `rotation` (0, 90, 180 or 270 degrees clockwise, the Export dialog's Rotate row, as Lightroom Classic's rotate buttons; sized before it is turned, placed and inset by the turned box; tested by `watermark_rotation_turns_the_text_in_its_corner` and `graphic_watermark_is_placed_scaled_and_blended`), `opacity` 0..1. Unknown keys and out-of-range values are errors (issue #183). The Export dialog previews it on the first exported photo's thumbnail (`draw_watermark_preview` scales the 6 px minimum text size to the preview so it matches the file), tested by `watermark_preview_scales_the_minimum_text_size` and `export_dialog_previews_the_watermark` | | LR-EXP-NAMING | File naming | P1 | ✅ | `cmd:app.export` (`naming`, `startNumber`), `crates/engine/src/rename.rs` (`expand_tokens`) | one template language for export, Rename Photos and import renaming: `{name}`, `{num}` (number at the end of the name), `{seq}` / `{seq:N}`, `{date}` / `{date:%Y-%m-%d}`, `{folder}`, `{camera}`, `{lens}`, `{iso}`, `{rating}`, `{title}`, `{creator}`, `{ext}`; free-form template rather than a list of named schemes | | LR-EXP-LOCATION | Destination folder | P0 | ✅ | `cmd:app.export` (`dir`, `destinationMode`: specificFolder / sameAsOriginal, `subfolder`, `conflict`: unique / overwrite / skip), `cmd:export.checkTarget`, `crates/ui-egui/src/dialogs.rs` (Choose… folder picker), `crates/engine/src/originals.rs`, `crates/catalog/src/safe_file.rs` | folder picker on the desktop; Export to: Specific folder or Same folder as original photo (each photo into its original's folder + the subfolder; a demo/browser photo or a missing folder is that photo's error, issue #956); existing files get `-2`, `-3`… by default; the policy covers a file and its sidecars together; a catalogued original (or its sidecar) is never written over, whatever the policy or an exact `path` (export, `ui.render`, MCP `render_photo`, merge `previewPath`, `lightcraft-cli render`); files are written to a temp file and renamed into place (issue #93; not synced file by file — exports can be made again, issue #134) | | LR-EXP-PREVIOUS | Export with previous settings | P0 | ✅ | `cmd:app.exportPrevious`, `cmd:dialog.export` | last options persist in prefs.json; dialog prefilled; no named export presets yet | @@ -465,7 +465,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-OFFLINE | Offline editing | P1 | ✅ | | local-first: everything works offline | | LR-BEHAV-WEB-SAFETY | Library safety in the browser build | P1 | 🟡 | `cmd:file.backupLibrary`, `cmd:file.restoreLibrary`, `apps/lightcraft-web/src/safety.rs`, `apps/lightcraft-web/src/backup.rs`, `apps/lightcraft-web/src/files.rs` | web only (experimental): Back Up Library (zip of the catalog and every stored original) and a non-destructive Restore; failed saves show as unsaved and are retried; a photo that can't be stored isn't added; one tab per library (Web Locks); notices for storage that isn't persistent and for a library that can't open; `?reset` asks first; a panic shows a message. Missing: `?safe` start, deleting originals of removed photos, zip64 (backups > 4 GB) | | LR-BEHAV-GPU | GPU acceleration | P0 | ✅ | `crates/gpu/src/render.rs`, `cmd:app.gpu`, `docs/gpu-pipeline.md`, `crates/ui-egui/src/panels/notices.rs` | CPU fallback per render on device limits, out of memory, device errors / loss, incomplete or black results (`perf.gpuReason`, `perf.gpuFallback`; each render reports its own reason — `lightcraft_gpu::try_render`, `gpuFallback` per exported file — issue #675); short submissions for slow iGPUs; backend choice (DX12 only on Windows, `LIGHTCRAFT_GPU_BACKEND` / `WGPU_BACKEND`), device created after the window opens, crash sentinel (issue #136); a GPU lost while LightCraft runs (driver reset) stops it with that message and turns GPU rendering off for the next start, which says why (issue #1337; the window's renderer can't survive the lost device); quitting waits (up to 2 s) for renders in flight and starts no new GPU work, so none is inside the driver when the process exits (`crates/gpu/src/exit.rs`, issue #620; seen crashing only on Linux + NVIDIA, other drivers unverified); with GPU rendering on and no adapter found at all (e.g. no Vulkan loader on NixOS outside `nix develop`), the desktop app says once per session that it renders on the CPU and points to Help ▸ System Info (`gpu_notice`; not when the GPU is turned off or only a software adapter exists); no tiling beyond the buffer limit (CPU) | -| LR-BEHAV-RENDER-FIDELITY | Rendering matches Lightroom | P1 | 🟡 | `crates/pipeline/src/lib.rs`, `crates/pipeline/src/tone.rs` | every slider exists and works, but the character of the result (tone curve shape, highlight recovery, texture / clarity / dehaze, noise reduction, sharpening, default look) is tuned by eye; there is no systematic side-by-side comparison against Lightroom on the same CC0 raws. Needs a fidelity suite: Lightroom reference renders kept only in the local `plan/` (never committed), compared per slider and preset with a perceptual metric. Tuning that changes how existing settings render ships as a new process version (LRC-DEV-PROCESS, `docs/process-versions.md`) | +| LR-BEHAV-RENDER-FIDELITY | Rendering matches Lightroom | P1 | 🟡 | `crates/pipeline/src/lib.rs`, `crates/pipeline/src/tone.rs` | Process V4 calibrates global camera-look Contrast and Blacks against black-box Lightroom exports of Sony ILCE-7CR photos. Held-out response errors are 0.038 and 0.077 stops; V1/V2 keep their rendering. Whites retains V2 and awaits a follow-up. Exposure, Highlights/Shadows, other operators and broader camera coverage remain open (`docs/light-v3.md`). | | LR-BEHAV-DRAGDROP | Drag and drop | P1 | ✅ | `crates/ui-egui/src/lib.rs`, `crates/ui-egui/src/panels/grid.rs` (`drag_feedback`), `crates/ui-egui/src/panels/left.rs` (`drop_target`, `album_drag_over`, `top_level_drop_target`, `drag_auto_scroll`), `crates/ui-egui/src/destination.rs`, `crates/ui-egui/src/widgets.rs` (`context_menu`), `crates/ui-egui/src/widgets/text_field.rs`, `crates/ui-egui/src/tests/carried_right_click.rs`, `crates/ui-egui/src/tests/carried_text_field_menu.rs` | a right-click while photos are carried opens no context menu (every menu opened through `widgets::context_menu`: sidebar rows, grid cells, lists; a text field's own Cut / Copy / Paste menu too); files → app (a drop-target card while they hover, then the import review); grid photos → an album row (adds the selection, with a count badge while dragging); sidebar album / folder rows → a folder (moves it; its name follows the pointer); a drag of albums or grid photos near the top or bottom edge of the sidebar scrolls it (faster nearer the edge, only while the pointer is over the sidebar); when another folder has the same name, the dragged label, the Move question and the toast name the folder it is in (`home (/a)`); an album drop's toast does the same for an album of that name in another album folder (two in the same place have nothing to tell them apart and keep the plain name); only the primary button drags photos and drops them: a right-button drag over a grid cell neither picks photos up nor changes the selection, and a right-button release while photos are dragged neither drops them nor ends the drag | | LR-BEHAV-TOAST | Toast notifications | P1 | ✅ | `crates/ui-egui/src/panels.rs` | | | LR-BEHAV-DIALOGS | Dialogs fit the window | P1 | ✅ | `crates/ui-egui/src/dialogs.rs` (`dialog_body`, `list_height`), `crates/ui-egui/src/tests/dialog_fit.rs`, `crates/ui-egui/src/tests/dialog_copy.rs`, `crates/ui-egui/src/tests/dialogs.rs` (`a_click_outside_closes_the_dialog_when_settings_allow_it`) | a dialog taller than the window (Export on a 1366×768 screen, issue #781) never runs off it: its options scroll while the title bar and the Cancel / confirm row stay on screen (the confirm button names its action: Create, Rename, Create Stacks, Export 3 Photos…, with "OK" kept only for a one-field prompt opened with a command that has no verb, `crates/ui-egui/src/tests/dialog_copy.rs`); lists that scroll on their own (What's New, All Metadata, shortcuts, smart-album rules, credits) get shorter first; dialogs that fit look as before; Import keeps its own resizable, scrolling window; Settings → Dialogs → Close a dialog by clicking outside it (off by default, so a stray click never throws away a dialog's choices): a click pressed and released on the dimmed backdrop closes the dialog like Esc and doesn't reach the panels below, while a drag that ends outside (a slider pulled past the edge) or a click that closes a dropdown keeps it; the import review never closes this way (`clicked_backdrop`); a one-line prompt (Rename Folder, New Folder on Disk, the preset and version names, New Library when its name can't be used, Auto-Tag from Tracklog) the engine refuses stays open with its text and shows the reason in a toast, so the name can be corrected, where it used to close without a word; a New Folder on Disk that works says so (“Created folder “Selects” in “2026/Shoot””, naming the parent by its last two folders as dialogs do) | @@ -716,7 +716,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-QUICKDEV | Quick develop | P2 | ✅ | `cmd:develop.quickAdjust`, `crates/ui-egui/src/panels/edit.rs` (`quick_develop`) | grid with several photos selected: Edit panel ▸ Quick Develop steps (exposure ⅓ / 1 stop, contrast, highlights, shadows, whites, blacks, clarity, vibrance, temperature) added to each photo's own value, one undo step | | LRC-LIB-PEOPLE | People view | P2 | 🟡 | `cmd:view.people`, `cmd:view.person`, `cmd:faces.person`, `cmd:faces.unnamed`, `cmd:faces.nameFaces`, `crates/ui-egui/src/panels/people.rs`, `crates/ui-egui/src/panels/person.rs`, `crates/ui-egui/src/panels/unnamed.rs`, `crates/engine/src/face_tiles.rs` | Named People cards (face close-up, the photo count on the picture, name) for the photos the active filters let through, with the filter chips shown above them, sized by the thumbnail slider. Below them the **Unnamed faces**: every face nobody has named as a cropped picture, look-alikes next to each other once recognition has looked at them, a suggested name on a face the named ones recognise; click or Shift-click to select, type a name, Enter names the whole group in one undo step. A click on a person opens their page: only cropped faces, then **More** (unnamed faces that look like them, best first; click to confirm one, × to hide for the session, or ↑ / hovered-or-focused A key to confirm all currently shown non-hidden suggestions at or above that face's score, including ties, in one undo step). Every face is shown by the detector's box where the scan has one, so faces are equally close. Until recognition is set up a line at the top offers the next step (Settings ▸ Faces, or Turn on), as does the loupe's name box. Face pictures of unedited raws are cut from the largest embedded preview (planned read: header and JPEG only, never the sensor data) when it holds at least ¾ of the tile's pixels across the face, else developed as before; all are kept in the thumbnail disk cache at 16 px size steps, so a later launch shows them without reading the originals (#1440, `docs/faces.md`). No clusters with separators between groups, no persistent reject, no merge of two people | LRC-LIB-COMMENTS | Comments panel | P2 | ⬜ | | | -| LRC-LIB-VISUALSEARCH | Find similar photos | P2 | ✅ | `cmd:library.findSimilar`, `crates/pipeline/src/cull.rs` (`signature`) | photo menu / Photo ▸ Find Similar Photos: look-alike photos (composition and tones), most similar first, as a filter (`only`) | +| LRC-LIB-VISUALSEARCH | Find similar photos | P2 | ✅ | `cmd:library.findSimilar`, `crates/pipeline/src/cull.rs` (`signature`), `crates/engine/src/cmd/similar.rs`, `crates/ui-egui/src/find_similar.rs` | photo menu / Photo ▸ Find Similar Photos: look-alike photos (composition and tones), most similar first, as a filter (`only`); the app reads the photos on a worker thread under an activity row with ✕ | | LRC-LIB-MISSING | Missing files & relink | P1 | ✅ | `cmd:library.missing`, `cmd:photo.relink`, `cmd:library.findMissing`, `cmd:file.findMissing`, `cmd:photo.locate`, `crates/engine/src/cmd/missing.rs` (`checked_path`), `crates/ui-egui/src/missing_sweep.rs`, `crates/ui-egui/src/panels/left.rs` (`locate_missing_item`) | File → Find Missing Photos… (anywhere in a folder: same name, size and content hash; renamed files by size + content hash; same name and size alone only when unambiguous — look-alikes are skipped and reported; searched on a worker thread, one undo step), photo menu → Locate Missing File…; a folder or disk row's Locate Missing Files… chooses its new location and scopes the same recursive background finder to that folder and its subfolders. Unreadable files show "!" in the grid and a reason in the loupe; undo never moves files. Missing Photos in the sidebar (counted on a worker thread; the view, the Info panel, the grid's context menu and thumbnails read file availability from a cache a worker thread fills, so an offline NAS never stalls a frame); it covers library photos only — Local browse records are never checked, for the count, the view, `library.missing` and Find Missing alike; `library.missing` from the control channel or `mcp --connect` checks the files on a worker thread (a "Missing Photos" row in the activity stack, ✕ stops it) and answers when it ends, so a large library on a network share never stalls the window; the same request meanwhile shares the running check | | LRC-LIB-CONVERT | Convert to DNG | P2 | ✅ | `cmd:photo.convertToDng`, `crates/engine/src/cmd/convert.rs` | Photo ▸ Convert to DNG: lossless DNG next to the raw with the settings embedded, photo (and its virtual copies) relinked; originals kept; undoable; the DNG is decoded and compared with the raw data, written to a temp file, synced, read back and only then given a free name (never replacing a file) — a failed write leaves no DNG and the photo on its raw (issue #106) | | LRC-LIB-PREVIEWS | Build / discard previews | P1 | ✅ | `cmd:library.buildPreviews`, `cmd:library.previewProgress`, `cmd:library.cancelPreviews`, `cmd:library.clearPreviews`, `crates/engine/src/cmd/previews.rs`, `crates/preview/src/lib.rs` | File ▸ Previews: build standard-sized (Settings → Performance size) or 1:1 previews of the selected / visible photos in the background (a row in the activity stack, ✕ to stop), discard the cache; disk thumbnail + view cache; no smart previews (offline proxies) | @@ -724,12 +724,12 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-DEV-SNAPSHOTS | Named snapshots | P1 | ✅ | `cmd:version.create`, `cmd:version.restore` | = versions | | LRC-DEV-HISTORY | Full history panel | P1 | ✅ | `cmd:history.list`, `cmd:history.restore`, `cmd:history.previous`, `cmd:history.next`, `cmd:history.clear` | row menu: copy step to before, create version from step, clear history; clicking a step loads it without adding one (current step highlighted, later steps greyed and returnable until a new edit truncates them; one undo step; cursor saved in the catalog, old catalogs open at the latest step) | | LRC-DEV-SOFTPROOF | Soft proofing | P2 | 🟡 | `cmd:view.softProof`, `crates/pipeline/src/output.rs` (`Proof`), `crates/ui-egui/src/panels/edit.rs` (`soft_proofing`) | S in the loupe (in grids S stays Expand/Collapse Stack): paper-white surround and "Proof Preview", proof profile (sRGB / Display P3 / Adobe RGB / ProPhoto / Rec. 2020), destination (red) and display (blue) gamut warnings (the display's gamut is the monitor profile's, `cmd:app.displayProfile`, else sRGB), Create Proof Copy (a named virtual copy). printer / paper ICC profiles can be loaded as the proof profile (size-capped, the last few kept), with rendering intent (Perceptual / Relative Colorimetric), Simulate Paper & Ink and a device-gamut warning (`crates/codecs/src/proof.rs`, `crates/engine/src/proof.rs`); on the GPU for output-space proofs (destination and display gamut warnings included; equivalence-tested), an output-device profile's 3D table on the CPU | -| LRC-DEV-AUTOSYNC | Sync / auto sync / paste previous | P1 | ✅ | `cmd:develop.sync`, `cmd:develop.autoSync`, `cmd:develop.pastePrevious` | Edit ▸ Sync Settings / Auto Sync (⌥⇧⌘A): only the changed settings carry over, one undo step, slider drags sync on release, spots / red eye stay per photo; Edit panel banner | +| LRC-DEV-AUTOSYNC | Sync / auto sync / paste previous | P1 | ✅ | `cmd:develop.sync`, `cmd:develop.autoSync`, `cmd:develop.pastePrevious` | Edit ▸ Sync Settings / Auto Sync (⌥⇧⌘A): only the changed settings carry over, one undo step, slider drags sync on release, spots / red eye stay per photo; every synced setting gets the active photo's value; with Auto Sync, white balance goes on each photo as its mode or on its own scale (As Shot: its own camera white; Auto: its own, from its pixels; a light preset: its numbers; a Temp or Tint: only the slider that moved, so each keeps its own tint, as the same number on a photo of the same scale (the same Kelvin on raws edited in Kelvin) and moved by as much as the active photo on one of another scale, such as a JPEG beside a raw), `crates/engine/src/sync_same.rs`; Sync Settings copies the active photo's stored white balance; Edit panel banner | | LRC-DEV-MATCHEXP | Match total exposures | P2 | ✅ | `cmd:develop.matchExposure` | Photo ▸ Match Total Exposures: the selected photos' Exposure set so shutter × ISO ÷ aperture² plus the slider matches the active photo's | | LRC-DEV-CALIB | Calibration panel | P1 | ✅ | `ctl:calibration.*` | | | LRC-DEV-TAT | Targeted adjustment tools | P1 | ✅ | `cmd:develop.targeted` (`target`: curve / hue / sat / lum) | | | LRC-DEV-DEFAULTS | Per-camera raw defaults | P1 | ✅ | `cmd:library.preferences` (`camera`, `import.perCamera`), `crates/ui-egui/src/dialogs/settings.rs` | Settings → Import: raw default and per-camera presets | -| LRC-DEV-PROCESS | Process versions, Update to Current Process | P1 | ✅ | `cmd:develop.updateProcess`, `cmd:develop.reset`, `cmd:develop.get`, `crates/develop/src/settings.rs`, `crates/pipeline/src/finish.rs`, `docs/process-versions.md` | each photo records the rendering process its settings are interpreted by: settings saved before this existed load as V1, new photos and Reset get the latest, virtual copies inherit, copy / paste / sync / presets keep each photo's own; Photo ▸ Update to Current Process (one undo step, enabled while a selected photo is on an older process); a number from a newer LightCraft is kept and renders with the newest known process. Only V1 exists so far: this is what lets a retuned default tone (#146) or stronger Light sliders (#196) ship without changing existing edits | +| LRC-DEV-PROCESS | Process versions, Update to Current Process | P1 | ✅ | `cmd:develop.updateProcess`, `cmd:develop.reset`, `cmd:develop.get`, `crates/develop/src/settings.rs`, `crates/pipeline/src/finish.rs`, `docs/process-versions.md` | Each photo keeps its saved rendering process. V1 is legacy, V2 preserves Highlights/Shadows detail, V3 is pixel-scale sharpening, V4 calibrates camera-look Contrast and Blacks. New photos and Reset use the latest; Update is one undoable step and never downgrades a future number. Copy/paste/sync preserve the receiving process. Persistent render keys include the resolved process from V3 on; V1/V2 keys remain unchanged. | | LRC-DEV-VIEWOPTIONS | Develop view options | P2 | 🟡 | `cmd:view.viewOptions`, `crates/ui-egui/src/dialogs/settings.rs` (`view_options`) | View ▸ View Options… (⌘J), the Loupe View part: Show Info Overlay with Info 1 / Info 2, and the three lines of each (none, file name, capture date, dimensions, exposure, camera, lens, camera + lens) with Use Defaults; Show Briefly When Photo Changes under each Info (one at most): with the overlay off, that Info shows for 3 s each time the loupe changes photo; General's Show message when loading or rendering photos (on by default; off, the loupe does not say "Rendering…"); applied as they change, saved with the app settings; `view.viewOptions {info1, info2, briefly, loupeMessages}` sets them for agents. Not yet: the Grid View tab, more fields (ratings, metadata, copy name), the video-frame option | | LRC-DEV-LOUPEOVERLAY | Loupe overlay: layout image | P2 | 🟡 | `cmd:view.chooseLayoutImage`, `cmd:view.layoutImage`, `cmd:view.layoutImageOpacity`, `cmd:view.layoutImageMatte`, `crates/ui-egui/src/panels/layout_overlay.rs` | View ▸ Loupe Overlay: a PNG with transparency (a cover layout, a banner's safe areas) fitted and centred over the loupe photo, following zoom and pan; opacity and matte (the photo darkened outside the graphic's box) in steps; ⌥⌘O shows / hides it; read off the UI thread; saved with the UI state. Not yet: the Grid and Guides overlays, moving and resizing the layout with ⌘ held, free opacity / matte sliders | | LRC-DEV-VIDEO | Video frame capture | P2 | ⬜ | | | @@ -799,6 +799,9 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | LRC-DEV-AUTOSYNC (N-A3, note 18): Auto Sync carries white balance as a mode or on each photo's own scale: As Shot and Auto per photo (were the active photo's numbers), a Temp move keeps each photo's tint, the same number on photos of the same scale, a photo of another scale (a JPEG beside a raw) moves by as much; Sync Settings unchanged; status unchanged | +| 2026-11-02 | minor | LR-LIB-FLAG (PERF-STEP-STALL): flags, ratings and edits are written and synced to the catalog log off the UI thread (a 300 ms sync: slowest flag 0.2 ms, was 305 ms); a failed write is held and retried, never dropped | +| 2026-10-28 | minor | LR-EDIT-OPTICS-PROFILE: lensfun's database offered once on the first launch and downloaded on request (Download / Not Now, Settings) (pinned, CC BY-SA, never bundled), the library looked up when it arrives or Enable Lens Corrections is ticked, the Optics panel names the profile or the lens without one; status unchanged (🟡) | | 2026-10-30 | patch | LR-BEHAV-ACCESS: the Flatpak manifests grant `--talk-name=org.a11y.Bus`, so AccessKit can find out whether a screen reader is running and publish the window inside the sandbox; packaging lint requires it in both manifests; status unchanged (🟡), not tried with Orca | | 2026-10-27 | patch | LR-LIB-LABEL, MENU-PHOTO-LABEL, KEY-LABELS: Clear Color Label (`photo.clearLabel`) is a command of its own, so Help → Keyboard Shortcuts can give it a key (#2980); the Photo ▸ Set Color Label ▸ None row runs it; status unchanged | | 2026-10-25 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K / Ctrl+Alt+Shift+K (`dialog.keywordShortcut`, Set Keyword Shortcut) and ⇧K (`keyword.toggleShortcut`) add and remove the keyword shortcut's keywords; Keyword Shortcut leaves LRC-LIB-KEYWORDS' Not yet list; status counts unchanged (KEYC-METADATA stays 🟡) | @@ -815,6 +818,9 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-27 | patch | MENU-BAR: every shortcut the app shows (a menu row, a button's tooltip, a hint, the empty-album line, the Keyboard Shortcuts dialog) lists its modifiers on macOS in the menu bar's order, ⌃⌥⇧⌘ (`⇧⌘I`, not `⌘⇧I`); the empty-album line follows the keymap; status counts unchanged | | 2026-10-25 | patch | LR-BEHAV-TITLEBAR: the top bar's title-bar gestures come from craft-window's `title_bar`: a double-click follows the system setting, and a press on a button, the search field or a panel floating over the bar never moves the window; status counts unchanged | | 2026-10-25 | patch | LR-IMP-FORMATS: JPEG ICC APP2 chunk sequences are validated before colour conversion; valid reordered chunks remain supported and malformed profiles use the existing sRGB fallback; status unchanged (🟡) | +| 2026-10-13 | minor | LR-IMP-FORMATS / LR-IMP-CAMERA-COVERAGE: Canon CRW decodes (clean-room; 6 bodies pixel-exact, G5 preview-only) | +| 2026-10-25 | patch | LR-BEHAV-TITLEBAR: the top bar's title-bar gestures come from craft-window's `title_bar`: a double-click follows the system setting, and a press on a button, the search field or a panel floating over the bar never moves the window; status counts unchanged | +| 2026-10-26 | minor | LR-IMP-FORMATS: the Canon CRW decoder moved to craft-libs as `craft-crw` (path dependency until that branch merges); `crates/raw/src/vendor/crw.rs` is the adapter, the clean-room record lives in craft-libs (crates/crw/clean-room there) | | 2026-10-24 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 (`keyword.nextSet`, `keyword.previousSet`) go to the next / previous keyword set; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | minor | KEYC-METADATA: ⌘K / Ctrl+K (`panel.addKeywords`, Add Keywords) shows the Keywords panel, opens Keywording and puts the cursor in the Add keyword box; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | patch | LR-META-LOCATION: Info GPS text validates the complete decimal/DMS expression, axis markers and component ranges before metadata changes; readiness and feature counts unchanged | @@ -869,9 +875,12 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-15 | minor | LRC-PRINT-PAGE: Page Options (Page Numbers, Page Info, Crop Marks) on Single Image and Contact Sheet pages, in the Print dialog, `print.set` and templates; still 🟡 (no identity plate, watermark, photo info or Cut Guides) | | 2026-10-15 | minor | LR-IMP-FORMATS: Hasselblad 3FR and FFF show their uncompressed RGB preview (no JPEG in these files) in the grid and loupe until developed, and as the stand-in when a file fails to decode; status unchanged (🟡) | | 2026-10-15 | minor | LR-IMP-FORMATS: a Hasselblad FFF develops with the camera's colour matrix from the original 3FR header it embeds (tag `0xC51B`) instead of the neutral matrix; status unchanged (🟡) | +| 2026-10-22 | patch | LR-PROF-IMPORT: a real CC0 D750 profile (matrix-only, dual illuminant) and its chart NEFs are a pinned test corpus; against Lightroom Classic 15.6 mean ΔE2000 3.8 / 3.4; status unchanged (✅) | +| 2026-10-12 | minor | LR-PROF-IMPORT: the user's own DNG camera profiles (`.dcp`) import as camera profiles; none ship | | 2026-10-13 | minor | LRC-LIB-KEYWORDS: the Keyword List marks a keyword that has an applied keyword inside it (a dot in its box); status unchanged | | 2026-10-12 | minor | LR-IMP-FORMATS: folder discovery includes SR2/SRF; MCP and CLI reuse the engine extension list. DSC-F828 remains preview-only; decoder support and row status unchanged | | 2026-10-15 | patch | KEYC-RATING: `\` shows / hides the Filter Bar in Photo Grid and Square Grid (Show Original in Detail); status unchanged (🟡) | +| 2026-10-12 | minor | Calibrated Contrast and Blacks; mark the measured but incomplete Light controls partial and retain V2 Whites | | 2026-10-16 | minor | KEY-TOGGLEZOOM: Space held over a tool on the photo is the view's hand (click zooms, drag pans, the tool gets neither), a tap still toggles; a held Space toggles once (issue #1895); status unchanged | | 2026-10-16 | patch | LRC-LIB-CATALOG-IMPORT: VIDEO records appear in the Videos filter; reimport repairs older classification with edits, memberships and undo preserved (#1940, filter issue only). Status and summary counts unchanged. | | 2026-10-12 | minor | LR-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 (🟡) | @@ -941,6 +950,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-12 | minor | LR-IMP-FORMATS and LR-IMP-CAMERA-COVERAGE: 22 more CR3 bodies verified on one CC0 file each (all 110 CC0 CR3s decode); EOS R6 Mark III `ColorData` 66 white balance; status unchanged (🟡: CRX variants without public samples remain refused) | | 2026-10-11 | minor | Model setup folder action, opener error and retry (LR-MASK-OBJECTS). | | 2026-10-13 | minor | LR-PROF-CAMERACOLOR: the camera look follows the lens warp of lens-corrected camera JPEGs; status unchanged (🟡) | +| 2026-10-25 | minor | LR-PROF-CAMERACOLOR: chart-measured matrices for the Canon EOS D60 (first chart-calibrated model), white balance in Kelvin for its CRWs; CRW imports take make, model and capture time from the CIFF records (the catalog had no camera for them); status unchanged (🟡) | | 2026-10-13 | minor | LR-PROF-CAMERACOLOR: bundled Nikon Z 6II camera profile; status unchanged (🟡) | | 2026-10-13 | minor | LR-PROF-CAMERACOLOR: bundled Nikon Z 8 camera profile; status unchanged (🟡) | | 2026-10-13 | minor | LR-PROF-CAMERACOLOR: bundled Nikon D5300 camera profile; status unchanged (🟡) | @@ -1026,3 +1036,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-29 | patch | LR-BEHAV-TITLEBAR: a dialog's backdrop leaves the integrated title bar undimmed, as a macOS sheet does (the bar's controls stay inactive, a click on it is not a click outside the dialog, dragging its empty space still moves the window); status unchanged (🟡) | | 2026-10-29 | minor | LR-MASK-OBJECTS: an Object / Describe selection's stored grid is enlarged along the photo's edges (fast guided filter of its logits by log luminance, a 1.5-cell window), so a raised Exposure no longer draws an outline around the subject (#3272); existing AI masks are 1–2 px tighter at edges; status unchanged (🟡) | | 2026-10-30 | patch | LR-MASK-COLORRANGE: a colour-range mask keeps its first 64 samples however it is loaded (sidecar `lc:settings`, presets, `develop.merge`, `render --settings`, catalog and history), not only through `mask.add` / `mask.update`, so a document with thousands can't stall a render or lose the GPU device (issue #2556); status unchanged (✅) | +| 2026-10-31 | patch | LRC-LIB-VISUALSEARCH: Find Similar Photos reads the photos on a worker thread under an activity row with ✕ instead of on the UI thread, where a large library left the window not responding (#3468). A stopped search leaves the view as it was and keeps what it read; a control request gets the same `{photos}` when the search ends. | diff --git a/docs/process-versions.md b/docs/process-versions.md index 7e6788f11e..d477b6834d 100644 --- a/docs/process-versions.md +++ b/docs/process-versions.md @@ -1,5 +1,7 @@ # Process versions +> **Last updated:** 2026-10-12 · **Change:** minor (calibrated Contrast and Blacks) + Every photo's develop settings record the **rendering process** they are interpreted by (`DevelopSettings::process`, a `ProcessVersion` in `crates/develop/src/settings.rs`). Lightroom calls this the process version. It lets the look of LightCraft improve (a new default tone curve, issue #146; @@ -8,7 +10,9 @@ stronger Light sliders, issue #196) without changing a single photo someone has | Process | What it changes | |---|---| | **V1** | LightCraft's rendering from before process versions existed. Frozen. | -| **V2** (the latest) | Highlights and Shadows keep fine detail (issue #632): their base layer (`local::tone_base`) is the edge-aware filter of a separable median of log luminance (radius 0.15 % of the long edge, at most 24 px, `local::BASE_DETAIL`) instead of log luminance itself, so twigs, lines and texture take their surroundings' shift and keep their contrast; region edges stay sharp. CPU (`local::prepare`) and GPU prepare branch on `local::tone_base_detail` (0 = no median under V1); the base plane is cached per process (`local::BaseKey`). Renders without Highlights or Shadows (global or local) are the same as V1's. Tone map unchanged. | +| **V2** | Highlights and Shadows keep fine detail (issue #632): their base layer (`local::tone_base`) is the edge-aware filter of a separable median of log luminance (radius 0.15 % of the long edge, at most 24 px, `local::BASE_DETAIL`) instead of log luminance itself, so twigs, lines and texture take their surroundings' shift and keep their contrast; region edges stay sharp. CPU (`local::prepare`) and GPU prepare branch on `local::tone_base_detail` (0 = no median under V1); the base plane is cached per process (`local::BaseKey`). Renders without Highlights or Shadows (global or local) are the same as V1's. Tone map unchanged. | +| **V3** | Pixel-scale sharpening (issue #757): Radius uses the original photo’s pixels, Detail controls halo damping, and downsized sources retain a response-matched sharpening band. V1 and V2 keep texture-band sharpening exactly. The sharpen plane is keyed by radius and process and invalidated after noise-reduction changes. The Highlights/Shadows base and tone map are unchanged from V2. | +| **V4** (the latest) | V3 plus calibrated global Contrast (per channel) and Blacks (per-channel/luminance mix) on raws with a camera tone curve. Whites behaves exactly as V2, both signs; its calibration is a planned follow-up. Other sources and local adjustments retain V2 operators. See [calibrated Light operators](light-v3.md). | ## The rule @@ -73,7 +77,7 @@ written against the current rendering. `crs:ProcessVersion` numbers Adobe's rend ignored; a photo imported with Lightroom edits is on LightCraft's latest process, and an existing LightCraft photo that receives them keeps its own. -**A number this build doesn't know** (a library or sidecar written by a newer LightCraft) loads, is +**A number above this build's latest** (a library or sidecar written by a newer LightCraft) loads, is kept when saved, and renders with the newest process this build has. Update to Current Process never moves a photo to an older process; Reset does move it to this build's latest. @@ -88,3 +92,14 @@ The process is saved as `"process": ` in the settings JSON, except V1, w Settings made before process versions existed are therefore saved exactly as before, and their preview-cache keys (`DevelopSettings::hash64`) don't change. `develop.get` (MCP `get_develop`) always states the process. + +From process V3 on, persistent thumbnail, view-render and variant keys also include the +resolved rendering process. A future number can keep the same settings hash across builds +while resolving to different operators, so those keys must differ. V1 and V2 omit this +extra field and retain their existing cached renders. No cache-version bump is needed. + +## Revision history + +| Date | Change | Summary | +|---|---|---| +| 2026-10-12 | minor | Calibrated Contrast and Blacks, V2 Whites, resolved-process cache keys and number coordination | diff --git a/docs/raw-parity.md b/docs/raw-parity.md index 0c849b63ce..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-23 · **Change:** minor (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 @@ -15,14 +15,14 @@ ranked in [gaps.md](gaps.md). Details per format: [cr3.md](cr3.md), | Measure | Value | Kind | |---|---:|---| | Adobe-listed camera models | **1,446** | measured: [raw/adobe-cameras.tsv](raw/adobe-cameras.tsv) | -| Decoded from sensor data and **verified** on a real file | **551** (38%) | measured: [raw/evidence.tsv](raw/evidence.tsv) | -| Decoder path should handle it, **unverified** | **656** (45%) | measured from the format rules (631 of them DNG, mostly phones) | -| **Preview-only** (embedded JPEG) | **201** (14%) | measured | -| **Unsupported** (not imported, refused or decodes wrongly) | **38** (3%) | measured | +| Decoded from sensor data and **verified** on a real file | **557** (39%) | measured: [raw/evidence.tsv](raw/evidence.tsv) | +| Decoder path should handle it, **unverified** | **665** (46%) | measured from the format rules (631 of them DNG, mostly phones) | +| **Preview-only** (embedded JPEG) | **187** (13%) | measured | +| **Unsupported** (not imported, refused or decodes wrongly) | **37** (3%) | measured | | Models added since 2017 (Camera Raw 10+): verified / unverified / preview / unsupported | 182 / 542 / 22 / 8 of 754 | measured | | **Share of photographers whose camera fully works** (decodes from sensor data), use-weighted | **~94%** | estimated: measured classes × written usage weights × per-format confidence | -| …of which on a body we have verified | **~85%** | estimated, same weights | -| Camera colour: Adobe profiles vs ours | 1,500 Adobe Standard profiles, 481 models with Camera Matching profiles vs **9 bundled profiles** + per-file fits + 52 spectral matrices (plus same-sensor aliases) | measured (bundle listing, Adobe list, `assets/camera-profiles`) | +| …of which on a body we have verified | **~86%** | estimated, same weights | +| Camera colour: Adobe profiles vs ours | 1,500 Adobe Standard profiles, 481 models with Camera Matching profiles vs **9 bundled profiles** + per-file fits + 52 spectral matrices (plus same-sensor aliases) + chart-measured matrices (1 model, the EOS D60) | measured (bundle listing, Adobe list, `assets/camera-profiles`) | | Lens profiles: Adobe vs ours | **3,635 vs 0** (in-file corrections only) | measured | | **RAW readiness** (decoding 60%, colour 25%, lens 15%) | **~60%** (range 54–64%) | estimated, see [Scores](#scores) | @@ -86,7 +86,7 @@ unsupported to preview-only in the counts; sensor-decoding readiness is unchange | Maker | Adobe models | verified | unverified | preview | unsupported | Main reason for preview / unsupported | |---|---:|---:|---:|---:|---:|---| | Sony | 149 | 94 | 43 | 10 | 2 | DSLR-A200…A390 and A850 12-bit compressed ARW (preview, #535); A100 remains classified unsupported in the recorded evidence; DSC-F828 SRF imports as preview-only; DSC-V3 preview not verified | -| Canon | 134 | 95 | 16 | 21 | 2 | CRW (2000–2004 bodies) preview; EOS-1D / 1Ds TIFF raws not imported | +| Canon | 134 | 101 | 25 | 6 | 2 | PowerShot G5 CRW anomaly and pre-CIFF compacts preview; EOS-1D / 1Ds TIFF raws not imported | | Samsung | 128 | 10 | 109 | 9 | 0 | compressed SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini, Galaxy NX) | | Apple | 113 | 4 | 109 | 0 | 0 | — (DNG / ProRAW) | | Panasonic | 104 | 93 | 11 | 0 | 0 | — | @@ -103,13 +103,13 @@ unsupported to preview-only in the counts; sensor-decoding readiness is unchange | DJI | 21 | 4 | 17 | 0 | 0 | DNG | | OM Digital Solutions | 7 | 0 | 0 | 7 | 0 | **compressed ORF** | | Kodak, Konica Minolta, Epson, Sigma, GoPro, Contax, others | 56 | 12 | 16 | 13 | 15 | DCR, GPR not imported; KDC, X3F preview (Epson ERF and Minolta MRW decode) | -| **All** | **1,446** | **551 (38%)** | **656 (45%)** | **201 (14%)** | **38 (3%)** | | +| **All** | **1,446** | **557 (39%)** | **665 (46%)** | **187 (13%)** | **37 (3%)** | | ## By use (estimated) | Bucket | Weight | Camera fully works | On a verified body | Why | |---|---:|---:|---:|---| -| Canon | 33% | 95% | 93% | 18 of the 22 popular bodies write CR3; 26 CR3 bodies verified (raw.pixls.us has a CC0 file for each), the rest at 0.6 | +| Canon | 33% | 98% | 94% | 18 of the 22 popular bodies write CR3; 26 CR3 bodies verified (raw.pixls.us has a CC0 file for each), the rest at 0.6; CRW decoded | | Sony | 27% | 98% | 92% | bulk-checked | | Nikon | 16% | 98% | 89% | decoders cover every NEF coding but HE; 77 bodies verified | | Fujifilm | 10% | 94% | 92% | | @@ -120,9 +120,9 @@ unsupported to preview-only in the counts; sensor-decoding readiness is unchange | Leica | 1% | 99% | 72% | the Q3 verified, 13 more bodies pinned on CC0 files | | DJI | 1% | 96% | 19% | | | Medium format and others | 0.5% | 29% | 8% | IIQ, 3FR, X3F | -| **Weighted** | 100% | **94%** | **85%** | | +| **Weighted** | 100% | **94%** | **86%** | | -About 19 in 20 raw photographers' cameras decode, and about 5 in 6 use a body we have actually +About 19 in 20 raw photographers' cameras decode, and about 6 in 7 use a body we have actually checked (the per-model CC0 sweeps of October 2026); compressed ORF (OM / Olympus) is the largest gap left. ## Variant matrix (depth per format) @@ -141,7 +141,9 @@ checked (the per-model CC0 sweeps of October 2026); compressed ORF (OM / Olympus | CR3 | sRAW / mRAW | ⬜ | 4-plane Bayer only | | CR3 | HEIF / HDR PQ | ⬜ | HEVC tracks recognised, not decoded | | CR3 | dual-pixel raw | ⬜ | never substituted | -| CRW | all | ⬜ | preview | +| CRW | CIFF: EOS D30/D60/10D/300D, PowerShot G1/G6 | ✅ | clean-room derivation frozen in `craft-libs crates/crw/clean-room/02-crw-format.md`; 28 of 29 files pixel-exact vs a black-box reference (8 CC0 EOS, G1, G6, 18 private D60); as-shot WB from ColorBalance; EOS D60 colour matrices measured on a ColorChecker (Kelvin white balance) | +| CRW | CIFF: PowerShot G2/G3/G4, Pro1, S-series | 🟡 | same decoder and tables; no sample file checked | +| CRW | CIFF: PowerShot G5 | ⬜ | refused (entropy anomaly, `craft-libs crates/crw/clean-room/02-crw-format.md`); preview | | NEF | uncompressed, lossless, lossy type 1 / 2, lossy after split | ✅ | D5100, D7000, D7500, Z f corpus; ~60 NEFs by hand; #633; D4, D90, D5000, D600 and D610 image area measured against the camera JPEG (white level too for the D4, D90 and D5000) | | NEF | packed 14-bit stored under a compressed tag (Z 6II uncompressed) | ⬜ | #769; fix in PR #671 (not merged) | | NEF | High Efficiency / HE★ (JPEG XS) | ⬜ | named, preview (#193); needs a JPEG XS decoder | @@ -214,11 +216,11 @@ sample files. A pointer for contributors, not legal advice. | Item | Adobe | LightCraft | |---|---|---| -| 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 (**9 bundled**: 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)); else a neutral matrix | +| 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) | -| White balance in Kelvin | ✅ for every model | absolute Kelvin where the camera has colour matrices (its own, or one of the 52 spectral rows), 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) | +| 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): @@ -244,7 +246,7 @@ essentials user (the default look is what they keep). | Item | Adobe | LightCraft | |---|---|---| | Profile database | 3,635 profile files, 56 makers, auto-selected | **0** (Adobe LCPs never used; no database of our own) | -| In-file corrections | ✅ | DNG opcodes (WarpRectilinear, FixVignetteRadial, GainMap…) applied; Panasonic / Leica RW2 distortion (79 photos, 13 bodies, 11 lenses); Sony tag 0x7037 distortion for the ILCE-7RM4A (2 lenses), full-frame Bayer 3:2 ILCE-7CR files with correction Auto or forced Auto (3 lenses; see sony-lens-corrections.md for residuals and limits) the ILCE-7RM6 (3 lenses, 54 photos) and the APS-C ILCE-6700 (3 lenses, 30 photos; 1.38 px at a 10 mm wide end, 0.73 px elsewhere; `sony-ilce7rm6-lens-corrections.md`); Nikon NikonNEFInfo distortion (tag `0xc7d5`, about the sensor-shifted optical centre) for the Z 6II and Z f: F-mount lenses on the FTZ within 0.2 px of the camera JPEG, Z lenses within 0.5–1.5 px except the 24-70's wide end (7 px median; `docs/nikon-lens-corrections.md`) | +| In-file corrections | ✅ | DNG opcodes (WarpRectilinear, FixVignetteRadial, GainMap…) applied; Panasonic / Leica RW2 distortion (79 photos, 13 bodies, 11 lenses); Sony tag 0x7037 distortion for the ILCE-7RM4A (2 lenses) and ILCE-7M3 (3 lenses), full-frame Bayer 3:2 ILCE-7CR files with correction Auto or forced Auto (3 lenses; see sony-lens-corrections.md for residuals and limits) the ILCE-7RM6 (3 lenses, 54 photos) and the APS-C ILCE-6700 (3 lenses, 145 photos; 0.73 px worst, with a measured Sigma 10–18 mm exception at 10–10.5 mm; `sony-ilce7rm6-lens-corrections.md`); Nikon NikonNEFInfo distortion (tag `0xc7d5`, about the sensor-shifted optical centre) for the Z 6II and Z f: F-mount lenses on the FTZ within 0.2 px of the camera JPEG, Z lenses within 0.5–1.5 px except the 24-70's wide end (7 px median; `docs/nikon-lens-corrections.md`) | | Vignetting / lateral CA from maker notes | ✅ | ⬜ | | Manual distortion, vignetting, CA, defringe | ✅ | ✅ | @@ -280,9 +282,8 @@ works, from [raw/usage-weights.tsv](raw/usage-weights.tsv). | 5 | Sony DSLR-A200…A390 / A850 12-bit compressed ARW | +0.4 | 3–6 | ~0.08 | samples on raw.pixls.us | | 6 | Pre-X FinePix RAF | +0.6 | 4–8 | ~0.08 | samples | | 7 | Sony A100 regression (#702) and DSC-F828 sensor decoding (preview-only) | +0.1 | 1–2 | ~0.07 | samples on raw.pixls.us | -| 8 | Canon CRW (2000–2004 bodies) | +1.2 by the uniform tail weight, far less by real use | 6–12 | ≤ 0.1 | samples | -| 9 | Nikon HE / HE★ NEF (Z 8, Z 9, Z 6III, Z f, Z50II, Z5II set to HE) | +1.1 | 20–40 | ~0.04 | a pure-Rust JPEG XS decoder | -| 10 | Compressed SRW, Hasselblad 3FR, IIQ, X3F, KDC, DCR, GPR (ERF, MEF, MRW done) | +0.6 together | 45–85 | ~0.01 | samples; low use | +| 8 | Nikon HE / HE★ NEF (Z 8, Z 9, Z 6III, Z f, Z50II, Z5II set to HE) | +1.1 | 20–40 | ~0.04 | a pure-Rust JPEG XS decoder | +| 9 | Compressed SRW, Hasselblad 3FR, IIQ, X3F, KDC, DCR, GPR (ERF, MEF, MRW done) | +0.6 together | 45–85 | ~0.01 | samples; low use | Beyond decoding: @@ -299,12 +300,16 @@ Beyond decoding: |---|---|---| | 2026-10-26 | patch | Bundled camera profile count 5 → 9 (Nikon Z 6II, Z 8 and D5300, ILCE-7RM5); counts only | | 2026-10-23 | minor | Lens profiles: Sony ILCE-6700 (APS-C) in-file distortion through the ILCE-7RM6 conversion, knots spanning its own crop; lens score unchanged (~10%: one more body) | +| 2026-10-25 | patch | CRW variant rows split by verification status (EOS and G1/G6 verified; G2/G3/G4/Pro1/S-series unverified; G5 preview); the CIFF heap walk is bounded by a per-file record budget, so a block of sub-heap records pointing back at their parent no longer hangs decode | +| 2026-10-13 | minor | Canon CRW decoded (clean-room derivation, craft-libs `crates/crw/clean-room/`): EOS D30/D60/10D/300D, PowerShot G1/G6 verified pixel-exact (28 of 29 corpus files); G5 preview (entropy anomaly); as-shot WB from ColorBalance 0x10a9; 243 verified, 950 unverified, 217 preview; Canon bucket 76% (21% verified) | | 2026-10-18 | patch | X-T30, X-T30 II, X-Pro3, X100V, X-S10 and X-E4 take the X-T3's spectral matrices (same 26.1 MP X-Trans CMOS 4 sensor): an X-T30 raw with a black-and-white (Acros) camera JPEG no longer opens in the muted neutral fallback | | 2026-10-16 | minor | Kelvin white balance from Canon CR2 `ColorData` presets (PowerShot G1 X Mark III) | | 2026-10-15 | minor | DNGs with a look table and no tone curve (Lightroom-written, Adobe Standard) fit their tone to the embedded preview, also Lightroom's 1024 px one: two lossy ILCE-7CM2 DNGs no longer render 0.8 EV dark and flat | | 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) | @@ -330,6 +335,9 @@ Beyond decoding: | 2026-10-14 | minor | 97 Canon CR2, Pentax and Ricoh models verified (one CC0 raw.pixls.us file each, pinned, checked against the camera JPEG; `canon_pentax_corpus.rs`): 334 verified, 844 unverified, 232 preview; 50% of photographers on a verified body; use-weighted 85% unchanged | | 2026-10-14 | minor | Integration batch 36: CC0 per-model verification for 117 Nikon/Fujifilm, 97 Canon CR2/Pentax/Ricoh, 21 Sony/Leica and 23 Olympus/Samsung bodies, 22 more CR3 bodies and 30 more models; Epson ERF and Mamiya MEF decode; measured Nikon image areas (#1053, #1770): 515 verified, 675 unverified, 218 preview, 38 unsupported (re-measured with `coverage.py`) | | 2026-10-15 | minor | By-maker and by-use tables re-measured with `coverage.py` after batches 36–39 (545 verified, 651 unverified, 212 preview, 38 unsupported; ~94% of photographers' cameras fully work, ~85% on a verified body); rows the per-model PRs had updated are current again | +| 2026-10-15 | minor | Canon CRW merged with batches 36–39 and re-measured with `coverage.py`: 551 verified, 660 unverified, 197 preview, 38 unsupported; Canon 98% (94% on verified bodies); use-weighted 94% and 86% | +| 2026-10-25 | minor | Canon EOS D60: dual-illuminant matrices fitted to our own ColorChecker Classic shots (tungsten, sun; `crates/raw/src/chart_table.rs`), the first chart-calibrated model: its CRWs edit white balance in Kelvin; counts unchanged | | 2026-10-18 | minor | Minolta MRW decoded (`vendor/mrw.rs`): DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D verified; 551 verified, 656 unverified, 201 preview (re-measured with `coverage.py`) | | 2026-10-23 | minor | AHD blends its horizontal and vertical candidates where their homogeneity is close, so flat noise no longer becomes a maze pattern; Bayer demosaic row notes the pre-white-balance demosaic (#1328); scores unchanged | | 2026-10-30 | patch | RAF camera look fitted on the vignetting-corrected sensor (`LOOK_VERSION` 13): renders were up to 0.3 EV too bright in midtones and 0.6 EV in shadows; X-S10 mean ΔE00 vs the camera JPEG 2.71 → 2.55 on 60 photos | +| 2026-10-26 | minor | Canon CRW decoding moved to the shared craft-libs crate `craft-crw` (local path dependency until that branch merges); `vendor/crw.rs` is now the adapter onto `RawImage`, and the clean-room derivation record lives in craft-libs `crates/crw/clean-room/`; counts unchanged | diff --git a/docs/raw/coverage.py b/docs/raw/coverage.py index 3db93ce812..24f6ddd34e 100644 --- a/docs/raw/coverage.py +++ b/docs/raw/coverage.py @@ -32,6 +32,10 @@ HERE = os.path.dirname(os.path.abspath(__file__)) ORF_DECODED = re.compile(r"^(E-1|E-10|E-20|EVOLT E-300|EVOLT E-330|EVOLT E-400|EVOLT E-500|E-300|E-330|E-500|Camedia C-\S.*|Stylus XZ-2 iHS)$") # Samsung SRW bodies with compressed raw data (crates/raw/src/vendor/srw.rs refuses 32770 / 32772 / 32773). SRW_COMPRESSED = re.compile(r"(^|\W)(NX1|NX30|NX300|NX300M|NX500|NX2000|NX3000|NX3300|NX mini|EK-GN\d+|EK-KN\d+)(\W|$)") + +# CIFF-container CRW bodies (crates/raw/src/vendor/crw.rs): every CRW EOS and the CIFF PowerShots +# (the G and S series and the Pro 1). +CRW_DECODED = re.compile(r"^EOS |^PowerShot (G[1-6]$|Pro ?1$|S[34567]0$|S45$)") # Fujifilm bodies before the X series whose RAF has no raw IFD (crates/raw/src/vendor/raf.rs). RAF_OLD = re.compile(r"^(FinePix (E|F|S\d|S\d{3,4}|IS)|IS Pro|S5Pro|S3Pro|S2Pro)", re.I) @@ -89,9 +93,16 @@ def classify(maker, camera, ext_field): return "unverified", "MEF", "MEF decoder (uncompressed 12-bit)" if e == "ERF": return "unverified", "ERF", "ERF decoder (12-bit 16-byte blocks)" + if e == "CRW": + # CIFF-era bodies decode (craft-libs crates/crw/clean-room/02-crw-format.md): EOS D30/D60/10D/300D and + # the CIFF PowerShots; the pre-CIFF compacts (PowerShot 600, A5, A50, Pro70) and the + # unprobed Pro90 IS stay preview. The G5 is preview by evidence (entropy anomaly). + if CRW_DECODED.search(camera): + return "unverified", "CRW", "CRW decoder (CIFF; selector 0-2 tables)" + return "preview", "CRW", "pre-CIFF CRW is not decoded" if e == "MRW": return "unverified", "MRW", "MRW decoder (12-bit packed, 16-bit words)" - if e in ("CRW", "3FR", "FFF", "IIQ", "MOS", "KDC", "X3F", "RAW", "ORI"): + if e in ("3FR", "FFF", "IIQ", "MOS", "KDC", "X3F", "RAW", "ORI"): return "preview", e, f"{e} is opened from its embedded JPEG only" return "unsupported", e, f"{e or 'unknown'} is not imported" diff --git a/docs/raw/coverage.tsv b/docs/raw/coverage.tsv index c062ea95e2..cad79853a0 100644 --- a/docs/raw/coverage.tsv +++ b/docs/raw/coverage.tsv @@ -135,7 +135,7 @@ Canon EOS 6D CR2 2012 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_ Canon EOS 6D Mark II CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon EOS 7D CR2 2008 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Canon EOS 7D Mark II CR2 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 10D CRW 2003 preview CRW is opened from its embedded JPEG only +Canon EOS 10D CRW 2003 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES; 3 files) Canon EOS 20D CR2 2003 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon EOS 20Da CR2 2005 unverified CR2 lossless JPEG decoder Canon EOS 30D CR2 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) @@ -149,9 +149,9 @@ Canon EOS 80D CR2 2015 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW Canon EOS 90D CR3 2018 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) Canon EOS 200D (EOS Kiss X9, EOS Rebel SL2) CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon EOS 250D (EOS Rebel SL3, EOS 200D II, EOS Kiss X10) CR3 2018 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS D30 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon EOS D60 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon EOS 300D (EOS Digital Rebel, EOS Kiss Digital) CRW 2003 preview CRW is opened from its embedded JPEG only +Canon EOS D30 CRW 2003 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS D60 CRW 2003 verified corpus: crates/raw/tests/it/corpus.rs; 18 maintainer files exact (craft-libs crates/crw/clean-room/03-verification.md) +Canon EOS 300D (EOS Digital Rebel, EOS Kiss Digital) CRW 2003 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES; 3 files) Canon EOS 100D (EOS Digital Rebel SL1, EOS Kiss X7) CR2 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon EOS 500D (EOS Digital Rebel T1i, EOS Kiss X3 Digital) CR2 2008 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon EOS 550D (EOS Digital Rebel T2i, EOS Kiss X4 Digital) CR2 2010 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) @@ -202,20 +202,20 @@ Canon EOS R8 CR3 2022 verified corpus: crates/raw/tests/it/cr3_corpus.rs (exact Canon EOS R50 CR3 2022 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) Canon EOS R50 V CR3 2024 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) Canon EOS R100 CR3 2022 verified corpus: crates/raw/tests/it/cr3_corpus.rs (exact sensor hashes, docs/cr3.md) -Canon PowerShot 600 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon PowerShot A5 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon PowerShot A50 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon PowerShot G1 CRW 2003 preview CRW is opened from its embedded JPEG only +Canon PowerShot 600 CRW 2003 preview pre-CIFF CRW is not decoded +Canon PowerShot A5 CRW 2003 preview pre-CIFF CRW is not decoded +Canon PowerShot A50 CRW 2003 preview pre-CIFF CRW is not decoded +Canon PowerShot G1 CRW 2003 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Canon PowerShot G1 X CR2 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon PowerShot G1 X Mark II CR2 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon PowerShot G1 X Mark III CR2 2017 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G2 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon PowerShot G3 CRW 2003 preview CRW is opened from its embedded JPEG only +Canon PowerShot G2 CRW 2003 unverified CRW decoder (CIFF; selector 0-2 tables) +Canon PowerShot G3 CRW 2003 unverified CRW decoder (CIFF; selector 0-2 tables) Canon PowerShot G3 X CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G5 CRW 2003 preview CRW is opened from its embedded JPEG only +Canon PowerShot G5 CRW 2003 preview CRW entropy anomaly (craft-libs crates/crw/clean-room/02-crw-format.md section 4); embedded JPEG Canon PowerShot G5 X CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon PowerShot G5 X Mark II CR3 2018 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon PowerShot G6 CRW 2003 preview CRW is opened from its embedded JPEG only +Canon PowerShot G6 CRW 2003 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Canon PowerShot G7 X CR2 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon PowerShot G7 X Mark II CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon PowerShot G7 X Mark III CR3 2018 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) @@ -227,17 +227,17 @@ Canon PowerShot G11 CR2 2008 verified corpus: crates/raw/tests/it/body_corpus.rs Canon PowerShot G12 CR2 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon PowerShot G15 CR2 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon PowerShot G16 CR2 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot Pro 1 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon PowerShot Pro70 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon PowerShot Pro90 IS CRW 2003 preview CRW is opened from its embedded JPEG only -Canon PowerShot S30 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon PowerShot S40 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon PowerShot S45 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon PowerShot S50 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon PowerShot S60 CRW 2003 preview CRW is opened from its embedded JPEG only +Canon PowerShot Pro 1 CRW 2003 unverified CRW decoder (CIFF; selector 0-2 tables) +Canon PowerShot Pro70 CRW 2003 preview pre-CIFF CRW is not decoded +Canon PowerShot Pro90 IS CRW 2003 preview pre-CIFF CRW is not decoded +Canon PowerShot S30 CRW 2003 unverified CRW decoder (CIFF; selector 0-2 tables) +Canon PowerShot S40 CRW 2003 unverified CRW decoder (CIFF; selector 0-2 tables) +Canon PowerShot S45 CRW 2003 unverified CRW decoder (CIFF; selector 0-2 tables) +Canon PowerShot S50 CRW 2003 unverified CRW decoder (CIFF; selector 0-2 tables) +Canon PowerShot S60 CRW 2003 unverified CRW decoder (CIFF; selector 0-2 tables) Canon PowerShot S90 CR2 2008 unverified CR2 lossless JPEG decoder Canon PowerShot S95 CR2 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot S70 CRW 2003 preview CRW is opened from its embedded JPEG only +Canon PowerShot S70 CRW 2003 unverified CRW decoder (CIFF; selector 0-2 tables) Canon PowerShot S100 CR2 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon PowerShot S100V CR2 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon PowerShot S110 CR2 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) diff --git a/docs/raw/evidence.tsv b/docs/raw/evidence.tsv index 6212558585..1e6e7399af 100644 --- a/docs/raw/evidence.tsv +++ b/docs/raw/evidence.tsv @@ -569,3 +569,10 @@ Konica Minolta DiMAGE A200 verified corpus: crates/raw/tests/it/corpus.rs (xtask Konica Minolta Maxxum 7D Dynax 7D verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Konica Minolta DiMAGE 7 verified raw.pixls.us check: CC0 sample decoded and its WB / CFA matched to the embedded preview (vendor/mrw.rs) Konica Minolta DiMAGE A2 verified raw.pixls.us check: CC0 sample decoded and its WB / CFA matched to the embedded preview (vendor/mrw.rs) +Canon EOS D30 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS D60 verified corpus: crates/raw/tests/it/corpus.rs; 18 maintainer files exact (craft-libs crates/crw/clean-room/03-verification.md) +Canon EOS 10D verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES; 3 files) +Canon EOS 300D (EOS Digital Rebel, EOS Kiss Digital) verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES; 3 files) +Canon PowerShot G1 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon PowerShot G6 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon PowerShot G5 preview CRW entropy anomaly (craft-libs crates/crw/clean-room/02-crw-format.md section 4); embedded JPEG 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/sony-ilce7rm6-lens-corrections.md b/docs/sony-ilce7rm6-lens-corrections.md index 749fc4afae..f93ebe16d5 100644 --- a/docs/sony-ilce7rm6-lens-corrections.md +++ b/docs/sony-ilce7rm6-lens-corrections.md @@ -146,6 +146,24 @@ full-frame 0.25 px gate. Measured against the camera JPEG, the fitted polynomial 0.22–0.73 px against 0.23–0.68 px on the 27 photos, 1.35–1.38 px at 10 mm), so APS-C bodies use a 0.5 px gate (`APSC_FIT_ERROR_PX_AT_1440`). +**Lens exception: Sigma 10–18 mm F2.8 DC DN at 10–10.5 mm** (`LENS_EXCEPTIONS`, matched on Exif `LensModel` +`10-18mm F2.8 DC DN | Contemporary 023` and `FocalLength` ≤ 10.5 mm). Its wide end keeps 1.36–1.38 px under the +body's rule. On 115 further private photos of this lens (97 at 10 mm, 2 at 10.4–10.5 mm, 16 at 11.7–12.5 mm), a grid +over spacing 372–426 px and unit 14000–16500 was measured on the exact table. The photos at 10 mm were split by +shooting location: 63 to choose the values, 34 to check them. A larger spacing with a smaller unit fits about as well +(a ridge in the grid): 420 px / 14000 was best on the 63 choice photos (0.445 px worst) but put 2 of the 34 check photos +above 0.75 px, so the pick is **416 px / 14250**, within 0.51 px on both sets. +As rendered (`lightcraft-cli render`, Enable Lens Corrections on): + +| Sigma 10–18 mm | p95 at 1440 px | +|---|---| +| 10 mm, 97 photos (one night photo has too little detail to measure) | 0.38–0.55 px, median 0.44 (body's rule: about 1.4 px) | +| 10.4–10.5 mm, 2 photos | 0.36 px | +| 11.7–12.5 mm, 16 photos (body's rule, the exception does not apply) | 0.48–0.72 px, median 0.57 | + +At 11.7 mm and longer an exception of this kind fits worse than the body's rule (412 px / 14500 on the grid: 0.73–1.19 px against 0.48–0.69 px), so it stops at +10.5 mm, the longest measured focal length where it helps; 10.6–11.6 mm is unmeasured and takes the body's rule. + ## Two conventions A second Sony decoder, `crates/raw/src/vendor/arw_lens.rs` @@ -327,13 +345,14 @@ the resampled source by the source, framing and output size, so tone, colour and - **ILCE-7RM6 and ILCE-6700 only.** Other Sony bodies record the same tags; their knot spacing (defined here by the full-frame crop, or an APS-C body's own crop), unit and zoom rule are unverified, so they get no correction from this conversion (the ILCE-7RM4A's distortion has its own: [Two conventions](#two-conventions)). -- **ILCE-6700 at strong barrel distortion:** 1.36–1.38 px at the Sigma 10–18 mm's 10 mm end (above). The two public - raw.pixls.us ILCE-6700 files (one scene, E 16–55 mm F2.8 G at 16 mm, not used for fitting) both carry the same - table (−1829 at the last knot). On the compressed file the correction leaves p95 3.1 px (uncorrected 5.1 px, exact - table 3.4 px); with the same spacing this lens fits at unit 16000 (0.43 px), another lens-dependent unit (below). - On the lossless file the table, on its padded 6656 × 4608 frame, misses the 0.5 px fit gate, so that photo stays - uncorrected (5.3 px). Its vignetting and lateral CA tables are read, not applied: measured in #2801 (the camera JPEG - doesn't compensate vignetting, as on the ILCE-7RM6). +- **ILCE-6700 at strong barrel distortion:** the body's rule leaves 1.36–1.38 px at the Sigma 10–18 mm's 10 mm end; + that lens has a measured exception (above). The two public raw.pixls.us ILCE-6700 files (one scene, E 16–55 mm + F2.8 G at 16 mm, not used for fitting) both carry the same table (−1829 at the last knot). On the compressed file + the correction leaves p95 3.1 px (uncorrected 5.1 px, exact table 3.4 px); with the same spacing this lens fits at + unit 16000 (0.43 px), another lens-dependent unit (below). On the lossless file the table, on its padded + 6656 × 4608 frame, misses the 0.5 px fit gate, so that photo stays uncorrected (5.3 px). Other wide lenses with + similarly strong tables are unmeasured. Its vignetting and lateral CA tables are read, not applied: measured in + #2801 (the camera JPEG doesn't compensate vignetting, as on the ILCE-7RM6). - **APS-C distortion is unverified in camera on the ILCE-7RM6:** no APS-C photo with distortion correction on was available; the APS-C knot spacing is verified on CA only, and the APS-C zoom follows the full-frame rule. - **Aspect-ratio crops** (in-camera 4:3, 16:9, 1:1) were not measured; the correction uses the crop the file records. diff --git a/docs/sony-lens-corrections.md b/docs/sony-lens-corrections.md index 0252151cde..87f141a5d2 100644 --- a/docs/sony-lens-corrections.md +++ b/docs/sony-lens-corrections.md @@ -7,9 +7,10 @@ convention; that page's *Two conventions* section has the comparison and what wo Sony ARWs record three lens corrections per shot in the raw image IFD: shading (vignetting), lateral chromatic aberration (CA) and distortion, each as a camera setting and a radial table, with copies in the encrypted -`SR2SubIFD`. LightCraft **decodes all three** wherever a file carries them and applies distortion here on two validated -bodies: **ILCE-7RM4A (A7R IVA)** and **ILCE-7CR (A7CR)**. The A7R IVA keeps its existing Bayer 3:2 conversion, -validated with the FE 24-105mm F4 G OSS and FE 200-600mm F5.6-6.3 G OSS. The A7CR uses a separate conversion, +`SR2SubIFD`. LightCraft **decodes all three** wherever a file carries them and applies distortion here on three validated +bodies: **ILCE-7RM4A (A7R IVA)**, **ILCE-7M3 (A7 III)** and **ILCE-7CR (A7CR)**. The A7R IVA keeps its existing Bayer 3:2 conversion, +validated with the FE 24-105mm F4 G OSS and FE 200-600mm F5.6-6.3 G OSS; the A7 III uses the same conversion, validated +with the FE 16-35mm F4 ZA OSS, FE 28-70mm F3.5-5.6 OSS and FE 50mm F1.8 ([ILCE-7M3 validation](#ilce-7m3-validation)). The A7CR uses a separate conversion, limited to full-frame Bayer 3:2 files with distortion Auto or forced Auto. Apart from the separate ILCE-7RM6 converter, other models and shading and CA on every model are decoded only: no warp, vignetting or CA correction is added for them. The decoded record stays with the image (`RawInfo::lens_metadata` / `RawImage::lens_metadata`, types in `crates/raw/src/lens_metadata.rs`, decoder in @@ -289,9 +290,50 @@ decode or fail without a panic. `tests/sr2_heap.rs` measures the peak heap of de `SR2Private` directory holds eight fields aliasing the whole file: 37 kB, against 134 MB when those fields were decoded. No private photographs or reference TIFFs are committed. +## ILCE-7M3 validation + +Checked on 2026-10-12 against the camera's own JPEG of the same exposure, which is an independent renderer +that applied the correction (RAW+JPEG, Lens Comp. ▸ Distortion Comp.: Auto). RAW+JPEG pairs from one +ILCE-7M3 (26 in the table below, plus two left out as explained under it): a checkerboard filling the frame on a TV (handheld) and on a desktop monitor (tripod), compressed and +uncompressed raws, apertures from wide open to f/8, plus one textured wall. Tables covered strong barrel (16 mm, +−690 at the corner), strong pincushion (70 mm, +1161) and the sign change between them. + +Method (`tools/sony_distortion_check.py`): LightCraft renders each ARW at full size with the profile correction +on and off; sub-pixel board corners (Hessian saddle points refined with `cornerSubPix`, kept only where the four +quadrants alternate, labelled into rows and columns) are matched with the JPEG's by grid position, with the +match fixed by the central corners before any fit, because a board is periodic. A similarity (zoom, rotation, +shift) is fitted, as the camera fills its frame with its own zoom; no lens coefficient is fitted. The textured wall +uses SIFT matches instead. The script was checked on synthetic boards with a known radial distortion. + +| Lens / focal length | Shots | Corrected vs JPEG: median / p95 (px at 6000) | Uncorrected median | Corner (r > 0.9) | Camera / LightCraft correction | +|---|---:|---|---:|---:|---:| +| FE 16–35 F4 ZA / 16 mm | 10 | 0.33–0.38 / 1.01–1.15 | 16.7–17.0 | 1.40–1.56 px | 1.02 | +| FE 16–35 F4 ZA / 20 mm | 4 | 0.16–0.24 / 0.34–0.50 | 3.9–4.4 | 0.15–0.24 px | 0.98 | +| FE 16–35 F4 ZA / 35 mm | 2 | 0.18–0.21 / 0.39–0.44 | 11.0–11.1 | 0.18–0.26 px | 1.01–1.02 | +| FE 28–70 / 28 mm | 2 | 0.24–0.25 / 0.59–0.64 | 13.2–13.4 | 0.92 px | 1.02 | +| FE 28–70 / 33 mm | 1 | 0.07 / 0.16 | 0.8 | 0.07 px | 1.00 | +| FE 28–70 / 50 mm | 1 | 0.30 / 0.69 | 20.8 | 1.24 px | 1.01 | +| FE 28–70 / 70 mm | 1 | 0.44 / 0.93 | 26.4 | 1.49 px | 1.01 | +| FE 50 F1.8 / 50 mm | 4 | 0.06–0.12 / 0.15–0.31 | 2.8–3.0 | 0.08–0.14 px | 1.00–1.01 | +| Wall, 16 mm (SIFT) | 1 | 0.37 / 1.06 | 5.6 | 1.22 px | — | + +Residuals are in pixels of the 6000×4000 JPEG; at the 2376 px exports used above for the ILCE-7RM4A, the +board medians are 0.02–0.17 px and the p95 at most 0.46 px. The last column fits JPEG ≈ uncorrected + +α·(corrected − uncorrected) radially: LightCraft applies the camera's amount of correction within 2 %, slightly +less for strong barrel and slightly more at 20 mm, which is what remains at the 16 mm corners (about 1.5 px of a +35 px correction). Rows and columns of corrected boards are as straight as in the JPEG in every shot (largest +bow 0.8–7.8 px in both, from the screens), against 7–55 px uncorrected. Compressed and uncompressed raws, +the TV and the monitor, and wide open and f/8 agree. Two 16 mm board shots whose board stopped short of the +corners (reach 0.8 of the half diagonal) gave 0.85 px medians and are left out of the table. + +On this body Sony's crop tags and the default crop agree (origin 12, 12, 6000×4000 of 6048×4024), so the +warp sits on the image centre; fitted against the camera, the centre is within 0.3 px. Unit tests keep the warp from +three of these tables within 0.0008 of the half diagonal (2.9 px at 6000 px) of the camera's fitted geometry. +The photographs stay with their owner; none is committed. + ## Camera coverage and regression boundary -The model check is exact: `ILCE-7RM4` (A7R IV without the A suffix), `ILCE-7M3`, unknown/missing +The model check is exact: `ILCE-7RM4` (A7R IV without the A suffix), unknown/missing model names, and every other model remain unsupported by this distortion decoder. Matching tag numbers and table lengths do not establish the scale, interpolation or crop normalization on another body. Support can expand after independent geometry validation; do not add model-name prefix matching. @@ -309,7 +351,7 @@ fail on any absent pinned file instead. |---|---|---|---| | ILCE-7RM4A | Compressed (4822) | All three tables; 257 / 1 / 17 | One distortion warp | | ILCE-9M2 | Compressed (3989) | All three; 257 / 1 / 0 | None | -| ILCE-7M3 | Compressed, uncompressed | All three; 257 / 1 / 0 | None | +| ILCE-7M3 | Compressed, uncompressed | All three; 257 / 1 / 0 | One distortion warp | | ILCE-7M4 | 14-bit, lossless L/M/S | L/M/S: all three, 272 / 1 / 17; the 14-bit file (APS-C framing, 4608 × 3072): settings only, its 11-sample tables are not interpreted | None | | ILCE-7RM2 | 12-bit uncompressed | All three; 256 / 0 / 1 | None | | DSC-RX100 | One | Shading, from the `SR2SubIFD` (the raw IFD has no tables); CA and distortion in the 11-sample layout | None | @@ -324,8 +366,8 @@ fail on any absent pinned file instead. These are **model-boundary regression checks, not new geometric validation of those models**. `sony_lens_records_of_the_public_samples` also checks the exact tables, settings, provenance and framing evidence of the three A7CR codings and the A7R IVA sample, and that across the Sony corpus only the A7R IVA's distortion is ever -applied. In particular, -refusing the A7 III tables resolves the unverified corner warp identified in review. The lossless M/S +applied, besides the A7 III's. The A7 III tables were refused at first because their corner warp was unverified; +the [ILCE-7M3 validation](#ilce-7m3-validation) measured it against the camera's own JPEGs and enabled the body. The lossless M/S files are linear YCbCr and remain excluded independently of the model check. Header and full decode must agree for every sample. Synthetic tests also verify both TIFF byte orders, exact model matching, that the warp is centred on the standard default crop while the image keeps Sony's crop, and that DNG export preserves an accepted warp without adding one to rejected diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 757ed90555..c54e4884ad 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity: LightCraft vs Adobe Lightroom -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (gap 9: CI runs the tests on Linux x64 since #2667; macOS, Windows and the GPU equivalence tests still don't; Minolta MRW decoded, 6 bodies verified; RAW: 83% of Adobe's models decode, 38% verified after the camera-coverage sweep #1327; Platforms: the Windows x64 installer verified on Windows 11) · **Target:** Adobe Lightroom Classic 15.5 (August 2026) and Lightroom 9.6 (desktop) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (Canon CRW decoder shared via craft-libs `craft-crw`; Canon CRW decoded clean-room, 6 bodies verified; gap 9: CI runs the tests on Linux x64 since #2667; macOS, Windows and the GPU equivalence tests still don't; Minolta MRW decoded, 6 bodies verified; RAW: 85% of Adobe's models decode, 39% verified after the camera-coverage sweep #1327; Platforms: the Windows x64 installer verified on Windows 11) · **Target:** Adobe Lightroom Classic 15.5 (August 2026) and Lightroom 9.6 (desktop) The authoritative assessment of how close LightCraft is to Lightroom. The row-by-row checklist is [parity-checklist.md](parity-checklist.md); the ranked work list is [gaps.md](gaps.md); deep areas @@ -47,7 +47,7 @@ phase #85, duplicate Local entries #22, black GPU exports on an Intel iGPU #78). | Dimension | Breadth | Ready for real work | Remaining | Doc | |---|---:|---:|---:|---| | Features (weighted areas below) | ~77% (checklist 81.1%, measured) | ~61% | 600–1,100 h | [Features](#features) | -| ↳ RAW cameras, colour and lens profiles (part of features) | 83% of Adobe's 1,446 models decode (38% verified), measured | ~56% | 255–480 h | [raw-parity.md](raw-parity.md) | +| ↳ RAW cameras, colour and lens profiles (part of features) | 85% of Adobe's 1,446 models decode (39% verified), measured | ~56% | 255–480 h | [raw-parity.md](raw-parity.md) | | UI/UX fidelity | ~85% | ~70% | 32–54 h | [ui-parity.md](ui-parity.md) | | File formats (non-raw: images, sidecars, presets, catalogs) | ~85% | ~70% | 30–55 h | [file-format-parity.md](file-format-parity.md) | | Hardware | ~50% | ~40% | 40–80 h (+ tethering and printing, counted under Classic modules) | [hardware-parity.md](hardware-parity.md) | @@ -68,7 +68,7 @@ from the checklist sections and the deep-dive documents. |---|---:|---:|---:|---:|---| | Import and library (import, folders, albums, smart albums, keywords, metadata, search, faces) | 15% | 90% | 80% | 25–45 h | checklist A–E 83–92%; robust journal; 85k-photo libraries | | RAW decoding and camera coverage | 15% | 81% | 77% | 120–220 h | [raw-parity.md](raw-parity.md), measured model by model: 85% of photographers' cameras decode (use-weighted), × 0.9 for per-body bugs; CR3 variants, compressed ORF, HE NEF | -| Colour, camera profiles, render fidelity | 10% | 65% | 35% | 80–150 h | 9 bundled profiles vs Adobe's 1,500; per-file fits median ΔE ~5 vs the camera JPEG, ~10% far off; no fidelity suite ([raw-parity.md](raw-parity.md#colour)) | +| Colour, camera profiles, render fidelity | 10% | 65% | 35% | 80–150 h | 10 bundled profiles vs Adobe's 1,500; per-file fits median ΔE ~5 vs the camera JPEG, ~10% far off; no fidelity suite ([raw-parity.md](raw-parity.md#colour)) | | Global develop adjustments (light, colour, curves, grading, effects, detail) | 15% | 93% | 70% | 30–60 h | checklist F 91.7%; character tuned by eye | | Optics, lens profiles, crop and geometry | 6% | 80% | 50% | 40–80 h | no lens database; crop / Upright complete | | Masking | 8% | 67% | 45% | 60–110 h | checklist K 67.4%; AI masks heuristic or SAM 3 without mirror | @@ -301,6 +301,7 @@ P2 items 12–25 h; look tuning, performance, packaging, hardening 25–45 h. | Date | Change | Summary | |---|---|---| | 2026-10-24 | patch | Stability, the stability discount, the Beta-needs list and the estimate history: tests run in CI on Linux x64 since #2667 (FreeBSD nightly), not on macOS or Windows (gap 9); percentages and hours unchanged | +| 2026-10-13 | minor | Canon CRW decoded (clean-room, craft-libs `crates/crw/clean-room/`): 551 models verified with the coverage sweep (557 with MRW after merging main), Canon preview rows 21 → 6; RAW decoding unchanged | | 2026-10-19 | patch | Stability note: tests run in CI on Linux x64 (every PR) as well as FreeBSD; macOS and Windows remain (gap 9) | | 2026-10-19 | minor | Localization ~55% → ~64% (mean of the 12 key languages): Indonesian (`id`) catalog, every message but What's New; full target 61.2% → 61.5% (still ~61%) | | 2026-10-19 | patch | Platforms: the Windows installer is no longer listed as unverified (the 0.9.1 x64 MSI is tested on Windows 11; a confirmation after uninstalling from Settings → Apps, #892, remains); #790 noted as fixed in 0.9.1; percentages and hours unchanged | @@ -320,3 +321,4 @@ P2 items 12–25 h; look tuning, performance, packaging, hardening 25–45 h. | 2026-10-10 | minor | Stage re-checked against the core-workflow alpha gate: passes, stays alpha | | 2026-10-10 | major | Created as progress docs: full re-measure (checklist recount, installed Lightroom 9.6 bundle listing, code counts, catalogs, CI), feature areas with weights, dimensions, AI, stage, calibration; merged ROADMAP's *Where we stand* and *Parity estimate* | | 2026-10-14 | minor | RAW: 82% of Adobe's models decode, 36% verified (integration batch 36) | +| 2026-10-26 | minor | Canon CRW decoder moved to craft-libs as `craft-crw` (shared with the other Craft apps); LightCraft keeps the adapter, the EOS D60 colour work and its records; numbers unchanged | diff --git a/docs/user/troubleshooting/get-help.md b/docs/user/troubleshooting/get-help.md index 963c582213..5490bd1ab6 100644 --- a/docs/user/troubleshooting/get-help.md +++ b/docs/user/troubleshooting/get-help.md @@ -21,6 +21,18 @@ Open an issue in the [issue tracker](https://github.com/storytold/lightcraft/iss LightCraft writes its log to `logs/lightcraft.log` in its settings folder. On Windows that is `%APPDATA%\LightCraft\logs\`. Each start moves the previous log to `lightcraft.1.log`, and that one to `lightcraft.2.log`, so the log of a run that crashed survives the next start. +## A more detailed log + +When thumbnails or previews don't appear, appear slowly, or keep the computer busy, a log of every picture LightCraft draws helps. Start LightCraft with the environment variable `RUST_LOG` set to `warn,lightcraft*=info,lightcraft_ui_egui::render=debug`. On Windows, in PowerShell: + +```powershell +$env:RUST_LOG = "warn,lightcraft*=info,lightcraft_ui_egui::render=debug"; & "C:\Program Files\LightCraft\lightcraft.exe" +``` + +The log then has a line for each picture LightCraft asks for, with its file, and usually a line for how it ended: drawn, or dropped and why (for example, scrolled out of view, or replaced by a newer request). A few requests that are dropped while they wait, such as when photos are removed or LightCraft quits, have no ending line. A file that can't be read is still a warning. So the log shows whether a file was asked for once or many times. `LIGHTCRAFT_LOG=debug` instead turns on the detailed log of all of LightCraft. + +This log names the files LightCraft draws, with their folders. Look through it before you share it, and remove any names you'd rather keep private. + ## Still stuck? Ask in [Discord](https://discord.gg/artcraft). diff --git a/docs/web.md b/docs/web.md index 76b84cd7c0..d8065dd766 100644 --- a/docs/web.md +++ b/docs/web.md @@ -188,7 +188,8 @@ are the same in every version, so serve them with `Cache-Control: no-cache` (not ## Measuring -Open `http://127.0.0.1:8080/?bench` to run a scripted measurement: +Open `http://127.0.0.1:8080/?bench` to run a scripted measurement. It always runs on the generated demo photos in an unsaved library +(`?bench` implies `?store=memory`), so it never edits the library kept in browser storage: 1. Wait for the grid thumbnails. 2. Open the first photo in Detail. diff --git a/docs/whats-new.md b/docs/whats-new.md index 5289b03b66..854106ad44 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -7,8 +7,42 @@ 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-11-01 + +### Korean and Vietnamese text in exports draws whole +- macOS often stores Korean file names decomposed (NFD), each syllable as its jamo. Contact-sheet captions, export + watermarks, slideshow overlays and print page text drew those as loose jamo (`ㅈㅔㅈㅜㄷㅗ` for `제주도`), and + decomposed Vietnamese letters lost their stacked marks. Text is now composed before it is laid out, so both draw as + they do in the app (issue #3480, #3277). + +## 2026-10-31 + +### Find Similar Photos no longer freezes the window +- The first search reads every photo in the library, and it did that on the thread that draws the window, so in a large + library the app stopped responding and Windows offered to close it (issue #3468). The photos are now read in the + background: a "Find Similar Photos" row in the activity stack counts them, you can keep working meanwhile, and its ✕ + stops the search. A stopped search leaves the view as it was, and the next one goes on from what was read. The menu + item is off while a search runs, and opening another library stops it. When a search ends the grid shows the photos it + found, also from the Photo menu, and a message says how many. `library.findSimilar` from the control channel and + `mcp --connect` still gets `{photos}`, now when the search ends; a caller that stops waiting (the control server + gives a request 60 s) can ask again once that search has ended (while it runs, a new request is refused as already + running), and what was read isn't read again. + ## 2026-10-30 +### Lens distortion correction for the Sony A7 III +- Raws from the Sony A7 III (ILCE-7M3) now get the camera's own distortion correction, read from the file, like + the A7R IVA's: straight lines stay straight at wide angles (the FE 16–35 F4 ZA at 16 mm shifts detail near the + corners by up to about 40 px on a 24 MP photo) and at long ones (the FE 28–70 at 70 mm). Measured against the + camera's JPEG, the median error is well under a pixel (up to about 1.5 px in the 16 mm corners). Optics ▸ Enable Lens Corrections turns it off and Profile Distortion scales + it; photos imported before this pick it up with Photo ▸ Reload from Disk. Vignetting and chromatic aberration + from Sony files are not applied yet. + +### Lens corrections without grey corners +- Lens profiles, the camera's own distortion correction, manual Distortion and Chromatic Aberration now crop just + inside the corrected photo, as in Lightroom, so no grey corners or edge marks show. Perspective corrections still + need Constrain Crop to do the same. + ### The Flatpak may talk to the accessibility bus - The Flatpak package now has access to the accessibility bus (`org.a11y.Bus`) and no other new permission; its network, Pictures folder and GPU access are unchanged. Without it the sandbox hid the bus, which AccessKit needs to reach a screen reader such as Orca; this has not been tried with Orca yet. The Flatpak build is the only one affected. @@ -348,6 +382,18 @@ ## 2026-10-23 +### Export subfolders stay inside the export folder +- An export subfolder (typed in the Export dialog, saved in a preset or passed to `export`) can no longer lead + outside the chosen folder (issue #2571). `..` and `.` parts and a leading `/` are dropped, and `\` and `:` become + `_`, so a shared preset with `../..` in its subfolder writes inside your folder instead of elsewhere on disk. + Nested subfolders such as `Client/Jobs` still work. + +### Place names always download into the settings folder +- Download Place Names (for Fill Location from GPS) always saves the GeoNames files in the settings folder (issue + #2575). An agent or script driving LightCraft could name another folder and another server, and have that + server's files written there; it is now refused. Each file is saved complete or not at all, and replaces whatever + is in its place instead of writing through a link to somewhere else. + ### Videos in the grid are no longer sent to the image decoders - A video in the library (an MP4 or MOV brought in from a Lightroom catalog) no longer asks the image decoders for a grid thumbnail (issue #2682). They can't read one, so each video failed with "unrecognised image format", showed a @@ -419,6 +465,13 @@ - Saving a sidecar keeps another application's properties even when its namespace uses prefixes such as `lc` or `xmp`. Those foreign properties no longer become LightCraft settings or ratings when imported. +### The log can show every thumbnail and preview LightCraft asks for +- With `RUST_LOG=warn,lightcraft*=info,lightcraft_ui_egui::render=debug` (or `LIGHTCRAFT_LOG=debug`), the log has a + line for each picture LightCraft asks for, with its file, and one for how it ended: drawn, or dropped and why. + Before, only failures were logged, so the log couldn't tell a file asked for 37 times from one asked for once and + failing inside (issue #2682). + The usual log is unchanged. See [Get help with a problem](user/troubleshooting/get-help.md). + ### Find Missing Photos finds the files of a library made on Windows - A library made on Windows records its originals with Windows paths. Opened on macOS or Linux, its photos are missing until relinked, and Find Missing Photos found them only by their content, so it missed every photo it had @@ -1429,6 +1482,15 @@ file name, then id, instead of import order. Recently Added keeps a batch in file name order, and Auto-Stack orders a burst by file name, so the first file is the cover. +### More of the rendering on the GPU +- LUT profiles, masks with Refine Edges and soft proofing into a colour space render on the GPU (they used to send the + whole render to the CPU; soft proofing to a printer or paper profile still renders on the CPU), and so do spot removal, defringe and the histogram (they used to bounce the image through the CPU mid-render). + Results match the CPU within 3 levels in 8 bits (mean under half a level; `docs/gpu-pipeline.md`). +- Grid, filmstrip, preset and profile thumbnails render on the GPU once it is ready (about a quarter faster on an RTX + 5070, and the CPU stays free for decoding raws). +- While a slider is dragged, the loupe is drawn straight from the GPU: rendering and drawing share the window's + graphics device, so drafts are never copied to memory and back (`LIGHTCRAFT_GPU_WINDOW=0` turns this off). + ### Large preset collections - A library holding thousands of presets (a Lightroom collection imported whole: 11 000 presets, a 42 MB presets.json) stays responsive. Every command used to re-serialize the whole list to see whether it had changed diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index 254574d91b..3df5c29995 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -315,5 +315,20 @@ with a blend mode other than Normal or with a mask are reported, not applied. Bi or `.zip` bundles — as creative profiles: they appear in the profile browser under their folder's (or zip's) name and take the Amount slider (0–200 %) like the built-in looks. The LUT is applied to the finished, display-encoded colour (trilinear; `DOMAIN_MIN` / `DOMAIN_MAX` honoured; 1D LUTs are not supported); photos with a LUT profile render on the -CPU. A library on disk keeps a copy of each file in its `Profiles/` folder. Adobe's own profile formats (`.dcp`, XMP -camera/creative profiles with embedded tables) are deliberately not read. +CPU. A library on disk keeps a copy of each file in its `Profiles/` folder. XMP camera/creative profiles with embedded +tables are not read. + +## Profiles: camera profiles (`.dcp`) + +The same command (and File ▸ Import Profiles & Presets…, drag & drop) reads DNG Camera Profiles — the user's own `.dcp` +files, e.g. made with a colour-checker tool — as camera profiles (`dcp:-` ids, group *Camera Profiles*, +listed by `profiles.camera`). Read per DNG specification chapter 6 (`crates/raw/src/dcp.rs`): `ProfileName`, +`UniqueCameraModel`, `CalibrationIlluminant1/2`, `ColorMatrix1/2`, `ForwardMatrix1/2`, `ProfileHueSatMap*`, +`ProfileLookTable*`, `ProfileToneCurve` and `BaselineExposureOffset`. Choosing one (`develop.profile {id}`) replaces a raw +file's colour model when it is decoded — the file's own white balance, analog balance and baseline exposure stay, and a +profile without a `ProfileToneCurve` (most chart-made ones) keeps the photo's own contrast: the DNG's tone curve, else the +tone of the look fitted to its camera JPEG — so the +photo's source is decoded again when its profile changes; rendered (non-raw) photos ignore it. Smart previews and the +web build's render worker keep the file's own colour. A library on disk keeps a copy of each file in `Profiles/`; +`profile.deleteCamera` (or `profile.deleteImported`) removes one. No profile ships with LightCraft, and the repository +holds none: tests build theirs in memory (`lightcraft_raw::dcp::write_dcp`). diff --git a/tools/light_v3_constants.py b/tools/light_v3_constants.py new file mode 100644 index 0000000000..e5188afcd4 --- /dev/null +++ b/tools/light_v3_constants.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python3 +"""Process V4's fitted Light constants: the committed fits and the Rust file generated from them (docs/light-v3.md). + + light_v3_constants.py rust [-o crates/pipeline/src/light_v3_params.rs] [--check] + Write the Rust constants from the committed fits (tools/light_v3_fits/{contrast,blacks}.json): each + fit's parameter vector verbatim (shortest round-trip literals; crates/pipeline/src/light_v3.rs unpacks it as + Family.unpack does), where it came from, and, for the Rust tests only, Family's own curve and apply values at + fixed points (rounded to 12 significant digits, so the file is the same on every machine). Running it on a + checkout must reproduce the committed file byte for byte: --check says whether it does, writing nothing. + light_v3_constants.py sanitize FIT.json SLIDER [-o tools/light_v3_fits/SLIDER.json] + Turn a result of the fitting tool (fit_pointwise.py, kept with the private fitting data) into the committed + form: the coefficients, the counts and aggregate errors only (median per amount, reference, size and split). + Publish an error group or band only when at least three distinct photos contribute, + with no photo names, paths or per-photo values. Swapping a fit is sanitizing the new one over the slider's + file, then `rust`. + +The fitting data are private: black-box Lightroom exports of the owner's photos. A public render-fidelity tool for +measuring your own exports is proposed separately in #1181; it is not included in this checkout. + +Needs numpy only: tools/requirements-light-v3.txt. +""" + +import argparse +import hashlib +import json +import sys +from collections import defaultdict +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from light_v3_family import KNOTS as FAMILY_KNOTS, Family # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +FITS = ROOT / "tools" / "light_v3_fits" +OUT = ROOT / "crates" / "pipeline" / "src" / "light_v3_params.rs" +SLIDERS = {"contrast": "light.contrast", "blacks": "light.blacks"} +MODES = {"pc": "PerChannel", "lum": "Luminance", "mix": "Mix"} +KNOTS = [float(k) for k in FAMILY_KNOTS] +BANDS = ["<.03", ".03-.10", ".10-.25", ".25-.50", ".50-.90", ">.90"] +MIN_PHOTOS = 3 +# where the reference values are taken (encoded ProPhoto values, amounts, pixels) +REF_V = [0.0, 0.004, 0.012, 0.03, 0.07, 0.11, 0.17, 0.25, 0.33, 0.45, 0.58, 0.7, 0.81, 0.9, 0.97, 1.0] +REF_A = [-100.0, -63.0, -25.0, -4.0, -1.0, 1.0, 4.0, 25.0, 63.0, 100.0] +REF_PIX = [[0.02, 0.05, 0.01], [0.3, 0.25, 0.2], [0.55, 0.5, 0.62], [0.9, 0.85, 0.7], [0.15, 0.4, 0.35], [0.75, 0.97, 0.99]] + + +def layout(name, fit, path): + """Whether a fit is signed, after checking it against the family.""" + if fit.get("slider") != SLIDERS[name]: + sys.exit(f"{path}: a fit of {fit.get('slider')}, not {SLIDERS[name]}") + if fit.get("knots") != KNOTS: + sys.exit(f"{path}: knots {fit.get('knots')} are not the family's {KNOTS}") + if fit.get("mode") not in MODES: + sys.exit(f"{path}: unknown mode {fit.get('mode')}") + base = Family(fit["mode"]).size + n = len(fit["params"]) + if n != base: + sys.exit(f"{path}: {n} parameters, the family needs {base}") + return name == "contrast" + + + +def sanitize(args): + path = Path(args.fit) + raw = path.read_bytes() + fit = json.loads(raw) + signed = layout(args.slider, fit, path) + errors = {} + for split in ("tune", "check"): + by = defaultdict(list) + for r in fit.get(split, []): + by[(r["a_tgt"], r["a_ref"], r["long_edge"])].append(r) + rows = [] + for (a_tgt, a_ref, edge), g in sorted(by.items()): + photos = len({r["photo"] for r in g}) + if photos < MIN_PHOTOS: + continue + band_photos = {b: len({r["photo"] for r in g if b in r["cells"]}) for b in BANDS} + band_photos = {b: n for b, n in band_photos.items() if n >= MIN_PHOTOS} + bands = {b: float(np.median([r["cells"][b]["error"] for r in g if b in r["cells"]])) + for b in band_photos} + rows.append({"amount": a_tgt, "reference": a_ref, "long_edge": edge, "pairs": len(g), + "photos": photos, "encoded_error": float(np.median([r["encoded_error"] for r in g])), + "band_error": bands, "band_photos": band_photos}) + errors[split] = rows + out = { + "slider": fit["slider"], "mode": fit["mode"], "signed": signed, + "knots": fit["knots"], "params": fit["params"], "amounts": fit.get("amounts"), + "tune_pairs": fit.get("tune_pairs"), "tune_photos": fit.get("tune_photos"), + "check_pairs": fit.get("check_pairs"), "check_photos": len({r["photo"] for r in fit.get("check", [])}), + "cost": fit.get("cost") if len({r["photo"] for r in fit.get("tune", [])}) >= MIN_PHOTOS else None, + "status": fit.get("status"), + "fitted_as": {"file": path.name, "sha256": hashlib.sha256(raw).hexdigest()}, + "median_errors": errors, + } + text = json.dumps(out, indent=1) + "\n" + for bad in ("DSC", "/Users", "photo\"", ".ARW", ".arw", ".tif"): + if bad in text: + sys.exit(f"{path}: the sanitized fit still contains {bad!r}") + dest = Path(args.o) if args.o else FITS / f"{args.slider}.json" + dest.write_text(text) + print(f"{args.slider}: {path.name} -> {dest}") + + +def wrap(tokens, indent, width=140): + """Comma-separated tokens packed into lines of at most `width` characters, each indented.""" + lines, line = [], "" + for t in tokens: + if line and len(indent) + len(line) + len(t) + 2 > width: + lines.append(indent + line.rstrip()) + line = "" + line += t + ", " + if line: + lines.append(indent + line.rstrip()) + return lines + + +def exact(v): + return repr(float(v)) + + +def ref12(v): + """A reference value at 12 significant digits (numpy's last bit differs between machines and libraries).""" + s = f"{float(v):.12g}" + return s if any(c in s for c in ".en") else s + ".0" + + +def load(name): + path = FITS / f"{name}.json" + raw = path.read_bytes() + fit = json.loads(raw) + signed = layout(name, fit, path) + fam = Family(fit["mode"], signed=signed) + p = np.array(fit["params"], dtype=np.float64) + grid = np.linspace(0, 1, 20001) + ref = [] + for a in REF_A: + curve = fam.curve(p, a, np.array(REF_V)) + # Apply where the curve increases everywhere (the Rust tables flatten a fold). + increasing = bool(np.all(np.diff(fam.curve(p, a, grid)) >= 0)) + apply = fam.apply(p, a, np.array(REF_PIX)) if increasing else None + ref.append((a, list(curve), None if apply is None else [list(r) for r in apply])) + return {"name": name, "path": path.relative_to(ROOT).as_posix(), "sha256": hashlib.sha256(raw).hexdigest(), + "fit": fit, "signed": signed, "reference": ref} + + +def rust(args): + fits = [load(name) for name in SLIDERS] + out = [ + "//! Fitted constants of process V4's Contrast and Blacks ([`crate::light_v3`]).", + "//!", + "//! GENERATED by `tools/light_v3_constants.py rust` from the committed fits named below: do not edit by hand,", + "//! regenerate (the script must reproduce this file byte for byte).", + "//!", + "//! The values are fitted to black-box Lightroom exports of one person's Sony ILCE-7CR photos (the exports'", + "//! pixels only: no Lightroom code, tables or files), each slider against the same photo's Neutral or another", + "//! amount exported in the same batch, on the tune photos; the check photos were held out. The exports are", + "//! private; errors are published only with at least three contributing photos. These are our operator family's", + "//! parameters (`docs/light-v3.md`), not Lightroom's.", + "//!", + ] + for f in fits: + fit = f["fit"] + out += [f"//! - {f['name'].capitalize()}: `{f['path']}` (fitted as `{fit['fitted_as']['file']}`), mode " + f"`{fit['mode']}`; {fit['tune_pairs']} tune pairs on " + f"{fit['tune_photos']} photos, {fit['check_pairs']} check pairs on {fit['check_photos']} photos;", + f"//! sha256 `{f['sha256']}`."] + out += ["", "use crate::light_v3::{Fit, Mode};", "#[cfg(test)]", "use crate::light_v3::Reference;", "", + "/// The family's knots: the displacement shapes are piecewise linear on them.", + f"pub const KNOTS: [f64; {len(KNOTS)}] = [{', '.join(exact(k) for k in KNOTS)}];", ""] + for f in fits: + fit = f["fit"] + doc = [f"/// `{f['path']}`."] + out += [*doc, + f"pub const {f['name'].upper()}: Fit = Fit {{", + f" mode: Mode::{MODES[fit['mode']]},", + f" signed: {'true' if f['signed'] else 'false'},", + " params: &[", + *wrap([exact(v) for v in fit["params"]], " "), + " ],", + "};", + ""] + out += ["/// Where the reference values are taken: encoded values and pixels (encoded ProPhoto).", + "#[cfg(test)]", f"pub const REF_V: [f64; {len(REF_V)}] = [", *wrap(map(exact, REF_V), " "), "];", + "#[cfg(test)]", f"pub const REF_PIX: [[f64; 3]; {len(REF_PIX)}] = [", + *wrap(("[" + ", ".join(map(exact, r)) + "]" for r in REF_PIX), " "), "];", + ""] + for f in fits: + rows = [] + for a, curve, apply in f["reference"]: + rows += [" Reference {", f" amount: {exact(a)},", " curve: &[", + *wrap(map(ref12, curve), " "), " ],"] + if apply is None: + rows.append(" apply: None,") + else: + rows += [" apply: Some(&[", + *wrap(("[" + ", ".join(map(ref12, r)) + "]" for r in apply), " "), " ]),"] + rows.append(" },") + out += [f"/// The family's own `curve` at [`REF_V`] and `apply` on [`REF_PIX`] for `{f['path']}` (12 significant", + "/// digits).", "#[cfg(test)]", f"pub const {f['name'].upper()}_REFERENCE: &[Reference] = &[", *rows, + "];", ""] + dest = Path(args.o) if args.o else OUT + text = "\n".join(out) + if args.check: + same = dest.exists() and dest.read_text() == text + print(f"{dest}: {'reproduced byte for byte' if same else 'DIFFERS from what the committed fits give'}") + return 0 if same else 1 + dest.write_text(text) + for f in fits: + print(f"{f['name']}: {f['path']} ({f['fit']['fitted_as']['file']}) {f['fit']['mode']}" + f", {len(f['fit']['params'])} parameters") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + r = sub.add_parser("rust") + r.add_argument("-o"), r.add_argument("--check", action="store_true") + s = sub.add_parser("sanitize") + s.add_argument("fit"), s.add_argument("slider", choices=list(SLIDERS)), s.add_argument("-o") + args = ap.parse_args() + return rust(args) if args.cmd == "rust" else sanitize(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/light_v3_family.py b/tools/light_v3_family.py new file mode 100644 index 0000000000..c0562c48ed --- /dev/null +++ b/tools/light_v3_family.py @@ -0,0 +1,78 @@ +"""Process V3's Light operator family (docs/light-v3.md), as the fitting tool defines it. + +This is the part of the fitting tool (`fit_pointwise.py`, kept with the private fitting data) that +`light_v3_constants.py` needs to write the Rust tests' reference values: `Family.curve`, `Family.apply`, +`Family.law` and `Family.unpack` for Contrast and Blacks. `crates/pipeline/src/light_v3.rs` is the Rust port +of the same functions, and its tests compare the two. + +F_a(v) = v + s(a) D+(v) for a > 0, max(0, v - s(a) D-(v)) for a < 0, with D piecewise linear on KNOTS (D(1) = 0; +signed shapes also D(0) = 0) and s(t) = ((1 - exp(-t / tau)) / (1 - exp(-1 / tau)))^q, t = |a| / 100. v is a channel value of linear ProPhoto RGB (D50) through the sRGB +transfer curve. Modes: pc (per channel), lum (on the encoded ProPhoto luminance, linear RGB scaled by the ratio), +mix (w pc + (1 - w) lum in linear light, a weight per sign). +""" + +import numpy as np + +PRO_Y = np.array([0.2880402, 0.7118741, 0.0000857]) +KNOTS = np.array([0.0, 0.02, 0.05, 0.09, 0.14, 0.2, 0.28, 0.38, 0.5, 0.65, 0.82, 1.0]) + + +def lin(e): + return np.where(e <= 0.04045, e / 12.92, ((e + 0.055) / 1.055) ** 2.4) + + +def enc(l): + l = np.clip(l, 0.0, None) + return np.where(l <= 0.0031308, 12.92 * l, 1.055 * np.power(l, 1 / 2.4) - 0.055) + + +class Family: + def __init__(self, mode, signed=False): + self.mode = mode + # Contrast moves tones both ways around a pivot: signed shapes, anchored at black and white + self.signed = signed + self.n_shape = len(KNOTS) - 1 # D(1) = 0 + self.size = 2 * self.n_shape + 4 + (2 if mode == "mix" else 0) + + def unpack(self, p): + n = self.n_shape + d_pos = np.append(p[:n], 0.0) + d_neg = np.append(p[n:2 * n], 0.0) + if self.signed: + d_pos[0] = d_neg[0] = 0.0 + i = 2 * n + s_pos = (float(np.exp(p[i])), float(np.exp(p[i + 1]))) # (tau, q), positive amounts + s_neg = (float(np.exp(p[i + 2])), float(np.exp(p[i + 3]))) # negative amounts + i += 4 + w = (1 / (1 + np.exp(-p[i])), 1 / (1 + np.exp(-p[i + 1]))) if self.mode == "mix" else None + return d_pos, d_neg, s_pos, s_neg, w + + @staticmethod + def law(tq, a): + tau, q = tq + t = min(abs(a) / 100.0, 1.0) + tau = min(max(tau, 1e-3), 1e3) + return float(((1 - np.exp(-t / tau)) / (1 - np.exp(-1 / tau))) ** q) + + def curve(self, p, a, v): + """F_a on encoded values v (any shape).""" + if a == 0: + return v + d_pos, d_neg, s_pos, s_neg, _ = self.unpack(p) + if a > 0: + return v + self.law(s_pos, a) * np.interp(v, KNOTS, d_pos) + return np.maximum(v - self.law(s_neg, a) * np.interp(v, KNOTS, d_neg), 0.0) + + def apply(self, p, a, v): + """F_a applied to (n, 3) encoded ProPhoto pixels per the mode.""" + if self.mode == "pc": + return self.curve(p, a, v) + yl = lin(v) @ PRO_Y + ye = enc(yl) + y2 = lin(self.curve(p, a, ye)) + ratio = np.where(yl > 1e-6, y2 / np.maximum(yl, 1e-6), 1.0) + lum = enc(lin(v) * ratio[:, None]) + if self.mode == "lum": + return lum + w = self.unpack(p)[4][0 if a > 0 else 1] + return enc(w * lin(self.curve(p, a, v)) + (1 - w) * lin(lum)) diff --git a/tools/light_v3_fits/blacks.json b/tools/light_v3_fits/blacks.json new file mode 100644 index 0000000000..10be656b56 --- /dev/null +++ b/tools/light_v3_fits/blacks.json @@ -0,0 +1,629 @@ +{ + "slider": "light.blacks", + "mode": "mix", + "signed": false, + "knots": [ + 0.0, + 0.02, + 0.05, + 0.09, + 0.14, + 0.2, + 0.28, + 0.38, + 0.5, + 0.65, + 0.82, + 1.0 + ], + "params": [ + 0.0016748697345088984, + 0.032126630862752484, + 0.07188512588294256, + 0.09530584096821723, + 0.12925288090794965, + 0.12680972925019743, + 0.10913227308994669, + 0.10024857312175768, + 0.0835198499581404, + 0.05136152009684992, + 0.02045048232256003, + 0.00011845423640374467, + 0.2706623236742467, + 0.42355931120492346, + 0.37893058797626605, + 0.22045052169596244, + 0.20955478047682013, + 0.2107908996685734, + 0.16685612159796198, + 0.13055496600268582, + 0.08667135921560576, + 0.03499725744978859, + 14.344979966519135, + 0.1199976090379452, + 6.829791928600096, + 0.5956122696562978, + 0.6007994346537187, + 22.053184691621333 + ], + "amounts": { + "pos": [ + 1.0, + 2.0, + 10.0, + 25.0, + 50.0 + ], + "neg": [ + 1.0, + 2.0, + 10.0, + 25.0, + 50.0 + ] + }, + "tune_pairs": 148, + "tune_photos": 19, + "check_pairs": 60, + "check_photos": 6, + "cost": 0.0008745122527803675, + "status": "`xtol` termination condition is satisfied.", + "fitted_as": { + "file": "v2-blacks-mix.json", + "sha256": "7a4eaf80f609bce82796255f2143379c2a861d9e4ad837d8b1cee13d8ee8bbbf" + }, + "median_errors": { + "tune": [ + { + "amount": -100.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.003427741630935885, + "band_error": { + ".03-.10": 0.2213629580750902, + ".10-.25": 0.02608652782453921, + ".25-.50": 0.01578410979952499, + ".50-.90": 0.002808023738105474 + }, + "band_photos": { + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 10 + } + }, + { + "amount": -50.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.005919080768408077, + "band_error": { + "<.03": 2.540801442208995, + ".03-.10": 0.08111268411041608, + ".10-.25": 0.04438409233495842, + ".25-.50": 0.020550565205089452, + ".50-.90": 0.006222082011956415 + }, + "band_photos": { + "<.03": 13, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 10 + } + }, + { + "amount": -25.0, + "reference": 25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.0031214485072743755, + "band_error": { + "<.03": 0.16329115247026024, + ".03-.10": 0.036668113073784654, + ".10-.25": 0.022776150840884937, + ".25-.50": 0.014843370759525187, + ".50-.90": 0.0039038961386700737 + }, + "band_photos": { + "<.03": 15, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 11 + } + }, + { + "amount": -10.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0028229433114912773, + "band_error": { + "<.03": 0.13178410951728228, + ".03-.10": 0.04196128224444614, + ".10-.25": 0.01762880043633539, + ".25-.50": 0.007293565839224106, + ".50-.90": 0.002609491855638238 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": -2.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.00041129347233050275, + "band_error": { + "<.03": 0.019017656661272694, + ".03-.10": 0.005756775376322533, + ".10-.25": 0.002565234930383287, + ".25-.50": 0.001145782173166264, + ".50-.90": 0.000382322002835805 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 6 + } + }, + { + "amount": -1.0, + "reference": 1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0003722974487077393, + "band_error": { + "<.03": 0.018366070435347367, + ".03-.10": 0.004089734153371508, + ".10-.25": 0.0018553694269353212, + ".25-.50": 0.0009593820885241899, + ".50-.90": 0.0004271225438045706 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": 1.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0003760698824047078, + "band_error": { + "<.03": 0.017287292651452933, + ".03-.10": 0.004092564163348587, + ".10-.25": 0.0018455583699485529, + ".25-.50": 0.0009623571483044081, + ".50-.90": 0.0004186288558887353 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": 2.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.00020040955093125052, + "band_error": { + "<.03": 0.013753116645338119, + ".03-.10": 0.0007162453275012053, + ".10-.25": 0.0003540900235241904, + ".25-.50": 0.00038934971977656153, + ".50-.90": 0.0002782855548532337 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": 10.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.001783838738716413, + "band_error": { + "<.03": 0.05284982502051819, + ".03-.10": 0.03724809716093273, + ".10-.25": 0.019205512149578937, + ".25-.50": 0.006917961002757063, + ".50-.90": 0.0015806259646429421 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": 25.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.003709389204943277, + "band_error": { + "<.03": 0.09494415640775108, + ".03-.10": 0.0176749098453267, + ".10-.25": 0.018947490336089716, + ".25-.50": 0.013097052459767222, + ".50-.90": 0.003511734102272039 + }, + "band_photos": { + "<.03": 13, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 11 + } + }, + { + "amount": 50.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.002609444120265867, + "band_error": { + "<.03": 0.07482435736855328, + ".03-.10": 0.013436692118006998, + ".10-.25": 0.017886792958307664, + ".25-.50": 0.009087796540733195, + ".50-.90": 0.003603605087350397 + }, + "band_photos": { + "<.03": 13, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 10 + } + }, + { + "amount": 100.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.0052279389117479615, + "band_error": { + "<.03": 0.06867116555034346, + ".03-.10": 0.028802027760147397, + ".10-.25": 0.03517066425047481, + ".25-.50": 0.015005585548450773, + ".50-.90": 0.005419520070429491 + }, + "band_photos": { + "<.03": 13, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 10 + } + } + ], + "check": [ + { + "amount": -100.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.0026036276924897854, + "band_error": { + ".03-.10": 0.2724794859787279, + ".10-.25": 0.032524388827564095, + ".25-.50": 0.01623772080888221, + ".50-.90": 0.001974081452192045, + ">.90": 0.00327166522465544 + }, + "band_photos": { + ".03-.10": 6, + ".10-.25": 5, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": -50.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.00630845958129503, + "band_error": { + "<.03": 2.937882639375302, + ".03-.10": 0.08392136241031861, + ".10-.25": 0.046410663700769156, + ".25-.50": 0.020183223853684526, + ".50-.90": 0.004274811360970359, + ">.90": 0.0011760232124998261 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": -25.0, + "reference": 25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.0031592008349393005, + "band_error": { + "<.03": 0.14080623765681227, + ".03-.10": 0.0318373066028957, + ".10-.25": 0.03224211267963081, + ".25-.50": 0.016030589604536166, + ".50-.90": 0.0031808853864495733, + ">.90": 0.00110274155996526 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": -10.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.0032315112484176496, + "band_error": { + "<.03": 0.12510974742848963, + ".03-.10": 0.05015845177052797, + ".10-.25": 0.021326590472185665, + ".25-.50": 0.008380427925365043, + ".50-.90": 0.0016479323536602991, + ">.90": 0.00011413404472121791 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": -2.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.00045617733812925115, + "band_error": { + "<.03": 0.01925846038820568, + ".03-.10": 0.0063834108841469995, + ".10-.25": 0.003030159155055237, + ".25-.50": 0.001279033505962499, + ".50-.90": 0.0002698196294867122, + ">.90": 2.7633406386833942e-05 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": -1.0, + "reference": 1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.00038314168156171563, + "band_error": { + "<.03": 0.0179409887964789, + ".03-.10": 0.004554594316174306, + ".10-.25": 0.0021860614907081508, + ".25-.50": 0.0010348608044738427, + ".50-.90": 0.00027134539581991134, + ">.90": 2.327437207747032e-05 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": 1.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.00038163643693189483, + "band_error": { + "<.03": 0.01789697865555805, + ".03-.10": 0.0045282975606357224, + ".10-.25": 0.002195762186994404, + ".25-.50": 0.0009878774705477829, + ".50-.90": 0.0002783038732938448, + ">.90": 2.686083194581795e-05 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": 2.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.0001803959147575279, + "band_error": { + "<.03": 0.01212475922937082, + ".03-.10": 0.0009431699585146074, + ".10-.25": 0.000355929836981769, + ".25-.50": 0.0003440476619261129, + ".50-.90": 0.00019109718572074783, + ">.90": 1.9847289480291946e-05 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": 10.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.002290357662922615, + "band_error": { + "<.03": 0.05709934188572894, + ".03-.10": 0.0408071092493482, + ".10-.25": 0.020792684426191338, + ".25-.50": 0.007346519738751282, + ".50-.90": 0.0010646491817687589, + ">.90": 0.00026393508368777066 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": 25.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.0030198740694812503, + "band_error": { + "<.03": 0.0725997864669866, + ".03-.10": 0.022094528007660656, + ".10-.25": 0.026543951558102536, + ".25-.50": 0.01324388164672667, + ".50-.90": 0.0026208880613337988, + ">.90": 0.0010779135256942629 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": 50.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.002475906570262025, + "band_error": { + "<.03": 0.061356997170475686, + ".03-.10": 0.009863474631073559, + ".10-.25": 0.01476986021053679, + ".25-.50": 0.010247807139551512, + ".50-.90": 0.0031242534323023554, + ">.90": 0.002042051985148796 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": 100.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.004946325387271203, + "band_error": { + "<.03": 0.08131887755018244, + ".03-.10": 0.033910589363778845, + ".10-.25": 0.02538659945793769, + ".25-.50": 0.025997571830863868, + ".50-.90": 0.007104110918209644, + ">.90": 0.005182159260201775 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 5, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + } + ] + } +} diff --git a/tools/light_v3_fits/contrast.json b/tools/light_v3_fits/contrast.json new file mode 100644 index 0000000000..d6191b001d --- /dev/null +++ b/tools/light_v3_fits/contrast.json @@ -0,0 +1,688 @@ +{ + "slider": "light.contrast", + "mode": "pc", + "signed": true, + "knots": [ + 0.0, + 0.02, + 0.05, + 0.09, + 0.14, + 0.2, + 0.28, + 0.38, + 0.5, + 0.65, + 0.82, + 1.0 + ], + "params": [ + 9.797174393178826e-18, + -0.017053489024880908, + -0.04260284838408044, + -0.07195939270312468, + -0.09738651081071477, + -0.1088504066519633, + -0.10140378035603768, + -0.06947815571389163, + -0.007856500339789655, + 0.08463087858854193, + 0.1098534938016389, + 0.30583740028604467, + -0.05850866310699469, + -0.07854274245013221, + -0.09074476735486797, + -0.0906596002773617, + -0.08429179542961336, + -0.07428102082426319, + -0.05004459522573259, + -0.00906946010144, + 0.056653920573147026, + 0.09818533983265328, + 0.3070552562874873, + 0.10657448975892592, + -0.13962415708911588, + 0.37724097657204825 + ], + "amounts": { + "pos": [ + 1.0, + 2.0, + 10.0, + 20.0, + 25.0, + 50.0 + ], + "neg": [ + 1.0, + 2.0, + 10.0, + 25.0, + 50.0 + ] + }, + "tune_pairs": 155, + "tune_photos": 20, + "check_pairs": 61, + "check_photos": 6, + "cost": 0.007425023807942876, + "status": "`ftol` termination condition is satisfied.", + "fitted_as": { + "file": "v2-contrast-pc.json", + "sha256": "a3edbd6959efc611a62f77c35ec3d0228249a818e26d913a6813e966e245a218" + }, + "median_errors": { + "tune": [ + { + "amount": -100.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.011121768451379337, + "band_error": { + "<.03": 0.06473831720828421, + ".03-.10": 0.0930115027157312, + ".10-.25": 0.10855335247607187, + ".25-.50": 0.08458112931798814, + ".50-.90": 0.04951305393020604 + }, + "band_photos": { + "<.03": 15, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 11 + } + }, + { + "amount": -50.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.004286254992238507, + "band_error": { + "<.03": 0.08798561426579082, + ".03-.10": 0.023395491074571718, + ".10-.25": 0.04125160013916516, + ".25-.50": 0.02813656219386674, + ".50-.90": 0.01224863264329086 + }, + "band_photos": { + "<.03": 15, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 11 + } + }, + { + "amount": -50.0, + "reference": 50.0, + "long_edge": 6000, + "pairs": 3, + "photos": 3, + "encoded_error": 0.0056569939840179885, + "band_error": { + "<.03": 0.09798367558474397, + ".03-.10": 0.130792624631025 + }, + "band_photos": { + "<.03": 3, + ".03-.10": 3 + } + }, + { + "amount": -25.0, + "reference": 25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.006945703844995149, + "band_error": { + "<.03": 0.042459022563571834, + ".03-.10": 0.06599006511649402, + ".10-.25": 0.07119527732608275, + ".25-.50": 0.06194452558952893, + ".50-.90": 0.02380380595363875 + }, + "band_photos": { + "<.03": 15, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 12 + } + }, + { + "amount": -10.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0022531301423689854, + "band_error": { + "<.03": 0.03697373149772598, + ".03-.10": 0.03971304167226704, + ".10-.25": 0.022404234718419867, + ".25-.50": 0.009058685811361137, + ".50-.90": 0.010657569861098629 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": -2.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0003852393871073691, + "band_error": { + "<.03": 0.007012211524007572, + ".03-.10": 0.0066646566763887746, + ".10-.25": 0.00286755977345968, + ".25-.50": 0.0017240802086141635, + ".50-.90": 0.0018782060083671758 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": -1.0, + "reference": 1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0006543633779320837, + "band_error": { + "<.03": 0.01886873284344166, + ".03-.10": 0.010292594464825184, + ".10-.25": 0.005632954367000359, + ".25-.50": 0.002241935441265079, + ".50-.90": 0.0031058898304381823 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": 1.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0006527385589234222, + "band_error": { + "<.03": 0.018817926083770614, + ".03-.10": 0.010358472561087979, + ".10-.25": 0.005616058982285934, + ".25-.50": 0.0021934787509894807, + ".50-.90": 0.0030850495726458984 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": 2.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0008095368298390367, + "band_error": { + "<.03": 0.02333747747697981, + ".03-.10": 0.011422288253035966, + ".10-.25": 0.00742974381498245, + ".25-.50": 0.0038965317200995025, + ".50-.90": 0.0034447363133185732 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": 10.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 7, + "photos": 7, + "encoded_error": 0.0018082128746201764, + "band_error": { + "<.03": 0.045326689844745194, + ".03-.10": 0.011501487324692514, + ".10-.25": 0.019129575064688376, + ".25-.50": 0.0125055419250812, + ".50-.90": 0.0044824579865754555 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 7, + ".25-.50": 7, + ".50-.90": 5 + } + }, + { + "amount": 20.0, + "reference": 0.0, + "long_edge": 6000, + "pairs": 5, + "photos": 5, + "encoded_error": 0.00309267216217087, + "band_error": { + "<.03": 0.048859278779928295, + ".03-.10": 0.0445593256864193, + ".10-.25": 0.037886311299740134, + ".25-.50": 0.018012343705216413, + ".50-.90": 0.0076965072545667045 + }, + "band_photos": { + "<.03": 5, + ".03-.10": 5, + ".10-.25": 5, + ".25-.50": 5, + ".50-.90": 3 + } + }, + { + "amount": 25.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.007903821110042217, + "band_error": { + "<.03": 0.05150865439744394, + ".03-.10": 0.07246865874385416, + ".10-.25": 0.09144243025121834, + ".25-.50": 0.06400970326100287, + ".50-.90": 0.016674153313752264 + }, + "band_photos": { + "<.03": 15, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 10 + } + }, + { + "amount": 50.0, + "reference": -50.0, + "long_edge": 6000, + "pairs": 3, + "photos": 3, + "encoded_error": 0.006205513903254146, + "band_error": { + "<.03": 0.11470709333534655, + ".03-.10": 0.118067402841938, + ".10-.25": 0.2729320736520823 + }, + "band_photos": { + "<.03": 3, + ".03-.10": 3, + ".10-.25": 3 + } + }, + { + "amount": 50.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.013146197515222533, + "band_error": { + "<.03": 0.09093522091940583, + ".03-.10": 0.10255589841297505, + ".10-.25": 0.14165315810252282, + ".25-.50": 0.08784201480208256, + ".50-.90": 0.02373075387210262 + }, + "band_photos": { + "<.03": 15, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 10 + } + }, + { + "amount": 100.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 17, + "photos": 17, + "encoded_error": 0.019644083854275383, + "band_error": { + "<.03": 0.14785079413511482, + ".03-.10": 0.28522605929536815, + ".10-.25": 0.2893249382631822, + ".25-.50": 0.15281210908420345, + ".50-.90": 0.02904286478459617 + }, + "band_photos": { + "<.03": 14, + ".03-.10": 15, + ".10-.25": 16, + ".25-.50": 16, + ".50-.90": 9 + } + } + ], + "check": [ + { + "amount": -100.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.00614368415261454, + "band_error": { + "<.03": 0.059928983720484864, + ".03-.10": 0.03849443290379879, + ".10-.25": 0.06826161779527672, + ".25-.50": 0.06509598397385213, + ".50-.90": 0.05217615569259957, + ">.90": 0.031190911184747684 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": -50.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.0023659145274087735, + "band_error": { + "<.03": 0.06470759304831414, + ".03-.10": 0.009370845846563901, + ".10-.25": 0.026351516593929925, + ".25-.50": 0.019327549018610488, + ".50-.90": 0.011562978286385712, + ">.90": 0.005461528273139457 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": -25.0, + "reference": 25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.003398590038466944, + "band_error": { + "<.03": 0.03840228695869055, + ".03-.10": 0.020796501758207908, + ".10-.25": 0.040684964046721867, + ".25-.50": 0.04701568701600178, + ".50-.90": 0.019288472096135365, + ">.90": 0.013499652156282174 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": -10.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.0020376188455170567, + "band_error": { + "<.03": 0.03620494381244924, + ".03-.10": 0.03208240175435808, + ".10-.25": 0.010473635357755147, + ".25-.50": 0.017871803195692943, + ".50-.90": 0.010263293012151831, + ">.90": 0.002715647895860737 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": -2.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.00039351188188189697, + "band_error": { + "<.03": 0.008615997075480056, + ".03-.10": 0.0061276905656996485, + ".10-.25": 0.0016374797966802114, + ".25-.50": 0.002600678552877267, + ".50-.90": 0.0017840523386103938, + ">.90": 0.0003802946498026381 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": -1.0, + "reference": 1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.0006805247753234763, + "band_error": { + "<.03": 0.018760298025893515, + ".03-.10": 0.008662470862737264, + ".10-.25": 0.00263534266805685, + ".25-.50": 0.004147011742721331, + ".50-.90": 0.0029838535914747215, + ">.90": 0.0007237557973570842 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": 1.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.0006726023263027637, + "band_error": { + "<.03": 0.01891795182475012, + ".03-.10": 0.008848860673192677, + ".10-.25": 0.0027310450646397463, + ".25-.50": 0.0042898284968232525, + ".50-.90": 0.0029359593356539817, + ">.90": 0.0007228384571375645 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": 2.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.0007419673662760145, + "band_error": { + "<.03": 0.02288867540873815, + ".03-.10": 0.008542193659454047, + ".10-.25": 0.0028634353466732527, + ".25-.50": 0.005128283993017973, + ".50-.90": 0.0033098642592463267, + ">.90": 0.0008105193292430162 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": 10.0, + "reference": -1.0, + "long_edge": 2048, + "pairs": 4, + "photos": 4, + "encoded_error": 0.0011864056487623834, + "band_error": { + "<.03": 0.03999974952353827, + ".03-.10": 0.005283445715065133, + ".10-.25": 0.01467700568320757, + ".25-.50": 0.009489447536394666, + ".50-.90": 0.00398762454890003, + ">.90": 0.0016691396424735546 + }, + "band_photos": { + "<.03": 4, + ".03-.10": 4, + ".10-.25": 4, + ".25-.50": 3, + ".50-.90": 3, + ">.90": 3 + } + }, + { + "amount": 25.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.0036202176280724597, + "band_error": { + "<.03": 0.04541808011087295, + ".03-.10": 0.032641002299673386, + ".10-.25": 0.04250708854059583, + ".25-.50": 0.049747993323797084, + ".50-.90": 0.015917120629692874, + ">.90": 0.004955059580255294 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": 50.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.005293621966822463, + "band_error": { + "<.03": 0.0887657367547818, + ".03-.10": 0.03648056023382013, + ".10-.25": 0.07667411207439194, + ".25-.50": 0.06098566466448595, + ".50-.90": 0.020046398187211347, + ">.90": 0.005424273085440311 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + }, + { + "amount": 100.0, + "reference": -25.0, + "long_edge": 2048, + "pairs": 6, + "photos": 6, + "encoded_error": 0.00927203928537906, + "band_error": { + "<.03": 0.11764958884120004, + ".03-.10": 0.1451408972189724, + ".10-.25": 0.10497093206952726, + ".25-.50": 0.12045842741876807, + ".50-.90": 0.023191055675967395, + ">.90": 0.0075026383932912995 + }, + "band_photos": { + "<.03": 6, + ".03-.10": 6, + ".10-.25": 6, + ".25-.50": 5, + ".50-.90": 5, + ">.90": 3 + } + } + ] + } +} diff --git a/tools/requirements-light-v3.txt b/tools/requirements-light-v3.txt new file mode 100644 index 0000000000..3064a1e8c3 --- /dev/null +++ b/tools/requirements-light-v3.txt @@ -0,0 +1,3 @@ +# Python packages for tools/light_v3_constants.py (crates/pipeline/src/light_v3_params.rs, docs/light-v3.md). +# python3 -m venv .venv-light-v3 && .venv-light-v3/bin/pip install -r tools/requirements-light-v3.txt +numpy==2.4.6 diff --git a/tools/requirements-sony-distortion-check.txt b/tools/requirements-sony-distortion-check.txt new file mode 100644 index 0000000000..56ab4f9e23 --- /dev/null +++ b/tools/requirements-sony-distortion-check.txt @@ -0,0 +1,6 @@ +# Python packages for tools/sony_distortion_check.py (docs/sony-lens-corrections.md). +# python3 -m venv .venv-distortion && .venv-distortion/bin/pip install -r tools/requirements-sony-distortion-check.txt +numpy==2.5.3 +scipy==1.18.1 +opencv-python-headless==5.0.0.93 +Pillow==12.3.0 diff --git a/tools/sony_distortion_check.py b/tools/sony_distortion_check.py new file mode 100755 index 0000000000..ad76c12676 --- /dev/null +++ b/tools/sony_distortion_check.py @@ -0,0 +1,426 @@ +#!/usr/bin/env python3 +"""Compare LightCraft's Sony embedded distortion correction with the camera's own JPEG. + + python3 -m venv .venv-distortion && .venv-distortion/bin/pip install -r tools/requirements-sony-distortion-check.txt + .venv-distortion/bin/python tools/sony_distortion_check.py --cli target/release/lightcraft-cli \ + --work WORKDIR [--json results.json] PHOTO_DIR [PHOTO_DIR…] + +Every ARW with a JPG of the same name is rendered by LightCraft twice, embedded correction on +and off, and measured against the camera JPEG (shot with Lens Comp. Distortion on Auto): + +* agreement: offsets of matching features after the best similarity (scale, rotation, shift) + between the render and the JPEG, by distance from the centre (0 = centre, 1 = corner); +* straightness: how far each checkerboard row and column bows away from a straight line. + +Checkerboard shots use the board's corners (sub-pixel), other shots SIFT features (agreement +only). Offsets are in pixels of the camera JPEG (6000 px wide on the A7 III); the "@2376" +columns rescale them to the 2376 px exports docs/sony-lens-corrections.md reports (method and results +there, under "ILCE-7M3 validation"). +""" + +import argparse +import hashlib +import json +import os +import shutil +import subprocess +import sys + +import cv2 +import numpy as np +from scipy.spatial import cKDTree + +WORK_LONG_EDGE = 3000 # detection resolution; coordinates are rescaled to the JPEG's pixels +BINS = [0.0, 0.25, 0.5, 0.75, 0.9, 1.01] +REPORT_WIDTH = 2376 + + +def render(cli, arw, out, on): + """Render `arw` with the profile correction `on` or off to `out`, reusing an output newer than the CLI and ARW.""" + settings = out + ".settings.json" + with open(settings, "w") as f: + json.dump({"optics": {"lens_profile": on, "profile_distortion": 100}}, f) + exe = shutil.which(cli) or cli + current = os.path.exists(out) and os.path.getmtime(out) >= max(os.path.getmtime(exe), os.path.getmtime(arw)) + if not current: + r = subprocess.run([exe, "render", arw, "-o", out, "--settings", settings], capture_output=True) + if r.returncode != 0: + err = r.stderr.decode(errors="replace").strip() + raise RuntimeError(f"render failed ({r.returncode}) for {arw}: {err[-500:]}") + return out + + +def load_gray(path): + """Grey image at the working resolution and the factor back to its own full-size pixels.""" + img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) + if img is None: + raise RuntimeError(f"cannot read {path}") + h, w = img.shape + k = WORK_LONG_EDGE / max(w, h) + small = cv2.resize(img, (round(w * k), round(h * k)), interpolation=cv2.INTER_AREA) + return small, 1.0 / k, (w, h) + + +# ---------------------------------------------------------------- checkerboard corners + +def detect_corners(gray): + """X-corners of a checkerboard: Hessian saddle points, refined with cornerSubPix.""" + g = cv2.GaussianBlur(gray.astype(np.float32), (0, 0), 3.0) + gxx = cv2.Sobel(g, cv2.CV_32F, 2, 0, ksize=5) + gyy = cv2.Sobel(g, cv2.CV_32F, 0, 2, ksize=5) + gxy = cv2.Sobel(g, cv2.CV_32F, 1, 1, ksize=5) + saddle = gxy * gxy - gxx * gyy + top = np.percentile(saddle, 99.95) + if top <= 0: + return np.zeros((0, 2), np.float32) + peaks = (saddle == cv2.dilate(saddle, np.ones((15, 15), np.uint8))) & (saddle > 0.08 * top) + ys, xs = np.nonzero(peaks) + pts = np.stack([xs, ys], 1).astype(np.float32).reshape(-1, 1, 2) + if len(pts) == 0: + return pts.reshape(-1, 2) + crit = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 50, 0.005) + pts = cv2.cornerSubPix(gray, pts, (11, 11), (-1, -1), crit).reshape(-1, 2).astype(np.float64) + # Two peaks near one corner can refine to the same point; keep one of each such pair. + drop = {j for _, j in cKDTree(pts).query_pairs(3.0)} + pts = pts[[i for i in range(len(pts)) if i not in drop]] + return pts[[is_x_corner(g, p) for p in pts]] + + +def is_x_corner(g, p, r=12): + """A board corner has alternating quadrants: equal diagonals, contrasting neighbours. + A point on a straight edge (screen texture can make one look like a saddle) does not.""" + h, w = g.shape + x, y = int(round(p[0])), int(round(p[1])) + if not (r <= x < w - r and r <= y < h - r): + return False + a, c = g[y + r, x + r], g[y - r, x - r] + b, d = g[y - r, x + r], g[y + r, x - r] + contrast = abs((a + c) - (b + d)) / 2 + return contrast > 15 and contrast > 2 * max(abs(a - c), abs(b - d)) + + +def label_lattice(pts, centre): + """Integer (i, j) grid labels for corners connected to one near the centre. + i grows along +x, j along +y; local lattice vectors follow the distortion gradually. + The starting vectors are the consensus of many central corners, so a stray corner (screen + moiré) next to the start can't derail it; a few starts are tried, the largest result kept.""" + if len(pts) < 20: + return {} + tree = cKDTree(pts) + vectors = lattice_vectors(pts, tree, centre) + if vectors is None: + return {} + best = {} + for start in tree.query(centre, k=min(9, len(pts)))[1]: + labels = grow_lattice(pts, tree, int(start), *vectors) + if len(labels) > len(best): + best = labels + if len(best) > 0.8 * len(pts): + break + return best if len(best) > 50 else {} + + +def lattice_vectors(pts, tree, centre): + """Median neighbour offsets near +x and +y among the corners nearest the centre.""" + k = min(9, len(pts)) + offsets = [] + for i in tree.query(centre, k=min(60, len(pts)))[1]: + nn = tree.query(pts[i], k=k)[1] + offsets.extend(pts[nn[1:]] - pts[i]) + offsets = np.array(offsets) + length = np.linalg.norm(offsets, axis=1) + spacing = np.median(np.sort(length.reshape(-1, k - 1), axis=1)[:, :4]) + offsets = offsets[np.abs(length - spacing) < 0.25 * spacing] + angle = np.arctan2(offsets[:, 1], offsets[:, 0]) + near_x = np.abs(np.angle(np.exp(1j * angle))) < np.pi / 4 + near_y = np.abs(np.angle(np.exp(1j * (angle - np.pi / 2)))) < np.pi / 4 + if near_x.sum() < 10 or near_y.sum() < 10: + return None + return np.median(offsets[near_x], axis=0), np.median(offsets[near_y], axis=0) + + +def grow_lattice(pts, tree, start, a, b): + """Label corners (row, column) by stepping lattice vectors `a` and `b` out from corner `start`.""" + labels = {start: (0, 0)} + taken = {(0, 0): start} + vec = {start: (a, b)} + queue = [start] + while queue: + p = queue.pop() + i, j = labels[p] + va, vb = vec[p] + for di, dj, step in ((1, 0, va), (-1, 0, -va), (0, 1, vb), (0, -1, -vb)): + key = (i + di, j + dj) + if key in taken: + continue + dist, q = tree.query(pts[p] + step) + if dist > 0.3 * np.linalg.norm(step) or q in labels: + continue + found = pts[q] - pts[p] + na = found * di if di else va + nb = found * dj if dj else vb + labels[q] = key + taken[key] = q + vec[q] = (na, nb) + queue.append(q) + return labels + + +def board(path): + """Checkerboard corners of image `path`, keyed by (row, column), in its full-size pixels, and its size.""" + gray, back, size = load_gray(path) + pts = detect_corners(gray) + labels = label_lattice(pts, np.array(gray.shape[::-1]) / 2.0) + full = {lab: pts[k] * back for k, lab in labels.items()} + return full, size + + +def straightness(grid): + """Largest deviation from a fitted straight line over every row/column with 8+ corners.""" + lines = {} + for (i, j), p in grid.items(): + lines.setdefault(("col", i), []).append(p) + lines.setdefault(("row", j), []).append(p) + worst = [] + for pts in lines.values(): + if len(pts) < 8: + continue + pts = np.array(pts) + keep = np.ones(len(pts), bool) + for _ in range(3): # drop stray corners, then refit + c = pts[keep].mean(0) + _, _, vt = np.linalg.svd(pts[keep] - c) + dev = (pts - c) @ vt[1] + keep = np.abs(dev) <= max(1.0, 4 * np.median(np.abs(dev[keep]))) + if keep.sum() < 8: + break + if keep.sum() >= 8: + worst.append(np.abs(dev[keep]).max()) + if not worst: + return None + worst = np.array(worst) + return {"lines": len(worst), "median": float(np.median(worst)), "max": float(worst.max())} + + +def match_boards(src, src_size, dst, dst_size): + """Corner pairs between two labellings of the same shot. A board is periodic, so a fit can't + tell a one-square shift from the right match; the corners near the centre can, unfitted: + the two framings differ by a few percent of zoom, far less than a square there.""" + sc, dc = np.array(src_size) / 2.0, np.array(dst_size) / 2.0 + half_diag = np.hypot(*dst_size) / 2.0 + best = None + for oi in range(-3, 4): + for oj in range(-3, 4): + pairs = [(p, dst[(i + oi, j + oj)]) for (i, j), p in src.items() if (i + oi, j + oj) in dst] + central = [np.linalg.norm((p - sc) - (q - dc)) for p, q in pairs if np.linalg.norm(q - dc) < 0.3 * half_diag] + if len(pairs) < 50 or len(central) < 10: + continue + err = float(np.median(central)) + if best is None or err < best[0]: + best = (err, pairs) + if best is None: + return None, None + s, d = map(np.array, zip(*best[1])) + return s, d + + +# ---------------------------------------------------------------- SIFT (other scenes) + +def sift_pairs(src_path, dst_path): + """SIFT matches; both point sets in the destination's full-size pixels.""" + a, ka, size_a = load_gray(src_path) + b, kb, size_b = load_gray(dst_path) + sift = cv2.SIFT_create(nfeatures=20000) + pa, da = sift.detectAndCompute(a, None) + pb, db = sift.detectAndCompute(b, None) + if da is None or db is None: + return None, None + good = [m for m, n in cv2.BFMatcher().knnMatch(da, db, k=2) if m.distance < 0.75 * n.distance] + if len(good) < 30: + return None, None + s = np.array([pa[m.queryIdx].pt for m in good]) * ka * (size_b[0] / size_a[0]) + d = np.array([pb[m.trainIdx].pt for m in good]) * kb + return s, d + + +# ---------------------------------------------------------------- geometry + +def fit_similarity(s, d): + """Least-squares similarity (zoom, rotation, shift) mapping points `s` onto `d`, as complex (scale, offset).""" + zs = s[:, 0] + 1j * s[:, 1] + zd = d[:, 0] + 1j * d[:, 1] + ms, md = zs.mean(), zd.mean() + c = np.vdot(zs - ms, zd - md) / np.vdot(zs - ms, zs - ms) + return c, md - c * ms + + +def apply(model, p): + """Points `p` mapped by a `fit_similarity` model.""" + c, t = model + z = c * (p[:, 0] + 1j * p[:, 1]) + t + return np.stack([z.real, z.imag], 1) + + +def agreement(s, d, size): + """Similarity-fit render points s onto JPEG points d; residual statistics by radius.""" + pairs = {tuple(q): p for q, p in zip(d, s)} + keep = np.ones(len(s), bool) + # A loose first pass, then reject gross mismatches (SIFT outliers, mislabelled corners). + for limit in (0.02 * size[0], None, None): + model = fit_similarity(s[keep], d[keep]) + res = np.linalg.norm(apply(model, s) - d, axis=1) + cut = limit if limit else max(5 * np.median(res[keep]), 2.0) + keep = res < cut + if keep.sum() < 20: + return None + model = fit_similarity(s[keep], d[keep]) + s, d = s[keep], d[keep] + fitted = apply(model, s) + res = fitted - d + centre = np.array(size) / 2.0 + half_diag = np.hypot(*size) / 2.0 + rel = d - centre + r = np.linalg.norm(rel, axis=1) / half_diag + radial = np.sum(res * rel, axis=1) / np.maximum(np.linalg.norm(rel, axis=1), 1e-9) + mag = np.linalg.norm(res, axis=1) + bins = [] + for lo, hi in zip(BINS, BINS[1:]): + m = (r >= lo) & (r < hi) + bins.append({"r": f"{lo:.2f}-{min(hi, 1):.2f}", "n": int(m.sum()), + "median": float(np.median(mag[m])) if m.any() else None, + "radial": float(np.mean(radial[m])) if m.any() else None}) + return {"n": int(len(s)), "scale": float(abs(model[0])), "median": float(np.median(mag)), + "p95": float(np.percentile(mag, 95)), "max": float(mag.max()), "max_r": float(r.max()), + "bins": bins, "pairs": pairs} + + +def correction_fraction(on, off, size): + """How the camera's correction compares with LightCraft's: JPEG ≈ off + α·(on − off) radially, + both renders aligned to the JPEG on the same corners. 1 = the same amount as the camera; + above 1, the camera corrects more than LightCraft.""" + keys = [k for k in on["pairs"] if k in off["pairs"]] + if len(keys) < 50: + return None + d = np.array(keys) + raw_on = np.array([on["pairs"][k] for k in keys]) + raw_off = np.array([off["pairs"][k] for k in keys]) + keep = np.ones(len(d), bool) + for _ in range(4): + a = apply(fit_similarity(raw_on[keep], d[keep]), raw_on) + b = apply(fit_similarity(raw_off[keep], d[keep]), raw_off) + rel = d - np.array(size) / 2.0 + unit = rel / np.maximum(np.linalg.norm(rel, axis=1, keepdims=True), 1e-9) + u = np.sum((a - b) * unit, axis=1) + v = np.sum((d - b) * unit, axis=1) + if np.median(np.abs(u[keep])) < 1.0: # too little distortion at this focal length to tell + return None + alpha = float(u[keep] @ v[keep] / (u[keep] @ u[keep])) + e = np.abs(v - alpha * u) + keep = e <= max(0.5, 4 * np.median(e[keep])) # mismatched corners, not the lens + return alpha + + +# ---------------------------------------------------------------- driver + +def jpeg_for(arw): + """The camera JPEG next to `arw` (same stem), or None.""" + stem = os.path.splitext(arw)[0] + for ext in (".JPG", ".jpg", ".JPEG", ".jpeg"): + if os.path.exists(stem + ext): + return stem + ext + return None + + +def exif_summary(jpg): + """Lens, focal length and aperture of `jpg` from its Exif, for the report.""" + from PIL import Image + tags = Image.open(jpg).getexif().get_ifd(0x8769) + lens = tags.get(0xA434, "?") + focal = tags.get(0x920A) + fnum = tags.get(0x829D) + return f"{lens} {float(focal):.0f}mm f/{float(fnum):.1f}" if focal and fnum else str(lens) + + +def measure(cli, work, arw): + """Render `arw` corrected and uncorrected and measure both against its camera JPEG (None without one).""" + jpg = jpeg_for(arw) + if not jpg: + return None + name = os.path.splitext(os.path.basename(arw))[0] + # cards repeat names (DSC00001.ARW): the path's hash keeps renders of different folders apart + uid = hashlib.sha1(os.path.abspath(arw).encode()).hexdigest()[:8] + on = render(cli, arw, os.path.join(work, f"{name}.{uid}.on.png"), True) + off = render(cli, arw, os.path.join(work, f"{name}.{uid}.off.png"), False) + out = {"file": name, "shot": exif_summary(jpg)} + jgrid, jsize = board(jpg) + out["kind"] = "board" if jgrid else "scene" + if jgrid: + out["straight_jpeg"] = straightness(jgrid) + for tag, path in (("on", on), ("off", off)): + if jgrid: + grid, size = board(path) + if not grid: + continue + k = jsize[0] / size[0] + grid = {key: p * k for key, p in grid.items()} + out["straight_" + tag] = straightness(grid) + s, d = match_boards(grid, (size[0] * k, size[1] * k), jgrid, jsize) + else: + s, d = sift_pairs(path, jpg) + a = agreement(s, d, jsize) if s is not None else None + if a: + out["vs_jpeg_" + tag] = a + if "vs_jpeg_on" in out and "vs_jpeg_off" in out and out["kind"] == "board": + out["fraction"] = correction_fraction(out["vs_jpeg_on"], out["vs_jpeg_off"], jsize) + for tag in ("on", "off"): + out.get("vs_jpeg_" + tag, {}).pop("pairs", None) + out["jpeg_width"] = jsize[0] + return out + + +def show(o): + """Print one file's measurements.""" + k = REPORT_WIDTH / o["jpeg_width"] + print(f"\n{o['file']} {o['shot']} [{o['kind']}]") + for tag, label in (("on", "LightCraft corrected"), ("off", "LightCraft uncorrected")): + a = o.get("vs_jpeg_" + tag) + if a: + print(f" {label:24s} vs camera JPEG: median {a['median']:.2f} px, p95 {a['p95']:.2f}, max {a['max']:.2f}" + f" (@{REPORT_WIDTH}: {a['median'] * k:.2f} / {a['p95'] * k:.2f}) n={a['n']} reach r={a['max_r']:.2f}") + print(" by radius: " + " ".join( + f"{b['r']}: {b['median']:.2f} ({b['radial']:+.2f})" for b in a["bins"] if b["n"])) + for tag in ("jpeg", "on", "off"): + st = o.get("straight_" + tag) + if st: + print(f" straightness {tag:4s}: worst line {st['max']:.2f} px, median line {st['median']:.2f} px ({st['lines']} lines)") + if o.get("fraction") is not None: + print(f" camera correction / LightCraft correction: {o['fraction']:.3f} (1 = same amount)") + + +def main(): + """Measure every ARW with a camera JPEG in the given folders and print (and optionally save) the results.""" + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--cli", required=True) + ap.add_argument("--work", required=True) + ap.add_argument("--json") + ap.add_argument("dirs", nargs="+") + args = ap.parse_args() + os.makedirs(args.work, exist_ok=True) + arws = sorted(os.path.join(d, f) for d in args.dirs for f in os.listdir(d) if f.lower().endswith(".arw")) + results = [] + for arw in arws: + try: + o = measure(args.cli, args.work, arw) + except Exception as e: # keep going: one bad file must not stop the batch + print(f"\n{arw}: {e}", file=sys.stderr) + continue + if o: + show(o) + results.append(o) + if args.json: + with open(args.json, "w") as f: + json.dump(results, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/tools/spectral_camera_table.py b/tools/spectral_camera_table.py index d936983b47..f77d25ecae 100644 --- a/tools/spectral_camera_table.py +++ b/tools/spectral_camera_table.py @@ -129,6 +129,7 @@ def main(root, out): print(f"{f}: training dE76 A {e1:.3f}, D65 {e2:.3f}", file=sys.stderr) rows.append( f' Camera {{\n make: "{rust_lit(header["manufacturer"])}",\n model: "{rust_lit(header["model"])}",\n' + " illuminant: [17, 21],\n" f" color_matrix: [{mat(cm1)}, {mat(cm2)}],\n forward_matrix: [{mat(fm1)}, {mat(fm2)}],\n }}," ) aliases = json.load(open(os.path.join(root, "data/aliases.json")))["data"]["camera"]["model"] diff --git a/tools/test_light_v3_constants.py b/tools/test_light_v3_constants.py new file mode 100644 index 0000000000..fe3f99ca57 --- /dev/null +++ b/tools/test_light_v3_constants.py @@ -0,0 +1,69 @@ +"""Synthetic publication checks. Run with python3 -m unittest discover -s tools.""" + +import contextlib +import io +import json +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace + +import light_v3_constants as constants + + +class SanitizeTests(unittest.TestCase): + def test_counts_distinct_photos_for_each_group_and_band(self): + fit = json.loads((constants.FITS / "contrast.json").read_text()) + # Three repeated pairs from one photo must not qualify as three photos. + def row(photo, amount, bands): + return dict(photo=photo, a_tgt=amount, a_ref=0, long_edge=800, + encoded_error=0.25, cells={b: {"error": 0.5} for b in bands}) + + fit["check"] = [row("synthetic-a", 20, constants.BANDS) for _ in range(3)] + fit["check"] += [row(p, 40, constants.BANDS) for p in ("synthetic-a", "synthetic-b")] + fit["check"] += [row(p, 60, constants.BANDS[:2]) for p in ("synthetic-a", "synthetic-b", "synthetic-c")] + fit["check"] += [row("synthetic-a", 60, constants.BANDS) for _ in range(3)] + fit["check"] += [row("synthetic-b", 60, constants.BANDS[:3])] + fit["tune"] = fit["check"] + with tempfile.TemporaryDirectory() as temp: + source, dest = Path(temp) / "synthetic.json", Path(temp) / "public.json" + source.write_text(json.dumps(fit)) + with contextlib.redirect_stdout(io.StringIO()): + constants.sanitize(SimpleNamespace(fit=source, slider="contrast", o=dest)) + public = json.loads(dest.read_text()) + self.assertEqual(public["params"], fit["params"]) + self.assertEqual(public["check_photos"], 3) + for split in ("tune", "check"): + rows = public["median_errors"][split] + self.assertEqual([r["amount"] for r in rows], [60]) + self.assertEqual(rows[0]["photos"], 3) + self.assertEqual(set(rows[0]["band_error"]), set(constants.BANDS[:2])) + self.assertEqual(rows[0]["band_photos"], {b: 3 for b in constants.BANDS[:2]}) + + def test_single_photo_fit_has_no_error_aggregates(self): + fit = json.loads((constants.FITS / "contrast.json").read_text()) + fit["tune"] = [dict(photo="synthetic-a", a_tgt=20, a_ref=0, long_edge=800, + encoded_error=0.25, cells={})] + fit["check"] = [] + with tempfile.TemporaryDirectory() as temp: + source, dest = Path(temp) / "synthetic.json", Path(temp) / "public.json" + source.write_text(json.dumps(fit)) + with contextlib.redirect_stdout(io.StringIO()): + constants.sanitize(SimpleNamespace(fit=source, slider="contrast", o=dest)) + public = json.loads(dest.read_text()) + self.assertEqual(public["median_errors"], {"tune": [], "check": []}) + self.assertIsNone(public["cost"]) + + def test_committed_aggregates_have_at_least_three_photos(self): + for path in sorted(constants.FITS.glob("*.json")): + fit = json.loads(path.read_text()) + for rows in fit["median_errors"].values(): + for row in rows: + with self.subTest(fit=path.name, amount=row["amount"], edge=row["long_edge"]): + self.assertGreaterEqual(row.get("photos", row["pairs"]), 3) + self.assertEqual(set(row["band_error"]), set(row.get("band_photos", {}))) + self.assertTrue(all(n >= 3 for n in row.get("band_photos", {}).values())) + + +if __name__ == "__main__": + unittest.main() diff --git a/xtask/src/ci_report.rs b/xtask/src/ci_report.rs index 8be686ef11..ec5da20f3b 100644 --- a/xtask/src/ci_report.rs +++ b/xtask/src/ci_report.rs @@ -505,7 +505,8 @@ mod tests { fn tmp(name: &str) -> PathBuf { let d = std::env::temp_dir().join(format!("xtask-ci-report-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).unwrap(); + // exclusive: a directory planted at this predictable name fails the test instead of receiving its files + std::fs::create_dir(&d).unwrap(); d } diff --git a/xtask/src/corpus.rs b/xtask/src/corpus.rs index 434d48b279..815da66b54 100644 --- a/xtask/src/corpus.rs +++ b/xtask/src/corpus.rs @@ -1,6 +1,39 @@ use super::raw_samples::RAW_SAMPLES; use super::{Command, Path, root, run}; +/// A Nikon D750 ColorChecker set released under CC0 by dieli (github.com/dieli/d750-lightcraft-colorchecker), +/// pinned to one commit: a matrix-only dual-illuminant DNG camera profile (Cool White Fluorescent + D55) +/// made with Calibrite PROFILER from the two chart shots, the chart NEFs, and Lightroom Classic 15.6's +/// renders of them with that profile. Downloaded into `corpus/d750-colorchecker/` (the repository's own +/// layout) for the `.dcp` import tests; never committed. Fields: path, URL, SHA-256. +const D750_COLORCHECKER: &[(&str, &str, &str)] = &[ + ( + "raw/chart-daylight_flash.NEF", + "https://raw.githubusercontent.com/dieli/d750-lightcraft-colorchecker/f37f4054b62fa7fb02f35ab8b7ce508f2196459d/raw/chart-daylight_flash.NEF", + "ebb6768ca1a82e3dc8b455e03842245a8e0d067045f720fbf2dcf20b90f06624", + ), + ( + "raw/chart-indoor.NEF", + "https://raw.githubusercontent.com/dieli/d750-lightcraft-colorchecker/f37f4054b62fa7fb02f35ab8b7ce508f2196459d/raw/chart-indoor.NEF", + "d687c3efd25697208bdd1015856f30d00f1c4d768237c936640b61997b6d713a", + ), + ( + "profiles/20261016_NikonD750_DualIllumination_ColorCheckerPassport.dcp", + "https://raw.githubusercontent.com/dieli/d750-lightcraft-colorchecker/f37f4054b62fa7fb02f35ab8b7ce508f2196459d/profiles/20261016_NikonD750_DualIllumination_ColorCheckerPassport.dcp", + "eb7e9465a42099628ffe61838ae4626a4bb51982492975076808c54ebf8d3d78", + ), + ( + "images/daylight_flash-lightroom.jpg", + "https://raw.githubusercontent.com/dieli/d750-lightcraft-colorchecker/f37f4054b62fa7fb02f35ab8b7ce508f2196459d/images/daylight_flash-lightroom.jpg", + "725ee289efb6edcbbb792a41df5c74df5c865d9e31e55811453a43ddfc5c7bb0", + ), + ( + "images/indoor-lightroom.jpg", + "https://raw.githubusercontent.com/dieli/d750-lightcraft-colorchecker/f37f4054b62fa7fb02f35ab8b7ce508f2196459d/images/indoor-lightroom.jpg", + "213580e9b0d8e2a76c29aa2eaa9884b724e9b605df2b723ac51af975ec84c414", + ), +]; + pub(crate) fn cmd_corpus(download: bool) -> Result<(), String> { let corpus = root().join("corpus"); println!( @@ -9,29 +42,16 @@ Tests that use a corpus skip cleanly when it is absent. corpus/raw/ raw.pixls.us samples (CC0) — lightcraft-raw decodes every file. corpus/images/ CC0 / public-domain JPEG/PNG/TIFF/HEIC samples (optional) + corpus/d750-colorchecker/ Nikon D750 ColorChecker set (CC0, dieli): a .dcp, chart NEFs, Lightroom renders ", corpus.display() ); if !download { return Ok(()); } - let dest = corpus.join("raw"); - std::fs::create_dir_all(&dest).map_err(|e| format!("create {}: {e}", dest.display()))?; let mut bad = Vec::new(); - for (name, url, sha256) in RAW_SAMPLES { - let out = dest.join(name); - if !out.exists() { - let mut curl = Command::new("curl"); - curl.args(["-fsSL", "-o"]).arg(&out).arg(url); - run(curl, &format!("curl {url}"))?; - } - let actual = file_sha256(&out)?; - if actual != *sha256 { - // delete it, so the next run downloads it again instead of trusting it - std::fs::remove_file(&out).map_err(|e| format!("remove {}: {e}", out.display()))?; - bad.push(format!("{name}: sha256 is {actual}, expected {sha256} (file deleted; source {url})")); - } - } + fetch_pinned(&corpus.join("raw"), RAW_SAMPLES, &mut bad)?; + fetch_pinned(&corpus.join("d750-colorchecker"), D750_COLORCHECKER, &mut bad)?; if bad.is_empty() { return Ok(()); } @@ -46,6 +66,29 @@ Tests that use a corpus skip cleanly when it is absent. )) } +/// Download each `(path, url, sha256)` of `files` under `dest` unless present, and check its SHA-256 +/// (a mismatch is deleted, so the next run downloads it again, and reported in `bad`). +fn fetch_pinned(dest: &Path, files: &[(&str, &str, &str)], bad: &mut Vec) -> Result<(), String> { + for (name, url, sha256) in files { + let out = dest.join(name); + if let Some(dir) = out.parent() { + std::fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?; + } + if !out.exists() { + let mut curl = Command::new("curl"); + curl.args(["-fsSL", "-o"]).arg(&out).arg(url); + run(curl, &format!("curl {url}"))?; + } + let actual = file_sha256(&out)?; + if actual != *sha256 { + // delete it, so the next run downloads it again instead of trusting it + std::fs::remove_file(&out).map_err(|e| format!("remove {}: {e}", out.display()))?; + bad.push(format!("{name}: sha256 is {actual}, expected {sha256} (file deleted; source {url})")); + } + } + Ok(()) +} + fn file_sha256(path: &Path) -> Result { use sha2::{Digest, Sha256}; let mut file = std::fs::File::open(path).map_err(|e| format!("open {}: {e}", path.display()))?; @@ -56,16 +99,25 @@ fn file_sha256(path: &Path) -> Result { #[cfg(test)] mod corpus_tests { - use super::RAW_SAMPLES; + use super::{D750_COLORCHECKER, RAW_SAMPLES}; #[test] fn every_sample_has_a_unique_name_and_a_sha256() { - let mut names: Vec<_> = RAW_SAMPLES.iter().map(|s| s.0).collect(); - names.sort_unstable(); - names.dedup(); - assert_eq!(names.len(), RAW_SAMPLES.len(), "duplicate file name"); - for (name, _, sha256) in RAW_SAMPLES { - assert!(sha256.len() == 64 && sha256.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')), "{name}: not a lowercase sha256"); + for set in [RAW_SAMPLES, D750_COLORCHECKER] { + let mut names: Vec<_> = set.iter().map(|s| s.0).collect(); + names.sort_unstable(); + names.dedup(); + assert_eq!(names.len(), set.len(), "duplicate file name"); + for (name, _, sha256) in set { + assert!(sha256.len() == 64 && sha256.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')), "{name}: not a lowercase sha256"); + } + } + } + + #[test] + fn the_d750_set_is_pinned_to_one_commit() { + for (name, url, _) in D750_COLORCHECKER { + assert!(url.contains("/f37f4054b62fa7fb02f35ab8b7ce508f2196459d/") && url.ends_with(name), "{name}: {url}"); } } } diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index 2a881155bc..934135a020 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -47,6 +47,7 @@ pub const TABLE: &[(&str, Class)] = &[ ("codecs", Class::Layer(1)), ("meta", Class::Layer(1)), ("develop", Class::Layer(1)), + ("film", Class::Layer(1)), ("lensdb", Class::Layer(2)), ("inpaint", Class::Layer(1)), ("faces", Class::Layer(1)), diff --git a/xtask/src/raw_samples.rs b/xtask/src/raw_samples.rs index c9cbe7e42b..ae386352d6 100644 --- a/xtask/src/raw_samples.rs +++ b/xtask/src/raw_samples.rs @@ -926,6 +926,63 @@ pub(crate) const RAW_SAMPLES: &[(&str, &str, &str)] = &[ "https://raw.pixls.us/getfile.php/4204/nice/Leica%20-%20D-Lux%207%20-%204:3.RWL", "4f6db6492da83f7f2a5012591e370557249d1ed44d4c948784016605b799327c", ), + // Canon CRW (CIFF): the clean-room decode's verification corpus (craft-libs crates/crw/clean-room/03-verification.md); + // the PowerShot G5 is the documented anomaly the decoder refuses (embedded JPEG preview) + ( + "crw-canon-eos-d30.crw", + "https://raw.pixls.us/getfile.php/1307/nice/Canon%20-%20EOS%20D30%20-%20RAW%20(3:2).CRW", + "4ee482f2b6f9f1a8d370703ea04e9f2abaa49356973a7f56b229af93a78e8a2e", + ), + ( + "crw-canon-eos-d60.crw", + "https://raw.pixls.us/getfile.php/2010/nice/Canon%20-%20EOS%20D60%20-%20RAW%20(3:2).CRW", + "2b98659ecff170af1dfe44f89b493139e75e995b2979686f6ff0847cfb56b97f", + ), + ( + "crw-canon-eos-10d-a.crw", + "https://raw.pixls.us/getfile.php/2027/nice/Canon%20-%20EOS%2010D%20-%20RAW%20(3:2).CRW", + "b0730eb3a67cc2281a32e0b2ee104199246928d954a68b7e5b72366514c73d02", + ), + ( + "crw-canon-eos-10d-b.crw", + "https://raw.pixls.us/getfile.php/3164/nice/Canon%20-%20EOS%2010D%20-%20RAW%20(3:2).crw", + "e879c94afdc64dabc88b01ce2d02628aa225259303ec71dd61f7fb0322bfea2d", + ), + ( + "crw-canon-eos-10d-c.crw", + "https://raw.pixls.us/getfile.php/3165/nice/Canon%20-%20EOS%2010D%20-%20RAW%20(3:2).crw", + "58144118854657df5cd2185df40fecf6b665fc6754fef0416c2f222b68b025c6", + ), + ( + "crw-canon-eos-300d-a.crw", + "https://raw.pixls.us/getfile.php/1983/nice/Canon%20-%20EOS%20300D%20-%20RAW%20(3:2).crw", + "47da16e1668af5500eea63cf42cf2992d9cb3d32180b8d786f17f1e2a57f39f4", + ), + ( + "crw-canon-eos-300d-b.crw", + "https://raw.pixls.us/getfile.php/3162/nice/Canon%20-%20EOS%20300D%20-%20RAW%20(3:2).CRW", + "9e7f62239fe728046af28d0d4a8a722d35d40146a79794a5bda1775306af4383", + ), + ( + "crw-canon-eos-digital-rebel.crw", + "https://raw.pixls.us/getfile.php/1308/nice/Canon%20-%20EOS%20Digital%20Rebel%20-%20RAW%20(3:2).CRW", + "d6a3131bfac390fde01b96882ec378211f04570c3252708b58f0d05b33a9fdfc", + ), + ( + "crw-canon-powershot-g1.crw", + "https://raw.pixls.us/getfile.php/2073/nice/Canon%20-%20PowerShot%20G1%20-%20RAW%20(4:3).crw", + "f39be5acf14057ce04527fd8d0574e57ec8ed5fed082d7bfaff763075a44ee8a", + ), + ( + "crw-canon-powershot-g5.crw", + "https://raw.pixls.us/getfile.php/1746/nice/Canon%20-%20PowerShot%20G5%20-%20RAW%20(4:3).CRW", + "bb084223d714871b99de4f549eaf00513e30a7080feeead700252c2008060196", + ), + ( + "crw-canon-powershot-g6.crw", + "https://raw.pixls.us/getfile.php/4226/nice/Canon%20-%20PowerShot%20G6%20-%20RAW%20(4:3).CRW", + "244378e1f5660b6cc6cefc93a75ed4928d0b28aa6304ff327b61c748538f4fef", + ), ( "mrw-minolta-dimage7hi-words16.mrw", "https://raw.pixls.us/data/Minolta/DiMAGE%207Hi/RAW_MINOLTA_DIMAGE_7HI.MRW",