LR-META-EXIF-FULL: merge current main 5b4eb6924 (BM3D denoise, Remove Hot Pixels, culling previews) (#693)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	crates/engine/src/tests/import.rs
#	docs/parity-checklist.md
#	docs/target-app-parity.md
This commit is contained in:
Alex Chambers committed 2026-11-05 12:48:31 +01:00
commit 771f97df4f
169 files changed
+14196 -1147

No files matched your search

+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
+21
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",
@@ -4080,6 +4093,14 @@ dependencies = [
"web-sys",
]
[[package]]
name = "lightcraft-wincolor"
version = "0.18.0"
dependencies = [
"lightcraft-testkit",
"windows-sys 0.61.2",
]
[[package]]
name = "linebender_resource_handle"
version = "0.1.1"
+3
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" }
@@ -58,6 +59,8 @@ log = "0.4"
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
rayon = "1"
# free/total space of a drive (engine's low-disk alert); MIT OR Apache-2.0, pure Rust (rustix / windows-sys)
fs4 = { version = "1.1", default-features = false }
winapi-util = "0.1" # lightcraft-catalog reads a file's volume serial number and file index with it on Windows
proptest = "1"
bytemuck = { version = "1", features = ["derive"] }
+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");
+7 -7
View File
@@ -12,7 +12,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use lightcraft_engine::files::{load_bytes_with, probe_bytes};
use lightcraft_engine::files::{load_bytes_decoded, probe_bytes};
use lightcraft_engine::media::{FileLoader, FileProbe};
/// Prefix of the catalog paths of files kept in browser storage.
@@ -146,9 +146,9 @@ impl Originals {
let s = self.clone();
// (an imported camera profile is not applied on the web, as in the render worker: a raw keeps its own colour,
// whether it decodes in a worker or inline when workers are unavailable)
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, _dcp: Option<&lightcraft_engine::media::DcpProfile>| {
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, with: lightcraft_engine::media::RawDecode<'_>| {
let bytes = s.get(path).ok_or_else(|| format!("{path}: the original is still loading from browser storage"))?;
load_bytes_with(&bytes, max_edge, None)
load_bytes_decoded(&bytes, max_edge, lightcraft_engine::media::RawDecode { dcp: None, outliers: with.outliers })
});
let s = self.clone();
let probe: FileProbe = Arc::new(move |path: &str| {
@@ -285,15 +285,15 @@ mod tests {
color: ColorData { illuminant: [21, 0], color_matrix: [Some(swap), None], ..Default::default() },
};
assert_ne!(
load_bytes_with(&dng, 64, Some(&profile)).unwrap().0.data,
load_bytes_with(&dng, 64, None).unwrap().0.data,
lightcraft_engine::files::load_bytes_with(&dng, 64, Some(&profile)).unwrap().0.data,
lightcraft_engine::files::load_bytes_with(&dng, 64, None).unwrap().0.data,
"the profile changes a raw's colour where it is applied"
);
let store = Originals::default();
store.insert("h1", Arc::from(dng));
let (loader, _) = store.hooks();
let with = loader("web/h1/a.dng", 64, Some(&profile)).unwrap();
let without = loader("web/h1/a.dng", 64, None).unwrap();
let with = loader("web/h1/a.dng", 64, lightcraft_engine::media::RawDecode { dcp: Some(&profile), outliers: false }).unwrap();
let without = loader("web/h1/a.dng", 64, Default::default()).unwrap();
assert_eq!(with.0.data, without.0.data, "the web loader leaves it out");
}
+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
@@ -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();
}
}
+5
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 _;
@@ -371,6 +375,7 @@ fn main() -> eframe::Result {
app.notices.extend(launch_notices);
app.notices.extend(window_notice);
app.gpu_notice = true;
app.disk_space_notice = true;
// an empty library opens where Import is offered (a grid, with the sidebar); before
// the snapshot below, so this alone isn't written to the settings file
if problem.is_none() && files.is_empty() {
+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()
+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(),
}
}
+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
+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())
}
+8
View File
@@ -632,6 +632,13 @@ pub struct Detail {
pub nr_color: f64,
pub nr_color_detail: f64,
pub nr_color_smoothness: f64,
/// Replace single outlier photosites (noise spikes far above all their same-colour neighbours) in the
/// raw mosaic before demosaicing, so they do not become coloured dots (#1345). On for newly imported
/// raws ([`crate::DevelopSettings::for_raw`]); off for edits saved before it existed, so they look the
/// same. Raw files only. Omitted when off, so settings saved before it keep their JSON (and hash, and with it
/// their cached thumbnails).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub nr_outliers: bool,
}
impl Default for Detail {
@@ -649,6 +656,7 @@ impl Default for Detail {
nr_color: 0.0,
nr_color_detail: 50.0,
nr_color_smoothness: 50.0,
nr_outliers: false,
}
}
}
+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, None).expect("load"))));
println!(" {:<36} {}", "fs loader (2560, read+load):", best(n, || drop(loader(path, 2560, Default::default()).expect("load"))));
}
}
+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),
]
+1 -1
View File
@@ -1166,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 {
+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),
+363 -50
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())
}
@@ -361,8 +619,8 @@ fn original_only(source: crate::media::SourceRef) -> Option<crate::media::Source
use crate::media::SourceRef;
match source {
// (a smart preview keeps the file's own colour: an imported camera profile is applied when the original is read)
SourceRef::File { path, max_edge, loader, denoise, .. } => {
Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, camera_profile: None, reduced: None })
SourceRef::File { path, max_edge, loader, denoise, outliers, .. } => {
Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, camera_profile: None, outliers, reduced: None })
}
SourceRef::Loaded(d) if d.info.is_some() && !d.from_proxy && !d.reduced => Some(SourceRef::Loaded(d)),
_ => None,
@@ -476,10 +734,18 @@ fn smart(s: &mut Session, p: &Value) -> Result<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 };
@@ -496,19 +762,35 @@ fn smart(s: &mut Session, p: &Value) -> Result<Value> {
if background {
let what = if discard { "discarding smart previews" } else { "smart previews" };
let state = Arc::new(PreviewBuild { total: jobs.len(), what, ..Default::default() });
s.preview_build = Some(state.clone());
let previous = s.preview_build.replace(state.clone());
let task = task_for(s, &state);
let st = state.clone();
std::thread::Builder::new()
.name("lc-smart-previews".into())
.spawn(move || {
if let Err(e) = smart_run(&dir, custom, discard, jobs, Some((&st, &task))) {
log::warn!("{C}: {e}");
*st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e);
}
st.finished.store(true, Ordering::Relaxed);
})
.map_err(|e| bad(C, format!("could not start: {e}")))?;
let work = move || {
if let Err(e) = smart_run(&dir, custom, discard, jobs, Some((&st, &task))) {
log::warn!("{C}: {e}");
*st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e);
}
st.finished.store(true, Ordering::Relaxed);
};
#[cfg(test)]
let started = if test_gate::take_fail_spawn() {
drop(work);
Err(std::io::Error::other("no thread (test)"))
} else {
std::thread::Builder::new().name("lc-smart-previews".into()).spawn(work)
};
#[cfg(not(test))]
let started = std::thread::Builder::new().name("lc-smart-previews".into()).spawn(work);
if let Err(e) = started {
// never started: not left "running", and the background build it was to replace carries on
// (CodeRabbit on #3077)
state.finished.store(true, Ordering::Relaxed);
s.preview_build = previous;
return Err(bad(C, format!("could not start: {e}")));
}
if let Some(cancel) = gives_way {
cancel.store(true, Ordering::Relaxed);
}
return Ok(state.json());
}
let r = smart_run(&dir, custom, discard, jobs, None).map_err(|e| bad(C, e))?;
@@ -647,7 +929,7 @@ pub fn specs() -> Vec<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
),
@@ -674,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);
@@ -730,6 +1042,7 @@ mod tests {
fallback: None,
denoise: None,
camera_profile: None,
outliers: false,
reduced: None,
};
assert!(run_photo(jobs), "the thumbnail rendered from the view's decoded source");
+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
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());
}
}
+29 -1
View File
@@ -27,7 +27,7 @@ pub(crate) use colour::clipped_white;
use fs::quick_image_srgb;
pub use fs::{fs_hooks, fs_pair_loader, fs_reduced_loader};
pub(crate) use load::{DngWhite, WbScaleOf, dng_tone_curve};
pub use load::{load_bytes, load_bytes_with, load_vec, load_vec_pair, load_vec_reduced};
pub use load::{load_bytes, load_bytes_decoded, load_bytes_with, load_vec, load_vec_pair, load_vec_reduced};
#[cfg(test)]
use preview::PLAN_PREFIX;
pub(crate) use preview::decode_raw_preview;
@@ -109,5 +109,33 @@ impl CameraColourModel<'_> {
}
}
/// Remove Hot Pixels leaves a raw alone when more than this share of its photosites would be replaced (Settings ▸
/// Performance ▸ Hot pixel limit, `app.hotPixelLimit`), as `f64` bits. Process-wide, like the GPU switch.
static HOT_PIXEL_LIMIT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(lightcraft_raw::HOT_PIXEL_MAX_SHARE.to_bits());
/// The share of a raw's photosites Remove Hot Pixels may replace (0..1).
pub fn hot_pixel_limit() -> f64 {
f64::from_bits(HOT_PIXEL_LIMIT.load(std::sync::atomic::Ordering::Relaxed))
}
/// Set [`hot_pixel_limit`]; false (nothing changed) unless `share` is a new value in 0..=1. Sources decoded before
/// keep the old limit: the caller forgets them ([`crate::media::MediaCache::clear_sources`]).
pub fn set_hot_pixel_limit(share: f64) -> bool {
if !(0.0..=1.0).contains(&share) {
return false;
}
HOT_PIXEL_LIMIT.swap(share.to_bits(), std::sync::atomic::Ordering::Relaxed) != share.to_bits()
}
/// What [`hot_pixel_limit`] adds to the render cache keys of `settings`: nothing at the default limit or when they
/// don't remove hot pixels, so those renders stay valid whatever the limit.
pub fn hot_pixel_key(settings: &lightcraft_develop::DevelopSettings) -> u64 {
let limit = hot_pixel_limit();
if !settings.removes_hot_pixels() || limit.to_bits() == lightcraft_raw::HOT_PIXEL_MAX_SHARE.to_bits() {
return 0;
}
limit.to_bits().wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(29)
}
#[cfg(test)]
pub(crate) mod tests;
+12 -5
View File
@@ -1,7 +1,8 @@
use super::load::{load_vec, load_vec_pair, load_vec_reduced};
use super::preview::{fit_box, fs_preview_loader, preview_orientation};
use super::probe::probe_bytes;
use super::{Arc, DcpProfile, DenoiseSpec, FileLoader, FileProbe, Filter, PairLoader, ReducedLoader, fit};
use super::{Arc, DenoiseSpec, FileLoader, FileProbe, Filter, PairLoader, ReducedLoader, fit};
use crate::media::RawDecode;
/// The file's first [`lightcraft_raw::PREVIEW_PREFIX`] bytes (or the whole file when it is shorter),
/// which is what every format [`lightcraft_raw::bounded_preview`] covers keeps its pointer in.
@@ -37,6 +38,12 @@ pub(super) fn raf_preview_extent(prefix: &[u8]) -> Option<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, dcp: Option<&DcpProfile>| {
Arc::new(|path: &str, max_edge: usize, spec: &DenoiseSpec, with: RawDecode<'_>| {
let len = std::fs::metadata(path).map(|m| m.len() as usize).unwrap_or(0);
let weight = len * if max_edge <= crate::media::SourceLevel::Thumb.max_edge() { 4 } else { 10 };
let gate = crate::memory::work_gate();
let _permit = if crate::memory::is_background() { gate.acquire(weight) } else { gate.acquire_urgent(weight) };
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
let r = load_vec_pair(bytes, max_edge, spec, dcp);
let r = load_vec_pair(bytes, max_edge, spec, with);
crate::memory::release();
r
})
@@ -75,7 +82,7 @@ pub fn fs_pair_loader() -> PairLoader {
/// yields to them.
pub fn fs_hooks() -> (FileLoader, FileProbe) {
let loader: FileLoader =
Arc::new(|path: &str, max_edge: usize, dcp: Option<&DcpProfile>| fs_load(path, max_edge, |bytes| load_vec(bytes, max_edge, dcp)));
Arc::new(|path: &str, max_edge: usize, with: RawDecode<'_>| fs_load(path, max_edge, |bytes| load_vec(bytes, max_edge, with)));
let probe: FileProbe = Arc::new(|path: &str| {
use std::io::Read;
// one open, then everything from the open file: its size and modification time are not
@@ -95,7 +102,7 @@ pub fn fs_hooks() -> (FileLoader, FileProbe) {
/// The filesystem [`ReducedLoader`]: [`load_vec_reduced`] of the file, gated like [`fs_hooks`]' loader.
pub fn fs_reduced_loader() -> ReducedLoader {
Arc::new(|path: &str, max_edge: usize, dcp: Option<&DcpProfile>| fs_load(path, max_edge, |bytes| load_vec_reduced(bytes, max_edge, dcp)))
Arc::new(|path: &str, max_edge: usize, with: RawDecode<'_>| fs_load(path, max_edge, |bytes| load_vec_reduced(bytes, max_edge, with)))
}
/// Read `path` and `load` it, waiting on [`crate::memory::work_gate`] as [`fs_hooks`] explains.
+24 -9
View File
@@ -2,6 +2,7 @@ use super::colour::bin_factor;
use super::preview::{fit_box, load_embedded_preview};
use super::probe::preview_reason;
use super::{Arc, CameraColourModel, DcpProfile, DenoiseSpec, Filter, HIGHLIGHT_CLIP, Orientation, Rgb32f, SourceInfo, fit, xy_to_temp_tint};
use crate::media::RawDecode;
/// Decode a file into a linear Rec.2020 image no larger than `max_edge`, oriented.
///
@@ -9,26 +10,31 @@ use super::{Arc, CameraColourModel, DcpProfile, DenoiseSpec, Filter, HIGHLIGHT_C
/// instead of each one waking the pool from outside and waiting for it (which costs more than the
/// loops themselves when the machine is busy).
pub fn load_bytes(bytes: &[u8], max_edge: usize) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false, None).map(|(img, _, info, _)| (img, info)))
load_bytes_decoded(bytes, max_edge, RawDecode::default())
}
/// [`load_bytes`] developing a raw file with an imported camera profile (`dcp`) in place of its own colour model.
pub fn load_bytes_with(bytes: &[u8], max_edge: usize, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false, dcp).map(|(img, _, info, _)| (img, info)))
load_bytes_decoded(bytes, max_edge, RawDecode { dcp, outliers: false })
}
/// [`load_bytes`] decoding a raw file as `with` says.
pub fn load_bytes_decoded(bytes: &[u8], max_edge: usize, with: RawDecode<'_>) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false, with).map(|(img, _, info, _)| (img, info)))
}
/// [`load_bytes`] taking the file's bytes: a raw file's bytes are freed as soon as it is decoded
/// (less memory held while it is developed).
pub fn load_vec(bytes: Vec<u8>, max_edge: usize, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, false, dcp).map(|(img, _, info, _)| (img, info)))
pub fn load_vec(bytes: Vec<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, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo, bool), String> {
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, dcp).map(|(img, _, info, reduced)| (img, info, reduced))
load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, true, with).map(|(img, _, info, reduced)| (img, info, reduced))
})
}
@@ -39,10 +45,10 @@ pub fn load_vec_pair(
bytes: Vec<u8>,
max_edge: usize,
spec: &DenoiseSpec,
dcp: Option<&DcpProfile>,
with: RawDecode<'_>,
) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> {
rayon::scope(move |_| {
load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, Some(spec), false, dcp).map(|(img, twin, info, _)| (img, twin, info))
load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, Some(spec), false, with).map(|(img, twin, info, _)| (img, twin, info))
})
}
@@ -73,8 +79,9 @@ fn load_bytes_now(
max_edge: usize,
denoise: Option<&DenoiseSpec>,
allow_reduced: bool,
dcp: Option<&DcpProfile>,
with: RawDecode<'_>,
) -> Result<(Rgb32f, Option<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
@@ -96,6 +103,14 @@ fn load_bytes_now(
}
Err(Err(e)) => return Err(e),
};
// single outlier photosites, replaced in the mosaic before anything is developed from it (#1345)
if with.outliers {
let t = std::time::Instant::now();
let n = raw.suppress_hot_pixels_with(super::hot_pixel_limit());
if lightcraft_pipeline::profiling() {
eprintln!("[profile] raw outliers: {n} photosites replaced in {:.1} ms", t.elapsed().as_secs_f64() * 1e3);
}
}
// Embedded lens corrections are applied by the pipeline ("Enable Profile Corrections"), not baked in
// (removed before the camera look's binned sensor proxy too, which needs an empty `OpcodeList3`).
let info = raw.info();
+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, None).unwrap();
let (plain, cached, _) = load_vec_pair(bytes, 2048, &spec, Default::default()).unwrap();
assert_eq!(plain.data, ordinary.data, "requesting a twin must not change the ordinary path");
let cached = cached.unwrap();
assert_eq!((plain.width, plain.height), (24, 32));
@@ -1255,10 +1255,10 @@ fn exports_never_develop_a_dngs_reduced_copy() {
let mean = |img: &lightcraft_raster::Rgba8| img.data.iter().map(|p| p[1] as f64).sum::<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, None).unwrap();
let (copy, _, used) = load_vec_reduced(bytes.clone(), 512, Default::default()).unwrap();
assert!(used, "a thumbnail develops the copy");
assert!(!load_vec_reduced(bytes.clone(), 1024, None).unwrap().2, "no copy covers 1024 px");
let (full, _) = load_vec(bytes.clone(), 512, None).unwrap();
assert!(!load_vec_reduced(bytes.clone(), 1024, Default::default()).unwrap().2, "no copy covers 1024 px");
let (full, _) = load_vec(bytes.clone(), 512, Default::default()).unwrap();
assert!(g(&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);
+2
View File
@@ -528,6 +528,8 @@ impl Session {
key,
cached: Vec::new(),
embedded,
embedded_cache: None,
embedded_on_disk: false,
minimum_embedded_edge,
small: Some(Box::new(small)),
})
+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
+16 -2
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;
@@ -398,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
@@ -537,9 +547,12 @@ impl Session {
folder_changes: None,
activity: Default::default(),
preview_build: None,
prep: Default::default(),
loupe_edge: 0,
slideshow_export: None,
import_defaults: import::ImportDefaults::default(),
cache_mb: 0,
disk_alert: Default::default(),
slideshow: slideshow::PlaybackSettings::default(),
slide_layout: slide::SlideSettings::default(),
slide_overlays: slide_overlay::OverlaySettings::default(),
@@ -1003,8 +1016,9 @@ impl Session {
return Vec::new();
}
let Some(old) = self.develop_of(id) else { return Vec::new() };
let mut old_json = old.to_json();
let mut new_json = new.to_json();
// (Remove Hot Pixels, omitted when off, is stated: switching it off is a change)
let mut old_json = old.to_json_for_merge();
let mut new_json = new.to_json_for_merge();
// False is omitted from stored profile JSON. Keep it explicit for this comparison so
// switching camera local tone mapping off is a change without copying untouched values.
old_json["profile"]["camera_local_tone"] = Value::Bool(old.profile.camera_local_tone);
+43 -2
View File
@@ -258,6 +258,13 @@ impl Library {
}
}
/// [`PrefsFile`]'s `prep`, read leniently (see there).
fn lenient_prep<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<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 {
@@ -295,6 +302,11 @@ struct PrefsFile {
import: crate::import::ImportDefaults,
/// Thumbnail disk cache budget (MB, 0 = default).
cache_mb: u32,
/// This library's own background preparation settings (`None`: the app-wide ones). Read
/// leniently: a value a newer build wrote that this one doesn't know is `None`, and the rest of
/// the file is kept.
#[serde(skip_serializing_if = "Option::is_none", deserialize_with = "lenient_prep")]
prep: Option<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 =
@@ -585,6 +597,7 @@ impl Session {
self.recent_keywords = prefs.recent_keywords;
self.import_defaults = prefs.import;
self.cache_mb = prefs.cache_mb;
self.prep.library = prefs.prep.map(crate::prep::PrepSettings::sanitized);
self.slideshow = prefs.slideshow.sanitized();
self.slide_layout = prefs.slide_layout.sanitized();
self.slide_overlays = prefs.slide_overlays.sanitized();
@@ -688,6 +701,9 @@ impl Session {
crate::cmd::previews::refresh_stale_smart_previews(self);
}
self.library_identity = std::sync::Arc::new(());
// a library open is a new session for the low-disk alert: look at the drive now
self.disk_alert.reset();
self.check_disk_space(true);
Ok(())
}
@@ -900,6 +916,7 @@ impl Session {
recent_keywords: self.recent_keywords.clone(),
import: self.import_defaults.clone(),
cache_mb: self.cache_mb,
prep: self.prep.library,
smart_previews_dir: self.smart_previews_dir.as_ref().map(|d| d.to_string_lossy().to_string()),
forget_local_days: Some(self.forget_local_days),
slideshow: self.slideshow.clone(),
@@ -927,9 +944,23 @@ impl Session {
new
}
/// The thumbnail disk cache budget in bytes ([`Session::cache_mb`], else the default).
/// The thumbnail disk cache budget in bytes ([`Session::cache_mb`], else the default, which
/// grows with the library: [`crate::media::default_disk_cache_bytes`]).
pub fn cache_bytes(&self) -> u64 {
if self.cache_mb == 0 { crate::media::DISK_CACHE_BYTES } else { u64::from(self.cache_mb) << 20 }
if self.cache_mb == 0 { crate::media::default_disk_cache_bytes(self.catalog.len()) } else { u64::from(self.cache_mb) << 20 }
}
/// Bring the disk cache's budget up to date with the library (photos were added since it was
/// set): cheap, nothing is read or written. Called before previews are built, so it also
/// looks at the drive's free space when that is due ([`Session::check_disk_space`]).
pub fn fit_disk_cache(&mut self) {
let want = self.cache_bytes();
if let Some(d) = self.media.rendered.disk()
&& d.budget() != want
{
d.set_budget(want);
}
self.check_disk_space(false);
}
/// Change the thumbnail disk cache budget (MB, 0 = default) in place: the cached thumbnails
@@ -991,6 +1022,16 @@ fn unlocked_warning(lock: Option<&LibraryLock>) -> Option<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]
+6 -3
View File
@@ -35,14 +35,17 @@ mod settings_hash;
mod source;
pub use cache::DenoiseIndex;
#[cfg(test)]
pub(crate) use cache::rendered_budget;
pub use quick::{QuickJob, QuickSource, content_key, source_info};
pub use render::{RenderJob, RenderResult, ScreenFrame, develop, develop_reporting, fit_for_display};
pub use render::{RenderJob, RenderResult, ScreenFrame, develop, develop_reporting, fit_cached, fit_for_display};
#[cfg(test)]
use settings_hash::SETTINGS_HASH_ENTRIES;
use settings_hash::SettingsHashes;
pub use source::{
DISK_CACHE_BYTES, DecodedSource, DenoiseSpec, FACE_EDGE_STEP, FileLoader, FileProbe, MakeProduct, PairLoader, PreviewLoader, ProbeInfo,
RENDER_CACHE_VERSION, ReducedLoader, SourceLevel, SourceRef, THUMB_SIZES, Twin, face_edge, thumb_bucket,
DISK_CACHE_BYTES, DISK_CACHE_PER_PHOTO, DecodedSource, DenoiseSpec, FACE_EDGE_STEP, FileLoader, FileProbe, MakeProduct, PairLoader,
PreviewLoader, ProbeInfo, RENDER_CACHE_VERSION, RawDecode, ReducedLoader, SourceLevel, SourceRef, THUMB_SIZES, Twin, default_disk_cache_bytes,
face_edge, thumb_bucket,
};
pub struct MediaCache {
+14 -7
View File
@@ -75,9 +75,11 @@ impl Default for MediaCache {
}
}
/// Memory for rendered previews out of the cache share.
fn rendered_budget(share: usize) -> usize {
RENDERED_MEM_BYTES.min(share / 4)
/// Memory for rendered previews out of the cache share: a quarter of it, so a big budget keeps
/// a whole shoot's previews (a 20 GB budget holds about 230 standard previews, or 1 500 loupe
/// renders at 1 200 px), and at least [`RENDERED_MEM_BYTES`] where the share allows.
pub(crate) fn rendered_budget(share: usize) -> usize {
(share / 4).max(RENDERED_MEM_BYTES.min(share / 2))
}
impl MediaCache {
@@ -332,11 +334,12 @@ impl MediaCache {
}
fn source_ref_plain(&mut self, p: &Photo, level: SourceLevel, cached: bool, wanted: Option<(String, Arc<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)
&& let Some(a) = self.get_source(p.id, level).filter(|a| a.fits_outliers(outliers))
&& (a.camera_profile == wanted.as_ref().map(|(id, _)| id.clone()) || (a.from_proxy && self.original_offline(p)))
{
return SourceRef::Loaded(Box::new(a));
@@ -346,7 +349,7 @@ impl MediaCache {
if cached
&& level == SourceLevel::Thumb
&& self.denoise.spec(p.id).is_none()
&& let Some(big) = self.get_source(p.id, SourceLevel::Preview)
&& let Some(big) = self.get_source(p.id, SourceLevel::Preview).filter(|b| b.fits_outliers(outliers))
&& (big.camera_profile == wanted.as_ref().map(|(tag, _)| tag.clone()) || (big.from_proxy && self.original_offline(p)))
{
return SourceRef::Fit { from: Box::new(big), max_edge: level.max_edge() };
@@ -370,15 +373,17 @@ impl MediaCache {
return SourceRef::Smart { path: sp };
}
let mut r = self.origin_ref(&p.source, max_edge);
if let SourceRef::File { fallback, camera_profile, .. } = &mut r {
if let SourceRef::File { fallback, camera_profile, outliers: o, .. } = &mut r {
*fallback = Some(sp);
*camera_profile = wanted;
*o = outliers;
}
return r;
}
let mut r = self.origin_ref(&p.source, max_edge);
if let SourceRef::File { camera_profile, .. } = &mut r {
if let SourceRef::File { camera_profile, outliers: o, .. } = &mut r {
*camera_profile = wanted;
*o = outliers;
}
r
}
@@ -419,6 +424,7 @@ impl MediaCache {
fallback: None,
denoise: None,
camera_profile: None,
outliers: false,
reduced: None,
},
}
@@ -430,6 +436,7 @@ impl MediaCache {
fallback: None,
denoise: None,
camera_profile: None,
outliers: false,
reduced: None,
},
}
+37 -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.
@@ -79,13 +88,30 @@ impl QuickJob {
}
}
let mut embedded_fallback = None;
if let Some((path, loader, edge)) = &self.embedded
&& let Some(image) = loader(path, *edge)
{
if self.minimum_embedded_edge.is_none_or(|minimum| image.width.max(image.height) >= minimum) {
return done(rendered(image), Some(QuickSource::Embedded));
if let Some((path, loader, edge)) = &self.embedded {
let kept =
self.embedded_cache.as_ref().and_then(|(cache, k, _)| if self.embedded_on_disk { cache.get(*k) } else { cache.get_memory(*k) });
let image = match kept {
Some(img) => Some(Arc::unwrap_or_clone(img)),
None => {
let image = loader(path, *edge);
// written for the generation the job was made in: a cache cleared meanwhile stays clear
if let (Some(image), Some((cache, k, generation))) = (&image, &self.embedded_cache) {
if self.embedded_on_disk {
cache.put_deferred_at(*generation, *k, Arc::new(image.clone()));
} else {
cache.put_memory_at(*generation, *k, Arc::new(image.clone()));
}
}
image
}
};
if let Some(image) = image {
if self.minimum_embedded_edge.is_none_or(|minimum| image.width.max(image.height) >= minimum) {
return done(rendered(image), Some(QuickSource::Embedded));
}
embedded_fallback = Some(image);
}
embedded_fallback = Some(image);
}
if let Some(job) = self.small {
let r = job.run();
@@ -100,6 +126,11 @@ impl QuickJob {
}
}
/// The thumbnail cache's key for the camera JPEG standing for the thumbnail of cache key `k`.
pub(super) fn embedded_thumb_key(k: Hash128) -> Hash128 {
Hasher128::new().str("embedded-thumb").u64((k.0 >> 64) as u64).u64(k.0 as u64).finish()
}
/// What identifies a photo's pixels for caching: its content hash, else its source.
/// Which decode of a photo a loaded source is: its file's content and, when it has one, its database lens profile
/// ([`lens_key`]; the decode fits the starting colour through it). A job's source is kept only when this still
+106 -1
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,
};
@@ -241,8 +241,58 @@ impl RenderJob {
r
}
/// The view render kept for this job's photo and settings ([`Self::view_cache`]), fitted to the
/// size asked for, when it is at least that big, or unchanged when it covers the job's display
/// fit (else `None`: render). Only for what the cached
/// view is: a full-quality, 8-bit, whole-frame SDR render (the cache holds sRGB; a display
/// profile is applied to it like to any cached picture, [`crate::display::present`]).
pub fn cached_view(&self) -> Option<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)
{
@@ -395,6 +445,61 @@ impl RenderJob {
}
}
/// `img` fitted into `max_w × max_h` (its aspect kept), when it is big enough to need no
/// enlarging (within [`VIEW_REUSE_SLACK`]): as it is, or shrunk by averaging.
pub fn fit_cached(img: &Rgba8, max_w: usize, max_h: usize) -> Option<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.
+76 -12
View File
@@ -1,4 +1,4 @@
use super::quick::{QuickJob, content_key, source_info};
use super::quick::{QuickJob, content_key, embedded_thumb_key, source_info};
use super::render::{RenderJob, RenderResult};
use super::settings_hash::with_process;
use super::source::{PreviewLoader, RENDER_CACHE_VERSION, SourceLevel, SourceRef, THUMB_SIZES, face_edge, source_edge_needed, thumb_bucket};
@@ -58,7 +58,8 @@ impl crate::Session {
let content = Hasher128::new().str(&content_key).finish().0 as u64;
let source_key = super::quick::source_identity(&p);
// Temporary "before" settings must not replace the photo's cached develop hash.
let settings_hash = if before { settings.hash64() } else { self.media.settings_hashes.get(id, &settings) };
let settings_hash =
if before { settings.hash64() ^ crate::files::hot_pixel_key(&settings) } else { self.media.settings_hashes.get(id, &settings) };
let salt = self.media.denoise_salt(id, &settings);
let profile_salt = self.media.camera_profile_salt(&settings.profile.id);
let lens = super::quick::lens_key(&p);
@@ -131,6 +132,7 @@ impl crate::Session {
// (the photo's database lens profile stays part of it: a profile looked up again renders afresh)
let lens = self.catalog.photo(id).map_or(0, |p| super::quick::lens_key(p));
job.key = settings.hash64()
^ crate::files::hot_pixel_key(settings)
^ ((max_w as u64) << 40)
^ ((max_h as u64) << 20)
^ (apply_crop as u64)
@@ -144,7 +146,11 @@ impl crate::Session {
/// `profile_salt`: [`MediaCache::camera_profile_salt`] of `settings`' profile.
pub fn variant_key(p: &Photo, settings: &DevelopSettings, edge: usize, profile_salt: u64) -> Hash128 {
let mut k = Hasher128::new();
k.str(&content_key(p)).str("variant").u64(settings.hash64()).u64(edge as u64).u64(RENDER_CACHE_VERSION);
k.str(&content_key(p))
.str("variant")
.u64(settings.hash64() ^ crate::files::hot_pixel_key(settings))
.u64(edge as u64)
.u64(RENDER_CACHE_VERSION);
with_process(&mut k, settings).u64(crate::camera_profiles::cache_key());
if profile_salt != 0 {
k.str("dcp").u64(profile_salt);
@@ -264,12 +270,23 @@ impl crate::Session {
Some(crate::face_tiles::PreviewCut { path, loader, want, min, rect, aspect, edge })
}
/// Size-independent cache key of a photo's view render (loupe) for its current settings, its lens profile
/// included as in [`Self::variant_key`]. `profile_salt`: [`MediaCache::camera_profile_salt`] of the photo's profile.
pub(crate) fn view_key(p: &Photo, apply_crop: bool, profile_salt: u64) -> Hash128 {
/// Size-independent cache key of a photo's view render (loupe) for its current settings. The
/// denoised picture, camera profile and lens profile in use are part of it (as of the render's own
/// key, [`Self::variant_key`]): a view rendered before the photo's AI Denoise result was there is
/// not shown as the denoised one.
pub(crate) fn view_key(&self, p: &Photo, apply_crop: bool) -> Hash128 {
let salt = self.media.denoise_salt(p.id, &p.develop);
let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id);
let mut k = Hasher128::new();
k.str(&content_key(p)).str("view").u64(p.develop.hash64()).u64(apply_crop as u64).u64(RENDER_CACHE_VERSION);
k.str(&content_key(p))
.str("view")
.u64(p.develop.hash64() ^ crate::files::hot_pixel_key(&p.develop))
.u64(apply_crop as u64)
.u64(RENDER_CACHE_VERSION);
with_process(&mut k, &p.develop).u64(crate::camera_profiles::cache_key());
if salt != 0 {
k.u64(salt);
}
if profile_salt != 0 {
k.str("dcp").u64(profile_salt);
}
@@ -285,8 +302,7 @@ impl crate::Session {
pub fn loupe_job(&mut self, id: PhotoId, max_w: usize, max_h: usize, apply_crop: bool) -> Option<RenderJob> {
let mut job = self.render_job(id, max_w, max_h, false, apply_crop)?;
let p = self.catalog.photo(id)?;
let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id);
job.view_cache = Some((self.media.rendered.clone(), Self::view_key(p, apply_crop, profile_salt)));
job.view_cache = Some((self.media.rendered.clone(), self.view_key(p, apply_crop)));
Some(job)
}
@@ -396,11 +412,55 @@ impl crate::Session {
let small = self.thumb_job(id, THUMB_SIZES[THUMB_SIZES.len() - 1])?;
// (the thumbnail job itself starts with the cached thumbnail, after the sharper embedded preview)
let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id);
let cached = vec![(self.media.rendered.clone(), Self::view_key(&p, apply_crop, profile_salt))];
let h = Hasher128::new().str(&content_key(&p)).str("quick").u64(p.develop.hash64()).u64(apply_crop as u64).u64(profile_salt).finish();
let cached = vec![(self.media.rendered.clone(), self.view_key(&p, apply_crop))];
// (the photo too: a virtual copy shares the file and, unedited, the settings)
let h = Hasher128::new()
.str(&content_key(&p))
.str("quick")
.u64(p.develop.hash64() ^ crate::files::hot_pixel_key(&p.develop))
.u64(apply_crop as u64)
.u64(id.0)
.u64(profile_salt)
.finish();
let key = h.0 as u64;
let embedded = self.embedded_of(&p).map(|(path, l)| (path, l, max_edge.clamp(1, SourceLevel::Preview.max_edge())));
Some(QuickJob { request_id: 0, photo: id, key, cached, embedded, minimum_embedded_edge: None, small: apply_crop.then(|| Box::new(small)) })
let embedded_cache = embedded.as_ref().map(|(_, _, edge)| {
let cache = self.media.rendered.clone();
let generation = cache.generation();
(cache, Hasher128::new().str(&content_key(&p)).str("embedded").u64(*edge as u64).finish(), generation)
});
Some(QuickJob {
request_id: 0,
photo: id,
key,
cached,
embedded,
embedded_cache,
embedded_on_disk: false,
minimum_embedded_edge: None,
small: apply_crop.then(|| Box::new(small)),
})
}
/// The camera's embedded JPEG of an unedited raw at up to `max_edge` pixels (its full size for
/// a camera that stores one), for the loupe zoomed to 100 % while LightCraft renders the window
/// on screen: a focus check needs the pixels at once, and a 45 MP render of the window takes
/// seconds. Not kept in any cache (a full-size picture is 180 MB). `None` for other photos.
pub fn embedded_full_job(&mut self, id: PhotoId, max_edge: usize) -> Option<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
@@ -419,6 +479,10 @@ impl crate::Session {
key: job.key,
cached: job.cache.clone().into_iter().collect(),
embedded: Some((path, l, edge)),
// the camera JPEG is this thumbnail (an unedited raw): kept with the rendered ones, under
// a key of its own, so the folder's next visit reads it from the thumbnail cache
embedded_cache: job.cache.as_ref().map(|(c, k)| (c.clone(), embedded_thumb_key(*k), c.generation())),
embedded_on_disk: true,
minimum_embedded_edge: None,
small: Some(Box::new(job.clone())),
})
+1 -1
View File
@@ -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;
+53 -15
View File
@@ -24,10 +24,23 @@ pub fn thumb_bucket(long_edge: usize) -> usize {
/// Memory budgets.
pub(super) const THUMB_SOURCE_BYTES: usize = 384 << 20;
/// The least memory kept for rendered previews (when the budget allows it).
pub(super) const RENDERED_MEM_BYTES: usize = 128 << 20;
/// Disk budget for the thumbnail cache.
/// The smallest disk budget for the thumbnail and preview cache.
pub const DISK_CACHE_BYTES: u64 = 2 << 30;
/// What one photo's previews take on disk, about: its standard preview (a 2048 px JPEG, ~1 MB)
/// and its grid thumbnails. The default disk budget grows by this per photo of the library, so
/// built previews of a whole wedding are not pruned while they are being made (PERF-PREVIEW-REUSE).
pub const DISK_CACHE_PER_PHOTO: u64 = 3 << 19;
/// The default disk budget for a library of `photos`: [`DISK_CACHE_BYTES`], or room for every
/// photo's previews ([`DISK_CACHE_PER_PHOTO`]) when that is more.
pub fn default_disk_cache_bytes(photos: usize) -> u64 {
DISK_CACHE_BYTES.max((photos as u64).saturating_mul(DISK_CACHE_PER_PHOTO))
}
/// A cached view render this much smaller than asked for still serves the loupe (rounding: a
/// fit of the same frame into a box one pixel different).
pub(super) const VIEW_REUSE_SLACK: f64 = 0.01;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
@@ -74,15 +87,22 @@ pub(super) fn source_edge_needed(p: &Photo, settings: &DevelopSettings, apply_cr
if needed.is_finite() { needed.min(usize::MAX as f64 / 2.0) as usize } else { out_long }
}
/// Decodes a file into a linear Rec.2020 image no larger than `max_edge` (set by the app).
/// The third argument is the photo's imported camera profile ([`crate::cmd::dcp_profiles`]): a raw file is developed
/// with its colour model.
pub type FileLoader = Arc<dyn Fn(&str, usize, Option<&DcpProfile>) -> 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, Option<&DcpProfile>) -> 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.
@@ -105,8 +125,7 @@ pub struct DenoiseSpec {
/// Decodes a raw file once and develops it twice: as usual, and from the denoised picture in `spec` when that can be
/// read (`None` when it cannot). Both are at most `max_edge` long and the same size.
pub type PairLoader =
Arc<dyn Fn(&str, usize, &DenoiseSpec, Option<&DcpProfile>) -> 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 {
@@ -139,6 +158,8 @@ pub struct DecodedSource {
/// The imported camera profile (`dcp:…` id) the raw file was developed with, if any: a cached source made with
/// another one (or none) doesn't stand in for it.
pub camera_profile: Option<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,
@@ -149,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, camera_profile: None, from_proxy: false, reduced: false }
DecodedSource { image, info, camera_tone: None, denoised: None, camera_profile: None, outliers: false, from_proxy: false, reduced: false }
}
/// Whether this source can stand for one decoded with `outliers`: a raw decode must match it; anything without a
/// mosaic (a rendered file, a smart preview, a demo scene) has nothing the flag would change. A smart preview's
/// facts say `raw` for a raw photo, so it is told apart by `from_proxy`.
pub fn fits_outliers(&self, outliers: bool) -> bool {
self.outliers == outliers || self.from_proxy || !self.info.as_ref().is_some_and(|i| i.raw)
}
/// The picture to develop for a Denoise `amount` (0 to 1, see [`DevelopSettings::denoise_amount`]): the plain one,
@@ -243,6 +271,8 @@ pub enum SourceRef {
denoise: Option<(DenoiseSpec, PairLoader)>,
/// The photo's imported camera profile (id and profile): its raw file is developed with it.
camera_profile: Option<(String, Arc<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>,
},
@@ -270,17 +300,21 @@ impl SourceRef {
return Ok(DecodedSource { image: Arc::new(image), denoised: None, ..(**from).clone() });
}
SourceRef::Demo { scene, max_edge } => crate::demo::scene_pixels(scene, *max_edge)?,
SourceRef::File { path, max_edge, loader, fallback, denoise, camera_profile, reduced } => {
let dcp = camera_profile.as_ref().map(|(_, p)| p.as_ref());
SourceRef::File { path, max_edge, loader, fallback, denoise, camera_profile, outliers, reduced } => {
let with = RawDecode { dcp: camera_profile.as_ref().map(|(_, p)| p.as_ref()), outliers: *outliers };
let made_with = camera_profile.as_ref().map(|(id, _)| id.clone());
let plain = || match (reduced, loader) {
(Some(l), _) => l(path, *max_edge, dcp).map(|(image, info, reduced)| DecodedSource {
(Some(l), _) => l(path, *max_edge, with).map(|(image, info, reduced)| DecodedSource {
reduced,
camera_profile: made_with.clone(),
outliers: *outliers,
..DecodedSource::new(Arc::new(image), Some(info))
}),
(None, Some(l)) => l(path, *max_edge, with).map(|(image, info)| DecodedSource {
camera_profile: made_with.clone(),
outliers: *outliers,
..DecodedSource::new(Arc::new(image), Some(info))
}),
(None, Some(l)) => l(path, *max_edge, dcp)
.map(|(image, info)| DecodedSource { camera_profile: made_with.clone(), ..DecodedSource::new(Arc::new(image), Some(info)) }),
(None, None) => Err(format!("no decoder available for {path}")),
};
// the denoised picture comes with the plain one from a single decode; when it cannot be read the
@@ -294,7 +328,7 @@ impl SourceRef {
None => true,
};
if made {
pair(path, *max_edge, spec, dcp).and_then(|(image, twin, info)| {
pair(path, *max_edge, spec, with).and_then(|(image, twin, info)| {
if spec.make.is_some() && twin.is_none() {
return Err("the cached AI Denoise picture could not be read; clear the denoise cache and retry".into());
}
@@ -304,6 +338,7 @@ impl SourceRef {
camera_tone: None,
denoised: twin.map(|t| Arc::new(Twin::new(Arc::new(t)))),
camera_profile: made_with.clone(),
outliers: *outliers,
from_proxy: false,
reduced: false,
})
@@ -355,6 +390,9 @@ pub struct ProbeInfo {
pub embedded_lens: Option<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>,
+2
View File
@@ -91,6 +91,7 @@ fn decoder_info_survives_render_jobs_cache_and_eviction() {
fallback: None,
denoise: None,
camera_profile: None,
outliers: false,
reduced: None,
};
job.info = SourceInfo::default(); // Header facts cannot override decoder facts.
@@ -148,6 +149,7 @@ fn old_relative_white_balance_on_a_kelvin_camera_keeps_its_look_and_learns_the_a
fallback: None,
denoise: None,
camera_profile: None,
outliers: false,
reduced: None,
};
let undo_before = s.undo.len();
+176 -2
View File
@@ -6,6 +6,60 @@ fn session() -> crate::Session {
s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
s
}
/// PERF-CULL: an unedited raw's camera JPEG is read once for the loupe and kept in memory for a
/// step back; the full-size one (zoomed in) is made at the size asked for and kept nowhere; an
/// edited raw or another file has none.
#[test]
fn camera_previews_are_kept_for_a_revisit_and_full_size_ones_are_not() {
let reads = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let mut s = crate::Session::new();
let r = reads.clone();
s.media.preview_loader = Some(Arc::new(move |_: &str, edge: usize| {
r.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Some(Rgba8 { width: edge.min(64), height: 2, data: vec![[9, 8, 7, 255]; edge.min(64) * 2] })
}));
let mut raw = Photo::new(PhotoId(1), Source::File { path: "a.cr3".into() }, "a.cr3", "CR3", 6000, 4000, "2026-01-01");
raw.kind = MediaKind::Raw;
raw.develop = Arc::new(raw.camera_defaults());
s.catalog.apply(Op::AddPhoto { photo: Box::new(raw) }).unwrap();
let jpeg = Photo::new(PhotoId(2), Source::File { path: "b.jpg".into() }, "b.jpg", "JPEG", 600, 400, "2026-01-01");
s.catalog.apply(Op::AddPhoto { photo: Box::new(jpeg) }).unwrap();
for _ in 0..3 {
let q = s.quick_view_job(PhotoId(1), 48, true).unwrap();
let r = q.run();
assert_eq!(r.quick, Some(QuickSource::Embedded));
}
assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 1, "read once, then from memory");
let full = s.embedded_full_job(PhotoId(1), 8192).unwrap();
assert!(full.embedded_cache.is_none() && full.cached.is_empty() && full.small.is_none());
assert_eq!(full.embedded.as_ref().map(|e| e.2), Some(8192));
assert_ne!(full.key, s.quick_view_job(PhotoId(1), 48, true).unwrap().key);
assert_eq!(full.run().quick, Some(QuickSource::Embedded));
assert!(s.embedded_full_job(PhotoId(2), 8192).is_none(), "not a raw");
let mut edited = (*s.catalog.photo(PhotoId(1)).unwrap().develop).clone();
edited.light.exposure = 1.0;
s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(edited), label: "edit".into(), edited: None }).unwrap();
assert!(s.embedded_full_job(PhotoId(1), 8192).is_none(), "an edit is shown rendered");
}
/// A virtual copy shares its master's file and, unedited, its settings; its loupe stand-ins
/// are its own all the same (CodeRabbit on #3080).
#[test]
fn a_virtual_copy_has_its_own_stand_in_keys() {
let mut s = crate::Session::new();
s.media.preview_loader = Some(Arc::new(|_: &str, _: usize| None::<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
@@ -37,7 +91,7 @@ fn persistent_keys_name_the_process_the_settings_render_with() {
let resolved = u64::from(lightcraft_develop::Process::LATEST.version().0);
let keys = [
(s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1, None, 256),
(crate::Session::view_key(&p, true, 0), Some("view"), 1),
(s.view_key(&p, true), Some("view"), 1),
(crate::Session::variant_key(&p, &newer, 256, 0), Some("variant"), 256),
];
for (key, kind, size) in keys {
@@ -69,7 +123,7 @@ fn v1_and_v2_photos_keep_the_render_cache_keys_they_had() {
};
let keys = [
s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1 == before_v3(None, 256),
crate::Session::view_key(&p, true, 0) == before_v3(Some("view"), 1),
s.view_key(&p, true) == before_v3(Some("view"), 1),
crate::Session::variant_key(&p, &settings, 256, 0) == before_v3(Some("variant"), 256),
];
let old = process <= Process::V2;
@@ -217,6 +271,8 @@ fn a_render_that_panics_fails_instead_of_never_answering() {
key: 9,
cached: Vec::new(),
embedded: Some(("x.arw".into(), Arc::new(|_: &str, _: usize| -> Option<Rgba8> { panic!("preview reader bug") }), 256)),
embedded_cache: None,
embedded_on_disk: false,
minimum_embedded_edge: None,
small: None,
};
@@ -224,3 +280,121 @@ fn a_render_that_panics_fails_instead_of_never_answering() {
assert_eq!((r.request_id, r.key), (7, 9));
assert_eq!(r.rendered.err().as_deref(), Some("the render failed unexpectedly: preview reader bug"));
}
/// A raw photo's smart preview has no mosaic left: it stands in with the box on or off, so an offline raw keeps
/// reusing the decoded proxy instead of reading the file again for every render.
#[test]
fn a_smart_preview_fits_either_hot_pixel_setting() {
let raw = SourceInfo { raw: true, ..Default::default() };
let decoded = DecodedSource::new(Arc::new(Rgb32f::new(8, 8)), Some(raw));
assert!(decoded.fits_outliers(false) && !decoded.fits_outliers(true), "a raw decode must match the box");
let proxy = DecodedSource { from_proxy: true, ..decoded };
assert!(proxy.fits_outliers(false) && proxy.fits_outliers(true));
}
/// The Remove Hot Pixels box decides how a raw is decoded (#1345): the loader is told, and a source decoded with
/// the other setting is not reused. A rendered file has no mosaic, so its source stays.
#[test]
fn hot_pixel_box_decodes_the_raw_again() {
let mut s = session();
let asked = Arc::new(std::sync::Mutex::new(Vec::new()));
let log = asked.clone();
let raw = Arc::new(std::sync::atomic::AtomicBool::new(true));
let is_raw = raw.clone();
s.media.file_loader = Some(Arc::new(move |_, _, with: crate::media::RawDecode<'_>| {
log.lock().unwrap().push(with.outliers);
Ok((Rgb32f::new(8, 8), SourceInfo { raw: is_raw.load(std::sync::atomic::Ordering::Relaxed), ..Default::default() }))
}));
let set = |s: &mut crate::Session, on: bool| {
let mut d = (*s.catalog.photo(PhotoId(1)).unwrap().develop).clone();
d.detail.nr_outliers = on;
// a new edit each time, so a render cached for earlier settings is not simply shown again
d.light.exposure += 0.1;
s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(d), label: "box".into(), edited: None }).unwrap();
};
let render = |s: &mut crate::Session| {
let r = s.thumb_job(PhotoId(1), 256).unwrap().run();
s.accept(&r);
};
render(&mut s);
render(&mut s);
assert_eq!(*asked.lock().unwrap(), [false], "decoded once, then cached");
set(&mut s, true);
render(&mut s);
render(&mut s);
assert_eq!(*asked.lock().unwrap(), [false, true], "switched on: decoded again with the filter, then cached");
set(&mut s, false);
render(&mut s);
assert_eq!(*asked.lock().unwrap(), [false, true, false]);
// not a raw: the box changes nothing, the cached source is kept
raw.store(false, std::sync::atomic::Ordering::Relaxed);
s.media.forget(PhotoId(1));
set(&mut s, false);
render(&mut s);
set(&mut s, true);
render(&mut s);
assert_eq!(*asked.lock().unwrap(), [false, true, false, false]);
}
/// With the Detail section's eye off, Remove Hot Pixels contributes nothing either: the raw is decoded without it.
#[test]
fn detail_eye_off_decodes_the_raw_without_hot_pixel_removal() {
let mut s = session();
let asked = Arc::new(std::sync::Mutex::new(Vec::new()));
let log = asked.clone();
s.media.file_loader = Some(Arc::new(move |_, _, with: crate::media::RawDecode<'_>| {
log.lock().unwrap().push(with.outliers);
Ok((Rgb32f::new(8, 8), SourceInfo { raw: true, ..Default::default() }))
}));
for eye in [true, false] {
let mut d = (*s.catalog.photo(PhotoId(1)).unwrap().develop).clone();
d.detail.nr_outliers = true;
d.set_section_enabled("detail", eye);
d.light.exposure += 0.1;
s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(d), label: "eye".into(), edited: None }).unwrap();
let r = s.thumb_job(PhotoId(1), 256).unwrap().run();
s.accept(&r);
}
assert_eq!(*asked.lock().unwrap(), [true, false]);
}
/// CodeRabbit on #3544: a stand-in job decoding a camera JPEG when Discard Preview Cache clears the
/// cache doesn't put the picture back: it writes for the generation it was made in (memory and
/// disk alike), as render jobs do.
#[test]
fn a_camera_jpeg_decoded_across_a_cache_clear_is_not_kept() {
for on_disk in [false, true] {
let cache = Arc::new(PreviewCache::memory(64 << 20));
let made_in = cache.generation();
let key = Hash128(5);
let quick = QuickJob {
request_id: 1,
photo: PhotoId(1),
key: 2,
cached: Vec::new(),
embedded: Some(("x.arw".into(), Arc::new(|_: &str, _: usize| Some(Rgba8::new(16, 16))), 256)),
embedded_cache: Some((cache.clone(), key, made_in)),
embedded_on_disk: on_disk,
minimum_embedded_edge: None,
small: None,
};
// the user discards the cache while the job is on its way
cache.clear();
assert!(quick.run().rendered.is_ok(), "the stand-in is still shown");
assert!(cache.get_memory(key).is_none(), "on disk {on_disk}: nothing kept in the cleared cache");
// a job made after the clear keeps it as before
let quick = QuickJob {
request_id: 1,
photo: PhotoId(1),
key: 2,
cached: Vec::new(),
embedded: Some(("x.arw".into(), Arc::new(|_: &str, _: usize| Some(Rgba8::new(16, 16))), 256)),
embedded_cache: Some((cache.clone(), key, cache.generation())),
embedded_on_disk: on_disk,
minimum_embedded_edge: None,
small: None,
};
assert!(quick.run().rendered.is_ok());
assert!(cache.get_memory(key).is_some(), "on disk {on_disk}: kept when made after the clear");
}
}
+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");
}
}
+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
@@ -503,6 +503,7 @@ pub fn load(path: &Path) -> Result<crate::media::DecodedSource, String> {
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 {
+43
View File
@@ -44,6 +44,7 @@ mod organize;
mod persist;
mod prefs;
mod presets_scale;
mod preview_prep;
mod print;
mod process;
mod recheck;
@@ -1040,6 +1041,48 @@ fn auto_sync_carries_only_the_changed_settings() {
assert_eq!(s.develop_of(PhotoId(ids[1])).unwrap().light.exposure, 0.7);
}
#[test]
fn auto_sync_carries_remove_hot_pixels_off() {
use lightcraft_catalog::PhotoId;
let mut s = demo();
let ids: Vec<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;
+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);
}
+1 -1
View File
@@ -91,7 +91,7 @@ fn count_loads(s: &mut Session) -> Loads {
let loads = Loads::default();
let file = s.media.file_loader.clone().unwrap();
let n = loads.files.clone();
s.media.file_loader = Some(Arc::new(move |p: &str, e: usize, dcp: Option<&crate::media::DcpProfile>| {
s.media.file_loader = Some(Arc::new(move |p: &str, e: usize, dcp: crate::media::RawDecode<'_>| {
n.fetch_add(1, Ordering::SeqCst);
file(p, e, dcp)
}));
+209
View File
@@ -303,6 +303,149 @@ fn browsing_a_folder_lists_its_photos_without_adding_them() {
let _ = std::fs::remove_dir_all(&dir);
}
/// PERF-CULL-1: the Local view reads only what the library lacks, newest file first for the default
/// (newest capture first) sort, so the first screen is read first; other sorts follow their key.
#[test]
fn browsing_queues_unknown_files_in_the_order_the_view_shows_them() {
use lightcraft_catalog::{Sort, SortKey};
let dir = temp_dir("browse-order");
let set_time = |p: &Path, secs: u64| {
let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs);
std::fs::File::options().write(true).open(p).unwrap().set_modified(t).unwrap();
};
for (name, seed, secs) in [("a.png", 1u8, 300u64), ("b.png", 2, 100), ("c.png", 3, 200)] {
write_png(&dir.join(name), seed);
set_time(&dir.join(name), 1_700_000_000 + secs);
}
let mut s = Session::new().with_fs();
let known = dir.join("b.png").to_string_lossy().to_string();
s.execute("library.import", &json!({"paths": [known.clone()]})).unwrap();
let files: Vec<String> = ["a.png", "b.png", "c.png", "gone.png"].iter().map(|n| dir.join(n).to_string_lossy().to_string()).collect();
let (input, _) = crate::import::ScanInput::new(&mut s, &[]);
let names = |v: Vec<String>| v.iter().map(|f| Path::new(f).file_name().unwrap().to_string_lossy().to_string()).collect::<Vec<_>>();
// newest first, the file already in the library left out, an unreadable one last
let q = crate::import::browse_queue(&input, files.clone(), &Sort::default());
assert_eq!(names(q), ["a.png", "c.png", "gone.png"]);
let q = crate::import::browse_queue(&input, files.clone(), &Sort { ascending: true, ..Sort::default() });
assert_eq!(names(q), ["c.png", "a.png", "gone.png"]);
let q = crate::import::browse_queue(&input, files.clone(), &Sort { key: SortKey::FileName, ascending: false, ..Sort::default() });
assert_eq!(names(q), ["gone.png", "c.png", "a.png"]);
// by size an unreadable file is last in both directions (it was sized 0, first when ascending)
for ascending in [true, false] {
let q = crate::import::browse_queue(&input, files.clone(), &Sort { key: SortKey::FileSize, ascending, ..Sort::default() });
assert_eq!(names(q).last().map(String::as_str), Some("gone.png"), "ascending {ascending}");
}
let q = crate::import::browse_queue(&input, files, &Sort { key: SortKey::Rating, ..Sort::default() });
assert_eq!(names(q), ["gone.png", "c.png", "a.png"], "new photos tie on rating: by name, descending as the view");
let _ = std::fs::remove_dir_all(&dir);
}
/// Choosing another folder while a browse orders its files (`cancel` set) stops the ordering: no queue comes
/// back, and nothing more is read (CodeRabbit on #3055). Browsing hands back the probes of earlier scans it took.
#[test]
fn a_cancelled_browse_stops_ordering_and_keeps_earlier_probes() {
use lightcraft_catalog::{Sort, SortKey};
use std::sync::atomic::AtomicBool;
let dir = temp_dir("browse-cancel");
write_png(&dir.join("a.png"), 1);
write_png(&dir.join("b.png"), 2);
let files: Vec<String> = ["a.png", "b.png"].iter().map(|n| dir.join(n).to_string_lossy().to_string()).collect();
let mut s = Session::new().with_fs();
s.import_probes.insert(files[0].clone(), crate::media::ProbeInfo { file_size: 1, ..Default::default() });
let (mut input, _) = crate::import::ScanInput::new(&mut s, &[]);
for key in [SortKey::CaptureDate, SortKey::FileSize, SortKey::FileName, SortKey::Random] {
let sort = Sort { key, ..Sort::default() };
assert_eq!(crate::import::browse_queue_until(&input, files.clone(), &sort, &AtomicBool::new(true)), None, "{key:?}");
assert_eq!(crate::import::browse_queue_until(&input, files.clone(), &sort, &AtomicBool::new(false)).map(|q| q.len()), Some(2), "{key:?}");
}
let probes = input.take_probes();
assert!(probes.contains_key(&files[0]), "the earlier scan's probe comes back");
let _ = std::fs::remove_dir_all(&dir);
}
/// Browsing a folder with its subfolders lists nothing inside the library's own folder (the
/// import that follows would read it as photos), as the import's scan skips it.
#[test]
fn browsing_with_subfolders_skips_the_librarys_own_folder() {
let dir = temp_dir("browse-skip-lib");
std::fs::create_dir_all(dir.join("lib")).unwrap();
let mut s = Session::new().with_fs();
s.open_library(dir.join("lib"), false).unwrap();
write_png(&dir.join("a.png"), 1);
write_png(&dir.join("lib").join("inside.png"), 2);
let (input, _) = crate::import::ScanInput::new(&mut s, &[]);
let root = dir.to_string_lossy().to_string();
let names = |v: Vec<String>| v.iter().map(|f| Path::new(f).file_name().unwrap().to_string_lossy().to_string()).collect::<Vec<_>>();
assert_eq!(names(crate::import::browse_files(&input, &root, true).unwrap()), ["a.png"]);
assert_eq!(names(crate::import::browse_files(&input, &root, false).unwrap()), ["a.png"]);
// the library's folder chosen itself, with or without its subfolders
let lib = dir.join("lib").to_string_lossy().to_string();
assert!(crate::import::browse_files(&input, &lib, false).unwrap().is_empty());
assert!(crate::import::browse_files(&input, &lib, true).unwrap().is_empty());
// the library's folder by another name: through `..`, or a symlink to it
std::fs::create_dir_all(dir.join("other")).unwrap();
let around = dir.join("other").join("..").join("lib").to_string_lossy().to_string();
assert!(crate::import::browse_files(&input, &around, false).unwrap().is_empty(), "{around}");
assert!(crate::import::browse_files(&input, &around, true).unwrap().is_empty(), "{around}");
#[cfg(unix)]
{
let alias = dir.join("alias");
std::os::unix::fs::symlink(dir.join("lib"), &alias).unwrap();
let alias = alias.to_string_lossy().to_string();
assert!(crate::import::browse_files(&input, &alias, false).unwrap().is_empty(), "{alias}");
assert!(crate::import::browse_files(&input, &alias, true).unwrap().is_empty(), "{alias}");
}
// a folder next to the library named through it is outside it: browsed (CodeRabbit on #3077)
std::fs::create_dir_all(dir.join("outside")).unwrap();
write_png(&dir.join("outside").join("next.png"), 3);
let next = dir.join("lib").join("..").join("outside").to_string_lossy().to_string();
assert_eq!(names(crate::import::browse_files(&input, &next, false).unwrap()), ["next.png"], "{next}");
assert_eq!(names(crate::import::browse_files(&input, &next, true).unwrap()), ["next.png"], "{next}");
// under the folder's one spelling: the paths match the folder's own, so the catalog's records are found
// (CodeRabbit on #3055)
let direct = dir.join("outside").to_string_lossy().to_string();
for sub in [false, true] {
assert_eq!(crate::import::browse_files(&input, &next, sub).unwrap(), crate::import::browse_files(&input, &direct, sub).unwrap());
}
// a folder inside the library that isn't there is an error too, not an empty folder
let gone = dir.join("lib").join("not-there").to_string_lossy().to_string();
assert!(crate::import::browse_files(&input, &gone, false).is_err(), "{gone}");
// a folder that can't be listed is an error, not an empty folder (its photos aren't "gone")
let missing = dir.join("not-there").to_string_lossy().to_string();
assert!(crate::import::browse_files(&input, &missing, false).is_err());
assert!(crate::import::browse_files(&input, &missing, true).is_err());
let _ = std::fs::remove_dir_all(&dir);
}
/// Browsing's queue breaks ties the way the catalog does (by name, in the view's direction), and
/// the import- and edit-date sorts, where new photos tie, go by name rather than file time.
#[test]
fn browsing_breaks_ties_by_name_in_the_views_direction() {
use lightcraft_catalog::{Sort, SortKey};
let dir = temp_dir("browse-ties");
// names and file times run in opposite directions; x and y share a time and a size
for (name, secs) in [("x.png", 100u64), ("y.png", 100), ("z.png", 50)] {
write_png(&dir.join(name), 7);
let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000 + secs);
std::fs::File::options().write(true).open(dir.join(name)).unwrap().set_modified(t).unwrap();
}
let files: Vec<String> = ["y.png", "z.png", "x.png"].iter().map(|n| dir.join(n).to_string_lossy().to_string()).collect();
let order = |key: SortKey, ascending: bool| {
let mut f = files.clone();
crate::import::browse_order(&mut f, &Sort { key, ascending, ..Sort::default() });
f.iter().map(|f| Path::new(f).file_name().unwrap().to_string_lossy().to_string()).collect::<Vec<_>>()
};
assert_eq!(order(SortKey::CaptureDate, false), ["y.png", "x.png", "z.png"]);
assert_eq!(order(SortKey::CaptureDate, true), ["z.png", "x.png", "y.png"]);
for key in [SortKey::ImportDate, SortKey::EditDate, SortKey::Rating] {
assert_eq!(order(key, true), ["x.png", "y.png", "z.png"], "{key:?}");
assert_eq!(order(key, false), ["z.png", "y.png", "x.png"], "{key:?}");
}
assert_eq!(order(SortKey::FileSize, true), ["x.png", "y.png", "z.png"]);
assert_eq!(order(SortKey::FileSize, false), ["z.png", "y.png", "x.png"]);
let _ = std::fs::remove_dir_all(&dir);
}
/// Photos a.png, b.png, c.png imported from `old`, then: a renamed into `moved`; b renamed, with
/// an impostor (same name and size, other bytes) under its old name; c gone, with two impostors.
fn renamed_and_ambiguous_scene(tag: &str) -> (std::path::PathBuf, Session) {
@@ -2851,3 +2994,69 @@ fn heic_exif_orientation_does_not_rotate_the_picture_twice() {
}
}
}
/// A folder's one spelling: `.` is the current folder, `.` and `..` are taken out, never above the
/// root (CodeRabbit on #3055 / #3080).
#[test]
fn a_browsed_folder_has_one_spelling() {
use crate::import::browse_path;
let root = std::env::temp_dir();
assert_eq!(browse_path(&root.join("lib").join("..").join("outside")).unwrap(), root.join("outside"));
assert_eq!(browse_path(&root.join(".").join("a").join(".").join("b")).unwrap(), root.join("a").join("b"));
let top: PathBuf = root.ancestors().last().map(Path::to_path_buf).unwrap_or_default();
assert_eq!(browse_path(&top.join("..").join("x")).unwrap(), top.join("x"), "never above the root");
assert_eq!(browse_path(Path::new(".")).unwrap(), std::env::current_dir().unwrap(), "`.` is the current folder");
assert_eq!(browse_path(Path::new("a/..")).unwrap(), std::env::current_dir().unwrap());
// the UI's spelling, without the disk: the same where no link comes before a `..`
let by_name = crate::import::browse_spelling(&root.join("lib").join("..").join("outside")).unwrap();
assert_eq!(by_name, root.join("outside"));
assert_eq!(crate::import::browse_spelling(Path::new(".")).unwrap(), std::env::current_dir().unwrap());
}
/// `link/..` is the folder the system reads (POSIX: above where the link points; Windows: the
/// folder holding the link): browsing it lists what the system lists there (CodeRabbit on #3055 /
/// #3077 / #3080).
#[test]
fn a_link_before_dotdot_names_the_folder_the_system_reads() {
let dir = temp_dir("browse-link-dotdot");
std::fs::create_dir_all(dir.join("real").join("sub")).unwrap();
write_png(&dir.join("real").join("in-real.png"), 1);
write_png(&dir.join("beside-link.png"), 2);
let link = dir.join("link");
#[cfg(unix)]
let made = std::os::unix::fs::symlink(dir.join("real").join("sub"), &link);
#[cfg(windows)]
let made = std::os::windows::fs::symlink_dir(dir.join("real").join("sub"), &link);
if let Err(e) = made {
lightcraft_testkit::skip!(System, "can't make a folder link here: {e}");
let _ = std::fs::remove_dir_all(&dir);
return;
}
let mut s = Session::new().with_fs();
let (input, _) = crate::import::ScanInput::new(&mut s, &[]);
let through = link.join("..");
let names = |v: Vec<String>| v.iter().map(|f| Path::new(f).file_name().unwrap().to_string_lossy().to_string()).collect::<Vec<_>>();
let listed = names(crate::import::browse_files(&input, &through.to_string_lossy(), false).unwrap());
let mut system: Vec<String> =
std::fs::read_dir(&through).unwrap().flatten().map(|e| e.file_name().to_string_lossy().to_string()).filter(|n| n.ends_with(".png")).collect();
system.sort();
assert_eq!(listed, system, "{}", through.display());
#[cfg(unix)]
assert_eq!(listed, ["in-real.png"]);
let _ = std::fs::remove_dir_all(&dir);
}
/// A broken link before `..` is an error, not the link's own folder by name: the system can't read
/// `broken/..` either (CodeRabbit on #3577).
#[cfg(unix)]
#[test]
fn a_broken_link_before_dotdot_is_an_error() {
let dir = temp_dir("browse-broken-link-dotdot");
std::fs::create_dir_all(&dir).unwrap();
let link = dir.join("broken");
std::os::unix::fs::symlink(dir.join("nowhere"), &link).unwrap();
assert!(crate::import::browse_path(&link.join("..")).is_err());
// without reading the disk the spelling is still the folder by name
assert_eq!(crate::import::browse_spelling(&link.join("..")).unwrap(), dir);
let _ = std::fs::remove_dir_all(&dir);
}
+1 -1
View File
@@ -237,7 +237,7 @@ fn a_new_database_profile_changes_the_render_and_cache_keys() {
let render = s.render_job(id, 800, 600, false, true).unwrap().key;
let thumb = s.thumb_job(id, 256).unwrap().cache.unwrap().1;
let p = s.catalog.photo(id).unwrap().clone();
(render, thumb, Session::variant_key(&p, &p.develop, 128, 0), Session::view_key(&p, true, 0))
(render, thumb, Session::variant_key(&p, &p.develop, 128, 0), s.view_key(&p, true))
};
let before = keys(&mut s);
s.catalog.apply(Op::SetEmbeddedLens { id, lens: Some(Box::new(lens(-0.03))) }).unwrap();
+635
View File
@@ -0,0 +1,635 @@
//! Previews are made once and used (notes 47–49): the loupe shows a built or prepared preview
//! instead of rendering the photo again, a build skips photos whose previews are there, built
//! previews are on disk when the build says it is done, the import's queue shows one row, and the
//! background preparation follows the user and gives way to a build that was asked for.
use std::path::{Path, PathBuf};
use std::sync::atomic::Ordering;
use lightcraft_catalog::PhotoId;
use serde_json::json;
use crate::Session;
use crate::media::QuickSource;
fn temp_dir(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("lc-preview-prep-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
fn png(p: &Path, seed: u8) {
let img = lightcraft_raster::Rgba8::from_fn(600, 400, |x, y| [(x % 251) as u8, (y % 241) as u8, seed, 255]);
let b =
crate::export::encode_image(&img, &crate::export::ExportOptions { format: crate::export::ExportFormat::Png, ..Default::default() }).unwrap();
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, b).unwrap();
}
/// A library on disk with `n` photos (600 × 400 PNGs) imported, in name order.
fn library(tag: &str, n: usize) -> (Session, PathBuf, Vec<PhotoId>) {
let root = temp_dir(tag);
let paths: Vec<String> = (0..n)
.map(|i| {
let p = root.join("shoot").join(format!("p{i:02}.png"));
png(&p, (i * 20) as u8);
p.to_string_lossy().to_string()
})
.collect();
let mut s = Session::new().with_fs();
s.open_library(root.join("lib"), false).unwrap();
s.execute("library.import", &json!({"paths": paths})).unwrap();
let mut ids: Vec<(String, PhotoId)> = s.catalog.photos().map(|p| (p.file_name.clone(), p.id)).collect();
ids.sort();
(s, root, ids.into_iter().map(|(_, id)| id).collect())
}
fn ids_json(ids: &[PhotoId]) -> Vec<u64> {
ids.iter().map(|i| i.0).collect()
}
/// FredApps on #3077: building previews (asked for, and the background preparation while culling)
/// writes only into the library's own cache, never next to the photos: the shoot folder holds the
/// same files afterwards, byte for byte.
#[test]
fn building_previews_writes_nothing_next_to_the_photos() {
let (mut s, root, ids) = library("prep-beside", 4);
let shoot = root.join("shoot");
let listing = |dir: &std::path::Path| {
let mut v: Vec<(String, Vec<u8>)> = std::fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().path())
.map(|p| (p.file_name().unwrap().to_string_lossy().to_string(), std::fs::read(&p).unwrap()))
.collect();
v.sort();
v
};
let before = listing(&shoot);
assert_eq!(before.len(), 4);
let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap();
assert_eq!(r["done"], 4, "{r}");
for id in &ids {
s.prep_tick(crate::prep::Mode::Library, Some(*id), false);
}
if let Some(b) = s.preview_build.clone() {
assert!(wait_finished(&b), "the background build stops (a late write would slip past the check)");
}
assert_eq!(listing(&shoot), before, "nothing was written next to the photos");
let _ = std::fs::remove_dir_all(&root);
}
/// Note 47: a built preview at least as big as the loupe's size is what the loupe shows (fitted
/// down, no render); a smaller one is not (the photo renders).
#[test]
fn the_loupe_uses_a_built_preview_that_is_big_enough() {
let mut s = Session::with_demo();
let id = s.active().unwrap();
s.execute("library.buildPreviews", &json!({"ids": [id.0], "edge": 512, "wait": true})).unwrap();
let r = s.loupe_job(id, 300, 300, true).unwrap().run();
assert_eq!(r.quick, Some(QuickSource::Cached), "taken from the built preview");
let img = r.rendered.unwrap().image;
assert_eq!(img.width.max(img.height), 300, "fitted to the loupe's size");
// bigger than what was built: rendered
let r = s.loupe_job(id, 900, 900, true).unwrap().run();
assert_eq!(r.quick, None, "a preview too small for the loupe is not used");
assert!(r.rendered.is_ok());
// a draft (a slider held) never comes from the cache
let r = s.loupe_job(id, 300, 300, true).unwrap().draft().run();
assert_eq!(r.quick, None);
}
/// Shrinking a cached view keeps its colour (an average of the pixels it covers) and its aspect,
/// and refuses to enlarge.
#[test]
fn a_cached_view_is_fitted_down_never_up() {
let img = lightcraft_raster::Rgba8::from_fn(400, 200, |x, _| if x % 2 == 0 { [200, 100, 0, 255] } else { [100, 50, 0, 255] });
let f = crate::media::fit_cached(&img, 100, 100).unwrap();
assert_eq!((f.width, f.height), (100, 50));
assert!(f.data.iter().all(|p| p[0] == 150 && p[1] == 75), "averaged");
assert!(crate::media::fit_cached(&img, 800, 800).is_none(), "never enlarged");
assert_eq!(crate::media::fit_cached(&img, 401, 999).map(|f| f.width), Some(400), "a pixel short is the same size");
assert!(crate::media::fit_cached(&img, 0, 10).is_none());
}
/// Note 47: the rendered previews in memory follow the memory budget (they were capped at
/// 128 MB, about 84 loupe renders, whatever the budget).
#[test]
fn the_memory_for_rendered_previews_grows_with_the_budget() {
let share = crate::memory::cache_share(20 << 30);
assert!(crate::media::rendered_budget(share) >= 2 << 30, "a 20 GB budget keeps gigabytes of previews");
assert_eq!(crate::media::rendered_budget(256 << 20), 128 << 20, "a small budget keeps the old floor where it can");
assert!(crate::media::rendered_budget(64 << 20) <= 32 << 20, "and never more than the share allows");
}
/// Note 47: the disk cache's default room grows with the library, so a wedding's previews are not
/// pruned while they are built (the fixed 2 GB held about 2 000 standard previews).
#[test]
fn the_disk_cache_default_grows_with_the_library() {
assert_eq!(crate::media::default_disk_cache_bytes(10), crate::media::DISK_CACHE_BYTES);
assert!(crate::media::default_disk_cache_bytes(4000) >= 4000 * (1 << 20));
let (mut s, root, ids) = library("diskroom", 2);
assert_eq!(s.cache_bytes(), crate::media::DISK_CACHE_BYTES);
s.cache_mb = 700;
assert_eq!(s.cache_bytes(), 700 << 20, "a size the user chose is kept");
assert_eq!(ids.len(), 2);
let _ = std::fs::remove_dir_all(root);
}
/// Notes 47 and 49: a build skips photos whose previews are there (built before, or by the loupe),
/// renders those whose preview is too small, and its previews are on disk when it is done (they
/// were left to a writer that skips writes when it falls behind).
#[test]
fn a_build_skips_what_is_there_and_leaves_it_on_disk() {
let (mut s, root, ids) = library("skip", 4);
let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap();
assert_eq!((r["done"].as_u64(), r["skipped"].as_u64(), r["failed"].as_u64()), (Some(4), Some(0), Some(0)), "{r}");
// on disk now (no waiting for a writer), at the size built
for id in &ids {
let p = s.catalog.photo(*id).unwrap().clone();
let key = s.view_key(&p, true);
let disk = s.media.rendered.disk().expect("a library has a disk cache");
let (w, h) = disk.dims(key).expect("the view preview is on disk");
assert_eq!(w.max(h), 300);
}
// again: nothing is rendered
let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap();
assert_eq!((r["done"].as_u64(), r["skipped"].as_u64()), (Some(4), Some(4)), "{r}");
// forced, or bigger: rendered
let r = s.execute("library.buildPreviews", &json!({"ids": [ids[0].0], "edge": 300, "wait": true, "force": true})).unwrap();
assert_eq!(r["skipped"], 0, "{r}");
let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 500, "wait": true})).unwrap();
assert_eq!(r["skipped"], 0, "too small for what is asked: built again {r}");
// a library opened again finds them on disk (memory is empty)
drop(s);
let mut s = Session::new().with_fs();
s.open_library(root.join("lib"), false).unwrap();
let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 500, "wait": true})).unwrap();
assert_eq!(r["skipped"], 4, "{r}");
let r = s.loupe_job(ids[1], 400, 400, true).unwrap().run();
assert_eq!(r.quick, Some(QuickSource::Cached), "the loupe uses the preview built in the last session");
let _ = std::fs::remove_dir_all(root);
}
/// A forced build renders the grid thumbnail again too, not the one its cache holds (CodeRabbit on #3577:
/// the thumbnail job read its cache first, so `force` rebuilt only the view).
#[test]
fn a_forced_build_renders_the_thumbnail_again() {
let (mut s, root, ids) = library("force-thumb", 1);
let build = |s: &mut Session, force: bool| {
s.execute("library.buildPreviews", &json!({"ids": [ids[0].0], "edge": 300, "wait": true, "force": force})).unwrap()
};
build(&mut s, false);
let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300));
let thumb = jobs.iter().find(|j| j.view_cache.is_none() && j.cache.is_some()).expect("a thumbnail job");
let ((cache, key), generation) = (thumb.cache.clone().unwrap(), thumb.cache_generation);
let stand_in = lightcraft_raster::Rgba8 { width: 1, height: 1, data: vec![[1, 2, 3, 255]] };
assert!(cache.put_at(generation, key, std::sync::Arc::new(stand_in)));
let r = build(&mut s, false);
assert_eq!(r["skipped"], 1, "{r}");
assert_eq!(cache.get_at(generation, key).map(|i| i.width), Some(1), "unforced: kept");
let r = build(&mut s, true);
assert_eq!(r["failed"], 0, "{r}");
assert!(cache.get_at(generation, key).is_some_and(|i| i.width > 1), "forced: rendered again");
let _ = std::fs::remove_dir_all(root);
}
/// Note 47: standard previews are built at least as big as the loupe on this screen asks for.
#[test]
fn standard_previews_are_as_big_as_the_loupe() {
let mut s = Session::with_demo();
assert_eq!(crate::cmd::previews::standard_edge(&s), crate::cmd::previews::STANDARD_EDGE);
s.loupe_edge = 3000;
assert_eq!(crate::cmd::previews::standard_edge(&s), 3000);
s.loupe_edge = 1200;
assert_eq!(crate::cmd::previews::standard_edge(&s), crate::cmd::previews::STANDARD_EDGE);
}
/// Note 48: a background build goes from where the user is, in the direction they step, and
/// follows them when they jump.
#[test]
fn the_background_build_starts_where_the_user_is() {
use crate::cmd::previews::PreviewBuild;
let b = PreviewBuild { order: (10..20).collect(), ..Default::default() };
let mut queue: Vec<Option<u64>> = (10..20).map(Some).collect();
b.focus_on(PhotoId(14), false);
let mut took = Vec::new();
for _ in 0..3 {
let i = b.next_index(&queue).unwrap();
took.push(queue[i].take().unwrap());
}
assert_eq!(took, vec![14, 15, 16], "forward from the photo on screen");
b.focus_on(PhotoId(12), true);
let i = b.next_index(&queue).unwrap();
assert_eq!(queue[i], Some(12), "jumped back: from there, backwards");
queue[i] = None;
assert_eq!(b.next_index(&queue).map(|i| queue[i]), Some(Some(11)));
// the end reached: the rest the other way
b.focus_on(PhotoId(19), false);
for _ in 0..6 {
let i = b.next_index(&queue).unwrap();
queue[i] = None;
}
assert!(b.next_index(&queue).is_none(), "all taken");
}
/// Note 49: the background preparation gives way to a build that is asked for (no error, no
/// two builds), and is not started again for a view the user stopped it in.
#[test]
fn a_build_asked_for_replaces_the_background_one() {
let (mut s, root, ids) = library("replace", 3);
// held back: the photo on screen is being made all along (held until released below, not for a
// deadline a slow test machine could pass before the build asked for comes)
let hold = crate::prep::TestHold::new();
s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "background": true})).unwrap();
let bg = s.preview_build.clone().unwrap();
assert!(bg.background && bg.running());
assert!(s.activity.list().iter().any(|t| t.label == "Preparing photos in the background"), "{:?}", s.activity.list());
// a second background build is refused; one that is asked for replaces it
assert!(s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "background": true})).is_err());
let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap();
assert_eq!(r["done"], 3, "{r}");
assert!(bg.cancel.load(Ordering::Relaxed), "the background build was stopped");
drop(hold);
// its workers stop before their library is removed under them
assert!(wait_finished(&bg), "a cancelled build stops");
drop(s);
std::fs::remove_dir_all(&root).unwrap();
}
/// Note 48: the background preparation starts once the user steps through photos in the loupe
/// (not when a library opens), builds the view's previews in one cancellable row, and a stop
/// from that row holds for the view.
#[test]
fn the_background_preparation_starts_when_culling_and_can_be_stopped() {
let (mut s, root, ids) = library("prep", 4);
let mode = crate::prep::Mode::Library;
s.prep_tick(mode, None, false);
s.prep_tick(mode, Some(ids[0]), false);
assert!(s.preview_build.is_none(), "opening and looking at one photo starts nothing");
s.prep_tick(mode, Some(ids[1]), false);
s.prep_tick(mode, Some(ids[2]), false);
let b = s.preview_build.clone().expect("culling: the view is prepared");
assert!(b.background);
assert_eq!(b.total, 4);
for _ in 0..600 {
s.prep_tick(mode, Some(ids[2]), false);
if !b.running() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert!(!b.running(), "built");
assert_eq!(b.done.load(Ordering::Relaxed), 4);
s.prep_tick(mode, Some(ids[3]), false);
assert!(same_build(&s, &b), "not started again for the same view");
// switched off: nothing starts in a new view either
s.execute("prefs.setBackgroundPrep", &json!({"settings": {"library": {"previews": false}}})).unwrap();
let off = s.execute("prefs.backgroundPrep", &json!({})).unwrap();
assert_eq!(off["settings"]["library"]["previews"], false, "{off}");
assert_eq!(off["settings"]["culling"]["previews"], true, "each mode has its own");
let _ = std::fs::remove_dir_all(root);
}
/// While editing, the whole view's build follows the Library row (its switch and "which photos");
/// the Editing row's scope is only for the photos kept ready ahead.
#[test]
fn editing_builds_the_view_by_the_library_rows_scope() {
let (mut s, root, ids) = library("prep-develop", 4);
s.execute("prefs.setBackgroundPrep", &json!({"settings": {"develop": {"scope": "onScreen"}, "library": {"scope": "marked"}}})).unwrap();
s.execute("photo.rate", &json!({"ids": [ids[1].0], "rating": 3})).unwrap();
let mode = crate::prep::Mode::Develop;
for id in &ids {
s.prep_tick(mode, Some(*id), false);
}
let b = s.preview_build.clone().expect("the Library row asks for the view while editing");
assert_eq!(b.total, 1, "only the marked photos, as the Library row says");
b.cancel.store(true, Ordering::Relaxed);
// its workers stop before their library is removed under them
assert!(wait_finished(&b), "a cancelled build stops");
drop(s);
std::fs::remove_dir_all(&root).unwrap();
}
/// With "which photos" = marked, marking another photo changes what the view's build prepares: a
/// build for the newly marked set follows (it wasn't, as the view itself stayed the same).
#[test]
fn marking_a_photo_prepares_it_in_the_marked_scope() {
let (mut s, root, ids) = library("prep-marked", 4);
s.execute("prefs.setBackgroundPrep", &json!({"settings": {"library": {"scope": "marked"}}})).unwrap();
s.execute("photo.rate", &json!({"ids": [ids[1].0], "rating": 3})).unwrap();
let mode = crate::prep::Mode::Library;
let tick = |s: &mut Session, k: usize| s.prep_tick(mode, Some(ids[k % 3]), false);
for k in 0..3 {
tick(&mut s, k);
}
let first = s.preview_build.clone().expect("the marked photos are prepared");
assert_eq!(first.total, 1);
s.execute("photo.rate", &json!({"ids": [ids[3].0], "rating": 2})).unwrap();
let mut next = None;
for k in 0..600 {
tick(&mut s, k);
if let Some(b) = s.preview_build.clone().filter(|b| !std::sync::Arc::ptr_eq(b, &first)) {
next = Some(b);
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
let next = next.expect("a build for the newly marked set");
assert_eq!(next.total, 2);
next.cancel.store(true, Ordering::Relaxed);
// both builds' workers stop before their library is removed under them
for b in [&first, &next] {
assert!(wait_finished(b), "a cancelled build stops");
}
drop(s);
std::fs::remove_dir_all(&root).unwrap();
}
/// Waits (up to 30 s) for a build's workers to finish.
fn wait_finished(b: &crate::cmd::previews::PreviewBuild) -> bool {
for _ in 0..1500 {
if b.finished.load(Ordering::Relaxed) {
return true;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
false
}
/// A background build started for one view is stopped when another view is shown (here the
/// library changes under it), not left building photos no longer shown; it doesn't count as
/// stopped by the user, so the view now shown is prepared.
#[test]
fn a_view_change_stops_the_background_build_for_the_old_view() {
let (mut s, root, ids) = library("prep-view", 6);
let mode = crate::prep::Mode::Library;
// the build's lanes wait at their foreground check until released below
let hold = crate::prep::TestHold::new();
for id in &ids[..3] {
s.prep_tick(mode, Some(*id), false);
}
let b = s.preview_build.clone().expect("the view is prepared");
assert!(b.running());
s.catalog.apply(lightcraft_catalog::Op::RemovePhoto { id: ids[5] }).unwrap();
s.prep_tick(mode, Some(ids[2]), false);
let stopped = b.cancel.load(Ordering::Relaxed);
drop(hold);
assert!(stopped, "the old view's build is stopped");
// the user steps on in the view now shown
for k in 0..600 {
s.prep_tick(mode, Some(ids[k % 3]), false);
if s.preview_build.as_ref().is_some_and(|p| !std::sync::Arc::ptr_eq(p, &b)) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
let next = s.preview_build.clone().expect("a build for the view now shown");
assert!(!std::sync::Arc::ptr_eq(&next, &b));
assert_eq!(next.total, 5);
next.cancel.store(true, Ordering::Relaxed);
// both builds' workers stop before their library is removed under them
for b in [&b, &next] {
assert!(wait_finished(b), "a cancelled build stops");
}
drop(s);
std::fs::remove_dir_all(&root).unwrap();
}
fn same_build(s: &Session, b: &std::sync::Arc<crate::cmd::previews::PreviewBuild>) -> bool {
s.preview_build.as_ref().is_some_and(|p| std::sync::Arc::ptr_eq(p, b))
}
/// Note 48: a library keeps its own background settings (a timelapse library prepares nothing),
/// saved with it; the app-wide ones apply elsewhere.
#[test]
fn a_library_can_keep_its_own_background_settings() {
let (mut s, root, _ids) = library("own", 1);
let r = s.execute("prefs.setBackgroundPrep", &json!({"library": true, "settings": {"culling": {"previews": false, "ahead": 0}}})).unwrap();
assert_eq!(r["own"], true, "{r}");
assert_eq!(r["settings"]["culling"]["ahead"], 0);
assert_eq!(r["app"]["culling"]["ahead"], 5, "the app-wide ones are unchanged");
drop(s);
let mut s = Session::new().with_fs();
s.open_library(root.join("lib"), false).unwrap();
assert_eq!(s.prep_settings().culling.ahead, 0, "kept with the library");
assert_eq!(s.prep_settings().ahead(crate::prep::Mode::Culling), 0);
s.execute("prefs.setBackgroundPrep", &json!({"reset": true})).unwrap();
assert_eq!(s.prep_settings().culling.ahead, 5, "back to the app-wide settings");
assert!(s.execute("prefs.setBackgroundPrep", &json!({"settings": 3})).is_err());
let _ = std::fs::remove_dir_all(root);
}
/// Note 47: Build Previews with one photo open (selected) builds every photo in view, as its menu
/// item says ("Visible"); it built only the open photo, so culling after it found nothing built.
#[test]
fn build_previews_with_one_photo_open_builds_the_view() {
let mut s = Session::with_demo();
let n = s.visible_cloned().len();
assert!(n > 2);
let one = s.visible_cloned()[0];
s.selection = crate::Selection::single(one);
let r = s.execute("library.buildPreviews", &json!({"edge": 256, "wait": true})).unwrap();
assert_eq!(r["total"], n, "{r}");
let two: Vec<PhotoId> = s.visible_cloned().into_iter().take(2).collect();
s.selection = crate::Selection { ids: two.clone(), active: two.first().copied() };
let r = s.execute("library.buildPreviews", &json!({"edge": 256, "wait": true})).unwrap();
assert_eq!(r["total"], 2, "a choice of photos is built alone {r}");
}
/// A view the loupe kept only in memory (its deferred disk write skipped when the writer fell behind) is not
/// counted as built: the build renders it and writes it to disk (CodeRabbit on #3077).
#[test]
fn a_preview_kept_only_in_memory_is_built_and_written() {
let (mut s, root, ids) = library("memonly", 1);
let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300));
assert!(!jobs.is_empty());
for j in &jobs {
let img = std::sync::Arc::new(lightcraft_raster::Rgba8::new(300, 200));
if let Some((cache, key)) = &j.view_cache {
cache.put_memory(*key, img);
} else if let Some((cache, key)) = &j.cache {
cache.put_memory(*key, img);
}
}
assert!(!crate::cmd::previews::already_built(&jobs), "a copy only in memory is not a built preview");
let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap();
assert_eq!((r["skipped"].as_u64(), r["failed"].as_u64()), (Some(0), Some(0)), "{r}");
let p = s.catalog.photo(ids[0]).unwrap().clone();
let key = s.view_key(&p, true);
assert!(s.media.rendered.disk().and_then(|d| d.dims(key)).is_some(), "the view preview is on disk");
let _ = std::fs::remove_dir_all(root);
}
/// A view preview the cache folder can't take (full, or not writable) fails the photo instead of counting it
/// as built (CodeRabbit on #3077).
#[test]
fn a_preview_that_cannot_be_written_fails_the_build() {
let (mut s, root, ids) = library("unwritable", 2);
let dir = s.media.rendered.disk().expect("a library has a disk cache").dir().to_path_buf();
let _ = std::fs::remove_dir_all(&dir);
// a file where the cache folder goes: nothing can be written under it
std::fs::write(&dir, b"not a folder").unwrap();
let r = s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap();
assert_eq!(r["failed"].as_u64(), Some(2), "{r}");
let _ = std::fs::remove_file(&dir);
let _ = std::fs::remove_dir_all(root);
}
/// A photo whose preview cache is discarded while it renders is not counted as built: its preview isn't kept
/// (CodeRabbit on #3077).
#[test]
fn a_preview_rendered_for_a_discarded_cache_fails_the_photo() {
let (mut s, root, ids) = library("discarded", 1);
let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300));
s.execute("library.clearPreviews", &json!({})).unwrap();
assert!(!crate::cmd::previews::run_photo(jobs), "nothing was kept: the photo is not built");
let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300));
assert!(crate::cmd::previews::run_photo(jobs), "built for the cache as it is now");
let _ = std::fs::remove_dir_all(root);
}
/// A forced build renders a photo itself even when another build was rendering it and made its previews
/// (CodeRabbit on #3080): the other build's result is not taken as this one's.
#[test]
fn a_forced_build_renders_a_photo_another_build_was_rendering() {
let (mut s, root, ids) = library("forced-shared", 1);
s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "wait": true})).unwrap();
let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300));
let held = crate::cmd::previews::hold_building(ids[0].0, &jobs).expect("nobody renders it now");
s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300, "force": true})).unwrap();
let b = s.preview_build.clone().expect("the build");
std::thread::sleep(std::time::Duration::from_millis(300));
assert_eq!(b.done.load(Ordering::Relaxed), 0, "not counted while the other build holds it");
drop(held);
assert!(wait_finished(&b));
let counts =
(b.done.load(Ordering::Relaxed), b.failed.load(Ordering::Relaxed), b.shared.load(Ordering::Relaxed), b.skipped.load(Ordering::Relaxed));
assert_eq!(counts, (1, 0, 0, 0), "rendered here, not taken from the other build");
let _ = std::fs::remove_dir_all(root);
}
/// A photo another build is rendering is not counted until that render is over: here the other build never
/// made its previews, so this build renders it (CodeRabbit on #3080).
#[test]
fn a_photo_another_build_is_rendering_is_counted_only_once_it_is_built() {
let (mut s, root, ids) = library("shared", 1);
let jobs = crate::cmd::previews::jobs_for(&mut s, ids[0], Some(300));
let held = crate::cmd::previews::hold_building(ids[0].0, &jobs).expect("nobody renders it yet");
s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "edge": 300})).unwrap();
let b = s.preview_build.clone().expect("the build");
std::thread::sleep(std::time::Duration::from_millis(300));
assert_eq!(b.done.load(Ordering::Relaxed), 0, "not counted while the other build holds it");
drop(held);
assert!(wait_finished(&b));
assert_eq!((b.done.load(Ordering::Relaxed), b.failed.load(Ordering::Relaxed), b.shared.load(Ordering::Relaxed)), (1, 0, 0));
let p = s.catalog.photo(ids[0]).unwrap().clone();
let key = s.view_key(&p, true);
assert!(s.media.rendered.disk().and_then(|d| d.dims(key)).is_some(), "rendered here, on disk");
let _ = std::fs::remove_dir_all(root);
}
/// CodeRabbit on #3544: a library preparation setting that can't be saved is not kept, nor is
/// going back to the app-wide settings: the session stays as the command's error says.
#[test]
fn a_prep_setting_that_cant_be_saved_is_not_kept() {
use crate::prep::PrepSettings;
let (mut s, root, _) = library("prep-unsaved", 1);
let mut own = PrepSettings::default();
own.culling.ahead = 3;
s.set_prep_settings(own, true).unwrap();
// prefs.json can't be written: a folder stands in its place
let prefs = root.join("lib").join("prefs.json");
let _ = std::fs::remove_file(&prefs);
std::fs::create_dir_all(prefs.join("in-the-way")).unwrap();
let mut other = own;
other.culling.ahead = 5;
assert!(s.set_prep_settings(other, true).is_err());
assert_eq!(s.prep_json()["library"], json!(own), "the setting that couldn't be saved is not kept");
assert!(s.clear_library_prep().is_err());
assert_eq!(s.prep_json()["library"], json!(own), "nor going back to the app-wide settings");
let _ = std::fs::remove_dir_all(&root);
}
/// CodeRabbit on #3544: a build asked for with malformed ids fails without stopping the
/// background preparation that is running.
#[test]
fn a_bad_build_request_leaves_the_background_build_running() {
let _hold = crate::prep::TestHold::new();
let (mut s, root, ids) = library("prep-bad-ids", 3);
s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "background": true})).unwrap();
let b = s.preview_build.clone().expect("the background build");
assert!(b.running());
assert!(s.execute("library.buildPreviews", &json!({"ids": ["x"]})).is_err(), "ids that are not photo ids");
assert!(!b.cancel.load(std::sync::atomic::Ordering::Relaxed), "the background build was not stopped");
let _ = std::fs::remove_dir_all(&root);
}
/// CodeRabbit on #3577: smart previews asked for in the background with malformed ids fail without
/// stopping the background preparation either.
#[test]
fn a_bad_smart_preview_request_leaves_the_background_build_running() {
let _hold = crate::prep::TestHold::new();
let (mut s, root, ids) = library("prep-bad-smart-ids", 3);
s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "background": true})).unwrap();
let b = s.preview_build.clone().expect("the background build");
assert!(b.running());
assert!(s.execute("library.smartPreviews", &json!({"ids": ["x"], "background": true})).is_err(), "ids that are not photo ids");
assert!(!b.cancel.load(std::sync::atomic::Ordering::Relaxed), "the background build was not stopped");
// a smart-preview worker that can't start: the background build carries on, and stays the session's
crate::cmd::previews::test_gate::fail_next_spawn();
assert!(s.execute("library.smartPreviews", &json!({"ids": ids_json(&ids), "background": true})).is_err(), "the worker didn't start");
assert!(!b.cancel.load(std::sync::atomic::Ordering::Relaxed), "the background build was not stopped");
assert!(s.preview_build.as_ref().is_some_and(|now| std::sync::Arc::ptr_eq(now, &b)), "and is still the session's build");
// (stopped and finished before its folder goes)
b.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
drop(_hold);
let until = std::time::Instant::now() + std::time::Duration::from_secs(20);
while b.running() && std::time::Instant::now() < until {
std::thread::sleep(std::time::Duration::from_millis(5));
}
let _ = std::fs::remove_dir_all(&root);
}
/// CodeRabbit on #3544: a build asked for whose worker can't start fails without stopping or
/// replacing the background preparation that is running.
#[test]
fn a_build_that_cant_start_leaves_the_background_build_running() {
let _hold = crate::prep::TestHold::new();
let (mut s, root, ids) = library("prep-no-thread", 3);
s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "background": true})).unwrap();
let b = s.preview_build.clone().expect("the background build");
assert!(b.running());
crate::cmd::previews::test_gate::fail_next_spawn();
assert!(s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids)})).is_err(), "the worker didn't start");
assert!(!b.cancel.load(std::sync::atomic::Ordering::Relaxed), "the background build was not stopped");
assert!(s.preview_build.as_ref().is_some_and(|now| std::sync::Arc::ptr_eq(now, &b)), "and is still the session's build");
let _ = std::fs::remove_dir_all(&root);
}
/// CodeRabbit on #3080: a background build that can't start isn't tried again on every tick; the
/// view tries again once [`crate::prep::RETRY_AFTER`] has passed.
#[test]
fn a_build_that_cant_start_waits_before_trying_again() {
let (mut s, root, ids) = library("prep-retry", 3);
let mode = crate::prep::Mode::Library;
s.prep.fail_starts = 1;
for id in &ids {
s.prep_tick(mode, Some(*id), false);
}
assert!(s.preview_build.is_none(), "the start failed");
assert!(s.prep.retry_at.is_some());
// the app is told when to look again (a frame is asked for then)
assert!(s.prep_retry_in().is_some_and(|d| d <= crate::prep::RETRY_AFTER && d > crate::prep::RETRY_AFTER / 2));
s.prep_tick(mode, Some(ids[2]), false);
assert!(s.preview_build.is_none(), "not tried again at once");
// the wait is over: no more frames asked for it (CodeRabbit on #3077 / #3080)
s.prep.retry_at = s.prep.retry_at.map(|(view, _)| (view, web_time::Instant::now()));
assert_eq!(s.prep_retry_in(), None, "a deadline that has passed asks for no frame");
s.prep_tick(mode, Some(ids[2]), false);
let b = s.preview_build.clone().expect("tried again");
assert!(b.background && s.prep.retry_at.is_none());
b.cancel.store(true, Ordering::Relaxed);
let _ = wait_finished(&b);
let _ = std::fs::remove_dir_all(&root);
}
+243
View File
@@ -536,6 +536,249 @@ fn regions_from_sidecar_are_read_on_import() {
let _ = std::fs::remove_dir_all(&src);
}
/// MWG regions as an app that draws on the photo as stored writes them for [`write_turned_jpeg`]'s photo: its stored
/// 32 × 24 as `AppliedToDimensions` and no box saying how the photo was turned (no `mwg-rs:Rotation`). One face, its
/// box centred at (0.25, 0.4), 0.1 × 0.15 of that size.
const STORED_FRAME_REGIONS: &str = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about=""
xmlns:mwg-rs="http://www.metadataworkinggroup.com/schemas/regions/"
xmlns:stArea="http://ns.adobe.com/xmp/sType/Area#"
xmlns:stDim="http://ns.adobe.com/xap/1.0/sType/Dimensions#">
<mwg-rs:Regions rdf:parseType="Resource">
<mwg-rs:AppliedToDimensions rdf:parseType="Resource" stDim:w="32" stDim:h="24" stDim:unit="pixel"/>
<mwg-rs:RegionList>
<rdf:Bag>
<rdf:li rdf:parseType="Resource" mwg-rs:Name="Hannah" mwg-rs:Type="Face">
<mwg-rs:Area rdf:parseType="Resource" stArea:x="0.25" stArea:y="0.4" stArea:w="0.1" stArea:h="0.15" stArea:unit="normalized"/>
</rdf:li>
</rdf:Bag>
</mwg-rs:RegionList>
</mwg-rs:Regions>
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>"#;
/// A JPEG of 32 × 24 pixels stored sideways (Exif orientation 6, shown 24 × 32), with `packet` embedded when given.
fn write_turned_jpeg(path: &Path, packet: Option<&str>) {
let img = lightcraft_raster::Rgba8::from_fn(32, 24, |x, y| [(x * 7) as u8, (y * 9) as u8, 90, 255]);
let exif =
lightcraft_meta::write_exif(&lightcraft_meta::Metadata { orientation: Some(lightcraft_meta::Orientation::Rotate90), ..Default::default() });
let meta = lightcraft_codecs::EncodeMeta { exif: Some(&exif), xmp: packet, ..Default::default() };
let bytes = lightcraft_codecs::encode_jpeg(&lightcraft_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &meta).unwrap();
std::fs::write(path, bytes).unwrap();
}
/// Put more than the first MiB of APP15 segments between the JPEG at `path`'s start and its Exif.
fn pad_before_exif(path: &Path) {
let bytes = std::fs::read(path).unwrap();
let mut padded = bytes[..2].to_vec();
for _ in 0..17 {
padded.extend_from_slice(&[0xFF, 0xEF, 0xFF, 0xFF]);
padded.extend(std::iter::repeat_n(0, 0xFFFD));
}
padded.extend_from_slice(&bytes[2..]);
std::fs::write(path, padded).unwrap();
}
/// The face's box from [`STORED_FRAME_REGIONS`] on the upright photo: turned a quarter turn clockwise with it.
fn assert_on_the_upright_face(s: &Session, id: PhotoId, when: &str) {
let p = s.catalog.photo(id).unwrap();
assert_eq!((p.width, p.height), (24, 32), "the photo is upright");
let r = p.meta.regions.first().map(|r| r.rect).unwrap_or_default();
let want = [0.525, 0.2, 0.675, 0.3];
let got = [r.x0, r.y0, r.x1, r.y1];
assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-9), "{when}: the box is where the photo as stored had the face: {got:?}");
assert_eq!(p.meta.regions.len(), 1, "{when}");
}
/// Issue #2674: face boxes an app drew on a photo as stored (its sideways size as `AppliedToDimensions`, no
/// `mwg-rs:Rotation`) land on the faces of the photo as LightCraft shows it, upright: when imported, and when the
/// file's metadata is read again (the packet itself doesn't say how the photo turns; the file's Exif does). The
/// image's own size decides, not one the XMP states upright, and the Exif is found past the first MiB of the file.
#[test]
fn regions_drawn_on_the_photo_as_stored_land_on_the_upright_photo() {
let src = temp_dir("regions-stored-frame");
let embedded = src.join("embedded.jpg");
write_turned_jpeg(&embedded, Some(STORED_FRAME_REGIONS));
let beside = src.join("sidecar.jpg");
write_turned_jpeg(&beside, None);
std::fs::write(src.join("sidecar.xmp"), STORED_FRAME_REGIONS).unwrap();
// an Exif without a pixel size, and an XMP size of the upright photo
let stated = src.join("stated.jpg");
let upright_size = r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:ImageWidth="24" tiff:ImageLength="32""#;
write_turned_jpeg(&stated, Some(&STORED_FRAME_REGIONS.replace(r#"rdf:about="""#, upright_size)));
let late = src.join("late.jpg");
write_turned_jpeg(&late, None);
pad_before_exif(&late);
std::fs::write(src.join("late.xmp"), STORED_FRAME_REGIONS).unwrap();
for (file, what) in [(&embedded, "embedded XMP"), (&beside, "sidecar"), (&stated, "upright size in the XMP"), (&late, "Exif after the first MiB")]
{
let mut s = Session::new().with_fs();
let r = s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap();
assert_eq!(r["imported"].as_array().map(Vec::len), Some(1), "{r}");
let id = only(&s);
assert_on_the_upright_face(&s, id, &format!("{what}, imported"));
let read = s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap();
assert_eq!(read["failed"], json!([]), "{read}");
assert_eq!(read["read"].as_array().map(Vec::len), Some(1), "{what}: {read}");
assert_on_the_upright_face(&s, id, &format!("{what}, read again"));
}
let _ = std::fs::remove_dir_all(&src);
}
/// Review of #2857: a photo whose Exif states no orientation, but whose XMP says `tiff:Orientation=6`, is shown as
/// stored (LightCraft turns by the Exif alone), so boxes drawn on its stored frame are right as written: at import
/// and when the file's metadata is read again, which must agree.
#[test]
fn an_orientation_only_the_xmp_states_leaves_stored_frame_regions_as_written() {
let src = temp_dir("regions-xmp-orientation");
let file = src.join("p.jpg");
let packet = STORED_FRAME_REGIONS.replace(r#"rdf:about="""#, r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:Orientation="6""#);
let img = lightcraft_raster::Rgba8::from_fn(32, 24, |x, y| [(x * 7) as u8, (y * 9) as u8, 90, 255]);
// an Exif that states the size as stored (32 × 24, as cameras do) and no orientation
let exif = {
use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t};
let mut sub = IfdBuilder::new();
sub.set(t::PIXEL_X_DIMENSION, Value::Long(vec![32]));
sub.set(t::PIXEL_Y_DIMENSION, Value::Long(vec![24]));
let mut ifd0 = IfdBuilder::new();
ifd0.set_child(t::EXIF_IFD, sub);
[b"Exif\0\0".as_slice(), &TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap()].concat()
};
let meta = lightcraft_codecs::EncodeMeta { exif: Some(&exif), xmp: Some(&packet), ..Default::default() };
std::fs::write(&file, lightcraft_codecs::encode_jpeg(&lightcraft_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &meta).unwrap())
.unwrap();
let mut s = Session::new().with_fs();
s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap();
let id = only(&s);
let boxes = |s: &Session, when: &str| {
let p = s.catalog.photo(id).unwrap();
assert_eq!((p.width, p.height), (32, 24), "{when}: shown as stored");
assert_eq!(p.meta.regions.len(), 1, "{when}");
let r = p.meta.regions[0].rect;
[r.x0, r.y0, r.x1, r.y1]
};
let want = [0.2, 0.325, 0.3, 0.475];
let close = |got: [f64; 4]| got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-9);
let imported = boxes(&s, "imported");
assert!(close(imported), "imported: the box was turned by an orientation the Exif doesn't state: {imported:?}");
let read = s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap();
assert_eq!(read["failed"], json!([]), "{read}");
let again = boxes(&s, "read again");
assert!(close(again), "read again: {again:?}");
let _ = std::fs::remove_dir_all(&src);
}
/// Review of #2857 (P2): a MEF keeps orientation on its raw IFD, not IFD0. Import turns face boxes by the decoder's
/// orientation; Read Metadata from File must use the same source, or the boxes go back to the stored frame and
/// Synchronize Folder reports changes every pass. The sidecar has no `tiff:Orientation`.
#[test]
fn a_raws_decoder_orientation_turns_stored_frame_regions_on_import_and_reread() {
let src = temp_dir("regions-mef-orientation");
let file = src.join("p.mef");
// 16 × 6 CFA strip, orientation 6 on the raw IFD only (IFD0 has none) — same shape as `lightcraft_raw`'s MEF fixture.
let px: Vec<u16> = (0..16 * 6).map(|i| (i * 41 % 4096) as u16).collect();
let strip: Vec<u8> = px.chunks(2).flat_map(|p| [(p[0] >> 4) as u8, ((p[0] & 15) << 4) as u8 | (p[1] >> 8) as u8, p[1] as u8]).collect();
{
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags as t};
let mut raw = IfdBuilder::new();
raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0]));
raw.set(t::IMAGE_WIDTH, Value::Long(vec![16]));
raw.set(t::IMAGE_LENGTH, Value::Long(vec![6]));
raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![12]));
raw.set(t::COMPRESSION, Value::Short(vec![1]));
raw.set(t::PHOTOMETRIC, Value::Short(vec![t::photometric::CFA]));
raw.set(t::ORIENTATION, Value::Short(vec![6]));
raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2]));
raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2]));
raw.set_image(ImageData::Strips { rows_per_strip: 6, strips: vec![strip] });
let mut ifd0 = IfdBuilder::new();
ifd0.set(t::MAKE, Value::Ascii("Mamiya-OP Co.,Ltd.".into()));
ifd0.set(t::MODEL, Value::Ascii("MAMIYA ZD".into()));
ifd0.add_sub_ifd(raw);
std::fs::write(&file, TiffWriter::new(ByteOrder::Big, false).write(&[ifd0]).unwrap()).unwrap();
}
assert!(lightcraft_meta::extract(&std::fs::read(&file).unwrap()).orientation.is_none(), "IFD0 states no orientation");
assert_eq!(
lightcraft_raw::probe_info(&std::fs::read(&file).unwrap()).unwrap().orientation,
lightcraft_meta::Orientation::Rotate90,
"decoder reads the raw IFD"
);
let packet = STORED_FRAME_REGIONS.replace(r#"stDim:w="32" stDim:h="24""#, r#"stDim:w="16" stDim:h="6""#);
std::fs::write(src.join("p.xmp"), packet).unwrap();
let mut s = Session::new().with_fs();
s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap();
let id = only(&s);
let boxes = |s: &Session, when: &str| {
let p = s.catalog.photo(id).unwrap();
assert_eq!((p.width, p.height), (6, 16), "{when}: upright from orientation 6");
assert_eq!(p.meta.regions.len(), 1, "{when}");
let r = p.meta.regions[0].rect;
[r.x0, r.y0, r.x1, r.y1]
};
let imported = boxes(&s, "imported");
// Without the decoder orientation on re-read, readMetadataFromFile puts the box back to the stored-frame coords.
let read = s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap();
assert_eq!(read["failed"], json!([]), "{read}");
let again = boxes(&s, "read again");
assert_eq!(imported, again, "import and re-read must agree: imported={imported:?} again={again:?}");
let stored = [0.2, 0.325, 0.3, 0.475]; // STORED_FRAME_REGIONS centre/size as x0,y0,x1,y1 for 0.25,0.4,0.1,0.15
assert!(
imported.iter().zip(stored).any(|(g, w)| (g - w).abs() > 1e-6),
"imported boxes should have been turned off the stored frame: {imported:?}"
);
let _ = std::fs::remove_dir_all(&src);
}
/// A raw LightCraft can't decode: a TIFF whose first IFD holds Exif orientation 6, a 40 × 30 JPEG and `packet`.
fn turned_preview_only_raw(packet: &str) -> Vec<u8> {
let img = lightcraft_raster::Rgba8::from_fn(40, 30, |x, y| [(x * 6) as u8, (y * 8) as u8, 90, 255]);
let jpeg = lightcraft_codecs::encode_jpeg(&lightcraft_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &Default::default()).unwrap();
let data = 8 + 2 + 4 * 12 + 4;
let (jpeg_len, packet_at) = (u32::try_from(jpeg.len()).unwrap(), u32::try_from(data + jpeg.len()).unwrap());
let mut f = b"II*\0\x08\0\0\0\x04\0".to_vec();
for (tag, kind, count, value) in [(274u16, 3u16, 1, 6), (513, 4, 1, data as u32), (514, 4, 1, jpeg_len), (700, 1, packet.len() as u32, packet_at)]
{
f.extend(tag.to_le_bytes());
f.extend(kind.to_le_bytes());
f.extend(u32::to_le_bytes(count));
f.extend(u32::to_le_bytes(value));
}
f.extend([0; 4]);
f.extend(jpeg);
f.extend(packet.as_bytes());
f
}
/// A sidecar with no `mwg-rs:Regions` leaves the boxes read from the file itself, and a raw's Exif may state no pixel
/// size. A size only its XMP states, of the upright photo, has the shape of boxes drawn on it upright: they stay put.
#[test]
fn a_size_only_a_raws_xmp_states_leaves_upright_regions_as_written() {
let src = temp_dir("regions-xmp-size");
let file = src.join("p.iiq");
let upright_size = r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:ImageWidth="24" tiff:ImageLength="32""#;
let packet =
STORED_FRAME_REGIONS.replace(r#"stDim:w="32" stDim:h="24""#, r#"stDim:w="24" stDim:h="32""#).replace(r#"rdf:about="""#, upright_size);
std::fs::write(&file, turned_preview_only_raw(&packet)).unwrap();
std::fs::write(
src.join("p.xmp"),
r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Rating="2"/></rdf:RDF></x:xmpmeta>"#,
)
.unwrap();
let mut s = Session::new().with_fs();
s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap();
let p = s.catalog.photo(only(&s)).unwrap();
assert!(p.preview_only.is_some() && (p.width, p.height) == (30, 40), "{:?} {}x{}", p.preview_only, p.width, p.height);
assert_eq!(p.rating, 2, "the sidecar was read");
assert_eq!(p.meta.regions.len(), 1);
let r = p.meta.regions[0].rect;
let got = [r.x0, r.y0, r.x1, r.y1];
assert!(got.iter().zip([0.2, 0.325, 0.3, 0.475]).all(|(g, w)| (g - w).abs() < 1e-9), "{got:?}");
let _ = std::fs::remove_dir_all(&src);
}
/// Removing a face box is a catalog-only, undoable edit: it never rewrites the sidecar (Lightroom's
/// regions and everything else in it stay byte for byte), even with auto-write on.
#[test]
@@ -0,0 +1,289 @@
//! Opt-in quality check of the built-in denoiser on one public Bayer raw (CC0, from `cargo xtask corpus --download`).
//!
//! Noise of a known level is added to the raw's own mosaic, the built-in denoiser runs over it, and the result is
//! scored against the untouched mosaic demosaiced the same way. PSNR is measured on gamma-encoded camera RGB; the
//! detail figure is the gradient energy of the result over that of the truth (1 = as sharp, below 1 = smoother).
//!
//! LC_DENOISE_RAW=../../corpus/raw/arw-sony-a7m3-compressed.arw LC_DENOISE_OUT=/tmp/dn \
//! cargo test --release -p lightcraft-engine --test denoise_builtin_quality -- --ignored --nocapture
//! LC_DENOISE_OUT, when set, receives side-by-side PNGs (truth | noisy | denoised) of a 100 % crop per level.
use lightcraft_codecs::encode::{EncodeImage, EncodeMeta, Samples, encode_png};
use lightcraft_denoise_core::bayer::Layout;
use lightcraft_denoise_core::builtin::{Builtin, OVERLAP, TILE, demosaic, estimate_noise};
use lightcraft_denoise_core::manifest::Gain;
use lightcraft_denoise_core::nlm::Tuning;
use lightcraft_denoise_core::run::{Control, Params, denoise_bayer};
use std::time::Instant;
struct Rng(u64);
impl Rng {
/// The next uniform number, strictly between 0 and 1.
fn uniform(&mut self) -> f32 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((self.0 >> 40) as f32 + 0.5) / (1u64 << 24) as f32
}
/// The next standard normal number (Box-Muller).
fn normal(&mut self) -> f32 {
let (u, v) = (self.uniform(), self.uniform());
(-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos()
}
}
/// The plain demosaic of a mosaic (RGGB, even size) as camera RGB planes, through the tile packer the runner uses.
fn plain(mosaic: &[f32], w: usize, h: usize) -> Vec<[f32; 3]> {
let (cw, ch) = (w / 2, h / 2);
let mut planes = vec![vec![0f32; cw * ch]; 4];
for cy in 0..ch {
for cx in 0..cw {
for (p, (dx, dy)) in [(0, 0), (1, 0), (0, 1), (1, 1)].into_iter().enumerate() {
planes[p][cy * cw + cx] = mosaic[(2 * cy + dy) * w + 2 * cx + dx];
}
}
}
// `demosaic` takes square planes: run it on square blocks and stitch
let side = cw.min(ch);
let mut out = vec![[0f32; 3]; w * h];
for by in (0..ch).step_by(side) {
for bx in (0..cw).step_by(side) {
let (x0, y0) = (bx.min(cw - side), by.min(ch - side));
let block: Vec<Vec<f32>> = planes.iter().map(|pl| (0..side * side).map(|i| pl[(y0 + i / side) * cw + x0 + i % side]).collect()).collect();
let rgb = demosaic(&block, side);
let s2 = 2 * side;
for y in 0..s2 {
for x in 0..s2 {
let o = (2 * y0 + y) * w + 2 * x0 + x;
out[o] = [rgb[y * s2 + x], rgb[s2 * s2 + y * s2 + x], rgb[2 * s2 * s2 + y * s2 + x]];
}
}
}
}
out
}
/// A linear value encoded for viewing: clamped to 0..1, then gamma 2.2.
fn gamma(v: f32) -> f32 {
v.clamp(0.0, 1.0).powf(1.0 / 2.2)
}
/// PSNR in dB between two camera-RGB pictures after exposure `scale` and gamma, leaving out a 16-pixel border.
fn psnr(a: &[[f32; 3]], b: &[[f32; 3]], w: usize, h: usize, scale: f32) -> f64 {
let (mut sum, mut n) = (0f64, 0f64);
for y in 16..h - 16 {
for x in 16..w - 16 {
for c in 0..3 {
let d = f64::from(gamma(a[y * w + x][c] * scale) - gamma(b[y * w + x][c] * scale));
sum += d * d;
n += 1.0;
}
}
}
-10.0 * (sum / n).log10()
}
/// The summed gradient of the picture's green channel after exposure `scale` and gamma, leaving out a 16-pixel border.
fn gradient(a: &[[f32; 3]], w: usize, h: usize, scale: f32) -> f64 {
let mut sum = 0f64;
for y in 16..h - 16 {
for x in 16..w - 16 {
let g = |x: usize, y: usize| f64::from(gamma(a[y * w + x][1] * scale));
sum += (g(x + 1, y) - g(x, y)).abs() + (g(x, y + 1) - g(x, y)).abs();
}
}
sum
}
/// How much of the true picture's fine structure the result keeps: the slope of the result's high-pass (green minus
/// its 5 x 5 mean) against the truth's. Noise is independent of the truth, so unlike gradient energy it can't inflate it.
fn texture(a: &[[f32; 3]], truth: &[[f32; 3]], w: usize, h: usize, scale: f32) -> f64 {
let hp = |p: &[[f32; 3]], x: usize, y: usize| {
let mut m = 0f64;
for j in 0..5 {
for i in 0..5 {
m += f64::from(gamma(p[(y + j - 2) * w + x + i - 2][1] * scale));
}
}
f64::from(gamma(p[y * w + x][1] * scale)) - m / 25.0
};
let (mut xy, mut xx) = (0f64, 0f64);
for y in 16..h - 16 {
for x in 16..w - 16 {
let t = hp(truth, x, y);
xy += t * hp(a, x, y);
xx += t * t;
}
}
xy / xx
}
/// A `side × side` crop of the picture from `(x0, y0)` as 8-bit RGB with a daylight white balance, for the PNGs.
fn crop_rgb8(a: &[[f32; 3]], w: usize, (x0, y0): (usize, usize), side: usize, scale: f32) -> Vec<u8> {
let wb = [2.0f32, 1.0, 1.6];
let mut out = Vec::with_capacity(side * side * 3);
for y in 0..side {
for x in 0..side {
for c in 0..3 {
out.push((gamma(a[(y0 + y) * w + x0 + x][c] * wb[c] * scale) * 255.0 + 0.5) as u8);
}
}
}
out
}
/// Adds noise of known levels to a public raw's mosaic, denoises it with the built-in denoiser and prints how close the
/// result is to the untouched mosaic. Opt-in: it needs the raw named by `LC_DENOISE_RAW`.
#[test]
#[ignore = "needs a public raw: LC_DENOISE_RAW=<file>"]
fn the_built_in_denoiser_scored_on_a_real_raw_with_added_noise() {
let path = std::env::var("LC_DENOISE_RAW").unwrap_or_else(|_| "../../corpus/raw/arw-sony-a7m3-compressed.arw".into());
let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{path}: {e}"));
let n = lightcraft_raw::decode(&bytes).unwrap().normalized().unwrap();
let cfa = n.cfa.as_ref().unwrap();
let layout = Layout::from_cell([cfa.color_at(0, 0), cfa.color_at(1, 0), cfa.color_at(0, 1), cfa.color_at(1, 1)]).unwrap();
assert_eq!(layout, Layout { dx: 0, dy: 0 }, "the benchmark assumes RGGB");
// an even-aligned window from the middle of the frame keeps the colour pattern
let (w, h) = (1536usize, 1024usize);
let (ox, oy) = (((n.width - w) / 2) & !1, ((n.height - h) / 2) & !1);
let truth: Vec<f32> = (0..w * h).map(|i| n.data[(oy + i / w) * n.width + ox + i % w]).collect();
// LC_BIN=1: average each cell with the three nearest of its own colour (a 2 x 2 binning of the colour pattern's
// cells), which halves the reference's own noise so that noise added at a camera's low levels dominates it
let (w, h, truth) = if std::env::var("LC_BIN").is_ok_and(|v| v != "0") {
let (bw, bh) = (w / 2, h / 2);
let binned: Vec<f32> = (0..bw * bh)
.map(|i| {
let (x, y) = (i % bw, i / bw);
let (sx, sy, cx, cy) = (x / 2, y / 2, x % 2, y % 2);
let at = |di: usize, dj: usize| truth[(2 * (2 * sy + dj) + cy) * w + 2 * (2 * sx + di) + cx];
(at(0, 0) + at(1, 0) + at(0, 1) + at(1, 1)) / 4.0
})
.collect();
(bw, bh, binned)
} else {
(w, h, truth)
};
let mean = truth.iter().map(|v| f64::from(*v)).sum::<f64>() / truth.len() as f64;
let scale = (0.18 / mean) as f32;
let truth_rgb = plain(&truth, w, h);
let own = estimate_noise(&truth, w, h);
println!(
"the reference's own noise by the estimator: a {:.5} b {:.6} (sd at 0.18 {:.4}); a clean reference would read about 0",
own.0,
own.1,
(own.0 * 0.18 + own.1).sqrt()
);
println!("{path}: {}x{}, window {w}x{h}, mean {mean:.4}", n.width, n.height);
println!("{:<14}{:>10}{:>10}{:>9}{:>9}{:>9}{:>9}", "noise (a, b)", "noisy dB", "denoised", "gain", "detail", "texture", "seconds");
let out_dir = std::env::var("LC_DENOISE_OUT").ok();
#[cfg(feature = "denoise")]
let gpu = std::env::var("LC_GPU").is_ok_and(|v| v != "0").then(|| {
let p = Tuning::default().bm3d.unwrap();
let g = lightcraft_gpu::bm3d::Bm3dGpu::new(&p, TILE as usize).unwrap();
println!("on the graphics card: {} ({})", g.adapter(), g.build_report());
std::sync::Arc::new(g)
});
// LC_REAL=1 runs the noise levels measured on real Canon EOS R / R6 Mark III raws instead (their standard deviation at
// mid-grey is 0.003, 0.006, 0.0095, 0.015 and 0.038: ISO <= 400, 1600, 6400, 25600 and above)
let levels: &[(&str, f32, f32)] = if std::env::var("LC_REAL").is_ok_and(|v| v != "0") {
&[("iso400", 4e-5, 1e-7), ("iso1600", 2.1e-4, 3e-7), ("iso6400", 4.9e-4, 1e-6), ("iso25600", 1.19e-3, 1.7e-5), ("iso51200", 6.9e-3, 2.08e-4)]
} else {
&[("light", 0.002, 0.0002), ("medium", 0.008, 0.001), ("heavy", 0.025, 0.004), ("extreme", 0.06, 0.012)]
};
for &(name, a, b) in levels {
let mut rng = Rng(11);
let noisy: Vec<f32> = truth.iter().map(|&v| v + rng.normal() * (a * v.max(0.0) + b).sqrt()).collect();
let started = Instant::now();
let params = Params { tile: TILE as usize, overlap: OVERLAP as usize, gain: Gain::None, clip: Some(0.99), parallel: 4 };
// LC_EST=v1 (the first estimator) | true (the noise that was added) | anything else: the current estimator
// LC_FULL=1: measure the noise on the whole frame with the same noise added, as the app does (it measures the whole
// photo), instead of on the crop
let measure = |mosaic: &[f32], mw: usize, mh: usize| match std::env::var("LC_EST").as_deref() {
Ok("v1") => lightcraft_denoise_core::builtin::estimate_noise_v1(mosaic, mw, mh),
_ => estimate_noise(mosaic, mw, mh),
};
let est = match std::env::var("LC_EST").as_deref() {
Ok("true") => (a, b),
_ if std::env::var("LC_TRUE").is_ok_and(|v| v != "0") => (a, b),
_ if std::env::var("LC_FULL").is_ok_and(|v| v != "0") => {
let mut rng = Rng(23);
let frame: Vec<f32> = n.data.iter().map(|&v| v + rng.normal() * (a * v.max(0.0) + b).sqrt()).collect();
measure(&frame, n.width, n.height)
}
_ => measure(&noisy, w, h),
};
let mut tuning = Tuning::default();
let env = |k: &str| std::env::var(k).ok().and_then(|v| v.parse::<f32>().ok());
(tuning.search, tuning.search2) = (env("LC_S1").map_or(tuning.search, |v| v as usize), env("LC_S2").map_or(tuning.search2, |v| v as usize));
(tuning.h_light, tuning.h_heavy, tuning.h2) =
(env("LC_HL").unwrap_or(tuning.h_light), env("LC_HH").unwrap_or(tuning.h_heavy), env("LC_H2").unwrap_or(tuning.h2));
(tuning.light, tuning.heavy) = (env("LC_LIGHT").unwrap_or(tuning.light), env("LC_HEAVY").unwrap_or(tuning.heavy));
(tuning.half, tuning.half2) = (env("LC_P1").map_or(tuning.half, |v| v as usize), env("LC_P2").map_or(tuning.half2, |v| v as usize));
(tuning.loose, tuning.few) = (env("LC_LOOSE").unwrap_or(tuning.loose), env("LC_FEW").unwrap_or(tuning.few));
(tuning.search_c, tuning.h_c) = (env("LC_SC").map_or(tuning.search_c, |v| v as usize), env("LC_HC").unwrap_or(tuning.h_c));
// LC_NLM=1 runs the old non-local-means filter instead; LC_B_* override the block-matching filter's parameters
if env("LC_NLM").is_some_and(|v| v > 0.0) {
tuning.bm3d = None;
}
if let Some(b) = tuning.bm3d.as_mut() {
(b.block, b.step, b.search, b.group) = (
env("LC_B_N").map_or(b.block, |v| v as usize),
env("LC_B_STEP").map_or(b.step, |v| v as usize),
env("LC_B_S").map_or(b.search, |v| v as usize),
env("LC_B_K").map_or(b.group, |v| v as usize),
);
(b.tau1, b.tau2) = (env("LC_B_T1").unwrap_or(b.tau1), env("LC_B_T2").unwrap_or(b.tau2));
// LC_B_LOFF adds to every point of the threshold curve (a sweep of how hard it cleans)
let off = env("LC_B_LOFF").unwrap_or(0.0);
for point in &mut b.lambda {
point.1 += off;
}
b.sigma = env("LC_B_SIG").unwrap_or(b.sigma);
b.wiener = env("LC_B_WIENER").is_none_or(|v| v > 0.0);
}
let runner = Builtin { noise: Some(est), tuning };
// LC_GPU=1 (with `--features denoise`) runs the block-matching filter on the graphics card
#[cfg(feature = "denoise")]
let out = match &gpu {
Some(g) => {
let on_card = lightcraft_gpu::bm3d::BuiltinRunner::new(g.clone(), runner).unwrap();
denoise_bayer(&noisy, w, h, layout, &on_card, &params, &Control::default()).unwrap()
}
None => denoise_bayer(&noisy, w, h, layout, &runner, &params, &Control::default()).unwrap(),
};
#[cfg(not(feature = "denoise"))]
let out = denoise_bayer(&noisy, w, h, layout, &runner, &params, &Control::default()).unwrap();
let secs = started.elapsed().as_secs_f64();
let noisy_rgb = plain(&noisy, w, h);
let (p_noisy, p_out) = (psnr(&noisy_rgb, &truth_rgb, w, h, scale), psnr(&out.data, &truth_rgb, w, h, scale));
let detail = gradient(&out.data, w, h, scale) / gradient(&truth_rgb, w, h, scale);
let tex = texture(&out.data, &truth_rgb, w, h, scale);
println!(
"{:<14}{:>10.2}{:>10.2}{:>+9.2}{:>9.3}{:>9.3}{:>9.2} noise a {:.4} (true {a}), b {:.5} (true {b})",
name,
p_noisy,
p_out,
p_out - p_noisy,
detail,
tex,
secs,
est.0,
est.1
);
if let Some(dir) = &out_dir {
let side = 400;
let at = (w / 2 - side / 2, h / 2 - side / 2);
let tiles =
[crop_rgb8(&truth_rgb, w, at, side, scale), crop_rgb8(&noisy_rgb, w, at, side, scale), crop_rgb8(&out.data, w, at, side, scale)];
let mut sheet = Vec::with_capacity(side * side * 9);
for y in 0..side {
for t in &tiles {
sheet.extend_from_slice(&t[y * side * 3..(y + 1) * side * 3]);
}
}
let img = EncodeImage::new((3 * side) as u32, side as u32, 3, Samples::U8(&sheet));
std::fs::create_dir_all(dir).unwrap();
std::fs::write(format!("{dir}/{name}.png"), encode_png(&img, &EncodeMeta::default()).unwrap()).unwrap();
}
}
}
@@ -0,0 +1,130 @@
//! Opt-in accuracy check of the built-in denoiser's noise estimator (public CC0 raws from `cargo xtask corpus --download`).
//!
//! 1. `a_quantile_of_pure_noise_blocks_...`: white noise of a known level: what fraction of the true variance a quantile of
//! the blocks' variances is (the correction `NoiseProbe::correction` divides by).
//! 2. `the_noise_estimate_...`: noise of known levels added to 2 x 2-binned crops of many raws (which halves the pictures'
//! own noise), then the estimates against the truth, for the first version and the current one, at 0.03 (the dark
//! cells of a typical photo) and 0.18 (mid-grey).
//!
//! LC_CORPUS=C:/.../corpus/raw LC_STRIDE=6 cargo test --release -p lightcraft-engine --test denoise_noise_estimate -- --ignored --nocapture
use lightcraft_denoise_core::builtin::{NoiseProbe, estimate_noise_v1, estimate_noise_with};
struct Rng(u64);
impl Rng {
/// The next uniform number, strictly between 0 and 1.
fn uniform(&mut self) -> f32 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((self.0 >> 40) as f32 + 0.5) / (1u64 << 24) as f32
}
/// The next standard normal number (Box-Muller).
fn normal(&mut self) -> f32 {
let (u, v) = (self.uniform(), self.uniform());
(-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos()
}
}
/// The environment variable `k` as a number, if it is set and parses.
fn env(k: &str) -> Option<f32> {
std::env::var(k).ok().and_then(|v| v.parse().ok())
}
/// Prints what fraction of the true variance a quantile of pure-noise blocks' variances is, for each block size and
/// quantile: the calibration behind `NoiseProbe::correction`.
#[test]
#[ignore = "calibration printout"]
fn a_quantile_of_pure_noise_blocks_is_a_known_fraction_of_the_true_variance() {
let (w, h) = (2048usize, 2048usize);
let sigma = 0.01f32;
let mut rng = Rng(3);
let mosaic: Vec<f32> = (0..w * h).map(|i| 0.1 + 0.7 * (i % w) as f32 / w as f32 + rng.normal() * sigma).collect();
println!("{:>6}{:>9}{:>14} (estimated variance / true variance, correction 1; a brightness ramp, pure noise)", "block", "quantile", "fraction");
for block in [8usize, 12, 16, 24, 32] {
for quantile in [0.02f32, 0.05, 0.1, 0.2, 0.5] {
let (_, b) = estimate_noise_with(&mosaic, w, h, &NoiseProbe { block, quantile, correction: 1.0 });
println!("{block:>6}{quantile:>9}{:>14.3}", b / (sigma * sigma));
}
}
}
/// The 2 x 2 colour-cell binning of a window of a normalised mosaic (halves its own noise), as the quality benchmark does.
fn binned_crop(n: &lightcraft_raw::Normalized, side: usize) -> Option<(Vec<f32>, usize)> {
let side = side.min(n.width).min(n.height) & !3;
if side < 512 {
return None;
}
let (ox, oy) = (((n.width - side) / 2) & !1, ((n.height - side) / 2) & !1);
let half = side / 2;
let out = (0..half * half)
.map(|i| {
let (x, y) = (i % half, i / half);
let (sx, sy, cx, cy) = (x / 2, y / 2, x % 2, y % 2);
let at = |di: usize, dj: usize| n.data[(oy + 2 * (2 * sy + dj) + cy) * n.width + ox + 2 * (2 * sx + di) + cx];
(at(0, 0) + at(1, 0) + at(0, 1) + at(1, 1)) / 4.0
})
.collect();
Some((out, half))
}
/// Prints how the estimated noise compares with the noise added to crops of many raws, for the first version and for
/// several settings of the current one. Opt-in: it needs the raw corpus folder named by `LC_CORPUS`.
#[test]
#[ignore = "needs the public raw corpus: LC_CORPUS=<folder>"]
fn the_noise_estimate_follows_the_noise_added_to_many_different_pictures() {
let dir = std::env::var("LC_CORPUS").unwrap_or_else(|_| "../../corpus/raw".into());
let stride = env("LC_STRIDE").map_or(6, |v| v as usize).max(1);
let mut files: Vec<_> = std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{dir}: {e}")).flatten().map(|e| e.path()).collect();
files.sort();
let probes = [
("v1 (old)", None),
("block 16, q 0.10", Some(NoiseProbe { block: 16, quantile: 0.10, correction: env("LC_C").unwrap_or(0.8) })),
("block 12, q 0.05", Some(NoiseProbe { block: 12, quantile: 0.05, correction: env("LC_C2").unwrap_or(0.65) })),
("block 24, q 0.10", Some(NoiseProbe { block: 24, quantile: 0.10, correction: env("LC_C3").unwrap_or(0.85) })),
];
// sd at mid-grey 0.0062, 0.0094, 0.015, 0.038 (Canon EOS R / R6 Mark III at ISO 1600, 6400, 25600 and above)
let levels = [("sd .0062", 2.1e-4f32, 3e-7f32), ("sd .0094", 4.9e-4, 1e-6), ("sd .0152", 1.19e-3, 1.7e-5), ("sd .0381", 6.9e-3, 2.08e-4)];
// ratios[level][probe][where] -> estimated sd / true sd
let mut ratios: Vec<Vec<[Vec<f32>; 2]>> = levels.iter().map(|_| probes.iter().map(|_| [Vec::new(), Vec::new()]).collect()).collect();
let mut used = 0;
for path in files.iter().step_by(stride) {
let Ok(bytes) = std::fs::read(path) else { continue };
let Ok(raw) = lightcraft_raw::decode(&bytes) else { continue };
if raw.cpp != 1 || !raw.cfa.as_ref().is_some_and(lightcraft_raw::Cfa::is_bayer) {
continue;
}
let Ok(n) = raw.normalized() else { continue };
let Some((mosaic, side)) = binned_crop(&n, 2048) else { continue };
used += 1;
for (li, &(_, a, b)) in levels.iter().enumerate() {
let mut rng = Rng(11 + li as u64);
let noisy: Vec<f32> = mosaic.iter().map(|&v| v + rng.normal() * (a * v.max(0.0) + b).sqrt()).collect();
for (pi, (_, probe)) in probes.iter().enumerate() {
let (ea, eb) = match probe {
None => estimate_noise_v1(&noisy, side, side),
Some(p) => estimate_noise_with(&noisy, side, side, p),
};
for (wi, at) in [0.03f32, 0.18].into_iter().enumerate() {
ratios[li][pi][wi].push(((ea * at + eb) / (a * at + b)).sqrt());
}
}
}
}
println!("{used} pictures (every {stride}th raw of {dir}), each binned to {} cells, noise added at 4 levels", 1024);
println!("estimated sd / true sd: median [10th .. 90th percentile], share within -20 % .. +25 %");
for (li, (name, _, _)) in levels.iter().enumerate() {
for (wi, at) in ["at 0.03", "at 0.18"].into_iter().enumerate() {
println!("{name} {at}:");
for (pi, (pname, _)) in probes.iter().enumerate() {
let mut r = ratios[li][pi][wi].clone();
r.sort_by(f32::total_cmp);
if r.is_empty() {
continue;
}
let q = |f: f32| r[((r.len() - 1) as f32 * f) as usize];
let within = r.iter().filter(|&&v| (0.8..=1.25).contains(&v)).count() as f32 / r.len() as f32;
println!(" {pname:<18} {:.2} [{:.2} .. {:.2}] {:>3.0} % within", q(0.5), q(0.1), q(0.9), within * 100.0);
}
}
}
}
+592
View File
@@ -0,0 +1,592 @@
//! The built-in denoiser's block-matching filter ([`lightcraft_denoise::bm3d`], which is the reference) on the GPU:
//! three WGSL kernels (`wgsl/bm3d_*.wgsl`) that group alike blocks, filter each group's blocks together and put them
//! back, run twice (a hard threshold, then a Wiener filter built from its result) in one command buffer per tile.
//!
//! Only the filter stage runs here. Measuring the noise, the variance-stabilising transform and its inverse and the
//! demosaic stay on the processor ([`Builtin::run_with`]), so a tile differs from the processor's only by the rounding
//! of the filter itself. Like [`crate::nn`], the runner has a device of its own, respects the same switches and the same
//! crash sentinel, never panics, and a failure is an `Err` that makes the caller run that tile on the CPU.
use std::sync::{Arc, Condvar, Mutex};
use std::time::Duration;
use bytemuck::{Pod, Zeroable};
use lightcraft_denoise::bm3d::{self, Params};
use lightcraft_denoise::builtin::Builtin;
use lightcraft_denoise::nlm::hadamard;
use lightcraft_denoise::run::{Error, TileRunner};
use wgpu::util::DeviceExt;
use crate::nn::{CLOSING, Dev, TIMEOUT, dev, entry, mark_broken, pipeline, storage};
/// Tiles that can be on the GPU at once (each has buffers of its own).
const WORKSPACES: usize = 2;
/// The largest tile side (in cells) the buffers and dispatch sizes are made for.
const MAX_TILE: usize = 512;
/// The block side and the group size the kernels are written for.
const BLOCK: usize = 4;
const GROUP: usize = 16;
/// Invocations in a workgroup (the kernels' `@workgroup_size`).
const WORKGROUP: u32 = 64;
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct Uniforms {
t: u32,
nr: u32,
nb: u32,
search: u32,
cap: u32,
wiener: u32,
pad0: u32,
pad1: u32,
tau: f32,
lambda: f32,
sigma: f32,
pad2: f32,
}
struct Pipes {
matching: wgpu::ComputePipeline,
matching_layout: wgpu::BindGroupLayout,
collab: wgpu::ComputePipeline,
collab_layout: wgpu::BindGroupLayout,
agg: wgpu::ComputePipeline,
agg_layout: wgpu::BindGroupLayout,
/// How long each kernel took to build (the driver compiles them), for the log and the tests.
built: Vec<(String, f64)>,
}
/// Compile the three kernels (match, filter, put back) and make their bind-group layouts, timing each build.
fn build_pipes(d: &Dev) -> Pipes {
use wgpu::BufferBindingType::{Storage, Uniform};
let (ro, rw) = (Storage { read_only: true }, Storage { read_only: false });
let layout =
|entries: &[wgpu::BindGroupLayoutEntry]| d.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries });
let matching_layout = layout(&[entry(0, Uniform), entry(1, ro), entry(2, ro), entry(3, rw)]);
let collab_layout = layout(&[entry(0, Uniform), entry(1, ro), entry(2, ro), entry(3, ro), entry(4, ro), entry(5, rw), entry(6, rw)]);
let agg_layout = layout(&[entry(0, Uniform), entry(1, ro), entry(2, ro), entry(3, ro), entry(4, ro), entry(5, ro), entry(6, rw)]);
let common = include_str!("wgsl/bm3d_common.wgsl");
let transform = include_str!("wgsl/bm3d_transform.wgsl");
// the group's transforms, for the noisy blocks (`buf`) and for the pilot's (`pb`)
let collab_source = format!(
"{}\n{}\n{}",
transform.replace("{{A}}", "buf").replace("{{S}}", ""),
transform.replace("{{A}}", "pb").replace("{{S}}", "_p"),
include_str!("wgsl/bm3d_collab.wgsl")
);
let mut built = Vec::new();
let mut make = |name: &str, kernel: &str, layout: &wgpu::BindGroupLayout| {
let started = std::time::Instant::now();
let p = pipeline(d, name, &format!("{common}\n{kernel}"), layout);
built.push((name.to_string(), started.elapsed().as_secs_f64() * 1000.0));
p
};
let matching = make("bm3d match", include_str!("wgsl/bm3d_match.wgsl"), &matching_layout);
let collab = make("bm3d filter", &collab_source, &collab_layout);
let agg = make("bm3d put back", include_str!("wgsl/bm3d_agg.wgsl"), &agg_layout);
Pipes { matching, matching_layout, collab, collab_layout, agg, agg_layout, built }
}
/// One tile's buffers and bind groups.
struct Workspace {
y: wgpu::Buffer,
basic: wgpu::Buffer,
out: wgpu::Buffer,
/// The two steps' uniforms (their match tolerance and the filter they use differ).
first: wgpu::Buffer,
second: wgpu::Buffer,
staging: wgpu::Buffer,
/// Match, filter and put back, for the first step then the second.
bound: [wgpu::BindGroup; 6],
_slots: [wgpu::Buffer; 3],
}
/// The filter on the GPU for one tile size and one set of parameters. Cheap to share between threads: each call takes a
/// free workspace.
pub struct Bm3dGpu {
dev: &'static Dev,
pipes: Pipes,
/// The parameters it was made for, as they were given.
requested: Params,
t: usize,
/// Blocks that start a group, along a side, and how many blocks fit along a side.
nr: usize,
nb: usize,
consts: wgpu::Buffer,
free: Mutex<Vec<Workspace>>,
/// Workspaces made so far (they are made when a call finds none free, up to [`WORKSPACES`]).
made: Mutex<usize>,
wake: Condvar,
}
/// An error for something the kernels do not do, with `why` as its text.
fn unsupported<T>(why: impl Into<String>) -> Result<T, String> {
Err(why.into())
}
impl Bm3dGpu {
/// The filter with `params` for tiles of `t × t` cells on the GPU, or why it cannot be (no GPU, parameters or a size
/// the kernels do not do, the device refusing the buffers). Creates the device on first use and compiles the kernels.
pub fn new(params: &Params, t: usize) -> Result<Bm3dGpu, String> {
let _work = crate::exit::enter().ok_or(CLOSING)?;
let Some(plan) = bm3d::plan(params, t, 0.0) else { return unsupported("the tile is smaller than a block") };
let p = plan.params;
if p.block != BLOCK || p.group > GROUP || p.step == 0 {
return unsupported(format!("the kernels do {BLOCK} x {BLOCK} blocks in groups of at most {GROUP}"));
}
if t > MAX_TILE {
return unsupported(format!("tiles of more than {MAX_TILE} cells on a side are not done on the GPU"));
}
let d = dev()?;
let nb = t + 1 - BLOCK;
let axis = bm3d::starts(nb, p.step);
let nr = axis.len();
let blocks_bytes = (nr * nr * 4 * GROUP * BLOCK * BLOCK * 4) as u64;
if blocks_bytes > d.limits.max_storage_buffer_binding_size.min(d.limits.max_buffer_size) {
return unsupported(format!("{} cannot hold a tile's filtered blocks ({} MB)", d.info.name, blocks_bytes >> 20));
}
let (dct, window) = bm3d::constants(BLOCK);
let consts: Vec<u32> = dct.iter().chain(&window).map(|v| v.to_bits()).chain(axis.iter().map(|&a| a as u32)).collect();
let scope = [
d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory),
d.device.push_error_scope(wgpu::ErrorFilter::Validation),
d.device.push_error_scope(wgpu::ErrorFilter::Internal),
];
// the driver compiles the kernels here: a crash in it is reported at the next launch (issue #250)
let pipes = crate::backend::with_marker("denoise kernel compilation", || build_pipes(d));
let consts = d.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("bm3d consts"),
contents: bytemuck::cast_slice(&consts),
usage: wgpu::BufferUsages::STORAGE,
});
let mut me =
Bm3dGpu { dev: d, pipes, requested: *params, t, nr, nb, consts, free: Mutex::new(Vec::new()), made: Mutex::new(1), wake: Condvar::new() };
let first = me.workspace();
me.free = Mutex::new(vec![first]);
let [oom, validation, internal] = scope;
let errors = [pollster::block_on(internal.pop()), pollster::block_on(validation.pop()), pollster::block_on(oom.pop())];
if let Some(e) = errors.into_iter().flatten().next() {
return Err(format!("{}: the denoise kernels could not be set up ({e})", d.info.name));
}
Ok(me)
}
/// The adapter this runs on.
pub fn adapter(&self) -> String {
format!("{} ({:?})", self.dev.info.name, self.dev.info.backend)
}
/// The parameters it was made for.
pub fn params(&self) -> Params {
self.requested
}
/// How long each kernel took to build, e.g. `bm3d match: 812 ms`.
pub fn build_report(&self) -> String {
self.pipes.built.iter().map(|(k, ms)| format!("{k}: {ms:.0} ms")).collect::<Vec<_>>().join(", ")
}
/// A new workspace for this runner's tile size: the plane, scratch and staging buffers and the six bind groups.
fn workspace(&self) -> Workspace {
let d = self.dev;
let (t, groups) = (self.t, self.nr * self.nr);
let planes = (4 * t * t * 4) as u64;
let (y, basic, out) = (
storage(d, "bm3d y", planes, wgpu::BufferUsages::COPY_DST),
storage(d, "bm3d basic", planes, wgpu::BufferUsages::COPY_SRC),
storage(d, "bm3d out", planes, wgpu::BufferUsages::COPY_SRC),
);
let members = storage(d, "bm3d members", (groups * (GROUP + 1) * 4) as u64, wgpu::BufferUsages::empty());
let blocks = storage(d, "bm3d blocks", (groups * 4 * GROUP * BLOCK * BLOCK * 4) as u64, wgpu::BufferUsages::empty());
let weights = storage(d, "bm3d weights", (groups * 4 * 4) as u64, wgpu::BufferUsages::empty());
let uniform = |label| {
d.device.create_buffer(&wgpu::BufferDescriptor {
label: Some(label),
size: std::mem::size_of::<Uniforms>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
};
let (first, second) = (uniform("bm3d first step"), uniform("bm3d second step"));
let staging = d.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("bm3d readback"),
size: planes,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let bind = |layout: &wgpu::BindGroupLayout, buffers: &[&wgpu::Buffer]| {
let entries: Vec<wgpu::BindGroupEntry> =
buffers.iter().enumerate().map(|(i, b)| wgpu::BindGroupEntry { binding: i as u32, resource: b.as_entire_binding() }).collect();
d.device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout, entries: &entries })
};
let (m, c, a) = (&self.pipes.matching_layout, &self.pipes.collab_layout, &self.pipes.agg_layout);
let k = &self.consts;
let bound = [
bind(m, &[&first, k, &y, &members]),
// the first step's filter has no pilot: it is given a buffer it does not read
bind(c, &[&first, k, &y, &basic, &members, &blocks, &weights]),
bind(a, &[&first, k, &y, &members, &blocks, &weights, &basic]),
bind(m, &[&second, k, &basic, &members]),
bind(c, &[&second, k, &y, &basic, &members, &blocks, &weights]),
bind(a, &[&second, k, &y, &members, &blocks, &weights, &out]),
];
Workspace { y, basic, out, first, second, staging, bound, _slots: [members, blocks, weights] }
}
/// A free workspace, a new one when fewer than [`WORKSPACES`] exist, else wait for one to come back.
fn take(&self) -> Result<Workspace, Error> {
let mut free = self.free.lock().unwrap_or_else(|e| e.into_inner());
loop {
if let Some(w) = free.pop() {
return Ok(w);
}
{
let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
if *made < WORKSPACES {
*made += 1;
drop(made);
drop(free);
let d = self.dev;
let scopes =
[d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory), d.device.push_error_scope(wgpu::ErrorFilter::Validation)];
let w = self.workspace();
let [oom, validation] = scopes;
let (validation, oom) = (pollster::block_on(validation.pop()), pollster::block_on(oom.pop()));
if let Some(e) = oom.or(validation) {
self.forget();
return Err(Error::Runtime(format!("the GPU could not make room for another tile: {e}")));
}
return Ok(w);
}
}
free = self.wake.wait(free).unwrap_or_else(|e| e.into_inner());
}
}
/// A workspace comes back after a good run: it goes on the free list and one waiting caller is woken.
fn give(&self, w: Workspace) {
self.free.lock().unwrap_or_else(|e| e.into_inner()).push(w);
self.wake.notify_one();
}
/// A workspace is gone (dropped after a failure): room for a new one, and a waiting caller may make it.
fn forget(&self) {
// under `free`, as `take` is when it reads `made` and goes to wait: a wake-up sent between the two would be lost
let free = self.free.lock().unwrap_or_else(|e| e.into_inner());
let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
*made = made.saturating_sub(1);
drop(made);
drop(free);
self.wake.notify_one();
}
/// Denoise four unit-noise planes of `t × t` cells as [`bm3d::filter`] does; `noise` as there.
pub fn filter(&self, planes: &[Vec<f32>], t: usize, noise: f32) -> Result<Vec<Vec<f32>>, Error> {
if let Some(why) = crate::nn::broken_reason() {
return Err(Error::Runtime(format!("the GPU is not used any more: {why}")));
}
let Some(plan) = bm3d::plan(&self.requested, t, noise).filter(|_| t == self.t) else {
return Err(Error::Input("the tile is not the size the filter was made for".into()));
};
if planes.len() != 4 || planes.iter().any(|p| p.len() != t * t) {
return Err(Error::Input("the tile is not four square planes".into()));
}
let y = hadamard(planes);
// one tile is one piece of GPU work: a photo's worth would outlast any wait at exit
let Some(_work) = crate::exit::enter() else { return Err(Error::Runtime(CLOSING.into())) };
let w = self.take()?;
let flat: Vec<f32> = y.concat();
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.execute(&w, &flat, &plan))) {
Ok(Ok(out)) => {
self.give(w);
Ok(hadamard(&out.chunks_exact(t * t).map(<[f32]>::to_vec).collect::<Vec<_>>()))
}
Ok(Err(e)) => {
// its readback buffer may be left half-mapped: a fresh workspace is made when one is next needed
drop(w);
self.forget();
Err(e)
}
Err(_) => {
// a panic inside wgpu: this workspace is not given back, and the GPU is not used again
mark_broken("a denoise tile panicked");
drop(w);
self.forget();
Err(Error::Runtime("the GPU runner gave up".into()))
}
}
}
/// Run the filter's steps in `w` on the rotated planes `y` (one plane after another) and read the result back; a
/// device that runs out of memory or fails validation gives an error.
fn execute(&self, w: &Workspace, y: &[f32], plan: &bm3d::Plan) -> Result<Vec<f32>, Error> {
let d = self.dev;
let p = &plan.params;
let sigma = p.sigma.max(1e-3);
let var = sigma * sigma;
let uniforms = |tau: f32, wiener: u32| Uniforms {
t: self.t as u32,
nr: self.nr as u32,
nb: self.nb as u32,
search: p.search as u32,
cap: p.group as u32,
wiener,
pad0: 0,
pad1: 0,
tau,
lambda: plan.lambda * sigma,
sigma,
pad2: 0.0,
};
let groups = (self.nr * self.nr) as u32;
let cells = (self.t * self.t) as u32;
let scopes = [
d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory),
d.device.push_error_scope(wgpu::ErrorFilter::Validation),
d.device.push_error_scope(wgpu::ErrorFilter::Internal),
];
d.queue.write_buffer(&w.y, 0, bytemuck::cast_slice(y));
d.queue.write_buffer(&w.first, 0, bytemuck::bytes_of(&uniforms(p.tau1 * var, 0)));
d.queue.write_buffer(&w.second, 0, bytemuck::bytes_of(&uniforms(p.tau2 * var, 1)));
let mut enc = d.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
{
let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("bm3d tile"), timestamp_writes: None });
let steps = if p.wiener { 2 } else { 1 };
for step in 0..steps {
for (i, (pipe, count)) in
[(&self.pipes.matching, groups), (&self.pipes.collab, groups * 4), (&self.pipes.agg, cells)].into_iter().enumerate()
{
pass.set_pipeline(pipe);
pass.set_bind_group(0, w.bound.get(step * 3 + i), &[]);
pass.dispatch_workgroups(count.div_ceil(WORKGROUP), 1, 1);
}
}
}
let result = if p.wiener { &w.out } else { &w.basic };
let bytes = (y.len() * 4) as u64;
enc.copy_buffer_to_buffer(result, 0, &w.staging, 0, bytes);
d.queue.submit([enc.finish()]);
let slice = w.staging.slice(..bytes);
let (tx, rx) = std::sync::mpsc::channel();
slice.map_async(wgpu::MapMode::Read, move |r| {
let _ = tx.send(r);
});
let waited = d.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(TIMEOUT) });
let [oom, validation, internal] = scopes;
let errors = [pollster::block_on(internal.pop()), pollster::block_on(validation.pop()), pollster::block_on(oom.pop())];
let [internal, validation, oom] = errors;
if let Some(e) = oom {
// not a broken device: this tile runs on the CPU, and the next may fit
return Err(Error::Runtime(format!("the GPU ran out of memory: {e}")));
}
if let Some(e) = internal.or(validation) {
mark_broken(&format!("device error: {e}"));
return Err(Error::Runtime(format!("the GPU reported an error: {e}")));
}
if let Err(e) = waited {
mark_broken(&format!("the GPU did not finish a tile: {e}"));
return Err(Error::Runtime(format!("the GPU did not finish: {e}")));
}
match rx.recv_timeout(Duration::from_secs(10)) {
Ok(Ok(())) => {}
Ok(Err(e)) => return Err(Error::Runtime(format!("reading the result back failed: {e}"))),
Err(e) => return Err(Error::Runtime(format!("reading the result back failed: {e}"))),
}
let out = {
let data = slice.get_mapped_range().map_err(|e| Error::Runtime(format!("reading the result back failed: {e:?}")))?;
data.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect::<Vec<f32>>()
};
w.staging.unmap();
Ok(out)
}
}
/// The built-in denoiser with its filter on the GPU: a [`TileRunner`] for one photo (its noise level is in `builtin`).
pub struct BuiltinRunner {
gpu: Arc<Bm3dGpu>,
builtin: Builtin,
}
/// How close the card's filter is to the processor's on a tile, in the noise's deviations (the filter's own domain, where
/// the noise has deviation 1): the largest difference at one place and the mean one.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Agreement {
pub worst: f32,
pub mean: f32,
}
impl BuiltinRunner {
/// `builtin` must use the block-matching filter with the parameters `gpu` was made for.
pub fn new(gpu: Arc<Bm3dGpu>, builtin: Builtin) -> Result<Self, String> {
match builtin.bm3d_params() {
Some(p) if p == gpu.params() => Ok(BuiltinRunner { gpu, builtin }),
_ => Err("the settings of the built-in denoiser are not the ones the graphics card was set up for".into()),
}
}
/// The adapter it runs on.
pub fn adapter(&self) -> String {
self.gpu.adapter()
}
/// Run the filter of the tile `input` on the card and on the processor and say how far apart they are. The two
/// differ by the rounding of the card's arithmetic: a few blocks whose match or threshold falls either side of a
/// tie change a little (well under half a deviation), and a broken kernel by far more. (The final picture is not
/// compared: the demosaic's choice of direction at a pixel can flip on a tiny difference.)
pub fn agreement(&self, input: &[f32]) -> Result<Agreement, Error> {
let seen = std::cell::Cell::new(None);
self.builtin.run_with(input, &|planes, t, noise| {
let want = bm3d::filter(planes, t, &self.gpu.params(), noise);
let got = self.gpu.filter(planes, t, noise)?;
let (mut worst, mut sum, mut n) = (0f32, 0f64, 0usize);
for (a, b) in want.iter().flatten().zip(got.iter().flatten()) {
let d = (a - b).abs();
worst = if d.is_nan() { f32::INFINITY } else { worst.max(d) };
sum += f64::from(d);
n += 1;
}
seen.set(Some(Agreement { worst, mean: (sum / n.max(1) as f64) as f32 }));
Ok(got)
})?;
seen.get().ok_or_else(|| Error::Runtime("the filter was not run".into()))
}
}
impl TileRunner for BuiltinRunner {
/// Clean one tile with the built-in pipeline, its block-matching filter running on the card.
fn run(&self, input: &[f32]) -> Result<Vec<f32>, Error> {
self.builtin.run_with(input, &|planes, t, noise| self.gpu.filter(planes, t, noise))
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Four planes of `t × t` cells: edges, a ramp and some texture, plus unit noise (an LCG and Box-Muller).
fn scene(t: usize, seed: u64) -> Vec<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(|c| {
(0..t * t)
.map(|i| {
let (x, y) = ((i % t) as f32, (i / t) as f32);
let signal = 20.0
+ 0.1 * x
+ if (x as usize / 17 + y as usize / 23).is_multiple_of(2) { 6.0 } else { 0.0 }
+ 2.0 * ((x + 3.0 * c as f32) * 0.9).sin();
let (u, v) = (uniform(), uniform());
signal + (-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos()
})
.collect()
})
.collect()
}
/// The filter on the GPU, or `None` (with a note) on a machine with no usable GPU.
fn gpu(p: &Params, t: usize) -> Option<Bm3dGpu> {
match Bm3dGpu::new(p, t) {
Ok(g) => Some(g),
Err(e) => {
lightcraft_testkit::skip!(Gpu, "no GPU runner here ({e})");
None
}
}
}
/// The largest and the mean difference between two sets of planes.
fn differ(a: &[Vec<f32>], b: &[Vec<f32>]) -> (f32, f32) {
let (mut worst, mut sum, mut n) = (0f32, 0f64, 0usize);
for (x, y) in a.iter().flatten().zip(b.iter().flatten()) {
worst = worst.max((x - y).abs());
sum += f64::from((x - y).abs());
n += 1;
}
(worst, (sum / n.max(1) as f64) as f32)
}
/// At four tile sizes the card's result is finite and within 0.1 noise deviations of the processor's at worst, and
/// 1e-3 on average.
#[test]
fn the_gpu_gives_what_the_cpu_gives() {
let p = Params::default();
for (t, seed, noise) in [(32usize, 1u64, 0.003f32), (64, 2, 0.01), (100, 3, 0.04), (256, 4, 0.02)] {
let Some(g) = gpu(&p, t) else { return };
let planes = scene(t, seed);
let want = bm3d::filter(&planes, t, &p, noise);
let got = g.filter(&planes, t, noise).unwrap();
let (worst, mean) = differ(&got, &want);
eprintln!("{}: tile {t}, noise {noise}: worst {worst:e}, mean {mean:e} (noise deviation 1); {}", g.adapter(), g.build_report());
assert!(got.iter().flatten().all(|v| v.is_finite()));
assert!(mean < 1e-3 && worst < 0.1, "tile {t}: the GPU is off by {worst:e} at most and {mean:e} on average");
}
}
/// `forget` must change `made` under the `free` lock: a waiting `take` holds it from reading `made` until it sleeps, so
/// a slot given up in between cannot be announced to nobody (the waiter would sleep on a free slot for good).
#[test]
fn forgetting_a_workspace_waits_for_a_taker_that_is_about_to_sleep() {
let Some(g) = gpu(&Params::default(), 32) else { return };
let g = Arc::new(g);
let before = *g.made.lock().unwrap();
let held = g.free.lock().unwrap();
let other = g.clone();
let forgetter = std::thread::spawn(move || other.forget());
std::thread::sleep(std::time::Duration::from_millis(200));
assert_eq!(*g.made.lock().unwrap(), before, "forget changed the count while a taker held the free list");
drop(held);
forgetter.join().unwrap();
assert_eq!(*g.made.lock().unwrap(), before.saturating_sub(1));
}
/// One runner shared by four threads, each filtering several tiles, agrees with the processor on every one.
#[test]
fn a_runner_is_reusable_and_shared_between_threads() {
let p = Params::default();
let t = 48;
let Some(g) = gpu(&p, t) else { return };
let g = Arc::new(g);
let handles: Vec<_> = (0..4u64)
.map(|k| {
let g = g.clone();
std::thread::spawn(move || {
for round in 0..3 {
let planes = scene(t, 10 + k * 7 + round);
let want = bm3d::filter(&planes, t, &Params::default(), 0.01);
let got = g.filter(&planes, t, 0.01).unwrap();
let (worst, mean) = differ(&got, &want);
assert!(mean < 1e-3 && worst < 0.1, "thread {k}, round {round}: off by {worst:e} / {mean:e}");
}
})
})
.collect();
for h in handles {
h.join().unwrap();
}
}
/// Block or group sizes the kernels are not written for, and tiles too small or too big, are errors; so are a tile
/// or planes of the wrong size. NaN input does not panic, and a flat tile stays flat.
#[test]
fn what_the_kernels_do_not_do_is_an_error_and_odd_inputs_never_panic() {
// not the block or group size the kernels are written for, or too big a tile
assert!(Bm3dGpu::new(&Params { block: 6, ..Params::default() }, 64).is_err());
assert!(Bm3dGpu::new(&Params { group: 32, ..Params::default() }, 64).is_err());
assert!(Bm3dGpu::new(&Params::default(), 2).is_err());
assert!(Bm3dGpu::new(&Params::default(), 4096).is_err());
let Some(g) = gpu(&Params::default(), 32) else { return };
// a tile of another size, planes of the wrong size, numbers that are not finite
assert!(g.filter(&scene(40, 1), 40, 0.5).is_err());
assert!(g.filter(&scene(32, 1).into_iter().take(3).collect::<Vec<_>>(), 32, 0.5).is_err());
let nan = vec![vec![f32::NAN; 32 * 32]; 4];
let _ = g.filter(&nan, 32, f32::NAN);
let flat = vec![vec![5.0f32; 32 * 32]; 4];
let out = g.filter(&flat, 32, 0.5).unwrap();
assert!(out.iter().flatten().all(|v| (v - 5.0).abs() < 1e-3));
}
}
+2
View File
@@ -31,6 +31,8 @@ use lightcraft_raster::Rgb32f;
#[cfg(not(target_arch = "wasm32"))]
pub mod backend;
#[cfg(all(feature = "denoise", not(target_arch = "wasm32")))]
pub mod bm3d;
#[cfg(not(target_arch = "wasm32"))]
mod ctx;
#[cfg(not(target_arch = "wasm32"))]
+12 -12
View File
@@ -22,7 +22,7 @@ use lightcraft_denoise::run::{Error, TileRunner};
use wgpu::util::DeviceExt;
/// Longest wait for one tile's GPU work before the device is given up on.
const TIMEOUT: Duration = Duration::from_secs(60);
pub(crate) const TIMEOUT: Duration = Duration::from_secs(60);
/// The largest tile side (in input cells) the dispatch sizes and 32-bit indexing are checked for.
const MAX_TILE: usize = 1024;
/// The largest single buffer used: indices in the kernels are 32-bit element offsets.
@@ -33,18 +33,18 @@ const WORKSPACES: usize = 2;
// ---------------------------------------------------------------------------------------------------------------------
// the device
struct Dev {
device: wgpu::Device,
queue: wgpu::Queue,
info: wgpu::AdapterInfo,
limits: wgpu::Limits,
pub(crate) struct Dev {
pub(crate) device: wgpu::Device,
pub(crate) queue: wgpu::Queue,
pub(crate) info: wgpu::AdapterInfo,
pub(crate) limits: wgpu::Limits,
}
static DEV: OnceLock<Result<Dev, String>> = OnceLock::new();
static BROKEN: AtomicBool = AtomicBool::new(false);
static BROKEN_WHY: Mutex<Option<String>> = Mutex::new(None);
fn mark_broken(why: &str) {
pub(crate) fn mark_broken(why: &str) {
let mut w = BROKEN_WHY.lock().unwrap_or_else(|e| e.into_inner());
if w.is_none() {
*w = Some(why.to_string());
@@ -57,7 +57,7 @@ pub fn broken_reason() -> Option<String> {
BROKEN.load(Ordering::Relaxed).then(|| BROKEN_WHY.lock().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_else(|| "device error".into()))
}
fn dev() -> Result<&'static Dev, String> {
pub(crate) fn dev() -> Result<&'static Dev, String> {
if let Some(why) = broken_reason() {
return Err(format!("stopped after a GPU failure: {why}"));
}
@@ -73,7 +73,7 @@ fn dev() -> Result<&'static Dev, String> {
}
/// Why nothing runs on the GPU once [`crate::begin_shutdown`] was called.
const CLOSING: &str = "LightCraft is closing";
pub(crate) const CLOSING: &str = "LightCraft is closing";
fn create_device() -> Result<Dev, String> {
let Some(backends) = crate::backend::compute_backends() else { return Err("disabled by LIGHTCRAFT_GPU_BACKEND=off".into()) };
@@ -480,7 +480,7 @@ struct Pipelines {
built: Vec<(String, f64)>,
}
fn entry(binding: u32, ty: wgpu::BufferBindingType) -> wgpu::BindGroupLayoutEntry {
pub(crate) fn entry(binding: u32, ty: wgpu::BufferBindingType) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::COMPUTE,
@@ -489,7 +489,7 @@ fn entry(binding: u32, ty: wgpu::BufferBindingType) -> wgpu::BindGroupLayoutEntr
}
}
fn pipeline(d: &Dev, label: &str, src: &str, layout: &wgpu::BindGroupLayout) -> wgpu::ComputePipeline {
pub(crate) fn pipeline(d: &Dev, label: &str, src: &str, layout: &wgpu::BindGroupLayout) -> wgpu::ComputePipeline {
let module = d.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(src.into()) });
let pl = d.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(layout)], immediate_size: 0 });
d.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
@@ -574,7 +574,7 @@ struct Shared {
dummy: wgpu::Buffer,
}
fn storage(d: &Dev, label: &str, bytes: u64, extra: wgpu::BufferUsages) -> wgpu::Buffer {
pub(crate) fn storage(d: &Dev, label: &str, bytes: u64, extra: wgpu::BufferUsages) -> wgpu::Buffer {
d.device.create_buffer(&wgpu::BufferDescriptor {
label: Some(label),
size: bytes.max(16),
+86
View File
@@ -0,0 +1,86 @@
// Putting the filtered blocks back: every cell becomes the weighted average of the filtered blocks that cover it, added
// in the order the reference adds them (groups in raster order, a group's blocks in order), so no two invocations
// write the same cell. One invocation per cell, all four planes.
@group(0) @binding(2) var<storage, read> y: array<f32>;
@group(0) @binding(3) var<storage, read> members: array<u32>;
@group(0) @binding(4) var<storage, read> blocks: array<f32>;
@group(0) @binding(5) var<storage, read> weights: array<f32>;
@group(0) @binding(6) var<storage, read_write> dst: array<f32>;
// The first group start that is at least `v`.
fn lower_bound(v: u32) -> u32 {
var lo = 0u;
var hi = p.nr;
while (lo < hi) {
let mid = (lo + hi) / 2u;
if (axis(mid) < v) {
lo = mid + 1u;
} else {
hi = mid;
}
}
return lo;
}
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let g = gid.x;
let t = p.t;
if (g >= t * t) {
return;
}
let cx = g % t;
let cy = g / t;
// a group's blocks lie within `search` of its start and are N wide: only these starts can reach this cell
let reach = p.search + N - 1u;
var xlo = 0u;
if (cx >= reach) {
xlo = cx - reach;
}
var ylo = 0u;
if (cy >= reach) {
ylo = cy - reach;
}
var num: array<f32, 4>;
var den: array<f32, 4>;
for (var ch = 0u; ch < 4u; ch = ch + 1u) {
num[ch] = 0.0;
den[ch] = 0.0;
}
for (var rj = lower_bound(ylo); rj < p.nr; rj = rj + 1u) {
if (axis(rj) > cy + p.search) {
break;
}
for (var ri = lower_bound(xlo); ri < p.nr; ri = ri + 1u) {
if (axis(ri) > cx + p.search) {
break;
}
let rf = rj * p.nr + ri;
let m = members[rf * STRIDE];
for (var i = 0u; i < m; i = i + 1u) {
let pos = members[rf * STRIDE + 1u + i];
let px = pos % t;
let py = pos / t;
if (px <= cx && cx < px + N && py <= cy && cy < py + N) {
let cell = (cy - py) * N + (cx - px);
let w = win(cell);
for (var ch = 0u; ch < 4u; ch = ch + 1u) {
let ww = weights[rf * 4u + ch] * w;
num[ch] = num[ch] + ww * blocks[((rf * 4u + ch) * K + i) * NN + cell];
den[ch] = den[ch] + ww;
}
}
}
}
}
// cells no block reached keep their value
for (var ch = 0u; ch < 4u; ch = ch + 1u) {
let own = y[ch * t * t + g];
if (den[ch] > 0.0) {
dst[ch * t * t + g] = num[ch] / den[ch];
} else {
dst[ch * t * t + g] = own;
}
}
}
+76
View File
@@ -0,0 +1,76 @@
// Collaborative filtering of one group of one plane: the blocks are stacked, transformed (a 2-D DCT of each block, a
// Haar transform across the stack), shrunk (a hard threshold, or a Wiener filter built from the pilot) and transformed
// back. One invocation per group and plane; the filtered blocks and the group's weight are stored for the aggregation.
// (The transforms come from bm3d_transform.wgsl: `buf` is the noisy group, `pb` the pilot's.)
@group(0) @binding(2) var<storage, read> y: array<f32>;
@group(0) @binding(3) var<storage, read> pilot: array<f32>;
@group(0) @binding(4) var<storage, read> members: array<u32>;
@group(0) @binding(5) var<storage, read_write> blocks: array<f32>;
@group(0) @binding(6) var<storage, read_write> weights: array<f32>;
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let g = gid.x;
if (g >= p.nr * p.nr * 4u) {
return;
}
let rf = g / 4u;
let ch = g % 4u;
let t = p.t;
let m = members[rf * STRIDE];
for (var i = 0u; i < m; i = i + 1u) {
let pos = members[rf * STRIDE + 1u + i];
for (var j = 0u; j < N; j = j + 1u) {
for (var c = 0u; c < N; c = c + 1u) {
buf[i * NN + j * N + c] = y[ch * t * t + pos + j * t + c];
}
}
}
for (var i = 0u; i < m; i = i + 1u) {
dct_fwd(i * NN);
}
haar(m, true);
var weight = 1.0;
if (p.wiener == 0u) {
var kept = 0u;
for (var k = 0u; k < m * NN; k = k + 1u) {
if (abs(buf[k]) < p.lambda) {
buf[k] = 0.0;
} else {
kept = kept + 1u;
}
}
weight = 1.0 / f32(max(kept, 1u));
} else {
for (var i = 0u; i < m; i = i + 1u) {
let pos = members[rf * STRIDE + 1u + i];
for (var j = 0u; j < N; j = j + 1u) {
for (var c = 0u; c < N; c = c + 1u) {
pb[i * NN + j * N + c] = pilot[ch * t * t + pos + j * t + c];
}
}
}
for (var i = 0u; i < m; i = i + 1u) {
dct_fwd_p(i * NN);
}
haar_p(m, true);
var energy = 0.0;
for (var k = 0u; k < m * NN; k = k + 1u) {
let q = pb[k];
let w = q * q / (q * q + p.sigma * p.sigma);
buf[k] = buf[k] * w;
energy = energy + w * w;
}
weight = 1.0 / max(energy, 1e-3);
}
haar(m, false);
for (var i = 0u; i < m; i = i + 1u) {
dct_inv(i * NN);
}
let base = (rf * 4u + ch) * K * NN;
for (var k = 0u; k < m * NN; k = k + 1u) {
blocks[base + k] = buf[k];
}
weights[rf * 4u + ch] = weight;
}
+41
View File
@@ -0,0 +1,41 @@
// Block-matching collaborative filtering of one tile: the shared part of the three kernels. The reference is
// crates/denoise-core/src/bm3d.rs (the same steps in the same order, so the two agree to rounding): 4 x 4-cell blocks,
// groups of at most 16, planes of `t x t` cells with 4 planes one after the other.
struct P {
t: u32, // cells on a side of a plane
nr: u32, // blocks that start a group, along a side
nb: u32, // blocks along a side (t - 3)
search: u32, // how far a match is looked for, in cells
cap: u32, // most blocks in a group (at most 16)
wiener: u32, // 0: hard threshold, 1: Wiener shrinkage by the pilot
pad0: u32,
pad1: u32,
tau: f32, // how far above the noise two blocks may differ (mean square) and be grouped
lambda: f32, // hard threshold (already scaled by the noise's deviation)
sigma: f32, // the noise's deviation
pad2: f32,
}
@group(0) @binding(0) var<uniform> p: P;
// [0, 16): the DCT matrix, [16, 32): the window (both f32 bits), [32, ..): where the blocks that start a group are
@group(0) @binding(1) var<storage, read> consts: array<u32>;
const N: u32 = 4u;
const NN: u32 = 16u;
const K: u32 = 16u;
// a group's entry in `members`: its size, then its blocks' top-left cells
const STRIDE: u32 = 17u;
const INV_SQRT2: f32 = 0.70710677;
fn axis(i: u32) -> u32 {
return consts[32u + i];
}
fn dct(i: u32) -> f32 {
return bitcast<f32>(consts[i]);
}
fn win(i: u32) -> f32 {
return bitcast<f32>(consts[16u + i]);
}
+79
View File
@@ -0,0 +1,79 @@
// Grouping: for every block that starts a group, its nearest blocks (itself first) within the search window, nearest
// first, at most `cap` and at most `tau` away, cut to a power of two. One invocation per group.
@group(0) @binding(2) var<storage, read> src: array<f32>;
@group(0) @binding(3) var<storage, read_write> members: array<u32>;
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let g = gid.x;
if (g >= p.nr * p.nr) {
return;
}
let t = p.t;
let rx = axis(g % p.nr);
let ry = axis(g / p.nr);
var dist: array<f32, 17>;
var pos: array<u32, 17>;
var len = 1u;
dist[0] = 0.0;
pos[0] = ry * t + rx;
let r = i32(p.search);
let nb = i32(p.nb);
for (var oy = -r; oy <= r; oy = oy + 1) {
let by = i32(ry) + oy;
if (by < 0 || by >= nb) {
continue;
}
for (var ox = -r; ox <= r; ox = ox + 1) {
if (ox == 0 && oy == 0) {
continue;
}
let bx = i32(rx) + ox;
if (bx < 0 || bx >= nb) {
continue;
}
// the sum of squared differences, along each row and then down the rows, as the reference adds them
var s = 0.0;
for (var j = 0u; j < N; j = j + 1u) {
var h = 0.0;
let a0 = (ry + j) * t + rx;
let b0 = (u32(by) + j) * t + u32(bx);
for (var i = 0u; i < N; i = i + 1u) {
let d = src[a0 + i] - src[b0 + i];
h = h + d * d;
}
s = s + h;
}
s = s * 0.0625;
if (!(s <= p.tau)) {
continue;
}
if (len >= p.cap && s >= dist[len - 1u]) {
continue;
}
// after every block at most as far away, as the reference's ordered insert does
var at = 0u;
while (at < len && dist[at] <= s) {
at = at + 1u;
}
var k = len;
while (k > at) {
dist[k] = dist[k - 1u];
pos[k] = pos[k - 1u];
k = k - 1u;
}
dist[at] = s;
pos[at] = u32(by) * t + u32(bx);
len = min(len + 1u, p.cap);
}
}
var m = 1u;
while (m * 2u <= len) {
m = m * 2u;
}
members[g * STRIDE] = m;
for (var i = 0u; i < m; i = i + 1u) {
members[g * STRIDE + 1u + i] = pos[i];
}
}
+97
View File
@@ -0,0 +1,97 @@
// The transforms of one group, on the module-scope array `{{A}}` (the shader is built once for the noisy blocks and once
// for the pilot's). The arrays are not passed to functions: FXC (DX12) cannot index an array it is handed by reference
// without unrolling every loop.
var<private> {{A}}: array<f32, 256>;
fn dct_fwd{{S}}(base: u32) {
var tmp: array<f32, 16>;
for (var k = 0u; k < N; k = k + 1u) {
for (var j = 0u; j < N; j = j + 1u) {
var s = 0.0;
for (var i = 0u; i < N; i = i + 1u) {
s = s + dct(k * N + i) * {{A}}[base + i * N + j];
}
tmp[k * N + j] = s;
}
}
for (var k = 0u; k < N; k = k + 1u) {
for (var l = 0u; l < N; l = l + 1u) {
var s = 0.0;
for (var j = 0u; j < N; j = j + 1u) {
s = s + tmp[k * N + j] * dct(l * N + j);
}
{{A}}[base + k * N + l] = s;
}
}
}
fn dct_inv{{S}}(base: u32) {
var tmp: array<f32, 16>;
for (var i = 0u; i < N; i = i + 1u) {
for (var l = 0u; l < N; l = l + 1u) {
var s = 0.0;
for (var k = 0u; k < N; k = k + 1u) {
s = s + dct(k * N + i) * {{A}}[base + k * N + l];
}
tmp[i * N + l] = s;
}
}
for (var i = 0u; i < N; i = i + 1u) {
for (var j = 0u; j < N; j = j + 1u) {
var s = 0.0;
for (var l = 0u; l < N; l = l + 1u) {
s = s + tmp[i * N + l] * dct(l * N + j);
}
{{A}}[base + i * N + j] = s;
}
}
}
// The Haar transform across the `m` blocks (m is a power of two), at each of the 16 positions of a block.
fn haar{{S}}(m: u32, forward: bool) {
if (m < 2u) {
return;
}
var col: array<f32, 16>;
var tmp: array<f32, 16>;
for (var k = 0u; k < NN; k = k + 1u) {
for (var i = 0u; i < m; i = i + 1u) {
col[i] = {{A}}[i * NN + k];
}
if (forward) {
var len = m;
while (len > 1u) {
let half = len / 2u;
for (var i = 0u; i < half; i = i + 1u) {
let a = col[2u * i];
let c = col[2u * i + 1u];
tmp[i] = (a + c) * INV_SQRT2;
tmp[half + i] = (a - c) * INV_SQRT2;
}
for (var i = 0u; i < len; i = i + 1u) {
col[i] = tmp[i];
}
len = half;
}
} else {
var len = 2u;
while (len <= m) {
let half = len / 2u;
for (var i = 0u; i < half; i = i + 1u) {
let avg = col[i];
let det = col[half + i];
tmp[2u * i] = (avg + det) * INV_SQRT2;
tmp[2u * i + 1u] = (avg - det) * INV_SQRT2;
}
for (var i = 0u; i < len; i = i + 1u) {
col[i] = tmp[i];
}
len = len * 2u;
}
}
for (var i = 0u; i < m; i = i + 1u) {
{{A}}[i * NN + k] = col[i];
}
}
}
+2 -1
View File
@@ -53,7 +53,8 @@ fn check_v3_luminance_cutoff(chroma: f32, pixel: [f32; 3], expected: [u8; 4]) {
let cpu = render(&src, &info, &s, &req).image;
let gpu = lightcraft_gpu::try_render(&src, &info, &s, &req, None).expect("GPU render without CPU fallback").image;
for image in [&cpu, &gpu] {
assert!(image.data.iter().all(|p| *p == image.data[0]));
// (8-bit output is dithered: a flat source varies by a level)
assert!(image.data.iter().all(|p| p.iter().zip(image.data[0]).all(|(a, b)| a.abs_diff(b) <= 1)));
for (actual, expected) in image.data[0].into_iter().zip(expected) {
assert!(actual.abs_diff(expected) <= 1, "chroma {chroma}: {:?}, expected {expected}", image.data[0]);
}
+7 -2
View File
@@ -108,6 +108,11 @@ fn luma(img: &Rgba8, i: usize) -> f64 {
(p[0] as f64 + p[1] as f64 + p[2] as f64) / 3.0
}
/// A difference between two renders, without the one level of 8-bit dither any pixel can differ by.
fn above_dither(d: f64) -> f64 {
(d - 1.5).max(0.0)
}
fn centroid(w: usize, weights: impl Iterator<Item = f64>) -> (f64, f64) {
let (mut sx, mut sy, mut n) = (0.0, 0.0, 0.0);
for (i, v) in weights.enumerate() {
@@ -140,9 +145,9 @@ fn masks_stay_on_the_content_under_every_geometry_change_on_the_gpu() {
let plain = on_gpu(&src, &unmasked, None);
// (where the marked photo differs from an unmarked one: a warp leaves light blank canvas)
let bare = on_gpu(&Arc::new(marked(false)), &unmasked, None);
let mark = centroid(plain.width, (0..plain.data.len()).map(|i| (luma(&plain, i) - luma(&bare, i)).max(0.0)));
let mark = centroid(plain.width, (0..plain.data.len()).map(|i| above_dither(luma(&plain, i) - luma(&bare, i))));
for (how, m) in [("fresh", on_gpu(&src, &s, None)), ("cached", on_gpu(&src, &s, Some(&cache)))] {
let at = centroid(m.width, (0..m.data.len()).map(|i| (luma(&m, i) - luma(&plain, i)).max(0.0)));
let at = centroid(m.width, (0..m.data.len()).map(|i| above_dither(luma(&m, i) - luma(&plain, i))));
let d = ((at.0 - mark.0).powi(2) + (at.1 - mark.1).powi(2)).sqrt();
assert!(d < 2.0, "{name} after {what} ({how}): the mask's effect is at {at:?}, the mark at {mark:?}");
}
+11
View File
@@ -46,6 +46,14 @@ fn pos(v: Option<f64>) -> Option<f64> {
v.filter(|x| x.is_finite() && *x > 0.0)
}
/// The orientation the Exif's own first IFD states. [`from_tiff`] also reports one that only the XMP packet in
/// the Exif's tag 700 states; LightCraft displays a photo by the Exif's alone, so that one can't tell how a photo
/// is stored.
pub(crate) fn ifd0_orientation(bytes: &[u8]) -> Option<Orientation> {
let tiff = Tiff::parse_with(strip_exif_header(bytes), &ParseOptions::default()).ok()?;
tiff.ifds.first().and_then(|i| i.u16(t::ORIENTATION)).filter(|v| (1..=8).contains(v)).map(Orientation::from_exif)
}
/// Build [`Metadata`] from a parsed TIFF stream (IFD0 + Exif + GPS; DNG tags as fallbacks).
pub fn from_tiff(tiff: &Tiff) -> Metadata {
let ifd0 = tiff.ifds.first();
@@ -129,8 +137,11 @@ pub fn from_tiff(tiff: &Tiff) -> Metadata {
if let Some(x) = ifd0.and_then(|i| i.bytes(t::XMP)).map(String::from_utf8_lossy)
&& let Ok(x) = crate::parse_xmp(&x)
{
// (the size stays the one Exif states: `extract` turns regions by it, and a size only the XMP states may be the upright one)
let size = (m.width, m.height);
m.overlay_user_fields(&x.metadata);
m.fill_missing(&x.metadata);
(m.width, m.height) = size;
}
m
}
+207 -6
View File
@@ -296,7 +296,7 @@ impl Metadata {
pub fn extract(bytes: &[u8]) -> Metadata {
let e = embedded(bytes);
let exif = e.exif.as_deref().map(read_exif).unwrap_or_default();
let xmp = e.xmp.as_deref().and_then(|xmp| parse_xmp(xmp).ok()).map(|xmp| xmp.metadata);
let xmp = e.xmp.as_deref().and_then(|xmp| parse_xmp(xmp).ok());
extract_embedded(e, exif, xmp)
}
@@ -311,24 +311,51 @@ pub fn try_extract(bytes: &[u8]) -> Result<Metadata, ExtractError> {
None => Metadata::default(),
};
let xmp = match e.xmp.as_deref() {
Some(xmp) if is_psd => Some(parse_xmp(xmp).map_err(|_| ExtractError::MalformedPsd)?.metadata),
Some(xmp) => parse_xmp(xmp).ok().map(|xmp| xmp.metadata),
Some(xmp) if is_psd => Some(parse_xmp(xmp).map_err(|_| ExtractError::MalformedPsd)?),
Some(xmp) => parse_xmp(xmp).ok(),
None => None,
};
Ok(extract_embedded(e, exif, xmp))
}
fn extract_embedded(e: Embedded, mut m: Metadata, xmp: Option<Metadata>) -> Metadata {
fn extract_embedded(e: Embedded, mut m: Metadata, xmp: Option<XmpData>) -> Metadata {
// the size the Exif states: a size only the XMP states may be the upright one, so it can't tell how the photo is stored
let stored = m.width.zip(m.height);
// and the orientation the Exif states: the photo is displayed by that alone, so an orientation only the XMP
// states ([`Metadata::fill_missing`] reports it below) can't tell how the photo is stored either
let exif_orientation = e.exif.as_deref().and_then(exif::ifd0_orientation);
if let Some(i) = e.iptc.as_deref() {
m.fill_missing(&parse_iptc(i));
}
if let Some(xmp) = xmp {
m.overlay_user_fields(&xmp);
m.fill_missing(&xmp);
m.overlay_user_fields(&xmp.metadata);
m.fill_missing(&xmp.metadata);
// boxes another app drew on the photo as stored go where the upright photo has them (#2674)
if let (Some(drawn_on), Some(orientation), Some(stored)) = (xmp.regions_drawn_on(), exif_orientation, stored) {
upright_regions(&mut m.regions, drawn_on, orientation, stored);
}
}
m
}
/// Turn regions drawn on a photo as it is stored onto the upright photo. MWG gives each box as a fraction of
/// `AppliedToDimensions` (`drawn_on`); for a photo whose Exif `orientation` turns it a quarter turn, some apps give the
/// stored, sideways size there and boxes on the stored pixels to match (Lightroom says so per box with
/// `mwg-rs:Rotation` instead, which [`parse_xmp`] reads). When `drawn_on` has the shape of the photo as stored
/// (`stored`, before `orientation`) rather than the upright one, every box is turned with `orientation`. Returns
/// whether they were. A square photo or `drawn_on` looks the same both ways, and a half turn or a mirror doesn't
/// change the shape: their boxes are left as they are.
pub fn upright_regions(regions: &mut [Region], drawn_on: (f64, f64), orientation: Orientation, stored: (u32, u32)) -> bool {
let ((dw, dh), (sw, sh)) = (drawn_on, stored);
if regions.is_empty() || !orientation.swaps_axes() || sw == sh || dw == dh || (dw > dh) != (sw > sh) {
return false;
}
for r in regions.iter_mut() {
r.rect = orientation.map_norm_rect(r.rect);
}
true
}
/// A container-level error reported by [`try_extract`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExtractError {
@@ -463,4 +490,178 @@ mod tests {
assert_eq!(m.metering_name(), Some("Pattern"));
assert_eq!(m.exposure_program_name(), Some("Aperture-priority AE"));
}
/// An MWG regions packet with one face, its box centred at (0.25, 0.4) and 0.1 × 0.15 of `AppliedToDimensions`
/// `w` × `h`; `extra` goes on the region (e.g. Lightroom's `mwg-rs:Rotation`).
fn regions_packet(w: u32, h: u32, extra: &str) -> String {
format!(
r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about="" xmlns:mwg-rs="http://www.metadataworkinggroup.com/schemas/regions/"
xmlns:stArea="http://ns.adobe.com/xmp/sType/Area#" xmlns:stDim="http://ns.adobe.com/xap/1.0/sType/Dimensions#">
<mwg-rs:Regions rdf:parseType="Resource">
<mwg-rs:AppliedToDimensions rdf:parseType="Resource" stDim:w="{w}" stDim:h="{h}" stDim:unit="pixel"/>
<mwg-rs:RegionList><rdf:Bag>
<rdf:li rdf:parseType="Resource" mwg-rs:Name="Hannah" mwg-rs:Type="Face"{extra}>
<mwg-rs:Area rdf:parseType="Resource" stArea:x="0.25" stArea:y="0.4" stArea:w="0.1" stArea:h="0.15" stArea:unit="normalized"/>
</rdf:li>
</rdf:Bag></mwg-rs:RegionList>
</mwg-rs:Regions>
</rdf:Description></rdf:RDF></x:xmpmeta>"#
)
}
fn near(r: Rect, b: [f64; 4]) -> bool {
[r.x0 - b[0], r.y0 - b[1], r.x1 - b[2], r.y1 - b[3]].iter().all(|d| d.abs() < 1e-9)
}
/// The face's box as drawn: on the photo as stored, or on the upright one by apps that draw there.
const DRAWN: [f64; 4] = [0.2, 0.325, 0.3, 0.475];
/// The same box on the photo turned upright by Exif orientation 6 (a quarter turn clockwise).
const TURNED_6: [f64; 4] = [0.525, 0.2, 0.675, 0.3];
#[test]
fn boxes_drawn_on_the_stored_photo_turn_with_its_orientation() {
let region = || Region {
rect: Rect { x0: DRAWN[0], y0: DRAWN[1], x1: DRAWN[2], y1: DRAWN[3] },
kind: RegionKind::Face,
name: None,
description: None,
};
let turned = |o: Orientation, drawn_on: (f64, f64), stored: (u32, u32)| {
let mut regions = [region()];
let did = upright_regions(&mut regions, drawn_on, o, stored);
(did, regions[0].rect)
};
// drawn on the 6000 × 4000 photo as stored: every quarter turn and its mirror image land elsewhere
for (o, want) in [
(Orientation::Rotate90, TURNED_6),
(Orientation::Rotate270, [0.325, 0.7, 0.475, 0.8]),
(Orientation::Transpose, [0.325, 0.2, 0.475, 0.3]),
(Orientation::Transverse, [0.525, 0.7, 0.675, 0.8]),
] {
let (did, r) = turned(o, (6000.0, 4000.0), (6000, 4000));
assert!(did && near(r, want), "{o:?}: {r:?}");
// a smaller copy of the photo as stored is the same frame
assert!(near(turned(o, (1500.0, 1000.0), (6000, 4000)).1, want), "{o:?} on a smaller size");
}
// drawn on the upright photo (MWG's own frame), or where the shape can't tell the two apart: as they are
for (o, drawn_on, stored) in [
(Orientation::Rotate90, (4000.0, 6000.0), (6000, 4000)),
(Orientation::Rotate90, (4000.0, 4000.0), (6000, 4000)),
(Orientation::Rotate90, (4000.0, 4000.0), (4000, 4000)),
(Orientation::Rotate180, (6000.0, 4000.0), (6000, 4000)),
(Orientation::FlipH, (6000.0, 4000.0), (6000, 4000)),
(Orientation::Normal, (6000.0, 4000.0), (6000, 4000)),
] {
let (did, r) = turned(o, drawn_on, stored);
assert!(!did && near(r, DRAWN), "{o:?} drawn on {drawn_on:?} of {stored:?}: {r:?}");
}
}
/// Issue #2674: an app that doesn't say how the photo was turned (no `mwg-rs:Rotation`) drew the faces of a photo
/// with Exif orientation 6 on its stored pixels, with the stored 6000 × 4000 as `AppliedToDimensions`. The boxes
/// land on the faces of the upright photo, not where the stored photo had them.
#[test]
fn regions_drawn_on_the_stored_photo_are_read_onto_the_upright_one() {
let jpeg = |packet: &str| {
let mut j = vec![0xff, 0xd8];
let mut seg = |payload: Vec<u8>| {
j.extend([0xff, 0xe1]);
j.extend(u16::try_from(payload.len() + 2).unwrap().to_be_bytes());
j.extend(payload);
};
// orientation 6, 6000 × 4000 as stored
seg([b"Exif\0\0".as_slice(), &crate::exif::tests::sample_exif(lightcraft_tiff::ByteOrder::Little)].concat());
seg([b"http://ns.adobe.com/xap/1.0/\0".as_slice(), packet.as_bytes()].concat());
j.extend([0xff, 0xd9]);
j
};
let read = |packet: &str| {
let m = extract(&jpeg(packet));
assert_eq!((m.orientation, m.width, m.height), (Some(Orientation::Rotate90), Some(6000), Some(4000)));
assert_eq!(try_extract(&jpeg(packet)).unwrap().regions, m.regions);
assert_eq!(m.regions.len(), 1);
m.regions[0].rect
};
let stored = read(&regions_packet(6000, 4000, ""));
assert!(near(stored, TURNED_6), "drawn on the photo as stored: {stored:?}");
let upright = read(&regions_packet(4000, 6000, ""));
assert!(near(upright, DRAWN), "drawn on the upright photo, MWG's way: {upright:?}");
// Lightroom's boxes say how the photo was turned: turned once, by that
let lightroom = read(&regions_packet(6000, 4000, r#" mwg-rs:Rotation="-1.57080""#));
assert!(near(lightroom, TURNED_6), "Lightroom's −π/2: {lightroom:?}");
}
/// A size only the XMP states can't tell how the photo is stored: `tiff:ImageWidth` and `tiff:ImageLength` of the
/// upright photo have the shape of boxes drawn on it upright, and those must not be turned.
#[test]
fn a_size_only_the_xmp_states_turns_no_regions() {
// orientation 6, no pixel size
let exif = write_exif(&Metadata { orientation: Some(Orientation::Rotate90), ..Default::default() });
let exif = strip_exif_header(&exif);
let packet = regions_packet(4000, 6000, "")
.replace(r#"rdf:about="""#, r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:ImageWidth="4000" tiff:ImageLength="6000""#);
let mut j = vec![0xff, 0xd8];
let mut seg = |payload: Vec<u8>| {
j.extend([0xff, 0xe1]);
j.extend(u16::try_from(payload.len() + 2).unwrap().to_be_bytes());
j.extend(payload);
};
seg([b"Exif\0\0".as_slice(), exif].concat());
seg([b"http://ns.adobe.com/xap/1.0/\0".as_slice(), packet.as_bytes()].concat());
j.extend([0xff, 0xd9]);
let m = extract(&j);
assert_eq!((m.orientation, m.width, m.height), (Some(Orientation::Rotate90), Some(4000), Some(6000)));
assert_eq!(m.regions.len(), 1);
assert!(near(m.regions[0].rect, DRAWN), "{:?}", m.regions[0].rect);
assert_eq!(try_extract(&j).unwrap().regions, m.regions);
// a TIFF-based file: the whole file is the Exif block, with the XMP in its first IFD
let mut ifd0 = lightcraft_tiff::IfdBuilder::new();
ifd0.set(lightcraft_tiff::tags::ORIENTATION, lightcraft_tiff::Value::Short(vec![6]));
ifd0.set(lightcraft_tiff::tags::XMP, lightcraft_tiff::Value::Byte(packet.into_bytes()));
let m = extract(&lightcraft_tiff::TiffWriter::default().write(&[ifd0]).unwrap());
assert_eq!((m.orientation, m.width, m.height), (Some(Orientation::Rotate90), Some(4000), Some(6000)));
assert!(near(m.regions[0].rect, DRAWN), "TIFF: {:?}", m.regions[0].rect);
}
/// A photo whose Exif has a size but no orientation, and whose XMP says `tiff:Orientation=6`: LightCraft
/// displays it by the Exif alone, so it stays as stored, and boxes drawn on that stored frame are right as
/// written. Turning them by an orientation only the XMP states put them where the photo isn't (review of #2857).
#[test]
fn an_orientation_only_the_xmp_states_turns_no_regions() {
// 6000 × 4000 in the Exif, and no orientation
let size_ifd = || {
let mut sub = lightcraft_tiff::IfdBuilder::new();
sub.set(lightcraft_tiff::tags::PIXEL_X_DIMENSION, lightcraft_tiff::Value::Long(vec![6000]));
sub.set(lightcraft_tiff::tags::PIXEL_Y_DIMENSION, lightcraft_tiff::Value::Long(vec![4000]));
sub
};
let mut exif_ifd0 = lightcraft_tiff::IfdBuilder::new();
exif_ifd0.set_child(lightcraft_tiff::tags::EXIF_IFD, size_ifd());
let exif = lightcraft_tiff::TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[exif_ifd0]).unwrap();
let packet = regions_packet(6000, 4000, "")
.replace(r#"rdf:about="""#, r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:Orientation="6""#);
let mut j = vec![0xff, 0xd8];
let mut seg = |payload: Vec<u8>| {
j.extend([0xff, 0xe1]);
j.extend(u16::try_from(payload.len() + 2).unwrap().to_be_bytes());
j.extend(payload);
};
seg([b"Exif\0\0".as_slice(), &exif].concat());
seg([b"http://ns.adobe.com/xap/1.0/\0".as_slice(), packet.as_bytes()].concat());
j.extend([0xff, 0xd9]);
let m = extract(&j);
assert_eq!((m.width, m.height), (Some(6000), Some(4000)));
assert_eq!(m.orientation, Some(Orientation::Rotate90), "the XMP's orientation is still reported");
assert_eq!(m.regions.len(), 1);
assert!(near(m.regions[0].rect, DRAWN), "turned by an orientation the Exif doesn't state: {:?}", m.regions[0].rect);
assert_eq!(try_extract(&j).unwrap().regions, m.regions);
// a TIFF-based file: the first IFD has no orientation, its XMP (tag 700) has
let mut ifd0 = lightcraft_tiff::IfdBuilder::new();
ifd0.set(lightcraft_tiff::tags::XMP, lightcraft_tiff::Value::Byte(packet.into_bytes()));
ifd0.set_child(lightcraft_tiff::tags::EXIF_IFD, size_ifd());
let m = extract(&lightcraft_tiff::TiffWriter::default().write(&[ifd0]).unwrap());
assert_eq!(m.orientation, Some(Orientation::Rotate90));
assert!(near(m.regions[0].rect, DRAWN), "TIFF: {:?}", m.regions[0].rect);
}
}
+21 -5
View File
@@ -77,6 +77,17 @@ pub struct XmpData {
pub values: BTreeMap<String, XmpValue>,
}
impl XmpData {
/// The pixel size the packet's regions were drawn on (`mwg-rs:AppliedToDimensions`), unless one of them says how
/// the photo was turned (`mwg-rs:Rotation`: Lightroom's boxes, which the reader already turns upright). It tells
/// boxes drawn on the photo as stored from boxes drawn on it upright: see [`crate::upright_regions`].
pub fn regions_drawn_on(&self) -> Option<(f64, f64)> {
let regions = self.values.get("mwg-rs:Regions")?;
let turned = regions.field("mwg-rs:RegionList").is_some_and(|l| l.items().iter().any(|r| r.field("mwg-rs:Rotation").is_some()));
if turned { None } else { applied_to(regions) }
}
}
/// A structured XMP value.
#[derive(Clone, Debug, PartialEq)]
pub enum XmpValue {
@@ -441,15 +452,20 @@ fn parse_gps_coord(s: &str) -> Option<f64> {
/// Malformed or out-of-range entries are skipped rather than rejecting the whole list: one bad region
/// (from Lightroom, digiKam, Picasa, or a hand-edited file) shouldn't hide the rest.
fn parse_regions(regions: &XmpValue) -> Vec<Region> {
// `AppliedToDimensions` documents the pixel size regions were authored against. It's only consulted
// `AppliedToDimensions` documents the pixel size regions were authored against. Here it's only consulted
// for the rare region whose own Area is in pixel units instead of MWG's normalized default below.
let px_dims = regions.field("mwg-rs:AppliedToDimensions").and_then(|d| {
let px_dims = applied_to(regions);
let Some(list) = regions.field("mwg-rs:RegionList") else { return Vec::new() };
list.items().iter().filter_map(|item| parse_one_region(item, px_dims)).collect()
}
/// `mwg-rs:AppliedToDimensions` of a `mwg-rs:Regions` struct: (width, height) in pixels, both positive.
fn applied_to(regions: &XmpValue) -> Option<(f64, f64)> {
regions.field("mwg-rs:AppliedToDimensions").and_then(|d| {
let w = d.field("stDim:w").and_then(XmpValue::text).and_then(parse_number)?;
let h = d.field("stDim:h").and_then(XmpValue::text).and_then(parse_number)?;
(w > 0.0 && h > 0.0).then_some((w, h))
});
let Some(list) = regions.field("mwg-rs:RegionList") else { return Vec::new() };
list.items().iter().filter_map(|item| parse_one_region(item, px_dims)).collect()
})
}
fn parse_one_region(item: &XmpValue, px_dims: Option<(f64, f64)>) -> Option<Region> {
+30
View File
@@ -345,6 +345,36 @@ fn mwg_regions_quarter_turn_rotation_is_mapped_to_the_upright_frame() {
assert!(near(regions[4].rect, [0.6, 0.45, 0.8, 0.75]), "−π (orientation 3): {:?}", regions[4].rect);
}
/// The size a packet's boxes were drawn on is its `AppliedToDimensions`, unless a box says how the photo was turned
/// (Lightroom's `mwg-rs:Rotation`: those are upright already) or there is no size to go by.
#[test]
fn regions_drawn_on_is_the_applied_to_size_unless_a_box_says_how_it_was_turned() {
let packet = |dims: &str, rotation: &str| {
format!(
r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about="" xmlns:mwg-rs="http://www.metadataworkinggroup.com/schemas/regions/"
xmlns:stArea="http://ns.adobe.com/xmp/sType/Area#" xmlns:stDim="http://ns.adobe.com/xap/1.0/sType/Dimensions#">
<mwg-rs:Regions rdf:parseType="Resource">{dims}
<mwg-rs:RegionList><rdf:Bag>
<rdf:li rdf:parseType="Resource" mwg-rs:Type="Face">
<mwg-rs:Area rdf:parseType="Resource" stArea:x="0.3" stArea:y="0.4" stArea:w="0.2" stArea:h="0.3"/>
</rdf:li>
<rdf:li rdf:parseType="Resource" mwg-rs:Type="Face"{rotation}>
<mwg-rs:Area rdf:parseType="Resource" stArea:x="0.6" stArea:y="0.4" stArea:w="0.2" stArea:h="0.3"/>
</rdf:li>
</rdf:Bag></mwg-rs:RegionList>
</mwg-rs:Regions>
</rdf:Description></rdf:RDF>"#
)
};
let dims = r#"<mwg-rs:AppliedToDimensions rdf:parseType="Resource" stDim:w="6000" stDim:h="4000" stDim:unit="pixel"/>"#;
let drawn_on = |x: &str| parse_xmp(x).unwrap().regions_drawn_on();
assert_eq!(drawn_on(&packet(dims, "")), Some((6000.0, 4000.0)));
assert_eq!(drawn_on(&packet(dims, r#" mwg-rs:Rotation="-1.57080""#)), None, "one box turned by Lightroom");
assert_eq!(drawn_on(&packet("", "")), None, "no AppliedToDimensions");
assert_eq!(drawn_on(r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about=""/></rdf:RDF>"#), None);
}
/// A second, differently-shaped encoding: each region is its own `rdf:Description` (rather than an
/// `rdf:li rdf:parseType="Resource"`), `mwg-rs:Type` as an attribute instead of an element, and an
/// unrecognised `mwg-rs:Type` value kept verbatim.
+58 -5
View File
@@ -172,15 +172,43 @@ impl DiskCache {
}
}
pub fn put(&self, key: Hash128, img: &Rgba8) {
let Some(bytes) = encode_jpeg(img) else { return };
/// The size (width, height) of the picture kept under `key`, read from the start of its file
/// only (no decode, no hit counted, nothing written): to tell whether a preview is there and
/// big enough without loading it.
pub fn dims(&self, key: Hash128) -> Option<(usize, usize)> {
use std::io::Read;
let p = self.path(key);
let Some(parent) = p.parent() else { return };
if !p.parent().is_some_and(is_real_dir) {
return None;
}
let mut f = std::fs::File::open(&p).or_else(|_| std::fs::File::open(self.named(key, OLD_EXT))).ok()?;
// the size is normally in the first few KiB: more is read only when that is not enough
let mut head = Vec::new();
for limit in [FIRST_HEADER_BYTES, HEADER_BYTES] {
let more = limit.saturating_sub(head.len() as u64);
(&mut f).take(more).read_to_end(&mut head).ok()?;
if let Some(dims) = jpeg_dims(&head) {
return Some(dims);
}
if (head.len() as u64) < limit {
// the whole file was read
break;
}
}
None
}
/// Write `img` under `key`. Returns whether the file was written (a full or unwritable cache folder
/// gives `false`; the cache is unchanged then).
pub fn put(&self, key: Hash128, img: &Rgba8) -> bool {
let Some(bytes) = encode_jpeg(img) else { return false };
let p = self.path(key);
let Some(parent) = p.parent() else { return false };
// a folder the cache makes for itself says that it is a cache; one that was there
// already may hold somebody's files, and is not declared one
let made = !self.dir.exists();
if std::fs::create_dir_all(parent).is_err() || !is_real_dir(parent) {
return;
return false;
}
if made {
let _ = std::fs::write(self.dir.join(TAG), TAG_TEXT);
@@ -197,7 +225,7 @@ impl DiskCache {
let written = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp).and_then(|mut f| std::io::Write::write_all(&mut f, &bytes));
if written.is_err() || std::fs::rename(&tmp, &p).is_err() {
let _ = std::fs::remove_file(&tmp);
return;
return false;
}
self.writes.fetch_add(1, Ordering::Relaxed);
*used = used.saturating_sub(old_len).saturating_add(bytes.len() as u64);
@@ -205,7 +233,10 @@ impl DiskCache {
drop(total);
if over {
self.prune();
// (a picture bigger than the room pruning leaves goes too: it was not kept)
return p.is_file();
}
true
}
/// All cache files (only names of the cache's own shape, see [`is_cache_file`]):
@@ -374,6 +405,12 @@ impl DiskCache {
*t.get_or_insert_with(|| self.scan().iter().map(|f| f.1).sum())
}
/// Bytes on disk when already known, without reading the folder (`None` until [`Self::size`],
/// a write or a prune has counted them).
pub fn known_size(&self) -> Option<u64> {
*self.total.lock().unwrap_or_else(|e| e.into_inner())
}
pub fn clear(&self) {
for (p, _, _) in self.scan() {
let _ = std::fs::remove_file(p);
@@ -432,6 +469,22 @@ pub fn encode_jpeg(img: &Rgba8) -> Option<Vec<u8>> {
Some(out)
}
/// How much of a cached file [`DiskCache::dims`] reads: the JPEG headers this cache writes come
/// first and are a few hundred bytes.
const HEADER_BYTES: u64 = 64 << 10;
/// What [`DiskCache::dims`] reads first, which holds the size of the JPEGs this cache writes.
const FIRST_HEADER_BYTES: u64 = 4 << 10;
/// A JPEG's (width, height) from its headers (`None`: not a JPEG, or cut short before its frame header).
pub fn jpeg_dims(bytes: &[u8]) -> Option<(usize, usize)> {
use zune_core::bytestream::ZCursor;
let mut d = zune_jpeg::JpegDecoder::new(ZCursor::new(bytes));
d.decode_headers().ok()?;
let info = d.info()?;
let (w, h) = (info.width as usize, info.height as usize);
(w > 0 && h > 0).then_some((w, h))
}
/// Decode a cached thumbnail (see [`encode_jpeg`]).
pub fn decode_jpeg(bytes: &[u8]) -> Option<Rgba8> {
use zune_core::bytestream::ZCursor;
+67 -7
View File
@@ -21,7 +21,7 @@ use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, RwLock};
pub use disk::{DiskCache, decode_jpeg, encode_jpeg};
pub use disk::{DiskCache, decode_jpeg, encode_jpeg, jpeg_dims};
pub use hash::{Hash128, Hasher128, hash_bytes};
use lightcraft_raster::Rgba8;
pub use lru::{Lru, next_tick};
@@ -108,20 +108,80 @@ impl PreviewCache {
Some(img)
}
pub fn put(&self, key: Hash128, img: Arc<Rgba8>) {
self.put_at(self.generation(), key, img);
/// The size of the image kept under `key` (memory, else disk: read from its file's header), without
/// loading it or changing what is kept.
pub fn dims(&self, key: Hash128) -> Option<(usize, usize)> {
if self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner).is_none() {
return None;
}
if let Some(v) = self.mem.lock().unwrap_or_else(|e| e.into_inner()).peek(&key) {
return Some((v.width, v.height));
}
self.disk.as_ref()?.dims(key)
}
pub fn put_at(&self, generation: u64, key: Hash128, img: Arc<Rgba8>) {
/// The size of the image kept under `key` where it lasts: on disk when the cache has a disk (a copy only
/// in memory, whose deferred write may have been skipped, doesn't count), else in memory. Nothing is
/// loaded or changed.
pub fn stored_dims(&self, key: Hash128) -> Option<(usize, usize)> {
match &self.disk {
Some(d) if self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner).is_some() => d.dims(key),
Some(_) => None,
None => self.dims(key),
}
}
/// The memory LRU's copy of `key`, without looking on disk.
pub fn get_memory(&self, key: Hash128) -> Option<Arc<Rgba8>> {
if self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner).is_none() {
return None;
}
self.mem.lock().unwrap_or_else(|e| e.into_inner()).get(&key).cloned()
}
/// Keep `img` in memory only (it is never written to disk): for pictures that are cheap
/// enough to make again, such as a raw's decoded camera JPEG, but worth keeping for a revisit.
pub fn put_memory(&self, key: Hash128, img: Arc<Rgba8>) {
// (the guard is held through the insertion: a clear can't come between the look and the insertion)
let current = self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner);
if current.is_none() {
return;
}
let c = cost(&img);
self.mem.lock().unwrap_or_else(|e| e.into_inner()).insert(key, img, c);
drop(current);
}
/// [`Self::put_memory`] for a job that captured `generation`: nothing is kept once the cache
/// was cleared (or retired) after that, so a job started before Discard Preview Cache can't
/// put its picture back.
pub fn put_memory_at(&self, generation: u64, key: Hash128, img: Arc<Rgba8>) {
// (the guard is held through the insertion: a clear can't come between the look and the insertion)
let current = self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner);
if *current != Some(generation) {
return;
}
if let Some(d) = &self.disk {
d.put(key, &img);
}
let c = cost(&img);
self.mem.lock().unwrap_or_else(|e| e.into_inner()).insert(key, img, c);
drop(current);
}
pub fn put(&self, key: Hash128, img: Arc<Rgba8>) {
let _ = self.put_at(self.generation(), key, img);
}
/// [`Self::put`] for a job of `generation`. Returns whether the image is kept where it lasts: `false` when
/// the cache was cleared or retired since the job was made (nothing is kept; see [`Self::generation`] to
/// tell), or when the disk cache could not write the file (the image is kept in memory all the same).
pub fn put_at(&self, generation: u64, key: Hash128, img: Arc<Rgba8>) -> bool {
let current = self.generation.read().unwrap_or_else(std::sync::PoisonError::into_inner);
if *current != Some(generation) {
return false;
}
let written = self.disk.as_ref().is_none_or(|d| d.put(key, &img));
let c = cost(&img);
self.mem.lock().unwrap_or_else(|e| e.into_inner()).insert(key, img, c);
written
}
/// Like [`Self::put`], but the disk write (a JPEG encode) happens on a background thread, so
+60
View File
@@ -792,3 +792,63 @@ fn deferred_writes_are_bounded_and_drain_to_disk() {
assert!(keys.iter().all(|k| cache.get(*k).is_some()));
let _ = std::fs::remove_dir_all(&dir);
}
/// `put_at` says whether the image is kept where it lasts: not for a job made before the cache was cleared or
/// retired, nor when the disk cache can't write it (CodeRabbit on #3077).
#[test]
fn put_at_says_whether_the_image_was_kept() {
let dir = temp_dir("put-at-kept");
let cache = PreviewCache::with_disk(1 << 20, &dir, 1 << 20);
let (key, img) = (hash_bytes(b"kept"), Arc::new(gradient(8, 8, 3)));
let old = cache.generation();
assert!(cache.put_at(old, key, img.clone()), "kept");
cache.clear();
assert!(!cache.put_at(old, key, img.clone()), "a job from before the clear keeps nothing");
assert!(cache.put_at(cache.generation(), key, img.clone()));
let generation = cache.generation();
cache.retire();
assert!(!cache.put_at(generation, key, img.clone()), "nor one for a retired cache");
// a file where the cache folder goes: the write fails
let blocked = temp_dir("put-at-blocked");
std::fs::write(&blocked, b"not a folder").unwrap();
let cache = PreviewCache::with_disk(1 << 20, &blocked, 1 << 20);
assert!(!cache.put_at(cache.generation(), key, img.clone()), "not written");
let memory = PreviewCache::memory(1 << 20);
assert!(memory.put_at(memory.generation(), key, img), "a memory-only cache keeps it");
let _ = std::fs::remove_file(&blocked);
let _ = std::fs::remove_dir_all(&dir);
}
/// `dims` reads a cached file's first few KiB, and further when its size marker comes later (CodeRabbit on #3080).
#[test]
fn dims_finds_a_size_marker_past_the_first_few_kib() {
let dir = temp_dir("dims-far");
let d = DiskCache::new(&dir, 1 << 20);
let key = hash_bytes(b"far");
assert!(d.put(key, &gradient(40, 30, 5)));
assert_eq!(d.dims(key), Some((40, 30)));
// the same picture with a 10 KiB application segment before its frame header
let file = files_under(&dir).into_iter().find(|f| f.ends_with(disk::EXT)).expect("the cached file");
let path = dir.join(file);
let jpeg = std::fs::read(&path).unwrap();
let mut padded = jpeg[..2].to_vec();
let pad = 10 << 10;
padded.extend_from_slice(&[0xFF, 0xEF, ((pad + 2) >> 8) as u8, ((pad + 2) & 0xFF) as u8]);
padded.extend(std::iter::repeat_n(0u8, pad));
padded.extend_from_slice(&jpeg[2..]);
std::fs::write(&path, padded).unwrap();
assert_eq!(d.dims(key), Some((40, 30)), "found past the first read");
let _ = std::fs::remove_dir_all(&dir);
}
/// A picture bigger than the room pruning leaves is removed by the pruning its own write starts: `put` says it
/// was not kept (CodeRabbit on #3077).
#[test]
fn a_write_the_pruning_removes_is_not_reported_as_kept() {
let dir = temp_dir("pruned-away");
let d = DiskCache::new(&dir, 64);
assert!(!d.put(hash_bytes(b"too big"), &gradient(64, 64, 9)), "pruned away at once");
let roomy = DiskCache::new(&dir, 1 << 20);
assert!(roomy.put(hash_bytes(b"fits"), &gradient(64, 64, 9)));
let _ = std::fs::remove_dir_all(&dir);
}
+519
View File
@@ -0,0 +1,519 @@
//! Hot pixels on sensors that don't list their defects.
//!
//! A hot pixel is a single photosite that reads far too bright: a leaky or stuck cell, most visible
//! at high ISO and in dark areas. Demosaicing turns it into a small saturated dot of its colour
//! (red, green or blue), and colour noise reduction can only make that dot fainter, since the photosite
//! is too bright, not just the wrong colour. DNGs list such pixels in their opcodes and Panasonic marks
//! them in the data (both repaired elsewhere); other raws, such as Sony ARWs, carry no list.
//!
//! [`RawImage::suppress_hot_pixels`] finds them in the mosaic, before demosaicing:
//!
//! 1. **Noise model.** On a sparse sample of the image, each photosite is compared with the median of
//! its same-colour neighbours. The spread of that difference, per brightness, gives the noise
//! σ(level) as `σ² = a · level + b` (shot noise plus read noise), fitted to the image itself.
//! 2. **Candidates.** A photosite more than [`K_HOT`] σ above *every* same-colour neighbour (the
//! nearest eight, two photosites away on a Bayer grid, the nearest greens for green).
//! 3. **Real light is kept.** A star, a spark or a specular point lights more than one photosite: its
//! direct neighbours are raised too. A candidate with at least [`MIN_LIT`] neighbours more than
//! [`K_SPOT`] σ above their own surroundings is left alone. Hot photosites also come in adjacent
//! pairs, so a single lit neighbour doesn't count.
//! 4. The rest are replaced by the median of their same-colour neighbours.
//!
//! If more than a share of the photosites would be replaced (by default [`HOT_PIXEL_MAX_SHARE`]; the caller may
//! choose another), the image doesn't fit the model (a synthetic pattern, a star field shot through a pinhole) and
//! nothing is changed. Real light kept in step 3 doesn't count: a dense star field still has its hot pixels removed.
use crate::{RawData, RawImage};
use rayon::prelude::*;
/// A candidate stands more than this many σ above the brightest of its same-colour neighbours (pure noise
/// hardly reaches 4.5 σ above the brightest of eight; measured on two ILCE-7M4 files at ISO 3200 and 25600).
const K_HOT: f32 = 5.0;
/// A direct neighbour this many σ above its own surroundings means the light is real.
const K_SPOT: f32 = 4.0;
/// ...and it takes this many lit neighbours (a hot pair has one).
const MIN_LIT: usize = 2;
/// Every this many rows and columns are sampled for the noise model.
const SAMPLE_STEP: usize = 5;
/// Brightness bins of the noise model (on a square-root scale), and the samples a bin needs.
const BINS: usize = 32;
const MIN_BIN_SAMPLES: usize = 64;
/// Photosites this close to the active area's edge are left alone (their neighbourhood is cut).
const MARGIN: usize = 4;
/// More replaced than this share of the photosites and the result is discarded (unless the caller chooses another).
pub const HOT_PIXEL_MAX_SHARE: f64 = 2e-3;
/// For one position in the CFA pattern: the offsets of the nearest same-colour photosites (at most 8,
/// within two photosites) and of the 8 direct neighbours.
#[derive(Clone)]
struct Phase {
same: Vec<(isize, isize)>,
around: [(isize, isize); 8],
}
fn phases(cfa: &crate::Cfa) -> Vec<Phase> {
let around = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)];
let (pw, ph) = (cfa.width, cfa.height);
(0..ph)
.flat_map(|j| (0..pw).map(move |i| (i, j)))
.map(|(i, j)| {
// anchored far enough from 0 that i + dx stays positive
let (x0, y0) = (i + 2 * pw, j + 2 * ph);
let c = cfa.color_at(x0, y0);
let mut same: Vec<(isize, isize)> = (-2isize..=2)
.flat_map(|dy| (-2isize..=2).map(move |dx| (dx, dy)))
.filter(|&(dx, dy)| (dx, dy) != (0, 0) && cfa.color_at((x0 as isize + dx) as usize, (y0 as isize + dy) as usize) == c)
.collect();
same.sort_by_key(|&(dx, dy)| dx * dx + dy * dy);
same.truncate(8);
Phase { same, around }
})
.collect()
}
/// The noise σ at a brightness (in raw counts above black): `sqrt(a · level + b)`.
#[derive(Clone, Copy, Debug)]
struct Noise {
a: f32,
b: f32,
}
impl Noise {
fn sigma(&self, level: f32) -> f32 {
(self.a * level.max(0.0) + self.b).max(1.0).sqrt()
}
}
fn median(v: &mut [f32]) -> f32 {
if v.is_empty() {
return 0.0;
}
v.sort_by(f32::total_cmp);
let n = v.len();
if n % 2 == 1 { v[n / 2] } else { 0.5 * (v[n / 2 - 1] + v[n / 2]) }
}
/// The sample view the passes work on: the u16 mosaic, its width, the active area, the CFA phases.
struct View<'a> {
d: &'a [u16],
w: usize,
pw: usize,
ph: usize,
phases: &'a [Phase],
}
impl View<'_> {
/// Value at full-image `(x, y)`; callers keep `(x, y)` inside the image.
#[inline]
fn at(&self, x: isize, y: isize) -> f32 {
self.d[y as usize * self.w + x as usize] as f32
}
#[inline]
fn phase(&self, x: usize, y: usize) -> &Phase {
&self.phases[(y % self.ph) * self.pw + (x % self.pw)]
}
/// The same-colour neighbours' values around `(x, y)` into `buf`, and their maximum.
#[inline]
fn neighbours(&self, x: usize, y: usize, buf: &mut Vec<f32>) -> f32 {
buf.clear();
let mut max = f32::MIN;
for &(dx, dy) in &self.phase(x, y).same {
let v = self.at(x as isize + dx, y as isize + dy);
max = max.max(v);
buf.push(v);
}
max
}
}
impl RawImage {
/// Replace isolated hot photosites by the median of their same-colour neighbours (see the module docs).
/// Returns how many were replaced. Only single-plane integer CFA data is examined.
pub fn suppress_hot_pixels(&mut self) -> usize {
self.suppress_hot_pixels_with(HOT_PIXEL_MAX_SHARE)
}
/// [`Self::suppress_hot_pixels`], giving up when more than `max_share` of the photosites (0..1) would be replaced.
pub fn suppress_hot_pixels_with(&mut self, max_share: f64) -> usize {
let Some(cfa) = self.cfa.clone() else { return 0 };
let (w, h, a) = (self.width, self.height, self.active_area);
let black = self.black.mean();
let RawData::U16(d) = &mut self.data else { return 0 };
if self.cpp != 1
|| !cfa.valid()
|| w.checked_mul(h) != Some(d.len())
|| a.width < 4 * MARGIN
|| a.height < 4 * MARGIN
|| a.x + a.width > w
|| a.y + a.height > h
|| !black.is_finite()
{
return 0;
}
let phases = phases(&cfa);
if phases.iter().any(|p| p.same.len() < 4) {
return 0;
}
let (x0, x1, y0, y1) = (a.x + MARGIN, a.x + a.width - MARGIN, a.y + MARGIN, a.y + a.height - MARGIN);
let range = (self.white.iter().copied().fold(0.0f32, f32::max) - black).max(1.0);
let fixes = {
let v = View { d: d.as_slice(), w, pw: cfa.width, ph: cfa.height, phases: &phases };
let Some(noise) = noise_model(&v, (x0, x1, y0, y1), black, range) else { return 0 };
let candidates = candidates(&v, (x0, x1, y0, y1), black, noise);
let mut buf = Vec::with_capacity(8);
let n_cand = candidates.len();
let kept: Vec<_> = candidates.into_iter().filter(|&(x, y, _)| !lit_around(&v, x, y, black, noise, &mut buf)).collect();
// (real light kept above doesn't count against the limit)
let sites = (x1 - x0) * (y1 - y0);
let limit = max_share * sites as f64;
if limit.is_nan() || kept.len() as f64 > limit {
return 0;
}
if std::env::var_os("LIGHTCRAFT_PROFILE").is_some() {
eprintln!(
" hot pixels: noise σ² = {:.3}·L + {:.1} (σ at 0: {:.1}, at 1 %: {:.1}), {n_cand} candidates, {} real light",
noise.a,
noise.b,
noise.sigma(0.0),
noise.sigma(0.01 * range),
n_cand - kept.len()
);
// the strongest excesses below the threshold, to see how far the dots are
let mut hist = [0usize; 12];
let mut buf2 = Vec::with_capacity(8);
for y in (y0..y1).step_by(1) {
for x in x0..x1 {
let s = v.at(x as isize, y as isize);
let max = v.neighbours(x, y, &mut buf2);
if s <= max {
continue;
}
let m = median(&mut buf2);
let k = ((s - max) / noise.sigma(m - black)) as usize;
hist[k.min(11)] += 1;
}
}
eprintln!(" hot pixels: photosites by (s - max neighbour) / σ, 0..11+: {hist:?}");
// very bright photosites in dark surroundings, whatever the verdict
let mut bright = 0;
let mut buf4 = Vec::with_capacity(8);
for y in y0..y1 {
for x in x0..x1 {
let s = v.at(x as isize, y as isize) - black;
if s < 1500.0 {
continue;
}
v.neighbours(x, y, &mut buf4);
let m = median(&mut buf4) - black;
if m > 300.0 {
continue;
}
bright += 1;
if bright <= 4 {
eprintln!(
" bright at ({x}, {y}), colour {}, s {s:.0}, median {m:.0}, lit {}:",
cfa.color_at(x, y),
lit_around(&v, x, y, black, noise, &mut buf4)
);
for dy in -3isize..=3 {
let row: Vec<String> =
(-3isize..=3).map(|dx| format!("{:6.0}", v.at(x as isize + dx, y as isize + dy) - black)).collect();
eprintln!(" {}", row.join(" "));
}
}
}
}
eprintln!(" bright photosites in dark surroundings: {bright}");
// a few candidates rejected as real light: their 5 × 5 neighbourhood above black
let mut shown = 0;
let mut buf3 = Vec::with_capacity(8);
for y in y0..y1 {
for x in x0..x1 {
if shown >= 6 {
break;
}
let s = v.at(x as isize, y as isize);
let max = v.neighbours(x, y, &mut buf3);
if s <= max {
continue;
}
let m = median(&mut buf3);
if s - max > 8.0 * noise.sigma(m - black) && lit_around(&v, x, y, black, noise, &mut buf3) {
shown += 1;
eprintln!(" rejected at ({x}, {y}), colour {}:", cfa.color_at(x, y));
for dy in -2isize..=2 {
let row: Vec<String> =
(-2isize..=2).map(|dx| format!("{:6.0}", v.at(x as isize + dx, y as isize + dy) - black)).collect();
eprintln!(" {}", row.join(" "));
}
}
}
}
}
kept
};
for &(x, y, r) in &fixes {
d[y * w + x] = r;
}
fixes.len()
}
}
/// Fit `σ² = a · level + b` to the spread of (photosite − median of its same-colour neighbours) on a sample.
fn noise_model(v: &View<'_>, (x0, x1, y0, y1): (usize, usize, usize, usize), black: f32, range: f32) -> Option<Noise> {
let bin_of = |level: f32| (((level.max(0.0) / range).sqrt() * BINS as f32) as usize).min(BINS - 1);
let rows: Vec<usize> = (y0..y1).step_by(SAMPLE_STEP).collect();
let per_row: Vec<Vec<(usize, f32, f32)>> = rows
.par_iter()
.map(|&y| {
let mut buf = Vec::with_capacity(8);
(x0..x1)
.step_by(SAMPLE_STEP)
.map(|x| {
v.neighbours(x, y, &mut buf);
let m = median(&mut buf);
let level = m - black;
(bin_of(level), level, (v.at(x as isize, y as isize) - m).abs())
})
.collect()
})
.collect();
let mut bins: Vec<(Vec<f32>, f64, usize)> = vec![(Vec::new(), 0.0, 0); BINS];
for (b, level, dev) in per_row.into_iter().flatten() {
bins[b].0.push(dev);
bins[b].1 += level as f64;
bins[b].2 += 1;
}
// per bin: mean level and σ from the median absolute deviation (robust to the hot pixels themselves)
let pts: Vec<(f64, f64, f64)> = bins
.into_iter()
.filter(|(dev, _, n)| *n >= MIN_BIN_SAMPLES && !dev.is_empty())
.map(|(mut dev, sum, n)| {
let s = 1.4826 * median(&mut dev) as f64;
(sum / n as f64, s * s, n as f64)
})
.collect();
if pts.is_empty() {
return None;
}
// weighted least squares for σ² = a·L + b, both kept ≥ 0
let (sw, sl, sv) = pts.iter().fold((0.0, 0.0, 0.0), |(w, l, s), &(lv, var, n)| (w + n, l + n * lv, s + n * var));
let (ml, mv) = (sl / sw, sv / sw);
let (cov, varl) = pts.iter().fold((0.0, 0.0), |(c, vl), &(lv, var, n)| (c + n * (lv - ml) * (var - mv), vl + n * (lv - ml) * (lv - ml)));
let a = if varl > 0.0 { (cov / varl).max(0.0) } else { 0.0 };
let b = (mv - a * ml).max(0.0);
(a.is_finite() && b.is_finite()).then_some(Noise { a: a as f32, b: b as f32 })
}
/// Photosites far above every same-colour neighbour, with the value to replace them by.
fn candidates(v: &View<'_>, (x0, x1, y0, y1): (usize, usize, usize, usize), black: f32, noise: Noise) -> Vec<(usize, usize, u16)> {
(y0..y1)
.into_par_iter()
.flat_map_iter(|y| {
let mut buf = Vec::with_capacity(8);
let mut out = Vec::new();
for x in x0..x1 {
let s = v.at(x as isize, y as isize);
let max = v.neighbours(x, y, &mut buf);
if s <= max {
continue;
}
let m = median(&mut buf);
if s - max > K_HOT * noise.sigma(m - black) {
out.push((x, y, m.round().clamp(0.0, u16::MAX as f32) as u16));
}
}
out
})
.collect()
}
/// Are at least [`MIN_LIT`] direct neighbours of `(x, y)` clearly above their own same-colour surroundings
/// (real light)? A single one is not enough: hot photosites also come in adjacent pairs.
fn lit_around(v: &View<'_>, x: usize, y: usize, black: f32, noise: Noise, buf: &mut Vec<f32>) -> bool {
v.phase(x, y)
.around
.iter()
.filter(|&&(dx, dy)| {
let (nx, ny) = ((x as isize + dx) as usize, (y as isize + dy) as usize);
let s = v.at(nx as isize, ny as isize);
v.neighbours(nx, ny, buf);
let m = median(buf);
s - m > K_SPOT * noise.sigma(m - black)
})
.count()
>= MIN_LIT
}
#[cfg(test)]
mod tests {
use crate::*;
/// A `w × h` RGGB mosaic, black 512, white 16383, flat grey 2000 counts above black with
/// deterministic noise of about σ ≈ 30 counts.
fn mosaic(w: usize, h: usize) -> RawImage {
let mut seed = 0x2545_f491_4f6c_dd1du64;
let mut noise = || {
// sum of 4 uniforms, about N(0, 1)
(0..4)
.map(|_| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed >> 11) as f32 / (1u64 << 53) as f32 - 0.5
})
.sum::<f32>()
* 1.732
};
let data = (0..w * h).map(|_| (512.0 + 2000.0 + 30.0 * noise()).round() as u16).collect();
RawImage {
format: RawFormat::Arw,
width: w,
height: h,
cpp: 1,
data: RawData::U16(data),
cfa: Cfa::bayer("RGGB"),
bits: 14,
black: BlackLevel::uniform(512.0),
white: vec![16383.0],
active_area: Rect::new(0, 0, w, h),
crop: Rect::new(0, 0, w, h),
orientation: Orientation::Normal,
color: ColorData::default(),
wb_multipliers: None,
linearized: false,
opcodes: OpcodeLists::default(),
lens_metadata: Default::default(),
pixel_aspect: 1.0,
metadata: Metadata::default(),
}
}
fn get(r: &RawImage, x: usize, y: usize) -> u16 {
match &r.data {
RawData::U16(d) => d[y * r.width + x],
RawData::F32(_) => 0,
}
}
fn set(r: &mut RawImage, x: usize, y: usize, v: u16) {
let w = r.width;
if let RawData::U16(d) = &mut r.data {
d[y * w + x] = v;
}
}
#[test]
fn flat_noise_is_left_alone() {
let mut r = mosaic(256, 256);
let before = r.data.clone();
assert_eq!(r.suppress_hot_pixels(), 0);
assert_eq!(r.data, before);
}
#[test]
fn single_hot_photosites_of_each_colour_are_replaced() {
let mut r = mosaic(256, 256);
// red (even, even), green (odd, even), blue (odd, odd)
for &(x, y) in &[(100, 100), (101, 60), (151, 151)] {
set(&mut r, x, y, 9000);
}
assert_eq!(r.suppress_hot_pixels(), 3);
for &(x, y) in &[(100, 100), (101, 60), (151, 151)] {
let v = get(&r, x, y) as f32;
assert!((v - 2512.0).abs() < 120.0, "({x}, {y}) = {v}");
}
}
#[test]
fn an_adjacent_hot_pair_is_replaced() {
let mut r = mosaic(256, 256);
set(&mut r, 80, 80, 9000);
set(&mut r, 80, 81, 8000);
assert_eq!(r.suppress_hot_pixels(), 2);
assert!(get(&r, 80, 80) < 2700 && get(&r, 80, 81) < 2700);
}
#[test]
fn a_small_star_is_kept() {
let mut r = mosaic(256, 256);
// a point of light over a 3 × 3 block: brightest in the middle, its neighbours lit too
for dy in -1i32..=1 {
for dx in -1i32..=1 {
let v = if dx == 0 && dy == 0 { 12000 } else { 5000 };
set(&mut r, (120 + dx) as usize, (90 + dy) as usize, v);
}
}
let before = r.data.clone();
assert_eq!(r.suppress_hot_pixels(), 0);
assert_eq!(r.data, before);
}
#[test]
fn a_hot_photosite_in_a_dark_area_is_replaced() {
let mut r = mosaic(256, 256);
// a dark patch near black (noise is then read noise, smaller)
for y in 32..96 {
for x in 32..96 {
set(&mut r, x, y, 512 + 20 + ((x * 7 + y * 13) % 11) as u16);
}
}
set(&mut r, 64, 64, 1500);
assert_eq!(r.suppress_hot_pixels(), 1);
assert!(get(&r, 64, 64) < 600);
}
#[test]
fn a_dense_star_field_keeps_its_stars_and_loses_its_hot_pixels() {
let mut r = mosaic(256, 256);
// 225 small stars: more candidates than 0.2 % of the photosites, every one of them real light
for sy in 0..15 {
for sx in 0..15 {
let (cx, cy) = (16 + 16 * sx, 16 + 16 * sy);
for dy in -1i32..=1 {
for dx in -1i32..=1 {
let v = if dx == 0 && dy == 0 { 12000 } else { 5000 };
set(&mut r, (cx + dx) as usize, (cy + dy) as usize, v);
}
}
}
}
let hot = [(24, 24), (105, 72), (201, 153)];
for &(x, y) in &hot {
set(&mut r, x, y, 9000);
}
assert_eq!(r.suppress_hot_pixels(), 3);
for &(x, y) in &hot {
assert!(get(&r, x, y) < 2700, "({x}, {y}) = {}", get(&r, x, y));
}
assert_eq!(get(&r, 16, 16), 12000, "a star is left alone");
}
#[test]
fn the_limit_is_the_callers() {
let mut r = mosaic(256, 256);
let hot = [(40, 40), (101, 60), (151, 151), (200, 30)];
for &(x, y) in &hot {
set(&mut r, x, y, 9000);
}
let before = r.data.clone();
// 4 of 248 × 248 photosites: above a limit of 0.005 %, within 0.01 %
assert_eq!(r.suppress_hot_pixels_with(5e-5), 0);
assert_eq!(r.data, before);
assert_eq!(r.suppress_hot_pixels_with(1e-4), 4);
assert_eq!(r.clone().suppress_hot_pixels_with(f64::NAN), 0, "a limit that is not a number replaces nothing");
}
#[test]
fn too_many_candidates_change_nothing() {
let mut r = mosaic(128, 128);
for y in (8..120).step_by(4) {
for x in (8..120).step_by(4) {
set(&mut r, x, y, 12000);
}
}
let before = r.data.clone();
assert_eq!(r.suppress_hot_pixels(), 0);
assert_eq!(r.data, before);
}
}
+2
View File
@@ -34,6 +34,7 @@ mod dng;
pub mod dngwrite;
pub mod gaintable;
pub mod highlight;
mod hotpixel;
#[cfg(feature = "jxl")]
mod jxl;
pub mod kelvin_builtin;
@@ -55,6 +56,7 @@ mod wb_estimate;
pub use demosaic::{Method, demosaic};
pub use dngwrite::{DngCompression, DngWriteOptions, write_dng, write_rendered_dng};
pub use hotpixel::HOT_PIXEL_MAX_SHARE;
pub use lens_metadata::LensMetadata;
pub use lightcraft_color::Mat3;
pub use lightcraft_geom::Orientation;
+183 -37
View File
@@ -138,12 +138,68 @@ fn is_jxl(b: &[u8]) -> bool {
b.starts_with(&[0xff, 0x0a]) || b.starts_with(&[0, 0, 0, 0x0c, b'J', b'X', b'L', b' ', 0x0d, 0x0a, 0x87, 0x0a])
}
fn candidates<'a>(data: &'a [u8], ifd: &Ifd, base: u64, out: &mut Vec<&'a [u8]>) {
/// The bytes a file's own (offset, length) pair names, cut at the file's end; `None` when the offset
/// lies past it. Both numbers come from the file: never cast them (a `u64` offset past 4 GiB would
/// wrap to a small, wrong one on a 32-bit build) nor add them unchecked. A span the file's end cuts
/// short is kept only when it is a JPEG whose own end marker is inside it, after its scan (an
/// overstated length with the whole JPEG inside), cut at that marker: a truncated JPEG passes the
/// frame-header check, would win as the largest preview and then fail to decode (CodeRabbit on
/// #3077). An `FF D9` inside an APP payload doesn't count, bytes that don't start a JPEG are refused
/// without a scan, and the walks share `budget` (bytes, as [`scan_with_budget`]'s do), so a file of
/// many such pointers stays linear.
fn file_span<'a>(data: &'a [u8], offset: u64, len: u64, budget: &mut usize) -> Option<&'a [u8]> {
let start = usize::try_from(offset).ok()?;
let wanted = usize::try_from(offset.saturating_add(len)).unwrap_or(usize::MAX);
let span = data.get(start..wanted.min(data.len()))?;
if wanted > data.len() {
return span.get(..jpeg_end(span, budget)?);
}
Some(span)
}
/// Where the JPEG at the start of `s` ends (just past its end marker), walking its marker segments:
/// a segment's payload is skipped by its stated length (so an `FF D9` inside APP data isn't taken
/// for the end), entropy-coded bytes one at a time (stuffed `FF 00` and restart markers included).
/// `None` when `s` isn't a JPEG, ends first, reaches its end marker before a start of scan (no image
/// data), or the walk spends `budget` (one per step, shared by a file's walks). Each step moves
/// forward, so it ends within `s`.
fn jpeg_end(s: &[u8], budget: &mut usize) -> Option<usize> {
if !s.starts_with(&[0xff, 0xd8]) {
return None;
}
let (mut i, mut scanned) = (2usize, false);
loop {
*budget = budget.checked_sub(1)?;
match (s.get(i), s.get(i.checked_add(1)?)) {
(None, _) | (Some(&0xff), None) => return None,
(Some(&0xff), Some(&m)) => match m {
0xd9 => return if scanned { i.checked_add(2) } else { None },
// fill byte
0xff => i += 1,
// stuffed zero, restart marker, TEM: no length follows
0x00 | 0x01 | 0xd0..=0xd7 => i = i.checked_add(2)?,
_ => {
let (&hi, &lo) = (s.get(i.checked_add(2)?)?, s.get(i.checked_add(3)?)?);
let len = usize::from(u16::from_be_bytes([hi, lo]));
if len < 2 {
return None;
}
scanned |= m == 0xda;
i = i.checked_add(2)?.checked_add(len)?;
}
},
// entropy-coded data
(Some(_), _) => i += 1,
}
}
}
fn candidates<'a>(data: &'a [u8], ifd: &Ifd, base: u64, out: &mut Vec<&'a [u8]>, budget: &mut usize) {
// whole JPEG files stored as an undefined-type tag value (e.g. Panasonic `JpgFromRaw` 0x002e)
for e in &ifd.entries {
if matches!(e.value, lightcraft_tiff::Value::Undefined(_))
&& e.count() > 1024
&& let Some(s) = data.get(e.offset as usize..(e.offset.saturating_add(e.count() as u64) as usize).min(data.len()))
&& let Some(s) = file_span(data, e.offset, e.count() as u64, budget)
&& s.starts_with(&[0xff, 0xd8])
{
out.push(s);
@@ -151,7 +207,7 @@ fn candidates<'a>(data: &'a [u8], ifd: &Ifd, base: u64, out: &mut Vec<&'a [u8]>)
}
if let (Some(off), Some(len)) = (ifd.u64(t::JPEG_INTERCHANGE_FORMAT), ifd.u64(t::JPEG_INTERCHANGE_FORMAT_LENGTH)) {
let off = off.saturating_add(base);
if let Some(s) = data.get(off as usize..(off.saturating_add(len) as usize).min(data.len())) {
if let Some(s) = file_span(data, off, len, budget) {
out.push(s);
}
}
@@ -196,8 +252,12 @@ fn smallest_covering<'a>(found: &[&'a [u8]], largest: &[u8], min_edge: u32) -> O
let (a, b) = (u64::from(w) * u64::from(bh), u64::from(h) * u64::from(bw));
w > 0 && h > 0 && c == bc && a.abs_diff(b) * 100 <= a
};
// (one cut short before its end marker would fail to decode, and nothing would try another: CodeRabbit
// on #3583)
let whole = |s: &[u8]| trim_eoi(s).ends_with(&[0xff, 0xd9]);
found
.iter()
.filter(|s| whole(s))
.filter_map(|&s| jpeg_frame(s).filter(|&f| like(f) && f.0.max(f.1) >= min_edge).map(|(w, h, _)| (s, w.max(h))))
.min_by_key(|&(_, long)| long)
.map(|(s, _)| s)
@@ -210,6 +270,20 @@ fn preview_covering(bytes: &[u8], min_edge: Option<u32>) -> Option<Vec<u8>> {
}
let format = crate::probe(bytes);
if format == Some(crate::RawFormat::Cr3) {
// a Canon CR3 keeps its full-size JPEG beside a 1620 px `PRVW` (and a 160 px `THMB`): a
// thumbnail decodes the small copy, not 45 MP of JPEG (about 150 ms a photo, the grid's
// "popcorn" on a folder of R5 / R5 C raws)
// (without a JPEG track, the largest box is the picture's shape: the boxes alone may hold several)
if let Some(min) = min_edge {
let mut found = cr3_preview_box_list(bytes);
let full = cr3_full_jpeg(bytes);
found.extend(full);
if let Some(largest) = full.or_else(|| largest_by_pixels(&found))
&& let Some(j) = smallest_covering(&found, largest, min)
{
return Some(trim_eoi(j).to_vec());
}
}
return cr3_preview(bytes).map(|j| trim_eoi(j).to_vec());
}
if matches!(format, Some(crate::RawFormat::Crw | crate::RawFormat::Mrw | crate::RawFormat::X3f)) {
@@ -217,8 +291,10 @@ fn preview_covering(bytes: &[u8], min_edge: Option<u32>) -> Option<Vec<u8>> {
}
let tiff = Tiff::parse(bytes).ok()?;
let mut found: Vec<&[u8]> = Vec::new();
// the walks of pointers past the file's end share one budget (see file_span)
let mut budget = scan_budget(bytes.len());
for ifd in tiff.all_ifds() {
candidates(bytes, ifd, 0, &mut found);
candidates(bytes, ifd, 0, &mut found, &mut budget);
}
// maker-note preview IFDs (e.g. Nikon PreviewIFD 0x0011 holds JPEGInterchangeFormat relative to the note base)
if let Some(exif) = tiff.exif()
@@ -226,11 +302,11 @@ fn preview_covering(bytes: &[u8], min_edge: Option<u32>) -> Option<Vec<u8>> {
{
let make = tiff.find(t::MAKE).and_then(|e| e.value.as_str()).unwrap_or_default();
if let Some(mn) = makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make) {
candidates(bytes, &mn.ifd, mn.base, &mut found);
candidates(bytes, &mn.ifd, mn.base, &mut found, &mut budget);
if let Some(off) = mn.ifd.u64(0x0011)
&& let Ok((pifd, _)) = lightcraft_tiff::parse_ifd_at(bytes, mn.base + off, mn.order, mn.base, false, &Default::default())
{
candidates(bytes, &pifd, mn.base, &mut found);
candidates(bytes, &pifd, mn.base, &mut found, &mut budget);
}
}
}
@@ -442,53 +518,123 @@ fn scan_with_budget(data: &[u8], budget: usize) -> (Option<Vec<u8>>, u64) {
/// Canon CR3: the full-size JPEG track (see [`lightcraft_meta::cr3`]), else the `PRVW` / `THMB` boxes.
fn cr3_preview(bytes: &[u8]) -> Option<&[u8]> {
cr3_full_jpeg(bytes).or_else(|| cr3_preview_boxes(bytes))
}
/// A CR3's full-size JPEG track, when it holds a DCT JPEG.
fn cr3_full_jpeg(bytes: &[u8]) -> Option<&[u8]> {
let full = lightcraft_meta::cr3::parse_cr3(bytes)
.and_then(|c| c.tracks.iter().find(|t| t.kind == lightcraft_meta::cr3::Cr3TrackKind::Jpeg).and_then(|t| t.data));
if let Some(j) = full.and_then(|(at, len)| bytes.get(at..at.checked_add(len)?)).filter(|j| is_dct_jpeg(j)) {
return Some(j);
}
cr3_preview_boxes(bytes)
full.and_then(|(at, len)| bytes.get(at..at.checked_add(len)?)).filter(|j| is_dct_jpeg(j))
}
/// Canon CR3 (ISO base media file): the `PRVW` box (Laurent Clévy's CR3 notes; layout confirmed on a CC0
/// sample) is `u32 size, "PRVW", u32 0, u16 ?, u16 width, u16 height, u16 ?, u32 jpeg length, JPEG`; the smaller
/// `THMB` box has the same shape. Returns the larger valid one.
/// Marker-walk budget of the CR3 fallback: candidates can overlap (each claiming the rest of the file) and
/// [`is_dct_jpeg`] walks each marker by marker, so walking every candidate would be quadratic in file size.
/// The `THMB`/`PRVW` previews this finds are far below the cap together; once it is spent the scan stops.
const CR3_MAX_WALK: usize = 8 << 20;
/// Canon CR3 (ISO base media file): the `PRVW` box (Laurent Clévy's CR3 notes; layout confirmed on a CC0
/// sample) is `u32 size, "PRVW", u32 0, u16 ?, u16 width, u16 height, u16 ?, u32 jpeg length, JPEG`; the smaller
/// `THMB` box has the same shape. Returns the larger valid one.
fn cr3_preview_boxes(bytes: &[u8]) -> Option<&[u8]> {
let mut best: Option<&[u8]> = None;
largest_by_pixels(&cr3_preview_box_list(bytes))
}
/// Of `found`, the JPEG with the longest edge in pixels (a smaller picture can take more bytes); the
/// first of equals. CodeRabbit on #3077.
fn largest_by_pixels<'a>(found: &[&'a [u8]]) -> Option<&'a [u8]> {
let long = |j: &[u8]| jpeg_frame(j).map_or(0, |(w, h, _)| w.max(h));
found.iter().copied().rev().max_by_key(|j| long(j))
}
/// The valid JPEGs of a CR3's `PRVW` and `THMB` boxes, every one: a file may carry more than one
/// `PRVW`, and the smallest that covers a size is picked from them all.
fn cr3_preview_box_list(bytes: &[u8]) -> Vec<&[u8]> {
let mut out: Vec<&[u8]> = Vec::new();
let mut walked = 0usize;
// the boxes sit outside the media data: only the rest of the file is searched (the media data
// is most of the file, and a thumbnail is asked for every photo in view)
let file = bytes;
// (every top-level `mdat` is left out, not only the first: a PRVW-shaped JPEG in media data is not a
// preview; CodeRabbit on #3583)
let media = cr3_media_data(file);
let whole_file = media.is_empty();
let mut regions: Vec<&[u8]> = Vec::new();
let mut from = 0usize;
for (start, end) in media {
if start >= from {
regions.extend(file.get(from..start));
}
from = from.max(end);
}
regions.extend(file.get(from..));
for tag in [b"PRVW", b"THMB"] {
let mut from = 0;
while let Some(i) = bytes.get(from..).and_then(|s| s.windows(4).position(|w| w == tag)).map(|p| p + from) {
from = i + 4;
let Some(start) = i.checked_sub(4) else { continue };
let be32 = |at: usize| bytes.get(at..at + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize);
let (Some(size), Some(len)) = (be32(start), be32(start + 20)) else { continue };
let j = start + 24;
// 32-bit box lengths can wrap `usize` on wasm32: check the sums, then slice with `get`
let (Some(end), Some(lim)) = (j.checked_add(len), start.checked_add(size.max(24))) else { continue };
if len < 4 || end > lim {
continue;
}
let Some(jpeg) = bytes.get(j..end) else { continue };
// One that doesn't fit the budget left is skipped; a smaller one later may still fit.
if walked + jpeg.len() > CR3_MAX_WALK {
continue;
}
walked += jpeg.len();
if is_dct_jpeg(jpeg) {
if best.is_none_or(|b| b.len() < jpeg.len()) {
best = Some(jpeg);
}
// the whole file searched (its media data not found): the first valid box of a kind only, as
// the declared one comes before the media data and a later look-alike must not win
let mut taken = false;
for &bytes in &regions {
if whole_file && taken {
break;
}
let mut from = 0;
while let Some(i) = bytes.get(from..).and_then(|s| s.windows(4).position(|w| w == tag)).map(|p| p + from) {
from = i + 4;
let Some(start) = i.checked_sub(4) else { continue };
// (the sizes are the file's: checked, a 32-bit build must not wrap them)
let be32 = |at: usize| bytes.get(at..at.checked_add(4)?).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize);
let (Some(size), Some(len)) = (be32(start), start.checked_add(20).and_then(be32)) else { continue };
let (Some(j), Some(box_end)) = (start.checked_add(24), start.checked_add(size.max(24))) else { continue };
let Some(end) = j.checked_add(len).filter(|e| len >= 4 && *e <= box_end && *e <= bytes.len()) else { continue };
let Some(jpeg) = bytes.get(j..end) else { continue };
// One that doesn't fit the budget left is skipped; a smaller one later may still fit.
if walked.saturating_add(jpeg.len()) > CR3_MAX_WALK {
continue;
}
walked = walked.saturating_add(jpeg.len());
if is_dct_jpeg(jpeg) {
out.push(jpeg);
taken = true;
if whole_file {
break;
}
// (past it: a tag inside its JPEG is not another box)
from = end;
}
}
}
}
best
out
}
/// Where a CR3's top-level `mdat` boxes lie (`start..end` each, `end` clamped to the file, in file
/// order): the media data, most of the file. Empty when there is none, or the boxes stop making sense
/// before the first. The metadata and the small previews are in the other top-level boxes.
fn cr3_media_data(bytes: &[u8]) -> Vec<(usize, usize)> {
let mut out = Vec::new();
let _ = cr3_media_walk(bytes, &mut out);
out
}
/// [`cr3_media_data`]'s walk of the top-level boxes; `None` where they stop making sense.
fn cr3_media_walk(bytes: &[u8], out: &mut Vec<(usize, usize)>) -> Option<()> {
let be32 = |at: usize| bytes.get(at..at.checked_add(4)?).map(|s| u64::from(u32::from_be_bytes([s[0], s[1], s[2], s[3]])));
let be64 = |at: usize| bytes.get(at..at.checked_add(8)?).map(|s| u64::from_be_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]));
let mut at = 0usize;
for _ in 0..64 {
let size = be32(at)?;
let len = match size {
// (a box running to the end of the file)
0 => u64::try_from(bytes.len().saturating_sub(at)).unwrap_or(u64::MAX),
1 => be64(at.checked_add(8)?)?,
n => n,
};
let next = usize::try_from(len).ok().filter(|l| *l >= 8).and_then(|l| at.checked_add(l));
if bytes.get(at.checked_add(4)?..at.checked_add(8)?) == Some(b"mdat".as_slice()) {
out.push((at, next.unwrap_or(bytes.len()).min(bytes.len())));
}
at = next.filter(|n| *n < bytes.len())?;
}
None
}
/// Trim trailing garbage after the last EOI when a stored length over-reports.
+350
View File
@@ -296,6 +296,98 @@ fn cr3_prefers_the_full_size_jpeg_track() {
assert_eq!(embedded_preview(&file).unwrap(), small);
}
/// A CR3 whose `PRVW` box holds `prvw` and whose JPEG track holds `big`.
fn cr3_with(prvw_jpeg: &[u8], big: &[u8]) -> Vec<u8> {
let bx = |kind: &[u8; 4], body: &[u8]| -> Vec<u8> { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() };
let full = |kind: &[u8; 4], body: &[u8]| bx(kind, &[&[0u8; 4][..], body].concat());
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
let mut prvw = b"\0\0\0\0\0\x01\x06T\x048\0\x01".to_vec();
prvw.extend_from_slice(&(prvw_jpeg.len() as u32).to_be_bytes());
prvw.extend_from_slice(prvw_jpeg);
file.extend(bx(b"PRVW", &prvw));
let mut craw = vec![0u8; 82];
craw.extend(bx(b"JPEG", &[0; 4]));
let at = 4096u64;
let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat());
let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat());
let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat());
let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat()))));
file.extend(bx(b"moov", &trak));
file.resize(at as usize, 0);
file.extend_from_slice(big);
file
}
/// A CR3 thumbnail decodes the 1620 px `PRVW` copy, not the full-size JPEG (PERF-THUMB-FIRST:
/// 150 ms a photo for the full one); a size the copy can't cover, and the largest preview, are
/// still the full JPEG; a `PRVW` of another shape is never taken for the picture.
#[test]
fn cr3_thumbnails_take_the_smallest_copy_that_covers_them() {
let (prvw, big) = (sized_jpeg(1620, 1080, 3, 300), sized_jpeg(6000, 4000, 3, 3000));
let file = cr3_with(&prvw, &big);
assert_eq!(embedded_preview_covering(&file, 512).unwrap(), prvw);
assert_eq!(embedded_preview_covering(&file, 1620).unwrap(), prvw);
assert_eq!(embedded_preview_covering(&file, 2000).unwrap(), big);
assert_eq!(embedded_preview(&file).unwrap(), big);
let letterboxed = cr3_with(&sized_jpeg(1620, 1215, 3, 300), &big);
assert_eq!(embedded_preview_covering(&letterboxed, 512).unwrap(), big, "another shape is not a copy");
for n in (0..file.len()).step_by(13) {
let _ = embedded_preview_covering(&file[..n], 512);
}
}
/// PERF-CULL-4: the smallest preview that covers the size asked for, of the largest one's shape;
/// the largest when none covers it. A CR3's 8192 px track, 1620 px `PRVW` and 160 px `THMB`.
#[test]
fn the_smallest_preview_covering_the_size_is_chosen() {
let bx = |kind: &[u8; 4], body: &[u8]| -> Vec<u8> { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() };
let full = |kind: &[u8; 4], body: &[u8]| bx(kind, &[&[0u8; 4][..], body].concat());
let boxed = |j: &[u8]| {
let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec();
b.extend_from_slice(&(j.len() as u32).to_be_bytes());
b.extend_from_slice(j);
b
};
let (thmb, prvw, big) = (sized_jpeg(160, 107, 1, 50), sized_jpeg(1620, 1080, 1, 300), sized_jpeg(8192, 5464, 1, 3000));
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"THMB", &boxed(&thmb)));
file.extend(bx(b"PRVW", &boxed(&prvw)));
let mut craw = vec![0u8; 82];
craw.extend(bx(b"JPEG", &[0; 4]));
let at = 4096u64;
let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat());
let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat());
let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat());
let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat()))));
file.extend(bx(b"moov", &trak));
file.resize(at as usize, 0);
file.extend_from_slice(&big);
assert_eq!(embedded_preview(&file).unwrap(), big);
assert_eq!(embedded_preview_covering(&file, 512).unwrap(), prvw, "a grid thumbnail");
assert_eq!(embedded_preview_covering(&file, 1620).unwrap(), prvw);
assert_eq!(embedded_preview_covering(&file, 100).unwrap(), thmb);
assert_eq!(embedded_preview_covering(&file, 2560).unwrap(), big, "a large loupe");
assert_eq!(embedded_preview_covering(&file, u32::MAX).unwrap(), big);
// a smaller preview of another shape (letterboxed 16:9) is never a stand-in for the 3:2 one
let mut wide = file.clone();
let p = wide.windows(4).position(|w| w == b"PRVW").unwrap();
// the JPEG starts 20 bytes after the tag; its frame height 7 bytes into it
let height = p + 20 + 7;
wide[height..height + 2].copy_from_slice(&911u16.to_be_bytes());
assert_eq!(embedded_preview_covering(&wide, 512).unwrap(), big);
// without the JPEG track the boxes are chosen from too: the smallest that covers, else the largest
// (CodeRabbit on #3577: a box-only CR3 always gave its largest box)
let boxes_only = &file[..file.windows(4).position(|w| w == b"moov").unwrap() - 4];
assert_eq!(embedded_preview_covering(boxes_only, 100).unwrap(), thmb);
assert_eq!(embedded_preview_covering(boxes_only, 512).unwrap(), prvw);
assert_eq!(embedded_preview_covering(boxes_only, 2560).unwrap(), prvw, "none covers: the largest");
assert_eq!(embedded_preview(boxes_only).unwrap(), prvw);
// damaged files never panic
for n in (0..file.len()).step_by(7) {
let _ = embedded_preview_covering(&file[..n], 512);
}
}
/// A minimal CR3 whose Canon box holds `CMT2` (EXIF ColorSpace `exif`) and `CMT3` (maker-note ColorSpace `note`).
fn cr3_with_color_space(exif: Option<u16>, note: Option<u16>) -> Vec<u8> {
let bx = |kind: &[u8; 4], body: &[u8]| -> Vec<u8> { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() };
@@ -502,3 +594,261 @@ fn scanned_containers_give_the_largest_colour_jpeg() {
f.extend_from_slice(&mosaic);
assert_eq!(embedded_preview(&f), None);
}
/// A CR3's `PRVW` / `THMB` boxes are searched outside the media data only, but before and after
/// it: a `moov` after the `mdat` (its Canon `uuid` holding the `THMB`) still gives its preview, and
/// bytes inside the media data that look like a preview box are never taken for one.
#[test]
fn cr3_preview_boxes_after_the_media_data_are_found() {
let bx = |kind: &[u8; 4], body: &[u8]| -> Vec<u8> { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() };
let boxed = |j: &[u8]| {
let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec();
b.extend_from_slice(&(j.len() as u32).to_be_bytes());
b.extend_from_slice(j);
b
};
let (thmb, in_media) = (sized_jpeg(160, 107, 1, 50), sized_jpeg(1620, 1080, 1, 300));
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"mdat", &bx(b"PRVW", &boxed(&in_media))));
file.extend(bx(b"moov", &bx(b"uuid", &[&[0x85u8; 16][..], &bx(b"THMB", &boxed(&thmb))].concat())));
assert_eq!(embedded_preview(&file).unwrap(), thmb);
for n in (0..file.len()).step_by(5) {
let _ = embedded_preview(&file[..n]);
}
}
/// Every valid `PRVW` of a CR3 is a candidate (CodeRabbit on #3055): with a small one first and
/// one that covers the size after it, a thumbnail takes the second, not the full-size track.
#[test]
fn a_cr3_with_two_prvw_boxes_offers_both() {
let bx = |kind: &[u8; 4], body: &[u8]| -> Vec<u8> { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() };
let full = |kind: &[u8; 4], body: &[u8]| bx(kind, &[&[0u8; 4][..], body].concat());
let boxed = |j: &[u8]| {
let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec();
b.extend_from_slice(&(j.len() as u32).to_be_bytes());
b.extend_from_slice(j);
b
};
let (small, covering, big) = (sized_jpeg(300, 200, 1, 50), sized_jpeg(1620, 1080, 1, 300), sized_jpeg(8192, 5464, 1, 3000));
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"PRVW", &boxed(&small)));
file.extend(bx(b"PRVW", &boxed(&covering)));
let mut craw = vec![0u8; 82];
craw.extend(bx(b"JPEG", &[0; 4]));
let at = 4096u64;
let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat());
let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat());
let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat());
let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat()))));
file.extend(bx(b"moov", &trak));
// (the track in the media data, as a camera writes it, after a `free` box up to it)
let pad = at as usize - 16 - file.len();
file.extend(bx(b"free", &vec![0u8; pad]));
file.extend(bx(b"mdat", &big));
assert_eq!(embedded_preview_covering(&file, 1024).unwrap(), covering);
assert_eq!(embedded_preview_covering(&file, 200).unwrap(), small);
}
/// A CR3 preview box claiming the largest sizes a file can give is skipped, never wrapped or
/// panicked on (CodeRabbit on #3080: on a 32-bit build the plain sums could overflow).
#[test]
fn a_cr3_preview_box_with_hostile_sizes_is_skipped() {
let mut file = b"\0\0\0\x18ftypcrx \0\0\0\x01crx isom".to_vec();
file.extend_from_slice(&u32::MAX.to_be_bytes());
file.extend_from_slice(b"PRVW\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01");
file.extend_from_slice(&u32::MAX.to_be_bytes());
file.extend_from_slice(&fake_jpeg(64));
assert!(embedded_preview(&file).is_none());
assert!(embedded_preview_covering(&file, 64).is_none());
}
/// A corrupt raw whose preview pointer (JPEGInterchangeFormat and its length) lies past the end
/// of the file, or whose length runs past it, finds no preview and never panics; a real preview
/// beside the lying pointer is still found (FredApps on #3080: the preview must be read with
/// bounds on its offset and size).
#[test]
fn a_preview_pointer_past_the_end_of_the_file_finds_no_preview() {
let real = sized_jpeg(640, 480, 3, 200);
let lying = |off: u32, len: u32, with_real: bool| {
let mut ifd = IfdBuilder::new();
ifd.set(t::JPEG_INTERCHANGE_FORMAT, Value::Long(vec![off]));
ifd.set(t::JPEG_INTERCHANGE_FORMAT_LENGTH, Value::Long(vec![len]));
if with_real {
ifd.set(t::COMPRESSION, Value::Short(vec![6]));
ifd.set(t::IMAGE_WIDTH, Value::Long(vec![1]));
ifd.set(t::IMAGE_LENGTH, Value::Long(vec![1]));
ifd.set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![real.clone()] });
}
TiffWriter::default().write(&[ifd]).unwrap()
};
let short = lying(0, 0, false).len() as u32;
for (off, len) in [(u32::MAX, u32::MAX), (u32::MAX, 16), (short + 10, 4096), (8, u32::MAX), (short - 2, u32::MAX - 1)] {
let file = lying(off, len, false);
assert_eq!(embedded_preview(&file), None, "pointer {off:#x}+{len:#x} in a {} byte file", file.len());
assert_eq!(embedded_preview_covering(&file, 64), None);
assert_eq!(embedded_preview_color_space(&file), None);
let with_real = lying(off, len, true);
assert_eq!(embedded_preview(&with_real).as_deref(), Some(&real[..]), "the strip preview beside pointer {off:#x}+{len:#x}");
// and every truncation of the file (a raw cut short by a failed copy) is safe too
for n in 0..with_real.len() {
let _ = embedded_preview_covering(&with_real[..n], 64);
}
}
}
/// A preview pointer whose length runs past the end of a file that cuts its JPEG short (no end
/// marker) finds no preview, so a smaller whole one wins; an overstated length whose JPEG is whole
/// inside the file still finds it (CodeRabbit on #3077).
#[test]
fn a_preview_cut_short_by_the_end_of_the_file_is_not_taken() {
let big = sized_jpeg(1600, 1200, 3, 4000);
let small = sized_jpeg(160, 120, 3, 100);
// the small JPEG as a strip, the big one pointed to at the end of the file
let with_tail = |tail: &[u8], declared: u32| {
let probe = {
let mut ifd = IfdBuilder::new();
ifd.set(t::JPEG_INTERCHANGE_FORMAT, Value::Long(vec![0]));
ifd.set(t::JPEG_INTERCHANGE_FORMAT_LENGTH, Value::Long(vec![0]));
ifd.set(t::COMPRESSION, Value::Short(vec![6]));
ifd.set(t::IMAGE_WIDTH, Value::Long(vec![1]));
ifd.set(t::IMAGE_LENGTH, Value::Long(vec![1]));
ifd.set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![small.clone()] });
ifd
};
let at = TiffWriter::default().write(&[probe]).unwrap().len() as u32;
let mut ifd = IfdBuilder::new();
ifd.set(t::JPEG_INTERCHANGE_FORMAT, Value::Long(vec![at]));
ifd.set(t::JPEG_INTERCHANGE_FORMAT_LENGTH, Value::Long(vec![declared]));
ifd.set(t::COMPRESSION, Value::Short(vec![6]));
ifd.set(t::IMAGE_WIDTH, Value::Long(vec![1]));
ifd.set(t::IMAGE_LENGTH, Value::Long(vec![1]));
ifd.set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![small.clone()] });
let mut file = TiffWriter::default().write(&[ifd]).unwrap();
assert_eq!(file.len() as u32, at, "the pointer lands right after the TIFF");
file.extend_from_slice(tail);
file
};
// the big one with a start of scan after its frame header (sized_jpeg has none), as a real JPEG
let mut big = big;
big.splice(21..21, [0xff, 0xda, 0x00, 0x02]);
let declared = big.len() as u32 + 64;
// cut short: half of the big JPEG, no end marker
let cut = with_tail(&big[..big.len() / 2], declared);
assert_eq!(embedded_preview(&cut).as_deref(), Some(&small[..]), "the truncated JPEG is not taken");
// whole, its length overstated past the file's end: still the largest
let whole = with_tail(&big, declared);
assert_eq!(embedded_preview(&whole).as_deref(), Some(&big[..]), "a whole JPEG with an overstated length is kept");
// an end marker inside an APP1 payload is not the JPEG's end: cut short, still not taken
let mut with_app = vec![0xff, 0xd8, 0xff, 0xe1, 0x00, 0x08, 0x12, 0xff, 0xd9, 0x34, 0x56, 0x78];
with_app.extend_from_slice(&big[2..]);
let declared = with_app.len() as u32 + 64;
let cut = with_tail(&with_app[..with_app.len() / 2], declared);
assert_eq!(embedded_preview(&cut).as_deref(), Some(&small[..]), "an FF D9 in APP1 doesn't make a cut JPEG whole");
// whole, with other bytes after it up to the file's end: kept, cut at its own end marker
let mut tail = with_app.clone();
tail.extend_from_slice(&[0x11, 0xff, 0xd9, 0x22]);
let whole = with_tail(&tail, declared);
assert_eq!(embedded_preview(&whole).as_deref(), Some(&with_app[..]), "a whole JPEG is cut at its own end");
// an end marker before any start of scan: no image data, not taken (CodeRabbit on #3080)
let unscanned = sized_jpeg(1600, 1200, 3, 4000);
let whole = with_tail(&unscanned, unscanned.len() as u32 + 64);
assert_eq!(embedded_preview(&whole).as_deref(), Some(&small[..]), "a JPEG without a scan is not taken");
}
/// The walk to a JPEG's end refuses what isn't one and never runs past the bytes it has.
#[test]
fn the_end_of_a_jpeg_is_its_own_end_marker() {
let jpeg_end = |s: &[u8]| super::jpeg_end(s, &mut (1usize << 20));
assert_eq!(jpeg_end(&[0x12, 0x34, 0xff, 0xd9]), None, "not a JPEG");
assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xd9]), None, "an end before any scan: no image data");
// a stuffed zero and a restart marker in the scan data, then the end
assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xda, 0x00, 0x02, 0x55, 0xff, 0x00, 0xff, 0xd3, 0x66, 0xff, 0xd9]), Some(14));
// a segment length of 0 or 1, or one running past the end
assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xe1, 0x00, 0x01, 0xff, 0xd9]), None);
assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xe1, 0xff, 0xff, 0xff, 0xd9]), None);
for n in 0..12 {
assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xe1, 0x00, 0x04, 0xff, 0xd9, 0x55, 0xff, 0xff, 0xff][..n]), None, "{n} bytes");
}
}
/// CodeRabbit on #3080: the walks to a JPEG's end share one budget, so a file of many pointers past
/// its end can't make each walk run the whole file: a walk that would overspend it gives up.
#[test]
fn the_walks_to_a_jpegs_end_share_a_budget() {
use super::jpeg_end;
let mut j = vec![0xff, 0xd8, 0xff, 0xda, 0x00, 0x02];
j.extend(std::iter::repeat_n(0x55u8, 1000));
j.extend_from_slice(&[0xff, 0xd9]);
let mut budget = 1500;
assert_eq!(jpeg_end(&j, &mut budget), Some(j.len()), "the first walk fits");
assert!(budget < 1500 - 1000, "and is charged for its steps: {budget} left");
assert_eq!(jpeg_end(&j, &mut budget), None, "the second would overspend what is left");
assert_eq!(budget, 0);
}
/// A CR3 without a JPEG track whose smaller `PRVW` (another shape) takes more bytes: the picture is
/// the box with the most pixels, not the most bytes (CodeRabbit on #3077).
#[test]
fn a_box_only_cr3_is_judged_by_pixels_not_bytes() {
let bx = |kind: &[u8; 4], body: &[u8]| -> Vec<u8> { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() };
let boxed = |j: &[u8]| {
let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec();
b.extend_from_slice(&(j.len() as u32).to_be_bytes());
b.extend_from_slice(j);
b
};
let (big, square) = (sized_jpeg(1620, 1080, 3, 300), sized_jpeg(800, 800, 3, 5000));
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"PRVW", &boxed(&square)));
file.extend(bx(b"PRVW", &boxed(&big)));
// no media data found: the whole file is searched, and only its first box counts (a later look-alike could be
// in media data; CodeRabbit on #3583)
assert_eq!(embedded_preview(&file).unwrap(), square);
file.extend(bx(b"mdat", &[0u8; 16]));
assert_eq!(embedded_preview(&file).unwrap(), big);
assert_eq!(embedded_preview_covering(&file, 100).unwrap(), big, "the square is another picture's shape");
}
/// Every top-level `mdat` is media data, not only the first: a PRVW-shaped JPEG in a second one is
/// never the preview; and a `PRVW` cut short before its end marker isn't chosen to cover a size
/// (CodeRabbit on #3583).
#[test]
fn cr3_boxes_in_any_media_data_or_cut_short_are_not_previews() {
let bx = |kind: &[u8; 4], body: &[u8]| -> Vec<u8> { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() };
let boxed = |j: &[u8]| {
let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec();
b.extend_from_slice(&(j.len() as u32).to_be_bytes());
b.extend_from_slice(j);
b
};
let (real, fake) = (sized_jpeg(1620, 1080, 3, 300), sized_jpeg(3000, 2000, 3, 300));
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"PRVW", &boxed(&real)));
file.extend(bx(b"mdat", &[0u8; 64]));
file.extend(bx(b"mdat", &bx(b"PRVW", &boxed(&fake))));
assert_eq!(embedded_preview(&file).unwrap(), real, "the look-alike in the second mdat is media data");
// a PRVW cut short (no end marker): the full-size track covers a thumbnail instead
let mut short = real.clone();
short.truncate(real.len() - 2);
let big = sized_jpeg(6000, 4000, 3, 3000);
assert_eq!(embedded_preview_covering(&cr3_with(&short, &big), 512).unwrap(), big);
assert_eq!(embedded_preview_covering(&cr3_with(&real, &big), 512).unwrap(), real, "a whole one is still taken");
}
/// The copy a CR3 thumbnail is given decodes, whichever is chosen (CodeRabbit on #3583: the other CR3 fixtures have
/// no scan): real encoded JPEGs, the `PRVW` for a small size, the full-size track past it.
#[test]
fn the_cr3_copy_chosen_for_a_thumbnail_decodes() {
let encode = |w: u16, h: u16| {
let px: Vec<u8> = (0..usize::from(w) * usize::from(h)).flat_map(|i| [(i % 251) as u8, 90, 160]).collect();
let mut j = Vec::new();
jpeg_encoder::Encoder::new(&mut j, 85).encode(&px, w, h, jpeg_encoder::ColorType::Rgb).unwrap();
j
};
let file = cr3_with(&encode(96, 64), &encode(384, 256));
for (min, want) in [(64u32, (96, 64)), (200, (384, 256))] {
let j = embedded_preview_covering(&file, min).unwrap();
let (_, w, h, c) = crate::tiffraw::lossy_jpeg(&j, 3, 1 << 20).unwrap();
assert_eq!(((w, h), c), (want, 3), "covering {min} px");
}
}
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff. Show more