Merge raw-negative-channels (with main) into camera-colour-pushed-shadows

This commit is contained in:
robmdunn committed 2026-11-05 07:41:34 -05:00
commit 06358e583e
276 files changed
+27585 -1619

No files matched your search

+3
View File
@@ -14,3 +14,6 @@ plan/
# model weights are never committed (SAM 3: docs/ai-masks.md)
*.safetensors
*.safetensors.part
# Python tools import their public operator family.
__pycache__/
+10 -3
View File
@@ -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: #<issue>"]` (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).
+10 -3
View File
@@ -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: #<issue>"]` (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).
Generated
+31
View File
@@ -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",
@@ -3796,6 +3809,13 @@ dependencies = [
"webpki-roots",
]
[[package]]
name = "lightcraft-film"
version = "0.18.0"
dependencies = [
"libm",
]
[[package]]
name = "lightcraft-geocode"
version = "0.18.0"
@@ -4043,6 +4063,7 @@ dependencies = [
"lightcraft-slideshow",
"lightcraft-testkit",
"log",
"pollster 1.0.1",
"serde",
"serde_json",
"toml",
@@ -4058,9 +4079,11 @@ dependencies = [
"egui",
"js-sys",
"lightcraft-codecs",
"lightcraft-color",
"lightcraft-engine",
"lightcraft-preview",
"lightcraft-raster",
"lightcraft-raw",
"lightcraft-ui-egui",
"log",
"serde",
@@ -4070,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"
+5
View File
@@ -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" }
@@ -30,6 +31,7 @@ lightcraft-raw = { path = "crates/raw" }
lightcraft-codecs = { path = "crates/codecs" }
lightcraft-meta = { path = "crates/meta" }
lightcraft-develop = { path = "crates/develop" }
lightcraft-film = { path = "crates/film" }
lightcraft-lensdb = { path = "crates/lensdb" }
lightcraft-inpaint = { path = "crates/inpaint" }
lightcraft-scenes = { path = "crates/scenes" }
@@ -57,11 +59,14 @@ 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"] }
crc32fast = "1"
siphasher = "1"
libm = "0.2" # pure-Rust maths for lightcraft-film (target-independent results)
libc = "0.2" # dev-only: process CPU time in benches
dhat = "0.3" # opt-in heap profiling (lightcraft-cli --features dhat-heap) and heap tests; never in product builds
+585
View File
@@ -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<PathBuf, String> {
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<PathBuf, String> {
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<T>(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<Session, String> {
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::<usize>().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<PhotoId>) = 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<String> = 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<PhotoId> = 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<String> = 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<String> = 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::<Vec<_>>());
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<f64> = 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<f64> = 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<f64> = 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<String> = 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<String> = 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<PathBuf>) -> 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<u32> = (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::<u32>(&[], 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);
}
}
+9
View File
@@ -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 <model>.json to DIR (default: the profiles folder LightCraft reads,
<config>/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(())
+69
View File
@@ -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<u8>)> = 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");
+2
View File
@@ -80,3 +80,5 @@ heif = ["lightcraft-codecs/heif"]
[dev-dependencies]
egui = { workspace = true }
lightcraft-color = { workspace = true }
lightcraft-raw = { workspace = true }
+63 -3
View File
@@ -12,7 +12,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use lightcraft_engine::files::{load_bytes, probe_bytes};
use lightcraft_engine::files::{load_bytes_decoded, probe_bytes};
use lightcraft_engine::media::{FileLoader, FileProbe};
/// Prefix of the catalog paths of files kept in browser storage.
@@ -144,9 +144,11 @@ impl Originals {
/// Engine hooks that decode/probe from memory.
pub fn hooks(&self) -> (FileLoader, FileProbe) {
let s = self.clone();
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize| {
// (an imported camera profile is not applied on the web, as in the render worker: a raw keeps its own colour,
// whether it decodes in a worker or inline when workers are unavailable)
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, 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(&bytes, max_edge)
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| {
@@ -237,6 +239,64 @@ mod tests {
assert_eq!(out.image.width, 20);
}
/// CodeRabbit on #1063: without web workers a render runs inline and handed the selected camera profile to this
/// loader, which applied it, so the picture differed from the worker's (which keeps the raw's own colour, the
/// documented web behaviour). The loader now ignores it.
#[test]
fn the_web_loader_keeps_a_raws_own_colour_with_a_camera_profile() {
use lightcraft_raw::*;
let (w, h) = (32usize, 24usize);
let raw = RawImage {
format: RawFormat::Dng,
width: w,
height: h,
cpp: 1,
data: RawData::U16((0..w * h).map(|i| 256 + ((i % w) * 300 + (i / w) * 200) as u16).collect()),
cfa: Cfa::bayer("RGGB"),
bits: 14,
black: BlackLevel::uniform(256.0),
white: vec![16000.0],
active_area: Rect::new(0, 0, w, h),
crop: Rect::new(0, 0, w, h),
orientation: Orientation::Normal,
color: ColorData {
illuminant: [21, 0],
color_matrix: [Some(lightcraft_color::Mat3([[0.9, 0.2, -0.15], [-0.3, 1.25, 0.08], [0.02, -0.12, 0.85]])), None],
as_shot_neutral: Some([0.5, 1.0, 0.7]),
..Default::default()
},
wb_multipliers: None,
linearized: false,
pixel_aspect: 1.0,
opcodes: OpcodeLists::default(),
metadata: Default::default(),
lens_metadata: Default::default(),
};
let dng = write_dng(&raw, &DngWriteOptions::default()).unwrap();
// our own numbers: a matrix that swaps the camera's red and blue
let swap = lightcraft_color::Mat3([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]).mul(&lightcraft_color::Mat3([
[3.2406, -1.5372, -0.4986],
[-0.9689, 1.8758, 0.0415],
[0.0557, -0.2040, 1.0570],
]));
let profile = dcp::DcpProfile {
name: "Swap".into(),
camera_model: "LightCraft Test Camera".into(),
color: ColorData { illuminant: [21, 0], color_matrix: [Some(swap), None], ..Default::default() },
};
assert_ne!(
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, 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");
}
#[test]
fn download_names() {
assert_eq!(download_name("dir/x-lightcraft.png"), "x-lightcraft.png");
+7 -3
View File
@@ -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()?,
+3
View File
@@ -318,6 +318,7 @@ impl Workers {
loaded: None,
quick: None,
display: None,
frame: None,
};
g.done.push((b.slot, r, 0.0));
}
@@ -409,6 +410,7 @@ impl Workers {
loaded: None,
quick: None,
display: None,
frame: None,
},
ms,
));
@@ -463,6 +465,7 @@ impl RenderOffload for Workers {
loaded: None,
quick: None,
display: None,
frame: None,
};
g.done.push((slot, r, 0.0));
return None;
+3
View File
@@ -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"
+1 -29
View File
@@ -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<Vec<u8>> {
}
}
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<Vec<u8>> {
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();
}
}
+81 -2
View File
@@ -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 _;
@@ -79,7 +83,67 @@ fn app_icon() -> egui::IconData {
eframe::icon_data::from_png_bytes(png).unwrap_or_default()
}
struct App(LightcraftApp, PrefsWriter, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
struct App(LightcraftApp, PrefsWriter, Option<WindowTextures>, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
/// Draws renders that stayed on the GPU: registers their textures with the window's egui-wgpu
/// renderer (the GPU renderer runs on the window's device, see [`adopt_window_device`]).
struct WindowTextures {
device: eframe::wgpu::Device,
queue: eframe::wgpu::Queue,
renderer: std::sync::Arc<egui::mutex::RwLock<eframe::egui_wgpu::Renderer>>,
}
impl lightcraft_ui_egui::render::ScreenTextures for WindowTextures {
fn show(&mut self, frame: &lightcraft_engine::media::ScreenFrame, id: Option<egui::TextureId>) -> Option<egui::TextureId> {
let view = frame.texture.create_view(&Default::default());
let mut r = self.renderer.write();
let filter = eframe::wgpu::FilterMode::Linear;
Some(match id {
Some(id) => {
r.update_egui_texture_from_wgpu_texture(&self.device, &view, filter, id);
id
}
None => r.register_native_texture(&self.device, &view, filter),
})
}
fn free(&mut self, id: egui::TextureId) {
self.renderer.write().free_texture(&id);
}
fn read(&self, frame: &lightcraft_engine::media::ScreenFrame) -> Option<egui::ColorImage> {
match lightcraft_engine::gpu::read_texture(&self.device, &self.queue, &frame.texture, frame.width, frame.height) {
Ok(img) => Some(egui::ColorImage::from_rgba_unmultiplied([img.width, img.height], img.data.as_flattened())),
Err(e) => {
log::warn!("gpu: a view can't be read back for the screenshot: {e}");
None
}
}
}
}
/// Render on the window's device (off the UI thread: building the kernels takes a moment), so the
/// loupe's drafts are drawn straight from the GPU; the textures they leave are shown through
/// [`WindowTextures`] once that worked. Otherwise the GPU renderer makes a device of its own, as
/// before, and every render comes back as pixels.
fn adopt_window_device(rs: &eframe::egui_wgpu::RenderState, ctx: &egui::Context) -> WindowTextures {
let (device, queue, info) = (rs.device.clone(), rs.queue.clone(), rs.adapter.get_info());
let ctx = ctx.clone();
// before the first frame's GPU warm-up can start a device of its own
lightcraft_engine::gpu::set_window_device_pending(true);
let spawned = std::thread::Builder::new().name("lc-gpu-window".into()).spawn(move || {
match lightcraft_engine::gpu::adopt_window_device(device, queue, info) {
Ok(()) => log::info!("gpu: rendering on the window's device"),
Err(e) => log::info!("gpu: renders come back as pixels: {e}"),
}
ctx.request_repaint();
});
if let Err(e) = spawned {
log::warn!("gpu: {e}");
lightcraft_engine::gpu::set_window_device_pending(false);
}
WindowTextures { device: rs.device.clone(), queue: rs.queue.clone(), renderer: rs.renderer.clone() }
}
impl eframe::App for App {
fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
@@ -89,7 +153,7 @@ impl eframe::App for App {
}
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
if let Some(m) = self.2.as_mut()
if let Some(m) = self.3.as_mut()
&& m.update(&mut self.0, ctx)
&& lightcraft_ui_egui::panels::notices::may_close(&mut self.0)
{
@@ -109,6 +173,13 @@ impl eframe::App for App {
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
self.0.perf.host_frame_ms = frame.info().cpu_usage.map(|s| f64::from(s) * 1000.0);
// the GPU renderer adopted the window's device: its renders can be drawn as they are
if self.2.is_some()
&& lightcraft_engine::gpu::on_window_device()
&& let Some(t) = self.2.take()
{
self.0.renderer.set_screen_textures(Box::new(t));
}
self.0.ui(ui);
}
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
@@ -304,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() {
@@ -358,9 +430,16 @@ fn main() -> eframe::Result {
#[cfg(target_os = "macos")]
let menu =
(std::env::var_os("LIGHTCRAFT_NO_NATIVE_MENU").is_none()).then(|| native_menu::NativeMenu::install(&mut app, &cc.egui_ctx));
// the GPU renderer on the window's device, when GPU rendering is on
// (LIGHTCRAFT_GPU_WINDOW=0: a device of its own, renders read back - for comparison or a driver
// that misbehaves with compute and drawing on one device)
let window_device = std::env::var_os("LIGHTCRAFT_GPU_WINDOW").is_none_or(|v| v != "0");
let window_textures =
cc.wgpu_render_state.as_ref().filter(|_| gpu_on && window_device).map(|rs| adopt_window_device(rs, &cc.egui_ctx));
Ok(Box::new(App(
app,
writer,
window_textures,
#[cfg(target_os = "macos")]
menu,
)))
+87
View File
@@ -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<Vec<u8>> {
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<SystemTime>)>,
bytes: Option<Vec<u8>>,
}
#[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<Vec<u8>> {
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();
}
}
+5 -1
View File
@@ -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()
+3
View File
@@ -5,6 +5,7 @@ fn desktop_clear_color_stays_opaque_with_a_modal_open() {
let mut app = App(
LightcraftApp::new(Session::new(), Services::default()),
PrefsWriter::default(),
None,
#[cfg(target_os = "macos")]
None,
);
@@ -566,6 +567,7 @@ fn on_exit_ends_the_process_on_macos() {
let mut app = App(
app,
PrefsWriter::default(),
None,
#[cfg(target_os = "macos")]
None,
);
@@ -598,6 +600,7 @@ fn on_exit_removes_the_lock_owner_note() {
let mut app = App(
LightcraftApp::new(session, Services::default()),
PrefsWriter::default(),
None,
#[cfg(target_os = "macos")]
None,
);
+40
View File
@@ -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<lightcraft_ui_egui::ScreenProfileFn> {
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<MonitorColor> = 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(),
}
}
+11 -1
View File
@@ -154,6 +154,15 @@ pub fn base_options() -> WgpuConfiguration {
n.instance_descriptor.backend_options = backend::backend_options();
// no indirect-call validation pipeline: Intel Metal fails to compile it and the window never opens (#250)
n.instance_descriptor.flags = backend::instance_flags_from_env(n.instance_descriptor.flags);
// the GPU renderer may run on this device (`adopt_window_device`): it needs the adapter's
// buffer limits (a 24 MP photo is a 275 MiB buffer), not wgpu's defaults
let default = n.device_descriptor.clone();
n.device_descriptor = std::sync::Arc::new(move |adapter| {
if adapter.get_info().backend == wgpu::Backend::Gl {
return default(adapter);
}
wgpu::DeviceDescriptor { label: Some("lightcraft window"), required_limits: adapter.limits(), ..Default::default() }
});
}
c
}
@@ -192,7 +201,8 @@ fn probe(backends: Backends, compose_window: bool) -> Result<WgpuSetupExisting,
..Default::default()
}))
.map_err(|e| format!("no adapter: {e}"))?;
let base = if adapter.get_info().backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { wgpu::Limits::default() };
// (not GL: the adapter's own limits, which the GPU renderer needs when it adopts this device)
let base = if adapter.get_info().backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { adapter.limits() };
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("egui wgpu device"),
required_limits: wgpu::Limits { max_texture_dimension_2d: 8192, ..base },
+4
View File
@@ -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
+70
View File
@@ -0,0 +1,70 @@
//! Fault injection for the catalog log's writer thread (tests only: nothing in the product
//! installs a hook, and with none installed a check is one uncontended lock of an empty list).
//!
//! A test makes the drive under one library directory slow (a hook that sleeps) or failing (a
//! hook that returns an error) and proves that a flag never waits for it and that nothing handed
//! over is lost: `crates/catalog/src/tests_log_thread.rs`, `crates/engine/src/tests/slow_drive.rs`.
use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
/// Where the log thread is about to touch the drive.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Step {
/// Writing bytes to the log (or to the file that replaces it).
Write,
/// Syncing them.
Sync,
}
/// Runs before each [`Step`] in the hooked directory: an error fails that step.
pub type Hook = Arc<dyn Fn(Step) -> io::Result<()> + Send + Sync>;
static HOOKS: Mutex<Vec<(PathBuf, Hook)>> = Mutex::new(Vec::new());
/// Run `hook` before every write and sync of the catalog log in `dir` (replacing an earlier one).
#[doc(hidden)]
pub fn install(dir: &Path, hook: Hook) {
let mut hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
hooks.retain(|(d, _)| d != dir);
hooks.push((dir.to_path_buf(), hook));
}
/// Remove the hook of `dir`.
#[doc(hidden)]
pub fn remove(dir: &Path) {
HOOKS.lock().unwrap_or_else(PoisonError::into_inner).retain(|(d, _)| d != dir);
}
static ON_CALLER: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
/// Write the log in `dir` on the caller's thread, syncing before each append returns, as builds
/// before PERF-STEP-STALL did: a test's "before" (stores opened afterwards; the hooks run there too).
#[doc(hidden)]
pub fn write_on_caller(dir: &Path, on: bool) {
let mut dirs = ON_CALLER.lock().unwrap_or_else(PoisonError::into_inner);
dirs.retain(|d| d != dir);
if on {
dirs.push(dir.to_path_buf());
}
}
pub(crate) fn on_caller(dir: &Path) -> bool {
let dirs = ON_CALLER.lock().unwrap_or_else(PoisonError::into_inner);
!dirs.is_empty() && dirs.iter().any(|d| d == dir)
}
pub(crate) fn check(dir: &Path, step: Step) -> io::Result<()> {
let hook = {
let hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
if hooks.is_empty() {
return Ok(());
}
hooks.iter().find(|(d, _)| d == dir).map(|(_, h)| h.clone())
};
match hook {
Some(h) => h(step),
None => Ok(()),
}
}
+32 -2
View File
@@ -6,7 +6,10 @@
//! rename).
//! - `catalog.log` — JSON lines, one per op applied after the snapshot:
//! `{"seq":N,"crc":C,"op":{…}}` where `C` is the CRC-32 of the op's JSON text. Appends are
//! fsynced before [`Journal::append`] returns.
//! fsynced before [`Journal::append`] returns, except natively: [`crate::FsStore`] hands them to
//! a thread of its own that writes and syncs them in order right after (so a flag never waits
//! for the drive), holds and retries whatever fails ([`Journal::unwritten`]) and refuses later
//! appends meanwhile, so the log never has a gap and nothing handed over is dropped.
//!
//! Loading = snapshot + replay of the records with `seq > snapshot seq`. Recovery rules:
//! - a **torn final record** (crash mid-append: truncated line or bad CRC at the end) is dropped
@@ -195,6 +198,10 @@ pub struct Journal {
/// A failed append may have left part of its records after `log_bytes`, and cutting them off
/// failed too: the next append cuts the log back to `log_bytes` first.
tail_dirty: bool,
/// An append failed (natively that can be the store's own log thread failing to write records
/// handed over before, which it holds and retries): the next chance writes a snapshot, a fresh
/// file holding everything, in case only the log's file is broken.
snapshot_due: bool,
}
/// A background snapshot in flight.
@@ -383,6 +390,7 @@ impl Journal {
pending: None,
retry_at_records: 0,
tail_dirty: false,
snapshot_due: false,
};
let log = log.unwrap_or_default();
@@ -516,6 +524,7 @@ impl Journal {
self.tail_dirty = false;
}
if let Err(e) = self.store.append(LOG, buf.as_bytes()) {
self.snapshot_due = true;
// Part of the batch may be in the file. Cut it back to the last whole record, so the
// retry (same seqs) starts on a clean line instead of after a fragment that would
// read back as damage.
@@ -678,6 +687,7 @@ impl Journal {
}
fn record_snapshot(&mut self, t: SnapshotTiming) {
self.snapshot_due = false;
self.stats.snapshots += 1;
self.stats.last_snapshot = t;
self.stats.max_snapshot_ms = self.stats.max_snapshot_ms.max(t.total_ms);
@@ -697,6 +707,23 @@ impl Journal {
}
}
/// Wait until every appended record is in the file and synced (natively the store writes the
/// log on a thread of its own, [`crate::FsStore`]): before the files are read or copied from
/// outside. An error says why some aren't yet: they are held and retried, never dropped.
pub fn flush(&mut self) -> Result<()> {
self.store.flush().map_err(io)
}
/// Appended records the store holds because writing them failed (retried), and why; `None`
/// when nothing is held back. Never waits for the drive.
pub fn unwritten(&self) -> Option<(usize, String)> {
// a snapshot that holds every op holds whatever the log's thread still holds
if self.snapshot_seq >= self.seq && self.pending.is_none() {
return None;
}
self.store.unwritten()
}
/// Where persistence time went so far.
pub fn stats(&self) -> PersistStats {
PersistStats { snapshot_running: self.pending.is_some(), ..self.stats }
@@ -706,7 +733,10 @@ impl Journal {
pub fn wants_snapshot(&self) -> bool {
self.pending.is_none()
&& self.log_records >= self.retry_at_records
&& (self.log_records >= self.policy.max_records || self.log_bytes >= self.policy.max_bytes)
&& (self.snapshot_due
|| self.unwritten().is_some()
|| self.log_records >= self.policy.max_records
|| self.log_bytes >= self.policy.max_bytes)
}
pub fn seq(&self) -> u64 {
+7
View File
@@ -14,12 +14,17 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod dates;
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub mod fault;
pub mod folders;
mod index;
pub mod journal;
pub mod keywords;
pub mod local;
pub mod lock;
#[cfg(not(target_arch = "wasm32"))]
mod log_writer;
pub mod model;
pub mod query;
pub mod rules;
@@ -1490,6 +1495,8 @@ mod tests_journal;
mod tests_local;
#[cfg(test)]
mod tests_lock;
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests_log_thread;
#[cfg(test)]
mod tests_repair;
#[cfg(test)]
+377
View File
@@ -0,0 +1,377 @@
//! The thread that writes the catalog log for [`crate::FsStore`] (natively).
//!
//! An append hands its bytes over and returns; the thread writes them in order and makes each batch
//! durable (`sync_data`) before the next. The caller (the UI thread, for the app) never waits for
//! the drive: on Windows a write to a file waits for a sync of that file in flight, so with the log
//! written and synced on the UI thread every flag, rating and step waited for the drive, 30–90 ms
//! on a busy disk in a test and over a second on a photographer's machine while previews were
//! written.
//!
//! **Nothing handed over is ever dropped.** The store's log is the file's first `good` bytes (written
//! and synced) followed by `held`, the bytes handed over and not yet synced. A write or sync that
//! fails keeps `held` and retries it (on every later message, and every [`RETRY`] meanwhile), first
//! cutting the file back to `good` so a fragment of the failed write never stays in it. While a
//! failure stands, [`LogWriter::append`] refuses new bytes with the failure (the journal keeps those
//! records queued, as for any failed append) and [`LogWriter::unwritten`] says how many records are
//! held, so the app counts them as not saved and its quit prompt warns before anything could be
//! lost. Cutting the log back, replacing it and reading it act on that logical content, after
//! everything handed over before; the caller waits for them. Dropping the writer waits for
//! everything handed over and tries a last time.
use std::io::{self, Seek, Write};
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
/// How long a caller waits for the thread at most (a cut, a replace, a read, a flush).
const WAIT: Duration = Duration::from_secs(60);
/// How often held bytes are retried while a failure stands and nothing else arrives.
pub(crate) const RETRY: Duration = Duration::from_millis(500);
enum Msg {
Append(Vec<u8>),
Truncate(u64, Sender<io::Result<()>>),
Replace(Vec<u8>, Sender<io::Result<()>>),
Read(Sender<io::Result<Option<Vec<u8>>>>),
/// Reply once everything before is written and synced (or why it isn't).
Flush(Sender<io::Result<()>>),
}
/// What the caller can see without waiting.
#[derive(Default)]
struct Shared {
/// Why the held bytes couldn't be written (until they are, or the log is cut or replaced).
failed: Option<String>,
/// Records (lines) handed over and not yet written and synced, while `failed` stands.
held_records: usize,
}
pub(crate) struct LogWriter {
pub(crate) name: String,
tx: Option<Sender<Msg>>,
shared: Arc<Mutex<Shared>>,
thread: Option<std::thread::JoinHandle<()>>,
}
fn stopped() -> io::Error {
io::Error::other("the catalog log writer stopped")
}
fn not_written(why: &str) -> io::Error {
io::Error::other(format!("the catalog log could not be written: {why}"))
}
impl LogWriter {
/// A writer for `dir/name` (`None` when no thread can start: the store then writes itself).
pub(crate) fn start(dir: PathBuf, name: &str) -> Option<LogWriter> {
let (tx, rx) = channel::<Msg>();
let shared = Arc::new(Mutex::new(Shared::default()));
let sh = shared.clone();
let mut w = Writer::new(dir, name);
let thread = std::thread::Builder::new().name("catalog-log".into()).spawn(move || w.run(&rx, &sh)).ok()?;
Some(LogWriter { name: name.to_string(), tx: Some(tx), shared, thread: Some(thread) })
}
fn send(&self, m: Msg) -> io::Result<()> {
self.tx.as_ref().ok_or_else(stopped)?.send(m).map_err(|_| stopped())
}
fn ask<T>(&self, make: impl FnOnce(Sender<io::Result<T>>) -> Msg) -> io::Result<T> {
let (tx, rx) = channel();
self.send(make(tx))?;
rx.recv_timeout(WAIT).map_err(|e| match e {
RecvTimeoutError::Timeout => io::Error::new(io::ErrorKind::TimedOut, "the drive took over a minute to write the catalog log"),
RecvTimeoutError::Disconnected => stopped(),
})?
}
/// Hand `data` over (never waits for the drive). Refused while bytes handed over before can't
/// be written: the caller keeps `data` and appends it again later.
pub(crate) fn append(&self, data: &[u8]) -> io::Result<()> {
if let Some(why) = self.shared.lock().unwrap_or_else(PoisonError::into_inner).failed.clone() {
return Err(not_written(&why));
}
self.send(Msg::Append(data.to_vec()))
}
/// Cut the log to `len` bytes, after everything handed over; waits for it.
pub(crate) fn truncate(&self, len: u64) -> io::Result<()> {
self.ask(|r| Msg::Truncate(len, r))
}
/// Replace the log with `data` (atomically, durably), after everything handed over; waits.
pub(crate) fn replace(&self, data: &[u8]) -> io::Result<()> {
self.ask(|r| Msg::Replace(data.to_vec(), r))
}
/// The log as appended so far (written or still held), after everything handed over.
pub(crate) fn read(&self) -> io::Result<Option<Vec<u8>>> {
self.ask(Msg::Read)
}
/// Wait until everything handed over is written and synced; an error says why it isn't (the
/// bytes are still held and retried).
pub(crate) fn flush(&self) -> io::Result<()> {
self.ask(Msg::Flush)
}
/// Records handed over that can't be written yet, and why (`None`: nothing is held back by a
/// failure). Never waits.
pub(crate) fn unwritten(&self) -> Option<(usize, String)> {
let sh = self.shared.lock().unwrap_or_else(PoisonError::into_inner);
sh.failed.clone().map(|why| (sh.held_records.max(1), why))
}
}
impl Drop for LogWriter {
fn drop(&mut self) {
drop(self.tx.take());
if let Some(t) = self.thread.take() {
let _ = t.join();
}
}
}
/// The thread's side: the file and what is held for it.
struct Writer {
dir: PathBuf,
path: PathBuf,
tmp: PathBuf,
file: Option<std::fs::File>,
/// Bytes of the file written whole and synced (`None` until the file was first opened).
good: Option<u64>,
/// Handed over, not yet written and synced.
held: Vec<u8>,
failed: Option<String>,
}
fn lines(b: &[u8]) -> usize {
b.iter().filter(|c| **c == b'\n').count()
}
impl Writer {
fn new(dir: PathBuf, name: &str) -> Writer {
let path = dir.join(name);
let tmp = dir.join(format!("{name}.tmp"));
Writer { dir, path, tmp, file: None, good: None, held: Vec::new(), failed: None }
}
fn hook(&self, step: crate::fault::Step) -> io::Result<()> {
crate::fault::check(&self.dir, step)
}
/// Open the file positioned at `good` (a fragment past it, from a write that failed, is cut).
fn open(&mut self) -> io::Result<u64> {
if let (Some(_), Some(g)) = (&self.file, self.good) {
return Ok(g);
}
// (a link or a device planted at the name meanwhile is refused, as at the first append)
crate::store::check_regular_directory_entry(&self.path)?;
let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(false).open(&self.path)?;
let len = f.metadata()?.len();
let good = match self.good {
None => len,
Some(g) if len > g => {
f.set_len(g)?;
g
}
Some(g) if len < g => {
// shorter than what was synced: someone else cut it; continue at its end
log::error!("catalog: {} is {len} bytes, {g} were written", self.path.display());
len
}
Some(g) => g,
};
f.seek(io::SeekFrom::Start(good))?;
self.good = Some(good);
self.file = Some(f);
Ok(good)
}
/// Write and sync what is held.
fn write_held(&mut self) -> io::Result<()> {
if self.held.is_empty() {
return Ok(());
}
let r = (|| {
self.hook(crate::fault::Step::Write)?;
self.open()?;
let f = self.file.as_mut().ok_or_else(|| io::Error::other("catalog log not open"))?;
f.write_all(&self.held)?;
self.hook(crate::fault::Step::Sync)?;
self.file.as_ref().ok_or_else(|| io::Error::other("catalog log not open"))?.sync_data()
})();
match r {
Ok(()) => {
let n = self.held.len() as u64;
self.good = Some(self.good.unwrap_or(0).saturating_add(n));
self.held.clear();
Ok(())
}
Err(e) => {
// the handle may be dead (a network share that reconnected, a removed volume): the
// retry opens the file again and cuts what this attempt left past `good`
self.file = None;
Err(e)
}
}
}
/// Cut the logical log (file then held) to `len` bytes.
fn truncate(&mut self, len: u64) -> io::Result<()> {
let good = match self.good {
Some(g) => g,
None => match self.open() {
Ok(g) => g,
Err(e) if e.kind() == io::ErrorKind::NotFound => 0,
Err(e) => return Err(e),
},
};
// (to exactly `good` with bytes held: the file is cut, since a write that failed may have
// left some of them past `good`)
if len > good || (len == good && self.held.is_empty()) {
// within what is held: nothing on the drive changes (what a failed write left past
// `good` is cut before the next write)
let keep = usize::try_from(len - good).unwrap_or(usize::MAX).min(self.held.len());
self.held.truncate(keep);
return Ok(());
}
self.file = None;
let f = match std::fs::OpenOptions::new().write(true).open(&self.path) {
Ok(f) => f,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
self.good = None;
self.held.clear();
return Ok(());
}
Err(e) => return Err(e),
};
f.set_len(len)?;
f.sync_all()?;
self.good = Some(len);
self.held.clear();
Ok(())
}
fn replace(&mut self, data: &[u8]) -> io::Result<()> {
self.file = None;
let written = (|| {
self.hook(crate::fault::Step::Write)?;
let mut f = crate::store::create_staging(&self.tmp)?;
f.write_all(data)?;
self.hook(crate::fault::Step::Sync)?;
f.sync_all()?;
drop(f);
std::fs::rename(&self.tmp, &self.path)
})();
match written {
Ok(()) => {
// what was held is part of what the caller replaced the log with (a snapshot holds
// the records before it, `data` the ones after)
self.good = Some(data.len() as u64);
self.held.clear();
self.failed = None;
Ok(())
}
Err(e) => {
let _ = std::fs::remove_file(&self.tmp);
Err(e)
}
}
}
fn read(&mut self) -> io::Result<Option<Vec<u8>>> {
let mut bytes = match std::fs::read(&self.path) {
Ok(b) => b,
Err(e) if e.kind() == io::ErrorKind::NotFound && self.held.is_empty() => return Ok(None),
Err(e) if e.kind() == io::ErrorKind::NotFound => Vec::new(),
Err(e) => return Err(e),
};
if let Some(g) = self.good {
bytes.truncate(usize::try_from(g).unwrap_or(usize::MAX));
}
bytes.extend_from_slice(&self.held);
Ok(Some(bytes))
}
fn publish(&self, shared: &Mutex<Shared>) {
let mut sh = shared.lock().unwrap_or_else(PoisonError::into_inner);
sh.failed = self.failed.clone().filter(|_| !self.held.is_empty());
sh.held_records = if sh.failed.is_some() { lines(&self.held) } else { 0 };
}
fn run(&mut self, rx: &Receiver<Msg>, shared: &Mutex<Shared>) {
loop {
let first = if self.failed.is_some() && !self.held.is_empty() {
match rx.recv_timeout(RETRY) {
Ok(m) => Some(m),
Err(RecvTimeoutError::Timeout) => None,
Err(RecvTimeoutError::Disconnected) => break,
}
} else {
match rx.recv() {
Ok(m) => Some(m),
Err(_) => break,
}
};
let mut batch: Vec<Msg> = first.into_iter().collect();
while let Ok(m) = rx.try_recv() {
batch.push(m);
}
let mut flushes = Vec::new();
for m in batch {
match m {
Msg::Append(data) => self.held.extend_from_slice(&data),
// (published before the reply: the caller reads what it left at once)
Msg::Truncate(len, reply) => {
let r = self.truncate(len);
self.publish(shared);
let _ = reply.send(r);
}
Msg::Replace(data, reply) => {
let r = self.replace(&data);
self.publish(shared);
let _ = reply.send(r);
}
Msg::Read(reply) => {
let _ = reply.send(self.read());
}
Msg::Flush(reply) => flushes.push(reply),
}
}
self.step();
self.publish(shared);
for r in flushes {
let _ = r.send(match &self.failed {
Some(why) if !self.held.is_empty() => Err(not_written(why)),
_ => Ok(()),
});
}
}
// the store is closing: everything handed over gets one more try
self.step();
self.publish(shared);
if !self.held.is_empty() {
log::error!("catalog: {} record(s) could not be written to {} (the closing snapshot holds them)", lines(&self.held), self.path.display());
}
}
/// Write what is held; a failure is kept (and logged when it is new).
fn step(&mut self) {
match self.write_held() {
Ok(()) => {
if self.failed.take().is_some() {
log::info!("catalog: {} written again", self.path.display());
}
}
Err(e) => {
let why = e.to_string();
if self.failed.as_deref() != Some(why.as_str()) {
log::error!("catalog: {}: {why} ({} record(s) held, retried)", self.path.display(), lines(&self.held));
}
self.failed = Some(why);
}
}
}
}
+100 -6
View File
@@ -28,7 +28,9 @@ pub trait Store: Send {
self.write_atomic(name, &buf)?;
Ok(buf.len() as u64)
}
/// Append and make durable (fsync) before returning. On an error, part of `data` may have
/// Append and make durable (fsync): before returning, or, natively, by the store's own log
/// thread right after ([`FsStore`]: a write that fails is returned by a later append, and a
/// read through the store sees every byte handed over). On an error, part of `data` may have
/// been written (a full disk, a dropped network share): the journal cuts the file back to its
/// previous length with [`Store::truncate`] before appending again.
fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()>;
@@ -43,12 +45,23 @@ pub trait Store: Send {
fn background_writer(&self) -> Option<Box<dyn Store>> {
None
}
/// Wait until every append handed over is in the file and synced ([`FsStore`] writes them on a
/// thread of its own; the default has nothing to wait for). An error says why some aren't: they
/// are still held and retried, never dropped.
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
/// Records handed over by [`Store::append`] that can't be written yet (a write or sync on the
/// store's own thread failed: they are held and retried), and why. `None`: nothing held back.
fn unwritten(&self) -> Option<(usize, String)> {
None
}
}
/// Appends and truncates open the name's own file, so anything else at the name is the library's
/// problem: a link planted there redirects the write outside the directory (CWE-59), and a device
/// hangs the open. Refused with an error the open can show, before anything is written through.
fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
pub(crate) fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
match std::fs::symlink_metadata(path) {
Ok(md) if md.is_file() => Ok(()),
Ok(md) => Err(io::Error::other(format!("{} is a {:?}, not a regular file", path.display(), md.file_type()))),
@@ -60,15 +73,24 @@ fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
/// Files in a directory.
pub struct FsStore {
dir: PathBuf,
/// Open append handle (kept between appends; dropped on rewrite/truncate).
/// Open append handle (kept between appends; dropped on rewrite/truncate). Used when no thread
/// writes the log (the browser build, or one that couldn't start).
appender: Option<(String, std::fs::File)>,
/// The thread that writes the log (natively; started by the first append).
#[cfg(not(target_arch = "wasm32"))]
log: Option<crate::log_writer::LogWriter>,
}
impl FsStore {
/// Use `dir` (created if missing).
pub fn open(dir: impl AsRef<Path>) -> io::Result<FsStore> {
std::fs::create_dir_all(dir.as_ref())?;
Ok(FsStore { dir: dir.as_ref().to_path_buf(), appender: None })
Ok(FsStore {
dir: dir.as_ref().to_path_buf(),
appender: None,
#[cfg(not(target_arch = "wasm32"))]
log: None,
})
}
pub fn dir(&self) -> &Path {
&self.dir
@@ -76,6 +98,21 @@ impl FsStore {
fn path(&self, name: &str) -> PathBuf {
self.dir.join(name)
}
/// The log thread, when it writes `name`.
#[cfg(not(target_arch = "wasm32"))]
fn log_for(&self, name: &str) -> Option<&crate::log_writer::LogWriter> {
self.log.as_ref().filter(|w| w.name == name)
}
/// Wait until the log thread has written and synced everything handed to it.
pub fn flush_log(&self) -> io::Result<()> {
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = &self.log {
return w.flush();
}
Ok(())
}
fn sync_dir(&self) {
// Makes the rename durable on POSIX; opening a directory fails on Windows (where
// `rename` is already journaled by NTFS), so errors are ignored.
@@ -97,6 +134,11 @@ pub(crate) fn create_staging(tmp: &std::path::Path) -> io::Result<std::fs::File>
impl Store for FsStore {
fn read(&mut self, name: &str) -> io::Result<Option<Vec<u8>>> {
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = self.log_for(name) {
// what was handed over, written or still held
return w.read();
}
match std::fs::read(self.path(name)) {
Ok(b) => Ok(Some(b)),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
@@ -106,6 +148,13 @@ impl Store for FsStore {
fn write_atomic(&mut self, name: &str, data: &[u8]) -> io::Result<()> {
use std::io::Write;
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = self.log_for(name) {
// (after the appends handed over before)
w.replace(data)?;
self.sync_dir();
return Ok(());
}
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
self.appender = None;
}
@@ -122,6 +171,15 @@ impl Store for FsStore {
fn write_atomic_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn io::Write) -> io::Result<()>) -> io::Result<u64> {
use std::io::Write;
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = self.log_for(name) {
// (the log is small: buffered, and replaced by its thread after the appends before)
let mut buf = Vec::new();
fill(&mut buf)?;
w.replace(&buf)?;
self.sync_dir();
return Ok(buf.len() as u64);
}
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
self.appender = None;
}
@@ -148,6 +206,23 @@ impl Store for FsStore {
fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()> {
use std::io::Write;
#[cfg(not(target_arch = "wasm32"))]
{
if self.log.is_none() && !crate::fault::on_caller(&self.dir) {
check_regular_directory_entry(&self.path(name))?;
if !self.path(name).exists() {
// created here, so the open's errors are this append's and its entry is durable
std::fs::OpenOptions::new().create(true).append(true).open(self.path(name))?;
self.sync_dir();
}
self.appender = None;
self.log = crate::log_writer::LogWriter::start(self.dir.clone(), name);
}
// (another name than the log's is written here, as without a thread)
if let Some(w) = self.log_for(name) {
return w.append(data);
}
}
if self.appender.as_ref().is_none_or(|(n, _)| n != name) {
check_regular_directory_entry(&self.path(name))?;
let existed = self.path(name).exists();
@@ -158,6 +233,12 @@ impl Store for FsStore {
self.appender = Some((name.to_string(), f));
}
let Some((_, f)) = self.appender.as_mut() else { return Err(io::Error::other("appender not open")) };
#[cfg(not(target_arch = "wasm32"))]
let written = crate::fault::check(&self.dir, crate::fault::Step::Write)
.and_then(|()| f.write_all(data))
.and_then(|()| crate::fault::check(&self.dir, crate::fault::Step::Sync))
.and_then(|()| f.sync_data());
#[cfg(target_arch = "wasm32")]
let written = f.write_all(data).and_then(|()| f.sync_data());
if written.is_err() {
// The handle may be dead (a network share that reconnected, a removed volume): the next
@@ -169,6 +250,10 @@ impl Store for FsStore {
}
fn truncate(&mut self, name: &str, len: u64) -> io::Result<()> {
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = self.log_for(name) {
return w.truncate(len);
}
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
self.appender = None;
}
@@ -189,7 +274,16 @@ impl Store for FsStore {
#[cfg(not(target_arch = "wasm32"))]
fn background_writer(&self) -> Option<Box<dyn Store>> {
Some(Box::new(FsStore { dir: self.dir.clone(), appender: None }))
Some(Box::new(FsStore { dir: self.dir.clone(), appender: None, log: None }))
}
fn flush(&mut self) -> io::Result<()> {
self.flush_log()
}
#[cfg(not(target_arch = "wasm32"))]
fn unwritten(&self) -> Option<(usize, String)> {
self.log.as_ref().and_then(|w| w.unwritten())
}
}
@@ -256,13 +350,13 @@ impl Store for MemStore {
}
}
// (its one test plants a symlink, so the module is Unix-only: elsewhere `use super::*` would be unused)
#[cfg(all(test, unix))]
mod tests_staging {
use super::*;
/// A link planted at a staging name (`<name>.tmp`) is removed, never followed: the file it points to keeps its
/// bytes and the save still lands (issue #1502).
#[cfg(unix)]
#[test]
fn a_link_at_the_staging_name_is_never_written_through() {
let dir = std::env::temp_dir().join(format!("lc-staging-link-{}", std::process::id()));
+2 -1
View File
@@ -269,9 +269,10 @@ fn fs_store_background_snapshot() {
}
// a previous crash mid-snapshot left a partial temp file
std::fs::write(dir.join(format!("{SNAPSHOT}.tmp")), b"{\"format\":\"lightcraft-catal").unwrap();
// (closed first: its log thread writes what was handed over)
drop(j);
let (mut j2, c2, r) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
assert_eq!((c2.to_snapshot(), r.snapshot_seq), (live.to_snapshot(), 0));
drop(j);
let n = j2.seq();
j2.snapshot_in_background(&live).unwrap();
for k in 200..260 {
+232
View File
@@ -0,0 +1,232 @@
//! PERF-STEP-STALL: the catalog log's own thread ([`crate::log_writer`]). Appends return at once
//! however slow the drive is; everything handed over is written in order; a write that fails is
//! held, reported and retried, never dropped, and the log never has a gap.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use crate::fault::{self, Step};
use crate::store::{FsStore, Store};
const LOG: &str = "catalog.log";
fn temp_dir(tag: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("lc-log-thread-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
d
}
fn wait_until(what: &str, mut done: impl FnMut() -> bool) {
let t = Instant::now();
while !done() {
assert!(t.elapsed() < Duration::from_secs(20), "{what}");
std::thread::sleep(Duration::from_millis(10));
}
}
/// Appends are written by the thread in order; a read through the store sees every one; a cut
/// and a replace come after the appends before them; dropping the store writes what is left.
#[test]
fn appends_are_written_in_order_and_cuts_and_replaces_come_after_them() {
let dir = temp_dir("order");
let mut store = FsStore::open(&dir).unwrap();
let mut want = Vec::new();
for i in 0..200u32 {
let line = format!("{i}\n");
store.append(LOG, line.as_bytes()).unwrap();
want.extend_from_slice(line.as_bytes());
if i % 50 == 0 {
assert_eq!(store.read(LOG).unwrap().unwrap(), want, "all of it, through the store");
}
}
store.flush().unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), want, "all of it, in the file");
store.truncate(LOG, 4).unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n");
// never longer than it is
store.truncate(LOG, 400).unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n");
store.append(LOG, b"x\n").unwrap();
store.write_atomic(LOG, b"tail\n").unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\n");
store.append(LOG, b"more\n").unwrap();
drop(store);
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\nmore\n");
let _ = std::fs::remove_dir_all(&dir);
}
/// (a) Each sync takes 300 ms: 100 appends still return at once, and a flush then finds all of
/// them in the file (before, each append waited for its own sync: 30 s for these).
#[test]
fn an_append_never_waits_for_a_slow_sync() {
let dir = temp_dir("slow");
let mut store = FsStore::open(&dir).unwrap();
store.append(LOG, b"first\n").unwrap();
let syncs = Arc::new(AtomicUsize::new(0));
let n = syncs.clone();
fault::install(
&dir,
Arc::new(move |step| {
if step == Step::Sync {
n.fetch_add(1, Ordering::SeqCst);
std::thread::sleep(Duration::from_millis(300));
}
Ok(())
}),
);
let mut want = b"first\n".to_vec();
let mut slowest = Duration::ZERO;
for i in 0..100u32 {
let line = format!("{i}\n");
let t = Instant::now();
store.append(LOG, line.as_bytes()).unwrap();
slowest = slowest.max(t.elapsed());
want.extend_from_slice(line.as_bytes());
std::thread::sleep(Duration::from_millis(2));
}
assert!(slowest < Duration::from_millis(50), "an append waited {slowest:?}");
store.flush().unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), want);
// batched: far fewer syncs than appends
assert!(syncs.load(Ordering::SeqCst) < 50, "{} syncs", syncs.load(Ordering::SeqCst));
fault::remove(&dir);
let _ = std::fs::remove_dir_all(&dir);
}
/// (c) Writes fail for a while: what was handed over is held (reported, with the reason), later
/// appends are refused so the caller keeps them, and once writes work again the held bytes land,
/// in order, with no fragment of the failed attempts and no gap.
#[test]
fn a_failed_write_is_held_reported_and_retried() {
let dir = temp_dir("fail");
let mut store = FsStore::open(&dir).unwrap();
store.append(LOG, b"0\n").unwrap();
store.flush().unwrap();
let fail = Arc::new(AtomicBool::new(true));
let f = fail.clone();
fault::install(&dir, Arc::new(move |_| if f.load(Ordering::SeqCst) { Err(std::io::Error::other("disk full (test)")) } else { Ok(()) }));
// (one append: the log thread can fail the first before a second arrives, and then refuses it)
store.append(LOG, b"1\n2\n").unwrap();
wait_until("the failure is published", || store.unwritten().is_some());
let (held, why) = store.unwritten().unwrap();
assert!(why.contains("disk full"), "{why}");
assert!(held >= 1, "{held}");
let refused = store.append(LOG, b"3\n");
assert!(refused.is_err(), "refused while held");
assert!(store.flush().is_err(), "a flush says it isn't written");
// a read through the store still sees what was handed over
assert_eq!(store.read(LOG).unwrap().unwrap(), b"0\n1\n2\n");
// a cut within what is held keeps it (the journal cuts back to its own length on an error)
store.truncate(LOG, 6).unwrap();
assert_eq!(store.read(LOG).unwrap().unwrap(), b"0\n1\n2\n");
// a fragment of a failed write left in the file is cut before the retry
{
use std::io::Write;
let mut file = std::fs::OpenOptions::new().append(true).open(dir.join(LOG)).unwrap();
file.write_all(b"{\"seq\":").unwrap();
}
fail.store(false, Ordering::SeqCst);
wait_until("retried on its own", || store.unwritten().is_none());
store.append(LOG, b"3\n").unwrap();
store.flush().unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n2\n3\n");
fault::remove(&dir);
let _ = std::fs::remove_dir_all(&dir);
}
/// (b, c) Through the journal: ops appended while the drive is slow or failing all reopen, and a
/// journal over a log that failed has no gap (no damage on load).
#[test]
fn the_journal_reopens_every_op_after_a_slow_then_failing_drive() {
use crate::{Catalog, Journal, Op, Photo, PhotoId, Source};
let dir = temp_dir("journal");
let (mut j, mut c, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
let fail = Arc::new(AtomicBool::new(false));
let f = fail.clone();
fault::install(
&dir,
Arc::new(move |step| {
if f.load(Ordering::SeqCst) {
return Err(std::io::Error::other("network share dropped (test)"));
}
if step == Step::Sync {
std::thread::sleep(Duration::from_millis(40));
}
Ok(())
}),
);
let mut queued: Vec<Op> = Vec::new();
for id in 1..=60u64 {
if id == 20 {
fail.store(true, Ordering::SeqCst);
}
if id == 40 {
fail.store(false, Ordering::SeqCst);
}
let p = Photo::new(PhotoId(id), Source::Demo { scene: 0 }, &format!("p{id}.jpg"), "JPEG", 4, 3, "2026-11-02");
let op = Op::AddPhoto { photo: Box::new(p) };
c.apply(op.clone()).unwrap();
queued.push(op);
// as the engine does: a failed append keeps its ops queued for the next one
if j.append(&queued).is_ok() {
queued.clear();
}
std::thread::sleep(Duration::from_millis(5));
}
wait_until("everything written", || {
if !queued.is_empty() && j.append(&queued).is_ok() {
queued.clear();
}
queued.is_empty() && j.unwritten().is_none()
});
j.flush().unwrap();
let expect = c.to_snapshot();
drop(j);
fault::remove(&dir);
let (_, again, report): (_, Catalog, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
assert!(report.damaged.is_none(), "{report:?}");
assert_eq!(again.to_snapshot(), expect);
assert_eq!(again.len(), 60);
let _ = std::fs::remove_dir_all(&dir);
}
/// A sync that fails leaves the written bytes past the synced length in the file; a cut to exactly
/// that length removes them from the file too, so they never come back on the next open (review
/// of #3557).
#[test]
fn a_cut_to_the_synced_length_removes_bytes_a_failed_sync_left() {
let dir = temp_dir("cut-synced");
let mut store = FsStore::open(&dir).unwrap();
store
.append(
LOG, b"0
",
)
.unwrap();
store.flush().unwrap();
fault::install(&dir, Arc::new(|step| if step == Step::Sync { Err(std::io::Error::other("sync failed (test)")) } else { Ok(()) }));
store
.append(
LOG, b"1
",
)
.unwrap();
wait_until("the failure is published", || store.unwritten().is_some());
assert_eq!(
std::fs::read(dir.join(LOG)).unwrap(),
b"0
1
",
"written, not synced"
);
store.truncate(LOG, 2).unwrap();
fault::remove(&dir);
drop(store);
assert_eq!(
std::fs::read(dir.join(LOG)).unwrap(),
b"0
"
);
let _ = std::fs::remove_dir_all(&dir);
}
+3
View File
@@ -88,6 +88,9 @@ fn partial_append_then_retry_loads_cleanly() {
assert!(j.append(&batch).is_err(), "tear at {tear}");
// cut back to the last whole record
assert_eq!(t.files.get(LOG).unwrap().len(), good_len, "tear at {tear}");
// and a snapshot is due (records handed over before may be missing from a log written
// by a thread of its own: note 2 of 2026-10-25)
assert!(j.wants_snapshot(), "tear at {tear}");
j.append(&batch).unwrap();
let more = apply(&mut c, vec![Op::SetLabel { id, label: Some(ColorLabel::ALL[0]) }]);
j.append(&more).unwrap();
+4 -1
View File
@@ -55,5 +55,8 @@ fn a_file_path_rule_allocates_nothing_per_photo() {
}
let blocks = dhat::HeapStats::get().total_blocks - before;
assert!(hits > 0, "the rules matched nothing: the test measures nothing");
assert_eq!(blocks, 0, "{blocks} heap blocks for {} rule tests", 100 * rules.len() * photos.len());
// dhat counts every thread, and the test harness's own thread can allocate a few blocks while this
// runs. An allocation per photo would be thousands, two per rule test.
let tests = 100 * rules.len() * photos.len();
assert!(blocks < 64, "{blocks} heap blocks for {tests} rule tests");
}
+207
View File
@@ -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<Option<(lightcraft_raster::Rgba8, u16)>> {
// (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<f32>)> {
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<f32> =
(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<u8> {
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<u32> =
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::<u32>() 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:?}"),
}
}
}
+15
View File
@@ -169,6 +169,21 @@ pub fn decode(bytes: &[u8], opts: DecodeOptions) -> Result<Decoded> {
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<Option<(lightcraft_raster::Rgba8, u16)>> {
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 {
+4
View File
@@ -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);
+601
View File
@@ -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<f32>,
window: Vec<f32>,
}
/// 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<f32> = (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<f32>,
col: Vec<f32>,
col_tmp: Vec<f32>,
}
/// 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<f32>) {
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<usize> {
let mut v: Vec<usize> = (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<Vec<u32>> {
let nb = t + 1 - n;
let refs = starts(nb, step);
let nr = refs.len();
let cap = cap.max(1);
let mut lists: Vec<Vec<(f32, u32)>> = 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::<f32>() * 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<Vec<u32>> {
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<f32>], pilot: Option<&[Vec<f32>]>, groups: &[Vec<u32>], t: usize, p: &Params, lambda: f32, tf: &Transform) -> Vec<Vec<f32>> {
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<Plan> {
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<f32>, Vec<f32>) {
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<f32>], t: usize, p: &Params, noise: f32) -> Vec<Vec<f32>> {
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<f32> = (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::<f32>();
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<f32> = (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::<f32>() - v.iter().map(|x| x * x).sum::<f32>()).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<Vec<f32>> {
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<f32>], level: f32) -> f32 {
let all: Vec<f32> = planes.iter().flatten().copied().collect();
(all.iter().map(|v| (v - level) * (v - level)).sum::<f32>() / 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::<f32>() / 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()));
}
}
+679
View File
@@ -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<crate::bm3d::Params> {
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<f32>], usize, f32) -> Result<Vec<Vec<f32>>, Error>) -> Result<Vec<f32>, Error> {
let t = side_of(input.len()).ok_or_else(|| Error::Input("the tile is not four square planes".into()))?;
let clean: Vec<f32> = 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::<Vec<_>>(), t),
};
let st = Stabiliser::new(a, b);
let stabilised: Vec<Vec<f32>> = 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<Vec<f32>> = 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<f32>], t: usize, noise: f32) -> Vec<Vec<f32>> {
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<Vec<f32>, 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<usize> {
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::<f64>() / slice.len() as f64;
let mut variances: Vec<f32> = 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::<f64>() / slice.len() as f64;
let mut variances: Vec<f32> = 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<f32>], t: usize) -> Vec<f32> {
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<f32> {
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<f32>; 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<f32>; 3], t: usize, a: f32, b: f32, seed: u64) -> Vec<f32> {
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<f32>; 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<Vec<f32>> = 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<f32> = (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<f32> {
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<Vec<f32>> = 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<f32> = [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));
}
}
+3
View File
@@ -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;
+416
View File
@@ -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<crate::bm3d::Params>,
}
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<f32>]) -> Vec<Vec<f32>> {
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<f32> {
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<f32>], data: &[Vec<f32>], t: usize, p: &Pass) -> Vec<Vec<f32>> {
let Pass { radius, half, h, floor, loose, few } = *p;
let pad = radius + half;
let wd = t + 2 * pad;
let guide: Vec<Vec<f32>> = guide.iter().map(|p| padded(p, t, pad)).collect();
let data: Vec<Vec<f32>> = 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::<f32>() * 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<f32>], t: usize, tune: &Tuning, noise: f32) -> Vec<Vec<f32>> {
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<Vec<f32>> = 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<Vec<f32>> = (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<f32>]| p.iter().flatten().map(|v| v * v).sum::<f32>();
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<Vec<f32>> {
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<f32>], level: f32) -> f32 {
let all: Vec<f32> = planes.iter().flatten().copied().collect();
(all.iter().map(|v| (v - level) * (v - level)).sum::<f32>() / 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<f32>]| 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}");
}
}
}
+1 -1
View File
@@ -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,
+55 -1
View File
@@ -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<DevelopSettings, serde_json::Error> {
@@ -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();
+2 -2
View File
@@ -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())
}
+18 -2
View File
@@ -84,17 +84,25 @@ pub enum Process {
/// Highlights and Shadows keep the local contrast of the tones they move: their edge-aware base
/// is taken of a fine median of log luminance (issue #632).
V2,
/// Pixel-scale sharpening with working Radius and Detail controls.
V3,
/// V3, with Contrast and Blacks on a raw's camera look calibrated to Lightroom: the
/// camera curve keeps V2 Whites and fitted pointwise operators follow it
/// (`lightcraft_pipeline::light_v3`, `docs/light-v3.md`).
V4,
}
impl Process {
/// Every process, oldest first.
pub const ALL: [Process; 2] = [Process::V1, Process::V2];
pub const LATEST: Process = Process::V2;
pub const ALL: [Process; 4] = [Process::V1, Process::V2, Process::V3, Process::V4];
pub const LATEST: Process = Process::V4;
pub const fn version(self) -> ProcessVersion {
match self {
Process::V1 => ProcessVersion(1),
Process::V2 => ProcessVersion(2),
Process::V3 => ProcessVersion(3),
Process::V4 => ProcessVersion(4),
}
}
}
@@ -624,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 {
@@ -641,6 +656,7 @@ impl Default for Detail {
nr_color: 0.0,
nr_color_detail: 50.0,
nr_color_smoothness: 50.0,
nr_outliers: false,
}
}
}
+2
View File
@@ -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.
+1 -1
View File
@@ -144,7 +144,7 @@ fn benchmark_load(args: &[String], n: usize, only: &str) {
}
println!(" {:<36} {}", "load_bytes(2560):", best(n, || drop(lightcraft_engine::files::load_bytes(&bytes, 2560).expect("load"))));
let (loader, _) = lightcraft_engine::files::fs_hooks();
println!(" {:<36} {}", "fs loader (2560, read+load):", best(n, || drop(loader(path, 2560).expect("load"))));
println!(" {:<36} {}", "fs loader (2560, read+load):", best(n, || drop(loader(path, 2560, Default::default()).expect("load"))));
}
}
+2
View File
@@ -11,6 +11,7 @@ mod color;
pub(crate) mod convert;
mod cull;
pub mod curves;
pub mod dcp_profiles;
pub(crate) mod denoise;
mod develop;
mod edit;
@@ -154,6 +155,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(manage::specs());
v.extend(previews::specs());
v.extend(lut_profiles::specs());
v.extend(dcp_profiles::specs());
v.extend(mask_effects::specs());
v.extend(cull::specs());
v.extend(convert::specs());
+212
View File
@@ -0,0 +1,212 @@
//! Imported camera profiles: the user's own DNG Camera Profiles (`.dcp`), chosen like any other
//! profile (`develop.profile {id: "dcp:…"}`). Unlike the built-in looks and LUT profiles, which
//! work on developed colour, a camera profile replaces the raw file's colour model when it is
//! decoded (its matrices and hue/saturation map; see [`lightcraft_raw::dcp`]), so the photo's
//! source is decoded again when it changes. Other photos (JPEG, TIFF…) ignore it.
//!
//! A library on disk keeps a copy of each file in its `Profiles/` folder; the list lives in the
//! library's prefs and the profiles are parsed again when the library opens.
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use super::{CommandSpec, always, bad, cmd, str_param};
use crate::media::LoadedCameraProfile;
use crate::{Result, Session};
/// Profile id prefix of imported camera profiles.
pub const DCP_PREFIX: &str = "dcp:";
/// Profile browser group of imported camera profiles.
pub const DCP_GROUP: &str = "Camera Profiles";
/// One imported camera profile.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DcpEntry {
/// `dcp:<slug>`.
pub id: String,
/// `ProfileName`, else the file name.
pub name: String,
/// The camera it was made for (`UniqueCameraModel`).
#[serde(default)]
pub camera_model: String,
/// The `.dcp` file (the library's copy when there is a library on disk).
pub file: String,
}
/// Is `id` an imported camera profile id?
pub fn is_dcp_id(id: &str) -> bool {
id.starts_with(DCP_PREFIX)
}
fn profiles_dir(s: &Session) -> Option<PathBuf> {
s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Profiles"))
}
/// Parse every imported camera profile again and hand them to the decoder (missing or damaged
/// files are skipped: photos using them develop with the file's own colour, and the profile is not offered or
/// accepted by `develop.profile` until its file is back; the entry is kept).
///
/// A library's own copies are found in `profiles`, the `Profiles/` folder of the library being opened (`None`: not on
/// disk), wherever the saved path points: a library moved or restored elsewhere keeps its profiles (the saved path is
/// updated).
pub fn register_all(s: &mut Session, profiles: Option<&Path>) {
if let Some(dir) = profiles {
for p in &mut s.dcp_profiles {
if let Some(here) = library_copy(dir, &p.file) {
p.file = here.to_string_lossy().to_string();
}
}
}
let loaded: Vec<(String, LoadedCameraProfile)> = s
.dcp_profiles
.iter()
.filter_map(|p| {
lightcraft_raw::dcp::read_dcp(Path::new(&p.file)).ok().and_then(|b| LoadedCameraProfile::parse(&b).ok()).map(|d| (p.id.clone(), d))
})
.collect();
s.media.camera_profiles = loaded.into_iter().collect();
}
/// The copy of saved profile file `file` in the open library's profiles folder `dir`, when it is there under the
/// same name and `file` is not already it.
fn library_copy(dir: &Path, file: &str) -> Option<PathBuf> {
let saved = Path::new(file);
let here = dir.join(saved.file_name()?);
(here != saved && here.is_file()).then_some(here)
}
/// `.dcp` files under `paths` (folders searched).
pub fn dcp_files(paths: &[String]) -> Vec<PathBuf> {
let is_dcp = |f: &Path| f.extension().is_some_and(|x| x.eq_ignore_ascii_case("dcp"));
let mut out = Vec::new();
for p in paths {
let path = Path::new(p);
if path.is_dir() {
out.extend(crate::walk::files_in(path, None, crate::walk::Limits::default(), is_dcp).files);
} else if is_dcp(path) {
out.push(path.to_path_buf());
}
}
out
}
/// Import the `.dcp` files under `paths` → (imported `[{id, name, cameraModel}]`, failed `[[file, error]]`).
/// A profile already imported (same name, camera and bytes) is not added twice.
pub fn import_files(s: &mut Session, paths: &[String]) -> Result<(Vec<Value>, Vec<Value>)> {
const C: &str = "profile.import";
let dir = profiles_dir(s);
if let Some(d) = &dir {
std::fs::create_dir_all(d).map_err(|e| bad(C, format!("{}: {e}", d.display())))?;
}
let (mut imported, mut failed) = (Vec::new(), Vec::new());
for f in dcp_files(paths) {
let shown = f.display().to_string();
let bytes = match lightcraft_raw::dcp::read_dcp(&f) {
Ok(b) => b,
Err(e) => {
failed.push(json!([shown, e.to_string()]));
continue;
}
};
let loaded = match LoadedCameraProfile::parse(&bytes) {
Ok(p) => p,
Err(e) => {
failed.push(json!([shown, e.to_string()]));
continue;
}
};
let profile = loaded.profile.clone();
let stem = f.file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "Camera Profile".into());
let name = if profile.name.trim().is_empty() { stem.clone() } else { profile.name.trim().to_string() };
// the same profile imported again: keep the one there is
let same = s.dcp_profiles.iter().find(|p| {
p.name == name && p.camera_model == profile.camera_model && lightcraft_raw::dcp::read_dcp(Path::new(&p.file)).is_ok_and(|b| b == bytes)
});
if let Some(p) = same {
imported.push(json!({"id": p.id, "name": p.name, "cameraModel": p.camera_model, "existing": true}));
continue;
}
// (the file name keeps profiles with the same ProfileName apart, e.g. per-body copies)
let slug = crate::presets::slug(&format!("{}-{stem}", profile.camera_model));
let mut id = format!("{DCP_PREFIX}{slug}");
let mut n = 2;
while s.dcp_profiles.iter().any(|x| x.id == id) {
id = format!("{DCP_PREFIX}{slug}-{n}");
n += 1;
}
let file = match &dir {
Some(d) => {
let to = d.join(format!("{}.dcp", id.trim_start_matches(DCP_PREFIX)));
// a copy that fails (disk full, no access) fails this file only: the profiles
// copied before it stay imported, and nothing half-written is left behind
if let Err(e) = std::fs::write(&to, &bytes) {
if to.is_file() {
let _ = std::fs::remove_file(&to);
}
failed.push(json!([shown, format!("{}: {e}", to.display())]));
continue;
}
to.to_string_lossy().to_string()
}
// no library on disk: remember the original (the in-memory session ends with the app)
None => f.to_string_lossy().to_string(),
};
s.media.camera_profiles.insert(id.clone(), loaded);
s.dcp_profiles.push(DcpEntry { id: id.clone(), name: name.clone(), camera_model: profile.camera_model.clone(), file });
imported.push(json!({"id": id, "name": name, "cameraModel": profile.camera_model}));
}
Ok((imported, failed))
}
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "profile.deleteCamera";
let id = str_param(p, "id").ok_or_else(|| bad(C, "missing id"))?.to_string();
let Some(i) = s.dcp_profiles.iter().position(|x| x.id == id) else {
return Err(bad(C, format!("no imported camera profile `{id}`")));
};
// the library's copy goes first; a file outside the library is the user's and stays. A copy that can't be
// removed (in use, no access) keeps the profile, so the library never holds a file it no longer lists. A path
// with `..` in it is never the library's copy (it could lead out of the profiles folder).
if let Some(d) = profiles_dir(s)
&& let Some(entry) = s.dcp_profiles.get(i)
&& Path::new(&entry.file).starts_with(&d)
&& !Path::new(&entry.file).components().any(|c| c == std::path::Component::ParentDir)
{
match std::fs::remove_file(&entry.file) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(bad(C, format!("could not delete {}: {e}", entry.file))),
}
}
s.dcp_profiles.remove(i);
s.media.camera_profiles.remove(&id);
s.profile_favorites.retain(|f| f != &id);
s.profile_recent.retain(|f| f != &id);
s.save_prefs()?;
Ok(json!({"deleted": id}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "profiles.camera",
"Imported Camera Profiles",
[],
None,
"{} → {profiles: [{id, name, cameraModel, file}]}: the imported .dcp camera profiles (use with develop.profile)",
always,
|s, _| Ok(json!({"profiles": s.dcp_profiles}))
),
cmd!(
"profile.deleteCamera",
"Delete Imported Camera Profile",
[],
None,
"{id: dcp:…} — photos using it develop with their file's own colour again",
always,
delete
),
]
}
+6 -3
View File
@@ -118,6 +118,9 @@ fn identify(path: &Path, c: &str, sha_known: Option<&str>) -> Result<Source> {
&& 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<CommandSpec> {
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),
]
+11 -3
View File
@@ -557,9 +557,17 @@ pub fn specs() -> Vec<CommandSpec> {
}),
cmd!("develop.profile", "Set Profile", [], None, "{id: profile id (see profiles.list), amount?: 0..200}", has_active, |s, p| {
let id = str_param(p, "id").ok_or_else(|| bad("develop.profile", "missing id"))?.to_string();
if !crate::presets::PROFILES.iter().any(|x| x.id == id) && !s.lut_profiles.iter().any(|x| x.id == id) {
if !crate::presets::PROFILES.iter().any(|x| x.id == id)
&& !s.lut_profiles.iter().any(|x| x.id == id)
&& !s.dcp_profiles.iter().any(|x| x.id == id)
{
return Err(bad("develop.profile", format!("unknown profile `{id}`")));
}
// an imported camera profile whose file is missing or damaged: choosing it would develop with the
// file's own colour without saying so
if crate::cmd::dcp_profiles::is_dcp_id(&id) && !s.media.camera_profiles.contains_key(&id) {
return Err(bad("develop.profile", format!("camera profile `{id}` can't be used: its file is missing or damaged")));
}
edit(s, "develop.profile", "Profile", |d| {
d.profile.id = id.clone();
d.profile.amount = f64_or(p, "amount", d.profile.amount).clamp(0.0, 200.0);
@@ -570,7 +578,7 @@ pub fn specs() -> Vec<CommandSpec> {
}),
cmd!("profile.favorite", "Favorite Profile", [], None, "{id, favorite?: bool} (toggles when omitted)", always, |s, p| {
let id = str_param(p, "id").ok_or_else(|| bad("profile.favorite", "missing id"))?.to_string();
if crate::presets::profile(&id).is_none() && !s.lut_profiles.iter().any(|x| x.id == id) {
if crate::presets::profile(&id).is_none() && !s.lut_profiles.iter().any(|x| x.id == id) && !s.dcp_profiles.iter().any(|x| x.id == id) {
return Err(bad("profile.favorite", format!("unknown profile `{id}`")));
}
let on = s.profile_favorites.contains(&id);
@@ -1158,7 +1166,7 @@ pub fn specs() -> Vec<CommandSpec> {
|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 {
+75 -10
View File
@@ -47,6 +47,10 @@ pub struct PlaceNames {
shared: Arc<Mutex<DownloadShared>>,
/// (cities file, its size, its modification time, the parsed names).
cache: Option<(PathBuf, u64, Option<SystemTime>, Arc<GeoNames>)>,
/// (folder, server) a download goes to instead of `<settings>/geonames` and GeoNames. Only
/// tests set it: no command can, so a client never chooses where the files land (#2575).
#[cfg(not(target_arch = "wasm32"))]
download_to: Option<(PathBuf, String)>,
}
impl PlaceNames {
@@ -188,10 +192,7 @@ mod download {
use lightcraft_geocode::{GEONAMES_BASE, GEONAMES_ZIP};
use super::{
Cancel, DownloadOutcome, GEONAMES_ATTRIBUTION, GEONAMES_FILES, GeoNames, PoisonError, Result, Session, Value, bad, dataset_dir, json,
str_param,
};
use super::{Cancel, DownloadOutcome, GEONAMES_ATTRIBUTION, GEONAMES_FILES, GeoNames, PoisonError, Result, Session, Value, bad, json};
use crate::activity::Unit;
const MAX_ZIP: u64 = 64 * 1024 * 1024;
@@ -218,7 +219,11 @@ mod download {
return Err("the downloaded place list is empty".into());
}
let _ = std::fs::remove_file(staging.join(GEONAMES_ZIP));
let write = |name: &str, data: &[u8]| std::fs::write(dir.join(name), data).map_err(|e| format!("could not save {name}: {e}"));
// a temp file renamed over the old one: never half-written, and a link in its place is
// replaced, not written through (#2575); not synced, as a download can always be repeated
let write = |name: &str, data: &[u8]| {
lightcraft_catalog::safe_file::write_atomic_nosync(&dir.join(name), data).map_err(|e| format!("could not save {name}: {e}"))
};
for name in &GEONAMES_FILES[1..] {
// optional: without them states stay blank and countries are ISO codes
match get(name, base, &staging, cancel, task).and_then(|()| std::fs::read(staging.join(name)).map_err(|e| e.to_string())) {
@@ -241,10 +246,21 @@ mod download {
}
/// `metadata.downloadPlaceNames`: starts a background download (shown in the activity stack, cancellable).
/// The files always go to `<settings>/geonames`, from GeoNames: a control or MCP client naming a
/// folder (`dataset`) or a server (`base`) could have written a server's bytes into any folder (#2575).
pub(super) fn start(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "metadata.downloadPlaceNames";
let dir = dataset_dir(p).ok_or_else(|| bad(C, "no settings folder: give `dataset`"))?;
let base = str_param(p, "base").unwrap_or(GEONAMES_BASE).to_string();
if p.get("dataset").is_some() || p.get("base").is_some() {
return Err(bad(C, "the place names always download from GeoNames into the settings folder: `dataset` and `base` are not accepted"));
}
let target = s.place_names.download_to.clone();
let (dir, base) = match target {
Some(t) => t,
None => (
crate::config::config_dir().ok_or_else(|| bad(C, "no settings folder to save the place names in"))?.join("geonames"),
GEONAMES_BASE.to_string(),
),
};
if !base_allowed(&base) {
return Err(bad(C, "`base` must be an https:// address"));
}
@@ -309,7 +325,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Download Place Names (GeoNames)",
["Photo"],
None,
"{dataset?: folder} → {started, path, attribution} — downloads the GeoNames cities list (CC-BY 4.0, ~3 MB, from download.geonames.org) in the background for Fill Location from GPS; no photo data is sent",
"{} → {started, path, attribution} — downloads the GeoNames cities list (CC-BY 4.0, ~3 MB, from download.geonames.org) in the background for Fill Location from GPS, always into `geonames` in the settings folder (a folder or server named by the caller is refused); no photo data is sent",
always,
download::start
));
@@ -468,7 +484,8 @@ mod tests {
#[cfg(not(target_arch = "wasm32"))]
fn download(s: &mut Session, base: &str, dir: &Path) -> DownloadOutcome {
s.execute("metadata.downloadPlaceNames", &json!({"dataset": dir, "base": base})).unwrap();
s.place_names.download_to = Some((dir.to_path_buf(), base.to_string()));
s.execute("metadata.downloadPlaceNames", &json!({})).unwrap();
assert!(s.place_names.downloading() || s.place_names.lock().unreported.is_some());
let started = std::time::Instant::now();
loop {
@@ -493,7 +510,8 @@ mod tests {
let base = serve();
let dir = std::env::temp_dir().join(format!("lightcraft-geocode-dl-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
assert!(s.execute("metadata.downloadPlaceNames", &json!({"dataset": dir, "base": "http://example.com/"})).is_err());
s.place_names.download_to = Some((dir.clone(), "http://example.com/".into()));
assert!(s.execute("metadata.downloadPlaceNames", &json!({})).is_err(), "plain http to another machine");
for bad in ["missing", "garbage", "short"] {
let o = download(&mut s, &format!("{base}/{bad}/"), &dir);
@@ -516,6 +534,53 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// Issue #2575: a control or MCP client named the folder (`dataset`) and the server (`base`),
/// so it could have a server's bytes written as `cities15000.txt`, `admin1CodesASCII.txt` and
/// `countryInfo.txt` into any folder. Both are refused now, before anything starts.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_client_cannot_choose_where_the_place_names_download_to() {
let mut s = Session::with_demo();
let dir = std::env::temp_dir().join(format!("lightcraft-geocode-elsewhere-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
for p in [json!({"dataset": dir}), json!({"base": "https://example.com/"}), json!({"dataset": dir, "base": "https://example.com/"})] {
let e = s.execute("metadata.downloadPlaceNames", &p).unwrap_err().to_string();
assert!(e.contains("not accepted"), "{p}: {e}");
}
assert!(!s.place_names.downloading() && s.activity.list().is_empty(), "nothing started");
assert!(!dir.exists(), "nothing written");
}
/// The downloaded files replace what is there by renaming a complete temp file over it, so a
/// link planted under one of their names is replaced, not followed to the file it points at.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_download_replaces_a_planted_link_instead_of_writing_through_it() {
let mut s = Session::with_demo();
let base = serve();
let root = std::env::temp_dir().join(format!("lightcraft-geocode-link-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let dir = root.join("geonames");
std::fs::create_dir_all(&dir).unwrap();
let victim = root.join("victim.txt");
std::fs::write(&victim, "keep me").unwrap();
let link = dir.join("countryInfo.txt");
#[cfg(unix)]
let linked = std::os::unix::fs::symlink(&victim, &link);
#[cfg(windows)]
let linked = std::os::windows::fs::symlink_file(&victim, &link);
if let Err(e) = linked {
lightcraft_testkit::skip!(System, "can't create a symbolic link here: {e}");
let _ = std::fs::remove_dir_all(&root);
return;
}
assert_eq!(download(&mut s, &format!("{base}/good/"), &dir), DownloadOutcome::Done(2));
assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep me", "the link's target is untouched");
assert!(!std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link is now the downloaded file");
assert!(std::fs::read_to_string(&link).unwrap().contains("France"));
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn download_base_is_https_or_loopback_only() {
assert!(download::base_allowed("https://download.geonames.org/export/dump/"));
+4
View File
@@ -1367,6 +1367,8 @@ pub fn specs() -> Vec<CommandSpec> {
),
// ---- 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<CommandSpec> {
"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),
+13 -3
View File
@@ -77,11 +77,14 @@ fn cube_files(paths: &[String]) -> (Vec<(String, String, Option<String>)>, Vec<V
));
}
}
} else {
} else if path.extension().is_some_and(|x| x.eq_ignore_ascii_case("cube")) {
match std::fs::read_to_string(path) {
Ok(t) => out.push((stem(path), t, None)),
Err(e) => failed.push(json!([stem(path), e.to_string()])),
}
} else if !path.extension().is_some_and(|x| x.eq_ignore_ascii_case("dcp")) {
// (a .dcp is a camera profile: `dcp_profiles::import_files` takes it)
failed.push(json!([stem(path), "not a .cube, .dcp or .zip file"]));
}
}
(out, failed)
@@ -133,6 +136,10 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
s.lut_profiles.push(LutProfile { id: id.clone(), name: display.clone(), group: group.clone(), file });
imported.push(json!({"id": id, "name": display, "group": group}));
}
// camera profiles (.dcp) among them
let (cameras, camera_failed) = super::dcp_profiles::import_files(s, &paths)?;
imported.extend(cameras);
failed.extend(camera_failed);
s.save_prefs()?;
// presets that name these profiles use them now
crate::profile_refs::refresh(s);
@@ -146,12 +153,15 @@ pub fn specs() -> Vec<CommandSpec> {
"Import Profiles",
[],
None,
"{paths: [.cube file, folder or .zip]} — 3D LUTs become creative profiles (Amount 0–200 %; rendered on the CPU) in the profile browser's groups (folder / zip name, else Imported) → {imported: [{id, name, group}], failed}",
"{paths: [.cube / .dcp file, folder or .zip]} — 3D LUTs become creative profiles (Amount 0–200 %; rendered on the CPU) in the profile browser's groups (folder / zip name, else Imported); DNG camera profiles (.dcp, the user's own) become camera profiles (dcp: ids, group Camera Profiles) that replace a raw file's colour model when it is decoded → {imported: [{id, name, group | cameraModel}], failed}",
always,
import
),
cmd!("profile.deleteImported", "Delete Imported Profile", [], None, "{id: lut:…}", always, |s, p| {
cmd!("profile.deleteImported", "Delete Imported Profile", [], None, "{id: lut:… | dcp:…}", always, |s, p| {
let id = str_param(p, "id").ok_or_else(|| bad("profile.deleteImported", "missing id"))?.to_string();
if super::dcp_profiles::is_dcp_id(&id) {
return s.execute("profile.deleteCamera", p);
}
let Some(i) = s.lut_profiles.iter().position(|x| x.id == id) else {
return Err(bad("profile.deleteImported", format!("no imported profile `{id}`")));
};
+376 -53
View File
@@ -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<Option<String>>,
/// 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<u64>,
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<T>(&self, queue: &[Option<T>]) -> Option<usize> {
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<String> {
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<Vec<(usize, u64)>> = 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<Building> {
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<Building>, 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<Building>, 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<Building>, 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<Box<dyn std::any::Any>> {
Building::take(id, jobs).map(|b| Box::new(b) as Box<dyn std::any::Any>)
}
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<RenderJob>, cancel: Option<&AtomicBool>) -> Option<bool> {
/// `force`: the grid thumbnail is rendered too, not taken from the cache it is written to.
fn run_photo_cancellable(jobs: Vec<RenderJob>, cancel: Option<&AtomicBool>, force: bool) -> Option<bool> {
let mut decoded: Option<crate::media::DecodedSource> = None;
let mut ok = true;
for mut j in jobs {
@@ -97,7 +224,33 @@ fn run_photo_cancellable(jobs: Vec<RenderJob>, 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<RenderJob>, 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<RenderJob>) -> 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<Arc<PreviewGate>> {
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<bool> = 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<Vec<RenderJob>>, 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<RenderJob>);
/// 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<PhotoJobs>, 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::<Vec<_>>());
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<Vec<RenderJob>>, 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<Value> {
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<Vec<RenderJob>> = 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<PhotoJobs> = 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())
}
@@ -360,8 +618,9 @@ struct SmartCounts {
fn original_only(source: crate::media::SourceRef) -> Option<crate::media::SourceRef> {
use crate::media::SourceRef;
match source {
SourceRef::File { path, max_edge, loader, denoise, .. } => {
Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, reduced: None })
// (a smart preview keeps the file's own colour: an imported camera profile is applied when the original is read)
SourceRef::File { path, max_edge, loader, denoise, 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,
@@ -475,10 +734,18 @@ fn smart(s: &mut Session, p: &Value) -> Result<Value> {
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<SmartJob> = Vec::new();
for id in ids {
let Some(ph) = s.catalog.photo(id).cloned() else { continue };
@@ -486,26 +753,44 @@ fn smart(s: &mut Session, p: &Value) -> Result<Value> {
continue;
}
let path = crate::smart::sharded_file_path(&dir, &ph);
let source = (!discard).then(|| s.media.source_ref(&ph, crate::media::SourceLevel::Preview));
// (a smart preview keeps the file's own colour: never built with the photo's imported camera profile, nor
// from a cached source developed with it)
let source = (!discard).then(|| s.media.source_ref_without_profile(&ph, crate::media::SourceLevel::Preview));
jobs.push((id, path, source, preview_fitted_look(&ph)));
}
let custom = s.smart_previews_dir.is_some();
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))?;
@@ -644,7 +929,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
@@ -671,13 +956,43 @@ pub fn specs() -> Vec<CommandSpec> {
"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);
@@ -720,8 +1035,16 @@ mod tests {
let mut jobs = jobs_for(&mut s, id, Some(512));
assert_eq!(jobs.len(), 2, "view and thumbnail");
assert!(jobs[0].view_cache.is_some(), "the view renders first");
jobs[1].source =
SourceRef::File { path: "/nonexistent/photo.arw".into(), max_edge: 512, loader: None, fallback: None, denoise: None, reduced: None };
jobs[1].source = SourceRef::File {
path: "/nonexistent/photo.arw".into(),
max_edge: 512,
loader: None,
fallback: None,
denoise: None,
camera_profile: None,
outliers: false,
reduced: None,
};
assert!(run_photo(jobs), "the thumbnail rendered from the view's decoded source");
}
+15
View File
@@ -273,6 +273,21 @@ pub fn specs() -> Vec<CommandSpec> {
}
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);
+1 -1
View File
@@ -232,7 +232,7 @@ mod tests {
s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
}
let seen = files.clone();
s.media.file_loader = Some(Arc::new(move |path: &str, _| {
s.media.file_loader = Some(Arc::new(move |path: &str, _, _| {
let started = {
let mut reads = seen.reads.lock().unwrap();
*reads.entry(path.to_string()).or_default() += 1;
+1
View File
@@ -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;
+325
View File
@@ -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<lightcraft_denoise::builtin::Builtin>,
#[cfg(feature = "denoise")]
card: Arc<BuiltinCard>,
/// The runner of a photo that runs on the card.
#[cfg(feature = "denoise")]
hybrid: OnceLock<CardRunner>,
}
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<Value, String> {
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<f32> {
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<lightcraft_gpu::bm3d::Bm3dGpu>,
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<BuiltinGpu, String> {
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(&params, 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<Result<BuiltinGpu, String>>,
/// 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<Vec<(PathBuf, Arc<BuiltinCard>)>> = 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<BuiltinCard> {
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<BuiltinCard>,
}
#[cfg(feature = "denoise")]
impl TileRunner for CardRunner {
fn run(&self, input: &[f32]) -> Result<Vec<f32>, 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;
+155
View File
@@ -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::<f32>() / 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(&params, 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");
}
+6 -3
View File
@@ -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<T: Send + 'static, R>(
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<T: Send + 'static, R>(
/// 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;
}
+20
View File
@@ -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");
+2
View File
@@ -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<Value, String>;
+8
View File
@@ -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<Arc<dyn Model>, 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,
+25 -17
View File
@@ -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.
+5 -1
View File
@@ -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<Installed> {
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)));
}
-2
View File
@@ -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 {
+577
View File
@@ -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<Option<(DiskSpace, u64)>, 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<DiskSpace> {
#[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<dyn Fn(&Path) -> Option<DiskSpace> + 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<LowDiskAlert>,
/// When the free space was last read.
pub(crate) checked_at: Option<web_time::Instant>,
/// 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<std::sync::mpsc::Receiver<Answer>>,
/// 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<Reader>,
/// 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<LowDiskAlert> {
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<Reader>) {
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<std::time::Duration> {
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<std::time::Duration> {
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::<std::path::PathBuf>();
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());
}
}
+2
View File
@@ -912,6 +912,8 @@ fn ramp(depth: OutputDepth, space: OutputSpace) -> lightcraft_pipeline::Rendered
fn distinct_levels(bytes: &[u8]) -> (usize, lightcraft_codecs::Decoded) {
let d = lightcraft_codecs::decode(bytes, Default::default()).expect("decodes");
let mut v: Vec<u32> = (0..d.image.width).map(|x| d.image.get(x, 1)[1].to_bits()).collect();
// sorted first: 8-bit output is dithered, so equal levels aren't all side by side
v.sort_unstable();
v.dedup();
(v.len(), d)
}
+31 -1
View File
@@ -11,6 +11,8 @@ use lightcraft_pipeline::SourceInfo;
use lightcraft_raster::Rgb32f;
use lightcraft_raster::resample::{Filter, fit};
use lightcraft_raw::dcp::DcpProfile;
use crate::media::{DenoiseSpec, FileLoader, FileProbe, PairLoader, PreviewLoader, ProbeInfo, ReducedLoader};
mod colour;
@@ -25,7 +27,7 @@ pub(crate) use colour::clipped_white;
use fs::quick_image_srgb;
pub use fs::{fs_hooks, fs_pair_loader, fs_reduced_loader};
pub(crate) use load::{DngWhite, WbScaleOf, dng_tone_curve};
pub use load::{load_bytes, load_vec, load_vec_pair, load_vec_reduced};
pub use load::{load_bytes, load_bytes_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;
@@ -119,5 +121,33 @@ fn finite(rgb: [f32; 3]) -> [f32; 3] {
rgb.map(|v| if v.is_finite() { v } else { 0.0 })
}
/// 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;
+12 -4
View File
@@ -2,6 +2,7 @@ use super::load::{load_vec, load_vec_pair, load_vec_reduced};
use super::preview::{fit_box, fs_preview_loader, preview_orientation};
use super::probe::probe_bytes;
use super::{Arc, DenoiseSpec, FileLoader, FileProbe, Filter, PairLoader, ReducedLoader, fit};
use 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<u64> {
/// `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<lightcraft_raster::Rgba8> {
// 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| {
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);
let r = load_vec_pair(bytes, max_edge, spec, with);
crate::memory::release();
r
})
@@ -74,7 +81,8 @@ pub fn fs_pair_loader() -> PairLoader {
/// interactive loads (the loupe, exports) never wait — they are counted, so background work
/// yields to them.
pub fn fs_hooks() -> (FileLoader, FileProbe) {
let loader: FileLoader = Arc::new(|path: &str, max_edge: usize| fs_load(path, max_edge, |bytes| load_vec(bytes, max_edge)));
let loader: FileLoader =
Arc::new(|path: &str, max_edge: usize, 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
@@ -94,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| fs_load(path, max_edge, |bytes| load_vec_reduced(bytes, max_edge)))
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.
+187 -17
View File
@@ -1,7 +1,8 @@
use super::colour::bin_factor;
use super::preview::{fit_box, load_embedded_preview};
use super::probe::preview_reason;
use super::{Arc, CameraColourModel, DenoiseSpec, Filter, HIGHLIGHT_CLIP, Orientation, Rgb32f, SourceInfo, fit, xy_to_temp_tint};
use super::{Arc, CameraColourModel, DcpProfile, DenoiseSpec, Filter, HIGHLIGHT_CLIP, Orientation, Rgb32f, SourceInfo, fit, xy_to_temp_tint};
use crate::media::RawDecode;
/// Decode a file into a linear Rec.2020 image no larger than `max_edge`, oriented.
///
@@ -9,27 +10,46 @@ use super::{Arc, CameraColourModel, DenoiseSpec, Filter, HIGHLIGHT_CLIP, Orienta
/// instead of each one waking the pool from outside and waiting for it (which costs more than the
/// loops themselves when the machine is busy).
pub fn load_bytes(bytes: &[u8], max_edge: usize) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false).map(|(img, _, info, _)| (img, info)))
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> {
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<u8>, max_edge: usize) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, false).map(|(img, _, info, _)| (img, info)))
pub fn load_vec(bytes: Vec<u8>, 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<u8>, max_edge: usize) -> Result<(Rgb32f, SourceInfo, bool), String> {
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, true).map(|(img, _, info, reduced)| (img, info, reduced)))
pub fn load_vec_reduced(bytes: Vec<u8>, 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, with).map(|(img, _, info, reduced)| (img, info, reduced))
})
}
/// [`load_vec`] that also develops the photo's cached denoised picture (`spec`) from the same decode: the plain
/// picture, the denoised one (`None` when it cannot be read or does not fit this raw: the plain one is then all
/// there is) and the source facts. Both pictures are the same size.
pub fn load_vec_pair(bytes: Vec<u8>, max_edge: usize, spec: &DenoiseSpec) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> {
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, Some(spec), false).map(|(img, twin, info, _)| (img, twin, info)))
pub fn load_vec_pair(
bytes: Vec<u8>,
max_edge: usize,
spec: &DenoiseSpec,
with: RawDecode<'_>,
) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> {
rayon::scope(move |_| {
load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, Some(spec), false, with).map(|(img, twin, info, _)| (img, twin, info))
})
}
/// The denoised camera RGB of `raw` from its cached product, as the plain development would have it: the default
@@ -59,7 +79,9 @@ fn load_bytes_now(
max_edge: usize,
denoise: Option<&DenoiseSpec>,
allow_reduced: bool,
with: RawDecode<'_>,
) -> Result<(Rgb32f, Option<Rgb32f>, 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
@@ -81,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();
@@ -92,20 +122,46 @@ fn load_bytes_now(
let dng_lens_ops = (raw.format == lightcraft_raw::RawFormat::Dng && raw.opcodes.list3.iter().any(|op| op.is_lens_correction()))
.then(|| raw.opcodes.list3.clone());
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
// A camera profile without a tone curve of its own (most chart-made ones: a matrix, maybe a hue/saturation map)
// keeps the contrast the photo has without it: the file's own DNG tone curve, else the tone of the look fitted
// to its camera JPEG. (A chart pins colour, not a rendering: its curve would be a choice, and this one is the
// camera's.)
let kept_tone = match dcp {
Some(p) if p.color.profile.tone_curve.is_none() => raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve).or_else(|| {
let own = raw.color.clone();
// the same proxy as the starting colour's fit below: the DNG's lens opcodes back in, no embedded lens
let tone = with_dng_lens_ops(&mut raw, dng_lens_ops.as_ref(), lens.as_ref(), list3, |raw, embedded| {
crate::camera_preview::starting_colour(raw, &bytes, lens_geometry.as_ref(), embedded)
})
.2
.map(|look| look.tone);
raw.color = own;
tone
}),
_ => None,
};
// An imported camera profile replaces the file's colour model (its matrices and look; the shot's white stays), so
// the starting colour and the white balance scale below come from it, not from a fitted or built-in look.
// (the white balance stays on the scale the file and its camera give, the one the catalog's
// `Photo::relative_wb` and the quick previews use: a profile's matrices must not turn a relative white balance
// into Kelvin, which would read existing edits as absolute temperatures)
let own_scale = dcp.map(|_| WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata));
if let Some(p) = dcp {
raw.color = p.applied_to(&raw.color);
}
// Which scale white balance is edited on, and the as-shot white on it, from the file's own colour tags or
// the camera's measured matrices (`Photo::relative_wb` decides the same from the catalog's camera)
let scale = WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata);
let scale = match &own_scale {
Some(own) => scale.keeping_classification_of(own),
None => scale,
};
// the source's segmentation mattes (DNG semantic masks), read while the starting colour is fitted
let ((xy, t, camera_look), mattes) = rayon::join(
|| {
let removed = dng_lens_ops.map(|ops| std::mem::replace(&mut raw.opcodes.list3, ops));
// With the opcodes restored, the proxy already includes vignetting; do not apply it twice.
let embedded = if removed.is_some() { None } else { lens.as_ref() };
let colour = crate::camera_preview::starting_colour(&mut raw, &bytes, lens_geometry.as_ref(), embedded);
if let Some(ops) = removed {
raw.opcodes.list3 = ops;
}
colour
with_dng_lens_ops(&mut raw, dng_lens_ops.as_ref(), lens.as_ref(), list3, |raw, embedded| {
crate::camera_preview::starting_colour(raw, &bytes, lens_geometry.as_ref(), embedded)
})
},
|| dng_mattes(&bytes, &info),
);
@@ -183,7 +239,12 @@ fn load_bytes_now(
let tags = lightcraft_raw::ColorData { profile: Default::default(), ..raw.color.clone() };
Arc::new(lightcraft_pipeline::CameraColor { tags, developed_for: xy })
});
let camera_tone = camera_look.as_ref().map(|p| p.tone).or_else(|| raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve));
let camera_tone = camera_tone_of(
dcp.is_some(),
camera_look.as_ref().map(|p| p.tone),
raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve),
kept_tone,
);
let local_tone = local_tone(&raw);
let (temp, tint) = scale.as_shot(xy);
return Ok((
@@ -262,6 +323,13 @@ impl WbScaleOf {
WbScaleOf { own_matrix, relative: fitted && !covered, legacy_relative: fitted && covered, scale_white, camera }
}
/// This scale (a raw's, with an imported camera profile's colour model) on the white-balance scale `own` (the
/// same raw's with its own colour) gives: relative, or Kelvin edited on the relative scale before. The matrices,
/// and so the colour and the as-shot reading, stay this scale's.
pub(super) fn keeping_classification_of(self, own: &WbScaleOf) -> Self {
WbScaleOf { relative: own.relative, legacy_relative: own.legacy_relative, ..self }
}
/// What a DNG of this raw's camera RGB declares so that it shows the white balance as this scale does: the
/// camera's measured matrices when they give the scale, else the white the scale shows at As Shot (the presets'
/// reading; 6500 K / 0 on the relative scale; else `own`, the white the file's tags give).
@@ -348,3 +416,105 @@ pub(crate) fn dng_tone_curve(curve: &lightcraft_raw::profile::ToneCurve) -> Opti
});
lightcraft_pipeline::tone::CameraTone::new(knots)
}
/// A raw's `OpcodeList3`.
fn list3(raw: &mut lightcraft_raw::RawImage) -> &mut Vec<lightcraft_raw::Opcode> {
&mut raw.opcodes.list3
}
/// `fit(raw, embedded)` with a DNG's lens opcodes `ops` back in `raw`'s `OpcodeList3` (`list3`), as its preview has
/// them applied, and the list as it was afterwards. With the opcodes restored the proxy already includes the
/// vignetting, so `embedded` is `None` then (else `lens`): every tone fit of one photo sees the same proxy.
fn with_dng_lens_ops<R, L, T>(
raw: &mut R,
ops: Option<&Vec<lightcraft_raw::Opcode>>,
lens: Option<&L>,
list3: fn(&mut R) -> &mut Vec<lightcraft_raw::Opcode>,
fit: impl FnOnce(&mut R, Option<&L>) -> T,
) -> T {
let removed = ops.map(|ops| std::mem::replace(list3(raw), ops.clone()));
let embedded = if removed.is_some() { None } else { lens };
let out = fit(raw, embedded);
if let Some(ops) = removed {
*list3(raw) = ops;
}
out
}
/// The tone a raw's starting look gets from its camera: `look` (the tone of the look fitted to the camera JPEG),
/// `curve` (the colour model's own tone curve: the file's, or with an imported camera profile, the profile's) and
/// `kept` (the photo's own tone, kept for a profile without a curve). With a camera profile (`profile`), its curve
/// comes first, then the kept tone, and the fitted look's only last: the look was fitted without the profile, so it
/// must not replace the profile's curve or the contrast kept for it. Without one, the fitted look leads as before.
fn camera_tone_of<T>(profile: bool, look: Option<T>, curve: Option<T>, kept: Option<T>) -> Option<T> {
if profile { curve.or(kept).or(look) } else { look.or(curve).or(kept) }
}
#[cfg(test)]
mod camera_tone_tests {
use super::camera_tone_of;
/// CodeRabbit on #1063: with an imported camera profile, a fitted camera look's tone replaced the profile's own
/// tone curve and the tone kept for a profile without one. Without a profile the order is unchanged.
#[test]
fn a_camera_profiles_curve_and_kept_tone_come_before_the_fitted_look() {
assert_eq!(camera_tone_of(true, Some("look"), Some("profile"), Some("kept")), Some("profile"));
assert_eq!(camera_tone_of(true, Some("look"), None, Some("kept")), Some("kept"));
assert_eq!(camera_tone_of(true, Some("look"), None, None), Some("look"));
assert_eq!(camera_tone_of(false, Some("look"), Some("file"), Some("kept")), Some("look"));
assert_eq!(camera_tone_of(false, None, Some("file"), Some("kept")), Some("file"));
assert_eq!(camera_tone_of::<&str>(false, None, None, None), None);
}
}
#[cfg(test)]
mod wb_scale_tests {
use super::WbScaleOf;
/// CodeRabbit on #1063: a raw edited on the relative white-balance scale (no colour matrices, none measured for
/// its camera) turned to Kelvin once an imported camera profile's matrices replaced its colour, so its existing
/// edits (6500 K / 0 = as shot) were read as absolute temperatures, and the catalog and quick previews still
/// used the relative scale. The profile's matrices stay; the scale is the file's.
#[test]
fn a_camera_profile_keeps_a_relative_white_balance_relative() {
let format = lightcraft_raw::RawFormat::Cr3;
let meta = lightcraft_meta::Metadata::default();
let own_color = lightcraft_raw::ColorData::default();
let own = WbScaleOf::new(format, &own_color, Some([2.0, 1.0, 1.5]), &meta);
assert!(own.relative && !own.own_matrix, "a matrix-less raw of an unmeasured camera is relative");
let m = lightcraft_color::Mat3([[0.9, 0.1, 0.0], [0.1, 0.8, 0.1], [0.0, 0.2, 0.8]]);
let profiled = lightcraft_raw::ColorData { illuminant: [21, 0], color_matrix: [Some(m), None], ..Default::default() };
let with = WbScaleOf::new(format, &profiled, Some([2.0, 1.0, 1.5]), &meta);
assert!(!with.relative, "the profile's matrices alone would make it Kelvin");
let kept = with.keeping_classification_of(&own);
assert!(kept.relative && !kept.legacy_relative && kept.own_matrix, "relative, with the profile's matrices");
assert_eq!(kept.as_shot(lightcraft_color::Xy { x: 0.3127, y: 0.329 }), (6500.0, 0.0));
}
}
#[cfg(test)]
mod lens_ops_tests {
use lightcraft_raw::Opcode;
use super::with_dng_lens_ops;
fn same(v: &mut Vec<Opcode>) -> &mut Vec<Opcode> {
v
}
/// Both tone fits of a DNG (the kept tone for a camera profile without a curve, and the starting colour) see its
/// lens opcodes restored and no embedded lens; the list is as it was afterwards (CodeRabbit on #1063: the
/// kept-tone fit ran without the opcodes and with the embedded lens).
#[test]
fn a_dngs_tone_fit_sees_its_lens_opcodes_and_no_embedded_lens() {
let vignette = Opcode::FixVignetteRadial { k: [0.1, 0.0, 0.0, 0.0, 0.0], center: [0.5, 0.5] };
let ops = vec![vignette.clone()];
let mut list: Vec<Opcode> = Vec::new();
let lens = 7;
let seen = with_dng_lens_ops(&mut list, Some(&ops), Some(&lens), same, |l, embedded| (l.clone(), embedded.copied()));
assert_eq!(seen, (vec![vignette], None), "the opcodes are in, the embedded lens is not");
assert!(list.is_empty(), "the list is as it was");
let seen = with_dng_lens_ops(&mut list, None, Some(&lens), same, |l, embedded| (l.len(), embedded.copied()));
assert_eq!(seen, (0, Some(7)), "without DNG lens opcodes the embedded lens is used");
}
}
+19 -4
View File
@@ -33,7 +33,11 @@ pub(crate) fn decode_raw_preview(
opts: lightcraft_codecs::DecodeOptions,
covering: Option<usize>,
) -> Option<lightcraft_codecs::Decoded> {
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<lightcraft_codecs::Decoded> {
// 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<lightcraft_raster::Rgba8> {
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;
+15
View File
@@ -143,6 +143,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
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<ProbeInfo, String> {
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<ProbeInfo, String> {
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<ProbeInfo, String> {
content_hash,
embedded_lens: None,
xmp: None,
orientation: m.orientation,
preview_only: None,
})
}
+4 -4
View File
@@ -591,7 +591,7 @@ fn cached_denoise_uses_the_same_white_balance_profile_and_orientation_as_plain_r
product::write(&path, &camera_rgb, key).unwrap();
let spec = DenoiseSpec { product: path, key: key.into(), make: None };
let (ordinary, _) = load_bytes(&bytes, 2048).unwrap();
let (plain, cached, _) = load_vec_pair(bytes, 2048, &spec).unwrap();
let (plain, cached, _) = load_vec_pair(bytes, 2048, &spec, 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));
@@ -1289,10 +1289,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::<f64>() / img.data.len().max(1) as f64;
// the loaders: only the thumbnail's develops the copy, and only when it covers the size
let (copy, _, used) = load_vec_reduced(bytes.clone(), 512).unwrap();
let (copy, _, used) = load_vec_reduced(bytes.clone(), 512, Default::default()).unwrap();
assert!(used, "a thumbnail develops the copy");
assert!(!load_vec_reduced(bytes.clone(), 1024).unwrap().2, "no copy covers 1024 px");
let (full, _) = load_vec(bytes.clone(), 512).unwrap();
assert!(!load_vec_reduced(bytes.clone(), 1024, Default::default()).unwrap().2, "no copy covers 1024 px");
let (full, _) = load_vec(bytes.clone(), 512, Default::default()).unwrap();
assert!(g(&copy) > 4.0 * g(&full), "the fixture's copy is much brighter: {} vs {}", g(&copy), g(&full));
let dir = std::env::temp_dir().join(format!("lc-reduced-export-{}", std::process::id()));
+3 -1
View File
@@ -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::{
+2
View File
@@ -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);
+3
View File
@@ -512,6 +512,7 @@ impl Session {
stages: None,
view_cache: None,
display: None,
on_screen: false,
slide: None,
preview_cut: None,
display_fit: None,
@@ -527,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)),
})
+1 -1
View File
@@ -14,7 +14,7 @@ fn fixture(preview_edge: Option<usize>, renderable: bool, preview_only: bool) ->
let mut session = Session::new();
let reads = Arc::new(AtomicUsize::new(0));
let count = reads.clone();
session.media.file_loader = Some(Arc::new(move |_, edge| {
session.media.file_loader = Some(Arc::new(move |_, edge, _| {
count.fetch_add(1, Ordering::SeqCst);
if !renderable {
return Err("synthetic raw cannot be rendered".into());
+180 -1
View File
@@ -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<lightcraft_catalog::Catalog> {
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<String, ProbeInfo> {
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<String>, sort: &lightcraft_catalog::Sort) -> Vec<String> {
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<String>,
sort: &lightcraft_catalog::Sort,
cancel: &std::sync::atomic::AtomicBool,
) -> Option<Vec<String>> {
let known = library_files(&input.library, &files);
let mut files: Vec<String> = 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<Vec<String>> {
// 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<PathBuf> {
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<PathBuf> {
normalized(path, false)
}
fn normalized(path: &Path, resolve_links: bool) -> std::io::Result<PathBuf> {
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<u64>| {
let mut keyed: Vec<(Option<u64>, 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
+48 -12
View File
@@ -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;
@@ -80,6 +82,7 @@ pub mod slideshow;
pub mod slideshow_export;
pub mod smart;
pub mod sync;
mod sync_same;
pub mod text;
mod view;
pub mod walk;
@@ -359,6 +362,8 @@ pub struct Session {
/// The user's point-curve presets (`curve.*`; built-ins: [`cmd::curves::builtin_presets`]),
/// persisted in prefs.json.
pub curve_presets: Vec<cmd::curves::CurvePreset>,
/// Imported camera profiles (`.dcp`).
pub dcp_profiles: Vec<cmd::dcp_profiles::DcpEntry>,
/// Mask effect presets (the Masking panel's Effect menu).
pub mask_effects: Vec<cmd::mask_effects::MaskEffect>,
/// The effect a new mask of each kind (`brush`, `linear`…) starts with: the one last applied
@@ -395,10 +400,18 @@ pub struct Session {
pub slideshow_export: Option<std::sync::Arc<slideshow_export::ExportRun>>,
/// The last (or running) Build Previews.
pub preview_build: Option<std::sync::Arc<cmd::previews::PreviewBuild>>,
/// 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
@@ -518,6 +531,7 @@ impl Session {
metadata_presets: Vec::new(),
filter_presets: Vec::new(),
curve_presets: Vec::new(),
dcp_profiles: Vec::new(),
mask_effects: Vec::new(),
mask_tool_effects: Default::default(),
label_sets: Vec::new(),
@@ -533,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(),
@@ -614,7 +631,8 @@ impl Session {
}
}
if self.depth == 0 && self.library.is_some() {
// Make the command durable before reporting success. When the command's own records
// Make the command durable before reporting success (natively: handed to the catalog
// log's own thread, which syncs it right after and holds it until it can). When the command's own records
// can't be appended, it fails with `NotSaved`: the change stays applied in memory and
// queued, and the next save (any later command, or the frame loop) retries it. Other
// persistence trouble (a failed compaction, an older queued change still unwritten by
@@ -946,8 +964,9 @@ impl Session {
i.crop_edited |= crop_edited;
return self.apply_silent(Op::SetDevelop { id, settings, label: label.into(), edited: Some(now) });
}
let own_auto = self.own_auto_wb(id, &requested, label);
let mut ops = vec![self.develop_op(id, (*settings).clone(), label).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?];
ops.extend(self.auto_sync_ops(id, &requested, label));
ops.extend(self.auto_sync_ops(id, &requested, label, &own_auto));
let op = if ops.len() == 1 { ops.remove(0) } else { Op::Batch { ops } };
self.commit(label, op)
}
@@ -988,18 +1007,18 @@ impl Session {
/// never spot removal or red eye (they belong to one photo's pixels), nor the rendering process
/// (Sync doesn't carry it either), nor history / snapshot restores. Constrain Crop then fits each
/// photo's own crop: the active photo's fitted crop is never copied over another's.
fn auto_sync_ops(&self, id: PhotoId, new: &DevelopSettings, label: &str) -> Vec<Op> {
if !self.auto_sync
|| self.active() != Some(id)
|| self.selection.ids.len() < 2
|| label.starts_with("History:")
|| label.starts_with("Restore ")
{
///
/// White balance goes on each photo as the active photo's mode or value on the photo's own
/// scale ([`sync_same`]): As Shot its own camera white, Auto its own (`own_auto`, worked out on
/// its pixels), a Temp or Tint the same number, only the slider that moved.
fn auto_sync_ops(&self, id: PhotoId, new: &DevelopSettings, label: &str, own_auto: &std::collections::HashMap<PhotoId, (f64, f64)>) -> Vec<Op> {
if !self.auto_sync_applies(id, label) {
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);
@@ -1016,18 +1035,35 @@ impl Session {
return Vec::new();
}
}
let ainfo = self.source_info(id);
let wb_changed = old.wb != new.wb;
self.selection
.ids
.iter()
.filter(|x| **x != id)
.filter_map(|x| self.develop_of(*x).map(|d| (*x, d)))
.filter_map(|(x, d)| {
let synced = self.fit_constrained_crop(x, lightcraft_develop::apply_partial(&d, &delta, 1.0));
let mut synced = lightcraft_develop::apply_partial(&d, &delta, 1.0);
if wb_changed {
sync_same::synced_wb(&ainfo, &old, new, &self.source_info(x), &d, own_auto.get(&x).copied(), &mut synced);
}
let synced = self.fit_constrained_crop(x, synced);
(synced != *d).then(|| self.develop_op(x, synced, label)).flatten()
})
.collect()
}
/// Auto Sync carries an edit of photo `id` labelled `label` to the other selected photos: it is
/// on, `id` is the active photo of a selection of two or more, and the edit is not a History or
/// snapshot restore.
fn auto_sync_applies(&self, id: PhotoId, label: &str) -> bool {
self.auto_sync
&& self.active() == Some(id)
&& self.selection.ids.len() >= 2
&& !label.starts_with("History:")
&& !label.starts_with("Restore ")
}
/// The op that sets a photo's develop settings and appends a History entry (for batches).
pub fn develop_op(&self, id: PhotoId, settings: DevelopSettings, label: &str) -> Option<Op> {
self.catalog.photo(id)?;
+117 -15
View File
@@ -13,8 +13,12 @@
//! The files live in [`Store`]s: a directory ([`FsStore`]) natively, or any other implementation
//! via [`Session::open_library_in`] (the browser build keeps them in OPFS or IndexedDB).
//!
//! Every top-level [`Session::execute`] persists the ops it produced (fsynced) before returning,
//! so a crash loses at most the command in flight. When that write fails the command returns
//! Every top-level [`Session::execute`] persists the ops it produced before returning: fsynced
//! there, or natively handed to the catalog log's own thread, which writes and syncs them right
//! after (the UI thread never waits for the drive), so a crash or power cut loses at most the
//! batch in flight (what arrived during one sync). A write that thread
//! can't make is held and retried, counts as unsaved ([`Session::unsaved`]) and makes a snapshot
//! due. When that write fails the command returns
//! [`EngineError::NotSaved`]: its change stays applied in memory and queued, and every later save
//! retries the queue ([`Session::unsaved`] reports it meanwhile), so nothing is lost once the
//! disk is writable again. The log is compacted into a snapshot when it
@@ -134,6 +138,10 @@ pub struct Library {
/// Why the last write of presets.json failed; `None` once it is written. While set, the preset
/// changes exist only in memory and count as unsaved ([`Session::unsaved`], issue #2266).
presets_error: Option<String>,
/// Records the catalog log's own thread holds because writing them failed (it retries them),
/// and why; refreshed by every persist and every frame ([`Session::persist_if_dirty`]). While
/// set they count as unsaved ([`Session::unsaved`]), so quitting asks first.
log_held: Option<(usize, String)>,
/// When the frame loop may retry a failed append ([`Session::persist_if_dirty`] backs off).
retry_at: Option<web_time::Instant>,
/// What forgetting untouched Local records did when the library opened.
@@ -250,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<Option<crate::prep::PrepSettings>, 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 {
@@ -277,6 +292,8 @@ struct PrefsFile {
label_sets: Vec<crate::cmd::manage::LabelSet>,
/// Imported LUT profiles.
lut_profiles: Vec<crate::cmd::lut_profiles::LutProfile>,
/// Imported camera profiles (`.dcp`).
dcp_profiles: Vec<crate::cmd::dcp_profiles::DcpEntry>,
/// Keyword sets, the one in use, recent keywords.
keyword_sets: Vec<crate::cmd::keywords::KeywordSet>,
keyword_set: Option<String>,
@@ -285,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<crate::prep::PrepSettings>,
/// Folder for smart previews (default: `Smart Previews` in the library).
smart_previews_dir: Option<String>,
/// Days after which untouched Local records of unbrowsed folders are forgotten (missing =
@@ -322,6 +344,8 @@ fn poll_compaction(lib: &mut Library) {
log::error!("library: compaction: {e}");
lib.last_error = Some(format!("compaction: {e}"));
}
// (never waits: the log's thread publishes what it holds)
lib.log_held = lib.journal.unwritten();
}
/// How long the frame loop waits before retrying a failed append (commands retry at once).
@@ -501,13 +525,24 @@ impl Session {
/// Open `stores`; the new library takes `lock` once nothing can fail any more.
fn open_stores(&mut self, stores: LibraryStores, seed_demo: bool, lock: &mut Option<LibraryLock>) -> Result<()> {
let LibraryStores { dir, catalog, mut files, on_disk } = stores;
self.media.smart_dir = on_disk.then(|| crate::smart::dir(&dir));
// the current library may be these same files: let its background snapshot land first
if let Some(old) = self.library.as_mut()
&& let Err(e) = old.journal.wait()
{
log::error!("library: {e}");
// the current library may be these same files: let its background snapshot land first, and
// what its log's thread was handed reach the file before the new journal reads it. When
// that can't be written, the open fails and the current library stays open with what its
// thread holds (retried): read now, the files would miss it (review of #3557).
if let Some(old) = self.library.as_mut() {
if let Err(e) = old.journal.wait() {
log::error!("library: {e}");
}
if let Err(e) = old.journal.flush() {
old.log_held = old.journal.unwritten();
// a snapshot that holds every op leaves nothing for the files to miss
if old.journal.snapshot_seq() < old.journal.seq() {
return Err(EngineError::NotSaved(format!("the open library's changes aren't on disk yet, so it stays open: {e}")));
}
log::error!("library: {e} (every change is in its snapshot)");
}
}
self.media.smart_dir = on_disk.then(|| crate::smart::dir(&dir));
// Photo ids belong to one library; denoise work must not carry into the next.
self.denoise.library_changed();
self.media.denoise.clear();
@@ -555,11 +590,14 @@ impl Session {
self.label_sets = prefs.label_sets;
self.lut_profiles = prefs.lut_profiles;
crate::cmd::lut_profiles::register_all(self);
self.dcp_profiles = prefs.dcp_profiles;
crate::cmd::dcp_profiles::register_all(self, on_disk.then(|| dir.join("Profiles")).as_deref());
self.keyword_sets = prefs.keyword_sets;
self.keyword_set = prefs.keyword_set;
self.recent_keywords = prefs.recent_keywords;
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();
@@ -582,7 +620,11 @@ impl Session {
self.presets.push(u);
}
}
let known = |id: &String| crate::presets::profile(id).is_some() || self.lut_profiles.iter().any(|p| &p.id == id);
let known = |id: &String| {
crate::presets::profile(id).is_some()
|| self.lut_profiles.iter().any(|p| &p.id == id)
|| self.dcp_profiles.iter().any(|p| &p.id == id)
};
self.profile_favorites = f.profile_favorites.into_iter().filter(known).collect();
self.profile_recent = f.profile_recent.into_iter().filter(known).take(crate::presets::RECENT_PROFILES).collect();
}
@@ -631,6 +673,7 @@ impl Session {
last_error: None,
unsaved_error: None,
presets_error: None,
log_held: None,
retry_at: None,
forgot_local: None,
presets_saved,
@@ -658,10 +701,13 @@ 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(())
}
/// Write pending ops to the log (fsynced), compact when due, and save changed presets.
/// Write pending ops to the log (fsynced, or handed to the log's own thread natively), compact when due, and save changed presets.
/// Called after every top-level command; cheap when nothing changed. Fails (with
/// [`EngineError::NotSaved`]) only when the queued ops couldn't be written; they stay queued.
pub fn persist(&mut self) -> Result<()> {
@@ -726,13 +772,40 @@ impl Session {
pub fn persist_if_dirty(&mut self) {
let backing_off = self.library.as_ref().and_then(|l| l.retry_at).is_some_and(|t| web_time::Instant::now() < t);
let presets_unsaved = self.library.as_ref().is_some_and(|l| l.presets_error.is_some());
if self.library.is_some() && (!self.pending_log.is_empty() || presets_unsaved) && !backing_off {
// records the log's thread can't write: a snapshot (a fresh file holding everything) is due
let log_held = self.library.as_ref().is_some_and(|l| l.log_held.is_some());
if self.library.is_some() && (!self.pending_log.is_empty() || presets_unsaved || log_held) && !backing_off {
let _ = self.persist();
} else if let Some(lib) = self.library.as_mut() {
poll_compaction(lib);
}
}
/// Read again what the catalog log's own thread holds because writing it failed (never waits):
/// before a check of [`Session::unsaved`] that must be current, such as the quit prompt's.
pub fn refresh_unsaved(&mut self) {
if let Some(lib) = self.library.as_mut() {
lib.log_held = lib.journal.unwritten();
}
}
/// Every change applied is in the library's last snapshot (a closing snapshot landed), whatever
/// the catalog log's thread still holds or failed to reset. `false` without a library.
pub fn snapshot_holds_everything(&self) -> bool {
self.pending_log.is_empty() && self.library.as_ref().is_some_and(|l| l.journal.snapshot_seq() >= l.journal.seq())
}
/// Wait until what the catalog log's thread was handed is on disk, then read again what it
/// holds ([`Session::refresh_unsaved`]). Before the quit check: a change the thread accepted
/// but hasn't written yet is in no count of [`Session::unsaved`]. An error (a write failed, or
/// the drive took over a minute) means some changes may not be on disk yet.
pub fn flush_log(&mut self) -> Result<()> {
let Some(lib) = self.library.as_mut() else { return Ok(()) };
let flushed = lib.journal.flush();
lib.log_held = lib.journal.unwritten();
Ok(flushed?)
}
/// Changes applied in memory but not yet written to disk because saving failed: the number of
/// queued ops (plus one for presets.json) and why (`None` when everything is saved, or no library
/// is open). Retried by every command and by [`Session::persist_if_dirty`].
@@ -740,8 +813,9 @@ impl Session {
let lib = self.library.as_ref()?;
let ops = lib.unsaved_error.as_deref().filter(|_| !self.pending_log.is_empty());
let presets = lib.presets_error.as_deref();
let n = ops.map_or(0, |_| self.pending_log.len()) + usize::from(presets.is_some());
ops.or(presets).map(|why| (n, why))
let held = lib.log_held.as_ref().map(|(n, why)| (*n, why.as_str()));
let n = ops.map_or(0, |_| self.pending_log.len()) + held.map_or(0, |(n, _)| n) + usize::from(presets.is_some());
ops.or(held.map(|(_, why)| why)).or(presets).map(|why| (n, why))
}
/// Flush everything and write a snapshot (on quit). Ends an open interaction first.
@@ -760,6 +834,8 @@ impl Session {
let Some(lib) = self.library.as_mut() else { return Ok(()) };
let before = lib.journal.seq();
let snapshot = lib.journal.snapshot_with_unlogged(&self.catalog, unlogged);
// (a snapshot that landed holds what the log's thread held)
lib.log_held = lib.journal.unwritten();
if unlogged > 0 && lib.journal.seq() == before + unlogged {
// the snapshot holds the queued ops: they are saved, never append them again
log::info!("library: {unlogged} queued change(s) saved in the closing snapshot");
@@ -834,11 +910,13 @@ impl Session {
mask_tool_effects: self.mask_tool_effects.clone(),
label_sets: self.label_sets.clone(),
lut_profiles: self.lut_profiles.clone(),
dcp_profiles: self.dcp_profiles.clone(),
keyword_sets: self.keyword_sets.clone(),
keyword_set: self.keyword_set.clone(),
recent_keywords: self.recent_keywords.clone(),
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(),
@@ -866,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
@@ -930,6 +1022,16 @@ fn unlocked_warning(lock: Option<&LibraryLock>) -> Option<String> {
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 <dir>/catalog.snap` failed with the OS's "File exists" (creating a folder over
/// the file); it opens the library that file belongs to.
#[test]
+27 -3
View File
@@ -24,6 +24,7 @@ use lightcraft_develop::DevelopSettings;
use lightcraft_pipeline::{Quality, RenderRequest, Rendered, SourceInfo, StageCache};
use lightcraft_preview::{Hash128, Hasher128, Lru, PreviewCache};
use lightcraft_raster::{Histogram, Rgb32f, Rgba8};
pub use lightcraft_raw::dcp::DcpProfile;
use serde::{Deserialize, Serialize};
mod cache;
@@ -34,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, 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 {
@@ -79,6 +83,26 @@ pub struct MediaCache {
pub rendered: Arc<PreviewCache>,
/// Which photos have a cached denoised picture, and how to read it.
pub denoise: DenoiseIndex,
/// Imported camera profiles by id ([`crate::cmd::dcp_profiles`]), handed to the decoder of photos using them.
pub camera_profiles: std::collections::HashMap<String, LoadedCameraProfile>,
}
/// An imported camera profile ready for the decoder, with a fingerprint of its file: decoded sources and cached renders
/// made with it carry the fingerprint, so a profile deleted, or replaced by another under the same id, never has
/// its old pictures stand in.
#[derive(Clone, Debug)]
pub struct LoadedCameraProfile {
pub profile: Arc<DcpProfile>,
/// Never 0 (0 is "no camera profile" in a render key).
pub fingerprint: u64,
}
impl LoadedCameraProfile {
/// Parse a `.dcp` file's bytes.
pub fn parse(bytes: &[u8]) -> Result<Self, lightcraft_raw::dcp::DcpError> {
let profile = lightcraft_raw::dcp::parse_dcp(bytes)?;
Ok(LoadedCameraProfile { profile: Arc::new(profile), fingerprint: Hasher128::new().update(bytes).finish().0 as u64 | 1 })
}
}
#[cfg(test)]
+97 -18
View File
@@ -1,6 +1,6 @@
use super::settings_hash::SettingsHashes;
use super::source::{DecodedSource, DenoiseSpec, PairLoader, RENDERED_MEM_BYTES, SourceLevel, SourceRef, THUMB_SOURCE_BYTES};
use super::{Arc, DevelopSettings, Hasher128, Lru, MediaCache, Photo, PhotoId, PreviewCache, Rgb32f, Source, SourceInfo};
use super::{Arc, DcpProfile, DevelopSettings, HashMap, Hasher128, Lru, MediaCache, Photo, PhotoId, PreviewCache, Rgb32f, Source, SourceInfo};
/// The photos that have a cached denoised picture for the denoise model in use. Only memory: nothing here touches the
/// file system, so it can be asked on the UI thread.
@@ -70,13 +70,16 @@ impl Default for MediaCache {
scenes: Vec::new(),
rendered: Arc::new(PreviewCache::memory(rendered_budget(budget))),
denoise: DenoiseIndex::default(),
camera_profiles: HashMap::new(),
}
}
}
/// 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 {
@@ -202,14 +205,16 @@ impl MediaCache {
}
/// The facts of photo `id`'s cached sources: the decoder's when one has them, else `header`
/// (with a smart preview's stored camera tone curve).
pub(super) fn source_facts(&self, id: PhotoId, header: SourceInfo) -> SourceInfo {
/// (with a smart preview's stored camera tone curve). Only sources developed with `profile` (the photo's imported
/// camera profile tag, [`Self::camera_profile_of`], or none) count: one made with another profile has its facts.
pub(super) fn source_facts(&self, id: PhotoId, header: SourceInfo, profile: Option<&str>) -> SourceInfo {
let cached = || {
self.thumbs
.peek(&id)
.into_iter()
.chain(self.previews.iter().filter(|e| e.0 == id).map(|e| &e.1))
.chain(self.full.iter().filter(|e| e.0 == id).map(|e| &e.1))
.filter(|s| s.camera_profile.as_deref() == profile)
};
match cached().find(|s| s.info.is_some()).or_else(|| cached().next()) {
Some(s) => s.info_or(header),
@@ -221,7 +226,13 @@ impl MediaCache {
self.insert_source(id, level, DecodedSource::new(img, None));
}
pub(super) fn insert_source(&mut self, id: PhotoId, level: SourceLevel, img: DecodedSource) {
/// A decoded source with what the decoder reported about it (tests: photos of another as-shot white).
#[cfg(test)]
pub(crate) fn insert_with_info(&mut self, id: PhotoId, level: SourceLevel, img: Arc<Rgb32f>, info: lightcraft_pipeline::SourceInfo) {
self.insert_source(id, level, DecodedSource::new(img, Some(info)));
}
pub(crate) fn insert_source(&mut self, id: PhotoId, level: SourceLevel, img: DecodedSource) {
let tick = lightcraft_preview::next_tick();
match level {
SourceLevel::Thumb => {
@@ -296,24 +307,50 @@ impl MediaCache {
self.source_ref_with(p, level, false)
}
/// [`Self::source_ref`] without the photo's imported camera profile (keeping its denoised picture): a smart
/// preview keeps the file's own colour, and a cached source developed with the profile doesn't stand in for it.
#[cfg(not(target_arch = "wasm32"))]
pub fn source_ref_without_profile(&mut self, p: &Photo, level: SourceLevel) -> SourceRef {
self.source_ref_for(p, level, true, None)
}
fn source_ref_with(&mut self, p: &Photo, level: SourceLevel, cached: bool) -> SourceRef {
let mut r = self.source_ref_plain(p, level, cached);
let wanted = self.camera_profile_of(p);
self.source_ref_for(p, level, cached, wanted)
}
/// [`Self::source_ref_with`] developed with camera profile `wanted` (none: the file's own colour).
fn source_ref_for(&mut self, p: &Photo, level: SourceLevel, cached: bool, wanted: Option<(String, Arc<DcpProfile>)>) -> SourceRef {
let mut r = self.source_ref_plain(p, level, cached, wanted);
if let (SourceRef::File { denoise, .. }, Some((spec, loader))) = (&mut r, self.denoise.get(p.id)) {
*denoise = Some((spec.clone(), loader.clone()));
}
r
}
fn source_ref_plain(&mut self, p: &Photo, level: SourceLevel, cached: bool) -> SourceRef {
if cached && let Some(a) = self.get_source(p.id, level) {
/// Is photo `p`'s original known to be missing (cached answer only)?
fn original_offline(&self, p: &Photo) -> bool {
matches!(&p.source, Source::File { path } if self.availability.is_offline(path))
}
fn source_ref_plain(&mut self, p: &Photo, level: SourceLevel, cached: bool, wanted: Option<(String, Arc<DcpProfile>)>) -> 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).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));
}
// a thumbnail of a photo whose preview is decoded (the one in the loupe) is cut from it; not
// with a denoised picture, which the thumbnail would lose
// with a denoised picture, which the thumbnail would lose, nor from one decoded with another camera profile
if cached
&& level == SourceLevel::Thumb
&& self.denoise.spec(p.id).is_none()
&& let Some(big) = self.get_source(p.id, SourceLevel::Preview)
&& 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() };
}
@@ -336,12 +373,38 @@ impl MediaCache {
return SourceRef::Smart { path: sp };
}
let mut r = self.origin_ref(&p.source, max_edge);
if let SourceRef::File { fallback, .. } = &mut r {
if let SourceRef::File { fallback, camera_profile, outliers: o, .. } = &mut r {
*fallback = Some(sp);
*camera_profile = wanted;
*o = outliers;
}
return r;
}
self.origin_ref(&p.source, max_edge)
let mut r = self.origin_ref(&p.source, max_edge);
if let SourceRef::File { camera_profile, outliers: o, .. } = &mut r {
*camera_profile = wanted;
*o = outliers;
}
r
}
/// The imported camera profile photo `p` develops with, when its profile setting names one this library has: what a
/// source decoded with it is tagged with (its id and the file's fingerprint), and the profile.
pub fn camera_profile_of(&self, p: &Photo) -> Option<(String, Arc<DcpProfile>)> {
let id = &p.develop.profile.id;
if !crate::cmd::dcp_profiles::is_dcp_id(id) {
return None;
}
self.camera_profiles.get(id).map(|d| (format!("{id}#{:016x}", d.fingerprint), d.profile.clone()))
}
/// What a render with profile `profile_id` adds to its cache keys: the imported camera profile's fingerprint, 0
/// for any other profile and for a camera profile this library no longer has (it renders without it).
pub fn camera_profile_salt(&self, profile_id: &str) -> u64 {
if !crate::cmd::dcp_profiles::is_dcp_id(profile_id) {
return 0;
}
self.camera_profiles.get(profile_id).map_or(0, |d| d.fingerprint)
}
/// How to load `origin` at most `max_edge` pixels long, ignoring decoded sources in memory (a
@@ -354,12 +417,28 @@ impl MediaCache {
}
match self.scenes.iter().find(|s| s.id == *scene) {
Some(s) => SourceRef::Demo { scene: Box::new(s.clone()), max_edge },
None => SourceRef::File { path: format!("demo:{scene}"), max_edge, loader: None, fallback: None, denoise: None, reduced: None },
None => SourceRef::File {
path: format!("demo:{scene}"),
max_edge,
loader: None,
fallback: None,
denoise: None,
camera_profile: None,
outliers: false,
reduced: None,
},
}
}
Source::File { path } => {
SourceRef::File { path: path.clone(), max_edge, loader: self.file_loader.clone(), fallback: None, denoise: None, reduced: None }
}
Source::File { path } => SourceRef::File {
path: path.clone(),
max_edge,
loader: self.file_loader.clone(),
fallback: None,
denoise: None,
camera_profile: None,
outliers: false,
reduced: None,
},
}
}
}
+39 -6
View File
@@ -25,6 +25,15 @@ pub struct QuickJob {
pub cached: Vec<(Arc<PreviewCache>, 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<PreviewCache>, 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.
@@ -49,6 +58,7 @@ impl QuickJob {
loaded: None,
quick: None,
display: None,
frame: None,
})
}
@@ -66,6 +76,7 @@ impl QuickJob {
loaded: None,
quick,
display: None,
frame: None,
};
let rendered = |image: Rgba8| {
let histogram = Histogram::of_srgb8(&image);
@@ -77,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();
@@ -98,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
+201 -11
View File
@@ -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,
};
@@ -32,6 +32,9 @@ pub struct RenderJob {
pub view_cache: Option<(Arc<PreviewCache>, Hash128)>,
/// Render for this monitor profile ([`Self::with_display`]).
pub display: Option<Arc<crate::display::Display>>,
/// Shown on screen at once and not kept: the result may stay on the GPU as a texture
/// ([`Self::on_screen`]).
pub on_screen: bool,
/// Compose the render into a slideshow slide ([`Self::with_slide`]).
pub slide: Option<Arc<crate::slide::SlideCompose>>,
/// A face tile that can be cut from the raw's embedded preview, tried before `source`
@@ -57,6 +60,17 @@ pub fn fit_for_display(img: &Rgba8, max_w: usize, max_h: usize) -> Rgba8 {
Rgba8 { width: small.width, height: small.height, data: small.data.iter().map(|p| [c(p[0]), c(p[1]), c(p[2]), c(p[3])]).collect() }
}
/// A render left on the GPU for the window to draw ([`RenderResult::frame`]).
#[cfg(not(target_arch = "wasm32"))]
pub type ScreenFrame = lightcraft_gpu::DisplayFrame;
/// A render left on the GPU for the window to draw (never, in the browser build).
#[cfg(target_arch = "wasm32")]
#[derive(Clone, Debug)]
pub struct ScreenFrame {
pub width: usize,
pub height: usize,
}
pub struct RenderResult {
pub request_id: u64,
pub source_key: Option<Hash128>,
@@ -74,6 +88,9 @@ pub struct RenderResult {
/// The display profile (id) the image is encoded for; `None`: sRGB (see
/// [`crate::display::present`]).
pub display: Option<u64>,
/// The result as a texture on the window's GPU device ([`RenderJob::on_screen`]); `rendered`
/// then holds its histogram and an empty image.
pub frame: Option<ScreenFrame>,
}
impl RenderJob {
@@ -123,6 +140,15 @@ impl RenderJob {
self
}
/// The result is only drawn (an interactive draft of a view): when the GPU renderer runs on the
/// window's device it may hand back a texture ([`RenderResult::frame`]) instead of reading the
/// pixels back. Ignored where pixels are needed: thumbnails (cached), a full-quality render
/// kept as the view preview, and a monitor profile (corrected on the CPU).
pub fn on_screen(mut self) -> Self {
self.on_screen = true;
self
}
/// Render with some colour grading wheels (shadows, midtones, highlights) switched off for
/// viewing (the wheel eyes in the Edit panel). The photo's settings are untouched; the result
/// gets its own key and is never cached as the photo's preview or thumbnail.
@@ -189,6 +215,7 @@ impl RenderJob {
loaded: None,
quick: None,
display: None,
frame: None,
}
}
@@ -214,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<Rgba8> {
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)
{
@@ -232,6 +309,7 @@ impl RenderJob {
loaded: None,
quick: None,
display: None,
frame: None,
};
}
// a face tile of an unedited raw: cut from the camera's embedded preview when it is big enough
@@ -252,6 +330,7 @@ impl RenderJob {
loaded: None,
quick: None,
display: None,
frame: None,
};
}
let was_loaded = matches!(self.source, SourceRef::Loaded(_));
@@ -267,14 +346,43 @@ impl RenderJob {
// the plain picture, or (Denoise amount above 0 and a denoised picture cached) the mix the amount asks for
let src = &source.image_for(self.settings.denoise_amount());
let info = source.info_or(self.info);
// Thumbnails (many small jobs side by side) stay on the CPU; views and exports use
// the GPU when there is one.
let gpu = self.cache.is_none();
// Views and exports use the GPU when there is one (waiting for the device if it is
// still being created). Thumbnails (grid, filmstrip, preset and profile previews)
// use it once it is ready - ~20-30 % faster than the CPU at 256 px with six jobs
// side by side (`crates/gpu/tests/it/thumbs_bench.rs`), and the cores stay free for
// decoding - but never wait for it: at startup they render on the CPU.
let gpu = self.cache.is_none() || lightcraft_gpu::ready();
// a clipping preview tests sRGB values, like the histogram: rendered in sRGB, then
// converted for the display below
let clip_view = self.request.overlay.is_clipping();
let request = if clip_view { RenderRequest { display: None, ..self.request } } else { self.request };
let (mut rendered, gpu_fallback) = develop_reporting(src, &info, &self.settings, &request, self.stages.as_deref(), gpu);
let pixels_needed =
self.cache.is_some() || self.display.is_some() || (self.view_cache.is_some() && self.request.quality == Quality::Full);
let frame = (self.on_screen && !pixels_needed && gpu)
.then(|| develop_on_screen(src, &info, &self.settings, &request, self.stages.as_deref()));
let (mut rendered, gpu_fallback) = match frame {
Some(OnScreen::Frame(frame, histogram)) => {
return RenderResult {
request_id: self.request_id,
source_key: self.source_key,
photo: self.photo,
level: self.level,
key: self.key,
rendered: Ok(Rendered {
image: lightcraft_raster::Rgba8 { width: 0, height: 0, data: Vec::new() },
histogram,
deep: None,
}),
gpu_fallback: None,
loaded: (!was_loaded).then_some(source),
quick: None,
display: None,
frame: Some(frame),
};
}
Some(OnScreen::Pixels(r)) => (r, None),
None => develop_reporting(src, &info, &self.settings, &request, self.stages.as_deref(), gpu),
};
// for a display profile: the image goes to the display's values, the histogram
// and the cached view preview stay sRGB
let mut srgb = None;
@@ -329,6 +437,7 @@ impl RenderJob {
loaded: (!was_loaded).then_some(source),
quick: None,
display,
frame: None,
}
}
Err(e) => self.failed(e),
@@ -336,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<Rgba8> {
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.
@@ -370,12 +534,8 @@ fn develop_image(
stages: Option<&StageCache>,
gpu: bool,
) -> (Rendered, Option<String>) {
// LUT profiles have no GPU stage: they render on the CPU
let fallback = if gpu
&& !lightcraft_pipeline::lut::is_lut_profile(&s.profile.id)
&& !s.masks.iter().any(|m| m.visible && m.refine > 0.0)
&& req.proof.is_none()
{
// (LUT profiles, Refine Edges and soft proofs render on the GPU too)
let fallback = if gpu {
match lightcraft_gpu::try_render(src, info, s, req, stages) {
Ok(r) => return (r, None),
Err(lightcraft_gpu::Fallback::Failed(why)) => Some(why),
@@ -390,3 +550,33 @@ fn develop_image(
};
(rendered, fallback)
}
/// What [`develop_on_screen`] made.
enum OnScreen {
/// A texture on the window's device, and the histogram (never in the browser build).
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
Frame(ScreenFrame, Histogram),
/// Pixels (GPU or CPU).
Pixels(Rendered),
}
/// [`develop`] for a render that is only drawn: a texture on the window's device when the GPU
/// renderer can hand one over, else the pixels.
fn develop_on_screen(src: &Arc<Rgb32f>, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest, stages: Option<&StageCache>) -> OnScreen {
#[cfg(not(target_arch = "wasm32"))]
match lightcraft_gpu::render_display(src, info, s, req, stages) {
// an HDR edit's histogram shows the HDR range, as `develop_reporting` gives it
Some(lightcraft_gpu::Output::Display { frame, histogram }) => {
OnScreen::Frame(frame, lightcraft_pipeline::hdr_histogram(src, info, s, req).unwrap_or(histogram))
}
Some(lightcraft_gpu::Output::Image(mut r)) => {
if let Some(h) = lightcraft_pipeline::hdr_histogram(src, info, s, req) {
r.histogram = h;
}
OnScreen::Pixels(r)
}
None => OnScreen::Pixels(develop(src, info, s, req, stages, false)),
}
#[cfg(target_arch = "wasm32")]
OnScreen::Pixels(develop(src, info, s, req, stages, false))
}
+156 -25
View File
@@ -1,5 +1,6 @@
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};
use super::{Arc, DevelopSettings, Hash128, Hasher128, MediaKind, Op, Photo, PhotoId, RenderRequest, Rendered, Rgb32f, Source, SourceInfo};
@@ -41,7 +42,14 @@ impl crate::Session {
} else {
source_edge_needed(&p, &settings, apply_crop, max_w.max(max_h))
});
let source = self.media.source_ref(&p, level);
// the Before side develops with the Before settings' camera profile (or none), not the edit's
let source = if before {
let mut q = (*p).clone();
q.develop = settings.clone();
self.media.source_ref(&q, level)
} else {
self.media.source_ref(&p, level)
};
let request = RenderRequest { apply_crop, ..RenderRequest::fit(max_w, max_h) };
// the photo id is part of the key: two photos with the same settings and size must not
// share a result (a view slot showing photo A would otherwise look current for photo B)
@@ -50,8 +58,10 @@ 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);
let key = settings_hash
^ ((max_w as u64) << 40)
@@ -61,14 +71,20 @@ impl crate::Session {
^ id.0.wrapping_mul(0x9e37_79b9_7f4a_7c15)
^ content.rotate_left(17)
^ salt
^ lens.rotate_left(29);
^ profile_salt.rotate_left(29)
^ lens.rotate_left(37);
let cache = thumb_bucket.map(|b| {
let mut k = Hasher128::new();
k.str(&content_key).u64(settings_hash).u64(b as u64).u64(RENDER_CACHE_VERSION).u64(crate::camera_profiles::cache_key());
k.str(&content_key).u64(settings_hash).u64(b as u64).u64(RENDER_CACHE_VERSION);
with_process(&mut k, &settings).u64(crate::camera_profiles::cache_key());
// (only a render that uses a denoised picture has it in its key, so every other thumbnail stays valid)
if salt != 0 {
k.u64(salt);
}
// (likewise an imported camera profile's file: deleted or replaced, the thumbnail renders afresh)
if profile_salt != 0 {
k.str("dcp").u64(profile_salt);
}
// (likewise a database lens profile: thumbnails of every other photo keep their keys)
if lens != 0 {
k.u64(lens);
@@ -91,6 +107,7 @@ impl crate::Session {
stages: None,
view_cache: None,
display: None,
on_screen: false,
slide: None,
preview_cut: None,
display_fit: None,
@@ -101,27 +118,43 @@ impl crate::Session {
/// temporary preview while hovering a preset or profile; nothing is committed or cached).
pub fn preview_job(&mut self, id: PhotoId, max_w: usize, max_h: usize, apply_crop: bool, settings: &DevelopSettings) -> Option<RenderJob> {
let mut job = self.render_job(id, max_w, max_h, false, apply_crop)?;
// the source as these settings develop it: another camera profile (or none) decodes anew
let mut p = (**self.catalog.photo(id)?).clone();
let own_profile = self.media.camera_profile_of(&p).map(|c| c.0);
p.develop = Arc::new(settings.clone());
if self.media.camera_profile_of(&p).map(|c| c.0) != own_profile {
job.source = self.media.source_ref(&p, job.level);
}
job.settings = Arc::new(settings.clone());
// (the imported camera profile's file is in the key, as in `render_job`'s: a profile file replaced under the
// same id is a new picture)
let profile_salt = self.media.camera_profile_salt(&settings.profile.id);
// (the photo's database lens profile stays part of it: a profile looked up again renders afresh)
let lens = self.catalog.photo(id).map_or(0, |p| super::quick::lens_key(p));
job.key = settings.hash64()
^ crate::files::hot_pixel_key(settings)
^ ((max_w as u64) << 40)
^ ((max_h as u64) << 20)
^ (apply_crop as u64)
^ (job.level as u64) << 60
^ lens.rotate_left(29);
^ profile_salt.rotate_left(29)
^ lens.rotate_left(37);
Some(job)
}
/// Cache key of a variant thumbnail ([`Self::variant_job`]).
pub fn variant_key(p: &Photo, settings: &DevelopSettings, edge: usize) -> Hash128 {
/// `profile_salt`: [`MediaCache::camera_profile_salt`] of `settings`' profile.
pub fn variant_key(p: &Photo, settings: &DevelopSettings, edge: usize, profile_salt: u64) -> Hash128 {
let mut k = Hasher128::new();
k.str(&content_key(p))
.str("variant")
.u64(settings.hash64())
.u64(settings.hash64() ^ crate::files::hot_pixel_key(settings))
.u64(edge as u64)
.u64(RENDER_CACHE_VERSION)
.u64(crate::camera_profiles::cache_key());
.u64(RENDER_CACHE_VERSION);
with_process(&mut k, settings).u64(crate::camera_profiles::cache_key());
if profile_salt != 0 {
k.str("dcp").u64(profile_salt);
}
let lens = super::quick::lens_key(p);
if lens != 0 {
k.u64(lens);
@@ -135,11 +168,13 @@ impl crate::Session {
/// hash, so a variant renders once; `key` is derived from the same hash, so a frontend can
/// keep one texture per variant.
pub fn variant_job(&mut self, id: PhotoId, settings: &DevelopSettings, edge: usize) -> Option<RenderJob> {
let p = self.catalog.photo(id)?.clone();
let mut p = (**self.catalog.photo(id)?).clone();
let edge = edge.clamp(16, SourceLevel::Thumb.max_edge());
let level = SourceLevel::Thumb;
// decoded as these settings develop it (their camera profile, or none)
p.develop = Arc::new(settings.clone());
let source = self.media.source_ref(&p, level);
let ck = Self::variant_key(&p, settings, edge);
let ck = Self::variant_key(&p, settings, edge, self.media.camera_profile_salt(&settings.profile.id));
Some(RenderJob {
request_id: 0,
cache_generation: self.media.rendered.generation(),
@@ -156,6 +191,7 @@ impl crate::Session {
stages: None,
view_cache: None,
display: None,
on_screen: false,
slide: None,
preview_cut: None,
display_fit: None,
@@ -193,7 +229,7 @@ impl crate::Session {
let needed = (edge as f64 * w.max(h) / side).ceil().min(SourceLevel::Preview.max_edge() as f64);
let level = SourceLevel::for_size(needed as usize);
let source = self.media.source_ref(&p, level);
let ck = Self::variant_key(&p, &settings, edge);
let ck = Self::variant_key(&p, &settings, edge, self.media.camera_profile_salt(&settings.profile.id));
let preview_cut = self.face_preview_cut(&p, rect, edge, needed as usize);
Some(RenderJob {
request_id: 0,
@@ -211,6 +247,7 @@ impl crate::Session {
stages: None,
view_cache: None,
display: None,
on_screen: false,
slide: None,
preview_cut,
display_fit: None,
@@ -233,16 +270,26 @@ 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`].
pub(crate) fn view_key(p: &Photo, apply_crop: bool) -> 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(p.develop.hash64() ^ crate::files::hot_pixel_key(&p.develop))
.u64(apply_crop as u64)
.u64(RENDER_CACHE_VERSION)
.u64(crate::camera_profiles::cache_key());
.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);
}
let lens = super::quick::lens_key(p);
if lens != 0 {
k.u64(lens);
@@ -255,7 +302,7 @@ impl crate::Session {
pub fn loupe_job(&mut self, id: PhotoId, max_w: usize, max_h: usize, apply_crop: bool) -> Option<RenderJob> {
let mut job = self.render_job(id, max_w, max_h, false, apply_crop)?;
let p = self.catalog.photo(id)?;
job.view_cache = Some((self.media.rendered.clone(), Self::view_key(p, apply_crop)));
job.view_cache = Some((self.media.rendered.clone(), self.view_key(p, apply_crop)));
Some(job)
}
@@ -364,11 +411,56 @@ impl crate::Session {
let p = self.catalog.photo(id)?.clone();
let small = self.thumb_job(id, THUMB_SIZES[THUMB_SIZES.len() - 1])?;
// (the thumbnail job itself starts with the cached thumbnail, after the sharper embedded preview)
let cached = vec![(self.media.rendered.clone(), Self::view_key(&p, apply_crop))];
let h = Hasher128::new().str(&content_key(&p)).str("quick").u64(p.develop.hash64()).u64(apply_crop as u64).finish();
let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id);
let cached = vec![(self.media.rendered.clone(), self.view_key(&p, apply_crop))];
// (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<QuickJob> {
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
@@ -387,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())),
})
@@ -496,8 +592,10 @@ impl crate::Session {
/// Prefer decoder facts to header-only metadata for pixel-statistics commands.
pub fn source_info(&self, id: PhotoId) -> SourceInfo {
let header = self.catalog.photo(id).map(|p| source_info(p)).unwrap_or_default();
self.media.source_facts(id, header)
let photo = self.catalog.photo(id);
let header = photo.map(|p| source_info(p)).unwrap_or_default();
let profile = photo.and_then(|p| self.media.camera_profile_of(p)).map(|(tag, _)| tag);
self.media.source_facts(id, header, profile.as_deref())
}
/// The source proxy for pixel-statistics commands (auto tone/WB), loading synchronously.
@@ -511,4 +609,37 @@ impl crate::Session {
self.media.insert_source(id, level, r);
Ok(image)
}
/// [`Session::source_now`] for several photos at once, each with the facts its decoder gave
/// ([`Session::source_info`], read before another photo can push it out of the cache): the
/// ones not in memory are decoded in parallel, so a selection costs about one decode per core,
/// not one after another. In the order of `ids`. Callers pass a few at a time (all of them are
/// held decoded until this returns).
pub(crate) fn sources_now(&mut self, ids: &[PhotoId], level: SourceLevel) -> Vec<(PhotoId, Result<(Arc<Rgb32f>, SourceInfo), String>)> {
use rayon::prelude::*;
let refs: Vec<(PhotoId, Option<SourceRef>)> =
ids.iter().map(|&id| (id, self.catalog.photo(id).cloned().map(|p| self.media.source_ref(&p, level)))).collect();
let loaded: Vec<(PhotoId, Result<super::source::DecodedSource, String>)> =
refs.into_par_iter().map(|(id, r)| (id, r.ok_or_else(|| "no such photo".to_string()).and_then(|r| r.load_source()))).collect();
loaded
.into_iter()
.map(|(id, r)| {
let r = r.map(|r| {
let image = r.image.clone();
if let Some(info) = &r.info {
self.learn_as_shot_wb(id, info);
}
// read before the insert: the cache's budget may evict this very entry, and
// the header facts alone lack the decoder's camera colour
let facts = match r.info {
Some(_) => r.info_or(self.catalog.photo(id).map(|p| source_info(p)).unwrap_or_default()),
None => self.source_info(id),
};
self.media.insert_source(id, level, r);
(image, facts)
});
(id, r)
})
.collect()
}
}
+17 -2
View File
@@ -1,4 +1,4 @@
use super::{Arc, DevelopSettings, HashMap, PhotoId, VecDeque, Weak};
use super::{Arc, DevelopSettings, HashMap, Hasher128, PhotoId, VecDeque, Weak};
pub(super) const SETTINGS_HASH_ENTRIES: usize = 1024;
@@ -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;
@@ -34,3 +34,18 @@ impl SettingsHashes {
hash
}
}
/// Add the rendering process `s` renders with in this build to persistent render key `h`, from
/// process V3 on: a process number from a newer LightCraft renders with an older build's latest
/// process, so the same settings (and settings hash) render differently in a build that knows that
/// process, and the keys must tell those renders apart. Builds before V3 (which have no process in
/// their keys) resolve every number above V2 to V2: naming V3 and later keeps this build's renders
/// of those numbers apart from theirs, and V1 and V2 keep the keys they always had, so their
/// cached renders stay valid (`docs/process-versions.md`).
pub(super) fn with_process<'a>(h: &'a mut Hasher128, s: &DevelopSettings) -> &'a mut Hasher128 {
let v = s.process.process().version().0;
if v >= lightcraft_develop::Process::V3.version().0 {
h.u64(u64::from(v));
}
h
}
+66 -14
View File
@@ -1,7 +1,7 @@
use super::{Arc, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo};
use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo};
/// Bump when the pipeline's output changes, to invalidate cached thumbnails.
pub const RENDER_CACHE_VERSION: u64 = 75;
pub const RENDER_CACHE_VERSION: u64 = 76;
/// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache).
pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512];
@@ -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,13 +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).
pub type FileLoader = Arc<dyn Fn(&str, usize) -> 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<dyn Fn(&str, usize, RawDecode<'_>) -> 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<dyn Fn(&str, usize) -> Result<(Rgb32f, SourceInfo, bool), String> + Send + Sync>;
pub type ReducedLoader = Arc<dyn Fn(&str, usize, RawDecode<'_>) -> Result<(Rgb32f, SourceInfo, bool), String> + Send + Sync>;
/// A raw file's embedded (camera-rendered) preview as display sRGB, oriented, no larger than
/// `max_edge` (set by the app). `None`: no usable preview.
@@ -103,7 +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<dyn Fn(&str, usize, &DenoiseSpec) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> + Send + Sync>;
pub type PairLoader = Arc<dyn Fn(&str, usize, &DenoiseSpec, RawDecode<'_>) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> + Send + Sync>;
/// A photo's denoised picture next to its plain one, and the last mix of the two that was asked for.
pub struct Twin {
@@ -133,6 +155,11 @@ pub struct DecodedSource {
pub camera_tone: Option<lightcraft_pipeline::tone::CameraTone>,
/// The same picture developed from the AI-denoised mosaic, when the photo has one cached.
pub denoised: Option<Arc<Twin>>,
/// 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<String>,
/// 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,
@@ -143,7 +170,14 @@ pub struct DecodedSource {
impl DecodedSource {
pub fn new(image: Arc<Rgb32f>, info: Option<SourceInfo>) -> Self {
DecodedSource { image, info, camera_tone: None, denoised: None, from_proxy: false, reduced: false }
DecodedSource { image, info, camera_tone: None, denoised: None, camera_profile: None, 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,
@@ -235,6 +269,10 @@ pub enum SourceRef {
fallback: Option<std::path::PathBuf>,
/// The photo has a cached denoised picture: load it with the plain one (see [`PairLoader`]).
denoise: Option<(DenoiseSpec, PairLoader)>,
/// The photo's imported camera profile (id and profile): its raw file is developed with it.
camera_profile: Option<(String, Arc<DcpProfile>)>,
/// 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<ReducedLoader>,
},
@@ -262,12 +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, reduced } => {
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).map(|(image, info, reduced)| DecodedSource { reduced, ..DecodedSource::new(Arc::new(image), Some(info)) })
}
(None, Some(l)) => l(path, *max_edge).map(|(image, info)| DecodedSource::new(Arc::new(image), Some(info))),
(Some(l), _) => l(path, *max_edge, 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, None) => Err(format!("no decoder available for {path}")),
};
// the denoised picture comes with the plain one from a single decode; when it cannot be read the
@@ -281,7 +328,7 @@ impl SourceRef {
None => true,
};
if made {
pair(path, *max_edge, spec).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());
}
@@ -290,6 +337,8 @@ impl SourceRef {
info: Some(info),
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,
})
@@ -341,6 +390,9 @@ pub struct ProbeInfo {
pub embedded_lens: Option<lightcraft_develop::EmbeddedLens>,
/// The file's embedded XMP packet (raw/DNG files), for develop settings stored inside the file.
pub xmp: Option<String>,
/// 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<lightcraft_geom::Orientation>,
/// 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<String>,
+6 -2
View File
@@ -83,13 +83,15 @@ fn decoder_info_survives_render_jobs_cache_and_eviction() {
job.source = SourceRef::File {
path: "synthetic.arw".into(),
max_edge: 64,
loader: Some(Arc::new(move |_, _| {
loader: Some(Arc::new(move |_, _, _| {
let mut image = Rgb32f::new(64, 64);
image.data.fill([0.1; 3]);
Ok((image, loaded_info.clone()))
})),
fallback: None,
denoise: None,
camera_profile: None,
outliers: false,
reduced: None,
};
job.info = SourceInfo::default(); // Header facts cannot override decoder facts.
@@ -143,9 +145,11 @@ fn old_relative_white_balance_on_a_kelvin_camera_keeps_its_look_and_learns_the_a
job.source = SourceRef::File {
path: "/photos/DSC00001.ARW".into(),
max_edge: 64,
loader: Some(Arc::new(move |_, _| Ok((loaded_pixels.clone(), loaded_info.clone())))),
loader: Some(Arc::new(move |_, _, _| Ok((loaded_pixels.clone(), loaded_info.clone())))),
fallback: None,
denoise: None,
camera_profile: None,
outliers: false,
reduced: None,
};
let undo_before = s.undo.len();
+249 -3
View File
@@ -6,6 +6,131 @@ 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::<Rgba8>));
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
/// loupe's view render, variants) name the process the settings render with, so those are
/// never served (review of 5a7016c8: a catalog saved with a newer process kept main's V2 thumbnails).
#[test]
fn persistent_keys_name_the_process_the_settings_render_with() {
use lightcraft_develop::ProcessVersion;
let mut s = session();
let newer = DevelopSettings { process: ProcessVersion(ProcessVersion::LATEST.0 + 1), ..DevelopSettings::default() };
s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(newer.clone()), label: "newer".into(), edited: None }).unwrap();
let p = s.catalog.photo(PhotoId(1)).unwrap().clone();
let unnamed = |kind: Option<&str>, size: u64| {
let mut h = Hasher128::new();
h.str(&content_key(&p));
if let Some(k) = kind {
h.str(k);
}
h.u64(newer.hash64()).u64(size).u64(RENDER_CACHE_VERSION).u64(crate::camera_profiles::cache_key()).finish()
};
let named = |kind: Option<&str>, size: u64, process: u64| {
let mut h = Hasher128::new();
h.str(&content_key(&p));
if let Some(k) = kind {
h.str(k);
}
h.u64(newer.hash64()).u64(size).u64(RENDER_CACHE_VERSION).u64(process).u64(crate::camera_profiles::cache_key()).finish()
};
let resolved = u64::from(lightcraft_develop::Process::LATEST.version().0);
let keys = [
(s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1, None, 256),
(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 {
assert_ne!(key, unnamed(kind, size), "old builds did not name their resolved process");
assert_eq!(key, named(kind, size, resolved), "the key names the process used for rendering");
assert_ne!(key, named(kind, size, u64::from(newer.process.0)), "the saved future number is not the resolved process");
}
}
/// Photos on V1 and V2 keep the persistent keys builds before process V3 gave them (no process
/// in them), so their cached thumbnails, view renders and variants stay valid after upgrading
/// (review of 26cd2df1: every V1/V2 photo rendered again, and offline ones without smart
/// previews lost their thumbnails); V3 and later name their process.
#[test]
fn v1_and_v2_photos_keep_the_render_cache_keys_they_had() {
use lightcraft_develop::Process;
let mut s = session();
for process in [Process::V1, Process::V2, Process::V3] {
let settings = DevelopSettings { process: process.version(), ..DevelopSettings::default() };
s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(settings.clone()), label: "p".into(), edited: None }).unwrap();
let p = s.catalog.photo(PhotoId(1)).unwrap().clone();
let before_v3 = |kind: Option<&str>, size: u64| {
let mut h = Hasher128::new();
h.str(&content_key(&p));
if let Some(k) = kind {
h.str(k);
}
h.u64(settings.hash64()).u64(size).u64(RENDER_CACHE_VERSION).u64(crate::camera_profiles::cache_key()).finish()
};
let keys = [
s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1 == before_v3(None, 256),
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;
assert_eq!(keys, [old; 3], "{process:?}: thumbnail, view and variant keys");
}
}
#[test]
fn hashes_match_uncached_keys_and_are_not_recomputed_for_sizes_metadata_or_before() {
let mut s = session();
@@ -21,6 +146,7 @@ fn hashes_match_uncached_keys_and_are_not_recomputed_for_sizes_metadata_or_befor
.u64(settings)
.u64(b as u64)
.u64(RENDER_CACHE_VERSION)
.u64(u64::from(p.develop.process.process().version().0))
.u64(crate::camera_profiles::cache_key())
.finish();
let job = s.thumb_job(p.id, edge).unwrap();
@@ -70,7 +196,7 @@ fn hash_cache_is_bounded_weak_and_shared_settings_remain_independent() {
#[test]
fn source_from_before_content_reload_is_not_accepted() {
let mut s = session();
s.media.file_loader = Some(Arc::new(|_, _| Ok((Rgb32f::new(8, 8), SourceInfo::default()))));
s.media.file_loader = Some(Arc::new(|_, _, _| Ok((Rgb32f::new(8, 8), SourceInfo::default()))));
let old = s.thumb_job(PhotoId(1), 256).unwrap().run();
assert!(old.loaded.is_some());
s.catalog
@@ -94,7 +220,7 @@ fn source_from_before_content_reload_is_not_accepted() {
#[test]
fn source_from_before_a_lens_profile_change_is_not_accepted() {
let mut s = session();
s.media.file_loader = Some(Arc::new(|_, _| Ok((Rgb32f::new(8, 8), SourceInfo::default()))));
s.media.file_loader = Some(Arc::new(|_, _, _| Ok((Rgb32f::new(8, 8), SourceInfo::default()))));
let old = s.thumb_job(PhotoId(1), 256).unwrap().run();
assert!(old.loaded.is_some());
let lens = lightcraft_develop::EmbeddedLens { source: lightcraft_develop::LensSource::Database, ..Default::default() };
@@ -132,7 +258,7 @@ fn a_hover_preview_key_follows_the_lens_profile() {
#[test]
fn a_render_that_panics_fails_instead_of_never_answering() {
let mut s = session();
s.media.file_loader = Some(Arc::new(|_, _| panic!("decoder bug")));
s.media.file_loader = Some(Arc::new(|_, _, _| panic!("decoder bug")));
let mut job = s.thumb_job(PhotoId(1), 256).unwrap();
job.request_id = 42;
let (key, level, source_key) = (job.key, job.level, job.source_key);
@@ -145,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<Rgba8> { panic!("preview reader bug") }), 256)),
embedded_cache: None,
embedded_on_disk: false,
minimum_embedded_edge: None,
small: None,
};
@@ -152,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");
}
}
+532
View File
@@ -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<Scope> {
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<PrepSettings, String> {
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<Mode> {
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<PrepSettings>,
/// The background build this preparation started.
build: Option<Arc<PreviewBuild>>,
/// The view (its signature) whose build was started, or that the user stopped.
started_for: Option<u64>,
declined_for: Option<u64>,
/// 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<u64>,
last_at: Option<PhotoId>,
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<web_time::Instant> = 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<std::time::Duration> {
// (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<PhotoId>, 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<u64> = 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<PrepSettings>) -> 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");
}
}
+32 -13
View File
@@ -523,7 +523,23 @@ impl Session {
if let Some(p) = profile(id) {
return Some((p.name, p.group));
}
self.lut_profiles.iter().find(|p| p.id == id).map(|p| (p.name.as_str(), p.group.as_str()))
if let Some(p) = self.lut_profiles.iter().find(|p| p.id == id) {
return Some((p.name.as_str(), p.group.as_str()));
}
self.dcp_profiles.iter().find(|p| p.id == id).map(|p| (p.name.as_str(), crate::cmd::dcp_profiles::DCP_GROUP))
}
/// The imported profiles as (id, name, group): LUT profiles, then camera profiles (`.dcp`). A camera profile
/// whose file is missing or damaged (not loaded when the library opened) is left out, so it can't be chosen; its
/// entry stays and it is offered again once the file is back.
pub fn imported_profiles(&self) -> Vec<(String, String, String)> {
let luts = self.lut_profiles.iter().map(|p| (p.id.clone(), p.name.clone(), p.group.clone()));
let dcps = self
.dcp_profiles
.iter()
.filter(|p| self.media.camera_profiles.contains_key(&p.id))
.map(|p| (p.id.clone(), p.name.clone(), crate::cmd::dcp_profiles::DCP_GROUP.to_string()));
luts.chain(dcps).collect()
}
/// Remember `id` as the most recently applied profile.
@@ -537,28 +553,31 @@ impl Session {
pub fn profile_menu(&self) -> Value {
let item =
|p: &ProfileInfo| json!({"id": p.id, "name": p.name, "group": p.group, "favorite": self.profile_favorites.iter().any(|f| f == p.id)});
let lut_item = |id: &str| {
self.lut_profiles
.iter()
.find(|p| p.id == id)
.map(|p| json!({"id": p.id, "name": p.name, "group": p.group, "favorite": self.profile_favorites.contains(&p.id), "imported": true}))
let imported = self.imported_profiles();
let imported_item = |(id, name, group): &(String, String, String)| {
let mut v = json!({"id": id, "name": name, "group": group, "favorite": self.profile_favorites.contains(id), "imported": true});
if let Some(d) = self.dcp_profiles.iter().find(|d| &d.id == id) {
v["cameraModel"] = json!(d.camera_model);
}
v
};
let lut_item = |id: &str| imported.iter().find(|p| p.0 == id).map(imported_item);
let list = |ids: &[String]| ids.iter().filter_map(|id| profile(id).map(item).or_else(|| lut_item(id))).collect::<Vec<_>>();
let mut groups: Vec<Value> = profile_groups()
.into_iter()
.map(|g| json!({"name": g, "profiles": PROFILES.iter().filter(|p| p.group == g).map(item).collect::<Vec<_>>()}))
.collect();
// imported LUT profiles, by their groups
// imported LUT profiles by their groups, then camera profiles
let mut lut_groups: Vec<&str> = self.lut_profiles.iter().map(|p| p.group.as_str()).collect();
lut_groups.sort_unstable();
lut_groups.dedup();
// the camera profiles' group once, last (a LUT group of the same name joins it rather than showing twice)
lut_groups.retain(|g| *g != crate::cmd::dcp_profiles::DCP_GROUP);
if imported.iter().any(|p| p.2 == crate::cmd::dcp_profiles::DCP_GROUP) {
lut_groups.push(crate::cmd::dcp_profiles::DCP_GROUP);
}
for g in lut_groups {
let profiles: Vec<Value> = self
.lut_profiles
.iter()
.filter(|p| p.group == g)
.map(|p| json!({"id": p.id, "name": p.name, "group": p.group, "favorite": self.profile_favorites.contains(&p.id), "imported": true}))
.collect();
let profiles: Vec<Value> = imported.iter().filter(|p| p.2 == g).map(imported_item).collect();
groups.push(json!({"name": g, "profiles": profiles, "imported": true}));
}
json!({
+576 -2
View File
@@ -159,6 +159,12 @@ pub struct SidecarData {
pub extended_description: Option<String>,
pub keywords: Option<Vec<String>>,
pub regions: Option<Vec<lightcraft_meta::Region>>,
/// 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<lightcraft_meta::Orientation>,
/// 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<String>,
@@ -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<lightcraft_meta::Orientation> {
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::Orientation> {
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<lightcraft_meta::Orientation> {
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<lightcraft_meta::Orientation> {
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<lightcraft_meta::Orientation> {
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<lightcraft_meta::Orientation> {
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<lightcraft_meta::Orientation> {
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<lightcraft_meta::Orientation> {
// 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<lightcraft_meta::Orientation> {
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<Vec<u8>> {
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<String> {
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<T>(reader: &mut (impl Read + Seek), header_span: u64, marker_steps: usize, mut pick: impl FnMut(&[u8]) -> Option<T>) -> Option<T> {
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<u8>)]| {
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<u8>], late: &[Vec<u8>]| {
let app1 = |j: &mut Vec<u8>, payload: &Vec<u8>| {
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<u8>)]| {
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(&section);
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()));
+1
View File
@@ -363,6 +363,7 @@ impl TitleCompose {
quick: None,
display: None,
gpu_fallback: None,
frame: None,
}
}
}
+2
View File
@@ -502,6 +502,8 @@ pub fn load(path: &Path) -> Result<crate::media::DecodedSource, String> {
info,
camera_tone,
denoised: None,
camera_profile: None,
outliers: false,
from_proxy: true,
reduced: false,
})
+2 -2
View File
@@ -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 {
+132
View File
@@ -0,0 +1,132 @@
//! Auto Sync carries the active photo's VALUE to every selected photo, as Lightroom Classic does
//! (test notes 2026-10-24 note 18, the user's rule "same value for all synced values"). Where white
//! balance is a mode rather than a number, the mode travels and each photo applies it to itself:
//! As Shot gives each photo its own camera white, Auto each photo's own white from its pixels, a
//! light preset its numbers.
//!
//! A typed or dragged Temp or Tint is set on each photo's own scale: a raw edited in Kelvin gets
//! the same Kelvin (an old relative-scale value converted first, never read as Kelvin, which turned
//! photos blue: test notes 2026-10-15), and only the slider that moved changes (a Temp move keeps
//! each photo's own tint). A photo on another scale than the active one (a JPEG next to a raw) has
//! no "same" number and moves by as much as the active photo instead.
use std::collections::HashMap;
use lightcraft_catalog::PhotoId;
use lightcraft_develop::{DevelopSettings, WbMode};
use lightcraft_pipeline::SourceInfo;
use crate::Session;
/// White balance on this source is edited in Kelvin (a raw with a measured camera scale), not on
/// the relative scale (6500 K / 0 = as shot).
fn kelvin(info: &SourceInfo) -> bool {
info.raw && !info.relative_wb
}
/// The temperature and tint `mode` stands for on a source with `info` (As Shot and the light
/// presets; `None` for Auto and Custom, which need the pixels or the numbers).
fn wb_of_mode(info: &SourceInfo, mode: WbMode) -> Option<(f64, f64)> {
match mode {
WbMode::AsShot => Some((info.as_shot_temp, info.as_shot_tint)),
m => m.preset().map(|(t, ti)| {
// presets are Kelvin on raws with that scale, relative to daylight (6500 K = as shot) elsewhere
if kelvin(info) { (t, ti) } else { (6500.0 * t / 5500.0, ti) }
}),
}
}
/// `synced.wb` for a photo (source `oinfo`, settings `own` before the sync) when the active
/// photo's white balance went from `old` to `new` (source `ainfo`). `auto`: the photo's own Auto
/// white balance, when `new` is Auto (`None`: it couldn't be worked out, and the photo keeps its
/// white balance).
pub(crate) fn synced_wb(
ainfo: &SourceInfo,
old: &DevelopSettings,
new: &DevelopSettings,
oinfo: &SourceInfo,
own: &DevelopSettings,
auto: Option<(f64, f64)>,
synced: &mut DevelopSettings,
) {
use lightcraft_pipeline::local::{effective_wb, normalize_wb};
let mut d = own.clone();
normalize_wb(&mut d, oinfo);
// A light preset with numbers of its own (`develop.wb {mode, tint}` on a photo on the
// relative scale, where the stored numbers are what renders): those numbers travel, as a
// Custom white balance does (review of #3585)
let overridden = new.wb.mode.preset().is_some()
&& wb_of_mode(ainfo, new.wb.mode).is_some_and(|(t, ti)| {
let (at, ati) = effective_wb(ainfo, new);
(at - t).abs() > 1e-6 || (ati - ti).abs() > 1e-6
});
let mode = if overridden { WbMode::Custom } else { new.wb.mode };
let resolved = match mode {
WbMode::Auto => auto,
WbMode::Custom => None,
m => wb_of_mode(oinfo, m),
};
match (mode, resolved) {
(WbMode::Custom, _) => {
let (ot, oti) = effective_wb(oinfo, own);
let (at0, ati0) = effective_wb(ainfo, old);
let (at, ati) = effective_wb(ainfo, new);
let same_scale = kelvin(ainfo) == kelvin(oinfo);
// only what moved: a Temp move leaves each photo's own tint
let pick = |own: f64, was: f64, now: f64| {
if (now - was).abs() < 1e-9 {
own
} else if same_scale {
now
} else {
own + (now - was)
}
};
d.wb.temp = pick(ot, at0, at);
d.wb.tint = pick(oti, ati0, ati);
d.wb.mode = WbMode::Custom;
}
(m, Some((t, ti))) => {
d.wb.temp = t;
d.wb.tint = ti;
d.wb.mode = m;
}
// Auto couldn't be worked out on this photo (its pixels didn't load): it keeps its own
(_, None) => {
synced.wb = own.wb;
return;
}
}
let (t, ti) = (d.wb.temp, d.wb.tint);
lightcraft_develop::controls::set(&mut d, "wb.temp", t);
lightcraft_develop::controls::set(&mut d, "wb.tint", ti);
synced.wb = d.wb;
}
impl Session {
/// Each other selected photo's own Auto white balance, worked out on its own pixels, when
/// Auto Sync is about to carry the active photo's (`id`) switch to Auto (`new`) over. Empty
/// otherwise. A photo whose pixels don't load is left out (it keeps its white balance).
pub(crate) fn own_auto_wb(&mut self, id: PhotoId, new: &DevelopSettings, label: &str) -> HashMap<PhotoId, (f64, f64)> {
let mut own = HashMap::new();
if !self.auto_sync_applies(id, label) || new.wb.mode != WbMode::Auto || self.develop_of(id).is_some_and(|old| old.wb == new.wb) {
return own;
}
let others: Vec<PhotoId> = self.selection.ids.iter().copied().filter(|x| *x != id).collect();
// decoded in parallel, a core's worth at a time: a big selection never holds more
// decoded thumbnails at once than that, whatever the cache keeps
let batch = rayon::current_num_threads().clamp(1, 16);
for chunk in others.chunks(batch) {
for (x, src) in self.sources_now(chunk, crate::media::SourceLevel::Thumb) {
match src {
// with the facts its own decoder gave
Ok((src, info)) => {
own.insert(x, lightcraft_pipeline::auto::auto_wb(&src, &info));
}
Err(e) => log::warn!("Auto Sync: Auto white balance on photo {}: {e}", x.0),
}
}
}
own
}
}
+48
View File
@@ -7,10 +7,13 @@ mod album_missing;
mod album_order;
mod album_remove;
mod albums_local;
mod autosync_wb;
mod color;
mod constrain_crop;
mod crop_angle;
mod crop_aspect;
mod dcp;
mod dcp_corpus;
mod denoise;
mod export;
mod face_models;
@@ -41,6 +44,7 @@ mod organize;
mod persist;
mod prefs;
mod presets_scale;
mod preview_prep;
mod print;
mod process;
mod recheck;
@@ -49,6 +53,8 @@ mod settings_files;
mod shelved_folder;
mod slide;
mod slideshow_export;
#[cfg(not(target_arch = "wasm32"))]
mod slow_drive;
mod spots;
mod sync;
mod view_follow;
@@ -1035,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<PhotoId> = 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<PhotoId> = 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::<Vec<_>>();
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;
+189
View File
@@ -0,0 +1,189 @@
//! LRC-DEV-AUTOSYNC (N-A3, test notes 2026-10-24 note 18): Auto Sync sets every selected photo to
//! the active photo's value, and where white balance is a mode or another scale, each photo applies
//! it to itself. As Shot gives each photo its own camera white, Auto each photo's own from its
//! pixels, a light preset its numbers. A typed or dragged Temp is the same number on each photo of
//! the same scale (the same Kelvin on raws edited in Kelvin; an old relative-scale value converted
//! first, never read as Kelvin), moves a photo of another scale (a JPEG beside a raw) by as much as
//! the active photo, and leaves each photo's own tint.
use lightcraft_catalog::PhotoId;
use lightcraft_develop::{WbMode, WbScale, WhiteBalance};
use serde_json::json;
use crate::Session;
/// Give photo `id` a decoded raw source (thumbnail and preview) with as-shot white `(temp, tint)`;
/// `legacy`: a camera whose settings without a scale were written on the relative scale; `warm`
/// tints its pixels, so Auto finds another white on each photo.
fn raw_as_shot(s: &mut Session, id: PhotoId, temp: f64, tint: f64, legacy: bool, warm: f32) {
use crate::media::SourceLevel;
let mut img = lightcraft_raster::Rgb32f::new(48, 32);
for (i, px) in img.data.iter_mut().enumerate() {
let v = 0.1 + 0.6 * ((i % 48) as f32 / 48.0);
*px = [v * warm, v, v / warm];
}
let img = std::sync::Arc::new(img);
let info =
lightcraft_pipeline::SourceInfo { raw: true, legacy_relative_wb: legacy, as_shot_temp: temp, as_shot_tint: tint, ..Default::default() };
s.media.insert_with_info(id, SourceLevel::Thumb, img.clone(), info.clone());
s.media.insert_with_info(id, SourceLevel::Preview, img, info);
}
/// The white balance photo `id` renders with (Kelvin, tint).
fn wb(s: &Session, id: PhotoId) -> (f64, f64) {
lightcraft_pipeline::local::effective_wb(&s.source_info(id), &s.develop_of(id).unwrap())
}
fn close(x: (f64, f64), y: (f64, f64)) -> bool {
(x.0 - y.0).abs() < 1.0 && (x.1 - y.1).abs() < 0.5
}
/// Three demo photos (a active, b, c) selected, Auto Sync on, each a raw of another as-shot white;
/// c still holds an old relative-scale white (7000 there meant "a little warmer than as shot").
fn three_raws() -> (Session, [PhotoId; 3]) {
let mut s = Session::with_demo();
let ids: Vec<PhotoId> = s.visible_cloned().into_iter().take(3).collect();
let (a, b, c) = (ids[0], ids[1], ids[2]);
raw_as_shot(&mut s, a, 5200.0, 4.0, false, 1.0);
raw_as_shot(&mut s, b, 3300.0, -12.0, false, 1.4);
raw_as_shot(&mut s, c, 6100.0, 8.0, true, 0.7);
let mut d = (*s.develop_of(c).unwrap()).clone();
d.wb = WhiteBalance { mode: WbMode::Custom, temp: 7000.0, tint: 0.0, scale: WbScale::Legacy };
s.catalog.apply(lightcraft_catalog::Op::SetDevelop { id: c, settings: std::sync::Arc::new(d), label: "x".into(), edited: None }).unwrap();
s.execute("library.select", &json!({"ids": [a.0, b.0, c.0], "active": a.0})).unwrap();
s.execute("develop.autoSync", &json!({"on": true})).unwrap();
(s, [a, b, c])
}
/// As Shot and Auto are modes: each photo gets its own camera white, or its own Auto white worked
/// out on its own pixels, never the active photo's numbers. A light preset gives its numbers.
#[test]
fn auto_sync_white_balance_modes_apply_to_each_photo() {
let (mut s, [a, b, c]) = three_raws();
// As Shot: each photo's own camera white
s.execute("develop.wb", &json!({"mode": "asShot"})).unwrap();
for (id, own) in [(a, (5200.0, 4.0)), (b, (3300.0, -12.0)), (c, (6100.0, 8.0))] {
assert!(close(wb(&s, id), own), "As Shot on photo {}: {:?}, its own is {own:?}", id.0, wb(&s, id));
assert_eq!(s.develop_of(id).unwrap().wb.mode, WbMode::AsShot);
}
// a light preset: its numbers on every raw
s.execute("develop.wb", &json!({"mode": "tungsten"})).unwrap();
for id in [a, b, c] {
assert!(close(wb(&s, id), (2850.0, 0.0)), "Tungsten on photo {}: {:?}", id.0, wb(&s, id));
}
// Auto: each photo's own, from its own pixels
s.execute("develop.wb", &json!({"mode": "auto"})).unwrap();
for id in [b, c] {
let src = s.source_now(id, crate::media::SourceLevel::Thumb).unwrap();
let own = lightcraft_pipeline::auto::auto_wb(&src, &s.source_info(id));
assert!(close(wb(&s, id), own), "Auto on photo {}: {:?}, its own Auto is {own:?}", id.0, wb(&s, id));
assert_eq!(s.develop_of(id).unwrap().wb.mode, WbMode::Auto);
}
assert!(!close(wb(&s, a), wb(&s, b)), "not the active photo's Auto copied over: {:?}", wb(&s, a));
// one undo step puts every photo back
s.execute("edit.undo", &json!({})).unwrap();
for id in [a, b, c] {
assert!(close(wb(&s, id), (2850.0, 0.0)), "undo, photo {}: {:?}", id.0, wb(&s, id));
}
}
/// A Temp typed or dragged from As Shot: the same Kelvin on every raw, each keeping its own tint;
/// the photo holding an old relative-scale value gets the Kelvin too, never read on that scale.
#[test]
fn auto_sync_temp_is_the_same_kelvin_and_keeps_each_photos_tint() {
let (mut s, [a, b, c]) = three_raws();
s.execute("develop.wb", &json!({"mode": "asShot"})).unwrap();
// typed
s.execute("develop.set", &json!({"control": "wb.temp", "value": 5600.0})).unwrap();
assert!(close(wb(&s, a), (5600.0, 4.0)), "a: {:?}", wb(&s, a));
assert!(close(wb(&s, b), (5600.0, -12.0)), "b keeps its own tint: {:?}", wb(&s, b));
assert!(close(wb(&s, c), (5600.0, 8.0)), "c keeps its own tint: {:?}", wb(&s, c));
// a drag, synced on release
s.execute("develop.beginInteraction", &json!({"label": "Temp"})).unwrap();
for v in [5000.0, 4600.0] {
s.execute("develop.set", &json!({"control": "wb.temp", "value": v})).unwrap();
}
s.execute("develop.endInteraction", &json!({})).unwrap();
assert!(close(wb(&s, b), (4600.0, -12.0)) && close(wb(&s, c), (4600.0, 8.0)), "b {:?} c {:?}", wb(&s, b), wb(&s, c));
// a Tint move: the same tint on every photo, each keeping its Kelvin (all at 4600 here)
s.execute("develop.set", &json!({"control": "wb.tint", "value": 10.0})).unwrap();
for id in [a, b, c] {
assert!(close(wb(&s, id), (4600.0, 10.0)), "photo {}: {:?}", id.0, wb(&s, id));
}
}
/// A photo still holding an old relative-scale value: a Temp synced from a photo in Kelvin reaches
/// it as Kelvin, never as a number on the relative scale (where 6500 is as shot), which turned
/// photos blue (test notes 2026-10-15). Main already got this right; the guard keeps it so.
#[test]
fn auto_sync_temp_never_lands_on_an_old_relative_scale() {
let (mut s, [_, _, c]) = three_raws();
s.execute("develop.set", &json!({"control": "wb.temp", "value": 5600.0})).unwrap();
assert!((wb(&s, c).0 - 5600.0).abs() < 1.0, "c renders at {:?}", wb(&s, c));
assert_eq!(s.develop_of(c).unwrap().wb.scale, WbScale::Kelvin);
}
/// A JPEG selected with a raw has no "same" Kelvin (its white balance is relative to its own
/// colours): it moves by as much as the raw did. Before, it got the raw's Kelvin number, read on
/// its own scale.
#[test]
fn auto_sync_temp_moves_a_jpeg_by_as_much_as_the_raw() {
let mut s = Session::with_demo();
let ids: Vec<PhotoId> = s.visible_cloned().into_iter().take(2).collect();
let (a, b) = (ids[0], ids[1]);
raw_as_shot(&mut s, a, 5200.0, 4.0, false, 1.0);
// b: a JPEG (no raw white balance scale: 6500 / 0 = its own colours)
let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::filled(48, 32, [0.4, 0.4, 0.4]));
let info = lightcraft_pipeline::SourceInfo { raw: false, as_shot_temp: 6500.0, as_shot_tint: 0.0, ..Default::default() };
s.media.insert_with_info(b, crate::media::SourceLevel::Thumb, img.clone(), info.clone());
s.media.insert_with_info(b, crate::media::SourceLevel::Preview, img, info);
assert!(!s.source_info(b).raw);
s.execute("library.select", &json!({"ids": [a.0, b.0], "active": a.0})).unwrap();
s.execute("develop.autoSync", &json!({"on": true})).unwrap();
s.execute("develop.wb", &json!({"mode": "asShot"})).unwrap();
let before = wb(&s, b);
s.execute("develop.set", &json!({"control": "wb.temp", "value": 5600.0})).unwrap();
assert!(close(wb(&s, b), (before.0 + 400.0, before.1)), "the JPEG: {:?}, was {before:?}", wb(&s, b));
}
/// The other photos' pixels for Auto are read together (in parallel, review of #3571): in the
/// order asked, each photo its own, and a photo the library doesn't have is an error, not a panic.
#[test]
fn sources_for_auto_come_back_in_order_and_per_photo() {
let (mut s, [a, b, c]) = three_raws();
let want: Vec<_> = [b, c, a].iter().map(|&x| s.source_now(x, crate::media::SourceLevel::Thumb).unwrap()).collect();
let got = s.sources_now(&[b, PhotoId(u64::MAX), c, a], crate::media::SourceLevel::Thumb);
assert_eq!(got.iter().map(|(x, _)| *x).collect::<Vec<_>>(), vec![b, PhotoId(u64::MAX), c, a]);
assert!(got[1].1.is_err());
for (i, k) in [0, 2, 3].into_iter().enumerate() {
let (img, info) = got[k].1.as_ref().unwrap();
assert!(std::sync::Arc::ptr_eq(img, &want[i]), "photo {k}");
// the facts its decoder gave (the as-shot whites differ per photo here)
assert_eq!(info.as_shot_temp, s.source_info(got[k].0).as_shot_temp, "photo {k}");
}
assert_eq!(got[0].1.as_ref().unwrap().1.as_shot_temp, 3300.0, "b's own");
}
/// Review of #3585: a light preset given a tint of its own on a JPEG (where the stored numbers are
/// what renders) carries that tint to the other photos, as a Custom white balance would, not the
/// preset's tint.
#[test]
fn a_preset_with_its_own_tint_on_a_jpeg_carries_that_tint() {
let mut s = Session::with_demo();
let ids: Vec<PhotoId> = s.visible_cloned().into_iter().take(2).collect();
let (a, b) = (ids[0], ids[1]);
let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::filled(48, 32, [0.4, 0.4, 0.4]));
let info = lightcraft_pipeline::SourceInfo { raw: false, as_shot_temp: 6500.0, as_shot_tint: 0.0, ..Default::default() };
for id in [a, b] {
s.media.insert_with_info(id, crate::media::SourceLevel::Thumb, img.clone(), info.clone());
s.media.insert_with_info(id, crate::media::SourceLevel::Preview, img.clone(), info.clone());
}
s.execute("library.select", &json!({"ids": [a.0, b.0], "active": a.0})).unwrap();
s.execute("develop.autoSync", &json!({"on": true})).unwrap();
s.execute("develop.wb", &json!({"mode": "daylight", "tint": 30.0})).unwrap();
assert!(close(wb(&s, a), (6500.0, 30.0)), "a: {:?}", wb(&s, a));
assert!(close(wb(&s, b), wb(&s, a)), "b renders a's numbers: {:?}", wb(&s, b));
// a plain preset still gives the preset's numbers
s.execute("develop.wb", &json!({"mode": "shade"})).unwrap();
assert!(close(wb(&s, b), (6500.0 * 7500.0 / 5500.0, 10.0)), "b: {:?}", wb(&s, b));
}
+563
View File
@@ -0,0 +1,563 @@
//! Imported camera profiles (`.dcp`): import, choosing one for a raw photo, decoding with it, the
//! source cache, persistence and deletion. Profiles are built in memory (no profile file is committed).
use std::path::PathBuf;
use lightcraft_catalog::PhotoId;
use lightcraft_raw::dcp::{DcpProfile, write_dcp};
use lightcraft_raw::{ColorData, Mat3};
use serde_json::json;
use crate::Session;
use crate::media::SourceRef;
fn temp_dir(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("lc-dcp-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
/// A profile whose matrix swaps the camera's red and blue (our own numbers): photos developed with it
/// come out with red and blue exchanged, which is easy to see in a test.
fn swapping_profile(name: &str) -> DcpProfile {
let m = Mat3([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]);
let xyz_to_cam = m.mul(&Mat3([[3.2406, -1.5372, -0.4986], [-0.9689, 1.8758, 0.0415], [0.0557, -0.2040, 1.0570]]));
DcpProfile {
name: name.into(),
camera_model: "LightCraft Test Camera".into(),
color: ColorData { illuminant: [21, 0], color_matrix: [Some(xyz_to_cam), None], ..Default::default() },
}
}
fn mean_rgb(img: &lightcraft_raster::Rgb32f) -> [f32; 3] {
let n = img.data.len().max(1) as f32;
let s = img.data.iter().fold([0.0f32; 3], |a, p| [a[0] + p[0], a[1] + p[1], a[2] + p[2]]);
[s[0] / n, s[1] / n, s[2] / n]
}
#[test]
fn a_camera_profile_replaces_the_raw_colour_model_when_decoding() {
let dng = crate::tests_xmp::synthetic_dng_with(None, Default::default());
let (plain, plain_info) = crate::files::load_bytes(&dng, 64).unwrap();
let p = swapping_profile("Swap");
let (with, info) = crate::files::load_bytes_with(&dng, 64, Some(&p)).unwrap();
let (a, b) = (mean_rgb(&plain), mean_rgb(&with));
assert!((a[0] - b[0]).abs() > 1e-3 || (a[2] - b[2]).abs() > 1e-3, "the profile changes the colour: {a:?} vs {b:?}");
// white balance at render time works from the profile's matrices
let tags = &info.camera_color.as_ref().expect("a matrix colour model").tags;
assert_eq!(tags.color_matrix, p.color.color_matrix);
assert_ne!(plain_info.camera_color.as_ref().map(|c| c.tags.color_matrix), Some(p.color.color_matrix));
}
#[test]
fn a_profile_without_a_tone_curve_keeps_the_photos_contrast() {
use lightcraft_raw::profile::ToneCurve;
// a DNG with a tone curve of its own (our numbers: 18 % grey → 30 %)
let plain = crate::tests_xmp::synthetic_dng_with(None, Default::default());
let mut raw = lightcraft_raw::decode(&plain).unwrap();
raw.color.profile.tone_curve = ToneCurve::from_tag(&[0.0, 0.0, 0.18, 0.3, 1.0, 1.0]);
let dng = lightcraft_raw::write_dng(&raw, &Default::default()).unwrap();
// a chart-style profile (no curve) keeps the file's curve
let (_, info) = crate::files::load_bytes_with(&dng, 64, Some(&swapping_profile("Swap"))).unwrap();
let tone = info.camera_tone.expect("the file's tone curve stays");
assert!((tone.apply(0.18) - 0.3).abs() < 0.01, "{}", tone.apply(0.18));
// a profile with a curve of its own uses that one (18 % → 45 %)
let mut curved = swapping_profile("Curved");
curved.color.profile.tone_curve = ToneCurve::from_tag(&[0.0, 0.0, 0.18, 0.45, 1.0, 1.0]);
let (_, info) = crate::files::load_bytes_with(&dng, 64, Some(&curved)).unwrap();
let tone = info.camera_tone.expect("the profile's tone curve");
assert!((tone.apply(0.18) - 0.45).abs() < 0.01, "{}", tone.apply(0.18));
}
#[test]
fn import_choose_cache_persist_and_delete() {
let dir = temp_dir("session");
let (lib, files) = (dir.join("lib"), dir.join("files"));
std::fs::create_dir_all(files.join("profiles")).unwrap();
let raw = files.join("IMG_0001.dng");
std::fs::write(&raw, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap();
std::fs::write(files.join("profiles").join("Swap.dcp"), write_dcp(&swapping_profile("Swap")).unwrap()).unwrap();
std::fs::write(files.join("profiles").join("Broken.dcp"), b"IIRC\x08\0\0\0junk").unwrap();
let id;
let dcp_id;
{
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
let r = s.execute("library.import", &json!({"paths": [raw.to_string_lossy()]})).unwrap();
id = PhotoId(r["imported"][0].as_u64().unwrap());
s.execute("library.select", &json!({"ids": [id.0]})).unwrap();
// a folder: the good profile comes in, the broken one is reported
let r = s.execute("profile.import", &json!({"paths": [files.join("profiles").to_string_lossy()]})).unwrap();
assert_eq!(r["imported"].as_array().unwrap().len(), 1, "{r}");
assert_eq!(r["failed"].as_array().unwrap().len(), 1, "{r}");
dcp_id = r["imported"][0]["id"].as_str().unwrap().to_string();
assert!(dcp_id.starts_with("dcp:"));
assert_eq!(r["imported"][0]["cameraModel"], "LightCraft Test Camera");
// importing it again adds nothing
let again = s.execute("profile.import", &json!({"paths": [files.join("profiles").join("Swap.dcp").to_string_lossy()]})).unwrap();
assert_eq!(again["imported"][0]["existing"], true);
// a single .dcp file is a camera profile only, not also a LUT that "couldn't be read"
assert_eq!(again["failed"], json!([]), "{again}");
assert_eq!(s.dcp_profiles.len(), 1);
// the library keeps its own copy
assert!(std::path::Path::new(&s.dcp_profiles[0].file).starts_with(&lib));
// listed in the profile menu under Camera Profiles
let menu = s.profile_menu();
let group = menu["groups"].as_array().unwrap().iter().find(|g| g["name"] == "Camera Profiles").expect("a Camera Profiles group");
assert_eq!(group["profiles"][0]["id"], dcp_id.as_str());
// develop the photo with it: a decode made without it doesn't stand in
let before = s.render_job(id, 48, 48, false, true).unwrap().run();
let loaded = before.loaded.clone().expect("decoded from the file");
assert!(loaded.camera_profile.is_none());
s.media.insert(id, before.level, loaded.image.clone());
assert!(matches!(s.render_job(id, 48, 48, false, true).unwrap().source, SourceRef::Loaded(_)), "cached while nothing changed");
s.execute("develop.profile", &json!({"id": dcp_id})).unwrap();
let job = s.render_job(id, 48, 48, false, true).unwrap();
match &job.source {
SourceRef::File { camera_profile: Some((pid, _)), .. } => assert!(pid.starts_with(&format!("{dcp_id}#")), "{pid}"),
_ => panic!("the photo is decoded again with its camera profile"),
}
let after = job.run();
assert_eq!(
after.loaded.as_ref().and_then(|l| l.camera_profile.clone()),
s.media.camera_profile_of(s.catalog.photo(id).unwrap()).map(|c| c.0)
);
assert!(after.rendered.is_ok());
assert_ne!(mean_rgb(&before.loaded.unwrap().image), mean_rgb(&after.loaded.unwrap().image));
s.persist().unwrap();
s.close_library().unwrap();
}
// reopened: the profile is there and decodes again
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
assert_eq!(s.dcp_profiles.len(), 1);
assert!(s.media.camera_profiles.contains_key(&dcp_id));
assert_eq!(s.catalog.photo(id).unwrap().develop.profile.id, dcp_id);
assert_eq!(s.profile_info(&dcp_id).map(|(_, g)| g), Some("Camera Profiles"));
// deleted: photos using it develop with their file's own colour, the library's copy goes
let file = s.dcp_profiles[0].file.clone();
s.execute("profile.deleteImported", &json!({"id": dcp_id})).unwrap();
assert!(s.dcp_profiles.is_empty() && !std::path::Path::new(&file).exists());
let p = s.catalog.photo(id).unwrap().clone();
assert!(s.media.camera_profile_of(&p).is_none());
assert!(s.execute("develop.profile", &json!({"id": dcp_id})).is_err(), "no longer a known profile");
let _ = std::fs::remove_dir_all(&dir);
}
/// Hovering a camera profile (the loupe's preview, the browser's thumbnails) develops the photo with
/// it, and hovering a built-in profile while one is applied develops without it. Before, both used
/// the photo's own decode: a camera profile's colour never showed in a hover.
#[test]
fn hover_previews_and_browser_thumbnails_decode_with_the_hovered_camera_profile() {
let dir = temp_dir("hover");
let (lib, files) = (dir.join("lib"), dir.join("files"));
std::fs::create_dir_all(&files).unwrap();
let raw = files.join("IMG_0002.dng");
std::fs::write(&raw, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap();
let dcp_file = files.join("Swap.dcp");
std::fs::write(&dcp_file, write_dcp(&swapping_profile("Swap")).unwrap()).unwrap();
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
let r = s.execute("library.import", &json!({"paths": [raw.to_string_lossy()]})).unwrap();
let id = PhotoId(r["imported"][0].as_u64().unwrap());
s.execute("library.select", &json!({"ids": [id.0]})).unwrap();
let dcp_id =
s.execute("profile.import", &json!({"paths": [dcp_file.to_string_lossy()]})).unwrap()["imported"][0]["id"].as_str().unwrap().to_string();
let mean = |j: crate::media::RenderJob| {
let img = j.run().rendered.unwrap().image;
let n = img.data.len().max(1) as f64;
img.data.iter().fold([0.0f64; 3], |a, p| [a[0] + f64::from(p[0]) / n, a[1] + f64::from(p[1]) / n, a[2] + f64::from(p[2]) / n])
};
let differ = |a: [f64; 3], b: [f64; 3]| a.iter().zip(b).any(|(x, y)| (x - y).abs() > 2.0);
let close = |a: [f64; 3], b: [f64; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.6);
let own = (*s.develop_of(id).unwrap()).clone();
let mut hovered = own.clone();
hovered.profile.id = dcp_id.clone();
let builtin = mean(s.render_job(id, 64, 64, false, true).unwrap());
let hover = mean(s.preview_job(id, 64, 64, true, &hovered).unwrap());
assert!(differ(hover, builtin), "the hover shows the camera profile: {hover:?} vs {builtin:?}");
// the browser's thumbnail too, under its own cache key
let (va, vb) = (s.variant_job(id, &own, 64).unwrap(), s.variant_job(id, &hovered, 64).unwrap());
assert_ne!(va.cache.as_ref().unwrap().1, vb.cache.as_ref().unwrap().1);
assert!(matches!(&vb.source, SourceRef::File { camera_profile: Some(_), .. }), "decoded with the camera profile");
assert!(differ(mean(va), mean(vb)));
// selected: the same picture as the hover; hovering the built-in profile then: without it
s.execute("develop.profile", &json!({"id": dcp_id})).unwrap();
let selected = mean(s.render_job(id, 64, 64, false, true).unwrap());
assert!(close(hover, selected), "{hover:?} vs {selected:?}");
let back = mean(s.preview_job(id, 64, 64, true, &own).unwrap());
assert!(close(back, builtin), "{back:?} vs {builtin:?}");
// the profile's file replaced under the same id: the hover's key changes with it, so the old picture isn't
// taken for current (CodeRabbit on #1063)
let before = s.preview_job(id, 64, 64, true, &hovered).unwrap().key;
s.media.camera_profiles.get_mut(&dcp_id).unwrap().fingerprint ^= 0x10;
assert_ne!(s.preview_job(id, 64, 64, true, &hovered).unwrap().key, before);
let _ = std::fs::remove_dir_all(&dir);
}
/// A library with one raw photo and the `Swap` profile imported from `files/<sub>/Swap.dcp` and selected for it.
fn library_with_profile(dir: &std::path::Path) -> (Session, PhotoId, String) {
let (lib, files) = (dir.join("lib"), dir.join("files"));
std::fs::create_dir_all(files.join("a")).unwrap();
let raw = files.join("IMG_0003.dng");
std::fs::write(&raw, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap();
std::fs::write(files.join("a").join("Swap.dcp"), write_dcp(&swapping_profile("Swap")).unwrap()).unwrap();
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
let r = s.execute("library.import", &json!({"paths": [raw.to_string_lossy()]})).unwrap();
let id = PhotoId(r["imported"][0].as_u64().unwrap());
s.execute("library.select", &json!({"ids": [id.0]})).unwrap();
let r = s.execute("profile.import", &json!({"paths": [files.join("a").join("Swap.dcp").to_string_lossy()]})).unwrap();
let dcp_id = r["imported"][0]["id"].as_str().unwrap().to_string();
s.execute("develop.profile", &json!({"id": dcp_id})).unwrap();
(s, id, dcp_id)
}
/// The thumbnail, browser-thumbnail and loupe cache keys of photo `id` (as it is now), and its source tag.
fn render_keys(s: &mut Session, id: PhotoId) -> [lightcraft_preview::Hash128; 3] {
let settings = (*s.develop_of(id).unwrap()).clone();
[
s.thumb_job(id, 256).unwrap().cache.unwrap().1,
s.variant_job(id, &settings, 64).unwrap().cache.unwrap().1,
s.loupe_job(id, 200, 200, true).unwrap().view_cache.unwrap().1,
]
}
/// A camera profile deleted, or replaced by a different file under the same id, never has renders or decoded
/// sources made with the old one stand in: before, the cache keys followed only the profile id, which the photo keeps.
#[test]
fn a_deleted_or_replaced_camera_profile_never_reuses_renders_made_with_it() {
let dir = temp_dir("replace");
let (mut s, id, dcp_id) = library_with_profile(&dir);
let with = render_keys(&mut s, id);
let level = s.render_job(id, 48, 48, false, true).unwrap().level;
let old_tag = s.media.camera_profile_of(s.catalog.photo(id).unwrap()).map(|c| c.0);
assert!(old_tag.is_some());
// deleted: the photo keeps the id, renders without the profile, under other keys
s.execute("profile.deleteImported", &json!({"id": dcp_id})).unwrap();
assert_eq!(s.catalog.photo(id).unwrap().develop.profile.id, dcp_id);
let without = render_keys(&mut s, id);
for (a, b) in with.iter().zip(&without) {
assert_ne!(a, b, "a render made with the deleted profile would stand in");
}
// another profile under the same file name gets the same id back, and other keys again
let other_dir = dir.join("files").join("b");
std::fs::create_dir_all(&other_dir).unwrap();
let mut other = swapping_profile("Swap");
other.color.color_matrix = [Some(Mat3([[3.2406, -1.5372, -0.4986], [-0.9689, 1.8758, 0.0415], [0.0557, -0.2040, 1.0570]])), None];
std::fs::write(other_dir.join("Swap.dcp"), write_dcp(&other).unwrap()).unwrap();
let r = s.execute("profile.import", &json!({"paths": [other_dir.join("Swap.dcp").to_string_lossy()]})).unwrap();
assert_eq!(r["imported"][0]["id"], dcp_id.as_str(), "{r}");
let replaced = render_keys(&mut s, id);
for ((a, b), c) in with.iter().zip(&without).zip(&replaced) {
assert_ne!(a, c, "a render made with the replaced profile would stand in");
assert_ne!(b, c);
}
// nor does a source decoded with the old file
let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::new(4, 4));
s.media.insert_source(id, level, crate::media::DecodedSource { camera_profile: old_tag, ..crate::media::DecodedSource::new(img, None) });
assert!(!matches!(s.render_job(id, 48, 48, false, true).unwrap().source, SourceRef::Loaded(_)), "decoded again with the new file");
let _ = std::fs::remove_dir_all(&dir);
}
/// A grid thumbnail is cut from the photo's decoded preview only when that preview was decoded with the camera profile
/// the photo uses now; before, one made with another profile (or none) was fitted and cached under the new key.
#[test]
fn a_thumbnail_is_not_cut_from_a_preview_decoded_with_another_camera_profile() {
let dir = temp_dir("fit");
let (mut s, id, _) = library_with_profile(&dir);
let p = (**s.catalog.photo(id).unwrap()).clone();
let tag = s.media.camera_profile_of(&p).map(|c| c.0);
let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::new(1600, 1000));
let preview = |camera_profile| crate::media::DecodedSource { camera_profile, ..crate::media::DecodedSource::new(img.clone(), None) };
use crate::media::SourceLevel;
s.media.insert_source(id, SourceLevel::Preview, preview(None));
assert!(!matches!(s.media.source_ref(&p, SourceLevel::Thumb), SourceRef::Fit { .. }), "decoded without the profile");
s.media.insert_source(id, SourceLevel::Preview, preview(tag));
assert!(matches!(s.media.source_ref(&p, SourceLevel::Thumb), SourceRef::Fit { .. }), "decoded with it: still cut from it");
let _ = std::fs::remove_dir_all(&dir);
}
/// A library moved (or restored) elsewhere finds its camera profiles in its own `Profiles/` folder, and a camera
/// profile can be a favourite, which survives reopening like the recent list.
#[test]
fn a_moved_library_keeps_its_camera_profiles_and_their_favourites() {
let dir = temp_dir("moved");
let (mut s, id, dcp_id) = library_with_profile(&dir);
assert_eq!(s.execute("profile.favorite", &json!({"id": dcp_id})).unwrap()["favorite"], true);
assert!(s.profile_recent.contains(&dcp_id));
s.persist().unwrap();
s.close_library().unwrap();
drop(s);
let moved = dir.join("moved");
std::fs::rename(dir.join("lib"), &moved).unwrap();
let mut s = Session::new().with_fs();
s.open_library(&moved, false).unwrap();
assert!(s.media.camera_profiles.contains_key(&dcp_id), "the profile is found in the moved library");
assert!(std::path::Path::new(&s.dcp_profiles[0].file).starts_with(&moved), "{}", s.dcp_profiles[0].file);
assert!(s.media.camera_profile_of(s.catalog.photo(id).unwrap()).is_some());
assert!(s.profile_favorites.contains(&dcp_id) && s.profile_recent.contains(&dcp_id));
s.close_library().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
fn distance(a: [f32; 3], b: [f32; 3]) -> f32 {
(0..3).map(|i| (a[i] - b[i]).abs()).sum()
}
/// A smart preview keeps the file's own colour: Build Smart Previews never develops it with the photo's imported
/// camera profile, nor takes a cached source decoded with it. Before, only the stale-proxy refresh left the profile out.
#[test]
fn smart_previews_are_built_without_the_imported_camera_profile() {
use crate::media::{DecodedSource, SourceLevel};
let dir = temp_dir("smart");
let (mut s, id, _) = library_with_profile(&dir);
let p = (**s.catalog.photo(id).unwrap()).clone();
s.execute("library.smartPreviews", &json!({"ids": [id.0], "discard": true})).unwrap();
// a cached preview decoded with the profile (flat magenta, so it shows if the proxy is cut from it)
let tag = s.media.camera_profile_of(&p).map(|c| c.0);
let mut magenta = lightcraft_raster::Rgb32f::new(8, 8);
magenta.data.iter_mut().for_each(|px| *px = [1.0, 0.0, 1.0]);
s.media.insert_source(id, SourceLevel::Preview, DecodedSource { camera_profile: tag, ..DecodedSource::new(std::sync::Arc::new(magenta), None) });
let r = s.execute("library.smartPreviews", &json!({"ids": [id.0]})).unwrap();
assert_eq!((r["built"].as_u64(), r["repaired"].as_u64()), (Some(1), Some(0)), "{r}");
let smart_dir = s.media.smart_dir.clone().unwrap();
let proxy = crate::smart::load(&crate::smart::existing_file_path(&smart_dir, crate::smart::sharded_file_path(&smart_dir, &p))).unwrap();
let got = mean_rgb(&proxy.image);
let dng = std::fs::read(dir.join("files").join("IMG_0003.dng")).unwrap();
let edge = SourceLevel::Preview.max_edge();
let plain = mean_rgb(&crate::files::load_bytes(&dng, edge).unwrap().0);
let with = mean_rgb(&crate::files::load_bytes_with(&dng, edge, Some(&swapping_profile("Swap"))).unwrap().0);
assert!(distance(got, plain) < distance(got, with), "the proxy has the file's own colour: {got:?}, plain {plain:?}, profiled {with:?}");
// nor from the file developed with the profile
s.media.forget(id);
s.execute("library.smartPreviews", &json!({"ids": [id.0], "discard": true})).unwrap();
s.execute("library.smartPreviews", &json!({"ids": [id.0]})).unwrap();
let proxy = crate::smart::load(&crate::smart::existing_file_path(&smart_dir, crate::smart::sharded_file_path(&smart_dir, &p))).unwrap();
let got = mean_rgb(&proxy.image);
assert!(distance(got, plain) < distance(got, with), "the proxy has the file's own colour: {got:?}, plain {plain:?}, profiled {with:?}");
let _ = std::fs::remove_dir_all(&dir);
}
/// While the original is offline, a cached smart preview stands in for a photo developed with an imported camera
/// profile: it has no profile and decoding it again gives the same picture. Before, it was decoded again for every
/// render. Once the original is back, the photo is decoded from it with its profile.
#[test]
fn a_cached_smart_preview_stands_in_while_the_original_is_offline() {
use crate::media::{DecodedSource, SourceLevel, SourceRef};
let dir = temp_dir("proxy-offline");
let (mut s, id, _) = library_with_profile(&dir);
let p = (**s.catalog.photo(id).unwrap()).clone();
assert!(s.media.camera_profile_of(&p).is_some());
let proxy = DecodedSource { from_proxy: true, ..DecodedSource::new(std::sync::Arc::new(lightcraft_raster::Rgb32f::new(8, 8)), None) };
s.media.insert_source(id, SourceLevel::Preview, proxy);
let offline = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
let probe_offline = offline.clone();
s.media.availability.set_probe(std::sync::Arc::new(move |path: &str| {
!(path.ends_with("IMG_0003.dng") && probe_offline.load(std::sync::atomic::Ordering::Relaxed)) && std::path::Path::new(path).exists()
}));
assert!(matches!(s.media.source_ref(&p, SourceLevel::Preview), SourceRef::Loaded(a) if a.from_proxy), "the proxy stands in");
assert!(matches!(s.media.source_ref(&p, SourceLevel::Thumb), SourceRef::Fit { .. }), "the thumbnail is cut from it");
offline.store(false, std::sync::atomic::Ordering::Relaxed);
assert!(!matches!(s.media.source_ref(&p, SourceLevel::Preview), SourceRef::Loaded(_)), "the original is back: decoded with the profile");
assert!(!matches!(s.media.source_ref(&p, SourceLevel::Thumb), SourceRef::Fit { .. }));
let _ = std::fs::remove_dir_all(&dir);
}
/// The decoder facts reported for a photo come from a cached source developed with the camera profile it uses now;
/// before, a thumbnail decoded with another profile (or none) answered first.
#[test]
fn source_facts_come_from_a_source_developed_with_the_current_camera_profile() {
use crate::media::{DecodedSource, SourceLevel};
let dir = temp_dir("facts");
let (mut s, id, _) = library_with_profile(&dir);
let tag = s.media.camera_profile_of(s.catalog.photo(id).unwrap()).map(|c| c.0);
let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::new(4, 4));
let facts = |temp: f64, camera_profile| DecodedSource {
camera_profile,
..DecodedSource::new(img.clone(), Some(lightcraft_pipeline::SourceInfo { as_shot_temp: temp, ..Default::default() }))
};
s.media.insert_source(id, SourceLevel::Thumb, facts(3100.0, None));
s.media.insert_source(id, SourceLevel::Preview, facts(6200.0, tag));
assert_eq!(s.source_info(id).as_shot_temp, 6200.0);
let _ = std::fs::remove_dir_all(&dir);
}
/// The Before side (and its region renders) decodes with the Before settings' camera profile — here none, the
/// import defaults — not with the edit's: before, it reused or decoded a source developed with the edit's profile.
#[test]
fn the_before_side_decodes_with_its_own_camera_profile() {
use crate::media::{DecodedSource, SourceLevel};
let dir = temp_dir("before");
let (mut s, id, _) = library_with_profile(&dir);
let camera = |job: &crate::media::RenderJob| match &job.source {
SourceRef::File { camera_profile, .. } => camera_profile.as_ref().map(|c| c.0.clone()),
SourceRef::Loaded(a) => a.camera_profile.clone(),
_ => None,
};
s.media.forget(id);
let after = s.render_job(id, 256, 256, false, true).unwrap();
let tag = camera(&after);
assert!(tag.is_some(), "the edit develops with the imported profile");
let before = s.render_job(id, 256, 256, true, true).unwrap();
assert_eq!(camera(&before), None, "the Before side develops with the file's own colour");
// nor does a cached source developed with the edit's profile stand in for it
for level in [SourceLevel::Thumb, SourceLevel::Preview, SourceLevel::Full] {
let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::new(4, 4));
s.media.insert_source(id, level, DecodedSource { camera_profile: tag.clone(), ..DecodedSource::new(img, None) });
}
let before = s.render_job(id, 256, 256, true, true).unwrap();
assert!(!matches!(before.source, SourceRef::Loaded(_)), "the Before side is decoded afresh");
assert_eq!(camera(&before), None);
let _ = std::fs::remove_dir_all(&dir);
}
/// A profile whose copy into the library fails is reported as failed on its own: the profiles imported with
/// it stay imported (and are saved), and the command does not fail.
#[test]
fn a_profile_that_cannot_be_copied_fails_on_its_own() {
let dir = temp_dir("copy-fails");
let (lib, files) = (dir.join("lib"), dir.join("files"));
std::fs::create_dir_all(&files).unwrap();
for name in ["A", "B"] {
std::fs::write(files.join(format!("{name}.dcp")), write_dcp(&swapping_profile(name)).unwrap()).unwrap();
}
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
// a folder where B's copy goes: writing it fails
let blocked = lib.join("Profiles").join(format!("{}.dcp", crate::presets::slug("LightCraft Test Camera-B")));
std::fs::create_dir_all(&blocked).unwrap();
let r = s.execute("profile.import", &json!({"paths": [files.to_string_lossy()]})).unwrap();
let imported: Vec<&str> = r["imported"].as_array().unwrap().iter().filter_map(|p| p["name"].as_str()).collect();
assert_eq!(imported, ["A"], "{r}");
let failed = r["failed"].as_array().unwrap();
assert_eq!(failed.len(), 1, "{r}");
assert!(failed[0][0].as_str().is_some_and(|f| f.ends_with("B.dcp")), "{r}");
assert_eq!(s.dcp_profiles.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["A"]);
assert!(blocked.is_dir(), "the folder in the way is left alone");
let _ = std::fs::remove_dir_all(&dir);
}
/// A file that is neither a `.cube`, a `.dcp` nor a `.zip` is reported as failed instead of being passed over.
#[test]
fn importing_an_unsupported_profile_file_reports_it() {
let dir = temp_dir("unsupported");
let notes = dir.join("notes.txt");
std::fs::write(&notes, "not a profile").unwrap();
let mut s = Session::new();
let r = s.execute("profile.import", &json!({"paths": [notes.to_string_lossy()]})).unwrap();
assert_eq!(r["imported"].as_array().map(Vec::len), Some(0), "{r}");
assert_eq!(r["failed"], json!([["notes", "not a .cube, .dcp or .zip file"]]), "{r}");
let _ = std::fs::remove_dir_all(&dir);
}
/// A library copy that can't be removed keeps its profile: the command fails and nothing is forgotten, so the
/// library never holds a profile file it no longer lists (CodeRabbit on #1063).
#[test]
fn a_profile_whose_copy_cannot_be_deleted_stays() {
let dir = temp_dir("delete-fails");
let (mut s, _, dcp_id) = library_with_profile(&dir);
let file = s.dcp_profiles.iter().find(|p| p.id == dcp_id).map(|p| PathBuf::from(&p.file)).unwrap();
// a folder in the copy's place: removing it as a file fails (as a file in use does)
std::fs::remove_file(&file).unwrap();
std::fs::create_dir_all(&file).unwrap();
let r = s.execute("profile.deleteCamera", &json!({"id": dcp_id}));
assert!(r.is_err(), "{r:?}");
assert!(s.dcp_profiles.iter().any(|p| p.id == dcp_id), "the profile is still listed");
// gone already: deleting just forgets it
std::fs::remove_dir_all(&file).unwrap();
s.execute("profile.deleteCamera", &json!({"id": dcp_id})).unwrap();
assert!(s.dcp_profiles.iter().all(|p| p.id != dcp_id));
let _ = std::fs::remove_dir_all(&dir);
}
/// A listed path that climbs out of the profiles folder with `..` is not the library's copy: deleting the profile
/// leaves that file alone (CodeRabbit on #1063).
#[test]
fn deleting_a_profile_never_follows_dot_dot_out_of_the_profiles_folder() {
let dir = temp_dir("delete-dotdot");
let (mut s, _, dcp_id) = library_with_profile(&dir);
let entry = s.dcp_profiles.iter_mut().find(|p| p.id == dcp_id).unwrap();
let profiles = PathBuf::from(&entry.file).parent().unwrap().to_path_buf();
let outside = profiles.parent().unwrap().join("keep.txt");
std::fs::write(&outside, b"the user's").unwrap();
entry.file = profiles.join("..").join("keep.txt").to_string_lossy().into_owned();
s.execute("profile.deleteCamera", &json!({"id": dcp_id})).unwrap();
assert!(s.dcp_profiles.iter().all(|p| p.id != dcp_id), "forgotten");
assert!(outside.exists(), "the file outside the profiles folder stays");
let _ = std::fs::remove_dir_all(&dir);
}
/// CodeRabbit on #1063: a camera profile whose library copy is missing or damaged when the library opens stayed in the
/// profile browser and `develop.profile` accepted it, and the photo then silently developed with the raw's own
/// colour. It is no longer offered or accepted; its entry stays, and once the file is back it is offered again.
#[test]
fn a_damaged_camera_profile_is_not_offered_until_its_file_is_back() {
let dir = temp_dir("damaged");
let (mut s, _id, dcp_id) = library_with_profile(&dir);
let file = std::path::PathBuf::from(&s.dcp_profiles[0].file);
s.persist().unwrap();
s.close_library().unwrap();
drop(s);
let good = std::fs::read(&file).unwrap();
std::fs::write(&file, b"not a profile").unwrap();
let mut s = Session::new().with_fs();
s.open_library(dir.join("lib"), false).unwrap();
assert_eq!(s.dcp_profiles.len(), 1, "the entry stays");
assert!(!s.imported_profiles().iter().any(|p| p.0 == dcp_id), "not offered");
let menu = s.profile_menu().to_string();
assert!(!menu.contains(&dcp_id), "not in the profile menu: {menu}");
assert!(s.execute("develop.profile", &json!({"id": dcp_id})).is_err(), "not accepted");
s.close_library().unwrap();
drop(s);
std::fs::write(&file, good).unwrap();
let mut s = Session::new().with_fs();
s.open_library(dir.join("lib"), false).unwrap();
assert!(s.imported_profiles().iter().any(|p| p.0 == dcp_id), "offered again");
s.execute("develop.profile", &json!({"id": dcp_id})).unwrap();
s.close_library().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// CodeRabbit on #1063: a LUT profile group named like the camera profiles' ("Camera Profiles") that doesn't sort last
/// made the profile menu list that group twice, each with the same profiles. It is one group, last.
#[test]
fn a_lut_group_named_camera_profiles_joins_the_camera_profiles_group() {
let dir = temp_dir("group");
let (mut s, _id, dcp_id) = library_with_profile(&dir);
for (id, group) in [("lut:a", crate::cmd::dcp_profiles::DCP_GROUP), ("lut:z", "Zebra")] {
s.lut_profiles.push(crate::cmd::lut_profiles::LutProfile { id: id.into(), name: id.into(), group: group.into(), file: String::new() });
}
let menu = s.profile_menu();
let groups: Vec<&str> = menu["groups"].as_array().unwrap().iter().filter_map(|g| g["name"].as_str()).collect();
assert_eq!(groups.iter().filter(|g| **g == crate::cmd::dcp_profiles::DCP_GROUP).count(), 1, "{groups:?}");
assert_eq!(groups.last(), Some(&crate::cmd::dcp_profiles::DCP_GROUP), "{groups:?}");
let ids: Vec<&str> = menu["groups"]
.as_array()
.unwrap()
.iter()
.filter(|g| g["name"] == crate::cmd::dcp_profiles::DCP_GROUP)
.flat_map(|g| g["profiles"].as_array().unwrap().iter().filter_map(|p| p["id"].as_str()))
.collect();
assert!(ids.contains(&"lut:a") && ids.contains(&dcp_id.as_str()), "{ids:?}");
s.close_library().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// A `.dcp` file larger than the parser accepts is refused while it is read, before the whole file is loaded into
/// memory (CodeRabbit on #1063): the import reports it as failed with its own reason.
#[test]
fn an_oversized_camera_profile_is_refused_while_it_is_read() {
let dir = temp_dir("oversized");
let big = dir.join("Big.dcp");
let mut bytes = write_dcp(&swapping_profile("Big")).unwrap();
bytes.truncate(4);
std::fs::write(&big, &bytes).unwrap();
std::fs::OpenOptions::new().write(true).open(&big).unwrap().set_len(lightcraft_raw::dcp::MAX_DCP_BYTES + 1).unwrap();
let mut s = Session::new();
let r = s.execute("profile.import", &json!({"paths": [big.to_string_lossy()]})).unwrap();
assert_eq!(r["imported"], json!([]), "{r}");
assert_eq!(r["failed"][0][1], json!("the camera profile is larger than 64 MiB"), "{r}");
let _ = std::fs::remove_dir_all(&dir);
}
+243
View File
@@ -0,0 +1,243 @@
//! A real camera profile end to end: the Nikon D750 ColorChecker DCP and chart NEFs dieli released
//! under CC0 (github.com/dieli/d750-lightcraft-colorchecker, pinned in `D750_COLORCHECKER`,
//! xtask/src/main.rs; `cargo xtask corpus --download`). Each chart is imported, developed with the
//! imported profile, white balanced on the second-lightest grey patch (as in the reference) and
//! exported as sRGB; the 24 patches are then compared in CIELAB (ΔE2000) with Lightroom Classic
//! 15.6's render of the same NEF with the same profile.
//!
//! The comparison is lenient on purpose: the profile is matrix-only, so the colour model is the same,
//! but Lightroom adds its own default tone curve and rendering, which LightCraft does not copy. The
//! test pins the measured agreement against regressions (see `MEAN_LIMIT`, `MAX_LIMIT`) and prints
//! every patch's ΔE. Missing files are reported as skipped.
use std::path::{Path, PathBuf};
use lightcraft_catalog::PhotoId;
use serde_json::json;
use crate::Session;
use crate::export::{ExportOptions, export_photo};
/// Upper bounds for the mean and the largest patch ΔE2000 against Lightroom. Measured when this test
/// was written (2026-10-22): daylight/flash mean 3.84, max 7.77 (patch 16, yellow); indoor mean 3.35,
/// max 5.24 (patch 13, blue). The grey row agrees within about 1-3; the colour patches come out less
/// saturated than Lightroom's (its own rendering on top of the profile), which is most of the rest.
const MEAN_LIMIT: f64 = 5.0;
const MAX_LIMIT: f64 = 10.0;
fn set_dir() -> PathBuf {
std::env::var_os("LIGHTCRAFT_CORPUS")
.map(PathBuf::from)
.unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"))
.join("d750-colorchecker")
}
/// Patch centres (row-major, normalized x, y) in Lightroom's render of each chart, a crop around the
/// ColorChecker. Row 4 is the grey row, white to black.
fn reference_centres(chart: &str) -> Vec<(f64, f64)> {
let (xs, ys): (&[f64], &[f64]) = if chart.contains("indoor") {
(&[193.0, 361.0, 527.0, 692.0, 857.0, 1022.0], &[152.0, 318.0, 486.0, 660.0])
} else {
(&[197.0, 378.0, 555.0, 731.0, 906.0, 1080.0], &[135.0, 312.0, 490.0, 668.0])
};
ys.iter().flat_map(|y| xs.iter().map(move |x| (x / 1200.0, y / 801.0))).collect()
}
/// The same patches in the whole NEF frame (our export, uncropped), read off a 1200 × 802 render.
fn frame_centres(chart: &str) -> Vec<(f64, f64)> {
let (xs, ys): (&[f64], &[f64]) = if chart.contains("indoor") {
(&[468.0, 528.0, 587.0, 645.0, 704.0, 765.0], &[527.0, 585.0, 644.0, 705.0])
} else {
(&[462.0, 512.0, 560.0, 609.0, 658.0, 706.0], &[381.0, 430.0, 479.0, 529.0])
};
ys.iter().flat_map(|y| xs.iter().map(move |x| (x / 1200.0, y / 802.0))).collect()
}
/// Mean CIELAB (D50) of a box of half-width `radius` (a fraction of the image width) around each
/// centre, and the largest standard deviation of L* inside a box (a box on a patch edge shows up there).
fn patch_labs(bytes: &[u8], centres: &[(f64, f64)], radius: f64) -> (Vec<[f64; 3]>, f64) {
let d = lightcraft_codecs::decode(bytes, Default::default()).unwrap();
let to_xyz = d.space.to_xyz_d50;
let (w, h) = (d.image.width, d.image.height);
let r = (w as f64 * radius).max(1.0) as isize;
let mut worst = 0.0f64;
let labs = centres
.iter()
.map(|&(x, y)| {
let (cx, cy) = ((x * w as f64) as isize, (y * h as f64) as isize);
let (mut acc, mut ls) = ([0.0f64; 3], Vec::new());
for yy in (cy - r).max(0)..(cy + r).min(h as isize) {
for xx in (cx - r).max(0)..(cx + r).min(w as isize) {
let p = d.image.data[yy as usize * w + xx as usize];
let rgb = [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])];
for (a, v) in acc.iter_mut().zip(rgb) {
*a += v;
}
ls.push(lab(to_xyz.apply(rgb))[0]);
}
}
let n = ls.len().max(1) as f64;
let mean_l = ls.iter().sum::<f64>() / n;
worst = worst.max((ls.iter().map(|l| (l - mean_l).powi(2)).sum::<f64>() / n).sqrt());
lab(to_xyz.apply(acc.map(|v| v / n)))
})
.collect();
(labs, worst)
}
fn lab(xyz: [f64; 3]) -> [f64; 3] {
let white = [0.9642, 1.0, 0.8249];
let f = |t: f64| if t > 216.0 / 24389.0 { t.cbrt() } else { (24389.0 / 27.0 * t + 16.0) / 116.0 };
let [fx, fy, fz] = [f(xyz[0] / white[0]), f(xyz[1] / white[1]), f(xyz[2] / white[2])];
[116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)]
}
/// CIEDE2000 (Sharma, Wu and Dalal 2005).
fn de2000(a: [f64; 3], b: [f64; 3]) -> f64 {
use std::f64::consts::PI;
let (l1, a1, b1, l2, a2, b2) = (a[0], a[1], a[2], b[0], b[1], b[2]);
let c_bar = ((a1 * a1 + b1 * b1).sqrt() + (a2 * a2 + b2 * b2).sqrt()) / 2.0;
let g = 0.5 * (1.0 - (c_bar.powi(7) / (c_bar.powi(7) + 25f64.powi(7))).sqrt());
let (a1p, a2p) = ((1.0 + g) * a1, (1.0 + g) * a2);
let (c1p, c2p) = ((a1p * a1p + b1 * b1).sqrt(), (a2p * a2p + b2 * b2).sqrt());
let hue = |b: f64, a: f64| if b == 0.0 && a == 0.0 { 0.0 } else { b.atan2(a).rem_euclid(2.0 * PI) };
let (h1p, h2p) = (hue(b1, a1p), hue(b2, a2p));
let dl = l2 - l1;
let dc = c2p - c1p;
let dh = if c1p * c2p == 0.0 {
0.0
} else {
let d = h2p - h1p;
if d.abs() <= PI {
d
} else if d > PI {
d - 2.0 * PI
} else {
d + 2.0 * PI
}
};
let dhh = 2.0 * (c1p * c2p).sqrt() * (dh / 2.0).sin();
let l_bar = (l1 + l2) / 2.0;
let cp_bar = (c1p + c2p) / 2.0;
let hp_bar = if c1p * c2p == 0.0 {
h1p + h2p
} else if (h1p - h2p).abs() <= PI {
(h1p + h2p) / 2.0
} else if h1p + h2p < 2.0 * PI {
(h1p + h2p + 2.0 * PI) / 2.0
} else {
(h1p + h2p - 2.0 * PI) / 2.0
};
let t = 1.0 - 0.17 * (hp_bar - PI / 6.0).cos() + 0.24 * (2.0 * hp_bar).cos() + 0.32 * (3.0 * hp_bar + PI / 30.0).cos()
- 0.20 * (4.0 * hp_bar - 63.0 * PI / 180.0).cos();
let d_theta = 30.0 * (-(((hp_bar * 180.0 / PI) - 275.0) / 25.0).powi(2)).exp();
let rc = 2.0 * (cp_bar.powi(7) / (cp_bar.powi(7) + 25f64.powi(7))).sqrt();
let sl = 1.0 + 0.015 * (l_bar - 50.0).powi(2) / (20.0 + (l_bar - 50.0).powi(2)).sqrt();
let sc = 1.0 + 0.045 * cp_bar;
let sh = 1.0 + 0.015 * cp_bar * t;
let rt = -(2.0 * d_theta * PI / 180.0).sin() * rc;
((dl / sl).powi(2) + (dc / sc).powi(2) + (dhh / sh).powi(2) + rt * (dc / sc) * (dhh / sh)).sqrt()
}
#[test]
fn de2000_matches_the_published_test_pairs() {
// Sharma, Wu and Dalal (2005), table 1: pairs 1, 7 and 17
let cases = [
([50.0, 2.6772, -79.7751], [50.0, 0.0, -82.7485], 2.0425),
([50.0, 0.0, 0.0], [50.0, -1.0, 2.0], 2.3669),
([50.0, 2.5, 0.0], [73.0, 25.0, -18.0], 27.1492),
];
for (a, b, e) in cases {
assert!((de2000(a, b) - e).abs() < 1e-3, "{a:?} {b:?}: {} vs {e}", de2000(a, b));
}
}
#[test]
fn the_d750_profile_develops_its_charts_close_to_lightroom() {
let set = set_dir();
let dcp = set.join("profiles/20261016_NikonD750_DualIllumination_ColorCheckerPassport.dcp");
let charts = [("daylight_flash", "raw/chart-daylight_flash.NEF"), ("indoor", "raw/chart-indoor.NEF")];
let mut needed = vec![dcp.clone()];
for (name, raw) in charts {
needed.push(set.join(raw));
needed.push(set.join(format!("images/{name}-lightroom.jpg")));
}
if let Some(missing) = needed.iter().find(|p| !p.exists()) {
lightcraft_testkit::skip!(Corpus, "{} absent (cargo xtask corpus --download)", missing.display());
return;
}
let lib = std::env::temp_dir().join(format!("lc-dcp-d750-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&lib);
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
let r = s.execute("profile.import", &json!({"paths": [dcp.to_string_lossy()]})).unwrap();
let dcp_id = r["imported"][0]["id"].as_str().expect("the D750 profile imports").to_string();
assert!(r["imported"][0]["cameraModel"].as_str().unwrap().contains("D750"), "{r}");
let o = ExportOptions::from_json(&json!({"format": "png", "longEdge": 1200, "colorSpace": "srgb"}));
let mut report = String::new();
let mut means = Vec::new();
for (name, raw) in charts {
let r = s.execute("library.import", &json!({"paths": [set.join(raw).to_string_lossy()]})).unwrap();
let id = PhotoId(r["imported"][0].as_u64().expect("the NEF imports"));
s.execute("library.select", &json!({"ids": [id.0]})).unwrap();
s.execute("develop.profile", &json!({"id": dcp_id})).unwrap();
let centres = frame_centres(name);
let (reference, spread) =
patch_labs(&std::fs::read(set.join(format!("images/{name}-lightroom.jpg"))).unwrap(), &reference_centres(name), 0.02);
assert!(spread < 4.0, "{name}: every reference box lies inside its patch (L* spread {spread:.1})");
// white balance on the second-lightest grey (patch 20), as the reference was made
let wb = s.execute("develop.wbPick", &json!({"x": centres[19].0, "y": centres[19].1})).unwrap();
// exposure: the value whose grey row is closest to the reference's (golden-section search)
let render = |s: &mut Session, ev: f64| {
s.execute("develop.set", &json!({"control": "light.exposure", "value": ev})).unwrap();
let e = export_photo(s, id, &o, 1).expect("the chart develops with the D750 profile");
patch_labs(&e.bytes, &centres, 0.006)
};
let grey_de = |(labs, _): &(Vec<[f64; 3]>, f64)| (18..24).map(|i| de2000(labs[i], reference[i])).sum::<f64>() / 6.0;
let (mut lo, mut hi) = (-1.5f64, 1.5f64);
let phi = (5f64.sqrt() - 1.0) / 2.0;
let (mut m1, mut m2) = (hi - phi * (hi - lo), lo + phi * (hi - lo));
let (mut f1, mut f2) = (grey_de(&render(&mut s, m1)), grey_de(&render(&mut s, m2)));
for _ in 0..8 {
if f1 < f2 {
(hi, m2, f2) = (m2, m1, f1);
m1 = hi - phi * (hi - lo);
f1 = grey_de(&render(&mut s, m1));
} else {
(lo, m1, f1) = (m1, m2, f2);
m2 = lo + phi * (hi - lo);
f2 = grey_de(&render(&mut s, m2));
}
}
let ev = (lo + hi) / 2.0;
let (ours, spread) = render(&mut s, ev);
assert!(spread < 4.0, "{name}: every box lies inside its patch (L* spread {spread:.1})");
// LIGHTCRAFT_DCP_DUMP=<folder>: keep our renders, to check the patch boxes by eye
if let Some(dir) = std::env::var_os("LIGHTCRAFT_DCP_DUMP") {
s.execute("develop.set", &json!({"control": "light.exposure", "value": ev})).unwrap();
let _ = std::fs::write(Path::new(&dir).join(format!("{name}.png")), export_photo(&mut s, id, &o, 1).unwrap().bytes);
}
let des: Vec<f64> = ours.iter().zip(&reference).map(|(a, b)| de2000(*a, *b)).collect();
let mean = des.iter().sum::<f64>() / des.len() as f64;
let max = des.iter().cloned().fold(0.0, f64::max);
report += &format!("{name}: wb {} K / tint {}, exposure {ev:+.2}, mean ΔE2000 {mean:.2}, max {max:.2}\n", wb["temp"], wb["tint"]);
for (i, d) in des.iter().enumerate() {
report += &format!(
" patch {:2}: ΔE {d:5.2} ours L*a*b* {:6.1} {:6.1} {:6.1} Lightroom {:6.1} {:6.1} {:6.1}\n",
i + 1,
ours[i][0],
ours[i][1],
ours[i][2],
reference[i][0],
reference[i][1],
reference[i][2]
);
}
means.push((name, mean, max));
}
eprintln!("{report}");
let _ = std::fs::remove_dir_all(&lib);
for (name, mean, max) in means {
assert!(mean < MEAN_LIMIT && max < MAX_LIMIT, "{name}: mean ΔE2000 {mean:.2}, max {max:.2}\n{report}");
}
}
+59 -11
View File
@@ -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", &params).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);
}
+2 -2
View File
@@ -91,9 +91,9 @@ fn count_loads(s: &mut Session) -> Loads {
let loads = Loads::default();
let file = s.media.file_loader.clone().unwrap();
let n = loads.files.clone();
s.media.file_loader = Some(Arc::new(move |p: &str, e: usize| {
s.media.file_loader = Some(Arc::new(move |p: &str, e: usize, dcp: crate::media::RawDecode<'_>| {
n.fetch_add(1, Ordering::SeqCst);
file(p, e)
file(p, e, dcp)
}));
let preview = s.media.preview_loader.clone().unwrap();
let n = loads.previews.clone();
Loaded 100 of 276 files, more files were not shown because too many files have changed in this diff. Show more