diff --git a/AGENTS.md b/AGENTS.md index f10fedb20b..a1396fd0e3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,9 +38,10 @@ of it. "unsupported" error or is disabled. Sole exception: a provably infallible literal, as `#[allow(clippy::expect_used)]` + `.expect("why it can't fail")`. - **`unsafe` lives only in `crates/sysmem`** (one FFI call, `malloc_zone_pressure_relief`, that returns freed - allocator pages to macOS after raw decodes). Every other production crate root has `#![forbid(unsafe_code)]`. A new - unsafe need goes in an isolated, well-tested helper crate like it: `// SAFETY:` on every block, a safe API, a safe - fallback where possible, and a line here naming it. + allocator pages to macOS after raw decodes) **and `crates/wincolor`** (Win32 calls that read the colour profile + Windows assigns to the monitor showing the window, and whether Windows colour-manages that monitor itself). Every + other production crate root has `#![forbid(unsafe_code)]`. A new unsafe need goes in an isolated, well-tested helper + crate like them: `// SAFETY:` on every block, a safe API, a safe fallback where possible, and a line here naming it. - **Input-derived numbers are hostile:** `get()` instead of `[i]`/`[a..b]` for offsets from files, users, agents or arithmetic on them; checked/saturating math for lengths, offsets and counts; no division by zero, NaN/inf or negative casts to `usize`; cap allocations sized by input; slice strings only at char boundaries. @@ -123,6 +124,12 @@ of it. with `/usr/bin/time`. Record numbers in `plan/STATUS.md` → Metrics. Budgets: slider update ≤ 16 ms (draft) / loupe ≤ 60 ms on ~2.5 MP; export ≤ 1 s per 24 MP JPEG. - Never commit media: test images are procedural (`lightcraft-scenes`) or CC0 downloads in the gitignored `corpus/`. +- **Flaky tests:** a test that fails, then passes on a rerun of the same commit, is flaky. Don't rerun until it + passes and move on: open an issue with the failing log, and if it failed on two unrelated PRs, quarantine it with + `#[ignore = "flaky: #"]` (a doctest: an `ignore` code fence and a comment naming the issue) in a PR of its + own until the issue is fixed. Never quarantine a test that fails every time; fix the code or the test. A test that + hangs is a failure too: under `cargo test`, libtest's "has been running for over 60 seconds" line names it; under + nextest (`LIGHTCRAFT_NEXTEST=1`), its `SLOW` lines do. - A test that can't run here (no GPU, corpus file, craft-fonts face, model) calls `lightcraft_testkit::skip!(Gpu, "why")` before it returns, not a bare `eprintln!`. `cargo xtask ci` then lists the skips and the machine's GPU adapters and data, and writes `target/ci/report.json` and `target/ci/summary.md` (Markdown for a PR). diff --git a/CLAUDE.md b/CLAUDE.md index 0597cbf465..209c73159f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -39,9 +39,10 @@ of it. "unsupported" error or is disabled. Sole exception: a provably infallible literal, as `#[allow(clippy::expect_used)]` + `.expect("why it can't fail")`. - **`unsafe` lives only in `crates/sysmem`** (one FFI call, `malloc_zone_pressure_relief`, that returns freed - allocator pages to macOS after raw decodes). Every other production crate root has `#![forbid(unsafe_code)]`. A new - unsafe need goes in an isolated, well-tested helper crate like it: `// SAFETY:` on every block, a safe API, a safe - fallback where possible, and a line here naming it. + allocator pages to macOS after raw decodes) **and `crates/wincolor`** (Win32 calls that read the colour profile + Windows assigns to the monitor showing the window, and whether Windows colour-manages that monitor itself). Every + other production crate root has `#![forbid(unsafe_code)]`. A new unsafe need goes in an isolated, well-tested helper + crate like them: `// SAFETY:` on every block, a safe API, a safe fallback where possible, and a line here naming it. - **Input-derived numbers are hostile:** `get()` instead of `[i]`/`[a..b]` for offsets from files, users, agents or arithmetic on them; checked/saturating math for lengths, offsets and counts; no division by zero, NaN/inf or negative casts to `usize`; cap allocations sized by input; slice strings only at char boundaries. @@ -137,6 +138,12 @@ of it. with `/usr/bin/time`. Record numbers in `plan/STATUS.md` → Metrics. Budgets: slider update ≤ 16 ms (draft) / loupe ≤ 60 ms on ~2.5 MP; export ≤ 1 s per 24 MP JPEG. - Never commit media: test images are procedural (`lightcraft-scenes`) or CC0 downloads in the gitignored `corpus/`. +- **Flaky tests:** a test that fails, then passes on a rerun of the same commit, is flaky. Don't rerun until it + passes and move on: open an issue with the failing log, and if it failed on two unrelated PRs, quarantine it with + `#[ignore = "flaky: #"]` (a doctest: an `ignore` code fence and a comment naming the issue) in a PR of its + own until the issue is fixed. Never quarantine a test that fails every time; fix the code or the test. A test that + hangs is a failure too: under `cargo test`, libtest's "has been running for over 60 seconds" line names it; under + nextest (`LIGHTCRAFT_NEXTEST=1`), its `SLOW` lines do. - A test that can't run here (no GPU, corpus file, craft-fonts face, model) calls `lightcraft_testkit::skip!(Gpu, "why")` before it returns, not a bare `eprintln!`. `cargo xtask ci` then lists the skips and the machine's GPU adapters and data, and writes `target/ci/report.json` and `target/ci/summary.md` (Markdown for a PR). diff --git a/Cargo.lock b/Cargo.lock index 1d0bb2bdc2..345f89d488 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2139,6 +2139,16 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" +[[package]] +name = "fs4" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5" +dependencies = [ + "rustix 1.1.5", + "windows-sys 0.61.2", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -3589,12 +3599,14 @@ dependencies = [ "lightcraft-sysmem", "lightcraft-testkit", "lightcraft-ui-egui", + "lightcraft-wincolor", "log", "muda", "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "pollster 1.0.1", + "raw-window-handle", "rfd", "serde_json", "winit", @@ -3732,6 +3744,7 @@ dependencies = [ "ab_glyph", "chrono", "craft-docpath", + "fs4", "harfrust 0.13.3", "jxl-oxide", "libc", @@ -4080,6 +4093,14 @@ dependencies = [ "web-sys", ] +[[package]] +name = "lightcraft-wincolor" +version = "0.18.0" +dependencies = [ + "lightcraft-testkit", + "windows-sys 0.61.2", +] + [[package]] name = "linebender_resource_handle" version = "0.1.1" diff --git a/Cargo.toml b/Cargo.toml index 061507c999..ac515d7aaa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ lightcraft-denoise = { path = "crates/denoise", default-features = false } lightcraft-geom = { path = "crates/geom" } lightcraft-faces = { path = "crates/faces" } lightcraft-sysmem = { path = "crates/sysmem" } +lightcraft-wincolor = { path = "crates/wincolor" } lightcraft-color = { path = "crates/color" } lightcraft-raster = { path = "crates/raster" } lightcraft-tiff = { path = "crates/tiff" } @@ -58,6 +59,8 @@ log = "0.4" # All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md). chrono = { version = "0.4.45", default-features = false, features = ["std"] } rayon = "1" +# free/total space of a drive (engine's low-disk alert); MIT OR Apache-2.0, pure Rust (rustix / windows-sys) +fs4 = { version = "1.1", default-features = false } winapi-util = "0.1" # lightcraft-catalog reads a file's volume serial number and file index with it on Windows proptest = "1" bytemuck = { version = "1", features = ["derive"] } diff --git a/apps/lightcraft-cli/src/bench_cull.rs b/apps/lightcraft-cli/src/bench_cull.rs new file mode 100644 index 0000000000..9107a94553 --- /dev/null +++ b/apps/lightcraft-cli/src/bench_cull.rs @@ -0,0 +1,585 @@ +//! `lightcraft-cli bench-cull FOLDER`: time what culling a shoot costs, headless, on real files. +//! +//! What a wedding photographer does most is open a folder of a few thousand raws, look at each +//! one, rate it and move on. This times the engine side of each step on the files themselves (the +//! desktop app's own frame timings come from `ui.inspect` → `perf.loupeSteps`, see +//! `tools/cull-bench.py`): +//! +//! - browse: reading the folder into the Local view (`library.browse`, the whole folder); +//! - grid thumbnails: the camera JPEG at 512 px for the first screen, on as many threads as the +//! app renders with; +//! - camera preview at loupe sizes (1280, 2560) and at full size (the 100 % view), one at a time; +//! - LightCraft's render of the loupe (2560 px) from a cold source; +//! - rating: `photo.rate` on many photos in a row, journal included; +//! - import: adding N files in place to a fresh library, and copying M of them into it (`--n 0`: +//! no import). +//! +//! `--files K` reads only the first K files (by name) of the folder, as browsing reads them: a +//! sample of a folder on a network share, where reading thousands of raws takes hours. +//! +//! Each number is printed as `name: X ms wall` (median, with p95 and n), the format +//! `cargo xtask bench` parses, and the lot as one JSON object with `--json FILE`. Nothing is +//! written next to the photos: every library is made in a new folder of the run's own under +//! `--work` (default: a folder in the system temp directory; nothing already there is deleted), +//! XMP auto-write stays off, and the source folder is only read. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Instant; + +use lightcraft_engine::Session; +use lightcraft_engine::catalog::PhotoId; +use serde_json::{Value, json}; + +const USAGE: &str = "lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]"; + +/// Threads the app renders thumbnails with (`Renderer::default`: cores − 1, at most 6). +fn render_threads() -> usize { + std::thread::available_parallelism().map(|n| n.get().saturating_sub(1)).unwrap_or(2).clamp(2, 6) +} + +/// Median, p95 and count of `ms` (milliseconds). +fn stats(ms: &[f64]) -> Value { + if ms.is_empty() { + return Value::Null; + } + let mut v = ms.to_vec(); + v.sort_by(f64::total_cmp); + let at = |q: f64| v.get(((v.len() - 1) as f64 * q).round() as usize).copied().unwrap_or(0.0); + json!({"p50": round(at(0.5)), "p95": round(at(0.95)), "max": round(at(1.0)), "n": v.len()}) +} + +fn round(x: f64) -> f64 { + (x * 10.0).round() / 10.0 +} + +fn ms_since(t: Instant) -> f64 { + t.elapsed().as_secs_f64() * 1000.0 +} + +/// Print one result line the way `xtask bench` parses it (`name: X ms wall`). +fn line(name: &str, s: &Value) { + if let Some(p50) = s.get("p50").and_then(Value::as_f64) { + println!("{name}: {p50:.1} ms wall (p95 {} ms, n {})", s["p95"], s["n"]); + } +} + +/// A new, empty folder `name` in this run's own folder; never deletes anything already there. +fn fresh_dir(root: &Path, name: &str) -> Result { + let d = root.join(name); + std::fs::create_dir(&d).map_err(|e| format!("{}: {e}", d.display()))?; + Ok(d) +} + +/// A folder of this run's own under `work`, which must not exist yet: a run never deletes or +/// reuses what is already under `--work`. +fn run_dir(work: &Path) -> Result { + std::fs::create_dir_all(work).map_err(|e| format!("{}: {e}", work.display()))?; + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + static RUNS: AtomicUsize = AtomicUsize::new(0); + let n = RUNS.fetch_add(1, Ordering::Relaxed); + let d = work.join(format!("bench-cull-run-{}-{stamp}-{n}", std::process::id())); + std::fs::create_dir(&d).map_err(|e| format!("{}: {e}", d.display()))?; + Ok(d) +} + +/// `take` items of `v` after the first `skip` (photos the stages before have read, so cold in the +/// file cache), or, when `v` has no more than `skip`, its first `take`: a small folder is measured +/// on photos already read rather than not at all. +fn sample_after(v: &[T], skip: usize, take: usize) -> &[T] { + let from = if v.len() > skip { skip } else { 0 }; + let rest = v.get(from..).unwrap_or_default(); + rest.get(..take.min(rest.len())).unwrap_or_default() +} + +/// Whether `path` names a file in `folder` (the source folder, which a run only reads), checked +/// twice: where its own entry sits (the folder holding it, the final link not followed: writing the +/// results replaces that entry, so a link to a file elsewhere that sits in the source folder, maybe +/// standing for a photo, would be replaced; CodeRabbit on #3080), and where it resolves to: a file +/// that is there by itself (a link to a photo there is the photo), a link that points nowhere yet +/// by where writing through it would create the file, and anything else by its nearest folder that +/// exists (a `--work` folder may not be there yet). +fn inside_source(path: &Path, folder: &Path) -> bool { + let Ok(folder) = std::fs::canonicalize(folder) else { return false }; + entry_inside(path, &folder) || resolves_inside(path, &folder, 0) +} + +/// Whether the folder holding `path`'s own entry (its nearest folder that exists, resolved) is in +/// `folder` (already resolved). The entry itself is not followed. +fn entry_inside(path: &Path, folder: &Path) -> bool { + let mut p = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")); + loop { + if let Ok(c) = std::fs::canonicalize(p) { + return c.starts_with(folder); + } + match p.parent() { + Some(up) if !up.as_os_str().is_empty() => p = up, + Some(_) => p = Path::new("."), + None => return false, + } + } +} + +/// [`inside_source`] for a `folder` already resolved; `hops`: links followed so far (a loop of +/// links counts as inside: refused). +fn resolves_inside(path: &Path, folder: &Path, hops: u32) -> bool { + if let Ok(c) = std::fs::canonicalize(path) { + return c.starts_with(folder); + } + if let Ok(target) = std::fs::read_link(path) { + if hops >= 40 { + return true; + } + let target = path.parent().map_or_else(|| target.clone(), |dir| dir.join(&target)); + return resolves_inside(&target, folder, hops + 1); + } + entry_inside(path, folder) +} + +/// Refuse `--json` or `--work` in the folder being measured: nothing is written next to the photos, +/// the results and the run's libraries included. Checked before anything is made. +fn check_outputs(folder: &Path, json: Option<&Path>, work: &Path) -> Result<(), String> { + // a `..` after a folder not made yet can't be resolved now, and the run makes that folder: + // `--json NEW/../FOLDER/r.json` would pass the checks below and land in the source folder + // (CodeRabbit on #3544) + for (name, p) in [("--json", json), ("--work", Some(work))] { + if let Some(p) = p.filter(|p| p.components().any(|c| c == std::path::Component::ParentDir)) { + return Err(format!("{}: {name} must not contain \"..\"; give the folder without it", p.display())); + } + } + if let Some(j) = json.filter(|j| inside_source(j, folder)) { + return Err(format!("{}: --json must not be in the folder being measured", j.display())); + } + if inside_source(&work.join("run"), folder) { + return Err(format!("{}: --work must not be in the folder being measured", work.display())); + } + Ok(()) +} + +fn library(dir: &Path) -> Result { + let mut s = Session::new().with_fs().with_system_clock(); + s.open_library(dir, false).map_err(|e| format!("{}: {e}", dir.display()))?; + // nothing is ever written next to the photos + s.execute("library.xmpPreferences", &json!({"autoWrite": false})).map_err(|e| e.to_string())?; + Ok(s) +} + +pub fn run(args: &[String]) -> Result<(), String> { + let mut folder = None; + let mut n = 2000usize; + let mut copy = 200usize; + let mut work = None; + let mut json_out = None; + let mut files = None; + let mut i = 0; + while i < args.len() { + let value = |i: usize| args.get(i + 1).cloned().ok_or_else(|| format!("{} needs a value\n{USAGE}", args[i])); + match args[i].as_str() { + "--n" => { + n = value(i)?.parse().map_err(|_| "--n needs a number".to_string())?; + i += 1; + } + "--copy" => { + copy = value(i)?.parse().map_err(|_| "--copy needs a number".to_string())?; + i += 1; + } + "--files" => { + files = Some(value(i)?.parse::().map_err(|_| "--files needs a number".to_string())?); + i += 1; + } + "--work" => { + work = Some(PathBuf::from(value(i)?)); + i += 1; + } + "--json" => { + json_out = Some(PathBuf::from(value(i)?)); + i += 1; + } + "-h" | "--help" => { + println!("{USAGE}"); + return Ok(()); + } + a if a.starts_with("--") => return Err(format!("unknown option {a}\n{USAGE}")), + // (a second folder would replace the first and be timed in its place: CodeRabbit on #3583) + a if folder.is_some() => return Err(format!("{a}: one FOLDER only\n{USAGE}")), + a => folder = Some(PathBuf::from(a)), + } + i += 1; + } + let folder = folder.ok_or_else(|| USAGE.to_string())?; + if !folder.is_dir() { + return Err(format!("{}: not a folder", folder.display())); + } + let work = work.unwrap_or_else(|| std::env::temp_dir().join(format!("lightcraft-bench-cull-{}", std::process::id()))); + check_outputs(&folder, json_out.as_deref(), &work)?; + let work = run_dir(&work)?; + let mut out = json!({"folder": folder.display().to_string(), "threads": render_threads()}); + + // --- browse: the whole folder into the Local view ------------------------------------------- + let mut s = library(&fresh_dir(&work, "lib-browse")?)?; + // `--files K`: only the first K files by name, read as browsing reads them (a sample of a slow + // network folder) + let t = Instant::now(); + let (photos, ids): (u64, Vec) = match files { + None => { + let r = s.execute("library.browse", &json!({"path": folder.display().to_string()})).map_err(|e| e.to_string())?; + (r["photos"].as_u64().unwrap_or(0), s.visible_cloned()) + } + Some(k) => { + let mut list: Vec = std::fs::read_dir(&folder) + .map_err(|e| format!("{}: {e}", folder.display()))? + .flatten() + .map(|e| e.path()) + .filter(|p| p.is_file() && lightcraft_engine::import::is_supported(p)) + .map(|p| p.display().to_string()) + .collect(); + list.sort(); + list.truncate(k); + let r = s.execute("library.import", &json!({"paths": list, "mode": "add", "local": true})).map_err(|e| e.to_string())?; + let ids: Vec = r["imported"].as_array().into_iter().flatten().filter_map(Value::as_u64).map(PhotoId).collect(); + (ids.len() as u64, ids) + } + }; + let browse_ms = ms_since(t); + let what = if files.is_some() { "first files" } else { "whole folder" }; + println!("browse {photos} photos ({what}): {browse_ms:.1} ms wall"); + out["browse"] = json!({"ms": round(browse_ms), "photos": photos, "perPhotoMs": round(browse_ms / photos.max(1) as f64)}); + let paths: Vec = ids + .iter() + .filter_map(|id| match &s.catalog.photo(*id)?.source { + lightcraft_engine::catalog::Source::File { path } => Some(path.clone()), + _ => None, + }) + .collect(); + if paths.is_empty() { + return Err(format!("{}: no photos", folder.display())); + } + let loader = s.media.preview_loader.clone().ok_or("no preview loader")?; + + // --- grid thumbnails: the first screen, in parallel ------------------------------------------ + let screen: Vec = paths.iter().take(48).cloned().collect(); + let next = Arc::new(AtomicUsize::new(0)); + let t = Instant::now(); + let per: Vec<(f64, f64)> = std::thread::scope(|sc| { + let workers: Vec<_> = (0..render_threads()) + .map(|_| { + let (next, loader, screen) = (next.clone(), loader.clone(), &screen); + sc.spawn(move || { + let mut done = Vec::new(); + while let Some(p) = screen.get(next.fetch_add(1, Ordering::Relaxed)) { + let a = Instant::now(); + let _ = loader(p, 512); + done.push((ms_since(a), ms_since(t))); + } + done + }) + }) + .collect(); + workers.into_iter().flat_map(|w| w.join().unwrap_or_default()).collect() + }); + let first = per.iter().map(|p| p.1).fold(f64::INFINITY, f64::min); + let all = per.iter().map(|p| p.1).fold(0.0, f64::max); + let each = stats(&per.iter().map(|p| p.0).collect::>()); + println!("grid: first thumbnail: {first:.1} ms wall"); + println!("grid: {} thumbnails: {all:.1} ms wall", per.len()); + line("grid: one 512 px thumbnail", &each); + out["thumbs"] = json!({"firstMs": round(first), "allMs": round(all), "count": per.len(), "each": each}); + + // --- camera previews at loupe sizes, one at a time (what a step costs without look-ahead) ----- + let sample = sample_after(&paths, 48, 20); + for edge in [1280usize, 2560, usize::MAX] { + let ms: Vec = sample + .iter() + .map(|p| { + let a = Instant::now(); + let _ = loader(p, edge); + ms_since(a) + }) + .collect(); + let name = if edge == usize::MAX { "camera preview full size (100 %)".to_string() } else { format!("camera preview {edge} px") }; + let st = stats(&ms); + line(&name, &st); + out[if edge == usize::MAX { "cameraFull".to_string() } else { format!("camera{edge}") }] = st; + } + + // --- LightCraft's loupe render (2560 px) from a cold source -------------------------------- + let ms: Vec = sample_after(&ids, 80, 5) + .iter() + .filter_map(|id| { + let job = s.loupe_job(*id, 2560, 1708, true)?; + let a = Instant::now(); + let r = job.run(); + let t = ms_since(a); + r.rendered.is_ok().then_some(t) + }) + .collect(); + let st = stats(&ms); + line("loupe render 2560 px (cold)", &st); + out["loupeRender"] = st; + + // --- rating: a culling pass of keypresses --------------------------------------------------- + let ms: Vec = ids + .iter() + .take(50) + .enumerate() + .filter_map(|(k, id)| { + // the key acts on the selected photo, as in the loupe + s.execute("library.select", &json!({"ids": [id.0], "active": id.0})).ok()?; + let a = Instant::now(); + s.execute("photo.rate", &json!({"rating": (k % 5) + 1})).ok()?; + Some(ms_since(a)) + }) + .collect(); + let st = stats(&ms); + line("rate one photo (journal written)", &st); + out["rate"] = st; + drop(s); + + // --- import: add in place, then copy ---------------------------------------------------------- + if n == 0 { + return finish(out, json_out); + } + let add: Vec = paths.iter().take(n).cloned().collect(); + let mut s = library(&fresh_dir(&work, "lib-add")?)?; + let t = Instant::now(); + let r = s.execute("library.import", &json!({"paths": add, "mode": "add"})).map_err(|e| e.to_string())?; + let add_ms = ms_since(t); + let added = r["imported"].as_array().map(Vec::len).unwrap_or(0); + println!("import {added} photos in place: {add_ms:.1} ms wall"); + out["importAdd"] = json!({"ms": round(add_ms), "photos": added, "perPhotoMs": round(add_ms / added.max(1) as f64)}); + drop(s); + if copy > 0 { + let some: Vec = paths.iter().take(copy).cloned().collect(); + let lib = fresh_dir(&work, "lib-copy")?; + let mut s = library(&lib)?; + let t = Instant::now(); + let r = s + .execute("library.import", &json!({"paths": some, "mode": "copy", "destination": lib.join("Originals").display().to_string()})) + .map_err(|e| e.to_string())?; + let copy_ms = ms_since(t); + let copied = r["imported"].as_array().map(Vec::len).unwrap_or(0); + println!("import {copied} photos by copying: {copy_ms:.1} ms wall"); + out["importCopy"] = json!({"ms": round(copy_ms), "photos": copied, "perPhotoMs": round(copy_ms / copied.max(1) as f64)}); + drop(s); + let _ = std::fs::remove_dir_all(&lib); + } + finish(out, json_out) +} + +fn finish(out: Value, json_out: Option) -> Result<(), String> { + if let Some(p) = json_out { + write_replacing(&p, serde_json::to_string_pretty(&out).unwrap_or_default().as_bytes())?; + } + println!("{}", serde_json::to_string(&out).unwrap_or_default()); + Ok(()) +} + +/// Write `bytes` to `path` through a new file next to it, renamed over `path`: an existing `path` +/// is replaced as a name, never written into. A hard link there shares its data with another file +/// (maybe a photo in the source folder, which [`inside_source`] can't tell), and writing into it +/// would overwrite that file too (CodeRabbit on #3077). The temporary file is removed on error. +fn write_replacing(path: &Path, bytes: &[u8]) -> Result<(), String> { + use std::io::Write; + let err = |e: std::io::Error| format!("{}: {e}", path.display()); + let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); + let name = path.file_name().ok_or_else(|| format!("{}: not a file name", path.display()))?; + static TEMPS: AtomicUsize = AtomicUsize::new(0); + let n = TEMPS.fetch_add(1, Ordering::Relaxed); + let mut tmp_name = std::ffi::OsString::from("."); + tmp_name.push(name); + tmp_name.push(format!(".{}-{n}.tmp", std::process::id())); + let tmp = dir.join(tmp_name); + let written = + std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp).and_then(|mut f| f.write_all(bytes).and_then(|()| f.sync_all())); + if let Err(e) = written.and_then(|()| std::fs::rename(&tmp, path)) { + let _ = std::fs::remove_file(&tmp); + return Err(err(e)); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_second_folder_is_an_error() { + let e = run(&["a".to_string(), "b".to_string()]).unwrap_err(); + assert!(e.starts_with("b: one FOLDER only"), "{e}"); + } + + /// `--work` may hold anything: a run makes a new folder of its own there and never deletes + /// what is already in it (it used to remove `lib-browse`, `lib-add` and `lib-copy` there). + #[test] + fn a_run_never_deletes_what_is_under_work() { + // a folder this test owns (made new), so the cleanup below removes nothing else + let work = run_dir(&std::env::temp_dir()).unwrap(); + let keep = work.join("lib-browse").join("keep.txt"); + std::fs::create_dir_all(keep.parent().unwrap()).unwrap(); + std::fs::write(&keep, b"mine").unwrap(); + let a = run_dir(&work).unwrap(); + let b = run_dir(&work).unwrap(); + assert_ne!(a, b); + fresh_dir(&a, "lib-browse").unwrap(); + assert!(fresh_dir(&a, "lib-browse").is_err(), "an existing folder is never reused"); + assert_eq!(std::fs::read(&keep).unwrap(), b"mine"); + let _ = std::fs::remove_dir_all(&work); + } + + /// A folder too small for the disjoint samples is measured on the photos it has (CodeRabbit on #3077). + #[test] + fn a_small_folder_is_sampled_from_its_start() { + let v: Vec = (0..100).collect(); + assert_eq!(sample_after(&v, 48, 20), &v[48..68]); + assert_eq!(sample_after(&v, 90, 20), &v[90..100]); + assert_eq!(sample_after(&v[..3], 48, 20), &v[..3]); + assert_eq!(sample_after(&v[..48], 48, 5), &v[..5]); + assert!(sample_after::(&[], 48, 20).is_empty()); + } + + /// A file link at `at` to `target`. + #[cfg(unix)] + fn link(target: &Path, at: &Path) -> std::io::Result<()> { + std::os::unix::fs::symlink(target, at) + } + + /// A file link at `at` to `target` (Windows: needs Developer Mode or the right to make links). + #[cfg(windows)] + fn link(target: &Path, at: &Path) -> std::io::Result<()> { + std::os::windows::fs::symlink_file(target, at) + } + + #[cfg(not(any(unix, windows)))] + fn link(_: &Path, _: &Path) -> std::io::Result<()> { + Err(std::io::Error::other("no file links here")) + } + + /// `--json` naming a link (made elsewhere) to a file in the source folder is refused: writing + /// the results would follow it and overwrite a photo (CodeRabbit on #3080). So is a link that + /// points to a file not made yet in the source folder, and a loop of links. + #[test] + fn a_json_link_into_the_source_folder_is_refused() { + let work = run_dir(&std::env::temp_dir()).unwrap(); + let src = fresh_dir(&work, "src").unwrap(); + let photo = src.join("a.jpg"); + std::fs::write(&photo, b"photo").unwrap(); + let to_photo = work.join("report.json"); + if let Err(e) = link(&photo, &to_photo) { + let _ = std::fs::remove_dir_all(&work); + lightcraft_testkit::skip!(System, "can't make a file link here ({e}); Windows needs Developer Mode"); + return; + } + assert!(inside_source(&to_photo, &src), "a link to a photo in the source folder"); + let e = check_outputs(&src, Some(&to_photo), &work.join("elsewhere")).unwrap_err(); + assert!(e.contains("--json"), "{e}"); + let to_new = work.join("new.json"); + link(&src.join("not-yet.json"), &to_new).unwrap(); + assert!(inside_source(&to_new, &src), "a link to a file not made yet in the source folder"); + let (x, y) = (work.join("x.json"), work.join("y.json")); + link(&y, &x).unwrap(); + link(&x, &y).unwrap(); + assert!(inside_source(&x, &src), "a loop of links"); + let to_elsewhere = work.join("fine.json"); + link(&work.join("out.json"), &to_elsewhere).unwrap(); + assert!(!inside_source(&to_elsewhere, &src), "a link to a file outside is fine"); + assert_eq!(std::fs::read(&photo).unwrap(), b"photo"); + let _ = std::fs::remove_dir_all(&work); + } + + /// `--json` naming a link that sits in the source folder and points to a file outside it is + /// refused: writing the results would replace the link itself, an entry of the source folder + /// (CodeRabbit on #3080). The link stays as it was. + #[test] + fn a_json_link_in_the_source_folder_to_a_file_outside_is_refused() { + let work = run_dir(&std::env::temp_dir()).unwrap(); + let src = fresh_dir(&work, "src").unwrap(); + let outside = work.join("out.json"); + std::fs::write(&outside, b"outside").unwrap(); + let in_src = src.join("a.jpg"); + if let Err(e) = link(&outside, &in_src) { + let _ = std::fs::remove_dir_all(&work); + lightcraft_testkit::skip!(System, "can't make a file link here ({e}); Windows needs Developer Mode"); + return; + } + assert!(inside_source(&in_src, &src), "a link in the source folder, wherever it points"); + let e = check_outputs(&src, Some(&in_src), &work.join("elsewhere")).unwrap_err(); + assert!(e.contains("--json"), "{e}"); + assert!(std::fs::symlink_metadata(&in_src).unwrap().file_type().is_symlink(), "the link stays"); + assert_eq!(std::fs::read_link(&in_src).unwrap(), outside); + assert_eq!(std::fs::read(&outside).unwrap(), b"outside"); + // a new file in the source folder (nothing there yet) is refused too + assert!(check_outputs(&src, Some(&src.join("new.json")), &work.join("elsewhere")).is_err()); + let _ = std::fs::remove_dir_all(&work); + } + + /// `--json` naming a hard link (made elsewhere) to a photo in the source folder passes + /// [`inside_source`] (a hard link has no target to resolve), so the results replace the link + /// instead of writing into it: the photo keeps its bytes (CodeRabbit on #3077). + #[test] + fn a_json_hard_link_to_a_photo_leaves_the_photo_alone() { + let work = run_dir(&std::env::temp_dir()).unwrap(); + let src = fresh_dir(&work, "src").unwrap(); + let photo = src.join("a.jpg"); + std::fs::write(&photo, b"photo").unwrap(); + let report = work.join("report.json"); + if let Err(e) = std::fs::hard_link(&photo, &report) { + let _ = std::fs::remove_dir_all(&work); + lightcraft_testkit::skip!(System, "can't make a hard link here ({e})"); + return; + } + finish(json!({"browse": 1}), Some(report.clone())).unwrap(); + assert_eq!(std::fs::read(&photo).unwrap(), b"photo", "the photo is unchanged"); + let written: Value = serde_json::from_slice(&std::fs::read(&report).unwrap()).unwrap(); + assert_eq!(written["browse"], 1); + let left: Vec<_> = std::fs::read_dir(&work).unwrap().flatten().map(|e| e.file_name()).collect(); + assert_eq!(left.len(), 2, "no temporary file is left: {left:?}"); + // a folder that isn't there: an error, nothing panics + assert!(write_replacing(&work.join("missing").join("r.json"), b"x").is_err()); + let _ = std::fs::remove_dir_all(&work); + } + + /// `--json` naming a file in the source folder is refused (CodeRabbit on #3077); elsewhere it is fine. + #[test] + fn the_results_never_go_in_the_source_folder() { + let work = run_dir(&std::env::temp_dir()).unwrap(); + let src = fresh_dir(&work, "src").unwrap(); + let sub = fresh_dir(&src, "sub").unwrap(); + assert!(inside_source(&src.join("a.png"), &src)); + assert!(inside_source(&sub.join("x.json"), &src)); + assert!(inside_source(&src.join("sub").join("..").join("a.png"), &src)); + assert!(!inside_source(&work.join("out.json"), &src)); + let _ = std::fs::remove_dir_all(&work); + } + + /// `--work` in the source folder is refused before anything is made there, also when it doesn't + /// exist yet (CodeRabbit on #3077); elsewhere it is fine. + #[test] + fn the_work_folder_never_goes_in_the_source_folder() { + let work = run_dir(&std::env::temp_dir()).unwrap(); + let src = fresh_dir(&work, "src").unwrap(); + let inside = src.join("out").join("deeper"); + let e = check_outputs(&src, None, &inside).unwrap_err(); + assert!(e.contains("--work"), "{e}"); + assert!(check_outputs(&src, None, &src).is_err(), "the source folder itself"); + assert!(!src.join("out").exists(), "nothing was made in the source folder"); + assert!(check_outputs(&src, None, &work.join("elsewhere")).is_ok()); + assert!(check_outputs(&src, Some(&src.join("r.json")), &work.join("elsewhere")).is_err()); + let _ = std::fs::remove_dir_all(&work); + } + + /// A `..` in `--json` or `--work` is refused: after a folder the run hasn't made yet it can't be + /// resolved now, and would lead into the source folder once the run makes it (CodeRabbit on #3544). + #[test] + fn a_dot_dot_in_the_outputs_is_refused() { + let work = run_dir(&std::env::temp_dir()).unwrap(); + let src = fresh_dir(&work, "src").unwrap(); + let sneaky = work.join("new").join("..").join("src").join("r.json"); + let e = check_outputs(&src, Some(&sneaky), &work.join("elsewhere")).unwrap_err(); + assert!(e.contains("--json") && e.contains(".."), "{e}"); + let e = check_outputs(&src, None, &work.join("new").join("..").join("src")).unwrap_err(); + assert!(e.contains("--work"), "{e}"); + assert!(!work.join("new").exists(), "nothing was made"); + let _ = std::fs::remove_dir_all(&work); + } +} diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rs index 7822bbed9a..d384229558 100644 --- a/apps/lightcraft-cli/src/main.rs +++ b/apps/lightcraft-cli/src/main.rs @@ -11,11 +11,13 @@ //! lightcraft-cli commands [--json] //! lightcraft-cli controls [--json] //! lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS/FILES… +//! lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE] //! ``` #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod alloc_release; +mod bench_cull; use std::io::Write; use std::path::Path; @@ -110,6 +112,12 @@ USAGE: model, written as .json to DIR (default: the profiles folder LightCraft reads, /camera-profiles, or $LIGHTCRAFT_CAMERA_PROFILES). Raws of a profiled model then take their colour from the profile and only their tone from their own JPEG. + lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE] + Time what culling a shoot costs on its own files: reading the folder (browse), the first + screen of grid thumbnails, camera previews at loupe sizes and full size, a loupe render, + rating, and importing N files in place (default 2000) and copying M (default 200). Libraries + are made in a new folder under DIR (default: the temp folder); nothing is written next to the + photos. --files K reads only the first K files by name (a sample of a slow network folder). lightcraft-cli --version | --help "; @@ -176,6 +184,7 @@ fn main() -> ExitCode { Some("controls") => controls(&args[1..]), Some("denoise-serve") => denoise_serve(&args[1..]), Some("calibrate") => calibrate(&args[1..]), + Some("bench-cull") => bench_cull::run(&args[1..]), Some("--version" | "-V" | "version") => { println!("lightcraft-cli {}", env!("CARGO_PKG_VERSION")); Ok(()) diff --git a/apps/lightcraft-cli/tests/it/cli.rs b/apps/lightcraft-cli/tests/it/cli.rs index 613197459c..2a052fc2d8 100644 --- a/apps/lightcraft-cli/tests/it/cli.rs +++ b/apps/lightcraft-cli/tests/it/cli.rs @@ -101,6 +101,75 @@ fn gradient_png(path: &std::path::Path) { std::fs::write(path, png).unwrap(); } +/// PERF-CULL-5: `bench-cull` times a folder end to end and writes nothing next to the photos. +#[test] +fn bench_cull_times_a_folder_and_leaves_it_untouched() { + let dir = tmp("bench-cull-src"); + std::fs::create_dir_all(&dir).unwrap(); + for (seed, name) in ["a.png", "b.png", "c.png"].iter().enumerate() { + // three different pictures (the same bytes would import as one photo) + let img = lightcraft_raster::Rgba8::from_fn(120, 80, |x, y| [(x * 2) as u8, (y * 3) as u8, (seed * 80) as u8, 255]); + let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &Default::default()).unwrap(); + std::fs::write(dir.join(name), png).unwrap(); + } + // every file's name and bytes: nothing added, and no photo written into (CodeRabbit on #3577) + let listing = |d: &std::path::Path| { + let mut v: Vec<(String, Vec)> = std::fs::read_dir(d) + .unwrap() + .map(|e| e.unwrap()) + .map(|e| (e.file_name().to_string_lossy().to_string(), std::fs::read(e.path()).unwrap())) + .collect(); + v.sort(); + v + }; + let before = listing(&dir); + let work = tmp("bench-cull-work"); + let json_out = tmp("bench-cull.json"); + let r = Command::new(binary()) + .arg("bench-cull") + .arg(&dir) + .args(["--n", "3", "--copy", "1", "--work"]) + .arg(&work) + .arg("--json") + .arg(&json_out) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&r.stdout); + assert!(r.status.success(), "{stdout}{}", String::from_utf8_lossy(&r.stderr)); + assert!(stdout.contains("browse 3 photos") && stdout.contains("ms wall"), "{stdout}"); + let v: Value = serde_json::from_str(&std::fs::read_to_string(&json_out).unwrap()).unwrap(); + assert_eq!(v["browse"]["photos"], 3); + assert_eq!(v["importAdd"]["photos"], 3); + assert_eq!(v["importCopy"]["photos"], 1); + assert_eq!(v["rate"]["n"], 3); + // a folder smaller than the samples is measured on the photos it has, not reported empty + for stage in ["camera1280", "camera2560", "cameraFull", "loupeRender"] { + assert_eq!(v[stage]["n"], 3, "{stage}: {}", v[stage]); + } + assert_eq!(listing(&dir), before, "nothing written next to the photos"); + // results asked for in the source folder: refused, the photo untouched + let photo = std::fs::read(dir.join("a.png")).unwrap(); + let r = Command::new(binary()) + .arg("bench-cull") + .arg(&dir) + .args(["--n", "0", "--work"]) + .arg(&work) + .arg("--json") + .arg(dir.join("a.png")) + .output() + .unwrap(); + assert!(!r.status.success() && String::from_utf8_lossy(&r.stderr).contains("--json"), "{}", String::from_utf8_lossy(&r.stderr)); + assert_eq!(std::fs::read(dir.join("a.png")).unwrap(), photo); + assert_eq!(listing(&dir), before); + // a sample of the folder, no import + let r = Command::new(binary()).arg("bench-cull").arg(&dir).args(["--files", "2", "--n", "0", "--work"]).arg(&work).output().unwrap(); + let stdout = String::from_utf8_lossy(&r.stdout); + assert!(r.status.success() && stdout.contains("browse 2 photos (first files)") && !stdout.contains("import"), "{stdout}"); + // a bad folder is an error, not a panic + let r = Command::new(binary()).args(["bench-cull", "/no/such/folder"]).output().unwrap(); + assert!(!r.status.success() && String::from_utf8_lossy(&r.stderr).contains("not a folder")); +} + #[test] fn calibrate_reads_raf_inputs_and_reports_bad_files() { let input = tmp("invalid.RAF"); diff --git a/apps/lightcraft-web/src/store.rs b/apps/lightcraft-web/src/store.rs index 8f7c8e2839..7f32051c2e 100644 --- a/apps/lightcraft-web/src/store.rs +++ b/apps/lightcraft-web/src/store.rs @@ -12,7 +12,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex}; -use lightcraft_engine::files::{load_bytes_with, probe_bytes}; +use lightcraft_engine::files::{load_bytes_decoded, probe_bytes}; use lightcraft_engine::media::{FileLoader, FileProbe}; /// Prefix of the catalog paths of files kept in browser storage. @@ -146,9 +146,9 @@ impl Originals { let s = self.clone(); // (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 loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, with: lightcraft_engine::media::RawDecode<'_>| { let bytes = s.get(path).ok_or_else(|| format!("{path}: the original is still loading from browser storage"))?; - load_bytes_with(&bytes, max_edge, None) + load_bytes_decoded(&bytes, max_edge, lightcraft_engine::media::RawDecode { dcp: None, outliers: with.outliers }) }); let s = self.clone(); let probe: FileProbe = Arc::new(move |path: &str| { @@ -285,15 +285,15 @@ mod tests { 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, + lightcraft_engine::files::load_bytes_with(&dng, 64, Some(&profile)).unwrap().0.data, + lightcraft_engine::files::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(); + let with = loader("web/h1/a.dng", 64, lightcraft_engine::media::RawDecode { dcp: Some(&profile), outliers: false }).unwrap(); + let without = loader("web/h1/a.dng", 64, Default::default()).unwrap(); assert_eq!(with.0.data, without.0.data, "the web loader leaves it out"); } diff --git a/apps/lightcraft-web/src/wire.rs b/apps/lightcraft-web/src/wire.rs index 53d389b6f7..bad3507783 100644 --- a/apps/lightcraft-web/src/wire.rs +++ b/apps/lightcraft-web/src/wire.rs @@ -129,7 +129,9 @@ impl WireJob { /// Identifies the decoded source this job needs. fn source_key(&self) -> String { match &self.origin { - Source::File { path } => format!("{}:{:?}:{}:{path}", self.cache_generation, self.source_identity, self.max_edge), + Source::File { path } => { + format!("{}:{:?}:{}:{}:{path}", self.cache_generation, self.source_identity, self.max_edge, self.settings.removes_hot_pixels()) + } Source::Demo { scene } => format!("{}:{:?}:{}:demo:{scene}", self.cache_generation, self.source_identity, self.max_edge), } } @@ -181,8 +183,10 @@ impl WorkerCore { None => { let src = match (&job.origin, original) { (Source::File { .. }, Some(bytes)) => { - let (image, info) = lightcraft_engine::files::load_bytes(bytes, job.max_edge)?; - DecodedSource::new(Arc::new(image), Some(info)) + let outliers = job.settings.removes_hot_pixels(); + let with = lightcraft_engine::media::RawDecode { dcp: None, outliers }; + let (image, info) = lightcraft_engine::files::load_bytes_decoded(bytes, job.max_edge, with)?; + DecodedSource { outliers, ..DecodedSource::new(Arc::new(image), Some(info)) } } (Source::File { path }, None) => return Err(format!("{path}: original not found in browser storage")), (origin @ Source::Demo { .. }, _) => self.media.origin_ref(origin, job.max_edge).load_source()?, diff --git a/apps/lightcraft/Cargo.toml b/apps/lightcraft/Cargo.toml index d00bc41e99..cf8aaf2e06 100644 --- a/apps/lightcraft/Cargo.toml +++ b/apps/lightcraft/Cargo.toml @@ -58,3 +58,6 @@ lightcraft-testkit = { workspace = true } [target.'cfg(windows)'.dependencies] craft-update = { workspace = true } +# the colour profile of the monitor showing the window (`win_screen_profile`) +lightcraft-wincolor = { workspace = true } +raw-window-handle = "0.6" diff --git a/apps/lightcraft/src/colord.rs b/apps/lightcraft/src/colord.rs index 70f7fbdd27..a517ba2b03 100644 --- a/apps/lightcraft/src/colord.rs +++ b/apps/lightcraft/src/colord.rs @@ -18,8 +18,6 @@ use std::time::Duration; const POLL: Duration = Duration::from_secs(3); /// A wait before trying again when colord isn't there (not installed, no system bus). const RETRY: Duration = Duration::from_secs(30); -/// The largest profile file read (real display profiles are a few KiB to a few MiB). -const MAX_PROFILE: u64 = 16 << 20; const SERVICE: &str = "org.freedesktop.ColorManager"; const DEVICE: &str = "org.freedesktop.ColorManager.Device"; @@ -72,7 +70,7 @@ fn read(conn: &zbus::blocking::Connection) -> Option> { } } let file = pick(&files)?; - load(std::path::Path::new(file)) + crate::profile_file::load(std::path::Path::new(file)) } /// The profile to use for these displays' profile files: the one they share, `None` with none or @@ -83,15 +81,6 @@ fn pick(files: &[String]) -> Option<&str> { named.all(|f| f == first).then_some(first) } -/// The bytes of profile file `path`, `None` when it can't be read or is implausibly large. -fn load(path: &std::path::Path) -> Option> { - use std::io::Read as _; - let file = std::fs::File::open(path).ok()?; - let mut bytes = Vec::new(); - file.take(MAX_PROFILE + 1).read_to_end(&mut bytes).ok()?; - (!bytes.is_empty() && bytes.len() as u64 <= MAX_PROFILE).then_some(bytes) -} - #[cfg(test)] mod tests { use super::*; @@ -105,21 +94,4 @@ mod tests { assert_eq!(pick(&s(&["/a.icc", "/b.icc"])), None, "which one the window is on isn't known"); assert_eq!(pick(&s(&[""])), None); } - - #[test] - fn profile_files_are_read_with_a_size_cap() { - let dir = std::env::temp_dir().join(format!("colord-test-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let small = dir.join("small.icc"); - std::fs::write(&small, b"acsp").unwrap(); - assert_eq!(load(&small).as_deref(), Some(&b"acsp"[..])); - let empty = dir.join("empty.icc"); - std::fs::write(&empty, b"").unwrap(); - assert_eq!(load(&empty), None); - assert_eq!(load(&dir.join("missing.icc")), None); - let big = dir.join("big.icc"); - std::fs::File::create(&big).unwrap().set_len(MAX_PROFILE + 1).unwrap(); - assert_eq!(load(&big), None); - std::fs::remove_dir_all(&dir).unwrap(); - } } diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 31ae7229f5..3a7bda6696 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -35,8 +35,12 @@ mod hdr_display; mod logging; #[cfg(target_os = "macos")] mod native_menu; +#[cfg(any(target_os = "linux", windows))] +mod profile_file; #[cfg(target_os = "macos")] mod screen_profile; +#[cfg(windows)] +mod win_screen_profile; mod window_gpu; use dialog_filter::FileDialogExt as _; @@ -371,6 +375,7 @@ fn main() -> eframe::Result { app.notices.extend(launch_notices); app.notices.extend(window_notice); app.gpu_notice = true; + app.disk_space_notice = true; // an empty library opens where Import is offered (a grid, with the sidebar); before // the snapshot below, so this alone isn't written to the settings file if problem.is_none() && files.is_empty() { diff --git a/apps/lightcraft/src/profile_file.rs b/apps/lightcraft/src/profile_file.rs new file mode 100644 index 0000000000..605fa3e2c9 --- /dev/null +++ b/apps/lightcraft/src/profile_file.rs @@ -0,0 +1,87 @@ +//! Reading a display's ICC profile file for the screen-profile services (`colord` on Linux, +//! `win_screen_profile` on Windows). + +use std::path::{Path, PathBuf}; +use std::time::SystemTime; + +/// The largest profile file read (real display profiles are a few KiB to a few MiB). +pub const MAX_PROFILE: u64 = 16 << 20; + +/// The bytes of profile file `path`, `None` when it can't be read or is implausibly large. +pub fn load(path: &Path) -> Option> { + use std::io::Read as _; + let file = std::fs::File::open(path).ok()?; + let mut bytes = Vec::new(); + file.take(MAX_PROFILE + 1).read_to_end(&mut bytes).ok()?; + (!bytes.is_empty() && bytes.len() as u64 <= MAX_PROFILE).then_some(bytes) +} + +/// A profile file read again only when it changes: the services are asked about once a second, and +/// calibration software rewrites its profile under the same name. +#[cfg_attr(not(windows), allow(dead_code))] +#[derive(Default)] +pub struct Cached { + /// The file last read: its path, length and modification time. + stamp: Option<(PathBuf, u64, Option)>, + bytes: Option>, +} + +#[cfg_attr(not(windows), allow(dead_code))] +impl Cached { + /// The bytes of profile file `path`, read again when it isn't the file read last time or has + /// changed since (see [`load`]). + pub fn read(&mut self, path: &Path) -> Option> { + let stamp = std::fs::metadata(path).ok().map(|m| (path.to_path_buf(), m.len(), m.modified().ok())); + if stamp.is_none() || stamp != self.stamp { + self.bytes = stamp.as_ref().and_then(|_| load(path)); + self.stamp = stamp; + } + self.bytes.clone() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn profile_files_are_read_with_a_size_cap() { + let dir = std::env::temp_dir().join(format!("profile-file-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let small = dir.join("small.icc"); + std::fs::write(&small, b"acsp").unwrap(); + assert_eq!(load(&small).as_deref(), Some(&b"acsp"[..])); + let empty = dir.join("empty.icc"); + std::fs::write(&empty, b"").unwrap(); + assert_eq!(load(&empty), None); + assert_eq!(load(&dir.join("missing.icc")), None); + let big = dir.join("big.icc"); + std::fs::File::create(&big).unwrap().set_len(MAX_PROFILE + 1).unwrap(); + assert_eq!(load(&big), None); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn a_cached_profile_is_read_again_when_the_file_changes() { + let dir = std::env::temp_dir().join(format!("profile-cache-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (a, b) = (dir.join("a.icc"), dir.join("b.icc")); + std::fs::write(&a, b"first").unwrap(); + std::fs::write(&b, b"other").unwrap(); + let mut cache = Cached::default(); + assert_eq!(cache.read(&a).as_deref(), Some(&b"first"[..])); + assert_eq!(cache.read(&a).as_deref(), Some(&b"first"[..])); + // another monitor's profile + assert_eq!(cache.read(&b).as_deref(), Some(&b"other"[..])); + // rewritten under the same name (a different length, so the change shows whatever the + // file system's time resolution) + std::fs::write(&b, b"calibrated").unwrap(); + assert_eq!(cache.read(&b).as_deref(), Some(&b"calibrated"[..])); + // gone: nothing, then read again once it is back + std::fs::remove_file(&b).unwrap(); + assert_eq!(cache.read(&b), None); + std::fs::write(&b, b"back").unwrap(); + assert_eq!(cache.read(&b).as_deref(), Some(&b"back"[..])); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/apps/lightcraft/src/session.rs b/apps/lightcraft/src/session.rs index ac46a43b5d..c02ce47a1e 100644 --- a/apps/lightcraft/src/session.rs +++ b/apps/lightcraft/src/session.rs @@ -144,7 +144,11 @@ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std:: // Linux: the profile the desktop assigns in colord, read off the UI thread #[cfg(target_os = "linux")] screen_profile: Some(colord::service()), - #[cfg(not(any(target_os = "macos", target_os = "linux")))] + // Windows: the profile it uses for the window's monitor, unless it colour-manages the + // desktop itself (HDR, Auto Color Management) + #[cfg(windows)] + screen_profile: win_screen_profile::service(cc), + #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))] screen_profile: None, pick_display_profile: Some(Box::new(|| { let mut d = file_dialog() diff --git a/apps/lightcraft/src/win_screen_profile.rs b/apps/lightcraft/src/win_screen_profile.rs new file mode 100644 index 0000000000..4fc91d8df0 --- /dev/null +++ b/apps/lightcraft/src/win_screen_profile.rs @@ -0,0 +1,40 @@ +//! The ICC profile Windows assigns to the monitor showing LightCraft's window. +//! +//! On an SDR desktop Windows passes what an app draws to the monitor unchanged, so sRGB previews +//! look oversaturated on a wide-gamut monitor and ignore a calibration. While no monitor profile is +//! chosen in Settings ▸ Display, previews are shown through the profile Windows uses for the window's +//! monitor (`Services::screen_profile`, see `lightcraft_wincolor`), followed when the window moves to +//! another monitor or the profile changes in Windows' Color Management. When Windows colour-manages +//! the desktop itself (HDR, Auto Color Management) previews stay sRGB, as Windows expects then. + +use lightcraft_wincolor::MonitorColor; + +/// The service the UI polls, for the window `cc` belongs to; `None` when its handle isn't a Win32 one. +pub fn service(cc: &eframe::CreationContext<'_>) -> Option { + use raw_window_handle::{HasWindowHandle, RawWindowHandle}; + let RawWindowHandle::Win32(handle) = cc.window_handle().ok()?.as_raw() else { return None }; + let hwnd = handle.hwnd.get(); + let mut file = crate::profile_file::Cached::default(); + let mut last: Option = None; + Some(Box::new(move || { + let answer = lightcraft_wincolor::monitor_color(hwnd); + if last.as_ref() != Some(&answer) { + log::info!("screen profile: {}", describe(&answer)); + last = Some(answer.clone()); + } + match answer { + MonitorColor::Profile(path) => file.read(&path), + MonitorColor::ManagedByWindows | MonitorColor::NoProfile | MonitorColor::Unknown => None, + } + })) +} + +/// For the log: what the window's monitor answered. +fn describe(answer: &MonitorColor) -> String { + match answer { + MonitorColor::Profile(path) => format!("the monitor's profile, {}", path.display()), + MonitorColor::ManagedByWindows => "Windows colour-manages this monitor (HDR or Auto Color Management): previews are sRGB".into(), + MonitorColor::NoProfile => "no profile is assigned to the monitor: previews are sRGB".into(), + MonitorColor::Unknown => "not known for this monitor: previews are sRGB".into(), + } +} diff --git a/contributors/people.toml b/contributors/people.toml index 836a3d801f..04286cc129 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -68,6 +68,10 @@ sync_github_name = true [people.ronibalthazar] sync_github_name = true +[people.esli1283] +real_name = "Aaron Lopez" +sync_github_name = false + [people.dotCooCoo] real_name = "Robert Lee" sync_github_name = true diff --git a/crates/codecs/src/jpeg.rs b/crates/codecs/src/jpeg.rs index 89af1372bf..3e09ae1c4e 100644 --- a/crates/codecs/src/jpeg.rs +++ b/crates/codecs/src/jpeg.rs @@ -862,3 +862,210 @@ mod tests { } } } + +/// [`crate::decode_jpeg_srgb8_fit`]: a plain 8-bit sRGB JPEG decoded (DCT-scaled when that still +/// covers the box) and area-averaged in linear light straight into 8-bit sRGB, without the +/// float image the general path builds (for a 45 MP camera preview fitted to 2560 px that float +/// image and its conversions were half the time). `Ok(None)` for anything else. +pub(crate) fn srgb8_fit(bytes: &[u8], max_w: u32, max_h: u32) -> Result> { + // (a Samsung SEF trailer read as the file it stands for, as the general decode does: CodeRabbit on #3583) + let bytes = &*without_sef_trailer(bytes); + let Some(m) = parse_markers(bytes) else { return Ok(None) }; + let plain = matches!(m.components, 1 | 3) + && m.precision == 8 + && matches!(m.sof, 0xC0..=0xC2) + && m.icc.is_none() + && !m.icc_invalid + && m.adobe_transform.is_none(); + let summary = m.exif.as_deref().map(exif::summarize).unwrap_or_default(); + if !plain || summary.adobe_rgb_hint || max_w == 0 || max_h == 0 { + return Ok(None); + } + let budget = DecodeOptions::default(); + check_size(F, m.width as u64, m.height as u64, &budget)?; + // as in the general decode: the decoders below walk every APP1 again + if m.app1 > MAX_APP1 { + return Err(Error::Malformed(F, "too many APP1 markers".into())); + } + let scale_to = (m.width >= max_w.saturating_mul(2) || m.height >= max_h.saturating_mul(2)).then_some((max_w, max_h)); + let non_interleaved = matches!(m.sof, 0xC0 | 0xC1) && m.first_scan_components < m.components; + let raw = + if scale_to.is_some() || non_interleaved { decode_jpeg_decoder(bytes, &m, scale_to, &budget)? } else { decode_zune(bytes, &m, &budget)? }; + let Buf::U8(px) = &raw.buf else { return Ok(None) }; + let ch = match raw.model { + Model::Rgb => 3, + Model::Gray => 1, + Model::Cmyk => return Ok(None), + }; + let (w, h) = (raw.width, raw.height); + if w == 0 || h == 0 || px.len() < w.saturating_mul(h).saturating_mul(ch) { + return Err(Error::Malformed(F, "short output".into())); + } + // the size `lightcraft_raster::resample::fit` gives: within the box, aspect kept, never larger + let s = (max_w as f64 / w as f64).min(max_h as f64 / h as f64).min(1.0); + let tw = ((w as f64 * s).round() as usize).clamp(1, w); + let th = ((h as f64 * s).round() as usize).clamp(1, h); + let orientation = summary.orientation.filter(|o| (1..=8).contains(o)).unwrap_or(1); + Ok(Some((area_average_srgb8(px, w, h, ch, tw, th), orientation))) +} + +/// Source pixels and weights each output pixel along one axis covers: a box of the scale's width +/// (`n` source pixels onto `out`), partly covered pixels at its ends weighted by their share. +fn box_taps(n: usize, out: usize) -> Vec<(usize, Vec)> { + let scale = n as f64 / out as f64; + (0..out) + .map(|o| { + let (a, b) = (o as f64 * scale, ((o + 1) as f64 * scale).min(n as f64)); + let first = (a.floor() as usize).min(n - 1); + let last = ((b.ceil() as usize).max(first + 1)).min(n); + let ws: Vec = + (first..last).map(|j| ((b.min(j as f64 + 1.0) - a.max(j as f64)).max(0.0) / (b - a).max(f64::MIN_POSITIVE)) as f32).collect(); + (first, ws) + }) + .collect() +} + +/// `px` (`w × h`, `ch` = 1 or 3 interleaved 8-bit sRGB samples) averaged over boxes in linear +/// light into `tw × th` opaque 8-bit sRGB pixels. A copy when the size doesn't change. +fn area_average_srgb8(px: &[u8], w: usize, h: usize, ch: usize, tw: usize, th: usize) -> lightcraft_raster::Rgba8 { + use lightcraft_color::transfer::{decode_srgb8, encode_srgb8}; + let mut out = lightcraft_raster::Rgba8::new(tw, th); + let sample = |x: usize, y: usize, c: usize| px.get((y * w + x) * ch + if ch == 3 { c } else { 0 }).copied().unwrap_or(0); + if (tw, th) == (w, h) { + lightcraft_raster::par_rows(&mut out.data, tw, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + *o = [sample(x, y, 0), sample(x, y, 1), sample(x, y, 2), 255]; + } + }); + return out; + } + let lut: [f32; 256] = std::array::from_fn(|i| decode_srgb8(i as u8)); + let xs = box_taps(w, tw); + let ys = box_taps(h, th); + // one source row filtered across into linear RGB at the output width + let across = |sy: usize, buf: &mut Vec<[f32; 3]>| { + buf.clear(); + let Some(src) = px.get(sy * w * ch..(sy + 1) * w * ch) else { + buf.resize(tw, [0.0; 3]); + return; + }; + for (x0, wx) in &xs { + let mut a = [0f32; 3]; + if let Some(span) = src.get(x0 * ch..(x0 + wx.len()) * ch) { + for (p, &k) in span.chunks_exact(ch).zip(wx) { + match p { + [r, g, b] => { + a[0] += lut[*r as usize] * k; + a[1] += lut[*g as usize] * k; + a[2] += lut[*b as usize] * k; + } + [v] => { + let l = lut[*v as usize] * k; + a = [a[0] + l, a[1] + l, a[2] + l]; + } + _ => {} + } + } + } + buf.push(a); + } + }; + lightcraft_raster::par_rows(&mut out.data, tw, |y, row| { + let Some((y0, wy)) = ys.get(y) else { return }; + let mut acc = vec![[0f32; 3]; tw]; + let mut line = Vec::with_capacity(tw); + for (dy, &k) in wy.iter().enumerate() { + across(y0 + dy, &mut line); + for (a, l) in acc.iter_mut().zip(&line) { + a[0] += l[0] * k; + a[1] += l[1] * k; + a[2] += l[2] * k; + } + } + for (o, a) in row.iter_mut().zip(&acc) { + *o = [encode_srgb8(a[0]), encode_srgb8(a[1]), encode_srgb8(a[2]), 255]; + } + }); + out +} + +#[cfg(test)] +mod srgb8_fit_tests { + use super::*; + + fn jpeg(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 3]) -> Vec { + let data: Vec<[u8; 4]> = (0..w * h) + .map(|i| { + let [r, g, b] = f(i % w, i / w); + [r, g, b, 255] + }) + .collect(); + let img = lightcraft_raster::Rgba8 { width: w, height: h, data }; + crate::encode_jpeg(&crate::EncodeImage::rgba8(&img), 95, crate::ChromaSubsampling::S420, &crate::EncodeMeta::default()).unwrap() + } + + /// The fast path shows what the general decode shows for a plain sRGB JPEG, at the same size. + #[test] + fn matches_the_general_decode_within_a_few_levels() { + let b = jpeg(1203, 801, |x, y| [((x * 7) ^ (y * 3)) as u8, (x / 5 + y / 3) as u8, ((x * y) % 251) as u8]); + for (mw, mh) in [(300u32, 300u32), (640, 640), (1203, 801), (5000, 5000), (500, 120)] { + let (fast, o) = srgb8_fit(&b, mw, mh).unwrap().unwrap(); + let slow = crate::decode(&b, DecodeOptions::fit(mw, mh)).unwrap().to_srgb8(); + assert_eq!((fast.width, fast.height), (slow.width, slow.height), "box {mw}×{mh}"); + assert_eq!(o, 1); + let diff: Vec = + fast.data.iter().zip(&slow.data).flat_map(|(a, b)| (0..3).map(move |c| (a[c] as i32 - b[c] as i32).unsigned_abs())).collect(); + let mean = diff.iter().sum::() as f64 / diff.len() as f64; + assert!(mean < 3.0, "box {mw}×{mh}: mean difference {mean}"); + } + } + + /// Anything but plain 8-bit sRGB goes the general way; junk is an error or `None`, never a panic. + #[test] + fn declines_what_it_does_not_cover_and_never_panics() { + let b = jpeg(64, 48, |x, _| [x as u8, 0, 0]); + assert!(srgb8_fit(&b, 0, 10).unwrap().is_none()); + assert!(srgb8_fit(b"not a jpeg", 10, 10).unwrap().is_none()); + for cut in [0, 2, 20, b.len() / 2, b.len() - 3] { + let _ = srgb8_fit(&b[..cut], 32, 32); + } + // a 1-pixel-wide image into a box much smaller in one axis + let thin = jpeg(1, 300, |_, y| [y as u8, y as u8, y as u8]); + let (img, _) = srgb8_fit(&thin, 10, 10).unwrap().unwrap(); + assert_eq!((img.width, img.height), (1, 10)); + } + + /// An incomplete ICC_PROFILE sequence (chunk 1 of 2) is "has a profile we can't read", not + /// "plain sRGB": the general decode handles it, as the doc says (CodeRabbit on #3577). + #[test] + fn an_incomplete_icc_sequence_goes_the_general_way() { + let b = jpeg(16, 16, |x, y| [x as u8, y as u8, 0]); + let mut seg = vec![0xFF, 0xE2, 0, 0]; + seg.extend_from_slice(b"ICC_PROFILE"); + seg.extend_from_slice(&[1, 2]); + seg.extend_from_slice(&[0u8; 64]); + let len = u16::try_from(seg.len() - 2).unwrap(); + seg[2..4].copy_from_slice(&len.to_be_bytes()); + let mut with = b[..2].to_vec(); + with.extend_from_slice(&seg); + with.extend_from_slice(&b[2..]); + assert!(parse_markers(&with).unwrap().icc_invalid); + assert!(srgb8_fit(&b, 8, 8).unwrap().is_some()); + assert!(srgb8_fit(&with, 8, 8).unwrap().is_none()); + } + + /// The 8-bit path refuses an APP1 flood before its decoders walk it again, as the general one does. + #[test] + fn an_app1_flood_is_refused_by_the_8_bit_path_too() { + let b = jpeg(16, 16, |x, y| [x as u8, y as u8, 0]); + let mut flood = b[..2].to_vec(); + for _ in 0..200 { + flood.extend_from_slice(&[0xFF, 0xE1, 0x00, 0x02]); + } + flood.extend_from_slice(&b[2..]); + match srgb8_fit(&flood, 8, 8) { + Err(Error::Malformed(_, m)) => assert!(m.contains("APP1"), "{m}"), + other => panic!("unexpected: {other:?}"), + } + } +} diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index 8210f33f01..ad918ddd02 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -169,6 +169,21 @@ pub fn decode(bytes: &[u8], opts: DecodeOptions) -> Result { std::panic::catch_unwind(|| decode_unguarded(bytes, format, &opts)).unwrap_or_else(|_| Err(Error::Malformed(format, "decoder panicked".into()))) } +/// A JPEG for display, fast: fitted within `max_w × max_h` (never enlarged) as 8-bit sRGB with its +/// EXIF orientation (1..=8, not applied), the picture `decode(bytes, DecodeOptions::fit(..)) +/// .to_srgb8()` gives within a few levels, in about half the time for a large camera preview. +/// `Ok(None)` when the file is not a plain 8-bit sRGB JPEG (an ICC profile or an Adobe RGB EXIF +/// hint, CMYK, 12-bit, lossless or arithmetic coding) or its headers can't be read: use +/// [`decode`], which reports a malformed header as an error. Bad scan data is an error here, and +/// nothing is ever a panic. +pub fn decode_jpeg_srgb8_fit(bytes: &[u8], max_w: u32, max_h: u32) -> Result> { + if sniff(bytes) != Some(Format::Jpeg) { + return Ok(None); + } + std::panic::catch_unwind(|| jpeg::srgb8_fit(bytes, max_w, max_h)) + .unwrap_or_else(|_| Err(Error::Malformed(Format::Jpeg, "decoder panicked".into()))) +} + /// What a file's headers say about its image: enough to catalogue it without decoding pixels. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Header { diff --git a/crates/codecs/tests/it/header.rs b/crates/codecs/tests/it/header.rs index f6ce7d3216..7fec902228 100644 --- a/crates/codecs/tests/it/header.rs +++ b/crates/codecs/tests/it/header.rs @@ -208,6 +208,10 @@ fn samsung_sef_trailer_without_eoi() { assert_eq!(full.image.data, reference.image.data, "the same pixels as the file with its EOI"); let small = decode(&pano, DecodeOptions::fit(32, 32)).unwrap(); assert_eq!((small.source_width, small.source_height), (160, 96)); + // the fast display decode too, scaled (where the trailer after the scan used to fail it) + let (fit, _) = lightcraft_codecs::decode_jpeg_srgb8_fit(&pano, 32, 32).unwrap().unwrap(); + let (fit_ref, _) = lightcraft_codecs::decode_jpeg_srgb8_fit(&jpeg, 32, 32).unwrap().unwrap(); + assert_eq!((fit.width, fit.height, &fit.data), (fit_ref.width, fit_ref.height, &fit_ref.data)); // an FF D9 inside the SEF data is not the image's end let eoi_in_data = sef_file(scan, block, b"SEFH", 0x08E0, &[0xFF, 0xC0, 0, 0x11, 0xFF, 0xD9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], None); assert_eq!(read_header(&eoi_in_data).unwrap().width, 160); diff --git a/crates/denoise-core/src/bm3d.rs b/crates/denoise-core/src/bm3d.rs new file mode 100644 index 0000000000..4419e8b921 --- /dev/null +++ b/crates/denoise-core/src/bm3d.rs @@ -0,0 +1,601 @@ +//! Block-matching collaborative filtering (after Dabov, Foi, Katkovnik and Egiazarian, "Image denoising by sparse 3-D +//! transform-domain collaborative filtering", 2007; the colour variant is their CBM3D), written from the paper. +//! +//! It works on the same planes as [`crate::nlm`]: four Bayer planes of unit noise (see [`crate::nlm::Stabiliser`]), +//! rotated by a Hadamard transform into a brightness plane and three colour-difference planes. Blocks of the +//! brightness plane that look alike are stacked into a group; the stack is transformed (2-D DCT of each block, Haar +//! across the stack) where the picture is sparse and the noise is not, shrunk, transformed back and put back with +//! weights. The first step shrinks by a hard threshold and gives a basic estimate; the second matches blocks on that +//! cleaner estimate and shrinks by a Wiener filter built from it. Every plane of a group follows the brightness +//! plane's matches, so the colour differences are only averaged across like brightness. + +use crate::nlm::hadamard; +use std::f32::consts::FRAC_1_SQRT_2; + +/// What the filter may be tuned by (the defaults are what the built-in denoiser uses). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Params { + /// Side of a block, in cells. + pub block: usize, + /// Distance, in cells, between the blocks that start a group (1 = every block; larger is faster). + pub step: usize, + /// How far, in cells, a match is looked for round a block. + pub search: usize, + /// The most blocks in a group (rounded down to a power of two). + pub group: usize, + /// How far above the noise two blocks may differ (mean square, in units of the noise variance) and still be + /// grouped, in the first step (on the noisy picture) and in the second (on the basic estimate). + pub tau1: f32, + pub tau2: f32, + /// The first step's hard-threshold level, in noise deviations, as a function of how noisy the photo is: points of + /// (the noise's deviation at mid-grey, with white = 1; the threshold), rising with the noise and joined in a straight + /// line against the logarithm of the noise (flat beyond the first and last). A quieter photo has more fine detail + /// per unit of noise to keep, a noisier one less. Fitted on real Canon raws with noise added at their ISO levels + /// (docs/denoise.md → Why block matching). + pub lambda: [(f32, f32); 6], + /// The noise's deviation as the filter takes it (1 = as measured; more cleans harder). + pub sigma: f32, + /// Whether the second (Wiener) step runs. + pub wiener: bool, +} + +impl Default for Params { + /// What the built-in denoiser runs with: 4 × 4 blocks taken every 3 cells, matched within 8 cells, up to 16 to a + /// group, the fitted threshold curve, and the Wiener step on. + fn default() -> Self { + Params { + block: 4, + step: 3, + search: 8, + group: 16, + tau1: 4.0, + tau2: 1.0, + lambda: [(0.0028, 1.2), (0.0062, 1.9), (0.0094, 2.3), (0.0152, 2.65), (0.038, 3.2), (0.14, 3.5)], + sigma: 1.0, + wiener: true, + } + } +} + +/// The threshold for a photo whose noise has deviation `noise` at mid-grey: `curve` read in a straight line against the +/// logarithm of the noise (the ends hold). A curve that is empty or not rising in its first coordinate gives its first +/// point's value for any noise, and a noise that is not a number is the quietest. +pub fn threshold_for(curve: &[(f32, f32)], noise: f32) -> f32 { + let Some(&(x0, y0)) = curve.first() else { return 3.0 }; + if !noise.is_finite() || noise <= x0 { + return y0; + } + for pair in curve.windows(2) { + let ((xa, ya), (xb, yb)) = (pair[0], pair[1]); + if xa.is_finite() && xb.is_finite() && xa > 0.0 && xb > xa && noise <= xb { + return ya + (yb - ya) * (noise / xa).ln() / (xb / xa).ln(); + } + } + curve.last().map_or(y0, |p| p.1) +} + +/// The orthonormal DCT-II of a block and the window the filtered blocks are put back with. +struct Transform { + n: usize, + c: Vec, + window: Vec, +} + +/// The zeroth-order modified Bessel function of the first kind (a series; the Kaiser window needs it). +fn bessel_i0(x: f32) -> f32 { + let (mut sum, mut term) = (1.0f32, 1.0f32); + for k in 1..30 { + term *= x * x / (4.0 * (k * k) as f32); + sum += term; + } + sum +} + +impl Transform { + /// The transform for `n × n` blocks: the DCT-II matrix and the Kaiser window the filtered blocks are put back with. + fn new(n: usize) -> Self { + let mut c = vec![0f32; n * n]; + for (k, row) in c.chunks_exact_mut(n).enumerate() { + let scale = if k == 0 { (1.0 / n as f32).sqrt() } else { (2.0 / n as f32).sqrt() }; + for (i, v) in row.iter_mut().enumerate() { + *v = scale * (std::f32::consts::PI * (2 * i + 1) as f32 * k as f32 / (2 * n) as f32).cos(); + } + } + // a Kaiser window (beta 2) down each side, so a block's edge counts less than its middle + let beta = 2.0f32; + let side: Vec = (0..n) + .map(|i| { + let r = if n > 1 { 2.0 * i as f32 / (n - 1) as f32 - 1.0 } else { 0.0 }; + bessel_i0(beta * (1.0 - r * r).max(0.0).sqrt()) / bessel_i0(beta) + }) + .collect(); + let window = side.iter().flat_map(|y| side.iter().map(move |x| x * y)).collect(); + Transform { n, c, window } + } + + /// `blk` (`n × n`) becomes its 2-D DCT. + fn forward(&self, blk: &mut [f32], tmp: &mut [f32]) { + let n = self.n; + for (trow, crow) in tmp.chunks_exact_mut(n).zip(self.c.chunks_exact(n)) { + trow.fill(0.0); + for (&ck, brow) in crow.iter().zip(blk.chunks_exact(n)) { + for (t, &b) in trow.iter_mut().zip(brow) { + *t += ck * b; + } + } + } + for (orow, trow) in blk.chunks_exact_mut(n).zip(tmp.chunks_exact(n)) { + for (o, crow) in orow.iter_mut().zip(self.c.chunks_exact(n)) { + *o = trow.iter().zip(crow).map(|(a, b)| a * b).sum(); + } + } + } + + /// The inverse of [`Transform::forward`]. + fn inverse(&self, blk: &mut [f32], tmp: &mut [f32]) { + let n = self.n; + tmp.fill(0.0); + for (crow, xrow) in self.c.chunks_exact(n).zip(blk.chunks_exact(n)) { + for (trow, &cki) in tmp.chunks_exact_mut(n).zip(crow) { + for (t, &x) in trow.iter_mut().zip(xrow) { + *t += cki * x; + } + } + } + for (brow, trow) in blk.chunks_exact_mut(n).zip(tmp.chunks_exact(n)) { + brow.fill(0.0); + for (&t, crow) in trow.iter().zip(self.c.chunks_exact(n)) { + for (b, &c) in brow.iter_mut().zip(crow) { + *b += t * c; + } + } + } + } +} + +/// The orthonormal Haar transform of a vector whose length is a power of two. +fn haar_forward(v: &mut [f32], tmp: &mut [f32]) { + let mut len = v.len(); + while len > 1 { + let half = len / 2; + for i in 0..half { + let (a, b) = (v.get(2 * i).copied().unwrap_or(0.0), v.get(2 * i + 1).copied().unwrap_or(0.0)); + if let Some(x) = tmp.get_mut(i) { + *x = (a + b) * FRAC_1_SQRT_2; + } + if let Some(x) = tmp.get_mut(half + i) { + *x = (a - b) * FRAC_1_SQRT_2; + } + } + if let (Some(dst), Some(src)) = (v.get_mut(..len), tmp.get(..len)) { + dst.copy_from_slice(src); + } + len = half; + } +} + +/// Undoes [`haar_forward`] in place; `tmp` is scratch of the same length. +fn haar_inverse(v: &mut [f32], tmp: &mut [f32]) { + let mut len = 2; + while len <= v.len() { + let half = len / 2; + for i in 0..half { + let (avg, det) = (v.get(i).copied().unwrap_or(0.0), v.get(half + i).copied().unwrap_or(0.0)); + if let Some(x) = tmp.get_mut(2 * i) { + *x = (avg + det) * FRAC_1_SQRT_2; + } + if let Some(x) = tmp.get_mut(2 * i + 1) { + *x = (avg - det) * FRAC_1_SQRT_2; + } + } + if let (Some(dst), Some(src)) = (v.get_mut(..len), tmp.get(..len)) { + dst.copy_from_slice(src); + } + len *= 2; + } +} + +/// Reusable buffers of the group transforms. +#[derive(Default)] +struct Scratch { + tmp: Vec, + col: Vec, + col_tmp: Vec, +} + +/// A group (`m` blocks of `n × n`, one after the other in `buf`) to the transform domain, or back. +fn group_transform(tf: &Transform, buf: &mut [f32], m: usize, s: &mut Scratch, forward: bool) { + let nn = tf.n * tf.n; + s.tmp.resize(nn, 0.0); + if !forward { + haar_columns(buf, m, nn, s, false); + } + for blk in buf.chunks_exact_mut(nn) { + if forward { + tf.forward(blk, &mut s.tmp); + } else { + tf.inverse(blk, &mut s.tmp); + } + } + if forward { + haar_columns(buf, m, nn, s, true); + } +} + +/// The Haar transform across the blocks of a group, at each of the `nn` positions of a block. +fn haar_columns(buf: &mut [f32], m: usize, nn: usize, s: &mut Scratch, forward: bool) { + if m < 2 { + return; + } + s.col.resize(m, 0.0); + s.col_tmp.resize(m, 0.0); + for k in 0..nn { + for (i, c) in s.col.iter_mut().enumerate() { + *c = buf.get(i * nn + k).copied().unwrap_or(0.0); + } + if forward { + haar_forward(&mut s.col, &mut s.col_tmp); + } else { + haar_inverse(&mut s.col, &mut s.col_tmp); + } + for (i, c) in s.col.iter().enumerate() { + if let Some(b) = buf.get_mut(i * nn + k) { + *b = *c; + } + } + } +} + +/// Copy the blocks of a group out of a plane (`members` are the blocks' top-left cells). +pub(crate) fn gather(plane: &[f32], t: usize, n: usize, members: &[u32], out: &mut Vec) { + out.clear(); + for &pos in members { + for j in 0..n { + let at = pos as usize + j * t; + match plane.get(at..at + n) { + Some(row) => out.extend_from_slice(row), + None => out.extend(std::iter::repeat_n(0.0, n)), + } + } + } +} + +/// Where a plane's blocks start along one side: every `step` cells, and the last one too, so the edge is covered. +pub fn starts(blocks: usize, step: usize) -> Vec { + let mut v: Vec = (0..blocks).step_by(step.max(1)).collect(); + if let Some(last) = blocks.checked_sub(1) + && v.last() != Some(&last) + { + v.push(last); + } + v +} + +/// Insert `(distance, block)` into a list ordered by distance, keeping at most `cap`. +fn insert(list: &mut Vec<(f32, u32)>, cap: usize, d: f32, pos: u32) { + if list.len() >= cap && list.last().is_some_and(|l| d >= l.0) { + return; + } + let at = list.partition_point(|e| e.0 <= d); + list.insert(at, (d, pos)); + list.truncate(cap); +} + +/// For every block that starts a group, the blocks of `plane` within `search` cells (itself first) whose mean squared +/// difference from it is at most `tau`, nearest first and at most `cap`. Blocks (of `n × n` cells) are named by their +/// top-left cell, and a block starts a group every `step` cells. +pub(crate) fn match_groups(plane: &[f32], t: usize, n: usize, step: usize, search: usize, cap: usize, tau: f32) -> Vec> { + let nb = t + 1 - n; + let refs = starts(nb, step); + let nr = refs.len(); + let cap = cap.max(1); + let mut lists: Vec> = Vec::with_capacity(nr * nr); + for &ry in &refs { + for &rx in &refs { + let mut l = Vec::with_capacity(cap + 1); + l.push((0.0, (ry * t + rx) as u32)); + lists.push(l); + } + } + let norm = 1.0 / (n * n) as f32; + let r = search as isize; + let (mut d, mut hsum) = (vec![0f32; t * t], vec![0f32; t * nr]); + let valid = |v: usize, o: isize| (v as isize + o) >= 0 && ((v as isize + o) as usize) < nb; + for oy in -r..=r { + for ox in -r..=r { + if ox == 0 && oy == 0 { + continue; + } + // squared differences between the plane and itself shifted by the offset + let (x0, x1) = (0.max(-ox) as usize, (t as isize).min(t as isize - ox) as usize); + for y in 0..t { + let sy = y as isize + oy; + if sy < 0 || sy >= t as isize { + continue; + } + let (Some(a), Some(b), Some(out)) = ( + plane.get(y * t + x0..y * t + x1), + plane.get(sy as usize * t + (x0 as isize + ox) as usize..sy as usize * t + (x1 as isize + ox) as usize), + d.get_mut(y * t + x0..y * t + x1), + ) else { + continue; + }; + for ((o, &a), &b) in out.iter_mut().zip(a).zip(b) { + *o = (a - b) * (a - b); + } + } + // block sums: along rows at the starting columns, then down at the starting rows + for y in 0..t { + for (ri, &rx) in refs.iter().enumerate() { + if !valid(rx, ox) { + continue; + } + let s: f32 = d.get(y * t + rx..y * t + rx + n).map_or(0.0, |v| v.iter().sum()); + if let Some(h) = hsum.get_mut(y * nr + ri) { + *h = s; + } + } + } + for (rj, &ry) in refs.iter().enumerate() { + if !valid(ry, oy) { + continue; + } + for (ri, &rx) in refs.iter().enumerate() { + if !valid(rx, ox) { + continue; + } + let s: f32 = (0..n).map(|j| hsum.get((ry + j) * nr + ri).copied().unwrap_or(0.0)).sum::() * norm; + if s <= tau { + let other = ((ry as isize + oy) as usize * t) as isize + (rx as isize + ox); + if let Some(l) = lists.get_mut(rj * nr + ri) { + insert(l, cap, s, other as u32); + } + } + } + } + } + } + lists.into_iter().map(|l| l.into_iter().map(|(_, pos)| pos).collect()).collect() +} + +/// [`match_groups`] with each group cut to a power of two, so the Haar transform across it is complete. +fn match_blocks(plane: &[f32], t: usize, p: &Params, tau: f32) -> Vec> { + let mut groups = match_groups(plane, t, p.block, p.step, p.search, p.group, tau); + for g in &mut groups { + let m = if g.is_empty() { 0 } else { 1usize << g.len().ilog2() }; + g.truncate(m); + } + groups +} + +/// Filter every plane of `y` over the groups: hard threshold when there is no `pilot`, Wiener shrinkage by it when +/// there is. +fn collaborate(y: &[Vec], pilot: Option<&[Vec]>, groups: &[Vec], t: usize, p: &Params, lambda: f32, tf: &Transform) -> Vec> { + let n = tf.n; + let sigma = p.sigma.max(1e-3); + let lambda = lambda * sigma; + let mut s = Scratch::default(); + let (mut buf, mut pbuf) = (Vec::new(), Vec::new()); + let mut out = Vec::with_capacity(y.len()); + for plane in y { + let mut num = vec![0f32; t * t]; + let mut den = vec![0f32; t * t]; + let c = out.len(); + let pilot_plane = pilot.and_then(|pl| pl.get(c)); + for members in groups { + let m = members.len(); + gather(plane, t, n, members, &mut buf); + group_transform(tf, &mut buf, m, &mut s, true); + let weight = match pilot_plane { + None => { + let mut kept = 0usize; + for v in buf.iter_mut() { + if v.abs() < lambda { + *v = 0.0; + } else { + kept += 1; + } + } + 1.0 / kept.max(1) as f32 + } + Some(pl) => { + gather(pl, t, n, members, &mut pbuf); + group_transform(tf, &mut pbuf, m, &mut s, true); + let mut energy = 0f32; + for (v, &q) in buf.iter_mut().zip(&pbuf) { + let w = q * q / (q * q + sigma * sigma); + *v *= w; + energy += w * w; + } + 1.0 / energy.max(1e-3) + } + }; + group_transform(tf, &mut buf, m, &mut s, false); + for (&pos, blk) in members.iter().zip(buf.chunks_exact(n * n)) { + for (j, row) in blk.chunks_exact(n).enumerate() { + let at = pos as usize + j * t; + let (Some(nu), Some(de)) = (num.get_mut(at..at + n), den.get_mut(at..at + n)) else { continue }; + let win = tf.window.get(j * n..(j + 1) * n).unwrap_or_default(); + for (((nu, de), &v), &w) in nu.iter_mut().zip(de.iter_mut()).zip(row).zip(win) { + *nu += weight * w * v; + *de += weight * w; + } + } + } + } + // cells no block reached keep their value + out.push(num.iter().zip(&den).zip(plane).map(|((&nu, &de), &own)| if de > 0.0 { nu / de } else { own }).collect()); + } + out +} + +/// What a run over tiles of `t` cells uses once the parameters are made safe: shared by every device that runs the filter. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Plan { + pub params: Params, + /// The first step's hard threshold, in noise deviations (before `params.sigma` scales it). + pub lambda: f32, +} + +/// The parameters as they are used for tiles of `t` cells and a photo whose noise has deviation `noise` at mid-grey +/// (white = 1; see [`Params::lambda`]), or `None` when the tiles are smaller than a block (they are then left as they +/// are). +pub fn plan(p: &Params, t: usize, noise: f32) -> Option { + let n = p.block.clamp(2, 16); + if t < n { + return None; + } + let params = Params { block: n, search: p.search.min(t), group: p.group.clamp(1, 64), ..*p }; + Some(Plan { params, lambda: threshold_for(&p.lambda, noise) }) +} + +/// The block-to-block DCT matrix (`n × n`, row `k` is frequency `k`) and the window (`n × n`) the filtered blocks are put +/// back with: the constants the graphics-card version is given so that both use the very same numbers. +pub fn constants(n: usize) -> (Vec, Vec) { + let tf = Transform::new(n.clamp(2, 16)); + (tf.c, tf.window) +} + +/// Denoise four unit-noise planes of `t × t` cells (see the module description); `noise` is the photo's noise at +/// mid-grey, which sets how hard it cleans (see [`Params::lambda`]). +pub fn filter(planes: &[Vec], t: usize, p: &Params, noise: f32) -> Vec> { + let y = hadamard(planes); + let Some(Plan { params: p, lambda }) = plan(p, t, noise) else { return hadamard(&y) }; + if y.len() != 4 || y.iter().any(|pl| pl.len() != t * t) { + return hadamard(&y); + } + let tf = Transform::new(p.block); + let var = p.sigma.max(1e-3).powi(2); + let Some(brightness) = y.first() else { return hadamard(&y) }; + let first = match_blocks(brightness, t, &p, p.tau1 * var); + let basic = collaborate(&y, None, &first, t, &p, lambda, &tf); + if !p.wiener { + return hadamard(&basic); + } + let Some(pilot) = basic.first() else { return hadamard(&basic) }; + let second = match_blocks(pilot, t, &p, p.tau2 * var); + hadamard(&collaborate(&y, Some(&basic), &second, t, &p, lambda, &tf)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The DCT keeps a block's energy, and both it and the Haar transform are undone exactly by their inverses. + #[test] + fn the_dct_and_haar_transforms_invert() { + for n in [2, 4, 8] { + let tf = Transform::new(n); + let block: Vec = (0..n * n).map(|i| (i as f32 * 0.7).sin() * 3.0).collect(); + let (mut b, mut tmp) = (block.clone(), vec![0f32; n * n]); + tf.forward(&mut b, &mut tmp); + let energy = |v: &[f32]| v.iter().map(|x| x * x).sum::(); + assert!((energy(&b) - energy(&block)).abs() < 1e-3, "the DCT keeps energy"); + tf.inverse(&mut b, &mut tmp); + assert!(b.iter().zip(&block).all(|(a, c)| (a - c).abs() < 1e-4)); + } + for m in [1usize, 2, 4, 16] { + let v: Vec = (0..m).map(|i| i as f32 * 0.3 - 1.0).collect(); + let (mut w, mut tmp) = (v.clone(), vec![0f32; m]); + haar_forward(&mut w, &mut tmp); + assert!((w.iter().map(|x| x * x).sum::() - v.iter().map(|x| x * x).sum::()).abs() < 1e-4); + haar_inverse(&mut w, &mut tmp); + assert!(w.iter().zip(&v).all(|(a, c)| (a - c).abs() < 1e-5)); + } + } + + /// Four planes of unit noise (an LCG and Box-Muller, so the tests need no dependency) round `level`. + fn noisy(t: usize, level: f32, seed: u64) -> Vec> { + let mut state = seed; + let mut uniform = move || { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((state >> 40) as f32 + 0.5) / (1u64 << 24) as f32 + }; + (0..4) + .map(|_| { + (0..t * t) + .map(|_| { + let (u, v) = (uniform(), uniform()); + level + (-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos() + }) + .collect() + }) + .collect() + } + + /// The deviation of the planes' values around `level`. + fn spread(planes: &[Vec], level: f32) -> f32 { + let all: Vec = planes.iter().flatten().copied().collect(); + (all.iter().map(|v| (v - level) * (v - level)).sum::() / all.len().max(1) as f32).sqrt() + } + + /// The threshold holds at the ends of the curve, passes through its points and never falls as the noise rises; a + /// noise that is not a number, an empty curve and curves out of order give a value instead of a panic. + #[test] + fn the_threshold_follows_the_noise_and_survives_odd_curves() { + let c = Params::default().lambda; + let at = |n: f32| threshold_for(&c, n); + assert_eq!((at(0.0), at(1.0)), (1.2, 3.5), "the ends hold"); + assert!((at(0.0062) - 1.9).abs() < 1e-4 && (at(0.0152) - 2.65).abs() < 1e-4, "the points are on the curve"); + let mut last = 0.0; + for i in 0..250 { + let v = at(0.001 * 1.04f32.powi(i)); + assert!(v >= last - 1e-6, "the threshold never falls as the noise rises"); + last = v; + } + assert_eq!(at(f32::NAN), 1.2, "a noise that is not a number is the quietest"); + assert_eq!(threshold_for(&[], 0.1), 3.0); + // curves that are out of order, or with numbers that are not numbers, give some value and never panic + for curve in [vec![(0.0, 1.0), (f32::NAN, 2.0), (0.01, 5.0), (0.005, 4.0)], vec![(0.01, 2.0), (0.01, 3.0)], vec![(-1.0, 2.0), (0.0, 3.0)]] { + for n in [0.0, 0.003, 0.02, 1.0, f32::INFINITY] { + assert!(threshold_for(&curve, n).is_finite() || !curve.iter().all(|p| p.1.is_finite())); + } + } + } + + /// Filtering a flat picture of pure noise leaves well under half of the noise's deviation. + #[test] + fn a_flat_noisy_picture_comes_out_much_quieter() { + let t = 48; + let planes = noisy(t, 5.0, 7); + let out = filter(&planes, t, &Params::default(), 0.5); + // the Hadamard transform keeps the level, so what is left of the spread is the noise that got through + assert!(spread(&out, 5.0) < 0.35 * spread(&planes, 5.0), "{} vs {}", spread(&out, 5.0), spread(&planes, 5.0)); + assert!(out.iter().flatten().all(|v| v.is_finite())); + } + + /// A step edge under noise stays a step: a few cells either side of it the values are still near their two levels. + #[test] + fn a_step_edge_stays_sharp() { + let t = 48; + let mut planes = noisy(t, 0.0, 9); + for pl in &mut planes { + for (i, v) in pl.iter_mut().enumerate() { + if i % t >= t / 2 { + *v += 12.0; + } + } + } + let out = filter(&planes, t, &Params::default(), 0.5); + let row = t / 2; + let at = |x: usize| out.iter().map(|pl| pl.get(row * t + x).copied().unwrap_or(0.0)).sum::() / 4.0; + assert!(at(t / 2 - 3) < 2.0 && at(t / 2 + 2) > 10.0, "{} {}", at(t / 2 - 3), at(t / 2 + 2)); + } + + /// Tiny and empty tiles, planes of NaN, a tuning with a zero block, step or group, and no planes at all give finite + /// values or empty planes and never a panic. + #[test] + fn odd_inputs_never_panic() { + // the sizes and values a tile or a caller could hand over + for t in [0usize, 1, 3, 4, 5, 9] { + let planes = noisy(t.max(1), 1.0, 3); + let out = filter(&planes, t, &Params::default(), 0.5); + assert!(out.iter().flatten().all(|v| v.is_finite())); + } + let planes = vec![vec![f32::NAN; 64]; 4]; + let _ = filter(&planes, 8, &Params::default(), 0.5); + let wild = Params { block: 0, step: 0, search: 1000, group: 0, ..Params::default() }; + assert!(filter(&noisy(16, 2.0, 1), 16, &wild, 0.5).iter().flatten().all(|v| v.is_finite())); + assert!(filter(&[], 8, &Params::default(), 0.5).iter().all(|p| p.is_empty())); + } +} diff --git a/crates/denoise-core/src/builtin.rs b/crates/denoise-core/src/builtin.rs new file mode 100644 index 0000000000..268943a722 --- /dev/null +++ b/crates/denoise-core/src/builtin.rs @@ -0,0 +1,679 @@ +//! The built-in denoiser: what AI Denoise runs when no model has been installed, so it works out of the box. +//! +//! It is a [`TileRunner`] with the same contract as a model (four Bayer planes in, camera RGB at twice the plane +//! size out), written from scratch and needing no file: the noise level of the photo is measured from the photo itself +//! (Poisson-Gaussian: variance = a · signal + b; [`estimate_noise`], with a tile's own measure as the fallback), the +//! four planes are cleaned together by block-matching collaborative filtering on variance-stabilised data +//! ([`crate::bm3d`]; the non-local-means filter of [`crate::nlm`] is the fallback), which cleans harder as the noise +//! grows, and the cleaned mosaic is demosaiced with edge-directed green and colour-difference red and blue. + +use crate::bayer::reflect; +use crate::licence::{Commercial, Licence}; +use crate::manifest::{DenoiserManifest, Domain, Gain}; +use crate::nlm::{self, Stabiliser, Tuning}; +use crate::run::{Error, TileRunner}; + +/// Id of the built-in denoiser; no installed model may use it (the models folder is never searched for it). +pub const ID: &str = "builtin"; +/// Changes when the algorithm does, so that cached pictures made by an older one are made again. +pub const VERSION: u32 = 5; +/// Side of its tile, in cells. +pub const TILE: u32 = 256; +/// Cells neighbouring tiles share. +pub const OVERLAP: u32 = 16; + +/// Cells on a side of the blocks the noise level is measured over. +const BLOCK: usize = 16; +/// The smallest variance used, so that a clean tile is left alone instead of divided by zero. +const MIN_VARIANCE: f32 = 1e-10; +/// Blocks with a mean above this (white = 1) may be clipped and say nothing about the noise. +const CLIPPED: f32 = 0.9; + +/// The manifest of the built-in denoiser, as the engine treats an installed model. +pub fn manifest() -> DenoiserManifest { + DenoiserManifest { + id: ID.into(), + name: "Built-in".into(), + version: VERSION.to_string(), + licence: Licence { + name: "MIT OR Apache-2.0".into(), + commercial: Commercial::Yes, + url: None, + notice: "Part of LightCraft: no download, no weights.".into(), + }, + source: None, + sha256: None, + size_bytes: None, + provenance: "Block-matching collaborative filtering with a noise level measured from each photo, written for LightCraft.".into(), + domain: Domain::BayerToRgb, + tile: TILE, + overlap: OVERLAP, + gain: Gain::None, + } +} + +/// The built-in denoiser as a tile runner. +#[derive(Clone, Copy, Debug, Default)] +pub struct Builtin { + /// The noise of the whole photo as `(a, b)`, variance = `a · signal + b` (see [`estimate_noise`]). Without it each + /// tile measures its own, which is rougher and can show as a change of strength between tiles. + pub noise: Option<(f32, f32)>, + pub tuning: Tuning, +} + +impl Builtin { + /// The runner told the photo's noise as `(a, b)`, variance = `a · signal + b` (see [`estimate_noise`]), with the default tuning. + pub fn with_noise(noise: (f32, f32)) -> Self { + Builtin { noise: Some(noise), tuning: Tuning::default() } + } + + /// The block-matching filter's parameters when this one uses it (the only filter with a graphics-card version, see + /// `lightcraft_gpu::bm3d`), else `None`. + pub fn bm3d_params(&self) -> Option { + self.tuning.bm3d + } + + /// [`TileRunner::run`] with the filter stage given: it gets the four variance-stabilised planes (unit noise), their + /// side, and the photo's noise at mid-grey (which sets how strongly to clean, see [`Tuning::strength`]), and returns + /// the cleaned planes. Everything else (measuring the noise, stabilising and its inverse, demosaicing) is shared, so + /// a filter that is the same computation on another device gives the same picture. + pub fn run_with(&self, input: &[f32], filter: &dyn Fn(&[Vec], usize, f32) -> Result>, Error>) -> Result, Error> { + let t = side_of(input.len()).ok_or_else(|| Error::Input("the tile is not four square planes".into()))?; + let clean: Vec = input.iter().map(|v| if v.is_finite() { *v } else { 0.0 }).collect(); + let n = t * t; + let (a, b) = match self.noise { + Some((a, b)) if a.is_finite() && b.is_finite() => (a, b), + _ => noise_model(&clean.chunks_exact(n).collect::>(), t), + }; + let st = Stabiliser::new(a, b); + let stabilised: Vec> = clean.chunks_exact(n).map(|p| p.iter().map(|&v| st.forward(v)).collect()).collect(); + let cleaned = filter(&stabilised, t, (a * 0.18 + b).max(0.0).sqrt())?; + if cleaned.len() != 4 || cleaned.iter().any(|p| p.len() != n) { + return Err(Error::Runtime("the filter returned planes of the wrong size".into())); + } + let planes: Vec> = cleaned.iter().map(|p| p.iter().map(|&v| st.inverse(v)).collect()).collect(); + Ok(demosaic(&planes, t)) + } + + /// The filter stage on the processor. + pub fn filter_on_cpu(&self, stabilised: &[Vec], t: usize, noise: f32) -> Vec> { + match &self.tuning.bm3d { + Some(p) => crate::bm3d::filter(stabilised, t, p, noise), + None => nlm::filter(stabilised, t, &self.tuning, noise), + } + } +} + +impl TileRunner for Builtin { + /// Clean one tile, all on the processor. + fn run(&self, input: &[f32]) -> Result, Error> { + self.run_with(input, &|planes, t, noise| Ok(self.filter_on_cpu(planes, t, noise))) + } +} + +/// The side of the planes of a tile of `len` values, if it is four squares. +fn side_of(len: usize) -> Option { + let per = len / 4; + let t = (per as f64).sqrt().round() as usize; + (len.is_multiple_of(4) && (8..=2048).contains(&t) && t * t == per).then_some(t) +} + +/// Measure the noise of a tile: `(a, b)` with variance = `a · signal + b`. Each block of a plane gives the signal +/// (its mean) and the variance of its cells' difference from their four neighbours (which texture and edges only +/// raise), the lower part of the variances at each brightness is the noise, and a line is fitted through them. +fn noise_model(planes: &[&[f32]], t: usize) -> (f32, f32) { + let mut blocks: Vec<(f32, f32)> = Vec::new(); + for p in planes { + let at = |x: usize, y: usize| p.get(y * t + x).copied().unwrap_or(0.0); + let mut by = 1; + while by + BLOCK < t { + let mut bx = 1; + while bx + BLOCK < t { + let (mut sum, mut sq) = (0f64, 0f64); + for y in by..by + BLOCK { + for x in bx..bx + BLOCK { + let c = at(x, y); + let r = c - 0.25 * (at(x - 1, y) + at(x + 1, y) + at(x, y - 1) + at(x, y + 1)); + sum += f64::from(c); + sq += f64::from(r * r); + } + } + let cells = (BLOCK * BLOCK) as f64; + let mean = (sum / cells) as f32; + // a cell minus the mean of four neighbours has 1.25 times the variance of one + let variance = (sq / cells / 1.25) as f32; + if mean < CLIPPED && mean.is_finite() && variance.is_finite() { + blocks.push((mean, variance)); + } + bx += BLOCK; + } + by += BLOCK; + } + } + fit_noise(blocks) +} + +/// The noise of a whole mosaic as `(a, b)` (variance = `a · signal + b`), measured from the picture itself. +/// +/// Each of the four colour planes (they sit at different levels in a raw, so they are never mixed) is cut into blocks. +/// A block's noise variance is read from a second-difference operator (`[1 -2 1; -2 4 -2; 1 -2 1]`, which cancels flat +/// and smoothly sloping signal and has `36 σ²` of white noise's variance); texture and edges only add to it. At each +/// brightness the quietest few blocks are the noise (a low quantile, divided by the bias of that quantile of pure +/// noise), and a line is fitted through them. A picture with no flat area still reads somewhat high, never low. +pub fn estimate_noise(mosaic: &[f32], width: usize, height: usize) -> (f32, f32) { + estimate_noise_with(mosaic, width, height, &NoiseProbe::default()) +} + +/// [`estimate_noise`], or `None` when the mosaic could not be measured (too small, the wrong size, or no unclipped +/// block): the runner then measures each tile's own noise instead of being told a made-up one. +pub fn measure_noise(mosaic: &[f32], width: usize, height: usize) -> Option<(f32, f32)> { + let noise = estimate_noise(mosaic, width, height); + (noise != (0.0, MIN_VARIANCE)).then_some(noise) +} + +/// What [`estimate_noise_with`] may be tuned by. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct NoiseProbe { + /// Cells on a side of the blocks, in a colour plane. + pub block: usize, + /// Which of a brightness's blocks (by how noisy they look, 0 = the quietest) is taken as the noise. + pub quantile: f32, + /// What that quantile of the variances of noise-only blocks is, as a fraction of their true variance. + pub correction: f32, +} + +impl Default for NoiseProbe { + /// The settings the estimator was calibrated with: 12-cell blocks, the quietest 5 %, and the 0.67 bias of that quantile. + fn default() -> Self { + NoiseProbe { block: 12, quantile: 0.05, correction: 0.67 } + } +} + +/// [`estimate_noise`] with its settings given. +pub fn estimate_noise_with(mosaic: &[f32], width: usize, height: usize, probe: &NoiseProbe) -> (f32, f32) { + let (pw, ph) = (width / 2, height / 2); + let b = probe.block.clamp(6, 64); + if pw < b + 2 || ph < b + 2 || width.checked_mul(height) != Some(mosaic.len()) { + return (0.0, MIN_VARIANCE); + } + let mut blocks: Vec<(f32, f32)> = Vec::new(); + let mut plane = vec![0f32; pw * ph]; + for c in 0..4 { + let (dx, dy) = (c % 2, c / 2); + for (y, row) in plane.chunks_exact_mut(pw).enumerate() { + for (x, v) in row.iter_mut().enumerate() { + *v = mosaic.get((2 * y + dy) * width + 2 * x + dx).copied().unwrap_or(0.0); + } + } + let at = |x: usize, y: usize| plane.get(y * pw + x).copied().unwrap_or(0.0); + let mut by = 1; + while by + b < ph { + let mut bx = 1; + while bx + b < pw { + let (mut sum, mut sq, mut top) = (0f64, 0f64, f32::MIN); + for y in by..by + b { + for x in bx..bx + b { + let m = at(x, y); + let r = 4.0 * m - 2.0 * (at(x - 1, y) + at(x + 1, y) + at(x, y - 1) + at(x, y + 1)) + + (at(x - 1, y - 1) + at(x + 1, y - 1) + at(x - 1, y + 1) + at(x + 1, y + 1)); + sum += f64::from(m); + sq += f64::from(r * r); + top = top.max(m); + } + } + let cells = (b * b) as f64; + let (mean, variance) = ((sum / cells) as f32, (sq / cells / 36.0) as f32); + if top < CLIPPED && mean.is_finite() && variance.is_finite() { + blocks.push((mean, variance)); + } + bx += b; + } + by += b; + } + } + fit_quiet_blocks(blocks, probe.quantile, probe.correction) +} + +/// Fit `variance = a · signal + b` through the `(mean, variance)` of blocks: at each brightness (about 300 blocks of +/// each) the `quantile` of the variances, divided by `correction`, is the noise. +fn fit_quiet_blocks(mut blocks: Vec<(f32, f32)>, quantile: f32, correction: f32) -> (f32, f32) { + if blocks.is_empty() { + return (0.0, MIN_VARIANCE); + } + blocks.sort_by(|x, y| x.0.total_cmp(&y.0)); + let groups = (blocks.len() / 300).clamp(1, 10); + let q = if quantile.is_finite() { quantile.clamp(0.0, 0.5) } else { 0.1 }; + let correction = if correction.is_finite() && correction > 0.05 { correction } else { 1.0 }; + let mut points: Vec<(f64, f64)> = Vec::new(); + for g in 0..groups { + let slice = blocks.get(g * blocks.len() / groups..(g + 1) * blocks.len() / groups).unwrap_or(&[]); + if slice.is_empty() { + continue; + } + let mean = slice.iter().map(|b| f64::from(b.0)).sum::() / slice.len() as f64; + let mut variances: Vec = slice.iter().map(|b| b.1).collect(); + variances.sort_by(f32::total_cmp); + let quiet = variances.get(((variances.len() as f32 * q) as usize).min(variances.len().saturating_sub(1))).copied().unwrap_or(0.0); + points.push((mean, f64::from(quiet / correction))); + } + fit_line(&points) +} + +/// The noise of a whole mosaic as `(a, b)` (variance = `a · signal + b`), from blocks spread over the picture. This is +/// the first version (blocks mix the colour planes, a plain neighbour difference, the lower quarter of the blocks): +/// it reads texture as noise and reports at least about 0.003 at mid-grey whatever the noise. Kept to compare with. +pub fn estimate_noise_v1(mosaic: &[f32], width: usize, height: usize) -> (f32, f32) { + const SIDE: usize = 32; + const MOST_BLOCKS: usize = 6000; + let mut blocks: Vec<(f32, f32)> = Vec::new(); + if width < SIDE + 4 || height < SIDE + 4 || width.checked_mul(height) != Some(mosaic.len()) { + return (0.0, MIN_VARIANCE); + } + let total = (width / SIDE).saturating_mul(height / SIDE); + let skip = (total / MOST_BLOCKS + 1).isqrt().max(1); + let at = |x: usize, y: usize| mosaic.get(y * width + x).copied().unwrap_or(0.0); + let mut by = 2; + while by + SIDE + 2 <= height { + let mut bx = 2; + while bx + SIDE + 2 <= width { + let (mut sum, mut sq) = (0f64, 0f64); + for y in by..by + SIDE { + for x in bx..bx + SIDE { + let c = at(x, y); + // the neighbours of the same colour, two samples away + let r = c - 0.25 * (at(x - 2, y) + at(x + 2, y) + at(x, y - 2) + at(x, y + 2)); + sum += f64::from(c); + sq += f64::from(r * r); + } + } + let cells = (SIDE * SIDE) as f64; + let (mean, variance) = ((sum / cells) as f32, (sq / cells / 1.25) as f32); + if mean < CLIPPED && mean.is_finite() && variance.is_finite() { + blocks.push((mean, variance)); + } + bx += SIDE * skip; + } + by += SIDE * skip; + } + fit_noise(blocks) +} + +/// Fit `variance = a · signal + b` through the `(mean, variance)` of blocks: the quieter part of the variances at +/// each brightness is the noise (texture and edges only raise a block's variance), and a line is fitted through them. +fn fit_noise(mut blocks: Vec<(f32, f32)>) -> (f32, f32) { + if blocks.is_empty() { + return (0.0, MIN_VARIANCE); + } + blocks.sort_by(|x, y| x.0.total_cmp(&y.0)); + let groups = (blocks.len() / 8).clamp(1, 6); + let points: Vec<(f64, f64)> = { + let mut points: Vec<(f64, f64)> = Vec::new(); + for g in 0..groups { + let slice = blocks.get(g * blocks.len() / groups..(g + 1) * blocks.len() / groups).unwrap_or(&[]); + if slice.is_empty() { + continue; + } + let mean = slice.iter().map(|b| f64::from(b.0)).sum::() / slice.len() as f64; + let mut variances: Vec = slice.iter().map(|b| b.1).collect(); + variances.sort_by(f32::total_cmp); + let quiet = variances.get(variances.len() / 4).copied().unwrap_or(0.0); + points.push((mean, f64::from(quiet))); + } + points + }; + fit_line(&points) +} + +/// The line `variance = a · signal + b` through `(signal, variance)` points, with neither `a` nor `b` negative. +fn fit_line(points: &[(f64, f64)]) -> (f32, f32) { + if points.is_empty() { + return (0.0, MIN_VARIANCE); + } + let n = points.len() as f64; + let (sx, sy) = points.iter().fold((0.0, 0.0), |s, p| (s.0 + p.0, s.1 + p.1)); + let (sxx, sxy) = points.iter().fold((0.0, 0.0), |s, p| (s.0 + p.0 * p.0, s.1 + p.0 * p.1)); + let det = n * sxx - sx * sx; + let (mut a, mut b) = + if points.len() >= 2 && det.abs() > 1e-12 { ((n * sxy - sx * sy) / det, (sy - (n * sxy - sx * sy) / det * sx) / n) } else { (0.0, sy / n) }; + if a < 0.0 { + (a, b) = (0.0, sy / n); + } else if b < 0.0 { + (a, b) = (if sxx > 0.0 { sxy / sxx } else { 0.0 }, 0.0); + } + (a.max(0.0) as f32, (b.max(0.0) as f32).max(MIN_VARIANCE)) +} + +/// Demosaic four planes `[R, G1, G2, B]` of an RGGB tile into camera RGB planes `[R, G, B]` of `2t × 2t`. +pub fn demosaic(planes: &[Vec], t: usize) -> Vec { + let s = 2 * t; + let si = s as isize; + // the mosaic: R at (even, even), G1 at (odd, even), G2 at (even, odd), B at (odd, odd) + let mut m = vec![0f32; s * s]; + for (p, plane) in planes.iter().enumerate() { + let (dx, dy) = (p % 2, p / 2); + for cy in 0..t { + for cx in 0..t { + if let (Some(dst), Some(v)) = (m.get_mut((2 * cy + dy) * s + 2 * cx + dx), plane.get(cy * t + cx)) { + *dst = *v; + } + } + } + } + let at = |x: isize, y: isize| m.get(reflect(y, s) * s + reflect(x, s)).copied().unwrap_or(0.0); + // green everywhere: measured where there is a green sample, else interpolated along the smoother direction + let mut g = vec![0f32; s * s]; + for y in 0..si { + for x in 0..si { + let v = if (x + y) % 2 == 1 { + at(x, y) + } else { + let c = at(x, y); + let (l, r, u, d) = (at(x - 1, y), at(x + 1, y), at(x, y - 1), at(x, y + 1)); + let (gh, gv) = + ((l + r) / 2.0 + (2.0 * c - at(x - 2, y) - at(x + 2, y)) / 4.0, (u + d) / 2.0 + (2.0 * c - at(x, y - 2) - at(x, y + 2)) / 4.0); + let (dh, dv) = + ((l - r).abs() + (2.0 * c - at(x - 2, y) - at(x + 2, y)).abs(), (u - d).abs() + (2.0 * c - at(x, y - 2) - at(x, y + 2)).abs()); + let est = if dh < dv { + gh + } else if dv < dh { + gv + } else { + (gh + gv) / 2.0 + }; + est.clamp(l.min(r).min(u).min(d), l.max(r).max(u).max(d)) + }; + if let Some(dst) = g.get_mut(y as usize * s + x as usize) { + *dst = v; + } + } + } + let gat = |x: isize, y: isize| g.get(reflect(y, s) * s + reflect(x, s)).copied().unwrap_or(0.0); + // red and blue: the difference from green is smooth, so interpolate it from the nearest samples of the colour + let chroma = |px: isize, py: isize| -> Vec { + let diff = |x: isize, y: isize| at(x, y) - gat(x, y); + let mut out = vec![0f32; s * s]; + for y in 0..si { + for x in 0..si { + let (col, row) = (x % 2 == px, y % 2 == py); + let d = match (col, row) { + (true, true) => diff(x, y), + (false, true) => (diff(x - 1, y) + diff(x + 1, y)) / 2.0, + (true, false) => (diff(x, y - 1) + diff(x, y + 1)) / 2.0, + (false, false) => (diff(x - 1, y - 1) + diff(x + 1, y - 1) + diff(x - 1, y + 1) + diff(x + 1, y + 1)) / 4.0, + }; + if let Some(dst) = out.get_mut(y as usize * s + x as usize) { + *dst = d + gat(x, y); + } + } + } + out + }; + let mut out = chroma(0, 0); + out.extend_from_slice(&g); + out.extend(chroma(1, 1)); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Deterministic standard normal numbers. + struct Noise(u64); + + impl Noise { + /// The next uniform number, strictly between 0 and 1. + fn uniform(&mut self) -> f32 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((self.0 >> 40) as f32 + 0.5) / (1u64 << 24) as f32 + } + + /// The next standard normal number (Box-Muller). + fn normal(&mut self) -> f32 { + let (u, v) = (self.uniform(), self.uniform()); + (-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos() + } + } + + /// A scene of camera RGB with an edge and a gradient, `s × s`. + fn scene(s: usize) -> [Vec; 3] { + let mut out = [vec![0f32; s * s], vec![0f32; s * s], vec![0f32; s * s]]; + for y in 0..s { + for x in 0..s { + let base = 0.15 + 0.5 * x as f32 / s as f32; + let step = if y > s / 2 { 0.2 } else { 0.0 }; + for (c, plane) in out.iter_mut().enumerate() { + plane[y * s + x] = base + step * (1.0 + c as f32 * 0.3) / 1.6; + } + } + } + out + } + + /// The scene's RGGB mosaic with noise of variance `a · signal + b`, as the four planes a tile has. + fn mosaic_planes(truth: &[Vec; 3], t: usize, a: f32, b: f32, seed: u64) -> Vec { + let s = 2 * t; + let mut rng = Noise(seed); + let mut planes = vec![0f32; 4 * t * t]; + for (p, &(dx, dy)) in [(0, 0), (1, 0), (0, 1), (1, 1)].iter().enumerate() { + let c = [0, 1, 1, 2][p]; + for cy in 0..t { + for cx in 0..t { + let v = truth[c][(2 * cy + dy) * s + 2 * cx + dx]; + planes[p * t * t + cy * t + cx] = v + rng.normal() * (a * v + b).sqrt(); + } + } + } + planes + } + + /// Mean squared error of an RGB result against the scene, away from the tile's edges. + fn error(out: &[f32], truth: &[Vec; 3], s: usize) -> f64 { + let (mut sum, mut n) = (0f64, 0f64); + for (c, plane) in truth.iter().enumerate() { + for y in 12..s - 12 { + for x in 12..s - 12 { + let d = f64::from(out[c * s * s + y * s + x] - plane[y * s + x]); + sum += d * d; + n += 1.0; + } + } + } + sum / n + } + + /// A noisy tile comes out at least five times closer to the scene (squared error) than a plain demosaic of it. + #[test] + fn a_noisy_tile_comes_out_much_closer_to_the_scene_than_a_plain_demosaic() { + let (t, a, b) = (64, 0.004, 0.0004); + let truth = scene(2 * t); + let input = mosaic_planes(&truth, t, a, b, 7); + let planes: Vec> = input.chunks_exact(t * t).map(<[f32]>::to_vec).collect(); + let plain = error(&demosaic(&planes, t), &truth, 2 * t); + let cleaned = error(&Builtin::default().run(&input).unwrap(), &truth, 2 * t); + assert!(cleaned < plain / 5.0, "plain {plain}, cleaned {cleaned}"); + } + + /// A tile with no noise is demosaiced almost exactly, and the step between two rows of its scene survives. + #[test] + fn a_noise_free_tile_is_demosaiced_without_blurring_its_edge() { + let t = 64; + let truth = scene(2 * t); + let input = mosaic_planes(&truth, t, 0.0, 0.0, 1); + let out = Builtin::default().run(&input).unwrap(); + assert!(error(&out, &truth, 2 * t) < 2e-5); + // the step between rows 63 and 65 survives + let s = 2 * t; + let (above, below) = (out[s * (s / 2 - 2) + s / 2], out[s * (s / 2 + 2) + s / 2]); + assert!(below - above > 0.9 * 0.2 / 1.6, "{above} {below}"); + } + + /// The tile's own noise model finds the added noise within 30 % at two brightness levels. + #[test] + fn the_noise_level_is_found_from_the_tile() { + let (t, a, b) = (128, 0.004, 0.0004); + let truth = scene(2 * t); + let input = mosaic_planes(&truth, t, a, b, 3); + let planes: Vec<&[f32]> = input.chunks_exact(t * t).collect(); + let (ea, eb) = noise_model(&planes, t); + for signal in [0.2f32, 0.5] { + let (want, got) = (a * signal + b, ea * signal + eb); + assert!((got / want - 1.0).abs() < 0.3, "at {signal}: {got} against {want}"); + } + } + + /// Black, mid-grey and fully clipped tiles give finite results that stay at their level. + #[test] + fn flat_dark_and_clipped_tiles_do_not_break_it() { + let t = 32; + for v in [0.0f32, 0.5, 1.0] { + let out = Builtin::default().run(&vec![v; 4 * t * t]).unwrap(); + assert_eq!(out.len(), 3 * 4 * t * t); + assert!(out.iter().all(|x| x.is_finite() && (x - v).abs() < 1e-4), "{v}"); + } + } + + /// Empty tiles and tiles that are not four squares are errors; NaN and infinite values in a tile are cleaned up. + #[test] + fn bad_tiles_are_errors_and_bad_numbers_are_cleaned_up() { + assert!(Builtin::default().run(&[]).is_err()); + assert!(Builtin::default().run(&[0.0; 30]).is_err()); + assert!(Builtin::default().run(&vec![0.0; 4 * 9 * 10]).is_err()); + let mut input = vec![0.3f32; 4 * 16 * 16]; + input[5] = f32::NAN; + input[77] = f32::INFINITY; + assert!(Builtin::default().run(&input).unwrap().iter().all(|v| v.is_finite())); + } + + /// The whole-mosaic estimate finds the added noise within 25 %; a mosaic that is too small or not the size it says + /// gets the minimum variance instead of a panic. + #[test] + fn the_noise_of_a_whole_mosaic_is_found_and_hostile_mosaics_are_refused() { + let (s, a, b) = (384, 0.01f32, 0.0005f32); + let truth = scene(s); + let mut rng = Noise(5); + let mosaic: Vec = (0..s * s) + .map(|i| { + let (x, y) = (i % s, i / s); + let v = truth[[0, 1, 1, 2][(y % 2) * 2 + x % 2]][i]; + v + rng.normal() * (a * v + b).sqrt() + }) + .collect(); + let (ea, eb) = estimate_noise(&mosaic, s, s); + for signal in [0.2f32, 0.5] { + let (want, got) = (a * signal + b, ea * signal + eb); + assert!((got / want - 1.0).abs() < 0.25, "at {signal}: {got} against {want}"); + } + // too small, or not the size it says: no estimate, and no panic + assert_eq!(estimate_noise(&mosaic, 10, 10).1, MIN_VARIANCE); + assert_eq!(estimate_noise(&mosaic, s, s - 1).1, MIN_VARIANCE); + assert_eq!(estimate_noise(&[], 0, 0).1, MIN_VARIANCE); + assert_eq!(measure_noise(&[], 0, 0), None, "a mosaic that cannot be measured has no noise to tell the runner"); + assert_eq!(measure_noise(&mosaic, 10, 10), None); + assert!(measure_noise(&mosaic, s, s).is_some()); + assert_eq!(estimate_noise(&mosaic, usize::MAX, usize::MAX).1, MIN_VARIANCE); + } + + /// A 640 x 640 mosaic: a smooth slope (dark at the top, bright at the bottom), texture (fine lines, edges) over its + /// left part and flat over the rest, with noise of variance `a · signal + b` added. + fn textured_and_flat(a: f32, b: f32, flat_from: usize, seed: u64) -> Vec { + let s = 640; + let mut rng = Noise(seed); + (0..s * s) + .map(|i| { + let (x, y) = (i % s, i / s); + let slope = 0.02 + 0.6 * y as f32 / s as f32 + 0.1 * x as f32 / s as f32; + let texture = if x < flat_from { + 0.04 * ((x as f32 * 1.3).sin() + (y as f32 * 0.9).sin()) + if (x / 9 + y / 7) % 2 == 0 { 0.05 } else { 0.0 } + } else { + 0.0 + }; + let v = (slope + texture).max(0.0); + v + rng.normal() * (a * v + b).sqrt() + }) + .collect() + } + + /// With texture over most of the picture and a flat strip beside it, the estimate follows the strip's noise within + /// 25 % (in deviation), where the first version read the texture as several times too much. + #[test] + fn the_noise_is_read_from_the_flat_areas_and_not_from_the_texture_beside_them() { + let (a, b) = (5e-4f32, 1e-6f32); + // texture over the left 70 % and flat over the rest: the flat part is what shows the noise + let mosaic = textured_and_flat(a, b, 450, 7); + let (ea, eb) = estimate_noise(&mosaic, 640, 640); + for signal in [0.1f32, 0.2, 0.4] { + let (want, got) = ((a * signal + b).sqrt(), (ea * signal + eb).sqrt()); + assert!((got / want - 1.0).abs() < 0.25, "the deviation at {signal}: {got} against {want}"); + } + // the first version read the texture as noise (several times too much); this one is far closer + let old = estimate_noise_v1(&mosaic, 640, 640); + assert!(((old.0 * 0.2 + old.1) / (a * 0.2 + b)).sqrt() > 1.4, "the first version is the thing this one improves on"); + } + + /// A picture that is all texture is read as noisier than it is, never as meaningfully quieter. + #[test] + fn a_picture_with_no_flat_area_reads_noisier_than_it_is_never_quieter() { + let (a, b) = (5e-4f32, 1e-6f32); + let mosaic = textured_and_flat(a, b, 640, 9); + let (ea, eb) = estimate_noise(&mosaic, 640, 640); + for signal in [0.1f32, 0.3] { + assert!(ea * signal + eb >= 0.9 * (a * signal + b), "at {signal}: {} against {}", ea * signal + eb, a * signal + b); + } + } + + /// Black, fully clipped and NaN mosaics, and a nonsensical probe setting, give finite numbers and no panic. + #[test] + fn a_clipped_or_all_dark_mosaic_is_measured_without_a_panic() { + for level in [0.0f32, 1.0, f32::NAN] { + let mosaic = vec![level; 200 * 200]; + let (a, b) = estimate_noise(&mosaic, 200, 200); + assert!(a.is_finite() && b.is_finite() && a >= 0.0 && b > 0.0, "{level}: {a} {b}"); + } + let probe = NoiseProbe { block: 0, quantile: f32::NAN, correction: -1.0 }; + let (a, b) = estimate_noise_with(&vec![0.3; 200 * 200], 200, 200, &probe); + assert!(a.is_finite() && b.is_finite()); + } + + /// A heavily noisy tile is cleaned to under an eighth of a plain demosaic's error, whether the runner measures the + /// noise itself or is told it. + #[test] + fn a_heavily_noisy_tile_is_cleaned_far_more_than_a_plain_demosaic_and_by_the_photos_noise() { + let (t, a, b) = (64, 0.03, 0.004); + let truth = scene(2 * t); + let input = mosaic_planes(&truth, t, a, b, 9); + let planes: Vec> = input.chunks_exact(t * t).map(<[f32]>::to_vec).collect(); + let plain = error(&demosaic(&planes, t), &truth, 2 * t); + let own = error(&Builtin::default().run(&input).unwrap(), &truth, 2 * t); + let told = error(&Builtin::with_noise((a, b)).run(&input).unwrap(), &truth, 2 * t); + assert!(own < plain / 8.0 && told < plain / 8.0, "plain {plain}, own {own}, told {told}"); + } + + /// Noise values that are not numbers fall back to the tile's own measurement; a tuning with no search, and the + /// non-local-means fallback, still give finite pictures; and the strength rises with the noise from 0 to 1. + #[test] + fn noise_values_that_are_not_numbers_fall_back_to_the_tiles_own_and_the_strength_follows_the_noise() { + let t = 32; + let input = vec![0.3f32; 4 * t * t]; + for bad in [(f32::NAN, 1e-3), (0.01, f32::INFINITY), (-1.0, -1.0)] { + let out = Builtin { noise: Some(bad), tuning: Tuning::default() }.run(&input).unwrap(); + assert!(out.iter().all(|v| v.is_finite()), "{bad:?}"); + } + // no search at all is a plain demosaic, not a crash + let none = Builtin { noise: Some((0.01, 1e-3)), tuning: Tuning { search: 0, search2: 0, bm3d: None, ..Tuning::default() } }; + assert!(none.run(&input).unwrap().iter().all(|v| v.is_finite())); + let nlm = Builtin { noise: Some((0.01, 1e-3)), tuning: Tuning { bm3d: None, ..Tuning::default() } }; + assert!(nlm.run(&input).unwrap().iter().all(|v| v.is_finite())); + let tune = Tuning::default(); + let ramp: Vec = [0.0, 0.02, 0.05, 0.1, 0.2].iter().map(|&n| tune.strength(n)).collect(); + assert!(ramp.windows(2).all(|w| w[0] <= w[1]) && ramp[0] == 0.0 && ramp[4] == 1.0, "{ramp:?}"); + } + + /// The built-in denoiser's manifest passes the manifest check and carries the tile and overlap the runner uses. + #[test] + fn its_manifest_is_valid() { + let m = manifest(); + crate::manifest::validate(&m).unwrap(); + assert_eq!((m.tile, m.overlap), (TILE, OVERLAP)); + } +} diff --git a/crates/denoise-core/src/lib.rs b/crates/denoise-core/src/lib.rs index 568ed9f8ec..1537b96893 100644 --- a/crates/denoise-core/src/lib.rs +++ b/crates/denoise-core/src/lib.rs @@ -4,10 +4,13 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod archive; pub mod bayer; +pub mod bm3d; +pub mod builtin; pub mod hash; pub mod known; pub mod licence; pub mod manifest; +pub mod nlm; pub mod product; pub mod run; pub mod tiles; diff --git a/crates/denoise-core/src/nlm.rs b/crates/denoise-core/src/nlm.rs new file mode 100644 index 0000000000..ed18377263 --- /dev/null +++ b/crates/denoise-core/src/nlm.rs @@ -0,0 +1,416 @@ +//! The built-in denoiser's filter: variance stabilisation and a non-local-means average whose weights come from all +//! four colour planes of a tile at once, so the planes are cleaned together instead of each on its own. +//! +//! Noise in a raw file has variance `a · signal + b`. The generalised Anscombe transform ([`Stabiliser`]) turns that +//! into noise of variance 1 everywhere, so one threshold fits every brightness. The four planes are then rotated +//! (a Hadamard transform, which keeps unit noise) into a brightness plane and three colour-difference planes. +//! Each cell becomes the average of the cells around it whose patch, over all four planes, looks like its own +//! within the noise, in two passes: the second finds matches on the first pass's much cleaner picture, so it can +//! look further and keep finer detail. + +use crate::bayer::reflect; + +/// What the filter may be tuned by (the defaults are what the built-in denoiser uses). +/// +/// How strongly a photo is cleaned follows its noise, measured as the standard deviation at mid-grey (0.18, white = 1): +/// below `light` it is cleaned gently and in one pass, above `heavy` as hard as the filter goes, and in between smoothly. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Tuning { + /// Search window radius, in cells, of the first pass. + pub search: usize, + /// Search window radius of the second pass, which finds matches on the first pass's cleaner picture; 0 skips it. + pub search2: usize, + /// How far above the noise two patches may differ and still be averaged in the first pass (larger blurs more), + /// for a light and for a heavily noisy photo. + pub h_light: f32, + pub h_heavy: f32, + /// The same for the second pass, which is blended in as the noise grows. + pub h2: f32, + /// Noise at mid-grey where the stronger settings start and where they are in full. + pub light: f32, + pub heavy: f32, + /// Search radius and threshold of the colour-difference planes' own pass, guided by the cleaned brightness + /// plane (colour noise is the cheapest to remove without losing texture); radius 0 skips it. + pub search_c: usize, + pub h_c: f32, + /// Patch radius (a patch is `2 · half + 1` cells on a side) of the first and of the later passes. + pub half: usize, + pub half2: usize, + /// How much looser (a multiple of the threshold) the average is that cells with few matching patches lean on in + /// the first pass; 0 turns it off. + pub loose: f32, + /// The matched weight below which they lean on it, in a heavily noisy photo (scaled down with the noise). + pub few: f32, + /// Block-matching collaborative filtering ([`crate::bm3d`]) is what cleans the planes; with `None` the non-local-means + /// averages above do (their settings apply only then). + pub bm3d: Option, +} + +impl Default for Tuning { + /// The built-in denoiser's tuning: block matching on, and the non-local-means settings it falls back to when that is off. + fn default() -> Self { + Tuning { + search: 3, + search2: 5, + h_light: 0.3, + h_heavy: 0.45, + h2: 0.1, + light: 0.03, + heavy: 0.14, + search_c: 7, + h_c: 1.0, + half: 1, + half2: 1, + loose: 4.0, + few: 0.6, + bm3d: Some(crate::bm3d::Params::default()), + } + } +} + +impl Tuning { + /// 0 for a lightly noisy photo up to 1 for a heavily noisy one. + pub fn strength(&self, noise: f32) -> f32 { + let span = (self.heavy - self.light).max(1e-6); + let x = ((noise - self.light) / span).clamp(0.0, 1.0); + x * x * (3.0 - 2.0 * x) + } +} + +/// The generalised Anscombe transform for noise of variance `a · v + b`. +#[derive(Clone, Copy, Debug)] +pub struct Stabiliser { + a: f32, + b: f32, +} + +/// Below this the noise has no signal-dependent part worth modelling. +const MIN_GAIN: f32 = 1e-6; + +impl Stabiliser { + /// The transform for noise of variance `a · signal + b`; a gain or offset that is not a number counts as none. + pub fn new(a: f32, b: f32) -> Self { + Stabiliser { a: if a.is_finite() { a.max(0.0) } else { 0.0 }, b: if b.is_finite() { b.max(1e-12) } else { 1e-12 } } + } + + /// A value as a signal with unit noise deviation (a plain scaling when the noise has no signal-dependent part). + pub fn forward(self, v: f32) -> f32 { + if self.a < MIN_GAIN { + return v / self.b.sqrt(); + } + let x = (v + self.b / self.a) / self.a; + 2.0 * (x + 0.375).max(0.0).sqrt() + } + + /// The inverse, with the correction for the bias a plain inverse has on averaged data. + pub fn inverse(self, y: f32) -> f32 { + if self.a < MIN_GAIN { + return y * self.b.sqrt(); + } + let x = if y >= 1.5 { + let (i1, i2) = (1.0 / y, 1.0 / (y * y)); + y * y / 4.0 + 0.25 * 1.5f32.sqrt() * i1 - 11.0 / 8.0 * i2 + 5.0 / 8.0 * 1.5f32.sqrt() * i2 * i1 - 0.125 + } else { + y * y / 4.0 - 0.375 + }; + self.a * x - self.b / self.a + } +} + +/// The orthonormal 4 × 4 Hadamard transform across four planes (its own inverse). +pub fn hadamard(p: &[Vec]) -> Vec> { + let n = p.first().map_or(0, Vec::len); + let mut out = vec![vec![0f32; n]; 4]; + for i in 0..n { + let g = |c: usize| p.get(c).and_then(|v| v.get(i)).copied().unwrap_or(0.0); + let (r, g1, g2, b) = (g(0), g(1), g(2), g(3)); + let vals = [(r + g1 + g2 + b) / 2.0, (r - g1 + g2 - b) / 2.0, (r + g1 - g2 - b) / 2.0, (r - g1 - g2 + b) / 2.0]; + for (c, v) in vals.into_iter().enumerate() { + if let Some(o) = out.get_mut(c).and_then(|o| o.get_mut(i)) { + *o = v; + } + } + } + out +} + +/// A plane with `pad` cells mirrored round every edge (`t + 2 · pad` on a side). +fn padded(src: &[f32], t: usize, pad: usize) -> Vec { + let wd = t + 2 * pad; + let mut out = vec![0f32; wd * wd]; + for y in 0..wd { + let sy = reflect(y as isize - pad as isize, t); + for x in 0..wd { + let sx = reflect(x as isize - pad as isize, t); + if let (Some(o), Some(v)) = (out.get_mut(y * wd + x), src.get(sy * t + sx)) { + *o = *v; + } + } + } + out +} + +/// What one [`pass`] is run with. +#[derive(Clone, Copy)] +struct Pass { + /// Search window radius and patch radius, in cells. + radius: usize, + half: usize, + /// The threshold and the floor of the weights (see [`pass`]). + h: f32, + floor: f32, + /// A second, looser average (threshold `h · loose`) that cells with few matches lean on, so a cell no patch + /// resembles is not left as it was; 0 turns it off. + loose: f32, + /// Matched weight below which a cell starts to lean on that looser average. + few: f32, +} + +/// One pass: every cell becomes the weighted average of the cells within `radius` whose patch (`2 · half + 1` cells +/// on a side), over all planes, is like its own. `guide` holds the planes the patches are compared on, `data` the +/// planes that are averaged (the same ones in the first pass). Weights are `exp(-(excess) / h)`, `excess` being how +/// far the mean squared difference of the patches is above `floor` (what two noisy views of one signal give). +fn pass(guide: &[Vec], data: &[Vec], t: usize, p: &Pass) -> Vec> { + let Pass { radius, half, h, floor, loose, few } = *p; + let pad = radius + half; + let wd = t + 2 * pad; + let guide: Vec> = guide.iter().map(|p| padded(p, t, pad)).collect(); + let data: Vec> = data.iter().map(|p| padded(p, t, pad)).collect(); + let (n, region, span) = (t * t, t + 2 * half, 2 * half + 1); + let planes = data.len().max(1); + let mut num = vec![vec![0f32; n]; planes]; + let mut den = vec![0f32; n]; + let mut num_l = vec![vec![0f32; n]; if loose > 0.0 { planes } else { 0 }]; + let mut den_l = vec![0f32; if loose > 0.0 { n } else { 0 }]; + let (mut d, mut rows) = (vec![0f32; region * region], vec![0f32; region * t]); + let norm = 1.0 / ((span * span) as f32 * guide.len().max(1) as f32); + let r = radius as isize; + for oy in -r..=r { + for ox in -r..=r { + if ox == 0 && oy == 0 { + continue; + } + let shift = oy * wd as isize + ox; + // squared differences over the planes, for the cells and the ring round them the patch reaches + for j in 0..region { + let base = (j + pad - half) * wd + pad - half; + for i in 0..region { + let pos = base + i; + let other = (pos as isize + shift) as usize; + let mut s = 0f32; + for p in &guide { + let (a, b) = (p.get(pos).copied().unwrap_or(0.0), p.get(other).copied().unwrap_or(0.0)); + s += (a - b) * (a - b); + } + if let Some(v) = d.get_mut(j * region + i) { + *v = s; + } + } + } + // the sum over each cell's patch: along rows, then down columns + for j in 0..region { + for x in 0..t { + let k = j * region + x; + let s: f32 = (0..span).map(|i| d.get(k + i).copied().unwrap_or(0.0)).sum(); + if let Some(v) = rows.get_mut(j * t + x) { + *v = s; + } + } + } + for y in 0..t { + for x in 0..t { + let k = y * t + x; + let patch = (0..span).map(|j| rows.get(k + j * t).copied().unwrap_or(0.0)).sum::() * norm; + let excess = (patch - floor).max(0.0); + let wide = if loose > 0.0 { loose } else { 1.0 }; + // beyond this the weight is below 5e-5: not worth the exponential and the sums + if excess > 10.0 * h * wide { + continue; + } + let pos = (y + pad) * wd + x + pad; + let other = (pos as isize + shift) as usize; + if excess <= 10.0 * h { + let w = (-excess / h).exp(); + if let Some(dn) = den.get_mut(k) { + *dn += w; + } + for (nu, p) in num.iter_mut().zip(&data) { + if let (Some(nu), Some(v)) = (nu.get_mut(k), p.get(other)) { + *nu += w * v; + } + } + } + if loose > 0.0 { + let w = (-excess / (h * loose)).exp(); + if let Some(dn) = den_l.get_mut(k) { + *dn += w; + } + for (nu, p) in num_l.iter_mut().zip(&data) { + if let (Some(nu), Some(v)) = (nu.get_mut(k), p.get(other)) { + *nu += w * v; + } + } + } + } + } + } + } + // the cell itself counts as much as a perfect match + let mut out = vec![vec![0f32; n]; planes]; + for (c, (o, (nu, p))) in out.iter_mut().zip(num.iter().zip(&data)).enumerate() { + for k in 0..n { + let own = p.get((k / t + pad) * wd + k % t + pad).copied().unwrap_or(0.0); + if let (Some(o), Some(nu), Some(dn)) = (o.get_mut(k), nu.get(k), den.get(k)) { + let tight = (nu + own) / (dn + 1.0); + *o = match (num_l.get(c).and_then(|v| v.get(k)), den_l.get(k)) { + (Some(nl), Some(dl)) => { + let loose = (nl + own) / (dl + 1.0); + let lean = if few > 0.0 { few / (dn + few) } else { 0.0 }; + tight + (loose - tight) * lean + } + _ => tight, + }; + } + } + } + out +} + +/// Denoise four unit-noise planes of `t × t` cells (see the module description); `noise` is the photo's noise at +/// mid-grey, which sets how strongly (see [`Tuning`]). +pub fn filter(planes: &[Vec], t: usize, tune: &Tuning, noise: f32) -> Vec> { + let y = hadamard(planes); + let k = tune.strength(if noise.is_finite() { noise } else { 0.0 }); + // two noisy views of one signal differ by 2 in mean square: the floor the excess is counted from + let h1 = tune.h_light + (tune.h_heavy - tune.h_light) * k; + let first = pass(&y, &y, t, &Pass { radius: tune.search, half: tune.half, h: h1, floor: 2.0, loose: tune.loose, few: tune.few * k }); + if tune.search2 == 0 || k <= 0.0 { + return hadamard(&first); + } + // the first pass's picture still carries a little noise (of unknown size), so the floor is 0 and the threshold + // alone decides + let second = pass(&first, &y, t, &Pass { radius: tune.search2, half: tune.half2, h: tune.h2, floor: 0.0, loose: 0.0, few: 0.0 }); + let mut blended: Vec> = first.iter().zip(&second).map(|(f, s)| f.iter().zip(s).map(|(f, s)| f + (s - f) * k).collect()).collect(); + if tune.search_c > 0 { + // matches found on the cleaned brightness plane alone, so colour is only averaged across like brightness + let guide = blended.get(..1).unwrap_or_default(); + let colour = pass( + guide, + y.get(1..).unwrap_or_default(), + t, + &Pass { radius: tune.search_c, half: tune.half2, h: tune.h_c, floor: 0.0, loose: 0.0, few: 0.0 }, + ); + for (b, c) in blended.iter_mut().skip(1).zip(&colour) { + for (b, c) in b.iter_mut().zip(c) { + *b += (c - *b) * k; + } + } + } + hadamard(&blended) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The transform is undone by its inverse within a little, a step of one noise deviation is a step of about 1 + /// whatever the brightness, and with no signal-dependent noise it is a plain scaling. + #[test] + fn the_stabiliser_round_trips_and_gives_unit_noise() { + let s = Stabiliser::new(0.01, 0.0005); + for v in [0.0f32, 0.01, 0.1, 0.5, 0.9] { + let back = s.inverse(s.forward(v)); + assert!((back - v).abs() < 0.005 + 0.03 * v, "{v} -> {back}"); + } + // a step of one standard deviation is a step of about 1 whatever the brightness + for v in [0.05f32, 0.2, 0.6] { + let sigma = (0.01 * v + 0.0005).sqrt(); + let step = s.forward(v + sigma) - s.forward(v); + assert!((step - 1.0).abs() < 0.15, "at {v}: {step}"); + } + let flat = Stabiliser::new(0.0, 4e-4); + assert!((flat.forward(0.1) - 5.0).abs() < 1e-4 && (flat.inverse(5.0) - 0.1).abs() < 1e-6); + } + + /// The Hadamard transform applied twice gives the planes back, and it keeps their energy. + #[test] + fn the_hadamard_transform_is_its_own_inverse_and_keeps_energy() { + let planes: Vec> = (0..4).map(|c| (0..9).map(|i| (c * 9 + i) as f32 * 0.37 - 3.0).collect()).collect(); + let back = hadamard(&hadamard(&planes)); + for (a, b) in planes.iter().flatten().zip(back.iter().flatten()) { + assert!((a - b).abs() < 1e-4); + } + let energy = |p: &[Vec]| p.iter().flatten().map(|v| v * v).sum::(); + assert!((energy(&planes) - energy(&hadamard(&planes))).abs() < 1e-2); + } + + /// Four planes of unit noise (an LCG and Box-Muller, so the tests need no dependency) round `level`. + fn noisy(t: usize, level: f32, seed: u64) -> Vec> { + let mut state = seed; + let mut uniform = move || { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((state >> 40) as f32 + 0.5) / (1u64 << 24) as f32 + }; + (0..4) + .map(|_| { + (0..t * t) + .map(|_| { + let (u, v) = (uniform(), uniform()); + level + (-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos() + }) + .collect() + }) + .collect() + } + + /// The deviation of the planes' values around `level`. + fn spread(planes: &[Vec], level: f32) -> f32 { + let all: Vec = planes.iter().flatten().copied().collect(); + (all.iter().map(|v| (v - level) * (v - level)).sum::() / all.len().max(1) as f32).sqrt() + } + + /// The colour planes' own pass leaves less noise than brightness alone would, and takes unit noise well below 0.5. + #[test] + fn the_colour_pass_cleans_colour_planes_further_than_brightness_alone_would() { + let (t, noise) = (40, 0.2); + let planes = noisy(t, 5.0, 3); + let with = filter(&planes, t, &Tuning::default(), noise); + let without = filter(&planes, t, &Tuning { search_c: 0, ..Tuning::default() }, noise); + // after the Hadamard rotation the colour differences are planes 1..4 of the mixed result, so compare it all + assert!(spread(&with, 5.0) < spread(&without, 5.0), "{} vs {}", spread(&with, 5.0), spread(&without, 5.0)); + assert!(spread(&with, 5.0) < 0.5, "unit noise should drop well below 0.5: {}", spread(&with, 5.0)); + } + + /// A cell far from its surroundings, which no patch resembles, ends up nearer to them with the looser average than without it. + #[test] + fn a_cell_no_patch_resembles_is_not_left_as_a_speck_in_heavy_noise() { + let (t, noise) = (40, 0.2); + let mut planes = noisy(t, 5.0, 9); + // one cell far from its surroundings in every plane: nothing matches it + let at = (t / 2) * t + t / 2; + for p in &mut planes { + if let Some(v) = p.get_mut(at) { + *v += 6.0; + } + } + let with = filter(&planes, t, &Tuning::default(), noise); + let without = filter(&planes, t, &Tuning { loose: 0.0, ..Tuning::default() }, noise); + let peak = |planes: &[Vec]| planes.iter().filter_map(|p| p.get(at)).map(|v| (v - 5.0).abs()).fold(0f32, f32::max); + assert!(peak(&with) < peak(&without), "{} vs {}", peak(&with), peak(&without)); + } + + /// Noise of 0, NaN or next to nothing, with one cell far from the rest, still gives finite values. + #[test] + fn a_photo_with_no_measured_noise_stays_finite_even_with_an_odd_cell() { + let t = 24; + let mut planes = noisy(t, 5.0, 5); + for p in &mut planes { + if let Some(v) = p.get_mut(t * t / 2) { + *v += 50.0; + } + } + for noise in [0.0, f32::NAN, 1e-9] { + assert!(filter(&planes, t, &Tuning::default(), noise).iter().flatten().all(|v| v.is_finite()), "noise {noise}"); + } + } +} diff --git a/crates/denoise/README.md b/crates/denoise/README.md index 0397193f69..3ea0b288af 100644 --- a/crates/denoise/README.md +++ b/crates/denoise/README.md @@ -1,6 +1,6 @@ # lightcraft-denoise -L1 pure-Rust AI RAW denoise primitives and CPU inference. No weights are bundled. +L1 pure-Rust AI RAW denoise primitives and CPU inference. No weights are bundled; `lightcraft_denoise_core::builtin` is the model-free denoiser used by default. See [user workflow and limitations](../../docs/denoise.md). `lightcraft-denoise-core` provides metadata, Bayer helpers and cache formats, diff --git a/crates/develop/src/lib.rs b/crates/develop/src/lib.rs index cb6caa3ba0..324fe29a02 100644 --- a/crates/develop/src/lib.rs +++ b/crates/develop/src/lib.rs @@ -27,6 +27,7 @@ impl DevelopSettings { s.wb.tint = as_shot_tint; s.detail.sharpen_amount = 40.0; s.detail.nr_color = 25.0; + s.detail.nr_outliers = true; s } @@ -38,6 +39,18 @@ impl DevelopSettings { serde_json::from_value(v.clone()) } + /// [`Self::to_json`] with Remove Hot Pixels (`detail.nr_outliers`) stated even when off, for JSON that is copied, + /// merged, scaled or compared key by key (copy / paste, presets, Auto Sync). The stored JSON leaves it out when + /// off, so settings saved before it keep their hash; a merge needs the `false`, or copying Detail would not turn + /// the box off and a preset applied at an amount would not find its base value. + pub fn to_json_for_merge(&self) -> Value { + let mut v = self.to_json(); + if let Some(detail) = v.get_mut("detail").and_then(Value::as_object_mut) { + detail.insert("nr_outliers".into(), Value::Bool(self.detail.nr_outliers)); + } + v + } + /// [`Self::from_json`] for settings from outside the app, such as a sidecar's `lc:settings` /// (issue #2555): kept in range as [`Self::merged`] keeps them. pub fn from_untrusted_json(v: &Value) -> Result { @@ -141,6 +154,12 @@ impl DevelopSettings { std::borrow::Cow::Owned(d) } + /// Whether a raw is decoded with its single outlier photosites replaced: Remove Hot Pixels is on and the Detail + /// section's eye is too (an Edit-panel section that is off contributes nothing, as in [`Self::effective`]). + pub fn removes_hot_pixels(&self) -> bool { + self.detail.nr_outliers && self.section_enabled("detail") + } + /// How much of the AI-denoised picture to mix in, 0 (none) to 1 (all of it): the Denoise amount, unless the Detail /// section is switched off or the value is not a number. pub fn denoise_amount(&self) -> f32 { @@ -167,7 +186,11 @@ impl DevelopSettings { self.curve = d; } Section::Color => self.wb.mode = WbMode::AsShot, - Section::Detail => self.enhance.denoise_on = None, + Section::Detail => { + self.enhance.denoise_on = None; + // not a slider: reset like them, to the general default (off) + self.detail.nr_outliers = false; + } // the creative profile is not a control: the chosen look goes back to the default one, // and so does the camera's own local tone mapping Section::Profile => { @@ -202,6 +225,37 @@ mod tests { use super::*; use serde_json::json; + /// Remove Hot Pixels (#1345) is on for a newly imported raw and off for everything else, and an edit saved + /// before the box existed reads as off, so it renders as it did. + #[test] + fn hot_pixel_box_is_on_for_new_raws_only() { + assert!(DevelopSettings::for_raw(5500.0, 10.0).detail.nr_outliers); + assert!(!DevelopSettings::default().detail.nr_outliers); + let mut saved = DevelopSettings::for_raw(5500.0, 10.0).to_json(); + let detail = saved.get_mut("detail").and_then(|d| d.as_object_mut()).unwrap(); + assert!(detail.remove("nr_outliers").is_some()); + let read = DevelopSettings::from_json(&saved).unwrap(); + assert!(!read.detail.nr_outliers); + assert_eq!(read.detail.nr_color, 25.0, "the rest of the saved edit is kept"); + assert_ne!(read.hash64(), DevelopSettings::for_raw(5500.0, 10.0).hash64(), "cached renders are told apart"); + // off is omitted: an edit saved before the box keeps its JSON, and so its hash and cached thumbnails + assert_eq!(read.to_json(), saved); + // copying Detail still carries the box when it is off + let copied = crate::extract_groups(&read, &[crate::SettingsGroup::Detail]); + assert_eq!(copied["detail"]["nr_outliers"], false); + let mut target = DevelopSettings::for_raw(5500.0, 10.0).to_json(); + crate::presets::deep_merge(&mut target, &copied); + assert!(!DevelopSettings::from_json(&target).unwrap().detail.nr_outliers); + // the Detail eye switches it off for the decode too, and Reset Detail resets it like the sliders + let mut raw = DevelopSettings::for_raw(5500.0, 10.0); + assert!(raw.removes_hot_pixels()); + raw.set_section_enabled("detail", false); + assert!(!raw.removes_hot_pixels()); + raw.set_section_enabled("detail", true); + raw.reset_section(Section::Detail); + assert!(!raw.detail.nr_outliers && !raw.removes_hot_pixels()); + } + #[test] fn serde_roundtrip_default_and_edited() { let mut s = DevelopSettings::default(); diff --git a/crates/develop/src/presets.rs b/crates/develop/src/presets.rs index d5a658f51c..b69f2df460 100644 --- a/crates/develop/src/presets.rs +++ b/crates/develop/src/presets.rs @@ -126,7 +126,7 @@ impl SettingsGroup { /// The subset of `s` covering `groups`, as a partial JSON object. pub fn extract_groups(s: &DevelopSettings, groups: &[SettingsGroup]) -> Value { - let full = s.to_json(); + let full = s.to_json_for_merge(); let mut out = Map::new(); for g in groups { for k in g.keys() { @@ -186,7 +186,7 @@ fn scale_patch(base: &Value, patch: &Value, t: f64) -> Value { /// Apply a partial settings object with an amount (1.0 = 100 %). Out-of-range values are clamped /// through the control specs, as every merge does ([`DevelopSettings::merged`]). pub fn apply_partial(s: &DevelopSettings, partial: &Value, amount: f64) -> DevelopSettings { - let patch = if (amount - 1.0).abs() < 1e-9 { Cow::Borrowed(partial) } else { Cow::Owned(scale_patch(&s.to_json(), partial, amount)) }; + let patch = if (amount - 1.0).abs() < 1e-9 { Cow::Borrowed(partial) } else { Cow::Owned(scale_patch(&s.to_json_for_merge(), partial, amount)) }; // (a white balance without a scale keeps its old meaning: `DevelopSettings::merged`) s.merged(&patch).unwrap_or_else(|_| s.clone()) } diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index 201b33d5f0..82de362e5f 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -632,6 +632,13 @@ pub struct Detail { pub nr_color: f64, pub nr_color_detail: f64, pub nr_color_smoothness: f64, + /// Replace single outlier photosites (noise spikes far above all their same-colour neighbours) in the + /// raw mosaic before demosaicing, so they do not become coloured dots (#1345). On for newly imported + /// raws ([`crate::DevelopSettings::for_raw`]); off for edits saved before it existed, so they look the + /// same. Raw files only. Omitted when off, so settings saved before it keep their JSON (and hash, and with it + /// their cached thumbnails). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub nr_outliers: bool, } impl Default for Detail { @@ -649,6 +656,7 @@ impl Default for Detail { nr_color: 0.0, nr_color_detail: 50.0, nr_color_smoothness: 50.0, + nr_outliers: false, } } } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0d40c73184..a01f28510b 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -49,6 +49,8 @@ lightcraft-segment = { workspace = true, optional = true } lightcraft-fetch = { workspace = true } # capture-time parsing for face recognition (native only) chrono = { workspace = true } +# free space of the drive holding the preview cache (the low-disk alert; pure Rust: rustix / windows-sys) +fs4 = { workspace = true } [features] # AI masks with SAM 3 (Object / Describe). Off for the web and CLI builds. diff --git a/crates/engine/examples/render_bench.rs b/crates/engine/examples/render_bench.rs index 789867c665..23e577b010 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, None).expect("load")))); + println!(" {:<36} {}", "fs loader (2560, read+load):", best(n, || drop(loader(path, 2560, Default::default()).expect("load")))); } } diff --git a/crates/engine/src/cmd/denoise.rs b/crates/engine/src/cmd/denoise.rs index 1cb99ccf35..52686a5a15 100644 --- a/crates/engine/src/cmd/denoise.rs +++ b/crates/engine/src/cmd/denoise.rs @@ -118,6 +118,9 @@ fn identify(path: &Path, c: &str, sha_known: Option<&str>) -> Result { && let Some(bytes) = read_capped(&sibling, MAX_MANIFEST_BYTES) { let m = manifest::parse(&bytes).map_err(|e| bad(c, format!("{}: {e}", sibling.display())))?; + if m.id == lightcraft_denoise::builtin::ID { + return Err(bad(c, "the id `builtin` is LightCraft's own denoiser: give the model another id in its denoise-model.json")); + } return Ok(Source { manifest: m, entry: None, file_name }); } Err(bad( @@ -660,20 +663,20 @@ pub fn specs() -> Vec { cmd!(query "denoise.models.downloadCancel", "Cancel Denoise Model Download", [], None, "{id} → {discarded} — stop a download, or delete a finished one that was not installed", always, download_cancel), cmd!(query "denoise.models.test", "Test Denoise Model", [], None, "{id} → {ok, result} — load an installed model and check it gives sensible pictures; needs the denoise runtime", always, test), cmd!(query "denoise.models.remove", "Remove Denoise Model", [], None, "{id} → {removed, model} — delete an installed model (its cached pictures stay until they are evicted)", always, remove), - cmd!(query "denoise.models.select", "Choose Denoise Model", [], None, "{id: installed model | null} → {model} — null switches denoise off", always, select), + cmd!(query "denoise.models.select", "Choose Denoise Model", [], None, "{id: installed model | null} → {model} — null uses the built-in denoiser", always, select), cmd!(query "denoise.settings", "Denoise Settings", [], None, "{auto?: bool, cacheGb?: 1..10000, threads?: 1..64 | null, runOn?: auto | gpu | cpu} → the settings — `auto`: make the picture of the photos being looked at that have a Denoise amount; `cacheGb`: how much the cached pictures may take; `threads`: most tiles run at once; `runOn`: where the model runs — `auto` (the default) the graphics card where it is faster than the processor (both timed on this computer when the card is set up), `gpu` the card whenever it can run the model, `cpu` the processor. Setting `runOn` also lets the card be tried again after a set-up that failed or closed LightCraft", always, settings), cmd!( "denoise.toggle", "AI Denoise", [], None, - "{id?: photoId, enabled?: bool} → {id, enabled, amount} — turn AI Denoise on (50% initially) or off for one raw photo, independent of selection and Auto Sync; needs an installed model to turn on", + "{id?: photoId, enabled?: bool} → {id, enabled, amount} — turn AI Denoise on (50% initially) or off for one raw photo, independent of selection and Auto Sync; uses the built-in denoiser when no model is chosen", always, toggle ), cmd!(query "denoise.queue", "Denoise Photos", [], None, "{ids?: [photoId], scope?: selected | visible | withAmount, retry?: false} → {added, …status} — make the denoised pictures of raw photos that have none, in the background. `retry` tries photos that failed before", always, queue), cmd!(query "denoise.cancel", "Cancel Denoise", [], None, "{id?, all?} → {cancelled} — stop the photo being made and/or forget the ones waiting (all of them when `id` is omitted)", always, cancel), - cmd!(query "denoise.status", "Denoise Status", [], None, "{id?} → {enabled, model, runtime, productsDir, queued, running: {photo, done, total, seconds} | null, ready, made, auto, runOn, device: {kind: gpu | cpu | pending | none, adapter?, reason?, cardMs?, cpuMs?, fellBack?, remote?: {address, state: pending | unavailable | used | idle | slower | given up, device?, remoteMs?, localMs?, reason?, failures?, lastError?}}, cache: {files, bytes, limitBytes}, generation, photo?: {state: notApplicable | noModel | ready | queued | running | failed | idle, …}}", always, status), + cmd!(query "denoise.status", "Denoise Status", [], None, "{id?} → {enabled, model, runtime, productsDir, queued, running: {photo, done, total, seconds} | null, ready, made, auto, runOn, device: {kind: gpu | cpu | pending | none, adapter?, reason?, cardMs?, cpuMs?, fellBack?, remote?: {address, state: pending | unavailable | used | idle | slower | given up, device?, remoteMs?, localMs?, reason?, failures?, lastError?}}, cache: {files, bytes, limitBytes}, generation, photo?: {state: notApplicable | ready | queued | running | failed | idle, …}}", always, status), cmd!(query "denoise.pump", "Denoise Pump", [], None, "{pace?: pause | light | normal | full} → {active, running, queued, ready, generation, downloading} — called every frame by the app: takes in finished work and keeps one photo going", always, pump), cmd!(query "denoise.clear", "Clear Denoise Cache", [], None, "{} → {deleted, bytes} — delete every cached denoised picture of this library (they are made again when wanted)", always, clear), ] diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index 292ad27795..e78407f5ea 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -1166,7 +1166,7 @@ pub fn specs() -> Vec { |s, p| { let c = "preset.update"; let id = active(s, c)?; - let current = s.develop_of(id).unwrap_or_default().to_json(); + let current = s.develop_of(id).unwrap_or_default().to_json_for_merge(); let groups = groups_param(p, c)?; let pr = user_preset(s, p, c)?; pr.settings = match groups { diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index b99e97c054..4274e689c9 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -1367,6 +1367,8 @@ pub fn specs() -> Vec { ), // ---- persistence cmd!(query "library.info", "Library Info", [], None, "{}", always, |s, _| { + // the answer of a free-space read that ran on a worker (lowDiskSpace below) + s.poll_disk_space(); let photos = s.catalog.len(); let albums = s.catalog.albums().count(); let (rendered_n, rendered_bytes) = s.media.rendered.mem_usage(); @@ -1402,6 +1404,8 @@ pub fn specs() -> Vec { "lastError": lib.last_error, // settings files that were unreadable or damaged at open (kept, defaults used) "settingsWarnings": lib.settings_warnings, + // the drive holding the preview cache ran low this session (warned once) + "lowDiskSpace": s.disk_space_alert_raised(), // changes applied in memory whose write failed (retried by every save) "unsavedOps": s.unsaved().map_or(0, |u| u.0), "unsavedError": s.unsaved().map(|u| u.1), diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index 95aff90b79..0d506b5adf 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -31,6 +31,20 @@ pub struct PreviewBuild { pub what: &'static str, /// Why the whole build failed (e.g. the smart previews folder isn't there). pub error: std::sync::Mutex>, + /// Photos whose previews were there already (from an earlier build, the loupe or the photos + /// prepared ahead): counted as done, not rendered again (PERF-PREVIEW-REUSE). + pub skipped: AtomicUsize, + /// Photos left alone because another job was building them at that moment. + pub shared: AtomicUsize, + /// Started by the background preparation ([`crate::prep`]): it yields to the photo on screen, + /// and a build the user (or an import) asks for replaces it. + pub background: bool, + /// The photos in build order (ids), and where the user is among them: the next photo built + /// is the nearest one not built yet from there, in the direction of travel + /// ([`PreviewBuild::focus_on`]). + pub order: Vec, + pub focus: AtomicUsize, + pub backward: AtomicBool, /// Test-only: the gate this build's lanes wait at before a photo's first render (see /// [`test_gate`]). Captured by `build` on the calling thread; production builds never have one. #[cfg(test)] @@ -47,10 +61,38 @@ impl PreviewBuild { "cancelled": self.cancel.load(Ordering::Relaxed), "what": if self.what.is_empty() { "previews" } else { self.what }, "repaired": self.repaired.load(Ordering::Relaxed), + "skipped": self.skipped.load(Ordering::Relaxed), + "shared": self.shared.load(Ordering::Relaxed), + "background": self.background, "error": self.error(), }) } + pub fn running(&self) -> bool { + !self.finished.load(Ordering::Relaxed) + } + + /// The user is at photo `id`, moving `backward` or forward: build from there on. + pub fn focus_on(&self, id: lightcraft_catalog::PhotoId, backward: bool) { + if let Some(i) = self.order.iter().position(|p| *p == id.0) { + self.focus.store(i, Ordering::Relaxed); + self.backward.store(backward, Ordering::Relaxed); + } + } + + /// Index of the next photo to build in `queue` (`None`: none left): the first one still there + /// from the focus on in the direction of travel, then the rest the other way. + pub(crate) fn next_index(&self, queue: &[Option]) -> Option { + let n = queue.len(); + let at = self.focus.load(Ordering::Relaxed).min(n.saturating_sub(1)); + let there = |i: &usize| queue.get(*i).is_some_and(Option::is_some); + if self.backward.load(Ordering::Relaxed) { + (0..=at).rev().find(there).or_else(|| (at..n).find(there)) + } else { + (at..n).find(there).or_else(|| (0..at).rev().find(there)) + } + } + pub fn error(&self) -> Option { self.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone() } @@ -69,9 +111,93 @@ pub(crate) fn jobs_for(s: &mut Session, id: lightcraft_catalog::PhotoId, edge: O if e >= thumb { view.into_iter().chain(grid).collect() } else { grid.into_iter().chain(view).collect() } } +/// The previews the build of one photo would make are all there already, big enough: its view +/// render at least as large as asked for (`view_cache` of the view job) and its grid thumbnail +/// (`cache` of the thumbnail job), on disk when the cache has one: a render the loupe kept only in +/// memory (its deferred disk write skipped) is built again, and written. Only file headers are read. +pub(crate) fn already_built(jobs: &[RenderJob]) -> bool { + !jobs.is_empty() + && jobs.iter().all(|j| { + if let Some((cache, key)) = &j.view_cache { + let want = j.request.max_w.max(j.request.max_h) as f64; + cache.stored_dims(*key).is_some_and(|(w, h)| w.max(h) as f64 >= want * 0.99) + } else if let Some((cache, key)) = &j.cache { + cache.stored_dims(*key).is_some() + } else { + false + } + }) +} + +/// Photos some preview build is rendering right now, by (the cache they go to, photo id): two +/// builds (a background one being replaced, and the one replacing it) never render the same photo +/// at once. +static BUILDING: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Holds a photo in [`BUILDING`] while it is rendered. +struct Building((usize, u64)); + +impl Building { + /// `id` of `jobs` (the cache their results go to tells sessions apart). + fn take(id: u64, jobs: &[RenderJob]) -> Option { + let cache = jobs.iter().find_map(|j| j.view_cache.as_ref().or(j.cache.as_ref())).map_or(0, |(c, _)| Arc::as_ptr(c) as usize); + let id = (cache, id); + let mut b = BUILDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if b.contains(&id) { + return None; + } + b.push(id); + Some(Building(id)) + } + + /// [`Self::take`], waiting while another build renders the photo (a build asked for replacing the + /// background one may meet it on the same photo): the photo is not counted until that render is over, as + /// built when it made the previews, else rendered here. With whether it had to wait; `None` when `cancel` + /// was asked for meanwhile. (On the web, with one thread, a photo held is not waited for: `Some((None, true))`.) + fn wait(id: u64, jobs: &[RenderJob], cancel: &AtomicBool) -> Option<(Option, bool)> { + if let Some(b) = Self::take(id, jobs) { + return Some((Some(b), false)); + } + Self::wait_held(id, jobs, cancel) + } + + /// [`Self::wait`] for a photo another build holds. + #[cfg(not(target_arch = "wasm32"))] + fn wait_held(id: u64, jobs: &[RenderJob], cancel: &AtomicBool) -> Option<(Option, bool)> { + loop { + if cancel.load(Ordering::Relaxed) { + return None; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + if let Some(b) = Self::take(id, jobs) { + return Some((Some(b), true)); + } + } + } + + /// [`Self::wait`] for a photo another build holds: on the web, with one thread, it is not waited for. + #[cfg(target_arch = "wasm32")] + fn wait_held(_id: u64, _jobs: &[RenderJob], cancel: &AtomicBool) -> Option<(Option, bool)> { + (!cancel.load(Ordering::Relaxed)).then_some((None, true)) + } +} + +/// Tests: hold `id` of `jobs` as a build rendering it would, until the returned value is dropped. +#[cfg(test)] +pub(crate) fn hold_building(id: u64, jobs: &[RenderJob]) -> Option> { + Building::take(id, jobs).map(|b| Box::new(b) as Box) +} + +impl Drop for Building { + fn drop(&mut self) { + BUILDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner).retain(|x| *x != self.0); + } +} + /// The build's row in the activity stack (`what` as in [`PreviewBuild::what`]). fn task_for(s: &Session, state: &PreviewBuild) -> TaskGuard { let (kind, label) = match state.what { + "" if state.background => ("previews", "Preparing photos in the background"), "" => ("previews", "Building previews"), "smart previews" => ("smartPreviews", "Building smart previews"), _ => ("smartPreviews", "Discarding smart previews"), @@ -84,7 +210,8 @@ fn task_for(s: &Session, state: &PreviewBuild) -> TaskGuard { /// Render one photo's jobs in order. The source the first job decodes serves the ones after it /// (the grid thumbnail is made from the view's source instead of decoding the file again). /// `None` when `cancel` was asked for before a job started: that photo is not counted as done. -fn run_photo_cancellable(jobs: Vec, cancel: Option<&AtomicBool>) -> Option { +/// `force`: the grid thumbnail is rendered too, not taken from the cache it is written to. +fn run_photo_cancellable(jobs: Vec, cancel: Option<&AtomicBool>, force: bool) -> Option { let mut decoded: Option = None; let mut ok = true; for mut j in jobs { @@ -97,7 +224,33 @@ fn run_photo_cancellable(jobs: Vec, cancel: Option<&AtomicBool>) -> O { j.source = crate::media::SourceRef::Loaded(Box::new(src.clone())); } + // The view render is written to the disk cache here, before the photo counts as built, + // not left to the cache's writer (which skips writes when it falls behind): a built + // preview is on disk, for this session and the next. (Taken out of the job: it would only + // queue the write, and would serve a smaller cached view.) + // A preview that isn't kept fails the photo: it is not built (a full or unwritable cache folder, or the + // cache discarded while the photo rendered). + let keep = j.view_cache.take().map(|v| (v, j.cache_generation)); + // forced: the thumbnail job's cache is only written to, after the render (a job reads its cache first; + // CodeRabbit on #3577) + let rewrite = if force { j.cache.take().map(|c| (c, j.cache_generation)) } else { None }; let r = j.run(); + if let (Some(((cache, key), generation)), Ok(img)) = (rewrite, r.rendered.as_ref()) + && !cache.put_at(generation, key, Arc::new(img.image.clone())) + { + log::warn!("building previews: the grid thumbnail could not be kept"); + ok = false; + } + if let (Some(((cache, key), generation)), Ok(img)) = (keep, r.rendered.as_ref()) + && !cache.put_at(generation, key, Arc::new(img.image.clone())) + { + if cache.generation() == generation { + log::warn!("building previews: the view preview could not be written to the cache folder"); + } else { + log::warn!("building previews: the preview cache was discarded while the photo rendered"); + } + ok = false; + } ok &= r.rendered.is_ok(); if decoded.is_none() { decoded = r.loaded; @@ -109,7 +262,7 @@ fn run_photo_cancellable(jobs: Vec, cancel: Option<&AtomicBool>) -> O /// [`run_photo_cancellable`] for callers that render a photo without a cancel flag. #[cfg(test)] pub(crate) fn run_photo(jobs: Vec) -> bool { - run_photo_cancellable(jobs, None) == Some(true) + run_photo_cancellable(jobs, None, false) == Some(true) } /// How many photos render side by side: as many as an export batch for standard previews (each @@ -224,34 +377,83 @@ pub(crate) mod test_gate { pub(crate) fn take() -> Option> { NEXT_GATE.with(|g| g.borrow_mut().take()) } + + thread_local! { + /// The next build started on this thread fails to start its worker (a thread the system + /// won't give), taken by `build`. + static FAIL_SPAWN: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + /// Have the next build started on this thread fail to start its worker. + pub(crate) fn fail_next_spawn() { + FAIL_SPAWN.with(|f| f.set(true)); + } + + /// Whether this build's worker is to fail to start (once). + pub(crate) fn take_fail_spawn() -> bool { + FAIL_SPAWN.with(std::cell::Cell::take) + } } -fn run_all(jobs: Vec>, state: &PreviewBuild, task: &TaskGuard, lanes: usize) { +/// One photo's work in a build: its id and its render jobs ([`jobs_for`]). +type PhotoJobs = (u64, Vec); + +/// Build every photo of `jobs` on `lanes` threads. `force`: render even the photos whose previews +/// are there. `task`: the build's own row (`None`: another job's row shows it, e.g. the import's +/// Getting photos ready). +fn run_all(jobs: Vec, state: &PreviewBuild, task: Option<&TaskGuard>, lanes: usize, force: bool) { let total = jobs.len(); - let queue = std::sync::Mutex::new(jobs.into_iter()); + let queue = std::sync::Mutex::new(jobs.into_iter().map(Some).collect::>()); let work = || { loop { if state.cancel.load(Ordering::Relaxed) { break; } - let next = queue.lock().unwrap_or_else(std::sync::PoisonError::into_inner).next(); - let Some(photo_jobs) = next else { break }; + // the background preparation waits while the photo on screen is being made + if state.background && crate::prep::wait_for_foreground(&state.cancel) { + break; + } + let next = { + let mut q = queue.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + state.next_index(&q).and_then(|i| q.get_mut(i)).and_then(Option::take) + }; + let Some((id, photo_jobs)) = next else { break }; // A cancel accepted while this lane waited for the queue (or for another lane's // photo) stops before this photo's first render; a cancelled photo is not counted. if state.cancel.load(Ordering::Relaxed) { break; } - #[cfg(test)] - if let Some(gate) = &state.gate { - gate.enter(); - } - let outcome = crate::guard::catch("building previews", || run_photo_cancellable(photo_jobs, Some(&state.cancel))).unwrap_or(Some(false)); - let Some(ok) = outcome else { break }; - if !ok { - state.failed.fetch_add(1, Ordering::Relaxed); + if !force && already_built(&photo_jobs) { + state.skipped.fetch_add(1, Ordering::Relaxed); + } else if let Some((held, shared)) = Building::wait(id, &photo_jobs, &state.cancel) { + // another build was rendering this photo: what it made counts, if it made it (not + // for a forced build, which renders every photo itself) + if !force && shared && (held.is_none() || already_built(&photo_jobs)) { + state.shared.fetch_add(1, Ordering::Relaxed); + let done = state.done.fetch_add(1, Ordering::Relaxed).saturating_add(1); + if let Some(task) = task { + task.progress(done as u64, total as u64); + } + continue; + } + #[cfg(test)] + if let Some(gate) = &state.gate { + gate.enter(); + } + let outcome = + crate::guard::catch("building previews", || run_photo_cancellable(photo_jobs, Some(&state.cancel), force)).unwrap_or(Some(false)); + let Some(ok) = outcome else { break }; + if !ok { + state.failed.fetch_add(1, Ordering::Relaxed); + } + } else { + // cancelled while another build was rendering it: not counted + break; } let done = state.done.fetch_add(1, Ordering::Relaxed).saturating_add(1); - task.progress(done as u64, total as u64); + if let Some(task) = task { + task.progress(done as u64, total as u64); + } } }; #[cfg(not(target_arch = "wasm32"))] @@ -272,43 +474,99 @@ fn run_all(jobs: Vec>, state: &PreviewBuild, task: &TaskGuard, la state.finished.store(true, Ordering::Relaxed); } +/// The long edge a standard preview is built at: [`STANDARD_EDGE`], or what the loupe asks for +/// on this screen when that is more ([`Session::loupe_edge`]), so the loupe finds what was built. +pub fn standard_edge(s: &Session) -> usize { + STANDARD_EDGE.max(s.loupe_edge.min(8192)) +} + fn build(s: &mut Session, p: &Value) -> Result { const C: &str = "library.buildPreviews"; // tests: this invocation's gate, consumed here so an early error cannot attach it to a later build #[cfg(test)] let gate = test_gate::take(); let edge = match str_param(p, "size").unwrap_or("standard") { - "standard" => Some(p.get("edge").and_then(Value::as_u64).map_or(STANDARD_EDGE, |e| e.clamp(256, 8192) as usize)), + "standard" => Some(p.get("edge").and_then(Value::as_u64).map_or_else(|| standard_edge(s), |e| e.clamp(256, 8192) as usize)), "full" | "1:1" => None, other => return Err(bad(C, format!("unknown size `{other}` (standard|full)"))), }; - if s.preview_build.as_ref().is_some_and(|b| !b.finished.load(Ordering::Relaxed)) { - return Err(bad(C, "a preview build is already running")); + let background = p.get("background").and_then(Value::as_bool).unwrap_or(false); + let force = p.get("force").and_then(Value::as_bool).unwrap_or(false); + // (`row: false`: the job that asked shows the progress in its own row) + let row = p.get("row").and_then(Value::as_bool).unwrap_or(true); + // the background preparation gives way to a build that was asked for; nothing replaces a build + // that was asked for (it carries on, and the photos it built are skipped by the next). The + // background one is stopped only once this request is known to be good (below): a request + // with bad ids leaves it running (CodeRabbit on #3544) + let mut gives_way = None; + if let Some(b) = s.preview_build.as_ref().filter(|b| b.running()) { + if b.background && !background { + gives_way = Some(b.cancel.clone()); + } else { + return Err(bad(C, "a preview build is already running")); + } } - // explicit ids, else the selection, else everything in view - let ids = if p.get("ids").is_some() || p.get("id").is_some() || !s.selection.ids.is_empty() { s.targets(p)? } else { s.visible_cloned() }; - let jobs: Vec> = ids.iter().map(|id| jobs_for(s, *id, edge)).filter(|j| !j.is_empty()).collect(); + s.fit_disk_cache(); + // explicit ids, else the selected photos (more than one: as the menu says), else everything in + // view (a single photo selected is the one open, not a choice of photos: "Visible" in the menu) + let ids = if p.get("ids").is_some() || p.get("id").is_some() || (!background && s.selection.ids.len() > 1) { + s.targets(p)? + } else { + s.visible_cloned() + }; + let jobs: Vec = ids.iter().map(|id| (id.0, jobs_for(s, *id, edge))).filter(|j| !j.1.is_empty()).collect(); + // the background build stays the session's until this one has started (a worker that can't + // start leaves it running and in place: CodeRabbit on #3544) + let previous = s.preview_build.clone(); + let order = jobs.iter().map(|j| j.0).collect(); + #[cfg_attr(not(test), allow(unused_mut))] + let mut build_state = PreviewBuild { total: jobs.len(), background, order, ..Default::default() }; #[cfg(test)] - let state = Arc::new(PreviewBuild { total: jobs.len(), gate, ..Default::default() }); - #[cfg(not(test))] - let state = Arc::new(PreviewBuild { total: jobs.len(), ..Default::default() }); + { + build_state.gate = gate; + } + let state = Arc::new(build_state); + if let Some(at) = p.get("from").and_then(Value::as_u64) { + state.focus_on(lightcraft_catalog::PhotoId(at), p.get("backward").and_then(Value::as_bool).unwrap_or(false)); + } s.preview_build = Some(state.clone()); - let task = task_for(s, &state); - let lanes = lanes(jobs.len(), edge.is_none()); + let task = row.then(|| task_for(s, &state)); + // the background preparation leaves most of the machine to the photo on screen and the user + let lanes = if background { crate::prep::background_lanes() } else { lanes(jobs.len(), edge.is_none()) }; let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false) || cfg!(target_arch = "wasm32"); if wait { - run_all(jobs, &state, &task, lanes); + if let Some(cancel) = gives_way { + cancel.store(true, Ordering::Relaxed); + } + run_all(jobs, &state, task.as_ref(), lanes, force); return Ok(state.json()); } #[cfg(not(target_arch = "wasm32"))] { // the row stays while the worker runs (it is dropped with the closure, however that ends) let st = state.clone(); - std::thread::Builder::new() - .name("lc-build-previews".into()) - .spawn(move || run_all(jobs, &st, &task, lanes)) - .map_err(|e| bad(C, format!("could not start: {e}")))?; + #[cfg(test)] + let started = if test_gate::take_fail_spawn() { + drop(task); + Err(std::io::Error::other("no thread (test)")) + } else { + std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &st, task.as_ref(), lanes, force)) + }; + #[cfg(not(test))] + let started = std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &st, task.as_ref(), lanes, force)); + if let Err(e) = started { + // never started: not left "running", which would hold every later build back, and the + // build it was to replace carries on + state.finished.store(true, Ordering::Relaxed); + s.preview_build = previous; + return Err(bad(C, format!("could not start: {e}"))); + } + if let Some(cancel) = gives_way { + cancel.store(true, Ordering::Relaxed); + } } + #[cfg(target_arch = "wasm32")] + let _ = previous; Ok(state.json()) } @@ -361,8 +619,8 @@ fn original_only(source: crate::media::SourceRef) -> Option { - Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, camera_profile: None, reduced: None }) + SourceRef::File { path, max_edge, loader, denoise, outliers, .. } => { + Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, camera_profile: None, outliers, reduced: None }) } SourceRef::Loaded(d) if d.info.is_some() && !d.from_proxy && !d.reduced => Some(SourceRef::Loaded(d)), _ => None, @@ -476,10 +734,18 @@ fn smart(s: &mut Session, p: &Value) -> Result { let dir = s.media.smart_dir.clone().ok_or_else(|| bad(C, "smart previews need a library on disk"))?; let discard = p.get("discard").and_then(Value::as_bool).unwrap_or(false); let background = p.get("background").and_then(Value::as_bool).unwrap_or(false); - if background && s.preview_build.as_ref().is_some_and(|b| !b.finished.load(Ordering::Relaxed)) { - return Err(bad(C, "a preview build is already running")); + // (as Build Previews: the photos named, or the selected ones when more than one is, else + // everything in view; read first, so a request with bad ids stops nothing: CodeRabbit on #3577) + let ids = if p.get("ids").is_some() || p.get("id").is_some() || s.selection.ids.len() > 1 { s.targets(p)? } else { s.visible_cloned() }; + // (the background preparation gives way, as to Build Previews: once this one's worker has started) + let mut gives_way = None; + if background && let Some(b) = s.preview_build.as_ref().filter(|b| b.running()) { + if b.background { + gives_way = Some(b.cancel.clone()); + } else { + return Err(bad(C, "a preview build is already running")); + } } - let ids = if p.get("ids").is_some() || !s.selection.ids.is_empty() { s.targets(p)? } else { s.visible_cloned() }; let mut jobs: Vec = Vec::new(); for id in ids { let Some(ph) = s.catalog.photo(id).cloned() else { continue }; @@ -496,19 +762,35 @@ fn smart(s: &mut Session, p: &Value) -> Result { if background { let what = if discard { "discarding smart previews" } else { "smart previews" }; let state = Arc::new(PreviewBuild { total: jobs.len(), what, ..Default::default() }); - s.preview_build = Some(state.clone()); + let previous = s.preview_build.replace(state.clone()); let task = task_for(s, &state); let st = state.clone(); - std::thread::Builder::new() - .name("lc-smart-previews".into()) - .spawn(move || { - if let Err(e) = smart_run(&dir, custom, discard, jobs, Some((&st, &task))) { - log::warn!("{C}: {e}"); - *st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e); - } - st.finished.store(true, Ordering::Relaxed); - }) - .map_err(|e| bad(C, format!("could not start: {e}")))?; + let work = move || { + if let Err(e) = smart_run(&dir, custom, discard, jobs, Some((&st, &task))) { + log::warn!("{C}: {e}"); + *st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e); + } + st.finished.store(true, Ordering::Relaxed); + }; + #[cfg(test)] + let started = if test_gate::take_fail_spawn() { + drop(work); + Err(std::io::Error::other("no thread (test)")) + } else { + std::thread::Builder::new().name("lc-smart-previews".into()).spawn(work) + }; + #[cfg(not(test))] + let started = std::thread::Builder::new().name("lc-smart-previews".into()).spawn(work); + if let Err(e) = started { + // never started: not left "running", and the background build it was to replace carries on + // (CodeRabbit on #3077) + state.finished.store(true, Ordering::Relaxed); + s.preview_build = previous; + return Err(bad(C, format!("could not start: {e}"))); + } + if let Some(cancel) = gives_way { + cancel.store(true, Ordering::Relaxed); + } return Ok(state.json()); } let r = smart_run(&dir, custom, discard, jobs, None).map_err(|e| bad(C, e))?; @@ -647,7 +929,7 @@ pub fn specs() -> Vec { "Build Smart Previews", [], None, - "{ids?, discard?: bool, background?: bool} — build (or discard) the smart previews of the selected photos (else all in view): compact proxies in the library that keep photos editable and exportable (at proxy size) while their originals are offline; a damaged proxy (cut short) is rebuilt → {built, repaired, removed, failed}; with background (the app's menu) the files are read and written on a worker thread → {total, done, failed, repaired, running, what} like library.buildPreviews (progress: library.previewProgress, stop: library.cancelPreviews)", + "{ids?, discard?: bool, background?: bool} — build (or discard) the smart previews of the selected photos (when more than one is selected; else all in view): compact proxies in the library that keep photos editable and exportable (at proxy size) while their originals are offline; a damaged proxy (cut short) is rebuilt → {built, repaired, removed, failed}; with background (the app's menu) the files are read and written on a worker thread → {total, done, failed, repaired, running, what} like library.buildPreviews (progress: library.previewProgress, stop: library.cancelPreviews)", always, smart ), @@ -674,13 +956,43 @@ pub fn specs() -> Vec { "Build Previews", [], None, - "{size?: standard (2048 px, or `edge`) | full (1:1), ids?, wait?: bool} — render the grid thumbnail and loupe view of the selected photos (else all in view) into the preview cache, in the background unless `wait` → {total, done, failed, running}", + "{size?: standard (2048 px, or the loupe's size when bigger, or `edge`) | full (1:1), ids?, wait?: bool, force?: bool, from?: id, backward?: bool, background?: bool, row?: bool} — render the grid thumbnail and loupe view of the selected photos (when more than one is selected; else all in view) into the preview cache (memory and disk), in the background unless `wait`. Photos whose previews are there already (big enough) are skipped unless `force`; the photos nearest `from` go first. `background`: the background preparation's build (two lanes, waits while the photo on screen renders; a build asked for replaces it). `row: false`: no row of its own in the activity stack (the caller's row shows it) → {total, done, failed, skipped, shared, running}", always, build ), - cmd!(query "library.previewProgress", "Preview Build Progress", [], None, "{} → {total, done, failed, repaired, running, cancelled, what, error} | null", always, |s, _| { + cmd!(query "library.previewProgress", "Preview Build Progress", [], None, "{} → {total, done, failed, repaired, skipped, shared, background, running, cancelled, what, error} | null", always, |s, _| { Ok(s.preview_build.as_ref().map_or(Value::Null, |b| b.json())) }), + cmd!(query "prefs.backgroundPrep", "Background Preparation Settings", [], None, "{} → {app, library|null, settings (in use), own: bool (this library keeps its own), building} — what is prepared in the background per mode (culling | library: previews of every photo in view, ahead = photos ahead rendered for the loupe, eyeAhead = photos ahead whose eye focus strip is worked out, scope all|marked|onScreen; develop: ahead = photos kept decoded ready to edit, scope)", always, |s, _| { + Ok(s.prep_json()) + }), + cmd!( + "prefs.setBackgroundPrep", + "Set Background Preparation", + [], + None, + "{settings?: partial {culling?, library?, develop?}, library?: bool (this library's own settings; else the app-wide ones), reset?: bool (this library goes back to the app-wide settings)} → as prefs.backgroundPrep", + always, + |s, p| { + const C: &str = "prefs.setBackgroundPrep"; + let library = p.get("library").and_then(Value::as_bool).unwrap_or(false); + if p.get("reset").and_then(Value::as_bool).unwrap_or(false) { + s.clear_library_prep()?; + return Ok(s.prep_json()); + } + if library && s.library.is_none() { + return Err(bad(C, "no library is open")); + } + let base = if library { s.prep.library.unwrap_or(s.prep.app) } else { s.prep.app }; + let next = match p.get("settings") { + Some(patch) if patch.is_object() => base.patched(patch).map_err(|e| bad(C, e))?, + Some(_) => return Err(bad(C, "settings must be an object")), + None => base, + }; + s.set_prep_settings(next, library)?; + Ok(s.prep_json()) + } + ), cmd!("library.cancelPreviews", "Cancel Preview Build", [], None, "{}", always, |s, _| { if let Some(b) = &s.preview_build { b.cancel.store(true, Ordering::Relaxed); @@ -730,6 +1042,7 @@ mod tests { fallback: None, denoise: None, camera_profile: None, + outliers: false, reduced: None, }; assert!(run_photo(jobs), "the thumbnail rendered from the view's decoded source"); diff --git a/crates/engine/src/cmd/query.rs b/crates/engine/src/cmd/query.rs index 5ceacb9539..8b96430248 100644 --- a/crates/engine/src/cmd/query.rs +++ b/crates/engine/src/cmd/query.rs @@ -273,6 +273,21 @@ pub fn specs() -> Vec { } Ok(serde_json::to_value(s.memory_report()).unwrap_or_default()) }), + cmd!(query "app.hotPixelLimit", "Hot Pixel Limit", [], None, "{percent?: number} — Remove Hot Pixels leaves a raw alone when more than this share of its photosites would be replaced (0.001..100 %, default 0.2 %; real light it keeps doesn't count); returns {percent, default}", always, |s, p| { + if let Some(v) = p.get("percent").filter(|v| !v.is_null()) { + let Some(percent) = v.as_f64().filter(|x| (0.001..=100.0).contains(x)) else { + return Err(bad("app.hotPixelLimit", "percent must be a number in 0.001..100")); + }; + // (the default as an `f32` from the app's settings, 0.2000000029…, is the default: its keys stay) + let default = lightcraft_raw::HOT_PIXEL_MAX_SHARE; + let share = if (percent / 100.0 / default - 1.0).abs() < 1e-6 { default } else { percent / 100.0 }; + if crate::files::set_hot_pixel_limit(share) { + // decoded with the old limit, and their render keys change + s.media.clear_sources(); + } + } + Ok(json!({"percent": crate::files::hot_pixel_limit() * 100.0, "default": lightcraft_raw::HOT_PIXEL_MAX_SHARE * 100.0})) + }), cmd!(query "journal.list", "Command Journal", [], None, "{limit?}", always, |s, p| { let lim = p.get("limit").and_then(Value::as_u64).unwrap_or(100) as usize; let start = s.journal.len().saturating_sub(lim); diff --git a/crates/engine/src/denoise.rs b/crates/engine/src/denoise.rs index 44ef3eef72..d12c97f6ff 100644 --- a/crates/engine/src/denoise.rs +++ b/crates/engine/src/denoise.rs @@ -36,6 +36,7 @@ use crate::merge::ByteReader; use crate::model_download::Downloads; use crate::{Selection, Session}; +mod builtin; mod gpu; mod model; mod products; diff --git a/crates/engine/src/denoise/builtin.rs b/crates/engine/src/denoise/builtin.rs new file mode 100644 index 0000000000..7816d13f5b --- /dev/null +++ b/crates/engine/src/denoise/builtin.rs @@ -0,0 +1,325 @@ +use super::gpu::GPU_SETUP_MARKER; +#[cfg(feature = "denoise")] +use super::gpu::{GPU_MAX_FALLBACKS, GPU_PARALLEL, GPU_SETUP_LIMIT, card_is_faster, card_tile_ms, set_up_card}; +#[cfg(feature = "denoise")] +use super::model::worth_retrying; +use super::model::{Model, RunOn}; +#[cfg(feature = "denoise")] +use super::state::Pace; +#[cfg(feature = "denoise")] +use super::{Arc, AtomicUsize, Mutex, Ordering, PoisonError, RunError}; +use super::{OnceLock, Path, PathBuf, TileRunner, Value, json}; + +/// The built-in denoiser (`lightcraft_denoise::builtin`): nothing to load, so it is what runs until a model is chosen. Its +/// filter runs on the graphics card when there is one that agrees with the CPU on a check tile and is faster, else on +/// the CPU (see [`BuiltinCard`]); the rest of it always runs on the CPU. +pub(super) struct BuiltinModel { + runner: OnceLock, + #[cfg(feature = "denoise")] + card: Arc, + /// The runner of a photo that runs on the card. + #[cfg(feature = "denoise")] + hybrid: OnceLock, +} + +impl BuiltinModel { + /// For a photo, with the card's state for the set-up marker `marker` (where its set-up is recorded). + pub(super) fn new(#[cfg_attr(not(feature = "denoise"), allow(unused_variables))] marker: &Path) -> Self { + BuiltinModel { + runner: OnceLock::new(), + #[cfg(feature = "denoise")] + card: builtin_card(marker), + #[cfg(feature = "denoise")] + hybrid: OnceLock::new(), + } + } +} + +impl Model for BuiltinModel { + fn runner(&self, run_on: RunOn, threads: usize) -> (&dyn TileRunner, usize) { + let cpu = self.runner.get_or_init(Default::default); + #[cfg(feature = "denoise")] + { + let threads = threads.max(1); + self.card.last_threads.store(threads, Ordering::Relaxed); + if let Ok(side) = self.card.choose(run_on, threads, true) + && let Ok(gpu) = lightcraft_gpu::bm3d::BuiltinRunner::new(side.gpu.clone(), *cpu) + { + let hybrid = self.hybrid.get_or_init(|| CardRunner { gpu, cpu: *cpu, card: self.card.clone() }); + return (hybrid, threads.min(GPU_PARALLEL)); + } + } + #[cfg(not(feature = "denoise"))] + let _ = run_on; + (cpu, threads) + } + + /// Measure the whole photo's noise once, so every tile is cleaned by the photo's noise instead of its own. A photo + /// that cannot be measured is told nothing: each tile then measures its own. + fn prepare(&self, mosaic: &[f32], width: usize, height: usize) { + if let Some(noise) = lightcraft_denoise::builtin::measure_noise(mosaic, width, height) { + let _ = self.runner.set(lightcraft_denoise::builtin::Builtin::with_noise(noise)); + } + } + + fn self_test(&self, _run_on: RunOn) -> Result { + let side = 16; + let out = lightcraft_denoise::builtin::Builtin::with_noise((0.01, 0.001)).run(&vec![0.25; 4 * side * side]).map_err(|e| e.to_string())?; + if out.len() != 12 * side * side || out.iter().any(|v| !v.is_finite()) { + return Err("the built-in denoiser gave an unexpected result".into()); + } + Ok(json!({"ok": true, "builtin": true})) + } + + /// Planes, the two mosaics and the working copies of a 256-cell tile. + fn bytes_per_tile(&self) -> usize { + 64 * 1024 * 1024 + } + + fn device(&self, run_on: RunOn) -> Value { + #[cfg(feature = "denoise")] + { + self.card.device(run_on) + } + #[cfg(not(feature = "denoise"))] + { + let _ = run_on; + json!({"kind": "cpu", "reason": "built-in"}) + } + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// the built-in denoiser on the graphics card + +/// The noise the check tile is made with and the built-in denoiser is told for it (variance = a · signal + b). +#[cfg(feature = "denoise")] +const CHECK_NOISE: (f32, f32) = (0.01, 0.001); +/// How far the card's filter may be from the CPU's on the check tile, in the noise's deviations: at most this at one place +/// (a few blocks whose match or threshold falls either side of a tie in the two devices' roundings change by up to about a +/// tenth; a broken kernel by far more), and this on average. +#[cfg(feature = "denoise")] +const BUILTIN_AGREE_WORST: f32 = 0.3; +#[cfg(feature = "denoise")] +const BUILTIN_AGREE_MEAN: f32 = 1e-3; + +/// A mosaic tile (four planes of `side` cells): a ramp, edges and some texture with noise of [`CHECK_NOISE`], the same +/// every time. +#[cfg(feature = "denoise")] +fn builtin_check_tile(side: usize) -> Vec { + let mut state = 0x2545_f491_4f6c_dd1du64; + let mut uniform = move || { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((state >> 40) as f32 + 0.5) / (1u64 << 24) as f32 + }; + let mut out = Vec::with_capacity(4 * side * side); + for plane in 0..4 { + for i in 0..side * side { + let (x, y) = (i % side, i / side); + let step = if (x / 37 + y / 29) % 2 == 0 { 0.25 } else { 0.0 }; + let signal = + (0.1 + 0.4 * x as f32 / side as f32 + 0.1 * y as f32 / side as f32 + step + 0.05 * ((x as f32 + 4.0 * plane as f32) * 0.7).sin()) + .clamp(0.02, 0.95); + let (u, v) = (uniform(), uniform()); + let noise = (-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos(); + out.push((signal + noise * (CHECK_NOISE.0 * signal + CHECK_NOISE.1).sqrt()).max(0.0)); + } + } + out +} + +/// The card set up for the built-in denoiser: its kernels, and the check tile's time on it and on the CPU. +#[cfg(feature = "denoise")] +struct BuiltinGpu { + gpu: Arc, + adapter: String, + /// The check tile on the card, the fastest of a few runs (ms). + card_ms: f64, + /// The check tile on the CPU, on one thread (ms). + cpu_ms: f64, +} + +/// Set the card up for the built-in denoiser: kernels built, the check tile run on both and compared, both timed. +#[cfg(feature = "denoise")] +fn make_builtin_gpu(marker: &Path) -> Result { + use lightcraft_denoise::builtin::{Builtin, TILE}; + let tile = TILE as usize; + let builtin = Builtin::with_noise(CHECK_NOISE); + let params = builtin.bm3d_params().ok_or("the built-in denoiser does not use the block-matching filter")?; + let input = Arc::new(builtin_check_tile(tile)); + let on_card = input.clone(); + let card = move || -> Result<_, String> { + let gpu = Arc::new(lightcraft_gpu::bm3d::Bm3dGpu::new(¶ms, tile)?); + let runner = lightcraft_gpu::bm3d::BuiltinRunner::new(gpu.clone(), builtin)?; + let agreement = runner.agreement(&on_card).map_err(|e| format!("the GPU could not run the check tile: {e}"))?; + let whole = runner.run(&on_card).map_err(|e| format!("the GPU could not run the check tile: {e}"))?; + let card_ms = card_tile_ms(&runner, &on_card); + Ok((gpu, agreement, whole, card_ms)) + }; + let on_cpu = || { + let started = web_time::Instant::now(); + (builtin.run(&input), started.elapsed().as_secs_f64() * 1000.0) + }; + let ((gpu, agreement, whole, card_ms), (want, cpu_ms)) = set_up_card(marker, GPU_SETUP_LIMIT, card, on_cpu)?; + let want = want.map_err(|e| format!("the CPU could not check the GPU: {e}"))?; + if whole.len() != want.len() || !whole.iter().all(|v| v.is_finite()) { + return Err("its picture of the check tile is not the CPU's size or has numbers that are not finite: not used".into()); + } + if !(agreement.worst <= BUILTIN_AGREE_WORST && agreement.mean <= BUILTIN_AGREE_MEAN) { + return Err(format!( + "its filter's answer on the check tile is not the CPU's (off by {:.2} at most and {:.1e} on average, in noise deviations): not used", + agreement.worst, agreement.mean + )); + } + let adapter = gpu.adapter(); + Ok(BuiltinGpu { gpu, adapter, card_ms, cpu_ms }) +} + +/// What the built-in denoiser knows about the graphics card in this process: set up for the first photo that may use it, +/// and used while it keeps working. Kept by the marker of its set-up (see [`builtin_card`]) so that every photo shares it. +#[cfg(feature = "denoise")] +pub(super) struct BuiltinCard { + marker: PathBuf, + gpu: OnceLock>, + /// Tiles the card got wrong (an error, numbers that are not finite) and the CPU ran. + fallbacks: AtomicUsize, + /// Tiles at once of the photo started last (0: none yet), to say where the work runs. + last_threads: AtomicUsize, +} + +#[cfg(feature = "denoise")] +static BUILTIN_CARDS: Mutex)>> = Mutex::new(Vec::new()); + +/// The card's state for the set-up marker `marker`, made the first time it is asked for. +#[cfg(feature = "denoise")] +pub(super) fn builtin_card(marker: &Path) -> Arc { + let mut all = BUILTIN_CARDS.lock().unwrap_or_else(PoisonError::into_inner); + if let Some((_, c)) = all.iter().find(|(m, _)| m == marker) { + return c.clone(); + } + let c = Arc::new(BuiltinCard { + marker: marker.to_path_buf(), + gpu: OnceLock::new(), + fallbacks: AtomicUsize::new(0), + last_threads: AtomicUsize::new(0), + }); + all.push((marker.to_path_buf(), c.clone())); + c +} + +/// Forget the card's state for the marker (and the marker): the card is tried afresh for the next photo. +#[cfg(feature = "denoise")] +pub(super) fn forget_builtin_card(marker: &Path) { + BUILTIN_CARDS.lock().unwrap_or_else(PoisonError::into_inner).retain(|(m, _)| m != marker); + let _ = std::fs::remove_file(marker); +} + +/// Where the card's set-up is recorded for the built-in denoiser whose `onnx` is its model's (made-up) path in the models +/// folder: beside it, and in the temporary folder when there is no models folder. +pub(super) fn builtin_marker(onnx: &Path) -> PathBuf { + match onnx.parent() { + Some(p) if !p.as_os_str().is_empty() => onnx.with_file_name(GPU_SETUP_MARKER), + _ => std::env::temp_dir().join(format!("lightcraft-builtin-{GPU_SETUP_MARKER}")), + } +} + +#[cfg(feature = "denoise")] +impl BuiltinCard { + /// The card when it can be used now, else why not. `start` sets it up when that has not been tried yet; without it + /// nothing is started. + fn card(&self, start: bool) -> Result<&BuiltinGpu, String> { + let side = if start { + Some(self.gpu.get_or_init(|| { + let made = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| make_builtin_gpu(&self.marker))) + .unwrap_or_else(|_| Err("the GPU runner gave up".into())); + if let Err(why) = &made { + log::info!("denoise: the built-in denoiser runs on the CPU ({why})"); + } + made + })) + } else { + self.gpu.get() + }; + let g = match side { + None => return Err("the graphics card is not set up yet".into()), + Some(Err(why)) => return Err(why.clone()), + Some(Ok(g)) => g, + }; + if let Some(why) = lightcraft_gpu::nn::broken_reason() { + return Err(format!("the graphics card stopped working ({why})")); + } + if self.fallbacks.load(Ordering::Relaxed) >= GPU_MAX_FALLBACKS { + return Err(format!("{} got {GPU_MAX_FALLBACKS} tiles wrong", g.adapter)); + } + Ok(g) + } + + /// The card, when a photo made `threads` tiles at a time under `run_on` runs on it; else why the CPU does. + fn choose(&self, run_on: RunOn, threads: usize, start: bool) -> Result<&BuiltinGpu, String> { + if run_on == RunOn::Cpu { + return Err("the processor is chosen in Settings".into()); + } + let g = self.card(start)?; + if run_on == RunOn::Auto && !card_is_faster(g.card_ms, g.cpu_ms, threads) { + return Err(format!("it is faster than {} on this computer", g.adapter)); + } + Ok(g) + } + + fn fell_back(&self, why: &str) { + let n = self.fallbacks.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 { + log::warn!("denoise: a tile came back wrong from the GPU ({why}); the CPU runs it"); + } else if n == GPU_MAX_FALLBACKS { + log::warn!("denoise: the GPU got {n} tiles wrong; the CPU does the rest"); + } + } + + /// Where the tiles run (see [`Model::device`]). + pub(super) fn device(&self, run_on: RunOn) -> Value { + if run_on != RunOn::Cpu && self.gpu.get().is_none() { + return json!({"kind": "pending"}); + } + let threads = match self.last_threads.load(Ordering::Relaxed) { + 0 => Pace::Full.parallel(std::thread::available_parallelism().map_or(1, |n| n.get()), None), + n => n, + }; + let mut v = match self.choose(run_on, threads, false) { + Ok(g) => json!({"kind": "gpu", "adapter": g.adapter}), + // a set-up that crashed or ran out of time can be tried again (`denoise.settings {runOn}`) + Err(why) => json!({"kind": "cpu", "retry": worth_retrying(&why), "reason": why}), + }; + if let (Some(Ok(g)), Some(o)) = (self.gpu.get(), v.as_object_mut()) { + o.insert("cardMs".into(), json!(g.card_ms)); + o.insert("cpuMs".into(), json!(g.cpu_ms)); + o.insert("fellBack".into(), json!(self.fallbacks.load(Ordering::Relaxed))); + } + v + } +} + +/// The built-in denoiser for a photo that runs on the card: the filter there, and the CPU running any tile the card gets +/// wrong, so a photo is always finished. +#[cfg(feature = "denoise")] +struct CardRunner { + gpu: lightcraft_gpu::bm3d::BuiltinRunner, + cpu: lightcraft_denoise::builtin::Builtin, + card: Arc, +} + +#[cfg(feature = "denoise")] +impl TileRunner for CardRunner { + fn run(&self, input: &[f32]) -> Result, RunError> { + if self.card.card(false).is_ok() { + match self.gpu.run(input) { + Ok(out) if out.iter().all(|v| v.is_finite()) => return Ok(out), + Ok(_) => self.card.fell_back("numbers that are not finite"), + Err(e) => self.card.fell_back(&e.to_string()), + } + } + self.cpu.run(input) + } +} + +#[cfg(all(test, feature = "denoise"))] +mod tests; diff --git a/crates/engine/src/denoise/builtin/tests.rs b/crates/engine/src/denoise/builtin/tests.rs new file mode 100644 index 0000000000..ef85e8559f --- /dev/null +++ b/crates/engine/src/denoise/builtin/tests.rs @@ -0,0 +1,155 @@ +use super::*; +use crate::denoise::forget_gpu_set_ups; + +/// A folder of the test's own: the card's set-up leaves its marker in it. +fn folder(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-engine-builtin-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// The built-in denoiser for one photo of `noise` `(a, b)`, its card state kept by a marker in a folder of its own. +fn builtin(name: &str) -> (BuiltinModel, PathBuf) { + let dir = folder(name); + let m = BuiltinModel::new(&dir.join(GPU_SETUP_MARKER)); + let _ = m.runner.set(lightcraft_denoise::builtin::Builtin::with_noise(CHECK_NOISE)); + (m, dir) +} + +/// Compare a tile from the card with the CPU's picture: equal on average, and with few values far off. (The demosaic +/// chooses a direction at each pixel, so a tiny difference of the filter can change a pixel by a good deal.) +fn agree(want: &[f32], got: &[f32]) { + assert_eq!(want.len(), got.len()); + let scale = want.iter().fold(1e-9f32, |m, v| m.max(v.abs())); + let mean = want.iter().zip(got).map(|(a, b)| (a - b).abs()).sum::() / want.len() as f32 / scale; + let far = want.iter().zip(got).filter(|(a, b)| (*a - *b).abs() > 0.05 * scale).count() as f32 / want.len() as f32; + assert!(mean < 1e-3 && far < 5e-3, "off by {mean:e} on average of the largest value, {far:e} of the values far off"); +} + +/// With the card chosen, the built-in denoiser's tile agrees with the processor's, a few tiles feed the card at once, +/// and a set-up that ended leaves no marker; where there is no card it stays on the processor. +#[test] +fn the_built_in_denoiser_on_the_card_gives_the_cpus_tile() { + use lightcraft_denoise::builtin::{Builtin, TILE}; + let (m, dir) = builtin("builtin-card"); + let tile = builtin_check_tile(TILE as usize); + let want = Builtin::with_noise(CHECK_NOISE).run(&tile).unwrap(); + let (runner, at_once) = m.runner(RunOn::Gpu, 16); + let device = m.device(RunOn::Gpu); + eprintln!("device: {device}"); + match device["kind"].as_str() { + Some("gpu") => { + assert!(at_once <= GPU_PARALLEL, "a card is fed by a few tiles at once"); + agree(&want, &runner.run(&tile).unwrap()); + assert!(device["cardMs"].as_f64().is_some_and(|ms| ms > 0.0) && device["cpuMs"].as_f64().is_some_and(|ms| ms > 0.0), "{device}"); + } + Some("cpu") => { + lightcraft_testkit::skip!(Gpu, "the built-in denoiser stays on the CPU here: {}", device["reason"]); + assert_eq!(at_once, 16); + } + other => panic!("the first photo decides where the work runs, not {other:?}"), + } + assert!(!dir.join(GPU_SETUP_MARKER).exists(), "a set-up that ended leaves no marker"); + forget_builtin_card(&dir.join(GPU_SETUP_MARKER)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// With the processor chosen, the built-in denoiser gives the processor's tile bit for bit, uses all the threads +/// asked for and never sets the card up. +#[test] +fn with_the_processor_chosen_the_built_in_denoiser_runs_on_the_cpu_and_never_starts_the_card() { + use lightcraft_denoise::builtin::{Builtin, TILE}; + let (m, dir) = builtin("builtin-cpu"); + let tile = builtin_check_tile(TILE as usize); + let (runner, at_once) = m.runner(RunOn::Cpu, 16); + assert_eq!(runner.run(&tile).unwrap(), Builtin::with_noise(CHECK_NOISE).run(&tile).unwrap(), "the CPU path is the CPU runner, bit for bit"); + assert_eq!(at_once, 16, "the threads asked for are the threads used"); + assert_eq!(m.device(RunOn::Cpu)["kind"], "cpu"); + assert_eq!(m.device(RunOn::Auto)["kind"], "pending", "the card was not even set up"); + forget_builtin_card(&dir.join(GPU_SETUP_MARKER)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A set-up marker left behind (the app closed while it ran) keeps the card off the built-in denoiser, with a reason +/// and a retry, until choosing where denoise runs forgets it. +#[test] +fn a_set_up_marker_left_behind_keeps_the_card_off_the_built_in_denoiser_until_a_choice_is_made() { + let (m, dir) = builtin("builtin-marker"); + let marker = dir.join(GPU_SETUP_MARKER); + std::fs::write(&marker, "setting up the graphics card for AI Denoise (unix time 1)\n").unwrap(); + let (_, at_once) = m.runner(RunOn::Gpu, 6); + assert_eq!(at_once, 6, "no card: the threads asked for"); + let device = m.device(RunOn::Gpu); + assert_eq!(device["kind"], "cpu", "{device}"); + assert_eq!(device["retry"], true, "{device}"); + assert!(device["reason"].as_str().unwrap().contains("closed"), "{device}"); + // choosing where denoise runs forgets it (and the marker): the card is set up afresh for the next photo + forget_gpu_set_ups(&dir); + assert!(!marker.exists()); + let (again, _) = builtin("builtin-marker-again"); + assert_eq!(again.device(RunOn::Auto)["kind"], "pending"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The card's filter stays within the agreement limits of the processor's on the check tile, well inside them, and +/// gives the same answer every time. +#[test] +fn the_cards_filter_agrees_with_the_cpus_on_the_check_tile_and_gives_the_same_answer_every_time() { + use lightcraft_denoise::builtin::{Builtin, TILE}; + let tile = builtin_check_tile(TILE as usize); + let b = Builtin::with_noise(CHECK_NOISE); + let params = b.bm3d_params().unwrap(); + let gpu = match lightcraft_gpu::bm3d::Bm3dGpu::new(¶ms, TILE as usize) { + Ok(g) => Arc::new(g), + Err(why) => return lightcraft_testkit::skip!(Gpu, "no card for the built-in denoiser here: {why}"), + }; + let runner = lightcraft_gpu::bm3d::BuiltinRunner::new(gpu, b).unwrap(); + let a = runner.agreement(&tile).unwrap(); + eprintln!("the card's filter is off by {:.3} at most and {:.1e} on average (noise deviations)", a.worst, a.mean); + assert!(a.worst <= BUILTIN_AGREE_WORST && a.mean <= BUILTIN_AGREE_MEAN, "{a:?}"); + assert!(a.worst < 0.15 && a.mean < 1e-4, "a card within the limits but far from what it manages: {a:?}"); + let (first, again) = (runner.run(&tile).unwrap(), runner.run(&tile).unwrap()); + assert_eq!(first, again, "the card gives the same answer every time"); + agree(&Builtin::with_noise(CHECK_NOISE).run(&tile).unwrap(), &first); +} + +/// A tile the card cannot do (another size than it was made for) is run on the processor, and after three of them +/// the card is stopped for the built-in denoiser. +#[test] +fn a_tile_the_card_gets_wrong_is_run_on_the_processor_and_three_stop_the_card_for_the_built_in_denoiser() { + use lightcraft_denoise::builtin::Builtin; + let (m, dir) = builtin("builtin-wrong"); + let (_, _) = m.runner(RunOn::Gpu, 8); + if m.device(RunOn::Gpu)["kind"] != "gpu" { + lightcraft_testkit::skip!(Gpu, "no card for the built-in denoiser here: {}", m.device(RunOn::Gpu)["reason"]); + forget_builtin_card(&dir.join(GPU_SETUP_MARKER)); + let _ = std::fs::remove_dir_all(&dir); + return; + } + // a tile of another size than the card was made for is one it cannot do: the CPU runs it, and three stop the card + let small = 64; + let input = builtin_check_tile(small); + let want = Builtin::with_noise(CHECK_NOISE).run(&input).unwrap(); + let (runner, _) = m.runner(RunOn::Gpu, 8); + for _ in 0..GPU_MAX_FALLBACKS { + assert_eq!(runner.run(&input).unwrap(), want, "a tile the card cannot do is the CPU's tile"); + } + let device = m.device(RunOn::Gpu); + assert_eq!(device["kind"], "cpu", "{device}"); + assert!(device["reason"].as_str().unwrap().contains("tiles wrong"), "{device}"); + assert_eq!(device["fellBack"], GPU_MAX_FALLBACKS); + let (_, at_once) = m.runner(RunOn::Gpu, 8); + assert_eq!(at_once, 8, "the next photo runs on the CPU, even with the card chosen"); + forget_builtin_card(&dir.join(GPU_SETUP_MARKER)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A photo whose noise cannot be measured is not told a made-up noise (which would leave it undenoised): the runner +/// keeps measuring each tile's own. +#[test] +fn a_photo_whose_noise_cannot_be_measured_leaves_the_runner_to_measure_each_tile() { + let m = BuiltinModel::new(&std::env::temp_dir().join("lc-engine-builtin-unmeasured")); + m.prepare(&[0.5; 100], 10, 10); + assert!(m.runner.get().is_none(), "nothing was measured, so nothing is set"); +} diff --git a/crates/engine/src/denoise/gpu.rs b/crates/engine/src/denoise/gpu.rs index a2a493fab9..0c662d0d1c 100644 --- a/crates/engine/src/denoise/gpu.rs +++ b/crates/engine/src/denoise/gpu.rs @@ -14,7 +14,7 @@ const GPU_AGREE: f32 = 1e-3; /// Longest the card may take to set up (build its kernels, run the check tile, time it) before the processor does the /// work instead. #[cfg(feature = "denoise")] -const GPU_SETUP_LIMIT: Duration = Duration::from_secs(30); +pub(super) const GPU_SETUP_LIMIT: Duration = Duration::from_secs(30); /// Tiles the card may get wrong (an error, numbers that are not finite) before it stops being used for the model. #[cfg(feature = "denoise")] @@ -80,7 +80,10 @@ pub(super) fn set_up_card( return Err(GPU_CRASHED.into()); } let secs = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map_or(0, |d| d.as_secs()); - // a marker that cannot be written only loses the crash guard + // the models folder may not exist yet; a marker that cannot be written only loses the crash guard + if let Some(parent) = marker.parent() { + let _ = std::fs::create_dir_all(parent); + } let _ = std::fs::write(marker, format!("setting up the graphics card for AI Denoise (unix time {secs})\n")); running.push(marker.to_path_buf()); SetUpEnded(marker.to_path_buf()) @@ -107,7 +110,7 @@ pub(super) fn set_up_card( /// The card's time for one tile once it is warm: the fastest of up to three runs, stopping after about two seconds (a /// slow card is slow enough to tell at once). #[cfg(feature = "denoise")] -fn card_tile_ms(runner: &dyn TileRunner, input: &[f32]) -> f64 { +pub(super) fn card_tile_ms(runner: &dyn TileRunner, input: &[f32]) -> f64 { if runner.run(input).is_err() { return f64::INFINITY; } diff --git a/crates/engine/src/denoise/gpu_tests.rs b/crates/engine/src/denoise/gpu_tests.rs index bff11cc20c..71081d9c11 100644 --- a/crates/engine/src/denoise/gpu_tests.rs +++ b/crates/engine/src/denoise/gpu_tests.rs @@ -279,6 +279,26 @@ fn a_set_up_runs_beside_the_cpu_and_removes_its_marker() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_set_up_makes_the_folder_of_its_marker() { + let dir = folder("setup-folder").join("not").join("yet"); + let marker = dir.join(GPU_SETUP_MARKER); + let (m, seen) = (marker.clone(), Arc::new(AtomicBool::new(false))); + let s = seen.clone(); + let r = set_up_card( + &marker, + Duration::from_secs(10), + move || { + s.store(m.exists(), Ordering::Relaxed); + Ok(()) + }, + || (), + ); + assert_eq!(r, Ok(((), ()))); + assert!(seen.load(Ordering::Relaxed), "the crash guard is written even when the models folder was missing"); + let _ = std::fs::remove_dir_all(dir.ancestors().nth(2).unwrap_or(&dir)); +} + #[test] fn a_set_up_that_takes_too_long_is_given_up_on() { let dir = folder("slowsetup"); diff --git a/crates/engine/src/denoise/model.rs b/crates/engine/src/denoise/model.rs index c906415746..253668c2c9 100644 --- a/crates/engine/src/denoise/model.rs +++ b/crates/engine/src/denoise/model.rs @@ -51,6 +51,8 @@ pub(crate) trait Model: Send + Sync { /// What runs a photo's tiles, and how many to run at once, when `threads` may be used and the setting is `run_on` /// (a graphics card is kept busy by a few). The first time the card may be used it is set up and checked here. fn runner(&self, run_on: RunOn, threads: usize) -> (&dyn TileRunner, usize); + /// Called once per photo with its whole mosaic before the tiles run, for a model that adapts to the photo. + fn prepare(&self, _mosaic: &[f32], _width: usize, _height: usize) {} /// Check it does something sensible: the test's result, or why not. Unless `run_on` is the processor the graphics /// card is set up and checked too, and the result says where the work will run. fn self_test(&self, run_on: RunOn) -> Result; diff --git a/crates/engine/src/denoise/products.rs b/crates/engine/src/denoise/products.rs index bf601b14d1..8aab9a2a4d 100644 --- a/crates/engine/src/denoise/products.rs +++ b/crates/engine/src/denoise/products.rs @@ -1,3 +1,4 @@ +use super::builtin::{BuiltinModel, builtin_marker}; use super::model::{Loader, Model, ModelSlot, RunOn, STACK}; use super::settings::EXT; use super::{ @@ -133,6 +134,9 @@ impl Progress { /// The loaded model, loading it first when it is not (kept for the next photo). pub(super) fn loaded(spec: &JobSpec) -> Result, MakeError> { + if spec.manifest.id == lightcraft_denoise::builtin::ID { + return Ok(Arc::new(BuiltinModel::new(&builtin_marker(&spec.onnx)))); + } if let Some(m) = spec.model.lock().unwrap_or_else(PoisonError::into_inner).clone() { return Ok(m); } @@ -196,6 +200,10 @@ pub(crate) fn make_product(spec: &JobSpec, progress: Option<&Progress>) -> Resul let (_, budget) = crate::memory::work_gate().usage(); let parallel = spec.parallel.clamp(1, 4).min((budget / scratch.max(1)).max(1)); let _held = crate::memory::work_gate().acquire(mosaic.data.len().saturating_mul(20).saturating_add(scratch.saturating_mul(parallel))); + model.prepare(&mosaic.data, mosaic.width, mosaic.height); + if cancelled() { + return Err(MakeError::Cancelled); + } let (runner, parallel) = model.runner(spec.run_on, parallel); let params = Params { tile: spec.manifest.tile as usize, diff --git a/crates/engine/src/denoise/session.rs b/crates/engine/src/denoise/session.rs index 10529d61db..b01a669bb5 100644 --- a/crates/engine/src/denoise/session.rs +++ b/crates/engine/src/denoise/session.rs @@ -1,3 +1,5 @@ +#[cfg(feature = "denoise")] +use super::builtin::{builtin_card, builtin_marker}; #[cfg(doc)] use super::model::Model; use super::model::STACK; @@ -15,6 +17,11 @@ impl Session { let loaded = self.denoise.active.as_ref().and_then(|a| a.model.lock().unwrap_or_else(PoisonError::into_inner).clone()); match loaded { Some(m) => m.device(self.denoise.settings.run_on()), + #[cfg(feature = "denoise")] + None if self.denoise.active.as_ref().is_some_and(|a| a.id == lightcraft_denoise::builtin::ID) => { + let onnx = self.denoise.active.as_ref().map(|a| a.onnx.clone()).unwrap_or_default(); + builtin_card(&builtin_marker(&onnx)).device(self.denoise.settings.run_on()) + } None => json!({"kind": "none"}), } } @@ -37,23 +44,20 @@ impl Session { let id = self.denoise.settings.model.clone()?; installed_models(dir).into_iter().find(|i| i.manifest.id == id) }); - let found = chosen.map(|i| (i.fingerprint(), i)); - let same = match (&self.denoise.active, &found) { - (None, None) => true, - (Some(a), Some((fp, _))) => a.fingerprint == *fp, - _ => false, + // no model chosen (or the one chosen is gone): the built-in denoiser + let (fingerprint, manifest, onnx) = match chosen { + Some(i) => (i.fingerprint(), i.manifest, i.onnx), + None => { + let manifest = lightcraft_denoise::builtin::manifest(); + let onnx = self.denoise.models_dir.as_deref().map(|d| d.join(lightcraft_denoise::builtin::ID)).unwrap_or_default(); + (format!("{}@{}", manifest.id, manifest.version), manifest, onnx) + } }; - if same { + if self.denoise.active.as_ref().is_some_and(|a| a.fingerprint == fingerprint) { return; } // another model: what was made with the old one is not this one's, and what failed may work now - self.denoise.active = found.map(|(fingerprint, i)| Active { - id: i.manifest.id.clone(), - manifest: i.manifest, - onnx: i.onnx, - fingerprint, - model: Arc::new(Mutex::new(None)), - }); + self.denoise.active = Some(Active { id: manifest.id.clone(), manifest, onnx, fingerprint, model: Arc::new(Mutex::new(None)) }); if let Some(r) = self.denoise.running.take() { r.progress.cancel_now(); } @@ -142,8 +146,8 @@ impl Session { return PhotoState::NotApplicable; } if self.denoise.active.is_none() { - // the model folder has not been looked at yet (just started): not "no model" until it has been - return if self.denoise.active_seen.is_none() { PhotoState::Idle } else { PhotoState::NoModel }; + // the model in use has not been looked at yet (just started) + return PhotoState::Idle; } if self.denoise_products_dir().is_none() { return PhotoState::Failed { @@ -310,8 +314,12 @@ impl Session { /// Keep the cache within its limit: the pictures nobody asks for go first, the oldest first; `keep` (the one just /// made) never goes. The index forgets what was deleted. pub(crate) fn denoise_evict(&mut self, keep: Option<&Path>) { - let Some(models) = self.denoise.models_dir.clone() else { return }; - self.denoise_evict_to(read_settings(&models).cache_bytes(), keep); + self.denoise_evict_to(self.denoise_cache_limit(), keep); + } + + /// The cache's size limit in bytes (the default without a models folder). + pub(crate) fn denoise_cache_limit(&self) -> u64 { + self.denoise.models_dir.as_deref().map(read_settings).unwrap_or_default().cache_bytes() } /// [`Self::denoise_evict`] for a limit of `limit` bytes. diff --git a/crates/engine/src/denoise/settings.rs b/crates/engine/src/denoise/settings.rs index d71c7b0745..247007cbd8 100644 --- a/crates/engine/src/denoise/settings.rs +++ b/crates/engine/src/denoise/settings.rs @@ -1,3 +1,5 @@ +#[cfg(feature = "denoise")] +use super::builtin::{builtin_marker, forget_builtin_card}; use super::gpu::GPU_SETUP_MARKER; use super::model::RunOn; use super::{DenoiserManifest, Deserialize, Duration, Path, PathBuf, Serialize, Value}; @@ -108,7 +110,7 @@ pub(crate) fn installed_models(dir: &Path) -> Vec { let p = e.path(); let Some(name) = p.file_name().and_then(|n| n.to_str()).map(str::to_string) else { continue }; let onnx = p.join("model.onnx"); - if !lightcraft_denoise::licence::valid_id(&name) || !p.is_dir() || !onnx.is_file() { + if name == lightcraft_denoise::builtin::ID || !lightcraft_denoise::licence::valid_id(&name) || !p.is_dir() || !onnx.is_file() { continue; } let Some(m) = read_capped(&p.join("denoise-model.json"), lightcraft_denoise::manifest::MAX_MANIFEST_BYTES) @@ -132,4 +134,6 @@ pub(crate) fn forget_gpu_set_ups(dir: &Path) { for i in installed_models(dir) { let _ = std::fs::remove_file(i.onnx.with_file_name(GPU_SETUP_MARKER)); } + #[cfg(feature = "denoise")] + forget_builtin_card(&builtin_marker(&dir.join(lightcraft_denoise::builtin::ID))); } diff --git a/crates/engine/src/denoise/state.rs b/crates/engine/src/denoise/state.rs index 37b79cf8b9..027ce0a43f 100644 --- a/crates/engine/src/denoise/state.rs +++ b/crates/engine/src/denoise/state.rs @@ -54,8 +54,6 @@ impl Pace { pub enum PhotoState { /// Not a photo denoise applies to (not a raw, offline, a demo). NotApplicable, - /// No model is chosen: nothing can be made. - NoModel, /// Its picture is made: the Amount slider works. Ready, Queued { diff --git a/crates/engine/src/disk_space.rs b/crates/engine/src/disk_space.rs new file mode 100644 index 0000000000..eb7f29e967 --- /dev/null +++ b/crates/engine/src/disk_space.rs @@ -0,0 +1,577 @@ +//! A once-per-session alert when the drive holding the library's preview cache runs low. +//! +//! The automatic preview cache budget grows with the library and has no ceiling +//! ([`crate::media::default_disk_cache_bytes`]): a large library can fill its drive. Rather than cap +//! it, the session looks at the drive's free space when the library opens and, at most every +//! [`CHECK_EVERY`] while the app runs (thumbnails and previews fill the cache); when it is under [`LOW_FREE_PERCENT`] of the drive or +//! under [`LOW_FREE_BYTES`], it hands out one [`LowDiskAlert`] ([`crate::Session::take_disk_space_alert`]) +//! that the UI shows with a way to Settings ▸ Performance, where the cache can be given a limit. It is +//! not repeated until the next library open or app run. Reading the free space can fail (a network +//! share that doesn't say, the web build): then there is no alert, only a log line. +//! Natively the read runs on a worker thread and its answer is taken on a later call, so a slow +//! network share never holds up the UI thread that asks. + +use std::path::Path; + +/// The drive is low when less than this share of it (percent) is free… +pub const LOW_FREE_PERCENT: u64 = 10; +/// …or when less than this is free (20 GB), whichever comes first. +pub const LOW_FREE_BYTES: u64 = 20 << 30; +/// While a library is open, the free space is read at most this often (statvfs on the cache's +/// drive: cheap, but not something for every frame or every write). +pub const CHECK_EVERY: std::time::Duration = std::time::Duration::from_secs(5 * 60); +/// A read when the library opens that hasn't answered after this long shows in the activity stack. +const SHOW_ROW_AFTER: std::time::Duration = std::time::Duration::from_millis(200); +/// A read whose thread couldn't start (the system out of threads for a moment) is tried again this +/// soon, not after [`CHECK_EVERY`]. +pub const RETRY_AFTER: std::time::Duration = std::time::Duration::from_secs(10); + +/// What a read's worker answers: the drive's space and the cache's size when low (`None`: the drive +/// didn't say), or that the read couldn't start. +type Answer = Result, NotStarted>; + +/// A read's thread couldn't be started. +struct NotStarted; + +/// Space on one drive, in bytes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DiskSpace { + /// Free for this user (what can still be written). + pub available: u64, + /// The drive's size. + pub total: u64, +} + +impl DiskSpace { + /// Under [`LOW_FREE_PERCENT`] of the drive free, or under [`LOW_FREE_BYTES`]. A drive that + /// reports no size isn't judged by its share. + pub fn is_low(&self) -> bool { + let under_share = self.total > 0 && u128::from(self.available) * 100 < u128::from(self.total) * u128::from(LOW_FREE_PERCENT); + under_share || self.available < LOW_FREE_BYTES + } +} + +/// What the UI tells the user once: the drive's free space and size, and how big the preview +/// cache is now. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LowDiskAlert { + pub space: DiskSpace, + /// Bytes the preview cache takes on that drive. + pub cache_bytes: u64, +} + +/// The free space of the drive holding `dir` (or its parent when `dir` isn't there yet). `None` +/// (logged) when it can't be read. +pub fn read(dir: &Path) -> Option { + #[cfg(not(target_arch = "wasm32"))] + { + let probe = if dir.exists() { dir } else { dir.parent().unwrap_or(dir) }; + match fs4::statvfs(probe) { + Ok(s) => Some(DiskSpace { available: s.available_space(), total: s.total_space() }), + Err(e) => { + log::info!("disk space: can't read the free space of {}: {e}", probe.display()); + None + } + } + } + #[cfg(target_arch = "wasm32")] + { + let _ = dir; + None + } +} + +/// Reads the free space of a drive ([`read`]; a test can put a slow one in its place). +pub type Reader = std::sync::Arc Option + Send + Sync>; + +/// The session's state of the alert (reset when a library opens). +#[derive(Default)] +pub(crate) struct DiskAlertState { + /// The alert was handed out (or is waiting to be) this session: never again until reset. + pub(crate) raised: bool, + /// The alert waiting for the UI. + pub(crate) pending: Option, + /// When the free space was last read. + pub(crate) checked_at: Option, + /// The read running on a worker (natively): a network share can take its time to answer, and + /// the check runs on the UI thread. It answers with the drive's space and, when that is low, + /// the preview cache's size (counting the cache can mean reading every file's size: that too + /// stays off the UI thread). + probe: Option>, + /// The running read was started for the library open before this one: its answer is ignored, + /// and the drive is read again for the current library once it has come. Until then no second + /// read starts, so switching libraries while a drive hangs never piles up workers. + stale: bool, + /// In place of [`read`] (tests). + pub(crate) reader: Option, + /// Tests: the read's thread that fails to start (`"disk-space"`, `"disk-space-read"`). + pub(crate) fail_spawn: Option<&'static str>, +} + +/// Start a named thread; `fail` stands for a system that can't (tests). +#[cfg(not(target_arch = "wasm32"))] +fn spawn(name: &str, fail: bool, f: impl FnOnce() + Send + 'static) -> std::io::Result<()> { + if fail { + return Err(std::io::Error::other("no thread (test)")); + } + std::thread::Builder::new().name(name.into()).spawn(f).map(drop) +} + +impl DiskAlertState { + /// A fresh state for a newly opened library (the reader stays; a read still running is kept, + /// marked stale). + pub(crate) fn reset(&mut self) { + let probe = self.probe.take(); + let stale = probe.is_some(); + *self = DiskAlertState { reader: self.reader.take(), fail_spawn: self.fail_spawn, probe, stale, ..Default::default() }; + } +} + +impl crate::Session { + /// Read the free space of the drive holding the preview cache, at most every [`CHECK_EVERY`] + /// (`now`: whatever the last read, as when the library opens), and raise the alert if it is low + /// ([`Session::note_disk_space`](crate::Session::note_disk_space)). Nothing once the alert was + /// raised this session, without an on-disk library, or when the space can't be read. + /// The read itself runs on a worker (natively) and its answer is taken by a later call or + /// [`Session::poll_disk_space`]: a slow drive never holds up the caller. + pub fn check_disk_space(&mut self, now: bool) { + self.poll_disk_space(); + // (a read still running for an earlier library open starts this library's read when it answers) + if self.disk_alert.raised || self.disk_alert.probe.is_some() { + return; + } + let Some(dir) = self.library.as_ref().filter(|l| l.on_disk).map(crate::library::Library::thumbs_dir) else { return }; + let at = web_time::Instant::now(); + if !now && self.disk_alert.checked_at.is_some_and(|t| at.saturating_duration_since(t) < CHECK_EVERY) { + return; + } + self.disk_alert.checked_at = Some(at); + let reader = self.disk_alert.reader.clone(); + let rendered = self.media.rendered.clone(); + let read_now = move || { + let space = match reader { + Some(r) => r(&dir), + None => read(&dir), + }?; + // the cache is counted only when the alert will tell its size + let cache_bytes = if space.is_low() { rendered.disk().map_or(0, |d| d.size()) } else { 0 }; + Some((space, cache_bytes)) + }; + #[cfg(not(target_arch = "wasm32"))] + { + // a read when the library opens that takes more than a moment (a network share slow to + // answer, or the cache counted when the drive is low) shows in the activity stack; a quick + // one, and the quiet periodic ones every few minutes, don't + let activity = now.then(|| self.activity.clone()); + let fail = self.disk_alert.fail_spawn; + let (tx, rx) = std::sync::mpsc::channel(); + let started = spawn("disk-space", fail == Some("disk-space"), move || { + let answer = match activity { + None => Ok(read_now()), + Some(activity) => { + let (done, answered) = std::sync::mpsc::channel(); + let reading = spawn("disk-space-read", fail == Some("disk-space-read"), move || { + let _ = done.send(read_now()); + }); + match reading { + Err(e) => { + log::info!("disk space: can't start the free-space read: {e}"); + Err(NotStarted) + } + Ok(()) => match answered.recv_timeout(SHOW_ROW_AFTER) { + Ok(answer) => Ok(answer), + Err(_) => { + let _row = activity.start("cache", "Checking free disk space", crate::activity::Cancel::No); + Ok(answered.recv().ok().flatten()) + } + }, + } + } + }; + let _ = tx.send(answer); + }); + match started { + Ok(()) => self.disk_alert.probe = Some(rx), + Err(e) => { + log::info!("disk space: can't start the free-space read: {e}"); + self.retry_disk_space_soon(); + } + } + } + #[cfg(target_arch = "wasm32")] + if let Some((space, cache_bytes)) = read_now() { + self.raise_disk_alert(space, cache_bytes); + } + } + + /// Take the answer of the free-space read running on a worker, if it has come, and raise the + /// alert when the drive is low. An answer for an earlier library open is dropped and the drive + /// of the current one is read instead. Called by [`Session::check_disk_space`], + /// [`Session::take_disk_space_alert`] and `library.info`. + pub fn poll_disk_space(&mut self) { + let Some(rx) = self.disk_alert.probe.as_ref() else { return }; + let answer = match rx.try_recv() { + Ok(answer) => answer, + Err(std::sync::mpsc::TryRecvError::Empty) => return, + // (a worker that ended without answering: tried again soon too) + Err(std::sync::mpsc::TryRecvError::Disconnected) => Err(NotStarted), + }; + self.disk_alert.probe = None; + if std::mem::take(&mut self.disk_alert.stale) { + self.check_disk_space(true); + } else { + match answer { + Ok(Some((space, cache_bytes))) => { + self.raise_disk_alert(space, cache_bytes); + } + Ok(None) => {} + Err(NotStarted) => self.retry_disk_space_soon(), + } + } + } + + /// A read that couldn't start counts as made [`RETRY_AFTER`] less than [`CHECK_EVERY`] ago: the next check + /// reads the drive after [`RETRY_AFTER`] (CodeRabbit on #3577: it waited the whole five minutes). + fn retry_disk_space_soon(&mut self) { + let now = web_time::Instant::now(); + self.disk_alert.checked_at = Some(now.checked_sub(CHECK_EVERY.saturating_sub(RETRY_AFTER)).unwrap_or(now)); + } + + /// Raise the low-disk alert for `space` when it is low and the alert wasn't raised this session + /// yet (the numbers come from [`read`], or from a test). Returns whether it was raised now. + /// Counts the preview cache here, on the caller's thread: the session's own reads count it on + /// their worker. + pub fn note_disk_space(&mut self, space: DiskSpace) -> bool { + if self.disk_alert.raised || !space.is_low() { + return false; + } + let cache_bytes = self.media.rendered.disk().map_or(0, |d| d.size()); + self.raise_disk_alert(space, cache_bytes) + } + + /// [`Session::note_disk_space`] with the cache's size already counted. + fn raise_disk_alert(&mut self, space: DiskSpace, cache_bytes: u64) -> bool { + if self.disk_alert.raised || !space.is_low() { + return false; + } + log::warn!("disk space: {} of {} bytes free; the preview cache takes {cache_bytes} bytes", space.available, space.total); + self.disk_alert.raised = true; + self.disk_alert.pending = Some(LowDiskAlert { space, cache_bytes }); + true + } + + /// The low-disk alert not shown yet, if any (handed out once per session). + pub fn take_disk_space_alert(&mut self) -> Option { + self.poll_disk_space(); + self.disk_alert.pending.take() + } + + /// Read the drive's space with `reader` instead of asking the system (tests of the app). + #[doc(hidden)] + pub fn set_disk_space_reader(&mut self, reader: Option) { + self.disk_alert.reader = reader; + } + + /// Forget when the space was last read, as if [`CHECK_EVERY`] had passed (tests of the app). + #[doc(hidden)] + pub fn forget_disk_space_check(&mut self) { + self.disk_alert.checked_at = None; + } + + /// Whether a free-space read is running on its worker (its answer not taken yet). + pub fn disk_space_reading(&self) -> bool { + self.disk_alert.probe.is_some() + } + + /// How long until [`Session::check_disk_space`] reads the drive again (zero when it is due, `None` + /// when it won't: the alert was raised, a read runs, or nothing has been read yet). + pub fn disk_space_next_check_in(&self) -> Option { + let a = &self.disk_alert; + if a.raised || a.probe.is_some() { + return None; + } + Some(CHECK_EVERY.saturating_sub(a.checked_at?.elapsed())) + } + + /// How long the free-space read running on its worker has run (`Duration::MAX` for one started for the + /// library before), or `None` when none runs. + pub fn disk_space_read_running_for(&self) -> Option { + let a = &self.disk_alert; + a.probe.as_ref()?; + Some(a.checked_at.filter(|_| !a.stale).map_or(std::time::Duration::MAX, |t| t.elapsed())) + } + + /// Whether the low-disk alert was raised since the library opened (`library.info` → + /// `lowDiskSpace`). + pub fn disk_space_alert_raised(&self) -> bool { + self.disk_alert.raised + } +} + +#[cfg(test)] +mod tests { + use super::{DiskSpace, LOW_FREE_BYTES}; + use crate::Session; + + const GB: u64 = 1 << 30; + + #[test] + fn plenty_of_room_on_both_counts_raises_no_alert() { + let mut s = Session::new(); + assert!(!s.note_disk_space(DiskSpace { available: 200 * GB, total: 1000 * GB }), "20 % and 200 GB free"); + assert!(!s.note_disk_space(DiskSpace { available: 25 * GB, total: 100 * GB }), "25 % and 25 GB free"); + assert!(s.take_disk_space_alert().is_none()); + assert!(!s.disk_space_alert_raised()); + } + + #[test] + fn under_ten_percent_free_raises_the_alert() { + let mut s = Session::new(); + // 300 GB is far above 20 GB, but only 7.5 % of a 4 TB drive + let space = DiskSpace { available: 300 * GB, total: 4000 * GB }; + assert!(s.note_disk_space(space)); + let alert = s.take_disk_space_alert().expect("the alert is handed out"); + assert_eq!(alert.space, space); + assert!(s.disk_space_alert_raised()); + } + + #[test] + fn under_twenty_gb_free_raises_the_alert() { + let mut s = Session::new(); + // 15 % of a 100 GB drive is free, but that is under 20 GB + let space = DiskSpace { available: 15 * GB, total: 100 * GB }; + assert!(space.available < LOW_FREE_BYTES); + assert!(s.note_disk_space(space)); + assert_eq!(s.take_disk_space_alert().map(|a| a.space), Some(space)); + } + + #[test] + fn the_alert_is_raised_once_per_session() { + let mut s = Session::new(); + let low = DiskSpace { available: GB, total: 500 * GB }; + assert!(s.note_disk_space(low)); + assert!(s.take_disk_space_alert().is_some()); + assert!(s.take_disk_space_alert().is_none(), "handed out once"); + assert!(!s.note_disk_space(DiskSpace { available: GB / 2, ..low }), "lower still: not again this session"); + assert!(s.take_disk_space_alert().is_none()); + s.check_disk_space(true); + assert!(s.take_disk_space_alert().is_none(), "a check after the alert reads nothing"); + } + + #[test] + fn opening_a_library_starts_a_new_session_for_the_alert() { + let dir = std::env::temp_dir().join(format!("lc-disk-alert-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&dir, false).unwrap(); + // whatever this machine's drive holds, raise it by hand + let _ = s.take_disk_space_alert(); + let low = DiskSpace { available: GB, total: 500 * GB }; + if !s.disk_space_alert_raised() { + assert!(s.note_disk_space(low)); + } + assert!(!s.note_disk_space(low), "once per session"); + s.close_library().unwrap(); + s.open_library(&dir, false).unwrap(); + let _ = s.take_disk_space_alert(); + let raised_by_open = s.disk_space_alert_raised(); + assert!(raised_by_open || s.note_disk_space(low), "a new library open may warn again"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A drive that takes its time to answer (a network share) doesn't hold up the library open + /// or the checks on the UI thread: the read runs on a worker and its answer is taken later. + #[test] + fn a_slow_drive_does_not_hold_up_the_check() { + use std::sync::{Arc, Mutex, mpsc}; + let dir = std::env::temp_dir().join(format!("lc-disk-alert-slow-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (release, wait) = mpsc::channel::<()>(); + let wait = Mutex::new(wait); + let mut s = Session::new().with_fs(); + s.disk_alert.reader = Some(Arc::new(move |_: &std::path::Path| { + // answers once the test lets it (or after 10 s, so a broken test can't hang) + let _ = wait.lock().unwrap().recv_timeout(std::time::Duration::from_secs(10)); + Some(DiskSpace { available: GB, total: 500 * GB }) + })); + s.open_library(&dir, false).unwrap(); + assert!(s.take_disk_space_alert().is_none(), "the open didn't wait for the drive's answer"); + // the read the open started shows in the activity stack once it takes more than a moment + // (CodeRabbit on #3077) + let reading = |s: &Session| s.activity.list().iter().any(|t| t.kind == "cache" && t.label == "Checking free disk space"); + let until = web_time::Instant::now() + std::time::Duration::from_secs(10); + while !reading(&s) { + assert!(web_time::Instant::now() < until, "{:?}", s.activity.list()); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(s.disk_space_reading()); + s.check_disk_space(true); + assert!(s.take_disk_space_alert().is_none(), "nor does a check while the read runs"); + release.send(()).unwrap(); + let until = std::time::Instant::now() + std::time::Duration::from_secs(10); + let alert = loop { + if let Some(a) = s.take_disk_space_alert() { + break a; + } + assert!(std::time::Instant::now() < until, "the drive's answer was never taken"); + std::thread::sleep(std::time::Duration::from_millis(5)); + }; + assert_eq!(alert.space.available, GB); + assert!(s.disk_space_alert_raised()); + assert!(!reading(&s) && !s.disk_space_reading(), "the row goes with the read"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A drive that hangs while the user switches libraries: the read still running is kept, no + /// second worker starts beside it, its answer (for the old library) is dropped, and the current + /// library's drive is read once it has come. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn switching_libraries_while_a_drive_hangs_starts_no_second_read() { + use std::sync::{Arc, Mutex, mpsc}; + use std::time::{Duration, Instant}; + let root = std::env::temp_dir().join(format!("lc-disk-alert-switch-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let (a, b) = (root.join("a"), root.join("b")); + std::fs::create_dir_all(&a).unwrap(); + std::fs::create_dir_all(&b).unwrap(); + let (release, wait) = mpsc::channel::<()>(); + let (started_tx, started) = mpsc::channel::(); + let wait = Mutex::new(wait); + let started_tx = Mutex::new(started_tx); + let mut s = Session::new().with_fs(); + s.disk_alert.reader = Some(Arc::new(move |dir: &std::path::Path| { + let _ = started_tx.lock().unwrap().send(dir.to_path_buf()); + let _ = wait.lock().unwrap().recv_timeout(Duration::from_secs(10)); + Some(DiskSpace { available: GB, total: 500 * GB }) + })); + s.open_library(&a, false).unwrap(); + let first = started.recv_timeout(Duration::from_secs(10)).expect("the open reads the drive"); + assert!(first.starts_with(&a), "{first:?}"); + s.close_library().unwrap(); + s.open_library(&b, false).unwrap(); + s.check_disk_space(true); + assert!(started.recv_timeout(Duration::from_millis(300)).is_err(), "no second read beside the hanging one"); + release.send(()).unwrap(); + let until = Instant::now() + Duration::from_secs(10); + let second = loop { + assert!(s.take_disk_space_alert().is_none(), "the old library's answer is dropped"); + if let Ok(dir) = started.try_recv() { + break dir; + } + assert!(Instant::now() < until, "the current library's drive was never read"); + std::thread::sleep(Duration::from_millis(5)); + }; + assert!(second.starts_with(&b), "{second:?}"); + assert!(!s.disk_space_alert_raised()); + release.send(()).unwrap(); + let until = Instant::now() + Duration::from_secs(10); + while s.take_disk_space_alert().is_none() { + assert!(Instant::now() < until, "the current library's answer was never taken"); + std::thread::sleep(Duration::from_millis(5)); + } + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&root); + } + + /// When the drive is low, the preview cache is counted on the read's worker too: counting it can + /// mean reading the size of every file (a big cache on a slow share), never on the UI thread + /// that takes the answer. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_preview_cache_is_counted_off_the_ui_thread() { + use std::sync::{Arc, Mutex, mpsc}; + use std::time::{Duration, Instant}; + let dir = std::env::temp_dir().join(format!("lc-disk-alert-count-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (release, wait) = mpsc::channel::<()>(); + let wait = Mutex::new(wait); + let mut s = Session::new().with_fs(); + s.disk_alert.reader = Some(Arc::new(move |_: &std::path::Path| { + let _ = wait.lock().unwrap().recv_timeout(Duration::from_secs(10)); + Some(DiskSpace { available: GB, total: 500 * GB }) + })); + s.open_library(&dir, false).unwrap(); + let disk = || s.media.rendered.disk().map(lightcraft_preview::DiskCache::known_size); + assert_eq!(disk(), Some(None), "an on-disk library has a preview cache, not counted yet"); + release.send(()).unwrap(); + // no poll here: only the worker can count the cache + let until = Instant::now() + Duration::from_secs(10); + let counted = loop { + if let Some(Some(bytes)) = disk() { + break bytes; + } + assert!(Instant::now() < until, "the worker never counted the cache"); + std::thread::sleep(Duration::from_millis(5)); + }; + let until = Instant::now() + Duration::from_secs(10); + let alert = loop { + if let Some(a) = s.take_disk_space_alert() { + break a; + } + assert!(Instant::now() < until, "the drive's answer was never taken"); + std::thread::sleep(Duration::from_millis(5)); + }; + assert_eq!(alert.cache_bytes, counted); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_free_space_of_a_real_drive_is_read() { + let space = super::read(&std::env::temp_dir().join("lc-disk-alert-not-there")).expect("the temp folder's drive says its size"); + assert!(space.total > 0 && space.available <= space.total, "{space:?}"); + } + + /// A read whose thread can't start is tried again after [`super::RETRY_AFTER`], not after the five minutes + /// of [`super::CHECK_EVERY`] (CodeRabbit on #3577); for either of its two threads. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_read_that_could_not_start_is_tried_again_soon() { + use std::time::{Duration, Instant}; + for thread in ["disk-space", "disk-space-read"] { + let dir = std::env::temp_dir().join(format!("lc-disk-alert-nothread-{thread}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new().with_fs(); + s.disk_alert.reader = Some(std::sync::Arc::new(|_: &std::path::Path| Some(DiskSpace { available: GB, total: 500 * GB }))); + s.disk_alert.fail_spawn = Some(thread); + s.open_library(&dir, false).unwrap(); + let until = Instant::now() + Duration::from_secs(10); + while s.disk_space_reading() { + assert!(Instant::now() < until, "{thread}: the read never ended"); + s.poll_disk_space(); + std::thread::sleep(Duration::from_millis(5)); + } + let since = s.disk_alert.checked_at.expect("a check was made").elapsed(); + assert!( + since + super::RETRY_AFTER + Duration::from_secs(1) >= super::CHECK_EVERY, + "{thread}: next read in {:?}", + super::CHECK_EVERY.saturating_sub(since) + ); + // the thread can start again: the retry reads the drive and raises the alert + s.disk_alert.fail_spawn = None; + s.disk_alert.checked_at = s.disk_alert.checked_at.and_then(|t| t.checked_sub(super::RETRY_AFTER)); + s.check_disk_space(false); + let until = Instant::now() + Duration::from_secs(10); + while s.take_disk_space_alert().is_none() { + assert!(Instant::now() < until, "{thread}: the retry never read the drive"); + std::thread::sleep(Duration::from_millis(5)); + } + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } + } + + #[test] + fn a_drive_that_reports_no_size_is_judged_by_its_free_bytes() { + assert!(!DiskSpace { available: 50 * GB, total: 0 }.is_low()); + assert!(DiskSpace { available: 5 * GB, total: 0 }.is_low()); + } +} diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 4f09be75ba..0e40d0fc5f 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -27,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_bytes_with, load_vec, load_vec_pair, load_vec_reduced}; +pub use load::{load_bytes, load_bytes_decoded, load_bytes_with, load_vec, load_vec_pair, load_vec_reduced}; #[cfg(test)] use preview::PLAN_PREFIX; pub(crate) use preview::decode_raw_preview; @@ -109,5 +109,33 @@ impl CameraColourModel<'_> { } } +/// Remove Hot Pixels leaves a raw alone when more than this share of its photosites would be replaced (Settings ▸ +/// Performance ▸ Hot pixel limit, `app.hotPixelLimit`), as `f64` bits. Process-wide, like the GPU switch. +static HOT_PIXEL_LIMIT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(lightcraft_raw::HOT_PIXEL_MAX_SHARE.to_bits()); + +/// The share of a raw's photosites Remove Hot Pixels may replace (0..1). +pub fn hot_pixel_limit() -> f64 { + f64::from_bits(HOT_PIXEL_LIMIT.load(std::sync::atomic::Ordering::Relaxed)) +} + +/// Set [`hot_pixel_limit`]; false (nothing changed) unless `share` is a new value in 0..=1. Sources decoded before +/// keep the old limit: the caller forgets them ([`crate::media::MediaCache::clear_sources`]). +pub fn set_hot_pixel_limit(share: f64) -> bool { + if !(0.0..=1.0).contains(&share) { + return false; + } + HOT_PIXEL_LIMIT.swap(share.to_bits(), std::sync::atomic::Ordering::Relaxed) != share.to_bits() +} + +/// What [`hot_pixel_limit`] adds to the render cache keys of `settings`: nothing at the default limit or when they +/// don't remove hot pixels, so those renders stay valid whatever the limit. +pub fn hot_pixel_key(settings: &lightcraft_develop::DevelopSettings) -> u64 { + let limit = hot_pixel_limit(); + if !settings.removes_hot_pixels() || limit.to_bits() == lightcraft_raw::HOT_PIXEL_MAX_SHARE.to_bits() { + return 0; + } + limit.to_bits().wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(29) +} + #[cfg(test)] pub(crate) mod tests; diff --git a/crates/engine/src/files/fs.rs b/crates/engine/src/files/fs.rs index 05784d542b..e839873cf0 100644 --- a/crates/engine/src/files/fs.rs +++ b/crates/engine/src/files/fs.rs @@ -1,7 +1,8 @@ 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, DcpProfile, DenoiseSpec, FileLoader, FileProbe, Filter, PairLoader, ReducedLoader, fit}; +use super::{Arc, DenoiseSpec, FileLoader, FileProbe, Filter, PairLoader, ReducedLoader, fit}; +use crate::media::RawDecode; /// 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. @@ -37,6 +38,12 @@ pub(super) fn raf_preview_extent(prefix: &[u8]) -> Option { /// `adobe_rgb`: the container declares the preview Adobe RGB ([`PreviewRead::adobe_rgb`]), applied /// as [`decode_raw_preview`] applies it. `None` when the bytes are not a decodable image. pub(super) fn quick_image_srgb(header: &[u8], window: &[u8], adobe_rgb: bool, max_edge: usize) -> Option { + // a plain sRGB camera JPEG (nearly all of them) straight to 8-bit (PERF-CULL-3: 45 MP preview + // of an EOS R5 C fitted to 2560 px, 194 → ~110 ms); anything else takes the general decode + let edge = u32::try_from(max_edge).unwrap_or(u32::MAX); + if !adobe_rgb && let Ok(Some((image, orientation))) = lightcraft_codecs::decode_jpeg_srgb8_fit(window, edge, edge) { + return Some(image.oriented(preview_orientation(header, orientation))); + } let decoded = if adobe_rgb && window.starts_with(&[0xff, 0xd8]) { lightcraft_codecs::decode_jpeg_with_fallback(window, fit_box(max_edge), lightcraft_codecs::NamedSpace::AdobeRgb) } else { @@ -54,13 +61,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, dcp: Option<&DcpProfile>| { + Arc::new(|path: &str, max_edge: usize, spec: &DenoiseSpec, with: RawDecode<'_>| { 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, dcp); + let r = load_vec_pair(bytes, max_edge, spec, with); crate::memory::release(); r }) @@ -75,7 +82,7 @@ pub fn fs_pair_loader() -> PairLoader { /// yields to them. pub fn fs_hooks() -> (FileLoader, FileProbe) { 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))); + Arc::new(|path: &str, max_edge: usize, with: RawDecode<'_>| fs_load(path, max_edge, |bytes| load_vec(bytes, max_edge, with))); 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 @@ -95,7 +102,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, dcp: Option<&DcpProfile>| fs_load(path, max_edge, |bytes| load_vec_reduced(bytes, max_edge, dcp))) + Arc::new(|path: &str, max_edge: usize, with: RawDecode<'_>| fs_load(path, max_edge, |bytes| load_vec_reduced(bytes, max_edge, with))) } /// 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 004723dca8..0e396dd815 100644 --- a/crates/engine/src/files/load.rs +++ b/crates/engine/src/files/load.rs @@ -2,6 +2,7 @@ use super::colour::bin_factor; use super::preview::{fit_box, load_embedded_preview}; use super::probe::preview_reason; use super::{Arc, CameraColourModel, DcpProfile, DenoiseSpec, Filter, HIGHLIGHT_CLIP, Orientation, Rgb32f, SourceInfo, fit, xy_to_temp_tint}; +use crate::media::RawDecode; /// Decode a file into a linear Rec.2020 image no larger than `max_edge`, oriented. /// @@ -9,26 +10,31 @@ use super::{Arc, CameraColourModel, DcpProfile, DenoiseSpec, Filter, HIGHLIGHT_C /// 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, None).map(|(img, _, info, _)| (img, info))) + load_bytes_decoded(bytes, max_edge, RawDecode::default()) } /// [`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_decoded(bytes, max_edge, RawDecode { dcp, outliers: false }) +} + +/// [`load_bytes`] decoding a raw file as `with` says. +pub fn load_bytes_decoded(bytes: &[u8], max_edge: usize, with: RawDecode<'_>) -> Result<(Rgb32f, SourceInfo), String> { + rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false, with).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, 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))) +pub fn load_vec(bytes: Vec, max_edge: usize, with: RawDecode<'_>) -> Result<(Rgb32f, SourceInfo), String> { + rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, false, with).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, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo, bool), String> { +pub fn load_vec_reduced(bytes: Vec, max_edge: usize, with: RawDecode<'_>) -> 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_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, true, with).map(|(img, _, info, reduced)| (img, info, reduced)) }) } @@ -39,10 +45,10 @@ pub fn load_vec_pair( bytes: Vec, max_edge: usize, spec: &DenoiseSpec, - dcp: Option<&DcpProfile>, + with: RawDecode<'_>, ) -> 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)) + load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, Some(spec), false, with).map(|(img, twin, info, _)| (img, twin, info)) }) } @@ -73,8 +79,9 @@ fn load_bytes_now( max_edge: usize, denoise: Option<&DenoiseSpec>, allow_reduced: bool, - dcp: Option<&DcpProfile>, + with: RawDecode<'_>, ) -> Result<(Rgb32f, Option, SourceInfo, bool), String> { + let dcp = with.dcp; 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 // (Lightroom's merges) develops the smallest that covers it; a denoised photo's twin needs the full mosaic @@ -96,6 +103,14 @@ fn load_bytes_now( } Err(Err(e)) => return Err(e), }; + // single outlier photosites, replaced in the mosaic before anything is developed from it (#1345) + if with.outliers { + let t = std::time::Instant::now(); + let n = raw.suppress_hot_pixels_with(super::hot_pixel_limit()); + if lightcraft_pipeline::profiling() { + eprintln!("[profile] raw outliers: {n} photosites replaced in {:.1} ms", t.elapsed().as_secs_f64() * 1e3); + } + } // Embedded lens corrections are applied by the pipeline ("Enable Profile Corrections"), not baked in // (removed before the camera look's binned sensor proxy too, which needs an empty `OpcodeList3`). let info = raw.info(); diff --git a/crates/engine/src/files/preview.rs b/crates/engine/src/files/preview.rs index 825167f5c1..85ee2c5fb8 100644 --- a/crates/engine/src/files/preview.rs +++ b/crates/engine/src/files/preview.rs @@ -33,7 +33,11 @@ pub(crate) fn decode_raw_preview( opts: lightcraft_codecs::DecodeOptions, covering: Option, ) -> Option { - let jpeg = stand_in_image(bytes, covering)?; + decode_stand_in(bytes, &stand_in_image(bytes, covering)?, opts) +} + +/// [`decode_raw_preview`] of the stand-in `jpeg` already found in the raw file `bytes` (by [`stand_in_image`]). +fn decode_stand_in(bytes: &[u8], jpeg: &[u8], opts: lightcraft_codecs::DecodeOptions) -> Option { // the colour space is a property of the JPEG; a TIFF stand-in (the file itself, or a Hasselblad RGB preview // wrapped as a TIFF) and a JPEG XL preview are read by their own decoders let is_jpeg = jpeg.starts_with(&[0xff, 0xd8]); @@ -43,9 +47,9 @@ pub(crate) fn decode_raw_preview( lightcraft_raw::PreviewColorSpace::Srgb => lightcraft_codecs::NamedSpace::Srgb, lightcraft_raw::PreviewColorSpace::AdobeRgb => lightcraft_codecs::NamedSpace::AdobeRgb, }; - lightcraft_codecs::decode_jpeg_with_fallback(&jpeg, opts, space).ok() + lightcraft_codecs::decode_jpeg_with_fallback(jpeg, opts, space).ok() } - None => lightcraft_codecs::decode(&jpeg, opts).ok(), + None => lightcraft_codecs::decode(jpeg, opts).ok(), } } @@ -80,7 +84,18 @@ pub fn load_embedded_preview(bytes: &[u8], max_edge: usize) -> Option<(Rgb32f, S /// loupe and grid show it until the raw itself has been developed ([`crate::media::QuickJob`]). The smallest /// embedded JPEG that covers `max_edge` is decoded, not the largest. pub fn embedded_preview_srgb(bytes: &[u8], max_edge: usize) -> Option { - let mut d = decode_raw_preview(bytes, fit_box(max_edge), Some(max_edge))?; + // a plain sRGB camera JPEG straight to 8-bit, as the quick path decodes it (PERF-CULL-3), so + // both paths give the same picture; anything else takes the general decode + let edge = u32::try_from(max_edge).unwrap_or(u32::MAX); + // (found once: the general decode below takes the same stand-in when the fast path declines) + let jpeg = stand_in_image(bytes, Some(max_edge))?; + if lightcraft_raw::embedded_preview_color_space(bytes) != Some(lightcraft_raw::PreviewColorSpace::AdobeRgb) + && matches!(jpeg, std::borrow::Cow::Owned(_)) + && let Ok(Some((image, orientation))) = lightcraft_codecs::decode_jpeg_srgb8_fit(&jpeg, edge, edge) + { + return Some(image.oriented(preview_orientation(bytes, orientation))); + } + let mut d = decode_stand_in(bytes, &jpeg, fit_box(max_edge))?; if d.image.width.max(d.image.height) > max_edge { d.image = fit(&d.image, max_edge, max_edge, Filter::Box); d.alpha = None; diff --git a/crates/engine/src/files/probe.rs b/crates/engine/src/files/probe.rs index 41a0854f71..a63446401e 100644 --- a/crates/engine/src/files/probe.rs +++ b/crates/engine/src/files/probe.rs @@ -143,6 +143,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { as_shot_wb: None, content_hash, xmp: lightcraft_meta::embedded(bytes).xmp, + orientation: m.orientation, preview_only: Some(why), ..Default::default() }); @@ -177,6 +178,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { as_shot_wb, content_hash, xmp: lightcraft_meta::embedded(bytes).xmp, + orientation: Some(raw.orientation), preview_only: None, }); } @@ -192,6 +194,18 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { if o.swaps_axes() { std::mem::swap(&mut w, &mut h); } + // regions another app drew on the photo as stored: `extract` could only tell by the size the metadata states, which + // can be missing or wrong; the header's is the size as stored, so the boxes as written are turned by it (#2674) + let mut meta = meta; + if o.swaps_axes() + && !meta.regions.is_empty() + && let Some(xmp) = lightcraft_meta::embedded(bytes).xmp.and_then(|x| lightcraft_meta::parse_xmp(&x).ok()) + && let Some(drawn_on) = xmp.regions_drawn_on() + && !xmp.metadata.regions.is_empty() + { + meta.regions = xmp.metadata.regions; + lightcraft_meta::upright_regions(&mut meta.regions, drawn_on, o, (header.width, header.height)); + } let format = match ext_upper(name).as_str() { "JPG" | "JPEG" => "JPEG".to_string(), "" => format!("{fmt:?}").to_uppercase(), @@ -210,6 +224,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { content_hash, embedded_lens: None, xmp: None, + orientation: m.orientation, preview_only: None, }) } diff --git a/crates/engine/src/files/tests.rs b/crates/engine/src/files/tests.rs index 4fab917c82..e8eabc72db 100644 --- a/crates/engine/src/files/tests.rs +++ b/crates/engine/src/files/tests.rs @@ -591,7 +591,7 @@ fn cached_denoise_uses_the_same_white_balance_profile_and_orientation_as_plain_r product::write(&path, &camera_rgb, key).unwrap(); let spec = DenoiseSpec { product: path, key: key.into(), make: None }; let (ordinary, _) = load_bytes(&bytes, 2048).unwrap(); - let (plain, cached, _) = load_vec_pair(bytes, 2048, &spec, None).unwrap(); + let (plain, cached, _) = load_vec_pair(bytes, 2048, &spec, Default::default()).unwrap(); assert_eq!(plain.data, ordinary.data, "requesting a twin must not change the ordinary path"); let cached = cached.unwrap(); assert_eq!((plain.width, plain.height), (24, 32)); @@ -1255,10 +1255,10 @@ fn exports_never_develop_a_dngs_reduced_copy() { let mean = |img: &lightcraft_raster::Rgba8| img.data.iter().map(|p| p[1] as f64).sum::() / img.data.len().max(1) as f64; // the loaders: only the thumbnail's develops the copy, and only when it covers the size - let (copy, _, used) = load_vec_reduced(bytes.clone(), 512, None).unwrap(); + let (copy, _, used) = load_vec_reduced(bytes.clone(), 512, Default::default()).unwrap(); assert!(used, "a thumbnail develops the copy"); - 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!(!load_vec_reduced(bytes.clone(), 1024, Default::default()).unwrap().2, "no copy covers 1024 px"); + let (full, _) = load_vec(bytes.clone(), 512, Default::default()).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.rs b/crates/engine/src/import.rs index 6a6b6e6a70..b4ee766048 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -53,7 +53,9 @@ pub(crate) use files::{expand_noting, probe_all, probe_paths, probe_with}; use job::PreparedItem; pub use job::{ImportJob, Prepared, candidate_thumb_key, import, import_with}; pub(crate) use scan::scan_files; -pub use scan::{ScanInput, ScanOutput, ScanProgress, scan, scan_with}; +pub use scan::{ + ScanInput, ScanOutput, ScanProgress, browse_files, browse_order, browse_path, browse_queue, browse_queue_until, browse_spelling, scan, scan_with, +}; #[cfg(test)] use scan::{library_files, library_hashes}; pub use types::{ diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index df7cfe418a..d283bb0ac4 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -253,6 +253,8 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare } } let sidecar = sidecar.map(|sc| sc.resolve_label(&s.catalog)).filter(|sc| *sc != crate::sidecar::SidecarData::default()); + // the photo is upright as the file's own orientation turns it, when the file states one + let sidecar = sidecar.map(|sc| crate::sidecar::SidecarData { orientation: info.orientation.or(sc.orientation), ..sc }); // a copy is catalogued under its new name let name = Path::new(&stored).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.clone()); let mut p = Photo::new(id, Source::File { path: stored }, &name, &info.format, info.width, info.height, &now); diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index ae635cb10d..e8ed759dd2 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -528,6 +528,8 @@ impl Session { key, cached: Vec::new(), embedded, + embedded_cache: None, + embedded_on_disk: false, minimum_embedded_edge, small: Some(Box::new(small)), }) diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index 57ee995f26..ad247c22c6 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -1,4 +1,4 @@ -use super::files::{Seen, expand, probe_all, reusable_probes}; +use super::files::{Seen, expand, is_supported, probe_all, reusable_probes}; use super::types::ImportCandidate; use super::{HashMap, Path, PathBuf, PhotoId, ProbeInfo, Session, Source}; @@ -98,6 +98,185 @@ impl ScanInput { pub(crate) fn library(&self) -> std::sync::Arc { std::sync::Arc::clone(&self.library) } + + /// The probes of earlier scans this input took from the session ([`ScanInput::new`]), to hand back with a + /// scan's output that probes nothing itself (browsing), so a later import doesn't read those files again. + pub fn take_probes(&mut self) -> HashMap { + std::mem::take(&mut self.cache) + } +} + +/// What browsing a folder (Local) has to read: the files of `files` the library has no photo at, +/// in the order the view will show them (see [`browse_order`]). Unlike [`scan_with`] nothing is +/// read, so the import that follows adds the photos batch by batch as it reads them, and the first +/// screen of a 3,000-raw wedding shows within a second instead of after every file was read +/// (measured on 2,933 EOS R5 C CR3s: 30.6 s to the first photo before). +pub fn browse_queue(input: &ScanInput, files: Vec, sort: &lightcraft_catalog::Sort) -> Vec { + browse_queue_until(input, files, sort, &std::sync::atomic::AtomicBool::new(false)).unwrap_or_default() +} + +/// [`browse_queue`] that stops reading the files' times or sizes once `cancel` is set (another folder was +/// chosen): `None` then. +pub fn browse_queue_until( + input: &ScanInput, + files: Vec, + sort: &lightcraft_catalog::Sort, + cancel: &std::sync::atomic::AtomicBool, +) -> Option> { + let known = library_files(&input.library, &files); + let mut files: Vec = files.into_iter().filter(|f| !known.contains_key(Path::new(f))).collect(); + browse_order_until(&mut files, sort, cancel).then_some(files) +} + +/// The files browsing `root` (Local) lists: the supported, non-hidden files in it, or below it +/// with `subfolders`, never inside the library's own folder (as [`scan_with`] skips it). +/// +/// A folder that can't be listed whole (gone, no access, a network share dropping out) is an +/// error, not an empty or partial listing: the browse bookkeeping would take the files missing +/// from it for files gone. (With `subfolders` the walk skips the folders below it that it can't +/// read, as the import's scan does.) +pub fn browse_files(input: &ScanInput, root: &str, subfolders: bool) -> std::io::Result> { + // one spelling for the folder, and so for its files: `lib/../outside` lists `outside`'s files as + // the catalog stores them, not as new photos under another name + let root_path = browse_path(Path::new(root))?; + let root = root_path.to_string_lossy().to_string(); + // the library's folder itself, or a folder inside it: nothing to browse + if input.skip.as_deref().is_some_and(|lib| inside(&root_path, lib)) { + return Ok(Vec::new()); + } + if subfolders { + // (the root itself must be there to be walked) + std::fs::read_dir(&root)?; + return Ok(expand(&[root], input.skip.as_deref())); + } + let mut v = Vec::new(); + for entry in std::fs::read_dir(&root)? { + let entry = entry?; + if crate::walk::is_hidden_entry(&entry) { + continue; + } + let f = entry.path(); + if f.is_file() && is_supported(&f) { + v.push(f.to_string_lossy().to_string()); + } + } + v.sort(); + Ok(v) +} + +/// The folder `path` names, as one spelling for the view, its listing and the catalog's records: +/// absolute (`.` is the current folder), with `.` and `..` taken out the way the system reads them. +/// Windows takes `..` out by name; elsewhere `link/..` is the folder above where the link points, +/// so a link before a `..` is resolved first. Everything else keeps its spelling (a mapped drive +/// stays a drive letter, a link not followed by `..` stays the link), as the records were made. +/// +/// It may read the disk (a link on a stalled network mount can block it): call it off the UI thread. +/// [`browse_spelling`] is the UI's spelling meanwhile. +pub fn browse_path(path: &Path) -> std::io::Result { + normalized(path, true) +} + +/// [`browse_path`] without reading the disk: `.` and `..` taken out by name. What the view shows +/// until the worker has resolved the folder; the same folder unless a link comes before a `..` +/// (not on Windows, which takes `..` out by name too). +pub fn browse_spelling(path: &Path) -> std::io::Result { + normalized(path, false) +} + +fn normalized(path: &Path, resolve_links: bool) -> std::io::Result { + use std::path::Component; + // (no disk access: the current folder is the process's) + let path = std::path::absolute(path)?; + let mut out = PathBuf::new(); + for c in path.components() { + match c { + Component::CurDir => {} + Component::ParentDir => { + // a link before `..` is left through where it points; a broken one is an error, not + // its parent folder by name (CodeRabbit on #3577) + #[cfg(not(windows))] + if resolve_links && std::fs::symlink_metadata(&out).is_ok_and(|m| m.file_type().is_symlink()) { + out = std::fs::canonicalize(&out)?; + } + #[cfg(windows)] + let _ = resolve_links; + // (above the root: still the root) + if matches!(out.components().next_back(), Some(Component::Normal(_))) { + out.pop(); + } + } + c => out.push(c.as_os_str()), + } + } + Ok(out) +} + +/// Whether `root` (a [`browse_path`]) is `lib` or a folder inside it: as written, or once both are +/// resolved (a symlink to the library names the same folder), as the recursive walk tells. A root +/// that can't be resolved (gone, or a network share that won't say) is compared as written when it +/// is there; one that isn't there is not inside, and listing it reports why. +fn inside(root: &Path, lib: &Path) -> bool { + let as_written = || root.starts_with(browse_path(lib).unwrap_or_else(|_| lib.to_path_buf())); + match std::fs::canonicalize(root) { + Ok(resolved) => as_written() || std::fs::canonicalize(lib).is_ok_and(|lib| resolved.starts_with(lib)), + Err(_) => root.exists() && as_written(), + } +} + +/// Order `files` the way a view sorted by `sort` will show them, as far as the file system can +/// tell before the files are read: by modification time for the capture date (a camera's file +/// time is its capture time, near enough to fill the first screen first), by name, or by size. +/// New photos share one import time and have no edit time, so the import- and edit-date sorts +/// show them by name. Ties go by name in the view's direction, as the catalog breaks them +/// ([`lightcraft_catalog::Sort::order`]); new photos tie on rating too. Random keeps the given order. Files whose +/// time or size can't be read go last. +pub fn browse_order(files: &mut [String], sort: &lightcraft_catalog::Sort) { + browse_order_until(files, sort, &std::sync::atomic::AtomicBool::new(false)); +} + +/// [`browse_order`] that stops reading the files' times or sizes once `cancel` is set: `false` then, and +/// `files` is left as it was. +fn browse_order_until(files: &mut [String], sort: &lightcraft_catalog::Sort, cancel: &std::sync::atomic::AtomicBool) -> bool { + use lightcraft_catalog::SortKey; + use lightcraft_catalog::query::cmp_name; + use std::cmp::Ordering; + use std::sync::atomic::Ordering::Relaxed; + let asc = sort.ascending; + let name = |f: &str| Path::new(f).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let directed = |o: Ordering| if asc { o } else { o.reverse() }; + // `key` per file (`None`: unreadable, last in either direction), then the name, in the view's direction + let by_key = |files: &mut [String], key: &dyn Fn(&str) -> Option| { + let mut keyed: Vec<(Option, String, String)> = Vec::with_capacity(files.len()); + for f in files.iter() { + if cancel.load(Relaxed) { + return false; + } + keyed.push((key(f), name(f), f.clone())); + } + keyed.sort_by(|a, b| match (a.0, b.0) { + (Some(x), Some(y)) => directed(x.cmp(&y).then_with(|| cmp_name(&a.1, &b.1))), + (Some(_), None) => Ordering::Less, + (None, Some(_)) => Ordering::Greater, + (None, None) => directed(cmp_name(&a.1, &b.1)), + }); + for (slot, (_, _, f)) in files.iter_mut().zip(keyed) { + *slot = f; + } + true + }; + match sort.key { + SortKey::CaptureDate => by_key(files, &|f| { + let t = std::fs::metadata(f).and_then(|m| m.modified()).ok()?; + // (nanoseconds since the epoch fit a u64 until 2554; earlier times count as the epoch) + Some(t.duration_since(std::time::UNIX_EPOCH).map_or(0, |d| u64::try_from(d.as_nanos()).unwrap_or(u64::MAX))) + }), + SortKey::ImportDate | SortKey::EditDate | SortKey::Rating | SortKey::FileName => { + files.sort_by(|a, b| directed(cmp_name(&name(a), &name(b)))); + !cancel.load(Relaxed) + } + SortKey::FileSize => by_key(files, &|f| std::fs::metadata(f).ok().map(|m| m.len())), + SortKey::Random => !cancel.load(Relaxed), + } } /// Find and probe what importing `paths` would add, marking duplicates (by path, or by content diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f71f9becd1..b0e3d2b9e5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -28,6 +28,7 @@ pub mod crs_masks; pub mod demo; pub mod denoise; pub mod devices; +pub mod disk_space; pub mod display; pub mod doc_path; mod errors; @@ -61,6 +62,7 @@ mod model_download; pub mod open_path; pub mod originals; mod pdf; +pub mod prep; pub mod preset_import; pub mod preset_luminar; pub mod presets; @@ -398,10 +400,18 @@ pub struct Session { pub slideshow_export: Option>, /// The last (or running) Build Previews. pub preview_build: Option>, + /// Preparing photos in the background: settings (app-wide and this library's) and the build + /// it runs ([`prep`]). + pub prep: prep::PrepState, + /// The long edge (px) the loupe renders at on this screen, as the frontend last said + /// (0: not known). Standard previews are built at least this big, so the loupe can use them. + pub loupe_edge: usize, /// Develop defaults applied on import (persisted in prefs.json). pub import_defaults: import::ImportDefaults, /// Disk budget of the library's thumbnail cache in MB (0 = default; persisted in prefs.json). pub cache_mb: u32, + /// The once-per-session alert for a drive running low under the preview cache ([`disk_space`]). + pub(crate) disk_alert: disk_space::DiskAlertState, /// Slideshow playback settings (`slideshow.playback`; persisted in prefs.json). pub slideshow: slideshow::PlaybackSettings, /// Slideshow slide layout: Layout, Options and Backdrop (`slideshow.layout`; persisted in @@ -537,9 +547,12 @@ impl Session { folder_changes: None, activity: Default::default(), preview_build: None, + prep: Default::default(), + loupe_edge: 0, slideshow_export: None, import_defaults: import::ImportDefaults::default(), cache_mb: 0, + disk_alert: Default::default(), slideshow: slideshow::PlaybackSettings::default(), slide_layout: slide::SlideSettings::default(), slide_overlays: slide_overlay::OverlaySettings::default(), @@ -1003,8 +1016,9 @@ impl Session { return Vec::new(); } let Some(old) = self.develop_of(id) else { return Vec::new() }; - let mut old_json = old.to_json(); - let mut new_json = new.to_json(); + // (Remove Hot Pixels, omitted when off, is stated: switching it off is a change) + let mut old_json = old.to_json_for_merge(); + let mut new_json = new.to_json_for_merge(); // False is omitted from stored profile JSON. Keep it explicit for this comparison so // switching camera local tone mapping off is a change without copying untouched values. old_json["profile"]["camera_local_tone"] = Value::Bool(old.profile.camera_local_tone); diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 23e333c4ca..8cd242face 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -258,6 +258,13 @@ impl Library { } } +/// [`PrefsFile`]'s `prep`, read leniently (see there). +fn lenient_prep<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result, D::Error> { + use serde::Deserialize; + let value = serde_json::Value::deserialize(d)?; + Ok(serde_json::from_value(value).ok()) +} + #[derive(Default, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] struct PrefsFile { @@ -295,6 +302,11 @@ struct PrefsFile { import: crate::import::ImportDefaults, /// Thumbnail disk cache budget (MB, 0 = default). cache_mb: u32, + /// This library's own background preparation settings (`None`: the app-wide ones). Read + /// leniently: a value a newer build wrote that this one doesn't know is `None`, and the rest of + /// the file is kept. + #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "lenient_prep")] + prep: Option, /// Folder for smart previews (default: `Smart Previews` in the library). smart_previews_dir: Option, /// Days after which untouched Local records of unbrowsed folders are forgotten (missing = @@ -585,6 +597,7 @@ impl Session { self.recent_keywords = prefs.recent_keywords; self.import_defaults = prefs.import; self.cache_mb = prefs.cache_mb; + self.prep.library = prefs.prep.map(crate::prep::PrepSettings::sanitized); self.slideshow = prefs.slideshow.sanitized(); self.slide_layout = prefs.slide_layout.sanitized(); self.slide_overlays = prefs.slide_overlays.sanitized(); @@ -688,6 +701,9 @@ impl Session { crate::cmd::previews::refresh_stale_smart_previews(self); } self.library_identity = std::sync::Arc::new(()); + // a library open is a new session for the low-disk alert: look at the drive now + self.disk_alert.reset(); + self.check_disk_space(true); Ok(()) } @@ -900,6 +916,7 @@ impl Session { recent_keywords: self.recent_keywords.clone(), import: self.import_defaults.clone(), cache_mb: self.cache_mb, + prep: self.prep.library, smart_previews_dir: self.smart_previews_dir.as_ref().map(|d| d.to_string_lossy().to_string()), forget_local_days: Some(self.forget_local_days), slideshow: self.slideshow.clone(), @@ -927,9 +944,23 @@ impl Session { new } - /// The thumbnail disk cache budget in bytes ([`Session::cache_mb`], else the default). + /// The thumbnail disk cache budget in bytes ([`Session::cache_mb`], else the default, which + /// grows with the library: [`crate::media::default_disk_cache_bytes`]). pub fn cache_bytes(&self) -> u64 { - if self.cache_mb == 0 { crate::media::DISK_CACHE_BYTES } else { u64::from(self.cache_mb) << 20 } + if self.cache_mb == 0 { crate::media::default_disk_cache_bytes(self.catalog.len()) } else { u64::from(self.cache_mb) << 20 } + } + + /// Bring the disk cache's budget up to date with the library (photos were added since it was + /// set): cheap, nothing is read or written. Called before previews are built, so it also + /// looks at the drive's free space when that is due ([`Session::check_disk_space`]). + pub fn fit_disk_cache(&mut self) { + let want = self.cache_bytes(); + if let Some(d) = self.media.rendered.disk() + && d.budget() != want + { + d.set_budget(want); + } + self.check_disk_space(false); } /// Change the thumbnail disk cache budget (MB, 0 = default) in place: the cached thumbnails @@ -991,6 +1022,16 @@ fn unlocked_warning(lock: Option<&LibraryLock>) -> Option { mod resolve_tests { use super::*; + /// A library's background preparation value this build doesn't know reads as none (the + /// app-wide settings apply) and keeps the rest of `prefs.json`. + #[test] + fn an_unknown_background_preparation_value_keeps_the_other_prefs() { + let v = serde_json::json!({"cacheMb": 77, "prep": {"culling": {"scope": "someday"}}}); + let read: PrefsFile = serde_json::from_value(v).unwrap(); + assert!(read.prep.is_none()); + assert_eq!(read.cache_mb, 77); + } + /// `--library /catalog.snap` failed with the OS's "File exists" (creating a folder over /// the file); it opens the library that file belongs to. #[test] diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index a4528795b1..dcba02494d 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -35,14 +35,17 @@ mod settings_hash; mod source; pub use cache::DenoiseIndex; +#[cfg(test)] +pub(crate) use cache::rendered_budget; pub use quick::{QuickJob, QuickSource, content_key, source_info}; -pub use render::{RenderJob, RenderResult, ScreenFrame, develop, develop_reporting, fit_for_display}; +pub use render::{RenderJob, RenderResult, ScreenFrame, develop, develop_reporting, fit_cached, fit_for_display}; #[cfg(test)] use settings_hash::SETTINGS_HASH_ENTRIES; use settings_hash::SettingsHashes; pub use source::{ - DISK_CACHE_BYTES, DecodedSource, DenoiseSpec, FACE_EDGE_STEP, FileLoader, FileProbe, MakeProduct, PairLoader, PreviewLoader, ProbeInfo, - RENDER_CACHE_VERSION, ReducedLoader, SourceLevel, SourceRef, THUMB_SIZES, Twin, face_edge, thumb_bucket, + DISK_CACHE_BYTES, DISK_CACHE_PER_PHOTO, DecodedSource, DenoiseSpec, FACE_EDGE_STEP, FileLoader, FileProbe, MakeProduct, PairLoader, + PreviewLoader, ProbeInfo, RENDER_CACHE_VERSION, RawDecode, ReducedLoader, SourceLevel, SourceRef, THUMB_SIZES, Twin, default_disk_cache_bytes, + face_edge, thumb_bucket, }; pub struct MediaCache { diff --git a/crates/engine/src/media/cache.rs b/crates/engine/src/media/cache.rs index 234efb1485..acba8b85be 100644 --- a/crates/engine/src/media/cache.rs +++ b/crates/engine/src/media/cache.rs @@ -75,9 +75,11 @@ impl Default for MediaCache { } } -/// Memory for rendered previews out of the cache share. -fn rendered_budget(share: usize) -> usize { - RENDERED_MEM_BYTES.min(share / 4) +/// Memory for rendered previews out of the cache share: a quarter of it, so a big budget keeps +/// a whole shoot's previews (a 20 GB budget holds about 230 standard previews, or 1 500 loupe +/// renders at 1 200 px), and at least [`RENDERED_MEM_BYTES`] where the share allows. +pub(crate) fn rendered_budget(share: usize) -> usize { + (share / 4).max(RENDERED_MEM_BYTES.min(share / 2)) } impl MediaCache { @@ -332,11 +334,12 @@ impl MediaCache { } fn source_ref_plain(&mut self, p: &Photo, level: SourceLevel, cached: bool, wanted: Option<(String, Arc)>) -> SourceRef { + let outliers = p.develop.removes_hot_pixels(); // (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) + && let Some(a) = self.get_source(p.id, level).filter(|a| a.fits_outliers(outliers)) && (a.camera_profile == wanted.as_ref().map(|(id, _)| id.clone()) || (a.from_proxy && self.original_offline(p))) { return SourceRef::Loaded(Box::new(a)); @@ -346,7 +349,7 @@ impl MediaCache { if cached && level == SourceLevel::Thumb && self.denoise.spec(p.id).is_none() - && let Some(big) = self.get_source(p.id, SourceLevel::Preview) + && let Some(big) = self.get_source(p.id, SourceLevel::Preview).filter(|b| b.fits_outliers(outliers)) && (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() }; @@ -370,15 +373,17 @@ impl MediaCache { return SourceRef::Smart { path: sp }; } let mut r = self.origin_ref(&p.source, max_edge); - if let SourceRef::File { fallback, camera_profile, .. } = &mut r { + if let SourceRef::File { fallback, camera_profile, outliers: o, .. } = &mut r { *fallback = Some(sp); *camera_profile = wanted; + *o = outliers; } return r; } let mut r = self.origin_ref(&p.source, max_edge); - if let SourceRef::File { camera_profile, .. } = &mut r { + if let SourceRef::File { camera_profile, outliers: o, .. } = &mut r { *camera_profile = wanted; + *o = outliers; } r } @@ -419,6 +424,7 @@ impl MediaCache { fallback: None, denoise: None, camera_profile: None, + outliers: false, reduced: None, }, } @@ -430,6 +436,7 @@ impl MediaCache { fallback: None, denoise: None, camera_profile: None, + outliers: false, reduced: None, }, } diff --git a/crates/engine/src/media/quick.rs b/crates/engine/src/media/quick.rs index 335a118ca6..25c93e9f81 100644 --- a/crates/engine/src/media/quick.rs +++ b/crates/engine/src/media/quick.rs @@ -25,6 +25,15 @@ pub struct QuickJob { pub cached: Vec<(Arc, Hash128)>, /// Embedded preview of an unedited raw: (path, loader, max edge). pub embedded: Option<(String, PreviewLoader, usize)>, + /// Where a decoded [`Self::embedded`] preview is kept in memory, so stepping back to a photo + /// shows its camera JPEG again without reading and decoding it (culling goes back and forth): + /// the cache (memory only, never its disk), the key for this photo and edge, and the cache's + /// generation when the job was made (a Discard Preview Cache since then keeps the picture out). + pub embedded_cache: Option<(Arc, Hash128, u64)>, + /// Whether [`Self::embedded_cache`] keeps the decoded preview on disk too: a grid thumbnail, + /// so a folder seen before fills in from small files at once instead of every raw being read + /// and its camera JPEG decoded again (the loupe's large stand-ins stay in memory). + pub embedded_on_disk: bool, /// Import tiles need this many pixels when a render can provide them. `None` accepts any /// camera JPEG immediately (ordinary transient stand-ins and preview-only imports). /// An undersized JPEG remains the fallback if the render fails or is unavailable. @@ -79,13 +88,30 @@ impl QuickJob { } } let mut embedded_fallback = None; - if let Some((path, loader, edge)) = &self.embedded - && let Some(image) = loader(path, *edge) - { - if self.minimum_embedded_edge.is_none_or(|minimum| image.width.max(image.height) >= minimum) { - return done(rendered(image), Some(QuickSource::Embedded)); + if let Some((path, loader, edge)) = &self.embedded { + let kept = + self.embedded_cache.as_ref().and_then(|(cache, k, _)| if self.embedded_on_disk { cache.get(*k) } else { cache.get_memory(*k) }); + let image = match kept { + Some(img) => Some(Arc::unwrap_or_clone(img)), + None => { + let image = loader(path, *edge); + // written for the generation the job was made in: a cache cleared meanwhile stays clear + if let (Some(image), Some((cache, k, generation))) = (&image, &self.embedded_cache) { + if self.embedded_on_disk { + cache.put_deferred_at(*generation, *k, Arc::new(image.clone())); + } else { + cache.put_memory_at(*generation, *k, Arc::new(image.clone())); + } + } + image + } + }; + if let Some(image) = image { + if self.minimum_embedded_edge.is_none_or(|minimum| image.width.max(image.height) >= minimum) { + return done(rendered(image), Some(QuickSource::Embedded)); + } + embedded_fallback = Some(image); } - embedded_fallback = Some(image); } if let Some(job) = self.small { let r = job.run(); @@ -100,6 +126,11 @@ impl QuickJob { } } +/// The thumbnail cache's key for the camera JPEG standing for the thumbnail of cache key `k`. +pub(super) fn embedded_thumb_key(k: Hash128) -> Hash128 { + Hasher128::new().str("embedded-thumb").u64((k.0 >> 64) as u64).u64(k.0 as u64).finish() +} + /// What identifies a photo's pixels for caching: its content hash, else its source. /// Which decode of a photo a loaded source is: its file's content and, when it has one, its database lens profile /// ([`lens_key`]; the decode fits the starting colour through it). A job's source is kept only when this still diff --git a/crates/engine/src/media/render.rs b/crates/engine/src/media/render.rs index 56dc3b7cb9..bd8ee5292f 100644 --- a/crates/engine/src/media/render.rs +++ b/crates/engine/src/media/render.rs @@ -1,5 +1,5 @@ use super::quick::QuickSource; -use super::source::{DecodedSource, SourceLevel, SourceRef}; +use super::source::{DecodedSource, SourceLevel, SourceRef, VIEW_REUSE_SLACK}; use super::{ Arc, DevelopSettings, Hash128, Histogram, PhotoId, PreviewCache, Quality, RenderRequest, Rendered, Rgb32f, Rgba8, Source, SourceInfo, StageCache, }; @@ -241,8 +241,58 @@ impl RenderJob { r } + /// The view render kept for this job's photo and settings ([`Self::view_cache`]), fitted to the + /// size asked for, when it is at least that big, or unchanged when it covers the job's display + /// fit (else `None`: render). Only for what the cached + /// view is: a full-quality, 8-bit, whole-frame SDR render (the cache holds sRGB; a display + /// profile is applied to it like to any cached picture, [`crate::display::present`]). + pub fn cached_view(&self) -> Option { + let (cache, key) = self.view_cache.as_ref()?; + if self.request.quality != Quality::Full + || self.request.depth != lightcraft_pipeline::OutputDepth::U8 + || self.request.window.is_some() + || self.settings.hdr.enabled + || self.slide.is_some() + { + return None; + } + let img = cache.get_at(self.cache_generation, *key)?; + fit_cached(&img, self.request.max_w, self.request.max_h).or_else(|| { + // the loupe at rest asks for at least the preview level and shows the render shrunk to + // the drawn size (the display fit): a cached view that covers the drawn size is enough + let (fw, fh) = self.display_fit?; + let (w, h) = (img.width, img.height); + let s = (fw as f64 / w.max(1) as f64).min(fh as f64 / h.max(1) as f64); + (w > 0 && h > 0 && fw > 0 && fh > 0 && s <= 1.0 + VIEW_REUSE_SLACK).then(|| Arc::unwrap_or_clone(img)) + }) + } + /// The photo's render (without slide composition). fn run_photo(self) -> RenderResult { + // the loupe: a cached view render of these settings at least this big is the render (built + // previews and the photos prepared ahead are used, not rendered again; PERF-PREVIEW-REUSE) + if let Some(mut image) = self.cached_view() { + // as for a render: the histogram of the full picture, then the display fit + let histogram = Histogram::of_srgb8(&image); + if let Some((fw, fh)) = self.display_fit + && (image.width > fw.max(1) || image.height > fh.max(1)) + { + image = fit_for_display(&image, fw, fh); + } + return RenderResult { + request_id: self.request_id, + source_key: self.source_key, + photo: self.photo, + level: self.level, + key: self.key, + rendered: Ok(Rendered { image, histogram, deep: None }), + gpu_fallback: None, + loaded: None, + quick: Some(QuickSource::Cached), + display: None, + frame: None, + }; + } if let Some((cache, key)) = &self.cache && let Some(img) = cache.get_at(self.cache_generation, *key) { @@ -395,6 +445,61 @@ impl RenderJob { } } +/// `img` fitted into `max_w × max_h` (its aspect kept), when it is big enough to need no +/// enlarging (within [`VIEW_REUSE_SLACK`]): as it is, or shrunk by averaging. +pub fn fit_cached(img: &Rgba8, max_w: usize, max_h: usize) -> Option { + let (w, h) = (img.width, img.height); + if w == 0 || h == 0 || max_w == 0 || max_h == 0 { + return None; + } + let s = (max_w as f64 / w as f64).min(max_h as f64 / h as f64); + if !s.is_finite() || s > 1.0 + VIEW_REUSE_SLACK { + return None; + } + let (nw, nh) = (((w as f64 * s).round() as usize).clamp(1, w), ((h as f64 * s).round() as usize).clamp(1, h)); + if nw == w && nh == h { + return Some(img.clone()); + } + Some(shrink_rgba(img, nw, nh)) +} + +/// `img` shrunk to `nw × nh` (no larger than it), each pixel the average of the ones it covers. +fn shrink_rgba(img: &Rgba8, nw: usize, nh: usize) -> Rgba8 { + let (w, h) = (img.width, img.height); + let (nw, nh) = (nw.clamp(1, w.max(1)), nh.clamp(1, h.max(1))); + // the source columns / rows each output column / row covers: [start, end) + let spans = |n: usize, of: usize| -> Vec<(usize, usize)> { + (0..n) + .map(|i| { + let a = i.saturating_mul(of) / n; + let b = (i.saturating_add(1).saturating_mul(of) / n).max(a.saturating_add(1)).min(of); + (a, b) + }) + .collect() + }; + let (xs, ys) = (spans(nw, w), spans(nh, h)); + let mut data = Vec::with_capacity(nw.saturating_mul(nh)); + let mut row = vec![[0u32; 4]; nw]; + for &(y0, y1) in &ys { + row.iter_mut().for_each(|r| *r = [0; 4]); + for y in y0..y1 { + let Some(line) = img.data.get(y * w..(y + 1) * w) else { continue }; + for (acc, &(x0, x1)) in row.iter_mut().zip(&xs) { + for px in line.get(x0..x1).unwrap_or(&[]) { + for (a, v) in acc.iter_mut().zip(px) { + *a += u32::from(*v); + } + } + } + } + for (acc, &(x0, x1)) in row.iter().zip(&xs) { + let n = (x1.saturating_sub(x0).saturating_mul(y1.saturating_sub(y0))).max(1) as u32; + data.push(acc.map(|a| ((a + n / 2) / n).min(255) as u8)); + } + } + Rgba8 { width: nw, height: nh, data } +} + /// Render `src`: on the GPU when `gpu` is set and a GPU is available (`lightcraft_gpu`), else on /// the CPU, reusing `stages` either way. Both produce the same image within 1–3 LSB (see /// `docs/gpu-pipeline.md`); `LIGHTCRAFT_GPU=0` or [`lightcraft_gpu::set_enabled`] forces the CPU. diff --git a/crates/engine/src/media/session.rs b/crates/engine/src/media/session.rs index ac1b8145a9..a3d5069177 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -1,4 +1,4 @@ -use super::quick::{QuickJob, content_key, source_info}; +use super::quick::{QuickJob, content_key, embedded_thumb_key, source_info}; use super::render::{RenderJob, RenderResult}; use super::settings_hash::with_process; use super::source::{PreviewLoader, RENDER_CACHE_VERSION, SourceLevel, SourceRef, THUMB_SIZES, face_edge, source_edge_needed, thumb_bucket}; @@ -58,7 +58,8 @@ impl crate::Session { 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 settings_hash = + if before { settings.hash64() ^ crate::files::hot_pixel_key(&settings) } 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); @@ -131,6 +132,7 @@ impl crate::Session { // (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() + ^ crate::files::hot_pixel_key(settings) ^ ((max_w as u64) << 40) ^ ((max_h as u64) << 20) ^ (apply_crop as u64) @@ -144,7 +146,11 @@ impl crate::Session { /// `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); + k.str(&content_key(p)) + .str("variant") + .u64(settings.hash64() ^ crate::files::hot_pixel_key(settings)) + .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); @@ -264,12 +270,23 @@ impl crate::Session { Some(crate::face_tiles::PreviewCut { path, loader, want, min, rect, aspect, edge }) } - /// Size-independent cache key of a photo's view render (loupe) for its current settings, its lens profile - /// included as in [`Self::variant_key`]. `profile_salt`: [`MediaCache::camera_profile_salt`] of the photo's profile. - pub(crate) fn view_key(p: &Photo, apply_crop: bool, profile_salt: u64) -> Hash128 { + /// Size-independent cache key of a photo's view render (loupe) for its current settings. The + /// denoised picture, camera profile and lens profile in use are part of it (as of the render's own + /// key, [`Self::variant_key`]): a view rendered before the photo's AI Denoise result was there is + /// not shown as the denoised one. + pub(crate) fn view_key(&self, p: &Photo, apply_crop: bool) -> Hash128 { + let salt = self.media.denoise_salt(p.id, &p.develop); + let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id); let mut k = Hasher128::new(); - k.str(&content_key(p)).str("view").u64(p.develop.hash64()).u64(apply_crop as u64).u64(RENDER_CACHE_VERSION); + k.str(&content_key(p)) + .str("view") + .u64(p.develop.hash64() ^ crate::files::hot_pixel_key(&p.develop)) + .u64(apply_crop as u64) + .u64(RENDER_CACHE_VERSION); with_process(&mut k, &p.develop).u64(crate::camera_profiles::cache_key()); + if salt != 0 { + k.u64(salt); + } if profile_salt != 0 { k.str("dcp").u64(profile_salt); } @@ -285,8 +302,7 @@ impl crate::Session { pub fn loupe_job(&mut self, id: PhotoId, max_w: usize, max_h: usize, apply_crop: bool) -> Option { let mut job = self.render_job(id, max_w, max_h, false, apply_crop)?; let p = self.catalog.photo(id)?; - let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id); - job.view_cache = Some((self.media.rendered.clone(), Self::view_key(p, apply_crop, profile_salt))); + job.view_cache = Some((self.media.rendered.clone(), self.view_key(p, apply_crop))); Some(job) } @@ -396,11 +412,55 @@ impl crate::Session { let small = self.thumb_job(id, THUMB_SIZES[THUMB_SIZES.len() - 1])?; // (the thumbnail job itself starts with the cached thumbnail, after the sharper embedded preview) let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id); - let cached = vec![(self.media.rendered.clone(), Self::view_key(&p, apply_crop, profile_salt))]; - let h = Hasher128::new().str(&content_key(&p)).str("quick").u64(p.develop.hash64()).u64(apply_crop as u64).u64(profile_salt).finish(); + let cached = vec![(self.media.rendered.clone(), self.view_key(&p, apply_crop))]; + // (the photo too: a virtual copy shares the file and, unedited, the settings) + let h = Hasher128::new() + .str(&content_key(&p)) + .str("quick") + .u64(p.develop.hash64() ^ crate::files::hot_pixel_key(&p.develop)) + .u64(apply_crop as u64) + .u64(id.0) + .u64(profile_salt) + .finish(); let key = h.0 as u64; let embedded = self.embedded_of(&p).map(|(path, l)| (path, l, max_edge.clamp(1, SourceLevel::Preview.max_edge()))); - Some(QuickJob { request_id: 0, photo: id, key, cached, embedded, minimum_embedded_edge: None, small: apply_crop.then(|| Box::new(small)) }) + let embedded_cache = embedded.as_ref().map(|(_, _, edge)| { + let cache = self.media.rendered.clone(); + let generation = cache.generation(); + (cache, Hasher128::new().str(&content_key(&p)).str("embedded").u64(*edge as u64).finish(), generation) + }); + Some(QuickJob { + request_id: 0, + photo: id, + key, + cached, + embedded, + embedded_cache, + embedded_on_disk: false, + minimum_embedded_edge: None, + small: apply_crop.then(|| Box::new(small)), + }) + } + + /// The camera's embedded JPEG of an unedited raw at up to `max_edge` pixels (its full size for + /// a camera that stores one), for the loupe zoomed to 100 % while LightCraft renders the window + /// on screen: a focus check needs the pixels at once, and a 45 MP render of the window takes + /// seconds. Not kept in any cache (a full-size picture is 180 MB). `None` for other photos. + pub fn embedded_full_job(&mut self, id: PhotoId, max_edge: usize) -> Option { + let p = self.catalog.photo(id)?.clone(); + let (path, l) = self.embedded_of(&p)?; + let key = Hasher128::new().str(&content_key(&p)).str("embedded-full").u64(id.0).u64(max_edge as u64).finish().0 as u64; + Some(QuickJob { + request_id: 0, + photo: id, + key, + cached: Vec::new(), + embedded: Some((path, l, max_edge.max(1))), + embedded_cache: None, + embedded_on_disk: false, + minimum_embedded_edge: None, + small: None, + }) } /// A first grid thumbnail for an unedited raw: the cached render for `job` (the real @@ -419,6 +479,10 @@ impl crate::Session { key: job.key, cached: job.cache.clone().into_iter().collect(), embedded: Some((path, l, edge)), + // the camera JPEG is this thumbnail (an unedited raw): kept with the rendered ones, under + // a key of its own, so the folder's next visit reads it from the thumbnail cache + embedded_cache: job.cache.as_ref().map(|(c, k)| (c.clone(), embedded_thumb_key(*k), c.generation())), + embedded_on_disk: true, minimum_embedded_edge: None, small: Some(Box::new(job.clone())), }) diff --git a/crates/engine/src/media/settings_hash.rs b/crates/engine/src/media/settings_hash.rs index 39f76d52bb..66598924dc 100644 --- a/crates/engine/src/media/settings_hash.rs +++ b/crates/engine/src/media/settings_hash.rs @@ -17,7 +17,7 @@ impl SettingsHashes { { return *hash; } - let hash = settings.hash64(); + let hash = settings.hash64() ^ crate::files::hot_pixel_key(settings); #[cfg(test)] { self.computations += 1; diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index f13349f18c..ce2e89862f 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -24,10 +24,23 @@ pub fn thumb_bucket(long_edge: usize) -> usize { /// Memory budgets. pub(super) const THUMB_SOURCE_BYTES: usize = 384 << 20; +/// The least memory kept for rendered previews (when the budget allows it). pub(super) const RENDERED_MEM_BYTES: usize = 128 << 20; -/// Disk budget for the thumbnail cache. +/// The smallest disk budget for the thumbnail and preview cache. pub const DISK_CACHE_BYTES: u64 = 2 << 30; +/// What one photo's previews take on disk, about: its standard preview (a 2048 px JPEG, ~1 MB) +/// and its grid thumbnails. The default disk budget grows by this per photo of the library, so +/// built previews of a whole wedding are not pruned while they are being made (PERF-PREVIEW-REUSE). +pub const DISK_CACHE_PER_PHOTO: u64 = 3 << 19; +/// The default disk budget for a library of `photos`: [`DISK_CACHE_BYTES`], or room for every +/// photo's previews ([`DISK_CACHE_PER_PHOTO`]) when that is more. +pub fn default_disk_cache_bytes(photos: usize) -> u64 { + DISK_CACHE_BYTES.max((photos as u64).saturating_mul(DISK_CACHE_PER_PHOTO)) +} +/// A cached view render this much smaller than asked for still serves the loupe (rounding: a +/// fit of the same frame into a box one pixel different). +pub(super) const VIEW_REUSE_SLACK: f64 = 0.01; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] @@ -74,15 +87,22 @@ pub(super) fn source_edge_needed(p: &Photo, settings: &DevelopSettings, apply_cr if needed.is_finite() { needed.min(usize::MAX as f64 / 2.0) as usize } else { out_long } } -/// Decodes a file into a linear Rec.2020 image no larger than `max_edge` (set by the app). -/// 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>; +/// How a raw file is decoded for a photo. +#[derive(Clone, Copy, Default)] +pub struct RawDecode<'a> { + /// The photo's imported camera profile ([`crate::cmd::dcp_profiles`]): a raw file is developed with its colour model. + pub dcp: Option<&'a DcpProfile>, + /// Replace a raw's single outlier photosites first ([`DevelopSettings`] `detail.nr_outliers`). + pub outliers: bool, +} + +/// Decodes a file into a linear Rec.2020 image no larger than `max_edge` (set by the app), as the third argument says. +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. @@ -105,8 +125,7 @@ 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 { @@ -139,6 +158,8 @@ pub struct DecodedSource { /// 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, + /// Decoded with a raw's single outlier photosites replaced (`detail.nr_outliers`). + pub outliers: bool, /// 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, @@ -149,7 +170,14 @@ pub struct DecodedSource { impl DecodedSource { pub fn new(image: Arc, info: Option) -> Self { - DecodedSource { image, info, camera_tone: None, denoised: None, camera_profile: None, from_proxy: false, reduced: false } + DecodedSource { image, info, camera_tone: None, denoised: None, camera_profile: None, outliers: false, from_proxy: false, reduced: false } + } + + /// Whether this source can stand for one decoded with `outliers`: a raw decode must match it; anything without a + /// mosaic (a rendered file, a smart preview, a demo scene) has nothing the flag would change. A smart preview's + /// facts say `raw` for a raw photo, so it is told apart by `from_proxy`. + pub fn fits_outliers(&self, outliers: bool) -> bool { + self.outliers == outliers || self.from_proxy || !self.info.as_ref().is_some_and(|i| i.raw) } /// The picture to develop for a Denoise `amount` (0 to 1, see [`DevelopSettings::denoise_amount`]): the plain one, @@ -243,6 +271,8 @@ pub enum SourceRef { 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)>, + /// Replace a raw's single outlier photosites before developing it (`detail.nr_outliers`). + outliers: bool, /// A thumbnail's loader, used instead of `loader` (see [`ReducedLoader`]); `None` for every other job. reduced: Option, }, @@ -270,17 +300,21 @@ 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, camera_profile, reduced } => { - let dcp = camera_profile.as_ref().map(|(_, p)| p.as_ref()); + SourceRef::File { path, max_edge, loader, fallback, denoise, camera_profile, outliers, reduced } => { + let with = RawDecode { dcp: camera_profile.as_ref().map(|(_, p)| p.as_ref()), outliers: *outliers }; let made_with = camera_profile.as_ref().map(|(id, _)| id.clone()); let plain = || match (reduced, loader) { - (Some(l), _) => l(path, *max_edge, dcp).map(|(image, info, reduced)| DecodedSource { + (Some(l), _) => l(path, *max_edge, with).map(|(image, info, reduced)| DecodedSource { reduced, camera_profile: made_with.clone(), + outliers: *outliers, + ..DecodedSource::new(Arc::new(image), Some(info)) + }), + (None, Some(l)) => l(path, *max_edge, with).map(|(image, info)| DecodedSource { + camera_profile: made_with.clone(), + outliers: *outliers, ..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 @@ -294,7 +328,7 @@ impl SourceRef { None => true, }; if made { - pair(path, *max_edge, spec, dcp).and_then(|(image, twin, info)| { + pair(path, *max_edge, spec, with).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()); } @@ -304,6 +338,7 @@ impl SourceRef { camera_tone: None, denoised: twin.map(|t| Arc::new(Twin::new(Arc::new(t)))), camera_profile: made_with.clone(), + outliers: *outliers, from_proxy: false, reduced: false, }) @@ -355,6 +390,9 @@ pub struct ProbeInfo { pub embedded_lens: Option, /// The file's embedded XMP packet (raw/DNG files), for develop settings stored inside the file. pub xmp: Option, + /// The file's Exif orientation, when it states one: how its stored pixels turn upright (`width` and `height` are + /// the upright size). + pub orientation: Option, /// A raw variant that can't be decoded yet: why. The file is described (and will be shown and /// edited) from its embedded preview; see [`lightcraft_catalog::Photo::preview_only`]. pub preview_only: Option, diff --git a/crates/engine/src/media/tests.rs b/crates/engine/src/media/tests.rs index 7d5f80b6e5..0db6e0a958 100644 --- a/crates/engine/src/media/tests.rs +++ b/crates/engine/src/media/tests.rs @@ -91,6 +91,7 @@ fn decoder_info_survives_render_jobs_cache_and_eviction() { fallback: None, denoise: None, camera_profile: None, + outliers: false, reduced: None, }; job.info = SourceInfo::default(); // Header facts cannot override decoder facts. @@ -148,6 +149,7 @@ fn old_relative_white_balance_on_a_kelvin_camera_keeps_its_look_and_learns_the_a fallback: None, denoise: None, camera_profile: None, + outliers: false, 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 85089d231d..9379288e26 100644 --- a/crates/engine/src/media/thumbnail_hash_tests.rs +++ b/crates/engine/src/media/thumbnail_hash_tests.rs @@ -6,6 +6,60 @@ fn session() -> crate::Session { s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); s } +/// PERF-CULL: an unedited raw's camera JPEG is read once for the loupe and kept in memory for a +/// step back; the full-size one (zoomed in) is made at the size asked for and kept nowhere; an +/// edited raw or another file has none. +#[test] +fn camera_previews_are_kept_for_a_revisit_and_full_size_ones_are_not() { + let reads = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let mut s = crate::Session::new(); + let r = reads.clone(); + s.media.preview_loader = Some(Arc::new(move |_: &str, edge: usize| { + r.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Some(Rgba8 { width: edge.min(64), height: 2, data: vec![[9, 8, 7, 255]; edge.min(64) * 2] }) + })); + let mut raw = Photo::new(PhotoId(1), Source::File { path: "a.cr3".into() }, "a.cr3", "CR3", 6000, 4000, "2026-01-01"); + raw.kind = MediaKind::Raw; + raw.develop = Arc::new(raw.camera_defaults()); + s.catalog.apply(Op::AddPhoto { photo: Box::new(raw) }).unwrap(); + let jpeg = Photo::new(PhotoId(2), Source::File { path: "b.jpg".into() }, "b.jpg", "JPEG", 600, 400, "2026-01-01"); + s.catalog.apply(Op::AddPhoto { photo: Box::new(jpeg) }).unwrap(); + for _ in 0..3 { + let q = s.quick_view_job(PhotoId(1), 48, true).unwrap(); + let r = q.run(); + assert_eq!(r.quick, Some(QuickSource::Embedded)); + } + assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 1, "read once, then from memory"); + let full = s.embedded_full_job(PhotoId(1), 8192).unwrap(); + assert!(full.embedded_cache.is_none() && full.cached.is_empty() && full.small.is_none()); + assert_eq!(full.embedded.as_ref().map(|e| e.2), Some(8192)); + assert_ne!(full.key, s.quick_view_job(PhotoId(1), 48, true).unwrap().key); + assert_eq!(full.run().quick, Some(QuickSource::Embedded)); + assert!(s.embedded_full_job(PhotoId(2), 8192).is_none(), "not a raw"); + let mut edited = (*s.catalog.photo(PhotoId(1)).unwrap().develop).clone(); + edited.light.exposure = 1.0; + s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(edited), label: "edit".into(), edited: None }).unwrap(); + assert!(s.embedded_full_job(PhotoId(1), 8192).is_none(), "an edit is shown rendered"); +} + +/// A virtual copy shares its master's file and, unedited, its settings; its loupe stand-ins +/// are its own all the same (CodeRabbit on #3080). +#[test] +fn a_virtual_copy_has_its_own_stand_in_keys() { + let mut s = crate::Session::new(); + s.media.preview_loader = Some(Arc::new(|_: &str, _: usize| None::)); + for id in [1, 2] { + let mut raw = Photo::new(PhotoId(id), Source::File { path: "a.cr3".into() }, "a.cr3", "CR3", 6000, 4000, "2026-01-01"); + raw.kind = MediaKind::Raw; + raw.develop = Arc::new(raw.camera_defaults()); + s.catalog.apply(Op::AddPhoto { photo: Box::new(raw) }).unwrap(); + } + let quick = |s: &mut crate::Session, id: u64| s.quick_view_job(PhotoId(id), 48, true).unwrap().key; + assert_ne!(quick(&mut s, 1), quick(&mut s, 2)); + let full = |s: &mut crate::Session, id: u64| s.embedded_full_job(PhotoId(id), 8192).unwrap().key; + assert_ne!(full(&mut s, 1), full(&mut s, 2)); +} + /// Settings saved by a newer LightCraft (a process number this build doesn't know) render with /// this build's latest process, and a build that resolved the number to an older process /// cached other pixels under the same settings hash: the persistent keys (thumbnails, the @@ -37,7 +91,7 @@ fn persistent_keys_name_the_process_the_settings_render_with() { let resolved = u64::from(lightcraft_develop::Process::LATEST.version().0); let keys = [ (s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1, None, 256), - (crate::Session::view_key(&p, true, 0), Some("view"), 1), + (s.view_key(&p, true), Some("view"), 1), (crate::Session::variant_key(&p, &newer, 256, 0), Some("variant"), 256), ]; for (key, kind, size) in keys { @@ -69,7 +123,7 @@ fn v1_and_v2_photos_keep_the_render_cache_keys_they_had() { }; let keys = [ s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1 == before_v3(None, 256), - crate::Session::view_key(&p, true, 0) == before_v3(Some("view"), 1), + s.view_key(&p, true) == before_v3(Some("view"), 1), crate::Session::variant_key(&p, &settings, 256, 0) == before_v3(Some("variant"), 256), ]; let old = process <= Process::V2; @@ -217,6 +271,8 @@ fn a_render_that_panics_fails_instead_of_never_answering() { key: 9, cached: Vec::new(), embedded: Some(("x.arw".into(), Arc::new(|_: &str, _: usize| -> Option { panic!("preview reader bug") }), 256)), + embedded_cache: None, + embedded_on_disk: false, minimum_embedded_edge: None, small: None, }; @@ -224,3 +280,121 @@ fn a_render_that_panics_fails_instead_of_never_answering() { assert_eq!((r.request_id, r.key), (7, 9)); assert_eq!(r.rendered.err().as_deref(), Some("the render failed unexpectedly: preview reader bug")); } + +/// A raw photo's smart preview has no mosaic left: it stands in with the box on or off, so an offline raw keeps +/// reusing the decoded proxy instead of reading the file again for every render. +#[test] +fn a_smart_preview_fits_either_hot_pixel_setting() { + let raw = SourceInfo { raw: true, ..Default::default() }; + let decoded = DecodedSource::new(Arc::new(Rgb32f::new(8, 8)), Some(raw)); + assert!(decoded.fits_outliers(false) && !decoded.fits_outliers(true), "a raw decode must match the box"); + let proxy = DecodedSource { from_proxy: true, ..decoded }; + assert!(proxy.fits_outliers(false) && proxy.fits_outliers(true)); +} + +/// The Remove Hot Pixels box decides how a raw is decoded (#1345): the loader is told, and a source decoded with +/// the other setting is not reused. A rendered file has no mosaic, so its source stays. +#[test] +fn hot_pixel_box_decodes_the_raw_again() { + let mut s = session(); + let asked = Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + let raw = Arc::new(std::sync::atomic::AtomicBool::new(true)); + let is_raw = raw.clone(); + s.media.file_loader = Some(Arc::new(move |_, _, with: crate::media::RawDecode<'_>| { + log.lock().unwrap().push(with.outliers); + Ok((Rgb32f::new(8, 8), SourceInfo { raw: is_raw.load(std::sync::atomic::Ordering::Relaxed), ..Default::default() })) + })); + let set = |s: &mut crate::Session, on: bool| { + let mut d = (*s.catalog.photo(PhotoId(1)).unwrap().develop).clone(); + d.detail.nr_outliers = on; + // a new edit each time, so a render cached for earlier settings is not simply shown again + d.light.exposure += 0.1; + s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(d), label: "box".into(), edited: None }).unwrap(); + }; + let render = |s: &mut crate::Session| { + let r = s.thumb_job(PhotoId(1), 256).unwrap().run(); + s.accept(&r); + }; + render(&mut s); + render(&mut s); + assert_eq!(*asked.lock().unwrap(), [false], "decoded once, then cached"); + set(&mut s, true); + render(&mut s); + render(&mut s); + assert_eq!(*asked.lock().unwrap(), [false, true], "switched on: decoded again with the filter, then cached"); + set(&mut s, false); + render(&mut s); + assert_eq!(*asked.lock().unwrap(), [false, true, false]); + // not a raw: the box changes nothing, the cached source is kept + raw.store(false, std::sync::atomic::Ordering::Relaxed); + s.media.forget(PhotoId(1)); + set(&mut s, false); + render(&mut s); + set(&mut s, true); + render(&mut s); + assert_eq!(*asked.lock().unwrap(), [false, true, false, false]); +} + +/// With the Detail section's eye off, Remove Hot Pixels contributes nothing either: the raw is decoded without it. +#[test] +fn detail_eye_off_decodes_the_raw_without_hot_pixel_removal() { + let mut s = session(); + let asked = Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + s.media.file_loader = Some(Arc::new(move |_, _, with: crate::media::RawDecode<'_>| { + log.lock().unwrap().push(with.outliers); + Ok((Rgb32f::new(8, 8), SourceInfo { raw: true, ..Default::default() })) + })); + for eye in [true, false] { + let mut d = (*s.catalog.photo(PhotoId(1)).unwrap().develop).clone(); + d.detail.nr_outliers = true; + d.set_section_enabled("detail", eye); + d.light.exposure += 0.1; + s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(d), label: "eye".into(), edited: None }).unwrap(); + let r = s.thumb_job(PhotoId(1), 256).unwrap().run(); + s.accept(&r); + } + assert_eq!(*asked.lock().unwrap(), [true, false]); +} + +/// CodeRabbit on #3544: a stand-in job decoding a camera JPEG when Discard Preview Cache clears the +/// cache doesn't put the picture back: it writes for the generation it was made in (memory and +/// disk alike), as render jobs do. +#[test] +fn a_camera_jpeg_decoded_across_a_cache_clear_is_not_kept() { + for on_disk in [false, true] { + let cache = Arc::new(PreviewCache::memory(64 << 20)); + let made_in = cache.generation(); + let key = Hash128(5); + let quick = QuickJob { + request_id: 1, + photo: PhotoId(1), + key: 2, + cached: Vec::new(), + embedded: Some(("x.arw".into(), Arc::new(|_: &str, _: usize| Some(Rgba8::new(16, 16))), 256)), + embedded_cache: Some((cache.clone(), key, made_in)), + embedded_on_disk: on_disk, + minimum_embedded_edge: None, + small: None, + }; + // the user discards the cache while the job is on its way + cache.clear(); + assert!(quick.run().rendered.is_ok(), "the stand-in is still shown"); + assert!(cache.get_memory(key).is_none(), "on disk {on_disk}: nothing kept in the cleared cache"); + // a job made after the clear keeps it as before + let quick = QuickJob { + request_id: 1, + photo: PhotoId(1), + key: 2, + cached: Vec::new(), + embedded: Some(("x.arw".into(), Arc::new(|_: &str, _: usize| Some(Rgba8::new(16, 16))), 256)), + embedded_cache: Some((cache.clone(), key, cache.generation())), + embedded_on_disk: on_disk, + minimum_embedded_edge: None, + small: None, + }; + assert!(quick.run().rendered.is_ok()); + assert!(cache.get_memory(key).is_some(), "on disk {on_disk}: kept when made after the clear"); + } +} diff --git a/crates/engine/src/prep.rs b/crates/engine/src/prep.rs new file mode 100644 index 0000000000..bb53d24418 --- /dev/null +++ b/crates/engine/src/prep.rs @@ -0,0 +1,532 @@ +//! Preparing photos in the background (PERF-PREVIEW-PREP, notes 47 and 48): while the user culls, +//! the photos ahead are made ready before they are reached, and with the machine otherwise idle +//! the previews of every photo in view are built, so stepping never waits for a render. +//! +//! What is prepared is set per mode, because each mode needs something else: +//! - **Culling** (a folder browsed before import, the Import tab): previews of every photo in the +//! folder, the next photos' loupe renders and their eye focus strips. +//! - **Library**: the same for the photos in the library's view. +//! - **Develop** (editing): the next photos decoded and kept ready to edit. +//! +//! Each mode has its own switch for the whole-view build, how many photos ahead to prepare (0 = +//! none) and which photos ([`Scope`]). The settings are app-wide (the desktop app keeps them in `ui.json`) +//! and a library can keep its own (its `prefs.json`): a timelapse library prepares nothing while a +//! wedding library prepares everything. +//! +//! The whole-view build is the preview build ([`crate::cmd::previews`]) in its background form: two +//! lanes, waiting whenever the photo on screen is being made ([`foreground`]), nearest photos to the +//! user first and re-aimed as they move ([`crate::cmd::previews::PreviewBuild::focus_on`]), photos +//! with previews skipped, one row in the activity stack that can be cancelled. It starts once the +//! user is culling (a few photos stepped through in the loupe), never just because a library was +//! opened (note 36: opening an old library to look at two photos must not start rebuilding). + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use lightcraft_catalog::PhotoId; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::Session; +use crate::cmd::previews::PreviewBuild; + +/// Which photos a mode prepares. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Scope { + /// Every photo in view (the folder, the collection, the filter). + #[default] + All, + /// Only picks, and photos with stars or a colour label. + Marked, + /// Only the photo on screen: nothing ahead, nothing in the background. + OnScreen, +} + +impl Scope { + pub fn parse(s: &str) -> Option { + match s { + "all" => Some(Scope::All), + "marked" => Some(Scope::Marked), + "onScreen" => Some(Scope::OnScreen), + _ => None, + } + } +} + +/// The most photos prepared ahead of the one on screen. +pub const MAX_AHEAD: u8 = 20; + +/// What one mode prepares. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct ModePrep { + /// Build the previews of every photo in scope in the background. + pub previews: bool, + /// Photos ahead (in the direction of travel) whose loupe render is made before they are reached (0 = none). + pub ahead: u8, + /// Photos ahead whose eye focus strip is worked out before they are reached (0 = only the one on + /// screen), for a frontend that shows one (the desktop app doesn't yet). + pub eye_ahead: u8, + pub scope: Scope, +} + +impl Default for ModePrep { + fn default() -> Self { + ModePrep { previews: true, ahead: 5, eye_ahead: 8, scope: Scope::All } + } +} + +/// Editing: what is kept ready for the next photos. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct DevelopPrep { + /// Photos ahead decoded and kept ready to edit (0 = none). + pub ahead: u8, + pub scope: Scope, +} + +impl Default for DevelopPrep { + fn default() -> Self { + DevelopPrep { ahead: 2, scope: Scope::All } + } +} + +/// The background preparation settings. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct PrepSettings { + pub culling: ModePrep, + pub library: ModePrep, + pub develop: DevelopPrep, +} + +impl PrepSettings { + /// Values from files or agents kept in range. + pub fn sanitized(mut self) -> Self { + for m in [&mut self.culling, &mut self.library] { + m.ahead = m.ahead.min(MAX_AHEAD); + m.eye_ahead = m.eye_ahead.min(MAX_AHEAD); + } + self.develop.ahead = self.develop.ahead.min(MAX_AHEAD); + self + } + + /// The settings of a browsing mode ([`Mode::Culling`] or [`Mode::Library`]; Develop prepares + /// views the way the Library does). + pub fn mode(&self, mode: Mode) -> ModePrep { + match mode { + Mode::Culling => self.culling, + Mode::Library | Mode::Develop => self.library, + } + } + + /// Photos ahead to render for the loupe in `mode` (0 when its scope is the photo on screen). + pub fn ahead(&self, mode: Mode) -> usize { + match mode { + Mode::Develop if self.develop.scope == Scope::OnScreen => 0, + Mode::Develop => usize::from(self.develop.ahead), + m => { + let p = self.mode(m); + if p.scope == Scope::OnScreen { 0 } else { usize::from(p.ahead) } + } + } + } + + /// Photos ahead whose eye focus strip is worked out in `mode`. + pub fn eye_ahead(&self, mode: Mode) -> usize { + let p = self.mode(mode); + if p.scope == Scope::OnScreen { 0 } else { usize::from(p.eye_ahead) } + } + + /// The scope that applies in `mode`. + pub fn scope(&self, mode: Mode) -> Scope { + match mode { + Mode::Develop => self.develop.scope, + m => self.mode(m).scope, + } + } + + /// Apply the fields of `patch` (a partial object, as `prefs.setBackgroundPrep` takes it). + pub fn patched(&self, patch: &Value) -> Result { + let mut v = serde_json::to_value(self).map_err(|e| e.to_string())?; + merge(&mut v, patch, 0); + let p: PrepSettings = serde_json::from_value(v).map_err(|e| format!("background preparation settings: {e}"))?; + Ok(p.sanitized()) + } +} + +/// `patch` merged into `into`, objects field by field (two levels deep: mode → field). +fn merge(into: &mut Value, patch: &Value, depth: usize) { + match (into, patch) { + (Value::Object(a), Value::Object(b)) if depth < 3 => { + for (k, v) in b { + match a.get_mut(k) { + Some(old) => merge(old, v, depth + 1), + None => { + a.insert(k.clone(), v.clone()); + } + } + } + } + (a, b) => *a = b.clone(), + } +} + +/// What the user is doing, as far as preparation goes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Mode { + Culling, + Library, + Develop, +} + +impl Mode { + pub fn parse(s: &str) -> Option { + match s { + "culling" => Some(Mode::Culling), + "library" => Some(Mode::Library), + "develop" => Some(Mode::Develop), + _ => None, + } + } + + /// The mode of what `s` shows when the frontend doesn't say: a folder browsed before import is + /// culling, anything else the library. + pub fn of(s: &Session) -> Mode { + if s.source == crate::LibrarySource::Folder { Mode::Culling } else { Mode::Library } + } +} + +/// Photos the user steps through in the loupe before the whole view is prepared: a library opened +/// to look at one photo starts nothing. +pub const STEPS_BEFORE_BUILD: usize = 3; +/// How long a view whose build couldn't start waits before trying again. +pub const RETRY_AFTER: std::time::Duration = std::time::Duration::from_secs(30); + +/// The background preparation's state in a session. +#[derive(Default)] +pub struct PrepState { + /// App-wide settings. + pub app: PrepSettings, + /// This library's own (`None`: it uses the app-wide ones). + pub library: Option, + /// The background build this preparation started. + build: Option>, + /// The view (its signature) whose build was started, or that the user stopped. + started_for: Option, + declined_for: Option, + /// A build that couldn't start: the view (its signature), and when it may try again (not on + /// every tick while the cause lasts; CodeRabbit on #3080). + pub retry_at: Option<(u64, web_time::Instant)>, + /// Tests: the next starts to fail, as a build thread that can't be spawned does. + #[cfg(test)] + pub(crate) fail_starts: usize, + /// The view the steps were counted in, the photo last seen, and the steps. + steps_in: Option, + last_at: Option, + steps: usize, +} + +impl std::fmt::Debug for PrepState { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PrepState").field("app", &self.app).field("library", &self.library).field("steps", &self.steps).finish() + } +} + +impl PrepState { + /// The settings in use. + pub fn settings(&self) -> PrepSettings { + self.library.unwrap_or(self.app) + } +} + +/// Until when (ms on [`clock_ms`]) the photo on screen is being made: background work waits. +static FOREGROUND_UNTIL: AtomicU64 = AtomicU64::new(0); + +/// How long a foreground signal holds background work back (ms): a little more than a frame +/// apart, so a frontend saying it every frame holds it back the whole time. +const FOREGROUND_HOLD_MS: u64 = 250; + +fn clock_ms() -> u64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + u64::try_from(START.get_or_init(web_time::Instant::now).elapsed().as_millis()).unwrap_or(u64::MAX) +} + +/// The frontend says the photo on screen is being made (a render it waits for is on its way): +/// background preparation waits until it has been quiet for a moment. +pub fn foreground() { + FOREGROUND_UNTIL.store(clock_ms().saturating_add(FOREGROUND_HOLD_MS), Ordering::Relaxed); +} + +/// Whether the photo on screen is being made now. +pub fn foreground_busy() -> bool { + #[cfg(test)] + if TEST_HOLD.load(Ordering::Relaxed) > 0 { + return true; + } + clock_ms() < FOREGROUND_UNTIL.load(Ordering::Relaxed) +} + +/// Tests: hold every background build at its foreground wait until released (a synchronization +/// point that doesn't depend on the hold's 250 ms). A count, not a switch: tests running side by +/// side each hold until their own release, and one test's release doesn't free another's build. +#[cfg(test)] +static TEST_HOLD: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Holds background builds while it lives (also when the test fails), whatever other holds do. +#[cfg(test)] +pub(crate) struct TestHold; + +#[cfg(test)] +impl TestHold { + pub(crate) fn new() -> Self { + TEST_HOLD.fetch_add(1, Ordering::Relaxed); + TestHold + } +} + +#[cfg(test)] +impl Drop for TestHold { + fn drop(&mut self) { + // (one release per hold made: never below 0) + TEST_HOLD.fetch_sub(1, Ordering::Relaxed); + } +} + +/// Wait while the photo on screen is being made. `true`: `cancel` was set meanwhile. +pub fn wait_for_foreground(cancel: &AtomicBool) -> bool { + #[cfg(not(target_arch = "wasm32"))] + while foreground_busy() { + if cancel.load(Ordering::Relaxed) { + return true; + } + std::thread::sleep(std::time::Duration::from_millis(30)); + } + cancel.load(Ordering::Relaxed) +} + +/// Photos the background build renders side by side: each render spreads over the cores already, +/// so two keep the machine busy while leaving room for the photo on screen. +pub fn background_lanes() -> usize { + let cores = std::thread::available_parallelism().map_or(2, |n| n.get()); + if cores >= 8 { 2 } else { 1 } +} + +/// A cheap identity of the photos a build prepares: a build is started once per view. `scope` +/// [`Scope::Marked`]: which of them are marked counts too (marking a photo changes the set). +fn signature(ids: &[PhotoId], s: &Session, scope: Scope) -> u64 { + let mut h = lightcraft_preview::Hasher128::new(); + h.u64(ids.len() as u64).u64(s.catalog.len() as u64); + // every id: a sort that moves photos in the middle is another view + for id in ids { + h.u64(id.0); + if scope == Scope::Marked { + h.u64(u64::from(marked(s, *id))); + } + } + h.finish().0 as u64 +} + +/// Whether `id` is a pick, or has stars or a colour label (the [`Scope::Marked`] photos). +pub fn marked(s: &Session, id: PhotoId) -> bool { + s.catalog.photo(id).is_some_and(|p| p.flag == lightcraft_catalog::Flag::Pick || p.rating > 0 || p.label.is_some()) +} + +impl Session { + /// How long until a view whose build couldn't start tries again ([`RETRY_AFTER`]), while one + /// waits: the app asks for a frame then, so the retry doesn't wait for the next input + /// (CodeRabbit on #3077/#3080). `None` once the time has come. + pub fn prep_retry_in(&self) -> Option { + // (a deadline that has passed asks for nothing: the pass at it tried again, or the view + // can't be tried now and a frame at once on every pass would keep an idle window drawing: + // CodeRabbit on #3077 / #3080) + let wait = self.prep.retry_at.map(|(_, at)| at.saturating_duration_since(web_time::Instant::now()))?; + (!wait.is_zero()).then_some(wait) + } + + /// The background preparation settings in use (this library's own, else the app-wide ones). + pub fn prep_settings(&self) -> PrepSettings { + self.prep.settings() + } + + /// Advance the background preparation (cheap; call every frame). `mode`: what the user is doing; + /// `at`: the photo in the loupe (`None` in the grid), `backward`: stepping back. + pub fn prep_tick(&mut self, mode: Mode, at: Option, backward: bool) { + let settings = self.prep.settings(); + let want = settings.mode(mode); + // the whole view's build follows its own row (Culling, or Library also while editing): its + // switch and its "which photos"; the Editing row's scope is for the photos kept ready ahead + let wanted = want.previews && want.scope != Scope::OnScreen; + // the running build: re-aimed at the user, stopped when switched off + if let Some(b) = self.prep.build.clone() { + if b.running() { + if !wanted { + b.cancel.store(true, Ordering::Relaxed); + } else if self.prep.started_for.is_some_and(|sig| sig != signature(&self.visible_cloned(), self, want.scope)) { + // another view (a folder, a filter, another library): this build's photos are + // not the ones shown; stopped, and the view now shown is prepared in its place + // (not counted as stopped by the user) + b.cancel.store(true, Ordering::Relaxed); + self.prep.started_for = None; + } else if let Some(id) = at { + b.focus_on(id, backward); + } + return; + } + self.prep.build = None; + let mine = self.preview_build.as_ref().is_some_and(|p| Arc::ptr_eq(p, &b)); + if b.cancel.load(Ordering::Relaxed) { + if mine && wanted { + // stopped from its row: not again for this view + self.prep.declined_for = self.prep.started_for; + } else { + // replaced by a build that was asked for, or switched off: may start again later + self.prep.started_for = None; + } + } + } + if !wanted { + return; + } + let Some(at) = at else { return }; + let ids = self.visible_cloned(); + let sig = signature(&ids, self, want.scope); + if self.prep.steps_in != Some(sig) { + self.prep.steps_in = Some(sig); + self.prep.steps = 0; + self.prep.last_at = None; + } + if self.prep.last_at != Some(at) { + self.prep.last_at = Some(at); + self.prep.steps = self.prep.steps.saturating_add(1); + } + let busy = self.preview_build.as_ref().is_some_and(|b| b.running()); + if busy + || self.prep.steps < STEPS_BEFORE_BUILD + || self.prep.started_for == Some(sig) + || self.prep.declined_for == Some(sig) + || self.prep.retry_at.is_some_and(|(view, at)| view == sig && web_time::Instant::now() < at) + || self.library.as_ref().is_none_or(|l| !l.on_disk) + { + return; + } + let ids: Vec = match want.scope { + Scope::Marked => ids.into_iter().filter(|id| marked(self, *id)).map(|id| id.0).collect(), + _ => ids.into_iter().map(|id| id.0).collect(), + }; + self.prep.started_for = Some(sig); + if ids.is_empty() { + return; + } + let p = json!({"ids": ids, "background": true, "from": at.0, "backward": backward}); + // (tests: a start made to fail, as a build thread that can't be spawned fails) + #[cfg(test)] + let fail = self.prep.fail_starts.checked_sub(1).map(|left| self.prep.fail_starts = left).is_some(); + #[cfg(not(test))] + let fail = false; + let started = if fail { + Err(crate::EngineError::Disabled("library.buildPreviews".into(), "test: the build couldn't start".into())) + } else { + self.execute("library.buildPreviews", &p) + }; + match started { + Ok(_) => { + self.prep.build = self.preview_build.clone(); + self.prep.retry_at = None; + } + Err(e) => { + // not started: this view tries again after a while (not on every tick) + self.prep.started_for = None; + self.prep.retry_at = web_time::Instant::now().checked_add(RETRY_AFTER).map(|at| (sig, at)); + log::info!("background preparation: {e}"); + } + } + } + + /// Change the background preparation settings: the app-wide ones, or (`library`) this library's + /// own. Saved at once. + pub fn set_prep_settings(&mut self, settings: PrepSettings, library: bool) -> crate::Result<()> { + let settings = settings.sanitized(); + if library { + let previous = self.prep.library; + self.prep.library = Some(settings); + self.save_library_prep(previous) + } else { + let previous = self.prep.app; + self.prep.app = settings; + let saved = self.save_prefs(); + if saved.is_err() { + self.prep.app = previous; + } + saved + } + } + + /// Back to the app-wide settings for this library. + pub fn clear_library_prep(&mut self) -> crate::Result<()> { + let previous = self.prep.library; + self.prep.library = None; + self.save_library_prep(previous) + } + + /// Save this library's preparation settings; when that fails, `previous` is put back, so the + /// session doesn't go on with settings the command reported as not changed (CodeRabbit on #3544). + fn save_library_prep(&mut self, previous: Option) -> crate::Result<()> { + let saved = self.save_prefs(); + if saved.is_err() { + self.prep.library = previous; + } + saved + } + + pub(crate) fn prep_json(&self) -> Value { + json!({ + "app": self.prep.app, + "library": self.prep.library, + "settings": self.prep.settings(), + "own": self.prep.library.is_some(), + "building": self.prep.build.as_ref().filter(|b| b.running()).map(|b| b.json()), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_patch_changes_only_what_it_names_and_is_kept_in_range() { + let p = PrepSettings::default().patched(&json!({"culling": {"ahead": 99}, "develop": {"scope": "onScreen"}})).unwrap(); + assert_eq!(p.culling.ahead, MAX_AHEAD); + assert_eq!(p.culling.eye_ahead, 8, "untouched"); + assert!(p.library.previews); + assert_eq!(p.develop.scope, Scope::OnScreen); + assert_eq!(p.ahead(Mode::Develop), 0); + assert!(PrepSettings::default().patched(&json!({"culling": {"scope": "sometimes"}})).is_err()); + } + + /// Tests side by side: one test's release doesn't free the build another test holds (CodeRabbit on #3077). + #[test] + fn one_tests_release_does_not_free_another_tests_hold() { + let a = TestHold::new(); + let b = TestHold::new(); + drop(a); + assert!(TEST_HOLD.load(Ordering::Relaxed) > 0 && foreground_busy(), "the other hold still holds"); + drop(b); + } + + #[test] + fn the_photo_on_screen_holds_background_work_back() { + let cancel = AtomicBool::new(false); + foreground(); + assert!(foreground_busy()); + let t = web_time::Instant::now(); + assert!(!wait_for_foreground(&cancel)); + assert!(t.elapsed().as_millis() >= 100, "waited for the foreground to go quiet"); + cancel.store(true, Ordering::Relaxed); + foreground(); + assert!(wait_for_foreground(&cancel), "a cancel ends the wait"); + } +} diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 252dd911a6..b927aa8f31 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -159,6 +159,12 @@ pub struct SidecarData { pub extended_description: Option, pub keywords: Option>, pub regions: Option>, + /// The size the regions were drawn on, when they don't say how the photo was turned + /// ([`lightcraft_meta::XmpData::regions_drawn_on`]), and how the photo's stored pixels turn upright: the + /// sidecar's `tiff:Orientation`, or the file's own Exif orientation where the caller knows it. With both, + /// [`merge_into`] puts boxes drawn on the photo as stored where the upright photo has them (#2674). + pub regions_drawn_on: Option<(f64, f64)>, + pub orientation: Option, /// Capture time (ISO 8601) from `exif:DateTimeOriginal`, `photoshop:DateCreated` or /// `xmp:CreateDate` (first found). Used only when the file itself has no capture time. pub captured: Option, @@ -205,6 +211,9 @@ pub fn parse_sidecar(xmp: &str, target: crate::crs::Target) -> std::result::Resu // `mwg-rs:Regions` byte for byte but never writes one) says nothing about regions, and the // photo's are kept. regions: d.values.contains_key("mwg-rs:Regions").then(|| m.regions.clone()), + regions_drawn_on: d.regions_drawn_on(), + // (only what the regions need: a packet that says nothing else still says nothing) + orientation: d.regions_drawn_on().and(m.orientation), captured: m.capture_time.map(|d| d.to_iso()), ..Default::default() }; @@ -335,6 +344,11 @@ pub fn merge_into(p: &mut Photo, sc: &SidecarData, now: &str) -> bool { } if let Some(r) = &sc.regions { m.regions = r.clone(); + // (the photo's size is the upright one) + if let (Some(drawn_on), Some(o)) = (sc.regions_drawn_on, sc.orientation) { + let stored = if o.swaps_axes() { (p.height, p.width) } else { (p.width, p.height) }; + lightcraft_meta::upright_regions(&mut m.regions, drawn_on, o, stored); + } } let develop = match &sc.develop { Some(DevelopPatch::Full(s)) => (**s).clone(), @@ -364,8 +378,277 @@ impl SidecarData { } self } + + /// Take the orientation of the photo file at `original` (LightCraft shows the photo turned by it, and the packet + /// may not repeat it) when the regions need it: they were drawn on a stated size ([`SidecarData::regions_drawn_on`]). + /// Only then is the file read ([`file_orientation`]). + pub fn with_file_orientation(self, original: &str) -> Self { + if self.regions_drawn_on.is_none() { + return self; + } + SidecarData { orientation: file_orientation(original).or(self.orientation), ..self } + } } +/// The orientation the photo file at `path` states, matching what the import stores on [`crate::media::ProbeInfo`]: +/// for a raw, the decoder's (`lightcraft_raw::probe_info`: CIFF for a CRW, the raw IFD for a MEF, …); otherwise Exif, +/// else XMP, as [`lightcraft_meta::extract`] reads it. A file shorter than [`ORIENTATION_SPAN`] is read whole. Most +/// non-raws state it in the Exif of their first [`ORIENTATION_SPAN`]; when that part doesn't, the Exif may come later +/// ([`late_orientation`]). A WebP's or PNG's chunks are always walked, since the last Exif chunk is the one that counts +/// ([`webp_orientation`], [`png_orientation`]). +fn file_orientation(path: &str) -> Option { + let mut file = std::fs::File::open(path).ok()?; + let mut head = Vec::new(); + (&mut file).take(ORIENTATION_SPAN).read_to_end(&mut head).ok()?; + // Import takes a raw's orientation from the decoder, not from Exif IFD0 / XMP alone. Re-read and sync must do the + // same, or face boxes turned at import are put back and Synchronize Folder reports changes every pass (#2857). + if lightcraft_raw::probe(&head).is_some() { + let bytes = if (head.len() as u64) < ORIENTATION_SPAN { + head + } else { + file.rewind().ok()?; + let mut all = Vec::new(); + file.read_to_end(&mut all).ok()?; + all + }; + return match lightcraft_raw::probe_info(&bytes) { + Ok(raw) => Some(raw.orientation), + // unsupported / preview-only: same fallback the import uses (`ProbeInfo::orientation` from meta) + Err(_) => lightcraft_meta::extract(&bytes).orientation, + }; + } + if (head.len() as u64) < ORIENTATION_SPAN { + return lightcraft_meta::extract(&head).orientation; + } + if head.get(..4) == Some(b"RIFF") && head.get(8..12) == Some(b"WEBP") { + return webp_orientation(&mut file); + } + if head.starts_with(b"\x89PNG\r\n\x1a\n") { + return png_orientation(&mut file); + } + if let Some(o) = exif_orientation(&head) { + return Some(o); + } + late_orientation(&mut file, &head).or_else(|| lightcraft_meta::extract(&head).orientation) +} + +/// The orientation the Exif in `bytes` (a file, or the start of one) states, leaving out a separate XMP packet (the +/// one the Exif holds in tag 700 counts, as in [`lightcraft_meta::read_exif`]). +fn exif_orientation(bytes: &[u8]) -> Option { + lightcraft_meta::embedded(bytes).exif.as_deref().map(lightcraft_meta::read_exif).and_then(|m| m.orientation) +} + +/// The orientation of a JPEG, TIFF or PSD whose `head` has no Exif stating it, found by the file's structure without +/// reading its image data (a JPEG's Exif can follow other long segments, many TIFF writers put the first IFD after the +/// strips, and a PSD's image resources can outgrow `head`). As the import does, a JPEG takes its first Exif segment, +/// else its first XMP segment. +fn late_orientation(file: &mut (impl Read + Seek), head: &[u8]) -> Option { + let len = file.seek(SeekFrom::End(0)).ok()?; + file.rewind().ok()?; + match head.get(..4)? { + [0xff, 0xd8, ..] => { + let (mut exif_seen, mut xmp) = (false, None); + let exif = read_jpeg_app1(file, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS, |segment| { + let embedded = lightcraft_meta::embedded(segment); + if let Some(exif) = embedded.exif + && !exif_seen + { + // the first Exif segment ends the walk if it states one; later ones don't count + exif_seen = true; + return lightcraft_meta::read_exif(&exif).orientation; + } + if xmp.is_none() { + xmp = embedded.xmp.map(|x| lightcraft_meta::parse_xmp(&x).ok().and_then(|x| x.metadata.orientation)); + } + None + }); + exif.or(xmp.flatten()) + } + b"II*\0" | b"MM\0*" => tiff_orientation(file, 0, len), + b"8BPS" => psd_orientation(file), + _ => None, + } +} + +/// A WebP's orientation as the import takes it: from its last `EXIF` chunk, else its last `XMP ` chunk, in whichever +/// order they come. The chunk headers are walked from the start of `file` (at most [`WEBP_CHUNK_STEPS`], ending at a +/// chunk that runs past the end of the file); then only the first IFD of the EXIF chunk is read, whatever its size +/// ([`tiff_orientation`]), and the XMP chunk if it is at most [`ORIENTATION_SPAN`]. +fn webp_orientation(file: &mut (impl Read + Seek)) -> Option { + let len = file.seek(SeekFrom::End(0)).ok()?; + let (mut exif, mut xmp) = (None, None); + let mut at = 12u64; + for _ in 0..WEBP_CHUNK_STEPS { + let mut header = [0; 8]; + if file.seek(SeekFrom::Start(at)).is_err() || file.read_exact(&mut header).is_err() { + break; + } + let [a, b, c, d, s0, s1, s2, s3] = header; + let size = u64::from(u32::from_le_bytes([s0, s1, s2, s3])); + let Some(end) = at.checked_add(8 + size).filter(|&end| end <= len) else { break }; + match &[a, b, c, d] { + b"EXIF" => exif = Some((at + 8, end)), + b"XMP " => xmp = Some((at + 8, size)), + _ => {} + } + // chunks are padded to an even size + at = end + (size & 1); + } + if let Some(o) = exif.and_then(|(start, end)| exif_chunk_orientation(file, start, end)) { + return Some(o); + } + let (start, size) = xmp?; + xmp_orientation(file, start, size) +} + +/// How many chunks [`webp_orientation`] passes over (an animated WebP has one per frame). +const WEBP_CHUNK_STEPS: usize = 4096; + +/// The orientation the Exif chunk from `start` to `end` in `file` states: its TIFF stream comes after an `Exif\0\0` if +/// the chunk starts with one (as `strip_exif_header` takes it). +fn exif_chunk_orientation(file: &mut (impl Read + Seek), start: u64, end: u64) -> Option { + let mut prefix = [0; 5]; + file.seek(SeekFrom::Start(start)).ok()?; + let prefixed = start + 6 <= end && file.read_exact(&mut prefix).is_ok() && &prefix == b"Exif\0"; + tiff_orientation(file, if prefixed { start + 6 } else { start }, end) +} + +/// A PNG's orientation as the import takes it: from its last `eXIf` chunk, else its last uncompressed XMP `iTXt` chunk, +/// wherever they come (a writer may put them after the image data). The chunk headers are walked from the start of +/// `file` to `IEND` (at most [`png_chunk_steps`], ending at a chunk that runs past the end of the file); then only the +/// first IFD of the `eXIf` chunk is read, whatever its size ([`tiff_orientation`]), and the `iTXt` chunk if it is at +/// most [`ORIENTATION_SPAN`]. +fn png_orientation(file: &mut (impl Read + Seek)) -> Option { + let len = file.seek(SeekFrom::End(0)).ok()?; + let (mut exif, mut xmp) = (None, None); + let mut at = 8u64; + for _ in 0..png_chunk_steps(len) { + let (mut header, mut key) = ([0; 8], [0; 19]); + if at + 12 > len || file.seek(SeekFrom::Start(at)).is_err() || file.read_exact(&mut header).is_err() { + break; + } + let [s0, s1, s2, s3, a, b, c, d] = header; + let size = u64::from(u32::from_be_bytes([s0, s1, s2, s3])); + let Some(end) = at.checked_add(8 + size).filter(|&end| end <= len) else { break }; + match &[a, b, c, d] { + b"eXIf" => exif = Some((at + 8, end)), + // the keyword, then compression flag 0 + b"iTXt" if size >= 20 && file.read_exact(&mut key).is_ok() && &key == b"XML:com.adobe.xmp\0\0" => xmp = Some((at + 8, size)), + b"IEND" => break, + _ => {} + } + // past the chunk's CRC + at = end + 4; + } + if let Some(o) = exif.and_then(|(start, end)| exif_chunk_orientation(file, start, end)) { + return Some(o); + } + let (start, size) = xmp?; + let chunk = read_within_span(file, start, size)?; + // keyword\0 compression-flag compression-method language\0 translated\0 text + let text = chunk.get(20..)?.splitn(3, |&c| c == 0).nth(2)?; + lightcraft_meta::parse_xmp(&String::from_utf8_lossy(text)).ok()?.metadata.orientation +} + +/// How many chunks [`png_orientation`] passes over in a file of `len` bytes: 4096 and one per KiB of the file, at most +/// 2^20. Image data is often split into many `IDAT` chunks (libpng writes 8 KiB ones by default), so the limit grows +/// with the file; each chunk costs two system calls, so a short file of empty chunks can't hold a worker for seconds. +fn png_chunk_steps(len: u64) -> u64 { + (4096 + len / 1024).min(1 << 20) +} + +/// A PSD's or PSB's orientation as the import takes it, from its image resources: the file's start up to their end is +/// read if it is at most [`PSD_RESOURCES_SPAN`]. They come before the layers and the image data, after the 26-byte +/// header and the colour-mode data; each of those two sections starts with its length. +fn psd_orientation(file: &mut (impl Read + Seek)) -> Option { + let mut length = [0; 4]; + file.seek(SeekFrom::Start(26)).ok()?; + file.read_exact(&mut length).ok()?; + let resources = 30 + u64::from(u32::from_be_bytes(length)); + file.seek(SeekFrom::Start(resources)).ok()?; + file.read_exact(&mut length).ok()?; + let end = resources + 4 + u64::from(u32::from_be_bytes(length)); + if end > PSD_RESOURCES_SPAN { + return None; + } + file.rewind().ok()?; + let mut bytes = Vec::new(); + (&mut *file).take(end).read_to_end(&mut bytes).ok()?; + lightcraft_meta::extract(&bytes).orientation +} + +/// How far into a PSD or PSB [`psd_orientation`] reads. +const PSD_RESOURCES_SPAN: u64 = 16 * 1024 * 1024; + +/// The orientation the TIFF stream from `start` to `end` in `file` states in its first IFD (a TIFF file, or the Exif +/// block of a WebP's EXIF chunk; its offsets count from `start`, and nothing past `end` is read). Only the IFD's 12-byte +/// entries are read (at most 65535 of them, under 1 MiB): its orientation tag, else (as [`lightcraft_meta::read_exif`] +/// does) the XMP packet its tag 700 holds, read if it is at most [`ORIENTATION_SPAN`]. +fn tiff_orientation(file: &mut (impl Read + Seek), start: u64, end: u64) -> Option { + // where the `len` bytes at `offset` in the stream are in the file, when all of them are in the stream + let within = |offset: u32, len: u64| { + let at = start.checked_add(u64::from(offset))?; + (at.checked_add(len)? <= end).then_some(at) + }; + file.seek(SeekFrom::Start(within(0, 8)?)).ok()?; + let mut header = [0; 8]; + file.read_exact(&mut header).ok()?; + let [b0, b1, b2, b3, i0, i1, i2, i3] = header; + let le = match &[b0, b1, b2, b3] { + b"II*\0" => true, + b"MM\0*" => false, + _ => return None, + }; + let u16_of = |b: [u8; 2]| if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }; + let u32_of = |b: [u8; 4]| if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }; + let ifd = u32_of([i0, i1, i2, i3]); + file.seek(SeekFrom::Start(within(ifd, 2)?)).ok()?; + let mut count = [0; 2]; + file.read_exact(&mut count).ok()?; + let count = u16_of(count); + within(ifd, 2 + 12 * u64::from(count))?; + let mut entries = vec![0; usize::from(count) * 12]; + file.read_exact(&mut entries).ok()?; + let mut xmp = None; + for &[t0, t1, y0, y1, c0, c1, c2, c3, v0, v1, v2, v3] in entries.as_chunks::<12>().0 { + let (tag, kind, count) = (u16_of([t0, t1]), u16_of([y0, y1]), u32_of([c0, c1, c2, c3])); + match (tag, kind) { + // exactly one SHORT (with more, the field also holds a second value, or an offset to them all) + (274, 3) if count == 1 => { + let v = u16_of([v0, v1]); + if (1..=8).contains(&v) { + return Some(lightcraft_meta::Orientation::from_exif(v)); + } + } + // BYTE or UNDEFINED, at an offset (a packet longer than the field's four bytes) + (700, 1 | 7) if count > 4 => xmp = Some((u32_of([v0, v1, v2, v3]), u64::from(count))), + _ => {} + } + } + let (offset, len) = xmp?; + xmp_orientation(file, within(offset, len)?, len) +} + +/// The orientation the XMP packet of `len` bytes at `at` in `file` states, read if it is at most [`ORIENTATION_SPAN`]. +fn xmp_orientation(file: &mut (impl Read + Seek), at: u64, len: u64) -> Option { + let packet = read_within_span(file, at, len)?; + lightcraft_meta::parse_xmp(&String::from_utf8_lossy(&packet)).ok()?.metadata.orientation +} + +/// The `len` bytes at `at` in `file`, read if they are at most [`ORIENTATION_SPAN`]. +fn read_within_span(file: &mut (impl Read + Seek), at: u64, len: u64) -> Option> { + if len > ORIENTATION_SPAN { + return None; + } + file.seek(SeekFrom::Start(at)).ok()?; + let mut bytes = Vec::new(); + (&mut *file).take(len).read_to_end(&mut bytes).ok()?; + Some(bytes) +} + +/// How much of a photo file [`file_orientation`] reads first. +const ORIENTATION_SPAN: u64 = 1 << 20; + /// The sidecar packet for a photo; the colour label is written by its name in `cat` (custom /// label names included, as other editors do). pub fn sidecar_packet(p: &Photo, cat: &lightcraft_catalog::Catalog) -> String { @@ -580,6 +863,11 @@ const JPEG_XMP_HEADER_STEPS: usize = 4096; /// consumes one iteration. Only a complete APP1 payload (at most 65533 bytes) reaches the shared /// parser, in a single SOI+APP1 wrapper (at most 65539 bytes). This does not validate the whole JPEG. fn read_jpeg_xmp(reader: &mut (impl Read + Seek), header_span: u64, marker_steps: usize) -> Option { + read_jpeg_app1(reader, header_span, marker_steps, |segment| lightcraft_meta::jpeg_segments(segment).xmp) +} + +/// Like [`read_jpeg_xmp`], stopping at the first APP1 segment (in its SOI+APP1 wrapper) that `pick` finds something in. +fn read_jpeg_app1(reader: &mut (impl Read + Seek), header_span: u64, marker_steps: usize, mut pick: impl FnMut(&[u8]) -> Option) -> Option { let mut header = reader.take(header_span); let mut soi = [0; 2]; header.read_exact(&mut soi).ok()?; @@ -620,8 +908,8 @@ fn read_jpeg_xmp(reader: &mut (impl Read + Seek), header_span: u64, marker_steps segment.extend_from_slice(&[0xff, 0xd8, 0xff, 0xe1, hi, lo]); segment.resize(segment_len, 0); header.read_exact(segment.get_mut(6..)?).ok()?; - if let Some(xmp) = lightcraft_meta::jpeg_segments(&segment).xmp { - return Some(xmp); + if let Some(found) = pick(&segment) { + return Some(found); } } None @@ -883,6 +1171,7 @@ impl Session { let Some(orig) = file_path(p) else { return Ok(None) }; let Some((packet, from)) = read_packet(orig, p.kind, self.sidecar_lookup(id)) else { return Ok(None) }; let sc = parse_sidecar(&packet, crate::crs::Target::for_photo(p)).map_err(|e| EngineError::Other(format!("{}: {e}", from.display())))?; + let sc = sc.with_file_orientation(orig); let mut warnings = sc.warnings.clone(); for warning in &mut warnings { warning.path = orig.to_string(); @@ -994,6 +1283,291 @@ impl Session { #[cfg(test)] mod tests { + /// Issue #2674: a WebP keeps its EXIF and XMP chunks after the image data, a TIFF's first IFD can follow its strips + /// and a JPEG's Exif other long segments, so the orientation can be past the first [`super::ORIENTATION_SPAN`] of + /// the file. Every file gives what the import gives reading it whole: Exif over XMP wherever each is, a WebP's last + /// EXIF chunk and a JPEG's first Exif segment, and none for a file that states none. + #[test] + fn the_file_orientation_is_found_after_the_image_data() { + let dir = std::env::temp_dir().join(format!("lightcraft-file-orientation-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { + orientation: Some(lightcraft_meta::Orientation::Rotate90), + ..Default::default() + }); + let span = super::ORIENTATION_SPAN as usize; + let (o6, o8) = (Some(lightcraft_meta::Orientation::Rotate90), Some(lightcraft_meta::Orientation::Rotate270)); + // a WebP: VP8X, then `chunks` + let webp = |chunks: &[(&[u8], Vec)]| { + let mut w = b"RIFF\0\0\0\0WEBP".to_vec(); + for (id, data) in [(&b"VP8X"[..], vec![0; 10])].iter().chain(chunks) { + w.extend_from_slice(id); + w.extend_from_slice(&(data.len() as u32).to_le_bytes()); + w.extend_from_slice(data); + if data.len() % 2 == 1 { + w.push(0); + } + } + w + }; + let image = |len: usize| (&b"VP8L"[..], vec![0; len]); + let exif_chunk = (&b"EXIF"[..], [&b"Exif\0\0"[..], &exif].concat()); + // an EXIF chunk over the span (orientation 6 too), one stating no orientation, and an XMP packet stating 8 + let huge_exif = (&b"EXIF"[..], [&b"Exif\0\0"[..], &exif, &vec![0; span]].concat()); + let plain = lightcraft_meta::write_exif(&lightcraft_meta::Metadata::default()); + let plain_chunk = (&b"EXIF"[..], [&b"Exif\0\0"[..], &plain].concat()); + let packet = lightcraft_meta::write_xmp(&lightcraft_meta::Metadata { orientation: o8, ..Default::default() }, None); + let xmp_chunk = (&b"XMP "[..], packet.clone().into_bytes()); + // the XMP packet padded with whitespace to `len` bytes + let padded_xmp = |len: usize| { + let mut p = packet.clone().into_bytes(); + p.resize(len, b' '); + (&b"XMP "[..], p) + }; + // an EXIF chunk holding only a TIFF header, whose IFD offset (16) points past the chunk's end into the next + // chunk's data, where an IFD stating orientation 6 sits + let stray_exif = (&b"EXIF"[..], b"II*\0\x10\0\0\0".to_vec()); + let stray_ifd = (&b"JUNK"[..], vec![1, 0, 0x12, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0]); + // a TIFF whose first IFD follows more than the first MiB of image data: an orientation tag of `values` values + // whose field starts with `value` (with more than two, it is an offset), a tag pointing elsewhere, and an XMP + // packet (tag 700) stored after the IFD + let tiff = |le: bool, orientation: Option<(u32, u16)>, xmp: Option<&str>| { + let (u16_of, u32_of): (fn(u16) -> [u8; 2], fn(u32) -> [u8; 4]) = + if le { (u16::to_le_bytes, u32::to_le_bytes) } else { (u16::to_be_bytes, u32::to_be_bytes) }; + let strips = span + 64; + let mut entries = Vec::new(); + if let Some((values, value)) = orientation { + entries.push((274u16, 3u16, values, [u16_of(value), [0, 0]].concat())); + } + entries.push((305, 2, 64, u32_of(4).to_vec())); + let packet_at = 8 + strips + 2 + 12 * (entries.len() + usize::from(xmp.is_some())) + 4; + if let Some(x) = xmp { + entries.push((700, 7, x.len() as u32, u32_of(packet_at as u32).to_vec())); + } + let mut t = if le { b"II*\0".to_vec() } else { b"MM\0*".to_vec() }; + t.extend_from_slice(&u32_of(8 + strips as u32)); + t.resize(8 + strips, 0); + t.extend_from_slice(&u16_of(entries.len() as u16)); + for (tag, kind, count, value) in entries { + t.extend_from_slice(&u16_of(tag)); + t.extend_from_slice(&u16_of(kind)); + t.extend_from_slice(&u32_of(count)); + t.extend_from_slice(&value); + } + t.extend_from_slice(&[0; 4]); + t.extend_from_slice(xmp.unwrap_or_default().as_bytes()); + t + }; + // a JPEG: the APP1 payloads `early`, more than the first MiB of other segments, `late`, the image data + let jpeg = |early: &[Vec], late: &[Vec]| { + let app1 = |j: &mut Vec, payload: &Vec| { + j.extend_from_slice(&[0xff, 0xe1]); + j.extend_from_slice(&(payload.len() as u16 + 2).to_be_bytes()); + j.extend_from_slice(payload); + }; + let mut j = vec![0xff, 0xd8]; + early.iter().for_each(|p| app1(&mut j, p)); + for _ in 0..17 { + j.extend_from_slice(&[0xff, 0xef, 0xff, 0xff]); + j.resize(j.len() + 0xfffd, 0); + } + late.iter().for_each(|p| app1(&mut j, p)); + j.extend_from_slice(&[0xff, 0xda, 0, 2, 0xff, 0xd9]); + j + }; + let exif_app1 = [&b"Exif\0\0"[..], &exif].concat(); + let plain_app1 = [&b"Exif\0\0"[..], &plain].concat(); + let xmp_app1 = [&b"http://ns.adobe.com/xap/1.0/\0"[..], packet.as_bytes()].concat(); + for (name, bytes, want) in [ + ("small.webp", webp(&[image(64), exif_chunk.clone()]), o6), + ("large.webp", webp(&[image(span + 64), exif_chunk.clone(), xmp_chunk.clone()]), o6), + // EXIF wins in whichever order the chunks come, and an XMP in the first MiB doesn't stop the search + ("reversed.webp", webp(&[image(span + 64), xmp_chunk.clone(), exif_chunk.clone()]), o6), + ("xmp-first.webp", webp(&[xmp_chunk.clone(), image(span + 64), exif_chunk.clone()]), o6), + ("none.webp", webp(&[image(span + 64), exif_chunk.clone()])[..span + 100].to_vec(), None), + ("xmp.webp", webp(&[image(span + 64), xmp_chunk.clone()]), o8), + // an EXIF chunk of any size is read by its IFD: one over the span, one (without `Exif\0\0`, big-endian) + // whose IFD is more than the span into it + ("huge.webp", webp(&[image(span + 64), huge_exif, xmp_chunk.clone()]), o6), + ("late-ifd.webp", webp(&[image(span + 64), (&b"EXIF"[..], tiff(false, Some((1, 6)), None)), xmp_chunk.clone()]), o6), + // nothing outside the EXIF chunk is read for its IFD + ("outside.webp", webp(&[image(span + 64), stray_exif, stray_ifd, xmp_chunk.clone()]), o8), + // the last EXIF chunk counts, here a late one stating no orientation after one in the first MiB + ("last-exif.webp", webp(&[exif_chunk, image(span + 64), plain_chunk, xmp_chunk]), o8), + // an XMP chunk of the span is read + ("span-xmp.webp", webp(&[image(64), padded_xmp(span)]), o8), + ("le.tif", tiff(true, Some((1, 8)), None), o8), + ("be.tif", tiff(false, Some((1, 8)), None), o8), + ("offset.tif", tiff(true, Some((3, 8)), None), None), + // the tag wins over the IFD's XMP; XMP fills in for no tag or an invalid one + ("both.tif", tiff(true, Some((1, 6)), Some(&packet)), o6), + ("xmp.tif", tiff(false, None, Some(&packet)), o8), + ("invalid.tif", tiff(true, Some((1, 0)), Some(&packet)), o8), + ("none.jpg", jpeg(&[], &[]), None), + ("xmp-first.jpg", jpeg(std::slice::from_ref(&xmp_app1), std::slice::from_ref(&exif_app1)), o6), + ("xmp-only.jpg", jpeg(&[], std::slice::from_ref(&xmp_app1)), o8), + // the first Exif segment counts, though it states no orientation + ("two-exif.jpg", jpeg(&[plain_app1], &[exif_app1, xmp_app1]), o8), + ] { + assert_eq!(lightcraft_meta::extract(&bytes).orientation, want, "import: {name}"); + let path = dir.join(name); + std::fs::write(&path, bytes).unwrap(); + assert_eq!(super::file_orientation(&path.to_string_lossy()), want, "{name}"); + } + // a larger XMP chunk isn't read, where the import (reading the whole file) takes its orientation + let over = webp(&[image(64), padded_xmp(span + 1)]); + assert_eq!(lightcraft_meta::extract(&over).orientation, o8); + std::fs::write(dir.join("over-xmp.webp"), over).unwrap(); + assert_eq!(super::file_orientation(&dir.join("over-xmp.webp").to_string_lossy()), None); + assert_eq!(super::file_orientation(&dir.join("missing.webp").to_string_lossy()), None); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// Issue #2674: the same for a PNG, whose `eXIf` and XMP `iTXt` chunks can follow the image data, and a PSD, whose + /// image resources can outgrow the first [`super::ORIENTATION_SPAN`]. + #[test] + fn a_png_or_psd_gives_the_orientation_the_import_gives() { + let dir = std::env::temp_dir().join(format!("lightcraft-png-psd-orientation-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let span = super::ORIENTATION_SPAN as usize; + let (o6, o8) = (Some(lightcraft_meta::Orientation::Rotate90), Some(lightcraft_meta::Orientation::Rotate270)); + let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { orientation: o6, ..Default::default() }); + let plain = lightcraft_meta::write_exif(&lightcraft_meta::Metadata::default()); + let packet = lightcraft_meta::write_xmp(&lightcraft_meta::Metadata { orientation: o8, ..Default::default() }, None); + // a PNG: its IHDR, then `chunks`, each with a CRC (nothing checks it) + let png = |chunks: &[(&[u8], Vec)]| { + let mut p = b"\x89PNG\r\n\x1a\n".to_vec(); + for (id, data) in [(&b"IHDR"[..], vec![0; 13])].iter().chain(chunks) { + p.extend_from_slice(&(data.len() as u32).to_be_bytes()); + p.extend_from_slice(id); + p.extend_from_slice(data); + p.extend_from_slice(&[0; 4]); + } + p + }; + let idat = |len: usize| (&b"IDAT"[..], vec![0; len]); + let iend = (&b"IEND"[..], Vec::new()); + let exif_chunk = (&b"eXIf"[..], exif.clone()); + let plain_chunk = (&b"eXIf"[..], plain.clone()); + // an `iTXt` chunk: the keyword, compression flag `flag`, method, no language, no translated keyword, the text + let itxt = |keyword: &[u8], flag: u8, text: &[u8]| (&b"iTXt"[..], [keyword, &[0, flag, 0, 0, 0], text].concat()); + let xmp_key = &b"XML:com.adobe.xmp"[..]; + let xmp_chunk = itxt(xmp_key, 0, packet.as_bytes()); + // the XMP packet padded with whitespace, in a chunk of `len` bytes + let padded_xmp = |len: usize| { + let mut p = packet.clone().into_bytes(); + p.resize(len - 22, b' '); + itxt(xmp_key, 0, &p) + }; + // a big-endian TIFF stream whose IFD, stating orientation 6, is more than the span into it + let ifd = [0u8, 1, 1, 0x12, 0, 3, 0, 0, 0, 1, 0, 6, 0, 0, 0, 0, 0, 0]; + let late_ifd = [&b"MM\0*"[..], &(8 + span as u32).to_be_bytes(), &vec![0; span], &ifd].concat(); + // an `eXIf` holding only a TIFF header, whose IFD offset (20) points past the chunk's end into the next chunk's + // data, where an IFD stating orientation 6 sits + let stray_exif = (&b"eXIf"[..], b"II*\0\x14\0\0\0".to_vec()); + let stray_ifd = (&b"juNK"[..], vec![1, 0, 0x12, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0]); + // a PSD: its header, `colour` bytes of colour-mode data, the image resources (id, data), `pixels` other bytes + let psd = |colour: usize, resources: &[(u16, &[u8])], pixels: usize| { + let mut section = Vec::new(); + for (id, data) in resources { + section.extend_from_slice(b"8BIM"); + section.extend_from_slice(&id.to_be_bytes()); + section.extend_from_slice(&[0, 0]); + section.extend_from_slice(&(data.len() as u32).to_be_bytes()); + section.extend_from_slice(data); + if data.len() % 2 == 1 { + section.push(0); + } + } + let mut p = b"8BPS\0\x01".to_vec(); + p.resize(26, 0); + p.extend_from_slice(&(colour as u32).to_be_bytes()); + p.resize(p.len() + colour, 0); + p.extend_from_slice(&(section.len() as u32).to_be_bytes()); + p.extend_from_slice(§ion); + p.resize(p.len() + pixels, 0); + p + }; + let long = vec![0; span + 64]; + let (exif_res, plain_res, xmp_res, long_res) = ((1058, &exif[..]), (1058, &plain[..]), (1060, packet.as_bytes()), (1039, &long[..])); + let late_png = png(&[idat(span + 64), exif_chunk.clone()]); + let late_psd = psd(0, &[long_res, exif_res], 0); + for (name, bytes, want) in [ + ("early.png", png(&[exif_chunk.clone(), idat(span + 64), iend.clone()]), o6), + ("late.png", png(&[idat(span + 64), exif_chunk.clone(), xmp_chunk.clone(), iend.clone()]), o6), + // the `eXIf` wins in whichever order the chunks come, and an XMP in the first MiB doesn't stop the search + ("reversed.png", png(&[idat(span + 64), xmp_chunk.clone(), exif_chunk.clone(), iend.clone()]), o6), + ("xmp-first.png", png(&[xmp_chunk.clone(), idat(span + 64), exif_chunk.clone(), iend.clone()]), o6), + ("xmp.png", png(&[idat(span + 64), xmp_chunk.clone(), iend.clone()]), o8), + ("none.png", png(&[idat(span + 64), iend.clone()]), None), + // the `eXIf` is cut short, or comes after the end of the image + ("cut.png", late_png[..late_png.len() - 6].to_vec(), None), + ("after-iend.png", png(&[idat(span + 64), iend.clone(), exif_chunk.clone()]), None), + // an `eXIf` of any size is read by its IFD: with `Exif\0\0`, over the span, and with its IFD past the span + ("prefixed.png", png(&[idat(span + 64), (&b"eXIf"[..], [&b"Exif\0\0"[..], &exif].concat())]), o6), + ("huge.png", png(&[idat(64), (&b"eXIf"[..], [&exif[..], &vec![0; span]].concat()), xmp_chunk.clone()]), o6), + ("late-ifd.png", png(&[idat(span + 64), (&b"eXIf"[..], late_ifd), xmp_chunk.clone()]), o6), + // nothing outside the `eXIf` is read for its IFD + ("outside.png", png(&[idat(span + 64), stray_exif, stray_ifd, xmp_chunk.clone()]), o8), + // the last `eXIf` counts, here a late one stating no orientation after one in the first MiB + ("last-exif.png", png(&[exif_chunk.clone(), idat(span + 64), plain_chunk, xmp_chunk.clone()]), o8), + // a compressed packet or another keyword isn't the XMP; a chunk of the span is read + ("compressed.png", png(&[idat(span + 64), xmp_chunk.clone(), itxt(xmp_key, 1, packet.as_bytes())]), o8), + ("only-compressed.png", png(&[idat(span + 64), itxt(xmp_key, 1, packet.as_bytes())]), None), + ("other-text.png", png(&[idat(span + 64), itxt(b"Comment", 0, packet.as_bytes())]), None), + ("short-text.png", png(&[idat(span + 64), xmp_chunk.clone(), (&b"iTXt"[..], b"XML:com.adobe.xmp\0\0".to_vec())]), o8), + ("span-xmp.png", png(&[idat(64), padded_xmp(span)]), o8), + ("late.psd", late_psd.clone(), o6), + ("early.psd", psd(0, &[exif_res], span + 64), o6), + // Exif wins in whichever order the resources come; XMP fills in for none, or none stating an orientation + ("both.psd", psd(0, &[xmp_res, long_res, exif_res], 0), o6), + ("xmp.psd", psd(768, &[long_res, xmp_res], 0), o8), + ("plain.psd", psd(0, &[long_res, plain_res, xmp_res], 0), o8), + ("none.psd", psd(0, &[long_res], span), None), + // as at import, nothing is taken from resources that are cut short or state their Exif twice + ("cut.psd", late_psd[..late_psd.len() - 1].to_vec(), None), + ("two-exif.psd", psd(0, &[long_res, exif_res, exif_res], 0), None), + ] { + assert_eq!(lightcraft_meta::extract(&bytes).orientation, want, "import: {name}"); + let path = dir.join(name); + std::fs::write(&path, bytes).unwrap(); + assert_eq!(super::file_orientation(&path.to_string_lossy()), want, "{name}"); + } + // a larger XMP chunk isn't read, where the import (reading the whole file) takes its orientation + let over = png(&[idat(64), padded_xmp(span + 1)]); + assert_eq!(lightcraft_meta::extract(&over).orientation, o8); + std::fs::write(dir.join("over-xmp.png"), over).unwrap(); + assert_eq!(super::file_orientation(&dir.join("over-xmp.png").to_string_lossy()), None); + std::fs::remove_dir_all(dir).unwrap(); + + // the `eXIf` as the last chunk walked, and as the first one not: IHDR, `chunks` of empty `IDAT`, the `eXIf` + let steps = super::png_chunk_steps; + let split = |chunks: usize| png(&[vec![idat(0); chunks], vec![exif_chunk.clone()]].concat()); + let len = |chunks: usize| (8 + 25 + 12 * chunks + 12 + exif.len()) as u64; + let walked = (0..).find(|&n| n as u64 + 2 == steps(len(n)) && n as u64 + 3 > steps(len(n + 1))).unwrap(); + let (last, past) = (split(walked), split(walked + 1)); + assert_eq!(last.len() as u64, len(walked)); + assert_eq!(super::png_orientation(&mut std::io::Cursor::new(&last)), o6); + assert_eq!(lightcraft_meta::extract(&past).orientation, o6); + assert_eq!(super::png_orientation(&mut std::io::Cursor::new(&past)), None); + // image data split into chunks of a KiB is walked whatever its length, up to the limit + let kib_chunks = png(&[vec![idat(1012); 6000], vec![exif_chunk.clone()]].concat()); + assert_eq!(super::png_orientation(&mut std::io::Cursor::new(&kib_chunks)), o6); + assert_eq!(steps(u64::MAX), 1 << 20); + + // image resources that end exactly at the limit, and a byte past it + let limit = super::PSD_RESOURCES_SPAN as usize; + let padding = vec![0; limit - 58 - exif.len().next_multiple_of(2)]; + let within = psd(0, &[(1039, &padding[..]), exif_res], 0); + assert_eq!(within.len(), limit); + assert_eq!(super::psd_orientation(&mut std::io::Cursor::new(&within)), o6); + let past = psd(1, &[(1039, &padding[..]), exif_res], 0); + assert_eq!(lightcraft_meta::extract(&past).orientation, o6); + assert_eq!(super::psd_orientation(&mut std::io::Cursor::new(&past)), None); + } + #[test] fn sidecars_are_written_only_beside_an_existing_original() { let dir = std::env::temp_dir().join(format!("lightcraft-sidecar-local-{}", std::process::id())); diff --git a/crates/engine/src/smart.rs b/crates/engine/src/smart.rs index 77f78bd299..b44d1f35a1 100644 --- a/crates/engine/src/smart.rs +++ b/crates/engine/src/smart.rs @@ -503,6 +503,7 @@ pub fn load(path: &Path) -> Result { camera_tone, denoised: None, camera_profile: None, + outliers: false, from_proxy: true, reduced: false, }) diff --git a/crates/engine/src/sync.rs b/crates/engine/src/sync.rs index 9bbbcbec18..6b09ed09f5 100644 --- a/crates/engine/src/sync.rs +++ b/crates/engine/src/sync.rs @@ -620,7 +620,7 @@ fn sidecar_has_news(labels: &Catalog, p: &Photo, naming: SidecarLookup, listing: } let Ok(text) = std::fs::read_to_string(&file) else { return false }; let Ok(sc) = crate::sidecar::parse_sidecar(&text, crate::crs::Target::for_photo(p)) else { return false }; - let sc = sc.resolve_label(labels); + let sc = sc.with_file_orientation(path).resolve_label(labels); let mut q = p.clone(); crate::sidecar::merge_into(&mut q, &sc, ""); (q.rating, q.flag, q.label, &q.meta, &q.captured, &q.develop) != (p.rating, p.flag, p.label, &p.meta, &p.captured, &p.develop) @@ -803,7 +803,7 @@ fn read_sidecar(path: &str, naming: SidecarLookup, target: crate::crs::Target) - return Err(format!("{}: too large for an XMP sidecar", file.display())); } let text = std::fs::read_to_string(&file).map_err(|e| format!("{}: {e}", file.display()))?; - crate::sidecar::parse_sidecar(&text, target).map_err(|e| format!("{}: {e}", file.display())) + crate::sidecar::parse_sidecar(&text, target).map(|sc| sc.with_file_orientation(path)).map_err(|e| format!("{}: {e}", file.display())) } impl SyncCommit { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a22547ec4a..03592df41b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -44,6 +44,7 @@ mod organize; mod persist; mod prefs; mod presets_scale; +mod preview_prep; mod print; mod process; mod recheck; @@ -1040,6 +1041,48 @@ fn auto_sync_carries_only_the_changed_settings() { assert_eq!(s.develop_of(PhotoId(ids[1])).unwrap().light.exposure, 0.7); } +#[test] +fn auto_sync_carries_remove_hot_pixels_off() { + use lightcraft_catalog::PhotoId; + let mut s = demo(); + let ids: Vec = s.catalog.photos().take(2).map(|p| p.id).collect(); + for id in &ids { + let mut d = (*s.develop_of(*id).unwrap()).clone(); + d.detail.nr_outliers = true; + s.set_develop(*id, d, "Setup").unwrap(); + } + s.execute("library.select", &json!({"ids": [ids[0].0, ids[1].0], "active": ids[0].0})).unwrap(); + s.execute("develop.autoSync", &json!({"on": true})).unwrap(); + // off is omitted from the stored JSON: switching it off is still a change Auto Sync carries + let mut d = (*s.develop_of(ids[0]).unwrap()).clone(); + d.detail.nr_outliers = false; + s.set_develop(ids[0], d, "Remove Hot Pixels").unwrap(); + assert!(!s.develop_of(ids[1]).unwrap().detail.nr_outliers); +} + +#[test] +fn the_hot_pixel_limit_renders_afresh_only_the_photos_that_remove_hot_pixels() { + use lightcraft_catalog::PhotoId; + let mut s = demo(); + let ids: Vec = s.catalog.photos().take(2).map(|p| p.id).collect(); + let mut d = (*s.develop_of(ids[0]).unwrap()).clone(); + d.detail.nr_outliers = true; + s.set_develop(ids[0], d, "Setup").unwrap(); + let keys = |s: &mut crate::Session| ids.iter().map(|id| s.thumb_job(*id, 256).unwrap().cache.unwrap().1).collect::>(); + let before = keys(&mut s); + assert_eq!(s.execute("app.hotPixelLimit", &json!({})).unwrap()["default"], 0.2); + assert!(s.execute("app.hotPixelLimit", &json!({"percent": 0})).is_err()); + assert!(s.execute("app.hotPixelLimit", &json!({"percent": "1"})).is_err()); + let r = s.execute("app.hotPixelLimit", &json!({"percent": 1.5})); + let after = keys(&mut s); + // (process-wide: back to the default before anything can fail) + s.execute("app.hotPixelLimit", &json!({"percent": 0.2f32})).unwrap(); + assert_eq!(r.unwrap()["percent"], 1.5); + assert_ne!(after[0], before[0], "a photo that removes hot pixels renders with the new limit"); + assert_eq!(after[1], before[1], "the other photo's thumbnail stays valid"); + assert_eq!(keys(&mut s), before, "the default limit keeps the keys it always had"); +} + #[test] fn auto_sync_camera_local_tone_off_preserves_other_settings() { use lightcraft_catalog::PhotoId; diff --git a/crates/engine/src/tests/denoise.rs b/crates/engine/src/tests/denoise.rs index bf0ae3a713..9003d878d1 100644 --- a/crates/engine/src/tests/denoise.rs +++ b/crates/engine/src/tests/denoise.rs @@ -108,7 +108,8 @@ fn model_installation_keeps_the_frame_pump_responsive_and_reuses_the_loaded_mode // The loader is blocked: the frame pump must still return, reporting installation in progress. let state = x.s.execute("denoise.models.downloads", &json!({})).unwrap(); assert_eq!(state["downloads"][0]["state"], "installing"); - assert_eq!(x.s.execute("denoise.pump", &json!({"pace": "pause"})).unwrap()["active"], false); + // the built-in denoiser is in use meanwhile + assert_eq!(x.s.execute("denoise.status", &json!({})).unwrap()["model"]["id"], "builtin"); assert!(x.s.execute("denoise.models.install", &json!({"path": path, "acknowledged": true, "background": true})).is_err()); release_tx.send(()).unwrap(); for _ in 0..600 { @@ -226,13 +227,13 @@ fn a_model_is_installed_chosen_and_removed_with_the_terms_accepted() { // it can be checked again, switched off and on, and removed assert_eq!(x.s.execute("denoise.models.test", &json!({"id": "stand-in"})).unwrap()["ok"], true); assert_eq!(x.s.execute("denoise.models.select", &json!({"id": null})).unwrap()["model"], Value::Null); - assert!(x.s.denoise.active.is_none()); + assert_eq!(x.s.denoise.active.as_ref().map(|a| a.id.as_str()), Some("builtin"), "without a model the built-in denoiser runs"); assert!(x.s.execute("denoise.models.select", &json!({"id": "nothing"})).is_err()); x.s.execute("denoise.models.select", &json!({"id": "stand-in"})).unwrap(); assert!(x.s.denoise.active.is_some()); let r = x.s.execute("denoise.models.remove", &json!({"id": "stand-in"})).unwrap(); assert_eq!(r["model"], Value::Null); - assert!(x.s.denoise.active.is_none()); + assert_eq!(x.s.denoise.active.as_ref().map(|a| a.id.as_str()), Some("builtin")); assert!(!x.dir.join("denoise-models").join("stand-in").exists()); // ids that are not folder names, and folders that are not models, are never touched for bad in ["../library", "", "a/b", "settings.json"] { @@ -407,10 +408,13 @@ fn an_export_makes_its_picture_when_the_queue_has_not_and_never_comes_out_withou x.s.denoise_pump(crate::denoise::Pace::Pause); assert_eq!(x.s.denoise_photo_state(id), PhotoState::Ready); - // no model: the export says so instead of leaving the denoise out + // no model: the built-in denoiser makes the picture instead (the stand-in is not asked) x.s.execute("denoise.models.select", &json!({"id": null})).unwrap(); - let e = export_photo(&mut x.s, id, &o, 1).err().unwrap(); - assert!(e.contains("no denoise model is chosen") && e.contains("ramp.dng"), "{e}"); + let runs = x.runs.load(Ordering::Relaxed); + let builtin = decode(&export_photo(&mut x.s, id, &o, 1).unwrap().bytes); + assert_eq!(x.runs.load(Ordering::Relaxed), runs); + assert!(builtin.is_finite()); + assert_eq!(std::fs::read_dir(x.dir.join("library").join("denoise")).unwrap().flatten().count(), 2, "its picture is its own"); set_amount(&mut x.s, 0.0); assert!(export_photo(&mut x.s, id, &o, 1).is_ok(), "without an amount nothing is asked of the model"); let _ = std::fs::remove_dir_all(&x.dir); @@ -478,14 +482,13 @@ fn only_raw_photos_on_disk_are_denoised_and_nothing_is_queued_without_a_model() let id = demo.active().unwrap(); assert_eq!(demo.denoise_photo_state(id), PhotoState::NotApplicable, "a generated photo has no sensor data"); let e = demo.execute("denoise.queue", &json!({})).unwrap_err().to_string(); - assert!(e.contains("no denoise model is chosen"), "{e}"); + assert!(e.contains("open a library on disk first"), "no model is needed, a place for the pictures is: {e}"); // no models folder at all (the web build): the commands say so, nothing panics let mut web = Session::with_demo(); for cmd in ["denoise.models.install", "denoise.models.select", "denoise.models.remove", "denoise.settings"] { assert!(web.execute(cmd, &json!({"path": "x", "acknowledged": true, "id": "x"})).is_err(), "{cmd}"); } - assert_eq!(web.execute("denoise.pump", &json!({})).unwrap()["active"], false); - assert_eq!(web.execute("denoise.status", &json!({})).unwrap()["enabled"], false); + assert_eq!(web.execute("denoise.status", &json!({})).unwrap()["model"]["id"], "builtin"); // no library open: nowhere to keep pictures, and the queue says so let x = setup("eligible2", true); let mut bare = Session::new().with_fs(); @@ -797,8 +800,6 @@ fn the_denoise_switch_validates_arguments_and_accepts_explicit_targets_without_s for params in [json!({"id": "bad"}), json!({"id": u64::MAX}), json!({"id": id.0, "enabled": "yes"})] { assert!(x.s.execute("denoise.toggle", ¶ms).is_err()); } - assert!(x.s.execute("denoise.toggle", &json!({"id": id.0, "enabled": true})).is_err()); - assert_eq!(x.s.develop_of(id).unwrap().enhance.denoise, 0.0); let model = model_files(&x.dir, "toggle-model"); x.s.execute("denoise.models.install", &json!({"path": model.to_string_lossy(), "acknowledged": true})).unwrap(); x.s.selection = Default::default(); @@ -859,3 +860,50 @@ fn denoise_row_while_queue_is_busy() { assert!(rows(&x.s).is_empty(), "the row goes once the photo is made"); let _ = std::fs::remove_dir_all(&x.dir); } + +/// With no model installed, turning denoise on makes the picture with the built-in denoiser alone; it is not an +/// installed model, and no model can take its id. +#[test] +fn without_a_model_the_built_in_denoiser_makes_the_picture_by_itself() { + let mut x = setup("builtin", false); + let id = photo(&x.s); + assert!(x.s.denoise.active.is_none(), "nothing is looked at before it is needed"); + let r = x.s.execute("denoise.toggle", &json!({"id": id.0, "enabled": true})).unwrap(); + assert_eq!(r["amount"], 50.0); + assert_eq!(x.s.denoise.active.as_ref().map(|a| a.id.as_str()), Some("builtin")); + let r = pump_until_ready(&mut x.s, 1); + assert_eq!(r["queued"], 0, "{r}"); + assert_eq!(x.s.denoise_photo_state(id), PhotoState::Ready); + assert_eq!(x.runs.load(Ordering::Relaxed), 0, "no model was involved"); + assert_eq!(x.s.execute("denoise.status", &json!({})).unwrap()["model"]["name"], "Built-in"); + assert!(x.s.execute("denoise.models.test", &json!({"id": "builtin"})).is_err(), "it is not an installed model"); + // a model cannot take its id + let onnx = model_files(&x.dir, "builtin"); + let e = x.s.execute("denoise.models.install", &json!({"path": onnx.to_string_lossy(), "acknowledged": true})).unwrap_err().to_string(); + assert!(e.contains("builtin"), "{e}"); + let _ = std::fs::remove_dir_all(&x.dir); +} + +/// A build with no models folder still makes products with the built-in denoiser, so its cache obeys the default limit. +#[test] +fn without_a_models_folder_the_cache_still_obeys_the_default_limit() { + let mut x = setup("builtin-evict", false); + x.s.execute("denoise.toggle", &json!({"id": photo(&x.s).0, "enabled": true})).unwrap(); + pump_until_ready(&mut x.s, 1); + x.s.set_denoise_models_dir(None); + let limit = u64::from(crate::denoise::DEFAULT_CACHE_GB) << 30; + assert_eq!(x.s.denoise_cache_limit(), limit); + // sparse files are cheap on Unix only: elsewhere a file that size may reserve its space + #[cfg(unix)] + { + let stray = x.dir.join("library").join("denoise").join("aaaa.lcdn"); + let f = std::fs::File::create(&stray).unwrap(); + f.set_len(limit + 1).unwrap(); + f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(1000)).unwrap(); + drop(f); + x.s.denoise_evict(None); + assert!(!stray.exists(), "the stray picture goes"); + assert_eq!(x.s.denoise_photo_state(photo(&x.s)), PhotoState::Ready, "the photo's own picture stays"); + } + let _ = std::fs::remove_dir_all(&x.dir); +} diff --git a/crates/engine/src/tests/face_tiles.rs b/crates/engine/src/tests/face_tiles.rs index b166dcd859..d3b50aefc4 100644 --- a/crates/engine/src/tests/face_tiles.rs +++ b/crates/engine/src/tests/face_tiles.rs @@ -91,7 +91,7 @@ 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, dcp: Option<&crate::media::DcpProfile>| { + s.media.file_loader = Some(Arc::new(move |p: &str, e: usize, dcp: crate::media::RawDecode<'_>| { n.fetch_add(1, Ordering::SeqCst); file(p, e, dcp) })); diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index e87e2883d2..87fcba4486 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -303,6 +303,149 @@ fn browsing_a_folder_lists_its_photos_without_adding_them() { let _ = std::fs::remove_dir_all(&dir); } +/// PERF-CULL-1: the Local view reads only what the library lacks, newest file first for the default +/// (newest capture first) sort, so the first screen is read first; other sorts follow their key. +#[test] +fn browsing_queues_unknown_files_in_the_order_the_view_shows_them() { + use lightcraft_catalog::{Sort, SortKey}; + let dir = temp_dir("browse-order"); + let set_time = |p: &Path, secs: u64| { + let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs); + std::fs::File::options().write(true).open(p).unwrap().set_modified(t).unwrap(); + }; + for (name, seed, secs) in [("a.png", 1u8, 300u64), ("b.png", 2, 100), ("c.png", 3, 200)] { + write_png(&dir.join(name), seed); + set_time(&dir.join(name), 1_700_000_000 + secs); + } + let mut s = Session::new().with_fs(); + let known = dir.join("b.png").to_string_lossy().to_string(); + s.execute("library.import", &json!({"paths": [known.clone()]})).unwrap(); + let files: Vec = ["a.png", "b.png", "c.png", "gone.png"].iter().map(|n| dir.join(n).to_string_lossy().to_string()).collect(); + let (input, _) = crate::import::ScanInput::new(&mut s, &[]); + let names = |v: Vec| v.iter().map(|f| Path::new(f).file_name().unwrap().to_string_lossy().to_string()).collect::>(); + // newest first, the file already in the library left out, an unreadable one last + let q = crate::import::browse_queue(&input, files.clone(), &Sort::default()); + assert_eq!(names(q), ["a.png", "c.png", "gone.png"]); + let q = crate::import::browse_queue(&input, files.clone(), &Sort { ascending: true, ..Sort::default() }); + assert_eq!(names(q), ["c.png", "a.png", "gone.png"]); + let q = crate::import::browse_queue(&input, files.clone(), &Sort { key: SortKey::FileName, ascending: false, ..Sort::default() }); + assert_eq!(names(q), ["gone.png", "c.png", "a.png"]); + // by size an unreadable file is last in both directions (it was sized 0, first when ascending) + for ascending in [true, false] { + let q = crate::import::browse_queue(&input, files.clone(), &Sort { key: SortKey::FileSize, ascending, ..Sort::default() }); + assert_eq!(names(q).last().map(String::as_str), Some("gone.png"), "ascending {ascending}"); + } + let q = crate::import::browse_queue(&input, files, &Sort { key: SortKey::Rating, ..Sort::default() }); + assert_eq!(names(q), ["gone.png", "c.png", "a.png"], "new photos tie on rating: by name, descending as the view"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Choosing another folder while a browse orders its files (`cancel` set) stops the ordering: no queue comes +/// back, and nothing more is read (CodeRabbit on #3055). Browsing hands back the probes of earlier scans it took. +#[test] +fn a_cancelled_browse_stops_ordering_and_keeps_earlier_probes() { + use lightcraft_catalog::{Sort, SortKey}; + use std::sync::atomic::AtomicBool; + let dir = temp_dir("browse-cancel"); + write_png(&dir.join("a.png"), 1); + write_png(&dir.join("b.png"), 2); + let files: Vec = ["a.png", "b.png"].iter().map(|n| dir.join(n).to_string_lossy().to_string()).collect(); + let mut s = Session::new().with_fs(); + s.import_probes.insert(files[0].clone(), crate::media::ProbeInfo { file_size: 1, ..Default::default() }); + let (mut input, _) = crate::import::ScanInput::new(&mut s, &[]); + for key in [SortKey::CaptureDate, SortKey::FileSize, SortKey::FileName, SortKey::Random] { + let sort = Sort { key, ..Sort::default() }; + assert_eq!(crate::import::browse_queue_until(&input, files.clone(), &sort, &AtomicBool::new(true)), None, "{key:?}"); + assert_eq!(crate::import::browse_queue_until(&input, files.clone(), &sort, &AtomicBool::new(false)).map(|q| q.len()), Some(2), "{key:?}"); + } + let probes = input.take_probes(); + assert!(probes.contains_key(&files[0]), "the earlier scan's probe comes back"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Browsing a folder with its subfolders lists nothing inside the library's own folder (the +/// import that follows would read it as photos), as the import's scan skips it. +#[test] +fn browsing_with_subfolders_skips_the_librarys_own_folder() { + let dir = temp_dir("browse-skip-lib"); + std::fs::create_dir_all(dir.join("lib")).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(dir.join("lib"), false).unwrap(); + write_png(&dir.join("a.png"), 1); + write_png(&dir.join("lib").join("inside.png"), 2); + let (input, _) = crate::import::ScanInput::new(&mut s, &[]); + let root = dir.to_string_lossy().to_string(); + let names = |v: Vec| v.iter().map(|f| Path::new(f).file_name().unwrap().to_string_lossy().to_string()).collect::>(); + assert_eq!(names(crate::import::browse_files(&input, &root, true).unwrap()), ["a.png"]); + assert_eq!(names(crate::import::browse_files(&input, &root, false).unwrap()), ["a.png"]); + // the library's folder chosen itself, with or without its subfolders + let lib = dir.join("lib").to_string_lossy().to_string(); + assert!(crate::import::browse_files(&input, &lib, false).unwrap().is_empty()); + assert!(crate::import::browse_files(&input, &lib, true).unwrap().is_empty()); + // the library's folder by another name: through `..`, or a symlink to it + std::fs::create_dir_all(dir.join("other")).unwrap(); + let around = dir.join("other").join("..").join("lib").to_string_lossy().to_string(); + assert!(crate::import::browse_files(&input, &around, false).unwrap().is_empty(), "{around}"); + assert!(crate::import::browse_files(&input, &around, true).unwrap().is_empty(), "{around}"); + #[cfg(unix)] + { + let alias = dir.join("alias"); + std::os::unix::fs::symlink(dir.join("lib"), &alias).unwrap(); + let alias = alias.to_string_lossy().to_string(); + assert!(crate::import::browse_files(&input, &alias, false).unwrap().is_empty(), "{alias}"); + assert!(crate::import::browse_files(&input, &alias, true).unwrap().is_empty(), "{alias}"); + } + // a folder next to the library named through it is outside it: browsed (CodeRabbit on #3077) + std::fs::create_dir_all(dir.join("outside")).unwrap(); + write_png(&dir.join("outside").join("next.png"), 3); + let next = dir.join("lib").join("..").join("outside").to_string_lossy().to_string(); + assert_eq!(names(crate::import::browse_files(&input, &next, false).unwrap()), ["next.png"], "{next}"); + assert_eq!(names(crate::import::browse_files(&input, &next, true).unwrap()), ["next.png"], "{next}"); + // under the folder's one spelling: the paths match the folder's own, so the catalog's records are found + // (CodeRabbit on #3055) + let direct = dir.join("outside").to_string_lossy().to_string(); + for sub in [false, true] { + assert_eq!(crate::import::browse_files(&input, &next, sub).unwrap(), crate::import::browse_files(&input, &direct, sub).unwrap()); + } + // a folder inside the library that isn't there is an error too, not an empty folder + let gone = dir.join("lib").join("not-there").to_string_lossy().to_string(); + assert!(crate::import::browse_files(&input, &gone, false).is_err(), "{gone}"); + // a folder that can't be listed is an error, not an empty folder (its photos aren't "gone") + let missing = dir.join("not-there").to_string_lossy().to_string(); + assert!(crate::import::browse_files(&input, &missing, false).is_err()); + assert!(crate::import::browse_files(&input, &missing, true).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Browsing's queue breaks ties the way the catalog does (by name, in the view's direction), and +/// the import- and edit-date sorts, where new photos tie, go by name rather than file time. +#[test] +fn browsing_breaks_ties_by_name_in_the_views_direction() { + use lightcraft_catalog::{Sort, SortKey}; + let dir = temp_dir("browse-ties"); + // names and file times run in opposite directions; x and y share a time and a size + for (name, secs) in [("x.png", 100u64), ("y.png", 100), ("z.png", 50)] { + write_png(&dir.join(name), 7); + let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000 + secs); + std::fs::File::options().write(true).open(dir.join(name)).unwrap().set_modified(t).unwrap(); + } + let files: Vec = ["y.png", "z.png", "x.png"].iter().map(|n| dir.join(n).to_string_lossy().to_string()).collect(); + let order = |key: SortKey, ascending: bool| { + let mut f = files.clone(); + crate::import::browse_order(&mut f, &Sort { key, ascending, ..Sort::default() }); + f.iter().map(|f| Path::new(f).file_name().unwrap().to_string_lossy().to_string()).collect::>() + }; + assert_eq!(order(SortKey::CaptureDate, false), ["y.png", "x.png", "z.png"]); + assert_eq!(order(SortKey::CaptureDate, true), ["z.png", "x.png", "y.png"]); + for key in [SortKey::ImportDate, SortKey::EditDate, SortKey::Rating] { + assert_eq!(order(key, true), ["x.png", "y.png", "z.png"], "{key:?}"); + assert_eq!(order(key, false), ["z.png", "y.png", "x.png"], "{key:?}"); + } + assert_eq!(order(SortKey::FileSize, true), ["x.png", "y.png", "z.png"]); + assert_eq!(order(SortKey::FileSize, false), ["z.png", "y.png", "x.png"]); + let _ = std::fs::remove_dir_all(&dir); +} + /// Photos a.png, b.png, c.png imported from `old`, then: a renamed into `moved`; b renamed, with /// an impostor (same name and size, other bytes) under its old name; c gone, with two impostors. fn renamed_and_ambiguous_scene(tag: &str) -> (std::path::PathBuf, Session) { @@ -2851,3 +2994,69 @@ fn heic_exif_orientation_does_not_rotate_the_picture_twice() { } } } + +/// A folder's one spelling: `.` is the current folder, `.` and `..` are taken out, never above the +/// root (CodeRabbit on #3055 / #3080). +#[test] +fn a_browsed_folder_has_one_spelling() { + use crate::import::browse_path; + let root = std::env::temp_dir(); + assert_eq!(browse_path(&root.join("lib").join("..").join("outside")).unwrap(), root.join("outside")); + assert_eq!(browse_path(&root.join(".").join("a").join(".").join("b")).unwrap(), root.join("a").join("b")); + let top: PathBuf = root.ancestors().last().map(Path::to_path_buf).unwrap_or_default(); + assert_eq!(browse_path(&top.join("..").join("x")).unwrap(), top.join("x"), "never above the root"); + assert_eq!(browse_path(Path::new(".")).unwrap(), std::env::current_dir().unwrap(), "`.` is the current folder"); + assert_eq!(browse_path(Path::new("a/..")).unwrap(), std::env::current_dir().unwrap()); + // the UI's spelling, without the disk: the same where no link comes before a `..` + let by_name = crate::import::browse_spelling(&root.join("lib").join("..").join("outside")).unwrap(); + assert_eq!(by_name, root.join("outside")); + assert_eq!(crate::import::browse_spelling(Path::new(".")).unwrap(), std::env::current_dir().unwrap()); +} + +/// `link/..` is the folder the system reads (POSIX: above where the link points; Windows: the +/// folder holding the link): browsing it lists what the system lists there (CodeRabbit on #3055 / +/// #3077 / #3080). +#[test] +fn a_link_before_dotdot_names_the_folder_the_system_reads() { + let dir = temp_dir("browse-link-dotdot"); + std::fs::create_dir_all(dir.join("real").join("sub")).unwrap(); + write_png(&dir.join("real").join("in-real.png"), 1); + write_png(&dir.join("beside-link.png"), 2); + let link = dir.join("link"); + #[cfg(unix)] + let made = std::os::unix::fs::symlink(dir.join("real").join("sub"), &link); + #[cfg(windows)] + let made = std::os::windows::fs::symlink_dir(dir.join("real").join("sub"), &link); + if let Err(e) = made { + lightcraft_testkit::skip!(System, "can't make a folder link here: {e}"); + let _ = std::fs::remove_dir_all(&dir); + return; + } + let mut s = Session::new().with_fs(); + let (input, _) = crate::import::ScanInput::new(&mut s, &[]); + let through = link.join(".."); + let names = |v: Vec| v.iter().map(|f| Path::new(f).file_name().unwrap().to_string_lossy().to_string()).collect::>(); + let listed = names(crate::import::browse_files(&input, &through.to_string_lossy(), false).unwrap()); + let mut system: Vec = + std::fs::read_dir(&through).unwrap().flatten().map(|e| e.file_name().to_string_lossy().to_string()).filter(|n| n.ends_with(".png")).collect(); + system.sort(); + assert_eq!(listed, system, "{}", through.display()); + #[cfg(unix)] + assert_eq!(listed, ["in-real.png"]); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A broken link before `..` is an error, not the link's own folder by name: the system can't read +/// `broken/..` either (CodeRabbit on #3577). +#[cfg(unix)] +#[test] +fn a_broken_link_before_dotdot_is_an_error() { + let dir = temp_dir("browse-broken-link-dotdot"); + std::fs::create_dir_all(&dir).unwrap(); + let link = dir.join("broken"); + std::os::unix::fs::symlink(dir.join("nowhere"), &link).unwrap(); + assert!(crate::import::browse_path(&link.join("..")).is_err()); + // without reading the disk the spelling is still the folder by name + assert_eq!(crate::import::browse_spelling(&link.join("..")).unwrap(), dir); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/tests/lens_refresh.rs b/crates/engine/src/tests/lens_refresh.rs index 7678c93a3d..d3bf3a3574 100644 --- a/crates/engine/src/tests/lens_refresh.rs +++ b/crates/engine/src/tests/lens_refresh.rs @@ -237,7 +237,7 @@ fn a_new_database_profile_changes_the_render_and_cache_keys() { let render = s.render_job(id, 800, 600, false, true).unwrap().key; let thumb = s.thumb_job(id, 256).unwrap().cache.unwrap().1; let p = s.catalog.photo(id).unwrap().clone(); - (render, thumb, Session::variant_key(&p, &p.develop, 128, 0), Session::view_key(&p, true, 0)) + (render, thumb, Session::variant_key(&p, &p.develop, 128, 0), s.view_key(&p, true)) }; let before = keys(&mut s); s.catalog.apply(Op::SetEmbeddedLens { id, lens: Some(Box::new(lens(-0.03))) }).unwrap(); diff --git a/crates/engine/src/tests/preview_prep.rs b/crates/engine/src/tests/preview_prep.rs new file mode 100644 index 0000000000..0981c2cf96 --- /dev/null +++ b/crates/engine/src/tests/preview_prep.rs @@ -0,0 +1,635 @@ +//! Previews are made once and used (notes 47–49): the loupe shows a built or prepared preview +//! instead of rendering the photo again, a build skips photos whose previews are there, built +//! previews are on disk when the build says it is done, the import's queue shows one row, and the +//! background preparation follows the user and gives way to a build that was asked for. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::Ordering; + +use lightcraft_catalog::PhotoId; +use serde_json::json; + +use crate::Session; +use crate::media::QuickSource; + +fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lc-preview-prep-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn png(p: &Path, seed: u8) { + let img = lightcraft_raster::Rgba8::from_fn(600, 400, |x, y| [(x % 251) as u8, (y % 241) as u8, seed, 255]); + let b = + crate::export::encode_image(&img, &crate::export::ExportOptions { format: crate::export::ExportFormat::Png, ..Default::default() }).unwrap(); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, b).unwrap(); +} + +/// A library on disk with `n` photos (600 × 400 PNGs) imported, in name order. +fn library(tag: &str, n: usize) -> (Session, PathBuf, Vec) { + let root = temp_dir(tag); + let paths: Vec = (0..n) + .map(|i| { + let p = root.join("shoot").join(format!("p{i:02}.png")); + png(&p, (i * 20) as u8); + p.to_string_lossy().to_string() + }) + .collect(); + let mut s = Session::new().with_fs(); + s.open_library(root.join("lib"), false).unwrap(); + s.execute("library.import", &json!({"paths": paths})).unwrap(); + let mut ids: Vec<(String, PhotoId)> = s.catalog.photos().map(|p| (p.file_name.clone(), p.id)).collect(); + ids.sort(); + (s, root, ids.into_iter().map(|(_, id)| id).collect()) +} + +fn ids_json(ids: &[PhotoId]) -> Vec { + ids.iter().map(|i| i.0).collect() +} + +/// FredApps on #3077: building previews (asked for, and the background preparation while culling) +/// writes only into the library's own cache, never next to the photos: the shoot folder holds the +/// same files afterwards, byte for byte. +#[test] +fn building_previews_writes_nothing_next_to_the_photos() { + let (mut s, root, ids) = library("prep-beside", 4); + let shoot = root.join("shoot"); + let listing = |dir: &std::path::Path| { + let mut v: Vec<(String, Vec)> = std::fs::read_dir(dir) + .unwrap() + .map(|e| e.unwrap().path()) + .map(|p| (p.file_name().unwrap().to_string_lossy().to_string(), std::fs::read(&p).unwrap())) + .collect(); + v.sort(); + v + }; + let before = listing(&shoot); + assert_eq!(before.len(), 4); + let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap(); + assert_eq!(r["done"], 4, "{r}"); + for id in &ids { + s.prep_tick(crate::prep::Mode::Library, Some(*id), false); + } + if let Some(b) = s.preview_build.clone() { + assert!(wait_finished(&b), "the background build stops (a late write would slip past the check)"); + } + assert_eq!(listing(&shoot), before, "nothing was written next to the photos"); + let _ = std::fs::remove_dir_all(&root); +} + +/// Note 47: a built preview at least as big as the loupe's size is what the loupe shows (fitted +/// down, no render); a smaller one is not (the photo renders). +#[test] +fn the_loupe_uses_a_built_preview_that_is_big_enough() { + let mut s = Session::with_demo(); + let id = s.active().unwrap(); + s.execute("library.buildPreviews", &json!({"ids": [id.0], "edge": 512, "wait": true})).unwrap(); + let r = s.loupe_job(id, 300, 300, true).unwrap().run(); + assert_eq!(r.quick, Some(QuickSource::Cached), "taken from the built preview"); + let img = r.rendered.unwrap().image; + assert_eq!(img.width.max(img.height), 300, "fitted to the loupe's size"); + // bigger than what was built: rendered + let r = s.loupe_job(id, 900, 900, true).unwrap().run(); + assert_eq!(r.quick, None, "a preview too small for the loupe is not used"); + assert!(r.rendered.is_ok()); + // a draft (a slider held) never comes from the cache + let r = s.loupe_job(id, 300, 300, true).unwrap().draft().run(); + assert_eq!(r.quick, None); +} + +/// Shrinking a cached view keeps its colour (an average of the pixels it covers) and its aspect, +/// and refuses to enlarge. +#[test] +fn a_cached_view_is_fitted_down_never_up() { + let img = lightcraft_raster::Rgba8::from_fn(400, 200, |x, _| if x % 2 == 0 { [200, 100, 0, 255] } else { [100, 50, 0, 255] }); + let f = crate::media::fit_cached(&img, 100, 100).unwrap(); + assert_eq!((f.width, f.height), (100, 50)); + assert!(f.data.iter().all(|p| p[0] == 150 && p[1] == 75), "averaged"); + assert!(crate::media::fit_cached(&img, 800, 800).is_none(), "never enlarged"); + assert_eq!(crate::media::fit_cached(&img, 401, 999).map(|f| f.width), Some(400), "a pixel short is the same size"); + assert!(crate::media::fit_cached(&img, 0, 10).is_none()); +} + +/// Note 47: the rendered previews in memory follow the memory budget (they were capped at +/// 128 MB, about 84 loupe renders, whatever the budget). +#[test] +fn the_memory_for_rendered_previews_grows_with_the_budget() { + let share = crate::memory::cache_share(20 << 30); + assert!(crate::media::rendered_budget(share) >= 2 << 30, "a 20 GB budget keeps gigabytes of previews"); + assert_eq!(crate::media::rendered_budget(256 << 20), 128 << 20, "a small budget keeps the old floor where it can"); + assert!(crate::media::rendered_budget(64 << 20) <= 32 << 20, "and never more than the share allows"); +} + +/// Note 47: the disk cache's default room grows with the library, so a wedding's previews are not +/// pruned while they are built (the fixed 2 GB held about 2 000 standard previews). +#[test] +fn the_disk_cache_default_grows_with_the_library() { + assert_eq!(crate::media::default_disk_cache_bytes(10), crate::media::DISK_CACHE_BYTES); + assert!(crate::media::default_disk_cache_bytes(4000) >= 4000 * (1 << 20)); + let (mut s, root, ids) = library("diskroom", 2); + assert_eq!(s.cache_bytes(), crate::media::DISK_CACHE_BYTES); + s.cache_mb = 700; + assert_eq!(s.cache_bytes(), 700 << 20, "a size the user chose is kept"); + assert_eq!(ids.len(), 2); + let _ = std::fs::remove_dir_all(root); +} + +/// Notes 47 and 49: a build skips photos whose previews are there (built before, or by the loupe), +/// renders those whose preview is too small, and its previews are on disk when it is done (they +/// were left to a writer that skips writes when it falls behind). +#[test] +fn a_build_skips_what_is_there_and_leaves_it_on_disk() { + let (mut s, root, ids) = library("skip", 4); + let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap(); + assert_eq!((r["done"].as_u64(), r["skipped"].as_u64(), r["failed"].as_u64()), (Some(4), Some(0), Some(0)), "{r}"); + // on disk now (no waiting for a writer), at the size built + for id in &ids { + let p = s.catalog.photo(*id).unwrap().clone(); + let key = s.view_key(&p, true); + let disk = s.media.rendered.disk().expect("a library has a disk cache"); + let (w, h) = disk.dims(key).expect("the view preview is on disk"); + assert_eq!(w.max(h), 300); + } + // again: nothing is rendered + let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap(); + assert_eq!((r["done"].as_u64(), r["skipped"].as_u64()), (Some(4), Some(4)), "{r}"); + // forced, or bigger: rendered + let r = s.execute("library.buildPreviews", &json!({"ids": [ids[0].0], "edge": 300, "wait": true, "force": true})).unwrap(); + assert_eq!(r["skipped"], 0, "{r}"); + let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 500, "wait": true})).unwrap(); + assert_eq!(r["skipped"], 0, "too small for what is asked: built again {r}"); + // a library opened again finds them on disk (memory is empty) + drop(s); + let mut s = Session::new().with_fs(); + s.open_library(root.join("lib"), false).unwrap(); + let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 500, "wait": true})).unwrap(); + assert_eq!(r["skipped"], 4, "{r}"); + let r = s.loupe_job(ids[1], 400, 400, true).unwrap().run(); + assert_eq!(r.quick, Some(QuickSource::Cached), "the loupe uses the preview built in the last session"); + let _ = std::fs::remove_dir_all(root); +} + +/// A forced build renders the grid thumbnail again too, not the one its cache holds (CodeRabbit on #3577: +/// the thumbnail job read its cache first, so `force` rebuilt only the view). +#[test] +fn a_forced_build_renders_the_thumbnail_again() { + let (mut s, root, ids) = library("force-thumb", 1); + let build = |s: &mut Session, force: bool| { + s.execute("library.buildPreviews", &json!({"ids": [ids[0].0], "edge": 300, "wait": true, "force": force})).unwrap() + }; + build(&mut s, false); + let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300)); + let thumb = jobs.iter().find(|j| j.view_cache.is_none() && j.cache.is_some()).expect("a thumbnail job"); + let ((cache, key), generation) = (thumb.cache.clone().unwrap(), thumb.cache_generation); + let stand_in = lightcraft_raster::Rgba8 { width: 1, height: 1, data: vec![[1, 2, 3, 255]] }; + assert!(cache.put_at(generation, key, std::sync::Arc::new(stand_in))); + let r = build(&mut s, false); + assert_eq!(r["skipped"], 1, "{r}"); + assert_eq!(cache.get_at(generation, key).map(|i| i.width), Some(1), "unforced: kept"); + let r = build(&mut s, true); + assert_eq!(r["failed"], 0, "{r}"); + assert!(cache.get_at(generation, key).is_some_and(|i| i.width > 1), "forced: rendered again"); + let _ = std::fs::remove_dir_all(root); +} + +/// Note 47: standard previews are built at least as big as the loupe on this screen asks for. +#[test] +fn standard_previews_are_as_big_as_the_loupe() { + let mut s = Session::with_demo(); + assert_eq!(crate::cmd::previews::standard_edge(&s), crate::cmd::previews::STANDARD_EDGE); + s.loupe_edge = 3000; + assert_eq!(crate::cmd::previews::standard_edge(&s), 3000); + s.loupe_edge = 1200; + assert_eq!(crate::cmd::previews::standard_edge(&s), crate::cmd::previews::STANDARD_EDGE); +} + +/// Note 48: a background build goes from where the user is, in the direction they step, and +/// follows them when they jump. +#[test] +fn the_background_build_starts_where_the_user_is() { + use crate::cmd::previews::PreviewBuild; + let b = PreviewBuild { order: (10..20).collect(), ..Default::default() }; + let mut queue: Vec> = (10..20).map(Some).collect(); + b.focus_on(PhotoId(14), false); + let mut took = Vec::new(); + for _ in 0..3 { + let i = b.next_index(&queue).unwrap(); + took.push(queue[i].take().unwrap()); + } + assert_eq!(took, vec![14, 15, 16], "forward from the photo on screen"); + b.focus_on(PhotoId(12), true); + let i = b.next_index(&queue).unwrap(); + assert_eq!(queue[i], Some(12), "jumped back: from there, backwards"); + queue[i] = None; + assert_eq!(b.next_index(&queue).map(|i| queue[i]), Some(Some(11))); + // the end reached: the rest the other way + b.focus_on(PhotoId(19), false); + for _ in 0..6 { + let i = b.next_index(&queue).unwrap(); + queue[i] = None; + } + assert!(b.next_index(&queue).is_none(), "all taken"); +} + +/// Note 49: the background preparation gives way to a build that is asked for (no error, no +/// two builds), and is not started again for a view the user stopped it in. +#[test] +fn a_build_asked_for_replaces_the_background_one() { + let (mut s, root, ids) = library("replace", 3); + // held back: the photo on screen is being made all along (held until released below, not for a + // deadline a slow test machine could pass before the build asked for comes) + let hold = crate::prep::TestHold::new(); + s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "background": true})).unwrap(); + let bg = s.preview_build.clone().unwrap(); + assert!(bg.background && bg.running()); + assert!(s.activity.list().iter().any(|t| t.label == "Preparing photos in the background"), "{:?}", s.activity.list()); + // a second background build is refused; one that is asked for replaces it + assert!(s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "background": true})).is_err()); + let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap(); + assert_eq!(r["done"], 3, "{r}"); + assert!(bg.cancel.load(Ordering::Relaxed), "the background build was stopped"); + drop(hold); + // its workers stop before their library is removed under them + assert!(wait_finished(&bg), "a cancelled build stops"); + drop(s); + std::fs::remove_dir_all(&root).unwrap(); +} + +/// Note 48: the background preparation starts once the user steps through photos in the loupe +/// (not when a library opens), builds the view's previews in one cancellable row, and a stop +/// from that row holds for the view. +#[test] +fn the_background_preparation_starts_when_culling_and_can_be_stopped() { + let (mut s, root, ids) = library("prep", 4); + let mode = crate::prep::Mode::Library; + s.prep_tick(mode, None, false); + s.prep_tick(mode, Some(ids[0]), false); + assert!(s.preview_build.is_none(), "opening and looking at one photo starts nothing"); + s.prep_tick(mode, Some(ids[1]), false); + s.prep_tick(mode, Some(ids[2]), false); + let b = s.preview_build.clone().expect("culling: the view is prepared"); + assert!(b.background); + assert_eq!(b.total, 4); + for _ in 0..600 { + s.prep_tick(mode, Some(ids[2]), false); + if !b.running() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + assert!(!b.running(), "built"); + assert_eq!(b.done.load(Ordering::Relaxed), 4); + s.prep_tick(mode, Some(ids[3]), false); + assert!(same_build(&s, &b), "not started again for the same view"); + // switched off: nothing starts in a new view either + s.execute("prefs.setBackgroundPrep", &json!({"settings": {"library": {"previews": false}}})).unwrap(); + let off = s.execute("prefs.backgroundPrep", &json!({})).unwrap(); + assert_eq!(off["settings"]["library"]["previews"], false, "{off}"); + assert_eq!(off["settings"]["culling"]["previews"], true, "each mode has its own"); + let _ = std::fs::remove_dir_all(root); +} + +/// While editing, the whole view's build follows the Library row (its switch and "which photos"); +/// the Editing row's scope is only for the photos kept ready ahead. +#[test] +fn editing_builds_the_view_by_the_library_rows_scope() { + let (mut s, root, ids) = library("prep-develop", 4); + s.execute("prefs.setBackgroundPrep", &json!({"settings": {"develop": {"scope": "onScreen"}, "library": {"scope": "marked"}}})).unwrap(); + s.execute("photo.rate", &json!({"ids": [ids[1].0], "rating": 3})).unwrap(); + let mode = crate::prep::Mode::Develop; + for id in &ids { + s.prep_tick(mode, Some(*id), false); + } + let b = s.preview_build.clone().expect("the Library row asks for the view while editing"); + assert_eq!(b.total, 1, "only the marked photos, as the Library row says"); + b.cancel.store(true, Ordering::Relaxed); + // its workers stop before their library is removed under them + assert!(wait_finished(&b), "a cancelled build stops"); + drop(s); + std::fs::remove_dir_all(&root).unwrap(); +} + +/// With "which photos" = marked, marking another photo changes what the view's build prepares: a +/// build for the newly marked set follows (it wasn't, as the view itself stayed the same). +#[test] +fn marking_a_photo_prepares_it_in_the_marked_scope() { + let (mut s, root, ids) = library("prep-marked", 4); + s.execute("prefs.setBackgroundPrep", &json!({"settings": {"library": {"scope": "marked"}}})).unwrap(); + s.execute("photo.rate", &json!({"ids": [ids[1].0], "rating": 3})).unwrap(); + let mode = crate::prep::Mode::Library; + let tick = |s: &mut Session, k: usize| s.prep_tick(mode, Some(ids[k % 3]), false); + for k in 0..3 { + tick(&mut s, k); + } + let first = s.preview_build.clone().expect("the marked photos are prepared"); + assert_eq!(first.total, 1); + s.execute("photo.rate", &json!({"ids": [ids[3].0], "rating": 2})).unwrap(); + let mut next = None; + for k in 0..600 { + tick(&mut s, k); + if let Some(b) = s.preview_build.clone().filter(|b| !std::sync::Arc::ptr_eq(b, &first)) { + next = Some(b); + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + let next = next.expect("a build for the newly marked set"); + assert_eq!(next.total, 2); + next.cancel.store(true, Ordering::Relaxed); + // both builds' workers stop before their library is removed under them + for b in [&first, &next] { + assert!(wait_finished(b), "a cancelled build stops"); + } + drop(s); + std::fs::remove_dir_all(&root).unwrap(); +} + +/// Waits (up to 30 s) for a build's workers to finish. +fn wait_finished(b: &crate::cmd::previews::PreviewBuild) -> bool { + for _ in 0..1500 { + if b.finished.load(Ordering::Relaxed) { + return true; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + false +} + +/// A background build started for one view is stopped when another view is shown (here the +/// library changes under it), not left building photos no longer shown; it doesn't count as +/// stopped by the user, so the view now shown is prepared. +#[test] +fn a_view_change_stops_the_background_build_for_the_old_view() { + let (mut s, root, ids) = library("prep-view", 6); + let mode = crate::prep::Mode::Library; + // the build's lanes wait at their foreground check until released below + let hold = crate::prep::TestHold::new(); + for id in &ids[..3] { + s.prep_tick(mode, Some(*id), false); + } + let b = s.preview_build.clone().expect("the view is prepared"); + assert!(b.running()); + s.catalog.apply(lightcraft_catalog::Op::RemovePhoto { id: ids[5] }).unwrap(); + s.prep_tick(mode, Some(ids[2]), false); + let stopped = b.cancel.load(Ordering::Relaxed); + drop(hold); + assert!(stopped, "the old view's build is stopped"); + // the user steps on in the view now shown + for k in 0..600 { + s.prep_tick(mode, Some(ids[k % 3]), false); + if s.preview_build.as_ref().is_some_and(|p| !std::sync::Arc::ptr_eq(p, &b)) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + let next = s.preview_build.clone().expect("a build for the view now shown"); + assert!(!std::sync::Arc::ptr_eq(&next, &b)); + assert_eq!(next.total, 5); + next.cancel.store(true, Ordering::Relaxed); + // both builds' workers stop before their library is removed under them + for b in [&b, &next] { + assert!(wait_finished(b), "a cancelled build stops"); + } + drop(s); + std::fs::remove_dir_all(&root).unwrap(); +} + +fn same_build(s: &Session, b: &std::sync::Arc) -> bool { + s.preview_build.as_ref().is_some_and(|p| std::sync::Arc::ptr_eq(p, b)) +} + +/// Note 48: a library keeps its own background settings (a timelapse library prepares nothing), +/// saved with it; the app-wide ones apply elsewhere. +#[test] +fn a_library_can_keep_its_own_background_settings() { + let (mut s, root, _ids) = library("own", 1); + let r = s.execute("prefs.setBackgroundPrep", &json!({"library": true, "settings": {"culling": {"previews": false, "ahead": 0}}})).unwrap(); + assert_eq!(r["own"], true, "{r}"); + assert_eq!(r["settings"]["culling"]["ahead"], 0); + assert_eq!(r["app"]["culling"]["ahead"], 5, "the app-wide ones are unchanged"); + drop(s); + let mut s = Session::new().with_fs(); + s.open_library(root.join("lib"), false).unwrap(); + assert_eq!(s.prep_settings().culling.ahead, 0, "kept with the library"); + assert_eq!(s.prep_settings().ahead(crate::prep::Mode::Culling), 0); + s.execute("prefs.setBackgroundPrep", &json!({"reset": true})).unwrap(); + assert_eq!(s.prep_settings().culling.ahead, 5, "back to the app-wide settings"); + assert!(s.execute("prefs.setBackgroundPrep", &json!({"settings": 3})).is_err()); + let _ = std::fs::remove_dir_all(root); +} + +/// Note 47: Build Previews with one photo open (selected) builds every photo in view, as its menu +/// item says ("Visible"); it built only the open photo, so culling after it found nothing built. +#[test] +fn build_previews_with_one_photo_open_builds_the_view() { + let mut s = Session::with_demo(); + let n = s.visible_cloned().len(); + assert!(n > 2); + let one = s.visible_cloned()[0]; + s.selection = crate::Selection::single(one); + let r = s.execute("library.buildPreviews", &json!({"edge": 256, "wait": true})).unwrap(); + assert_eq!(r["total"], n, "{r}"); + let two: Vec = s.visible_cloned().into_iter().take(2).collect(); + s.selection = crate::Selection { ids: two.clone(), active: two.first().copied() }; + let r = s.execute("library.buildPreviews", &json!({"edge": 256, "wait": true})).unwrap(); + assert_eq!(r["total"], 2, "a choice of photos is built alone {r}"); +} + +/// A view the loupe kept only in memory (its deferred disk write skipped when the writer fell behind) is not +/// counted as built: the build renders it and writes it to disk (CodeRabbit on #3077). +#[test] +fn a_preview_kept_only_in_memory_is_built_and_written() { + let (mut s, root, ids) = library("memonly", 1); + let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300)); + assert!(!jobs.is_empty()); + for j in &jobs { + let img = std::sync::Arc::new(lightcraft_raster::Rgba8::new(300, 200)); + if let Some((cache, key)) = &j.view_cache { + cache.put_memory(*key, img); + } else if let Some((cache, key)) = &j.cache { + cache.put_memory(*key, img); + } + } + assert!(!crate::cmd::previews::already_built(&jobs), "a copy only in memory is not a built preview"); + let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap(); + assert_eq!((r["skipped"].as_u64(), r["failed"].as_u64()), (Some(0), Some(0)), "{r}"); + let p = s.catalog.photo(ids[0]).unwrap().clone(); + let key = s.view_key(&p, true); + assert!(s.media.rendered.disk().and_then(|d| d.dims(key)).is_some(), "the view preview is on disk"); + let _ = std::fs::remove_dir_all(root); +} + +/// A view preview the cache folder can't take (full, or not writable) fails the photo instead of counting it +/// as built (CodeRabbit on #3077). +#[test] +fn a_preview_that_cannot_be_written_fails_the_build() { + let (mut s, root, ids) = library("unwritable", 2); + let dir = s.media.rendered.disk().expect("a library has a disk cache").dir().to_path_buf(); + let _ = std::fs::remove_dir_all(&dir); + // a file where the cache folder goes: nothing can be written under it + std::fs::write(&dir, b"not a folder").unwrap(); + let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap(); + assert_eq!(r["failed"].as_u64(), Some(2), "{r}"); + let _ = std::fs::remove_file(&dir); + let _ = std::fs::remove_dir_all(root); +} + +/// A photo whose preview cache is discarded while it renders is not counted as built: its preview isn't kept +/// (CodeRabbit on #3077). +#[test] +fn a_preview_rendered_for_a_discarded_cache_fails_the_photo() { + let (mut s, root, ids) = library("discarded", 1); + let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300)); + s.execute("library.clearPreviews", &json!({})).unwrap(); + assert!(!crate::cmd::previews::run_photo(jobs), "nothing was kept: the photo is not built"); + let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300)); + assert!(crate::cmd::previews::run_photo(jobs), "built for the cache as it is now"); + let _ = std::fs::remove_dir_all(root); +} + +/// A forced build renders a photo itself even when another build was rendering it and made its previews +/// (CodeRabbit on #3080): the other build's result is not taken as this one's. +#[test] +fn a_forced_build_renders_a_photo_another_build_was_rendering() { + let (mut s, root, ids) = library("forced-shared", 1); + s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap(); + let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300)); + let held = crate::cmd::previews::hold_building(ids[0].0, &jobs).expect("nobody renders it now"); + s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "force": true})).unwrap(); + let b = s.preview_build.clone().expect("the build"); + std::thread::sleep(std::time::Duration::from_millis(300)); + assert_eq!(b.done.load(Ordering::Relaxed), 0, "not counted while the other build holds it"); + drop(held); + assert!(wait_finished(&b)); + let counts = + (b.done.load(Ordering::Relaxed), b.failed.load(Ordering::Relaxed), b.shared.load(Ordering::Relaxed), b.skipped.load(Ordering::Relaxed)); + assert_eq!(counts, (1, 0, 0, 0), "rendered here, not taken from the other build"); + let _ = std::fs::remove_dir_all(root); +} + +/// A photo another build is rendering is not counted until that render is over: here the other build never +/// made its previews, so this build renders it (CodeRabbit on #3080). +#[test] +fn a_photo_another_build_is_rendering_is_counted_only_once_it_is_built() { + let (mut s, root, ids) = library("shared", 1); + let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300)); + let held = crate::cmd::previews::hold_building(ids[0].0, &jobs).expect("nobody renders it yet"); + s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300})).unwrap(); + let b = s.preview_build.clone().expect("the build"); + std::thread::sleep(std::time::Duration::from_millis(300)); + assert_eq!(b.done.load(Ordering::Relaxed), 0, "not counted while the other build holds it"); + drop(held); + assert!(wait_finished(&b)); + assert_eq!((b.done.load(Ordering::Relaxed), b.failed.load(Ordering::Relaxed), b.shared.load(Ordering::Relaxed)), (1, 0, 0)); + let p = s.catalog.photo(ids[0]).unwrap().clone(); + let key = s.view_key(&p, true); + assert!(s.media.rendered.disk().and_then(|d| d.dims(key)).is_some(), "rendered here, on disk"); + let _ = std::fs::remove_dir_all(root); +} + +/// CodeRabbit on #3544: a library preparation setting that can't be saved is not kept, nor is +/// going back to the app-wide settings: the session stays as the command's error says. +#[test] +fn a_prep_setting_that_cant_be_saved_is_not_kept() { + use crate::prep::PrepSettings; + let (mut s, root, _) = library("prep-unsaved", 1); + let mut own = PrepSettings::default(); + own.culling.ahead = 3; + s.set_prep_settings(own, true).unwrap(); + // prefs.json can't be written: a folder stands in its place + let prefs = root.join("lib").join("prefs.json"); + let _ = std::fs::remove_file(&prefs); + std::fs::create_dir_all(prefs.join("in-the-way")).unwrap(); + let mut other = own; + other.culling.ahead = 5; + assert!(s.set_prep_settings(other, true).is_err()); + assert_eq!(s.prep_json()["library"], json!(own), "the setting that couldn't be saved is not kept"); + assert!(s.clear_library_prep().is_err()); + assert_eq!(s.prep_json()["library"], json!(own), "nor going back to the app-wide settings"); + let _ = std::fs::remove_dir_all(&root); +} + +/// CodeRabbit on #3544: a build asked for with malformed ids fails without stopping the +/// background preparation that is running. +#[test] +fn a_bad_build_request_leaves_the_background_build_running() { + let _hold = crate::prep::TestHold::new(); + let (mut s, root, ids) = library("prep-bad-ids", 3); + s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "background": true})).unwrap(); + let b = s.preview_build.clone().expect("the background build"); + assert!(b.running()); + assert!(s.execute("library.buildPreviews", &json!({"ids": ["x"]})).is_err(), "ids that are not photo ids"); + assert!(!b.cancel.load(std::sync::atomic::Ordering::Relaxed), "the background build was not stopped"); + let _ = std::fs::remove_dir_all(&root); +} + +/// CodeRabbit on #3577: smart previews asked for in the background with malformed ids fail without +/// stopping the background preparation either. +#[test] +fn a_bad_smart_preview_request_leaves_the_background_build_running() { + let _hold = crate::prep::TestHold::new(); + let (mut s, root, ids) = library("prep-bad-smart-ids", 3); + s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "background": true})).unwrap(); + let b = s.preview_build.clone().expect("the background build"); + assert!(b.running()); + assert!(s.execute("library.smartPreviews", &json!({"ids": ["x"], "background": true})).is_err(), "ids that are not photo ids"); + assert!(!b.cancel.load(std::sync::atomic::Ordering::Relaxed), "the background build was not stopped"); + // a smart-preview worker that can't start: the background build carries on, and stays the session's + crate::cmd::previews::test_gate::fail_next_spawn(); + assert!(s.execute("library.smartPreviews", &json!({"ids": ids_json(&ids), "background": true})).is_err(), "the worker didn't start"); + assert!(!b.cancel.load(std::sync::atomic::Ordering::Relaxed), "the background build was not stopped"); + assert!(s.preview_build.as_ref().is_some_and(|now| std::sync::Arc::ptr_eq(now, &b)), "and is still the session's build"); + // (stopped and finished before its folder goes) + b.cancel.store(true, std::sync::atomic::Ordering::Relaxed); + drop(_hold); + let until = std::time::Instant::now() + std::time::Duration::from_secs(20); + while b.running() && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let _ = std::fs::remove_dir_all(&root); +} + +/// CodeRabbit on #3544: a build asked for whose worker can't start fails without stopping or +/// replacing the background preparation that is running. +#[test] +fn a_build_that_cant_start_leaves_the_background_build_running() { + let _hold = crate::prep::TestHold::new(); + let (mut s, root, ids) = library("prep-no-thread", 3); + s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "background": true})).unwrap(); + let b = s.preview_build.clone().expect("the background build"); + assert!(b.running()); + crate::cmd::previews::test_gate::fail_next_spawn(); + assert!(s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids)})).is_err(), "the worker didn't start"); + assert!(!b.cancel.load(std::sync::atomic::Ordering::Relaxed), "the background build was not stopped"); + assert!(s.preview_build.as_ref().is_some_and(|now| std::sync::Arc::ptr_eq(now, &b)), "and is still the session's build"); + let _ = std::fs::remove_dir_all(&root); +} + +/// CodeRabbit on #3080: a background build that can't start isn't tried again on every tick; the +/// view tries again once [`crate::prep::RETRY_AFTER`] has passed. +#[test] +fn a_build_that_cant_start_waits_before_trying_again() { + let (mut s, root, ids) = library("prep-retry", 3); + let mode = crate::prep::Mode::Library; + s.prep.fail_starts = 1; + for id in &ids { + s.prep_tick(mode, Some(*id), false); + } + assert!(s.preview_build.is_none(), "the start failed"); + assert!(s.prep.retry_at.is_some()); + // the app is told when to look again (a frame is asked for then) + assert!(s.prep_retry_in().is_some_and(|d| d <= crate::prep::RETRY_AFTER && d > crate::prep::RETRY_AFTER / 2)); + s.prep_tick(mode, Some(ids[2]), false); + assert!(s.preview_build.is_none(), "not tried again at once"); + // the wait is over: no more frames asked for it (CodeRabbit on #3077 / #3080) + s.prep.retry_at = s.prep.retry_at.map(|(view, _)| (view, web_time::Instant::now())); + assert_eq!(s.prep_retry_in(), None, "a deadline that has passed asks for no frame"); + s.prep_tick(mode, Some(ids[2]), false); + let b = s.preview_build.clone().expect("tried again"); + assert!(b.background && s.prep.retry_at.is_none()); + b.cancel.store(true, Ordering::Relaxed); + let _ = wait_finished(&b); + let _ = std::fs::remove_dir_all(&root); +} diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index a9314c2173..0d27be67c9 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -536,6 +536,249 @@ fn regions_from_sidecar_are_read_on_import() { let _ = std::fs::remove_dir_all(&src); } +/// MWG regions as an app that draws on the photo as stored writes them for [`write_turned_jpeg`]'s photo: its stored +/// 32 × 24 as `AppliedToDimensions` and no box saying how the photo was turned (no `mwg-rs:Rotation`). One face, its +/// box centred at (0.25, 0.4), 0.1 × 0.15 of that size. +const STORED_FRAME_REGIONS: &str = r#" + + + + + + + + + + + + + + +"#; + +/// A JPEG of 32 × 24 pixels stored sideways (Exif orientation 6, shown 24 × 32), with `packet` embedded when given. +fn write_turned_jpeg(path: &Path, packet: Option<&str>) { + let img = lightcraft_raster::Rgba8::from_fn(32, 24, |x, y| [(x * 7) as u8, (y * 9) as u8, 90, 255]); + let exif = + lightcraft_meta::write_exif(&lightcraft_meta::Metadata { orientation: Some(lightcraft_meta::Orientation::Rotate90), ..Default::default() }); + let meta = lightcraft_codecs::EncodeMeta { exif: Some(&exif), xmp: packet, ..Default::default() }; + let bytes = lightcraft_codecs::encode_jpeg(&lightcraft_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &meta).unwrap(); + std::fs::write(path, bytes).unwrap(); +} + +/// Put more than the first MiB of APP15 segments between the JPEG at `path`'s start and its Exif. +fn pad_before_exif(path: &Path) { + let bytes = std::fs::read(path).unwrap(); + let mut padded = bytes[..2].to_vec(); + for _ in 0..17 { + padded.extend_from_slice(&[0xFF, 0xEF, 0xFF, 0xFF]); + padded.extend(std::iter::repeat_n(0, 0xFFFD)); + } + padded.extend_from_slice(&bytes[2..]); + std::fs::write(path, padded).unwrap(); +} + +/// The face's box from [`STORED_FRAME_REGIONS`] on the upright photo: turned a quarter turn clockwise with it. +fn assert_on_the_upright_face(s: &Session, id: PhotoId, when: &str) { + let p = s.catalog.photo(id).unwrap(); + assert_eq!((p.width, p.height), (24, 32), "the photo is upright"); + let r = p.meta.regions.first().map(|r| r.rect).unwrap_or_default(); + let want = [0.525, 0.2, 0.675, 0.3]; + let got = [r.x0, r.y0, r.x1, r.y1]; + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-9), "{when}: the box is where the photo as stored had the face: {got:?}"); + assert_eq!(p.meta.regions.len(), 1, "{when}"); +} + +/// Issue #2674: face boxes an app drew on a photo as stored (its sideways size as `AppliedToDimensions`, no +/// `mwg-rs:Rotation`) land on the faces of the photo as LightCraft shows it, upright: when imported, and when the +/// file's metadata is read again (the packet itself doesn't say how the photo turns; the file's Exif does). The +/// image's own size decides, not one the XMP states upright, and the Exif is found past the first MiB of the file. +#[test] +fn regions_drawn_on_the_photo_as_stored_land_on_the_upright_photo() { + let src = temp_dir("regions-stored-frame"); + let embedded = src.join("embedded.jpg"); + write_turned_jpeg(&embedded, Some(STORED_FRAME_REGIONS)); + let beside = src.join("sidecar.jpg"); + write_turned_jpeg(&beside, None); + std::fs::write(src.join("sidecar.xmp"), STORED_FRAME_REGIONS).unwrap(); + // an Exif without a pixel size, and an XMP size of the upright photo + let stated = src.join("stated.jpg"); + let upright_size = r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:ImageWidth="24" tiff:ImageLength="32""#; + write_turned_jpeg(&stated, Some(&STORED_FRAME_REGIONS.replace(r#"rdf:about="""#, upright_size))); + let late = src.join("late.jpg"); + write_turned_jpeg(&late, None); + pad_before_exif(&late); + std::fs::write(src.join("late.xmp"), STORED_FRAME_REGIONS).unwrap(); + for (file, what) in [(&embedded, "embedded XMP"), (&beside, "sidecar"), (&stated, "upright size in the XMP"), (&late, "Exif after the first MiB")] + { + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(1), "{r}"); + let id = only(&s); + assert_on_the_upright_face(&s, id, &format!("{what}, imported")); + let read = s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(read["failed"], json!([]), "{read}"); + assert_eq!(read["read"].as_array().map(Vec::len), Some(1), "{what}: {read}"); + assert_on_the_upright_face(&s, id, &format!("{what}, read again")); + } + let _ = std::fs::remove_dir_all(&src); +} + +/// Review of #2857: a photo whose Exif states no orientation, but whose XMP says `tiff:Orientation=6`, is shown as +/// stored (LightCraft turns by the Exif alone), so boxes drawn on its stored frame are right as written: at import +/// and when the file's metadata is read again, which must agree. +#[test] +fn an_orientation_only_the_xmp_states_leaves_stored_frame_regions_as_written() { + let src = temp_dir("regions-xmp-orientation"); + let file = src.join("p.jpg"); + let packet = STORED_FRAME_REGIONS.replace(r#"rdf:about="""#, r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:Orientation="6""#); + let img = lightcraft_raster::Rgba8::from_fn(32, 24, |x, y| [(x * 7) as u8, (y * 9) as u8, 90, 255]); + // an Exif that states the size as stored (32 × 24, as cameras do) and no orientation + let exif = { + use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t}; + let mut sub = IfdBuilder::new(); + sub.set(t::PIXEL_X_DIMENSION, Value::Long(vec![32])); + sub.set(t::PIXEL_Y_DIMENSION, Value::Long(vec![24])); + let mut ifd0 = IfdBuilder::new(); + ifd0.set_child(t::EXIF_IFD, sub); + [b"Exif\0\0".as_slice(), &TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap()].concat() + }; + let meta = lightcraft_codecs::EncodeMeta { exif: Some(&exif), xmp: Some(&packet), ..Default::default() }; + std::fs::write(&file, lightcraft_codecs::encode_jpeg(&lightcraft_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &meta).unwrap()) + .unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); + let id = only(&s); + let boxes = |s: &Session, when: &str| { + let p = s.catalog.photo(id).unwrap(); + assert_eq!((p.width, p.height), (32, 24), "{when}: shown as stored"); + assert_eq!(p.meta.regions.len(), 1, "{when}"); + let r = p.meta.regions[0].rect; + [r.x0, r.y0, r.x1, r.y1] + }; + let want = [0.2, 0.325, 0.3, 0.475]; + let close = |got: [f64; 4]| got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-9); + let imported = boxes(&s, "imported"); + assert!(close(imported), "imported: the box was turned by an orientation the Exif doesn't state: {imported:?}"); + let read = s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(read["failed"], json!([]), "{read}"); + let again = boxes(&s, "read again"); + assert!(close(again), "read again: {again:?}"); + let _ = std::fs::remove_dir_all(&src); +} + +/// Review of #2857 (P2): a MEF keeps orientation on its raw IFD, not IFD0. Import turns face boxes by the decoder's +/// orientation; Read Metadata from File must use the same source, or the boxes go back to the stored frame and +/// Synchronize Folder reports changes every pass. The sidecar has no `tiff:Orientation`. +#[test] +fn a_raws_decoder_orientation_turns_stored_frame_regions_on_import_and_reread() { + let src = temp_dir("regions-mef-orientation"); + let file = src.join("p.mef"); + // 16 × 6 CFA strip, orientation 6 on the raw IFD only (IFD0 has none) — same shape as `lightcraft_raw`'s MEF fixture. + let px: Vec = (0..16 * 6).map(|i| (i * 41 % 4096) as u16).collect(); + let strip: Vec = px.chunks(2).flat_map(|p| [(p[0] >> 4) as u8, ((p[0] & 15) << 4) as u8 | (p[1] >> 8) as u8, p[1] as u8]).collect(); + { + use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags as t}; + let mut raw = IfdBuilder::new(); + raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); + raw.set(t::IMAGE_WIDTH, Value::Long(vec![16])); + raw.set(t::IMAGE_LENGTH, Value::Long(vec![6])); + raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![12])); + raw.set(t::COMPRESSION, Value::Short(vec![1])); + raw.set(t::PHOTOMETRIC, Value::Short(vec![t::photometric::CFA])); + raw.set(t::ORIENTATION, Value::Short(vec![6])); + raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); + raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); + raw.set_image(ImageData::Strips { rows_per_strip: 6, strips: vec![strip] }); + let mut ifd0 = IfdBuilder::new(); + ifd0.set(t::MAKE, Value::Ascii("Mamiya-OP Co.,Ltd.".into())); + ifd0.set(t::MODEL, Value::Ascii("MAMIYA ZD".into())); + ifd0.add_sub_ifd(raw); + std::fs::write(&file, TiffWriter::new(ByteOrder::Big, false).write(&[ifd0]).unwrap()).unwrap(); + } + assert!(lightcraft_meta::extract(&std::fs::read(&file).unwrap()).orientation.is_none(), "IFD0 states no orientation"); + assert_eq!( + lightcraft_raw::probe_info(&std::fs::read(&file).unwrap()).unwrap().orientation, + lightcraft_meta::Orientation::Rotate90, + "decoder reads the raw IFD" + ); + let packet = STORED_FRAME_REGIONS.replace(r#"stDim:w="32" stDim:h="24""#, r#"stDim:w="16" stDim:h="6""#); + std::fs::write(src.join("p.xmp"), packet).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); + let id = only(&s); + let boxes = |s: &Session, when: &str| { + let p = s.catalog.photo(id).unwrap(); + assert_eq!((p.width, p.height), (6, 16), "{when}: upright from orientation 6"); + assert_eq!(p.meta.regions.len(), 1, "{when}"); + let r = p.meta.regions[0].rect; + [r.x0, r.y0, r.x1, r.y1] + }; + let imported = boxes(&s, "imported"); + // Without the decoder orientation on re-read, readMetadataFromFile puts the box back to the stored-frame coords. + let read = s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(read["failed"], json!([]), "{read}"); + let again = boxes(&s, "read again"); + assert_eq!(imported, again, "import and re-read must agree: imported={imported:?} again={again:?}"); + let stored = [0.2, 0.325, 0.3, 0.475]; // STORED_FRAME_REGIONS centre/size as x0,y0,x1,y1 for 0.25,0.4,0.1,0.15 + assert!( + imported.iter().zip(stored).any(|(g, w)| (g - w).abs() > 1e-6), + "imported boxes should have been turned off the stored frame: {imported:?}" + ); + let _ = std::fs::remove_dir_all(&src); +} + +/// A raw LightCraft can't decode: a TIFF whose first IFD holds Exif orientation 6, a 40 × 30 JPEG and `packet`. +fn turned_preview_only_raw(packet: &str) -> Vec { + let img = lightcraft_raster::Rgba8::from_fn(40, 30, |x, y| [(x * 6) as u8, (y * 8) as u8, 90, 255]); + let jpeg = lightcraft_codecs::encode_jpeg(&lightcraft_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &Default::default()).unwrap(); + let data = 8 + 2 + 4 * 12 + 4; + let (jpeg_len, packet_at) = (u32::try_from(jpeg.len()).unwrap(), u32::try_from(data + jpeg.len()).unwrap()); + let mut f = b"II*\0\x08\0\0\0\x04\0".to_vec(); + for (tag, kind, count, value) in [(274u16, 3u16, 1, 6), (513, 4, 1, data as u32), (514, 4, 1, jpeg_len), (700, 1, packet.len() as u32, packet_at)] + { + f.extend(tag.to_le_bytes()); + f.extend(kind.to_le_bytes()); + f.extend(u32::to_le_bytes(count)); + f.extend(u32::to_le_bytes(value)); + } + f.extend([0; 4]); + f.extend(jpeg); + f.extend(packet.as_bytes()); + f +} + +/// A sidecar with no `mwg-rs:Regions` leaves the boxes read from the file itself, and a raw's Exif may state no pixel +/// size. A size only its XMP states, of the upright photo, has the shape of boxes drawn on it upright: they stay put. +#[test] +fn a_size_only_a_raws_xmp_states_leaves_upright_regions_as_written() { + let src = temp_dir("regions-xmp-size"); + let file = src.join("p.iiq"); + let upright_size = r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:ImageWidth="24" tiff:ImageLength="32""#; + let packet = + STORED_FRAME_REGIONS.replace(r#"stDim:w="32" stDim:h="24""#, r#"stDim:w="24" stDim:h="32""#).replace(r#"rdf:about="""#, upright_size); + std::fs::write(&file, turned_preview_only_raw(&packet)).unwrap(); + std::fs::write( + src.join("p.xmp"), + r#" + "#, + ) + .unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); + let p = s.catalog.photo(only(&s)).unwrap(); + assert!(p.preview_only.is_some() && (p.width, p.height) == (30, 40), "{:?} {}x{}", p.preview_only, p.width, p.height); + assert_eq!(p.rating, 2, "the sidecar was read"); + assert_eq!(p.meta.regions.len(), 1); + let r = p.meta.regions[0].rect; + let got = [r.x0, r.y0, r.x1, r.y1]; + assert!(got.iter().zip([0.2, 0.325, 0.3, 0.475]).all(|(g, w)| (g - w).abs() < 1e-9), "{got:?}"); + let _ = std::fs::remove_dir_all(&src); +} + /// Removing a face box is a catalog-only, undoable edit: it never rewrites the sidecar (Lightroom's /// regions and everything else in it stay byte for byte), even with auto-write on. #[test] diff --git a/crates/engine/tests/denoise_builtin_quality.rs b/crates/engine/tests/denoise_builtin_quality.rs new file mode 100644 index 0000000000..0a057f6ecc --- /dev/null +++ b/crates/engine/tests/denoise_builtin_quality.rs @@ -0,0 +1,289 @@ +//! Opt-in quality check of the built-in denoiser on one public Bayer raw (CC0, from `cargo xtask corpus --download`). +//! +//! Noise of a known level is added to the raw's own mosaic, the built-in denoiser runs over it, and the result is +//! scored against the untouched mosaic demosaiced the same way. PSNR is measured on gamma-encoded camera RGB; the +//! detail figure is the gradient energy of the result over that of the truth (1 = as sharp, below 1 = smoother). +//! +//! LC_DENOISE_RAW=../../corpus/raw/arw-sony-a7m3-compressed.arw LC_DENOISE_OUT=/tmp/dn \ +//! cargo test --release -p lightcraft-engine --test denoise_builtin_quality -- --ignored --nocapture +//! LC_DENOISE_OUT, when set, receives side-by-side PNGs (truth | noisy | denoised) of a 100 % crop per level. + +use lightcraft_codecs::encode::{EncodeImage, EncodeMeta, Samples, encode_png}; +use lightcraft_denoise_core::bayer::Layout; +use lightcraft_denoise_core::builtin::{Builtin, OVERLAP, TILE, demosaic, estimate_noise}; +use lightcraft_denoise_core::manifest::Gain; +use lightcraft_denoise_core::nlm::Tuning; +use lightcraft_denoise_core::run::{Control, Params, denoise_bayer}; +use std::time::Instant; + +struct Rng(u64); + +impl Rng { + /// The next uniform number, strictly between 0 and 1. + fn uniform(&mut self) -> f32 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((self.0 >> 40) as f32 + 0.5) / (1u64 << 24) as f32 + } + + /// The next standard normal number (Box-Muller). + fn normal(&mut self) -> f32 { + let (u, v) = (self.uniform(), self.uniform()); + (-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos() + } +} + +/// The plain demosaic of a mosaic (RGGB, even size) as camera RGB planes, through the tile packer the runner uses. +fn plain(mosaic: &[f32], w: usize, h: usize) -> Vec<[f32; 3]> { + let (cw, ch) = (w / 2, h / 2); + let mut planes = vec![vec![0f32; cw * ch]; 4]; + for cy in 0..ch { + for cx in 0..cw { + for (p, (dx, dy)) in [(0, 0), (1, 0), (0, 1), (1, 1)].into_iter().enumerate() { + planes[p][cy * cw + cx] = mosaic[(2 * cy + dy) * w + 2 * cx + dx]; + } + } + } + // `demosaic` takes square planes: run it on square blocks and stitch + let side = cw.min(ch); + let mut out = vec![[0f32; 3]; w * h]; + for by in (0..ch).step_by(side) { + for bx in (0..cw).step_by(side) { + let (x0, y0) = (bx.min(cw - side), by.min(ch - side)); + let block: Vec> = planes.iter().map(|pl| (0..side * side).map(|i| pl[(y0 + i / side) * cw + x0 + i % side]).collect()).collect(); + let rgb = demosaic(&block, side); + let s2 = 2 * side; + for y in 0..s2 { + for x in 0..s2 { + let o = (2 * y0 + y) * w + 2 * x0 + x; + out[o] = [rgb[y * s2 + x], rgb[s2 * s2 + y * s2 + x], rgb[2 * s2 * s2 + y * s2 + x]]; + } + } + } + } + out +} + +/// A linear value encoded for viewing: clamped to 0..1, then gamma 2.2. +fn gamma(v: f32) -> f32 { + v.clamp(0.0, 1.0).powf(1.0 / 2.2) +} + +/// PSNR in dB between two camera-RGB pictures after exposure `scale` and gamma, leaving out a 16-pixel border. +fn psnr(a: &[[f32; 3]], b: &[[f32; 3]], w: usize, h: usize, scale: f32) -> f64 { + let (mut sum, mut n) = (0f64, 0f64); + for y in 16..h - 16 { + for x in 16..w - 16 { + for c in 0..3 { + let d = f64::from(gamma(a[y * w + x][c] * scale) - gamma(b[y * w + x][c] * scale)); + sum += d * d; + n += 1.0; + } + } + } + -10.0 * (sum / n).log10() +} + +/// The summed gradient of the picture's green channel after exposure `scale` and gamma, leaving out a 16-pixel border. +fn gradient(a: &[[f32; 3]], w: usize, h: usize, scale: f32) -> f64 { + let mut sum = 0f64; + for y in 16..h - 16 { + for x in 16..w - 16 { + let g = |x: usize, y: usize| f64::from(gamma(a[y * w + x][1] * scale)); + sum += (g(x + 1, y) - g(x, y)).abs() + (g(x, y + 1) - g(x, y)).abs(); + } + } + sum +} + +/// How much of the true picture's fine structure the result keeps: the slope of the result's high-pass (green minus +/// its 5 x 5 mean) against the truth's. Noise is independent of the truth, so unlike gradient energy it can't inflate it. +fn texture(a: &[[f32; 3]], truth: &[[f32; 3]], w: usize, h: usize, scale: f32) -> f64 { + let hp = |p: &[[f32; 3]], x: usize, y: usize| { + let mut m = 0f64; + for j in 0..5 { + for i in 0..5 { + m += f64::from(gamma(p[(y + j - 2) * w + x + i - 2][1] * scale)); + } + } + f64::from(gamma(p[y * w + x][1] * scale)) - m / 25.0 + }; + let (mut xy, mut xx) = (0f64, 0f64); + for y in 16..h - 16 { + for x in 16..w - 16 { + let t = hp(truth, x, y); + xy += t * hp(a, x, y); + xx += t * t; + } + } + xy / xx +} + +/// A `side × side` crop of the picture from `(x0, y0)` as 8-bit RGB with a daylight white balance, for the PNGs. +fn crop_rgb8(a: &[[f32; 3]], w: usize, (x0, y0): (usize, usize), side: usize, scale: f32) -> Vec { + let wb = [2.0f32, 1.0, 1.6]; + let mut out = Vec::with_capacity(side * side * 3); + for y in 0..side { + for x in 0..side { + for c in 0..3 { + out.push((gamma(a[(y0 + y) * w + x0 + x][c] * wb[c] * scale) * 255.0 + 0.5) as u8); + } + } + } + out +} + +/// Adds noise of known levels to a public raw's mosaic, denoises it with the built-in denoiser and prints how close the +/// result is to the untouched mosaic. Opt-in: it needs the raw named by `LC_DENOISE_RAW`. +#[test] +#[ignore = "needs a public raw: LC_DENOISE_RAW="] +fn the_built_in_denoiser_scored_on_a_real_raw_with_added_noise() { + let path = std::env::var("LC_DENOISE_RAW").unwrap_or_else(|_| "../../corpus/raw/arw-sony-a7m3-compressed.arw".into()); + let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{path}: {e}")); + let n = lightcraft_raw::decode(&bytes).unwrap().normalized().unwrap(); + let cfa = n.cfa.as_ref().unwrap(); + let layout = Layout::from_cell([cfa.color_at(0, 0), cfa.color_at(1, 0), cfa.color_at(0, 1), cfa.color_at(1, 1)]).unwrap(); + assert_eq!(layout, Layout { dx: 0, dy: 0 }, "the benchmark assumes RGGB"); + // an even-aligned window from the middle of the frame keeps the colour pattern + let (w, h) = (1536usize, 1024usize); + let (ox, oy) = (((n.width - w) / 2) & !1, ((n.height - h) / 2) & !1); + let truth: Vec = (0..w * h).map(|i| n.data[(oy + i / w) * n.width + ox + i % w]).collect(); + // LC_BIN=1: average each cell with the three nearest of its own colour (a 2 x 2 binning of the colour pattern's + // cells), which halves the reference's own noise so that noise added at a camera's low levels dominates it + let (w, h, truth) = if std::env::var("LC_BIN").is_ok_and(|v| v != "0") { + let (bw, bh) = (w / 2, h / 2); + let binned: Vec = (0..bw * bh) + .map(|i| { + let (x, y) = (i % bw, i / bw); + let (sx, sy, cx, cy) = (x / 2, y / 2, x % 2, y % 2); + let at = |di: usize, dj: usize| truth[(2 * (2 * sy + dj) + cy) * w + 2 * (2 * sx + di) + cx]; + (at(0, 0) + at(1, 0) + at(0, 1) + at(1, 1)) / 4.0 + }) + .collect(); + (bw, bh, binned) + } else { + (w, h, truth) + }; + let mean = truth.iter().map(|v| f64::from(*v)).sum::() / truth.len() as f64; + let scale = (0.18 / mean) as f32; + let truth_rgb = plain(&truth, w, h); + let own = estimate_noise(&truth, w, h); + println!( + "the reference's own noise by the estimator: a {:.5} b {:.6} (sd at 0.18 {:.4}); a clean reference would read about 0", + own.0, + own.1, + (own.0 * 0.18 + own.1).sqrt() + ); + println!("{path}: {}x{}, window {w}x{h}, mean {mean:.4}", n.width, n.height); + println!("{:<14}{:>10}{:>10}{:>9}{:>9}{:>9}{:>9}", "noise (a, b)", "noisy dB", "denoised", "gain", "detail", "texture", "seconds"); + let out_dir = std::env::var("LC_DENOISE_OUT").ok(); + #[cfg(feature = "denoise")] + let gpu = std::env::var("LC_GPU").is_ok_and(|v| v != "0").then(|| { + let p = Tuning::default().bm3d.unwrap(); + let g = lightcraft_gpu::bm3d::Bm3dGpu::new(&p, TILE as usize).unwrap(); + println!("on the graphics card: {} ({})", g.adapter(), g.build_report()); + std::sync::Arc::new(g) + }); + // LC_REAL=1 runs the noise levels measured on real Canon EOS R / R6 Mark III raws instead (their standard deviation at + // mid-grey is 0.003, 0.006, 0.0095, 0.015 and 0.038: ISO <= 400, 1600, 6400, 25600 and above) + let levels: &[(&str, f32, f32)] = if std::env::var("LC_REAL").is_ok_and(|v| v != "0") { + &[("iso400", 4e-5, 1e-7), ("iso1600", 2.1e-4, 3e-7), ("iso6400", 4.9e-4, 1e-6), ("iso25600", 1.19e-3, 1.7e-5), ("iso51200", 6.9e-3, 2.08e-4)] + } else { + &[("light", 0.002, 0.0002), ("medium", 0.008, 0.001), ("heavy", 0.025, 0.004), ("extreme", 0.06, 0.012)] + }; + for &(name, a, b) in levels { + let mut rng = Rng(11); + let noisy: Vec = truth.iter().map(|&v| v + rng.normal() * (a * v.max(0.0) + b).sqrt()).collect(); + let started = Instant::now(); + let params = Params { tile: TILE as usize, overlap: OVERLAP as usize, gain: Gain::None, clip: Some(0.99), parallel: 4 }; + // LC_EST=v1 (the first estimator) | true (the noise that was added) | anything else: the current estimator + // LC_FULL=1: measure the noise on the whole frame with the same noise added, as the app does (it measures the whole + // photo), instead of on the crop + let measure = |mosaic: &[f32], mw: usize, mh: usize| match std::env::var("LC_EST").as_deref() { + Ok("v1") => lightcraft_denoise_core::builtin::estimate_noise_v1(mosaic, mw, mh), + _ => estimate_noise(mosaic, mw, mh), + }; + let est = match std::env::var("LC_EST").as_deref() { + Ok("true") => (a, b), + _ if std::env::var("LC_TRUE").is_ok_and(|v| v != "0") => (a, b), + _ if std::env::var("LC_FULL").is_ok_and(|v| v != "0") => { + let mut rng = Rng(23); + let frame: Vec = n.data.iter().map(|&v| v + rng.normal() * (a * v.max(0.0) + b).sqrt()).collect(); + measure(&frame, n.width, n.height) + } + _ => measure(&noisy, w, h), + }; + let mut tuning = Tuning::default(); + let env = |k: &str| std::env::var(k).ok().and_then(|v| v.parse::().ok()); + (tuning.search, tuning.search2) = (env("LC_S1").map_or(tuning.search, |v| v as usize), env("LC_S2").map_or(tuning.search2, |v| v as usize)); + (tuning.h_light, tuning.h_heavy, tuning.h2) = + (env("LC_HL").unwrap_or(tuning.h_light), env("LC_HH").unwrap_or(tuning.h_heavy), env("LC_H2").unwrap_or(tuning.h2)); + (tuning.light, tuning.heavy) = (env("LC_LIGHT").unwrap_or(tuning.light), env("LC_HEAVY").unwrap_or(tuning.heavy)); + (tuning.half, tuning.half2) = (env("LC_P1").map_or(tuning.half, |v| v as usize), env("LC_P2").map_or(tuning.half2, |v| v as usize)); + (tuning.loose, tuning.few) = (env("LC_LOOSE").unwrap_or(tuning.loose), env("LC_FEW").unwrap_or(tuning.few)); + (tuning.search_c, tuning.h_c) = (env("LC_SC").map_or(tuning.search_c, |v| v as usize), env("LC_HC").unwrap_or(tuning.h_c)); + // LC_NLM=1 runs the old non-local-means filter instead; LC_B_* override the block-matching filter's parameters + if env("LC_NLM").is_some_and(|v| v > 0.0) { + tuning.bm3d = None; + } + if let Some(b) = tuning.bm3d.as_mut() { + (b.block, b.step, b.search, b.group) = ( + env("LC_B_N").map_or(b.block, |v| v as usize), + env("LC_B_STEP").map_or(b.step, |v| v as usize), + env("LC_B_S").map_or(b.search, |v| v as usize), + env("LC_B_K").map_or(b.group, |v| v as usize), + ); + (b.tau1, b.tau2) = (env("LC_B_T1").unwrap_or(b.tau1), env("LC_B_T2").unwrap_or(b.tau2)); + // LC_B_LOFF adds to every point of the threshold curve (a sweep of how hard it cleans) + let off = env("LC_B_LOFF").unwrap_or(0.0); + for point in &mut b.lambda { + point.1 += off; + } + b.sigma = env("LC_B_SIG").unwrap_or(b.sigma); + b.wiener = env("LC_B_WIENER").is_none_or(|v| v > 0.0); + } + let runner = Builtin { noise: Some(est), tuning }; + // LC_GPU=1 (with `--features denoise`) runs the block-matching filter on the graphics card + #[cfg(feature = "denoise")] + let out = match &gpu { + Some(g) => { + let on_card = lightcraft_gpu::bm3d::BuiltinRunner::new(g.clone(), runner).unwrap(); + denoise_bayer(&noisy, w, h, layout, &on_card, ¶ms, &Control::default()).unwrap() + } + None => denoise_bayer(&noisy, w, h, layout, &runner, ¶ms, &Control::default()).unwrap(), + }; + #[cfg(not(feature = "denoise"))] + let out = denoise_bayer(&noisy, w, h, layout, &runner, ¶ms, &Control::default()).unwrap(); + let secs = started.elapsed().as_secs_f64(); + let noisy_rgb = plain(&noisy, w, h); + let (p_noisy, p_out) = (psnr(&noisy_rgb, &truth_rgb, w, h, scale), psnr(&out.data, &truth_rgb, w, h, scale)); + let detail = gradient(&out.data, w, h, scale) / gradient(&truth_rgb, w, h, scale); + let tex = texture(&out.data, &truth_rgb, w, h, scale); + println!( + "{:<14}{:>10.2}{:>10.2}{:>+9.2}{:>9.3}{:>9.3}{:>9.2} noise a {:.4} (true {a}), b {:.5} (true {b})", + name, + p_noisy, + p_out, + p_out - p_noisy, + detail, + tex, + secs, + est.0, + est.1 + ); + if let Some(dir) = &out_dir { + let side = 400; + let at = (w / 2 - side / 2, h / 2 - side / 2); + let tiles = + [crop_rgb8(&truth_rgb, w, at, side, scale), crop_rgb8(&noisy_rgb, w, at, side, scale), crop_rgb8(&out.data, w, at, side, scale)]; + let mut sheet = Vec::with_capacity(side * side * 9); + for y in 0..side { + for t in &tiles { + sheet.extend_from_slice(&t[y * side * 3..(y + 1) * side * 3]); + } + } + let img = EncodeImage::new((3 * side) as u32, side as u32, 3, Samples::U8(&sheet)); + std::fs::create_dir_all(dir).unwrap(); + std::fs::write(format!("{dir}/{name}.png"), encode_png(&img, &EncodeMeta::default()).unwrap()).unwrap(); + } + } +} diff --git a/crates/engine/tests/denoise_noise_estimate.rs b/crates/engine/tests/denoise_noise_estimate.rs new file mode 100644 index 0000000000..84fabe09a7 --- /dev/null +++ b/crates/engine/tests/denoise_noise_estimate.rs @@ -0,0 +1,130 @@ +//! Opt-in accuracy check of the built-in denoiser's noise estimator (public CC0 raws from `cargo xtask corpus --download`). +//! +//! 1. `a_quantile_of_pure_noise_blocks_...`: white noise of a known level: what fraction of the true variance a quantile of +//! the blocks' variances is (the correction `NoiseProbe::correction` divides by). +//! 2. `the_noise_estimate_...`: noise of known levels added to 2 x 2-binned crops of many raws (which halves the pictures' +//! own noise), then the estimates against the truth, for the first version and the current one, at 0.03 (the dark +//! cells of a typical photo) and 0.18 (mid-grey). +//! +//! LC_CORPUS=C:/.../corpus/raw LC_STRIDE=6 cargo test --release -p lightcraft-engine --test denoise_noise_estimate -- --ignored --nocapture +use lightcraft_denoise_core::builtin::{NoiseProbe, estimate_noise_v1, estimate_noise_with}; + +struct Rng(u64); + +impl Rng { + /// The next uniform number, strictly between 0 and 1. + fn uniform(&mut self) -> f32 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((self.0 >> 40) as f32 + 0.5) / (1u64 << 24) as f32 + } + + /// The next standard normal number (Box-Muller). + fn normal(&mut self) -> f32 { + let (u, v) = (self.uniform(), self.uniform()); + (-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos() + } +} + +/// The environment variable `k` as a number, if it is set and parses. +fn env(k: &str) -> Option { + std::env::var(k).ok().and_then(|v| v.parse().ok()) +} + +/// Prints what fraction of the true variance a quantile of pure-noise blocks' variances is, for each block size and +/// quantile: the calibration behind `NoiseProbe::correction`. +#[test] +#[ignore = "calibration printout"] +fn a_quantile_of_pure_noise_blocks_is_a_known_fraction_of_the_true_variance() { + let (w, h) = (2048usize, 2048usize); + let sigma = 0.01f32; + let mut rng = Rng(3); + let mosaic: Vec = (0..w * h).map(|i| 0.1 + 0.7 * (i % w) as f32 / w as f32 + rng.normal() * sigma).collect(); + println!("{:>6}{:>9}{:>14} (estimated variance / true variance, correction 1; a brightness ramp, pure noise)", "block", "quantile", "fraction"); + for block in [8usize, 12, 16, 24, 32] { + for quantile in [0.02f32, 0.05, 0.1, 0.2, 0.5] { + let (_, b) = estimate_noise_with(&mosaic, w, h, &NoiseProbe { block, quantile, correction: 1.0 }); + println!("{block:>6}{quantile:>9}{:>14.3}", b / (sigma * sigma)); + } + } +} + +/// The 2 x 2 colour-cell binning of a window of a normalised mosaic (halves its own noise), as the quality benchmark does. +fn binned_crop(n: &lightcraft_raw::Normalized, side: usize) -> Option<(Vec, usize)> { + let side = side.min(n.width).min(n.height) & !3; + if side < 512 { + return None; + } + let (ox, oy) = (((n.width - side) / 2) & !1, ((n.height - side) / 2) & !1); + let half = side / 2; + let out = (0..half * half) + .map(|i| { + let (x, y) = (i % half, i / half); + let (sx, sy, cx, cy) = (x / 2, y / 2, x % 2, y % 2); + let at = |di: usize, dj: usize| n.data[(oy + 2 * (2 * sy + dj) + cy) * n.width + ox + 2 * (2 * sx + di) + cx]; + (at(0, 0) + at(1, 0) + at(0, 1) + at(1, 1)) / 4.0 + }) + .collect(); + Some((out, half)) +} + +/// Prints how the estimated noise compares with the noise added to crops of many raws, for the first version and for +/// several settings of the current one. Opt-in: it needs the raw corpus folder named by `LC_CORPUS`. +#[test] +#[ignore = "needs the public raw corpus: LC_CORPUS="] +fn the_noise_estimate_follows_the_noise_added_to_many_different_pictures() { + let dir = std::env::var("LC_CORPUS").unwrap_or_else(|_| "../../corpus/raw".into()); + let stride = env("LC_STRIDE").map_or(6, |v| v as usize).max(1); + let mut files: Vec<_> = std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{dir}: {e}")).flatten().map(|e| e.path()).collect(); + files.sort(); + let probes = [ + ("v1 (old)", None), + ("block 16, q 0.10", Some(NoiseProbe { block: 16, quantile: 0.10, correction: env("LC_C").unwrap_or(0.8) })), + ("block 12, q 0.05", Some(NoiseProbe { block: 12, quantile: 0.05, correction: env("LC_C2").unwrap_or(0.65) })), + ("block 24, q 0.10", Some(NoiseProbe { block: 24, quantile: 0.10, correction: env("LC_C3").unwrap_or(0.85) })), + ]; + // sd at mid-grey 0.0062, 0.0094, 0.015, 0.038 (Canon EOS R / R6 Mark III at ISO 1600, 6400, 25600 and above) + let levels = [("sd .0062", 2.1e-4f32, 3e-7f32), ("sd .0094", 4.9e-4, 1e-6), ("sd .0152", 1.19e-3, 1.7e-5), ("sd .0381", 6.9e-3, 2.08e-4)]; + // ratios[level][probe][where] -> estimated sd / true sd + let mut ratios: Vec; 2]>> = levels.iter().map(|_| probes.iter().map(|_| [Vec::new(), Vec::new()]).collect()).collect(); + let mut used = 0; + for path in files.iter().step_by(stride) { + let Ok(bytes) = std::fs::read(path) else { continue }; + let Ok(raw) = lightcraft_raw::decode(&bytes) else { continue }; + if raw.cpp != 1 || !raw.cfa.as_ref().is_some_and(lightcraft_raw::Cfa::is_bayer) { + continue; + } + let Ok(n) = raw.normalized() else { continue }; + let Some((mosaic, side)) = binned_crop(&n, 2048) else { continue }; + used += 1; + for (li, &(_, a, b)) in levels.iter().enumerate() { + let mut rng = Rng(11 + li as u64); + let noisy: Vec = mosaic.iter().map(|&v| v + rng.normal() * (a * v.max(0.0) + b).sqrt()).collect(); + for (pi, (_, probe)) in probes.iter().enumerate() { + let (ea, eb) = match probe { + None => estimate_noise_v1(&noisy, side, side), + Some(p) => estimate_noise_with(&noisy, side, side, p), + }; + for (wi, at) in [0.03f32, 0.18].into_iter().enumerate() { + ratios[li][pi][wi].push(((ea * at + eb) / (a * at + b)).sqrt()); + } + } + } + } + println!("{used} pictures (every {stride}th raw of {dir}), each binned to {} cells, noise added at 4 levels", 1024); + println!("estimated sd / true sd: median [10th .. 90th percentile], share within -20 % .. +25 %"); + for (li, (name, _, _)) in levels.iter().enumerate() { + for (wi, at) in ["at 0.03", "at 0.18"].into_iter().enumerate() { + println!("{name} {at}:"); + for (pi, (pname, _)) in probes.iter().enumerate() { + let mut r = ratios[li][pi][wi].clone(); + r.sort_by(f32::total_cmp); + if r.is_empty() { + continue; + } + let q = |f: f32| r[((r.len() - 1) as f32 * f) as usize]; + let within = r.iter().filter(|&&v| (0.8..=1.25).contains(&v)).count() as f32 / r.len() as f32; + println!(" {pname:<18} {:.2} [{:.2} .. {:.2}] {:>3.0} % within", q(0.5), q(0.1), q(0.9), within * 100.0); + } + } + } +} diff --git a/crates/gpu/src/bm3d.rs b/crates/gpu/src/bm3d.rs new file mode 100644 index 0000000000..08d0858881 --- /dev/null +++ b/crates/gpu/src/bm3d.rs @@ -0,0 +1,592 @@ +//! The built-in denoiser's block-matching filter ([`lightcraft_denoise::bm3d`], which is the reference) on the GPU: +//! three WGSL kernels (`wgsl/bm3d_*.wgsl`) that group alike blocks, filter each group's blocks together and put them +//! back, run twice (a hard threshold, then a Wiener filter built from its result) in one command buffer per tile. +//! +//! Only the filter stage runs here. Measuring the noise, the variance-stabilising transform and its inverse and the +//! demosaic stay on the processor ([`Builtin::run_with`]), so a tile differs from the processor's only by the rounding +//! of the filter itself. Like [`crate::nn`], the runner has a device of its own, respects the same switches and the same +//! crash sentinel, never panics, and a failure is an `Err` that makes the caller run that tile on the CPU. + +use std::sync::{Arc, Condvar, Mutex}; +use std::time::Duration; + +use bytemuck::{Pod, Zeroable}; +use lightcraft_denoise::bm3d::{self, Params}; +use lightcraft_denoise::builtin::Builtin; +use lightcraft_denoise::nlm::hadamard; +use lightcraft_denoise::run::{Error, TileRunner}; +use wgpu::util::DeviceExt; + +use crate::nn::{CLOSING, Dev, TIMEOUT, dev, entry, mark_broken, pipeline, storage}; + +/// Tiles that can be on the GPU at once (each has buffers of its own). +const WORKSPACES: usize = 2; +/// The largest tile side (in cells) the buffers and dispatch sizes are made for. +const MAX_TILE: usize = 512; +/// The block side and the group size the kernels are written for. +const BLOCK: usize = 4; +const GROUP: usize = 16; +/// Invocations in a workgroup (the kernels' `@workgroup_size`). +const WORKGROUP: u32 = 64; + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct Uniforms { + t: u32, + nr: u32, + nb: u32, + search: u32, + cap: u32, + wiener: u32, + pad0: u32, + pad1: u32, + tau: f32, + lambda: f32, + sigma: f32, + pad2: f32, +} + +struct Pipes { + matching: wgpu::ComputePipeline, + matching_layout: wgpu::BindGroupLayout, + collab: wgpu::ComputePipeline, + collab_layout: wgpu::BindGroupLayout, + agg: wgpu::ComputePipeline, + agg_layout: wgpu::BindGroupLayout, + /// How long each kernel took to build (the driver compiles them), for the log and the tests. + built: Vec<(String, f64)>, +} + +/// Compile the three kernels (match, filter, put back) and make their bind-group layouts, timing each build. +fn build_pipes(d: &Dev) -> Pipes { + use wgpu::BufferBindingType::{Storage, Uniform}; + let (ro, rw) = (Storage { read_only: true }, Storage { read_only: false }); + let layout = + |entries: &[wgpu::BindGroupLayoutEntry]| d.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries }); + let matching_layout = layout(&[entry(0, Uniform), entry(1, ro), entry(2, ro), entry(3, rw)]); + let collab_layout = layout(&[entry(0, Uniform), entry(1, ro), entry(2, ro), entry(3, ro), entry(4, ro), entry(5, rw), entry(6, rw)]); + let agg_layout = layout(&[entry(0, Uniform), entry(1, ro), entry(2, ro), entry(3, ro), entry(4, ro), entry(5, ro), entry(6, rw)]); + let common = include_str!("wgsl/bm3d_common.wgsl"); + let transform = include_str!("wgsl/bm3d_transform.wgsl"); + // the group's transforms, for the noisy blocks (`buf`) and for the pilot's (`pb`) + let collab_source = format!( + "{}\n{}\n{}", + transform.replace("{{A}}", "buf").replace("{{S}}", ""), + transform.replace("{{A}}", "pb").replace("{{S}}", "_p"), + include_str!("wgsl/bm3d_collab.wgsl") + ); + let mut built = Vec::new(); + let mut make = |name: &str, kernel: &str, layout: &wgpu::BindGroupLayout| { + let started = std::time::Instant::now(); + let p = pipeline(d, name, &format!("{common}\n{kernel}"), layout); + built.push((name.to_string(), started.elapsed().as_secs_f64() * 1000.0)); + p + }; + let matching = make("bm3d match", include_str!("wgsl/bm3d_match.wgsl"), &matching_layout); + let collab = make("bm3d filter", &collab_source, &collab_layout); + let agg = make("bm3d put back", include_str!("wgsl/bm3d_agg.wgsl"), &agg_layout); + Pipes { matching, matching_layout, collab, collab_layout, agg, agg_layout, built } +} + +/// One tile's buffers and bind groups. +struct Workspace { + y: wgpu::Buffer, + basic: wgpu::Buffer, + out: wgpu::Buffer, + /// The two steps' uniforms (their match tolerance and the filter they use differ). + first: wgpu::Buffer, + second: wgpu::Buffer, + staging: wgpu::Buffer, + /// Match, filter and put back, for the first step then the second. + bound: [wgpu::BindGroup; 6], + _slots: [wgpu::Buffer; 3], +} + +/// The filter on the GPU for one tile size and one set of parameters. Cheap to share between threads: each call takes a +/// free workspace. +pub struct Bm3dGpu { + dev: &'static Dev, + pipes: Pipes, + /// The parameters it was made for, as they were given. + requested: Params, + t: usize, + /// Blocks that start a group, along a side, and how many blocks fit along a side. + nr: usize, + nb: usize, + consts: wgpu::Buffer, + free: Mutex>, + /// Workspaces made so far (they are made when a call finds none free, up to [`WORKSPACES`]). + made: Mutex, + wake: Condvar, +} + +/// An error for something the kernels do not do, with `why` as its text. +fn unsupported(why: impl Into) -> Result { + Err(why.into()) +} + +impl Bm3dGpu { + /// The filter with `params` for tiles of `t × t` cells on the GPU, or why it cannot be (no GPU, parameters or a size + /// the kernels do not do, the device refusing the buffers). Creates the device on first use and compiles the kernels. + pub fn new(params: &Params, t: usize) -> Result { + let _work = crate::exit::enter().ok_or(CLOSING)?; + let Some(plan) = bm3d::plan(params, t, 0.0) else { return unsupported("the tile is smaller than a block") }; + let p = plan.params; + if p.block != BLOCK || p.group > GROUP || p.step == 0 { + return unsupported(format!("the kernels do {BLOCK} x {BLOCK} blocks in groups of at most {GROUP}")); + } + if t > MAX_TILE { + return unsupported(format!("tiles of more than {MAX_TILE} cells on a side are not done on the GPU")); + } + let d = dev()?; + let nb = t + 1 - BLOCK; + let axis = bm3d::starts(nb, p.step); + let nr = axis.len(); + let blocks_bytes = (nr * nr * 4 * GROUP * BLOCK * BLOCK * 4) as u64; + if blocks_bytes > d.limits.max_storage_buffer_binding_size.min(d.limits.max_buffer_size) { + return unsupported(format!("{} cannot hold a tile's filtered blocks ({} MB)", d.info.name, blocks_bytes >> 20)); + } + let (dct, window) = bm3d::constants(BLOCK); + let consts: Vec = dct.iter().chain(&window).map(|v| v.to_bits()).chain(axis.iter().map(|&a| a as u32)).collect(); + let scope = [ + d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory), + d.device.push_error_scope(wgpu::ErrorFilter::Validation), + d.device.push_error_scope(wgpu::ErrorFilter::Internal), + ]; + // the driver compiles the kernels here: a crash in it is reported at the next launch (issue #250) + let pipes = crate::backend::with_marker("denoise kernel compilation", || build_pipes(d)); + let consts = d.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("bm3d consts"), + contents: bytemuck::cast_slice(&consts), + usage: wgpu::BufferUsages::STORAGE, + }); + let mut me = + Bm3dGpu { dev: d, pipes, requested: *params, t, nr, nb, consts, free: Mutex::new(Vec::new()), made: Mutex::new(1), wake: Condvar::new() }; + let first = me.workspace(); + me.free = Mutex::new(vec![first]); + let [oom, validation, internal] = scope; + let errors = [pollster::block_on(internal.pop()), pollster::block_on(validation.pop()), pollster::block_on(oom.pop())]; + if let Some(e) = errors.into_iter().flatten().next() { + return Err(format!("{}: the denoise kernels could not be set up ({e})", d.info.name)); + } + Ok(me) + } + + /// The adapter this runs on. + pub fn adapter(&self) -> String { + format!("{} ({:?})", self.dev.info.name, self.dev.info.backend) + } + + /// The parameters it was made for. + pub fn params(&self) -> Params { + self.requested + } + + /// How long each kernel took to build, e.g. `bm3d match: 812 ms`. + pub fn build_report(&self) -> String { + self.pipes.built.iter().map(|(k, ms)| format!("{k}: {ms:.0} ms")).collect::>().join(", ") + } + + /// A new workspace for this runner's tile size: the plane, scratch and staging buffers and the six bind groups. + fn workspace(&self) -> Workspace { + let d = self.dev; + let (t, groups) = (self.t, self.nr * self.nr); + let planes = (4 * t * t * 4) as u64; + let (y, basic, out) = ( + storage(d, "bm3d y", planes, wgpu::BufferUsages::COPY_DST), + storage(d, "bm3d basic", planes, wgpu::BufferUsages::COPY_SRC), + storage(d, "bm3d out", planes, wgpu::BufferUsages::COPY_SRC), + ); + let members = storage(d, "bm3d members", (groups * (GROUP + 1) * 4) as u64, wgpu::BufferUsages::empty()); + let blocks = storage(d, "bm3d blocks", (groups * 4 * GROUP * BLOCK * BLOCK * 4) as u64, wgpu::BufferUsages::empty()); + let weights = storage(d, "bm3d weights", (groups * 4 * 4) as u64, wgpu::BufferUsages::empty()); + let uniform = |label| { + d.device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }) + }; + let (first, second) = (uniform("bm3d first step"), uniform("bm3d second step")); + let staging = d.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("bm3d readback"), + size: planes, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let bind = |layout: &wgpu::BindGroupLayout, buffers: &[&wgpu::Buffer]| { + let entries: Vec = + buffers.iter().enumerate().map(|(i, b)| wgpu::BindGroupEntry { binding: i as u32, resource: b.as_entire_binding() }).collect(); + d.device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout, entries: &entries }) + }; + let (m, c, a) = (&self.pipes.matching_layout, &self.pipes.collab_layout, &self.pipes.agg_layout); + let k = &self.consts; + let bound = [ + bind(m, &[&first, k, &y, &members]), + // the first step's filter has no pilot: it is given a buffer it does not read + bind(c, &[&first, k, &y, &basic, &members, &blocks, &weights]), + bind(a, &[&first, k, &y, &members, &blocks, &weights, &basic]), + bind(m, &[&second, k, &basic, &members]), + bind(c, &[&second, k, &y, &basic, &members, &blocks, &weights]), + bind(a, &[&second, k, &y, &members, &blocks, &weights, &out]), + ]; + Workspace { y, basic, out, first, second, staging, bound, _slots: [members, blocks, weights] } + } + + /// A free workspace, a new one when fewer than [`WORKSPACES`] exist, else wait for one to come back. + fn take(&self) -> Result { + let mut free = self.free.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(w) = free.pop() { + return Ok(w); + } + { + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + if *made < WORKSPACES { + *made += 1; + drop(made); + drop(free); + let d = self.dev; + let scopes = + [d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory), d.device.push_error_scope(wgpu::ErrorFilter::Validation)]; + let w = self.workspace(); + let [oom, validation] = scopes; + let (validation, oom) = (pollster::block_on(validation.pop()), pollster::block_on(oom.pop())); + if let Some(e) = oom.or(validation) { + self.forget(); + return Err(Error::Runtime(format!("the GPU could not make room for another tile: {e}"))); + } + return Ok(w); + } + } + free = self.wake.wait(free).unwrap_or_else(|e| e.into_inner()); + } + } + + /// A workspace comes back after a good run: it goes on the free list and one waiting caller is woken. + fn give(&self, w: Workspace) { + self.free.lock().unwrap_or_else(|e| e.into_inner()).push(w); + self.wake.notify_one(); + } + + /// A workspace is gone (dropped after a failure): room for a new one, and a waiting caller may make it. + fn forget(&self) { + // under `free`, as `take` is when it reads `made` and goes to wait: a wake-up sent between the two would be lost + let free = self.free.lock().unwrap_or_else(|e| e.into_inner()); + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + *made = made.saturating_sub(1); + drop(made); + drop(free); + self.wake.notify_one(); + } + + /// Denoise four unit-noise planes of `t × t` cells as [`bm3d::filter`] does; `noise` as there. + pub fn filter(&self, planes: &[Vec], t: usize, noise: f32) -> Result>, Error> { + if let Some(why) = crate::nn::broken_reason() { + return Err(Error::Runtime(format!("the GPU is not used any more: {why}"))); + } + let Some(plan) = bm3d::plan(&self.requested, t, noise).filter(|_| t == self.t) else { + return Err(Error::Input("the tile is not the size the filter was made for".into())); + }; + if planes.len() != 4 || planes.iter().any(|p| p.len() != t * t) { + return Err(Error::Input("the tile is not four square planes".into())); + } + let y = hadamard(planes); + // one tile is one piece of GPU work: a photo's worth would outlast any wait at exit + let Some(_work) = crate::exit::enter() else { return Err(Error::Runtime(CLOSING.into())) }; + let w = self.take()?; + let flat: Vec = y.concat(); + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.execute(&w, &flat, &plan))) { + Ok(Ok(out)) => { + self.give(w); + Ok(hadamard(&out.chunks_exact(t * t).map(<[f32]>::to_vec).collect::>())) + } + Ok(Err(e)) => { + // its readback buffer may be left half-mapped: a fresh workspace is made when one is next needed + drop(w); + self.forget(); + Err(e) + } + Err(_) => { + // a panic inside wgpu: this workspace is not given back, and the GPU is not used again + mark_broken("a denoise tile panicked"); + drop(w); + self.forget(); + Err(Error::Runtime("the GPU runner gave up".into())) + } + } + } + + /// Run the filter's steps in `w` on the rotated planes `y` (one plane after another) and read the result back; a + /// device that runs out of memory or fails validation gives an error. + fn execute(&self, w: &Workspace, y: &[f32], plan: &bm3d::Plan) -> Result, Error> { + let d = self.dev; + let p = &plan.params; + let sigma = p.sigma.max(1e-3); + let var = sigma * sigma; + let uniforms = |tau: f32, wiener: u32| Uniforms { + t: self.t as u32, + nr: self.nr as u32, + nb: self.nb as u32, + search: p.search as u32, + cap: p.group as u32, + wiener, + pad0: 0, + pad1: 0, + tau, + lambda: plan.lambda * sigma, + sigma, + pad2: 0.0, + }; + let groups = (self.nr * self.nr) as u32; + let cells = (self.t * self.t) as u32; + let scopes = [ + d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory), + d.device.push_error_scope(wgpu::ErrorFilter::Validation), + d.device.push_error_scope(wgpu::ErrorFilter::Internal), + ]; + d.queue.write_buffer(&w.y, 0, bytemuck::cast_slice(y)); + d.queue.write_buffer(&w.first, 0, bytemuck::bytes_of(&uniforms(p.tau1 * var, 0))); + d.queue.write_buffer(&w.second, 0, bytemuck::bytes_of(&uniforms(p.tau2 * var, 1))); + let mut enc = d.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); + { + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("bm3d tile"), timestamp_writes: None }); + let steps = if p.wiener { 2 } else { 1 }; + for step in 0..steps { + for (i, (pipe, count)) in + [(&self.pipes.matching, groups), (&self.pipes.collab, groups * 4), (&self.pipes.agg, cells)].into_iter().enumerate() + { + pass.set_pipeline(pipe); + pass.set_bind_group(0, w.bound.get(step * 3 + i), &[]); + pass.dispatch_workgroups(count.div_ceil(WORKGROUP), 1, 1); + } + } + } + let result = if p.wiener { &w.out } else { &w.basic }; + let bytes = (y.len() * 4) as u64; + enc.copy_buffer_to_buffer(result, 0, &w.staging, 0, bytes); + d.queue.submit([enc.finish()]); + let slice = w.staging.slice(..bytes); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |r| { + let _ = tx.send(r); + }); + let waited = d.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(TIMEOUT) }); + let [oom, validation, internal] = scopes; + let errors = [pollster::block_on(internal.pop()), pollster::block_on(validation.pop()), pollster::block_on(oom.pop())]; + let [internal, validation, oom] = errors; + if let Some(e) = oom { + // not a broken device: this tile runs on the CPU, and the next may fit + return Err(Error::Runtime(format!("the GPU ran out of memory: {e}"))); + } + if let Some(e) = internal.or(validation) { + mark_broken(&format!("device error: {e}")); + return Err(Error::Runtime(format!("the GPU reported an error: {e}"))); + } + if let Err(e) = waited { + mark_broken(&format!("the GPU did not finish a tile: {e}")); + return Err(Error::Runtime(format!("the GPU did not finish: {e}"))); + } + match rx.recv_timeout(Duration::from_secs(10)) { + Ok(Ok(())) => {} + Ok(Err(e)) => return Err(Error::Runtime(format!("reading the result back failed: {e}"))), + Err(e) => return Err(Error::Runtime(format!("reading the result back failed: {e}"))), + } + let out = { + let data = slice.get_mapped_range().map_err(|e| Error::Runtime(format!("reading the result back failed: {e:?}")))?; + data.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect::>() + }; + w.staging.unmap(); + Ok(out) + } +} + +/// The built-in denoiser with its filter on the GPU: a [`TileRunner`] for one photo (its noise level is in `builtin`). +pub struct BuiltinRunner { + gpu: Arc, + builtin: Builtin, +} + +/// How close the card's filter is to the processor's on a tile, in the noise's deviations (the filter's own domain, where +/// the noise has deviation 1): the largest difference at one place and the mean one. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Agreement { + pub worst: f32, + pub mean: f32, +} + +impl BuiltinRunner { + /// `builtin` must use the block-matching filter with the parameters `gpu` was made for. + pub fn new(gpu: Arc, builtin: Builtin) -> Result { + match builtin.bm3d_params() { + Some(p) if p == gpu.params() => Ok(BuiltinRunner { gpu, builtin }), + _ => Err("the settings of the built-in denoiser are not the ones the graphics card was set up for".into()), + } + } + + /// The adapter it runs on. + pub fn adapter(&self) -> String { + self.gpu.adapter() + } + + /// Run the filter of the tile `input` on the card and on the processor and say how far apart they are. The two + /// differ by the rounding of the card's arithmetic: a few blocks whose match or threshold falls either side of a + /// tie change a little (well under half a deviation), and a broken kernel by far more. (The final picture is not + /// compared: the demosaic's choice of direction at a pixel can flip on a tiny difference.) + pub fn agreement(&self, input: &[f32]) -> Result { + let seen = std::cell::Cell::new(None); + self.builtin.run_with(input, &|planes, t, noise| { + let want = bm3d::filter(planes, t, &self.gpu.params(), noise); + let got = self.gpu.filter(planes, t, noise)?; + let (mut worst, mut sum, mut n) = (0f32, 0f64, 0usize); + for (a, b) in want.iter().flatten().zip(got.iter().flatten()) { + let d = (a - b).abs(); + worst = if d.is_nan() { f32::INFINITY } else { worst.max(d) }; + sum += f64::from(d); + n += 1; + } + seen.set(Some(Agreement { worst, mean: (sum / n.max(1) as f64) as f32 })); + Ok(got) + })?; + seen.get().ok_or_else(|| Error::Runtime("the filter was not run".into())) + } +} + +impl TileRunner for BuiltinRunner { + /// Clean one tile with the built-in pipeline, its block-matching filter running on the card. + fn run(&self, input: &[f32]) -> Result, Error> { + self.builtin.run_with(input, &|planes, t, noise| self.gpu.filter(planes, t, noise)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Four planes of `t × t` cells: edges, a ramp and some texture, plus unit noise (an LCG and Box-Muller). + fn scene(t: usize, seed: u64) -> Vec> { + let mut state = seed; + let mut uniform = move || { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((state >> 40) as f32 + 0.5) / (1u64 << 24) as f32 + }; + (0..4) + .map(|c| { + (0..t * t) + .map(|i| { + let (x, y) = ((i % t) as f32, (i / t) as f32); + let signal = 20.0 + + 0.1 * x + + if (x as usize / 17 + y as usize / 23).is_multiple_of(2) { 6.0 } else { 0.0 } + + 2.0 * ((x + 3.0 * c as f32) * 0.9).sin(); + let (u, v) = (uniform(), uniform()); + signal + (-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos() + }) + .collect() + }) + .collect() + } + + /// The filter on the GPU, or `None` (with a note) on a machine with no usable GPU. + fn gpu(p: &Params, t: usize) -> Option { + match Bm3dGpu::new(p, t) { + Ok(g) => Some(g), + Err(e) => { + lightcraft_testkit::skip!(Gpu, "no GPU runner here ({e})"); + None + } + } + } + + /// The largest and the mean difference between two sets of planes. + fn differ(a: &[Vec], b: &[Vec]) -> (f32, f32) { + let (mut worst, mut sum, mut n) = (0f32, 0f64, 0usize); + for (x, y) in a.iter().flatten().zip(b.iter().flatten()) { + worst = worst.max((x - y).abs()); + sum += f64::from((x - y).abs()); + n += 1; + } + (worst, (sum / n.max(1) as f64) as f32) + } + + /// At four tile sizes the card's result is finite and within 0.1 noise deviations of the processor's at worst, and + /// 1e-3 on average. + #[test] + fn the_gpu_gives_what_the_cpu_gives() { + let p = Params::default(); + for (t, seed, noise) in [(32usize, 1u64, 0.003f32), (64, 2, 0.01), (100, 3, 0.04), (256, 4, 0.02)] { + let Some(g) = gpu(&p, t) else { return }; + let planes = scene(t, seed); + let want = bm3d::filter(&planes, t, &p, noise); + let got = g.filter(&planes, t, noise).unwrap(); + let (worst, mean) = differ(&got, &want); + eprintln!("{}: tile {t}, noise {noise}: worst {worst:e}, mean {mean:e} (noise deviation 1); {}", g.adapter(), g.build_report()); + assert!(got.iter().flatten().all(|v| v.is_finite())); + assert!(mean < 1e-3 && worst < 0.1, "tile {t}: the GPU is off by {worst:e} at most and {mean:e} on average"); + } + } + + /// `forget` must change `made` under the `free` lock: a waiting `take` holds it from reading `made` until it sleeps, so + /// a slot given up in between cannot be announced to nobody (the waiter would sleep on a free slot for good). + #[test] + fn forgetting_a_workspace_waits_for_a_taker_that_is_about_to_sleep() { + let Some(g) = gpu(&Params::default(), 32) else { return }; + let g = Arc::new(g); + let before = *g.made.lock().unwrap(); + let held = g.free.lock().unwrap(); + let other = g.clone(); + let forgetter = std::thread::spawn(move || other.forget()); + std::thread::sleep(std::time::Duration::from_millis(200)); + assert_eq!(*g.made.lock().unwrap(), before, "forget changed the count while a taker held the free list"); + drop(held); + forgetter.join().unwrap(); + assert_eq!(*g.made.lock().unwrap(), before.saturating_sub(1)); + } + + /// One runner shared by four threads, each filtering several tiles, agrees with the processor on every one. + #[test] + fn a_runner_is_reusable_and_shared_between_threads() { + let p = Params::default(); + let t = 48; + let Some(g) = gpu(&p, t) else { return }; + let g = Arc::new(g); + let handles: Vec<_> = (0..4u64) + .map(|k| { + let g = g.clone(); + std::thread::spawn(move || { + for round in 0..3 { + let planes = scene(t, 10 + k * 7 + round); + let want = bm3d::filter(&planes, t, &Params::default(), 0.01); + let got = g.filter(&planes, t, 0.01).unwrap(); + let (worst, mean) = differ(&got, &want); + assert!(mean < 1e-3 && worst < 0.1, "thread {k}, round {round}: off by {worst:e} / {mean:e}"); + } + }) + }) + .collect(); + for h in handles { + h.join().unwrap(); + } + } + + /// Block or group sizes the kernels are not written for, and tiles too small or too big, are errors; so are a tile + /// or planes of the wrong size. NaN input does not panic, and a flat tile stays flat. + #[test] + fn what_the_kernels_do_not_do_is_an_error_and_odd_inputs_never_panic() { + // not the block or group size the kernels are written for, or too big a tile + assert!(Bm3dGpu::new(&Params { block: 6, ..Params::default() }, 64).is_err()); + assert!(Bm3dGpu::new(&Params { group: 32, ..Params::default() }, 64).is_err()); + assert!(Bm3dGpu::new(&Params::default(), 2).is_err()); + assert!(Bm3dGpu::new(&Params::default(), 4096).is_err()); + let Some(g) = gpu(&Params::default(), 32) else { return }; + // a tile of another size, planes of the wrong size, numbers that are not finite + assert!(g.filter(&scene(40, 1), 40, 0.5).is_err()); + assert!(g.filter(&scene(32, 1).into_iter().take(3).collect::>(), 32, 0.5).is_err()); + let nan = vec![vec![f32::NAN; 32 * 32]; 4]; + let _ = g.filter(&nan, 32, f32::NAN); + let flat = vec![vec![5.0f32; 32 * 32]; 4]; + let out = g.filter(&flat, 32, 0.5).unwrap(); + assert!(out.iter().flatten().all(|v| (v - 5.0).abs() < 1e-3)); + } +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 8863b45a04..342fe039d0 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -31,6 +31,8 @@ use lightcraft_raster::Rgb32f; #[cfg(not(target_arch = "wasm32"))] pub mod backend; +#[cfg(all(feature = "denoise", not(target_arch = "wasm32")))] +pub mod bm3d; #[cfg(not(target_arch = "wasm32"))] mod ctx; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/gpu/src/nn.rs b/crates/gpu/src/nn.rs index 334a663919..cca52177fc 100644 --- a/crates/gpu/src/nn.rs +++ b/crates/gpu/src/nn.rs @@ -22,7 +22,7 @@ use lightcraft_denoise::run::{Error, TileRunner}; use wgpu::util::DeviceExt; /// Longest wait for one tile's GPU work before the device is given up on. -const TIMEOUT: Duration = Duration::from_secs(60); +pub(crate) const TIMEOUT: Duration = Duration::from_secs(60); /// The largest tile side (in input cells) the dispatch sizes and 32-bit indexing are checked for. const MAX_TILE: usize = 1024; /// The largest single buffer used: indices in the kernels are 32-bit element offsets. @@ -33,18 +33,18 @@ const WORKSPACES: usize = 2; // --------------------------------------------------------------------------------------------------------------------- // the device -struct Dev { - device: wgpu::Device, - queue: wgpu::Queue, - info: wgpu::AdapterInfo, - limits: wgpu::Limits, +pub(crate) struct Dev { + pub(crate) device: wgpu::Device, + pub(crate) queue: wgpu::Queue, + pub(crate) info: wgpu::AdapterInfo, + pub(crate) limits: wgpu::Limits, } static DEV: OnceLock> = OnceLock::new(); static BROKEN: AtomicBool = AtomicBool::new(false); static BROKEN_WHY: Mutex> = Mutex::new(None); -fn mark_broken(why: &str) { +pub(crate) fn mark_broken(why: &str) { let mut w = BROKEN_WHY.lock().unwrap_or_else(|e| e.into_inner()); if w.is_none() { *w = Some(why.to_string()); @@ -57,7 +57,7 @@ pub fn broken_reason() -> Option { BROKEN.load(Ordering::Relaxed).then(|| BROKEN_WHY.lock().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_else(|| "device error".into())) } -fn dev() -> Result<&'static Dev, String> { +pub(crate) fn dev() -> Result<&'static Dev, String> { if let Some(why) = broken_reason() { return Err(format!("stopped after a GPU failure: {why}")); } @@ -73,7 +73,7 @@ fn dev() -> Result<&'static Dev, String> { } /// Why nothing runs on the GPU once [`crate::begin_shutdown`] was called. -const CLOSING: &str = "LightCraft is closing"; +pub(crate) const CLOSING: &str = "LightCraft is closing"; fn create_device() -> Result { let Some(backends) = crate::backend::compute_backends() else { return Err("disabled by LIGHTCRAFT_GPU_BACKEND=off".into()) }; @@ -480,7 +480,7 @@ struct Pipelines { built: Vec<(String, f64)>, } -fn entry(binding: u32, ty: wgpu::BufferBindingType) -> wgpu::BindGroupLayoutEntry { +pub(crate) fn entry(binding: u32, ty: wgpu::BufferBindingType) -> wgpu::BindGroupLayoutEntry { wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, @@ -489,7 +489,7 @@ fn entry(binding: u32, ty: wgpu::BufferBindingType) -> wgpu::BindGroupLayoutEntr } } -fn pipeline(d: &Dev, label: &str, src: &str, layout: &wgpu::BindGroupLayout) -> wgpu::ComputePipeline { +pub(crate) fn pipeline(d: &Dev, label: &str, src: &str, layout: &wgpu::BindGroupLayout) -> wgpu::ComputePipeline { let module = d.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(src.into()) }); let pl = d.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(layout)], immediate_size: 0 }); d.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { @@ -574,7 +574,7 @@ struct Shared { dummy: wgpu::Buffer, } -fn storage(d: &Dev, label: &str, bytes: u64, extra: wgpu::BufferUsages) -> wgpu::Buffer { +pub(crate) fn storage(d: &Dev, label: &str, bytes: u64, extra: wgpu::BufferUsages) -> wgpu::Buffer { d.device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: bytes.max(16), diff --git a/crates/gpu/src/wgsl/bm3d_agg.wgsl b/crates/gpu/src/wgsl/bm3d_agg.wgsl new file mode 100644 index 0000000000..41c012bdfe --- /dev/null +++ b/crates/gpu/src/wgsl/bm3d_agg.wgsl @@ -0,0 +1,86 @@ +// Putting the filtered blocks back: every cell becomes the weighted average of the filtered blocks that cover it, added +// in the order the reference adds them (groups in raster order, a group's blocks in order), so no two invocations +// write the same cell. One invocation per cell, all four planes. + +@group(0) @binding(2) var y: array; +@group(0) @binding(3) var members: array; +@group(0) @binding(4) var blocks: array; +@group(0) @binding(5) var weights: array; +@group(0) @binding(6) var dst: array; + +// The first group start that is at least `v`. +fn lower_bound(v: u32) -> u32 { + var lo = 0u; + var hi = p.nr; + while (lo < hi) { + let mid = (lo + hi) / 2u; + if (axis(mid) < v) { + lo = mid + 1u; + } else { + hi = mid; + } + } + return lo; +} + +@compute @workgroup_size(64) +fn main(@builtin(global_invocation_id) gid: vec3) { + let g = gid.x; + let t = p.t; + if (g >= t * t) { + return; + } + let cx = g % t; + let cy = g / t; + // a group's blocks lie within `search` of its start and are N wide: only these starts can reach this cell + let reach = p.search + N - 1u; + var xlo = 0u; + if (cx >= reach) { + xlo = cx - reach; + } + var ylo = 0u; + if (cy >= reach) { + ylo = cy - reach; + } + var num: array; + var den: array; + for (var ch = 0u; ch < 4u; ch = ch + 1u) { + num[ch] = 0.0; + den[ch] = 0.0; + } + for (var rj = lower_bound(ylo); rj < p.nr; rj = rj + 1u) { + if (axis(rj) > cy + p.search) { + break; + } + for (var ri = lower_bound(xlo); ri < p.nr; ri = ri + 1u) { + if (axis(ri) > cx + p.search) { + break; + } + let rf = rj * p.nr + ri; + let m = members[rf * STRIDE]; + for (var i = 0u; i < m; i = i + 1u) { + let pos = members[rf * STRIDE + 1u + i]; + let px = pos % t; + let py = pos / t; + if (px <= cx && cx < px + N && py <= cy && cy < py + N) { + let cell = (cy - py) * N + (cx - px); + let w = win(cell); + for (var ch = 0u; ch < 4u; ch = ch + 1u) { + let ww = weights[rf * 4u + ch] * w; + num[ch] = num[ch] + ww * blocks[((rf * 4u + ch) * K + i) * NN + cell]; + den[ch] = den[ch] + ww; + } + } + } + } + } + // cells no block reached keep their value + for (var ch = 0u; ch < 4u; ch = ch + 1u) { + let own = y[ch * t * t + g]; + if (den[ch] > 0.0) { + dst[ch * t * t + g] = num[ch] / den[ch]; + } else { + dst[ch * t * t + g] = own; + } + } +} diff --git a/crates/gpu/src/wgsl/bm3d_collab.wgsl b/crates/gpu/src/wgsl/bm3d_collab.wgsl new file mode 100644 index 0000000000..8ebd477b59 --- /dev/null +++ b/crates/gpu/src/wgsl/bm3d_collab.wgsl @@ -0,0 +1,76 @@ +// Collaborative filtering of one group of one plane: the blocks are stacked, transformed (a 2-D DCT of each block, a +// Haar transform across the stack), shrunk (a hard threshold, or a Wiener filter built from the pilot) and transformed +// back. One invocation per group and plane; the filtered blocks and the group's weight are stored for the aggregation. +// (The transforms come from bm3d_transform.wgsl: `buf` is the noisy group, `pb` the pilot's.) + +@group(0) @binding(2) var y: array; +@group(0) @binding(3) var pilot: array; +@group(0) @binding(4) var members: array; +@group(0) @binding(5) var blocks: array; +@group(0) @binding(6) var weights: array; + +@compute @workgroup_size(64) +fn main(@builtin(global_invocation_id) gid: vec3) { + let g = gid.x; + if (g >= p.nr * p.nr * 4u) { + return; + } + let rf = g / 4u; + let ch = g % 4u; + let t = p.t; + let m = members[rf * STRIDE]; + for (var i = 0u; i < m; i = i + 1u) { + let pos = members[rf * STRIDE + 1u + i]; + for (var j = 0u; j < N; j = j + 1u) { + for (var c = 0u; c < N; c = c + 1u) { + buf[i * NN + j * N + c] = y[ch * t * t + pos + j * t + c]; + } + } + } + for (var i = 0u; i < m; i = i + 1u) { + dct_fwd(i * NN); + } + haar(m, true); + var weight = 1.0; + if (p.wiener == 0u) { + var kept = 0u; + for (var k = 0u; k < m * NN; k = k + 1u) { + if (abs(buf[k]) < p.lambda) { + buf[k] = 0.0; + } else { + kept = kept + 1u; + } + } + weight = 1.0 / f32(max(kept, 1u)); + } else { + for (var i = 0u; i < m; i = i + 1u) { + let pos = members[rf * STRIDE + 1u + i]; + for (var j = 0u; j < N; j = j + 1u) { + for (var c = 0u; c < N; c = c + 1u) { + pb[i * NN + j * N + c] = pilot[ch * t * t + pos + j * t + c]; + } + } + } + for (var i = 0u; i < m; i = i + 1u) { + dct_fwd_p(i * NN); + } + haar_p(m, true); + var energy = 0.0; + for (var k = 0u; k < m * NN; k = k + 1u) { + let q = pb[k]; + let w = q * q / (q * q + p.sigma * p.sigma); + buf[k] = buf[k] * w; + energy = energy + w * w; + } + weight = 1.0 / max(energy, 1e-3); + } + haar(m, false); + for (var i = 0u; i < m; i = i + 1u) { + dct_inv(i * NN); + } + let base = (rf * 4u + ch) * K * NN; + for (var k = 0u; k < m * NN; k = k + 1u) { + blocks[base + k] = buf[k]; + } + weights[rf * 4u + ch] = weight; +} diff --git a/crates/gpu/src/wgsl/bm3d_common.wgsl b/crates/gpu/src/wgsl/bm3d_common.wgsl new file mode 100644 index 0000000000..0be039eca7 --- /dev/null +++ b/crates/gpu/src/wgsl/bm3d_common.wgsl @@ -0,0 +1,41 @@ +// Block-matching collaborative filtering of one tile: the shared part of the three kernels. The reference is +// crates/denoise-core/src/bm3d.rs (the same steps in the same order, so the two agree to rounding): 4 x 4-cell blocks, +// groups of at most 16, planes of `t x t` cells with 4 planes one after the other. + +struct P { + t: u32, // cells on a side of a plane + nr: u32, // blocks that start a group, along a side + nb: u32, // blocks along a side (t - 3) + search: u32, // how far a match is looked for, in cells + cap: u32, // most blocks in a group (at most 16) + wiener: u32, // 0: hard threshold, 1: Wiener shrinkage by the pilot + pad0: u32, + pad1: u32, + tau: f32, // how far above the noise two blocks may differ (mean square) and be grouped + lambda: f32, // hard threshold (already scaled by the noise's deviation) + sigma: f32, // the noise's deviation + pad2: f32, +} + +@group(0) @binding(0) var p: P; +// [0, 16): the DCT matrix, [16, 32): the window (both f32 bits), [32, ..): where the blocks that start a group are +@group(0) @binding(1) var consts: array; + +const N: u32 = 4u; +const NN: u32 = 16u; +const K: u32 = 16u; +// a group's entry in `members`: its size, then its blocks' top-left cells +const STRIDE: u32 = 17u; +const INV_SQRT2: f32 = 0.70710677; + +fn axis(i: u32) -> u32 { + return consts[32u + i]; +} + +fn dct(i: u32) -> f32 { + return bitcast(consts[i]); +} + +fn win(i: u32) -> f32 { + return bitcast(consts[16u + i]); +} diff --git a/crates/gpu/src/wgsl/bm3d_match.wgsl b/crates/gpu/src/wgsl/bm3d_match.wgsl new file mode 100644 index 0000000000..cee4e18f16 --- /dev/null +++ b/crates/gpu/src/wgsl/bm3d_match.wgsl @@ -0,0 +1,79 @@ +// Grouping: for every block that starts a group, its nearest blocks (itself first) within the search window, nearest +// first, at most `cap` and at most `tau` away, cut to a power of two. One invocation per group. + +@group(0) @binding(2) var src: array; +@group(0) @binding(3) var members: array; + +@compute @workgroup_size(64) +fn main(@builtin(global_invocation_id) gid: vec3) { + let g = gid.x; + if (g >= p.nr * p.nr) { + return; + } + let t = p.t; + let rx = axis(g % p.nr); + let ry = axis(g / p.nr); + var dist: array; + var pos: array; + var len = 1u; + dist[0] = 0.0; + pos[0] = ry * t + rx; + let r = i32(p.search); + let nb = i32(p.nb); + for (var oy = -r; oy <= r; oy = oy + 1) { + let by = i32(ry) + oy; + if (by < 0 || by >= nb) { + continue; + } + for (var ox = -r; ox <= r; ox = ox + 1) { + if (ox == 0 && oy == 0) { + continue; + } + let bx = i32(rx) + ox; + if (bx < 0 || bx >= nb) { + continue; + } + // the sum of squared differences, along each row and then down the rows, as the reference adds them + var s = 0.0; + for (var j = 0u; j < N; j = j + 1u) { + var h = 0.0; + let a0 = (ry + j) * t + rx; + let b0 = (u32(by) + j) * t + u32(bx); + for (var i = 0u; i < N; i = i + 1u) { + let d = src[a0 + i] - src[b0 + i]; + h = h + d * d; + } + s = s + h; + } + s = s * 0.0625; + if (!(s <= p.tau)) { + continue; + } + if (len >= p.cap && s >= dist[len - 1u]) { + continue; + } + // after every block at most as far away, as the reference's ordered insert does + var at = 0u; + while (at < len && dist[at] <= s) { + at = at + 1u; + } + var k = len; + while (k > at) { + dist[k] = dist[k - 1u]; + pos[k] = pos[k - 1u]; + k = k - 1u; + } + dist[at] = s; + pos[at] = u32(by) * t + u32(bx); + len = min(len + 1u, p.cap); + } + } + var m = 1u; + while (m * 2u <= len) { + m = m * 2u; + } + members[g * STRIDE] = m; + for (var i = 0u; i < m; i = i + 1u) { + members[g * STRIDE + 1u + i] = pos[i]; + } +} diff --git a/crates/gpu/src/wgsl/bm3d_transform.wgsl b/crates/gpu/src/wgsl/bm3d_transform.wgsl new file mode 100644 index 0000000000..59aa48416e --- /dev/null +++ b/crates/gpu/src/wgsl/bm3d_transform.wgsl @@ -0,0 +1,97 @@ +// The transforms of one group, on the module-scope array `{{A}}` (the shader is built once for the noisy blocks and once +// for the pilot's). The arrays are not passed to functions: FXC (DX12) cannot index an array it is handed by reference +// without unrolling every loop. + +var {{A}}: array; + +fn dct_fwd{{S}}(base: u32) { + var tmp: array; + for (var k = 0u; k < N; k = k + 1u) { + for (var j = 0u; j < N; j = j + 1u) { + var s = 0.0; + for (var i = 0u; i < N; i = i + 1u) { + s = s + dct(k * N + i) * {{A}}[base + i * N + j]; + } + tmp[k * N + j] = s; + } + } + for (var k = 0u; k < N; k = k + 1u) { + for (var l = 0u; l < N; l = l + 1u) { + var s = 0.0; + for (var j = 0u; j < N; j = j + 1u) { + s = s + tmp[k * N + j] * dct(l * N + j); + } + {{A}}[base + k * N + l] = s; + } + } +} + +fn dct_inv{{S}}(base: u32) { + var tmp: array; + for (var i = 0u; i < N; i = i + 1u) { + for (var l = 0u; l < N; l = l + 1u) { + var s = 0.0; + for (var k = 0u; k < N; k = k + 1u) { + s = s + dct(k * N + i) * {{A}}[base + k * N + l]; + } + tmp[i * N + l] = s; + } + } + for (var i = 0u; i < N; i = i + 1u) { + for (var j = 0u; j < N; j = j + 1u) { + var s = 0.0; + for (var l = 0u; l < N; l = l + 1u) { + s = s + tmp[i * N + l] * dct(l * N + j); + } + {{A}}[base + i * N + j] = s; + } + } +} + +// The Haar transform across the `m` blocks (m is a power of two), at each of the 16 positions of a block. +fn haar{{S}}(m: u32, forward: bool) { + if (m < 2u) { + return; + } + var col: array; + var tmp: array; + for (var k = 0u; k < NN; k = k + 1u) { + for (var i = 0u; i < m; i = i + 1u) { + col[i] = {{A}}[i * NN + k]; + } + if (forward) { + var len = m; + while (len > 1u) { + let half = len / 2u; + for (var i = 0u; i < half; i = i + 1u) { + let a = col[2u * i]; + let c = col[2u * i + 1u]; + tmp[i] = (a + c) * INV_SQRT2; + tmp[half + i] = (a - c) * INV_SQRT2; + } + for (var i = 0u; i < len; i = i + 1u) { + col[i] = tmp[i]; + } + len = half; + } + } else { + var len = 2u; + while (len <= m) { + let half = len / 2u; + for (var i = 0u; i < half; i = i + 1u) { + let avg = col[i]; + let det = col[half + i]; + tmp[2u * i] = (avg + det) * INV_SQRT2; + tmp[2u * i + 1u] = (avg - det) * INV_SQRT2; + } + for (var i = 0u; i < len; i = i + 1u) { + col[i] = tmp[i]; + } + len = len * 2u; + } + } + for (var i = 0u; i < m; i = i + 1u) { + {{A}}[i * NN + k] = col[i]; + } + } +} diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 7a21768de1..a85f96177b 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -53,7 +53,8 @@ fn check_v3_luminance_cutoff(chroma: f32, pixel: [f32; 3], expected: [u8; 4]) { 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])); + // (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]); } diff --git a/crates/gpu/tests/mask_geometry.rs b/crates/gpu/tests/mask_geometry.rs index 1cbd741a0e..c4dfdf842d 100644 --- a/crates/gpu/tests/mask_geometry.rs +++ b/crates/gpu/tests/mask_geometry.rs @@ -108,6 +108,11 @@ fn luma(img: &Rgba8, i: usize) -> f64 { (p[0] as f64 + p[1] as f64 + p[2] as f64) / 3.0 } +/// 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() { @@ -140,9 +145,9 @@ fn masks_stay_on_the_content_under_every_geometry_change_on_the_gpu() { 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))); + let mark = centroid(plain.width, (0..plain.data.len()).map(|i| above_dither(luma(&plain, i) - luma(&bare, i)))); 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 at = centroid(m.width, (0..m.data.len()).map(|i| above_dither(luma(&m, i) - luma(&plain, i)))); 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/meta/src/exif.rs b/crates/meta/src/exif.rs index 259fc5f9f3..9894f016ba 100644 --- a/crates/meta/src/exif.rs +++ b/crates/meta/src/exif.rs @@ -46,6 +46,14 @@ fn pos(v: Option) -> Option { v.filter(|x| x.is_finite() && *x > 0.0) } +/// The orientation the Exif's own first IFD states. [`from_tiff`] also reports one that only the XMP packet in +/// the Exif's tag 700 states; LightCraft displays a photo by the Exif's alone, so that one can't tell how a photo +/// is stored. +pub(crate) fn ifd0_orientation(bytes: &[u8]) -> Option { + let tiff = Tiff::parse_with(strip_exif_header(bytes), &ParseOptions::default()).ok()?; + tiff.ifds.first().and_then(|i| i.u16(t::ORIENTATION)).filter(|v| (1..=8).contains(v)).map(Orientation::from_exif) +} + /// Build [`Metadata`] from a parsed TIFF stream (IFD0 + Exif + GPS; DNG tags as fallbacks). pub fn from_tiff(tiff: &Tiff) -> Metadata { let ifd0 = tiff.ifds.first(); @@ -129,8 +137,11 @@ pub fn from_tiff(tiff: &Tiff) -> Metadata { if let Some(x) = ifd0.and_then(|i| i.bytes(t::XMP)).map(String::from_utf8_lossy) && let Ok(x) = crate::parse_xmp(&x) { + // (the size stays the one Exif states: `extract` turns regions by it, and a size only the XMP states may be the upright one) + let size = (m.width, m.height); m.overlay_user_fields(&x.metadata); m.fill_missing(&x.metadata); + (m.width, m.height) = size; } m } diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index c238fcda6f..7c7d9d1ce9 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -296,7 +296,7 @@ impl Metadata { pub fn extract(bytes: &[u8]) -> Metadata { let e = embedded(bytes); let exif = e.exif.as_deref().map(read_exif).unwrap_or_default(); - let xmp = e.xmp.as_deref().and_then(|xmp| parse_xmp(xmp).ok()).map(|xmp| xmp.metadata); + let xmp = e.xmp.as_deref().and_then(|xmp| parse_xmp(xmp).ok()); extract_embedded(e, exif, xmp) } @@ -311,24 +311,51 @@ pub fn try_extract(bytes: &[u8]) -> Result { None => Metadata::default(), }; let xmp = match e.xmp.as_deref() { - Some(xmp) if is_psd => Some(parse_xmp(xmp).map_err(|_| ExtractError::MalformedPsd)?.metadata), - Some(xmp) => parse_xmp(xmp).ok().map(|xmp| xmp.metadata), + Some(xmp) if is_psd => Some(parse_xmp(xmp).map_err(|_| ExtractError::MalformedPsd)?), + Some(xmp) => parse_xmp(xmp).ok(), None => None, }; Ok(extract_embedded(e, exif, xmp)) } -fn extract_embedded(e: Embedded, mut m: Metadata, xmp: Option) -> Metadata { +fn extract_embedded(e: Embedded, mut m: Metadata, xmp: Option) -> Metadata { + // the size the Exif states: a size only the XMP states may be the upright one, so it can't tell how the photo is stored + let stored = m.width.zip(m.height); + // and the orientation the Exif states: the photo is displayed by that alone, so an orientation only the XMP + // states ([`Metadata::fill_missing`] reports it below) can't tell how the photo is stored either + let exif_orientation = e.exif.as_deref().and_then(exif::ifd0_orientation); if let Some(i) = e.iptc.as_deref() { m.fill_missing(&parse_iptc(i)); } if let Some(xmp) = xmp { - m.overlay_user_fields(&xmp); - m.fill_missing(&xmp); + m.overlay_user_fields(&xmp.metadata); + m.fill_missing(&xmp.metadata); + // boxes another app drew on the photo as stored go where the upright photo has them (#2674) + if let (Some(drawn_on), Some(orientation), Some(stored)) = (xmp.regions_drawn_on(), exif_orientation, stored) { + upright_regions(&mut m.regions, drawn_on, orientation, stored); + } } m } +/// Turn regions drawn on a photo as it is stored onto the upright photo. MWG gives each box as a fraction of +/// `AppliedToDimensions` (`drawn_on`); for a photo whose Exif `orientation` turns it a quarter turn, some apps give the +/// stored, sideways size there and boxes on the stored pixels to match (Lightroom says so per box with +/// `mwg-rs:Rotation` instead, which [`parse_xmp`] reads). When `drawn_on` has the shape of the photo as stored +/// (`stored`, before `orientation`) rather than the upright one, every box is turned with `orientation`. Returns +/// whether they were. A square photo or `drawn_on` looks the same both ways, and a half turn or a mirror doesn't +/// change the shape: their boxes are left as they are. +pub fn upright_regions(regions: &mut [Region], drawn_on: (f64, f64), orientation: Orientation, stored: (u32, u32)) -> bool { + let ((dw, dh), (sw, sh)) = (drawn_on, stored); + if regions.is_empty() || !orientation.swaps_axes() || sw == sh || dw == dh || (dw > dh) != (sw > sh) { + return false; + } + for r in regions.iter_mut() { + r.rect = orientation.map_norm_rect(r.rect); + } + true +} + /// A container-level error reported by [`try_extract`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ExtractError { @@ -463,4 +490,178 @@ mod tests { assert_eq!(m.metering_name(), Some("Pattern")); assert_eq!(m.exposure_program_name(), Some("Aperture-priority AE")); } + + /// An MWG regions packet with one face, its box centred at (0.25, 0.4) and 0.1 × 0.15 of `AppliedToDimensions` + /// `w` × `h`; `extra` goes on the region (e.g. Lightroom's `mwg-rs:Rotation`). + fn regions_packet(w: u32, h: u32, extra: &str) -> String { + format!( + r#" + + + + + + + + + + "# + ) + } + + fn near(r: Rect, b: [f64; 4]) -> bool { + [r.x0 - b[0], r.y0 - b[1], r.x1 - b[2], r.y1 - b[3]].iter().all(|d| d.abs() < 1e-9) + } + + /// The face's box as drawn: on the photo as stored, or on the upright one by apps that draw there. + const DRAWN: [f64; 4] = [0.2, 0.325, 0.3, 0.475]; + /// The same box on the photo turned upright by Exif orientation 6 (a quarter turn clockwise). + const TURNED_6: [f64; 4] = [0.525, 0.2, 0.675, 0.3]; + + #[test] + fn boxes_drawn_on_the_stored_photo_turn_with_its_orientation() { + let region = || Region { + rect: Rect { x0: DRAWN[0], y0: DRAWN[1], x1: DRAWN[2], y1: DRAWN[3] }, + kind: RegionKind::Face, + name: None, + description: None, + }; + let turned = |o: Orientation, drawn_on: (f64, f64), stored: (u32, u32)| { + let mut regions = [region()]; + let did = upright_regions(&mut regions, drawn_on, o, stored); + (did, regions[0].rect) + }; + // drawn on the 6000 × 4000 photo as stored: every quarter turn and its mirror image land elsewhere + for (o, want) in [ + (Orientation::Rotate90, TURNED_6), + (Orientation::Rotate270, [0.325, 0.7, 0.475, 0.8]), + (Orientation::Transpose, [0.325, 0.2, 0.475, 0.3]), + (Orientation::Transverse, [0.525, 0.7, 0.675, 0.8]), + ] { + let (did, r) = turned(o, (6000.0, 4000.0), (6000, 4000)); + assert!(did && near(r, want), "{o:?}: {r:?}"); + // a smaller copy of the photo as stored is the same frame + assert!(near(turned(o, (1500.0, 1000.0), (6000, 4000)).1, want), "{o:?} on a smaller size"); + } + // drawn on the upright photo (MWG's own frame), or where the shape can't tell the two apart: as they are + for (o, drawn_on, stored) in [ + (Orientation::Rotate90, (4000.0, 6000.0), (6000, 4000)), + (Orientation::Rotate90, (4000.0, 4000.0), (6000, 4000)), + (Orientation::Rotate90, (4000.0, 4000.0), (4000, 4000)), + (Orientation::Rotate180, (6000.0, 4000.0), (6000, 4000)), + (Orientation::FlipH, (6000.0, 4000.0), (6000, 4000)), + (Orientation::Normal, (6000.0, 4000.0), (6000, 4000)), + ] { + let (did, r) = turned(o, drawn_on, stored); + assert!(!did && near(r, DRAWN), "{o:?} drawn on {drawn_on:?} of {stored:?}: {r:?}"); + } + } + + /// Issue #2674: an app that doesn't say how the photo was turned (no `mwg-rs:Rotation`) drew the faces of a photo + /// with Exif orientation 6 on its stored pixels, with the stored 6000 × 4000 as `AppliedToDimensions`. The boxes + /// land on the faces of the upright photo, not where the stored photo had them. + #[test] + fn regions_drawn_on_the_stored_photo_are_read_onto_the_upright_one() { + let jpeg = |packet: &str| { + let mut j = vec![0xff, 0xd8]; + let mut seg = |payload: Vec| { + j.extend([0xff, 0xe1]); + j.extend(u16::try_from(payload.len() + 2).unwrap().to_be_bytes()); + j.extend(payload); + }; + // orientation 6, 6000 × 4000 as stored + seg([b"Exif\0\0".as_slice(), &crate::exif::tests::sample_exif(lightcraft_tiff::ByteOrder::Little)].concat()); + seg([b"http://ns.adobe.com/xap/1.0/\0".as_slice(), packet.as_bytes()].concat()); + j.extend([0xff, 0xd9]); + j + }; + let read = |packet: &str| { + let m = extract(&jpeg(packet)); + assert_eq!((m.orientation, m.width, m.height), (Some(Orientation::Rotate90), Some(6000), Some(4000))); + assert_eq!(try_extract(&jpeg(packet)).unwrap().regions, m.regions); + assert_eq!(m.regions.len(), 1); + m.regions[0].rect + }; + let stored = read(®ions_packet(6000, 4000, "")); + assert!(near(stored, TURNED_6), "drawn on the photo as stored: {stored:?}"); + let upright = read(®ions_packet(4000, 6000, "")); + assert!(near(upright, DRAWN), "drawn on the upright photo, MWG's way: {upright:?}"); + // Lightroom's boxes say how the photo was turned: turned once, by that + let lightroom = read(®ions_packet(6000, 4000, r#" mwg-rs:Rotation="-1.57080""#)); + assert!(near(lightroom, TURNED_6), "Lightroom's −π/2: {lightroom:?}"); + } + + /// A size only the XMP states can't tell how the photo is stored: `tiff:ImageWidth` and `tiff:ImageLength` of the + /// upright photo have the shape of boxes drawn on it upright, and those must not be turned. + #[test] + fn a_size_only_the_xmp_states_turns_no_regions() { + // orientation 6, no pixel size + let exif = write_exif(&Metadata { orientation: Some(Orientation::Rotate90), ..Default::default() }); + let exif = strip_exif_header(&exif); + let packet = regions_packet(4000, 6000, "") + .replace(r#"rdf:about="""#, r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:ImageWidth="4000" tiff:ImageLength="6000""#); + let mut j = vec![0xff, 0xd8]; + let mut seg = |payload: Vec| { + j.extend([0xff, 0xe1]); + j.extend(u16::try_from(payload.len() + 2).unwrap().to_be_bytes()); + j.extend(payload); + }; + seg([b"Exif\0\0".as_slice(), exif].concat()); + seg([b"http://ns.adobe.com/xap/1.0/\0".as_slice(), packet.as_bytes()].concat()); + j.extend([0xff, 0xd9]); + let m = extract(&j); + assert_eq!((m.orientation, m.width, m.height), (Some(Orientation::Rotate90), Some(4000), Some(6000))); + assert_eq!(m.regions.len(), 1); + assert!(near(m.regions[0].rect, DRAWN), "{:?}", m.regions[0].rect); + assert_eq!(try_extract(&j).unwrap().regions, m.regions); + // a TIFF-based file: the whole file is the Exif block, with the XMP in its first IFD + let mut ifd0 = lightcraft_tiff::IfdBuilder::new(); + ifd0.set(lightcraft_tiff::tags::ORIENTATION, lightcraft_tiff::Value::Short(vec![6])); + ifd0.set(lightcraft_tiff::tags::XMP, lightcraft_tiff::Value::Byte(packet.into_bytes())); + let m = extract(&lightcraft_tiff::TiffWriter::default().write(&[ifd0]).unwrap()); + assert_eq!((m.orientation, m.width, m.height), (Some(Orientation::Rotate90), Some(4000), Some(6000))); + assert!(near(m.regions[0].rect, DRAWN), "TIFF: {:?}", m.regions[0].rect); + } + + /// A photo whose Exif has a size but no orientation, and whose XMP says `tiff:Orientation=6`: LightCraft + /// displays it by the Exif alone, so it stays as stored, and boxes drawn on that stored frame are right as + /// written. Turning them by an orientation only the XMP states put them where the photo isn't (review of #2857). + #[test] + fn an_orientation_only_the_xmp_states_turns_no_regions() { + // 6000 × 4000 in the Exif, and no orientation + let size_ifd = || { + let mut sub = lightcraft_tiff::IfdBuilder::new(); + sub.set(lightcraft_tiff::tags::PIXEL_X_DIMENSION, lightcraft_tiff::Value::Long(vec![6000])); + sub.set(lightcraft_tiff::tags::PIXEL_Y_DIMENSION, lightcraft_tiff::Value::Long(vec![4000])); + sub + }; + let mut exif_ifd0 = lightcraft_tiff::IfdBuilder::new(); + exif_ifd0.set_child(lightcraft_tiff::tags::EXIF_IFD, size_ifd()); + let exif = lightcraft_tiff::TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[exif_ifd0]).unwrap(); + let packet = regions_packet(6000, 4000, "") + .replace(r#"rdf:about="""#, r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:Orientation="6""#); + let mut j = vec![0xff, 0xd8]; + let mut seg = |payload: Vec| { + j.extend([0xff, 0xe1]); + j.extend(u16::try_from(payload.len() + 2).unwrap().to_be_bytes()); + j.extend(payload); + }; + seg([b"Exif\0\0".as_slice(), &exif].concat()); + seg([b"http://ns.adobe.com/xap/1.0/\0".as_slice(), packet.as_bytes()].concat()); + j.extend([0xff, 0xd9]); + let m = extract(&j); + assert_eq!((m.width, m.height), (Some(6000), Some(4000))); + assert_eq!(m.orientation, Some(Orientation::Rotate90), "the XMP's orientation is still reported"); + assert_eq!(m.regions.len(), 1); + assert!(near(m.regions[0].rect, DRAWN), "turned by an orientation the Exif doesn't state: {:?}", m.regions[0].rect); + assert_eq!(try_extract(&j).unwrap().regions, m.regions); + // a TIFF-based file: the first IFD has no orientation, its XMP (tag 700) has + let mut ifd0 = lightcraft_tiff::IfdBuilder::new(); + ifd0.set(lightcraft_tiff::tags::XMP, lightcraft_tiff::Value::Byte(packet.into_bytes())); + ifd0.set_child(lightcraft_tiff::tags::EXIF_IFD, size_ifd()); + let m = extract(&lightcraft_tiff::TiffWriter::default().write(&[ifd0]).unwrap()); + assert_eq!(m.orientation, Some(Orientation::Rotate90)); + assert!(near(m.regions[0].rect, DRAWN), "TIFF: {:?}", m.regions[0].rect); + } } diff --git a/crates/meta/src/xmp.rs b/crates/meta/src/xmp.rs index 44edc04b8a..bb23bfd1ff 100644 --- a/crates/meta/src/xmp.rs +++ b/crates/meta/src/xmp.rs @@ -77,6 +77,17 @@ pub struct XmpData { pub values: BTreeMap, } +impl XmpData { + /// The pixel size the packet's regions were drawn on (`mwg-rs:AppliedToDimensions`), unless one of them says how + /// the photo was turned (`mwg-rs:Rotation`: Lightroom's boxes, which the reader already turns upright). It tells + /// boxes drawn on the photo as stored from boxes drawn on it upright: see [`crate::upright_regions`]. + pub fn regions_drawn_on(&self) -> Option<(f64, f64)> { + let regions = self.values.get("mwg-rs:Regions")?; + let turned = regions.field("mwg-rs:RegionList").is_some_and(|l| l.items().iter().any(|r| r.field("mwg-rs:Rotation").is_some())); + if turned { None } else { applied_to(regions) } + } +} + /// A structured XMP value. #[derive(Clone, Debug, PartialEq)] pub enum XmpValue { @@ -441,15 +452,20 @@ fn parse_gps_coord(s: &str) -> Option { /// Malformed or out-of-range entries are skipped rather than rejecting the whole list: one bad region /// (from Lightroom, digiKam, Picasa, or a hand-edited file) shouldn't hide the rest. fn parse_regions(regions: &XmpValue) -> Vec { - // `AppliedToDimensions` documents the pixel size regions were authored against. It's only consulted + // `AppliedToDimensions` documents the pixel size regions were authored against. Here it's only consulted // for the rare region whose own Area is in pixel units instead of MWG's normalized default below. - let px_dims = regions.field("mwg-rs:AppliedToDimensions").and_then(|d| { + let px_dims = applied_to(regions); + let Some(list) = regions.field("mwg-rs:RegionList") else { return Vec::new() }; + list.items().iter().filter_map(|item| parse_one_region(item, px_dims)).collect() +} + +/// `mwg-rs:AppliedToDimensions` of a `mwg-rs:Regions` struct: (width, height) in pixels, both positive. +fn applied_to(regions: &XmpValue) -> Option<(f64, f64)> { + regions.field("mwg-rs:AppliedToDimensions").and_then(|d| { let w = d.field("stDim:w").and_then(XmpValue::text).and_then(parse_number)?; let h = d.field("stDim:h").and_then(XmpValue::text).and_then(parse_number)?; (w > 0.0 && h > 0.0).then_some((w, h)) - }); - let Some(list) = regions.field("mwg-rs:RegionList") else { return Vec::new() }; - list.items().iter().filter_map(|item| parse_one_region(item, px_dims)).collect() + }) } fn parse_one_region(item: &XmpValue, px_dims: Option<(f64, f64)>) -> Option { diff --git a/crates/meta/src/xmp/tests.rs b/crates/meta/src/xmp/tests.rs index acf1d9fcef..6281546041 100644 --- a/crates/meta/src/xmp/tests.rs +++ b/crates/meta/src/xmp/tests.rs @@ -345,6 +345,36 @@ fn mwg_regions_quarter_turn_rotation_is_mapped_to_the_upright_frame() { assert!(near(regions[4].rect, [0.6, 0.45, 0.8, 0.75]), "−π (orientation 3): {:?}", regions[4].rect); } +/// The size a packet's boxes were drawn on is its `AppliedToDimensions`, unless a box says how the photo was turned +/// (Lightroom's `mwg-rs:Rotation`: those are upright already) or there is no size to go by. +#[test] +fn regions_drawn_on_is_the_applied_to_size_unless_a_box_says_how_it_was_turned() { + let packet = |dims: &str, rotation: &str| { + format!( + r#" + + {dims} + + + + + + + + + + "# + ) + }; + let dims = r#""#; + let drawn_on = |x: &str| parse_xmp(x).unwrap().regions_drawn_on(); + assert_eq!(drawn_on(&packet(dims, "")), Some((6000.0, 4000.0))); + assert_eq!(drawn_on(&packet(dims, r#" mwg-rs:Rotation="-1.57080""#)), None, "one box turned by Lightroom"); + assert_eq!(drawn_on(&packet("", "")), None, "no AppliedToDimensions"); + assert_eq!(drawn_on(r#""#), None); +} + /// A second, differently-shaped encoding: each region is its own `rdf:Description` (rather than an /// `rdf:li rdf:parseType="Resource"`), `mwg-rs:Type` as an attribute instead of an element, and an /// unrecognised `mwg-rs:Type` value kept verbatim. diff --git a/crates/preview/src/disk.rs b/crates/preview/src/disk.rs index ca82870483..a1395a04ca 100644 --- a/crates/preview/src/disk.rs +++ b/crates/preview/src/disk.rs @@ -172,15 +172,43 @@ impl DiskCache { } } - pub fn put(&self, key: Hash128, img: &Rgba8) { - let Some(bytes) = encode_jpeg(img) else { return }; + /// The size (width, height) of the picture kept under `key`, read from the start of its file + /// only (no decode, no hit counted, nothing written): to tell whether a preview is there and + /// big enough without loading it. + pub fn dims(&self, key: Hash128) -> Option<(usize, usize)> { + use std::io::Read; let p = self.path(key); - let Some(parent) = p.parent() else { return }; + if !p.parent().is_some_and(is_real_dir) { + return None; + } + let mut f = std::fs::File::open(&p).or_else(|_| std::fs::File::open(self.named(key, OLD_EXT))).ok()?; + // the size is normally in the first few KiB: more is read only when that is not enough + let mut head = Vec::new(); + for limit in [FIRST_HEADER_BYTES, HEADER_BYTES] { + let more = limit.saturating_sub(head.len() as u64); + (&mut f).take(more).read_to_end(&mut head).ok()?; + if let Some(dims) = jpeg_dims(&head) { + return Some(dims); + } + if (head.len() as u64) < limit { + // the whole file was read + break; + } + } + None + } + + /// Write `img` under `key`. Returns whether the file was written (a full or unwritable cache folder + /// gives `false`; the cache is unchanged then). + pub fn put(&self, key: Hash128, img: &Rgba8) -> bool { + let Some(bytes) = encode_jpeg(img) else { return false }; + let p = self.path(key); + let Some(parent) = p.parent() else { return false }; // a folder the cache makes for itself says that it is a cache; one that was there // already may hold somebody's files, and is not declared one let made = !self.dir.exists(); if std::fs::create_dir_all(parent).is_err() || !is_real_dir(parent) { - return; + return false; } if made { let _ = std::fs::write(self.dir.join(TAG), TAG_TEXT); @@ -197,7 +225,7 @@ impl DiskCache { let written = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp).and_then(|mut f| std::io::Write::write_all(&mut f, &bytes)); if written.is_err() || std::fs::rename(&tmp, &p).is_err() { let _ = std::fs::remove_file(&tmp); - return; + return false; } self.writes.fetch_add(1, Ordering::Relaxed); *used = used.saturating_sub(old_len).saturating_add(bytes.len() as u64); @@ -205,7 +233,10 @@ impl DiskCache { drop(total); if over { self.prune(); + // (a picture bigger than the room pruning leaves goes too: it was not kept) + return p.is_file(); } + true } /// All cache files (only names of the cache's own shape, see [`is_cache_file`]): @@ -374,6 +405,12 @@ impl DiskCache { *t.get_or_insert_with(|| self.scan().iter().map(|f| f.1).sum()) } + /// Bytes on disk when already known, without reading the folder (`None` until [`Self::size`], + /// a write or a prune has counted them). + pub fn known_size(&self) -> Option { + *self.total.lock().unwrap_or_else(|e| e.into_inner()) + } + pub fn clear(&self) { for (p, _, _) in self.scan() { let _ = std::fs::remove_file(p); @@ -432,6 +469,22 @@ pub fn encode_jpeg(img: &Rgba8) -> Option> { Some(out) } +/// How much of a cached file [`DiskCache::dims`] reads: the JPEG headers this cache writes come +/// first and are a few hundred bytes. +const HEADER_BYTES: u64 = 64 << 10; +/// What [`DiskCache::dims`] reads first, which holds the size of the JPEGs this cache writes. +const FIRST_HEADER_BYTES: u64 = 4 << 10; + +/// A JPEG's (width, height) from its headers (`None`: not a JPEG, or cut short before its frame header). +pub fn jpeg_dims(bytes: &[u8]) -> Option<(usize, usize)> { + use zune_core::bytestream::ZCursor; + let mut d = zune_jpeg::JpegDecoder::new(ZCursor::new(bytes)); + d.decode_headers().ok()?; + let info = d.info()?; + let (w, h) = (info.width as usize, info.height as usize); + (w > 0 && h > 0).then_some((w, h)) +} + /// Decode a cached thumbnail (see [`encode_jpeg`]). pub fn decode_jpeg(bytes: &[u8]) -> Option { use zune_core::bytestream::ZCursor; diff --git a/crates/preview/src/lib.rs b/crates/preview/src/lib.rs index 14bd50a1b3..3c5485ae8f 100644 --- a/crates/preview/src/lib.rs +++ b/crates/preview/src/lib.rs @@ -21,7 +21,7 @@ use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, RwLock}; -pub use disk::{DiskCache, decode_jpeg, encode_jpeg}; +pub use disk::{DiskCache, decode_jpeg, encode_jpeg, jpeg_dims}; pub use hash::{Hash128, Hasher128, hash_bytes}; use lightcraft_raster::Rgba8; pub use lru::{Lru, next_tick}; @@ -108,20 +108,80 @@ impl PreviewCache { Some(img) } - pub fn put(&self, key: Hash128, img: Arc) { - self.put_at(self.generation(), key, img); + /// The size of the image kept under `key` (memory, else disk: read from its file's header), without + /// loading it or changing what is kept. + pub fn dims(&self, key: Hash128) -> Option<(usize, usize)> { + if self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner).is_none() { + return None; + } + if let Some(v) = self.mem.lock().unwrap_or_else(|e| e.into_inner()).peek(&key) { + return Some((v.width, v.height)); + } + self.disk.as_ref()?.dims(key) } - pub fn put_at(&self, generation: u64, key: Hash128, img: Arc) { + /// The size of the image kept under `key` where it lasts: on disk when the cache has a disk (a copy only + /// in memory, whose deferred write may have been skipped, doesn't count), else in memory. Nothing is + /// loaded or changed. + pub fn stored_dims(&self, key: Hash128) -> Option<(usize, usize)> { + match &self.disk { + Some(d) if self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner).is_some() => d.dims(key), + Some(_) => None, + None => self.dims(key), + } + } + + /// The memory LRU's copy of `key`, without looking on disk. + pub fn get_memory(&self, key: Hash128) -> Option> { + if self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner).is_none() { + return None; + } + self.mem.lock().unwrap_or_else(|e| e.into_inner()).get(&key).cloned() + } + + /// Keep `img` in memory only (it is never written to disk): for pictures that are cheap + /// enough to make again, such as a raw's decoded camera JPEG, but worth keeping for a revisit. + pub fn put_memory(&self, key: Hash128, img: Arc) { + // (the guard is held through the insertion: a clear can't come between the look and the insertion) + let current = self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner); + if current.is_none() { + return; + } + let c = cost(&img); + self.mem.lock().unwrap_or_else(|e| e.into_inner()).insert(key, img, c); + drop(current); + } + + /// [`Self::put_memory`] for a job that captured `generation`: nothing is kept once the cache + /// was cleared (or retired) after that, so a job started before Discard Preview Cache can't + /// put its picture back. + pub fn put_memory_at(&self, generation: u64, key: Hash128, img: Arc) { + // (the guard is held through the insertion: a clear can't come between the look and the insertion) let current = self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner); if *current != Some(generation) { return; } - if let Some(d) = &self.disk { - d.put(key, &img); - } let c = cost(&img); self.mem.lock().unwrap_or_else(|e| e.into_inner()).insert(key, img, c); + drop(current); + } + + pub fn put(&self, key: Hash128, img: Arc) { + let _ = self.put_at(self.generation(), key, img); + } + + /// [`Self::put`] for a job of `generation`. Returns whether the image is kept where it lasts: `false` when + /// the cache was cleared or retired since the job was made (nothing is kept; see [`Self::generation`] to + /// tell), or when the disk cache could not write the file (the image is kept in memory all the same). + pub fn put_at(&self, generation: u64, key: Hash128, img: Arc) -> bool { + let current = self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner); + if *current != Some(generation) { + return false; + } + let written = self.disk.as_ref().is_none_or(|d| d.put(key, &img)); + let c = cost(&img); + self.mem.lock().unwrap_or_else(|e| e.into_inner()).insert(key, img, c); + written } /// Like [`Self::put`], but the disk write (a JPEG encode) happens on a background thread, so diff --git a/crates/preview/src/tests.rs b/crates/preview/src/tests.rs index 2f07e927fb..975c2ddf79 100644 --- a/crates/preview/src/tests.rs +++ b/crates/preview/src/tests.rs @@ -792,3 +792,63 @@ fn deferred_writes_are_bounded_and_drain_to_disk() { assert!(keys.iter().all(|k| cache.get(*k).is_some())); let _ = std::fs::remove_dir_all(&dir); } + +/// `put_at` says whether the image is kept where it lasts: not for a job made before the cache was cleared or +/// retired, nor when the disk cache can't write it (CodeRabbit on #3077). +#[test] +fn put_at_says_whether_the_image_was_kept() { + let dir = temp_dir("put-at-kept"); + let cache = PreviewCache::with_disk(1 << 20, &dir, 1 << 20); + let (key, img) = (hash_bytes(b"kept"), Arc::new(gradient(8, 8, 3))); + let old = cache.generation(); + assert!(cache.put_at(old, key, img.clone()), "kept"); + cache.clear(); + assert!(!cache.put_at(old, key, img.clone()), "a job from before the clear keeps nothing"); + assert!(cache.put_at(cache.generation(), key, img.clone())); + let generation = cache.generation(); + cache.retire(); + assert!(!cache.put_at(generation, key, img.clone()), "nor one for a retired cache"); + // a file where the cache folder goes: the write fails + let blocked = temp_dir("put-at-blocked"); + std::fs::write(&blocked, b"not a folder").unwrap(); + let cache = PreviewCache::with_disk(1 << 20, &blocked, 1 << 20); + assert!(!cache.put_at(cache.generation(), key, img.clone()), "not written"); + let memory = PreviewCache::memory(1 << 20); + assert!(memory.put_at(memory.generation(), key, img), "a memory-only cache keeps it"); + let _ = std::fs::remove_file(&blocked); + let _ = std::fs::remove_dir_all(&dir); +} + +/// `dims` reads a cached file's first few KiB, and further when its size marker comes later (CodeRabbit on #3080). +#[test] +fn dims_finds_a_size_marker_past_the_first_few_kib() { + let dir = temp_dir("dims-far"); + let d = DiskCache::new(&dir, 1 << 20); + let key = hash_bytes(b"far"); + assert!(d.put(key, &gradient(40, 30, 5))); + assert_eq!(d.dims(key), Some((40, 30))); + // the same picture with a 10 KiB application segment before its frame header + let file = files_under(&dir).into_iter().find(|f| f.ends_with(disk::EXT)).expect("the cached file"); + let path = dir.join(file); + let jpeg = std::fs::read(&path).unwrap(); + let mut padded = jpeg[..2].to_vec(); + let pad = 10 << 10; + padded.extend_from_slice(&[0xFF, 0xEF, ((pad + 2) >> 8) as u8, ((pad + 2) & 0xFF) as u8]); + padded.extend(std::iter::repeat_n(0u8, pad)); + padded.extend_from_slice(&jpeg[2..]); + std::fs::write(&path, padded).unwrap(); + assert_eq!(d.dims(key), Some((40, 30)), "found past the first read"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A picture bigger than the room pruning leaves is removed by the pruning its own write starts: `put` says it +/// was not kept (CodeRabbit on #3077). +#[test] +fn a_write_the_pruning_removes_is_not_reported_as_kept() { + let dir = temp_dir("pruned-away"); + let d = DiskCache::new(&dir, 64); + assert!(!d.put(hash_bytes(b"too big"), &gradient(64, 64, 9)), "pruned away at once"); + let roomy = DiskCache::new(&dir, 1 << 20); + assert!(roomy.put(hash_bytes(b"fits"), &gradient(64, 64, 9))); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/raw/src/hotpixel.rs b/crates/raw/src/hotpixel.rs new file mode 100644 index 0000000000..aa6131b18b --- /dev/null +++ b/crates/raw/src/hotpixel.rs @@ -0,0 +1,519 @@ +//! Hot pixels on sensors that don't list their defects. +//! +//! A hot pixel is a single photosite that reads far too bright: a leaky or stuck cell, most visible +//! at high ISO and in dark areas. Demosaicing turns it into a small saturated dot of its colour +//! (red, green or blue), and colour noise reduction can only make that dot fainter, since the photosite +//! is too bright, not just the wrong colour. DNGs list such pixels in their opcodes and Panasonic marks +//! them in the data (both repaired elsewhere); other raws, such as Sony ARWs, carry no list. +//! +//! [`RawImage::suppress_hot_pixels`] finds them in the mosaic, before demosaicing: +//! +//! 1. **Noise model.** On a sparse sample of the image, each photosite is compared with the median of +//! its same-colour neighbours. The spread of that difference, per brightness, gives the noise +//! σ(level) as `σ² = a · level + b` (shot noise plus read noise), fitted to the image itself. +//! 2. **Candidates.** A photosite more than [`K_HOT`] σ above *every* same-colour neighbour (the +//! nearest eight, two photosites away on a Bayer grid, the nearest greens for green). +//! 3. **Real light is kept.** A star, a spark or a specular point lights more than one photosite: its +//! direct neighbours are raised too. A candidate with at least [`MIN_LIT`] neighbours more than +//! [`K_SPOT`] σ above their own surroundings is left alone. Hot photosites also come in adjacent +//! pairs, so a single lit neighbour doesn't count. +//! 4. The rest are replaced by the median of their same-colour neighbours. +//! +//! If more than a share of the photosites would be replaced (by default [`HOT_PIXEL_MAX_SHARE`]; the caller may +//! choose another), the image doesn't fit the model (a synthetic pattern, a star field shot through a pinhole) and +//! nothing is changed. Real light kept in step 3 doesn't count: a dense star field still has its hot pixels removed. + +use crate::{RawData, RawImage}; +use rayon::prelude::*; + +/// A candidate stands more than this many σ above the brightest of its same-colour neighbours (pure noise +/// hardly reaches 4.5 σ above the brightest of eight; measured on two ILCE-7M4 files at ISO 3200 and 25600). +const K_HOT: f32 = 5.0; +/// A direct neighbour this many σ above its own surroundings means the light is real. +const K_SPOT: f32 = 4.0; +/// ...and it takes this many lit neighbours (a hot pair has one). +const MIN_LIT: usize = 2; +/// Every this many rows and columns are sampled for the noise model. +const SAMPLE_STEP: usize = 5; +/// Brightness bins of the noise model (on a square-root scale), and the samples a bin needs. +const BINS: usize = 32; +const MIN_BIN_SAMPLES: usize = 64; +/// Photosites this close to the active area's edge are left alone (their neighbourhood is cut). +const MARGIN: usize = 4; +/// More replaced than this share of the photosites and the result is discarded (unless the caller chooses another). +pub const HOT_PIXEL_MAX_SHARE: f64 = 2e-3; + +/// For one position in the CFA pattern: the offsets of the nearest same-colour photosites (at most 8, +/// within two photosites) and of the 8 direct neighbours. +#[derive(Clone)] +struct Phase { + same: Vec<(isize, isize)>, + around: [(isize, isize); 8], +} + +fn phases(cfa: &crate::Cfa) -> Vec { + let around = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]; + let (pw, ph) = (cfa.width, cfa.height); + (0..ph) + .flat_map(|j| (0..pw).map(move |i| (i, j))) + .map(|(i, j)| { + // anchored far enough from 0 that i + dx stays positive + let (x0, y0) = (i + 2 * pw, j + 2 * ph); + let c = cfa.color_at(x0, y0); + let mut same: Vec<(isize, isize)> = (-2isize..=2) + .flat_map(|dy| (-2isize..=2).map(move |dx| (dx, dy))) + .filter(|&(dx, dy)| (dx, dy) != (0, 0) && cfa.color_at((x0 as isize + dx) as usize, (y0 as isize + dy) as usize) == c) + .collect(); + same.sort_by_key(|&(dx, dy)| dx * dx + dy * dy); + same.truncate(8); + Phase { same, around } + }) + .collect() +} + +/// The noise σ at a brightness (in raw counts above black): `sqrt(a · level + b)`. +#[derive(Clone, Copy, Debug)] +struct Noise { + a: f32, + b: f32, +} + +impl Noise { + fn sigma(&self, level: f32) -> f32 { + (self.a * level.max(0.0) + self.b).max(1.0).sqrt() + } +} + +fn median(v: &mut [f32]) -> f32 { + if v.is_empty() { + return 0.0; + } + v.sort_by(f32::total_cmp); + let n = v.len(); + if n % 2 == 1 { v[n / 2] } else { 0.5 * (v[n / 2 - 1] + v[n / 2]) } +} + +/// The sample view the passes work on: the u16 mosaic, its width, the active area, the CFA phases. +struct View<'a> { + d: &'a [u16], + w: usize, + pw: usize, + ph: usize, + phases: &'a [Phase], +} + +impl View<'_> { + /// Value at full-image `(x, y)`; callers keep `(x, y)` inside the image. + #[inline] + fn at(&self, x: isize, y: isize) -> f32 { + self.d[y as usize * self.w + x as usize] as f32 + } + #[inline] + fn phase(&self, x: usize, y: usize) -> &Phase { + &self.phases[(y % self.ph) * self.pw + (x % self.pw)] + } + /// The same-colour neighbours' values around `(x, y)` into `buf`, and their maximum. + #[inline] + fn neighbours(&self, x: usize, y: usize, buf: &mut Vec) -> f32 { + buf.clear(); + let mut max = f32::MIN; + for &(dx, dy) in &self.phase(x, y).same { + let v = self.at(x as isize + dx, y as isize + dy); + max = max.max(v); + buf.push(v); + } + max + } +} + +impl RawImage { + /// Replace isolated hot photosites by the median of their same-colour neighbours (see the module docs). + /// Returns how many were replaced. Only single-plane integer CFA data is examined. + pub fn suppress_hot_pixels(&mut self) -> usize { + self.suppress_hot_pixels_with(HOT_PIXEL_MAX_SHARE) + } + + /// [`Self::suppress_hot_pixels`], giving up when more than `max_share` of the photosites (0..1) would be replaced. + pub fn suppress_hot_pixels_with(&mut self, max_share: f64) -> usize { + let Some(cfa) = self.cfa.clone() else { return 0 }; + let (w, h, a) = (self.width, self.height, self.active_area); + let black = self.black.mean(); + let RawData::U16(d) = &mut self.data else { return 0 }; + if self.cpp != 1 + || !cfa.valid() + || w.checked_mul(h) != Some(d.len()) + || a.width < 4 * MARGIN + || a.height < 4 * MARGIN + || a.x + a.width > w + || a.y + a.height > h + || !black.is_finite() + { + return 0; + } + let phases = phases(&cfa); + if phases.iter().any(|p| p.same.len() < 4) { + return 0; + } + let (x0, x1, y0, y1) = (a.x + MARGIN, a.x + a.width - MARGIN, a.y + MARGIN, a.y + a.height - MARGIN); + let range = (self.white.iter().copied().fold(0.0f32, f32::max) - black).max(1.0); + let fixes = { + let v = View { d: d.as_slice(), w, pw: cfa.width, ph: cfa.height, phases: &phases }; + let Some(noise) = noise_model(&v, (x0, x1, y0, y1), black, range) else { return 0 }; + let candidates = candidates(&v, (x0, x1, y0, y1), black, noise); + let mut buf = Vec::with_capacity(8); + let n_cand = candidates.len(); + let kept: Vec<_> = candidates.into_iter().filter(|&(x, y, _)| !lit_around(&v, x, y, black, noise, &mut buf)).collect(); + // (real light kept above doesn't count against the limit) + let sites = (x1 - x0) * (y1 - y0); + let limit = max_share * sites as f64; + if limit.is_nan() || kept.len() as f64 > limit { + return 0; + } + if std::env::var_os("LIGHTCRAFT_PROFILE").is_some() { + eprintln!( + " hot pixels: noise σ² = {:.3}·L + {:.1} (σ at 0: {:.1}, at 1 %: {:.1}), {n_cand} candidates, {} real light", + noise.a, + noise.b, + noise.sigma(0.0), + noise.sigma(0.01 * range), + n_cand - kept.len() + ); + // the strongest excesses below the threshold, to see how far the dots are + let mut hist = [0usize; 12]; + let mut buf2 = Vec::with_capacity(8); + for y in (y0..y1).step_by(1) { + for x in x0..x1 { + let s = v.at(x as isize, y as isize); + let max = v.neighbours(x, y, &mut buf2); + if s <= max { + continue; + } + let m = median(&mut buf2); + let k = ((s - max) / noise.sigma(m - black)) as usize; + hist[k.min(11)] += 1; + } + } + eprintln!(" hot pixels: photosites by (s - max neighbour) / σ, 0..11+: {hist:?}"); + // very bright photosites in dark surroundings, whatever the verdict + let mut bright = 0; + let mut buf4 = Vec::with_capacity(8); + for y in y0..y1 { + for x in x0..x1 { + let s = v.at(x as isize, y as isize) - black; + if s < 1500.0 { + continue; + } + v.neighbours(x, y, &mut buf4); + let m = median(&mut buf4) - black; + if m > 300.0 { + continue; + } + bright += 1; + if bright <= 4 { + eprintln!( + " bright at ({x}, {y}), colour {}, s {s:.0}, median {m:.0}, lit {}:", + cfa.color_at(x, y), + lit_around(&v, x, y, black, noise, &mut buf4) + ); + for dy in -3isize..=3 { + let row: Vec = + (-3isize..=3).map(|dx| format!("{:6.0}", v.at(x as isize + dx, y as isize + dy) - black)).collect(); + eprintln!(" {}", row.join(" ")); + } + } + } + } + eprintln!(" bright photosites in dark surroundings: {bright}"); + // a few candidates rejected as real light: their 5 × 5 neighbourhood above black + let mut shown = 0; + let mut buf3 = Vec::with_capacity(8); + for y in y0..y1 { + for x in x0..x1 { + if shown >= 6 { + break; + } + let s = v.at(x as isize, y as isize); + let max = v.neighbours(x, y, &mut buf3); + if s <= max { + continue; + } + let m = median(&mut buf3); + if s - max > 8.0 * noise.sigma(m - black) && lit_around(&v, x, y, black, noise, &mut buf3) { + shown += 1; + eprintln!(" rejected at ({x}, {y}), colour {}:", cfa.color_at(x, y)); + for dy in -2isize..=2 { + let row: Vec = + (-2isize..=2).map(|dx| format!("{:6.0}", v.at(x as isize + dx, y as isize + dy) - black)).collect(); + eprintln!(" {}", row.join(" ")); + } + } + } + } + } + kept + }; + for &(x, y, r) in &fixes { + d[y * w + x] = r; + } + fixes.len() + } +} + +/// Fit `σ² = a · level + b` to the spread of (photosite − median of its same-colour neighbours) on a sample. +fn noise_model(v: &View<'_>, (x0, x1, y0, y1): (usize, usize, usize, usize), black: f32, range: f32) -> Option { + let bin_of = |level: f32| (((level.max(0.0) / range).sqrt() * BINS as f32) as usize).min(BINS - 1); + let rows: Vec = (y0..y1).step_by(SAMPLE_STEP).collect(); + let per_row: Vec> = rows + .par_iter() + .map(|&y| { + let mut buf = Vec::with_capacity(8); + (x0..x1) + .step_by(SAMPLE_STEP) + .map(|x| { + v.neighbours(x, y, &mut buf); + let m = median(&mut buf); + let level = m - black; + (bin_of(level), level, (v.at(x as isize, y as isize) - m).abs()) + }) + .collect() + }) + .collect(); + let mut bins: Vec<(Vec, f64, usize)> = vec![(Vec::new(), 0.0, 0); BINS]; + for (b, level, dev) in per_row.into_iter().flatten() { + bins[b].0.push(dev); + bins[b].1 += level as f64; + bins[b].2 += 1; + } + // per bin: mean level and σ from the median absolute deviation (robust to the hot pixels themselves) + let pts: Vec<(f64, f64, f64)> = bins + .into_iter() + .filter(|(dev, _, n)| *n >= MIN_BIN_SAMPLES && !dev.is_empty()) + .map(|(mut dev, sum, n)| { + let s = 1.4826 * median(&mut dev) as f64; + (sum / n as f64, s * s, n as f64) + }) + .collect(); + if pts.is_empty() { + return None; + } + // weighted least squares for σ² = a·L + b, both kept ≥ 0 + let (sw, sl, sv) = pts.iter().fold((0.0, 0.0, 0.0), |(w, l, s), &(lv, var, n)| (w + n, l + n * lv, s + n * var)); + let (ml, mv) = (sl / sw, sv / sw); + let (cov, varl) = pts.iter().fold((0.0, 0.0), |(c, vl), &(lv, var, n)| (c + n * (lv - ml) * (var - mv), vl + n * (lv - ml) * (lv - ml))); + let a = if varl > 0.0 { (cov / varl).max(0.0) } else { 0.0 }; + let b = (mv - a * ml).max(0.0); + (a.is_finite() && b.is_finite()).then_some(Noise { a: a as f32, b: b as f32 }) +} + +/// Photosites far above every same-colour neighbour, with the value to replace them by. +fn candidates(v: &View<'_>, (x0, x1, y0, y1): (usize, usize, usize, usize), black: f32, noise: Noise) -> Vec<(usize, usize, u16)> { + (y0..y1) + .into_par_iter() + .flat_map_iter(|y| { + let mut buf = Vec::with_capacity(8); + let mut out = Vec::new(); + for x in x0..x1 { + let s = v.at(x as isize, y as isize); + let max = v.neighbours(x, y, &mut buf); + if s <= max { + continue; + } + let m = median(&mut buf); + if s - max > K_HOT * noise.sigma(m - black) { + out.push((x, y, m.round().clamp(0.0, u16::MAX as f32) as u16)); + } + } + out + }) + .collect() +} + +/// Are at least [`MIN_LIT`] direct neighbours of `(x, y)` clearly above their own same-colour surroundings +/// (real light)? A single one is not enough: hot photosites also come in adjacent pairs. +fn lit_around(v: &View<'_>, x: usize, y: usize, black: f32, noise: Noise, buf: &mut Vec) -> bool { + v.phase(x, y) + .around + .iter() + .filter(|&&(dx, dy)| { + let (nx, ny) = ((x as isize + dx) as usize, (y as isize + dy) as usize); + let s = v.at(nx as isize, ny as isize); + v.neighbours(nx, ny, buf); + let m = median(buf); + s - m > K_SPOT * noise.sigma(m - black) + }) + .count() + >= MIN_LIT +} + +#[cfg(test)] +mod tests { + use crate::*; + + /// A `w × h` RGGB mosaic, black 512, white 16383, flat grey 2000 counts above black with + /// deterministic noise of about σ ≈ 30 counts. + fn mosaic(w: usize, h: usize) -> RawImage { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut noise = || { + // sum of 4 uniforms, about N(0, 1) + (0..4) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f32 / (1u64 << 53) as f32 - 0.5 + }) + .sum::() + * 1.732 + }; + let data = (0..w * h).map(|_| (512.0 + 2000.0 + 30.0 * noise()).round() as u16).collect(); + RawImage { + format: RawFormat::Arw, + width: w, + height: h, + cpp: 1, + data: RawData::U16(data), + cfa: Cfa::bayer("RGGB"), + bits: 14, + black: BlackLevel::uniform(512.0), + white: vec![16383.0], + active_area: Rect::new(0, 0, w, h), + crop: Rect::new(0, 0, w, h), + orientation: Orientation::Normal, + color: ColorData::default(), + wb_multipliers: None, + linearized: false, + opcodes: OpcodeLists::default(), + lens_metadata: Default::default(), + pixel_aspect: 1.0, + metadata: Metadata::default(), + } + } + + fn get(r: &RawImage, x: usize, y: usize) -> u16 { + match &r.data { + RawData::U16(d) => d[y * r.width + x], + RawData::F32(_) => 0, + } + } + + fn set(r: &mut RawImage, x: usize, y: usize, v: u16) { + let w = r.width; + if let RawData::U16(d) = &mut r.data { + d[y * w + x] = v; + } + } + + #[test] + fn flat_noise_is_left_alone() { + let mut r = mosaic(256, 256); + let before = r.data.clone(); + assert_eq!(r.suppress_hot_pixels(), 0); + assert_eq!(r.data, before); + } + + #[test] + fn single_hot_photosites_of_each_colour_are_replaced() { + let mut r = mosaic(256, 256); + // red (even, even), green (odd, even), blue (odd, odd) + for &(x, y) in &[(100, 100), (101, 60), (151, 151)] { + set(&mut r, x, y, 9000); + } + assert_eq!(r.suppress_hot_pixels(), 3); + for &(x, y) in &[(100, 100), (101, 60), (151, 151)] { + let v = get(&r, x, y) as f32; + assert!((v - 2512.0).abs() < 120.0, "({x}, {y}) = {v}"); + } + } + + #[test] + fn an_adjacent_hot_pair_is_replaced() { + let mut r = mosaic(256, 256); + set(&mut r, 80, 80, 9000); + set(&mut r, 80, 81, 8000); + assert_eq!(r.suppress_hot_pixels(), 2); + assert!(get(&r, 80, 80) < 2700 && get(&r, 80, 81) < 2700); + } + + #[test] + fn a_small_star_is_kept() { + let mut r = mosaic(256, 256); + // a point of light over a 3 × 3 block: brightest in the middle, its neighbours lit too + for dy in -1i32..=1 { + for dx in -1i32..=1 { + let v = if dx == 0 && dy == 0 { 12000 } else { 5000 }; + set(&mut r, (120 + dx) as usize, (90 + dy) as usize, v); + } + } + let before = r.data.clone(); + assert_eq!(r.suppress_hot_pixels(), 0); + assert_eq!(r.data, before); + } + + #[test] + fn a_hot_photosite_in_a_dark_area_is_replaced() { + let mut r = mosaic(256, 256); + // a dark patch near black (noise is then read noise, smaller) + for y in 32..96 { + for x in 32..96 { + set(&mut r, x, y, 512 + 20 + ((x * 7 + y * 13) % 11) as u16); + } + } + set(&mut r, 64, 64, 1500); + assert_eq!(r.suppress_hot_pixels(), 1); + assert!(get(&r, 64, 64) < 600); + } + + #[test] + fn a_dense_star_field_keeps_its_stars_and_loses_its_hot_pixels() { + let mut r = mosaic(256, 256); + // 225 small stars: more candidates than 0.2 % of the photosites, every one of them real light + for sy in 0..15 { + for sx in 0..15 { + let (cx, cy) = (16 + 16 * sx, 16 + 16 * sy); + for dy in -1i32..=1 { + for dx in -1i32..=1 { + let v = if dx == 0 && dy == 0 { 12000 } else { 5000 }; + set(&mut r, (cx + dx) as usize, (cy + dy) as usize, v); + } + } + } + } + let hot = [(24, 24), (105, 72), (201, 153)]; + for &(x, y) in &hot { + set(&mut r, x, y, 9000); + } + assert_eq!(r.suppress_hot_pixels(), 3); + for &(x, y) in &hot { + assert!(get(&r, x, y) < 2700, "({x}, {y}) = {}", get(&r, x, y)); + } + assert_eq!(get(&r, 16, 16), 12000, "a star is left alone"); + } + + #[test] + fn the_limit_is_the_callers() { + let mut r = mosaic(256, 256); + let hot = [(40, 40), (101, 60), (151, 151), (200, 30)]; + for &(x, y) in &hot { + set(&mut r, x, y, 9000); + } + let before = r.data.clone(); + // 4 of 248 × 248 photosites: above a limit of 0.005 %, within 0.01 % + assert_eq!(r.suppress_hot_pixels_with(5e-5), 0); + assert_eq!(r.data, before); + assert_eq!(r.suppress_hot_pixels_with(1e-4), 4); + assert_eq!(r.clone().suppress_hot_pixels_with(f64::NAN), 0, "a limit that is not a number replaces nothing"); + } + + #[test] + fn too_many_candidates_change_nothing() { + let mut r = mosaic(128, 128); + for y in (8..120).step_by(4) { + for x in (8..120).step_by(4) { + set(&mut r, x, y, 12000); + } + } + let before = r.data.clone(); + assert_eq!(r.suppress_hot_pixels(), 0); + assert_eq!(r.data, before); + } +} diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index e8052c3bbb..371891ddf7 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -34,6 +34,7 @@ mod dng; pub mod dngwrite; pub mod gaintable; pub mod highlight; +mod hotpixel; #[cfg(feature = "jxl")] mod jxl; pub mod kelvin_builtin; @@ -55,6 +56,7 @@ mod wb_estimate; pub use demosaic::{Method, demosaic}; pub use dngwrite::{DngCompression, DngWriteOptions, write_dng, write_rendered_dng}; +pub use hotpixel::HOT_PIXEL_MAX_SHARE; pub use lens_metadata::LensMetadata; pub use lightcraft_color::Mat3; pub use lightcraft_geom::Orientation; diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rs index 2b16c441ad..d661439780 100644 --- a/crates/raw/src/preview.rs +++ b/crates/raw/src/preview.rs @@ -138,12 +138,68 @@ fn is_jxl(b: &[u8]) -> bool { b.starts_with(&[0xff, 0x0a]) || b.starts_with(&[0, 0, 0, 0x0c, b'J', b'X', b'L', b' ', 0x0d, 0x0a, 0x87, 0x0a]) } -fn candidates<'a>(data: &'a [u8], ifd: &Ifd, base: u64, out: &mut Vec<&'a [u8]>) { +/// The bytes a file's own (offset, length) pair names, cut at the file's end; `None` when the offset +/// lies past it. Both numbers come from the file: never cast them (a `u64` offset past 4 GiB would +/// wrap to a small, wrong one on a 32-bit build) nor add them unchecked. A span the file's end cuts +/// short is kept only when it is a JPEG whose own end marker is inside it, after its scan (an +/// overstated length with the whole JPEG inside), cut at that marker: a truncated JPEG passes the +/// frame-header check, would win as the largest preview and then fail to decode (CodeRabbit on +/// #3077). An `FF D9` inside an APP payload doesn't count, bytes that don't start a JPEG are refused +/// without a scan, and the walks share `budget` (bytes, as [`scan_with_budget`]'s do), so a file of +/// many such pointers stays linear. +fn file_span<'a>(data: &'a [u8], offset: u64, len: u64, budget: &mut usize) -> Option<&'a [u8]> { + let start = usize::try_from(offset).ok()?; + let wanted = usize::try_from(offset.saturating_add(len)).unwrap_or(usize::MAX); + let span = data.get(start..wanted.min(data.len()))?; + if wanted > data.len() { + return span.get(..jpeg_end(span, budget)?); + } + Some(span) +} + +/// Where the JPEG at the start of `s` ends (just past its end marker), walking its marker segments: +/// a segment's payload is skipped by its stated length (so an `FF D9` inside APP data isn't taken +/// for the end), entropy-coded bytes one at a time (stuffed `FF 00` and restart markers included). +/// `None` when `s` isn't a JPEG, ends first, reaches its end marker before a start of scan (no image +/// data), or the walk spends `budget` (one per step, shared by a file's walks). Each step moves +/// forward, so it ends within `s`. +fn jpeg_end(s: &[u8], budget: &mut usize) -> Option { + if !s.starts_with(&[0xff, 0xd8]) { + return None; + } + let (mut i, mut scanned) = (2usize, false); + loop { + *budget = budget.checked_sub(1)?; + match (s.get(i), s.get(i.checked_add(1)?)) { + (None, _) | (Some(&0xff), None) => return None, + (Some(&0xff), Some(&m)) => match m { + 0xd9 => return if scanned { i.checked_add(2) } else { None }, + // fill byte + 0xff => i += 1, + // stuffed zero, restart marker, TEM: no length follows + 0x00 | 0x01 | 0xd0..=0xd7 => i = i.checked_add(2)?, + _ => { + let (&hi, &lo) = (s.get(i.checked_add(2)?)?, s.get(i.checked_add(3)?)?); + let len = usize::from(u16::from_be_bytes([hi, lo])); + if len < 2 { + return None; + } + scanned |= m == 0xda; + i = i.checked_add(2)?.checked_add(len)?; + } + }, + // entropy-coded data + (Some(_), _) => i += 1, + } + } +} + +fn candidates<'a>(data: &'a [u8], ifd: &Ifd, base: u64, out: &mut Vec<&'a [u8]>, budget: &mut usize) { // whole JPEG files stored as an undefined-type tag value (e.g. Panasonic `JpgFromRaw` 0x002e) for e in &ifd.entries { if matches!(e.value, lightcraft_tiff::Value::Undefined(_)) && e.count() > 1024 - && let Some(s) = data.get(e.offset as usize..(e.offset.saturating_add(e.count() as u64) as usize).min(data.len())) + && let Some(s) = file_span(data, e.offset, e.count() as u64, budget) && s.starts_with(&[0xff, 0xd8]) { out.push(s); @@ -151,7 +207,7 @@ fn candidates<'a>(data: &'a [u8], ifd: &Ifd, base: u64, out: &mut Vec<&'a [u8]>) } if let (Some(off), Some(len)) = (ifd.u64(t::JPEG_INTERCHANGE_FORMAT), ifd.u64(t::JPEG_INTERCHANGE_FORMAT_LENGTH)) { let off = off.saturating_add(base); - if let Some(s) = data.get(off as usize..(off.saturating_add(len) as usize).min(data.len())) { + if let Some(s) = file_span(data, off, len, budget) { out.push(s); } } @@ -196,8 +252,12 @@ fn smallest_covering<'a>(found: &[&'a [u8]], largest: &[u8], min_edge: u32) -> O let (a, b) = (u64::from(w) * u64::from(bh), u64::from(h) * u64::from(bw)); w > 0 && h > 0 && c == bc && a.abs_diff(b) * 100 <= a }; + // (one cut short before its end marker would fail to decode, and nothing would try another: CodeRabbit + // on #3583) + let whole = |s: &[u8]| trim_eoi(s).ends_with(&[0xff, 0xd9]); found .iter() + .filter(|s| whole(s)) .filter_map(|&s| jpeg_frame(s).filter(|&f| like(f) && f.0.max(f.1) >= min_edge).map(|(w, h, _)| (s, w.max(h)))) .min_by_key(|&(_, long)| long) .map(|(s, _)| s) @@ -210,6 +270,20 @@ fn preview_covering(bytes: &[u8], min_edge: Option) -> Option> { } let format = crate::probe(bytes); if format == Some(crate::RawFormat::Cr3) { + // a Canon CR3 keeps its full-size JPEG beside a 1620 px `PRVW` (and a 160 px `THMB`): a + // thumbnail decodes the small copy, not 45 MP of JPEG (about 150 ms a photo, the grid's + // "popcorn" on a folder of R5 / R5 C raws) + // (without a JPEG track, the largest box is the picture's shape: the boxes alone may hold several) + if let Some(min) = min_edge { + let mut found = cr3_preview_box_list(bytes); + let full = cr3_full_jpeg(bytes); + found.extend(full); + if let Some(largest) = full.or_else(|| largest_by_pixels(&found)) + && let Some(j) = smallest_covering(&found, largest, min) + { + return Some(trim_eoi(j).to_vec()); + } + } return cr3_preview(bytes).map(|j| trim_eoi(j).to_vec()); } if matches!(format, Some(crate::RawFormat::Crw | crate::RawFormat::Mrw | crate::RawFormat::X3f)) { @@ -217,8 +291,10 @@ fn preview_covering(bytes: &[u8], min_edge: Option) -> Option> { } let tiff = Tiff::parse(bytes).ok()?; let mut found: Vec<&[u8]> = Vec::new(); + // the walks of pointers past the file's end share one budget (see file_span) + let mut budget = scan_budget(bytes.len()); for ifd in tiff.all_ifds() { - candidates(bytes, ifd, 0, &mut found); + candidates(bytes, ifd, 0, &mut found, &mut budget); } // maker-note preview IFDs (e.g. Nikon PreviewIFD 0x0011 holds JPEGInterchangeFormat relative to the note base) if let Some(exif) = tiff.exif() @@ -226,11 +302,11 @@ fn preview_covering(bytes: &[u8], min_edge: Option) -> Option> { { let make = tiff.find(t::MAKE).and_then(|e| e.value.as_str()).unwrap_or_default(); if let Some(mn) = makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make) { - candidates(bytes, &mn.ifd, mn.base, &mut found); + candidates(bytes, &mn.ifd, mn.base, &mut found, &mut budget); if let Some(off) = mn.ifd.u64(0x0011) && let Ok((pifd, _)) = lightcraft_tiff::parse_ifd_at(bytes, mn.base + off, mn.order, mn.base, false, &Default::default()) { - candidates(bytes, &pifd, mn.base, &mut found); + candidates(bytes, &pifd, mn.base, &mut found, &mut budget); } } } @@ -442,53 +518,123 @@ fn scan_with_budget(data: &[u8], budget: usize) -> (Option>, u64) { /// Canon CR3: the full-size JPEG track (see [`lightcraft_meta::cr3`]), else the `PRVW` / `THMB` boxes. fn cr3_preview(bytes: &[u8]) -> Option<&[u8]> { + cr3_full_jpeg(bytes).or_else(|| cr3_preview_boxes(bytes)) +} + +/// A CR3's full-size JPEG track, when it holds a DCT JPEG. +fn cr3_full_jpeg(bytes: &[u8]) -> Option<&[u8]> { let full = lightcraft_meta::cr3::parse_cr3(bytes) .and_then(|c| c.tracks.iter().find(|t| t.kind == lightcraft_meta::cr3::Cr3TrackKind::Jpeg).and_then(|t| t.data)); - if let Some(j) = full.and_then(|(at, len)| bytes.get(at..at.checked_add(len)?)).filter(|j| is_dct_jpeg(j)) { - return Some(j); - } - cr3_preview_boxes(bytes) + full.and_then(|(at, len)| bytes.get(at..at.checked_add(len)?)).filter(|j| is_dct_jpeg(j)) } -/// Canon CR3 (ISO base media file): the `PRVW` box (Laurent Clévy's CR3 notes; layout confirmed on a CC0 -/// sample) is `u32 size, "PRVW", u32 0, u16 ?, u16 width, u16 height, u16 ?, u32 jpeg length, JPEG`; the smaller -/// `THMB` box has the same shape. Returns the larger valid one. /// Marker-walk budget of the CR3 fallback: candidates can overlap (each claiming the rest of the file) and /// [`is_dct_jpeg`] walks each marker by marker, so walking every candidate would be quadratic in file size. /// The `THMB`/`PRVW` previews this finds are far below the cap together; once it is spent the scan stops. const CR3_MAX_WALK: usize = 8 << 20; +/// Canon CR3 (ISO base media file): the `PRVW` box (Laurent Clévy's CR3 notes; layout confirmed on a CC0 +/// sample) is `u32 size, "PRVW", u32 0, u16 ?, u16 width, u16 height, u16 ?, u32 jpeg length, JPEG`; the smaller +/// `THMB` box has the same shape. Returns the larger valid one. fn cr3_preview_boxes(bytes: &[u8]) -> Option<&[u8]> { - let mut best: Option<&[u8]> = None; + largest_by_pixels(&cr3_preview_box_list(bytes)) +} + +/// Of `found`, the JPEG with the longest edge in pixels (a smaller picture can take more bytes); the +/// first of equals. CodeRabbit on #3077. +fn largest_by_pixels<'a>(found: &[&'a [u8]]) -> Option<&'a [u8]> { + let long = |j: &[u8]| jpeg_frame(j).map_or(0, |(w, h, _)| w.max(h)); + found.iter().copied().rev().max_by_key(|j| long(j)) +} + +/// The valid JPEGs of a CR3's `PRVW` and `THMB` boxes, every one: a file may carry more than one +/// `PRVW`, and the smallest that covers a size is picked from them all. +fn cr3_preview_box_list(bytes: &[u8]) -> Vec<&[u8]> { + let mut out: Vec<&[u8]> = Vec::new(); let mut walked = 0usize; + // the boxes sit outside the media data: only the rest of the file is searched (the media data + // is most of the file, and a thumbnail is asked for every photo in view) + let file = bytes; + // (every top-level `mdat` is left out, not only the first: a PRVW-shaped JPEG in media data is not a + // preview; CodeRabbit on #3583) + let media = cr3_media_data(file); + let whole_file = media.is_empty(); + let mut regions: Vec<&[u8]> = Vec::new(); + let mut from = 0usize; + for (start, end) in media { + if start >= from { + regions.extend(file.get(from..start)); + } + from = from.max(end); + } + regions.extend(file.get(from..)); for tag in [b"PRVW", b"THMB"] { - let mut from = 0; - while let Some(i) = bytes.get(from..).and_then(|s| s.windows(4).position(|w| w == tag)).map(|p| p + from) { - from = i + 4; - let Some(start) = i.checked_sub(4) else { continue }; - let be32 = |at: usize| bytes.get(at..at + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize); - let (Some(size), Some(len)) = (be32(start), be32(start + 20)) else { continue }; - let j = start + 24; - // 32-bit box lengths can wrap `usize` on wasm32: check the sums, then slice with `get` - let (Some(end), Some(lim)) = (j.checked_add(len), start.checked_add(size.max(24))) else { continue }; - if len < 4 || end > lim { - continue; - } - let Some(jpeg) = bytes.get(j..end) else { continue }; - // One that doesn't fit the budget left is skipped; a smaller one later may still fit. - if walked + jpeg.len() > CR3_MAX_WALK { - continue; - } - walked += jpeg.len(); - if is_dct_jpeg(jpeg) { - if best.is_none_or(|b| b.len() < jpeg.len()) { - best = Some(jpeg); - } + // the whole file searched (its media data not found): the first valid box of a kind only, as + // the declared one comes before the media data and a later look-alike must not win + let mut taken = false; + for &bytes in ®ions { + if whole_file && taken { break; } + let mut from = 0; + while let Some(i) = bytes.get(from..).and_then(|s| s.windows(4).position(|w| w == tag)).map(|p| p + from) { + from = i + 4; + let Some(start) = i.checked_sub(4) else { continue }; + // (the sizes are the file's: checked, a 32-bit build must not wrap them) + let be32 = |at: usize| bytes.get(at..at.checked_add(4)?).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize); + let (Some(size), Some(len)) = (be32(start), start.checked_add(20).and_then(be32)) else { continue }; + let (Some(j), Some(box_end)) = (start.checked_add(24), start.checked_add(size.max(24))) else { continue }; + let Some(end) = j.checked_add(len).filter(|e| len >= 4 && *e <= box_end && *e <= bytes.len()) else { continue }; + let Some(jpeg) = bytes.get(j..end) else { continue }; + // One that doesn't fit the budget left is skipped; a smaller one later may still fit. + if walked.saturating_add(jpeg.len()) > CR3_MAX_WALK { + continue; + } + walked = walked.saturating_add(jpeg.len()); + if is_dct_jpeg(jpeg) { + out.push(jpeg); + taken = true; + if whole_file { + break; + } + // (past it: a tag inside its JPEG is not another box) + from = end; + } + } } } - best + out +} + +/// Where a CR3's top-level `mdat` boxes lie (`start..end` each, `end` clamped to the file, in file +/// order): the media data, most of the file. Empty when there is none, or the boxes stop making sense +/// before the first. The metadata and the small previews are in the other top-level boxes. +fn cr3_media_data(bytes: &[u8]) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + let _ = cr3_media_walk(bytes, &mut out); + out +} + +/// [`cr3_media_data`]'s walk of the top-level boxes; `None` where they stop making sense. +fn cr3_media_walk(bytes: &[u8], out: &mut Vec<(usize, usize)>) -> Option<()> { + let be32 = |at: usize| bytes.get(at..at.checked_add(4)?).map(|s| u64::from(u32::from_be_bytes([s[0], s[1], s[2], s[3]]))); + let be64 = |at: usize| bytes.get(at..at.checked_add(8)?).map(|s| u64::from_be_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]])); + let mut at = 0usize; + for _ in 0..64 { + let size = be32(at)?; + let len = match size { + // (a box running to the end of the file) + 0 => u64::try_from(bytes.len().saturating_sub(at)).unwrap_or(u64::MAX), + 1 => be64(at.checked_add(8)?)?, + n => n, + }; + let next = usize::try_from(len).ok().filter(|l| *l >= 8).and_then(|l| at.checked_add(l)); + if bytes.get(at.checked_add(4)?..at.checked_add(8)?) == Some(b"mdat".as_slice()) { + out.push((at, next.unwrap_or(bytes.len()).min(bytes.len()))); + } + at = next.filter(|n| *n < bytes.len())?; + } + None } /// Trim trailing garbage after the last EOI when a stored length over-reports. diff --git a/crates/raw/src/preview/tests.rs b/crates/raw/src/preview/tests.rs index aa2dc0da74..561d39645d 100644 --- a/crates/raw/src/preview/tests.rs +++ b/crates/raw/src/preview/tests.rs @@ -296,6 +296,98 @@ fn cr3_prefers_the_full_size_jpeg_track() { assert_eq!(embedded_preview(&file).unwrap(), small); } +/// A CR3 whose `PRVW` box holds `prvw` and whose JPEG track holds `big`. +fn cr3_with(prvw_jpeg: &[u8], big: &[u8]) -> Vec { + let bx = |kind: &[u8; 4], body: &[u8]| -> Vec { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; + let full = |kind: &[u8; 4], body: &[u8]| bx(kind, &[&[0u8; 4][..], body].concat()); + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + let mut prvw = b"\0\0\0\0\0\x01\x06T\x048\0\x01".to_vec(); + prvw.extend_from_slice(&(prvw_jpeg.len() as u32).to_be_bytes()); + prvw.extend_from_slice(prvw_jpeg); + file.extend(bx(b"PRVW", &prvw)); + let mut craw = vec![0u8; 82]; + craw.extend(bx(b"JPEG", &[0; 4])); + let at = 4096u64; + let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat()); + let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat()); + let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat()); + let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat())))); + file.extend(bx(b"moov", &trak)); + file.resize(at as usize, 0); + file.extend_from_slice(big); + file +} + +/// A CR3 thumbnail decodes the 1620 px `PRVW` copy, not the full-size JPEG (PERF-THUMB-FIRST: +/// 150 ms a photo for the full one); a size the copy can't cover, and the largest preview, are +/// still the full JPEG; a `PRVW` of another shape is never taken for the picture. +#[test] +fn cr3_thumbnails_take_the_smallest_copy_that_covers_them() { + let (prvw, big) = (sized_jpeg(1620, 1080, 3, 300), sized_jpeg(6000, 4000, 3, 3000)); + let file = cr3_with(&prvw, &big); + assert_eq!(embedded_preview_covering(&file, 512).unwrap(), prvw); + assert_eq!(embedded_preview_covering(&file, 1620).unwrap(), prvw); + assert_eq!(embedded_preview_covering(&file, 2000).unwrap(), big); + assert_eq!(embedded_preview(&file).unwrap(), big); + let letterboxed = cr3_with(&sized_jpeg(1620, 1215, 3, 300), &big); + assert_eq!(embedded_preview_covering(&letterboxed, 512).unwrap(), big, "another shape is not a copy"); + for n in (0..file.len()).step_by(13) { + let _ = embedded_preview_covering(&file[..n], 512); + } +} + +/// PERF-CULL-4: the smallest preview that covers the size asked for, of the largest one's shape; +/// the largest when none covers it. A CR3's 8192 px track, 1620 px `PRVW` and 160 px `THMB`. +#[test] +fn the_smallest_preview_covering_the_size_is_chosen() { + let bx = |kind: &[u8; 4], body: &[u8]| -> Vec { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; + let full = |kind: &[u8; 4], body: &[u8]| bx(kind, &[&[0u8; 4][..], body].concat()); + let boxed = |j: &[u8]| { + let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec(); + b.extend_from_slice(&(j.len() as u32).to_be_bytes()); + b.extend_from_slice(j); + b + }; + let (thmb, prvw, big) = (sized_jpeg(160, 107, 1, 50), sized_jpeg(1620, 1080, 1, 300), sized_jpeg(8192, 5464, 1, 3000)); + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"THMB", &boxed(&thmb))); + file.extend(bx(b"PRVW", &boxed(&prvw))); + let mut craw = vec![0u8; 82]; + craw.extend(bx(b"JPEG", &[0; 4])); + let at = 4096u64; + let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat()); + let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat()); + let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat()); + let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat())))); + file.extend(bx(b"moov", &trak)); + file.resize(at as usize, 0); + file.extend_from_slice(&big); + assert_eq!(embedded_preview(&file).unwrap(), big); + assert_eq!(embedded_preview_covering(&file, 512).unwrap(), prvw, "a grid thumbnail"); + assert_eq!(embedded_preview_covering(&file, 1620).unwrap(), prvw); + assert_eq!(embedded_preview_covering(&file, 100).unwrap(), thmb); + assert_eq!(embedded_preview_covering(&file, 2560).unwrap(), big, "a large loupe"); + assert_eq!(embedded_preview_covering(&file, u32::MAX).unwrap(), big); + // a smaller preview of another shape (letterboxed 16:9) is never a stand-in for the 3:2 one + let mut wide = file.clone(); + let p = wide.windows(4).position(|w| w == b"PRVW").unwrap(); + // the JPEG starts 20 bytes after the tag; its frame height 7 bytes into it + let height = p + 20 + 7; + wide[height..height + 2].copy_from_slice(&911u16.to_be_bytes()); + assert_eq!(embedded_preview_covering(&wide, 512).unwrap(), big); + // without the JPEG track the boxes are chosen from too: the smallest that covers, else the largest + // (CodeRabbit on #3577: a box-only CR3 always gave its largest box) + let boxes_only = &file[..file.windows(4).position(|w| w == b"moov").unwrap() - 4]; + assert_eq!(embedded_preview_covering(boxes_only, 100).unwrap(), thmb); + assert_eq!(embedded_preview_covering(boxes_only, 512).unwrap(), prvw); + assert_eq!(embedded_preview_covering(boxes_only, 2560).unwrap(), prvw, "none covers: the largest"); + assert_eq!(embedded_preview(boxes_only).unwrap(), prvw); + // damaged files never panic + for n in (0..file.len()).step_by(7) { + let _ = embedded_preview_covering(&file[..n], 512); + } +} + /// A minimal CR3 whose Canon box holds `CMT2` (EXIF ColorSpace `exif`) and `CMT3` (maker-note ColorSpace `note`). fn cr3_with_color_space(exif: Option, note: Option) -> Vec { let bx = |kind: &[u8; 4], body: &[u8]| -> Vec { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; @@ -502,3 +594,261 @@ fn scanned_containers_give_the_largest_colour_jpeg() { f.extend_from_slice(&mosaic); assert_eq!(embedded_preview(&f), None); } + +/// A CR3's `PRVW` / `THMB` boxes are searched outside the media data only, but before and after +/// it: a `moov` after the `mdat` (its Canon `uuid` holding the `THMB`) still gives its preview, and +/// bytes inside the media data that look like a preview box are never taken for one. +#[test] +fn cr3_preview_boxes_after_the_media_data_are_found() { + let bx = |kind: &[u8; 4], body: &[u8]| -> Vec { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; + let boxed = |j: &[u8]| { + let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec(); + b.extend_from_slice(&(j.len() as u32).to_be_bytes()); + b.extend_from_slice(j); + b + }; + let (thmb, in_media) = (sized_jpeg(160, 107, 1, 50), sized_jpeg(1620, 1080, 1, 300)); + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"mdat", &bx(b"PRVW", &boxed(&in_media)))); + file.extend(bx(b"moov", &bx(b"uuid", &[&[0x85u8; 16][..], &bx(b"THMB", &boxed(&thmb))].concat()))); + assert_eq!(embedded_preview(&file).unwrap(), thmb); + for n in (0..file.len()).step_by(5) { + let _ = embedded_preview(&file[..n]); + } +} + +/// Every valid `PRVW` of a CR3 is a candidate (CodeRabbit on #3055): with a small one first and +/// one that covers the size after it, a thumbnail takes the second, not the full-size track. +#[test] +fn a_cr3_with_two_prvw_boxes_offers_both() { + let bx = |kind: &[u8; 4], body: &[u8]| -> Vec { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; + let full = |kind: &[u8; 4], body: &[u8]| bx(kind, &[&[0u8; 4][..], body].concat()); + let boxed = |j: &[u8]| { + let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec(); + b.extend_from_slice(&(j.len() as u32).to_be_bytes()); + b.extend_from_slice(j); + b + }; + let (small, covering, big) = (sized_jpeg(300, 200, 1, 50), sized_jpeg(1620, 1080, 1, 300), sized_jpeg(8192, 5464, 1, 3000)); + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"PRVW", &boxed(&small))); + file.extend(bx(b"PRVW", &boxed(&covering))); + let mut craw = vec![0u8; 82]; + craw.extend(bx(b"JPEG", &[0; 4])); + let at = 4096u64; + let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat()); + let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat()); + let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat()); + let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat())))); + file.extend(bx(b"moov", &trak)); + // (the track in the media data, as a camera writes it, after a `free` box up to it) + let pad = at as usize - 16 - file.len(); + file.extend(bx(b"free", &vec![0u8; pad])); + file.extend(bx(b"mdat", &big)); + assert_eq!(embedded_preview_covering(&file, 1024).unwrap(), covering); + assert_eq!(embedded_preview_covering(&file, 200).unwrap(), small); +} + +/// A CR3 preview box claiming the largest sizes a file can give is skipped, never wrapped or +/// panicked on (CodeRabbit on #3080: on a 32-bit build the plain sums could overflow). +#[test] +fn a_cr3_preview_box_with_hostile_sizes_is_skipped() { + let mut file = b"\0\0\0\x18ftypcrx \0\0\0\x01crx isom".to_vec(); + file.extend_from_slice(&u32::MAX.to_be_bytes()); + file.extend_from_slice(b"PRVW\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01"); + file.extend_from_slice(&u32::MAX.to_be_bytes()); + file.extend_from_slice(&fake_jpeg(64)); + assert!(embedded_preview(&file).is_none()); + assert!(embedded_preview_covering(&file, 64).is_none()); +} + +/// A corrupt raw whose preview pointer (JPEGInterchangeFormat and its length) lies past the end +/// of the file, or whose length runs past it, finds no preview and never panics; a real preview +/// beside the lying pointer is still found (FredApps on #3080: the preview must be read with +/// bounds on its offset and size). +#[test] +fn a_preview_pointer_past_the_end_of_the_file_finds_no_preview() { + let real = sized_jpeg(640, 480, 3, 200); + let lying = |off: u32, len: u32, with_real: bool| { + let mut ifd = IfdBuilder::new(); + ifd.set(t::JPEG_INTERCHANGE_FORMAT, Value::Long(vec![off])); + ifd.set(t::JPEG_INTERCHANGE_FORMAT_LENGTH, Value::Long(vec![len])); + if with_real { + ifd.set(t::COMPRESSION, Value::Short(vec![6])); + ifd.set(t::IMAGE_WIDTH, Value::Long(vec![1])); + ifd.set(t::IMAGE_LENGTH, Value::Long(vec![1])); + ifd.set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![real.clone()] }); + } + TiffWriter::default().write(&[ifd]).unwrap() + }; + let short = lying(0, 0, false).len() as u32; + for (off, len) in [(u32::MAX, u32::MAX), (u32::MAX, 16), (short + 10, 4096), (8, u32::MAX), (short - 2, u32::MAX - 1)] { + let file = lying(off, len, false); + assert_eq!(embedded_preview(&file), None, "pointer {off:#x}+{len:#x} in a {} byte file", file.len()); + assert_eq!(embedded_preview_covering(&file, 64), None); + assert_eq!(embedded_preview_color_space(&file), None); + let with_real = lying(off, len, true); + assert_eq!(embedded_preview(&with_real).as_deref(), Some(&real[..]), "the strip preview beside pointer {off:#x}+{len:#x}"); + // and every truncation of the file (a raw cut short by a failed copy) is safe too + for n in 0..with_real.len() { + let _ = embedded_preview_covering(&with_real[..n], 64); + } + } +} + +/// A preview pointer whose length runs past the end of a file that cuts its JPEG short (no end +/// marker) finds no preview, so a smaller whole one wins; an overstated length whose JPEG is whole +/// inside the file still finds it (CodeRabbit on #3077). +#[test] +fn a_preview_cut_short_by_the_end_of_the_file_is_not_taken() { + let big = sized_jpeg(1600, 1200, 3, 4000); + let small = sized_jpeg(160, 120, 3, 100); + // the small JPEG as a strip, the big one pointed to at the end of the file + let with_tail = |tail: &[u8], declared: u32| { + let probe = { + let mut ifd = IfdBuilder::new(); + ifd.set(t::JPEG_INTERCHANGE_FORMAT, Value::Long(vec![0])); + ifd.set(t::JPEG_INTERCHANGE_FORMAT_LENGTH, Value::Long(vec![0])); + ifd.set(t::COMPRESSION, Value::Short(vec![6])); + ifd.set(t::IMAGE_WIDTH, Value::Long(vec![1])); + ifd.set(t::IMAGE_LENGTH, Value::Long(vec![1])); + ifd.set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![small.clone()] }); + ifd + }; + let at = TiffWriter::default().write(&[probe]).unwrap().len() as u32; + let mut ifd = IfdBuilder::new(); + ifd.set(t::JPEG_INTERCHANGE_FORMAT, Value::Long(vec![at])); + ifd.set(t::JPEG_INTERCHANGE_FORMAT_LENGTH, Value::Long(vec![declared])); + ifd.set(t::COMPRESSION, Value::Short(vec![6])); + ifd.set(t::IMAGE_WIDTH, Value::Long(vec![1])); + ifd.set(t::IMAGE_LENGTH, Value::Long(vec![1])); + ifd.set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![small.clone()] }); + let mut file = TiffWriter::default().write(&[ifd]).unwrap(); + assert_eq!(file.len() as u32, at, "the pointer lands right after the TIFF"); + file.extend_from_slice(tail); + file + }; + // the big one with a start of scan after its frame header (sized_jpeg has none), as a real JPEG + let mut big = big; + big.splice(21..21, [0xff, 0xda, 0x00, 0x02]); + let declared = big.len() as u32 + 64; + // cut short: half of the big JPEG, no end marker + let cut = with_tail(&big[..big.len() / 2], declared); + assert_eq!(embedded_preview(&cut).as_deref(), Some(&small[..]), "the truncated JPEG is not taken"); + // whole, its length overstated past the file's end: still the largest + let whole = with_tail(&big, declared); + assert_eq!(embedded_preview(&whole).as_deref(), Some(&big[..]), "a whole JPEG with an overstated length is kept"); + // an end marker inside an APP1 payload is not the JPEG's end: cut short, still not taken + let mut with_app = vec![0xff, 0xd8, 0xff, 0xe1, 0x00, 0x08, 0x12, 0xff, 0xd9, 0x34, 0x56, 0x78]; + with_app.extend_from_slice(&big[2..]); + let declared = with_app.len() as u32 + 64; + let cut = with_tail(&with_app[..with_app.len() / 2], declared); + assert_eq!(embedded_preview(&cut).as_deref(), Some(&small[..]), "an FF D9 in APP1 doesn't make a cut JPEG whole"); + // whole, with other bytes after it up to the file's end: kept, cut at its own end marker + let mut tail = with_app.clone(); + tail.extend_from_slice(&[0x11, 0xff, 0xd9, 0x22]); + let whole = with_tail(&tail, declared); + assert_eq!(embedded_preview(&whole).as_deref(), Some(&with_app[..]), "a whole JPEG is cut at its own end"); + // an end marker before any start of scan: no image data, not taken (CodeRabbit on #3080) + let unscanned = sized_jpeg(1600, 1200, 3, 4000); + let whole = with_tail(&unscanned, unscanned.len() as u32 + 64); + assert_eq!(embedded_preview(&whole).as_deref(), Some(&small[..]), "a JPEG without a scan is not taken"); +} + +/// The walk to a JPEG's end refuses what isn't one and never runs past the bytes it has. +#[test] +fn the_end_of_a_jpeg_is_its_own_end_marker() { + let jpeg_end = |s: &[u8]| super::jpeg_end(s, &mut (1usize << 20)); + assert_eq!(jpeg_end(&[0x12, 0x34, 0xff, 0xd9]), None, "not a JPEG"); + assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xd9]), None, "an end before any scan: no image data"); + // a stuffed zero and a restart marker in the scan data, then the end + assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xda, 0x00, 0x02, 0x55, 0xff, 0x00, 0xff, 0xd3, 0x66, 0xff, 0xd9]), Some(14)); + // a segment length of 0 or 1, or one running past the end + assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xe1, 0x00, 0x01, 0xff, 0xd9]), None); + assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xe1, 0xff, 0xff, 0xff, 0xd9]), None); + for n in 0..12 { + assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xe1, 0x00, 0x04, 0xff, 0xd9, 0x55, 0xff, 0xff, 0xff][..n]), None, "{n} bytes"); + } +} + +/// CodeRabbit on #3080: the walks to a JPEG's end share one budget, so a file of many pointers past +/// its end can't make each walk run the whole file: a walk that would overspend it gives up. +#[test] +fn the_walks_to_a_jpegs_end_share_a_budget() { + use super::jpeg_end; + let mut j = vec![0xff, 0xd8, 0xff, 0xda, 0x00, 0x02]; + j.extend(std::iter::repeat_n(0x55u8, 1000)); + j.extend_from_slice(&[0xff, 0xd9]); + let mut budget = 1500; + assert_eq!(jpeg_end(&j, &mut budget), Some(j.len()), "the first walk fits"); + assert!(budget < 1500 - 1000, "and is charged for its steps: {budget} left"); + assert_eq!(jpeg_end(&j, &mut budget), None, "the second would overspend what is left"); + assert_eq!(budget, 0); +} + +/// A CR3 without a JPEG track whose smaller `PRVW` (another shape) takes more bytes: the picture is +/// the box with the most pixels, not the most bytes (CodeRabbit on #3077). +#[test] +fn a_box_only_cr3_is_judged_by_pixels_not_bytes() { + let bx = |kind: &[u8; 4], body: &[u8]| -> Vec { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; + let boxed = |j: &[u8]| { + let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec(); + b.extend_from_slice(&(j.len() as u32).to_be_bytes()); + b.extend_from_slice(j); + b + }; + let (big, square) = (sized_jpeg(1620, 1080, 3, 300), sized_jpeg(800, 800, 3, 5000)); + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"PRVW", &boxed(&square))); + file.extend(bx(b"PRVW", &boxed(&big))); + // no media data found: the whole file is searched, and only its first box counts (a later look-alike could be + // in media data; CodeRabbit on #3583) + assert_eq!(embedded_preview(&file).unwrap(), square); + file.extend(bx(b"mdat", &[0u8; 16])); + assert_eq!(embedded_preview(&file).unwrap(), big); + assert_eq!(embedded_preview_covering(&file, 100).unwrap(), big, "the square is another picture's shape"); +} + +/// Every top-level `mdat` is media data, not only the first: a PRVW-shaped JPEG in a second one is +/// never the preview; and a `PRVW` cut short before its end marker isn't chosen to cover a size +/// (CodeRabbit on #3583). +#[test] +fn cr3_boxes_in_any_media_data_or_cut_short_are_not_previews() { + let bx = |kind: &[u8; 4], body: &[u8]| -> Vec { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; + let boxed = |j: &[u8]| { + let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec(); + b.extend_from_slice(&(j.len() as u32).to_be_bytes()); + b.extend_from_slice(j); + b + }; + let (real, fake) = (sized_jpeg(1620, 1080, 3, 300), sized_jpeg(3000, 2000, 3, 300)); + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"PRVW", &boxed(&real))); + file.extend(bx(b"mdat", &[0u8; 64])); + file.extend(bx(b"mdat", &bx(b"PRVW", &boxed(&fake)))); + assert_eq!(embedded_preview(&file).unwrap(), real, "the look-alike in the second mdat is media data"); + // a PRVW cut short (no end marker): the full-size track covers a thumbnail instead + let mut short = real.clone(); + short.truncate(real.len() - 2); + let big = sized_jpeg(6000, 4000, 3, 3000); + assert_eq!(embedded_preview_covering(&cr3_with(&short, &big), 512).unwrap(), big); + assert_eq!(embedded_preview_covering(&cr3_with(&real, &big), 512).unwrap(), real, "a whole one is still taken"); +} + +/// The copy a CR3 thumbnail is given decodes, whichever is chosen (CodeRabbit on #3583: the other CR3 fixtures have +/// no scan): real encoded JPEGs, the `PRVW` for a small size, the full-size track past it. +#[test] +fn the_cr3_copy_chosen_for_a_thumbnail_decodes() { + let encode = |w: u16, h: u16| { + let px: Vec = (0..usize::from(w) * usize::from(h)).flat_map(|i| [(i % 251) as u8, 90, 160]).collect(); + let mut j = Vec::new(); + jpeg_encoder::Encoder::new(&mut j, 85).encode(&px, w, h, jpeg_encoder::ColorType::Rgb).unwrap(); + j + }; + let file = cr3_with(&encode(96, 64), &encode(384, 256)); + for (min, want) in [(64u32, (96, 64)), (200, (384, 256))] { + let j = embedded_preview_covering(&file, min).unwrap(); + let (_, w, h, c) = crate::tiffraw::lossy_jpeg(&j, 3, 1 << 20).unwrap(); + assert_eq!(((w, h), c), (want, 3), "covering {min} px"); + } +} diff --git a/crates/ui-egui/examples/thumb_request_bench.rs b/crates/ui-egui/examples/thumb_request_bench.rs index ada42356de..980434b317 100644 --- a/crates/ui-egui/examples/thumb_request_bench.rs +++ b/crates/ui-egui/examples/thumb_request_bench.rs @@ -168,7 +168,7 @@ fn verify_texture(h: &Headless, id: PhotoId) { let edge = tex.size[0].max(tex.size[1]); assert!([128, 256, 384, 512].contains(&edge), "thumbnail must use a supported size bucket"); let Source::File { path } = &p.source else { unreachable!() }; - let (source, info) = h.app.session.media.file_loader.as_ref().unwrap()(path, 512, None).unwrap(); + let (source, info) = h.app.session.media.file_loader.as_ref().unwrap()(path, 512, Default::default()).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.json b/crates/ui-egui/locales/cs.json index 0b142df5e6..51851dda54 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -23,9 +23,6 @@ "A pen's pressure sets the size and flow of the brush": "Přítlak pera určuje velikost a tok štětce", "AI Denoise": "Redukce šumu pomocí AI", "AI Denoise Model": "Model pro redukci šumu pomocí AI", - "AI Denoise is enabled on the requesting photo": "Redukce šumu pomocí AI je u požadované fotografie zapnutá", - "AI Denoise is off: press Use on a model.": "Redukce šumu pomocí AI je vypnutá: u modelu klikněte na Použít.", - "AI Denoise needs a model. Install one in Settings.": "Redukce šumu pomocí AI vyžaduje model. Nainstalujte jej v Nastavení.", "AI Mask Model Status": "Stav modelu pro maskování pomocí AI", "About": "O aplikaci", "About LightCraft": "O aplikaci LightCraft", @@ -183,7 +180,6 @@ "After 7 days": "Po 7 dnech", "After 90 days": "Po 90 dnech", "After a year": "Po roce", - "After installation, AI Denoise will turn on for the requesting photo.": "Po instalaci se u požadované fotografie zapne redukce šumu pomocí AI.", "Album": "Album", "Albums": "Alba", "Albums hold library photos: Add to My Photos first": "Alba obsahují fotografie z knihovny: nejprve je přidejte do mých fotografií", @@ -333,9 +329,7 @@ "Cancel Download": "Zrušit stahování", "Cancel Face Model Download": "Zrušit stahování modelu rozpoznávání obličejů", "Cancel Interaction": "Zrušit interakci", - "Cancel Pending Photo Action": "Zrušit čekající akci s fotografií", "Cancel Preview Build": "Zrušit vytváření náhledů", - "Cancel pending action": "Zrušit čekající akci", "Candidate": "Kandidát", "Caption": "Popisek", "Capture Date": "Datum pořízení", @@ -945,10 +939,8 @@ "Inspecting Lightroom Catalog": "Prohlížení katalogu Lightroom", "Install Denoise Model": "Nainstalovat model pro redukci šumu", "Install Face Model": "Nainstalovat model rozpoznávání obličejů", - "Install a denoise model to enable AI Denoise on this photo": "Chcete-li u této fotografie zapnout redukci šumu pomocí AI, nainstalujte model", "Install from file…": "Nainstalovat ze souboru…", "Install the SAM 3 Model": "Nainstalovat model SAM 3", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Nainstalujte vlastní model ONNX se souborem denoise-model.json vedle něj. Toto sestavení nenabízí stahování modelů.", "Instant ’70s": "Instantní sedmdesátky", "Intent:": "Záměr:", "Interface": "Rozhraní", @@ -1245,6 +1237,7 @@ "Specific folder": "Konkrétní složka", "Same folder as original photo": "Stejná složka jako původní fotografie", "Tidying the thumbnail cache": "Úklid mezipaměti miniatur", + "Checking free disk space": "Kontrola volného místa na disku", "No masks yet. Choose a mask type above.": "Zatím žádné masky. Vyberte typ masky nahoře.", "No matching commands": "Žádné odpovídající příkazy", "No matching photos": "Žádné odpovídající fotografie", @@ -1352,8 +1345,6 @@ "Paste pages": "Vložit stránky", "Pastel Haze": "Pastelový opar", "Pen Pressure": "Přítlak pera", - "Pending photo action cancelled": "Čekající akce s fotografií byla zrušena", - "Pending photo action cancelled because its library or photo changed": "Čekající akce byla zrušena, protože se změnila knihovna nebo fotografie", "People": "Lidé", "People Count": "Počet osob", "Percent": "Procenta", @@ -1747,7 +1738,6 @@ "Set date & time": "Nastavit datum a čas", "Set name": "Název sady", "Set the mix from the photo's colours": "Nastavit směs podle barev fotografie", - "Set up AI Denoise…": "Nastavit redukci šumu pomocí AI…", "Settings": "Nastavení", "Settings file problem": "Problém souboru nastavení", "Settings new raw photos start from. Changing them doesn't touch photos already in the library.": "Výchozí nastavení nových fotografií RAW. Jejich změna neovlivní fotografie, které již jsou v knihovně.", @@ -1943,9 +1933,7 @@ "Thirds": "Třetiny", "This Computer": "Tento počítač", "This build can't download the model yet. To install it by hand, put model.safetensors, vocab.json and merges.txt from Meta's facebook/sam3 in the folder above: Object and Describe work as soon as they are there.": "Toto sestavení zatím neumí model stáhnout. Pro ruční instalaci vložte model.safetensors, vocab.json a merges.txt z facebook/sam3 společnosti Meta do složky výše: Objekt a Popsat budou fungovat, jakmile tam soubory budou.", - "This build cannot run denoise models.": "Toto sestavení neumí spouštět modely pro redukci šumu.", "This build cannot run recognition models: they can be added and chosen, not used.": "Toto sestavení neumí spouštět modely rozpoznávání: lze je přidat a vybrat, ale nelze je použít.", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "Toto sestavení nemá kam ukládat modely pro redukci šumu, takže redukce šumu pomocí AI není dostupná. (Desktopová aplikace tuto možnost má.)", "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "Toto sestavení nemá kam ukládat modely obličejů, takže seznam modelů není dostupný. (Desktopová aplikace tuto možnost má.)", "This file cannot be used yet": "Tento soubor zatím nelze použít", "This folder is not available (drive disconnected?). Smart previews are not built or used until it is back or you choose another folder.": "Tato složka není dostupná (odpojený disk?). Inteligentní náhledy se nevytvářejí ani nepoužívají, dokud nebude znovu dostupná nebo nezvolíte jinou složku.", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 552ce68016..a89c918694 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -1229,6 +1229,7 @@ "Remove (H)": "Entfernen (H)", "Remove CA": "Chromatische Aberration entfernen", "Remove Chromatic Aberration": "Chromatische Aberration entfernen", + "Remove Hot Pixels": "Hotpixel entfernen", "Camera local tone mapping": "Lokale Tonwertzuordnung der Kamera", "Apply the local tone mapping stored in the raw (Apple ProRAW), as the camera renders it": "Die in der RAW-Datei gespeicherte lokale Tonwertzuordnung (Apple ProRAW) anwenden, wie die Kamera sie rendert", "Remove Disk from Library": "Datenträger aus Bibliothek entfernen", @@ -1867,8 +1868,6 @@ "Back to this person": "Zurück zu dieser Person", "AI Denoise": "KI-Entrauschen", "AI Denoise Model": "KI-Entrauschungsmodell", - "AI Denoise is off: press Use on a model.": "KI-Entrauschen ist aus: Klicke bei einem Modell auf „Verwenden“.", - "AI Denoise needs a model. Install one in Settings.": "KI-Entrauschen benötigt ein Modell. Installiere eines in den Einstellungen.", "Accept & Download": "Akzeptieren und herunterladen", "Already installed. Remove it before installing a replacement.": "Bereits installiert. Entferne es, bevor du einen Ersatz installierst.", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "Automatisch verwendet die Grafikkarte, wo sie schneller als der Prozessor ist: Beide werden beim ersten berechneten Foto auf diesem Computer gemessen.", @@ -1887,7 +1886,6 @@ "Inspect Denoise Model": "Entrauschungsmodell prüfen", "Install Denoise Model": "Entrauschungsmodell installieren", "Install from file…": "Aus Datei installieren…", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Installiere ein eigenes ONNX-Modell mit einer denoise-model.json daneben. Diese Version bietet keine Modelldownloads an.", "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "Sein entrauschtes Bild ist noch nicht berechnet, und Bilder werden nicht automatisch berechnet (Einstellungen, KI-Entrauschen).", "LightCraft does not know this model, so it assumed:": "LightCraft kennt dieses Modell nicht und hat daher angenommen:", "Limit": "Grenze", @@ -1900,7 +1898,6 @@ "Open the model's page": "Seite des Modells öffnen", "Opens the model's own page in your browser, to read about it or get the file yourself.": "Öffnet die Seite des Modells im Browser, um mehr darüber zu lesen oder die Datei selbst herunterzuladen.", "Processor": "Prozessor", - "Set up AI Denoise…": "KI-Entrauschen einrichten…", "Speed": "Geschwindigkeit", "Starting…": "Wird gestartet…", "Tested and works on this computer": "Getestet, funktioniert auf diesem Computer", @@ -1909,8 +1906,6 @@ "The model is kept on this computer only. LightCraft never uploads or shares it.": "Das Modell bleibt nur auf diesem Computer. LightCraft lädt es nie hoch und gibt es nie weiter.", "The processor does the work.": "Der Prozessor erledigt die Arbeit.", "There is no model file to install": "Es gibt keine Modelldatei zum Installieren", - "This build cannot run denoise models.": "Diese Version kann keine Entrauschungsmodelle ausführen.", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "Diese Version hat keinen Speicherort für Entrauschungsmodelle, daher ist KI-Entrauschen nicht verfügbar. (Die Desktop-App schon.)", "This file cannot be used yet": "Diese Datei kann noch nicht verwendet werden", "Tick the box to accept the model's terms first": "Setze zuerst das Häkchen, um die Bedingungen des Modells zu akzeptieren", "Try again": "Erneut versuchen", @@ -1947,12 +1942,6 @@ "Download Denoise Model": "Entrauschungsmodell herunterladen", "Remove Denoise Model": "Entrauschungsmodell entfernen", "Test Denoise Model": "Entrauschungsmodell testen", - "AI Denoise is enabled on the requesting photo": "KI-Entrauschen ist für das anfragende Foto aktiviert", - "After installation, AI Denoise will turn on for the requesting photo.": "Nach der Installation wird KI-Entrauschen für das anfragende Foto eingeschaltet.", - "Cancel pending action": "Ausstehende Aktion abbrechen", - "Install a denoise model to enable AI Denoise on this photo": "Installiere ein Entrauschungsmodell, um KI-Entrauschen für dieses Foto zu aktivieren", - "Pending photo action cancelled": "Ausstehende Fotoaktion abgebrochen", - "Pending photo action cancelled because its library or photo changed": "Ausstehende Fotoaktion abgebrochen, weil sich die Bibliothek oder das Foto geändert hat", "ONNX model": "ONNX-Modell", "commercial use subject to GPL conditions": "kommerzielle Nutzung unter GPL-Bedingungen", "Decrease Rating": "Bewertung verringern", @@ -2180,7 +2169,6 @@ "Adding to Apple Photos": "Wird zu Apple Fotos hinzugefügt", "Add Face Model…": "Gesichtsmodell hinzufügen…", "Cancel Face Model Download": "Download des Gesichtsmodells abbrechen", - "Cancel Pending Photo Action": "Ausstehende Fotoaktion abbrechen", "Choose Face Recognition Model": "Gesichtserkennungsmodell wählen", "Choose a model below (Use) to start.": "Wähle unten ein Modell („Verwenden“), um zu beginnen.", "Detect Faces": "Gesichter erkennen", @@ -2329,6 +2317,7 @@ "Specific folder": "Bestimmter Ordner", "Same folder as original photo": "Im selben Ordner wie das Originalfoto", "Tidying the thumbnail cache": "Miniaturcache wird aufgeräumt", + "Checking free disk space": "Freier Speicherplatz wird geprüft", "Reset all edits (Cmd+Shift+R)": "Alle Bearbeitungen zurücksetzen (⌘⇧R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Smart-Alben aktualisieren sich selbst: Ändere ihre Regeln oder verwende Foto → Foto löschen", "LightCraft stopped": "LightCraft wurde beendet", @@ -3459,6 +3448,8 @@ "The photos are imported once it ends": "Die Fotos werden danach importiert", "An import is running. Drop photos when it has finished": "Ein Import läuft. Lege die Fotos ab, wenn er fertig ist", "Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst", + "Camera preview": "Kameravorschau", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "Das eigene JPEG der Kamera, angezeigt, bis LightCraft die Raw-Datei gerendert hat. Farbe und Tonwerte am gerenderten Foto beurteilen.", "Profile: from the file (the camera's own correction)": "Profil: aus der Datei (Korrektur der Kamera)", "Downloading the lens database…": "Objektivdatenbank wird geladen…", "This file names no lens.": "Diese Datei nennt kein Objektiv.", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index b82a261256..101d7c4fb0 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -187,7 +187,6 @@ "Cancel Download": "Cancelar descarga", "Cancel Face Model Download": "Cancelar la descarga del modelo de caras", "Cancel Interaction": "Cancelar interacción", - "Cancel Pending Photo Action": "Cancelar la acción pendiente sobre la foto", "Canon CR2 photos from the EOS 7D, 50D, 60D, 550D, 600D, 1200D, 1300D, 5D Mark II and 1D Mark IV (and other": "Fotos CR2 de Canon de las EOS 7D, 50D, 60D, 550D, 600D, 1200D, 1300D, 5D Mark II y 1D Mark IV (y otros", "Canon CR3 files show their full-size embedded JPEG (e.g. 6960 × 4640 on an EOS R6 Mark III) instead of the": "Los archivos CR3 de Canon muestran su JPEG incrustado a tamaño completo (p. ej., 6960 × 4640 en una EOS R6 Mark III) en lugar de la", "Canon EOS R5 Mark II C-RAW files that opened as \"preview only\" (more than half of them, depending on the": "Los archivos C-RAW de la Canon EOS R5 Mark II que se abrían como «solo vista previa» (más de la mitad, según la", @@ -1882,8 +1881,6 @@ "Back to this person": "Volver a esta persona", "AI Denoise": "Reducción de ruido con IA", "AI Denoise Model": "Modelo de reducción de ruido con IA", - "AI Denoise is off: press Use on a model.": "La reducción de ruido con IA está desactivada: pulsar Usar en un modelo.", - "AI Denoise needs a model. Install one in Settings.": "La reducción de ruido con IA necesita un modelo. Instalar uno en Ajustes.", "Accept & Download": "Aceptar y descargar", "Already installed. Remove it before installing a replacement.": "Ya está instalado. Quitarlo antes de instalar uno nuevo.", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "Automático usa la tarjeta gráfica cuando es más rápida que el procesador: ambos se cronometran en este equipo la primera vez que se genera una foto.", @@ -1905,7 +1902,6 @@ "Install Face Model": "Instalar modelo de caras", "JPEG with the same name (`IMG_0001.CR3` + `IMG_0001.JPG`) no longer share one sidecar: the raw keeps `IMG_0001.xmp`,": "JPEG con el mismo nombre (`IMG_0001.CR3` + `IMG_0001.JPG`) ya no comparten un archivo complementario: el raw conserva `IMG_0001.xmp`,", "Install from file…": "Instalar desde archivo…", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Instalar un modelo ONNX propio con denoise-model.json junto a él. Esta versión no ofrece descargas de modelos.", "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "Su imagen sin ruido aún no se ha generado, y las imágenes no se generan por sí solas (Ajustes, Reducción de ruido con IA).", "LightCraft does not know this model, so it assumed:": "LightCraft no conoce este modelo, así que supuso:", "Limit": "Límite", @@ -1918,7 +1914,6 @@ "Open the model's page": "Abrir la página del modelo", "Opens the model's own page in your browser, to read about it or get the file yourself.": "Abre la página del modelo en el navegador, para leer sobre él u obtener el archivo a mano.", "Processor": "Procesador", - "Set up AI Denoise…": "Configurar la reducción de ruido con IA…", "Speed": "Velocidad", "Starting…": "Iniciando…", "Tested and works on this computer": "Probado y funciona en este equipo", @@ -1927,9 +1922,7 @@ "The model is kept on this computer only. LightCraft never uploads or shares it.": "El modelo se guarda solo en este equipo. LightCraft nunca lo sube ni lo comparte.", "The processor does the work.": "El procesador hace el trabajo.", "There is no model file to install": "No hay ningún archivo de modelo que instalar", - "This build cannot run denoise models.": "Esta versión no puede ejecutar modelos de reducción de ruido.", "This build cannot run recognition models: they can be added and chosen, not used.": "Esta versión no puede ejecutar modelos de reconocimiento: se pueden añadir y elegir, pero no usar.", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "Esta versión no tiene dónde guardar modelos de reducción de ruido, así que la reducción de ruido con IA no está disponible. (La aplicación de escritorio sí.)", "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "Esta versión no tiene dónde guardar modelos de caras, así que la lista de modelos no está disponible. (La aplicación de escritorio sí.)", "This file cannot be used yet": "Este archivo aún no se puede usar", "Tick the box to accept the model's terms first": "Marcar antes la casilla para aceptar las condiciones del modelo", @@ -1974,12 +1967,6 @@ "The catalog has a format version (issue #102). Opening a library from an older LightCraft upgrades it; a library": "El catálogo tiene una versión de formato (issue #102). Abrir una biblioteca de un LightCraft anterior la actualiza; una biblioteca", "The control port (`--control`) closes a connection as soon as it receives anything that isn't a JSON request": "El puerto de control (`--control`) cierra una conexión en cuanto recibe algo que no es una solicitud JSON", "The thumbnail cache only ever counts and deletes its own files (issue #98): a library opened on a folder that": "La caché de miniaturas solo cuenta y elimina sus propios archivos (issue #98): una biblioteca abierta en una carpeta que", - "AI Denoise is enabled on the requesting photo": "La reducción de ruido con IA está activada en la foto que la pidió", - "After installation, AI Denoise will turn on for the requesting photo.": "Tras la instalación, la reducción de ruido con IA se activará en la foto que la pidió.", - "Cancel pending action": "Cancelar acción pendiente", - "Install a denoise model to enable AI Denoise on this photo": "Instalar un modelo de reducción de ruido para activar la reducción de ruido con IA en esta foto", - "Pending photo action cancelled": "Acción pendiente sobre la foto cancelada", - "Pending photo action cancelled because its library or photo changed": "Acción pendiente sobre la foto cancelada porque cambió su biblioteca o su foto", "ONNX model": "Modelo ONNX", "commercial use subject to GPL conditions": "uso comercial sujeto a las condiciones de la GPL", "Decrease Rating": "Reducir valoración", @@ -2333,6 +2320,7 @@ "Specific folder": "Carpeta específica", "Same folder as original photo": "Misma carpeta que la foto original", "Tidying the thumbnail cache": "Ordenando la caché de miniaturas", + "Checking free disk space": "Comprobando el espacio libre en disco", "Reset all edits (Cmd+Shift+R)": "Restablecer todas las ediciones (Cmd+Mayús+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Los álbumes inteligentes se actualizan solos: cambie sus reglas o use Foto → Eliminar foto", "LightCraft stopped": "LightCraft se detuvo", @@ -2378,6 +2366,8 @@ "The photos are imported once it ends": "Las fotos se importarán después", "An import is running. Drop photos when it has finished": "Hay una importación en curso. Suelta las fotos cuando termine", "Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos", + "Camera preview": "Vista previa de la cámara", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "El JPEG propio de la cámara, mostrado hasta que LightCraft haya renderizado el RAW. Juzga el color y el tono en la foto renderizada.", "Profile: from the file (the camera's own correction)": "Perfil: del archivo (corrección de la propia cámara)", "Downloading the lens database…": "Descargando la base de datos de objetivos…", "This file names no lens.": "Este archivo no indica ningún objetivo.", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index df80342abe..17f2ca7728 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -30,9 +30,6 @@ "A slide stays up for its duration, its fade in included. A fade of 0 cuts.": "Dia pysyy näkyvillä kestonsa ajan, häivytys mukaan lukien. Häivytys 0 vaihtaa suoraan.", "AI Denoise": "Tekoälykohinanpoisto", "AI Denoise Model": "Tekoälykohinanpoiston malli", - "AI Denoise is enabled on the requesting photo": "Tekoälykohinanpoisto on käytössä sitä pyytävällä kuvalla", - "AI Denoise is off: press Use on a model.": "Tekoälykohinanpoisto on pois päältä: paina mallin kohdalla Käytä.", - "AI Denoise needs a model. Install one in Settings.": "Tekoälykohinanpoisto tarvitsee mallin. Asenna sellainen asetuksissa.", "AI Mask Model Status": "Tekoälymaskin mallin tila", "AV1 video, each slide held for its duration with its fades. No sound: music is not exported yet.": "AV1-video, jossa kutakin diaa näytetään sen keston ajan häivytyksineen. Ei ääntä: musiikkia ei vielä viedä.", "About": "Tietoja", @@ -86,7 +83,6 @@ "After 7 days": "7 päivän kuluttua", "After 90 days": "90 päivän kuluttua", "After a year": "Vuoden kuluttua", - "After installation, AI Denoise will turn on for the requesting photo.": "Asennuksen jälkeen tekoälykohinanpoisto otetaan käyttöön sitä pyytävälle kuvalle.", "Album": "Albumi", "Albums": "Albumit", "Albums hold library photos: Add to My Photos first": "Albumit sisältävät kirjaston kuvia: lisää ensin Omiin kuviin", @@ -253,9 +249,7 @@ "Cancel Download": "Peruuta lataus", "Cancel Face Model Download": "Peruuta kasvomallin lataus", "Cancel Interaction": "Peruuta vuorovaikutus", - "Cancel Pending Photo Action": "Peruuta odottava kuvatoiminto", "Cancel Preview Build": "Peruuta esikatselun luonti", - "Cancel pending action": "Peruuta odottava toiminto", "Candidate": "Ehdokas", "Caption": "Kuvateksti", "Capture Date": "Kuvauspäivä", @@ -956,10 +950,8 @@ "Inspecting Lightroom Catalog": "Tarkastellaan Lightroom-katalogia", "Install Denoise Model": "Asenna kohinanpoistomalli", "Install Face Model": "Asenna kasvomalli", - "Install a denoise model to enable AI Denoise on this photo": "Asenna kohinanpoistomalli ottaaksesi tekoälykohinanpoiston käyttöön tällä kuvalla", "Install from file…": "Asenna tiedostosta…", "Install the SAM 3 Model": "Asenna SAM 3 -malli", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Asenna oma ONNX-mallisi, jonka vieressä on denoise-model.json. Tämä versio ei tarjoa mallilatauksia.", "Instant ’70s": "Välitön 70-luku", "Intent:": "Tarkoitus:", "Interface": "Käyttöliittymä", @@ -1406,8 +1398,6 @@ "Pastel Haze": "Pastellihuntu", "Pause / Resume Slideshow": "Keskeytä / jatka diaesitystä", "Pen Pressure": "Kynän paine", - "Pending photo action cancelled": "Odottava kuvatoiminto peruttu", - "Pending photo action cancelled because its library or photo changed": "Odottava kuvatoiminto peruttu, koska sen kirjasto tai kuva muuttui", "People": "Henkilöt", "People Count": "Henkilöiden määrä", "Percent": "Prosentti", @@ -1813,7 +1803,6 @@ "Set date & time": "Aseta päivämäärä ja aika", "Set name": "Aseta nimi", "Set the mix from the photo's colours": "Aseta sekoitus kuvan väreistä", - "Set up AI Denoise…": "Ota tekoälykohinanpoisto käyttöön…", "Settings": "Asetukset", "Settings file problem": "Asetustiedoston ongelma", "Settings new raw photos start from. Changing them doesn't touch photos already in the library.": "Asetukset, joista uudet raw-kuvat lähtevät liikkeelle. Niiden muuttaminen ei koske kirjastossa jo olevia kuvia.", @@ -2043,9 +2032,7 @@ "Thirds": "Kolmasosat", "This Computer": "Tämä tietokone", "This build can't download the model yet. To install it by hand, put model.safetensors, vocab.json and merges.txt from Meta's facebook/sam3 in the folder above: Object and Describe work as soon as they are there.": "Tämä versio ei vielä voi ladata mallia. Asentaaksesi sen käsin laita Metan facebook/sam3-mallin tiedostot model.safetensors, vocab.json ja merges.txt yllä olevaan kansioon: Kohde ja Kuvaile toimivat heti, kun ne ovat siellä.", - "This build cannot run denoise models.": "Tämä versio ei voi ajaa kohinanpoistomalleja.", "This build cannot run recognition models: they can be added and chosen, not used.": "Tämä versio ei voi ajaa tunnistusmalleja: ne voi lisätä ja valita, mutta ei käyttää.", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "Tällä versiolla ei ole paikkaa kohinanpoistomalleille, joten tekoälykohinanpoisto ei ole käytettävissä. (Työpöytäsovelluksessa on.)", "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "Tällä versiolla ei ole paikkaa kasvomalleille, joten malliluettelo ei ole käytettävissä. (Työpöytäsovelluksessa on.)", "This file cannot be used yet": "Tätä tiedostoa ei voi vielä käyttää", "This folder is not available (drive disconnected?). Smart previews are not built or used until it is back or you choose another folder.": "Tämä kansio ei ole käytettävissä (asema irrotettu?). Älyesikatseluita ei luoda eikä käytetä, ennen kuin se on takaisin tai valitset toisen kansion.", @@ -2065,6 +2052,7 @@ "Thursday": "torstai", "Tick the box to accept the model's terms first": "Hyväksy ensin mallin ehdot valitsemalla ruutu", "Tidying the thumbnail cache": "Siivotaan pikkukuvien välimuistia", + "Checking free disk space": "Tarkistetaan vapaata levytilaa", "Time zone": "Aikavyöhyke", "Tint": "Värisävy", "Title": "Otsikko", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index e513e217de..ed035df142 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -1701,8 +1701,6 @@ "Back to this person": "Retour à cette personne", "AI Denoise": "Débruitage IA", "AI Denoise Model": "Modèle de débruitage IA", - "AI Denoise is off: press Use on a model.": "Le débruitage IA est désactivé : appuyez sur Utiliser sur un modèle.", - "AI Denoise needs a model. Install one in Settings.": "Le débruitage IA nécessite un modèle. Installez-en un dans les Réglages.", "Accept & Download": "Accepter et télécharger", "Already installed. Remove it before installing a replacement.": "Déjà installé. Supprimez-le avant d'installer un remplaçant.", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "Automatique utilise la carte graphique lorsqu'elle est plus rapide que le processeur : les deux sont chronométrés sur cet ordinateur la première fois qu'une photo est générée.", @@ -1721,7 +1719,6 @@ "Inspect Denoise Model": "Inspecter le modèle de débruitage", "Install Denoise Model": "Installer le modèle de débruitage", "Install from file…": "Installer à partir d'un fichier…", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Installez votre propre modèle ONNX avec denoise-model.json à côté. Cette version ne propose aucun téléchargement de modèle.", "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "Son image débruitée n'est pas encore générée, et les images ne sont pas générées automatiquement (Réglages, Débruitage IA).", "LightCraft does not know this model, so it assumed:": "LightCraft ne connaît pas ce modèle ; il a donc supposé :", "Limit": "Limite", @@ -1734,7 +1731,6 @@ "Open the model's page": "Ouvrir la page du modèle", "Opens the model's own page in your browser, to read about it or get the file yourself.": "Ouvre la page du modèle dans votre navigateur, pour vous renseigner ou récupérer le fichier vous-même.", "Processor": "Processeur", - "Set up AI Denoise…": "Configurer le débruitage IA…", "Speed": "Vitesse", "Starting…": "Démarrage…", "Tested and works on this computer": "Testé et fonctionnel sur cet ordinateur", @@ -1743,8 +1739,6 @@ "The model is kept on this computer only. LightCraft never uploads or shares it.": "Le modèle est conservé uniquement sur cet ordinateur. LightCraft ne le téléverse ni ne le partage jamais.", "The processor does the work.": "Le processeur effectue le travail.", "There is no model file to install": "Il n'y a aucun fichier de modèle à installer", - "This build cannot run denoise models.": "Cette version ne peut pas exécuter de modèles de débruitage.", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "Cette version n'a aucun endroit où conserver les modèles de débruitage ; le débruitage IA n'est donc pas disponible. (L'application de bureau en a un.)", "This file cannot be used yet": "Ce fichier ne peut pas encore être utilisé", "Tick the box to accept the model's terms first": "Cochez d'abord la case pour accepter les conditions du modèle", "Try again": "Réessayer", @@ -1781,12 +1775,6 @@ "Download Denoise Model": "Télécharger le modèle de débruitage", "Remove Denoise Model": "Supprimer le modèle de débruitage", "Test Denoise Model": "Tester le modèle de débruitage", - "AI Denoise is enabled on the requesting photo": "Le débruitage IA est activé sur la photo à l'origine de la demande", - "After installation, AI Denoise will turn on for the requesting photo.": "Après l'installation, le débruitage IA sera activé pour la photo à l'origine de la demande.", - "Cancel pending action": "Annuler l'action en attente", - "Install a denoise model to enable AI Denoise on this photo": "Installez un modèle de débruitage pour activer le débruitage IA sur cette photo", - "Pending photo action cancelled": "Action de photo en attente annulée", - "Pending photo action cancelled because its library or photo changed": "Action de photo en attente annulée car sa bibliothèque ou sa photo a changé", "ONNX model": "Modèle ONNX", "commercial use subject to GPL conditions": "usage commercial soumis aux conditions de la GPL", "Camera local tone mapping": "Mappage local des tons de l’appareil", @@ -2039,7 +2027,6 @@ "Auto-Tag from Tracklog: GPS locations for your photos from a GPX track log, matched by capture time.": "Géolocalisation depuis un tracé : positions GPS de vos photos tirées d'un tracé GPX, associées par date de prise de vue.", "Browser version (experimental), keeping a library safe (issue #107): File ▸ Back Up Library… downloads the catalog": "Version navigateur (expérimentale), protection de la bibliothèque (ticket #107) : Fichier → Sauvegarder la bibliothèque… télécharge le catalogue", "Cancel Face Model Download": "Annuler le téléchargement du modèle de visages", - "Cancel Pending Photo Action": "Annuler l'action en attente sur la photo", "Canon CR2 photos from the EOS 7D, 50D, 60D, 550D, 600D, 1200D, 1300D, 5D Mark II and 1D Mark IV (and other": "Les photos CR2 Canon des EOS 7D, 50D, 60D, 550D, 600D, 1200D, 1300D, 5D Mark II et 1D Mark IV (et d'autres", "Canon CR3 files show their full-size embedded JPEG (e.g. 6960 × 4640 on an EOS R6 Mark III) instead of the": "Les fichiers CR3 Canon affichent leur JPEG intégré en pleine taille (p. ex. 6960 × 4640 sur un EOS R6 Mark III) au lieu de l'", "Canon EOS R5 Mark II C-RAW files that opened as \"preview only\" (more than half of them, depending on the": "Les fichiers C-RAW du Canon EOS R5 Mark II qui s'ouvraient en « aperçu uniquement » (plus de la moitié, selon la", @@ -2328,6 +2315,7 @@ "Specific folder": "Dossier spécifique", "Same folder as original photo": "Même dossier que la photo d’origine", "Tidying the thumbnail cache": "Rangement du cache des miniatures", + "Checking free disk space": "Vérification de l'espace disque libre", "Reset all edits (Cmd+Shift+R)": "Réinitialiser toutes les retouches (Cmd+Maj+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Les albums intelligents se mettent à jour d'eux-mêmes : modifiez leurs règles ou utilisez Photo → Supprimer la photo", "LightCraft stopped": "LightCraft s’est arrêté", @@ -2409,6 +2397,8 @@ "The photos are imported once a library is open": "Les photos seront importées dès qu'une bibliothèque sera ouverte", "Open a library first, then drop the presets again": "Ouvrez d'abord une bibliothèque, puis déposez à nouveau les préréglages", "This library couldn't be checked:": "Impossible de vérifier cette bibliothèque :", + "Camera preview": "Aperçu de l'appareil", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "Le JPEG de l'appareil photo, affiché jusqu'à ce que LightCraft ait rendu le fichier RAW. Jugez la couleur et les tons sur la photo rendue.", "Profile: from the file (the camera's own correction)": "Profil : du fichier (correction de l'appareil)", "Downloading the lens database…": "Téléchargement de la base de données d'objectifs…", "This file names no lens.": "Ce fichier n'indique aucun objectif.", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 7f5e56e1ce..11e4f344ef 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -30,9 +30,6 @@ "A pen's pressure sets the size and flow of the brush": "Tekanan pena mengatur ukuran dan aliran kuas", "AI Denoise": "Pengurangan noise AI", "AI Denoise Model": "Model pengurangan noise AI", - "AI Denoise is enabled on the requesting photo": "Pengurangan noise AI diaktifkan pada foto yang bersangkutan", - "AI Denoise is off: press Use on a model.": "Pengurangan noise AI nonaktif: tekan Gunakan pada salah satu model.", - "AI Denoise needs a model. Install one in Settings.": "Pengurangan noise AI memerlukan model. Instal model di Pengaturan.", "AI Mask Model Status": "Status model masker AI", "AV1 video, each slide held for its duration with its fades. No sound: music is not exported yet.": "Video AV1; setiap slide ditampilkan sesuai durasinya, lengkap dengan transisi pudar. Tanpa suara: musik belum ikut diekspor.", "About": "Tentang", @@ -87,7 +84,6 @@ "After 7 days": "Setelah 7 hari", "After 90 days": "Setelah 90 hari", "After a year": "Setelah satu tahun", - "After installation, AI Denoise will turn on for the requesting photo.": "Setelah terinstal, pengurangan noise AI akan aktif untuk foto tersebut.", "Album": "Album", "Albums": "Album", "Albums hold library photos: Add to My Photos first": "Album hanya berisi foto pustaka: tambahkan ke Foto saya terlebih dahulu", @@ -257,9 +253,7 @@ "Cancel Download": "Batalkan unduhan", "Cancel Face Model Download": "Batalkan unduhan model wajah", "Cancel Interaction": "Batalkan interaksi", - "Cancel Pending Photo Action": "Batalkan tindakan foto yang tertunda", "Cancel Preview Build": "Batalkan pembuatan pratinjau", - "Cancel pending action": "Batalkan tindakan yang tertunda", "Candidate": "Kandidat", "Caption": "Keterangan", "Capture Date": "Tanggal pengambilan", @@ -961,10 +955,8 @@ "Inspecting Lightroom Catalog": "Memeriksa katalog Lightroom", "Install Denoise Model": "Instal model pengurangan noise", "Install Face Model": "Instal model wajah", - "Install a denoise model to enable AI Denoise on this photo": "Instal model untuk mengaktifkan pengurangan noise AI pada foto ini", "Install from file…": "Instal dari file…", "Install the SAM 3 Model": "Instal model SAM 3", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Instal model ONNX Anda sendiri beserta file denoise-model.json di sebelahnya. Build ini tidak menyediakan unduhan model.", "Instant ’70s": "Instant ’70s", "Intent:": "Metode rendering:", "Interface": "Antarmuka", @@ -1390,8 +1382,6 @@ "Pastel Haze": "Kabut Pastel", "Pause / Resume Slideshow": "Jeda / lanjutkan tayangan slide", "Pen Pressure": "Tekanan pena", - "Pending photo action cancelled": "Tindakan foto yang tertunda dibatalkan", - "Pending photo action cancelled because its library or photo changed": "Tindakan foto yang tertunda dibatalkan karena pustaka atau fotonya berubah", "People": "Orang", "People Count": "Jumlah orang", "Percent": "Persen", @@ -1810,7 +1800,6 @@ "Set date & time": "Atur tanggal & waktu", "Set name": "Nama set", "Set the mix from the photo's colours": "Atur campuran berdasarkan warna foto", - "Set up AI Denoise…": "Siapkan pengurangan noise AI…", "Settings": "Pengaturan", "Settings file problem": "Masalah file pengaturan", "Settings new raw photos start from. Changing them doesn't touch photos already in the library.": "Pengaturan awal untuk foto raw baru. Mengubahnya tidak memengaruhi foto yang sudah ada di pustaka.", @@ -2042,9 +2031,7 @@ "Thirds": "Aturan sepertiga", "This Computer": "Komputer ini", "This build can't download the model yet. To install it by hand, put model.safetensors, vocab.json and merges.txt from Meta's facebook/sam3 in the folder above: Object and Describe work as soon as they are there.": "Build ini belum bisa mengunduh model. Untuk menginstalnya secara manual, letakkan model.safetensors, vocab.json, dan merges.txt dari facebook/sam3 milik Meta ke folder di atas: masker Objek dan Deskripsi langsung berfungsi setelah file tersebut tersedia.", - "This build cannot run denoise models.": "Build ini tidak dapat menjalankan model pengurangan noise.", "This build cannot run recognition models: they can be added and chosen, not used.": "Build ini tidak dapat menjalankan model pengenalan: model bisa ditambahkan dan dipilih, tetapi tidak bisa digunakan.", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "Build ini tidak memiliki tempat untuk menyimpan model pengurangan noise, sehingga pengurangan noise AI tidak tersedia. (Tersedia di aplikasi desktop.)", "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "Build ini tidak memiliki tempat untuk menyimpan model wajah, sehingga daftar model tidak tersedia. (Tersedia di aplikasi desktop.)", "This file cannot be used yet": "File ini belum dapat digunakan", "This folder is not available (drive disconnected?). Smart previews are not built or used until it is back or you choose another folder.": "Folder ini tidak tersedia (drive terputus?). Pratinjau pintar tidak akan dibuat atau dipakai sampai folder ini tersedia lagi atau Anda memilih folder lain.", @@ -2062,6 +2049,7 @@ "Thursday": "Kamis", "Tick the box to accept the model's terms first": "Centang kotak untuk menyetujui ketentuan model terlebih dahulu", "Tidying the thumbnail cache": "Merapikan cache thumbnail", + "Checking free disk space": "Memeriksa ruang disk kosong", "Time zone": "Zona waktu", "Tint": "Rona", "Title": "Judul", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index c77a85b41f..6aca1673bf 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -937,6 +937,7 @@ "Specific folder": "Cartella specifica", "Same folder as original photo": "Stessa cartella della foto originale", "Tidying the thumbnail cache": "Riordino della cache delle miniature", + "Checking free disk space": "Controllo dello spazio libero su disco", "No masks yet. Choose a mask type above.": "Ancora nessuna maschera. Scegli un tipo di maschera qui sopra.", "No matching commands": "Nessun comando corrispondente", "No matching photos": "Nessuna foto corrispondente", @@ -1731,8 +1732,6 @@ "Back to this person": "Torna a questa persona", "AI Denoise": "Riduzione disturbo IA", "AI Denoise Model": "Modello di riduzione disturbo IA", - "AI Denoise is off: press Use on a model.": "La riduzione disturbo IA è disattivata: premi Usa su un modello.", - "AI Denoise needs a model. Install one in Settings.": "La riduzione disturbo IA ha bisogno di un modello. Installane uno nelle Impostazioni.", "Accept & Download": "Accetta e scarica", "Already installed. Remove it before installing a replacement.": "Già installato. Rimuovilo prima di installarne un altro.", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "Automatico usa la scheda grafica quando è più veloce del processore: la prima volta che si elabora una foto, su questo computer vengono cronometrati entrambi.", @@ -1751,7 +1750,6 @@ "Inspect Denoise Model": "Esamina il modello di riduzione disturbo", "Install Denoise Model": "Installa un modello di riduzione disturbo", "Install from file…": "Installa da file…", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Installa un tuo modello ONNX con accanto denoise-model.json. Questa versione non offre download di modelli.", "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "La sua immagine con il disturbo ridotto non è ancora pronta, e le immagini non vengono generate da sole (Impostazioni, Riduzione disturbo IA).", "LightCraft does not know this model, so it assumed:": "LightCraft non conosce questo modello, quindi ha ipotizzato:", "Limit": "Limite", @@ -1764,7 +1762,6 @@ "Open the model's page": "Apri la pagina del modello", "Opens the model's own page in your browser, to read about it or get the file yourself.": "Apre nel browser la pagina del modello, per leggerne i dettagli o scaricare il file da te.", "Processor": "Processore", - "Set up AI Denoise…": "Configura la riduzione disturbo IA…", "Speed": "Velocità", "Starting…": "Avvio in corso…", "Tested and works on this computer": "Testato e funzionante su questo computer", @@ -1773,8 +1770,6 @@ "The model is kept on this computer only. LightCraft never uploads or shares it.": "Il modello resta solo su questo computer. LightCraft non lo carica né lo condivide mai.", "The processor does the work.": "Il lavoro lo fa il processore.", "There is no model file to install": "Non c'è nessun file di modello da installare", - "This build cannot run denoise models.": "Questa versione non può eseguire modelli di riduzione disturbo.", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "Questa versione non ha dove tenere i modelli di riduzione disturbo, quindi la riduzione disturbo IA non è disponibile. (L'app desktop ce l'ha.)", "This file cannot be used yet": "Questo file non si può ancora usare", "Tick the box to accept the model's terms first": "Prima spunta la casella per accettare le condizioni del modello", "Try again": "Riprova", @@ -1813,12 +1808,6 @@ "Download Denoise Model": "Scarica il modello di riduzione disturbo", "Remove Denoise Model": "Rimuovi il modello di riduzione disturbo", "Test Denoise Model": "Testa il modello di riduzione disturbo", - "AI Denoise is enabled on the requesting photo": "La riduzione disturbo IA è attiva sulla foto che l'ha richiesta", - "After installation, AI Denoise will turn on for the requesting photo.": "Dopo l'installazione, la riduzione disturbo IA si attiverà sulla foto che l'ha richiesta.", - "Cancel pending action": "Annulla l'azione in sospeso", - "Install a denoise model to enable AI Denoise on this photo": "Installa un modello di riduzione disturbo per attivare la riduzione disturbo IA su questa foto", - "Pending photo action cancelled": "Azione sulla foto in sospeso annullata", - "Pending photo action cancelled because its library or photo changed": "Azione sulla foto in sospeso annullata perché la libreria o la foto sono cambiate", "ONNX model": "Modello ONNX", "commercial use subject to GPL conditions": "uso commerciale soggetto alle condizioni della GPL", "Decrease Rating": "Diminuisci valutazione", @@ -2279,7 +2268,6 @@ "This raw is now developed from its raw data": "Questo raw ora viene sviluppato dai suoi dati raw", "This raw variant still can't be decoded": "Questa variante raw non si può ancora decodificare", "Cancel Face Model Download": "Annulla il download del modello dei volti", - "Cancel Pending Photo Action": "Annulla l'azione in sospeso sulla foto", "Choose Face Recognition Model": "Scegli il modello di riconoscimento dei volti", "Choose a model below (Use) to start.": "Per cominciare, scegli un modello qui sotto (Usa).", "Detect Faces": "Rileva i volti", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 72ed66ad20..bd03abd901 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -1714,8 +1714,6 @@ "Back to this person": "この人物に戻る", "AI Denoise": "AIノイズ除去", "AI Denoise Model": "AIノイズ除去モデル", - "AI Denoise is off: press Use on a model.": "AIノイズ除去はオフです:モデルの「使用」を押してください。", - "AI Denoise needs a model. Install one in Settings.": "AIノイズ除去にはモデルが必要です。設定でインストールしてください。", "Accept & Download": "同意してダウンロード", "Already installed. Remove it before installing a replacement.": "インストール済みです。置き換える前に削除してください。", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "「自動」は処理装置より速い場合にグラフィックカードを使います。最初に写真を作成するとき、このコンピューターで両方の速度を計ります。", @@ -1734,7 +1732,6 @@ "Inspect Denoise Model": "ノイズ除去モデルを調べる", "Install Denoise Model": "ノイズ除去モデルをインストール", "Install from file…": "ファイルからインストール…", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "denoise-model.json を横に置いた独自の ONNX モデルをインストールしてください。このビルドにはモデルのダウンロードがありません。", "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "ノイズ除去した画像はまだ作成されておらず、自動では作成されません(設定、AIノイズ除去)。", "LightCraft does not know this model, so it assumed:": "LightCraft はこのモデルを知らないため、次のように仮定しました:", "Limit": "上限", @@ -1747,7 +1744,6 @@ "Open the model's page": "モデルのページを開く", "Opens the model's own page in your browser, to read about it or get the file yourself.": "モデルのページをブラウザーで開き、詳細を読んだりファイルを自分で入手したりできます。", "Processor": "処理装置", - "Set up AI Denoise…": "AIノイズ除去を設定…", "Speed": "速度", "Starting…": "開始中…", "Tested and works on this computer": "このコンピューターでテスト済み、動作します", @@ -1756,8 +1752,6 @@ "The model is kept on this computer only. LightCraft never uploads or shares it.": "モデルはこのコンピューターにのみ保存されます。LightCraft がアップロードや共有をすることはありません。", "The processor does the work.": "処理装置が処理します。", "There is no model file to install": "インストールするモデルファイルがありません", - "This build cannot run denoise models.": "このビルドではノイズ除去モデルを実行できません。", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "このビルドにはノイズ除去モデルの保存場所がないため、AIノイズ除去は使えません。(デスクトップ版にはあります。)", "This file cannot be used yet": "このファイルはまだ使えません", "Tick the box to accept the model's terms first": "まずチェックボックスをオンにしてモデルの条件に同意してください", "Try again": "再試行", @@ -1794,12 +1788,6 @@ "Download Denoise Model": "ノイズ除去モデルをダウンロード", "Remove Denoise Model": "ノイズ除去モデルを削除", "Test Denoise Model": "ノイズ除去モデルをテスト", - "AI Denoise is enabled on the requesting photo": "要求した写真でAIノイズ除去が有効になりました", - "After installation, AI Denoise will turn on for the requesting photo.": "インストール後、要求した写真でAIノイズ除去がオンになります。", - "Cancel pending action": "保留中の操作をキャンセル", - "Install a denoise model to enable AI Denoise on this photo": "この写真でAIノイズ除去を使うには、ノイズ除去モデルをインストールしてください", - "Pending photo action cancelled": "保留中の写真操作をキャンセルしました", - "Pending photo action cancelled because its library or photo changed": "ライブラリまたは写真が変更されたため、保留中の写真操作をキャンセルしました", "ONNX model": "ONNX モデル", "commercial use subject to GPL conditions": "商用利用は GPL の条件に従う", "Decrease Rating": "評価を下げる", @@ -2044,7 +2032,6 @@ "Auto-Tag from Tracklog: GPS locations for your photos from a GPX track log, matched by capture time.": "トラックログから自動タグ付け:GPX トラックログから撮影日時で照合した GPS 位置を写真に付けます。", "Browser version (experimental), keeping a library safe (issue #107): File ▸ Back Up Library… downloads the catalog": "ブラウザー版(試験的)、ライブラリを安全に保つ(issue #107):ファイル → ライブラリをバックアップ… でカタログと", "Cancel Face Model Download": "顔モデルのダウンロードをキャンセル", - "Cancel Pending Photo Action": "保留中の写真操作をキャンセル", "Canon CR2 photos from the EOS 7D, 50D, 60D, 550D, 600D, 1200D, 1300D, 5D Mark II and 1D Mark IV (and other": "EOS 7D、50D、60D、550D、600D、1200D、1300D、5D Mark II、1D Mark IV の Canon CR2 写真(およびその他", "Canon CR3 files show their full-size embedded JPEG (e.g. 6960 × 4640 on an EOS R6 Mark III) instead of the": "Canon CR3 ファイルは、フルサイズの埋め込み JPEG(例:EOS R6 Mark III で 6960 × 4640)を表示し、", "Canon EOS R5 Mark II C-RAW files that opened as \"preview only\" (more than half of them, depending on the": "「プレビューのみ」で開いていた Canon EOS R5 Mark II の C-RAW ファイル(撮影シーンによっては半数以上", @@ -2331,6 +2318,7 @@ "Specific folder": "指定フォルダー", "Same folder as original photo": "元の写真と同じフォルダー", "Tidying the thumbnail cache": "サムネールキャッシュを整理中", + "Checking free disk space": "ディスクの空き容量を確認中", "Reset all edits (Cmd+Shift+R)": "すべての編集をリセット(⌘⇧R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "スマートアルバムは自動で更新されます。ルールを変更するか、写真 → 写真を削除を使ってください", "LightCraft stopped": "LightCraftが終了しました", @@ -2376,6 +2364,8 @@ "The photos are imported once it ends": "終わりしだい写真を読み込みます", "An import is running. Drop photos when it has finished": "読み込み中です。完了してから写真をドロップしてください", "Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください", + "Camera preview": "カメラのプレビュー", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "LightCraft が RAW を現像するまで表示される、カメラ自身の JPEG です。色とトーンは現像後の写真で判断してください。", "Profile: from the file (the camera's own correction)": "プロファイル: ファイル内(カメラ自身の補正)", "Downloading the lens database…": "レンズデータベースをダウンロード中…", "This file names no lens.": "このファイルにはレンズ名がありません。", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index e9d0ba8b05..d2b75bb0ca 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -81,9 +81,6 @@ "AI Denoise": "AI ხმაურის მოცილება", "AI Denoise Model": "AI ხმაურის მოცილების მოდელი", "AI Denoise and Find Missing Photos. Each row has the task's name, a progress bar, the count and what it is working": "AI ხმაურის მოცილება და დაკარგული ფოტოების მოძებნა. თითოეულ სტრიქონს აქვს ამოცანის სახელი, პროგრესის ზოლი, რაოდენობა და ის, რაზეც", - "AI Denoise is enabled on the requesting photo": "AI ხმაურის მოცილება ჩართულია მომთხოვნ ფოტოზე", - "AI Denoise is off: press Use on a model.": "AI ხმაურის მოცილება გამორთულია: მოდელზე დააჭირეთ „გამოყენებას“.", - "AI Denoise needs a model. Install one in Settings.": "AI ხმაურის მოცილებას მოდელი სჭირდება. დააინსტალირეთ პარამეტრებში.", "AI Mask Model Status": "AI ნიღბების მოდელის მდგომარეობა", "AI RAW denoise": "RAW-ის AI ხმაურის მოცილება", "AI masks with SAM 3 (Object and Describe in the Masking panel): click an object to select it (⌥-click leaves a": "AI ნიღბები SAM 3-ით (ობიექტი და აღწერა ნიღბვის პანელში): დაწკაპეთ ობიექტზე მის მოსანიშნად (⌥-დაწკაპუნება ტოვებს", @@ -138,7 +135,6 @@ "After 7 days": "7 დღის შემდეგ", "After 90 days": "90 დღის შემდეგ", "After a year": "ერთი წლის შემდეგ", - "After installation, AI Denoise will turn on for the requesting photo.": "დაინსტალირების შემდეგ AI ხმაურის მოცილება მომთხოვნ ფოტოზე ჩაირთვება.", "Agents list and stop tasks with `activity.list` and `activity.cancel`; `ui.inspect` reports them as `activity`.": "აგენტები ამოცანებს ჩამოთვლიან და აჩერებენ `activity.list`-ით და `activity.cancel`-ით; `ui.inspect` მათ `activity`-ად აბრუნებს.", "Agents use `app.newLibrary {path, name}`, `app.recentLibraries` and `app.clearRecentLibraries`.": "აგენტები იყენებენ `app.newLibrary {path, name}`, `app.recentLibraries` და `app.clearRecentLibraries`.", "Agents: `app.export {addToPhotos, photosAlbum}`, `export.addToPhotos {paths}` for files already on disk, and": "აგენტები: `app.export {addToPhotos, photosAlbum}`, `export.addToPhotos {paths}` დისკზე უკვე არსებული ფაილებისთვის, და", @@ -315,9 +311,7 @@ "Cancel Download": "ჩამოტვირთვის გაუქმება", "Cancel Face Model Download": "სახეების მოდელის ჩამოტვირთვის გაუქმება", "Cancel Interaction": "ურთიერთქმედების გაუქმება", - "Cancel Pending Photo Action": "ფოტოს მოლოდინში მყოფი მოქმედების გაუქმება", "Cancel Preview Build": "წინასწარი ხედების შექმნის გაუქმება", - "Cancel pending action": "მოლოდინში მყოფი მოქმედების გაუქმება", "Candidate": "კანდიდატი", "Canon CR2 and Pentax PEF raws get the same starting look fitted to the camera's own JPEG as ARW, NEF, RW2, RAF": "Canon CR2 და Pentax PEF RAW-ები კამერის საკუთარ JPEG-ზე მორგებულ იმავე საწყის იერს იღებს, როგორც ARW, NEF, RW2, RAF", "Canon CR2 highlights": "Canon CR2-ის ღია ტონები", @@ -1026,10 +1020,8 @@ "Inspecting Lightroom Catalog": "Lightroom-ის კატალოგი მოწმდება", "Install Denoise Model": "ხმაურის მოცილების მოდელის ინსტალაცია", "Install Face Model": "სახეების მოდელის ინსტალაცია", - "Install a denoise model to enable AI Denoise on this photo": "ამ ფოტოზე AI ხმაურის მოცილების ჩასართავად დააინსტალირეთ ხმაურის მოცილების მოდელი", "Install from file…": "ინსტალაცია ფაილიდან…", "Install the SAM 3 Model": "SAM 3 მოდელის ინსტალაცია", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "დააინსტალირეთ საკუთარი ONNX მოდელი, გვერდით denoise-model.json ფაილით. ეს ვერსია მოდელების ჩამოტვირთვას არ გთავაზობთ.", "Instant ’70s": "მყისიერი ’70-იანები", "Intent:": "განზრახვა:", "Interface": "ინტერფეისი", @@ -1473,8 +1465,6 @@ "Paste from Previous": "წინადან ჩასმა", "Paste pages": "გვერდების ჩასმა", "Pastel Haze": "პასტელის ნისლი", - "Pending photo action cancelled": "ფოტოს მოლოდინში მყოფი მოქმედება გაუქმდა", - "Pending photo action cancelled because its library or photo changed": "ფოტოს მოლოდინში მყოფი მოქმედება გაუქმდა, რადგან მისი ბიბლიოთეკა ან ფოტო შეიცვალა", "Pentax raws without black borders": "Pentax-ის RAW ფაილები შავი კიდეების გარეშე", "People": "ადამიანები", "People Count": "ადამიანების რაოდენობა", @@ -1889,7 +1879,6 @@ "Set date & time": "თარიღისა და დროის დაყენება", "Set name": "ნაკრების სახელი", "Set the mix from the photo's colours": "მიქსის დაყენება ფოტოს ფერების მიხედვით", - "Set up AI Denoise…": "AI ხმაურის მოცილების გამართვა…", "Setting or clearing a colour label shows a brief bottom confirmation, like rating a photo; custom label names appear in the message too.": "ფერადი იარლიყის დაყენება ან მოხსნა ქვემოთ მოკლე დადასტურებას აჩვენებს, როგორც ფოტოს შეფასება; შეტყობინებაში იარლიყების მორგებული სახელებიც ჩანს.", "Settings": "პარამეტრები", "Settings file problem": "პარამეტრების ფაილის პრობლემა", @@ -2149,9 +2138,7 @@ "Thirds": "მესამედები", "This Computer": "ეს კომპიუტერი", "This build can't download the model yet. To install it by hand, put model.safetensors, vocab.json and merges.txt from Meta's facebook/sam3 in the folder above: Object and Describe work as soon as they are there.": "ამ ვერსიას მოდელის ჩამოტვირთვა ჯერ არ შეუძლია. ხელით დასაინსტალირებლად ზემოთ მითითებულ საქაღალდეში მოათავსეთ model.safetensors, vocab.json და merges.txt Meta-ს facebook/sam3-დან: „ობიექტი“ და „აღწერა“ იქ მათი გაჩენისთანავე იმუშავებს.", - "This build cannot run denoise models.": "ამ ვერსიას ხმაურის მოცილების მოდელების გაშვება არ შეუძლია.", "This build cannot run recognition models: they can be added and chosen, not used.": "ამ ვერსიას ამოცნობის მოდელების გაშვება არ შეუძლია: მათი დამატება და არჩევა შეიძლება, გამოყენება — არა.", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "ამ ვერსიას ხმაურის მოცილების მოდელების შესანახი ადგილი არ აქვს, ამიტომ AI ხმაურის მოცილება მიუწვდომელია. (სამაგიდო აპლიკაციას აქვს.)", "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "ამ ვერსიას სახეების მოდელების შესანახი ადგილი არ აქვს, ამიტომ მოდელების სია მიუწვდომელია. (სამაგიდო აპლიკაციას აქვს.)", "This file cannot be used yet": "ამ ფაილის გამოყენება ჯერ შეუძლებელია", "This folder is not available (drive disconnected?). Smart previews are not built or used until it is back or you choose another folder.": "ეს საქაღალდე მიუწვდომელია (დისკი გამოერთებულია?). ჭკვიანი წინასწარი ხედები არ იქმნება და არ გამოიყენება, სანამ ის არ დაბრუნდება ან სხვა საქაღალდეს არ აირჩევთ.", @@ -2945,6 +2932,7 @@ "This row covers more than one disk: drop on a folder inside it": "ეს სტრიქონი ერთზე მეტ დისკს მოიცავს: ჩააგდეთ მის შიგნით მყოფ საქაღალდეზე", "This screen is off: turn it on under Titles to play it.": "ეს ეკრანი გამორთულია: დასაკრავად ჩართეთ „ტიტრებში“.", "Tidying the thumbnail cache": "ესკიზების ქეში სუფთავდება", + "Checking free disk space": "დისკზე თავისუფალი ადგილის შემოწმება", "Title text": "ტიტრის ტექსტი", "Titles": "ტიტრები", "Tokens: {file}, {name}, {title}, {caption}, {date}, {exposure}, {iso}, {focal}, {camera}, {lens}, {rating}, {creator}, {copyright}. Other text shows as typed.": "ტეგები: {file}, {name}, {title}, {caption}, {date}, {exposure}, {iso}, {focal}, {camera}, {lens}, {rating}, {creator}, {copyright}. სხვა ტექსტი ისე ჩანს, როგორც აკრიფეთ.", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 6d1eeb7dad..a67aed3ba6 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -1665,8 +1665,6 @@ "Back to this person": "Wróć do tej osoby", "AI Denoise": "Odszumianie AI", "AI Denoise Model": "Model odszumiania AI", - "AI Denoise is off: press Use on a model.": "Odszumianie AI jest wyłączone: kliknij „Użyj” przy modelu.", - "AI Denoise needs a model. Install one in Settings.": "Odszumianie AI wymaga modelu. Zainstaluj go w Ustawieniach.", "Accept & Download": "Akceptuj i pobierz", "Already installed. Remove it before installing a replacement.": "Już zainstalowano. Usuń obecny model przed zainstalowaniem nowego.", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "Tryb automatyczny używa karty graficznej, jeśli jest szybsza od procesora. Przy pierwszym przetwarzaniu zdjęcia LightCraft mierzy wydajność obu urządzeń.", @@ -1685,7 +1683,6 @@ "Inspect Denoise Model": "Sprawdź model odszumiania", "Install Denoise Model": "Zainstaluj model odszumiania", "Install from file…": "Zainstaluj z pliku…", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Zainstaluj własny model ONNX z plikiem denoise-model.json w tym samym katalogu. W tej kompilacji nie można pobierać modeli.", "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "Nie utworzono jeszcze odszumionego obrazu, a obrazy nie są przetwarzane automatycznie (Ustawienia, Odszumianie AI).", "LightCraft does not know this model, so it assumed:": "LightCraft nie rozpoznaje tego modelu, dlatego przyjęto następujące założenia:", "Limit": "Limit", @@ -1698,7 +1695,6 @@ "Open the model's page": "Otwórz stronę modelu", "Opens the model's own page in your browser, to read about it or get the file yourself.": "Otwiera stronę modelu w przeglądarce, gdzie można przeczytać o nim lub samodzielnie pobrać plik.", "Processor": "Procesor", - "Set up AI Denoise…": "Skonfiguruj odszumianie AI…", "Speed": "Szybkość", "Starting…": "Uruchamianie…", "Tested and works on this computer": "Przetestowano — działa na tym komputerze", @@ -1707,8 +1703,6 @@ "The model is kept on this computer only. LightCraft never uploads or shares it.": "Model jest przechowywany wyłącznie na tym komputerze. LightCraft nigdy go nie przesyła ani nie udostępnia.", "The processor does the work.": "Przetwarzanie wykonuje procesor.", "There is no model file to install": "Brak pliku modelu do zainstalowania", - "This build cannot run denoise models.": "Ta kompilacja nie obsługuje modeli odszumiania.", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "Ta kompilacja nie ma miejsca na przechowywanie modeli odszumiania, więc odszumianie AI jest niedostępne (dostępne w aplikacji komputerowej).", "This file cannot be used yet": "Nie można jeszcze użyć tego pliku", "Tick the box to accept the model's terms first": "Najpierw zaznacz pole akceptacji warunków modelu", "Try again": "Spróbuj ponownie", @@ -1744,12 +1738,6 @@ "Download Denoise Model": "Pobierz model odszumiania", "Remove Denoise Model": "Usuń model odszumiania", "Test Denoise Model": "Przetestuj model odszumiania", - "AI Denoise is enabled on the requesting photo": "Odszumianie AI włączono dla wybranego zdjęcia", - "After installation, AI Denoise will turn on for the requesting photo.": "Po instalacji odszumianie AI zostanie włączone dla wybranego zdjęcia.", - "Cancel pending action": "Anuluj oczekującą operację", - "Install a denoise model to enable AI Denoise on this photo": "Zainstaluj model odszumiania, aby włączyć odszumianie AI dla tego zdjęcia", - "Pending photo action cancelled": "Anulowano oczekującą operację", - "Pending photo action cancelled because its library or photo changed": "Anulowano oczekującą operację, ponieważ zmieniła się biblioteka lub zdjęcie", "ONNX model": "Model ONNX", "commercial use subject to GPL conditions": "użytek komercyjny na warunkach licencji GPL", "Decrease Rating": "Zmniejsz ocenę", @@ -2069,7 +2057,6 @@ "Appearance Mode": "Tryb wyglądu", "Appearance Settings…": "Ustawienia wyglądu…", "Cancel Face Model Download": "Anuluj pobieranie modelu twarzy", - "Cancel Pending Photo Action": "Anuluj oczekującą operację na zdjęciu", "Canon EOS R5 Mark II C-RAW files that opened as \"preview only\" (more than half of them, depending on the": "Pliki C-RAW z aparatu Canon EOS R5 Mark II, które otwierały się jako „tylko podgląd” (w zależności od", "scene) now develop from their sensor data with every editing tool, like the camera's other raws. Photos": "sceny ponad połowa z nich), są teraz wywoływane z danych matrycy wszystkimi narzędziami, jak inne pliki RAW. Zdjęcia", "imported earlier switch over with Photo ▸ Reload from Disk.": "zaimportowane wcześniej przełączysz poleceniem Zdjęcie → Wczytaj ponownie z dysku.", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 821bc56ff3..43f89f051c 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1714,8 +1714,6 @@ "Back to this person": "Voltar para esta pessoa", "AI Denoise": "Redução de ruído com IA", "AI Denoise Model": "Modelo de redução de ruído com IA", - "AI Denoise is off: press Use on a model.": "A redução de ruído com IA está desativada: clique em Usar em um modelo.", - "AI Denoise needs a model. Install one in Settings.": "A redução de ruído com IA precisa de um modelo. Instale um em Configurações.", "Accept & Download": "Aceitar e baixar", "Already installed. Remove it before installing a replacement.": "Já instalado. Remova-o antes de instalar um substituto.", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "Automático usa a placa de vídeo quando ela é mais rápida que o processador: ambos são cronometrados neste computador na primeira vez que uma foto é gerada.", @@ -1734,7 +1732,6 @@ "Inspect Denoise Model": "Inspecionar modelo de redução de ruído", "Install Denoise Model": "Instalar modelo de redução de ruído", "Install from file…": "Instalar de arquivo…", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Instale seu próprio modelo ONNX com o denoise-model.json ao lado dele. Esta versão não oferece downloads de modelos.", "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "A imagem com ruído reduzido ainda não foi gerada, e as imagens não são geradas automaticamente (Configurações, Redução de ruído com IA).", "LightCraft does not know this model, so it assumed:": "O LightCraft não conhece este modelo, então presumiu:", "Limit": "Limite", @@ -1747,7 +1744,6 @@ "Open the model's page": "Abrir a página do modelo", "Opens the model's own page in your browser, to read about it or get the file yourself.": "Abre a página do próprio modelo no seu navegador, para ler sobre ele ou baixar o arquivo você mesmo.", "Processor": "Processador", - "Set up AI Denoise…": "Configurar redução de ruído com IA…", "Speed": "Velocidade", "Starting…": "Iniciando…", "Tested and works on this computer": "Testado e funcionando neste computador", @@ -1756,8 +1752,6 @@ "The model is kept on this computer only. LightCraft never uploads or shares it.": "O modelo fica somente neste computador. O LightCraft nunca o envia nem o compartilha.", "The processor does the work.": "O processador faz o trabalho.", "There is no model file to install": "Não há arquivo de modelo para instalar", - "This build cannot run denoise models.": "Esta versão não consegue executar modelos de redução de ruído.", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "Esta versão não tem onde guardar modelos de redução de ruído, então a redução de ruído com IA não está disponível. (O aplicativo para desktop tem.)", "This file cannot be used yet": "Este arquivo ainda não pode ser usado", "Tick the box to accept the model's terms first": "Marque a caixa para aceitar primeiro os termos do modelo", "Try again": "Tentar novamente", @@ -1794,12 +1788,6 @@ "Download Denoise Model": "Baixar modelo de redução de ruído", "Remove Denoise Model": "Remover modelo de redução de ruído", "Test Denoise Model": "Testar modelo de redução de ruído", - "AI Denoise is enabled on the requesting photo": "A redução de ruído com IA está ativada na foto que a solicitou", - "After installation, AI Denoise will turn on for the requesting photo.": "Após a instalação, a redução de ruído com IA será ativada na foto que a solicitou.", - "Cancel pending action": "Cancelar ação pendente", - "Install a denoise model to enable AI Denoise on this photo": "Instale um modelo de redução de ruído para ativar a redução de ruído com IA nesta foto", - "Pending photo action cancelled": "Ação pendente da foto cancelada", - "Pending photo action cancelled because its library or photo changed": "Ação pendente da foto cancelada porque a biblioteca ou a foto foi alterada", "ONNX model": "Modelo ONNX", "commercial use subject to GPL conditions": "uso comercial sujeito às condições da GPL", "Decrease Rating": "Diminuir avaliação", @@ -2025,7 +2013,6 @@ "Sort Albums A–Z": "Ordenar álbuns de A a Z", "Go back to listing them by name": "Voltar a listá-los por nome", "Sort Contents A–Z": "Ordenar conteúdo de A a Z", - "Cancel Pending Photo Action": "Cancelar ação pendente da foto", "Show Person": "Mostrar pessoa", "Add Face Model…": "Adicionar modelo de rostos…", "Cancel Face Model Download": "Cancelar download do modelo de rostos", @@ -2171,6 +2158,7 @@ "Specific folder": "Pasta específica", "Same folder as original photo": "Mesma pasta da foto original", "Tidying the thumbnail cache": "Organizando o cache de miniaturas", + "Checking free disk space": "Verificando o espaço livre em disco", "Reset all edits (Cmd+Shift+R)": "Redefinir todas as edições (Cmd+Shift+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Álbuns inteligentes se atualizam sozinhos: altere as regras ou use Foto → Excluir foto", "LightCraft stopped": "O LightCraft parou", @@ -2222,6 +2210,8 @@ "The photos are imported once it ends": "As fotos serão importadas depois", "An import is running. Drop photos when it has finished": "Uma importação está em andamento. Solte as fotos quando ela terminar", "Finish Lightroom catalog import before adding photos": "Conclua a importação do catálogo do Lightroom antes de adicionar fotos", + "Camera preview": "Prévia da câmera", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "O JPEG da própria câmera, mostrado até o LightCraft renderizar o RAW. Avalie cor e tom na foto renderizada.", "Profile: from the file (the camera's own correction)": "Perfil: do arquivo (correção da própria câmera)", "Downloading the lens database…": "Baixando o banco de dados de lentes…", "This file names no lens.": "Este arquivo não indica nenhuma lente.", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index db51744bfa..4972f221d0 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -1602,8 +1602,6 @@ "Back to this person": "Вернуться к этому человеку", "AI Denoise": "ИИ-шумоподавление", "AI Denoise Model": "Модель ИИ-шумоподавления", - "AI Denoise is off: press Use on a model.": "ИИ-шумоподавление выключено: нажмите «Использовать» у модели.", - "AI Denoise needs a model. Install one in Settings.": "Для ИИ-шумоподавления нужна модель. Установите её в настройках.", "Accept & Download": "Принять и загрузить", "Already installed. Remove it before installing a replacement.": "Уже установлено. Удалите перед установкой замены.", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "Автоматический режим использует видеокарту, когда она быстрее процессора: время обоих измеряется на этом компьютере при первой обработке фото.", @@ -1622,7 +1620,6 @@ "Inspect Denoise Model": "Проверить модель шумоподавления", "Install Denoise Model": "Установить модель шумоподавления", "Install from file…": "Установить из файла…", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Установите собственную модель ONNX, положив рядом denoise-model.json. В этой сборке загрузка моделей недоступна.", "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "Его изображение с подавленным шумом ещё не создано, а изображения сами не создаются (Настройки, ИИ-шумоподавление).", "LightCraft does not know this model, so it assumed:": "LightCraft не знает эту модель и предполагает:", "Limit": "Ограничение", @@ -1636,7 +1633,6 @@ "Open the model's page": "Открыть страницу модели", "Opens the model's own page in your browser, to read about it or get the file yourself.": "Открывает страницу модели в браузере, чтобы прочитать о ней или получить файл самостоятельно.", "Processor": "Процессор", - "Set up AI Denoise…": "Настроить ИИ-шумоподавление…", "Speed": "Скорость", "Starting…": "Запуск…", "Tested and works on this computer": "Проверено и работает на этом компьютере", @@ -1645,8 +1641,6 @@ "The model is kept on this computer only. LightCraft never uploads or shares it.": "Модель хранится только на этом компьютере. LightCraft никогда не выгружает и не распространяет её.", "The processor does the work.": "Работу выполняет процессор.", "There is no model file to install": "Нет файла модели для установки", - "This build cannot run denoise models.": "Эта сборка не может запускать модели шумоподавления.", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "В этой сборке негде хранить модели шумоподавления, поэтому ИИ-шумоподавление недоступно. (В настольном приложении есть.)", "This file cannot be used yet": "Этот файл пока нельзя использовать", "Tick the box to accept the model's terms first": "Сначала отметьте согласие с условиями модели", "Try again": "Повторить попытку", @@ -1683,12 +1677,6 @@ "Download Denoise Model": "Загрузить модель шумоподавления", "Remove Denoise Model": "Удалить модель шумоподавления", "Test Denoise Model": "Проверить модель шумоподавления", - "AI Denoise is enabled on the requesting photo": "ИИ-шумоподавление включено для запросившего фото", - "After installation, AI Denoise will turn on for the requesting photo.": "После установки ИИ-шумоподавление включится для запросившего фото.", - "Cancel pending action": "Отменить отложенное действие", - "Install a denoise model to enable AI Denoise on this photo": "Установите модель шумоподавления, чтобы включить ИИ-шумоподавление для этого фото", - "Pending photo action cancelled": "Отложенное действие с фото отменено", - "Pending photo action cancelled because its library or photo changed": "Отложенное действие с фото отменено, так как изменилась библиотека или фото", "ONNX model": "Модель ONNX", "commercial use subject to GPL conditions": "коммерческое использование на условиях GPL", "Decrease Rating": "Уменьшить оценку", @@ -1999,7 +1987,6 @@ "Camera make and model": "Производитель и модель камеры", "Cancel AI Mask Model Download": "Отменить загрузку модели ИИ-масок", "Cancel Face Model Download": "Отменить загрузку модели лиц", - "Cancel Pending Photo Action": "Отменить отложенное действие с фото", "Canon CR2 photos from the EOS 7D, 50D, 60D, 550D, 600D, 1200D, 1300D, 5D Mark II and 1D Mark IV (and other": "Фото Canon CR2 с EOS 7D, 50D, 60D, 550D, 600D, 1200D, 1300D, 5D Mark II и 1D Mark IV (и других", "Canon CR3 files show their full-size embedded JPEG (e.g. 6960 × 4640 on an EOS R6 Mark III) instead of the": "Файлы Canon CR3 показывают полноразмерный встроенный JPEG (например, 6960 × 4640 на EOS R6 Mark III) вместо", "Capture date and time in your own format (directives below)": "Дата и время съёмки в вашем формате (директивы ниже)", @@ -2539,6 +2526,7 @@ "Specific folder": "Указанная папка", "Same folder as original photo": "Та же папка, что и у оригинала", "Tidying the thumbnail cache": "Упорядочивание кэша миниатюр", + "Checking free disk space": "Проверка свободного места на диске", "Reset all edits (Cmd+Shift+R)": "Сбросить все правки (Cmd+Shift+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Смарт-альбомы обновляются сами: измените их правила или выберите Фото → Удалить фото", "LightCraft stopped": "LightCraft остановился", @@ -2584,6 +2572,8 @@ "The photos are imported once it ends": "Фото будут импортированы после этого", "An import is running. Drop photos when it has finished": "Импорт уже выполняется. Перетащите фото, когда он закончится", "Finish Lightroom catalog import before adding photos": "Завершите импорт каталога Lightroom, прежде чем добавлять фото", + "Camera preview": "Превью камеры", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "Собственный JPEG камеры, показанный, пока LightCraft не обработает RAW. Оценивайте цвет и тон по обработанному фото.", "Profile: from the file (the camera's own correction)": "Профиль: из файла (коррекция самой камеры)", "Downloading the lens database…": "Загружается база объективов…", "This file names no lens.": "В этом файле не указан объектив.", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 4c4267d523..12024b0ec2 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -95,15 +95,11 @@ "After 7 days": "Efter 7 dagar", "After 90 days": "Efter 90 dagar", "After a year": "Efter ett år", - "After installation, AI Denoise will turn on for the requesting photo.": "Efter installationen aktiveras AI-brusreducering för fotot som begärde den.", "afterwards (issue #101): the partial write is cut off before LightCraft retries, so the next launch replays every": "efteråt (ärende #101): den ofullständiga skrivningen kapas innan LightCraft försöker igen, så nästa start spelar upp varje", "again. Change the period (or turn it off) in Settings → Performance.": "igen. Ändra intervallet (eller stäng av det) i Inställningar → Prestanda.", "against the library's originals no longer scans the whole library when nothing is at that path.": "mot bibliotekets original söker inte längre igenom hela biblioteket när det inte finns något på den sökvägen.", "AI Denoise": "AI-brusreducering", - "AI Denoise is enabled on the requesting photo": "AI-brusreducering är aktiverad på fotot som begärde den", - "AI Denoise is off: press Use on a model.": "AI-brusreducering är av: tryck på Använd på en modell.", "AI Denoise Model": "Modell för AI-brusreducering", - "AI Denoise needs a model. Install one in Settings.": "AI-brusreducering behöver en modell. Installera en i Inställningar.", "AI Mask Model Status": "Status för AI-maskmodell", "AI masks with SAM 3 (Object and Describe in the Masking panel): click an object to select it (⌥-click leaves a": "AI-masker med SAM 3 (Objekt och Beskriv i panelen Maskering): klicka på ett objekt för att markera det (⌥-klick lämnar ett", "Album": "Album", @@ -291,8 +287,6 @@ "Cancel Download": "Avbryt hämtning", "Cancel Face Model Download": "Avbryt hämtning av ansiktsmodell", "Cancel Interaction": "Avbryt interaktion", - "Cancel pending action": "Avbryt väntande åtgärd", - "Cancel Pending Photo Action": "Avbryt väntande fotoåtgärd", "Cancel Preview Build": "Avbryt bygge av förhandsgranskningar", "Candidate": "Kandidat", "Canon CR2 photos from the EOS 7D, 50D, 60D, 550D, 600D, 1200D, 1300D, 5D Mark II and 1D Mark IV (and other": "Canon CR2-foton från EOS 7D, 50D, 60D, 550D, 600D, 1200D, 1300D, 5D Mark II och 1D Mark IV (och andra", @@ -1022,12 +1016,10 @@ "Inspect Lightroom Catalog": "Inspektera Lightroom-katalog", "Inspect Photo": "Inspektera foto", "Inspecting Lightroom Catalog": "Inspekterar Lightroom-katalog", - "Install a denoise model to enable AI Denoise on this photo": "Installera en brusreduceringsmodell för att aktivera AI-brusreducering för det här fotot", "Install Denoise Model": "Installera brusreduceringsmodell", "Install Face Model": "Installera ansiktsmodell", "Install from file…": "Installera från fil…", "Install the SAM 3 Model": "Installera SAM 3-modellen", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Installera din egen ONNX-modell med denoise-model.json bredvid. Den här versionen erbjuder inga modellnedladdningar.", "installed": "installerad", "Instant ’70s": "Instant 70-tal", "Intent:": "Återgivningsmetod:", @@ -1532,8 +1524,6 @@ "Paste Settings from Previous": "Klistra in inställningar från föregående", "Pastel Haze": "Pastelldis", "Pen Pressure": "Penntryck", - "Pending photo action cancelled": "Väntande fotoåtgärd avbröts", - "Pending photo action cancelled because its library or photo changed": "Väntande fotoåtgärd avbröts eftersom dess bibliotek eller foto ändrades", "People": "Människor", "People Count": "Antal personer", "Percent": "Procent", @@ -1962,7 +1952,6 @@ "Set Rating": "Ange betyg", "Set the mix from the photo's colours": "Ange mixen utifrån fotots färger", "Set Top of Stack": "Ange överst i stapeln", - "Set up AI Denoise…": "Konfigurera AI-brusreducering…", "Settings": "Inställningar", "Settings file problem": "Problem med inställningsfil", "Settings files are never quietly reset (issue #103): a damaged `prefs.json`, `presets.json` or `view.json` is kept": "Inställningsfiler återställs aldrig i tysthet (ärende #103): en skadad `prefs.json`, `presets.json` eller `view.json` behålls", @@ -2219,9 +2208,7 @@ "They move to Recently Deleted and can be restored; no file on disk is touched.": "De flyttas till Nyligen raderade och kan återställas; inga filer på disken påverkas.", "Thirds": "Tredjedelar", "This build can't download the model yet. To install it by hand, put model.safetensors, vocab.json and merges.txt from Meta's facebook/sam3 in the folder above: Object and Describe work as soon as they are there.": "Den här versionen kan inte hämta modellen än. Om du vill installera den manuellt lägger du model.safetensors, vocab.json och merges.txt från Metas facebook/sam3 i mappen ovan: Objekt och Beskriv fungerar så snart de finns där.", - "This build cannot run denoise models.": "Den här versionen kan inte köra brusreduceringsmodeller.", "This build cannot run recognition models: they can be added and chosen, not used.": "Den här versionen kan inte köra igenkänningsmodeller: de kan läggas till och väljas, men inte användas.", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "Den här versionen har ingenstans att spara brusreduceringsmodeller, så AI-brusreducering är inte tillgänglig. (Skrivbordsappen har det.)", "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "Den här versionen har ingenstans att spara ansiktsmodeller, så modellistan är inte tillgänglig. (Skrivbordsappen har det.)", "This Computer": "Den här datorn", "This file cannot be used yet": "Den här filen kan inte användas än", @@ -2242,6 +2229,7 @@ "Thursday": "Torsdag", "Tick the box to accept the model's terms first": "Markera rutan för att godkänna modellens villkor först", "Tidying the thumbnail cache": "Städar miniatyrcachen", + "Checking free disk space": "Kontrollerar ledigt diskutrymme", "Time zone": "Tidszon", "Tint": "Färgton", "Title": "Titel", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 085be4f7e4..beb3e4b278 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -1705,8 +1705,6 @@ "Back to this person": "Повернутися до цієї особи", "AI Denoise": "ШІ: усунення шуму", "AI Denoise Model": "Модель усунення шуму ШІ", - "AI Denoise is off: press Use on a model.": "Усунення шуму ШІ вимкнено: натисніть «Використовувати» на моделі.", - "AI Denoise needs a model. Install one in Settings.": "Для усунення шуму ШІ потрібна модель. Установіть її в налаштуваннях.", "Accept & Download": "Прийняти й завантажити", "Already installed. Remove it before installing a replacement.": "Уже встановлено. Видаліть перед установленням заміни.", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "Автоматичний режим використовує відеокарту, коли вона швидша за процесор: час обох вимірюється на цьому комп’ютері під час першої обробки фото.", @@ -1725,7 +1723,6 @@ "Inspect Denoise Model": "Перевірити модель усунення шуму", "Install Denoise Model": "Установити модель усунення шуму", "Install from file…": "Установити з файлу…", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Установіть власну модель ONNX із denoise-model.json поруч. Ця збірка не пропонує завантаження моделей.", "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "Зображення з усуненим шумом ще не створено, а автоматичне створення вимкнено (Налаштування, ШІ: усунення шуму).", "LightCraft does not know this model, so it assumed:": "LightCraft не знає цю модель, тому припускає:", "Limit": "Обмеження", @@ -1738,7 +1735,6 @@ "Open the model's page": "Відкрити сторінку моделі", "Opens the model's own page in your browser, to read about it or get the file yourself.": "Відкриває сторінку моделі в браузері, щоб прочитати про неї або отримати файл самостійно.", "Processor": "Процесор", - "Set up AI Denoise…": "Налаштувати усунення шуму ШІ…", "Starting…": "Запуск…", "Tested and works on this computer": "Перевірено й працює на цьому комп’ютері", "The denoise model is installed and in use: the AI Denoise Amount slider under Detail now works": "Модель усунення шуму встановлено й використовується: повзунок інтенсивності усунення шуму ШІ в деталях тепер працює", @@ -1746,8 +1742,6 @@ "The model is kept on this computer only. LightCraft never uploads or shares it.": "Модель зберігається лише на цьому комп’ютері. LightCraft ніколи не вивантажує й не поширює її.", "The processor does the work.": "Роботу виконує процесор.", "There is no model file to install": "Немає файлу моделі для встановлення", - "This build cannot run denoise models.": "Ця збірка не може запускати моделі усунення шуму.", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "Ця збірка не має місця для моделей усунення шуму, тому ця функція ШІ недоступна. (Настільний застосунок має.)", "This file cannot be used yet": "Цей файл поки не можна використовувати", "Tick the box to accept the model's terms first": "Спочатку позначте прийняття умов моделі", "Try again": "Спробувати знову", @@ -1784,12 +1778,6 @@ "Download Denoise Model": "Завантажити модель усунення шуму", "Remove Denoise Model": "Видалити модель усунення шуму", "Test Denoise Model": "Перевірити модель усунення шуму", - "AI Denoise is enabled on the requesting photo": "Усунення шуму ШІ ввімкнено для фото, що запросило дію", - "After installation, AI Denoise will turn on for the requesting photo.": "Після встановлення усунення шуму ШІ ввімкнеться для фото, що запросило дію.", - "Cancel pending action": "Скасувати відкладену дію", - "Install a denoise model to enable AI Denoise on this photo": "Установіть модель усунення шуму, щоб увімкнути його для цього фото", - "Pending photo action cancelled": "Відкладену дію фото скасовано", - "Pending photo action cancelled because its library or photo changed": "Відкладену дію фото скасовано, оскільки змінилася бібліотека або фото", "ONNX model": "Модель ONNX", "commercial use subject to GPL conditions": "комерційне використання за умов GPL", "\"saved in memory but not written to disk\", the top bar shows a warning, and LightCraft keeps retrying until the": "«збережено в пам’яті, але не записано на диск», верхня панель показує попередження, а LightCraft повторює спроби, доки", @@ -1950,7 +1938,6 @@ "Sort Albums A–Z": "Сортувати альбоми А–Я", "Go back to listing them by name": "Повернутися до списку за назвою", "Sort Contents A–Z": "Сортувати вміст А–Я", - "Cancel Pending Photo Action": "Скасувати відкладену дію фото", "Show Person": "Показати особу", "Add Face Model…": "Додати модель облич…", "Cancel Face Model Download": "Скасувати завантаження моделі облич", @@ -2329,6 +2316,7 @@ "Specific folder": "Вказана папка", "Same folder as original photo": "Та сама папка, що й оригінал", "Tidying the thumbnail cache": "Упорядкування кешу мініатюр", + "Checking free disk space": "Перевірка вільного місця на диску", "Reset all edits (Cmd+Shift+R)": "Скинути всі зміни (Cmd+Shift+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Розумні альбоми оновлюються самі: змініть їхні правила або виберіть Фото → Видалити фото", "LightCraft stopped": "LightCraft зупинився", @@ -2374,6 +2362,8 @@ "The photos are imported once it ends": "Фото буде імпортовано після цього", "An import is running. Drop photos when it has finished": "Імпорт уже виконується. Перетягніть фото, коли він завершиться", "Finish Lightroom catalog import before adding photos": "Завершіть імпорт каталогу Lightroom, перш ніж додавати фото", + "Camera preview": "Прев'ю камери", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "Власний JPEG камери, показаний, доки LightCraft не обробить RAW. Оцінюйте колір і тон за обробленим фото.", "Profile: from the file (the camera's own correction)": "Профіль: з файлу (корекція самої камери)", "Downloading the lens database…": "Завантажується база об'єктивів…", "This file names no lens.": "У цьому файлі не вказано об'єктив.", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index dd93d0485c..22e907f721 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -35,9 +35,6 @@ "A sleeping NAS, a dropped network share or a USB drive spinning up no longer freezes the window (issue #104):": "NAS đang ngủ, ổ mạng bị ngắt hoặc ổ USB đang quay lên không còn làm đóng băng cửa sổ (issue #104):", "AI Denoise": "Khử nhiễu AI", "AI Denoise Model": "Mô hình khử nhiễu AI", - "AI Denoise is enabled on the requesting photo": "Khử nhiễu AI đã bật trên ảnh yêu cầu", - "AI Denoise is off: press Use on a model.": "Khử nhiễu AI đang tắt: nhấn Dùng trên một mô hình.", - "AI Denoise needs a model. Install one in Settings.": "Khử nhiễu AI cần một mô hình. Hãy cài trong Cài đặt.", "AI Mask Model Status": "Trạng thái mô hình mặt nạ AI", "AI masks with SAM 3 (Object and Describe in the Masking panel): click an object to select it (⌥-click leaves a": "Mặt nạ AI với SAM 3 (Object và Describe trong bảng Mặt nạ): bấm vào đối tượng để chọn (⌥-click để lại", "About": "Giới thiệu", @@ -88,7 +85,6 @@ "After 7 days": "Sau 7 ngày", "After 90 days": "Sau 90 ngày", "After a year": "Sau một năm", - "After installation, AI Denoise will turn on for the requesting photo.": "Sau khi cài, Khử nhiễu AI sẽ bật cho ảnh yêu cầu.", "Album": "Album", "Albums": "Album", "Albums hold library photos: Add to My Photos first": "Album chứa ảnh thư viện: hãy Thêm vào Ảnh của tôi trước", @@ -243,9 +239,7 @@ "Cancel Download": "Hủy tải", "Cancel Face Model Download": "Hủy tải mô hình khuôn mặt", "Cancel Interaction": "Hủy tương tác", - "Cancel Pending Photo Action": "Hủy thao tác ảnh đang chờ", "Cancel Preview Build": "Hủy tạo bản xem trước", - "Cancel pending action": "Hủy thao tác đang chờ", "Candidate": "Ảnh ứng viên", "Canon CR2 photos from the EOS 7D, 50D, 60D, 550D, 600D, 1200D, 1300D, 5D Mark II and 1D Mark IV (and other": "Ảnh Canon CR2 từ EOS 7D, 50D, 60D, 550D, 600D, 1200D, 1300D, 5D Mark II và 1D Mark IV (và các", "Canon CR3 files show their full-size embedded JPEG (e.g. 6960 × 4640 on an EOS R6 Mark III) instead of the": "Tệp Canon CR3 hiển thị JPEG nhúng full-size (ví dụ 6960 × 4640 trên EOS R6 Mark III) thay vì", @@ -880,10 +874,8 @@ "Inspecting Lightroom Catalog": "Đang kiểm tra catalog Lightroom", "Install Denoise Model": "Cài mô hình khử nhiễu", "Install Face Model": "Cài mô hình khuôn mặt", - "Install a denoise model to enable AI Denoise on this photo": "Cài mô hình khử nhiễu để bật AI Khử nhiễu cho ảnh này", "Install from file…": "Cài từ tệp…", "Install the SAM 3 Model": "Cài mô hình SAM 3", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Cài mô hình ONNX của bạn kèm denoise-model.json bên cạnh. Bản build này không tải mô hình.", "Instant ’70s": "Thập niên 70 tức thì", "Intent:": "Ý định:", "Interface": "Giao diện", @@ -1281,8 +1273,6 @@ "Paste from Previous": "Dán từ ảnh trước", "Paste pages": "Dán trang", "Pastel Haze": "Sương pastel", - "Pending photo action cancelled": "Đã hủy thao tác ảnh đang chờ", - "Pending photo action cancelled because its library or photo changed": "Đã hủy thao tác ảnh đang chờ vì thư viện hoặc ảnh đã thay đổi", "People": "Người", "People Count": "Số người", "Percent": "Phần trăm", @@ -1668,7 +1658,6 @@ "Set date & time": "Đặt ngày & giờ", "Set name": "Đặt tên", "Set the mix from the photo's colours": "Đặt hỗn hợp từ màu của ảnh", - "Set up AI Denoise…": "Thiết lập AI Khử nhiễu…", "Settings": "Cài đặt", "Settings file problem": "Lỗi tệp thiết lập", "Settings files are never quietly reset (issue #103): a damaged `prefs.json`, `presets.json` or `view.json` is kept": "Tệp cài đặt không bao giờ im lặng đặt lại (issue #103): `prefs.json`, `presets.json` hoặc `view.json` hỏng được giữ", @@ -1873,9 +1862,7 @@ "Thirds": "Một phần ba", "This Computer": "Máy này", "This build can't download the model yet. To install it by hand, put model.safetensors, vocab.json and merges.txt from Meta's facebook/sam3 in the folder above: Object and Describe work as soon as they are there.": "Bản build này chưa tải mô hình được. Cài tay: đặt model.safetensors, vocab.json và merges.txt từ facebook/sam3 của Meta vào thư mục trên: Object và Describe hoạt động ngay khi có đủ.", - "This build cannot run denoise models.": "Bản build này không chạy được mô hình khử nhiễu.", "This build cannot run recognition models: they can be added and chosen, not used.": "Bản build này không chạy mô hình nhận dạng: có thể thêm và chọn, không dùng được.", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "Bản build này không có chỗ lưu mô hình khử nhiễu, nên AI Denoise không khả dụng. (App desktop có.)", "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "Bản build này không có chỗ lưu mô hình khuôn mặt, nên danh sách mô hình không khả dụng. (App desktop có.)", "This file cannot be used yet": "Tệp này chưa dùng được", "This folder is not available (drive disconnected?). Smart previews are not built or used until it is back or you choose another folder.": "Thư mục không khả dụng (ổ đã rút?). Xem trước thông minh không được tạo hay dùng cho đến khi ổ trở lại hoặc bạn chọn thư mục khác.", @@ -2568,6 +2555,7 @@ "Thumbnail size": "Kích thước ảnh thu nhỏ", "Import Thumbnail Size": "Kích thước ảnh thu nhỏ khi nhập", "Tidying the thumbnail cache": "Đang dọn dẹp bộ nhớ đệm ảnh thu nhỏ", + "Checking free disk space": "Đang kiểm tra dung lượng đĩa trống", "Title bar": "Thanh tiêu đề", "Title text": "Văn bản tiêu đề", "Titles": "Tiêu đề", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 5f138b6f9c..6b1c636724 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -1708,8 +1708,6 @@ "Back to this person": "返回此人", "AI Denoise": "AI 降噪", "AI Denoise Model": "AI 降噪模型", - "AI Denoise is off: press Use on a model.": "AI 降噪已关闭:请在某个模型上点击“使用”。", - "AI Denoise needs a model. Install one in Settings.": "AI 降噪需要模型。请在设置中安装一个。", "Accept & Download": "接受并下载", "Already installed. Remove it before installing a replacement.": "已安装。安装替代模型前请先将其移除。", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "自动模式会在显卡快于处理器时使用显卡:两者都会在首次生成照片时于本机计时比较。", @@ -1728,7 +1726,6 @@ "Inspect Denoise Model": "查看降噪模型", "Install Denoise Model": "安装降噪模型", "Install from file…": "从文件安装…", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "请自行安装 ONNX 模型,并在其旁边放置 denoise-model.json。此版本不提供模型下载。", "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "该照片的降噪结果尚未生成,而且不会自动生成(设置、AI 降噪)。", "LightCraft does not know this model, so it assumed:": "LightCraft 不认识此模型,因此按以下假设处理:", "Limit": "上限", @@ -1741,7 +1738,6 @@ "Open the model's page": "打开该模型的页面", "Opens the model's own page in your browser, to read about it or get the file yourself.": "在浏览器中打开该模型的主页,以便查阅说明或自行获取文件。", "Processor": "处理器", - "Set up AI Denoise…": "设置 AI 降噪…", "Speed": "速度", "Starting…": "正在启动…", "Tested and works on this computer": "已在本机测试通过并可正常使用", @@ -1750,8 +1746,6 @@ "The model is kept on this computer only. LightCraft never uploads or shares it.": "模型仅保存在本机。LightCraft 绝不会上传或分享它。", "The processor does the work.": "由处理器完成运算。", "There is no model file to install": "没有可安装的模型文件", - "This build cannot run denoise models.": "此版本无法运行降噪模型。", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "此版本没有存放降噪模型的位置,因此无法使用 AI 降噪。(桌面版可以。)", "This file cannot be used yet": "此文件暂时无法使用", "Tick the box to accept the model's terms first": "请先勾选以接受该模型的条款", "Try again": "重试", @@ -1788,12 +1782,6 @@ "Download Denoise Model": "下载降噪模型", "Remove Denoise Model": "移除降噪模型", "Test Denoise Model": "测试降噪模型", - "AI Denoise is enabled on the requesting photo": "已在发起请求的照片上启用 AI 降噪", - "After installation, AI Denoise will turn on for the requesting photo.": "安装完成后,将为发起请求的照片开启 AI 降噪。", - "Cancel pending action": "取消待处理操作", - "Install a denoise model to enable AI Denoise on this photo": "安装降噪模型后即可在此照片上启用 AI 降噪", - "Pending photo action cancelled": "已取消待处理的照片操作", - "Pending photo action cancelled because its library or photo changed": "待处理的照片操作已取消,因为其所属图库或照片发生了变化", "ONNX model": "ONNX 模型", "commercial use subject to GPL conditions": "商用须遵循 GPL 条款", "Decrease Rating": "降低星级", @@ -2013,7 +2001,6 @@ "Remove from favorites": "从收藏中移除", "Add Face Model…": "添加人脸模型…", "Cancel Face Model Download": "取消人脸模型下载", - "Cancel Pending Photo Action": "取消待处理的照片操作", "Choose Face Recognition Model": "选择人脸识别模型", "Choose a model below (Use) to start.": "请在下方选择模型(点击“使用”)以开始。", "Detect Faces": "检测人脸", @@ -2164,6 +2151,7 @@ "Specific folder": "指定文件夹", "Same folder as original photo": "与原始照片相同的文件夹", "Tidying the thumbnail cache": "正在整理缩略图缓存", + "Checking free disk space": "正在检查可用磁盘空间", "Reset all edits (Cmd+Shift+R)": "重置所有编辑 (Cmd+Shift+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "智能相册会自动更新:请更改其规则,或使用“照片 → 删除照片”", "LightCraft stopped": "LightCraft 已停止", @@ -2221,6 +2209,8 @@ "The photos are imported once it ends": "结束后即导入这些照片", "An import is running. Drop photos when it has finished": "正在导入。导入完成后再拖放照片", "Finish Lightroom catalog import before adding photos": "添加照片前,请先完成 Lightroom 目录的导入", + "Camera preview": "相机预览", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "相机自己的 JPEG,在 LightCraft 渲染出原始文件之前显示。请在渲染后的照片上判断颜色和影调。", "Profile: from the file (the camera's own correction)": "配置文件:来自文件(相机自身的校正)", "Downloading the lens database…": "正在下载镜头数据库…", "This file names no lens.": "此文件未注明镜头。", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 275accbeb0..ffcfaa6816 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -1714,8 +1714,6 @@ "Back to this person": "Back to this person", "AI Denoise": "AI Denoise", "AI Denoise Model": "AI Denoise Model", - "AI Denoise is off: press Use on a model.": "AI Denoise is off: press Use on a model.", - "AI Denoise needs a model. Install one in Settings.": "AI Denoise needs a model. Install one in Settings.", "Accept & Download": "Accept & Download", "Already installed. Remove it before installing a replacement.": "Already installed. Remove it before installing a replacement.", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.", @@ -1734,7 +1732,6 @@ "Inspect Denoise Model": "Inspect Denoise Model", "Install Denoise Model": "Install Denoise Model", "Install from file…": "Install from file…", - "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.", "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).", "LightCraft does not know this model, so it assumed:": "LightCraft does not know this model, so it assumed:", "Limit": "Limit", @@ -1747,7 +1744,6 @@ "Open the model's page": "Open the model's page", "Opens the model's own page in your browser, to read about it or get the file yourself.": "Opens the model's own page in your browser, to read about it or get the file yourself.", "Processor": "Processor", - "Set up AI Denoise…": "Set up AI Denoise…", "Speed": "Speed", "Starting…": "Starting…", "Tested and works on this computer": "Tested and works on this computer", @@ -1756,8 +1752,6 @@ "The model is kept on this computer only. LightCraft never uploads or shares it.": "The model is kept on this computer only. LightCraft never uploads or shares it.", "The processor does the work.": "The processor does the work.", "There is no model file to install": "There is no model file to install", - "This build cannot run denoise models.": "This build cannot run denoise models.", - "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)": "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)", "This file cannot be used yet": "This file cannot be used yet", "Tick the box to accept the model's terms first": "Tick the box to accept the model's terms first", "Try again": "Try again", @@ -1794,12 +1788,6 @@ "Download Denoise Model": "Download Denoise Model", "Remove Denoise Model": "Remove Denoise Model", "Test Denoise Model": "Test Denoise Model", - "AI Denoise is enabled on the requesting photo": "AI Denoise is enabled on the requesting photo", - "After installation, AI Denoise will turn on for the requesting photo.": "After installation, AI Denoise will turn on for the requesting photo.", - "Cancel pending action": "Cancel pending action", - "Install a denoise model to enable AI Denoise on this photo": "Install a denoise model to enable AI Denoise on this photo", - "Pending photo action cancelled": "Pending photo action cancelled", - "Pending photo action cancelled because its library or photo changed": "Pending photo action cancelled because its library or photo changed", "ONNX model": "ONNX model", "commercial use subject to GPL conditions": "commercial use subject to GPL conditions", "Decrease Rating": "降低評分", @@ -2132,6 +2120,7 @@ "Specific folder": "指定資料夾", "Same folder as original photo": "與原始照片相同的資料夾", "Tidying the thumbnail cache": "正在整理縮圖快取", + "Checking free disk space": "正在檢查可用磁碟空間", "Reset all edits (Cmd+Shift+R)": "重設所有編輯(Cmd+Shift+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "智慧型相簿會自動更新:請變更其規則,或使用「照片 → 刪除照片」", "LightCraft stopped": "LightCraft 已停止", @@ -2177,6 +2166,8 @@ "The photos are imported once it ends": "結束後即匯入這些照片", "An import is running. Drop photos when it has finished": "正在匯入。匯入完成後再拖放照片", "Finish Lightroom catalog import before adding photos": "新增照片前,請先完成 Lightroom 目錄的匯入", + "Camera preview": "相機預覽", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "相機自己的 JPEG,在 LightCraft 算繪出原始檔之前顯示。請在算繪後的照片上判斷色彩與色調。", "Profile: from the file (the camera's own correction)": "設定檔:來自檔案(相機本身的校正)", "Downloading the lens database…": "正在下載鏡頭資料庫…", "This file names no lens.": "此檔案未註明鏡頭。", diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba91d2f71..74425972d8 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -6,7 +6,7 @@ use super::{ MAX_PENDING_SHOTS, MAX_SHOT_BYTES, MAX_SHOT_TOTAL_BYTES, MAX_TEXTURE_SIDE, PendingGesture, PendingShot, Perf, Receiver, SCREEN_PROFILE, SCREENSHOT_FALLBACK_MS, SCREENSHOT_SETTLE_MS, SHOT_FORCE_BUSY_MS, SHOT_SETTLE_FRAMES, SHOT_SETTLE_MS, Sender, Session, ShotGeometry, TOAST_SECONDS, UiState, Value, docking, drop_overlay, export_task, focus_scan, frame_rate, headless, i18n, import, lightroom_import, menus, - merge, model_setup, panels, pick, recheck, render, shortcuts, slideshow_export, state, sync, tasks, theme, updates_ui, widgets, + merge, panels, pick, recheck, render, shortcuts, slideshow_export, state, sync, tasks, theme, updates_ui, widgets, }; mod control; @@ -65,6 +65,8 @@ impl LightcraftApp { #[cfg(test)] library_passes: vec![], #[cfg(test)] + prep_ticks: 0, + #[cfg(test)] missing_count_test_delay: None, shadow: None, synthetic: vec![], @@ -94,6 +96,9 @@ impl LightcraftApp { space_hand: None, brush_live: None, loupe_shown: None, + loupe_timing: Default::default(), + prep_synced: false, + look_ahead: Default::default(), region_view: None, region_before_view: None, size_hold: Default::default(), @@ -106,6 +111,7 @@ impl LightcraftApp { merge: merge::MergeState::default(), import: None, scan: None, + scans_stopping: Default::default(), waiting_import: Default::default(), sync: None, sync_owns_changes: false, @@ -123,7 +129,10 @@ impl LightcraftApp { window_is_fullscreen: false, gpu_applied: None, gpu_notice: false, + disk_space_notice: false, + disk_notice: None, memory_applied: None, + hot_pixels_applied: None, display_applied: None, display_error: None, screen_profile: None, @@ -133,7 +142,6 @@ impl LightcraftApp { alt_asks_for_library: false, recent_checks: Default::default(), activity_expanded: false, - model_setup: Default::default(), } } @@ -194,9 +202,6 @@ impl LightcraftApp { /// [`LightcraftApp::run`], keeping what kind of error a refusal is: for code that decides on it /// (offer a model's download, treat a cancel as one) instead of reading the message. pub fn run_typed(&mut self, id: &str, params: Value) -> Result { - if let Some(result) = model_setup::intercept(self, id, ¶ms) { - return result.map_err(CommandError::from); - } if let Some(r) = menus::run_ui_command(self, id, ¶ms) { if r.is_ok() { docking::reveal_command(self, id)?; @@ -488,6 +493,41 @@ impl LightcraftApp { } } + /// The app-wide background preparation settings live with the app settings (`ui.json`): taken + /// into the session once, then a change made through `prefs.setBackgroundPrep` is saved with + /// them. Run at the start of every logic pass, before any command of that pass (also before + /// the fonts are ready and the window is drawn). + fn sync_prep_settings(&mut self) { + if !self.prep_synced { + self.session.prep.app = self.ui.settings.background_prep.sanitized(); + self.prep_synced = true; + } else if self.session.prep.app != self.ui.settings.background_prep { + self.ui.settings.background_prep = self.session.prep.app; + } + } + + /// Preparing photos in the background ([`lightcraft_engine::prep`]): the whole view's previews + /// once the user is culling in the loupe, built from the photo on screen in the direction of travel. + /// Advanced on every logic pass, the hidden ones too (a minimised window keeps preparing). + fn background_prep(&mut self, ctx: &egui::Context) { + #[cfg(test)] + { + self.prep_ticks += 1; + } + let mode = panels::detail::prep_mode(self); + let loupe = self.ui.fullscreen || self.ui.view == state::ViewMode::Detail; + let at = if loupe { self.session.active() } else { None }; + let backward = self.look_ahead.backward(); + self.session.prep_tick(mode, at, backward); + if self.session.preview_build.as_ref().is_some_and(|b| b.running()) { + ctx.request_repaint_after(std::time::Duration::from_millis(500)); + } + // a build that couldn't start tries again at its time, also when nothing else draws a frame + if let Some(wait) = self.session.prep_retry_in() { + ctx.request_repaint_after(wait); + } + } + /// AI masks: apply finished background requests (clicks, descriptions, detail passes) and /// show their errors; start a zoomed-in detail pass once the clicking stops /// (`ui.detail_due`); watch the model download. Never waits for the model. @@ -584,6 +624,7 @@ impl LightcraftApp { /// hidden, from `Context::run_logic`. It may read the refreshed viewport fields only: never /// `i.time`, events, keys or dropped files. pub fn logic(&mut self, ctx: &egui::Context) { + self.sync_prep_settings(); i18n::set_language(self.ui.language); // The fork's AccessKit root language and bidi runs follow the locale; presentation only. // Compare against the cached string: `Context::language()` allocates on every call, and diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 91eebe1cee..798101a7ef 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -1,6 +1,6 @@ use super::{ - LightcraftApp, docking, drop_overlay, export_task, focus_scan, import, lightroom_import, merge, model_setup, monotonic_ms, panels, pick, recheck, - shortcuts, slideshow_export, state, sync, tasks, theme, updates_ui, widgets, + LightcraftApp, docking, drop_overlay, export_task, focus_scan, import, lightroom_import, merge, monotonic_ms, panels, pick, recheck, shortcuts, + slideshow_export, state, sync, tasks, theme, updates_ui, widgets, }; impl LightcraftApp { @@ -44,7 +44,8 @@ impl LightcraftApp { /// monotonic app clock, so a hidden `run_logic` keeps it advancing and a second layout pass is /// a no-op rather than a duplicate. pub(super) fn logic_background(&mut self, ctx: &egui::Context) { - panels::notices::logic(self); + self.background_prep(ctx); + panels::notices::logic(self, ctx); // closing the window (or Quit) with changes only in memory: retry, else ask first if ctx.input(|i| i.viewport().close_requested()) && !panels::notices::may_close(self) { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); @@ -80,7 +81,6 @@ impl LightcraftApp { self.slideshow_tick(ctx, now); panels::denoise::pump_background(self, ctx, now); panels::faces::pump_background(self, ctx, now); - model_setup::pump(self, ctx, now); focus_scan::pump(self, ctx, now); // auto import: list the watched folder every few seconds (on a worker thread: it may be on // a network share), then import what's new like any import (also on a worker thread) @@ -265,6 +265,7 @@ impl LightcraftApp { self.import_dropped_files(ctx); } self.check_external_editor(ctx); + theme::refresh_window_on_first_focus(ctx); // Alt (Option on macOS) while a slider is dragged shows its temporary preview self.ui.alt_held = ctx.input(|i| i.modifiers.alt); // Recent-library checks and launch-list keys read focus/time/keys: they belong to the UI @@ -358,6 +359,8 @@ impl LightcraftApp { } self.widgets = std::mem::take(&mut self.next_widgets); self.widget_hits = std::mem::take(&mut self.next_widget_hits); + // a frame without the loupe (grid, Compare, Survey, slideshow…) ends the loupe's step timing + self.loupe_timing.end_frame(ctx.input(|i| i.time)); panels::notices::finish_ui_pass(self, ctx); panels::library_problem::finish_ui_pass(self, ctx); self.ui_passes = self.ui_passes.wrapping_add(1); diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs index 9a5c612f12..0871f2b02a 100644 --- a/crates/ui-egui/src/app/prefs.rs +++ b/crates/ui-egui/src/app/prefs.rs @@ -48,6 +48,12 @@ impl LightcraftApp { let _ = self.session.execute("app.memoryBudget", &serde_json::json!({"mb": mb})); } self.memory_applied = Some(mb); + let limit = self.ui.settings.hot_pixel_limit; + if self.hot_pixels_applied != Some(limit) { + self.hot_pixels_applied = Some(limit); + // (a value the engine refuses, from a hand-edited file, leaves its limit as it was) + let _ = self.session.execute("app.hotPixelLimit", &serde_json::json!({"percent": limit})); + } // the monitor profile (Settings ▸ Display): previews follow it from the next frame if self.display_applied.as_ref() != Some(&self.ui.settings.display_profile) { let path = self.ui.settings.display_profile.clone(); @@ -84,9 +90,14 @@ impl LightcraftApp { /// While no display profile is chosen, show previews through the profile of the screen the /// window is on (`services.screen_profile`), read about once a second so moving the window to /// another screen is followed. Without the service (or a profile) the display is sRGB. - fn follow_screen_profile(&mut self, _ctx: &egui::Context) { + fn follow_screen_profile(&mut self, ctx: &egui::Context) { + if self.services.screen_profile.is_none() { + return; + } + // an idle window draws no frames: wake up to read again, so a profile changed in Windows is followed + ctx.request_repaint_after(std::time::Duration::from_secs(1)); let now = self.tick_now(); - if self.services.screen_profile.is_none() || self.screen_profile_read.is_some_and(|t| (0.0..1.0).contains(&(now - t))) { + if self.screen_profile_read.is_some_and(|t| (0.0..1.0).contains(&(now - t))) { return; } self.screen_profile_read = Some(now); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 3c6c2e1576..63403650b2 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -133,7 +133,7 @@ pub fn inspect(app: &LightcraftApp, ctx: &egui::Context) -> Value { "selection": app.session.selection.ids.iter().map(|p| p.0).collect::>(), "activeMask": app.session.active_mask, "widgetCount": app.widgets.len(), - "perf": {"viewFollowed": app.session.view_followed, "viewWorkedOut": app.session.view_worked_out, "frameMs": app.perf.frame_ms, "logicMs": app.perf.logic_ms, "updateMs": app.perf.update_ms, "maxUpdateMs": app.perf.max_update_ms, "fps": app.perf.fps, "lastRenderMs": app.renderer.last_main_ms, "renderQueue": app.renderer.queued(), "rendersInFlight": app.renderer.in_flight(), "pendingSlots": app.renderer.pending_slots(), "mergeRunning": app.merge.busy(), "lastMerge": app.merge.last_result, "rendersDone": app.renderer.completed, "thumbTextures": app.renderer.thumb_textures(), "variantTextures": app.renderer.variant_textures(), "gpu": (lightcraft_engine::gpu::ready() && lightcraft_engine::gpu::available()).then(lightcraft_engine::gpu::adapter_name).flatten(), "gpuReason": lightcraft_engine::gpu::unavailable_reason(), "gpuFallback": lightcraft_engine::gpu::last_fallback(), "gpuWindowDevice": lightcraft_engine::gpu::on_window_device(), "screenTextures": app.renderer.has_screen_textures(), "mainOnGpu": app.renderer.textures.get(&crate::render::Slot::Main).is_some_and(|t| t.native.is_some())}, + "perf": {"viewFollowed": app.session.view_followed, "viewWorkedOut": app.session.view_worked_out, "frameMs": app.perf.frame_ms, "logicMs": app.perf.logic_ms, "updateMs": app.perf.update_ms, "maxUpdateMs": app.perf.max_update_ms, "fps": app.perf.fps, "lastRenderMs": app.renderer.last_main_ms, "renderQueue": app.renderer.queued(), "rendersInFlight": app.renderer.in_flight(), "pendingSlots": app.renderer.pending_slots(), "mergeRunning": app.merge.busy(), "lastMerge": app.merge.last_result, "rendersDone": app.renderer.completed, "thumbTextures": app.renderer.thumb_textures(), "thumbsMade": app.renderer.thumbs_made, "variantTextures": app.renderer.variant_textures(), "gpu": (lightcraft_engine::gpu::ready() && lightcraft_engine::gpu::available()).then(lightcraft_engine::gpu::adapter_name).flatten(), "gpuReason": lightcraft_engine::gpu::unavailable_reason(), "gpuFallback": lightcraft_engine::gpu::last_fallback(), "gpuWindowDevice": lightcraft_engine::gpu::on_window_device(), "screenTextures": app.renderer.has_screen_textures(), "mainOnGpu": app.renderer.textures.get(&crate::render::Slot::Main).is_some_and(|t| t.native.is_some()), "loupeSteps": app.loupe_timing.to_json(), "previewCache": preview_cache_json(app)}, "loupe": app.loupe_shown.map(|(p, src)| json!({ "photo": p.0, "source": src, @@ -894,3 +894,20 @@ pub fn save_screenshot(app: &mut LightcraftApp, image: &egui::ColorImage, target } } } + +/// The preview cache's numbers for `ui.inspect` → `perf.previewCache`: what memory holds, and the +/// disk cache's hits, misses and writes this session (notes 47 and 48: are built previews used?). +fn preview_cache_json(app: &crate::LightcraftApp) -> serde_json::Value { + use std::sync::atomic::Ordering; + let (entries, bytes) = app.session.media.rendered.mem_usage(); + let disk = app.session.media.rendered.disk(); + serde_json::json!({ + "memEntries": entries, + "memBytes": bytes, + "diskHits": disk.map(|d| d.hits.load(Ordering::Relaxed)), + "diskMisses": disk.map(|d| d.misses.load(Ordering::Relaxed)), + "diskWrites": disk.map(|d| d.writes.load(Ordering::Relaxed)), + "diskBudget": disk.map(|d| d.budget()), + "loupeEdge": app.session.loupe_edge, + }) +} diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index e5bfab8817..c927608e01 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -34,11 +34,12 @@ pub(crate) use body::thumb_edge; use body::{DEFAULT_BELOW_GRID, badge_rect, dup_counts}; pub use body::{DEFAULT_FOLDER_TEMPLATE, body, example_destination, source_summary}; pub(crate) use body::{DIALOG_SIZE, THUMB_SIZE_DEFAULT, note_dialog_bottom, thumb_size}; +pub(crate) use scan::StoppingScans; #[cfg(not(target_arch = "wasm32"))] pub(crate) use scan::cards_seen; -pub use scan::{ScanTask, browse, open, poll_scan, running}; #[cfg(test)] -pub(crate) use scan::{stall_scan, stall_scan_of}; +pub(crate) use scan::{HELD_RESOLVES, ScanEnd, scan_by_hand, stall_scan, stall_scan_of}; +pub use scan::{ScanTask, browse, open, poll_scan, running}; pub(crate) use tags::{tag_field_width, tag_help, tag_toggle, unknown_tags_warning}; pub use task::{ImportTask, start, start_paths, tick}; diff --git a/crates/ui-egui/src/dialogs/import/scan.rs b/crates/ui-egui/src/dialogs/import/scan.rs index 67b1fa176b..c82f67123c 100644 --- a/crates/ui-egui/src/dialogs/import/scan.rs +++ b/crates/ui-egui/src/dialogs/import/scan.rs @@ -5,7 +5,7 @@ use super::{ImportDialog, LightcraftApp, Ordering, ScanInput, ScanOutput, ScanPr /// window must keep answering meanwhile). pub struct ScanTask { progress: std::sync::Arc, - rx: std::sync::mpsc::Receiver, + rx: std::sync::mpsc::Receiver, /// Open the review with "copy into the library" checked (a camera / card). pub copy: bool, /// Open the review with this album chosen (an album's context menu ▸ Import…). @@ -16,6 +16,91 @@ pub struct ScanTask { sources: Vec, /// The scan's row in the activity stack (its ✕ and `activity.cancel` set `progress.cancel`). guard: lightcraft_engine::activity::TaskGuard, + /// Browsing: the folder as the worker resolved it, once it has. The view shows it as given until then + /// (resolving reads the disk, which a stalled network mount can block: never on this thread). + resolved: Option>, +} + +/// What a scan's worker sends back. Every way it ends sends one, so the probes of earlier scans that +/// [`ScanInput::new`] took from the session always go back to it (a later import doesn't read those files again). +pub(crate) enum ScanEnd { + /// The scan finished. + Done(ScanOutput), + /// Browsing stopped without a listing: the folder couldn't be listed (`failed`), or another folder was + /// chosen. Never an empty listing, which the browse bookkeeping would take for every file gone. + Stopped { probes: std::collections::HashMap, failed: bool }, +} + +impl ScanEnd { + /// The probes this end hands back to the session. + fn into_probes(self) -> std::collections::HashMap { + match self { + ScanEnd::Done(out) => out.probes, + ScanEnd::Stopped { probes, .. } => probes, + } + } +} + +/// Scans stopped without waiting for their workers ([`stop_scan`]), in the order they were stopped, which is +/// the order they started (one scan runs at a time), and which of their probes went back to the session. +#[derive(Default)] +pub(crate) struct StoppingScans { + /// How many scans were stopped: each one's number. + stopped: u64, + /// Each stopped scan's number and channel, kept until its worker ends. + pending: Vec<(u64, std::sync::mpsc::Receiver)>, + /// The probes a stopped scan put back: by whom, and what they said (to tell they are still the ones there). + from: std::collections::HashMap, +} + +/// What tells two probes of one file apart: a file that changed but kept its size has another content hash. +type ProbeMark = (u64, Option, Option); + +fn mark(p: &lightcraft_engine::media::ProbeInfo) -> ProbeMark { + (p.file_size, p.content_hash.clone(), p.file_modified.clone()) +} + +/// Stop the running scan (if any) without waiting for its worker: the scan is closed at once, and its +/// channel is kept until the worker ends, so the probes it holds still come back ([`collect_stopped`]). +fn stop_scan(app: &mut LightcraftApp) { + if let Some(t) = app.scan.take() { + t.progress.cancel.store(true, Ordering::Relaxed); + let s = &mut app.scans_stopping; + s.stopped = s.stopped.saturating_add(1); + s.pending.push((s.stopped, t.rx)); + } +} + +/// The probes of stopped scans whose workers have ended go back to the session (called every frame). A probe +/// the session got since a scan started is newer than that scan's and stays, except one that a scan stopped +/// before it put back: a later scan read that file again, so its probe wins, whichever worker ends first +/// (an older probe of a file changed at the same size would hand the copy check a stale content hash). +fn collect_stopped(app: &mut LightcraftApp, ctx: &egui::Context) { + let probes = &mut app.session.import_probes; + let StoppingScans { pending, from, .. } = &mut app.scans_stopping; + pending.retain(|(seq, rx)| match rx.try_recv() { + Ok(end) => { + for (k, v) in end.into_probes() { + let replace = match probes.get(&k) { + None => true, + Some(have) => from.get(&k).is_some_and(|(by, m)| by < seq && *m == mark(have)), + }; + if replace { + from.insert(k.clone(), (*seq, mark(&v))); + probes.insert(k, v); + } + } + false + } + Err(std::sync::mpsc::TryRecvError::Empty) => true, + Err(std::sync::mpsc::TryRecvError::Disconnected) => false, + }); + if pending.is_empty() { + // no stopped scan left to compare with + from.clear(); + } else { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } } /// The activity row of a scan: the review's ("Scanning folder") or the Local view's ("Reading folder"). @@ -66,14 +151,14 @@ pub fn open(app: &mut LightcraftApp, paths: Vec) -> Result) -> Result) -> Result { - let dir = std::path::absolute(std::path::Path::new(path)).map_err(|e| e.to_string())?; - if !dir.is_dir() { - return Err(format!("{path}: not a folder")); - } + // one spelling for the view, the listing and the catalog's records: `a/lib/../outside` is `a/outside`. Taken out + // by name here, without reading the disk (a link on a stalled network mount would freeze the window): the worker + // resolves the folder, checks it is one, and the view takes its spelling when it says (see `poll_scan`) + let dir = lightcraft_engine::import::browse_spelling(std::path::Path::new(path)).map_err(|e| e.to_string())?; if app.scan.as_ref().is_some_and(|t| !t.browse) || app.import.as_ref().is_some_and(|t| !t.browse) { return Err("an import is running".into()); } let dir_s = dir.to_string_lossy().trim_end_matches(['/', '\\']).to_string(); let subfolders = subfolders.unwrap_or_else(|| app.session.browse.as_ref().is_some_and(|b| b.subfolders)); let running = app.scan.as_ref().is_some_and(|t| t.browse) || app.import.as_ref().is_some_and(|t| t.browse); - if running && app.session.browse.as_ref().is_some_and(|b| b.path == dir_s && b.subfolders == subfolders) { + // (a path through `..` can name another folder than its spelling, past a link: only the worker can tell, so it + // browses again; CodeRabbit on #3583) + let through_dotdot = std::path::Path::new(path).components().any(|c| c == std::path::Component::ParentDir); + if running && !through_dotdot && app.session.browse.as_ref().is_some_and(|b| b.path == dir_s && b.subfolders == subfolders) { // already reading this folder: clicking it again must not restart the progress app.session.source = lightcraft_engine::LibrarySource::Folder; app.session.keep_active_in_view(); return Ok(json!({"path": dir_s, "subfolders": subfolders, "scanning": true})); } - if let Some(t) = app.scan.take() { - t.progress.cancel.store(true, Ordering::Relaxed); - } + stop_scan(app); app.import = None; app.session.browse = Some(lightcraft_engine::Browse { path: dir_s.clone(), subfolders }); app.session.source = lightcraft_engine::LibrarySource::Folder; // the photos the library already knows from this folder show at once: keep or pick the active one app.session.keep_active_in_view(); - let (input, _) = ScanInput::new(&mut app.session, std::slice::from_ref(&dir_s)); + let (mut input, _) = ScanInput::new(&mut app.session, std::slice::from_ref(&dir_s)); let progress = std::sync::Arc::new(ScanProgress::default()); let (tx, rx) = std::sync::mpsc::channel(); let p = progress.clone(); - let root = dir_s.clone(); + // the worker resolves the path as given: on Unix `link/..` is the folder above where the link points, which the + // spelling (`..` taken out by name) can't tell + let given = path.to_owned(); + let sort = app.session.sort; + let (resolved_tx, resolved) = std::sync::mpsc::channel(); let job = move || { - let files: Vec = if subfolders { - lightcraft_engine::import::expand(&[root], None) - } else { - let mut v: Vec = std::fs::read_dir(&root) - .map(|rd| { - rd.flatten() - .filter(|e| !lightcraft_engine::walk::is_hidden_entry(e)) - .map(|e| e.path()) - .filter(|f| f.is_file() && lightcraft_engine::import::is_supported(f)) - .map(|f| f.to_string_lossy().to_string()) - .collect() - }) - .unwrap_or_default(); - v.sort(); - v + let root = match resolve_browse_root(&given) { + Ok(root) => root, + Err(e) => { + log::warn!("browse: can't read {given}: {e}"); + let _ = tx.send(ScanEnd::Stopped { probes: input.take_probes(), failed: true }); + return; + } }; - let _ = tx.send(scan_with(input, &files, &p)); + let _ = resolved_tx.send(root.clone()); + // (never the library's own folder, which the import would otherwise read as photos) + let files = match lightcraft_engine::import::browse_files(&input, &root, subfolders) { + Ok(files) => files, + Err(e) => { + // no listing is sent: the scan ends as failed, and no record is taken for a file gone + log::warn!("browse: can't list {root}: {e}"); + let _ = tx.send(ScanEnd::Stopped { probes: input.take_probes(), failed: true }); + return; + } + }; + // Nothing is read here: the import that follows reads the files and adds them batch by + // batch, first screen first, so the view fills while the rest is read (PERF-CULL-1). + // Another folder chosen meanwhile (`p.cancel`) stops the ordering, and no listing is sent. + let Some(queue) = lightcraft_engine::import::browse_queue_until(&input, files.clone(), &sort, &p.cancel) else { + let _ = tx.send(ScanEnd::Stopped { probes: input.take_probes(), failed: false }); + return; + }; + p.total.store(queue.len(), Ordering::Relaxed); + p.done.store(queue.len(), Ordering::Relaxed); + // the files the library knows come too, marked as such: the folder bookkeeping (browse + // times, records of files gone) needs the whole listing; only the queue is imported + let queued: std::collections::HashSet<&String> = queue.iter().collect(); + let known: Vec = files.iter().filter(|f| !queued.contains(f)).cloned().collect(); + let known = + known.into_iter().map(|path| lightcraft_engine::import::ImportCandidate { path, duplicate: Some("path".into()), ..Default::default() }); + let candidates = + queue.iter().cloned().map(|path| lightcraft_engine::import::ImportCandidate { path, ..Default::default() }).chain(known).collect(); + // the probes of earlier scans go back to the session with the result, for the import that follows + let _ = tx.send(ScanEnd::Done(lightcraft_engine::import::ScanOutput { candidates, probes: input.take_probes() })); }; #[cfg(not(target_arch = "wasm32"))] std::thread::spawn(job); + // the job takes the probes back out of `input`, so it is an FnMut where it runs in place #[cfg(target_arch = "wasm32")] - job(); + { + let mut job = job; + job(); + } let guard = scan_guard(app, &progress, true); - app.scan = Some(ScanTask { progress, rx, copy: false, album: None, browse: true, sources: Vec::new(), guard }); + app.scan = Some(ScanTask { progress, rx, copy: false, album: None, browse: true, sources: Vec::new(), guard, resolved: Some(resolved) }); app.renderer.forget_imports(); Ok(json!({"path": dir_s, "subfolders": subfolders, "scanning": true})) } +/// The browsed folder `given` (the path as `browse` received it, not its [`lightcraft_engine::import::browse_spelling`]) +/// as [`lightcraft_engine::import::browse_path`] resolves it, checked to be a folder: on the browse worker, as it reads the disk. +fn resolve_browse_root(given: &str) -> Result { + #[cfg(test)] + held_resolve(given); + let dir = lightcraft_engine::import::browse_path(std::path::Path::new(given)).map_err(|e| e.to_string())?; + if !dir.is_dir() { + return Err(format!("{given}: not a folder")); + } + Ok(dir.to_string_lossy().trim_end_matches(['/', '\\']).to_string()) +} + +/// Tests: browsed folders whose resolution waits (as on a stalled network mount) while they are listed here. +#[cfg(test)] +pub(crate) static HELD_RESOLVES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +#[cfg(test)] +fn held_resolve(given: &str) { + let held = || HELD_RESOLVES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).iter().any(|p| p == given); + let start = std::time::Instant::now(); + while held() && start.elapsed() < std::time::Duration::from_secs(30) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } +} + /// Collect a finished scan and open the review (called every frame). pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { show_pending_review(app, ctx); + collect_stopped(app, ctx); let Some(task) = app.scan.as_ref() else { return }; ctx.request_repaint_after(std::time::Duration::from_millis(100)); - let out = match task.rx.try_recv() { + // the worker resolved the browsed folder: the view takes its spelling (before its listing, sent after it) + if let Some(root) = task.resolved.as_ref().and_then(|r| r.try_recv().ok()) + && let Some(b) = app.session.browse.as_mut().filter(|b| b.path != root) + { + b.path = root; + app.session.keep_active_in_view(); + } + let Some(task) = app.scan.as_ref() else { return }; + let end = match task.rx.try_recv() { Ok(o) => o, Err(std::sync::mpsc::TryRecvError::Empty) => { if task.guard.is_cancelled() { // ✕: the worker stops at its next file; don't wait for it (a NAS read can take a while) - app.scan = None; + stop_scan(app); return; } let (total, done) = (task.progress.total.load(Ordering::Relaxed), task.progress.done.load(Ordering::Relaxed)); @@ -160,16 +309,32 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { return; } Err(_) => { + // a cancelled scan whose worker ended without a result was not a failure + let cancelled = task.guard.is_cancelled() || task.progress.cancel.load(Ordering::Relaxed); app.scan = None; - app.toast(ctx, crate::i18n::tr("Scan failed")); + if !cancelled { + app.toast(ctx, crate::i18n::tr("Scan failed")); + } return; } }; let Some(task) = app.scan.take() else { return }; - if task.progress.cancel.load(Ordering::Relaxed) { + let cancelled = task.progress.cancel.load(Ordering::Relaxed); + let out = match end { + ScanEnd::Done(out) => out, + ScanEnd::Stopped { probes, failed } => { + app.session.import_probes.extend(probes); + if failed && !cancelled { + app.toast(ctx, crate::i18n::tr("Scan failed")); + } + return; + } + }; + // the probes go back to the session however the scan ended (the ones of a scan stopped earlier may be there) + app.session.import_probes.extend(out.probes); + if cancelled { return; } - app.session.import_probes = out.probes; if task.browse { // the folder and the ones its photos are in count as browsed now, as `library.browse` records them, so // their untouched Local photos aren't forgotten while the folder is in use @@ -247,11 +412,17 @@ pub(crate) fn stall_scan(app: &mut LightcraftApp) -> Box { /// Tests: the same, for a Local folder browse scan (`browse`) instead of the review's scan. #[cfg(test)] pub(crate) fn stall_scan_of(app: &mut LightcraftApp, browse: bool) -> Box { + Box::new(scan_by_hand(app, browse)) +} + +/// Tests: a scan whose worker is the test: what it sends through the returned channel is the scan's end. +#[cfg(test)] +pub(crate) fn scan_by_hand(app: &mut LightcraftApp, browse: bool) -> std::sync::mpsc::Sender { let progress = std::sync::Arc::new(ScanProgress::default()); - let (tx, rx) = std::sync::mpsc::channel::(); + let (tx, rx) = std::sync::mpsc::channel::(); let guard = scan_guard(app, &progress, false); - app.scan = Some(ScanTask { progress, rx, copy: false, album: None, browse, sources: Vec::new(), guard }); - Box::new(tx) + app.scan = Some(ScanTask { progress, rx, copy: false, album: None, browse, sources: Vec::new(), guard, resolved: None }); + tx } /// Whether an import or any scan (the review's, or a Local folder browse) is running, or a finished scan's diff --git a/crates/ui-egui/src/dialogs/settings.rs b/crates/ui-egui/src/dialogs/settings.rs index 271b6e7c91..900ee796ca 100644 --- a/crates/ui-egui/src/dialogs/settings.rs +++ b/crates/ui-egui/src/dialogs/settings.rs @@ -16,7 +16,7 @@ use egui::RichText; use serde_json::{Value, json}; use crate::LightcraftApp; -use crate::state::{GridBadges, PREVIEW_LIMITS, StartupView}; +use crate::state::{GridBadges, HOT_PIXEL_LIMIT_DEFAULT, HOT_PIXEL_LIMITS, PREVIEW_LIMITS, StartupView}; use crate::theme::Tokens; use crate::widgets::register; @@ -57,8 +57,8 @@ pub const TABS: &[(&str, &str)] = &[ ("denoise", "AI Denoise"), ]; -/// Thumbnail cache sizes offered (MB). -const CACHE_SIZES: [u32; 5] = [512, 1024, 2048, 4096, 8192]; +/// Preview cache sizes offered (MB; 0 = automatic: room for every photo of the library). +const CACHE_SIZES: [u32; 8] = [512, 1024, 2048, 4096, 8192, 51_200, 204_800, 0]; const LABEL_W: f32 = 150.0; diff --git a/crates/ui-egui/src/dialogs/settings/performance.rs b/crates/ui-egui/src/dialogs/settings/performance.rs index 370cf08bac..4fe223f696 100644 --- a/crates/ui-egui/src/dialogs/settings/performance.rs +++ b/crates/ui-egui/src/dialogs/settings/performance.rs @@ -1,7 +1,9 @@ use super::widgets::{check, choices, heading, hint, row}; #[cfg(not(target_arch = "wasm32"))] use super::widgets::{label_width, path_label}; -use super::{CACHE_SIZES, LABEL_W, LightcraftApp, PREVIEW_LIMITS, RichText, Tokens, Value, json, register}; +use super::{ + CACHE_SIZES, HOT_PIXEL_LIMIT_DEFAULT, HOT_PIXEL_LIMITS, LABEL_W, LightcraftApp, PREVIEW_LIMITS, RichText, Tokens, Value, json, register, +}; // --------------------------------------------------------------------------------- Performance @@ -49,15 +51,45 @@ pub(super) fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &To let opts = [(0u32, auto.as_str()), (512, "512 MB"), (1024, "1 GB"), (2048, "2 GB"), (4096, "4 GB")]; choices(ui, "settingsMemory", &opts, &mut app.ui.settings.memory_mb); }); - heading(ui, t, crate::i18n::tr("Thumbnail cache")); - let cur = (app.session.cache_bytes() >> 20) as u32; + row(ui, t, crate::i18n::tr("Hot pixel limit"), |ui| { + let opts: Vec<(f32, String)> = HOT_PIXEL_LIMITS + .iter() + .map(|p| (*p, if *p == HOT_PIXEL_LIMIT_DEFAULT { format!("{p} % ({})", crate::i18n::tr("default")) } else { format!("{p} %") })) + .collect(); + let opts: Vec<(f32, &str)> = opts.iter().map(|(p, l)| (*p, l.as_str())).collect(); + choices(ui, "settingsHotPixels", &opts, &mut app.ui.settings.hot_pixel_limit); + }); + hint( + ui, + t, + crate::i18n::tr( + "Remove Hot Pixels (Detail) leaves a raw unchanged when more than this share of its photosites would be replaced: such a photo doesn't look like hot pixels on a sensor.", + ), + ); + heading(ui, t, crate::i18n::tr("Preview cache")); + let cur = app.session.cache_mb; row(ui, t, crate::i18n::tr("Size limit"), |ui| { - let opts = [(512u32, "512 MB"), (1024, "1 GB"), (2048, "2 GB"), (4096, "4 GB"), (8192, "8 GB")]; - let mut v = if CACHE_SIZES.contains(&cur) { cur } else { 2048 }; + let gb = lightcraft_engine::media::default_disk_cache_bytes(app.session.catalog.len()).div_ceil(1 << 30); + let auto = format!("{} ({gb} GB)", crate::i18n::tr("Automatic")); + let custom = custom_cache_option(cur); + let mut opts = + vec![(512u32, "512 MB"), (1024, "1 GB"), (2048, "2 GB"), (4096, "4 GB"), (8192, "8 GB"), (51_200, "50 GB"), (204_800, "200 GB")]; + opts.extend(custom.as_ref().map(|(mb, l)| (*mb, l.as_str()))); + opts.push((0, auto.as_str())); + // (a saved size the list doesn't offer shows as its own option, not as Automatic: picking + // Automatic then changes it; CodeRabbit on #3583) + let mut v = if CACHE_SIZES.contains(&cur) || custom.is_some() { cur } else { 0 }; if choices(ui, "settingsCache", &opts, &mut v) { let _ = app.run("library.preferences", json!({"cacheMb": v})); } }); + hint( + ui, + t, + crate::i18n::tr( + "Grid thumbnails and the previews the loupe shows, kept on disk so photos open at once next time. Automatic makes room for every photo in this library (about 1.5 MB a photo). 50 GB: normal · 200 GB: better, for several weddings or large shoots.", + ), + ); let used = app.session.media.rendered.disk().map(|d| d.size()); row(ui, t, crate::i18n::tr("In use"), |ui| { ui.label( @@ -70,6 +102,7 @@ pub(super) fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &To let _ = app.run("library.clearPreviews", json!({})); } }); + background_prep(app, ui, t); heading(ui, t, crate::i18n::tr("Local folders")); row(ui, t, crate::i18n::tr("Forget unchanged photos"), |ui| { let opts = [(0u32, "Never"), (7, "After 7 days"), (30, "After 30 days"), (90, "After 90 days"), (365, "After a year")]; @@ -89,6 +122,92 @@ pub(super) fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &To smart_previews(app, ui, t); } +/// Settings ▸ Performance ▸ Prepare photos in the background (notes 47 and 48): per mode, what +/// is made ready before the user gets to it (`prefs.backgroundPrep`), app-wide or for this library. +fn background_prep(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + use lightcraft_engine::prep::{Mode, Scope}; + heading(ui, t, crate::i18n::tr("Prepare photos in the background")); + hint( + ui, + t, + crate::i18n::tr( + "While you go through photos in the loupe, the next ones are made ready before you reach them, and when the computer is otherwise idle the previews of every photo in view are built. The photo on screen always comes first; the work shows in the activity list, where it can be stopped.", + ), + ); + let own = app.session.prep.library.is_some(); + let lib_open = app.session.library.is_some(); + if lib_open { + let mut v = own; + if check(ui, "settings.prepOwn", &mut v, "Use different settings for this library") { + let r = if v { + let cur = app.session.prep_settings(); + app.run("prefs.setBackgroundPrep", json!({"library": true, "settings": cur})) + } else { + app.run("prefs.setBackgroundPrep", json!({"reset": true})) + }; + if let Err(e) = r { + log::warn!("background preparation: {e}"); + } + } + hint(ui, t, crate::i18n::tr("For example, a timelapse library can prepare nothing while a wedding library prepares everything.")); + } + let cur = app.session.prep_settings(); + let mut patch: Option = None; + let scopes = [(Scope::All, "Every photo"), (Scope::Marked, "Picks, rated and labelled"), (Scope::OnScreen, "Only the photo on screen")]; + for (mode, key, title) in [(Mode::Culling, "culling", "Culling (a folder before import)"), (Mode::Library, "library", "Library")] { + let m = cur.mode(mode); + ui.add_space(4.0); + ui.label(RichText::new(crate::i18n::tr(title)).font(t.semibold(12.0)).color(t.text)); + let mut previews = m.previews; + row(ui, t, crate::i18n::tr("Previews"), |ui| { + if check(ui, &format!("settings.prep.{key}.previews"), &mut previews, "Build previews for every photo in view") { + patch = Some(json!({key: {"previews": previews}})); + } + }); + hint(ui, t, crate::i18n::tr("Starts once you step through a few photos. Uses about 1.5 MB of disk a photo, and the computer's spare time.")); + let mut ahead = m.ahead; + row(ui, t, crate::i18n::tr("Photos ahead"), |ui| { + let opts = [(0u8, "Off"), (3, "3"), (5, "5"), (10, "10"), (20, "20")]; + if choices(ui, &format!("settingsPrepAhead-{key}"), &opts, &mut ahead) { + patch = Some(json!({key: {"ahead": ahead}})); + } + }); + let mut scope = m.scope; + row(ui, t, crate::i18n::tr("Which photos"), |ui| { + if choices(ui, &format!("settingsPrepScope-{key}"), &scopes, &mut scope) { + patch = Some(json!({key: {"scope": scope}})); + } + }); + } + ui.add_space(4.0); + ui.label(RichText::new(crate::i18n::tr("Editing")).font(t.semibold(12.0)).color(t.text)); + let mut ahead = cur.develop.ahead; + row(ui, t, crate::i18n::tr("Photos ahead"), |ui| { + let opts = [(0u8, "Off"), (1, "1"), (2, "2"), (3, "3"), (5, "5")]; + if choices(ui, "settingsPrepAhead-develop", &opts, &mut ahead) { + patch = Some(json!({"develop": {"ahead": ahead}})); + } + }); + hint( + ui, + t, + crate::i18n::tr( + "The next photos are opened and kept ready to edit, so the first slider move on them is quick. Uses memory: a few hundred MB a photo.", + ), + ); + let mut scope = cur.develop.scope; + row(ui, t, crate::i18n::tr("Which photos"), |ui| { + if choices(ui, "settingsPrepScope-develop", &scopes, &mut scope) { + patch = Some(json!({"develop": {"scope": scope}})); + } + }); + if let Some(patch) = patch + && let Err(e) = app.run("prefs.setBackgroundPrep", json!({"library": own, "settings": patch})) + { + log::warn!("background preparation: {e}"); + } +} + /// Where this library keeps its smart previews (the offline-editing proxies, which can be large): /// the effective folder, what is in it, and choosing another one. #[cfg(not(target_arch = "wasm32"))] @@ -193,3 +312,24 @@ fn smart_previews(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } hint(ui, t, crate::i18n::tr("Keep it on a drive with room: smart previews are about 1 MB per photo. The thumbnail cache stays in the library.")); } + +/// The cache size limit saved in the settings, as an option of its own when the list doesn't offer +/// it (set through `library.preferences`, or by an older version): its value and label. +fn custom_cache_option(cur: u32) -> Option<(u32, String)> { + if cur == 0 || CACHE_SIZES.contains(&cur) { + return None; + } + let label = if cur.is_multiple_of(1024) { format!("{} GB", cur / 1024) } else { format!("{cur} MB") }; + Some((cur, label)) +} + +#[cfg(test)] +mod tests { + #[test] + fn a_saved_cache_size_the_list_does_not_offer_is_an_option() { + assert_eq!(super::custom_cache_option(0), None, "Automatic"); + assert_eq!(super::custom_cache_option(51_200), None, "offered"); + assert_eq!(super::custom_cache_option(10_240), Some((10_240, "10 GB".to_string()))); + assert_eq!(super::custom_cache_option(3000), Some((3000, "3000 MB".to_string()))); + } +} diff --git a/crates/ui-egui/src/headless/tests.rs b/crates/ui-egui/src/headless/tests.rs index 7ba584faf0..eb05be0c4c 100644 --- a/crates/ui-egui/src/headless/tests.rs +++ b/crates/ui-egui/src/headless/tests.rs @@ -1,5 +1,7 @@ +/// A raw photo is offered the AI Denoise switch with no set-up and one click turns it on with the built-in +/// denoiser; Settings still offers installing a model, and a photo that is not raw is not offered it. #[test] -fn detail_offers_ai_denoise_for_raw_photos_and_leads_to_its_settings() { +fn detail_offers_ai_denoise_for_raw_photos_without_any_set_up() { use crate::state::Dialog; use lightcraft_catalog::{MediaKind, Op, Photo, PhotoId, Source}; let mut h = demo([1400.0, 900.0]); @@ -29,13 +31,17 @@ fn detail_offers_ai_denoise_for_raw_photos_and_leads_to_its_settings() { h.step(); h.step(); let w = widgets(&mut h); - assert!(w.contains("\"denoise:setup\""), "a raw photo with no model is offered the setup: {w}"); - // One click lands in Settings, with local installation available even without a download offer. - let r = h.request("ui.clickWidget", json!({"id": "denoise:setup"}), t); + assert!(w.contains("\"denoise:enabled\"") && !w.contains("\"denoise:setup\""), "a raw photo is offered the switch, with no set-up: {w}"); + // One click turns it on with the built-in denoiser: nothing to install first. + let r = h.request("ui.clickWidget", json!({"id": "denoise:enabled"}), t); assert_eq!(r["ok"], true, "{r}"); h.step(); h.step(); - assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "denoise".into() })); + assert_eq!(h.app.ui.dialog, None); + assert!(h.app.session.develop_of(id).is_some_and(|d| d.enhance.denoise_enabled())); + assert_eq!(h.app.session.execute("denoise.status", &json!({})).unwrap()["model"]["id"], "builtin"); + // Settings still offers installing a model of one's own. + h.app.ui.dialog = Some(Dialog::Settings { tab: "denoise".into() }); h.settle(SETTLE); let listed = h.app.session.execute("denoise.models.list", &json!({})).unwrap(); assert_eq!(listed["models"].as_array().unwrap().len(), lightcraft_denoise::known::all().len(), "{listed}"); @@ -50,7 +56,7 @@ fn detail_offers_ai_denoise_for_raw_photos_and_leads_to_its_settings() { h.settle(SETTLE); h.step(); h.step(); - assert!(!widgets(&mut h).contains("\"denoise:setup\""), "nothing is offered for a photo denoise does not apply to"); + assert_eq!(h.app.session.denoise_photo_state(h.app.session.active().unwrap()), lightcraft_engine::denoise::PhotoState::NotApplicable); let _ = std::fs::remove_dir_all(&dir); } @@ -527,6 +533,10 @@ fn demo_grid_snapshot_has_ui_pixels() { assert!(bright > 30, "no text in the top bar ({bright} bright px)"); // thumbnails arrived (photo textures were drawn) assert!(h.app.renderer.thumb_textures() > 0); + // and are counted for benchmarks, a count that eviction doesn't lower + let r = h.request("ui.inspect", json!({}), SETTLE); + let made = r["result"]["perf"]["thumbsMade"].as_u64().unwrap_or(0); + assert!(made >= h.app.renderer.thumb_textures() as u64, "{}", r["result"]["perf"]); } #[test] @@ -3416,6 +3426,15 @@ fn browsing_from_the_ui_records_the_folder() { assert_eq!(h.app.session.visible_cloned().len(), 1); assert!(h.app.session.catalog.last_browsed(&root).is_some(), "the browsed folder"); assert!(h.app.session.catalog.last_browsed(&day_s).is_some(), "the folder its photo is in"); + // browsed again: a subfolder with only photos the library knows (nothing to import) still + // counts as browsed + h.app.session.catalog.apply(lightcraft_catalog::Op::SetBrowsed { folder: day_s.clone(), at: None }).unwrap(); + assert!(h.app.session.catalog.last_browsed(&day_s).is_none()); + let r = h.request("engine.execute", json!({"command": "library.browse", "params": {"path": root, "subfolders": true}}), t); + assert_eq!(r["result"]["scanning"], true, "{r}"); + h.settle(SETTLE); + assert_eq!(h.app.session.visible_cloned().len(), 1); + assert!(h.app.session.catalog.last_browsed(&day_s).is_some(), "a folder of known photos only"); let _ = std::fs::remove_dir_all(&dir); } @@ -5057,6 +5076,133 @@ fn screenshot_request_is_answered_without_a_window() { assert_eq!(r["result"]["width"], 640, "{r}"); } +/// Note 47: stepping in the loupe to a photo whose preview was built shows that preview as the +/// photo (fitted to the loupe, no render), and standard previews are built at the loupe's size. +#[test] +fn the_loupe_shows_built_previews_without_rendering_again() { + use crate::render::Slot; + use lightcraft_engine::media::QuickSource; + let mut h = demo([1000.0, 700.0]); + let t = Duration::from_secs(10); + // nothing prepared ahead here: what the loupe shows comes from the build alone + h.request( + "engine.execute", + json!({"command": "prefs.setBackgroundPrep", "params": {"settings": {"library": {"ahead": 0, "previews": false}}}}), + t, + ); + h.request("ui.set", json!({"view": "detail", "right": "none"}), t); + h.settle(SETTLE); + let edge = h.app.session.loupe_edge; + assert!(edge > 100, "the loupe said its size: {edge}"); + let ids = h.app.session.visible_cloned(); + let all: Vec = ids.iter().map(|i| i.0).collect(); + let r = h.request("engine.execute", json!({"command": "library.buildPreviews", "params": {"wait": true, "edge": edge, "ids": all}}), t); + assert_eq!(r["result"]["done"], ids.len(), "{r}"); + let next = ids.get(1).copied().expect("a second photo"); + h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [next.0], "active": next.0}}), t); + assert!(h.step_until(SETTLE, |h| h.app.renderer.textures.get(&Slot::Main).is_some_and(|t| t.photo == next))); + let main = h.app.renderer.textures.get(&Slot::Main).unwrap(); + assert_eq!(main.quick, Some(QuickSource::Cached), "the built preview is the loupe's picture"); + let r = h.request("ui.inspect", json!({}), t); + assert!(r["result"]["perf"]["previewCache"]["memEntries"].as_u64().unwrap_or(0) > 0, "{}", r["result"]["perf"]["previewCache"]); +} + +/// Editing, the loupe renders the photo from its source even when a built preview of it is cached +/// (CodeRabbit on #3077): the cached view would show at once but leave the source undecoded, and +/// the first slider draft would wait for it. +#[test] +fn editing_renders_the_loupe_from_its_source_not_a_built_preview() { + use crate::render::Slot; + use lightcraft_engine::media::QuickSource; + let mut h = demo([1000.0, 700.0]); + let t = Duration::from_secs(10); + h.request( + "engine.execute", + json!({"command": "prefs.setBackgroundPrep", "params": {"settings": {"library": {"ahead": 0, "previews": false}, "develop": {"ahead": 0}}}}), + t, + ); + h.request("ui.set", json!({"view": "detail", "right": "none"}), t); + h.settle(SETTLE); + let edge = h.app.session.loupe_edge; + let ids = h.app.session.visible_cloned(); + let all: Vec = ids.iter().map(|i| i.0).collect(); + let r = h.request("engine.execute", json!({"command": "library.buildPreviews", "params": {"wait": true, "edge": edge, "ids": all}}), t); + assert_eq!(r["result"]["done"], ids.len(), "{r}"); + h.request("ui.set", json!({"right": "edit"}), t); + let next = ids.get(1).copied().expect("a second photo"); + h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [next.0], "active": next.0}}), t); + assert!(h.step_until(SETTLE, |h| h.app.renderer.textures.get(&Slot::Main).is_some_and(|t| t.photo == next))); + let main = h.app.renderer.textures.get(&Slot::Main).unwrap(); + assert_ne!(main.quick, Some(QuickSource::Cached), "rendered from the source while editing"); +} + +/// The loupe holds background preparation back only while its render is on the way (CodeRabbit on +/// #3077): once the photo is shown, the frames that follow don't renew the hold. +#[test] +fn a_shown_loupe_render_does_not_hold_background_preparation() { + use crate::render::Slot; + let mut h = demo([1000.0, 700.0]); + let t = Duration::from_secs(10); + h.request("ui.set", json!({"view": "detail", "right": "none"}), t); + let id = h.app.session.active().expect("an active photo"); + let signals = || crate::panels::detail::FOREGROUND_SIGNALS.with(std::cell::Cell::get); + let before = signals(); + assert!( + h.step_until(SETTLE, |h| h.app.renderer.textures.get(&Slot::Main).is_some_and(|t| t.photo == id) && !h.app.renderer.is_pending(Slot::Main)) + ); + assert!(signals() > before, "the hold was asked for while the render was on its way"); + let shown = signals(); + for _ in 0..10 { + h.step(); + } + assert_eq!(signals(), shown, "no hold while the render is on screen"); +} + +/// The app-wide background preparation settings are kept with the app settings (`ui.json`): +/// the saved ones reach the session at launch, and a change made through the command is saved. +#[test] +fn app_wide_preparation_settings_are_saved_with_the_app_settings() { + let mut h = demo([1000.0, 700.0]); + let t = Duration::from_secs(10); + let mut saved = lightcraft_engine::prep::PrepSettings::default(); + saved.library.ahead = 3; + // (as if read from ui.json before the first frame) + h.app.ui.settings.background_prep = saved; + h.app.prep_synced = false; + h.step(); + assert_eq!(h.app.session.prep.app, saved, "the saved settings reach the session"); + h.request("engine.execute", json!({"command": "prefs.setBackgroundPrep", "params": {"settings": {"library": {"ahead": 10}}}}), t); + h.step(); + assert_eq!(h.app.ui.settings.background_prep.library.ahead, 10, "a change is kept with the app settings"); + assert_eq!(h.app.session.prep.app.library.ahead, 10); +} + +/// Note 48: the loupe prepares as many photos ahead as the settings say, a few at a time, and +/// none when that is off. +#[test] +fn the_loupe_prepares_the_photos_ahead_the_settings_ask_for() { + let mut h = demo([1000.0, 700.0]); + let t = Duration::from_secs(10); + let n = h.app.session.visible_cloned().len(); + assert!(n >= 4, "the demo has photos to step through"); + h.request("engine.execute", json!({"command": "prefs.setBackgroundPrep", "params": {"settings": {"library": {"ahead": 3}}}}), t); + h.request("ui.set", json!({"view": "detail", "right": "none"}), t); + h.settle(SETTLE); + for _ in 0..40 { + h.step(); + } + h.settle(SETTLE); + // the first photo: three ahead (no photo behind it) + assert_eq!(h.app.renderer.prefetch_slots_asked(), 3.min(n - 1)); + h.app.renderer.forget_all(); + h.request("engine.execute", json!({"command": "prefs.setBackgroundPrep", "params": {"settings": {"library": {"ahead": 0}}}}), t); + for _ in 0..40 { + h.step(); + } + h.settle(SETTLE); + assert_eq!(h.app.renderer.prefetch_slots_asked(), 0, "off: nothing prepared ahead"); +} + /// A size typed in the Export dialog is the size exported: the pixel fields kept only multiples /// of 16, so 1080 became 1088 and 3000 became 3008 (issue #3300). #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 00311afd33..c9457e4417 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -33,9 +33,9 @@ pub mod icons; pub mod lens_db; pub mod lightroom_import; pub mod links; +pub mod loupe_timing; pub mod menus; mod missing_sweep; -mod model_setup; pub mod panels; pub mod pick; pub mod recheck; @@ -145,7 +145,6 @@ impl QuitPrompt { } pub struct LightcraftApp { - pub(crate) model_setup: model_setup::Pending, /// Per-catalog-revision caches of library-wide results the panels show every frame /// (expensive on big libraries). pub caches: Caches, @@ -223,6 +222,9 @@ pub struct LightcraftApp { /// effects (which the global shortcut guard also hides). #[cfg(test)] pub(crate) library_passes: Vec, + /// Test-only: how many times background preparation was advanced (once per logic pass). + #[cfg(test)] + pub(crate) prep_ticks: u32, /// Test-only: a delay for the sidebar's Missing Photos count worker (a slow disk). Kept here, /// not in `ui`, because `ui.set` rebuilds `ui` and would drop it. #[cfg(test)] @@ -289,6 +291,14 @@ pub struct LightcraftApp { /// What the loupe drew last frame: photo and source ("render", "cached", "embedded", "small", /// "thumb", "none"). pub loupe_shown: Option<(lightcraft_catalog::PhotoId, &'static str)>, + /// When each photo stepped to in the loupe first showed (`ui.inspect` → `perf.loupeSteps`). + pub loupe_timing: loupe_timing::LoupeTiming, + /// The app-wide background preparation settings were handed from the saved app settings to + /// the session ([`Self::background_prep`]). + prep_synced: bool, + /// The loupe's look-ahead: the photo it was made for, the direction of travel (+1 / -1), the + /// catalog revision and the edge, so it is worked out again only when one of them changes. + pub(crate) look_ahead: panels::detail::LookAhead, /// The window render the loupe asked for last, by job key (see [`region`]); kept for the few /// windows whose textures can be on screen, and for the inspector. pub region_view: Option, @@ -314,6 +324,9 @@ pub struct LightcraftApp { pub import: Option, /// A folder scan in progress (feeds the import review). pub scan: Option, + /// Scans stopped without waiting for their workers: each channel is kept until its worker ends, so + /// the probes it took from the session come back. + pub(crate) scans_stopping: import::StoppingScans, /// Files that waited for a library and wait for the running import or Synchronize Folder too. pub waiting_import: panels::library_problem::WaitingImport, /// A Synchronize Folder scan in progress (feeds its dialog). @@ -350,8 +363,18 @@ pub struct LightcraftApp { /// Say once, when the GPU device has been tried, that no graphics processor was found /// ([`panels::notices::gpu_notice`]). The desktop app sets it; headless sessions and tests don't. pub gpu_notice: bool, + /// Tell the user once per session when the drive holding the preview cache runs low + /// ([`panels::notices::disk_space_notice`]). The desktop app sets it; headless sessions and tests + /// don't (their drive is whatever the machine has). + pub disk_space_notice: bool, + /// The low-disk notice's text while it is queued in [`LightcraftApp::notices`]: it is shown with a + /// button to Settings ▸ Performance. With the library it was raised for + /// ([`lightcraft_engine::Session::library_generation`]): another library open drops it. + pub(crate) disk_notice: Option<(u64, String)>, /// The memory budget setting last applied (MB, 0 = automatic). memory_applied: Option, + /// The hot pixel limit last applied (percent). + hot_pixels_applied: Option, /// The display profile setting last applied (`app.displayProfile`). pub(crate) display_applied: Option, /// Why the display profile setting could not be applied (shown in Settings ▸ Display). diff --git a/crates/ui-egui/src/loupe_timing.rs b/crates/ui-egui/src/loupe_timing.rs new file mode 100644 index 0000000000..e0df23768f --- /dev/null +++ b/crates/ui-egui/src/loupe_timing.rs @@ -0,0 +1,269 @@ +//! How long the loupe takes to show each photo it is stepped to, measured on the frames it draws. +//! +//! Culling is stepping through photos, so the number that matters is the time from the step (the +//! first frame that draws the new photo) to the first frame that shows something of it, to the +//! first frame with a full-size picture (the camera's embedded JPEG or a cached render) and to the +//! first frame with LightCraft's own render. `ui.inspect` → `perf.loupeSteps` reports the latest +//! steps; `perf-scratch`-style drivers turn them into medians and p95 without the control +//! channel's own round trip in the numbers. + +use std::collections::VecDeque; + +use lightcraft_catalog::PhotoId; +use serde_json::{Value, json}; + +/// Steps kept for `ui.inspect`. +const KEEP: usize = 256; + +/// A photo left sooner than this (s) after it was stepped to was skipped past: the user is +/// holding an arrow key or tapping through. +pub const FAST_STEP_SECS: f64 = 0.25; +/// While stepping fast, how long a photo has to stay before its render is started (s). Until then +/// the loupe shows its camera JPEG or thumbnail, and the workers make the next ones' instead of +/// starting a full raw develop that the next step throws away. +pub const SETTLE_SECS: f64 = 0.12; + +/// One photo's way onto the screen (times in ms since the frame it was stepped to). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct StepTiming { + pub photo: PhotoId, + /// First frame that drew anything of the photo (often the grid thumbnail, magnified). + pub any_ms: Option, + /// What that was. + pub any_source: &'static str, + /// First frame with a full-size stand-in or better: the camera's JPEG, a cached render, the render. + pub full_ms: Option, + pub full_source: &'static str, + /// First frame with LightCraft's own render of the photo (`render` or `cached`). + pub sharp_ms: Option, + /// How long the photo stayed in the loupe (ms): a step taken before `sharp_ms` was skipped past. + pub dwell_ms: f64, +} + +impl StepTiming { + fn to_json(self) -> Value { + json!({ + "photo": self.photo.0, + "anyMs": self.any_ms, + "anySource": self.any_source, + "fullMs": self.full_ms, + "fullSource": self.full_source, + "sharpMs": self.sharp_ms, + "dwellMs": self.dwell_ms, + }) + } +} + +/// The loupe's step timings. +#[derive(Debug, Default)] +pub struct LoupeTiming { + current: Option<(f64, StepTiming)>, + done: VecDeque, + /// Steps finished since the app started (never lowered when old ones leave `done`): a driver's + /// cursor for the steps made after it looked. + total: u64, + /// Whether the loupe drew a photo in the frame being drawn ([`LoupeTiming::end_frame`]). + drawn: bool, + /// How long the photo before the current one stayed (ms), when the loupe stepped to it from + /// that photo; `None` when the loupe opened on it (from the grid, or coming back to the loupe). + stepped_from: Option, +} + +/// Sources that show the photo at full size: the camera's JPEG, a cached or a fresh render. +fn full_size(source: &str) -> bool { + matches!(source, "embedded" | "cached" | "render" | "preview") +} + +impl LoupeTiming { + /// The loupe drew `photo` from `source` (what [`crate::panels::detail`] reports in + /// `loupe_shown`) in the frame that started at `now` (s). + pub fn observe(&mut self, photo: PhotoId, source: &'static str, now: f64) { + self.drawn = true; + if self.current.as_ref().is_none_or(|(_, t)| t.photo != photo) { + let stepped = self.current.is_some(); + self.finish(now); + self.stepped_from = if stepped { self.done.back().map(|t| t.dwell_ms) } else { None }; + let t = StepTiming { photo, any_ms: None, any_source: "none", full_ms: None, full_source: "none", sharp_ms: None, dwell_ms: 0.0 }; + self.current = Some((now, t)); + } + let Some((since, t)) = self.current.as_mut() else { return }; + let ms = ((now - *since) * 1000.0).max(0.0); + if !ms.is_finite() { + return; + } + t.dwell_ms = ms; + if source != "none" && t.any_ms.is_none() { + t.any_ms = Some(ms); + t.any_source = source; + } + if full_size(source) && t.full_ms.is_none() { + t.full_ms = Some(ms); + t.full_source = source; + } + if matches!(source, "render" | "cached") && t.sharp_ms.is_none() { + t.sharp_ms = Some(ms); + } + } + + /// Whether the user is stepping fast and `photo` (being drawn in the frame at `now`) has not + /// stayed [`SETTLE_SECS`] yet: the photo before it was left within [`FAST_STEP_SECS`]. + pub fn settling(&self, photo: PhotoId, now: f64) -> bool { + let (since, prev_dwell) = match &self.current { + // the first frame of a step: `observe` has not seen this photo yet + Some((since, t)) if t.photo != photo => (now, (now - since) * 1000.0), + // (a photo the loupe opened on, not stepped to, never settles: the step that ended by + // leaving the loupe is not its predecessor) + Some((since, _)) => (*since, self.stepped_from.unwrap_or(f64::INFINITY)), + None => return false, + }; + prev_dwell.is_finite() && prev_dwell < FAST_STEP_SECS * 1000.0 && now - since < SETTLE_SECS + } + + /// The loupe is not showing a photo any more (the grid is up). + pub fn left(&mut self, now: f64) { + self.finish(now); + } + + /// A frame (started at `now`) was drawn: when the loupe drew no photo in it (the grid, Compare, Survey, + /// Reference, People or the slideshow is up), the photo it showed was left then, so time away from the + /// loupe never counts as time on that photo. + pub fn end_frame(&mut self, now: f64) { + if !std::mem::take(&mut self.drawn) { + self.left(now); + } + } + + fn finish(&mut self, now: f64) { + if let Some((since, mut t)) = self.current.take() { + let dwell = (now - since) * 1000.0; + if dwell.is_finite() { + t.dwell_ms = dwell.max(t.dwell_ms); + } + if self.done.len() >= KEEP { + self.done.pop_front(); + } + self.done.push_back(t); + self.total = self.total.saturating_add(1); + } + } + + /// The finished steps, oldest first (the latest [`KEEP`]), how many have finished in all, and the photo on screen now. + pub fn to_json(&self) -> Value { + json!({ + "steps": self.done.iter().map(|t| t.to_json()).collect::>(), + "total": self.total, + "current": self.current.as_ref().map(|(_, t)| t.to_json()), + }) + } + + #[cfg(test)] + fn steps(&self) -> Vec { + self.done.iter().copied().collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_step_records_when_each_kind_of_picture_first_showed() { + let mut l = LoupeTiming::default(); + l.observe(PhotoId(1), "none", 10.0); + l.observe(PhotoId(1), "thumb", 10.016); + l.observe(PhotoId(1), "embedded", 10.040); + l.observe(PhotoId(1), "embedded", 10.056); + l.observe(PhotoId(1), "render", 11.0); + l.observe(PhotoId(2), "thumb", 12.0); + let s = l.steps(); + assert_eq!(s.len(), 1); + let t = s[0]; + assert_eq!(t.photo, PhotoId(1)); + assert_eq!((t.any_source, t.full_source), ("thumb", "embedded")); + assert!((t.any_ms.unwrap() - 16.0).abs() < 0.01); + assert!((t.full_ms.unwrap() - 40.0).abs() < 0.01); + assert!((t.sharp_ms.unwrap() - 1000.0).abs() < 0.01); + assert!((t.dwell_ms - 2000.0).abs() < 0.01); + assert_eq!(l.to_json()["current"]["photo"], 2); + } + + #[test] + fn stepping_fast_holds_the_render_back_until_the_photo_stays() { + let mut l = LoupeTiming::default(); + // the first photo opened: no step before it + assert!(!l.settling(PhotoId(1), 0.0)); + l.observe(PhotoId(1), "embedded", 0.0); + // a deliberate step (the photo before stayed 2 s): render at once + assert!(!l.settling(PhotoId(2), 2.0)); + l.observe(PhotoId(2), "embedded", 2.0); + // held arrow: the photo before stayed 33 ms + assert!(l.settling(PhotoId(3), 2.033)); + l.observe(PhotoId(3), "thumb", 2.033); + assert!(l.settling(PhotoId(3), 2.1)); + // …until this one has stayed long enough + assert!(!l.settling(PhotoId(3), 2.033 + SETTLE_SECS + 0.001)); + } + + /// Leaving the loupe soon after a step and coming back on another photo is not a fast step + /// (CodeRabbit on #3077): the photo the loupe opens on renders at once, on every frame. + #[test] + fn coming_back_to_the_loupe_on_another_photo_is_not_a_fast_step() { + let mut l = LoupeTiming::default(); + l.observe(PhotoId(1), "embedded", 0.0); + l.end_frame(0.0); + // the grid is up after 100 ms on the photo + l.end_frame(0.1); + assert!(!l.settling(PhotoId(2), 0.2), "the first frame back"); + l.observe(PhotoId(2), "thumb", 0.2); + l.end_frame(0.2); + assert!(!l.settling(PhotoId(2), 0.25), "nor the frames after it"); + // a fast step from there still settles + l.observe(PhotoId(2), "embedded", 0.25); + assert!(l.settling(PhotoId(3), 0.3)); + l.observe(PhotoId(3), "thumb", 0.3); + assert!(l.settling(PhotoId(3), 0.35)); + } + + /// A frame without the loupe finishes the photo it showed: coming back to it later starts a new step, and + /// neither counts the time away (CodeRabbit on #3055). + #[test] + fn leaving_the_loupe_finishes_its_photo() { + let mut l = LoupeTiming::default(); + l.observe(PhotoId(1), "embedded", 10.0); + l.end_frame(10.0); + l.observe(PhotoId(1), "embedded", 10.5); + l.end_frame(10.5); + assert!(l.steps().is_empty(), "frames that draw the loupe keep the step open"); + // the grid is up from 11 s to 60 s + l.end_frame(11.0); + l.end_frame(60.0); + let s = l.steps(); + assert_eq!(s.len(), 1); + assert!((s[0].dwell_ms - 1000.0).abs() < 0.01, "dwell ends when the loupe went: {}", s[0].dwell_ms); + // back in the loupe on the same photo: a new step, timed from its return + l.observe(PhotoId(1), "render", 60.0); + l.observe(PhotoId(1), "render", 60.2); + l.end_frame(60.2); + assert_eq!(l.steps().len(), 1); + assert_eq!(l.to_json()["current"]["sharpMs"], 0.0); + assert!((l.to_json()["current"]["dwellMs"].as_f64().unwrap() - 200.0).abs() < 0.01); + } + + #[test] + fn a_photo_stepped_past_has_no_sharp_time_and_the_list_is_bounded() { + let mut l = LoupeTiming::default(); + for i in 0..(KEEP as u64 + 10) { + l.observe(PhotoId(i), "thumb", i as f64 * 0.033); + } + l.left(1000.0); + let s = l.steps(); + assert_eq!(s.len(), KEEP); + // the count of steps goes on past the kept list: a driver's cursor (CodeRabbit on #3077) + assert_eq!(l.to_json()["total"], KEEP as u64 + 10); + assert!(s.iter().all(|t| t.sharp_ms.is_none() && t.full_ms.is_none())); + // a non-finite clock never poisons the record + l.observe(PhotoId(9999), "render", f64::NAN); + l.observe(PhotoId(9999), "render", f64::INFINITY); + assert!(l.to_json().is_object()); + } +} diff --git a/crates/ui-egui/src/menus/menubar.rs b/crates/ui-egui/src/menus/menubar.rs index 672c7cbccc..b73729a913 100644 --- a/crates/ui-egui/src/menus/menubar.rs +++ b/crates/ui-egui/src/menus/menubar.rs @@ -465,17 +465,31 @@ fn live_label(app: &LightcraftApp, id: &str, label: &str) -> String { } /// The parameterized submenus. +/// The params of Build Standard-Sized Previews: automatic builds as big as the loupe on this screen shows photos +/// (the engine's standard size, once a loupe has been drawn); before that, in a fresh session, the standard +/// 2560 px, not the engine's 2048 px minimum, so a typical fit view needn't render again; a chosen limit is used as is. +pub(crate) fn standard_build_params(settings: &crate::state::AppSettings, loupe_edge: usize) -> Value { + match settings.preview_limit { + 0 if loupe_edge == 0 => json!({"size": "standard", "edge": settings.standard_preview_edge()}), + 0 => json!({"size": "standard"}), + edge => json!({"size": "standard", "edge": edge}), + } +} + pub(crate) fn expanded(app: &LightcraftApp, name: &str) -> Option> { let active = app.session.active().and_then(|id| app.session.catalog.photo(id).cloned()); let has = active.is_some(); Some(match name { "Previews" => { - let running = app.session.preview_build.as_ref().is_some_and(|b| !b.finished.load(std::sync::atomic::Ordering::Relaxed)); + // (the background preparation's build gives way to one asked for here) + let running = app.session.preview_build.as_ref().is_some_and(|b| b.running() && !b.background); + let stoppable = app.session.preview_build.as_ref().is_some_and(|b| b.running()); + let standard = standard_build_params(&app.ui.settings, app.session.loupe_edge); let scope = if app.session.selection.ids.len() > 1 { "Selected" } else { "Visible" }; vec![ item( "library.buildPreviews", - json!({"size": "standard", "edge": app.ui.settings.standard_preview_edge()}), + standard, crate::i18n::tr_format!("Build Standard-Sized Previews ({scope})", scope = crate::i18n::tr(scope)), None, !running, @@ -489,7 +503,7 @@ pub(crate) fn expanded(app: &LightcraftApp, name: &str) -> Option> !running, None, ), - item("library.cancelPreviews", Value::Null, "Stop Building Previews", None, running, None), + item("library.cancelPreviews", Value::Null, "Stop Building Previews", None, stoppable, None), MenuNode::Separator, // (read and written on a worker thread: the originals may be on a slow drive) item( diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index c803de7193..f4398d2842 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -60,7 +60,6 @@ pub fn language_from_command(id: &str) -> Option { pub const UI_COMMANDS: &[UiCommand] = &[ ("ui.dock", "Arrange Panel", None, ""), ("ui.dock.reset", "Reset Panel Layout", None, "Window"), - ("modelSetup.cancel", "Cancel Pending Photo Action", None, ""), ("view.photoGrid", "Photo Grid", None, "View"), ("view.squareGrid", "Square Grid", None, "View"), // G: Photo Grid ↔ Square Grid (from other views: the photo grid) diff --git a/crates/ui-egui/src/model_setup.rs b/crates/ui-egui/src/model_setup.rs deleted file mode 100644 index 78587697eb..0000000000 --- a/crates/ui-egui/src/model_setup.rs +++ /dev/null @@ -1,160 +0,0 @@ -//! Resume a denoise request after model setup, bound to its original photo and library. - -use crate::i18n::tr; -use crate::{LightcraftApp, state::Dialog}; -use lightcraft_catalog::{PhotoId, Source}; -use lightcraft_engine::denoise::PhotoState; -use serde_json::{Value, json}; - -struct Request { - library: u64, - photo: PhotoId, - source: Source, -} - -impl Request { - fn capture(app: &LightcraftApp, id: PhotoId) -> Result { - let photo = app.session.catalog.photo(id).filter(|p| !p.deleted).ok_or("the requested photo is no longer available")?; - Ok(Self { library: app.session.library_generation(), photo: id, source: photo.source.clone() }) - } - - fn valid(&self, app: &LightcraftApp) -> bool { - self.library == app.session.library_generation() - && app.session.catalog.photo(self.photo).is_some_and(|p| !p.deleted && p.source == self.source) - } -} - -#[derive(Default)] -pub(crate) struct Pending { - denoise: Option, - next_check: f64, -} - -pub(crate) fn denoise_requested(app: &LightcraftApp, id: PhotoId) -> bool { - app.model_setup.denoise.as_ref().is_some_and(|r| r.photo == id && r.valid(app)) -} - -pub(crate) fn intercept(app: &mut LightcraftApp, command: &str, params: &Value) -> Option> { - if matches!(command, "app.openLibrary" | "file.restoreLibrary") { - app.model_setup = Pending::default(); - return None; - } - if command == "modelSetup.cancel" { - if params.get("kind").and_then(Value::as_str) != Some("denoise") { - return Some(Err("modelSetup.cancel: use kind denoise".into())); - } - app.model_setup.denoise = None; - app.ui.status = tr("Pending photo action cancelled").into(); - return Some(Ok(json!({"cancelled": true}))); - } - if command == "denoise.models.downloadCancel" { - app.model_setup.denoise = None; - } - if command != "denoise.toggle" { - return None; - } - let id = match params.get("id") { - Some(v) => match v.as_u64() { - Some(id) => PhotoId(id), - None => return Some(Err("denoise.toggle: id must be a photo id".into())), - }, - None => match app.session.active() { - Some(id) => id, - None => return Some(Err("select a raw photo".into())), - }, - }; - let enabled = app.session.develop_of(id).is_some_and(|d| d.enhance.denoise_enabled()); - let on = match params.get("enabled") { - Some(v) => match v.as_bool() { - Some(on) => on, - None => return Some(Err("denoise.toggle: enabled must be true or false".into())), - }, - None => !enabled && !denoise_requested(app, id), - }; - if !on { - app.model_setup.denoise = None; - return Some(app.session.execute("denoise.toggle", &json!({"id": id.0, "enabled": false})).map_err(|e| e.to_string())); - } - let _ = app.session.execute("denoise.status", &json!({"id": id.0})); - if !matches!(app.session.denoise_photo_state(id), PhotoState::NoModel) { - return None; - } - if app.session.execute("denoise.models.list", &json!({})).ok().is_none_or(|v| v["dir"].is_null()) { - return None; - } - Some(Request::capture(app, id).map(|request| { - app.model_setup.denoise = Some(request); - app.model_setup.next_check = 0.0; - app.ui.dialog = Some(Dialog::Settings { tab: "denoise".into() }); - app.ui.status = tr("Install a denoise model to enable AI Denoise on this photo").into(); - json!({"setupRequired": true, "photo": id.0}) - })) -} - -/// Show the pending model-setup note for `kind` in the model dialog, with a button that cancels -/// the pending action. Does nothing unless a valid denoise setup is waiting. -pub(crate) fn notice(app: &mut LightcraftApp, ui: &mut egui::Ui, kind: &str) { - if kind != "denoise" || !app.model_setup.denoise.as_ref().is_some_and(|r| r.valid(app)) { - return; - } - ui.add(egui::Label::new(tr("After installation, AI Denoise will turn on for the requesting photo.")).wrap()); - let r = ui.small_button(tr("Cancel pending action")); - crate::widgets::register(ui, "modelSetup:cancel:denoise", r.rect); - if r.clicked() { - let _ = app.run("modelSetup.cancel", json!({"kind": "denoise"})); - } - ui.add_space(6.0); -} - -/// The model setup was dismissed with nothing on the way: neither Settings nor a model's terms -/// are showing, no model download or installation is running, and the photo still has no model. -fn abandoned(app: &mut LightcraftApp) -> bool { - if matches!(app.ui.dialog, Some(Dialog::Settings { .. } | Dialog::DenoiseModel { .. })) { - return false; - } - let Some(photo) = app.model_setup.denoise.as_ref().map(|r| r.photo) else { return false }; - if !matches!(app.session.denoise_photo_state(photo), PhotoState::NoModel) { - return false; - } - let Ok(v) = app.session.execute("denoise.models.downloads", &json!({})) else { return false }; - !v["downloads"].as_array().into_iter().flatten().any(|d| matches!(d["state"].as_str(), Some("running" | "done" | "installing" | "installed"))) -} - -/// Advance a pending model setup. An abandoned setup is cancelled on any call (the -/// abandonment/download probe is not throttled); while another interaction is open it waits, and -/// otherwise it checks the photo's model state at most every 250 ms. A photo that still has no -/// model (or cannot use one) keeps waiting; otherwise denoise is enabled and the outcome reported -/// in the status line. -pub(crate) fn pump(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { - if app.model_setup.denoise.is_none() { - return; - } - if abandoned(app) { - // the setup was closed without installing anything: the switch goes back off (issue #922) - app.model_setup.denoise = None; - app.ui.status = tr("Pending photo action cancelled").into(); - return; - } - if app.session.interaction.is_some() { - ctx.request_repaint_after(std::time::Duration::from_millis(250)); - return; - } - if now < app.model_setup.next_check { - return; - } - app.model_setup.next_check = now + 0.25; - let Some(request) = app.model_setup.denoise.take() else { return }; - if !request.valid(app) { - app.ui.status = tr("Pending photo action cancelled because its library or photo changed").into(); - return; - } - if matches!(app.session.denoise_photo_state(request.photo), PhotoState::NoModel | PhotoState::NotApplicable) { - app.model_setup.denoise = Some(request); - ctx.request_repaint_after(std::time::Duration::from_millis(250)); - return; - } - match app.run("denoise.toggle", json!({"id": request.photo.0, "enabled": true})) { - Ok(_) => app.ui.status = tr("AI Denoise is enabled on the requesting photo").into(), - Err(error) => app.ui.status = error, - } -} diff --git a/crates/ui-egui/src/panels/denoise.rs b/crates/ui-egui/src/panels/denoise.rs index 4bb3ceeb33..c9eb0bfa5d 100644 --- a/crates/ui-egui/src/panels/denoise.rs +++ b/crates/ui-egui/src/panels/denoise.rs @@ -141,9 +141,9 @@ fn watch_downloads(app: &mut LightcraftApp, ctx: &egui::Context) { ctx.request_repaint_after(std::time::Duration::from_millis(120)); } -/// Per-photo AI Denoise switch, including a request waiting for model installation. +/// Per-photo AI Denoise switch. pub fn detail_toggle(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, on: bool, applicable: bool) { - let mut enabled = on || crate::model_setup::denoise_requested(app, id); + let mut enabled = on; egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 6, bottom: 2 }).show(ui, |ui| { let r = ui.add_enabled(applicable, egui::Checkbox::new(&mut enabled, crate::i18n::tr("AI Denoise"))); register(ui, "denoise:enabled", r.rect); @@ -180,17 +180,6 @@ pub fn detail_status(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, am }; match state { PhotoState::NotApplicable | PhotoState::Ready => {} - PhotoState::NoModel => { - egui::Frame::NONE.inner_margin(pad).show(ui, |ui| { - note(ui, "AI Denoise needs a model. Install one in Settings.", t.text_dim); - ui.add_space(2.0); - let r = ui.small_button(crate::i18n::tr("Set up AI Denoise…")); - register(ui, "denoise:setup", r.rect); - if r.clicked() { - let _ = app.run("denoise.toggle", json!({"id": id.0, "enabled": true})); - } - }); - } PhotoState::Idle => { if amount > 0.0 && app.session.denoise_auto() { // the pump has not met this photo yet: let it come round soon instead of waiting out its pause @@ -250,20 +239,22 @@ pub fn detail_status(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, am pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let list = models(app, ui.ctx()); heading(ui, t, "AI Denoise"); - crate::model_setup::notice(app, ui, "denoise"); if list["dir"].is_null() { - hint(ui, t, "This build has nowhere to keep denoise models, so AI Denoise is not available. (The desktop app has.)"); + hint(ui, t, "This build has nowhere to keep your own denoise models, so it cannot use one. (The desktop app has.)"); return; } hint( ui, t, - "Cleans noise out of raw photos with an AI model, before the picture is built: the AI Denoise Amount slider under Detail sets how much of it you see. \ + "Cleans noise out of raw photos before the picture is built: the AI Denoise Amount slider under Detail sets how much of it you see. \ Your files are never changed and no extra files are made in your library: the cleaned picture is cached data that is made again when needed.", ); let runtime = list["runtime"].as_bool() == Some(true); + if list["model"].is_null() { + hint(ui, t, "In use: the built-in denoiser. It needs nothing installed, so turning AI Denoise on just works."); + } if !runtime { - hint(ui, t, "This build cannot run denoise models."); + hint(ui, t, "This build cannot run your own denoise models."); } let all: Vec = list["models"].as_array().cloned().unwrap_or_default(); let downloads = app @@ -271,7 +262,7 @@ pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { .execute("denoise.models.downloads", &json!({})) .map(|v| v["downloads"].as_array().cloned().unwrap_or_default()) .unwrap_or_default(); - heading(ui, t, "Models"); + heading(ui, t, "Your own model (optional)"); let installing = downloads.iter().any(|d| d["id"] == "local-install" && d["state"].as_str() == Some("installing")); let r = crate::button::Button::new("Install from file…") .enabled(runtime && app.services.pick_denoise_model.is_some()) @@ -293,7 +284,11 @@ pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { hint(ui, t, why); } if all.is_empty() { - hint(ui, t, "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads."); + hint( + ui, + t, + "To use a model of your own instead of the built-in denoiser, install an ONNX file with denoise-model.json beside it. This build offers no model downloads.", + ); } if let Some(job) = downloads.iter().find(|d| d["id"] == "local-install") { match job["state"].as_str() { @@ -307,7 +302,7 @@ pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { model_row(app, ui, t, m, dl, runtime); } if all.iter().all(|m| m["selected"] != true) && all.iter().any(|m| m["installed"] == true) { - hint(ui, t, "AI Denoise is off: press Use on a model."); + hint(ui, t, "The built-in denoiser is in use: press Use on a model to use that instead."); } hint(ui, t, "Works on raw files from cameras with a standard (Bayer) sensor. Other files keep their normal noise reduction."); work_section(app, ui, t, &list); @@ -523,7 +518,7 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, app.caches.denoise.epoch += 1; } if selected { - let r = ui.button(tr("Turn off")); + let r = ui.button(tr("Stop using")); register(ui, format!("denoise:off:{id}"), r.rect); if r.clicked() { let _ = app.run("denoise.models.select", json!({"id": null})); diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 3e321304d2..534949ab00 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -18,6 +18,7 @@ mod crop; mod filmstrip; mod geometry; mod info; +mod look_ahead; mod masks; mod retouch; mod window; @@ -41,11 +42,15 @@ use geometry::{animated_rect, middle_pan}; pub(crate) use geometry::{fit_rect, fit_texture_rect, focus_pan, navigate_gesture, output_px, pan_image, snap_fit_rect, texture_side}; #[cfg(test)] use info::RENDERING_AFTER_SECS; +use info::camera_preview_badge; use info::{ FILTER_PILL_HEIGHT, FILTER_PILL_INSET, brief_info, filter_pill, filter_pill_shown, info_overlay, info_overlay_extent, label_badge_rect, preview_only_pill, quick_name, }; pub(crate) use info::{draw_focus_point, failed_pill, loupe_pill, rendering_overdue}; +use look_ahead::BEHIND; +pub use look_ahead::LookAhead; +pub(crate) use look_ahead::{Prepare, look_ahead}; use masks::{RegionContext, RegionEdit, color_range_pick, mask_overlay, region_overlay}; use retouch::{eye_overlay, remove_overlay}; pub(crate) use window::overlay_supports_window; @@ -229,11 +234,12 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // one axis only. A box that matches the source to rounding is rendered at exactly its size. let short = |e: usize, a: f32| ((e as f32 / a).round() as usize).max(1); let (rw, rh) = if aspect >= 1.0 { (want, short(want, aspect)) } else { (short(want, 1.0 / aspect), want) }; + note_loupe_edge(app, sizes.canvas_long, !interacting && !split && !split_view); // hover and before renders are stand-ins: the preview size is plenty and keeps them cheap let se = app.ui.settings.stand_in_edge(want, texture_side); let (sw, sh) = if aspect >= 1.0 { (se, short(se, aspect)) } else { (short(se, 1.0 / aspect), se) }; let ask = LoupeAsk { id, with_crop: !crop_tool, interacting, fit_px, overlay }; - request_main(app, ui, &ask, [rw, rh], plan.window_edge.is_none()); + let settling = request_main_or_settle(app, ui, &ask, [rw, rh], plan.window_edge.is_none(), now); // hovering a preset or profile: the photo with that look, shown instead of the loupe render // once it is ready (nothing is committed) let hover_key = request_hover(app, &ask, [sw, sh]); @@ -242,8 +248,14 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } // until the loupe has this photo: show its cached render / embedded preview / a thumbnail request_stand_in(app, id, want, !crop_tool); + if !interacting { + // (what Settings ▸ Performance lets this mode prepare ahead) + let prepare = prepare_ahead(app); + look_ahead(app, id, want.max(8), !crop_tool, prepare); + } let show_before = app.ui.before_after == BeforeAfter::Original || ui.input(|i| i.key_down(egui::Key::Backslash)); - if split || show_before || split_view { + // (the Before render waits for a settled photo like the loupe's own) + if !settling && (split || show_before || split_view) { request_before(app, &ask, [sw, sh]); } // zoomed past what the whole-frame render holds: also render the part on screen, at no more @@ -263,13 +275,16 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { look, holding: navigating || app.size_hold.holding(now), }; - let window_views = if window_ctx.frame_edge.is_some() { + // (stepping fast: no window is asked for until the photo stays, as for the frame above) + let window_views = if window_ctx.frame_edge.is_some() && !settling { let mode = ViewMode { split, show_before, split_view }; window_views(mode, &Views { img_rect, target_rect, before_img, before_target, areas: &areas, main_area, canvas }) } else { Vec::new() }; let windows = request_windows(app, &window_ctx, window_views); + let single = hover_key.is_none() && !split && !show_before && !split_view && !interacting; + let camera_full = request_camera_full(app, &photo, single && !windows.is_empty(), native_long.min(texture_side)); let p = ui.painter_at(canvas); let draw = |slot: Slot, r: Rect, clip: Rect| draw_slot(app, &p, id, ppp, slot, r, clip); // soft proofing: a paper-white surround and the proof's name, as Lightroom shows it @@ -306,16 +321,21 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { none_message(app, &p, &t, canvas, id); } } - app.loupe_shown = Some((id, shown)); + // a wipe shows the Before whole-frame render on its side of the line… let line = crate::region::wipe_line(img_rect, canvas); draw_wipe_before(app, &p, id, img_rect, line); + let camera_full_drawn = camera_full && draw_camera_full(app, &p, id, img_rect, display_aspect, window_cover(&windows)); // …and the window renders go over the whole-frame ones, all of them, where they belong in the // frame (clipped to their pane, or their side of the line) - for (v, view) in &windows { - // (holding `\` in a wipe shows the Before everywhere: it is the Before view alone then) - let mode = if show_before { BeforeAfter::Original } else { app.ui.before_after }; - let clip = crate::region::window_clip(mode, v.before, v.visible, canvas, img_rect); - draw_window(&p.with_clip_rect(clip), app, &window_ctx, v, view); + let drawn = draw_windows(app, &p, &window_ctx, &windows, [canvas, img_rect], (show_before, split)); + let shown = shown_after_windows(shown, camera_full_drawn, drawn); + app.loupe_shown = Some((id, shown)); + app.loupe_timing.observe(id, shown, now); + // the camera's own JPEG is on screen, not LightCraft's rendering of the raw: say so (once), so + // colour and tone are not judged on it (PERF-CULL-4; Lightroom Classic badges its embedded + // previews). Not over a window render, which is LightCraft's own. + if camera_jpeg_shown(app, &photo, shown, drawn) { + camera_preview_badge(ui, canvas, img_rect.intersect(canvas)); } if let Some((bg, g)) = before_badge { paint_badge(&p, bg, g); @@ -462,21 +482,69 @@ fn prefetch_neighbours(app: &mut LightcraftApp, id: PhotoId, main_area: Rect, pp return; } let ids = app.session.visible_cloned(); - if let Some(i) = ids.iter().position(|p| *p == id) { - let next = ids.get(i + 1).copied(); - let prev = i.checked_sub(1).and_then(|j| ids.get(j)).copied(); - for (n, nid) in [next, prev].into_iter().enumerate() { - let Some(nid) = nid else { continue }; - let Some(np) = app.session.catalog.photo(nid).cloned() else { continue }; - let nf = Frame::with_lens(np.width.max(1) as usize, np.height.max(1) as usize, &np.develop, with_crop, np.embedded_lens.as_ref()); - let na = nf.aspect() as f32; - let nr = fit_rect(main_area, na, app.ui.zoom, output_px(&nf), ppp, app.ui.pan); - let nw = app.ui.settings.prefetch_edge(nr.width().max(nr.height()) * ppp, output_px(&nf).into_iter().max().unwrap_or(1), texture_side); - let (w, h) = if na >= 1.0 { (nw, (nw as f32 / na) as usize) } else { ((nw as f32 * na) as usize, nw) }; - if let Some(job) = app.session.loupe_job(nid, w.max(8), h.max(8), with_crop) { - app.renderer.prefetch(Slot::Prefetch(n as u8), job, PREFETCH_PRIORITY); - } + let mode = prep_mode(app); + let prep = app.session.prep_settings(); + let ahead = prep.ahead(mode); + // editing: the next photos are decoded and kept, ready for their edits (their view render is not + // what is wanted, and a cached one would leave the photo undecoded) + let develop = mode == lightcraft_engine::prep::Mode::Develop; + let Some(i) = ids.iter().position(|p| *p == id).filter(|_| ahead > 0) else { return }; + let mut targets = app.look_ahead.targets_n(&ids, i, ahead, BEHIND); + if prep.scope(mode) == lightcraft_engine::prep::Scope::Marked { + targets.retain(|t| lightcraft_engine::prep::marked(&app.session, *t)); + } + // a few at a time, nearest first (the pool keeps workers free for the photo the user goes to) + let mut room = PREFETCH_AT_ONCE.saturating_sub(app.renderer.prefetches_pending()); + let todo: Vec<(usize, PhotoId)> = targets.into_iter().filter_map(|nid| ids.iter().position(|p| *p == nid).map(|at| (at, nid))).collect(); + for (at, nid) in todo { + if room == 0 { + break; } + let n = prefetch_slot(at); + let Some(mut job) = neighbour_job(app, nid, main_area, ppp, texture_side, with_crop) else { continue }; + if develop { + job.view_cache = None; + } + // (asked for already, in this slot: queued, running or made) + if app.renderer.prefetch_asked(n, job.key) { + continue; + } + room -= 1; + app.renderer.prefetch(n, job, PREFETCH_PRIORITY); + } +} + +/// The render a neighbour is prepared with: its loupe render at the size it will be drawn at. +fn neighbour_job( + app: &mut LightcraftApp, + nid: PhotoId, + main_area: Rect, + ppp: f32, + texture_side: usize, + with_crop: bool, +) -> Option { + let np = app.session.catalog.photo(nid)?; + let nf = Frame::with_lens(np.width.max(1) as usize, np.height.max(1) as usize, &np.develop, with_crop, np.embedded_lens.as_ref()); + let na = nf.aspect() as f32; + let nr = fit_rect(main_area, na, app.ui.zoom, output_px(&nf), ppp, app.ui.pan); + let nw = app.ui.settings.prefetch_edge(nr.width().max(nr.height()) * ppp, output_px(&nf).into_iter().max().unwrap_or(1), texture_side); + let (w, h) = if na >= 1.0 { (nw, (nw as f32 / na) as usize) } else { ((nw as f32 * na) as usize, nw) }; + app.session.loupe_job(nid, w.max(8), h.max(8), with_crop) +} + +/// What Settings ▸ Performance lets the mode the user is in prepare ahead. +fn prepare_ahead(app: &LightcraftApp) -> Prepare { + let mode = prep_mode(app); + let prep = app.session.prep_settings(); + Prepare::of(prep.ahead(mode), prep.scope(mode)) +} + +/// The most the loupe shows a whole photo at (the canvas's long side; a photo of another shape than +/// this one may fill it), noted while it shows one view fitted (`single`): standard previews are +/// built at least this big. +fn note_loupe_edge(app: &mut LightcraftApp, canvas_long: f32, single: bool) { + if single && matches!(app.ui.zoom, Zoom::Fit) && canvas_long.is_finite() && canvas_long >= 1.0 { + app.session.loupe_edge = canvas_long.ceil() as usize; } } @@ -733,10 +801,138 @@ struct LoupeAsk { overlay: lightcraft_pipeline::Overlay, } +/// Stepping fast (an arrow held down): the render waits until the photo stays, the camera JPEG or +/// thumbnail shows meanwhile, and a render queued for a photo already left is dropped. Otherwise +/// the loupe's own render is requested. Whether the photo is still settling. +fn request_main_or_settle(app: &mut LightcraftApp, ui: &egui::Ui, a: &LoupeAsk, size: [usize; 2], whole_draft: bool, now: f64) -> bool { + let settling = !a.interacting && app.loupe_timing.settling(a.id, now); + if !settling { + request_main(app, ui, a, size, whole_draft); + return false; + } + drop_unsettled(&mut app.renderer, a.id); + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(crate::loupe_timing::SETTLE_SECS / 2.0)); + true +} + +/// While the photo settles: drop the raw renders still queued for a photo the user is stepping +/// past (one already running finishes). Its whole-frame render unless that is on screen already, +/// the zoomed-in windows (a region render decodes the raw as much as the frame) and the Before +/// view, which is a raw render too. +pub(crate) fn drop_unsettled(renderer: &mut crate::render::Renderer, photo: PhotoId) { + if renderer.textures.get(&Slot::Main).is_none_or(|t| t.photo != photo) { + renderer.drop_queued(Slot::Main); + } + for slot in [Slot::Region, Slot::RegionBefore, Slot::Before] { + renderer.drop_queued(slot); + } +} + +/// Zoomed in on an unedited raw (`zoomed`: one view, window renders up): its camera JPEG at full +/// size under the window render, so a focus check doesn't wait for the raw (PERF-CULL-5; Capture +/// One's Cull view shows the embedded JPEG at 100 % too). Released when the view is not zoomed any +/// more (180 MB). Whether it is wanted. +fn request_camera_full(app: &mut LightcraftApp, photo: &lightcraft_catalog::Photo, zoomed: bool, edge: usize) -> bool { + let wanted = zoomed && app.session.embedded_thumb_is_final(photo); + if wanted { + if let Some(q) = app.session.embedded_full_job(photo.id, edge) { + app.renderer.request_quick(Slot::QuickFull, q, 98); + } + } else if app.renderer.textures.contains_key(&Slot::QuickFull) || app.renderer.is_pending(Slot::QuickFull) { + app.renderer.forget(Slot::QuickFull); + } + wanted +} + +/// The camera JPEG at full size, magnified like the whole-frame render, until the window is +/// there: only where the window will go (`cover`, see [`window_cover`]). A window capped smaller +/// than the view leaves strips around it, and those keep the developed whole-frame render rather +/// than an unlabelled camera JPEG (CodeRabbit on #3544). Whether it was drawn. +fn draw_camera_full(app: &LightcraftApp, p: &egui::Painter, id: PhotoId, img_rect: Rect, display_aspect: f32, cover: Option) -> bool { + let Some(cover) = cover else { return false }; + let Some(tex) = app.renderer.textures.get(&Slot::QuickFull).filter(|t| t.photo == id) else { return false }; + if !crate::region::same_aspect(tex.size[0].max(1) as f32 / tex.size[1].max(1) as f32, display_aspect) { + return false; + } + p.with_clip_rect(p.clip_rect().intersect(cover)).image(tex.id(), img_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + true +} + +/// Where on screen the requested window renders go (each its window's share of its view's drawn +/// rect), joined: `None` without any. +fn window_cover(windows: &[(WindowView, crate::region::RegionView)]) -> Option { + windows + .iter() + .map(|(v, w)| { + let (fw, fh) = (w.full.0.max(1) as f32, w.full.1.max(1) as f32); + let at = v.img.min + vec2(w.window.x as f32 / fw * v.img.width(), w.window.y as f32 / fh * v.img.height()); + Rect::from_min_size(at, vec2(w.window.w as f32 / fw * v.img.width(), w.window.h as f32 / fh * v.img.height())) + }) + .reduce(|a, b| a.union(b)) +} + +/// Which window renders [`draw_windows`] drew. +#[derive(Clone, Copy)] +struct WindowsDrawn { + /// Any of them. + any: bool, + /// The window of the view shown whole: the After side's in a split view, the Before's when + /// the Before is shown alone; what the timing and the source shown are about. Holding `\` + /// side by side or top/bottom keeps both panes, and the After pane is still the one shown. + shown: bool, +} + +/// Draw the window renders over the whole-frame ones, each where it belongs in the frame +/// (clipped to its pane, or its side of the line). +fn draw_windows( + app: &LightcraftApp, + p: &egui::Painter, + ctx: &WindowCtx, + windows: &[(WindowView, crate::region::RegionView)], + [canvas, img_rect]: [Rect; 2], + (show_before, split): (bool, bool), +) -> WindowsDrawn { + let mut out = WindowsDrawn { any: false, shown: false }; + // (holding `\` in a wipe shows the Before everywhere: it is the Before view alone then; side by + // side or top/bottom, both panes stay, and each window stays in its own) + let before_alone = show_before && !split; + for (v, view) in windows { + let mode = if before_alone { BeforeAfter::Original } else { app.ui.before_after }; + let clip = crate::region::window_clip(mode, v.before, v.visible, canvas, img_rect); + let drawn = draw_window(&p.with_clip_rect(clip), app, ctx, v, view); + out.any |= drawn; + out.shown |= drawn && (!v.before || before_alone); + } + out +} + +/// What is on screen once the window renders are drawn: the camera JPEG at full size stands in +/// for the whole-frame render until a window covers it, and a window rendered over a stand-in +/// (thumbnail or camera JPEG) before the whole frame is the raw's own render. +fn shown_after_windows(shown: &'static str, camera_full_drawn: bool, drawn: WindowsDrawn) -> &'static str { + if camera_full_drawn && !drawn.any { + "embedded" + } else if drawn.shown && !matches!(shown, "render" | "cached") { + "render" + } else { + shown + } +} + +/// Whether the camera's own JPEG is what is on screen (not under a window render). +fn camera_jpeg_shown(app: &LightcraftApp, photo: &lightcraft_catalog::Photo, shown: &str, drawn: WindowsDrawn) -> bool { + !drawn.any && (shown == "embedded" || (shown == "thumb" && app.session.embedded_thumb_is_final(photo))) +} + /// Request the loupe's own render at `[rw, rh]` (drafts during drags). fn request_main(app: &mut LightcraftApp, ui: &egui::Ui, a: &LoupeAsk, [rw, rh]: [usize; 2], whole_draft: bool) { let (id, interacting, fit_px, overlay) = (a.id, a.interacting, a.fit_px, a.overlay); - if let Some(job) = app.session.loupe_job(id, rw.max(8), rh.max(8), a.with_crop) { + if let Some(mut job) = app.session.loupe_job(id, rw.max(8), rh.max(8), a.with_crop) { + // editing: the photo is rendered from its source, which stays decoded for the first slider + // draft (a cached view render would show at once but leave the source unread until then) + if prep_mode(app) == lightcraft_engine::prep::Mode::Develop { + job.view_cache = None; + } let job = if interacting { job.draft() } else { job }; // at rest the render is shrunk to exactly the size it is drawn at with a Lanczos filter on // the worker, so the window draws it texel for texel instead of shrinking it with 2-tap @@ -745,6 +941,11 @@ fn request_main(app: &mut LightcraftApp, ui: &egui::Ui, a: &LoupeAsk, [rw, rh]: let job = job.with_overlay(overlay).with_proof(app.ui.soft_proof.then_some(app.ui.proof)); let job = job.with_hidden_grading(app.ui.grading_hidden_for(id)); app.renderer.request(Slot::Main, job, 100); + // the photo on screen comes first: background preparation waits while it is being made + // (only then: this runs every loupe frame, and a render already shown asks for nothing) + if app.renderer.is_pending(Slot::Main) { + signal_foreground(); + } // a drag's draft that renders in a few ms (GPU) is drawn in this frame, not the next (zoomed // in, what changes on screen is the window's draft) #[cfg(not(target_arch = "wasm32"))] @@ -757,6 +958,19 @@ fn request_main(app: &mut LightcraftApp, ui: &egui::Ui, a: &LoupeAsk, [rw, rh]: } } +/// Tell background preparation the loupe is waiting for its render ([`lightcraft_engine::prep::foreground`]). +fn signal_foreground() { + #[cfg(test)] + FOREGROUND_SIGNALS.with(|n| n.set(n.get() + 1)); + lightcraft_engine::prep::foreground(); +} + +#[cfg(test)] +thread_local! { + /// Tests: how often this thread's loupe told background preparation to wait. + pub(crate) static FOREGROUND_SIGNALS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Hovering a preset or profile: the photo with that look, shown instead of the loupe render once /// it is ready (nothing is committed). The key of its render and the label to show. fn request_hover(app: &mut LightcraftApp, a: &LoupeAsk, [sw, sh]: [usize; 2]) -> Option<(u64, String)> { @@ -887,6 +1101,26 @@ fn request_stand_in(app: &mut LightcraftApp, id: PhotoId, edge: usize, with_crop /// Neighbour prefetch: below on-screen thumbnails, above background thumbnail refreshes. const PREFETCH_PRIORITY: u32 = 4; +/// Photos prepared ahead at once (each render spreads over the cores already): the others wait, +/// so the photo the user steps to next finds a worker free. +const PREFETCH_AT_ONCE: usize = 2; +/// Prepared-ahead slots, by the photo's place in the view: a step keeps the photos still ahead in +/// the slots they have (nothing is asked for twice), and the jump to another part of the shoot +/// replaces what was waiting. +const PREFETCH_SLOTS: usize = 32; + +fn prefetch_slot(at: usize) -> Slot { + Slot::Prefetch((at % PREFETCH_SLOTS) as u8) +} + +/// What the user is doing, for the background preparation: editing (a tool panel open), else +/// culling a folder or browsing the library. +pub fn prep_mode(app: &LightcraftApp) -> lightcraft_engine::prep::Mode { + match app.ui.right { + RightPanel::Edit | RightPanel::Crop | RightPanel::Remove | RightPanel::Masking | RightPanel::RedEye => lightcraft_engine::prep::Mode::Develop, + _ => lightcraft_engine::prep::Mode::of(&app.session), + } +} /// Targeted adjustment tool: dragging up/down on the photo raises/lowers the tone-curve region or /// the colour-mixer bands under the press point (`develop.targeted`, one call per whole step, all @@ -1075,6 +1309,29 @@ pub(crate) fn click_zoom_and_pan(app: &mut LightcraftApp, resp: &egui::Response, #[cfg(test)] mod tests { + /// The camera JPEG goes only where the window render will: a window of the left half of the + /// frame covers the left half of the drawn photo, not the strips beside it. + #[test] + fn the_camera_jpeg_covers_only_where_the_window_goes() { + use super::{WindowView, window_cover}; + use crate::region::RegionView; + use egui::{Rect, pos2}; + use lightcraft_pipeline::PixelWindow; + assert_eq!(window_cover(&[]), None, "no window: no camera JPEG"); + let img = Rect::from_min_max(pos2(100.0, 50.0), pos2(700.0, 450.0)); + let v = WindowView { slot: crate::render::Slot::Region, before: false, img, target: img, visible: img }; + let w = RegionView { + photo: lightcraft_catalog::PhotoId(1), + before: false, + key: 1, + full: (6000, 4000), + window: PixelWindow { x: 0, y: 1000, w: 3000, h: 2000 }, + settings: 0, + }; + let r = window_cover(&[(v, w)]).unwrap(); + assert_eq!(r, Rect::from_min_max(pos2(100.0, 150.0), pos2(400.0, 350.0)), "the window's share of the drawn rect"); + } + /// The rotation pointer's arc bulges away from the side of the crop box it is on, and follows /// a box that is itself rotated. #[test] diff --git a/crates/ui-egui/src/panels/detail/info.rs b/crates/ui-egui/src/panels/detail/info.rs index da5ae1bed6..99a0fc1108 100644 --- a/crates/ui-egui/src/panels/detail/info.rs +++ b/crates/ui-egui/src/panels/detail/info.rs @@ -201,6 +201,24 @@ pub(super) fn filter_pill(app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Re } } +/// A small "Camera preview" label at the top right of the photo while the loupe shows the camera's +/// embedded JPEG (widget `loupe:cameraPreview`), with what that means on hover. +pub(super) fn camera_preview_badge(ui: &egui::Ui, canvas: Rect, over: Rect) { + let t = Tokens::get(ui.ctx()); + let p = ui.painter_at(canvas); + let text = crate::i18n::tr("Camera preview"); + let g = p.layout_no_wrap(text.to_string(), t.font(11.5), Color32::from_gray(225)); + let size = vec2(g.size().x + 16.0, 18.0); + let over = if over.is_positive() { over } else { canvas }; + let r = Rect::from_min_size(pos2(over.right() - size.x - 8.0, over.top() + 8.0), size); + p.rect_filled(r, 9.0, Color32::from_black_alpha(165)); + p.galley(pos2(r.left() + 8.0, r.center().y - g.size().y / 2.0), g, Color32::from_gray(225)); + register(ui, "loupe:cameraPreview", r); + let tip = crate::i18n::tr("The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo."); + let resp = ui.interact(r, egui::Id::unique("camera-preview-badge"), Sense::hover()).on_hover_text(tip); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{text}: {tip}"))); +} + /// A raw shown from its embedded JPEG (issue #10): a pill at the canvas' top centre saying so; /// hovering it explains (registered as `notice:previewOnly:loupe`). pub(super) fn preview_only_pill(ui: &mut egui::Ui, canvas: Rect, reason: &str) { diff --git a/crates/ui-egui/src/panels/detail/look_ahead.rs b/crates/ui-egui/src/panels/detail/look_ahead.rs new file mode 100644 index 0000000000..839bf9fe92 --- /dev/null +++ b/crates/ui-egui/src/panels/detail/look_ahead.rs @@ -0,0 +1,119 @@ +//! The loupe's look-ahead: stand-ins and thumbnails for the photos it is likely to be stepped to +//! next (PERF-CULL-2). + +use super::{LightcraftApp, PhotoId}; + +/// How many photos ahead (in the direction of travel) the loupe makes its stand-in for, and how +/// many behind (a step back is common when culling). +const AHEAD: usize = 5; +pub(super) const BEHIND: usize = 1; +/// The look-ahead's priority: below the loupe's own render (100), above everything else. +const AHEAD_PRIORITY: u32 = 96; +/// Thumbnails the loupe keeps while stepping (as many as the grid keeps), and how many photos on +/// either side of the open one stay when it trims them. +const MAX_LOUPE_THUMBS: usize = 600; +const KEEP_AROUND: usize = 64; +/// The thumbnail size the look-ahead asks for (the filmstrip's at 2x). +const AHEAD_THUMB_EDGE: usize = 256; + +/// What [`look_ahead`] last worked out (see `LightcraftApp::look_ahead`). +#[derive(Debug, Default)] +pub struct LookAhead { + /// The last photo the loupe showed, for the direction of travel. + last: Option, + /// +1 forward (the default), -1 backward. + dir: i8, + /// (photo, direction, catalog revision, visible list generation, edge, crop, which photos) the + /// requests were made for: a new source, filter or sort changes the neighbours without an edit, + /// and a change of the preparation settings what may be made. + made_for: Option<(PhotoId, i8, u64, u64, usize, bool, Prepare, u64)>, +} + +/// Which photos the look-ahead may prepare, from Settings ▸ Performance for what the user is doing +/// ([`lightcraft_engine::prep::Mode`]): none when its "Photos ahead" is 0 or it prepares only the photo +/// on screen, else the photos of its "which photos". +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Prepare { + Nothing, + Photos(lightcraft_engine::prep::Scope), +} + +impl Prepare { + /// For `ahead` photos ahead (the mode's count, 0 for the photo on screen only) of `scope`. + pub(crate) fn of(ahead: usize, scope: lightcraft_engine::prep::Scope) -> Prepare { + if ahead == 0 || scope == lightcraft_engine::prep::Scope::OnScreen { Prepare::Nothing } else { Prepare::Photos(scope) } + } +} + +impl LookAhead { + /// The photos to prepare around `id` at position `i` of `ids`: [`AHEAD`] in the direction of + /// travel, nearest first, then [`BEHIND`] the other way, of those `prepare` allows. (The + /// stand-ins are cheap: as many as [`AHEAD`] whatever the mode's count, which is for the full + /// renders made ahead.) + fn targets(&self, app: &LightcraftApp, ids: &[PhotoId], i: usize, prepare: Prepare) -> Vec { + let Prepare::Photos(scope) = prepare else { return Vec::new() }; + let mut targets = self.targets_n(ids, i, AHEAD, BEHIND); + if scope == lightcraft_engine::prep::Scope::Marked { + targets.retain(|t| lightcraft_engine::prep::marked(&app.session, *t)); + } + targets + } + + /// `ahead` photos in the direction of travel from position `i` of `ids`, nearest first, then + /// `behind` the other way. + pub fn targets_n(&self, ids: &[PhotoId], i: usize, ahead: usize, behind: usize) -> Vec { + let dir: isize = if self.dir < 0 { -1 } else { 1 }; + let at = |k: isize| i.checked_add_signed(k).and_then(|j| ids.get(j)).copied(); + let cap = |n: usize| n.min(ids.len()) as isize; + let ahead = (1..=cap(ahead)).filter_map(|k| at(dir * k)); + let behind = (1..=cap(behind)).filter_map(|k| at(-dir * k)); + ahead.chain(behind).collect() + } + + /// Whether the user is stepping backwards. + pub fn backward(&self) -> bool { + self.dir < 0 + } +} + +/// Culling: make the loupe's stand-ins (the camera JPEG of an unedited raw, or a cached render) of +/// the next photos in the direction of travel, so that a step shows the next one at once instead +/// of after reading and decoding it (see [`Slot::QuickAhead`]). +/// Only the photos `prepare` allows (Settings ▸ Performance): none at all asks for nothing, and drops the +/// stand-ins still queued. +pub(crate) fn look_ahead(app: &mut LightcraftApp, id: PhotoId, edge: usize, crop: bool, prepare: Prepare) { + let rev = app.session.catalog.revision; + if app.look_ahead.last != Some(id) { + let ids = app.session.visible_cloned(); + let pos = |p: PhotoId| ids.iter().position(|q| *q == p); + if let (Some(prev), Some(i)) = (app.look_ahead.last, pos(id)) + && let Some(j) = pos(prev) + { + app.look_ahead.dir = if j > i { -1 } else { 1 }; + } + app.look_ahead.last = Some(id); + } + let (visible_gen, ids) = app.session.visible_shared(); + // (the renderer's epoch: a reset drops the stand-ins made, which are then asked for again) + let want = (id, app.look_ahead.dir, rev, visible_gen, edge, crop, prepare, app.renderer.epoch()); + if app.look_ahead.made_for == Some(want) { + return; + } + app.look_ahead.made_for = Some(want); + let Some(i) = ids.iter().position(|p| *p == id) else { return }; + let targets = app.look_ahead.targets(app, &ids, i, prepare); + // stepping through a whole wedding in the loupe would keep every thumbnail it ever drew: keep + // the ones around the photo (what the filmstrip can show) once there are many + if app.renderer.thumb_textures() > MAX_LOUPE_THUMBS { + let keep = ids.iter().skip(i.saturating_sub(KEEP_AROUND)).take(2 * KEEP_AROUND + 1).copied().collect(); + app.renderer.evict_thumbs(&keep, MAX_LOUPE_THUMBS); + } + // their thumbnails first (a small embedded JPEG each, a few ms): something to show at once + // even when a step outruns the full-size previews, and in full screen, where no filmstrip + // asks for them + for &nid in &targets { + crate::panels::grid::request_thumb(app, nid, AHEAD_THUMB_EDGE, AHEAD_PRIORITY + 2); + } + let jobs = targets.into_iter().filter_map(|nid| app.session.quick_view_job(nid, edge, crop)).collect(); + app.renderer.look_ahead(jobs, AHEAD_PRIORITY); +} diff --git a/crates/ui-egui/src/panels/detail/window.rs b/crates/ui-egui/src/panels/detail/window.rs index 3351fab289..5dbaa55f4a 100644 --- a/crates/ui-egui/src/panels/detail/window.rs +++ b/crates/ui-egui/src/panels/detail/window.rs @@ -110,13 +110,14 @@ pub(super) fn request_window(app: &mut LightcraftApp, c: &WindowCtx, v: &WindowV /// Draw `v`'s window texture over the whole-frame render, if it is the one asked for (or, in a /// drag, an earlier draft of it). -pub(super) fn draw_window(p: &egui::Painter, app: &LightcraftApp, c: &WindowCtx, v: &WindowView, wanted: &crate::region::RegionView) { - let Some(tex) = app.renderer.textures.get(&v.slot).filter(|t| t.photo == c.id) else { return }; +pub(super) fn draw_window(p: &egui::Painter, app: &LightcraftApp, c: &WindowCtx, v: &WindowView, wanted: &crate::region::RegionView) -> bool { + let Some(tex) = app.renderer.textures.get(&v.slot).filter(|t| t.photo == c.id) else { return false }; let Some(tile) = app.region_tiles.get(&(v.before, tex.key)).filter(|t| t.is_current(c.id, wanted.full, wanted.settings, c.interacting)) else { - return; + return false; }; let (fw, fh) = (tile.full.0 as f32, tile.full.1 as f32); let at = v.img.min + vec2(tile.window.x as f32 / fw * v.img.width(), tile.window.y as f32 / fh * v.img.height()); let dst = Rect::from_min_size(at, vec2(tile.window.w as f32 / fw * v.img.width(), tile.window.h as f32 / fh * v.img.height())); p.image(tex.id(), dst, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + true } diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index 632bad5cbb..195bcb6488 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -308,6 +308,15 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { { control(app, ui, d, c, true); } + // single outlier photosites, replaced in the raw mosaic (#1345): raws only + if app.session.catalog.photo(id).is_some_and(|p| p.develops_raw()) { + egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 4, bottom: 0 }).show(ui, |ui| { + let mut on = d.detail.nr_outliers; + if crate::dialogs::settings::check(ui, "detail.nrOutliers", &mut on, "Remove Hot Pixels") { + let _ = app.run("develop.merge", json!({"settings": {"detail": {"nr_outliers": on}}, "label": "Remove Hot Pixels"})); + } + }); + } ui.add_space(8.0); }); section(app, ui, &d, "optics", "Optics", |app, ui, d| { diff --git a/crates/ui-egui/src/panels/notices.rs b/crates/ui-egui/src/panels/notices.rs index cc01701932..7a95a423e0 100644 --- a/crates/ui-egui/src/panels/notices.rs +++ b/crates/ui-egui/src/panels/notices.rs @@ -1,6 +1,7 @@ //! Things the user must not miss (issue #103): settings files that were damaged or unreadable when //! the library opened (and host warnings such as a damaged `ui.json`), and quitting while changes -//! are only in memory or while tasks that would be cut short are running (issue #345). +//! are only in memory or while tasks that would be cut short are running (issue #345). Also, once +//! per session, that the drive holding the preview cache is running low ([`disk_space_notice`]). use egui::{Align2, RichText, vec2}; @@ -8,11 +9,35 @@ use crate::theme::Tokens; use crate::widgets::WidgetHit; use crate::{LightcraftApp, QuitPrompt}; -/// Collect the library's settings-file warnings (each is shown once), and the no-GPU notice once the GPU device has -/// been tried. -pub fn logic(app: &mut LightcraftApp) { +/// Collect the library's settings-file warnings (each is shown once), the no-GPU notice once the GPU device has +/// been tried, and the low-disk notice (once per session). +pub fn logic(app: &mut LightcraftApp, ctx: &egui::Context) { let new = app.session.take_library_warnings(); app.notices.extend(new); + // a low-disk notice still queued from the library that was open before is not this one's + if let Some((generation, text)) = app.disk_notice.as_ref() + && *generation != app.session.library_generation() + { + let text = text.clone(); + app.notices.retain(|n| *n != text); + app.disk_notice = None; + } + if app.disk_space_notice { + // the cache grows with every thumbnail and preview, not only while previews are built: the + // engine reads the free space at most every few minutes (a clock check otherwise) + app.session.check_disk_space(false); + // an idle window still takes the read's answer and makes the next check: a pass soon while + // the read runs, and one when the next check is due + if !app.session.disk_space_alert_raised() { + let s = &app.session; + ctx.request_repaint_after(disk_check_wait(s.disk_space_read_running_for(), s.disk_space_next_check_in())); + } + if let Some(alert) = app.session.take_disk_space_alert() { + let text = disk_space_notice(&alert); + app.disk_notice = Some((app.session.library_generation(), text.clone())); + app.notices.push(text); + } + } use lightcraft_engine::gpu; if app.gpu_notice && app.gpu_applied == Some(true) && gpu::ready() { app.gpu_notice = false; @@ -22,6 +47,18 @@ pub fn logic(app: &mut LightcraftApp) { } } +/// How soon the notice logic looks again for the free-space read: soon while a read runs, less often once it has +/// run for a while (a drive that hangs must not keep an idle window drawing four times a second for good), and +/// when the next check is due (`next_in`: sooner after a read that couldn't start) when none runs. +fn disk_check_wait(running_for: Option, next_in: Option) -> std::time::Duration { + use std::time::Duration; + match running_for { + Some(d) if d < Duration::from_secs(5) => Duration::from_millis(250), + Some(_) => Duration::from_secs(5), + None => next_in.unwrap_or(lightcraft_engine::disk_space::CHECK_EVERY), + } +} + /// What to tell the user when GPU rendering is on (`enabled`) but the GPU could not be used for `reason`: only when no /// graphics adapter was found at all ("no GPU adapter among …", e.g. no Vulkan loader on Linux), which makes every /// render much slower without saying so. Nothing when it was turned off (preference, `LIGHTCRAFT_GPU`), a software @@ -40,6 +77,34 @@ pub fn gpu_notice(reason: Option<&str>, enabled: bool) -> Option { Some(text) } +/// Bytes in plain words: "12.3 GB", "850 MB" (binary units, as the cache size choices). +fn size_words(bytes: u64) -> String { + const GB: f64 = (1u64 << 30) as f64; + const MB: f64 = (1u64 << 20) as f64; + let b = bytes as f64; + if b >= 100.0 * GB { + format!("{:.0} GB", b / GB) + } else if b >= GB { + format!("{:.1} GB", b / GB) + } else { + format!("{:.0} MB", b / MB) + } +} + +/// What to tell the user when the drive holding the preview cache runs low: its free space, the +/// cache's size, and where a limit can be set (the notice's button opens Settings ▸ Performance). +pub fn disk_space_notice(alert: &lightcraft_engine::disk_space::LowDiskAlert) -> String { + let free = size_words(alert.space.available); + let total = size_words(alert.space.total); + let cache = size_words(alert.cache_bytes); + crate::i18n::tr_format!( + "The drive with this library's previews is almost full: {free} free of {total}. The preview cache takes {cache} and grows as the library does. To keep it smaller, set a size limit in Settings → Performance.", + free = free, + total = total, + cache = cache + ) +} + /// The quit prompt's text while `count` cancellable tasks run (`names` lists them). fn tasks_message(count: usize, names: &str) -> String { if count == 1 { @@ -113,6 +178,7 @@ enum Choice { QuitAnyway, Cancel, Ok, + Settings, } /// The prompt (quit or settings notice) that owns input this frame, if any. @@ -597,11 +663,27 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { app.quit_confirmed = true; app.ui.quit = true; } - Some(Choice::Cancel | Choice::Ok) | None => app.quit_prompt = None, + Some(Choice::Cancel | Choice::Ok | Choice::Settings) | None => app.quit_prompt = None, } return; } if let Some(text) = app.notices.first().cloned() { + let disk = app.disk_notice.as_ref().filter(|(_, t)| *t == text).map(|(generation, _)| *generation); + if let Some(generation) = disk { + // another library opened since `logic` ran this frame: the notice is the previous library's, + // and the next `logic` takes it away + if generation != app.session.library_generation() { + return; + } + let buttons = [("noticeSettings", "Open Performance Settings", Choice::Settings), ("noticeOk", "OK", Choice::Ok)]; + let Some(i) = window(ctx, "settings-notice", "Drive almost full", &text, &buttons, &mut app.notice_input) else { return }; + app.notices.remove(0); + app.disk_notice = None; + if buttons.get(i).is_some_and(|(_, _, choice)| *choice == Choice::Settings) { + app.ui.dialog = Some(crate::state::Dialog::Settings { tab: "performance".into() }); + } + return; + } let buttons = [("noticeOk", "OK", Choice::Ok)]; if window(ctx, "settings-notice", "Settings file problem", &text, &buttons, &mut app.notice_input).is_some() { app.notices.remove(0); @@ -613,6 +695,42 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { mod tests { use super::{PromptKey, gpu_notice, prepare_ui_pass, prompt_allows_event, prompt_key}; + /// A library switch between `logic` and drawing leaves the previous library's low-disk notice queued for + /// that frame: it is not drawn, nor answered (CodeRabbit on #3577). + #[test] + fn a_low_disk_notice_of_the_library_before_is_not_drawn() { + let ctx = egui::Context::default(); + let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services::default()); + let text = "Drive almost full".to_string(); + app.notices.push(text.clone()); + app.disk_notice = Some((app.session.library_generation().wrapping_add(1), text)); + // the prompt's first button pressed, as Enter would + app.notice_input.activate = Some(0); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert_eq!(app.notices.len(), 1, "not answered"); + assert!(app.ui.dialog.is_none(), "Settings didn't open"); + // the current library's: drawn and answered + app.disk_notice = app.disk_notice.take().map(|(_, t)| (app.session.library_generation(), t)); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert!(app.notices.is_empty(), "answered"); + } + + /// The window wakes four times a second while a free-space read runs, then every few seconds once it hangs + /// (CodeRabbit on #3577: it asked for 250 ms passes for as long as the drive hung). + #[test] + fn a_hanging_free_space_read_is_looked_at_less_often() { + use lightcraft_engine::disk_space::{CHECK_EVERY, RETRY_AFTER}; + use std::time::Duration; + assert_eq!(super::disk_check_wait(Some(Duration::ZERO), None), Duration::from_millis(250)); + assert_eq!(super::disk_check_wait(Some(Duration::from_secs(60)), None), Duration::from_secs(5)); + assert_eq!(super::disk_check_wait(Some(Duration::MAX), None), Duration::from_secs(5)); + assert_eq!(super::disk_check_wait(None, None), CHECK_EVERY); + // after a read that couldn't start: at the retry, not five minutes on (CodeRabbit on #3077) + assert_eq!(super::disk_check_wait(None, Some(RETRY_AFTER)), RETRY_AFTER); + } + /// The prompt barrier keeps its own keys and pointer input, drops text/wheel input, and drops /// the start/move half of a new touch gesture while keeping End/Cancel to clear egui's private /// touch state. No prompt means everything survives. diff --git a/crates/ui-egui/src/render.rs b/crates/ui-egui/src/render.rs index 9237e43066..e8c3a90788 100644 --- a/crates/ui-egui/src/render.rs +++ b/crates/ui-egui/src/render.rs @@ -45,6 +45,13 @@ pub enum Slot { /// Background preparation of a neighbouring photo (no texture: its decoded source and view /// render are cached by the engine). 0 = next, 1 = previous. Prefetch(u8), + /// The loupe's stand-in for a photo the user is likely to step to next (the camera JPEG of an + /// unedited raw, or a cached render), made ahead in the direction of travel so a step shows it + /// at once: [`Renderer::request_quick`] takes the texture over into [`Slot::Preview`]. + QuickAhead(u8), + /// The loupe zoomed in on an unedited raw: its camera JPEG at full size, drawn under the window + /// render until that arrives (a focus check at 100 % without waiting for the raw). + QuickFull, /// A variant thumbnail (profile / preset browsers), by its job key ([`Session::variant_job`]). /// Kept in a bounded LRU ([`VARIANT_TEXTURES`]). Variant(u64), @@ -242,6 +249,11 @@ pub const MAX_VARIANT_TEXTURES: usize = 800; /// Priority of variant thumbnail jobs: below on-screen grid thumbnails and the loupe. const VARIANT_PRIORITY: u32 = 6; +/// The camera-preview edge a loupe stand-in is made at (0: one that doesn't depend on the size). +fn quick_edge(job: &QuickJob) -> usize { + job.embedded.as_ref().map_or(0, |e| e.2) +} + pub struct Renderer { #[cfg(test)] pub(crate) thumb_jobs_built: usize, @@ -283,6 +295,14 @@ pub struct Renderer { pub completed: u64, /// Finished jobs thrown away because a newer request for their slot had replaced them. pub discarded: u64, + /// Photos given a grid thumbnail since start (a render replacing a stand-in isn't counted again): + /// unlike [`Renderer::thumb_textures`] it never goes down when old thumbnails are evicted (for + /// benchmarks). + pub thumbs_made: u64, + /// The photos [`Self::thumbs_made`] counted, by library (a hash of its folder) and id: a + /// thumbnail made again after eviction, or after going to another library and back, is the + /// same photo (photo ids are a library's own). Never cleared. + thumbs_counted: std::collections::HashSet<(u64, PhotoId)>, /// Keep a CPU copy of every texture so the UI can be rasterized headlessly (set when the app /// is driven by the control channel). pub keep_pixels: bool, @@ -290,6 +310,10 @@ pub struct Renderer { stages: HashMap>, /// Slot → key of the last quick job requested for it (each is tried once). quick_tried: HashMap, + /// The camera-preview edge each loupe stand-in ([`Slot::Preview`], [`Slot::QuickAhead`]) was + /// asked for (0: one that doesn't depend on the size): a stand-in made ahead for a smaller loupe + /// isn't taken over by a larger one. + quick_edge: HashMap, /// Jobs that failed (unreadable or missing file…), by slot and job key, with the error and /// the photo: not requested again until the key changes (an edit, another size) — the grid /// asks every frame. @@ -327,6 +351,9 @@ pub struct Renderer { native_frames: HashMap, } +/// How many [`Slot::QuickAhead`] stand-ins the loupe keeps ready. +pub const AHEAD_SLOTS: u8 = 6; + /// After this long without renders the GPU renderer's pool of recycled buffers is freed. #[cfg(not(target_arch = "wasm32"))] const IDLE_TRIM: std::time::Duration = std::time::Duration::from_secs(3); @@ -395,9 +422,12 @@ impl Renderer { last_main_ms: 0.0, completed: 0, discarded: 0, + thumbs_made: 0, + thumbs_counted: Default::default(), keep_pixels: false, stages: HashMap::new(), quick_tried: HashMap::new(), + quick_edge: HashMap::new(), failed: HashMap::new(), catalog_rev: 0, prefetched: HashMap::new(), @@ -731,7 +761,9 @@ impl Renderer { } } - /// Request a stand-in for `slot` (once per job key). + /// Request a stand-in for `slot` (once per job key). The loupe's [`Slot::Preview`] takes over + /// a stand-in already made ahead for the same photo ([`Slot::QuickAhead`]) instead of making it + /// again: shown in this frame when it is ready, or as soon as that job finishes. pub fn request_quick(&mut self, slot: Slot, mut job: QuickJob, priority: u32) { if self.quick_tried.get(&slot) == Some(&job.key) { if self.pending.get(&slot).is_some_and(|p| p.0 == job.key && p.1 != priority) { @@ -758,6 +790,14 @@ impl Renderer { return; } self.quick_tried.insert(slot, job.key); + if matches!(slot, Slot::Preview | Slot::QuickAhead(_)) { + self.quick_edge.insert(slot, quick_edge(&job)); + } + if slot == Slot::Preview && self.take_ahead(job.photo, job.key, quick_edge(&job)) { + self.pending.remove(&slot); + self.requests.remove(&slot); + return; + } let source = job .small .as_ref() @@ -772,7 +812,84 @@ impl Renderer { ); let key = job.key; let display = self.display.clone(); - self.pool.submit(slot, key, priority, Box::new(move || Self::run_for(|| job.run(), &display))); + let background = matches!(slot, Slot::QuickAhead(_)); + self.pool.submit( + slot, + key, + priority, + Box::new(move || { + let run = || if background { lightcraft_engine::memory::in_background(|| job.run()) } else { job.run() }; + Self::run_for(run, &display) + }), + ); + } + + /// Whether the stand-in asked for in `slot` is at least `edge` pixels (see `quick_edge`). + fn ahead_covers(&self, slot: Slot, edge: usize) -> bool { + self.quick_edge.get(&slot).copied().unwrap_or(0) >= edge + } + + /// Move a [`Slot::QuickAhead`] texture of `photo` made for `key`, at least `edge` pixels, into + /// [`Slot::Preview`]. + fn take_ahead(&mut self, photo: PhotoId, key: u64, edge: usize) -> bool { + let Some(slot) = self + .textures + .iter() + .find(|(s, t)| matches!(s, Slot::QuickAhead(_)) && t.photo == photo && t.key == key && self.ahead_covers(**s, edge)) + .map(|(s, _)| *s) + else { + return false; + }; + let Some(tex) = self.textures.remove(&slot) else { return false }; + self.quick_tried.remove(&slot); + self.textures.insert(Slot::Preview, tex); + true + } + + /// Make the loupe's stand-ins for the photos it is likely to be stepped to next (see + /// [`Slot::QuickAhead`]), most likely first: `jobs[0]` gets `priority`, each next one less. + /// A slot keeps a photo for as long as the photo stays wanted (made or being made, it is not + /// made again when the user steps and the photos shift places); slots holding photos not + /// wanted any more are freed for the new ones, and their queued jobs dropped. + pub fn look_ahead(&mut self, jobs: Vec, priority: u32) { + let slots: Vec = (0..AHEAD_SLOTS).map(Slot::QuickAhead).collect(); + let held = |r: &Self, s: Slot| r.textures.get(&s).map(|t| t.key).or_else(|| r.quick_tried.get(&s).copied()); + // (a stand-in asked for at a smaller loupe size isn't kept for a larger one) + let wanted: HashMap = jobs.iter().map(|j| (j.key, quick_edge(j))).collect(); + let mut free = Vec::new(); + for &s in &slots { + let key = held(self, s); + if key.is_none_or(|k| wanted.get(&k).is_none_or(|&edge| !self.ahead_covers(s, edge))) { + self.textures.remove(&s); + // a job already running: its result is thrown away when it arrives (not left as a + // hidden stand-in), unless the loupe is waiting for just that one (a step to the + // photo): then the slot stays reserved for it until it arrives + let preview_edge = self.quick_edge.get(&Slot::Preview).copied().unwrap_or(0); + let loupe_waits = + key.is_some_and(|k| self.pending.get(&Slot::Preview).is_some_and(|p| p.0 == k)) && self.ahead_covers(s, preview_edge); + if !self.drop_queued(s) && loupe_waits { + continue; + } + self.quick_tried.remove(&s); + self.pending.remove(&s); + self.requests.remove(&s); + free.push(s); + } + } + let have: HashMap = slots.iter().filter_map(|&s| held(self, s).map(|k| (k, s))).collect(); + let mut free = free.into_iter(); + for (rank, job) in jobs.into_iter().enumerate() { + let priority = priority.saturating_sub(rank as u32); + if let Some(&s) = have.get(&job.key) { + // kept: a job still queued moves to its new place in the order + if self.quick_tried.get(&s) == Some(&job.key) { + self.request_quick(s, job, priority); + } + continue; + } + let Some(slot) = free.next() else { break }; + self.request_quick(slot, job, priority); + } } /// Render a slideshow title screen into `slot` (once per screen key, like [`Self::request`]): @@ -817,6 +934,21 @@ impl Renderer { ); } + /// Prepared-ahead jobs ([`Slot::Prefetch`]) queued or running. + pub fn prefetches_pending(&self) -> usize { + self.pending.keys().filter(|s| matches!(s, Slot::Prefetch(_))).count() + } + + /// Prepared-ahead slots asked for since the renderer last forgot everything. + pub fn prefetch_slots_asked(&self) -> usize { + self.prefetched.keys().filter(|s| matches!(s, Slot::Prefetch(_))).count() + } + + /// Whether `slot` was last asked for the job of `key` (queued, running or done). + pub fn prefetch_asked(&self, slot: Slot, key: u64) -> bool { + self.prefetched.get(&slot) == Some(&key) + } + /// Drop the slideshow slides other than `keep`: their textures and their requests that have /// not started (a slide that is no longer near is not worth rendering). pub fn release_slides(&mut self, keep: &[lightcraft_engine::slideshow::Item]) { @@ -869,6 +1001,11 @@ impl Renderer { self.textures.retain(|_, t| t.native.is_none()); } + /// Changes when [`Self::forget_all`] drops every texture and request: what was asked for before is gone. + pub fn epoch(&self) -> u64 { + self.epoch + } + pub fn is_pending(&self, slot: Slot) -> bool { self.pending.contains_key(&slot) } @@ -1132,6 +1269,89 @@ impl Renderer { finished } + /// The slot a finished job goes to. Made ahead for the photo the loupe is now waiting for, it is + /// the loupe's stand-in (the loupe's own request for it, if one was started, is dropped when it + /// arrives); also when the loupe's own request failed and it still wants that photo: the + /// stand-in made ahead still shows, but never over another photo's request. + fn stand_in_slot(&mut self, slot: Slot, r: &RenderResult) -> Slot { + let waiting = self.pending.get(&Slot::Preview).is_some_and(|p| p.0 == r.key); + let failed = !self.pending.contains_key(&Slot::Preview) + && self.quick_tried.get(&Slot::Preview) == Some(&r.key) + && self.failed.get(&Slot::Preview).is_some_and(|f| f.0 == r.key && f.3 == r.photo); + if !matches!(slot, Slot::QuickAhead(_)) + || r.rendered.is_err() + || !(waiting || failed) + || !self.ahead_covers(slot, self.quick_edge.get(&Slot::Preview).copied().unwrap_or(0)) + { + return slot; + } + self.pending.remove(&Slot::Preview); + self.requests.remove(&Slot::Preview); + self.quick_tried.remove(&slot); + Slot::Preview + } + + /// A superseded result an interactive view still takes: a draft newer than what it shows. + fn is_newer_draft(&self, slot: Slot, r: &RenderResult) -> bool { + slot.is_view() + && self.requests.contains_key(&slot) + && r.request_id >= self.epoch + && self.shown_ids.get(&slot).is_none_or(|shown| r.request_id > *shown) + && r.rendered.is_ok() + } + + /// Convert `r` to the display profile in use; whether that changed it. + fn convert_for_display(&self, r: &mut RenderResult) -> bool { + let Some(d) = &self.display else { return false }; + let before = r.display; + lightcraft_engine::display::present(r, d); + r.display != before + } + + /// Show a render that stayed on the GPU (`r.frame`) in `slot`; whether it could be. When it + /// can't, views come back as pixels from then on. + fn show_frame(&mut self, ctx: &egui::Context, slot: Slot, r: &RenderResult, look: Option<(u64, bool)>, ms: f64) -> bool { + let (Some(frame), Ok(rendered)) = (r.frame.as_ref(), r.rendered.as_ref()) else { return false }; + self.failed.remove(&slot); + let shown = self.screen.as_mut().and_then(|s| s.show(frame, self.natives.get(&slot).copied())); + let Some(id) = shown else { + // can't be shown: from now on views come back as pixels + log::warn!("render {slot:?}: a GPU-resident render can't be shown; rendering pixels"); + self.free_natives(); + self.screen = None; + return false; + }; + self.natives.insert(slot, id); + if self.keep_pixels { + self.native_frames.insert(slot, frame.clone()); + } + let (size, histogram) = ([frame.width, frame.height], rendered.histogram.clone()); + match self.textures.get_mut(&slot) { + Some(t) => { + t.show_native(id); + t.look = look; + t.key = r.key; + t.photo = r.photo; + t.size = size; + t.histogram = Some(histogram); + t.ms = ms; + t.quick = None; + } + None => { + // (`tex` is never drawn while `native` is set) + let blank = egui::ColorImage::filled([1, 1], egui::Color32::BLACK); + let tex = ctx.load_texture(format!("{slot:?}"), blank, egui::TextureOptions::LINEAR); + let t = + Tex { look, key: r.key, photo: r.photo, tex, size, histogram: Some(histogram), ms, quick: None, pixels: None, native: Some(id) }; + self.textures.insert(slot, t); + } + } + if slot == Slot::Main { + self.last_main_ms = ms; + } + true + } + /// Turn finished jobs into textures. Returns true if anything changed. fn collect(&mut self, ctx: &egui::Context, session: &mut Session, inline_ms: f64) -> bool { let finished = self.take_finished(inline_ms); @@ -1152,12 +1372,7 @@ impl Renderer { // shows, and the source it decoded: a drag supersedes every request before it // finishes, and a source thrown away with them is decoded again for every tick. let (source, look) = if self.requests.get(&slot).map(|request| request.id) != Some(r.request_id) { - let newer_draft = slot.is_view() - && self.requests.contains_key(&slot) - && r.request_id >= self.epoch - && self.shown_ids.get(&slot).is_none_or(|shown| r.request_id > *shown) - && r.rendered.is_ok(); - if !newer_draft { + if !self.is_newer_draft(slot, &r) { self.discarded += 1; let replaced = self.requests.contains_key(&slot); self.decided(|| { @@ -1180,66 +1395,16 @@ impl Renderer { self.shown_ids.insert(slot, r.request_id); } // (results from an offload, which doesn't know the display profile: converted here) - if let Some(d) = &self.display { - let before = r.display; - lightcraft_engine::display::present(&mut r, d); - if r.display != before { - color = None; // converted after the worker made its texture pixels - } + if self.convert_for_display(&mut r) { + color = None; // converted after the worker made its texture pixels } if self.pending.get(&slot).is_some_and(|p| p.0 == r.key) { self.pending.remove(&slot); } + slot = self.stand_in_slot(slot, &r); // a render that stayed on the GPU: drawn from its texture - if let (Some(frame), Ok(rendered)) = (r.frame.as_ref(), r.rendered.as_ref()) { - self.failed.remove(&slot); - let shown = self.screen.as_mut().and_then(|s| s.show(frame, self.natives.get(&slot).copied())); - let Some(id) = shown else { - // can't be shown: from now on views come back as pixels - log::warn!("render {slot:?}: a GPU-resident render can't be shown; rendering pixels"); - self.free_natives(); - self.screen = None; - continue; - }; - self.natives.insert(slot, id); - if self.keep_pixels { - self.native_frames.insert(slot, frame.clone()); - } - let (size, histogram) = ([frame.width, frame.height], rendered.histogram.clone()); - match self.textures.get_mut(&slot) { - Some(t) => { - t.show_native(id); - t.look = look; - t.key = r.key; - t.photo = r.photo; - t.size = size; - t.histogram = Some(histogram); - t.ms = ms; - t.quick = None; - } - None => { - // (`tex` is never drawn while `native` is set) - let blank = egui::ColorImage::filled([1, 1], egui::Color32::BLACK); - let tex = ctx.load_texture(format!("{slot:?}"), blank, egui::TextureOptions::LINEAR); - let t = Tex { - look, - key: r.key, - photo: r.photo, - tex, - size, - histogram: Some(histogram), - ms, - quick: None, - pixels: None, - native: Some(id), - }; - self.textures.insert(slot, t); - } - } - if slot == Slot::Main { - self.last_main_ms = ms; - } - changed = true; + if r.frame.is_some() && r.rendered.is_ok() { + changed |= self.show_frame(ctx, slot, &r, look, ms); continue; } let rendered = match r.rendered { @@ -1259,7 +1424,7 @@ impl Renderer { x } Err(e) => { - if !matches!(slot, Slot::Prefetch(_)) { + if !matches!(slot, Slot::Prefetch(_) | Slot::QuickAhead(_)) { let message = render_failure_message(slot, r.photo, source.as_ref(), &e); #[cfg(test)] self.failure_messages.push(message.clone()); @@ -1291,6 +1456,11 @@ impl Renderer { slot = Slot::Thumb(id); } } + // (a photo's first thumbnail: not a render replacing its stand-in, nor one made again) + let first_thumb = match slot { + Slot::Thumb(id) | Slot::ThumbQuick(id) => self.thumbs_counted.insert((library_key(session), id)), + _ => false, + }; if let Slot::Thumb(id) = slot { self.textures.remove(&Slot::ThumbQuick(id)); } @@ -1332,7 +1502,11 @@ impl Renderer { ); } } - if slot == Slot::Main { + if first_thumb { + self.thumbs_made += 1; + } + // (a preview taken from the cache says nothing about how long a render takes) + if slot == Slot::Main && r.quick.is_none() { self.last_main_ms = ms; } changed = true; @@ -1413,6 +1587,29 @@ impl Renderer { .collect() } + /// Forget everything about `slot`: its texture, its queued job, and that its stand-in was asked + /// for (so asking again makes it again). + pub fn forget(&mut self, slot: Slot) { + self.drop_queued(slot); + self.pending.remove(&slot); + self.requests.remove(&slot); + self.quick_tried.remove(&slot); + self.release(slot); + } + + /// Drop `slot`'s job if it is still queued (a running one finishes). Returns whether one was. + pub fn drop_queued(&mut self, slot: Slot) -> bool { + let dropped = self.pool.reprioritize(|s, p| if *s == slot { None } else { Some(p) }); + let before = self.queue.len(); + self.queue.retain(|q| q.slot != slot); + let any = !dropped.is_empty() || self.queue.len() != before; + if any { + self.pending.remove(&slot); + self.requests.remove(&slot); + } + any + } + /// Drop the import review thumbnails (a new review, or the dialog closed). pub fn forget_imports(&mut self) { self.retain_imports(&Default::default()); @@ -1773,3 +1970,13 @@ mod color_image_tests { assert!(color_image(&img).pixels.is_empty()); } } + +/// Which library `session` has open, for [`Renderer::thumbs_made`]: a hash of its folder (the same +/// library opened again is the same), 0 with none. +fn library_key(session: &Session) -> u64 { + use std::hash::{Hash, Hasher}; + let Some(lib) = session.library.as_ref() else { return 0 }; + let mut h = std::collections::hash_map::DefaultHasher::new(); + lib.dir.hash(&mut h); + h.finish() +} diff --git a/crates/ui-egui/src/render/thumbnail_tests.rs b/crates/ui-egui/src/render/thumbnail_tests.rs index 7a2cb1a6a9..b2a87e6522 100644 --- a/crates/ui-egui/src/render/thumbnail_tests.rs +++ b/crates/ui-egui/src/render/thumbnail_tests.rs @@ -1541,3 +1541,407 @@ fn undo_to_embedded_thumb_rejects_late_full_render() { assert_eq!(quick.pixels.as_ref().unwrap().pixels, pixels_a); assert!(!app.renderer.is_pending(full_slot)); } + +/// PERF-CULL-2: the loupe's stand-ins made ahead are taken over at the step (no job, the texture +/// at once), a photo still wanted keeps its slot as the photos shift, and a step to a photo whose +/// stand-in is still being made shows it when it arrives. +#[test] +fn a_step_takes_over_the_camera_preview_made_ahead() { + let gate = Arc::new(std::sync::Mutex::new(())); + let mut s = Session::new(); + let g = gate.clone(); + s.media.preview_loader = Some(Arc::new(move |_: &str, _| { + drop(g.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); + Some(lightcraft_raster::Rgba8 { width: 4, height: 4, data: vec![[200, 100, 50, 255]; 16] }) + })); + let raw = |id: u64| { + let mut p = Photo::new(PhotoId(id), Source::File { path: format!("r{id}.cr3") }, &format!("r{id}.cr3"), "CR3", 6000, 4000, "2026-01-01"); + p.kind = lightcraft_catalog::MediaKind::Raw; + p.develop = Arc::new(p.camera_defaults()); + p + }; + let (mut app, _, ctx) = fixture_with(s, raw(1)); + for id in 2..=4 { + app.session.catalog.apply(Op::AddPhoto { photo: Box::new(raw(id)) }).unwrap(); + } + let job = |app: &mut crate::LightcraftApp, id: u64| app.session.quick_view_job(PhotoId(id), 64, true).unwrap(); + let wait = |app: &mut crate::LightcraftApp, done: &dyn Fn(&Renderer) -> bool| { + let t0 = std::time::Instant::now(); + while !done(&app.renderer) { + assert!(t0.elapsed() < std::time::Duration::from_secs(20), "the stand-ins never arrived"); + std::thread::sleep(std::time::Duration::from_millis(5)); + app.renderer.poll(&ctx, &mut app.session); + } + }; + let ahead_of = |r: &Renderer, id: u64| r.textures.iter().any(|(s, t)| matches!(s, Slot::QuickAhead(_)) && t.photo == PhotoId(id)); + let jobs = vec![job(&mut app, 2), job(&mut app, 3)]; + app.renderer.look_ahead(jobs, 96); + wait(&mut app, &|r| ahead_of(r, 2) && ahead_of(r, 3)); + // the step to photo 2: its stand-in is the loupe's at once, nothing is made again + let q = job(&mut app, 2); + app.renderer.request_quick(Slot::Preview, q, 110); + assert!(!app.renderer.is_pending(Slot::Preview)); + assert_eq!(app.renderer.textures.get(&Slot::Preview).map(|t| t.photo), Some(PhotoId(2))); + assert!(!ahead_of(&app.renderer, 2)); + // the next look-ahead (3 and 4): 3 keeps its slot and is not made again + let held = gate.lock().unwrap(); + let jobs = vec![job(&mut app, 3), job(&mut app, 4)]; + app.renderer.look_ahead(jobs, 96); + assert!(ahead_of(&app.renderer, 3), "a photo still wanted keeps what was made for it"); + let pending_ahead: Vec = app.renderer.pending.keys().copied().filter(|s| matches!(s, Slot::QuickAhead(_))).collect(); + assert_eq!(pending_ahead.len(), 1, "only photo 4 is being made: {pending_ahead:?}"); + // the step to photo 4 while its stand-in is still being made: shown when it arrives + let q = job(&mut app, 4); + app.renderer.request_quick(Slot::Preview, q, 110); + drop(held); + wait(&mut app, &|r| r.textures.get(&Slot::Preview).is_some_and(|t| t.photo == PhotoId(4)) && !r.is_pending(Slot::Preview)); + wait(&mut app, &|r| !r.pending.keys().any(|s| matches!(s, Slot::QuickAhead(_) | Slot::Preview))); + assert_eq!(app.renderer.textures.get(&Slot::Preview).map(|t| t.photo), Some(PhotoId(4))); +} + +/// A loupe with unedited raws 1..=n whose camera previews are read at once, on a renderer +/// that runs nothing until asked (`run_inline`). +fn raw_loupe(n: u64) -> (crate::LightcraftApp, egui::Context) { + let mut s = Session::new(); + s.media.preview_loader = Some(Arc::new(|_: &str, _| Some(lightcraft_raster::Rgba8 { width: 4, height: 4, data: vec![[200, 100, 50, 255]; 16] }))); + let raw = |id: u64| { + let mut p = Photo::new(PhotoId(id), Source::File { path: format!("r{id}.cr3") }, &format!("r{id}.cr3"), "CR3", 6000, 4000, "2026-01-01"); + p.kind = lightcraft_catalog::MediaKind::Raw; + p.develop = Arc::new(p.camera_defaults()); + p + }; + let (mut app, _, ctx) = fixture_with(s, raw(1)); + for id in 2..=n { + app.session.catalog.apply(Op::AddPhoto { photo: Box::new(raw(id)) }).unwrap(); + } + app.renderer.pool = JobPool::new(0); + (app, ctx) +} + +/// The look-ahead with every photo allowed (the default preparation settings). +const ALL: crate::panels::detail::Prepare = crate::panels::detail::Prepare::Photos(lightcraft_engine::prep::Scope::All); + +fn quick(app: &mut crate::LightcraftApp, id: u64, edge: usize) -> QuickJob { + app.session.quick_view_job(PhotoId(id), edge, true).unwrap() +} + +/// The loupe's stand-ins ahead follow Settings ▸ Performance: none when the mode prepares only the photo on +/// screen (or none ahead), and the ones still queued are dropped then; only marked photos in the marked scope +/// (CodeRabbit on #3077). +#[test] +fn the_look_ahead_prepares_only_what_the_preparation_settings_allow() { + use crate::panels::detail::{Prepare, look_ahead}; + use lightcraft_engine::prep::Scope; + let (mut app, _ctx) = raw_loupe(4); + app.session.sort.key = lightcraft_catalog::SortKey::FileName; + app.session.sort.ascending = true; + // (asked for: queued, running or made) + let ahead = |r: &Renderer| r.quick_tried.keys().filter(|s| matches!(s, Slot::QuickAhead(_))).count(); + look_ahead(&mut app, PhotoId(1), 64, true, Prepare::of(5, Scope::All)); + assert_eq!(ahead(&app.renderer), 3, "photos 2 to 4 are made ahead"); + // the photo on screen only: nothing ahead, and what was queued goes + look_ahead(&mut app, PhotoId(1), 64, true, Prepare::of(0, Scope::OnScreen)); + assert_eq!(ahead(&app.renderer), 0, "nothing is made ahead for the photo on screen only"); + look_ahead(&mut app, PhotoId(1), 64, true, Prepare::of(0, Scope::All)); + assert_eq!(ahead(&app.renderer), 0, "nor with no photos ahead"); + // picks, rated and labelled: only those + app.session.execute("library.select", &serde_json::json!({"ids": [3]})).unwrap(); + app.session.execute("photo.rate", &serde_json::json!({"rating": 2})).unwrap(); + look_ahead(&mut app, PhotoId(1), 64, true, Prepare::of(5, Scope::Marked)); + let k3 = quick(&mut app, 3, 64).key; + let queued: Vec = app.renderer.quick_tried.iter().filter(|(s, _)| matches!(s, Slot::QuickAhead(_))).map(|(_, k)| *k).collect(); + assert_eq!(queued, vec![k3], "only the rated photo is made ahead"); +} + +/// A renderer reset (`forget_all`: a library switch, a colour-management change) drops the stand-ins asked +/// for ahead; the same photo asks for them again (CodeRabbit on #3577: the look-ahead took them for made). +#[test] +fn the_look_ahead_asks_again_after_a_renderer_reset() { + use crate::panels::detail::look_ahead; + let (mut app, _ctx) = raw_loupe(4); + let ahead = |r: &Renderer| r.quick_tried.keys().filter(|s| matches!(s, Slot::QuickAhead(_))).count(); + look_ahead(&mut app, PhotoId(1), 64, true, ALL); + let asked = ahead(&app.renderer); + assert!(asked > 0); + app.renderer.forget_all(); + assert_eq!(ahead(&app.renderer), 0); + look_ahead(&mut app, PhotoId(1), 64, true, ALL); + assert_eq!(ahead(&app.renderer), asked, "asked for again"); +} + +/// A stand-in still queued ahead whose photo moves up in the order (the user stepped) is +/// queued at its new place, not left behind photos now further away (CodeRabbit on #3055). +#[test] +fn a_kept_ahead_job_moves_to_its_new_place_in_the_order() { + let (mut app, _ctx) = raw_loupe(3); + let jobs = vec![quick(&mut app, 2, 64), quick(&mut app, 3, 64)]; + let (k2, k3) = (jobs[0].key, jobs[1].key); + app.renderer.look_ahead(jobs, 96); + let priority_of = |r: &Renderer, key: u64| { + let slot = r.quick_tried.iter().find(|(s, k)| matches!(s, Slot::QuickAhead(_)) && **k == key).map(|(s, _)| *s).unwrap(); + r.pending[&slot].1 + }; + assert_eq!((priority_of(&app.renderer, k2), priority_of(&app.renderer, k3)), (96, 95)); + let jobs = vec![quick(&mut app, 3, 64), quick(&mut app, 2, 64)]; + app.renderer.look_ahead(jobs, 96); + assert_eq!((priority_of(&app.renderer, k3), priority_of(&app.renderer, k2)), (96, 95)); + assert_eq!(app.renderer.pool.queued(), 2, "nothing is queued twice"); +} + +/// A stand-in made ahead that is no longer wanted while it is being made is thrown away when it +/// arrives, not kept as a hidden texture (CodeRabbit on #3077); one the loupe waits for is kept. +#[test] +fn an_ahead_stand_in_no_longer_wanted_is_dropped_when_it_arrives() { + let gate = Arc::new(std::sync::Mutex::new(())); + let mut s = Session::new(); + let g = gate.clone(); + s.media.preview_loader = Some(Arc::new(move |_: &str, _| { + drop(g.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); + Some(lightcraft_raster::Rgba8 { width: 4, height: 4, data: vec![[200, 100, 50, 255]; 16] }) + })); + let raw = |id: u64| { + let mut p = Photo::new(PhotoId(id), Source::File { path: format!("r{id}.cr3") }, &format!("r{id}.cr3"), "CR3", 6000, 4000, "2026-01-01"); + p.kind = lightcraft_catalog::MediaKind::Raw; + p.develop = Arc::new(p.camera_defaults()); + p + }; + let (mut app, _, ctx) = fixture_with(s, raw(1)); + app.session.catalog.apply(Op::AddPhoto { photo: Box::new(raw(2)) }).unwrap(); + let wait = |app: &mut crate::LightcraftApp, done: &dyn Fn(&Renderer) -> bool, what: &str| { + let t0 = std::time::Instant::now(); + while !done(&app.renderer) { + assert!(t0.elapsed() < std::time::Duration::from_secs(20), "{what}"); + std::thread::sleep(std::time::Duration::from_millis(5)); + app.renderer.poll(&ctx, &mut app.session); + } + }; + let any_ahead = |r: &Renderer| r.textures.keys().any(|s| matches!(s, Slot::QuickAhead(_))); + let held = gate.lock().unwrap(); + let job = quick(&mut app, 2, 64); + app.renderer.look_ahead(vec![job], 96); + wait(&mut app, &|r| r.pool.queued() == 0, "the stand-in never started"); + // not wanted any more (the user went elsewhere) while it is being made + app.renderer.look_ahead(Vec::new(), 96); + assert!(!app.renderer.pending.keys().any(|s| matches!(s, Slot::QuickAhead(_)))); + let done = app.renderer.completed; + drop(held); + wait(&mut app, &|r| r.completed > done, "the stand-in never finished"); + assert!(!any_ahead(&app.renderer), "a stand-in nobody wants is left as a hidden texture"); + // the step to photo 2 while its stand-in is being made: the loupe takes it when it arrives + let held = gate.lock().unwrap(); + let job = quick(&mut app, 2, 32); + app.renderer.look_ahead(vec![job], 96); + wait(&mut app, &|r| r.pool.queued() == 0, "the stand-in never started"); + let job = quick(&mut app, 2, 32); + app.renderer.request_quick(Slot::Preview, job, 110); + app.renderer.look_ahead(Vec::new(), 96); + drop(held); + wait(&mut app, &|r| r.textures.get(&Slot::Preview).is_some_and(|t| t.photo == PhotoId(2)), "the loupe never got its stand-in"); +} + +/// The loupe waits for a stand-in made ahead that is still being made when the next look-ahead +/// brings new photos: its slot stays reserved, so the result still reaches the loupe (CodeRabbit +/// on #3055 and #3080). +#[test] +fn a_running_stand_in_the_loupe_waits_for_keeps_its_slot() { + // the first camera preview read (photo 2's, made ahead) waits for `first`, every later one + // for `later` + let first = Arc::new(std::sync::Mutex::new(())); + let later = Arc::new(std::sync::Mutex::new(())); + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let mut s = Session::new(); + let (f, l, c) = (first.clone(), later.clone(), calls.clone()); + s.media.preview_loader = Some(Arc::new(move |_: &str, _| { + let gate = if c.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 { &f } else { &l }; + drop(gate.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); + Some(lightcraft_raster::Rgba8 { width: 4, height: 4, data: vec![[200, 100, 50, 255]; 16] }) + })); + let raw = |id: u64| { + let mut p = Photo::new(PhotoId(id), Source::File { path: format!("r{id}.cr3") }, &format!("r{id}.cr3"), "CR3", 6000, 4000, "2026-01-01"); + p.kind = lightcraft_catalog::MediaKind::Raw; + p.develop = Arc::new(p.camera_defaults()); + p + }; + let (mut app, _, ctx) = fixture_with(s, raw(1)); + for id in 2..=3 { + app.session.catalog.apply(Op::AddPhoto { photo: Box::new(raw(id)) }).unwrap(); + } + app.renderer.pool = JobPool::new(4); + let wait = |app: &mut crate::LightcraftApp, done: &dyn Fn(&Renderer) -> bool, what: &str| { + let t0 = std::time::Instant::now(); + while !done(&app.renderer) { + assert!(t0.elapsed() < std::time::Duration::from_secs(20), "{what}"); + std::thread::sleep(std::time::Duration::from_millis(5)); + app.renderer.poll(&ctx, &mut app.session); + } + }; + let held_first = first.lock().unwrap(); + let held_later = later.lock().unwrap(); + let job = quick(&mut app, 2, 64); + app.renderer.look_ahead(vec![job], 96); + wait(&mut app, &|r| r.pool.queued() == 0, "photo 2's stand-in never started"); + wait(&mut app, &|_| calls.load(std::sync::atomic::Ordering::SeqCst) == 1, "photo 2's preview was never read"); + // the step to photo 2, then the next look-ahead, for photos 3 and 1 + let job = quick(&mut app, 2, 64); + app.renderer.request_quick(Slot::Preview, job, 110); + assert!(app.renderer.is_pending(Slot::Preview)); + let jobs = vec![quick(&mut app, 3, 64), quick(&mut app, 1, 64)]; + app.renderer.look_ahead(jobs, 96); + let done = app.renderer.completed; + drop(held_first); + wait(&mut app, &|r| r.completed > done, "photo 2's stand-in never finished"); + assert_eq!(app.renderer.textures.get(&Slot::Preview).map(|t| t.photo), Some(PhotoId(2)), "the loupe lost the stand-in it waited for"); + drop(held_later); + wait(&mut app, &|r| r.pool.queued() == 0 && !r.pending.keys().any(|s| matches!(s, Slot::QuickAhead(_))), "the look-ahead never finished"); +} + +/// The stand-in made ahead still shows when the loupe's own request for it failed first +/// (CodeRabbit on #3055). +#[test] +fn a_stand_in_made_ahead_shows_after_the_loupes_own_request_failed() { + let (mut app, ctx) = raw_loupe(2); + let job = quick(&mut app, 2, 64); + let key = job.key; + app.renderer.look_ahead(vec![job], 96); + let job = quick(&mut app, 2, 64); + app.renderer.request_quick(Slot::Preview, job, 110); + assert!(app.renderer.is_pending(Slot::Preview)); + // the loupe's request fails (its job never runs) + assert!(app.renderer.drop_queued(Slot::Preview)); + app.renderer.failed.insert(Slot::Preview, (key, "unreadable".into(), 0, PhotoId(2))); + assert_eq!(app.renderer.pool.run_inline(1), 1); + app.renderer.poll(&ctx, &mut app.session); + assert_eq!(app.renderer.textures.get(&Slot::Preview).map(|t| t.photo), Some(PhotoId(2))); + assert!(!app.renderer.failed.contains_key(&Slot::Preview)); + // the user has stepped on to photo 3 when photo 2's stand-in arrives: 3's request stays + let (mut app, ctx) = raw_loupe(3); + let job = quick(&mut app, 2, 64); + let key = job.key; + app.renderer.look_ahead(vec![job], 96); + let job = quick(&mut app, 2, 64); + app.renderer.request_quick(Slot::Preview, job, 110); + assert!(app.renderer.drop_queued(Slot::Preview)); + app.renderer.failed.insert(Slot::Preview, (key, "unreadable".into(), 0, PhotoId(2))); + let job = quick(&mut app, 3, 64); + let key3 = job.key; + // (queued behind the stand-in made ahead, so that one arrives first) + app.renderer.request_quick(Slot::Preview, job, 50); + let ahead = app.renderer.pool.run_inline(1); + assert_eq!(ahead, 1); + app.renderer.poll(&ctx, &mut app.session); + assert!(app.renderer.textures.get(&Slot::Preview).is_none_or(|t| t.photo != PhotoId(2)), "photo 2 took photo 3's place"); + assert_eq!(app.renderer.pending.get(&Slot::Preview).map(|p| p.0), Some(key3), "photo 3's request is kept"); +} + +/// A stand-in made ahead for a smaller loupe isn't taken over when the loupe has grown: the +/// larger one is made (CodeRabbit on #3077). +#[test] +fn a_stand_in_made_ahead_for_a_smaller_loupe_is_not_taken_over() { + let (mut app, ctx) = raw_loupe(2); + let small = quick(&mut app, 2, 32); + let large = quick(&mut app, 2, 64); + assert_eq!(small.key, large.key, "the same stand-in, at another size"); + app.renderer.look_ahead(vec![small], 96); + assert_eq!(app.renderer.pool.run_inline(1), 1); + app.renderer.poll(&ctx, &mut app.session); + assert!(app.renderer.textures.keys().any(|s| matches!(s, Slot::QuickAhead(_)))); + app.renderer.request_quick(Slot::Preview, large, 110); + assert!(app.renderer.is_pending(Slot::Preview), "the larger stand-in is made"); + assert!(!app.renderer.textures.contains_key(&Slot::Preview)); + // the same size is taken over at once + let (mut app, ctx) = raw_loupe(2); + let job = quick(&mut app, 2, 64); + app.renderer.look_ahead(vec![job], 96); + assert_eq!(app.renderer.pool.run_inline(1), 1); + app.renderer.poll(&ctx, &mut app.session); + let job = quick(&mut app, 2, 64); + app.renderer.request_quick(Slot::Preview, job, 110); + assert!(!app.renderer.is_pending(Slot::Preview)); + assert_eq!(app.renderer.textures.get(&Slot::Preview).map(|t| t.photo), Some(PhotoId(2))); +} + +/// The benchmark's thumbnail count is per photo: a render replacing a photo's stand-in isn't +/// counted again (CodeRabbit on #3055). +#[test] +fn a_thumbnail_replacing_its_stand_in_is_not_counted_again() { + let mut s = Session::new(); + s.media.preview_loader = Some(Arc::new(|_, _| Some(lightcraft_raster::Rgba8 { width: 4, height: 4, data: vec![[200, 100, 50, 255]; 16] }))); + let mut raw = (*photo()).clone(); + raw.kind = lightcraft_catalog::MediaKind::Raw; + raw.develop = Arc::new(raw.camera_defaults()); + let (mut app, work, ctx) = fixture_with(s, raw); + app.renderer.pool = JobPool::new(0); + let id = PhotoId(1); + crate::panels::grid::request_thumb(&mut app, id, 384, 10); + assert_eq!(app.renderer.pool.run_inline(1), 1); + app.renderer.poll(&ctx, &mut app.session); + assert!(app.renderer.textures.contains_key(&Slot::ThumbQuick(id))); + assert_eq!(app.renderer.thumbs_made, 1); + let mut edited = (*app.session.catalog.photo(id).unwrap().develop).clone(); + edited.light.exposure += 0.5; + app.session.commit("Exposure", Op::SetDevelop { id, settings: Arc::new(edited), label: "Exposure".into(), edited: None }).unwrap(); + crate::panels::grid::request_thumb(&mut app, id, 384, 10); + let (slot, job) = take_job(&work); + assert_eq!(slot, Slot::Thumb(id)); + finish(&mut app, &work, &ctx, slot, job.run()); + assert!(app.renderer.textures.contains_key(&Slot::Thumb(id)), "the render replaced the stand-in"); + assert_eq!(app.renderer.thumbs_made, 1, "still one photo"); + // evicted and made again (scrolled away and back): the same photo (CodeRabbit on #3055) + app.renderer.evict_thumbs(&Default::default(), 0); + assert!(!app.renderer.textures.contains_key(&Slot::Thumb(id)), "evicted"); + crate::panels::grid::request_thumb(&mut app, id, 384, 10); + let (slot, job) = take_job(&work); + finish(&mut app, &work, &ctx, slot, job.run()); + assert!(app.renderer.textures.contains_key(&slot), "made again"); + assert_eq!(app.renderer.thumbs_made, 1, "an evicted photo made again is not counted again"); +} + +/// The loupe's look-ahead asks again when only the crop changes (its stand-ins' keys include the +/// crop), instead of keeping stand-ins the loupe can no longer use (CodeRabbit on #3077). +#[test] +fn the_look_ahead_asks_again_when_only_the_crop_changes() { + let (mut app, _ctx) = raw_loupe(3); + let ahead_keys = |r: &Renderer| r.quick_tried.iter().filter(|(s, _)| matches!(s, Slot::QuickAhead(_))).map(|(_, k)| *k).collect::>(); + crate::panels::detail::look_ahead(&mut app, PhotoId(1), 64, true, ALL); + let cropped = app.session.quick_view_job(PhotoId(2), 64, true).unwrap().key; + assert!(ahead_keys(&app.renderer).contains(&cropped)); + crate::panels::detail::look_ahead(&mut app, PhotoId(1), 64, false, ALL); + let uncropped = app.session.quick_view_job(PhotoId(2), 64, false).unwrap().key; + assert_ne!(cropped, uncropped); + assert!(ahead_keys(&app.renderer).contains(&uncropped), "the stand-ins are made again without the crop"); +} + +/// The loupe's look-ahead asks again when the view's order changes around the same photo (a new +/// sort, filter or source changes its neighbours without an edit; CodeRabbit on #3055). +#[test] +fn the_look_ahead_follows_a_new_order_around_the_same_photo() { + let (mut app, _ctx) = raw_loupe(5); + let ahead_keys = |r: &Renderer| r.quick_tried.iter().filter(|(s, _)| matches!(s, Slot::QuickAhead(_))).map(|(_, k)| *k).collect::>(); + app.session.sort.key = lightcraft_catalog::SortKey::FileName; + app.session.sort.ascending = true; + crate::panels::detail::look_ahead(&mut app, PhotoId(3), 64, true, ALL); + let one = quick(&mut app, 1, 64).key; + assert!(!ahead_keys(&app.renderer).contains(&one), "r1 is two behind: not prepared"); + // reversed: r1 is two ahead now + app.session.sort.ascending = false; + crate::panels::detail::look_ahead(&mut app, PhotoId(3), 64, true, ALL); + assert!(ahead_keys(&app.renderer).contains(&one), "the new neighbours are prepared"); +} + +/// Stepping fast (an arrow held down), the raw renders still queued for the photo left behind are +/// dropped, the Before view's too (CodeRabbit on #3055); the whole-frame render on screen stays. +#[test] +fn stepping_fast_drops_the_queued_before_render() { + let (mut app, _work, ctx) = fixture(); + app.renderer.set_offload(Box::new(Blocked)); + for slot in [Slot::Main, Slot::Before, Slot::Region, Slot::RegionBefore] { + let job = app.session.render_job(PhotoId(1), 64, 64, false, true).unwrap(); + app.renderer.request(slot, job, 100); + } + app.renderer.poll(&ctx, &mut app.session); + assert!(app.renderer.is_pending(Slot::Before), "queued behind the blocked worker"); + crate::panels::detail::drop_unsettled(&mut app.renderer, PhotoId(2)); + for slot in [Slot::Main, Slot::Before, Slot::Region, Slot::RegionBefore] { + assert!(!app.renderer.is_pending(slot), "{slot:?} still queued"); + } +} diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index cc08022484..695a9d7d6d 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -70,7 +70,8 @@ pub struct Services { /// Open dialog for a monitor ICC profile (`.icc` / `.icm`; Settings ▸ Display; desktop only). pub pick_display_profile: Option, /// The profile of the screen showing the window, used while none is chosen in Settings ▸ - /// Display (macOS, whose windows aren't colour-managed: issue #787). + /// Display: macOS's screen profile (its windows aren't colour-managed: issue #787), colord's on + /// Linux, and on Windows the monitor's (none while Windows colour-manages the desktop itself). pub screen_profile: Option, /// Save dialog for an exported `.lcpreset` file. pub save_preset_file: Option, diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 6f4b42723f..6d25426298 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -8,9 +8,9 @@ mod view; pub use dialog::{Dialog, NameEdit, SyncCounts, default_preset_groups}; pub use settings::{ - AppSettings, AppearanceMode, DarkTheme, EditFile, EditFormat, EditSpace, GridBadges, KeywordChips, LOUPE_EDGE_CEILING, LOUPE_EDGE_STEP, - LaunchLibrary, LightTheme, LightroomImport, MIN_TEXTURE_SIDE, PHOTOCRAFT, PREVIEW_LIMITS, RECENT_LIBRARIES, STANDARD_PREVIEW_EDGE, StartupView, - WINDOW_FRAME_CEILING, + AppSettings, AppearanceMode, DarkTheme, EditFile, EditFormat, EditSpace, GridBadges, HOT_PIXEL_LIMIT_DEFAULT, HOT_PIXEL_LIMITS, KeywordChips, + LOUPE_EDGE_CEILING, LOUPE_EDGE_STEP, LaunchLibrary, LightTheme, LightroomImport, MIN_TEXTURE_SIDE, PHOTOCRAFT, PREVIEW_LIMITS, RECENT_LIBRARIES, + STANDARD_PREVIEW_EDGE, StartupView, WINDOW_FRAME_CEILING, }; pub use view::{ BRIEF_INFO_SECS, BeforeAfter, BriefInfo, CLICK_ZOOMS, CropOverlay, FOCUS_KEYWORDS_PASSES, InfoOverlay, KeywordingView, LEFT_WIDTH, LayoutImage, diff --git a/crates/ui-egui/src/state/settings.rs b/crates/ui-egui/src/state/settings.rs index b858b9a55f..62b50557cc 100644 --- a/crates/ui-egui/src/state/settings.rs +++ b/crates/ui-egui/src/state/settings.rs @@ -153,6 +153,9 @@ pub struct AppSettings { pub photocraft_file: EditFile, /// Memory the caches may hold together, in MB (0 = automatic; `app.memoryBudget`). pub memory_mb: u32, + /// Remove Hot Pixels leaves a raw alone when more than this share of its photosites, in percent, would be + /// replaced (`app.hotPixelLimit`). + pub hot_pixel_limit: f32, /// The Info panel's metadata fields with several photos selected: true (the default) shows the /// values the selected photos share and marks each field where they differ (Selected Photos), /// false shows the active photo's values (Target Photo) (`view.infoSelectedPhotos`). @@ -166,6 +169,11 @@ pub struct AppSettings { /// View ▸ View Options ▸ Show message when loading or rendering photos: the loupe says /// "Rendering…" while the photo it shows is not the finished render. pub loupe_messages: bool, + /// Settings ▸ Performance ▸ Prepare photos in the background, app-wide (a library may keep its + /// own in its `prefs.json`): handed to the session at launch and kept in step with it. Read + /// leniently: a value this build doesn't know is the defaults, never the other settings lost. + #[serde(deserialize_with = "lenient")] + pub background_prep: lightcraft_engine::prep::PrepSettings, /// Shortcuts the user changed (Help ▸ Keyboard Shortcuts): command id → shortcut, `""` = none. pub keymap: crate::shortcuts::Keymap, /// Auto (follow the system), Dark or Light. @@ -233,11 +241,13 @@ impl Default for AppSettings { photocraft_path: String::new(), photocraft_file: EditFile { format: EditFormat::Psd, ..EditFile::default() }, memory_mb: 0, + hot_pixel_limit: HOT_PIXEL_LIMIT_DEFAULT, info_selected_photos: true, film_names: true, film_badges: true, grid_badges: GridBadges::Auto, loupe_messages: true, + background_prep: Default::default(), keymap: Default::default(), appearance_mode: AppearanceMode::Dark, dark_theme: DarkTheme::Charcoal, @@ -315,6 +325,10 @@ impl EditFile { /// Preview size limits offered in Settings → Performance (0 = Automatic). pub const PREVIEW_LIMITS: [u32; 5] = [0, 1600, 2560, 3840, 5120]; +/// Hot pixel limits offered in Settings → Performance (percent of a raw's photosites), and the default. +pub const HOT_PIXEL_LIMITS: [f32; 5] = [0.05, 0.1, 0.2, 0.5, 1.0]; +pub const HOT_PIXEL_LIMIT_DEFAULT: f32 = 0.2; + /// The most the loupe ever renders in one go (memory and GPU texture size), whatever the setting. pub const LOUPE_EDGE_CEILING: u32 = 8192; @@ -430,6 +444,16 @@ fn deserialize_favorite_themes<'de, D: serde::Deserializer<'de>>(d: D) -> Result mod loupe_info_tests { use super::*; + /// A background preparation value this build doesn't know (a newer build's scope) reads as the + /// defaults and keeps the rest of the settings. + #[test] + fn an_unknown_background_preparation_value_costs_nothing_else() { + let v = serde_json::json!({"filmNames": false, "backgroundPrep": {"culling": {"scope": "someday"}}}); + let read: AppSettings = serde_json::from_value(v).unwrap(); + assert_eq!(read.background_prep, lightcraft_engine::prep::PrepSettings::default()); + assert!(!read.film_names); + } + /// The lines chosen in View Options are saved with the app's settings; a settings file from /// before they existed, or with a line this build doesn't know, gets the default lines and /// keeps the rest of its settings. diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 4401d5d179..08094f8410 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -24,6 +24,7 @@ mod dialog_settings; mod dialog_settings_text; mod dialog_tab; mod dialogs; +mod disk_space; mod docking_acceptance; mod drop_import; mod edit_layout; @@ -62,7 +63,6 @@ mod masking_layout; mod menubar; mod merge_preview; mod missing_sweep; -mod model_setup; mod move_folder; mod offline; mod open_lightroom; @@ -80,6 +80,7 @@ mod recheck; mod rename_person; mod rules_editor; mod sam_setup; +mod scan_probes; mod scroll; mod slider_reset; mod slideshow; diff --git a/crates/ui-egui/src/tests/disk_space.rs b/crates/ui-egui/src/tests/disk_space.rs new file mode 100644 index 0000000000..c2434afedf --- /dev/null +++ b/crates/ui-egui/src/tests/disk_space.rs @@ -0,0 +1,151 @@ +//! The low-disk notice: once per session, when the drive holding the preview cache runs low, with a +//! button to Settings ▸ Performance (where the cache's size limit is). + +use std::time::Duration; + +use lightcraft_engine::disk_space::DiskSpace; +use serde_json::json; + +use crate::headless::Headless; +use crate::state::Dialog; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const GB: u64 = 1 << 30; + +fn has(h: &Headless, id: &str) -> bool { + h.app.widgets.iter().any(|(w, _)| w == id) +} + +#[test] +fn a_low_drive_is_told_once_with_a_way_to_the_performance_settings() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()); + app.disk_space_notice = true; + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + h.step(); + assert!(h.app.notices.is_empty(), "no notice before the drive is low"); + // 12 GB free of a 500 GB drive: under 20 GB and under 10 % + assert!(h.app.session.note_disk_space(DiskSpace { available: 12 * GB, total: 500 * GB })); + h.step(); + h.step(); + assert_eq!(h.app.notices.len(), 1, "{:?}", h.app.notices); + let text = h.app.notices[0].clone(); + assert!(text.contains("12.0 GB free of 500 GB") && text.contains("Settings → Performance"), "{text}"); + let inspect = h.request("ui.inspect", json!({}), T); + assert_eq!(inspect["result"]["notices"][0], text.as_str(), "{inspect}"); + assert!(has(&h, "button:noticeSettings") && has(&h, "button:noticeOk"), "the notice offers the settings"); + let r = h.request("ui.clickWidget", json!({"id": "button:noticeSettings"}), T); + assert_eq!(r["ok"], true, "{r}"); + assert!(h.app.notices.is_empty(), "the button dismisses the notice"); + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "performance".into() }), "and opens Settings ▸ Performance"); + // lower still, later in the same session: not again + assert!(!h.app.session.note_disk_space(DiskSpace { available: 2 * GB, total: 500 * GB })); + h.step(); + h.step(); + assert!(h.app.notices.is_empty(), "once per session"); +} + +#[test] +fn without_the_desktop_flag_no_notice_is_shown() { + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()), [1300.0, 900.0], 1.0); + assert!(h.app.session.note_disk_space(DiskSpace { available: GB, total: 500 * GB })); + h.step(); + assert!(h.app.notices.is_empty(), "headless sessions and tests don't show it"); +} + +/// A notice still queued when another library opens belongs to the library before: it goes, and +/// the new library's drive is judged on its own. +#[test] +fn a_queued_notice_goes_when_another_library_opens() { + let dir = std::env::temp_dir().join(format!("lc-disk-notice-switch-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo().with_fs(), Services::default()); + app.disk_space_notice = true; + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + h.step(); + assert!(h.app.session.note_disk_space(DiskSpace { available: GB, total: 500 * GB })); + h.step(); + assert_eq!(h.app.notices.len(), 1, "{:?}", h.app.notices); + // another library opens before the notice was answered + h.app.session.open_library(&dir, false).unwrap(); + h.step(); + h.step(); + assert!(h.app.notices.iter().all(|n| !n.contains("1.0 GB free of 500 GB")), "the previous library's notice is gone: {:?}", h.app.notices); + let _ = h.app.session.close_library(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The drive is read again every few minutes whatever is filling the cache, not only while +/// previews are built (CodeRabbit on #3080): thumbnails and the loupe's previews alone can take a +/// drive under the line after the library opened. +#[test] +fn a_drive_that_runs_low_without_a_preview_build_is_told() { + use std::sync::atomic::{AtomicBool, Ordering}; + let dir = std::env::temp_dir().join(format!("lc-disk-notice-later-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let low = std::sync::Arc::new(AtomicBool::new(false)); + let mut session = lightcraft_engine::Session::with_demo().with_fs(); + let l = low.clone(); + session.set_disk_space_reader(Some(std::sync::Arc::new(move |_: &std::path::Path| { + Some(DiskSpace { available: if l.load(Ordering::Relaxed) { GB } else { 400 * GB }, total: 500 * GB }) + }))); + let mut app = LightcraftApp::new(session, Services::default()); + app.disk_space_notice = true; + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + h.app.session.open_library(&dir, false).unwrap(); + // (the open's read answered: a pass before that would see no alert yet whatever the drive holds) + assert!(h.step_until(T, |h| !h.app.session.disk_space_reading() && h.app.session.preview_build.is_none())); + assert!(!h.app.session.disk_space_alert_raised()); + for _ in 0..5 { + h.step(); + } + assert!(h.app.notices.is_empty(), "plenty of space at open: {:?}", h.app.notices); + // later, the drive fills up while nothing builds previews + low.store(true, Ordering::Relaxed); + h.app.session.forget_disk_space_check(); + assert!(h.app.session.preview_build.as_ref().is_none_or(|b| !b.running())); + assert!(h.step_until(T, |h| !h.app.notices.is_empty()), "the low drive is told"); + assert!(h.app.notices[0].contains("1.0 GB free of 500 GB"), "{:?}", h.app.notices); + let _ = h.app.session.close_library(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// An idle window still takes the drive's answer and makes the next check (CodeRabbit on #3077): +/// while a read runs the notice logic asks for a pass soon, and otherwise for one when the next +/// check is due; once the alert was raised it asks for nothing. +#[test] +fn an_idle_window_wakes_for_the_disk_check() { + use std::sync::{Arc, Mutex, mpsc}; + let dir = std::env::temp_dir().join(format!("lc-disk-notice-idle-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (release, wait) = mpsc::channel::<()>(); + let wait = Mutex::new(wait); + let mut session = lightcraft_engine::Session::with_demo().with_fs(); + session.set_disk_space_reader(Some(Arc::new(move |_: &std::path::Path| { + let _ = wait.lock().unwrap().recv_timeout(Duration::from_secs(10)); + Some(DiskSpace { available: GB, total: 500 * GB }) + }))); + let mut app = LightcraftApp::new(session, Services::default()); + app.disk_space_notice = true; + app.session.open_library(&dir, false).unwrap(); + assert!(app.session.disk_space_reading()); + let ctx = egui::Context::default(); + let pass = |app: &mut LightcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |_| crate::panels::notices::logic(app, &ctx)); + out.textures_delta.clear(); + out.viewport_output.values().map(|v| v.repaint_delay).min().unwrap_or(Duration::MAX) + }; + assert!(pass(&mut app) <= Duration::from_millis(250), "a pass soon while the read runs"); + release.send(()).unwrap(); + let until = std::time::Instant::now() + T; + while app.notices.is_empty() { + assert!(std::time::Instant::now() < until, "the answer was never taken"); + pass(&mut app); + } + assert!(pass(&mut app) > Duration::from_secs(60), "raised: nothing more to wake for"); + let _ = app.session.close_library(); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/tests/drop_import.rs b/crates/ui-egui/src/tests/drop_import.rs index e5d427d65e..6136ccf93f 100644 --- a/crates/ui-egui/src/tests/drop_import.rs +++ b/crates/ui-egui/src/tests/drop_import.rs @@ -1193,13 +1193,12 @@ fn auto_import_waits_for_a_browse_that_starts_during_its_listing() { let dir = Scratch::new("auto-browse"); let mut h = app(&dir); second_auto_import_listing(&mut h, &dir); - let scan = crate::import::stall_scan_of(&mut h.app, true); + let tx = crate::import::scan_by_hand(&mut h.app, true); apply_auto_import_listing(&mut h); assert!(h.app.import.is_none(), "no Auto Import for the browse to replace"); // the browse finds one photo of its own and imports it - let Ok(tx) = scan.downcast::>() else { panic!("the stalled scan's sender") }; let found = ImportCandidate { path: dir.path("trip/a.png"), ..Default::default() }; - tx.send(ScanOutput { candidates: vec![found], probes: Default::default() }).unwrap(); + tx.send(crate::import::ScanEnd::Done(ScanOutput { candidates: vec![found], probes: Default::default() })).unwrap(); drop(tx); assert!(h.step_until(T, |h| h.app.import.is_some()), "the browse starts its import"); assert!(h.step_until(T, |h| h.app.import.is_none()), "and it ends"); diff --git a/crates/ui-egui/src/tests/lifecycle_037.rs b/crates/ui-egui/src/tests/lifecycle_037.rs index 7b51cb3feb..dbff222044 100644 --- a/crates/ui-egui/src/tests/lifecycle_037.rs +++ b/crates/ui-egui/src/tests/lifecycle_037.rs @@ -2332,3 +2332,43 @@ fn synthetic_modifier_ownership_follows_host_changes_across_frames() { assert_eq!(app.synthetic_mods, egui::Modifiers::NONE); assert!(!app.synthetic_mods_release); } + +/// Background preparation is advanced on every logic pass, the hidden ones too (CodeRabbit on +/// #3077): a minimised window keeps preparing the view's previews, and a shown frame ticks it once. +#[test] +fn background_preparation_advances_while_the_window_is_hidden() { + let mut app = app(); + let ctx = egui::Context::default(); + let hidden = viewport_raw(egui::vec2(800.0, 600.0), false); + let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx)); + let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx)); + assert_eq!(app.prep_ticks, 2, "each hidden pass advances it"); + let visible = viewport_raw(egui::vec2(800.0, 600.0), true); + let _ = ctx.run_logic(&visible, |ctx| app.logic(ctx)); + assert_eq!(app.prep_ticks, 3, "a shown pass advances it once"); +} +/// CodeRabbit on #3077/#3080: a background build that couldn't start asks for a frame at its retry +/// time, so the retry happens with no input and no other timed frame. +#[test] +fn a_build_waiting_to_retry_asks_for_a_frame_at_its_time() { + let mut app = app(); + let ctx = egui::Context::default(); + let delays = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let seen = delays.clone(); + ctx.set_request_repaint_callback(move |info| seen.lock().unwrap().push(info.delay)); + let wait = std::time::Duration::from_secs(7); + let hidden = viewport_raw(egui::vec2(800.0, 600.0), false); + // (the first passes ask for frames at once, which would hide a later request) + for _ in 0..3 { + let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx)); + } + delays.lock().unwrap().clear(); + app.session.prep.retry_at = Some((0, std::time::Instant::now() + wait)); + let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx)); + let got = delays.lock().unwrap().clone(); + assert!(got.iter().any(|d| *d > std::time::Duration::from_secs(6) && *d <= wait), "a frame at the retry time: {got:?}"); + app.session.prep.retry_at = None; + delays.lock().unwrap().clear(); + let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx)); + assert!(!delays.lock().unwrap().iter().any(|d| *d > std::time::Duration::from_secs(6) && *d <= wait), "none without a retry waiting"); +} diff --git a/crates/ui-egui/src/tests/model_setup.rs b/crates/ui-egui/src/tests/model_setup.rs deleted file mode 100644 index 22c4ca7f92..0000000000 --- a/crates/ui-egui/src/tests/model_setup.rs +++ /dev/null @@ -1,225 +0,0 @@ -//! Synthetic setup flows: model installation must resume the requested action on its original targets. -use std::path::{Path, PathBuf}; - -use lightcraft_catalog::{MediaKind, Op, Photo, PhotoId, Source}; -use lightcraft_denoise::manifest::{DenoiserManifest, Domain, Gain}; -use lightcraft_engine::Session; -use serde_json::json; - -use crate::{LightcraftApp, Services, model_setup, state::Dialog}; - -fn setup(name: &str) -> (LightcraftApp, PathBuf, PhotoId) { - let dir = std::env::temp_dir().join(format!("lc-model-flow-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let mut s = Session::new().with_fs(); - s.open_library(dir.join("library"), true).unwrap(); - s.set_denoise_models_dir(Some(dir.join("denoise"))); - s.execute("denoise.settings", &json!({"runOn": "cpu"})).unwrap(); - let id = PhotoId(s.catalog.photos().map(|p| p.id.0).max().unwrap() + 1); - let mut raw = Photo::new( - id, - Source::File { path: dir.join("synthetic.dng").to_string_lossy().into_owned() }, - "synthetic.dng", - "DNG", - 128, - 128, - "2026-10-07", - ); - raw.kind = MediaKind::Raw; - s.commit("fixture", Op::AddPhoto { photo: Box::new(raw) }).unwrap(); - (LightcraftApp::new(s, Services::default()), dir, id) -} - -fn denoise_file(dir: &Path) -> PathBuf { - let source = dir.join("source"); - std::fs::create_dir_all(&source).unwrap(); - let bytes = lightcraft_denoise::synthetic::smoothing_onnx(); - std::fs::write(source.join("model.onnx"), &bytes).unwrap(); - let m = DenoiserManifest { - id: "test-smoothing".into(), - name: "Synthetic smoothing".into(), - version: "1".into(), - licence: Default::default(), - source: None, - sha256: None, - size_bytes: Some(bytes.len() as u64), - provenance: "Synthetic tests".into(), - domain: Domain::BayerToRgb, - tile: 64, - overlap: 16, - gain: Gain::None, - }; - std::fs::write(source.join("denoise-model.json"), serde_json::to_vec(&m).unwrap()).unwrap(); - source.join("model.onnx") -} - -fn install_denoise(app: &mut LightcraftApp, dir: &Path) { - app.run("denoise.models.install", json!({"path": denoise_file(dir), "acknowledged": true})).unwrap(); -} - -#[test] -fn accepting_a_local_model_installs_in_background_and_resumes_the_pending_action() { - let (mut app, dir, raw) = setup("local-install"); - let path = denoise_file(&dir); - app.run("denoise.toggle", json!({"id": raw.0, "enabled": true})).unwrap(); - let info = app.run("denoise.models.inspect", json!({"path": path})).unwrap(); - assert!(crate::panels::denoise::install(&mut app, &info, false).is_err()); - assert!(!dir.join("denoise/test-smoothing/model.onnx").exists()); - let result = crate::panels::denoise::install(&mut app, &info, true).unwrap(); - assert_eq!(result["started"], "local-install"); - assert_eq!(app.ui.dialog, Some(Dialog::Settings { tab: "denoise".into() })); - let ctx = egui::Context::default(); - // a deadline, not a count of tries: the install copies on a background thread, slow on a busy machine - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); - while std::time::Instant::now() < deadline { - crate::panels::denoise::pump(&mut app, &ctx); - if app.session.denoise_photo_state(raw) != lightcraft_engine::denoise::PhotoState::NoModel { - break; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } - resume(&mut app); - assert_eq!(amount(&app, raw), 50.0); - assert!(dir.join("denoise/test-smoothing/model.onnx").is_file()); - assert!(path.is_file(), "a user-supplied original is preserved"); - drop(app); - let _ = std::fs::remove_dir_all(dir); -} - -fn amount(app: &LightcraftApp, id: PhotoId) -> f64 { - app.session.develop_of(id).unwrap().enhance.denoise -} -fn resume(app: &mut LightcraftApp) { - model_setup::pump(app, &egui::Context::default(), app.tick_now()); -} - -#[test] -fn denoise_installation_enables_only_the_requesting_photo_once_and_is_undoable() { - let (mut app, dir, raw) = setup("denoise"); - let other = app.session.active().unwrap(); - app.session.auto_sync = true; - let r = app.run("denoise.toggle", json!({"id": raw.0, "enabled": true})).unwrap(); - assert_eq!(r["setupRequired"], true); - assert_eq!(app.ui.dialog, Some(Dialog::Settings { tab: "denoise".into() })); - assert_eq!(amount(&app, raw), 0.0, "setup alone never changes the photo"); - app.run("library.select", json!({"ids": [other.0]})).unwrap(); - let undo = app.session.undo.len(); - install_denoise(&mut app, &dir); - resume(&mut app); - assert_eq!(amount(&app, raw), 50.0); - assert_eq!(amount(&app, other), 0.0); - assert_eq!(app.session.active(), Some(other)); - assert_eq!(app.session.undo.len(), undo + 1); - resume(&mut app); - assert_eq!(app.session.undo.len(), undo + 1, "a later frame cannot apply it again"); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(amount(&app, raw), 0.0); - app.run("denoise.toggle", json!({"id": raw.0, "enabled": true})).unwrap(); - app.run("develop.set", json!({"ids": [raw.0], "control": "enhance.denoise", "value": 75})).unwrap(); - app.run("denoise.toggle", json!({"id": raw.0, "enabled": true})).unwrap(); - assert_eq!(amount(&app, raw), 75.0, "enabling an already chosen amount keeps it"); - app.run("denoise.toggle", json!({"id": raw.0, "enabled": false})).unwrap(); - assert_eq!(amount(&app, raw), 75.0, "switching off keeps the Amount"); - assert_eq!(app.session.develop_of(raw).unwrap().denoise_amount(), 0.0, "but mixes nothing in"); - drop(app); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn cancelled_denoise_requests_do_not_apply_after_installation() { - for (name, command, params) in [ - ("cancel-action", "modelSetup.cancel", json!({"kind": "denoise"})), - ("cancel-toggle", "denoise.toggle", json!({"enabled": false})), - ("cancel-download", "denoise.models.downloadCancel", json!({"id": "rawnind-bayer"})), - ] { - let (mut app, dir, raw) = setup(name); - app.run("library.select", json!({"ids": [raw.0]})).unwrap(); - app.run("denoise.toggle", json!({"enabled": true})).unwrap(); - app.run(command, params).unwrap(); - install_denoise(&mut app, &dir); - resume(&mut app); - assert_eq!(amount(&app, raw), 0.0, "{name}"); - drop(app); - let _ = std::fs::remove_dir_all(dir); - } -} - -#[test] -fn pending_actions_do_not_cross_libraries_or_relinked_sources() { - for changed in ["library", "source"] { - let (mut app, dir, raw) = setup(changed); - app.run("denoise.toggle", json!({"id": raw.0, "enabled": true})).unwrap(); - if changed == "library" { - app.session.open_library(dir.join("other-library"), true).unwrap(); - } else { - app.session - .commit( - "relink", - Op::Relink { - id: raw, - file_name: "another.dng".into(), - source: Source::File { path: dir.join("another.dng").to_string_lossy().into_owned() }, - format: Some("DNG".into()), - }, - ) - .unwrap(); - } - install_denoise(&mut app, &dir); - resume(&mut app); - assert!(!model_setup::denoise_requested(&app, raw)); - assert!(app.session.catalog.photos().all(|p| p.develop.enhance.denoise == 0.0)); - assert!(app.ui.status.contains("cancelled")); - drop(app); - let _ = std::fs::remove_dir_all(dir); - } -} - -#[test] -fn hostile_or_inapplicable_toggle_arguments_are_errors_without_changes() { - let (mut app, dir, raw) = setup("hostile"); - let jpeg = app.session.active().unwrap(); - for params in [json!({"id": "wrong"}), json!({"id": u64::MAX}), json!({"id": raw.0, "enabled": 1}), json!({"id": jpeg.0, "enabled": true})] { - assert!(app.run("denoise.toggle", params).is_err()); - assert_eq!(amount(&app, raw), 0.0); - } - assert!(app.run("modelSetup.cancel", json!({"kind": "nonsense"})).is_err()); - drop(app); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn model_installation_waits_for_an_active_slider_gesture_to_finish() { - let (mut app, dir, raw) = setup("interaction"); - app.run("denoise.toggle", json!({"id": raw.0, "enabled": true})).unwrap(); - app.session.begin_interaction("Exposure").unwrap(); - install_denoise(&mut app, &dir); - resume(&mut app); - assert_eq!(amount(&app, raw), 0.0); - assert!(app.session.interaction.is_some()); - app.session.end_interaction().unwrap(); - resume(&mut app); - assert_eq!(amount(&app, raw), 50.0); - drop(app); - let _ = std::fs::remove_dir_all(dir); -} - -/// Issue #922: closing the setup without installing a model turns the AI Denoise switch back off -/// and drops the "Cancel pending action" offer; while the setup stays open the request waits. -#[test] -fn dismissing_the_setup_without_a_model_leaves_ai_denoise_off() { - let (mut app, dir, raw) = setup("dismissed"); - let r = app.run("denoise.toggle", json!({"id": raw.0, "enabled": true})).unwrap(); - assert_eq!(r["setupRequired"], true); - resume(&mut app); - assert!(model_setup::denoise_requested(&app, raw), "the open setup keeps the request"); - app.ui.dialog = None; - resume(&mut app); - assert!(!model_setup::denoise_requested(&app, raw), "a dismissed setup leaves nothing pending"); - assert!(app.ui.status.contains("cancelled"), "{}", app.ui.status); - // installing later changes nothing; asking again offers the setup again - install_denoise(&mut app, &dir); - resume(&mut app); - assert_eq!(amount(&app, raw), 0.0); - drop(app); - let _ = std::fs::remove_dir_all(dir); -} diff --git a/crates/ui-egui/src/tests/preview_limit.rs b/crates/ui-egui/src/tests/preview_limit.rs index ce5a5aba42..ddd6c74790 100644 --- a/crates/ui-egui/src/tests/preview_limit.rs +++ b/crates/ui-egui/src/tests/preview_limit.rs @@ -1290,6 +1290,38 @@ mod in_the_loupe { assert!(window[0].1.right() >= canvas.right() - 0.5, "the Before window stops at the wipe line: {:?}", window[0].1); } + // Given Before and After side by side at 1:1 with `\` held, the After pane is still the view + // shown: a Before window drawn while the After pane shows a stand-in does not make the loupe + // say the render is on screen + #[test] + fn holding_backslash_side_by_side_the_before_window_is_not_the_shown_render() { + let (_fx, mut h, _) = detail_in([1800.0, 900.0]); + h.app.ui.before_after = crate::state::BeforeAfter::SideBySide; + h.request("engine.execute", json!({"command": "view.zoom100"}), T); + h.settle(SETTLE); + h.events.push(egui::Event::Key { + key: egui::Key::Backslash, + physical_key: Some(egui::Key::Backslash), + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }); + h.settle(SETTLE); + // (the key's own shortcut switches to the Before view; side by side is chosen again with the key down) + h.app.ui.before_after = crate::state::BeforeAfter::SideBySide; + h.settle(SETTLE); + assert!(h.app.renderer.textures.contains_key(&Slot::RegionBefore), "the Before window is rendered"); + // the After pane back to a stand-in: no whole-frame render and no window of its own + h.app.renderer.textures.remove(&Slot::Main); + h.app.renderer.textures.remove(&Slot::Region); + h.step(); + assert!(!drawn(&h, Slot::RegionBefore).is_empty(), "the Before window is painted"); + // (the step must not bring the After pane's render back, or the check below proves nothing) + assert!(!h.app.renderer.textures.contains_key(&Slot::Main), "the whole-frame render came back during the step"); + assert!(!h.app.renderer.textures.contains_key(&Slot::Region), "the After window came back during the step"); + assert_ne!(h.app.loupe_shown.map(|l| l.1), Some("render"), "the After pane shows a stand-in, not the render"); + } + // Given Before and After side by side at 1:1, each window is painted inside its own pane: its // margin (a window is wider than what its pane shows) does not spill into the neighbour #[test] @@ -1306,6 +1338,33 @@ mod in_the_loupe { assert!(after.iter().all(|(_, clip, _)| clip.left() >= canvas.center().x), "the After window spills into the Before pane: {after:?}"); } + // Given Before and After side by side at 1:1 with `\` held, both panes stay, so each window + // stays clipped to its own pane: the Before window's margin does not cover the After pane + #[test] + fn holding_backslash_side_by_side_keeps_each_window_in_its_pane() { + let (_fx, mut h, _) = detail_in([1800.0, 900.0]); + h.app.ui.before_after = crate::state::BeforeAfter::SideBySide; + h.request("engine.execute", json!({"command": "view.zoom100"}), T); + h.settle(SETTLE); + h.events.push(egui::Event::Key { + key: egui::Key::Backslash, + physical_key: Some(egui::Key::Backslash), + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }); + h.settle(SETTLE); + // (the key's own shortcut switches to the Before view; side by side is chosen again with the key down) + h.app.ui.before_after = crate::state::BeforeAfter::SideBySide; + h.settle(SETTLE); + h.step(); + let canvas = h.app.canvas_rect.unwrap(); + let (before, after) = (drawn(&h, Slot::RegionBefore), drawn(&h, Slot::Region)); + assert!(!before.is_empty() && !after.is_empty()); + assert!(before.iter().all(|(_, clip, _)| clip.right() <= canvas.center().x), "the Before window spills into the After pane: {before:?}"); + assert!(after.iter().all(|(_, clip, _)| clip.left() >= canvas.center().x), "the After window spills into the Before pane: {after:?}"); + } + // Given a Before and an After with the same look (an unedited photo), both windows are kept // apart: the job key is the same, and one tile must not replace the other #[test] @@ -1583,3 +1642,16 @@ mod in_the_loupe { assert_ne!(after.settings, before.settings); } } + +// Build Standard-Sized Previews on Automatic: the loupe's size once one was drawn (the engine's standard), the +// standard 2560 px in a fresh session, not the engine's 2048 px minimum a fit view would render again over +// (CodeRabbit on #3077); a chosen limit as is +#[test] +fn standard_build_keeps_the_standard_size_before_a_loupe_was_drawn() { + use crate::menubar::standard_build_params; + use serde_json::json; + assert_eq!(standard_build_params(&with_limit(0), 0), json!({"size": "standard", "edge": STANDARD_PREVIEW_EDGE})); + assert_eq!(standard_build_params(&with_limit(0), 2400), json!({"size": "standard"})); + assert_eq!(standard_build_params(&with_limit(3840), 0), json!({"size": "standard", "edge": 3840})); + assert_eq!(standard_build_params(&with_limit(3840), 2400), json!({"size": "standard", "edge": 3840})); +} diff --git a/crates/ui-egui/src/tests/scan_probes.rs b/crates/ui-egui/src/tests/scan_probes.rs new file mode 100644 index 0000000000..04c7ad10d0 --- /dev/null +++ b/crates/ui-egui/src/tests/scan_probes.rs @@ -0,0 +1,204 @@ +//! A scan takes the probes of earlier scans from the session (`ScanInput::new`) and hands them back +//! however it ends: finished, stopped by another folder or by ✕, or unable to list its folder, so a later +//! import doesn't read those files again. + +use std::time::Duration; + +use crate::LightcraftApp; +use crate::headless::Headless; +use crate::import::ScanEnd; + +const T: Duration = Duration::from_secs(10); +const KEPT: &str = "/nowhere/kept.cr3"; + +fn demo() -> Headless { + let services = crate::Services { png: None, ..Default::default() }; + Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1000.0, 700.0], 1.0) +} + +fn probes() -> std::collections::HashMap { + [(KEPT.to_string(), lightcraft_engine::media::ProbeInfo { file_size: 7, ..Default::default() })].into_iter().collect() +} + +fn kept(h: &Headless) -> bool { + h.app.session.import_probes.get(KEPT).is_some_and(|p| p.file_size == 7) +} + +fn failed_toast(h: &Headless) -> bool { + h.app.ui.toast.as_ref().is_some_and(|t| t.0.contains("Scan failed")) +} + +fn cancel_scan(h: &mut Headless) { + let id = h.app.session.activity.list().iter().find(|t| t.kind == "scan").map(|t| t.id).expect("the scan's row"); + h.app.session.activity.cancel(id).expect("the scan can be cancelled"); +} + +#[test] +fn a_browse_replaced_by_another_folder_hands_back_its_probes() { + let mut h = demo(); + let base = std::env::temp_dir().join(format!("lc-ui-scan-probes-{}", std::process::id())); + let (a, b) = (base.join("a"), base.join("b")); + std::fs::create_dir_all(&a).unwrap(); + std::fs::create_dir_all(&b).unwrap(); + h.app.session.import_probes = probes(); + crate::import::browse(&mut h.app, &a.to_string_lossy(), None).unwrap(); + assert!(h.app.session.import_probes.is_empty(), "the first browse took the probes"); + // another folder at once: the first browse is stopped (or its result left unread) + crate::import::browse(&mut h.app, &b.to_string_lossy(), None).unwrap(); + assert!(h.step_until(T, |h| h.app.scan.is_none() && kept(h)), "the first browse's probes came back"); + let _ = std::fs::remove_dir_all(&base); +} + +#[test] +fn a_browse_that_cannot_list_its_folder_hands_back_its_probes() { + let mut h = demo(); + let tx = crate::import::scan_by_hand(&mut h.app, true); + tx.send(ScanEnd::Stopped { probes: probes(), failed: true }).unwrap(); + h.step(); + assert!(h.app.scan.is_none()); + assert!(kept(&h), "the probes came back"); + assert!(failed_toast(&h), "the failure is reported: {:?}", h.app.ui.toast); +} + +#[test] +fn a_scan_closed_with_its_cross_hands_back_its_probes_when_the_worker_ends() { + let mut h = demo(); + let tx = crate::import::scan_by_hand(&mut h.app, false); + cancel_scan(&mut h); + h.step(); + assert!(h.app.scan.is_none(), "✕ closes the scan at once"); + // the worker ends later, with the probes it took + tx.send(ScanEnd::Done(lightcraft_engine::import::ScanOutput { candidates: Vec::new(), probes: probes() })).unwrap(); + assert!(h.step_until(T, kept), "the probes came back"); + assert!(h.app.ui.dialog.is_none(), "no review opened"); + assert!(!failed_toast(&h)); +} + +#[test] +fn a_cancelled_scan_whose_worker_ends_without_a_result_is_not_a_failure() { + let mut h = demo(); + let tx = crate::import::scan_by_hand(&mut h.app, true); + cancel_scan(&mut h); + drop(tx); + h.step(); + assert!(h.app.scan.is_none()); + assert!(!failed_toast(&h), "a cancelled scan says nothing: {:?}", h.app.ui.toast); +} + +/// Two stopped scans hand back a probe of one file: the later scan read it again, so its probe stays, +/// whichever worker ends first (CodeRabbit on #3577: the older one won when its worker ended first, +/// and its content hash is stale for a file changed at the same size). +#[test] +fn the_later_stopped_scans_probe_wins_whichever_worker_ends_first() { + let probe = |hash: &str| { + let p = lightcraft_engine::media::ProbeInfo { file_size: 7, content_hash: Some(hash.into()), ..Default::default() }; + [(KEPT.to_string(), p)].into_iter().collect() + }; + for later_ends_first in [false, true] { + let mut h = demo(); + let older = crate::import::scan_by_hand(&mut h.app, true); + cancel_scan(&mut h); + h.step(); + let newer = crate::import::scan_by_hand(&mut h.app, true); + cancel_scan(&mut h); + h.step(); + assert!(h.app.scan.is_none(), "both stopped"); + let a = ScanEnd::Stopped { probes: probe("older"), failed: false }; + let b = ScanEnd::Stopped { probes: probe("newer"), failed: false }; + if later_ends_first { + newer.send(b).unwrap(); + h.step(); + older.send(a).unwrap(); + } else { + older.send(a).unwrap(); + h.step(); + newer.send(b).unwrap(); + } + h.step(); + let hash = h.app.session.import_probes.get(KEPT).and_then(|p| p.content_hash.clone()); + assert_eq!(hash.as_deref(), Some("newer"), "later worker ends first: {later_ends_first}"); + } +} + +/// Browsing reads the disk only on its worker (CodeRabbit on #3077): a folder whose resolution is held (a link on +/// a stalled network mount) still lets `browse` return at once, the view shows the folder as given, and the scan +/// waits; once resolved, the folder is read. +#[test] +fn a_browse_whose_folder_resolves_slowly_returns_at_once_and_waits() { + let mut h = demo(); + let dir = std::env::temp_dir().join(format!("lc-ui-browse-held-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + // (spelled with `sub/..`: the worker is handed the path as given, not the view's spelling of it) + let given = dir.join("sub").join("..").to_string_lossy().to_string(); + let spelled = lightcraft_engine::import::browse_spelling(&dir).unwrap().to_string_lossy().trim_end_matches(['/', '\\']).to_string(); + crate::import::HELD_RESOLVES.lock().unwrap().push(given.clone()); + let start = std::time::Instant::now(); + let r = crate::import::browse(&mut h.app, &given, None).unwrap(); + assert!(start.elapsed() < Duration::from_secs(2), "returned after {:?}", start.elapsed()); + assert_eq!(r["scanning"], true, "{r}"); + assert_eq!(h.app.session.browse.as_ref().map(|b| b.path.clone()), Some(spelled), "shown as spelled meanwhile"); + for _ in 0..5 { + h.step(); + } + assert!(h.app.scan.is_some(), "still waiting for the folder"); + crate::import::HELD_RESOLVES.lock().unwrap().retain(|p| *p != given); + assert!(h.step_until(T, |h| h.app.scan.is_none()), "read once resolved"); + assert!(!failed_toast(&h), "{:?}", h.app.ui.toast); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A path that isn't a folder is found out by the worker, not by the window's thread: `browse` returns, and the scan +/// then ends as failed. +#[test] +fn a_browse_of_a_missing_folder_fails_on_its_worker() { + let mut h = demo(); + let gone = std::env::temp_dir().join(format!("lc-ui-browse-gone-{}", std::process::id())).join("not-there"); + assert!(crate::import::browse(&mut h.app, &gone.to_string_lossy(), None).is_ok()); + assert!(h.step_until(T, |h| h.app.scan.is_none())); + assert!(failed_toast(&h), "the failure is reported: {:?}", h.app.ui.toast); +} + +/// The worker resolves the path as given (CodeRabbit on #3055 / #3077 / #3080): on Unix `photos/link/../select`, with +/// `link` pointing at `real/day`, is `real/select`, not the `photos/select` that taking `..` out by name would read. +#[cfg(unix)] +#[test] +fn a_browse_through_a_link_and_dot_dot_reads_the_folder_the_system_names() { + let mut h = demo(); + let base = std::env::temp_dir().join(format!("lc-ui-browse-link-{}", std::process::id())); + let (day, real_select, photos) = (base.join("real/day"), base.join("real/select"), base.join("photos")); + for d in [&day, &real_select, &photos.join("select")] { + std::fs::create_dir_all(d).unwrap(); + } + std::os::unix::fs::symlink(&day, photos.join("link")).unwrap(); + let given = photos.join("link").join("..").join("select"); + crate::import::browse(&mut h.app, &given.to_string_lossy(), None).unwrap(); + assert!(h.step_until(T, |h| h.app.scan.is_none()), "the browse ended"); + assert!(!failed_toast(&h), "{:?}", h.app.ui.toast); + let want = std::fs::canonicalize(&real_select).unwrap(); + let shown = h.app.session.browse.as_ref().map(|b| std::fs::canonicalize(&b.path).unwrap()); + assert_eq!(shown, Some(want), "the folder the system names, not photos/select"); + let _ = std::fs::remove_dir_all(&base); +} + +/// Browsing a folder that is being read again keeps its progress, but not through `..` (CodeRabbit on #3583): past +/// a link, `x/link/../y` can be another folder than the `x/y` it is spelled as, so the worker reads it again. +#[test] +fn a_browse_through_dot_dot_reads_again_while_its_spelling_is_being_read() { + let mut h = demo(); + let dir = std::env::temp_dir().join(format!("lc-ui-browse-dotdot-{}", std::process::id())); + std::fs::create_dir_all(dir.join("sub")).unwrap(); + let plain = dir.to_string_lossy().to_string(); + crate::import::HELD_RESOLVES.lock().unwrap().push(plain.clone()); + let row = |h: &Headless| h.app.session.activity.list().iter().find(|t| t.kind == "scan").map(|t| t.id); + crate::import::browse(&mut h.app, &plain, None).unwrap(); + let first = row(&h); + assert!(first.is_some(), "the browse's row"); + crate::import::browse(&mut h.app, &plain, None).unwrap(); + assert_eq!(row(&h), first, "the same folder again: the same read"); + let given = dir.join("sub").join("..").to_string_lossy().to_string(); + crate::import::browse(&mut h.app, &given, None).unwrap(); + assert_ne!(row(&h), first, "through `..`: read again"); + crate::import::HELD_RESOLVES.lock().unwrap().retain(|p| *p != plain); + assert!(h.step_until(T, |h| h.app.scan.is_none()), "the browse ended"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 0c562f451f..de2be96a6c 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -412,6 +412,25 @@ pub fn current(ctx: &egui::Context) -> Option { ctx.data(|d| d.get_temp::(theme_id())) } +/// Windows only: tell the window its theme again, the first time it has focus. A first theme that +/// reaches a focused window as it comes up changes the title's colour but not the caption's, so +/// with LightCraft dark on a light system the title is white on a light caption (it looks blank), +/// and light on dark is dark on dark, until focus next moves (#3381). The same command repaints +/// the caption once the window is up. A window that opens without focus shows the right colours +/// from the start. +pub fn refresh_window_on_first_focus(ctx: &egui::Context) { + let done = egui::Id::unique("lightcraft-window-theme-refreshed"); + if !cfg!(target_os = "windows") || !ctx.input(|i| i.focused) || ctx.data(|d| d.get_temp::(done)).is_some() { + return; + } + ctx.data_mut(|d| d.insert_temp(done, true)); + let theme = match ctx.theme() { + egui::Theme::Dark => egui::SystemTheme::Dark, + egui::Theme::Light => egui::SystemTheme::Light, + }; + ctx.send_viewport_cmd(egui::ViewportCommand::SetTheme(theme)); +} + /// Style `ctx` with the default theme. pub fn apply(ctx: &egui::Context) { apply_kind(ctx, ThemeKind::default()); @@ -506,6 +525,51 @@ mod tests { } } + /// The `SetTheme(Light)` commands one frame of `ctx` sends the window, with or without + /// [`refresh_window_on_first_focus`] in it. + #[cfg(target_os = "windows")] + fn light_theme_commands(ctx: &egui::Context, focused: bool, refresh: bool) -> usize { + let raw = egui::RawInput { focused, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if refresh { + refresh_window_on_first_focus(ui.ctx()); + } + }); + out.textures_delta.clear(); + let commands = out.viewport_output.remove(&egui::ViewportId::ROOT).map(|v| v.commands).unwrap_or_default(); + commands.iter().filter(|c| matches!(c, egui::ViewportCommand::SetTheme(egui::SystemTheme::Light))).count() + } + + /// #3381: egui sends the theme with the first frame, and the window hears it once more the + /// first time it has focus, not on every later focus. + #[cfg(target_os = "windows")] + #[test] + fn the_window_hears_its_theme_again_the_first_time_it_has_focus() { + let ctx = egui::Context::default(); + apply_kind(&ctx, ThemeKind::Silver); + let sent = |focused: bool| light_theme_commands(&ctx, focused, true); + assert_eq!(sent(false), 1, "egui's own, with the first frame"); + assert_eq!(sent(false), 0, "no focus yet"); + assert_eq!(sent(true), 1, "the first frame with focus"); + assert_eq!(sent(true), 0, "still focused"); + assert_eq!(sent(false), 0, "focus lost"); + assert_eq!(sent(true), 0, "focus back: Windows repaints this by itself"); + } + + /// #3381: a window that has focus from its very first frame hears the theme once more in that + /// frame, on top of egui's own command. (In the app the first frame never gets here: `ui` + /// returns before the fonts are ready, so egui's command always goes a frame earlier.) + #[cfg(target_os = "windows")] + #[test] + fn a_window_focused_from_its_first_frame_hears_its_theme_again_in_that_frame() { + let first_frame = |refresh: bool| { + let ctx = egui::Context::default(); + apply_kind(&ctx, ThemeKind::Silver); + light_theme_commands(&ctx, true, refresh) + }; + assert_eq!(first_frame(true), first_frame(false) + 1); + } + /// Every theme scrolls 100 points a wheel notch, and a zoom notch stays egui's stock ~1.22x /// (`exp(40 / 200)`) instead of growing with the longer scroll. #[test] diff --git a/crates/wincolor/Cargo.toml b/crates/wincolor/Cargo.toml new file mode 100644 index 0000000000..8cf4739a11 --- /dev/null +++ b/crates/wincolor/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "lightcraft-wincolor" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "LightCraft wincolor (L0): the colour profile Windows assigns to the monitor showing a window. One of the two crates allowed `unsafe` (Win32 calls)." + +# The workspace lints: they deny `unsafe_code` (deny, not forbid), which the `win32` module in +# src/lib.rs allows for its Win32 calls; every other crate root has `#![forbid(unsafe_code)]`. See +# AGENTS.md and craftrules standards/never-crash.md ("isolated helper library crate"). +[lints] +workspace = true + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = [ + "Win32_Foundation", + "Win32_Graphics_Gdi", + "Win32_UI_ColorSystem", + "Win32_Devices_Display", +] } + +[dev-dependencies] +# tests record why they skip (`cargo xtask ci` lists the skips) +lightcraft-testkit = { workspace = true } + +# the desktop window, for a test +[target.'cfg(windows)'.dev-dependencies] +windows-sys = { version = "0.61", features = ["Win32_UI_WindowsAndMessaging"] } diff --git a/crates/wincolor/src/lib.rs b/crates/wincolor/src/lib.rs new file mode 100644 index 0000000000..8a1112ad0d --- /dev/null +++ b/crates/wincolor/src/lib.rs @@ -0,0 +1,366 @@ +//! The colour profile Windows assigns to the monitor showing a window. +//! +//! On an SDR desktop Windows doesn't colour-manage ordinary windows: the values an app draws go to +//! the monitor as they are, so on a wide-gamut monitor sRGB previews look oversaturated, and on a +//! calibrated one the calibration is ignored. Photo apps convert to the monitor's profile themselves. +//! LightCraft reads it here and shows previews through it while no profile is chosen in Settings ▸ +//! Display, as it does with the screen's profile on macOS and colord's on Linux. +//! +//! When Windows colour-manages the desktop itself (HDR, or Auto Color Management on Windows 11), it +//! treats what an ordinary app draws as sRGB and converts it for the monitor; converting in the app +//! too would do it twice, so the answer is then [`MonitorColor::ManagedByWindows`]. +//! +//! The profile comes from Windows Color System, which holds what Settings ▸ Display ▸ Color profile +//! and Color Management assign, per user or for the system: it is read afresh on every call, so a +//! change shows without restarting. (GDI's `GetICMProfileW` answers what the profile was when the +//! process first asked, and serves only as a fallback when the monitor's device can't be found.) +//! +//! The Win32 calls (`MonitorFromWindow`, `GetMonitorInfoW`, `EnumDisplayDevicesW`, the `Wcs…` +//! profile functions, `QueryDisplayConfig` + `DisplayConfigGetDeviceInfo`) are in the `win32` module, +//! the only place besides `crates/sysmem` where LightCraft allows `unsafe`. The API is safe, and any +//! failure answers [`MonitorColor::Unknown`]. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::path::PathBuf; + +/// What Windows says about colour on the monitor showing a window. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum MonitorColor { + /// Windows colour-manages this monitor's desktop (HDR or Auto Color Management): an app draws + /// sRGB and converts nothing. + ManagedByWindows, + /// The ICC profile assigned to the monitor (the user's own when they chose per-user profiles, + /// else the system's). + Profile(PathBuf), + /// No profile is assigned: Windows treats the monitor as sRGB. + NoProfile, + /// Not known: not Windows, no such window, or a call failed. + Unknown, +} + +/// What Windows says about colour on the monitor the window `hwnd` is mostly on (the nearest one +/// when it is off screen or minimised). `hwnd` is the window's `HWND` as an integer; anything that +/// isn't a window answers [`MonitorColor::Unknown`]. +pub fn monitor_color(hwnd: isize) -> MonitorColor { + #[cfg(windows)] + { + win32::monitor_color(hwnd) + } + #[cfg(not(windows))] + { + let _ = hwnd; + MonitorColor::Unknown + } +} + +/// `true` when Windows colour-manages the desktop on a display with these advanced-colour flags +/// (`DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO`'s bit field): advanced colour enabled (bit 1: HDR, or +/// Auto Color Management) or wide colour enforced (bit 2). +#[cfg(any(windows, test))] +fn managed(flags: u32) -> bool { + flags & 0b110 != 0 +} + +/// The answer Windows' own colour management settles, `None` when the monitor's profile decides: +/// [`MonitorColor::ManagedByWindows`] while it colour-manages the desktop, and +/// [`MonitorColor::Unknown`] when its state can't be read (`managed` is `None`), since applying the +/// monitor's profile on top of Windows' conversion would convert twice. +#[cfg(any(windows, test))] +fn settled_by_windows(managed: Option) -> Option { + match managed { + Some(true) => Some(MonitorColor::ManagedByWindows), + Some(false) => None, + None => Some(MonitorColor::Unknown), + } +} + +/// The text of a NUL-terminated UTF-16 buffer (all of it without a NUL). +#[cfg(any(windows, test))] +fn until_nul(units: &[u16]) -> &[u16] { + units.iter().position(|&u| u == 0).and_then(|n| units.get(..n)).unwrap_or(units) +} + +#[cfg(windows)] +#[allow(unsafe_code)] +mod win32 { + use super::{MonitorColor, managed, settled_by_windows, until_nul}; + use std::ffi::OsString; + use std::os::windows::ffi::OsStringExt; + use std::path::PathBuf; + use windows_sys::Win32::Devices::Display::{ + DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO, DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_DEVICE_INFO_HEADER, + DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO, DISPLAYCONFIG_MODE_INFO, DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_SOURCE_DEVICE_NAME, + DisplayConfigGetDeviceInfo, GetDisplayConfigBufferSizes, QDC_ONLY_ACTIVE_PATHS, QueryDisplayConfig, + }; + use windows_sys::Win32::Foundation::{ERROR_SUCCESS, HWND}; + use windows_sys::Win32::Graphics::Gdi::{ + CreateDCW, DISPLAY_DEVICE_ACTIVE, DISPLAY_DEVICEW, DeleteDC, EnumDisplayDevicesW, GetMonitorInfoW, MONITOR_DEFAULTTONEAREST, MONITORINFO, + MONITORINFOEXW, MonitorFromWindow, + }; + use windows_sys::Win32::UI::ColorSystem::{ + CPST_NONE, CPT_ICC, GetColorDirectoryW, GetICMProfileW, WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER, WCS_PROFILE_MANAGEMENT_SCOPE_SYSTEM_WIDE, + WcsGetDefaultColorProfile, WcsGetDefaultColorProfileSize, WcsGetUsePerUserProfiles, + }; + + /// The most display paths read (a machine has a handful). + const MAX_PATHS: u32 = 64; + /// The most monitors looked at on one display output (several in clone mode). + const MAX_MONITORS: u32 = 16; + /// The device class of monitors in Windows Color System (`'mntr'`, as in an ICC header). + const CLASS_MONITOR: u32 = u32::from_be_bytes(*b"mntr"); + /// The longest profile name read, in bytes (names are file names in the colour directory). + const MAX_NAME_BYTES: u32 = 64 << 10; + + pub fn monitor_color(hwnd: isize) -> MonitorColor { + let Some(device) = monitor_device(hwnd) else { return MonitorColor::Unknown }; + // (an advanced-colour state that can't be read, as on Windows before 10 1709 or with a + // driver that doesn't say, is unknown: previews then stay sRGB, as before profiles were read) + if let Some(answer) = settled_by_windows(managed_by_windows(&device)) { + return answer; + } + match monitor_id(&device) { + Some(id) => wcs_profile(&id), + None => icm_profile(&device).map_or(MonitorColor::Unknown, MonitorColor::Profile), + } + } + + /// The GDI device name (`\\.\DISPLAY1`) of the monitor showing `hwnd`, NUL-terminated. + fn monitor_device(hwnd: isize) -> Option<[u16; 32]> { + if hwnd == 0 { + return None; + } + // SAFETY: `MonitorFromWindow` takes any handle value: window handles are looked up in the + // system's table, not dereferenced, and one that isn't a window gives a null monitor (or + // the nearest monitor). It writes nothing. + let monitor = unsafe { MonitorFromWindow(hwnd as HWND, MONITOR_DEFAULTTONEAREST) }; + if monitor.is_null() { + return None; + } + let mut info = MONITORINFOEXW::default(); + info.monitorInfo.cbSize = size_of::() as u32; + // SAFETY: `info` is a `MONITORINFOEXW` whose `cbSize` says so, and the pointer is taken from + // the whole struct, so `GetMonitorInfoW` may write all of it (it writes at most `cbSize` + // bytes). `monitor` came from `MonitorFromWindow` just above. + let ok = unsafe { GetMonitorInfoW(monitor, (&raw mut info).cast::()) }; + (ok != 0 && !until_nul(&info.szDevice).is_empty() && info.szDevice.contains(&0)).then_some(info.szDevice) + } + + /// The device id (`MONITOR\GSM7750\{…}\0002`) of the monitor on display output `device`, as + /// Windows Color System names it, NUL-terminated: the first active monitor there. + fn monitor_id(device: &[u16; 32]) -> Option<[u16; 128]> { + if !device.contains(&0) { + return None; + } + let mut first = None; + for i in 0..MAX_MONITORS { + let mut dd = DISPLAY_DEVICEW { cb: size_of::() as u32, ..Default::default() }; + // SAFETY: `device` is NUL-terminated (checked above) and `dd` is a `DISPLAY_DEVICEW` whose + // `cb` says so; `EnumDisplayDevicesW` writes at most that struct and fails past the last + // monitor. + if unsafe { EnumDisplayDevicesW(device.as_ptr(), i, &mut dd, 0) } == 0 { + break; + } + if until_nul(&dd.DeviceID).is_empty() || !dd.DeviceID.contains(&0) { + continue; + } + if dd.StateFlags & DISPLAY_DEVICE_ACTIVE != 0 { + return Some(dd.DeviceID); + } + first.get_or_insert(dd.DeviceID); + } + first + } + + /// The profile Windows Color System assigns to monitor `id`: in the user's scope when they chose + /// per-user profiles for it, else the system's. + fn wcs_profile(id: &[u16; 128]) -> MonitorColor { + let mut per_user = 0; + // SAFETY: `id` is NUL-terminated (from `monitor_id`); one `BOOL` to write. + let asked = unsafe { WcsGetUsePerUserProfiles(id.as_ptr(), CLASS_MONITOR, &mut per_user) }; + let scope = if asked != 0 && per_user != 0 { WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER } else { WCS_PROFILE_MANAGEMENT_SCOPE_SYSTEM_WIDE }; + let mut bytes = 0u32; + // SAFETY: as above; one `u32` to write (the name's size in bytes, its NUL included). It fails + // when no profile is assigned in that scope. + if unsafe { WcsGetDefaultColorProfileSize(scope, id.as_ptr(), CPT_ICC, CPST_NONE, 0, &mut bytes) } == 0 { + return MonitorColor::NoProfile; + } + if !(4..=MAX_NAME_BYTES).contains(&bytes) { + return MonitorColor::Unknown; + } + let mut name = vec![0u16; bytes.div_ceil(2) as usize]; + // SAFETY: `name` holds at least `bytes` bytes, the size given; Windows writes at most that. + if unsafe { WcsGetDefaultColorProfile(scope, id.as_ptr(), CPT_ICC, CPST_NONE, 0, bytes, name.as_mut_ptr()) } == 0 { + return MonitorColor::Unknown; + } + let name = PathBuf::from(OsString::from_wide(until_nul(&name))); + if name.as_os_str().is_empty() { + return MonitorColor::NoProfile; + } + // a name is a file in the colour directory (a full path is kept as it is) + if name.is_absolute() { + return MonitorColor::Profile(name); + } + color_directory().map_or(MonitorColor::Unknown, |dir| MonitorColor::Profile(dir.join(name))) + } + + /// The system's colour directory (`…\spool\drivers\color`), where profiles are installed. + fn color_directory() -> Option { + let mut dir = [0u16; 1024]; + let mut bytes = size_of_val(&dir) as u32; + // SAFETY: a null machine name means this one; `dir` holds `bytes` bytes, and Windows writes at + // most that many (failing when the path doesn't fit), updating `bytes`. + let ok = unsafe { GetColorDirectoryW(std::ptr::null(), dir.as_mut_ptr(), &mut bytes) }; + let dir = until_nul(&dir); + (ok != 0 && !dir.is_empty()).then(|| PathBuf::from(OsString::from_wide(dir))) + } + + /// GDI's profile for the display `device`: what it was when this process first asked (see the + /// crate notes), for when the monitor's device isn't found. + fn icm_profile(device: &[u16; 32]) -> Option { + if !device.contains(&0) { + return None; + } + // SAFETY: `device` is NUL-terminated (checked above); the driver, port and mode may be null, + // which makes a DC for that display. A null result is handled below. + let dc = unsafe { CreateDCW(std::ptr::null(), device.as_ptr(), std::ptr::null(), std::ptr::null()) }; + if dc.is_null() { + return None; + } + // (profile paths are under the colour directory, well within this) + let mut name = [0u16; 1024]; + let mut len = name.len() as u32; + // SAFETY: `dc` is the valid DC created above; `name` holds `len` UTF-16 units and + // `GetICMProfileW` writes at most that many (failing when the name doesn't fit), updating `len`. + let ok = unsafe { GetICMProfileW(dc, &mut len, name.as_mut_ptr()) }; + // SAFETY: `dc` came from `CreateDCW` and is deleted exactly once, after its last use. + unsafe { DeleteDC(dc) }; + let path = until_nul(&name); + (ok != 0 && !path.is_empty()).then(|| PathBuf::from(OsString::from_wide(path))) + } + + /// Whether Windows colour-manages the desktop on the display `device`; `None` when it can't be + /// told. + fn managed_by_windows(device: &[u16; 32]) -> Option { + let (mut paths, mut modes) = (0u32, 0u32); + // SAFETY: two counts to write; nothing else is passed. + if unsafe { GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut paths, &mut modes) } != ERROR_SUCCESS { + return None; + } + if paths == 0 || paths > MAX_PATHS || modes > 2 * MAX_PATHS { + return None; + } + let mut path = vec![DISPLAYCONFIG_PATH_INFO::default(); paths as usize]; + let mut mode = vec![DISPLAYCONFIG_MODE_INFO::default(); modes as usize]; + // SAFETY: the arrays hold `paths` and `modes` elements as the counts say; Windows writes at + // most that many and lowers the counts to what it wrote. The topology id must be null with + // `QDC_ONLY_ACTIVE_PATHS`. + let r = + unsafe { QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &mut paths, path.as_mut_ptr(), &mut modes, mode.as_mut_ptr(), std::ptr::null_mut()) }; + if r != ERROR_SUCCESS { + return None; + } + path.truncate(paths as usize); + let wanted = until_nul(device); + for p in &path { + let mut source = DISPLAYCONFIG_SOURCE_DEVICE_NAME { + header: DISPLAYCONFIG_DEVICE_INFO_HEADER { + r#type: DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, + size: size_of::() as u32, + adapterId: p.sourceInfo.adapterId, + id: p.sourceInfo.id, + }, + ..Default::default() + }; + // SAFETY: the header's type and size describe `source`, and the pointer is taken from the + // whole struct, which `DisplayConfigGetDeviceInfo` fills (at most `size` bytes). + if unsafe { DisplayConfigGetDeviceInfo((&raw mut source).cast::()) } != 0 { + continue; + } + if until_nul(&source.viewGdiDeviceName) != wanted { + continue; + } + let mut color = DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO { + header: DISPLAYCONFIG_DEVICE_INFO_HEADER { + r#type: DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO, + size: size_of::() as u32, + adapterId: p.targetInfo.adapterId, + id: p.targetInfo.id, + }, + ..Default::default() + }; + // SAFETY: as above, for `color`. + if unsafe { DisplayConfigGetDeviceInfo((&raw mut color).cast::()) } != 0 { + return None; + } + // SAFETY: the union's two views are a bit field and the same 32 bits as a `u32`; every + // bit pattern is a valid `u32`. + let flags = unsafe { color.Anonymous.value }; + return Some(managed(flags)); + } + None + } + + #[cfg(test)] + pub fn desktop_window() -> isize { + // SAFETY: `GetDesktopWindow` takes nothing and returns the desktop's handle. + unsafe { windows_sys::Win32::UI::WindowsAndMessaging::GetDesktopWindow() as isize } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn no_window_is_unknown() { + assert_eq!(monitor_color(0), MonitorColor::Unknown); + } + + #[test] + fn hostile_handles_never_crash() { + // not windows: unknown, or (Windows answers the nearest monitor) a profile or managed + for h in [1isize, -1, 0x7fff_ffff, isize::MIN, isize::MAX] { + let _ = monitor_color(h); + } + } + + #[test] + fn advanced_colour_flags_decide_who_manages_colour() { + // supported only (an SDR desktop on an HDR-capable monitor): the app converts + assert!(!managed(0b0001)); + assert!(!managed(0)); + // HDR on / Auto Color Management (advanced colour enabled), or wide colour enforced + assert!(managed(0b0011)); + assert!(managed(0b0101)); + // forced off (bit 3) alone + assert!(!managed(0b1000)); + } + + #[test] + fn an_unreadable_advanced_colour_state_is_unknown_rather_than_a_profile() { + assert_eq!(settled_by_windows(Some(true)), Some(MonitorColor::ManagedByWindows)); + assert_eq!(settled_by_windows(Some(false)), None, "an SDR desktop: the monitor's profile decides"); + // Windows may be converting already: a profile on top would convert twice + assert_eq!(settled_by_windows(None), Some(MonitorColor::Unknown)); + } + + #[test] + fn utf16_text_stops_at_its_nul() { + assert_eq!(until_nul(&[65, 66, 0, 67]), &[65, 66]); + assert_eq!(until_nul(&[65, 66]), &[65, 66]); + assert_eq!(until_nul(&[0, 65]), &[] as &[u16]); + } + + /// The desktop's monitor has an answer, and a profile it names is a file that exists. + #[cfg(windows)] + #[test] + fn the_desktop_monitor_names_a_profile_that_exists_or_windows_manages_colour() { + let answer = monitor_color(win32::desktop_window()); + eprintln!("the desktop's monitor: {answer:?}"); + match answer { + MonitorColor::Profile(p) => assert!(p.is_file(), "{}", p.display()), + MonitorColor::ManagedByWindows | MonitorColor::NoProfile => {} + MonitorColor::Unknown => lightcraft_testkit::skip!(System, "no monitor answers for the desktop window (a session without a display)"), + } + } +} diff --git a/docs/architecture.md b/docs/architecture.md index aec9a51a20..904a9d1789 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -13,7 +13,7 @@ L5 depends on egui, eframe, winit or rfd, and that each crate only uses lower la | Layer | Crates (lines) | Role | |---|---|---| -| L0 | `geom` (1.4k), `color` (0.9k), `raster` (0.8k), `tiff` (2.0k), `fetch` (1.4k), `sysmem` (0.1k) | Matrices and warps, colour spaces and transfer functions, float image buffers, TIFF/IFD read and write, pinned HTTPS model downloads, the one `unsafe` FFI call (`malloc_zone_pressure_relief`) | +| L0 | `geom` (1.4k), `color` (0.9k), `raster` (0.8k), `tiff` (2.0k), `fetch` (1.4k), `sysmem` (0.1k), `wincolor` (0.3k) | Matrices and warps, colour spaces and transfer functions, float image buffers, TIFF/IFD read and write, pinned HTTPS model downloads, and the two crates with `unsafe` FFI: `malloc_zone_pressure_relief` (macOS) and the Win32 calls that read the window's monitor profile (Windows) | | L1 | `raw` (22.3k), `codecs` (7.3k), `meta` (4.3k), `develop` (2.5k), `denoise-core` (2.2k), `denoise` (2.7k), `faces` (5.3k), `scenes` (1.0k), `heif` (2.1k, optional) | Raw decoders and demosaic, DNG colour model; standard codecs and encoders; EXIF/XMP/IPTC; the non-destructive edit model and control specs; AI denoise; face detection and recognition; procedural demo photos; HEIC | | L2 | `pipeline` (9.8k) | The develop pipeline: scene-referred float, resolution independent; the CPU reference (oracle) for everything else | | L3 | `catalog` (11.0k), `gpu` (5.1k), `preview` (1.3k), `merge` (3.8k), `segment` (2.3k) | Library model and persistence; wgpu compute twin of the pipeline; thumbnail/preview cache and job pool; HDR and panorama merge; SAM 3 segmentation | diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 43ff7a7175..4f25582349 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -89,7 +89,7 @@ filmstrip is visible. | `engine.commands` | — | Engine + UI commands: id, label, menu, shortcut, params doc, enabled | | `ui.menu.list` | — | Menu entries (flat: id, label, menu path, shortcut, enabled) | | `ui.menu.tree` | — | The menu bar as shown (File … Help): items `{id, params?, label, shortcut?, enabled, checked?}`, separators, submenus — the model behind the native macOS menu bar and the in-window menus | -| `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why, `gpuWindowDevice` / `screenTextures` / `mainOnGpu` = renders run on the window's device / can be drawn from the GPU / the loupe shows one now — see `docs/gpu-pipeline.md`), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file; OK = `button:noticeOk`), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight as the activity stack in the top-left corner shows it, same shape as `activity.list`; a row appears once its task is 0.5 s old, ids `activity:row:`, ✕ = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | +| `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why, `gpuWindowDevice` / `screenTextures` / `mainOnGpu` = renders run on the window's device / can be drawn from the GPU / the loupe shows one now — see `docs/gpu-pipeline.md`, `loupeSteps` = how the loupe showed each photo it was stepped to, measured on the frames it drew: `{steps: [{photo, anyMs, anySource, fullMs, fullSource, sharpMs, dwellMs}], total, current}` — ms from the step to the first frame with anything of the photo, with a full-size picture (`embedded` camera JPEG, `cached` or `render`), and with LightCraft's own render; `dwellMs` is how long it stayed, the latest 256 steps; `total` counts every step finished since launch, a cursor that keeps rising when old steps leave the list; `thumbsMade` = photos given a grid thumbnail since launch (never lowered when old thumbnails are evicted, unlike `thumbTextures`); `previewCache` = the rendered-preview cache: `memEntries` / `memBytes` in memory, the disk cache's `diskHits`, `diskMisses`, `diskWrites` and `diskBudget` (bytes; all `null` without a library on disk), and `loupeEdge` (px, the loupe's longest edge, the size standard previews are built at)), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file, or once per session the drive holding the preview cache running low; OK = `button:noticeOk`, and the low-drive notice's `button:noticeSettings` opens Settings ▸ Performance), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight as the activity stack in the top-left corner shows it, same shape as `activity.list`; a row appears once its task is 0.5 s old, ids `activity:row:`, ✕ = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | | `ui.widgets` | `{filter?}` | On-screen widgets `{id, rect: [x, y, w, h]}` (screen points) | | `ui.clickWidget` / `ui.dragWidget` / `ui.hoverWidget` | `{id, count?, button?, fx?, fy?}` (`button: "right"` right-clicks; `count` is capped at 16) / `{id, toX?, toY?, dx?, dy?, steps?}` (steps are capped at 1000) / `{id, fx?, fy?}` | Real egui input on a widget (hover: the pointer rests on it, e.g. for preset/profile previews). `fx`/`fy` are fractions of the registered rect and may lie outside `[0,1]`; the resulting point must still be inside egui's clipped interaction rect, and a non-finite fraction or resolved point is rejected before any input is queued. Geometry comes from the latest completed layout; if the widget moves before the first event or before a press, or its latest clipped rect no longer contains the point, the request fails with an error instead of clicking another widget or retargeting. A target below an ordinary modal dialog may succeed as a no-op or a backdrop click, because egui routes that input to the dialog; a target covered by a non-modal overlay fails. The blocking library-problem/launch-list window is explicit: its dim takes the modal layer, but a background target fails instead of reporting a no-op success, and only that window's own controls (`button:library…`) pass. Its creation frame is shielded and redrawn with empty input like a prompt's, so background text/pointer input cannot act while the new modal areas settle. A quit prompt or settings notice is a real egui modal scope with a foreground backdrop. Only its own buttons (`button:quit…`, `button:noticeOk`) accept a `ui.clickWidget`; background targets fail, and background keystrokes, text/clipboard input, wheel/zoom input and AccessKit actions are dropped before panels see them. The prompt itself takes Tab/Shift+Tab, Enter/Space on the focused button, and Escape/Enter for the safe default Cancel; AccessKit Focus/Click works when targeted at a prompt button. Its first creation frame (including a Tasks→Unsaved or notice→next-notice transition) is shielded and redrawn with empty input, so a press/release in that frame, or a held press from before it, cannot act underneath it; a synthetic drag already in progress is canceled. Once settled, raw `ui.click`/`ui.drag`/`ui.pointer` and backdrop clicks are still delivered to the prompt backdrop as no-ops, and the prompt's own button clicks work normally. The area/layer check cannot see a different widget covering the point in the same layer. A `ui.clickWidget` whose widget disappears before its release also fails, after canceling the pointer press without a click or drag (the same rules apply when a click spans several host frames) | | `ui.move` / `ui.click` / `ui.drag` | `{x, y, count?, button?}` / `{x, y, toX, toY, steps?}` | Raw pointer input, screen points (the same click and step caps apply). In every pointer and scroll gesture a number other than `count` and `steps` must lie between −1,000,000 and 1,000,000, or the request is refused and queues nothing | diff --git a/docs/denoise.md b/docs/denoise.md index 64354e805a..cfba062c10 100644 --- a/docs/denoise.md +++ b/docs/denoise.md @@ -6,15 +6,134 @@ preserves Amount and mixes none of the cleaned picture. It affects only the requ photo, independently of Auto Sync, and is undoable. Manual luminance and colour noise reduction remain separate controls. -If no model is selected, turning it on opens **Settings ▸ AI Denoise** without changing -the photo. After installation, the pending request enables the original photo even if -the selection changed. Cancel the pending action in Settings. Cancelled downloads, -deleted or relinked photos, switching libraries and quitting cancel the request. -An active slider gesture finishes before the pending action resumes. +## The built-in denoiser -## Models and terms +AI Denoise needs no set-up. Unless you choose a model of your own (below), it runs the +**built-in denoiser** (`crates/denoise-core/src/builtin.rs`, id `builtin`): it measures +the photo's noise level once, from blocks of all four colour planes spread over the whole mosaic (variance = +a · signal + b; see [How the noise is measured](#how-the-noise-is-measured)), turns the noise into unit variance with a variance-stabilising transform, +and cleans the four Bayer planes together with block-matching collaborative filtering +(`crates/denoise-core/src/bm3d.rs`, after the published BM3D / CBM3D method). The four planes are rotated +into a brightness plane and three colour-difference planes; 4 × 4-cell blocks of the brightness plane that look alike +are stacked into groups (the colour planes follow the same matches, so colour noise is cleaned with the brightness). +Each stack is transformed (a 2-D DCT of every block, a Haar transform across the stack), small coefficients are +removed, and the blocks are put back with weights; a second step matches blocks again on that cleaner estimate and +shrinks by a Wiener filter built from it. How hard it thresholds follows the photo's noise: gently at low noise, to +keep fine detail, and harder as the noise grows. It then demosaics with +edge-directed green and colour-difference red and blue. It is written for +LightCraft, pure Rust, MIT OR Apache-2.0, has no weights and no download, and uses the +same tiling, cache, queue, preview and export path as a model. Its tile is 256 cells with a +16-cell overlap. The filter (the grouping, the transforms and the putting back, which are nearly all of its work) runs on +the graphics card when there is one that agrees with the processor and is faster (`crates/gpu/src/bm3d.rs`, WGSL kernels +in `crates/gpu/src/wgsl/bm3d_*.wgsl`); measuring the noise, the variance-stabilising transform and the demosaic stay on the +processor. The card is set up for the first photo that may use it, like a model's: its kernels are built, a check tile is +run on both devices and the card's filter must match the processor's to within a third of a noise deviation at the +worst place and a thousandth on average (they differ by the rounding of the arithmetic: a few blocks whose match or +threshold falls either side of a tie change by about a tenth), and both are timed. Settings ▸ AI Denoise ▸ Run on chooses +Automatic (the card where it is faster), Graphics card or Processor, and says where it runs; a set-up that crashed or ran out +of time is not tried again until you choose (Try the graphics card again). A tile the card gets wrong is run on the +processor, and three stop the card for the session. On an RTX 4080 SUPER a tile takes 22 ms on the card against 408 ms on one +processor thread, and the 1536 × 1024 benchmark crop 0.13 to 0.24 s against 1.0 to 2.1 s on four threads, with the very +same scores. A change +to the algorithm bumps `builtin::VERSION`, so cached pictures are made again. The id +`builtin` is reserved: a model with that id is refused. It is a classical filter, not a +trained network, so a good model can still do better on very noisy files. The earlier +non-local-means filter (`crates/denoise-core/src/nlm.rs`) is still there as a fallback +(`Tuning::bm3d = None`). Why block matching and not something else: see [Why block matching](#why-block-matching). -**No model weights are bundled.** Models live in the per-user `denoise-models` folder +To measure a change to it, run the opt-in benchmark on a public CC0 raw (see `cargo xtask corpus`): +`LC_DENOISE_RAW="$(git rev-parse --show-toplevel)/corpus/raw/arw-sony-a7m3-compressed.arw" LC_DENOISE_OUT=/tmp/dn cargo test --release -p lightcraft-engine --test denoise_builtin_quality -- --ignored --nocapture` +(the path must be absolute: tests run from the crate's folder). +It adds noise of four known levels to the raw, runs the denoiser and prints the PSNR against the +original, plus a texture figure (how much of the true picture's fine structure the result keeps; noise +can't inflate it); `LC_DENOISE_OUT` also writes truth | noisy | denoised PNGs. Use public files only. +`LC_B_N`, `LC_B_STEP`, `LC_B_S`, `LC_B_K`, `LC_B_T1`, `LC_B_T2`, `LC_B_LOFF` (added to every point of the threshold curve), +`LC_B_SIG` and `LC_B_WIENER` +override the matching `bm3d::Params` field for a sweep; `LC_NLM=1` runs the non-local-means filter instead (then +`LC_S1`, `LC_S2`, `LC_HL`, `LC_HH`, `LC_H2`, `LC_LIGHT`, `LC_HEAVY`, `LC_SC`, `LC_HC`, `LC_P1`, `LC_P2`, +`LC_LOOSE` and `LC_FEW` override its `nlm::Tuning` fields). +PSNR and texture trade off (smoothing more raises one and lowers the other), so judge a change on both and on the +crops. On the Sony A7 III crop (PSNR gain over the noisy picture in dB / texture, light, medium, heavy, extreme noise): +non-local means +3.70 / 0.62, +7.22 / 0.42, +9.69 / 0.22, +10.37 / 0.09; block matching +4.28 / 0.58, +7.60 / 0.44, ++10.04 / 0.22, +10.62 / 0.12, in about the same time (1 to 2 s for the 1536 × 1024 crop on 4 cores). `LC_GPU=1` (with +`--features denoise`) runs the block-matching filter on the graphics card instead: the same scores in 0.13 to 0.24 s on an +RTX 4080 SUPER. The tests `lightcraft-gpu` `bm3d::tests` (the card against `bm3d::filter` on synthetic tiles, shared between +threads) and the engine's `gpu_tests` (set-up check, fallback after wrong tiles, the processor chosen, a marker left behind) +need a graphics card and record a skip without one. + +### Why block matching + +The built-in filter was chosen by measuring, on the benchmark above (the public Sony A7 III crop with noise of four known +levels; PSNR gain over the noisy picture in dB / texture), not by taste. Candidates, all written from the published +papers (no GPL code), in the order tried: + +| Filter | light | medium | heavy | extreme | Time per crop (4 CPU threads) | +|---|---|---|---|---|---| +| Non-local means (the first built-in) | +3.70 / 0.62 | +7.22 / 0.42 | +9.69 / 0.22 | +10.37 / 0.09 | 1.1–1.7 s | +| **Block matching, hard threshold then Wiener (BM3D / CBM3D)** | **+4.28 / 0.58** | **+7.60 / 0.44** | **+10.04 / 0.22** | **+10.62 / 0.12** | 1.1–2.1 s | +| Weighted nuclear norm minimisation (WNNM), best setting per level | +4.68 / 0.56 | +8.14 / 0.39 | +10.04 / 0.22 | +10.35 / 0.15 | 15–20 s | + +- **Block matching beats non-local means** on PSNR at every level and on texture at medium, heavy and extreme noise + (only light noise keeps slightly less: 0.58 against 0.62, for 0.6 dB more). The crops show more needle and branch detail + and no colour blotches or isolated specks. It costs about the same on the processor. +- **WNNM**, the strongest classical method we know of (singular values of each group of blocks shrunk with weights), + gains about 0.4 dB at light noise and 0.03 of texture at medium and extreme, and nothing at heavy noise, for about ten + times the processing time (a 24 MP photo would take about five minutes on the processor, against about a quarter of a + minute). Its singular values came from Jacobi rotations of each group's Gram matrix; more iterations, a smaller feedback + and 6 × 6 blocks (115 s a crop) did not help. Not kept. Untried: patches over all four planes at once (about fourteen times + the work per group). +- **What the tuning showed** (for whoever changes it): the hard threshold has to rise with the noise (`Params::lambda` is a curve + of the noise's deviation at mid-grey against the threshold: 1.2 at 0.0028, 1.9 at 0.0062, 2.3 at 0.0094, 2.65 at 0.0152, 3.2 at + 0.038, 3.5 at 0.14; a fixed value wins at one level and loses at another, see + [Fitted on real cameras](#fitted-on-real-cameras)); a higher + threshold on the colour planes than on the brightness plane hurts both PSNR and texture, because the colour differences + carry real signal; 4 × 4 blocks beat 3, 5, 6 and 8 on quality (3 × 3 is a little faster, 6 × 6 and 8 × 8 much slower); the + match tolerances and the group size (16 against 8 or 32) barely matter; a search of 8 cells and a step of 3 cost 0.1 dB + against 12 and 2 and keep the + processor as fast as non-local means. The Wiener step adds a little over the hard threshold alone. +- **The first benchmark's limit:** its noise is synthetic and white, and its reference (a public raw's own mosaic) has noise of + its own, which hides what happens at the low noise levels of real cameras. Real high-ISO raws also have correlated, + low-frequency colour noise and banding, which none of this measures; judge a change to the real thing by eye on a + high-ISO raw too. + +### How the noise is measured + +`builtin::estimate_noise` reads `(a, b)` of a photo (variance = `a · signal + b`, signal in 0..1 after black and white +levels) from the picture itself, so no camera table is needed. Each of the four colour planes is read separately (they sit at +different levels in a raw), cut into 12 × 12-cell blocks, and a second-difference operator (`[1 -2 1; -2 4 -2; 1 -2 1]`, which +cancels flat and smoothly sloping signal; white noise has `36 σ²` of variance through it) gives each block's variance; texture +and edges only add to it. At each brightness (about 300 blocks of each) the quietest 5 % of blocks are the noise, divided by +the bias of that quantile of pure noise (0.67, measured by +`denoise_noise_estimate::a_quantile_of_pure_noise_blocks_is_a_known_fraction_of_the_true_variance`), and a line is fitted +through the points. The first version mixed the colour planes in each block and took the lower quarter of a plain +neighbour difference: it read the picture's texture as noise, never below about 0.003 at mid-grey whatever the +true noise (`estimate_noise_v1`, kept to compare). On 30 different public pictures with known noise added, the ratio of +estimated to true deviation at mid-grey, at the ISO 6400 level of a Canon R-series body (0.0094), had a 10th to 90th percentile of +0.97 to 1.29 against 0.94 to 1.96 for the first version, and at the ISO 1600 level (0.0062) 0.99 to 1.45 against 0.97 to 2.77 +(`LC_CORPUS= cargo test --release -p lightcraft-engine --test denoise_noise_estimate -- --ignored --nocapture`). +A picture with no flat area at all still reads somewhat high, never low. + +### Fitted on real cameras + +A Canon EOS R, EOS R6 Mark III, M50 Mark II and some EF-era bodies were measured on a private library of about 8,400 raws +(only aggregates were kept; no photo is in the repository). The deviation of the noise at mid-grey (the measure the filter +judges a photo by) was about 0.0024 to 0.0028 at ISO 400 and below, 0.005 to 0.006 at ISO 500 to 1600, 0.009 to 0.010 at ISO 2000 +to 6400, 0.015 to 0.018 at ISO 8000 to 25600 and 0.038 above that: far lower than the first benchmark's levels (0.024 to +0.14), so a filter tuned on those was too gentle exactly where these photos live. The curve above was fitted on clean low-ISO +photos of those cameras with noise of their measured levels added (`LC_REAL=1`; `LC_FULL=1` measures the noise on the whole +frame, as the app does). Against the first estimator with a constant threshold of 1.9, averaged over 10 EOS R and 5 R6 Mark III +photos, the output reached (PSNR in dB, EOS R / R6 Mark III): ISO 400 level 43.76 / 44.93 (from 43.27 / 44.66), 1600 41.03 / 41.86 +(41.05 / 41.82), 6400 39.93 / 40.69 (39.30 / 39.74), 25600 38.36 / 38.86 (36.18 / 36.21) and 51200 level 33.83 / 34.45 +(28.42 / 28.78), with the noise left in the result ("detail" above 1) falling from 1.3 to 3.1 down to 0.73 to 0.99. The threshold +at each level is the lowest that stays within about a quarter of a decibel of the best, so texture is kept (on the EOS R at the +25600 level the texture figure is 0.28, against 0.25 at the highest-PSNR threshold). The first estimator also cost PSNR by itself: told the true +noise instead of its estimate, the same filter did the right thing at every level; the new estimator is as good as that from +ISO 6400 up. + +## Models and terms (optional) + +**No model weights are bundled.** Choosing a model replaces the built-in denoiser; **Stop using** +(or removing the model) goes back to it. Models live in the per-user `denoise-models` folder (override with `LIGHTCRAFT_DENOISE_MODELS`). Settings provides **Install from file…** for a user-supplied ONNX file with a `denoise-model.json` beside it. The default build offers no model downloads. The separate `rawnind-model` Cargo feature enables the diff --git a/docs/display-profiles.md b/docs/display-profiles.md index 67892a3cbb..1a63ce7de5 100644 --- a/docs/display-profiles.md +++ b/docs/display-profiles.md @@ -16,17 +16,31 @@ have one share it; otherwise, and without colord, previews stay sRGB (choose a p that colour-manages windows itself with the same profile (KWin with an ICC profile set in Display Configuration) would correct twice; KWin keeps that profile in its own settings, not colord, so this only happens when both are set. +**Windows uses the profile it assigns to the monitor showing the window** (Settings ▸ System ▸ Display ▸ Color +profile, Color Management, or a calibrator) while none is chosen. On an SDR desktop Windows passes what an app draws to +the monitor unchanged, so without it a wide-gamut monitor shows sRGB previews oversaturated and a calibration is +ignored. `crates/wincolor` finds the monitor the window is mostly on and asks Windows Color System for its default +profile, in the user's scope when they chose per-user profiles for that monitor, else the system's. It is asked about +once a second, so moving the window to another monitor and changing the profile in Windows are both followed without +a restart. (GDI's `GetICMProfileW` keeps answering the profile a process first saw, so it is only the fallback when the +monitor's device can't be found.) With no profile assigned, previews are sRGB. **While Windows colour-manages the +desktop itself** (HDR on, or Auto Color Management on Windows 11: its advanced-colour state, from +`DisplayConfigGetDeviceInfo`), it treats an ordinary app's output as sRGB and converts it for the monitor, so previews +stay sRGB rather than be converted twice. So do they when that state can't be read (Windows 10 before 1709, a driver +that doesn't report it). The log says which applies (`screen profile: …`) whenever it changes. + ## Using it Settings ▸ Display ▸ **Choose Profile…** picks an `.icc` / `.icm` file (the dialog opens where the system keeps -them: `~/.local/share/icc` on Linux, ColorSync's folders on macOS, `…\spool\drivers\color` on Windows). **Use sRGB** -(on macOS and Linux **Use Screen Profile**) goes back to no profile. The choice is an app setting (`ui.json`, `displayProfile`) +them: `~/.local/share/icc` on Linux, ColorSync's folders on macOS, `…\spool\drivers\color` on Windows). **Use Screen +Profile** (in hosts without one, **Use sRGB**) goes back to no profile. The choice is an app setting (`ui.json`, `displayProfile`) and applies at once; a file that can't be used is reported there and previews stay sRGB. Agents and scripts: `app.displayProfile {"path": "/path/to/monitor.icc"}` (`""` or `null`: none; no `path`: report only) returns `{path, description, kind: "matrix" | "lut", primaries: {red, green, blue: [x, y]}}`; the screen's -profile (macOS or Linux, none chosen) reports `path: null, screen: true`. Hosts supply it as `Services::screen_profile` -(`apps/lightcraft/src/screen_profile.rs`, `apps/lightcraft/src/colord.rs`); headless sessions have none and stay sRGB. +profile (none chosen) reports `path: null, screen: true`. Hosts supply it as `Services::screen_profile` +(`apps/lightcraft/src/screen_profile.rs`, `apps/lightcraft/src/colord.rs`, `apps/lightcraft/src/win_screen_profile.rs`); +headless sessions have none and stay sRGB. ## How it works @@ -55,5 +69,6 @@ LUT-based profile's correction about 65 ms. Drafts during slider drags skip the ## Not yet -- Picking up the profile Windows assigns (WCS: needs FFI, so an isolated `unsafe` helper crate) and X11's - `_ICC_PROFILE`; following the window across monitors on Linux and Windows (macOS does both, above). +- X11's `_ICC_PROFILE`, and following the window across monitors on Linux (macOS and Windows do both, above). +- Windows' advanced-colour profiles (what a monitor uses while Auto Color Management is on): LightCraft leaves colour + to Windows then. diff --git a/docs/gaps.md b/docs/gaps.md index 566786a5f0..1424cb5b78 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps: where LightCraft falls short of Lightroom -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-05 · **Change:** minor (Contrast and Blacks calibrated in process V4, #523; PERF-STEP-STALL: flags, ratings and edits never wait for the drive; before: gap 1: the Canon EOS D60 is the first chart-calibrated model, its matrices from our own ColorChecker shots give its white balance a Kelvin scale; gap 20: Canon CRW decodes; LR-LIB-VIRTUALCOPY: default number exhaustion is validated before copy creation; gap 8: lens profile work is tracked in #329; gap 8: lensfun's lens database offered on the first launch and downloaded on request, looked up for the library; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; typed GPS input now rejects malformed coordinates before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in coordinates, elevations and timestamps; malformed references error; CDATA stays literal; ranked gaps unchanged; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; import: checked rename-sequence exhaustion; import review: remembered thumbnail size and density-aware previews (#2237, part of #2056); pre-import loupe/keyboard culling remains open; no ranked gap closes; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 9: CI runs the tests on Linux x64 since #2667; macOS, Windows and the GPU equivalence tests still don't; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 8: Sony ILCE-7RM6 in-file distortion conversion extends to the APS-C ILCE-6700; LR-META-EXIF-FULL rejects extra EXIF clock components and preserves date fallbacks; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; JPEG ICC APP2 sequence validation; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 24: extreme brush segments skip the intermediate dabs; **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-20 · **Change:** minor (gap 15: Print Page Options — page numbers, page info, crop marks) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-05 · **Change:** minor (gap 22: Windows previews follow the monitor's profile; gap 11: the built-in denoiser now uses block-matching collaborative filtering (better PSNR than non-local means at every noise level) and runs it on the graphics card when there is one; gap 11: AI Denoise works out of the box with a built-in denoiser; gap 26: culling uses built previews, background preparation per mode; before: Contrast and Blacks calibrated in process V4, #523; PERF-STEP-STALL: flags, ratings and edits never wait for the drive; gap 1: the Canon EOS D60 is the first chart-calibrated model, its matrices from our own ColorChecker shots give its white balance a Kelvin scale; gap 20: Canon CRW decodes; LR-LIB-VIRTUALCOPY: default number exhaustion is validated before copy creation; gap 8: lens profile work is tracked in #329; gap 8: lensfun's lens database offered on the first launch and downloaded on request, looked up for the library; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; typed GPS input now rejects malformed coordinates before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in coordinates, elevations and timestamps; malformed references error; CDATA stays literal; ranked gaps unchanged; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; import: checked rename-sequence exhaustion; import review: remembered thumbnail size and density-aware previews (#2237, part of #2056); pre-import loupe/keyboard culling remains open; no ranked gap closes; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 9: CI runs the tests on Linux x64 since #2667; macOS, Windows and the GPU equivalence tests still don't; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 8: Sony ILCE-7RM6 in-file distortion conversion extends to the APS-C ILCE-6700; LR-META-EXIF-FULL rejects extra EXIF clock components and preserves date fallbacks; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; JPEG ICC APP2 sequence validation; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 24: extreme brush segments skip the intermediate dabs; **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-20 · **Change:** minor (gap 15: Print Page Options — page numbers, page info, crop marks) Every known shortfall, one entry each, ranked by user impact (how many Lightroom users hit it, and how hard it blocks them), then by effort. **Agents pick work from the top** (the first entry nobody is @@ -25,7 +25,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 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**: 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) | +| 11 | **Enhance: Raw Details, Super Resolution; trained denoise weights and X-Trans** | ENH rows 0%; denoise Bayer only; the built-in denoiser is classical (block-matching collaborative filtering), RawNIND weights GPL and opt-in | Fujifilm users get no AI denoise; very noisy files gain less than from a trained model | 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) | | 14 | **HDR display** (EDR / Windows HDR); the headroom limit and SDR rendition from `crs` XMP (the HDR switch, `HDREditMode`, is read). HLG AVIF export done; the display's SDR/HDR decision is tested, blocked on eframe's 8-bit surface | HDR rows 70%; LR-VIEW-HDR-DISPLAY ⬜ | HDR editing works blind on HDR monitors | 12–25 | [hardware-parity](hardware-parity.md) | @@ -37,10 +37,10 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 20 | **Long-tail raw formats**: compressed SRW, ARQ pixel shift, IIQ, Hasselblad compression, X3F, 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) | +| 22 | **Pen pressure on macOS / Linux tablets** (brush size and flow follow pressure where winit reports a pen force), follow-window colour on Linux (Windows reads the monitor's profile from Windows Color System and follows the window, macOS the screen's, Linux colord's) | hardware-parity.md | brush users with tablets; multi-monitor setups | 9–18 | [hardware-parity](hardware-parity.md) | | 24 | **Brush live preview and masking feel** (#517, #518); Feather / Edge mask refinement (15.5) | issues | masking feels slower than Lightroom; extreme brush segments now skip the intermediate dabs | 8–12 | [ui-parity](ui-parity.md) | | 25 | **File writes**: AVIF import; Render to DNG as a catalog command (lossy DNG and the Render to DNG export format landed) (PSD export landed with Edit in PhotoCraft, #953) | file-format-parity.md | interchange edge cases | 19–34 | [file-format-parity](file-format-parity.md) | -| 26 | **Performance at scale**: flags, ratings and edits are written and synced to the catalog log by a thread of its own, so a key never waits for a busy drive (a 300 ms sync: 0.2 ms per flag, was 305 ms), and a write that fails is held, retried and counted as unsaved, never dropped (PERF-STEP-STALL); 85k-photo library opens in 1.7–4.7 s; 100k grid test pending; colour NR at half resolution; at 100k photos stack and album lookups are indexed (an "In a Stack" or "Album" smart album counts in ~14 ms, was 0.6–2.7 s) | ROADMAP log, gpu-pipeline.md | large-catalog users | 15–30 | [target-app-parity](target-app-parity.md#by-dimension) | +| 26 | **Performance at scale**: flags, ratings and edits are written and synced to the catalog log by a thread of its own, so a key never waits for a busy drive (a 300 ms sync: 0.2 ms per flag, was 305 ms), and a write that fails is held, retried and counted as unsaved, never dropped (PERF-STEP-STALL); 85k-photo library opens in 1.7–4.7 s; 100k grid test pending; colour NR at half resolution; at 100k photos stack and album lookups are indexed (an "In a Stack" or "Album" smart album counts in ~14 ms, was 0.6–2.7 s); culling a wedding: first photos of a 2,933-raw folder in 0.9 s and camera JPEGs ready ahead of each step, but a full-size 45 MP camera JPEG still takes ~150 ms to decode (held-arrow stepping at a 2,560 px loupe can outrun it), the 100 % view of the raw itself still takes ~5 s to render (the camera JPEG is shown at 100 % meanwhile, ~0.9 s), and browsing or importing still reads and hashes every raw whole (~10 ms a file on SSD, ~1 s a 25 MB file from a NAS); the loupe uses built previews and photos are prepared ahead and the whole view in the background (face detection, AI masks and denoise are not yet part of that preparation) | ROADMAP log, gpu-pipeline.md | large-catalog users | 15–30 | [target-app-parity](target-app-parity.md#by-dimension) | | 27 | **Windows / Linux runtime coverage**: the Windows x64 installer is verified on Windows 11 (0.9.1: install and upgrade end on the completion page, a custom folder is kept, Launch works, removal is clean), but uninstalling from Settings → Apps ends with no confirmation (#892, #931); GPU path proven on Apple and on one AMD GPU on Linux (Radeon 8060S, Vulkan); NVIDIA, Intel and DX12 unverified; Windows DirectComposition VRR workaround implemented, monitor verification pending; the Linux riscv64 tarball (new in 0.6.0, #844) is cross-compiled and never run beyond a QEMU smoke test | ROADMAP, issues, `release.yml` | non-Mac users find bugs first | 13–27 | [hardware-parity](hardware-parity.md) | | 29 | **HDR merge leftovers** (LR-MERGE-HDR): AI Denoise doesn't run on merged (linear) DNGs; JPEG brackets are treated as linear (no camera response curve); every frame is held as 32-bit float, ~0.86 GB per 67 MP frame (half-float frames would halve it) | tested on Sony A7R VI brackets 2026-10-14 ([merge.md](merge.md)); Lightroom's Denoise supports HDR DNGs | HDR shooters who denoise their merges, merge JPEGs, or merge 7+ frames of high-resolution raws on 16 GB machines | 10–20 (+ denoise linear-RGB contract, gap 11) | [merge](merge.md) | | 28 | **Small Classic shortcuts and keys**: Tab / ⇧Tab (hide the side panels / all panels; Tab moves the keyboard focus here) and F5. Rating `[` `]`, flag cycling (`` ` ``), `\` (Filter Bar), ⌘L (Enable Filters), ⌘⌥⇧C / ⌘⌥⇧V (Copy / Paste Metadata), F1 help, F6 / F7 / F8 (filmstrip, left panel, right panel) are bound; the grid-cycle key is shown beside both grid rows in View (#2500) | [ui-parity](ui-parity.md#shortcuts) | Classic muscle memory | 2–4 | [ui-parity](ui-parity.md) | @@ -90,6 +90,8 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | Gap 26: the loupe shows built previews (they were rendered again), photos ahead and the whole view are prepared in the background with settings per mode; gap not closed | +| 2026-10-27 | minor | Gap 26: culling speed measured and improved (progressive Local browse, camera previews made ahead, a CR3's smallest covering JPEG, camera JPEG first at 100 %); what is left listed; gap not closed | | 2026-11-02 | minor | PERF-STEP-STALL: the catalog log is written and synced off the UI thread, so stepping and flagging never wait for the drive (a 300 ms sync: slowest flag 0.2 ms, was 305 ms); a failed write is held and retried, counted as unsaved, never dropped; gap 26 not closed | | 2026-10-28 | minor | Gap 8 shrinks: the desktop app offers lensfun's lens database (CC BY-SA, pinned) once on the first launch and downloads it on request and looks the library's raws up when it arrives; validation, a profile picker and own calibration remain | | 2026-10-23 | patch | Gap 8: the Sigma 10–18 mm on the ILCE-6700 gets a measured lens exception at 10–10.5 mm (0.55 px worst over 99 photos, was about 1.4 px) | @@ -101,6 +103,9 @@ 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-24 | minor | AI Denoise measures a photo's noise by colour channel and ignores texture, and sets its strength from it (fitted on real Canon EOS R / R6 Mark III noise levels: up to 5.5 dB closer to the original at ISO 51200, 2.2 to 2.7 dB at ISO 25600); gap 11 unchanged | +| 2026-10-24 | minor | The built-in denoiser filters with block-matching collaborative filtering instead of non-local means (+0.25 to +0.6 dB on a public raw with added noise) and runs that filter on the graphics card where there is one (6 to 10 times faster per photo on an RTX 4080 SUPER, the same picture); gap 11 still stands (no X-Trans, no trained weights) | +| 2026-10-23 | minor | AI Denoise runs out of the box with a built-in pure-Rust denoiser; gap 11 no longer says nobody gets denoise without installing a model | | 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) | @@ -119,6 +124,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-22 | minor | Gap 30 added: multi-select metadata editing — Info panel and All Metadata dialog show one photo's values with no mixed-value indication | | 2026-10-22 | patch | LR-MAP-TRACKLOG: GPX coordinate attributes and point text decode XML references; malformed / unknown references return errors; CDATA remains literal; ranked gaps unchanged | | 2026-10-21 | minor | Gap 28 shrinks: F8 shows / hides the right panel (`view.rightPanel`); rating `[` `]`, flag cycling and F1 help were already bound, so the entry lists only filter-bar keys, Tab / ⇧Tab and F5; 2–4 h (was 4–8) | +| 2026-10-20 | minor | Gap 22 shrinks (11–22 → 9–18 h): on Windows, previews follow the profile Windows Color System assigns to the window's monitor (sRGB while Windows colour-manages the desktop: HDR, Auto Color Management) | | 2026-10-20 | minor | #2362: import destination albums use the shared hierarchy/search picker instead of a flat name list; existing import workflows retained; ranked gaps/readiness counts unchanged | | 2026-10-19 | minor | Gap 9 shrinks: `.github/workflows/ci.yml` runs `cargo xtask ci` on Linux x64 for every PR and push to main; macOS and Windows remain | | 2026-10-19 | minor | Gap 21: Indonesian (`id`) shipped with every catalog message but What's New; four new languages left (Hindi, Arabic, Korean, Vietnamese), 135–239 h | diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index 6e063e6f90..506f8fd929 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -91,6 +91,14 @@ leaves them apart. The transposed convolution's merged store ran right on that c `nn::tests::a_layer_stores_every_pixels_channels_where_the_next_reads_them` catches the fault on such a card; `a_transposed_convolution_stores_every_pixels_channels_where_the_next_reads_them` checks the other store exactly. +FXC also cannot address two things the WGSL looks harmless with, and answers with `X3550 … forcing loop to unroll` +and then `X3511 unable to unroll loop` (the shader module fails, so the pipeline is never made): an array handed to a +function through a pointer (`ptr>`) that the function then indexes with a loop variable, and a vector +indexed with a loop variable on the left of an assignment (`acc[ch] = …` with `acc: vec4`). The block-matching +kernels (`wgsl/bm3d_*.wgsl`) keep their working arrays at module scope (`var`, one copy of the transforms +generated per array, `bm3d_transform.wgsl`) and accumulate in `array` instead. A GPU test that only records a +skip when the device cannot build the kernels hides this, so read the skip note (`cargo test … -- --nocapture`). + **Off the startup path.** The compute device is created on a background thread once the window is up (`gpu::warm_up` from the first frame's settings), and never while GPU rendering is off: with Settings ▸ Performance ▸ *Use the GPU for rendering* unchecked (applied before the window opens), @@ -428,6 +436,11 @@ view shows a GPU-resident draft reads that texture back for the picture (`Screen - The next and previous photos in filmstrip order are prepared in the background once the current one is rendered (decoded source kept, view render cached): stepping through photos shows the developed image in ~50 ms. +- Culling (PERF-CULL): the stand-ins of the next five photos in the direction of travel and the one + behind are made ahead (`render::Slot::QuickAhead`) and taken over at the step, so a step shows + the camera JPEG at once; while an arrow key is held (a photo left within 0.25 s) the raw render + of a photo waits until it has stayed 0.12 s, and a render queued for a photo already left is + dropped. `ui.inspect` → `perf.loupeSteps` times each step on the frames drawn. ## Memory (M5.6) A view's stages keep an uploaded source only up to 96 MB (a Preview-level source); a bigger one (the original a zoom window is cut from) is kept once, outside the views' stages, for all views of the photo (the Before and After windows and every pan share it; the Before window of a Before/After waits at first open until the After's job has handed the original over, or each would decode and upload its own copy) and given back when the app idles with no zoom window on screen (a zoomed view keeps it for its next pan: a 64 MP original is 800 MB to upload again; issue #323: kept per view it counted against the stage budget on every tick of a drag, and not kept every new window uploaded 288 MB again). diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index a6c63b816a..ed4ead9329 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (pen pressure for brush masks; monitor profile from colord on Linux); previously major (created from the code, gpu-pipeline.md and the parity checklist) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-20 · **Change:** minor (monitor profile from Windows Color System on Windows); previously major (created from the code, gpu-pipeline.md and the parity checklist) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 What Lightroom does with the machine's hardware, per platform, and what LightCraft does. Sources: [gpu-pipeline.md](gpu-pipeline.md), [display-profiles.md](display-profiles.md), [denoise.md](denoise.md), @@ -12,7 +12,7 @@ What Lightroom does with the machine's hardware, per platform, and what LightCra | GPU export | ✅ | ✅ (6000 × 4000 in ~0.3 s vs ~1.2 s CPU) | ✅ | ✅ | — | ✅ (black-export fix on an Intel iGPU, #78) | | AI on GPU / neural engine | Metal / DirectML / Core ML, model per feature | AI denoise on GPU or CPU (setting); SAM 3 on Metal via candle; faces on CPU | CPU / GPU denoise | CPU / GPU denoise | — | 🟡 no Core ML / Neural Engine / DirectML | | HDR (EDR) display | ✅ (macOS EDR, Windows HDR) | ⬜ | ⬜ | ⬜ | ⬜ | ⬜ (LR-VIEW-HDR-DISPLAY) | -| Monitor profile | automatic per display, follows the window | ✅ the screen's profile, followed across screens | 🟡 picked by hand (WCS needs FFI) | 🟡 colord's profile (one display, or all sharing one); no follow across monitors | — | 🟡 Windows OS profile not read; Linux per-monitor follow missing | +| Monitor profile | automatic per display, follows the window | ✅ the screen's profile, followed across screens | ✅ the profile Windows Color System assigns to the window's monitor, followed across monitors and profile changes; sRGB while Windows colour-manages the desktop (HDR, Auto Color Management) | 🟡 colord's profile (one display, or all sharing one); no follow across monitors | — | 🟡 Linux per-monitor follow missing | | Second window / second monitor | ✅ (Classic) | ✅ (⌘F11) | ✅ | ✅ | — | ✅ (Classic secondary-window keys missing) | | Pen pressure / tilt (brush masks) | ✅ pressure for size / flow | ⬜ winit reports no tablet pressure on macOS | 🟡 pen force from winit touch events (untested on a tablet) | ⬜ winit has no X11 / Wayland tablet input | 🟡 pointer-event force where winit passes it | 🟡 brush size and flow follow pen pressure wherever egui gets a touch force (Brush ▸ Pen Pressure); no tilt; macOS / Linux tablets wait on winit | | Trackpad gestures | pinch zoom, pan | ✅ pinch, two-finger pan | 🟡 (winit) | 🟡 | 🟡 | ✅ on macOS | @@ -27,7 +27,7 @@ What Lightroom does with the machine's hardware, per platform, and what LightCra **~40% ready** (estimated): the GPU editing path is real and fast (measured: 24 MP exposure drag 3.9 ms on GPU vs 22–42 ms CPU; NR drag 18 ms vs 301–471 ms), but HDR display, pen pressure, -tethering, printing, automatic monitor profiles and neural-engine inference are missing. GPU +tethering, printing, per-monitor profiles on Linux and neural-engine inference are missing. GPU correctness is proven on Apple GPUs and on one AMD GPU on Linux (Radeon 8060S, Vulkan / RADV: the equivalence suite passes with the same max 1–2 LSB as on Metal, [gpu-pipeline.md](gpu-pipeline.md#correctness-cpu-oracle-and-equivalence-tests)). NVIDIA, Intel and Windows DX12 still rely on user reports. @@ -37,18 +37,19 @@ NVIDIA, Intel and Windows DX12 still rely on user reports. | Work | Hours | Needs | |---|---:|---| | HDR display (EDR on macOS, Windows HDR, Linux where possible) | 10–20 | an HDR display to verify (human) | -| OS monitor profile: Windows WCS (an FFI helper crate, like `crates/sysmem`), follow the window across displays on Linux | 4–8 | multi-monitor setup | +| OS monitor profile: follow the window across displays on Linux | 2–4 | multi-monitor setup | | Pen pressure for brush masks: done where winit reports a touch force; macOS and Linux tablets need winit tablet events (or a pure-Rust tablet layer) | 3–8 | a tablet | | Remaining stages on GPU (defringe, spot removal, masks) | 10–20 | | | Tethered capture (PTP over USB in pure Rust, Canon / Nikon / Sony first) | 25–45 | cameras (human) | | Printing with colour management | 15–25 | printers (human) | | Neural-engine / DirectML inference for AI features | 10–20 | depends on the AI model decision | -| **Total** | **80–150 h** (the core set for beta, HDR display + monitor profile + pen pressure: 20–40 h) | | +| **Total** | **75–142 h** (the core set for beta, HDR display + monitor profile + pen pressure: 15–32 h) | | ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-10-20 | minor | Monitor profile: Windows reads the window's monitor profile from Windows Color System (`crates/wincolor`), sRGB while Windows colour-manages the desktop; verified on Windows 11 by setting and clearing a Display P3 profile while the app ran. Remaining monitor-profile work 4–8 h → 2–4 h | | 2026-10-12 | minor | Monitor profile: Linux reads the display profile from colord; macOS row reflects #787 | | 2026-10-12 | minor | CPU ↔ GPU equivalence suite run on an AMD Radeon 8060S (Vulkan, RADV, Linux): 16 tests / 135 cases pass, max 2 LSB, mean ≤ 0.0003; first GPU verified outside Apple | | 2026-10-12 | minor | Pen pressure: strokes record per-point pressure from egui touch force, scaling dab size and flow; per-platform status | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 7a2be8ca85..c0f53da5b3 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (LR-PROF-IMPORT: the user's own .dcp camera profiles import, checked on a real D750 profile against Lightroom; before: LRC-DEV-AUTOSYNC: white balance syncs on each photo's own scale, As Shot and Auto per photo; LR-LIB-FLAG: a flag or rating never waits for the drive, PERF-STEP-STALL; LRC-LIB-VISUALSEARCH: Find Similar Photos reads the photos on a worker thread, so a large library no longer freezes the window; LR-MASK-LINEAR: masks stay on the photo's content under lens corrections, Upright, Transform and Rotate; LR-IMP-FORMATS: the Canon CRW decoder is the shared craft-libs crate `craft-crw`; LR-PROF-CAMERACOLOR: chart-measured matrices for the Canon EOS D60, its white balance in Kelvin; CRW imports name their camera; LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; LR-LIB-ALBUM: album commands leave out photos the library no longer has and record nothing when they add nothing; LR-BEHAV-DRAGDROP: a right-click on a text field while photos are carried from the grid opens no Cut / Copy / Paste menu; LR-BEHAV-DRAGDROP: a right-click while photos are carried from the grid opens no context menu; LR-LIB-VIRTUALCOPY: default numbering is preflighted across the requested batch and explicit names bypass suffix allocation; LR-BEHAV-DRAGDROP: only the primary button drags photos out of the grid and drops them; KEYC-RATING: deleting a keyword while Enable Filters has the filter put aside no longer leaves an empty one there; LR-BEHAV-DRAGDROP: a drop's destination is named with its parent when another folder or album has the same name; LR-VIEW-FILMSTRIP: photos drag from the filmstrip to the same sidebar targets as from the grid; LRC-LIB-LIBFOLDERS: a deep row's count follows its name in a narrow panel; LR-FILT-FLAG / LRC-LIB-FILTERBAR: the flag toggles combine, Picked + Unflagged, #2588; LR-VIEW-PHOTOGRID, LR-VIEW-FILMSTRIP, LR-VIEW-COMPARE, LR-VIEW-SURVEY, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: the active photo's selection ring shows on light themes and in Compare, Survey and the face tiles, and needs a loaded thumbnail; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-LOCATION: Info GPS text is fully validated before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in point fields; malformed references error; CDATA stays literal; LR-BEHAV-ACCESS: the Thumbnail size control is a slider to screen readers; LR-BEHAV-ACCESS: the Detail photo is named with its file name; LR-VIEW-PHOTOGRID: the grid's empty-view message names its shortcut as this platform writes it and as it is bound; LR-BEHAV-ACCESS: the grid's date headers are named as they read; LR-BEHAV-ACCESS: the sidebar's disclosure triangles name their row; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K Set Keyword Shortcut and ⇧K; KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K Edit Keywords; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-FOLDERS: Local's built-in places (Pictures, Desktop, Downloads, Home) offer no Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; LRC-LIB-CATALOG-SWITCH: a library's catalog.snap or folder given at launch opens that library; LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the dialog makes a new preview each time it opens, also after a failed one, #2708; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-MISSING: `library.missing` from the control channel checks the files on a worker thread instead of the UI thread; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-CROP-AUTO: Auto straighten reads the vertical vanishing point and the horizon; LR-META-EXIF-FULL: reject extra EXIF clock components so invalid capture-time candidates fall through to valid metadata; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-XMP / LRC-MAP-TRACKLOG: malformed ISO times are not projected or matched; LR-IMP-FORMATS: JPEG ICC APP2 chunk validation; LR-BEHAV-TITLEBAR: a dialog leaves the title bar undimmed, as a macOS sheet does; LR-BEHAV-ACCESS: the bars are toolbars and the panels landmarks for screen readers; LR-BEHAV-ACCESS: every dialog and prompt is exposed as a dialog (a modal one, an alert dialog for the prompts); LR-BEHAV-ACCESS: icon-only buttons are named by their label, with the shortcut as the description; MENU-HELP-HELP: on macOS the Help menu is registered with the application only once the menu bar is installed (muda ignores the call before), so AppKit knows which menu is Help; LR-BEHAV-ACCESS: a slider's value field is named ` value`, with how to use it as its description; MENU-BAR: every shortcut the app shows on macOS lists its modifiers ⌃⌥⇧⌘, as the menu bar does; MENU-BAR: on macOS two menu rows that run the same command each get their own native row and label (File ▸ Export… and File ▸ Export with Preset ▸ Custom…; File ▸ New Album… and Photo ▸ Add to Album ▸ New Album…); LR-BEHAV-DIALOGS: a one-line prompt that is refused stays open and says why, and a New Folder on Disk says it was made; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-VIEW-HISTOGRAM: the shadow and highlight clipping buttons take their tile and chevron from the theme, so the chevron reads in every theme; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MASK-BRUSH: extreme brush segments skip the intermediate dabs; LR-MASK-BRUSH: with the mask overlay hidden, the stroke being painted no longer tints the photo) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (LR-LIB-PEOPLE: face boxes another app drew on the photo as stored land on the upright photo, #2674; LR-PREF-DISPLAY: Windows previews follow the monitor's profile; LR-EDIT-DETAIL-DENOISE: built-in denoiser uses block-matching collaborative filtering and runs it on the graphics card when there is one; LR-EDIT-DETAIL-DENOISE: built-in denoiser, no model needed; LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; before: LR-PROF-IMPORT: the user's own .dcp camera profiles import, checked on a real D750 profile against Lightroom; LRC-DEV-AUTOSYNC: white balance syncs on each photo's own scale, As Shot and Auto per photo; LR-LIB-FLAG: a flag or rating never waits for the drive, PERF-STEP-STALL; LRC-LIB-VISUALSEARCH: Find Similar Photos reads the photos on a worker thread, so a large library no longer freezes the window; LR-MASK-LINEAR: masks stay on the photo's content under lens corrections, Upright, Transform and Rotate; LR-IMP-FORMATS: the Canon CRW decoder is the shared craft-libs crate `craft-crw`; LR-PROF-CAMERACOLOR: chart-measured matrices for the Canon EOS D60, its white balance in Kelvin; CRW imports name their camera; LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; LR-LIB-ALBUM: album commands leave out photos the library no longer has and record nothing when they add nothing; LR-BEHAV-DRAGDROP: a right-click on a text field while photos are carried from the grid opens no Cut / Copy / Paste menu; LR-BEHAV-DRAGDROP: a right-click while photos are carried from the grid opens no context menu; LR-LIB-VIRTUALCOPY: default numbering is preflighted across the requested batch and explicit names bypass suffix allocation; LR-BEHAV-DRAGDROP: only the primary button drags photos out of the grid and drops them; KEYC-RATING: deleting a keyword while Enable Filters has the filter put aside no longer leaves an empty one there; LR-BEHAV-DRAGDROP: a drop's destination is named with its parent when another folder or album has the same name; LR-VIEW-FILMSTRIP: photos drag from the filmstrip to the same sidebar targets as from the grid; LRC-LIB-LIBFOLDERS: a deep row's count follows its name in a narrow panel; LR-FILT-FLAG / LRC-LIB-FILTERBAR: the flag toggles combine, Picked + Unflagged, #2588; LR-VIEW-PHOTOGRID, LR-VIEW-FILMSTRIP, LR-VIEW-COMPARE, LR-VIEW-SURVEY, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: the active photo's selection ring shows on light themes and in Compare, Survey and the face tiles, and needs a loaded thumbnail; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-LOCATION: Info GPS text is fully validated before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in point fields; malformed references error; CDATA stays literal; LR-BEHAV-ACCESS: the Thumbnail size control is a slider to screen readers; LR-BEHAV-ACCESS: the Detail photo is named with its file name; LR-VIEW-PHOTOGRID: the grid's empty-view message names its shortcut as this platform writes it and as it is bound; LR-BEHAV-ACCESS: the grid's date headers are named as they read; LR-BEHAV-ACCESS: the sidebar's disclosure triangles name their row; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K Set Keyword Shortcut and ⇧K; KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K Edit Keywords; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-FOLDERS: Local's built-in places (Pictures, Desktop, Downloads, Home) offer no Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; LRC-LIB-CATALOG-SWITCH: a library's catalog.snap or folder given at launch opens that library; LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the dialog makes a new preview each time it opens, also after a failed one, #2708; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-MISSING: `library.missing` from the control channel checks the files on a worker thread instead of the UI thread; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-CROP-AUTO: Auto straighten reads the vertical vanishing point and the horizon; LR-META-EXIF-FULL: reject extra EXIF clock components so invalid capture-time candidates fall through to valid metadata; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-XMP / LRC-MAP-TRACKLOG: malformed ISO times are not projected or matched; LR-IMP-FORMATS: JPEG ICC APP2 chunk validation; LR-BEHAV-TITLEBAR: a dialog leaves the title bar undimmed, as a macOS sheet does; LR-BEHAV-ACCESS: the bars are toolbars and the panels landmarks for screen readers; LR-BEHAV-ACCESS: every dialog and prompt is exposed as a dialog (a modal one, an alert dialog for the prompts); LR-BEHAV-ACCESS: icon-only buttons are named by their label, with the shortcut as the description; MENU-HELP-HELP: on macOS the Help menu is registered with the application only once the menu bar is installed (muda ignores the call before), so AppKit knows which menu is Help; LR-BEHAV-ACCESS: a slider's value field is named ` value`, with how to use it as its description; MENU-BAR: every shortcut the app shows on macOS lists its modifiers ⌃⌥⇧⌘, as the menu bar does; MENU-BAR: on macOS two menu rows that run the same command each get their own native row and label (File ▸ Export… and File ▸ Export with Preset ▸ Custom…; File ▸ New Album… and Photo ▸ Add to Album ▸ New Album…); LR-BEHAV-DIALOGS: a one-line prompt that is refused stays open and says why, and a New Folder on Disk says it was made; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-VIEW-HISTOGRAM: the shadow and highlight clipping buttons take their tile and chevron from the theme, so the chevron reads in every theme; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MASK-BRUSH: extreme brush segments skip the intermediate dabs; LR-MASK-BRUSH: with the mask overlay hidden, the stroke being painted no longer tints the photo) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -52,10 +52,10 @@ cited here still exists. Formerly docs/parity.md. | X. Cross-cutting behaviours (BEHAV) | 23 | 6 | 1 | 1 | 8/8 (100%) | 7/10 (70%) | | Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 78 | 4 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | -| Lightroom Classic extras | 41 | 25 | 21 | 8 | — | 24/26 (92%) | -| **Total** | 418 | 68 | 57 | 35 | 193/203 (95%) | 146/161 (91%) | +| Lightroom Classic extras | 41 | 26 | 21 | 8 | — | 24/27 (89%) | +| **Total** | 417 | 70 | 57 | 35 | 192/203 (95%) | 146/162 (90%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.2%** of 543 in-scope rows — P0 97.5% of 203 · P1 94.4% of 161 · P2 56.7% of 178. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.1%** of 544 in-scope rows — P0 97.3% of 203 · P1 94.1% of 162 · P2 56.7% of 178. ## Top gaps and shortcut notes @@ -78,11 +78,11 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-IMP-RAWDEFAULT | Raw defaults | P1 | ✅ | `cmd:library.preferences`, `crates/engine/src/import.rs`, `crates/ui-egui/src/dialogs/settings.rs` | LightCraft default / a preset / per camera (make + model); non-raw default too; the preset look counts as unedited and Reset returns to it | | LR-IMP-MIGRATE | Migrate other catalogs | OOS | 🚫 | | | | LR-IMP-PROFILES | Import profiles & presets | P1 | ✅ | `cmd:file.importPresets`, `cmd:preset.import`, `cmd:profile.import`, `crates/engine/src/preset_import.rs`, `crates/engine/src/preset_luminar.rs` | presets: .lcpreset, XMP, classic .lrtemplate (local adjustment templates become mask effects, LR-MASK-EFFECTS), photos carrying edits ("DNG presets"), Luminar looks (.lmp, .mplumpack collections; sliders with a counterpart), .zip bundles, folders (folder → group), drag & drop (an `.xmp` dropped together with its photo is that photo's sidecar and is not imported as a preset, issue #936); masks carried over; unmapped settings reported (fields that only describe the preset or photo, e.g. `Cluster`, `SortName`, `SupportsAmount2`, the as-shot white, empty Point Color slots, are not); profiles: .cube 3D LUTs (one toast reports both halves; a LUT that fails is named with its reason); a preset that names a profile (`crs:Look`) applies the imported profile of that name, imported before or after it, and Lightroom's basic profiles map to ours (`crates/engine/src/profile_refs.rs`, issue #1001); Adobe profile formats deliberately unsupported (so `.xmp` creative profiles' colour tables aren't read) | -| LR-IMP-LOCAL | Work on files in place | P0 | ✅ | `cmd:library.browse`, `cmd:photo.addToLibrary`, `cmd:library.import` (mode add), `cmd:local.addRoot`, `cmd:local.hide`, `cmd:local.restoreHidden`, `crates/engine/src/cmd/browse.rs`, `crates/ui-egui/src/panels/left.rs` (`local_section`), `crates/ui-egui/src/panels/grid.rs` (`folder_header`) | Local: browse Pictures / Desktop / Downloads / Home or any folder without adding it (breadcrumb, Include subfolders, Add N to My Photos); browsed photos stay out of All Photos, albums and counts (album commands skip them and the album menus say to Add to My Photos first, issue #684); folders picked with Browse Folder… (or Keep in Local / Add to Local on a folder row) stay listed across restarts, and browsing a folder inside a listed one highlights it inside that tree (opened down to it, siblings reachable) instead of adding a root; edits go to XMP sidecars; importing promotes them; right-click a top-level location → Remove from Local hides the shortcut only (nothing on disk or in the catalog changes), saved with the UI state, and “Show N hidden locations” (or Browse Folder… on it) brings it back, each on its own from the row's list when several are hidden, or all at once with Restore All (issue #2114); a folder is one location however its path is spelled (`/` or `\`, trailing separator, `.`/`..`, drive-letter case; `folder_key` in `crates/catalog/src/query.rs`); browsed photos nobody changed are forgotten once their folder has not been browsed for 30 days (Settings → Performance → Local folders, 0 = never; checked when the library opens, or `cmd:library.forgetLocal` with `dryRun`; files and sidecars stay, browsing again brings them back; see `crates/catalog/src/local.rs` for what counts as a change); browsing a folder again forgets at once the untouched records of its files that another app deleted or moved, so they no longer fail to load on every visit (issue #1392; changed ones stay, shown as missing); browsing a folder keeps the active photo when the folder shows it, else makes the folder's first photo active as it arrives, the same rule as albums and the other sources (`Session::keep_active_in_view`; issue #1447: before, a library photo stayed active, so Photo Grid marked nothing and Detail, the histogram and the info showed a photo the folder doesn't hold) | +| LR-IMP-LOCAL | Work on files in place | P0 | ✅ | `cmd:library.browse`, `cmd:photo.addToLibrary`, `cmd:library.import` (mode add), `cmd:local.addRoot`, `cmd:local.hide`, `cmd:local.restoreHidden`, `crates/engine/src/cmd/browse.rs`, `crates/ui-egui/src/panels/left.rs` (`local_section`), `crates/ui-egui/src/panels/grid.rs` (`folder_header`), `crates/engine/src/import.rs` (`browse_queue`) | Local: browse Pictures / Desktop / Downloads / Home or any folder without adding it (breadcrumb, Include subfolders, Add N to My Photos); the folder's photos join the view batch by batch while they are read, first screen first (`browse_queue`: newest file first for the default sort), so a 2,933-raw wedding folder shows its first photos in 0.9 s instead of after every file was read (30.6 s; the whole folder still takes ~30 s); browsed photos stay out of All Photos, albums and counts (album commands skip them and the album menus say to Add to My Photos first, issue #684); folders picked with Browse Folder… (or Keep in Local / Add to Local on a folder row) stay listed across restarts, and browsing a folder inside a listed one highlights it inside that tree (opened down to it, siblings reachable) instead of adding a root; edits go to XMP sidecars; importing promotes them; right-click a top-level location → Remove from Local hides the shortcut only (nothing on disk or in the catalog changes), saved with the UI state, and “Show N hidden locations” (or Browse Folder… on it) brings it back, each on its own from the row's list when several are hidden, or all at once with Restore All (issue #2114); a folder is one location however its path is spelled (`/` or `\`, trailing separator, `.`/`..`, drive-letter case; `folder_key` in `crates/catalog/src/query.rs`); browsed photos nobody changed are forgotten once their folder has not been browsed for 30 days (Settings → Performance → Local folders, 0 = never; checked when the library opens, or `cmd:library.forgetLocal` with `dryRun`; files and sidecars stay, browsing again brings them back; see `crates/catalog/src/local.rs` for what counts as a change); browsing a folder again forgets at once the untouched records of its files that another app deleted or moved, so they no longer fail to load on every visit (issue #1392; changed ones stay, shown as missing); browsing a folder keeps the active photo when the folder shows it, else makes the folder's first photo active as it arrives, the same rule as albums and the other sources (`Session::keep_active_in_view`; issue #1447: before, a library photo stayed active, so Photo Grid marked nothing and Detail, the histogram and the info showed a photo the folder doesn't hold) | | LR-IMP-SIDECAR-SPLIT | Separate XMP sidecar variants | P2 | ⬜ | `cmd:library.xmpPreferences` | sidecar naming option exists (stem/full), no split sidecars | +| LR-IMP-PREVIEW-READ | Preview reads the header, not the raw | P0 | ✅ | `crates/raw/src/preview.rs` (`bounded_preview`, `embedded_preview_from_range`, `embedded_preview_covering`), `crates/engine/src/files.rs` (`preview_window`), `docs/raw-preview-reads.md`, `crates/engine/src/files.rs` (`preview_window`, `planned_preview`), `crates/raw/src/sparse.rs` (`preview_plan`), `crates/raw/src/dng.rs` (`decode_reduced`), `crates/codecs/src/lib.rs` (`decode_jpeg_srgb8_fit`) | a grid thumbnail and a loupe preview of an unedited raw show the camera's embedded JPEG, which sits near the start of the file (a 24 MP Fuji RAF keeps its 5.6 MB JPEG in a 56 MB file), so the preview loader reads the header and that JPEG instead of the whole file: 56.5 MB → 5.9 MB and ~10 s → 0.96 s measured on one real RAF over a GVFS/SMB Wi-Fi share (byte-identical preview pixels; `LIGHTCRAFT_PROFILE=1` reports the bytes); the RAF pointer is read from its fixed header fields, a CR3's boxes and a TIFF raw whose preview tag sits past the prefix are read through `lightcraft_raw::sparse::preview_plan`, which names the ranges `embedded_preview` reads and nothing else; a cached render as stand-in, an edited photo and a raw without an embedded JPEG still render; the formats it cannot describe (CRW/MRW/X3F are found by scanning, NEF/ORF/PEF probe from samples) keep the whole-file path, and a lying pointer, a short read or a file that changes underneath us falls back to it rather than losing the preview. An unedited raw's **grid thumbnail is that camera JPEG itself**, so no sensor decode is scheduled behind it (`Session::embedded_thumb_is_final`, `grid::skips_the_real_render`): drawing a 512 px thumbnail used to decode the whole raw — 45 s a photo at 1.2 MB/s, 8.3 GB for a 149-raw folder — and the queue it built delayed the render the user was waiting for. Stand-ins and grid thumbnails decode the smallest embedded JPEG that covers the requested size and is a copy of the largest (aspect ratio within 1 %, same component count), not always the largest, on the whole-file and the plan route alike: an A7R VI's 1616 × 1080 JPEG (0.3 MB) instead of its 9984 × 6656 one (5.6 MB), mid-sized NEF / RW2 JPEGs, and a Canon CR3's 1620 px `PRVW` (or 160 px `THMB`) instead of its 8192 px JPEG track (`cr3_preview_box_list`; EOS R5 C at 1280 px: 168–322 → 31 ms a photo); a plain 8-bit sRGB camera JPEG decodes straight to 8-bit (`decode_jpeg_srgb8_fit`, no float image), and the decoded camera JPEG of an unedited raw is kept in the library's thumbnail cache, so a folder seen before fills from small files (250 R5 C raws: first screen 553 → 294 ms, second visit 610 → 53 ms); a DNG that keeps reduced-resolution copies of its LinearRaw image (Lightroom HDR/panorama merges) develops a thumbnail or preview from the smallest copy that covers it (512 px of a 23836 × 7078 pano: 38 s → 1.1 s) | | LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG (ICC APP2 sequences require unique complete chunks with consistent totals; malformed profiles use the existing unsupported-profile sRGB fallback; a Samsung panorama whose scan data runs into its SEF trailer with no end-of-image marker reads as the image before the trailer, while a JPEG cut short is still refused, issue #3350, `crates/codecs/src/jpeg.rs`), PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP (lossy wide-gamut JXL decodes to the right colours: jxl-oxide desaturated XYB rendered to P3/Rec. 2020, worked around in `crates/codecs/src/jxl.rs`); DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared primaries and transfer curve (linear, sRGB, BT.709 or a power; PQ / HLG stay preview-only) without clipping or gamut mapping, checked on one real file with 108 lossy tiles and on 2 Lightroom Classic 15.1 lossy LinearRaw DNGs (ILCE-7CM2) whose tiles declare Rec. 2100 primaries with the sRGB curve, which were preview-only before, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), CRW (CIFF, the 2000–2004 Canon bodies: clean-room-derived decode frozen in `craft-libs crates/crw/clean-room/02-crw-format.md`, `crates/raw/src/vendor/crw.rs`; EOS D30/D60/10D/300D, PowerShot G1 (10-bit GBRG) and G6 pixel-exact against a black-box reference on 28 of 29 corpus files incl. 18 private D60s; as-shot white balance from the ColorBalance record's ShotInfo-selected slot; black level from the darkest flat masked-border strip; rotation from ImageInfo; starting look fitted from the file's own embedded JPEG like CR2/CR3 (`camera_preview::file_local_look`), accepted on all 10 decodable public corpus files (holdout RMS 0.009–0.047), with the fitted matrix absorbing the white balance on the bodies without a ColorBalance record (D30, PowerShots); the PowerShot G5's anomalous entropy coding and the pre-CIFF compacts stay preview-only, and G2/G3/G4/Pro1/S-series decode unverified for lack of redistributable samples), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth but CFA and black unverified), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/vendor/kodak.rs`, checked on the one CC0 sample against its IFD0 thumbnail), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`, checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; an FFF has no colour matrix of its own and takes the camera's from the original 3FR header it embeds in tag `0xC51B`; neither carries a JPEG, so their uncompressed 8-bit RGB preview (1217 × 913 in the H4D-40 FFF, 218 × 218 in the CFV 3FR) is the embedded preview, handed on as a baseline TIFF, `crates/raw/src/vendor/hasselblad.rs`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Minolta / Konica Minolta MRW (the `\0MRM` block container: `PRD` sensor size, 12-bit packed or 16-bit-word storage and the RGGB / GBRG cell, `WBG` gains in cell order, the `TTW` TIFF for Exif and orientation, black 0 and white from the saturation plateau; `crates/raw/src/vendor/mrw.rs`, DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D checked on CC0 files against their previews), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (EOS R6 Mark III `ColorData` version 66: as-shot white balance and black level from the file, white level from the data, `docs/cr3.md`) (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8/RP, incl. RP 1.6× crop mode (`crates/raw/tests/it/cr3_corpus.rs`, `docs/cr3.md`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed ORF, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes, and the notices carry a Reload from Disk button; each flag is stamped with the app version that set it, and a library opened in another version rechecks its preview-only raws in the background, so a raw a newer release decodes is cleared without a manual Reload, issue #662, `library.recheckPreviewOnly`), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and the Kodak DCS Pro / DCS760C TIFFs (compression 65000): IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Sigma X3F (container recognised by magic, preview found by a structural JPEG scan), the Canon CRWs the decoder refuses (PowerShot G5, pre-CIFF compacts), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `crates/heif`, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate); folder discovery and file pickers include Sony SR2 and SRF, with the same extension list used by CLI/MCP: DSC-R1 SR2 decodes from sensor data; DSC-F828 SRF stays preview-only; transparency is flattened onto white, in linear light, where the working image is built (`to_working` in `crates/codecs/src/lib.rs`): renders, previews, exports and contact sheets no longer turn transparent areas black, issue #1212; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); the Hasselblad Lunar, a Sony NEX-7 under Make HASSELBLAD, decodes as an ARW: a HASSELBLAD file with Sony's raw coding (compression 32767 or tag `0x7010`) goes to the ARW reader, and the body for its `Tag2010` layout comes from the maker note's `SonyModelID`, checked on the CC0 4051 file, issue #1275; an uncompressed MOS, whose IFD0 is the 16-bit mosaic with no Make tag, is recognised by Leaf's data block `0x8606` instead of opening as a greyscale image of its mosaic, issue #1275), and any decode failure of a recognised raw, not only an unsupported variant Nikon 12-bit small RAW (D810 / D4S): packed Y0/Y1/Cb/Cr rows decode to linear RGB; header probes retain geometry without decoding pixels, and truncated strips are refused. Chroma gains are approximate. | | LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/it/corpus.rs`, `crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/evidence.tsv`, `docs/raw/coverage-sweep.tsv`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases and 4 pinned EOS R5 Mark II files (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; their white balance now comes from the encrypted `SR2SubIFD`'s `WB_RGGBLevels`, the gains the camera applied, which 14 bodies (DSLR-A450 … A700, NEX-3/5/C3, SLT-A33/A35/A55, ILCE-6001, UMC-R10C) had no other source for and which the maker-note estimate read before missed by up to 100 % on preset shots, issue #535, checked against ExifTool on 100 decoded ARWs from 87 Sony bodies; the encrypted SR2 black level is now read from its directory entry (the DSLR-A450/A500/A550/A700 read 354–975 instead of 512), checked on 126 ARWs from 97 Sony bodies, and downsized lossless M/S ARWs use their measured black level 1024 instead of 512, checked on 12 files from 4 bodies, issue #535, and on a fifth, the ILCE-7CM2 (issue #697: 0.5.0 rendered its lossless M file with that 512 pedestal, the darkest half of a dusk scene +11 L* and blue, the lamplight white; its darkest 0.1 % per channel sits at 1017/1020/1024, and with 1024 the render is within +3 L* of the camera JPEG; the body's compressed and uncompressed "M-size" files are Bayer at 4736×3132 with black 512, two public ones in the corpus); pre-2017 Sony bodies shot in the camera's 16:9 mode (ILCE-7SM2, DSLR-A580) now get the 16:9 crop of their camera JPEG instead of the whole 3:2 frame with padding columns, issue #535; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked; private Z 8 crop verified; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone); the D7100, whose data holds picture beyond the camera's frame, develops at Lightroom's frame (the camera JPEG's size) in full frame and 1.3x crop, so Lightroom crops line up (#1248).; CR2 white levels came from masked rows holding samples at 16383, so on the EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i), 1200D (Rebel T5) and 100D (Rebel SL1) clipped highlights sat at 81–98% of the range and were not treated as clipped, now taken from the active area only, issue #1272). Canon CRW verified pixel-exact on 6 bodies (D30, D60, 10D, 300D, G1, G6; 10 CC0 files in the corpus, `crates/raw/tests/it/corpus.rs`, plus 18 maintainer D60 files via the digest-pinned sample test of craft-crw in craft-libs (crates/crw/tests/samples.rs there); `craft-libs crates/crw/clean-room/03-verification.md`). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Pentax PEFs without area tags (KP, KF, K-3 Mark III, K-70, K-1, K-1 Mark II, K-S1, K-S2, 645Z) no longer keep their masked border: black, empty and saturated lines are trimmed against the maker-note BlackPoint, issue #1271, measured on 38 CC0 PEFs from 30 bodies.; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Canon PowerShot G9, which writes no `ColorData`, takes its as-shot white balance from the WBInfo row (`0x0029`) of the preset ShotInfo names, issue #1273, checked on 1 CC0 file against neutral areas of the camera JPEG (within 0.1 %).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Olympus E-10 (no ImageProcessing directory) takes its as-shot gains and its black level (`0x1012` in `0x102c` ValidBits units: 128 at 12 bits) from the main maker note, issue #1273: its render against the camera thumbnail goes from ΔE76 18.5 with a rejected fit to 11.5 with the fit accepted (measured by AlexChambers).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone), and the Nikon D90 likewise on 10 of 550 NEFs (42 filler columns on the right that developed as a pink band; green clips below red and blue).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Public raw.pixls.us coverage sweep (#1327): 30 more models verified on 40 CC0 files, with SHA-256 and FNV-1a sensor hashes pinned (`crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/coverage-sweep.tsv`; `docs/raw/coverage.py`: 515 → 545 verified rows). Render/reference luminance correlation is 0.6801 to 0.9998; eleven candidates excluded for identity, provenance or missing/mismatched reference images. Nikon D6 / Z 6 / Z 7 uncompressed and Z 8 HE variants remain preview-only. Own-matrix DNG tone differs from the camera JPEG (#1277); sensor verification is not colour calibration. | -| LR-IMP-PREVIEW-READ | Preview reads the header, not the raw | P0 | ✅ | `crates/raw/src/preview.rs` (`bounded_preview`, `embedded_preview_from_range`, `embedded_preview_covering`), `crates/engine/src/files.rs` (`preview_window`), `docs/raw-preview-reads.md`, `crates/engine/src/files.rs` (`preview_window`, `planned_preview`), `crates/raw/src/sparse.rs` (`preview_plan`), `crates/raw/src/dng.rs` (`decode_reduced`) | a grid thumbnail and a loupe preview of an unedited raw show the camera's embedded JPEG, which sits near the start of the file (a 24 MP Fuji RAF keeps its 5.6 MB JPEG in a 56 MB file), so the preview loader reads the header and that JPEG instead of the whole file: 56.5 MB → 5.9 MB and ~10 s → 0.96 s measured on one real RAF over a GVFS/SMB Wi-Fi share (byte-identical preview pixels; `LIGHTCRAFT_PROFILE=1` reports the bytes); the RAF pointer is read from its fixed header fields, a CR3's boxes and a TIFF raw whose preview tag sits past the prefix are read through `lightcraft_raw::sparse::preview_plan`, which names the ranges `embedded_preview` reads and nothing else; a cached render as stand-in, an edited photo and a raw without an embedded JPEG still render; the formats it cannot describe (CRW/MRW/X3F are found by scanning, NEF/ORF/PEF probe from samples) keep the whole-file path, and a lying pointer, a short read or a file that changes underneath us falls back to it rather than losing the preview. An unedited raw's **grid thumbnail is that camera JPEG itself**, so no sensor decode is scheduled behind it (`Session::embedded_thumb_is_final`, `grid::skips_the_real_render`): drawing a 512 px thumbnail used to decode the whole raw — 45 s a photo at 1.2 MB/s, 8.3 GB for a 149-raw folder — and the queue it built delayed the render the user was waiting for. Stand-ins and grid thumbnails decode the smallest embedded JPEG that covers the requested size and is a copy of the largest (aspect ratio within 1 %, same component count), not always the largest, on the whole-file and the plan route alike: an A7R VI's 1616 × 1080 JPEG (0.3 MB) instead of its 9984 × 6656 one (5.6 MB), and mid-sized NEF / RW2 JPEGs; a DNG that keeps reduced-resolution copies of its LinearRaw image (Lightroom HDR/panorama merges) develops a thumbnail or preview from the smallest copy that covers it (512 px of a 23836 × 7078 pano: 38 s → 1.1 s) | | LR-IMP-CULL-AT-IMPORT | Culling analysis at import | P2 | 🟡 | `cmd:photo.analyze` | run Assisted Culling on the imported photos (they're selected after an import); not automatic | | LR-IMP-MOVE | Move on import [Classic] | P1 | ✅ | `cmd:library.import` (`mode` move), `crates/engine/src/import_move.rs`, `crates/engine/src/tests/import_move.rs`, `crates/ui-egui/src/dialogs/import.rs` | Transfer ▸ Move with Copy's destination, folders (day / month / one folder / custom template), rename template and example destination; XMP sidecars (both namings) move along; each source is removed only after its destination is written (hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate, unchecked files keep their sources, taken names get -1, -2…, never overwritten; if the rename sequence runs out, later files are reported as failed and earlier completed moves remain catalogued; files already in the destination/library are added in place; sources that can't be removed (read-only card) are kept and reported (`kept`). Undo removes the photos from the library but leaves the moved files at the destination. No Copy as DNG while moving | | LR-IMP-DNG-CONVERT | Convert to DNG on import [Classic] | P2 | ✅ | `cmd:library.import` (`dng`), `crates/ui-egui/src/dialogs/import.rs` | copy imports: Raw files ▸ Copy as DNG (lossless; the card is untouched); the raw copy is removed only once its DNG is verified and on disk (issue #106) | @@ -104,7 +104,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-FLAG | Pick / reject flags | P0 | ✅ | `cmd:photo.pick`, `cmd:photo.reject`, `cmd:photo.unflag`, `cmd:photo.flag` | P pick, X reject, U clear; 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 | +| LR-LIB-PEOPLE | People / faces | P2 | 🟡 | `cmd:faces.detect`, `cmd:view.people`, `cmd:view.faceBoxes`, `cmd:photo.removeRegion`, `cmd:photo.setRegion`, `cmd:library.filter`, `crates/ui-egui/src/panels/people.rs`, `crates/catalog/src/query.rs` (`people`), `crates/engine/src/media.rs` (`face_job`), `crates/meta/src/xmp.rs` | MVP: named face regions read from XMP (MWG-RS, read-only, see `docs/xmp-interop.md`; clipped to the photo; Lightroom's `Rotation` of ±π/2 and π handled, mirrored orientations taken as written; boxes another app drew on the photo as stored (a sideways `AppliedToDimensions`, no `Rotation`) turned with the file's Exif orientation, #2674; boxes follow Rotate Left/Right and flips; a sidecar stating `mwg-rs:Regions`, even empty, replaces the photo's on re-read, one without leaves them) become cards in the People view (View ▸ People, or the People button in the toolbar): a close-up of the person's largest face, name and photo count; a click filters the grid (`person` in `library.filter`, `person:` search token, filter chip). Face boxes in the loupe can be switched off (View ▸ Face Boxes, toolbar) resized with eight drag handles and removed with the × shown on hover (catalog-only and undoable, one undo step per drag; the sidecar is never rewritten for either); no moving a box by dragging it yet. Photo ▸ Detect Faces (`cmd:faces.detect`) finds faces with the YuNet detector (pure Rust, about 200 ms a photo, matches OpenCV's own YuNet on a 45-photo test set; the 232 KB model is a one-time download offered in the same step, never part of LightCraft) and adds them as unnamed boxes; names are suggested from the faces already named (recognition models are opt-in downloads, run on the CPU in a background thread; a face is named only when you confirm it); a person's page shows their cropped faces and the unnamed faces that look like them (LRC-LIB-PEOPLE), with a user-triggered ↑ action or targeted A key to name all shown suggestions at or above one score in one undo step; with recognition on, a background scan finds faces in photos that have none and embeds every face (one to three worker threads, raws through their embedded preview); an Unnamed faces section orders faces by likeness and names a selected group at once; no separated clusters, no manual tagging, no writing regions back | | LR-LIB-STACK | Stacks | P1 | ✅ | `cmd:stack.group`, `cmd:stack.ungroup`, `cmd:stack.toggle`, `cmd:stack.setTop`, `cmd:stack.remove`, `cmd:stack.auto`, `cmd:photo.delete`, `crates/catalog/src/stacks.rs` | grid/filmstrip count badges (a click expands / collapses the stack, selected or not), expand/collapse (a click or double-click on a grid badge toggles the stack once, #2233), auto-stack by capture time; delete / remove folder drop the photo from the stack so `i/n` updates (#1493); no visual-similarity auto-stack | | LR-LIB-VERSIONS | Versions | P1 | ✅ | `cmd:version.create` | see section M | | LR-LIB-DELETE | Delete / Recently Deleted | P0 | ✅ | `cmd:photo.delete`, `cmd:photo.restore`, `cmd:photo.deletePermanently` | Delete and Delete Permanently retain surviving selected photos; if none remain, select the next visible survivor (previous at the end) in the current source/filter/sort; permanent deletion removes catalog records, not files on disk; Restore and Delete Permanently in the Photo menu and the photo context menus for photos in Recently Deleted (before, the UI had no way to restore); importing a file that is in Recently Deleted again restores the photo with its edits, rating and albums (issues #298, #706: before, the import skipped it as "already in the library" while the grid showed it deleted) — the review dialog checks it, badges it "Will be restored", counts it as "in Recently Deleted" rather than "already in the library", and its choice Restore them / Import as new / Leave them starts on Restore; with Leave them such a file starts unchecked and Check All and the file-type toggles leave it out, but a click still checks it and it is restored (issue #1285: before, the click did nothing and the "In Recently Deleted" badge was drawn over the checkbox, which now sits above it); dropped files restore too ("Restored 1 photo from Recently Deleted"); a deleted photo matched by content whose file is gone is relinked to the imported file; Photo ▸ Empty Recently Deleted (`cmd:library.emptyRecentlyDeleted`, one undo step, shown while the trash is the source); import takes `onDeleted` restore (default) / skip / fresh for files in the trash (`cmd:library.import`; the report lists `restored`, and with skip flags the duplicate `existingDeleted`); browsing a folder in Local (`cmd:library.browse`), Auto Import and a Lightroom catalog import never restore a deleted photo; no confirmation dialog, no auto-purge after N days (needs a deleted-at date in the catalog); Delete asks first ("Move this photo to Recently Deleted?") from the key, the Photo menu and the photo context menu, on by default and switched off in Settings ▸ General (#1239: before, it was off by default and the context menu never asked); no auto-purge after N days (needs a deleted-at date in the catalog) | @@ -125,7 +125,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). |---|---|---|---|---|---| | LR-VIEW-PHOTOGRID | Justified photo grid | P0 | ✅ | `cmd:view.photoGrid`, `cmd:library.groups`, `cmd:library.sort` (`group`), `crates/ui-egui/src/panels/grid.rs`, `crates/catalog/src/dates.rs` | grouped by capture / import / edit date (day headers “Wednesday, 30 September 2026 · 12 photos”, months or years when zoomed out, or a fixed day/month/year/none choice in the sort menu); sticky header; clicking a header selects its photos; stacks never split; scrolls to the active photo only when it changes (or the grid comes back on screen), never on its own; a mouse-wheel notch scrolls a third of the grid's height, in both grids, as in Lightroom Classic (`theme::WHEEL_STRIP_SHARE`; trackpads scroll the points they report); queued embedded thumbnail stand-ins follow viewport priority changes without another extraction (`crates/ui-egui/src/render.rs`, issue #348; full-app visual/timing verification pending); selected photos are ringed in the theme's colours (`Tokens::ring_active` / `ring_selected`, 3:1 or more against the grid in every theme): the active photo gets a 3 pt two-tone ring (a thin inner line against the photo, so it shows on a white photo too), the other selected photos a 1.5 pt ring; the empty view (an empty album or other source in a library with photos, or an empty Recently Deleted) names Import Photos' shortcut as the menu bar writes it and as bound (⌘⇧I on macOS, Ctrl+Shift+I elsewhere), and none when it is unbound | | LR-VIEW-SQUAREGRID | Square grid | P0 | ✅ | `cmd:view.squareGrid` | same date headers and selection rings as the photo grid | -| LR-VIEW-DETAIL | Single-photo view | P0 | ✅ | `cmd:view.detail`, `crates/ui-egui/src/panels/detail.rs` | a “Rendering…” pill at the bottom of the photo (widget `loupe:rendering`; above the Navigator when that is in the way) once a render has been on its way for 0.5 s with nothing new on screen: over a stand-in (the raw's embedded JPEG, a thumbnail), the previous render after an edit, or, zoomed in, the magnified frame waiting for its window; Before views watch their own renders. Always on (Lightroom Classic makes it a View Options choice). When the render fails behind a stand-in, a caution pill says “This photo can't be opened” (“Original offline · no smart preview” when that is why) with the reason on hover and for screen readers (widget `loupe:renderFailed`; `ui.inspect` → `loupe.failed`) | +| LR-VIEW-DETAIL | Single-photo view | P0 | ✅ | `cmd:view.detail`, `crates/ui-egui/src/panels/detail.rs` | a “Rendering…” pill at the bottom of the photo (widget `loupe:rendering`; above the Navigator when that is in the way) once a render has been on its way for 0.5 s with nothing new on screen: over a stand-in (the raw's embedded JPEG, a thumbnail), the previous render after an edit, or, zoomed in, the magnified frame waiting for its window; Before views watch their own renders. Always on (Lightroom Classic makes it a View Options choice). When the render fails behind a stand-in, a caution pill says “This photo can't be opened” (“Original offline · no smart preview” when that is why) with the reason on hover and for screen readers (widget `loupe:renderFailed`; `ui.inspect` → `loupe.failed`). While the camera's embedded JPEG is on screen a “Camera preview” label at the top right says so, with what that means on hover (widget `loupe:cameraPreview`), so colour isn't judged on it. Culling: the stand-ins of the next five photos in the direction of travel and the one behind are made ahead and taken over at the step (`render::Slot::QuickAhead`; EOS R5 C wedding: step to the camera JPEG p50 187 → 0 ms), decoded camera JPEGs stay in memory for a step back, zoomed in on an unedited raw the camera JPEG is shown at full size under the window render until that arrives (100 % in ~0.9 s instead of ~5.6 s, `render::Slot::QuickFull`), and while an arrow key is held the raw render waits until a photo stays 0.12 s (`crates/ui-egui/src/loupe_timing.rs`); `ui.inspect` → `perf.loupeSteps` times each step on the frames drawn | | LR-VIEW-EDIT | Edit view | P0 | ✅ | `cmd:panel.edit` | | | LR-VIEW-FULLSCREEN | Full-screen preview | P1 | ✅ | `cmd:view.fullScreenPreview`, `cmd:view.enterFullScreen` | photo on black, arrows step, Esc exits; ⇧⌘F window full screen | | LR-VIEW-FILMSTRIP | Filmstrip | P0 | ✅ | `cmd:view.filmstrip`, `crates/ui-egui/src/panels/detail.rs` | the photo context menu on right-click; the mouse wheel scrolls it sideways, a third of its width per notch as in Lightroom Classic (trackpads scroll the points they report); it follows the active photo only when that changes (centred if off screen), so a scrolled strip stays put; every selected photo has the selected background; selected photos with a loaded thumbnail also show a ring, the active one in the heavier two-tone ring and the others in the lighter one, in the theme's colours, as in the grid (a selected cell with no thumbnail, still loading or failed, has the background and no ring); a drag from a cell carries the selection (a photo outside it drags alone and replaces it; in Compare it drags alone and leaves the selection, the active photo and the pair as they are) to the same sidebar rows as a drag from the grid, and a click without movement works as before (it selects the photo; in Compare it goes to the active side, see LR-VIEW-COMPARE) | @@ -207,10 +207,11 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | 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) | +| 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, works out of the box with a built-in classical denoiser (block-matching collaborative filtering, `crates/denoise-core/src/builtin.rs`; its filter runs on the graphics card when there is one that is faster, `crates/gpu/src/bm3d.rs`), optional user-installed 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; there is no model set-up step to abandon (#922) | | LR-EDIT-DETAIL-RAWDETAILS | Improved demosaic toggle | P2 | ⬜ | | | | LR-EDIT-DETAIL-SUPERRES | Super resolution | P2 | ⬜ | | | | LR-EDIT-DETAIL-AISHARPEN | AI sharpen | OOS | 🚫 | | | +| LR-EDIT-DETAIL-HOTPIXELS | Hot pixel removal | P1 | ✅ | `check:detail.nrOutliers`, `crates/raw/src/hotpixel.rs`, `crates/engine/src/files/load.rs` (`load_bytes_now`), `cmd:app.hotPixelLimit` | Lightroom has no control for this. Here a box under Noise Reduction (raws only), on for newly imported raws and off for edits saved before it existed (issue #1345): single photosites far above all their same-colour neighbours are replaced in the mosaic before demosaicing; a point lit across neighbouring photosites (a star, a spark) is kept. A raw with more than 0.2 % of its photosites to replace (real light kept doesn't count) is left unchanged; Settings ▸ Performance ▸ Hot pixel limit sets the share (test `the_hot_pixel_limit_renders_afresh_only_the_photos_that_remove_hot_pixels`). Switching it decodes the raw again (tests `hot_pixel_box_is_on_for_new_raws_only`, `hot_pixel_box_decodes_the_raw_again`) | | 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, 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 | ) @@ -430,10 +431,10 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| | LR-PREF-GENERAL | General settings | P0 | ✅ | `cmd:app.settings`, `cmd:app.openLibrary`, `crates/ui-egui/src/dialogs/settings.rs`, `crates/ui-egui/src/panels/notices.rs` | General / Import / Performance / Display / Interface tabs; app settings in ui.json (written atomically, saved when the library changes and every few seconds), library settings in prefs.json; At launch: open the last library or ask (see LRC-LIB-CATALOG-SWITCH); a damaged settings file is kept as `.corrupt-