Refresh LightCraft UI port on current main

This commit is contained in:
skylartaylor
2026-12-02 15:36:56 +01:00
99 changed files with 5039 additions and 713 deletions
Generated
+3
View File
@@ -5955,6 +5955,7 @@ dependencies = [
"lightcraft-develop",
"lightcraft-faces",
"lightcraft-geom",
"lightcraft-gpu",
"lightcraft-pipeline",
"lightcraft-raster",
"lightcraft-raw",
@@ -6006,6 +6007,7 @@ dependencies = [
"lightcraft-raster",
"lightcraft-raw",
"lightcraft-scenes",
"log",
"rayon",
"serde",
"thiserror 2.0.21",
@@ -6162,6 +6164,7 @@ dependencies = [
"lightcraft-engine",
"lightcraft-faces",
"lightcraft-geom",
"lightcraft-gpu",
"lightcraft-merge",
"lightcraft-meta",
"lightcraft-pipeline",
+2 -1
View File
@@ -515,7 +515,8 @@ at `warn`. `LIGHTCRAFT_LOG=info` or `debug` works as before (that level for Ligh
errors from the rest; any other value: warnings and errors only) and wins over `RUST_LOG`, which otherwise replaces
the default with env_logger-style directives such as `RUST_LOG=debug` or `RUST_LOG=warn,lightcraft_pipeline=trace` (a
directive ending in `*` covers every target starting with it, as in `lightcraft*=debug`). Panics are recorded there
too, and still in `lightcraft-panics.log` in the temp folder. The logger is `apps/lightcraft/src/logging.rs`.
too, and in `lightcraft-panics.log` in the settings folder; runs with `--memory` or `LIGHTCRAFT_NO_PREFS` report
them on standard error only. The logger is `apps/lightcraft/src/logging.rs`.
The web build needs the `wasm32-unknown-unknown` target and the matching `wasm-bindgen` CLI
(`cargo xtask web` prints the exact install command); see [docs/web.md](docs/web.md).
+2 -1
View File
@@ -436,7 +436,8 @@ CRAFT_FONTS_DIR=../craft-fonts cargo run --release -p lightcraft
错误;其他值:只记警告和错误),并且优先于 `RUST_LOG`,后者会把默认值替换为
env_logger 风格的指令,例如 `RUST_LOG=debug` 或 `RUST_LOG=warn,lightcraft_pipeline=trace`(以
`*` 结尾的指令覆盖所有以它开头的目标,如 `lightcraft*=debug`)。panic 也会记录在那里,
并且仍然写在临时文件夹里的 `lightcraft-panics.log`。日志器是 `apps/lightcraft/src/logging.rs`。
并且写在设置文件夹里的 `lightcraft-panics.log`;带 `--memory` 或
`LIGHTCRAFT_NO_PREFS` 运行时只写到标准错误。日志器是 `apps/lightcraft/src/logging.rs`。
网页版需要 `wasm32-unknown-unknown` target 和匹配的 `wasm-bindgen` CLI
(`cargo xtask web` 会打印确切的安装命令);见 [docs/web.md](docs/web.md)。
+2 -1
View File
@@ -462,7 +462,8 @@ CRAFT_FONTS_DIR=../craft-fonts cargo run --release -p lightcraft
用該層級,其餘只記警告與錯誤;其他值:只記警告與錯誤),並且優先於 `RUST_LOG`;未設定 `LIGHTCRAFT_LOG` 時,`RUST_LOG` 會把預設值換成
env_logger 風格的指令,例如 `RUST_LOG=debug` 或 `RUST_LOG=warn,lightcraft_pipeline=trace`(以
`*` 結尾的指令會涵蓋所有以它開頭的目標,如 `lightcraft*=debug`)。panic 一樣會記錄在那裡,
並且仍然會寫在暫存資料夾裡的 `lightcraft-panics.log`。記錄器程式碼位於 `apps/lightcraft/src/logging.rs`。
並且會寫在設定資料夾裡的 `lightcraft-panics.log`;帶 `--memory` 或
`LIGHTCRAFT_NO_PREFS` 執行時只會寫到標準錯誤輸出。記錄器程式碼位於 `apps/lightcraft/src/logging.rs`。
網頁版需要 `wasm32-unknown-unknown` target 以及對應版本的 `wasm-bindgen` CLI
(`cargo xtask web` 會印出確切的安裝指令);詳見 [docs/web.md](docs/web.md)。
+7 -2
View File
@@ -12,7 +12,7 @@ from [docs/gaps.md](docs/gaps.md). The full assessment, method and evidence are
| | Value | Kind |
|---|---:|---|
| **Feature breadth** (checklist) | **81.6%** of 532 rows (P0 98.0%, P1 95.2%, P2 50.0%) | measured: [parity-checklist.md](docs/parity-checklist.md) recount |
| **Feature breadth** (checklist) | **83.2%** of 546 rows (P0 97.5%, P1 94.2%, P2 56.7%) | measured: [parity-checklist.md](docs/parity-checklist.md) recount |
| **Feature breadth** (weighted by use) | **~77%** | estimated |
| **Ready for real work** (full target) | **~62%** (57–67%) | estimated: weighted sum over the dimensions |
| **Mainstream practitioner** | **~51%** (46–56%) | estimated |
@@ -44,7 +44,7 @@ Hours are calibrated on this repo's PR history; see
| Dimension | Ready | Breadth | Remaining | Doc |
|---|---:|---:|---:|---|
| Features | ~61% | ~77% (checklist 81.1%) | 600–1,100 h | [target-app-parity](docs/target-app-parity.md#features) |
| Features | ~61% | ~77% (checklist 83.2%) | 600–1,100 h | [target-app-parity](docs/target-app-parity.md#features) |
| ↳ RAW cameras, colour, lens profiles | ~60% | 85% of 1,446 Adobe models decode, 39% verified | 255–480 h | [raw-parity](docs/raw-parity.md) |
| UI/UX fidelity | ~70% | ~85% | 32–54 h | [ui-parity](docs/ui-parity.md) |
| File formats (non-raw) | ~70% | ~85% | 30–55 h | [file-format-parity](docs/file-format-parity.md) |
@@ -122,6 +122,10 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
六切 (203 × 254), 四切 (254 × 305) and 名刺 (55 × 91) — at their exact metric sizes. The Print dialog
and `print.set` take their customary names, and names are matched case-, space- and
punctuation-insensitively (`L判`, `l`, `L-size` are one paper).
- 2026-10-21: Panorama diagnostics identify omitted source photos, including all exposures in HDR
brackets. Synthetic regressions reproduce rejected genuine transforms and show why a lower
inlier fraction alone is unsafe. Registration of the full waterfall sequence remains open (#1765).
- 2026-10-13: Canon CRW (the 2000–2004 CIFF bodies) decodes from sensor data: compression
derived clean-room against a black-box reference and frozen (`craft-libs crates/crw/clean-room/02-crw-format.md`);
EOS D30/D60/10D/300D and PowerShot G1/G6 verified pixel-exact on 28 of 29 corpus files (18 of
@@ -205,6 +209,7 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
| 2026-10-22 | minor | Print: Japanese photo and postcard paper sizes (L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺) in the page setup, Print dialog and PDF output; headline numbers unchanged |
| 2026-10-22 | minor | Tone Curve input histogram (#987); headline counts and readiness estimates unchanged. See [the stage contract](docs/tone-curve-input.md). |
| 2026-10-19 | minor | Indonesian interface (`id`): every plain and formats message, plus 69 command labels, locale, menu command and tests; What's New left in English; Localization ~55% → ~64% (mean of the 12 key languages), 8 of 12 present |
| 2026-10-21 | minor | Panorama and HDR panorama marked partial (#1765): omitted photos are reported; verification remains unresolved. Checklist recount 83.5% to 83.3% (543 rows); refreshed the stale headline from the checklist. Readiness estimates unchanged |
| 2026-10-13 | minor | Canon CRW decoded (clean-room): 6 bodies verified pixel-exact, G5 preview; 551 models verified after merging the coverage sweep |
| 2026-10-12 | minor | Italian interface (`it`, #1192): 2,201 of 2,398 messages, locale, menu command and tests; headline numbers unchanged |
| 2026-10-13 | minor | Sony ILCA-99M2 camera colour profile in the log; numbers unchanged |
+136 -28
View File
@@ -105,19 +105,47 @@ pub(crate) fn control_port_from(what: &str, value: Option<String>) -> Option<u16
port
}
/// An isolated profile keeps the emergency crash log with its other app data: the Nightly profile's
/// settings folder, else `LIGHTCRAFT_CONFIG_DIR`, else (no override, or an empty one) the historical
/// system-temp location. The profile wins because Nightly refuses `LIGHTCRAFT_CONFIG_DIR`, and a
/// shared temp file would put a Nightly crash in Stable's log.
pub(crate) fn panic_log_path_with(
env: impl Fn(&str) -> Option<std::ffi::OsString>,
temp: std::path::PathBuf,
profile: Option<std::path::PathBuf>,
) -> std::path::PathBuf {
if let Some(root) = profile.filter(|root| !root.as_os_str().is_empty()) {
return root.join("Settings").join("lightcraft-panics.log");
/// The emergency crash log: `lightcraft-panics.log` in the settings folder, next to `ui.json` (an
/// isolated profile's with `LIGHTCRAFT_CONFIG_DIR`). Never the system temp folder: on Linux and
/// FreeBSD every user shares it, so another could create the file first or put a link there (issue
/// #2572). None (panics then go to standard error, and to the log file when there is one) for a
/// `--memory` session, which writes nothing (issue #164), with `LIGHTCRAFT_NO_PREFS` or with no
/// settings folder.
fn panic_log_path(in_memory: bool) -> Option<std::path::PathBuf> {
panic_log_path_with(in_memory, std::env::var_os("LIGHTCRAFT_NO_PREFS").is_some(), config_dir)
}
/// `config` (the settings folder) is looked up only when the crash log is kept.
fn panic_log_path_with(in_memory: bool, no_prefs: bool, config: impl FnOnce() -> Option<std::path::PathBuf>) -> Option<std::path::PathBuf> {
if in_memory || no_prefs {
return None;
}
config().map(|d| d.join("lightcraft-panics.log"))
}
/// Prepare only the selected settings directory before installing the emergency hook. A new profile
/// may not have reached the normal logger yet; if preparation fails, keep the stderr fallback.
fn prepare_panic_log(path: std::path::PathBuf) -> Option<std::path::PathBuf> {
let mut dirs = std::fs::DirBuilder::new();
dirs.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
dirs.mode(0o700);
}
dirs.create(path.parent()?).ok()?;
Some(path)
}
/// The panic hooks: the engine guard's (standard error, and the crash log when there is one), then
/// the log file's.
pub(crate) fn install_panic_hooks(logger: Option<&'static super::logging::AppLogger>, in_memory: bool) {
if let Some(path) = panic_log_path(in_memory).and_then(prepare_panic_log) {
lightcraft_engine::guard::install_hook(path);
}
if let Some(logger) = logger {
super::logging::record_panics(logger);
}
env("LIGHTCRAFT_CONFIG_DIR").filter(|value| !value.is_empty()).map(std::path::PathBuf::from).unwrap_or(temp).join("lightcraft-panics.log")
}
/// What to tell the user when LightCraft stopped while running (`error`), and why when the GPU
@@ -169,25 +197,105 @@ pub(crate) fn startup_failed(error: &str, log_file: Option<&std::path::Path>) {
mod config_path_tests {
use super::*;
/// #2572: the crash log is in the settings folder (an isolated profile's too: `config_dir` honours
/// `LIGHTCRAFT_CONFIG_DIR`); without one (an empty override, no home folder), with
/// `LIGHTCRAFT_NO_PREFS` or in a `--memory` session there is none, and the last two never look the
/// folder up.
#[test]
fn config_override_keeps_panic_log_in_isolated_profile() {
let temp = std::path::PathBuf::from("temp");
assert_eq!(panic_log_path_with(|_| Some("isolated".into()), temp.clone(), None), std::path::PathBuf::from("isolated/lightcraft-panics.log"));
assert_eq!(panic_log_path_with(|_| None, temp.clone(), None), temp.join("lightcraft-panics.log"));
assert_eq!(panic_log_path_with(|_| Some("".into()), temp.clone(), None), temp.join("lightcraft-panics.log"));
fn panic_log_lives_in_the_settings_folder() {
let settings = || Some(std::path::PathBuf::from("settings"));
assert_eq!(panic_log_path_with(false, false, settings), Some(std::path::Path::new("settings").join("lightcraft-panics.log")));
assert_eq!(panic_log_path_with(false, false, || None), None);
let unasked = || -> Option<std::path::PathBuf> { panic!("the settings folder was looked up") };
assert_eq!(panic_log_path_with(false, true, unasked), None);
assert_eq!(panic_log_path_with(true, false, unasked), None);
}
/// Nightly's crash log lives in its own profile's settings folder, never in Stable's temp file,
/// and an inherited LIGHTCRAFT_CONFIG_DIR cannot move it out again.
/// The emergency hook works before the logger creates a new profile's directory, but leaves
/// no files or settings directory in no-persistence modes. A child isolates the panic hook
/// and active profile; both possible settings paths and the temp directory are synthetic.
#[test]
fn nightly_profile_owns_the_panic_log() {
let temp = std::path::PathBuf::from("temp");
let profile = std::path::PathBuf::from("/launcher/profiles/lightcraft");
assert_eq!(
panic_log_path_with(|_| Some("stable settings".into()), temp.clone(), Some(profile.clone())),
profile.join("Settings/lightcraft-panics.log")
);
assert_eq!(panic_log_path_with(|_| None, temp.clone(), Some(profile.clone())), profile.join("Settings/lightcraft-panics.log"));
assert_eq!(panic_log_path_with(|_| None, temp.clone(), Some("".into())), temp.join("lightcraft-panics.log"));
fn a_panic_is_kept_in_the_settings_folder_not_the_temp_folder() {
if let Ok(mode) = std::env::var("LIGHTCRAFT_TEST_PANIC_LOG") {
let root = std::path::PathBuf::from(std::env::var_os("LIGHTCRAFT_TEST_PANIC_ROOT").unwrap());
let settings = if mode == "nightly" {
let profile = root.join("nightly");
let settings = profile.join("Settings");
lightcraft_engine::config::set_profile_root(profile).unwrap();
settings
} else {
root.join("settings")
};
assert_eq!(config_dir(), Some(settings.clone()));
assert!(!settings.exists(), "the logger has not initialized these settings");
if mode == "existing" {
std::fs::create_dir(&settings).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&settings, std::fs::Permissions::from_mode(0o750)).unwrap();
}
}
#[cfg(unix)]
let before = if mode == "existing" {
use std::os::unix::fs::PermissionsExt;
Some(std::fs::metadata(&settings).unwrap().permissions().mode())
} else {
None
};
install_panic_hooks(None, mode == "memory");
let persists = mode != "memory" && mode != "no-prefs";
if persists {
assert!(settings.is_dir(), "{mode}: settings directory was not prepared");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let after = std::fs::metadata(&settings).unwrap().permissions().mode();
if let Some(before) = before {
assert_eq!(after, before, "existing settings permissions were changed");
} else {
assert_eq!(after & 0o077, 0, "{mode}: fresh settings directory is not private");
}
}
} else {
assert!(!settings.exists(), "{mode}: settings directory was created by startup");
}
assert!(std::thread::spawn(|| panic!("lc-2572 probe")).join().is_err());
let kept = std::fs::read_to_string(settings.join("lightcraft-panics.log")).unwrap_or_default();
assert_eq!(kept.contains("lc-2572 probe"), persists, "{mode}: {kept:?}");
if !persists {
assert!(!settings.exists(), "{mode}: the hook created a settings directory");
}
assert!(!root.join("temp/lightcraft-panics.log").exists(), "{mode}: crash log fell back to temp");
if mode == "nightly" {
assert!(!root.join("settings").exists(), "Nightly did not initialize the other profile");
}
return;
}
let scratch = std::env::temp_dir().join(format!("lightcraft-panic-log-{}", std::process::id()));
std::fs::create_dir(&scratch).unwrap();
for mode in ["first-run", "nightly", "existing", "memory", "no-prefs"] {
let root = scratch.join(mode);
let temp = root.join("temp");
std::fs::create_dir_all(&temp).unwrap();
let mut child = std::process::Command::new(std::env::current_exe().unwrap());
child
.args(["--exact", "launch::config_path_tests::a_panic_is_kept_in_the_settings_folder_not_the_temp_folder", "--nocapture"])
.env("LIGHTCRAFT_TEST_PANIC_LOG", mode)
.env("LIGHTCRAFT_TEST_PANIC_ROOT", &root)
.env("LIGHTCRAFT_CONFIG_DIR", root.join("settings"))
.env_remove("LIGHTCRAFT_NO_PREFS")
.env("TMPDIR", &temp)
.env("TMP", &temp)
.env("TEMP", &temp);
if mode == "no-prefs" {
child.env("LIGHTCRAFT_NO_PREFS", "1");
}
let out = child.output().unwrap();
assert!(out.status.success(), "{mode}: {}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
}
std::fs::remove_dir_all(&scratch).unwrap();
}
}
+2 -2
View File
@@ -341,8 +341,8 @@ pub fn install() -> Option<&'static AppLogger> {
Some(logger)
}
/// Chain a panic hook after the current one (the engine guard's: standard error plus
/// `lightcraft-panics.log` in the temp folder) that also puts the panic in the log file.
/// Chain a panic hook after the current one (the engine guard's when there is a crash log: standard
/// error plus `lightcraft-panics.log` in the settings folder) that also puts the panic in the log file.
pub fn record_panics(logger: &'static AppLogger) {
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
+5 -11
View File
@@ -71,7 +71,7 @@ use gpu_crash::{gpu_crash_check_at, gpu_crash_notice, window_wgpu_options};
#[cfg(test)]
use launch::launch_imports_in;
use launch::{
HELP, LaunchArgs, control_port_from, launch_imports, launch_library_choice, log_dir, panic_log_path_with, startup_failed, stopped_text,
HELP, LaunchArgs, control_port_from, install_panic_hooks, launch_imports, launch_library_choice, log_dir, startup_failed, stopped_text,
stopped_while_running,
};
#[cfg(test)]
@@ -450,16 +450,6 @@ fn main() -> eframe::Result {
}
// First, so every start-up record is kept for the log file (`logging`).
let logger = logging::install();
// The crash log follows the profile: Nightly keeps it in <profile>/Settings, never in the shared
// system-temp file Stable writes.
lightcraft_engine::guard::install_hook(panic_log_path_with(
|name| std::env::var_os(name),
std::env::temp_dir(),
lightcraft_engine::config::profile_root().map(std::path::Path::to_path_buf),
));
if let Some(logger) = logger {
logging::record_panics(logger);
}
alloc_release::install();
let nightly = launch_profile::current().is_nightly();
// Nightly has no control server: an inherited port variable or flag must not open a socket the
@@ -489,6 +479,10 @@ fn main() -> eframe::Result {
if !nightly && let Some(value) = control {
control_port = control_port_from("--control", Some(value));
}
// Like the log file, after the arguments: `--version`, `--help` and a usage error create no
// portable `LightCraftData` folder for the crash log (a panic until here still reaches
// standard error).
install_panic_hooks(logger, in_memory);
// The log file: opened after the arguments, so `--version`, `--help` and a usage error leave
// no file behind. Records logged until now are written to it first.
let mut log_file = None;
+52 -5
View File
@@ -68,6 +68,7 @@
//! | 12 | history steps and versions share segmentation grids (#2154) | `Catalog.grids`, `SegMask.grid` |
//! | 13 | Lens Blur | `DevelopSettings.lens_blur`, `Mask.adjust.lens_blur` |
//! | 14 | bursts arranged by hand in Assisted Culling | `Analysis.rank` |
//! | 15 | per-photo denoiser selection | `DevelopSettings.enhance.denoise_model` |
//!
//! Rules:
//! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a
@@ -98,6 +99,8 @@
//! later snapshot (compaction, or closing), which first keeps the files as they were at open
//! (the snapshot, and the log up to where it ended then) and is not written when it can't. Those
//! files stay even if that snapshot then fails and the library is still in its old format.
//! Until the new snapshot is written, ops carrying a denoiser pin use a journal tag older
//! builds refuse. Otherwise they would accept the op and silently drop the new field.
//! - **A newer format is refused, untouched**: a snapshot whose `version` is above [`VERSION`],
//! or a log record whose CRC matches (so it is exactly what was written) but whose op doesn't
//! parse, fails [`Journal::open`] with [`CatalogError::Newer`] before any file is modified — it
@@ -112,7 +115,7 @@ pub const LOG: &str = "catalog.log";
const FORMAT: &str = "lightcraft-catalog";
/// The catalog format this build writes (and the newest it reads). See the module docs →
/// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added.
pub const VERSION: u32 = 14;
pub const VERSION: u32 = 15;
/// When [`Journal::wants_snapshot`] says it's time to compact the log.
#[derive(Clone, Copy, Debug)]
@@ -301,11 +304,33 @@ fn io(e: std::io::Error) -> CatalogError {
/// One log line (without the newline) for op number `seq`.
pub fn encode_record(seq: u64, op: &Op) -> String {
let body = serde_json::to_string(op).unwrap_or_default();
record(seq, serde_json::to_string(op).unwrap_or_default())
}
fn record(seq: u64, body: String) -> String {
let crc = crc32fast::hash(body.as_bytes());
format!("{{\"seq\":{seq},\"crc\":{crc},\"op\":{body}}}")
}
/// A log-only tag for an edit whose snapshot does not yet protect its denoiser pin.
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(tag = "op", rename_all = "camelCase")]
enum ProtectedOp<T> {
PinnedDenoise { change: T },
}
fn has_denoiser_pin(op: &Op) -> bool {
match op {
Op::AddPhoto { photo } => photo.settings_holders().any(|s| s.enhance.denoise_model.is_some()),
Op::SetDevelop { settings, .. } => settings.enhance.denoise_model.is_some(),
Op::SetVersions { versions, .. } => versions.iter().any(|v| v.settings.enhance.denoise_model.is_some()),
Op::SetHistory { history, .. } => history.iter().any(|h| h.settings.enhance.denoise_model.is_some()),
Op::PushHistory { step, .. } => step.settings.enhance.denoise_model.is_some(),
Op::Batch { ops } => ops.iter().any(has_denoiser_pin),
_ => false,
}
}
/// Parse one log line (without the newline). `None` if it's malformed, the CRC doesn't match, or
/// the op is one this version doesn't know (see [`Journal::open`]).
pub fn decode_record(line: &str) -> Option<(u64, Op)> {
@@ -337,7 +362,7 @@ fn decode_line(line: &str) -> Line {
if crc32fast::hash(body.as_bytes()) != crc {
return Line::Bad;
}
match serde_json::from_str(body) {
match serde_json::from_str(body).or_else(|_| serde_json::from_str(body).map(|ProtectedOp::PinnedDenoise { change }| change)) {
Ok(op) => Line::Record(seq, op),
Err(_) => Line::Newer(seq),
}
@@ -500,7 +525,19 @@ impl Journal {
/// modified), or if the library is in an older format and its damaged log can't be replaced,
/// its snapshot can't be kept, or it can't be told whether its upgrade was written (see the
/// module docs → *Format versions*).
pub fn open(mut store: Box<dyn Store>) -> Result<(Journal, Catalog, LoadReport)> {
/// When unassigned denoise edits in an old library need their previous global model,
/// use [`Self::open_with_legacy_denoise`] to supply it.
pub fn open(store: Box<dyn Store>) -> Result<(Journal, Catalog, LoadReport)> {
Self::open_with_legacy_denoise(store, || Err(CatalogError::Invalid("opening this older library requires its previous denoise model".into())))
}
/// Open a library with access to the previous globally selected denoiser. The resolver
/// runs only if an older catalog holds denoise settings that need that model's identity.
/// The pins are written in the same snapshot as the format upgrade and add no history.
pub fn open_with_legacy_denoise(
mut store: Box<dyn Store>,
resolve: impl FnOnce() -> Result<lightcraft_develop::DenoiseModelPin>,
) -> Result<(Journal, Catalog, LoadReport)> {
let mut report = LoadReport::default();
let snap = store.read(SNAPSHOT).map_err(io)?;
let log = store.read(LOG).map_err(io)?;
@@ -624,6 +661,9 @@ impl Journal {
// is appended: a snapshot in this format makes older builds refuse the library instead
// of misreading ops or dropping fields they don't know.
let older = (!report.created && snapshot_version != Some(VERSION)).then(|| snapshot_version.unwrap_or(0));
if older.is_some() {
catalog.pin_legacy_denoise(resolve)?;
}
if let Some(at) = damaged_at {
let name = format!("{LOG}.damaged-{}", j.seq);
j.store.write_atomic(&name, &log).map_err(io)?;
@@ -655,6 +695,8 @@ impl Journal {
let empty = format!("{{\"format\":\"{FORMAT}\",\"version\":{VERSION},\"seq\":0,\"catalog\":{}}}\n", catalog.to_snapshot());
if let Err(e) = j.store.write_atomic(SNAPSHOT, empty.as_bytes()) {
log::warn!("catalog: can't write the new library's snapshot: {e}");
// Until its first snapshot is durable, even a new library is log-only.
j.behind = Some(0);
}
} else if let (Some(from), None) = (older, &report.damaged) {
// The library may go on as it is when it can't be upgraded now (the next open tries
@@ -864,7 +906,12 @@ impl Journal {
let mut seq = self.seq;
for op in ops {
seq = seq.checked_add(1).ok_or_else(|| CatalogError::Corrupt(format!("{LOG}: op counter overflow")))?;
buf.push_str(&encode_record(seq, op));
let line = if self.behind.is_some() && has_denoiser_pin(op) {
record(seq, serde_json::to_string(&ProtectedOp::PinnedDenoise { change: op }).unwrap_or_default())
} else {
encode_record(seq, op)
};
buf.push_str(&line);
buf.push('\n');
}
if self.tail_dirty {
+22 -1
View File
@@ -45,7 +45,7 @@ use index::file_path;
pub use index::{file_name_index_key, folder_index_key, photo_folder_index_key};
pub use journal::{Journal, LoadReport, PersistStats, SnapshotPolicy, SnapshotTiming};
pub use keywords::KeywordNode;
use lightcraft_develop::DevelopSettings;
use lightcraft_develop::{DenoiseModelPin, DevelopSettings};
pub use local::{DEFAULT_FORGET_DAYS, ForgetPlan, LocalRecords, folder_of};
pub use lock::{LibraryLock, LockError, LockOwner};
pub use model::*;
@@ -751,6 +751,27 @@ impl Catalog {
// ---- writes
/// Freeze a pre-v15 library's global denoiser before writing its upgraded snapshot.
fn pin_legacy_denoise(&mut self, resolve: impl FnOnce() -> Result<DenoiseModelPin>) -> Result<()> {
let needs_pin = |settings: &DevelopSettings| settings.enhance.needs_denoise_model();
let mut photos = self.photos.values_mut().filter(|photo| photo.settings_holders().any(|s| needs_pin(s)));
let Some(first) = photos.next() else { return Ok(()) };
let pin = resolve()?;
for p in std::iter::once(first).chain(photos) {
let p = Arc::make_mut(p);
self.index.text_moved(p.id, p);
let at_baseline = p.local_baseline.is_some_and(|b| b == p.fingerprint());
for settings in p.settings_holders_mut().filter(|s| needs_pin(s)) {
Arc::make_mut(settings).enhance.denoise_model = Some(pin.clone());
*settings = shared::settings(settings.clone());
}
if at_baseline {
p.set_local_baseline();
}
}
Ok(())
}
fn photo_mut(&mut self, id: PhotoId) -> Result<&mut Photo> {
self.touch(id);
let p = self.photos.get_mut(&id).map(Arc::make_mut).ok_or(CatalogError::NoPhoto(id))?;
+34 -3
View File
@@ -577,8 +577,8 @@ impl Photo {
.chain(self.history.iter().map(|h| &h.settings))
.chain(self.import_look.iter())
}
/// [`Photo::settings_holders`] with mutable access (resolving a snapshot's grid references).
pub(crate) fn settings_holders_mut(&mut self) -> impl Iterator<Item = &mut Arc<DevelopSettings>> {
/// Every stored develop state, including the import look, history and versions.
pub fn settings_holders_mut(&mut self) -> impl Iterator<Item = &mut Arc<DevelopSettings>> {
let Photo { develop, versions, history, import_look, .. } = self;
std::iter::once(develop)
.chain(versions.iter_mut().map(|v| &mut v.settings))
@@ -687,7 +687,7 @@ impl Photo {
if self.develop.wb.mode == WbMode::AsShot && defaults.wb.mode == WbMode::AsShot {
defaults.wb = self.develop.wb;
}
*self.develop != defaults && !self.develop.is_unedited()
!self.develop.matches_default_look(defaults) && !self.develop.is_unedited()
}
/// Capture time if known, else import time (sort key).
pub fn date(&self) -> &str {
@@ -767,6 +767,37 @@ mod edited_tests {
assert!(!p.is_edited(), "a full reset is unedited too");
}
#[test]
fn an_inactive_denoiser_choice_keeps_a_raw_unedited() {
use lightcraft_develop::DenoiseModelPin;
let mut p = Photo::new(PhotoId(1), Source::Demo { scene: 0 }, "a.arw", "ARW", 10, 10, "2026-10-01T00:00:00");
p.kind = MediaKind::Raw;
p.as_shot_wb = Some((5200.0, 4.0));
let pin = DenoiseModelPin { id: "example".into(), version: "1".into(), sha256: Some("a".repeat(64)) };
let mut picked = p.import_defaults();
picked.enhance.denoise_model = Some(pin.clone());
p.develop = Arc::new(picked);
assert!(!p.is_edited(), "choosing a model alone leaves the raw as imported");
Arc::make_mut(&mut p.develop).light.exposure = 0.5;
assert!(p.is_edited(), "the exposure adjustment still counts");
let mut preset = p.camera_defaults();
preset.light.exposure = 0.25;
preset.enhance.denoise = 60.0;
preset.enhance.denoise_on = Some(false);
p.import_look = Some(Arc::new(preset.clone()));
let mut picked = preset.clone();
picked.enhance.denoise_model = Some(pin);
p.develop = Arc::new(picked);
assert!(!p.is_edited(), "choosing a model also preserves a preset's look with denoise off");
preset.enhance.denoise_on = Some(true);
p.import_look = Some(Arc::new(preset));
Arc::make_mut(&mut p.develop).enhance.denoise_on = Some(true);
assert!(p.is_edited(), "a different model at the preset's active amount changes the look");
}
#[test]
fn the_process_a_photo_renders_with_is_not_an_edit() {
use lightcraft_develop::ProcessVersion;
+2
View File
@@ -132,11 +132,13 @@ impl Catalog {
/// Ops that dissolve every stack containing one of `photos`.
pub fn ungroup_ops(&self, photos: &[PhotoId]) -> Vec<Op> {
let photos: HashSet<PhotoId> = photos.iter().copied().collect();
self.stacks.values().filter(|s| s.photos.iter().any(|p| photos.contains(p))).map(|s| Op::RemoveStack { id: s.id }).collect()
}
/// Ops that take `photos` out of their stacks (a stack left with one photo is dissolved).
pub fn remove_from_stacks_ops(&self, photos: &[PhotoId]) -> Vec<Op> {
let photos: HashSet<PhotoId> = photos.iter().copied().collect();
self.stacks
.values()
.filter(|s| s.photos.iter().any(|p| photos.contains(p)))
+125 -2
View File
@@ -219,6 +219,129 @@ fn v13_analysis_loads_unarranged_and_is_upgraded() {
assert_eq!(again.photo(id).unwrap().analysis, Some(b));
}
#[test]
fn v14_denoiser_is_pinned_during_upgrade_and_only_once() {
let mut base = Catalog::new();
let id = base.alloc_photo_id();
let mut local = Photo::new(id, Source::File { path: "/p/a.dng".into() }, "a.dng", "DNG", 160, 120, "2026-01-01");
local.local = true;
Arc::make_mut(&mut local.develop).enhance.denoise = 25.0;
Arc::make_mut(&mut local.develop).enhance.denoise_on = Some(false);
local.import_look = Some(local.develop.clone());
local.set_local_baseline();
base.apply(Op::AddPhoto { photo: Box::new(local) }).unwrap();
let id2 = base.alloc_photo_id();
let mut other = Photo::new(id2, Source::File { path: "/p/b.dng".into() }, "b.dng", "DNG", 160, 120, "2026-01-01");
let legacy_pin = DenoiseModelPin { id: "legacy".into(), version: "1".into(), sha256: Some("a".repeat(64)) };
let existing_pin = DenoiseModelPin { id: "existing".into(), version: "2".into(), sha256: None };
let mut pinned = DevelopSettings::default();
pinned.enhance.denoise = 40.0;
pinned.enhance.denoise_model = Some(existing_pin.clone());
other.versions.push(Version { name: "Saved".into(), created: "then".into(), settings: Arc::new(pinned), auto: false });
let unedited = other.develop.clone();
base.apply(Op::AddPhoto { photo: Box::new(other) }).unwrap();
let mut step = DevelopSettings::default();
step.enhance.denoise_on = Some(true);
let op = Op::PushHistory { id: id2, step: HistoryStep { label: "Denoise".into(), settings: Arc::new(step) } };
let m = MemStore::new();
let old = format!("{{\"format\":\"lightcraft-catalog\",\"version\":14,\"seq\":2,\"catalog\":{}}}\n", base.to_snapshot()).into_bytes();
m.set(SNAPSHOT, old.clone());
let log = format!("{}\n", encode_record(3, &op)).into_bytes();
m.set(LOG, log.clone());
assert!(matches!(Journal::open(Box::new(m.clone())), Err(CatalogError::Invalid(why)) if why.contains("previous denoise model")));
assert_eq!(m.get(SNAPSHOT), Some(old.clone()));
assert_eq!(m.get(LOG), Some(log.clone()));
let err = CatalogError::Io("cannot preserve the global model".into());
assert_eq!(
Journal::open_with_legacy_denoise(Box::new(m.clone()), || Err(CatalogError::Io("cannot preserve the global model".into()))).err(),
Some(err)
);
assert_eq!(m.get(SNAPSHOT), Some(old.clone()));
assert_eq!(m.get(LOG), Some(log));
let (_, loaded, report) = Journal::open_with_legacy_denoise(Box::new(m.clone()), || Ok(legacy_pin.clone())).unwrap();
assert_eq!((report.replayed, report.upgraded_from), (1, Some(14)));
assert_eq!(m.get(&report.kept[0]), Some(old));
let first = loaded.photo(id).unwrap();
assert!(first.untouched_local());
assert_eq!(first.develop.enhance.denoise_on, Some(false));
assert_eq!(first.develop.enhance.denoise_model.as_ref(), Some(&legacy_pin));
assert_eq!(first.import_look.as_ref().unwrap().enhance.denoise_model.as_ref(), Some(&legacy_pin));
let second = loaded.photo(id2).unwrap();
assert_eq!(second.develop, unedited);
assert_eq!(second.history[0].settings.enhance.denoise_model.as_ref(), Some(&legacy_pin));
assert_eq!(second.versions[0].settings.enhance.denoise_model.as_ref(), Some(&existing_pin));
let snapshot = m.get(SNAPSHOT);
let (_, reopened, report) = Journal::open_with_legacy_denoise(Box::new(m.clone()), || panic!("already migrated")).unwrap();
assert_eq!(report.upgraded_from, None);
assert_eq!(reopened.to_snapshot(), loaded.to_snapshot());
assert_eq!(m.get(SNAPSHOT), snapshot);
}
#[test]
fn pinned_ops_protect_a_library_until_its_current_snapshot_is_durable() {
use std::sync::atomic::{AtomicBool, Ordering};
static FULL: AtomicBool = AtomicBool::new(true);
for old_library in [true, false] {
FULL.store(true, Ordering::SeqCst);
let files = MemStore::new();
let (base, old_log, _) = legacy_parts();
let old_snap = format!("{{\"format\":\"lightcraft-catalog\",\"version\":14,\"seq\":2,\"catalog\":{}}}\n", base.to_snapshot());
if old_library {
files.set(SNAPSHOT, old_snap.as_bytes().to_vec());
files.set(LOG, old_log.as_bytes().to_vec());
}
let store = Refusing { files: files.clone(), refuse: |name| name == SNAPSHOT && FULL.load(Ordering::SeqCst) };
let (mut journal, mut catalog, report) = Journal::open(Box::new(store)).unwrap();
assert_eq!(report.upgraded_from, None);
let seq = journal.seq();
let add = photo(&mut catalog);
catalog.apply(add.clone()).unwrap();
let id = catalog.photos().next().unwrap().id;
let rating = Op::SetRating { id, rating: 1 };
let mut develop = DevelopSettings::default();
develop.enhance.denoise_model = Some(DenoiseModelPin { id: "custom".into(), version: "2".into(), sha256: Some("a".repeat(64)) });
let develop = Arc::new(develop);
let pinned = Op::Batch { ops: vec![Op::SetDevelop { id, settings: develop.clone(), label: "Model".into(), edited: None }] };
catalog.apply(rating.clone()).unwrap();
catalog.apply(pinned.clone()).unwrap();
journal.append(&[add, rating.clone(), pinned.clone()]).unwrap();
let log = String::from_utf8(files.get(LOG).unwrap()).unwrap();
let mut tail = log.lines().rev();
let protected = tail.next().unwrap();
assert_eq!(tail.next().unwrap(), encode_record(seq + 2, &rating), "an ordinary edit stays readable");
assert_eq!(journal::decode_record(protected), Some((seq + 3, pinned.clone())));
// The v14 reader verifies the CRC, then deserializes the body directly as Op.
// A valid CRC with an unknown op is Newer, which refuses the library untouched.
let record: serde_json::Value = serde_json::from_str(protected).unwrap();
let body = protected.split_once(",\"op\":").unwrap().1.strip_suffix('}').unwrap();
assert_eq!(record["crc"].as_u64(), Some(u64::from(crc32fast::hash(body.as_bytes()))));
assert!(serde_json::from_str::<Op>(body).is_err());
// Reopening after a crash replays the tagged change from the log.
let crashed = MemStore::new();
if old_library {
crashed.set(SNAPSHOT, old_snap.as_bytes().to_vec());
}
crashed.set(LOG, log.into_bytes());
let (_, reopened, _) = Journal::open(Box::new(crashed)).unwrap();
assert_eq!(reopened.photo(id).unwrap().develop, develop);
FULL.store(false, Ordering::SeqCst);
journal.snapshot(&catalog).unwrap();
if old_library {
assert_eq!(files.get("catalog.snap.v14-3"), Some(old_snap.into_bytes()));
assert_eq!(files.get("catalog.log.v14-3"), Some(old_log.into_bytes()));
}
journal.append(std::slice::from_ref(&pinned)).unwrap();
assert_eq!(String::from_utf8(files.get(LOG).unwrap()).unwrap(), encode_record(seq + 4, &pinned) + "\n");
}
}
/// Guard for the version rule (see `journal` → *Format versions*): adding an [`Op`] variant breaks
/// this match. When it does, bump `journal::VERSION`, add a row to the format table, and add the
/// variant here under the new version. A version that only adds serialized fields raises
@@ -265,9 +388,9 @@ fn op_variants_are_versioned() {
Op::SetHistoryCursor { .. } => 8,
}
}
/// v14: `Analysis.rank` (v13: Lens Blur in develop settings and mask adjustments; v12: `Catalog.grids` and `SegMask.grid`;
/// v15: `Enhance.denoise_model` (v14: `Analysis.rank`; v13: Lens Blur; v12: `Catalog.grids` and `SegMask.grid`;
/// v11: `EmbeddedLens.source`; v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`).
const NEWEST_FIELDS: u32 = 14;
const NEWEST_FIELDS: u32 = 15;
let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None });
assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version");
}
+101 -16
View File
@@ -203,22 +203,77 @@ struct Scratch {
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) {
/// A group (`m` blocks of `n × n`, one after the other in `buf`) back from the transform domain.
fn group_inverse(tf: &Transform, buf: &mut [f32], m: usize, s: &mut Scratch) {
let nn = tf.n * tf.n;
s.tmp.resize(nn, 0.0);
if !forward {
haar_columns(buf, m, nn, s, false);
}
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);
tf.inverse(blk, &mut s.tmp);
}
}
/// The 2-D DCT of the blocks of one plane, each worked out the first time a group asks for it: a block joins many
/// groups, and its coefficients do not depend on the group.
#[derive(Default)]
struct BlockCoeffs {
/// The coefficients of block `i`, at `i * n * n`.
data: Vec<f32>,
/// Whether block `i` is in `data` yet.
done: Vec<bool>,
/// Blocks along a side of the plane.
nb: usize,
}
impl BlockCoeffs {
/// Forget the blocks, for a plane of `t × t` cells that holds blocks of `n × n`.
fn reset(&mut self, t: usize, n: usize) {
self.nb = (t + 1).saturating_sub(n);
let count = self.nb * self.nb;
self.done.clear();
self.done.resize(count, false);
if self.data.len() < count * n * n {
self.data = vec![0.0; count * n * n];
}
}
if forward {
haar_columns(buf, m, nn, s, true);
/// A group (`members` are the blocks' top-left cells) in the transform domain: the blocks' DCTs one after the other
/// in `out`, then the Haar transform across them.
fn group(&mut self, tf: &Transform, plane: &[f32], t: usize, members: &[u32], out: &mut Vec<f32>, s: &mut Scratch) {
let n = tf.n;
let nn = n * n;
s.tmp.resize(nn, 0.0);
out.clear();
for &pos in members {
let (x, y) = (pos as usize % t.max(1), pos as usize / t.max(1));
let idx = y * self.nb + x;
if x < self.nb && y < self.nb {
let hit = self.done.get(idx).copied().unwrap_or(false);
if let (Some(slot), false) = (self.data.get_mut(idx * nn..(idx + 1) * nn), hit) {
for (j, dst) in slot.chunks_exact_mut(n).enumerate() {
let at = pos as usize + j * t;
match plane.get(at..at + n) {
Some(row) => dst.copy_from_slice(row),
None => dst.fill(0.0),
}
}
tf.forward(slot, &mut s.tmp);
if let Some(d) = self.done.get_mut(idx) {
*d = true;
}
}
if let Some(slot) = self.data.get(idx * nn..(idx + 1) * nn) {
out.extend_from_slice(slot);
continue;
}
}
// a block outside the plane's grid: not cached
let mut one = Vec::new();
gather(plane, t, n, &[pos], &mut one);
tf.forward(&mut one, &mut s.tmp);
out.extend_from_slice(&one);
}
haar_columns(out, members.len(), nn, s, true);
}
}
@@ -376,16 +431,18 @@ fn collaborate(y: &[Vec<f32>], pilot: Option<&[Vec<f32>]>, groups: &[Vec<u32>],
let lambda = lambda * sigma;
let mut s = Scratch::default();
let (mut buf, mut pbuf) = (Vec::new(), Vec::new());
let (mut cache, mut pcache) = (BlockCoeffs::default(), BlockCoeffs::default());
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));
cache.reset(t, n);
pcache.reset(t, n);
for members in groups {
let m = members.len();
gather(plane, t, n, members, &mut buf);
group_transform(tf, &mut buf, m, &mut s, true);
cache.group(tf, plane, t, members, &mut buf, &mut s);
let weight = match pilot_plane {
None => {
let mut kept = 0usize;
@@ -399,8 +456,7 @@ fn collaborate(y: &[Vec<f32>], pilot: Option<&[Vec<f32>]>, groups: &[Vec<u32>],
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);
pcache.group(tf, pl, t, members, &mut pbuf, &mut s);
let mut energy = 0f32;
for (v, &q) in buf.iter_mut().zip(&pbuf) {
let w = q * q / (q * q + sigma * sigma);
@@ -410,7 +466,7 @@ fn collaborate(y: &[Vec<f32>], pilot: Option<&[Vec<f32>]>, groups: &[Vec<u32>],
1.0 / energy.max(1e-3)
}
};
group_transform(tf, &mut buf, m, &mut s, false);
group_inverse(tf, &mut buf, m, &mut s);
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;
@@ -523,6 +579,35 @@ mod tests {
.collect()
}
/// The cached group transform gives bit for bit what gathering the blocks and transforming each one does, for
/// matched groups, repeated blocks and the last block of the grid, whatever order the blocks are asked for.
#[test]
fn the_cached_group_transform_matches_transforming_each_block() {
let (t, n) = (24, 8);
let nb = t + 1 - n;
let tf = Transform::new(n);
let planes = noisy(t, 3.0, 11);
let plane = &planes[0];
let mut groups = match_groups(plane, t, n, 3, 6, 8, 2.0 * 2.0);
groups.push(vec![5, 5, 7, 5]);
groups.push(vec![(nb * t + nb - 1) as u32, 0, (nb * t + nb - 1) as u32, (nb - 1) as u32]);
let (mut cache, mut s) = (BlockCoeffs::default(), Scratch::default());
cache.reset(t, n);
let (mut got, mut want) = (Vec::new(), Vec::new());
for members in groups.iter().chain(groups.iter().rev()) {
let m = members.len();
cache.group(&tf, plane, t, members, &mut got, &mut s);
gather(plane, t, n, members, &mut want);
let mut tmp = vec![0f32; n * n];
for blk in want.chunks_exact_mut(n * n) {
tf.forward(blk, &mut tmp);
}
haar_columns(&mut want, m, n * n, &mut s, true);
assert_eq!(got.len(), want.len());
assert!(got.iter().zip(&want).all(|(a, b)| a.to_bits() == b.to_bits()), "group {members:?}");
}
}
/// 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();
+56 -7
View File
@@ -39,16 +39,19 @@ impl DevelopSettings {
serde_json::from_value(v.clone())
}
/// [`Self::to_json`] with Remove Hot Pixels (`detail.nr_outliers`) and AI Defringe (`optics.ai_defringe`,
/// `optics.ai_defringe_on`) stated even at their defaults, 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.
/// [`Self::to_json`] with the defaults for Remove Hot Pixels, AI Denoise and AI Defringe
/// stated explicitly for copy / paste, presets and Auto Sync. A merge needs to see a
/// default value when copying it must clear the target's setting. The stored JSON leaves
/// these defaults out so existing settings keep their hashes.
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));
}
if let Some(enhance) = v.get_mut("enhance").and_then(Value::as_object_mut) {
enhance.entry("denoise_on").or_insert(Value::Null);
enhance.entry("denoise_model").or_insert(Value::Null);
}
// AI Defringe's Amount and switch are left out at their defaults too: a paste from a photo without it must
// switch it off
if let Some(optics) = v.get_mut("optics").and_then(Value::as_object_mut) {
@@ -73,6 +76,13 @@ impl DevelopSettings {
pub fn merged(&self, partial: &Value) -> Result<DevelopSettings, serde_json::Error> {
let mut v = self.to_json();
presets::deep_merge(&mut v, partial);
// An exact model identity is a single choice; a partial must never retain the
// previous model's SHA when the new identity has no SHA.
if let Some(model) = partial.get("enhance").and_then(|e| e.get("denoise_model"))
&& let Some(enhance) = v.get_mut("enhance").and_then(Value::as_object_mut)
{
enhance.insert("denoise_model".into(), model.clone());
}
let mut out = DevelopSettings::from_json(&v)?;
if let Some(wb) = partial.get("wb").and_then(Value::as_object)
&& (wb.contains_key("temp") || wb.contains_key("tint"))
@@ -121,16 +131,25 @@ impl DevelopSettings {
h
}
/// True if nothing differs from a fresh default (ignoring white balance "as shot" values, and
/// the rendering process: that is not an edit).
/// True if nothing differs from a fresh default, ignoring as-shot white balance, the
/// rendering process and a denoiser choice on its own.
pub fn is_unedited(&self) -> bool {
let mut a = self.clone();
let d = DevelopSettings::default();
a.wb = d.wb;
a.process = d.process;
a.enhance.denoise_model = None;
a == d
}
/// Compare to a photo's default look, ignoring only the remembered model when AI Denoise contributes nothing.
pub fn matches_default_look(&self, mut defaults: Self) -> bool {
if self.enhance.denoise_model != defaults.enhance.denoise_model && self.denoise_amount() == 0.0 {
defaults.enhance.denoise_model.clone_from(&self.enhance.denoise_model);
}
self == &defaults
}
pub fn section_enabled(&self, section: &str) -> bool {
!self.disabled_sections.iter().any(|s| s == section)
}
@@ -202,6 +221,7 @@ impl DevelopSettings {
Section::Optics => self.optics.ai_defringe_on = None,
Section::Detail => {
self.enhance.denoise_on = None;
self.enhance.denoise_model = None;
// not a slider: reset like them, to the general default (off)
self.detail.nr_outliers = false;
}
@@ -557,6 +577,35 @@ mod tests {
assert_eq!(s.enhance.denoise_on, None);
}
#[test]
fn detail_copies_the_entire_denoiser_identity_or_clears_it() {
let original = DevelopSettings::default();
let saved = original.to_json();
assert!(saved["enhance"].get("denoise_model").is_none());
assert_eq!(DevelopSettings::from_json(&saved).unwrap().hash64(), original.hash64());
let mut target = original.clone();
target.enhance.denoise_model = Some(DenoiseModelPin { id: "external".into(), version: "1".into(), sha256: Some("a".repeat(64)) });
assert!(target.is_unedited());
assert_ne!(target.hash64(), original.hash64());
target.enhance.denoise_on = Some(false);
let mut picked = original.clone();
picked.enhance.denoise_model = Some(DenoiseModelPin { id: "builtin".into(), version: "5".into(), sha256: None });
let groups = &[SettingsGroup::Detail];
let patch = extract_groups(&picked, groups);
assert_eq!(apply_partial(&target, &patch, 0.25).enhance.denoise_model, target.enhance.denoise_model);
for amount in [0.5, 1.0] {
let applied = apply_partial(&target, &patch, amount);
assert_eq!(applied.enhance.denoise_model, picked.enhance.denoise_model);
assert!(applied.enhance.denoise_on.is_none());
}
let cleared = apply_partial(&target, &extract_groups(&original, groups), 1.0);
assert_eq!(cleared.enhance, original.enhance);
picked.reset_section(Section::Detail);
assert!(picked.enhance.denoise_model.is_none());
}
#[test]
fn next_mask_id_after_the_highest_id_is_unused() {
// ids come from files, pastes and agents: one at the limit must not overflow (a panic in
+2
View File
@@ -257,6 +257,8 @@ fn interpolate_object(base: Option<&Map<String, Value>>, patch: &Map<String, Val
bv.cloned()
}
}
// A model's id, version and digest are one discrete choice.
Value::Object(_) if k == "denoise_model" => interpolate_leaf(bv, pv, t),
Value::Object(p) => Some(Value::Object(interpolate_object(bv.and_then(Value::as_object), p, t))),
_ => interpolate_leaf(bv, pv, t),
};
+33 -6
View File
@@ -109,20 +109,27 @@ pub enum Process {
/// V10, calibrated against Lightroom exports of real edits: global Shadows answers large amounts
/// compressively (`lightcraft_pipeline::finish::tone_slider`), a negative Texture smooths less
/// (`finish::texture_slider`) and the Global grading wheel tints less (`colorops::global_wheel`).
/// `ProcessVersion(11)` and `ProcessVersion(12)` name no process here (12 is left to the open claim
/// of #4047): a saved 11 or 12 renders as V10.
/// `ProcessVersion(11)` and `ProcessVersion(12)` name no process: a saved 11 or 12 renders as V10.
V13,
/// V13, with Heal and Remove spots pinned to the photo on the spot's edge: the correction is a
/// membrane fill of the log ratio of photo to source, the source's fine detail is matched to its
/// surroundings, and every spot reads its source at whole pixels
/// (`lightcraft_pipeline::spots::HealMethod`).
V14,
/// V14, with brush Flow as the coverage a stroke adds per brush radius it travels, as in
/// Lightroom: a dab adds `1 − (1 − flow)^(distance from the previous dab / radius)`, so a
/// stroke's strength no longer depends on how densely its dabs lie; V1 to V14 add `flow` per dab.
V15,
/// V15, with a brush stroke's edge feathered as one dab's is: a stroke's coverage is its Flow
/// build-up times the highest falloff of the dabs that reach a point, so overlapping dabs no
/// longer pile their soft edges up into a hard one; V1 to V15 accumulate each dab's falloff.
V16,
}
impl Process {
/// Every process, oldest first (`ProcessVersion(9)` names none and renders as V8; 11 and 12 name none and
/// render as V10, 12 being claimed by an open pull request).
pub const ALL: [Process; 11] = [
/// render as V10).
pub const ALL: [Process; 13] = [
Process::V1,
Process::V2,
Process::V3,
@@ -134,8 +141,10 @@ impl Process {
Process::V10,
Process::V13,
Process::V14,
Process::V15,
Process::V16,
];
pub const LATEST: Process = Process::V14;
pub const LATEST: Process = Process::V16;
pub const fn version(self) -> ProcessVersion {
match self {
@@ -150,6 +159,8 @@ impl Process {
Process::V10 => ProcessVersion(10),
Process::V13 => ProcessVersion(13),
Process::V14 => ProcessVersion(14),
Process::V15 => ProcessVersion(15),
Process::V16 => ProcessVersion(16),
}
}
}
@@ -1488,12 +1499,23 @@ impl Default for LensBlur {
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
/// The model identity saved with a photo's denoise settings.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct DenoiseModelPin {
pub id: String,
pub version: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sha256: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Enhance {
pub denoise: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub denoise_on: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub denoise_model: Option<DenoiseModelPin>,
pub raw_details: bool,
pub super_resolution: bool,
}
@@ -1502,6 +1524,11 @@ impl Enhance {
pub fn denoise_enabled(&self) -> bool {
self.denoise_on.unwrap_or(self.denoise > 0.0)
}
/// Remember the model when denoise is enabled, or when a disabled switch retains a positive amount.
pub fn needs_denoise_model(&self) -> bool {
self.denoise_model.is_none() && (self.denoise_enabled() || self.denoise > 0.0)
}
}
/// HDR editing. When enabled, an HDR render ([`Hdr::peak`]) keeps highlights above SDR white (1.0)
+2 -1
View File
@@ -97,7 +97,8 @@ use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights};
/// dark, with skewed colour. The same for a DNG's tone fit; a CR3 proxy gets the gain where its framed pixels come from.
/// 27: geometry-gated external lens and camera framing for JPEG calibration correspondences.
/// 28: a fitted matrix whose rows aren't led by their own channel is refused (#3973).
pub const LOOK_VERSION: u32 = 28;
/// 29: resolved lens geometry can align CR3 camera-JPEG colour and tone samples against the existing framing fallback.
pub const LOOK_VERSION: u32 = 29;
#[derive(Clone, Debug)]
pub(crate) struct CameraLook {
+2 -5
View File
@@ -126,11 +126,8 @@ pub(super) fn starting_colour_with(
(xy, t, look.or_else(|| dark(raw, &t)))
}
/// Additional profile resolution for this proposal's pooled/DNG routes; CR3 keeps Main's route.
/// Resolve the file or database correction before the pooled and DNG colour fits remove lens opcodes.
pub(crate) fn correspondence_correction(raw: &RawImage, bytes: &[u8]) -> Option<lightcraft_develop::EmbeddedLens> {
if raw.format == RawFormat::Cr3 {
return None;
}
crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(bytes))
}
@@ -152,7 +149,7 @@ pub(super) fn starting_colour_tags_with_correction(
bytes: &[u8],
correction: Option<&lightcraft_develop::EmbeddedLens>,
) -> Option<ColorData> {
let correction = correction.filter(|_| raw.format != RawFormat::Cr3).map(|correction| lightcraft_develop::EmbeddedLens {
let correction = correction.map(|correction| lightcraft_develop::EmbeddedLens {
vignette: crate::files::embedded_lens(&raw.info()).and_then(|lens| lens.vignette),
..*correction
});
+13 -8
View File
@@ -325,7 +325,7 @@ pub(super) fn database_vignetting(
reference: &Rgb32f,
clipped: &[bool],
vignette: &lightcraft_develop::EmbeddedVignette,
frame: ProxyFrame,
frame: ProxyFrame<'_>,
) {
let amount = camera_vignetting_amount(sensor, reference, clipped, vignette, frame);
apply_vignetting(sensor, vignette, frame, amount);
@@ -338,15 +338,17 @@ pub(super) fn database_vignetting(
/// moved to its camera JPEG's framing, [`super::proxy::framed_proxies`]) takes each pixel to the position it shows, and
/// `orientation` maps that position to the oriented frame.
#[derive(Clone, Copy, Debug)]
pub(super) struct ProxyFrame {
pub(super) struct ProxyFrame<'a> {
pub(super) orientation: lightcraft_geom::Orientation,
pub(super) framing: Option<Cr3Framing>,
/// Accepted lens warp in the oriented CR3 crop, applied after the JPEG framing.
pub(super) lens: Option<&'a lightcraft_develop::EmbeddedLens>,
}
impl ProxyFrame {
impl ProxyFrame<'_> {
/// A proxy whose pixels are where they were sampled, in the frame `orientation` maps to the oriented one.
pub(super) fn new(orientation: lightcraft_geom::Orientation) -> Self {
Self { orientation, framing: None }
Self { orientation, framing: None, lens: None }
}
}
@@ -404,7 +406,7 @@ pub(super) fn camera_vignetting_amount(
reference: &Rgb32f,
clipped: &[bool],
vignette: &lightcraft_develop::EmbeddedVignette,
frame: ProxyFrame,
frame: ProxyFrame<'_>,
) -> f64 {
vignetting_amount_from_gains(sensor, reference, clipped, vignetting_gains(sensor, vignette, frame))
}
@@ -450,10 +452,11 @@ pub(super) fn vignetting_amount_from_gains(sensor: &Rgb32f, reference: &Rgb32f,
/// The render's vignetting gain (`optics::embedded_vignette_gain`) at each pixel of `sensor`, at the position `frame`
/// gives it in the oriented, cropped frame `vignette` is in.
pub(super) fn vignetting_gains(sensor: &Rgb32f, vignette: &lightcraft_develop::EmbeddedVignette, frame: ProxyFrame) -> Vec<f64> {
pub(super) fn vignetting_gains(sensor: &Rgb32f, vignette: &lightcraft_develop::EmbeddedVignette, frame: ProxyFrame<'_>) -> Vec<f64> {
let (w, h) = (sensor.width as f64, sensor.height as f64);
let (ow, oh) = if frame.orientation.swaps_axes() { (h, w) } else { (w, h) };
let width = sensor.width.max(1);
let warp = frame.lens.map(|lens| super::proxy::profile_warp(lens, ow, oh));
(0..sensor.data.len())
.map(|i| {
let (px, py) = ((i % width) as f64 + 0.5, (i / width) as f64 + 0.5);
@@ -465,13 +468,15 @@ pub(super) fn vignetting_gains(sensor: &Rgb32f, vignette: &lightcraft_develop::E
None => (px, py),
};
let (x, y) = frame.orientation.map(px, py, w, h);
lightcraft_pipeline::optics::embedded_vignette_gain(vignette, lightcraft_geom::Point::new(x, y), ow, oh)
let point = lightcraft_geom::Point::new(x, y);
let point = warp.as_ref().map_or(point, |warp| warp.corrected_to_source(point, 1));
lightcraft_pipeline::optics::embedded_vignette_gain(vignette, point, ow, oh)
})
.collect()
}
/// Multiply `sensor` by `amount` of `vignette`'s correction, as the Vignetting amount slider scales it.
pub(super) fn apply_vignetting(sensor: &mut Rgb32f, vignette: &lightcraft_develop::EmbeddedVignette, frame: ProxyFrame, amount: f64) {
pub(super) fn apply_vignetting(sensor: &mut Rgb32f, vignette: &lightcraft_develop::EmbeddedVignette, frame: ProxyFrame<'_>, amount: f64) {
let gains = vignetting_gains(sensor, vignette, frame);
for (p, g) in sensor.data.iter_mut().zip(gains) {
let gain = (1.0 + (g - 1.0) * amount) as f32;
+193 -53
View File
@@ -85,6 +85,13 @@ pub(super) fn structure_agrees(sensor: &Rgb32f, reference: &Rgb32f) -> bool {
at_zero >= MIN_STRUCTURE && shift.0.abs() <= 1 && shift.1.abs() <= 1
}
/// Per-file fits measure database shading against the camera JPEG. A pooled CR3
/// fit applies shading only to its warp proposal and retains its unshaded fallback.
pub(super) enum ProxyLens<'a> {
PerFile(Option<&'a lightcraft_develop::EmbeddedLens>),
Pooled(Option<&'a lightcraft_develop::EmbeddedLens>),
}
/// Same-size proxies of the sensor (white-balanced, baseline exposure, through `transform`'s
/// matrix: the generic camera ≈ sRGB model) and of the file's embedded camera JPEG (linear Rec.2020),
/// and per proxy pixel whether any sensor sample it covers is clipped. `embedded`'s vignetting correction is applied to
@@ -98,20 +105,20 @@ pub(super) fn proxies(
lens: Option<&LensGeometry>,
embedded: Option<&lightcraft_develop::EmbeddedLens>,
) -> Option<(Rgb32f, Rgb32f, Vec<bool>)> {
framed_proxies(raw, bytes, transform, size, min_fraction, lens, embedded).map(|(sensor, reference, clipped, _)| (sensor, reference, clipped))
framed_proxies(raw, bytes, transform, size, min_fraction, lens, ProxyLens::PerFile(embedded))
.map(|(sensor, reference, clipped, _)| (sensor, reference, clipped))
}
/// [`proxies`], and the CR3 framing the sensor proxy was moved to ([`estimate_cr3_framing`]; `None` when it was not
/// moved): a pixel of the returned CR3 sensor proxy shows the oriented sensor at `framing.source` of its position.
pub(super) fn framed_proxies(
/// [`proxies`], and the mapping from the selected proxy to its oriented sensor, used for database vignetting.
pub(super) fn framed_proxies<'a>(
raw: &RawImage,
bytes: &[u8],
transform: &CameraTransform,
size: usize,
min_fraction: f64,
lens: Option<&LensGeometry>,
embedded: Option<&lightcraft_develop::EmbeddedLens>,
) -> Option<(Rgb32f, Rgb32f, Vec<bool>, Option<Cr3Framing>)> {
profile: ProxyLens<'a>,
) -> Option<(Rgb32f, Rgb32f, Vec<bool>, ProxyFrame<'a>)> {
let edge = (2 * size).max(384) as u32;
let decoded = crate::files::decode_raw_preview(
bytes,
@@ -146,11 +153,15 @@ pub(super) fn framed_proxies(
let k = (crop.width.max(crop.height).div_ceil(edge as usize).max(2)).div_ceil(2) * 2;
let mut sensor = sensor_proxy(raw, k, edge as usize)?;
let mut clipped = clip_mask(&sensor);
let mut framing = None;
let mut frame = ProxyFrame::new(raw.orientation);
let embedded = match profile {
ProxyLens::PerFile(lens) | ProxyLens::Pooled(lens) => lens,
};
let cr3_pool = raw.format == RawFormat::Cr3 && matches!(profile, ProxyLens::Pooled(_));
// A database describes the lens; only the share of its shading correction visible in the JPEG
// belongs in the fit. File-owned corrections describe what the camera applied to this image.
let database_vignette = embedded.filter(|e| e.source == lightcraft_develop::LensSource::Database && lens.is_none()).and_then(|e| e.vignette);
if database_vignette.is_none() {
if !cr3_pool && database_vignette.is_none() {
correct_vignetting(&mut sensor, embedded, raw.orientation);
}
// The camera may have corrected its JPEG with the lens warp the file carries (Nikon Z lenses always, at up to 9 %
@@ -162,8 +173,8 @@ pub(super) fn framed_proxies(
let gain = 2f32.powf(transform.baseline_exposure as f32);
let to_working = |p: [f32; 3]| transform.matrix.apply_f32(std::array::from_fn(|i| p[i] * transform.wb[i] * gain));
// External profiles describe the developed default crop, unlike OpcodeList3's active-area warp.
// Keep the established CR3/in-file routes; only an uncalibrated file with no in-file warp
// may propose this additional correspondence geometry. Its acceptance uses edges, never RGB error.
// For non-CR3 files a database warp may compete with the uncorrected sensor only in the absence
// of an in-file warp. CR3 also compares its proposal against the framing-only fallback below.
let aligned_external = embedded
.filter(|correction| {
raw.format != RawFormat::Cr3
@@ -185,13 +196,21 @@ pub(super) fn framed_proxies(
}
if raw.format == RawFormat::Cr3 {
// Orient the camera JPEG and the sensor identically before collecting pixel correspondences.
let correction = embedded.filter(|correction| transform.matrix_is_fallback && lens.is_none() && correction.warp.is_some());
// A pooled fit historically used an unshaded framing fallback. Apply database shading
// only to the proposed sensor, at the source position before orientation and the warp.
let pooled_candidate = correction.filter(|c| cr3_pool && c.vignette.is_some()).map(|correction| {
let mut candidate = sensor.clone();
correct_vignetting(&mut candidate, Some(correction), raw.orientation);
let mut candidate = candidate.into_oriented(raw.orientation);
candidate.map_in_place(to_working);
candidate
});
sensor = sensor.into_oriented(raw.orientation);
clipped = clipped.into_oriented(raw.orientation);
reference = reference.into_oriented(raw.orientation);
sensor.map_in_place(to_working);
// Canon's JPEG can be cropped differently from the sensor. Estimate only that common
// framing from edge directions, independently of the subsequent colour fit.
(sensor, clipped, framing) = align_cr3_framing(sensor, clipped, &reference);
(sensor, clipped, frame) = align_cr3_geometry(sensor, clipped, &reference, correction, pooled_candidate.as_ref());
}
let mut sensor = fit(&sensor, size, size, Filter::Box);
let mut reference_small = reference_at(&reference, &sensor);
@@ -210,12 +229,10 @@ pub(super) fn framed_proxies(
if raw.format != RawFormat::Cr3 && !external_applied {
sensor.map_in_place(to_working);
}
if let Some(vignette) = database_vignette.filter(|_| !external_applied) {
// CR3 is now in the JPEG’s oriented frame. Other proxies are still in sensor orientation.
let orientation = if raw.format == RawFormat::Cr3 { lightcraft_geom::Orientation::Normal } else { raw.orientation };
database_vignetting(&mut sensor, &reference, &clipped, &vignette, ProxyFrame { orientation, framing });
if let Some(vignette) = database_vignette.filter(|_| !external_applied && !cr3_pool) {
database_vignetting(&mut sensor, &reference, &clipped, &vignette, frame);
}
Some((sensor, reference, clipped, framing))
Some((sensor, reference, clipped, frame))
}
fn clipped_pixels(mask: &Rgb32f, sensor: &Rgb32f) -> Vec<bool> {
@@ -252,12 +269,45 @@ impl Cr3Framing {
/// A separate third of the edges must confirm a substantial improvement and a close match.
/// A weak, flat or unrelated preview leaves the sensor framing unchanged.
pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Option<Cr3Framing> {
estimate_framing_against(sensor, reference, None)
estimate_framing_against(sensor, reference, None, None)
}
/// Score both a proposed lens geometry and its bounded framing against the original sensor.
/// The identity framing is a valid candidate: lens correction alone may already align the JPEG.
fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: Option<&Rgb32f>) -> Option<Cr3Framing> {
#[cfg(test)]
thread_local! {
static FRAMING_SEARCHES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static LAST_GEOMETRY_SCORES: std::cell::Cell<Option<[f64; 4]>> = const { std::cell::Cell::new(None) };
static LAST_FRAMED_SCORES: std::cell::Cell<Option<[f64; 4]>> = const { std::cell::Cell::new(None) };
}
/// Read and reset this thread's framing-search budget, independent of elapsed time.
#[cfg(test)]
pub(super) fn take_framing_search_count() -> usize {
FRAMING_SEARCHES.replace(0)
}
/// Return this test thread's last `[train_before, train_after, held_before, held_after]`
/// scores against the original sensor geometry.
#[cfg(test)]
pub(super) fn geometry_gate_scores() -> Option<[f64; 4]> {
LAST_GEOMETRY_SCORES.get()
}
/// Return this test thread's last `[train_before, train_after, held_before, held_after]`
/// scores comparing the CR3 proposal with the established framing fallback.
#[cfg(test)]
pub(super) fn geometry_framed_scores() -> Option<[f64; 4]> {
LAST_FRAMED_SCORES.get()
}
/// Judge a proposed lens warp and bounded framing against the original sensor on fixed
/// training and independent held-out edges. Lens-only correction may be sufficient.
fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: Option<&Rgb32f>, framed: Option<&Rgb32f>) -> Option<Cr3Framing> {
#[cfg(test)]
{
FRAMING_SEARCHES.set(FRAMING_SEARCHES.get() + 1);
LAST_GEOMETRY_SCORES.set(None);
LAST_FRAMED_SCORES.set(None);
}
if sensor.width.checked_mul(sensor.height)? != sensor.data.len() || reference.width.checked_mul(reference.height)? != reference.data.len() {
return None;
}
@@ -276,6 +326,11 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: Optio
if (original.width, original.height) != (w, h) || original.data.len() != sensor.data.len() {
return None;
}
let framed = framed.map(|image| fit(image, PROXY, PROXY, Filter::Box));
if framed.as_ref().is_some_and(|image| (image.width, image.height) != (w, h) || image.data.len() != sensor.data.len()) {
return None;
}
let mut framed_gradients = framed.as_ref().map(|_| Rgb32f::new(w, h));
let mut gradients = Rgb32f::new(w, h);
let mut original_gradients = Rgb32f::new(w, h);
let mut edges = Vec::new();
@@ -291,6 +346,10 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: Optio
gradients.data[y * w + x] = [d[0], d[1], 0.0];
let d = derivative(&original);
original_gradients.data[y * w + x] = [d[0], d[1], 0.0];
if let (Some(image), Some(gradients)) = (&framed, &mut framed_gradients) {
let d = derivative(image);
gradients.data[y * w + x] = [d[0], d[1], 0.0];
}
let d = derivative(&reference);
let magnitude = d[0].hypot(d[1]);
let value = luminance_2020(reference.data[y * w + x]);
@@ -391,9 +450,24 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: Optio
score(&original_gradients, Cr3Framing::IDENTITY, true, proposal.then_some((&gradients, best.1)))?,
score(&gradients, best.1, true, proposal.then_some((&original_gradients, Cr3Framing::IDENTITY)))?,
);
#[cfg(test)]
if proposal {
LAST_GEOMETRY_SCORES.set(Some([best.2, best.0, held_before, held_after]));
}
if best.0 < 0.9 || best.0 < best.2 + 0.04 || held_after < 0.9 || held_after < held_before + 0.04 {
return None;
}
if let Some(framed) = &framed_gradients {
let before = score(framed, Cr3Framing::IDENTITY, false, Some((&gradients, best.1)))?;
let after = score(&gradients, best.1, false, Some((framed, Cr3Framing::IDENTITY)))?;
let held_before = score(framed, Cr3Framing::IDENTITY, true, Some((&gradients, best.1)))?;
let held_after = score(&gradients, best.1, true, Some((framed, Cr3Framing::IDENTITY)))?;
#[cfg(test)]
LAST_FRAMED_SCORES.set(Some([before, after, held_before, held_after]));
if after < before || held_after < held_before {
return None;
}
}
if lightcraft_pipeline::profiling() {
eprintln!("[profile] camera JPEG framing {:?}, held-out edge agreement {held_before:.4} -> {held_after:.4}", best.1);
}
@@ -403,29 +477,56 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: Optio
/// Exercise the proposal gate independently of lens-map construction in regressions.
#[cfg(test)]
pub(super) fn estimate_profile_framing(candidate: &Rgb32f, reference: &Rgb32f, original: &Rgb32f) -> Option<Cr3Framing> {
estimate_framing_against(candidate, reference, Some(original))
estimate_framing_against(candidate, reference, Some(original), None)
}
/// The sensor proxy and its clip mask (same size), both moved to the camera JPEG's framing, and that framing (`None`
/// when they stay as they are).
fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rgb32f, Rgb32f, Option<Cr3Framing>) {
let Some(framing) = estimate_cr3_framing(&sensor, reference) else { return (sensor, clipped, None) };
let apply = |image: &Rgb32f| {
let (w, h) = (image.width, image.height);
let mut aligned = Rgb32f::new(w, h);
for (i, pixel) in aligned.data.iter_mut().enumerate() {
let (x, y) = framing.source((i % w) as f32 + 0.5, (i / w) as f32 + 0.5, w, h);
*pixel = if x >= 0.5 && y >= 0.5 && x <= w as f32 - 0.5 && y <= h as f32 - 0.5 { image.sample_bilinear(x, y) } else { [f32::NAN; 3] };
}
aligned
};
(apply(&sensor), apply(&clipped), Some(framing))
/// Choose CR3 correspondence without copying the unregistered sensor or mask. The
/// unwarped fallback and warped proposal need separate searches: their pixels and
/// support rules differ, and the proposal must preserve the accepted fallback.
pub(super) fn align_cr3_geometry<'a>(
sensor: Rgb32f,
clipped: Rgb32f,
reference: &Rgb32f,
correction: Option<&'a lightcraft_develop::EmbeddedLens>,
candidate_sensor: Option<&Rgb32f>,
) -> (Rgb32f, Rgb32f, ProxyFrame<'a>) {
// The pooled proposal may include database shading. Its framing-only competitor
// must use the original sensor, exactly as it will be returned if the warp loses.
let framing = estimate_cr3_framing(&sensor, reference);
let fallback = framing.map(|framing| apply_cr3_framing(&sensor, framing));
let source = candidate_sensor.unwrap_or(&sensor);
let orientation = lightcraft_geom::Orientation::Normal;
if let Some(lens) = correction
&& let Some((aligned, mask, framing)) =
align_profile_geometry_against(source, &clipped, reference, lens, orientation, Some(fallback.as_ref().unwrap_or(&sensor)))
{
return (aligned, mask, ProxyFrame { orientation, framing: Some(framing), lens: Some(lens) });
}
// The mask is needed only if the fallback wins; when no framing is accepted,
// return both original allocations unchanged.
let clipped = if let Some(framing) = framing { apply_cr3_framing(&clipped, framing) } else { clipped };
(fallback.unwrap_or(sensor), clipped, ProxyFrame { orientation, framing, lens: None })
}
/// Move one image to the accepted camera framing, preserving invalid border samples.
fn apply_cr3_framing(image: &Rgb32f, framing: Cr3Framing) -> Rgb32f {
let (w, h) = (image.width, image.height);
let mut aligned = Rgb32f::new(w, h);
for (i, pixel) in aligned.data.iter_mut().enumerate() {
let (x, y) = framing.source((i % w) as f32 + 0.5, (i / w) as f32 + 0.5, w, h);
*pixel = if x >= 0.5 && y >= 0.5 && x <= w as f32 - 0.5 && y <= h as f32 - 0.5 { image.sample_bilinear(x, y) } else { [f32::NAN; 3] };
}
aligned
}
/// Resample a correspondence image with a common source map. Nonfinite/outside coordinates
/// become NaN so they cannot contribute colour or tone training pairs. A nonnegative clip mask
/// uses the same bilinear map: any clipped contributing sample remains strictly positive.
pub(super) fn resample_correspondence(image: &Rgb32f, source: impl Fn(f64, f64) -> lightcraft_geom::Point) -> Rgb32f {
pub(super) fn resample_correspondence(
image: &Rgb32f,
source: impl Fn(f64, f64) -> lightcraft_geom::Point,
sample: fn(&Rgb32f, f64, f64) -> [f32; 3],
) -> Rgb32f {
let (w, h) = (image.width, image.height);
let mut out = Rgb32f::new(w, h);
if w == 0 || h == 0 {
@@ -434,7 +535,7 @@ pub(super) fn resample_correspondence(image: &Rgb32f, source: impl Fn(f64, f64)
for (i, pixel) in out.data.iter_mut().enumerate() {
let p = source((i % w) as f64 + 0.5, (i / w) as f64 + 0.5);
*pixel = if p.x.is_finite() && p.y.is_finite() && p.x >= 0.5 && p.y >= 0.5 && p.x <= w as f64 - 0.5 && p.y <= h as f64 - 0.5 {
sample_correspondence(image, p.x as f32 - 0.5, p.y as f32 - 0.5)
sample(image, p.x, p.y)
} else {
[f32::NAN; 3]
};
@@ -442,10 +543,11 @@ pub(super) fn resample_correspondence(image: &Rgb32f, source: impl Fn(f64, f64)
out
}
/// Bilinear interpolation inside the image, with integer coordinates at pixel centres.
/// Bilinear interpolation at the established non-CR3 proxy's f32 precision.
/// At an exact coordinate the two bounds coincide. An invalid neighbour with zero weight
/// must not turn a usable training pixel or its clip mask into NaN.
fn sample_correspondence(image: &Rgb32f, x: f32, y: f32) -> [f32; 3] {
pub(super) fn sample_correspondence(image: &Rgb32f, x: f64, y: f64) -> [f32; 3] {
let (x, y) = (x as f32 - 0.5, y as f32 - 0.5);
let row = |y| -> [f32; 3] {
let left = image.get(x.floor() as usize, y);
let right = image.get(x.ceil() as usize, y);
@@ -456,6 +558,20 @@ fn sample_correspondence(image: &Rgb32f, x: f32, y: f32) -> [f32; 3] {
std::array::from_fn(|i| top[i] + (bottom[i] - top[i]) * y.fract())
}
/// Two-stage CR3 registration keeps f64 source coordinates so a positive neighbour weight survives near pixel centres.
pub(super) fn sample_cr3_correspondence(image: &Rgb32f, x: f64, y: f64) -> [f32; 3] {
let (x, y) = (x - 0.5, y - 0.5);
let blend = |a: [f32; 3], b: [f32; 3], t: f64| std::array::from_fn(|i| (f64::from(a[i]) * (1.0 - t) + f64::from(b[i]) * t) as f32);
// The first warp can leave a NaN border. Read a neighbour only when it contributes.
let (x0, y0) = (x.floor() as usize, y.floor() as usize);
let row = |y| {
let left = image.get(x0, y);
if x.fract() == 0.0 { left } else { blend(left, image.get(x0 + 1, y), x.fract()) }
};
let top = row(y0);
if y.fract() == 0.0 { top } else { blend(top, row(y0 + 1), y.fract()) }
}
/// A resolved profile is a proposal for camera-JPEG geometry, never an instruction to change
/// the rendered RAW's optics. The lens is already relative to the oriented default crop;
/// re-express it in this un-oriented sensor proxy's frame before using its green-plane warp.
@@ -467,27 +583,43 @@ pub(super) fn align_profile_geometry(
correction: &lightcraft_develop::EmbeddedLens,
orientation: lightcraft_geom::Orientation,
) -> Option<(Rgb32f, Rgb32f)> {
align_profile_geometry_against(sensor, clipped, reference, correction, orientation, None).map(|(sensor, mask, _)| (sensor, mask))
}
/// Propose lens geometry plus bounded framing and require the original training/held-out gates.
/// When supplied, the framed CR3 baseline must also be preserved or improved on both splits.
fn align_profile_geometry_against(
sensor: &Rgb32f,
clipped: &Rgb32f,
reference: &Rgb32f,
correction: &lightcraft_develop::EmbeddedLens,
orientation: lightcraft_geom::Orientation,
cr3_baseline: Option<&Rgb32f>,
) -> Option<(Rgb32f, Rgb32f, Cr3Framing)> {
if correction.warp.is_none() || (sensor.width, sensor.height) != (clipped.width, clipped.height) {
return None;
}
let (w, h) = (sensor.width as f64, sensor.height as f64);
let (ow, oh) = if orientation.swaps_axes() { (h, w) } else { (w, h) };
let correction = lightcraft_pipeline::optics::reorient_lens(correction, orientation.inverse(), ow, oh);
let mut warp = lightcraft_pipeline::optics::Warp::identity(w, h);
warp.lens = Some(correction);
warp.lens_dist = 1.0;
let warp = profile_warp(&correction, w, h);
let source = |x, y| warp.corrected_to_source(lightcraft_geom::Point::new(x, y), 1);
let candidate = resample_correspondence(sensor, source);
let framing = estimate_framing_against(&candidate, reference, Some(sensor))?;
let mask = resample_correspondence(clipped, source);
let sample = if cr3_baseline.is_some() { sample_cr3_correspondence } else { sample_correspondence };
let candidate = resample_correspondence(sensor, source, sample);
let framing = estimate_framing_against(&candidate, reference, Some(sensor), cr3_baseline)?;
let mask = resample_correspondence(clipped, source, sample);
let frame = |x: f64, y: f64| {
let (x, y) = framing.source(x as f32, y as f32, sensor.width, sensor.height);
lightcraft_geom::Point::new(f64::from(x), f64::from(y))
};
let mask = resample_correspondence(&mask, frame);
let aligned = resample_correspondence(&candidate, frame);
let mask = resample_correspondence(&mask, frame, sample);
let aligned = resample_correspondence(&candidate, frame, sample);
// CR3 shading is handled by the caller on the selected geometry.
if cr3_baseline.is_some() {
return Some((aligned, mask, framing));
}
let Some(vignette) = correction.vignette.filter(|_| correction.source == lightcraft_develop::LensSource::Database) else {
return Some((aligned, mask));
return Some((aligned, mask, framing));
};
// Estimate shading only after the edges agree. Each gain belongs to the source position reached
@@ -501,12 +633,20 @@ pub(super) fn align_profile_geometry(
});
let amount = vignetting_amount_from_gains(&small, &reference_at(reference, &small), &clipped_pixels(&mask, &small), gains);
if amount == 0.0 {
return Some((aligned, mask));
return Some((aligned, mask, framing));
}
// Apply the measured share before interpolation, exactly where the sensor samples came from.
let mut shaded = sensor.clone();
apply_vignetting(&mut shaded, &vignette, ProxyFrame::new(lightcraft_geom::Orientation::Normal), amount);
Some((resample_correspondence(&resample_correspondence(&shaded, source), frame), mask))
Some((resample_correspondence(&resample_correspondence(&shaded, source, sample), frame, sample), mask, framing))
}
/// Green-plane mapping from corrected pixels to their sensor positions at this proxy size.
pub(super) fn profile_warp(lens: &lightcraft_develop::EmbeddedLens, w: f64, h: f64) -> lightcraft_pipeline::optics::Warp {
let mut warp = lightcraft_pipeline::optics::Warp::identity(w, h);
warp.lens = Some(*lens);
warp.lens_dist = 1.0;
warp
}
/// What one photo contributes to a camera profile ([`profile_samples`]), in white-balanced camera RGB.
@@ -531,7 +671,7 @@ pub(crate) fn profile_samples(
return None;
}
let transform = lightcraft_raw::color::camera_transform(raw, lightcraft_raw::color::as_shot_white_xy(raw));
let (sensor, reference, clipped) = proxies(raw, bytes, &transform, PROFILE_PROXY, 0.0, lens, correction)?;
let (sensor, reference, clipped, _) = framed_proxies(raw, bytes, &transform, PROFILE_PROXY, 0.0, lens, ProxyLens::Pooled(correction))?;
let to_camera = transform.matrix.inverse()?;
// clipped sensor pixels don't record the scene's colour (see `fit_look`)
let sensor = without_clipped(&sensor, &clipped).unwrap_or(sensor);
+651 -66
View File
@@ -1,4 +1,4 @@
use super::proxy::{align_profile_geometry, resample_correspondence};
use super::proxy::{align_profile_geometry, resample_correspondence, sample_correspondence, sample_cr3_correspondence};
use super::tone::{ELASTICITY_BLACK, MAX_TONE_ELASTICITY, TONE_REPAIR_ELASTICITY, limit_elasticity};
use super::*;
use lightcraft_raw::profile::{HsvTableApply, ProfileLookHueSat};
@@ -1016,13 +1016,27 @@ fn correspondence_samples_use_only_neighbours_with_nonzero_weight() {
let mut image = Rgb32f::new(2, 2);
image.data.fill([f32::NAN; 3]);
image.set(0, 0, valid);
let sample = |image: &Rgb32f, x, y| resample_correspondence(image, |_, _| lightcraft_geom::Point::new(x, y)).get(0, 0);
assert_eq!(sample(&image, 0.5, 0.5), valid);
assert!(sample(&image, 1.0, 1.0).iter().all(|v| v.is_nan()));
for (x, y) in [(1, 0), (0, 1)] {
let mut axis = image.clone();
axis.set(x, y, valid.map(|v| 3.0 * v));
assert_eq!(sample(&axis, 0.5 + x as f64 * 0.5, 0.5 + y as f64 * 0.5), valid.map(|v| 2.0 * v));
for interpolation in [sample_correspondence, sample_cr3_correspondence] {
let sample = |image: &Rgb32f, x, y| resample_correspondence(image, |_, _| lightcraft_geom::Point::new(x, y), interpolation).get(0, 0);
assert_eq!(sample(&image, 0.5, 0.5), valid);
assert!(sample(&image, 1.0, 1.0).iter().all(|v| v.is_nan()));
for (x, y) in [(1, 0), (0, 1)] {
let mut axis = image.clone();
axis.set(x, y, valid.map(|v| 3.0 * v));
assert_eq!(sample(&axis, 0.5 + x as f64 * 0.5, 0.5 + y as f64 * 0.5), valid.map(|v| 2.0 * v));
}
}
let sample = |image: &Rgb32f, x, y| resample_correspondence(image, |_, _| lightcraft_geom::Point::new(x, y), sample_cr3_correspondence).get(0, 0);
// These coordinates still have a positive neighbour weight even though casting them to f32 rounds to the centre.
let next = 0.5f64.next_up();
for (x, y) in [(next, 0.5), (0.5, next)] {
assert!(sample(&image, x, y).iter().all(|v| v.is_nan()));
}
let mut mask = Rgb32f::new(2, 2);
mask.set(0, 0, [1.0; 3]);
let almost_next_centre = 1.5f64.next_down();
for (x, y) in [(almost_next_centre, 0.5), (0.5, almost_next_centre)] {
assert!(sample(&mask, x, y)[0] > 0.0, "a clipped neighbour with positive weight must count");
}
}
@@ -1042,11 +1056,15 @@ fn profile_geometry_target(sensor: &Rgb32f, lens: &lightcraft_develop::EmbeddedL
let mut warp = lightcraft_pipeline::optics::Warp::identity(sensor.width as f64, sensor.height as f64);
warp.lens = Some(*lens);
warp.lens_dist = 1.0;
let warped = resample_correspondence(sensor, |x, y| warp.corrected_to_source(lightcraft_geom::Point::new(x, y), 1));
resample_correspondence(&warped, |x, y| {
let (x, y) = framing.source(x as f32, y as f32, sensor.width, sensor.height);
lightcraft_geom::Point::new(f64::from(x), f64::from(y))
})
let warped = resample_correspondence(sensor, |x, y| warp.corrected_to_source(lightcraft_geom::Point::new(x, y), 1), sample_correspondence);
resample_correspondence(
&warped,
|x, y| {
let (x, y) = framing.source(x as f32, y as f32, sensor.width, sensor.height);
lightcraft_geom::Point::new(f64::from(x), f64::from(y))
},
sample_correspondence,
)
}
fn geometry_rms(a: &Rgb32f, b: &Rgb32f) -> f64 {
@@ -1345,8 +1363,8 @@ fn assert_file_owned_dng_vignette_contract(
#[test]
fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() {
const DB: &str = r#"<lensdatabase>
<camera><maker>Synthetic</maker><model>Uncalibrated</model><mount>T</mount><cropfactor>1.5</cropfactor></camera>
<lens><maker>Synthetic</maker><model>Synthetic 18mm</model><mount>T</mount><cropfactor>1.5</cropfactor>
<camera><maker>Synthetic</maker><model>Uncalibrated</model><mount>compact</mount><cropfactor>1.5</cropfactor></camera>
<lens><maker>Synthetic</maker><model>Synthetic 18mm</model><model>18mm f/3.5</model><mount>compact</mount><cropfactor>1.5</cropfactor>
<calibration><distortion model="poly5" focal="18" k1="-0.24" k2="0.08" /></calibration>
</lens></lensdatabase>"#;
const CHILD: &str = "LIGHTCRAFT_TEST_COLOUR_TAG_LOOKUP_CHILD";
@@ -1391,28 +1409,21 @@ fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop()
let mut target = profile_geometry_target(&sensor, &lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] });
target.map_in_place(|p| p.map(|v| v.powf(0.7)));
use craft_tiff::{IfdBuilder, Value, tags};
let mut ifd = IfdBuilder::new();
ifd.set(tags::MAKE, Value::Ascii("Synthetic".into()));
ifd.set(tags::MODEL, Value::Ascii("Uncalibrated".into()));
let mut exif = IfdBuilder::new();
exif.set(tags::FOCAL_LENGTH, Value::Rational(vec![(18, 1)]));
exif.set(tags::LENS_MODEL, Value::Ascii("Synthetic 18mm".into()));
ifd.set_child(tags::EXIF_IFD, exif);
let file = profile_geometry_file(&target, ifd);
// Standalone non-CR3 scope: a coherent profile must not alter Main's CR3 framing route.
let shot = |jpeg: &Rgb32f, identity: Option<(u16, Value)>| {
let mut ifd = IfdBuilder::new();
ifd.set(tags::MAKE, Value::Ascii("Synthetic".into()));
ifd.set(tags::MODEL, Value::Ascii("Uncalibrated".into()));
let mut exif = IfdBuilder::new();
exif.set(tags::FOCAL_LENGTH, Value::Rational(vec![(18, 1)]));
if let Some((tag, value)) = identity {
exif.set(tag, value);
}
ifd.set_child(tags::EXIF_IFD, exif);
profile_geometry_file(jpeg, ifd)
};
let file = shot(&target, Some((tags::LENS_MODEL, Value::Ascii("Synthetic 18mm".into()))));
let mut cr3 = raw.clone();
cr3.format = RawFormat::Cr3;
let baseline = proxies(&cr3, &file, &transform, PROXY, 0.0, None, None).unwrap();
let proposed = proxies(&cr3, &file, &transform, PROXY, 0.0, None, Some(&lens)).unwrap();
let bits = |image: &Rgb32f| image.data.iter().flatten().map(|v| v.to_bits()).collect::<Vec<_>>();
assert_eq!(bits(&baseline.0), bits(&proposed.0), "CR3 sensor keeps Main framing");
assert_eq!(bits(&baseline.1), bits(&proposed.1), "CR3 reference is unchanged");
assert_eq!(baseline.2, proposed.2, "CR3 clipping is unchanged");
let cr3_samples = |correction: Option<&lightcraft_develop::EmbeddedLens>| {
let samples = profile_samples(&cr3, &file, None, correction).expect("CR3 colour and tone samples");
(samples.colour, samples.tone)
};
assert!(cr3_samples(None) == cr3_samples(Some(&lens)), "CR3 pooled samples preserve the original framing");
let (plain, reference, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, None).unwrap();
let (mut aligned, _, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, Some(&lens)).unwrap();
let mut plain_render = plain;
@@ -1448,8 +1459,7 @@ fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop()
assert_file_owned_dng_vignette_contract(&mut raw, &file, &lens, &white, &expected_tags);
// A real configured profile with nonzero vignetting must still be available to Main's
// per-file CR3 path, while this proposal's new Pool/DNG lookup stays excluded.
// Resolve a real configured CR3 profile through the shared Pool/DNG lookup.
let vignetted_db =
DB.replace("</calibration>", r#"<vignetting model="pa" focal="18" aperture="3.5" distance="1000" k1="-0.4" k2="0" k3="0" /></calibration>"#);
let path = std::path::PathBuf::from(std::env::var_os(crate::lens_profiles::ENV).unwrap()).join("synthetic.xml");
@@ -1457,37 +1467,37 @@ fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop()
crate::lens_profiles::reload();
let resolved = crate::lens_profiles::for_raw(&cr3.info(), || lightcraft_meta::extract(&file)).unwrap();
assert!(resolved.warp.is_some() && resolved.vignette.is_some(), "fixture resolves both corrections");
let mut main_lens = resolved;
main_lens.warp = None;
let main_proxy = proxies(&cr3, &file, &transform, PROXY, 0.0, None, Some(&main_lens)).unwrap();
let actual_proxy = proxies(&cr3, &file, &transform, PROXY, 0.0, None, Some(&resolved)).unwrap();
assert_eq!(bits(&main_proxy.0), bits(&actual_proxy.0), "CR3 keeps Main's vignetting and framing, ignoring the new radial proposal");
let (mut unshaded, reference, clipped, framing) = super::proxy::framed_proxies(&cr3, &file, &transform, PROXY, 0.0, None, None).unwrap();
let frame = ProxyFrame { orientation: lightcraft_geom::Orientation::Normal, framing };
let vignette = resolved.vignette.as_ref().unwrap();
let share = camera_vignetting_amount(&unshaded, &reference, &clipped, vignette, frame);
let gains = vignetting_gains(&unshaded, vignette, frame);
for (p, gain) in unshaded.data.iter_mut().zip(gains) {
*p = p.map(|v| v * (1.0 + (gain - 1.0) * share) as f32);
assert_eq!(correspondence_correction(&cr3, &file), Some(resolved));
let warp_only = lightcraft_develop::EmbeddedLens { vignette: None, ..resolved };
let expected = super::colour::starting_colour_tags_with_correction(&mut cr3.clone(), &file, Some(&warp_only));
assert_ne!(expected, super::colour::starting_colour_tags_with_correction(&mut cr3.clone(), &file, None));
assert_eq!(starting_colour_tags(&mut cr3.clone(), &file), expected, "public CR3 DNG lookup keeps the warp and excludes database shading");
// Both the unique fixed mount and an explicit specification alias identify this same lens.
let spec = |aperture| Some((tags::LENS_SPECIFICATION, Value::Rational(vec![(18, 1), (18, 1), (aperture, 10), (aperture, 10)])));
for identity in [None, spec(35)] {
let variant = shot(&target, identity);
assert_eq!(correspondence_correction(&cr3, &variant), Some(resolved));
assert_eq!(starting_colour_tags(&mut cr3.clone(), &variant), expected);
}
assert_eq!(bits(&unshaded), bits(&actual_proxy.0), "CR3 uses the share measured at the framed sensor positions");
assert_eq!(main_proxy.2, actual_proxy.2, "CR3 masks keep Main semantics");
assert!(cr3_samples(Some(&main_lens)) == cr3_samples(Some(&resolved)), "the database warp must not change pooled CR3 samples");
assert!(correspondence_correction(&cr3, &file).is_none(), "the actual shared Pool/DNG lookup excludes CR3");
let expected = super::colour::starting_colour_tags_with_correction(&mut cr3.clone(), &file, None);
assert_eq!(starting_colour_tags(&mut cr3.clone(), &file), expected, "public DNG lookup keeps Main's CR3 route");
assert_eq!(
super::colour::starting_colour_tags_with_correction(&mut cr3, &file, Some(&resolved)),
expected,
"injected CR3 correction cannot bypass DNG scope"
);
assert!(correspondence_correction(&cr3, &shot(&target, spec(28))).is_none(), "an unmatched specification prevents mount fallback");
// The unnamed lens still resolves when the JPEG uses plain sensor geometry. Its warp and
// database shading must then leave the pooled samples identical to the no-profile fallback.
let plain_file = shot(&sensor, None);
let correction = correspondence_correction(&cr3, &plain_file).unwrap();
let fallback = profile_samples(&cr3, &plain_file, None, None).unwrap();
let selected = profile_samples(&cr3, &plain_file, None, Some(&correction)).unwrap();
assert!(!fallback.colour.is_empty() && !fallback.tone.is_empty());
assert_eq!(selected.colour, fallback.colour);
assert_eq!(selected.tone, fallback.tone);
}
#[test]
fn correspondence_mask_keeps_every_contributing_clipped_sample_and_invalid_border() {
let mut mask = Rgb32f::new(8, 6);
mask.data[2 * 8 + 3] = [1.0; 3];
let result = resample_correspondence(&mask, |x, y| lightcraft_geom::Point::new(x + 0.75, y + 0.5));
let result = resample_correspondence(&mask, |x, y| lightcraft_geom::Point::new(x + 0.75, y + 0.5), sample_correspondence);
assert!(result.data[8 + 2][0] > 0.0 && result.data[8 + 3][0] > 0.0);
assert!(result.data[2 * 8 + 2][0] > 0.0 && result.data[2 * 8 + 3][0] > 0.0);
assert_eq!(result.data[0][0], 0.0);
@@ -1497,6 +1507,577 @@ fn correspondence_mask_keeps_every_contributing_clipped_sample_and_invalid_borde
assert!(reduced.data[1][0] > 0.0 && reduced.data[5][0] > 0.0);
}
#[test]
fn cr3_framing_only_does_not_report_profile_gate_scores() {
let original = profile_geometry_scene(384, 256);
let candidate = profile_geometry_target(&original, &synthetic_profile_lens(), Cr3Framing::IDENTITY);
// Seed real proposal diagnostics, then ensure the framing-only call clears them.
assert!(super::proxy::estimate_profile_framing(&candidate, &candidate, &original).is_some());
assert!(super::proxy::geometry_gate_scores().is_some());
let _ = estimate_cr3_framing(&original, &original);
assert!(super::proxy::geometry_gate_scores().is_none());
assert!(super::proxy::geometry_framed_scores().is_none());
}
/// Rejected registration must preserve both input allocations and pixel bits. A
/// missing/ineligible warp uses only the fallback search; an eligible warp adds
/// exactly one search on different (warped) pixels, never repeats either search.
#[test]
fn cr3_unchanged_geometry_preserves_allocations_and_bounds_search_work() {
for (correction, searches) in [(None, 1), (Some(Default::default()), 1), (Some(synthetic_profile_lens()), 2)] {
let sensor = profile_geometry_scene(384, 256);
let reference = sensor.clone();
let mut mask = Rgb32f::new(sensor.width, sensor.height);
mask.data[17] = [1.0; 3];
let sensor_ptr = sensor.data.as_ptr();
let mask_ptr = mask.data.as_ptr();
let mask_bits: Vec<_> = mask.data.iter().map(|p| p.map(f32::to_bits)).collect();
super::proxy::take_framing_search_count();
let (aligned, aligned_mask, frame) = super::proxy::align_cr3_geometry(sensor, mask, &reference, correction.as_ref(), None);
assert!(frame.lens.is_none(), "rejected geometry must leave no lens mapping");
assert_eq!(super::proxy::take_framing_search_count(), searches, "bounded search budget for missing or rejected geometry");
assert_eq!(aligned.data.as_ptr(), sensor_ptr, "no accepted framing or warp: retain sensor allocation");
assert_eq!(aligned_mask.data.as_ptr(), mask_ptr, "no accepted framing or warp: retain mask allocation");
assert_eq!(aligned.data, reference.data);
assert_eq!(aligned_mask.data.iter().map(|p| p.map(f32::to_bits)).collect::<Vec<_>>(), mask_bits);
}
}
/// Exercise selection through the same orchestration as file-local and pooled
/// fitting, including the proposal's comparisons with the framed fallback.
#[test]
fn cr3_geometry_selects_matching_profile_with_one_search_per_geometry() {
let sensor = profile_geometry_scene(384, 256);
let lens = synthetic_profile_lens();
let framing = Cr3Framing { scale: 0.95, offset: [0.006, -0.004] };
let expected = profile_geometry_target(&sensor, &lens, framing);
let mut reference = expected.clone();
reference.map_in_place(|p| p.map(|v| v.powf(0.7)));
let mask = Rgb32f::new(sensor.width, sensor.height);
let expected_mask = profile_geometry_target(&mask, &lens, framing);
super::proxy::take_framing_search_count();
let (aligned, aligned_mask, frame) = super::proxy::align_cr3_geometry(sensor, mask, &reference, Some(&lens), None);
assert_eq!(frame.lens, Some(&lens));
assert!(frame.framing.is_some());
assert_eq!(super::proxy::take_framing_search_count(), 2);
assert!(super::proxy::geometry_gate_scores().is_some(), "proposal passed original geometry gates");
assert!(super::proxy::geometry_framed_scores().is_some(), "proposal was compared with fallback on both splits");
assert_profile_geometry_mask(&aligned, &aligned_mask, &expected_mask);
assert!(geometry_rms(&aligned, &expected) < 0.008, "matching proposal selected despite nonlinear JPEG tone");
}
#[test]
fn cr3_pooled_warp_must_match_the_unshaded_framing() {
let sensor = profile_geometry_scene(192, 128);
let mask = Rgb32f::new(sensor.width, sensor.height);
let mut lens = synthetic_profile_lens();
lens.vignette =
Some(lightcraft_develop::EmbeddedVignette { k: [3.0, 0.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.5, 0.5), radius: 0.6 });
let mut shaded = sensor.clone();
correct_vignetting(&mut shaded, Some(&lens), lightcraft_geom::Orientation::Normal);
// The JPEG corrects only 53% of the profile distortion. The full proposal beats the
// vignette-corrected framing on both edge sets, but loses to the actual unshaded fallback.
let mut jpeg_lens = lens;
jpeg_lens.warp.as_mut().unwrap().planes = [[1.0212, -0.1272, 0.0424, 0.0, 0.0, 0.0]; 3];
let reference = profile_geometry_target(&sensor, &jpeg_lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] });
let (fallback, _, _) = super::proxy::align_cr3_geometry(sensor.clone(), mask.clone(), &reference, None, None);
let (selected, _, frame) = super::proxy::align_cr3_geometry(sensor, mask, &reference, Some(&lens), Some(&shaded));
assert!(frame.lens.is_none(), "the full warp is worse than the unshaded fallback");
let [train_before, train_after, held_before, held_after] = super::proxy::geometry_framed_scores().unwrap();
assert!(train_after < train_before && held_after < held_before);
assert_eq!(selected.data, fallback.data);
}
/// Check the full known valid crop, so the RMS cannot hide lost samples behind NaNs.
fn assert_profile_geometry_mask(aligned: &Rgb32f, aligned_mask: &Rgb32f, expected_mask: &Rgb32f) {
assert_eq!((aligned.width, aligned.height), (expected_mask.width, expected_mask.height));
assert_eq!((aligned_mask.width, aligned_mask.height), (expected_mask.width, expected_mask.height));
assert_eq!(aligned.data.len(), expected_mask.data.len());
assert_eq!(aligned_mask.data.len(), expected_mask.data.len());
for (i, ((pixel, mask), expected)) in aligned.data.iter().zip(&aligned_mask.data).zip(&expected_mask.data).enumerate() {
// The barrel warp and inward framing used below keep the entire crop valid.
assert_eq!(*expected, [0.0; 3], "ground-truth crop must be valid and unclipped at {i}");
assert!(pixel.iter().all(|v| v.is_finite()), "alignment lost a valid ground-truth sample at {i}");
assert_eq!(*mask, *expected, "valid aligned pixels must retain the zero clip mask at {i}");
}
}
/// Forward accepted CR3 geometry through file-local fits, pooled pairs and DNG colour tags,
/// using the same default-cropped sensor samples.
#[test]
fn cr3_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() {
let mut raw = profile_geometry_raw(&profile_geometry_scene(416, 288), [1.0; 3]);
raw.format = RawFormat::Cr3;
let transform = lightcraft_raw::color::camera_transform(&raw, D65);
assert!(transform.matrix_is_fallback);
let mut sensor = sensor_proxy(&raw, 2, 384).unwrap();
assert_eq!((sensor.width, sensor.height), (384, 256));
sensor.map_in_place(|p| transform.matrix.apply_f32(p));
let lens = synthetic_profile_lens();
let mut target = profile_geometry_target(&sensor, &lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] });
target.map_in_place(|p| p.map(|v| v.powf(0.7)));
let file = profile_geometry_file(&target, craft_tiff::IfdBuilder::new());
let (plain, reference, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, None).unwrap();
let (mut aligned, _, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, Some(&lens)).unwrap();
let mut plain_render = plain;
plain_render.map_in_place(|p| p.map(|v| v.powf(0.7)));
aligned.map_in_place(|p| p.map(|v| v.powf(0.7)));
assert!(
geometry_rms(&aligned, &reference) < geometry_rms(&plain_render, &reference) * 0.3,
"the file-local route uses the resolved crop-relative correction"
);
let error = |pairs: Vec<([f64; 3], [f64; 3])>| {
let sum: f64 = pairs.iter().map(|(x, y)| transform.matrix.apply(*x).iter().zip(y).map(|(x, y)| (x.powf(0.7) - y).powi(2)).sum::<f64>()).sum();
sum / pairs.len() as f64
};
let plain_samples = profile_samples(&raw, &file, None, None).unwrap();
let aligned_samples = profile_samples(&raw, &file, None, Some(&lens)).unwrap();
let tone_error = |samples: &[([f64; 3], f64)]| {
assert!(!samples.is_empty());
samples
.iter()
.map(|(x, y)| {
let rgb = transform.matrix.apply(*x).map(|v| v.powf(0.7));
(luma(rgb) - y).powi(2)
})
.sum::<f64>()
/ samples.len() as f64
};
assert!(tone_error(&aligned_samples.tone) < tone_error(&plain_samples.tone) * 0.1, "pooled tone samples use the selected geometry");
let before = error(plain_samples.colour);
let after = error(aligned_samples.colour);
assert!(after < before * 0.1, "pooled colour calibration uses the same geometry: {before} -> {after}");
// Merge / DNG conversion must encode the same calibrated colour as opening the RAW.
let mut opened = raw.clone();
let (_, t, look) = starting_colour(&mut opened, &file, None, Some(&lens));
assert!(look.is_some(), "the synthetic corrected preview supplies a camera look");
let scale = crate::files::WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata);
let white = scale.dng_white(&raw.color, lightcraft_raw::color::as_shot_white_xy(&raw));
let expected_tags = dng_colour(&raw.color, &white, &t, look.as_ref()).unwrap();
let tags = super::colour::starting_colour_tags_with_correction(&mut raw, &file, Some(&lens)).unwrap();
assert_eq!(tags, expected_tags, "DNG tags use the resolved correspondence geometry too");
assert_external_dng_vignette_contract(&raw, &sensor, &lens, &white);
}
/// Apply oriented CR3 geometry once, with white balance applied once, across all EXIF orientations.
#[test]
fn cr3_profile_geometry_shares_orientation_and_applies_white_balance_once() {
check_cr3_profile_geometry_orientation(false);
}
/// Keep the upstream source-position vignetting correction before CR3 profile geometry.
#[test]
fn cr3_vignetting_precedes_profile_geometry_in_every_orientation() {
check_cr3_profile_geometry_orientation(true);
}
fn check_cr3_profile_geometry_orientation(vignetted: bool) {
let mut scene = profile_geometry_scene(416, 288);
scene.map_in_place(|p| p.map(|v| v * 0.3));
let mut raw = profile_geometry_raw(&scene, [1.25, 1.0, 0.8]);
raw.format = RawFormat::Cr3;
let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw));
assert!(transform.wb.windows(2).any(|v| (v[0] - v[1]).abs() > 0.01), "the fixture must exercise nonuniform as-shot WB");
assert!(transform.matrix_is_fallback);
let mut sensor = sensor_proxy(&raw, 2, 384).unwrap();
assert_eq!((sensor.width, sensor.height), (384, 256));
let mut lens = synthetic_profile_lens();
// A file-owned vignette is applied in full; a database vignette is measured separately below.
lens.source = lightcraft_develop::LensSource::File;
if vignetted {
lens.vignette =
Some(lightcraft_develop::EmbeddedVignette { k: [1.0, 0.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.45, 0.55), radius: 0.6 });
}
super::look_fit::correct_vignetting(&mut sensor, Some(&lens), lightcraft_geom::Orientation::Normal);
sensor.map_in_place(|p| {
transform.matrix.apply_f32(std::array::from_fn(|i| p[i] * transform.wb[i] * 2f32.powf(transform.baseline_exposure as f32)))
});
let mut target = profile_geometry_target(&sensor, &lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] });
target.map_in_place(|p| p.map(|v| v.powf(0.7)));
let to_srgb = lightcraft_color::SRGB.from_xyz().mul(&REC2020.to_xyz());
let jpeg_range = target
.data
.iter()
.filter(|p| p.iter().all(|v| v.is_finite()))
.flat_map(|p| to_srgb.apply_f32(*p))
.fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), v| (lo.min(v), hi.max(v)));
assert!(jpeg_range.0 >= 0.0 && jpeg_range.1 <= 1.0, "the generated reference must not clip: {jpeg_range:?}");
let file = profile_geometry_file(&target, craft_tiff::IfdBuilder::new());
for exif in 1..=8 {
let orientation = lightcraft_geom::Orientation::from_exif(exif);
raw.orientation = orientation;
let oriented_lens = lightcraft_pipeline::optics::reorient_lens(&lens, orientation, 384.0, 256.0);
let (aligned, reference, clipped) = proxies(&raw, &file, &transform, PROFILE_PROXY, 0.0, None, Some(&oriented_lens)).unwrap();
if vignetted && exif == 6 {
let sensor = without_clipped(&aligned, &clipped).unwrap_or_else(|| aligned.clone());
let to_camera = transform.matrix.inverse().unwrap();
let expected = samples_from_proxies(&sensor, &reference, &to_camera).unwrap();
let samples = profile_samples(&raw, &file, None, Some(&oriented_lens)).unwrap();
assert!(!expected.colour.is_empty() && !expected.tone.is_empty());
assert!(
samples.colour == expected.colour && samples.tone == expected.tone,
"both pooled inputs keep the source-position vignette of the accepted warp in a rotated crop"
);
// The JPEG was generated with half this database gain. Measure it through the normal per-file path.
let mut database = oriented_lens;
database.source = lightcraft_develop::LensSource::Database;
let vignette = database.vignette.as_mut().unwrap();
vignette.k[0] *= 2.0;
let vignette = *vignette;
let warp_only = lightcraft_develop::EmbeddedLens { vignette: None, ..database };
let (unshaded, jpeg, mask, frame) =
super::proxy::framed_proxies(&raw, &file, &transform, PROXY, 0.0, None, super::proxy::ProxyLens::PerFile(Some(&warp_only))).unwrap();
assert!(frame.lens.is_some(), "the lens warp wins before measuring its shading");
let framing = frame.framing.unwrap();
let amount = camera_vignetting_amount(&unshaded, &jpeg, &mask, &vignette, frame);
assert!((0.3..=0.7).contains(&amount), "partially corrected JPEG, measured {amount}");
let (measured, _, _) = super::look_fit::look_proxies(&raw, &file, &transform, None, Some(&database)).unwrap();
let (w, h) = (unshaded.width, unshaded.height);
let mut warp = lightcraft_pipeline::optics::Warp::identity(w as f64, h as f64);
warp.lens = Some(database);
warp.lens_dist = 1.0;
for (i, (before, after)) in unshaded.data.iter().zip(&measured.data).enumerate() {
let (x, y) = framing.source((i % w) as f32 + 0.5, (i / w) as f32 + 0.5, w, h);
let source = warp.corrected_to_source(lightcraft_geom::Point::new(f64::from(x), f64::from(y)), 1);
let gain = lightcraft_pipeline::optics::embedded_vignette_gain(&vignette, source, w as f64, h as f64);
let expected = before.map(|v| v * (1.0 + amount * (gain - 1.0)) as f32);
assert_eq!(*after, expected, "database shading uses the selected sensor position at pixel {i}");
}
}
let mut no_warp = oriented_lens;
no_warp.warp = None;
let (baseline, _, _) = proxies(&raw, &file, &transform, PROFILE_PROXY, 0.0, None, Some(&no_warp)).unwrap();
assert!(
aligned.data.iter().flatten().zip(baseline.data.iter().flatten()).any(|(a, b)| a.to_bits() != b.to_bits()),
"orientation {exif}: profile geometry must be accepted with identical vignetting on both routes"
);
let mut displayed = aligned.clone();
displayed.map_in_place(|p| p.map(|v| v.powf(0.7)));
let rms = geometry_rms(&displayed, &reference);
assert!(rms < 0.009, "orientation {exif}: WB exactly once and matching frames: {rms}");
let oriented_target = target.clone().into_oriented(orientation);
let expected = reference_at(&oriented_target, &aligned);
assert!(geometry_rms(&displayed, &expected) < 0.009, "orientation {exif}: absolute oriented ground truth");
// Missing geometry must take the same established CR3 framing path as a rejected profile.
let (plain, plain_ref, plain_clip) = proxies(&raw, &file, &transform, PROXY, 0.0, None, None).unwrap();
let (fallback, fallback_ref, fallback_clip) = proxies(&raw, &file, &transform, PROXY, 0.0, None, Some(&Default::default())).unwrap();
assert_eq!(plain.data, fallback.data);
assert_eq!(plain_ref.data, fallback_ref.data);
assert_eq!(plain_clip, fallback_clip);
}
}
/// Sensor, JPEG and clipping samples returned by the diagnostic proxy calls.
type DiagnosticProxy = (Rgb32f, Rgb32f, Vec<bool>);
/// Keep diagnostic TSV fields single-line and reversible, including literal backslashes.
fn diagnostic_tsv_field(value: &str) -> String {
value.replace('\\', "\\\\").replace('\t', "\\t").replace('\r', "\\r").replace('\n', "\\n")
}
/// Keep the PNG component bounded even when the native input name is already at its filesystem limit.
fn diagnostic_artifact_id(name: &std::ffi::OsStr) -> String {
lightcraft_denoise_core::hash::sha256_hex(name.as_encoded_bytes())
}
/// Atomically claim an empty directory so a failed or concurrent run cannot alter earlier output.
fn diagnostic_run_dir(root: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
std::fs::create_dir_all(root)?;
let mut run = 1u64;
loop {
let path = root.join(format!("run-{run}"));
match std::fs::create_dir(&path) {
Ok(()) => return Ok(path),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => run += 1,
Err(error) => return Err(error),
}
}
}
#[cfg(any(unix, windows))]
#[test]
fn cr3_diagnostics_preserve_distinct_native_filenames() {
#[cfg(unix)]
let names = {
use std::os::unix::ffi::OsStrExt;
[b"A\x80.CR3", b"A\x81.CR3"].map(|bytes| std::ffi::OsStr::from_bytes(bytes).to_owned())
};
#[cfg(windows)]
let names = {
use std::os::windows::ffi::OsStringExt;
[0xd800, 0xd801].map(|unit| std::ffi::OsString::from_wide(&[65, unit, 46, 67, 82, 51]))
};
assert_eq!(names[0].to_string_lossy(), names[1].to_string_lossy());
assert_ne!(diagnostic_artifact_id(&names[0]), diagnostic_artifact_id(&names[1]));
}
/// Preserve missing-proxy cases in the diagnostic TSV without inventing geometry or fit results.
/// `proxies` exposes no rejection reason, so the row records only which call returned `None`.
fn diagnostic_proxies_or_report(
name: impl AsRef<std::ffi::OsStr>,
raw: &RawImage,
profile_warp: bool,
plain: Option<DiagnosticProxy>,
chosen: Option<DiagnosticProxy>,
report: &mut impl std::io::Write,
) -> std::io::Result<Option<(DiagnosticProxy, DiagnosticProxy)>> {
let name = name.as_ref();
let status = match (plain, chosen) {
(Some(plain), Some(chosen)) => return Ok(Some((plain, chosen))),
(None, Some(_)) => "missing_plain_proxy",
(Some(_), None) => "missing_chosen_proxy",
(None, None) => "missing_both_proxies",
};
let mut fields = vec![String::new(); 18];
fields[0] = diagnostic_tsv_field(&name.to_string_lossy());
fields[1] = diagnostic_tsv_field(raw.metadata.model.as_deref().unwrap_or(""));
fields[2] = format!("{:?}", raw.orientation);
fields[3] = profile_warp.to_string();
fields[15] = status.to_owned();
fields[16] = "proxies returned None; underlying cause unavailable".to_owned();
fields[17] = diagnostic_artifact_id(name);
writeln!(report, "{}", fields.join("\t"))?;
Ok(None)
}
/// Build a small RGB CR3-shaped raw and embedded JPEG without opening any real photo.
fn diagnostic_proxy_fixture() -> (RawImage, Vec<u8>) {
let scene = profile_geometry_scene(96, 64);
let mut raw = profile_geometry_raw(&scene, [1.0; 3]);
raw.format = RawFormat::Cr3;
raw.crop = raw.active_area;
let file = profile_geometry_file(&scene, craft_tiff::IfdBuilder::new());
(raw, file)
}
/// Exercise the corpus diagnostic's actual proxy-result handling across missing and available inputs.
#[test]
fn cr3_diagnostics_report_missing_proxies_and_continue() {
let (mut raw, bytes) = diagnostic_proxy_fixture();
let transform = lightcraft_raw::color::camera_transform(&raw, D65);
let available = proxies(&raw, &bytes, &transform, PROXY, 0.0, None, None).unwrap();
// A valid spectral transform does not guarantee a usable sensor proxy. This synthetic
// single-channel raw lacks a CFA, so the established proxy path deliberately returns None.
let camera = lightcraft_raw::spectral::find(Some("Canon"), "Canon EOS R8").unwrap();
raw.color.color_matrix = camera.color_matrix.map(Some);
raw.color.forward_matrix = camera.forward_matrix.map(Some);
raw.color.illuminant = [17, 21];
raw.cpp = 1;
raw.data = lightcraft_raw::RawData::U16(vec![0; raw.width * raw.height]);
let calibrated = lightcraft_raw::color::camera_transform(&raw, D65);
assert!(!calibrated.matrix_is_fallback);
let missing = proxies(&raw, &bytes, &calibrated, PROXY, 0.0, None, None);
assert!(missing.is_none());
let mut report = Vec::new();
for (plain, chosen, status) in [
(missing.clone(), missing.clone(), "missing_both_proxies"),
(missing.clone(), Some(available.clone()), "missing_plain_proxy"),
(Some(available.clone()), missing, "missing_chosen_proxy"),
] {
assert!(diagnostic_proxies_or_report(status, &raw, true, plain, chosen, &mut report).unwrap().is_none());
}
let (plain, chosen) = diagnostic_proxies_or_report("available", &raw, false, Some(available.clone()), Some(available.clone()), &mut report)
.unwrap()
.expect("a later usable file must still reach measurement and image export");
let bits = |image: &Rgb32f| image.data.iter().flatten().map(|v| v.to_bits()).collect::<Vec<_>>();
assert_eq!(bits(&plain.0), bits(&available.0));
assert_eq!(chosen.1.data, available.1.data);
let report = String::from_utf8(report).unwrap();
let rows: Vec<_> = report.lines().collect();
assert_eq!(rows.len(), 3, "available proxies must not create an unavailable row");
for row in rows {
let fields: Vec<_> = row.split('\t').collect();
assert_eq!(fields.len(), 18);
assert_eq!(fields[17], diagnostic_artifact_id(fields[0].as_ref()));
assert_eq!(fields[0], fields[15], "all three missing cases retain distinct statuses");
assert!(fields[4..15].iter().all(|v| v.is_empty()), "unavailable metrics, gates and fits stay empty");
assert_eq!(fields[16], "proxies returned None; underlying cause unavailable");
}
}
/// Tabs, line endings and literal escape sequences remain distinguishable in the TSV.
#[test]
fn cr3_diagnostics_escape_text_fields_in_missing_rows() {
let name = "A\tB\nC\rD\\t.CR3";
let model = "Camera\tmodel\nline\rreturn\\n";
assert_eq!(diagnostic_tsv_field(name), r"A\tB\nC\rD\\t.CR3");
assert_eq!(diagnostic_tsv_field(model), r"Camera\tmodel\nline\rreturn\\n");
let (mut raw, _) = diagnostic_proxy_fixture();
raw.metadata.model = Some(model.into());
let mut report = Vec::new();
assert!(diagnostic_proxies_or_report(name, &raw, false, None, None, &mut report).unwrap().is_none());
let report = String::from_utf8(report).unwrap();
assert_eq!(report.lines().count(), 1);
let fields: Vec<_> = report.trim_end_matches('\n').split('\t').collect();
assert_eq!(fields.len(), 18);
assert_eq!(fields[0], diagnostic_tsv_field(name));
assert_eq!(fields[1], diagnostic_tsv_field(model));
assert_eq!(fields[15], "missing_both_proxies");
assert_eq!(fields[16], "proxies returned None; underlying cause unavailable");
}
/// Reusing an output root for missing or incomplete measurements preserves every earlier run.
#[test]
fn cr3_diagnostics_isolate_reruns_and_bound_png_names() {
let root = crate::tests_xmp::temp_dir("cr3-diagnostic-rerun");
let previous = diagnostic_run_dir(&root).unwrap();
let name = format!("{}.CR3", "x".repeat(251));
let id = diagnostic_artifact_id(name.as_ref());
let png_name = format!("{id}-chosen.png");
std::fs::write(previous.join(&png_name), b"previous image").unwrap();
std::fs::write(previous.join("geometry.tsv"), b"previous report").unwrap();
let current = diagnostic_run_dir(&root).unwrap();
let (raw, _) = diagnostic_proxy_fixture();
let report_path = current.join("geometry.tsv");
let mut report = std::fs::File::create(&report_path).unwrap();
assert!(diagnostic_proxies_or_report(&name, &raw, true, None, None, &mut report).unwrap().is_none());
let row = std::fs::read_to_string(report_path).unwrap();
assert_eq!(row.trim_end().split('\t').next_back(), Some(id.as_str()));
assert!(!current.join(&png_name).exists());
assert_eq!(std::fs::read(previous.join(&png_name)).unwrap(), b"previous image");
assert_eq!(std::fs::read(previous.join("geometry.tsv")).unwrap(), b"previous report");
std::fs::remove_dir_all(root).unwrap();
}
/// Opt-in diagnostic only: never opens the app or changes a catalogue. It exports the actual
/// selected correspondences, and reports rejection as rejection rather than decoder success.
#[test]
#[ignore = "explicit local corpus diagnostic; requires LIGHTCRAFT_CR3_DIAGNOSTICS and LIGHTCRAFT_CORPUS"]
fn corpus_cr3_profile_geometry_diagnostics() {
use std::io::Write;
let output = std::env::var_os("LIGHTCRAFT_CR3_DIAGNOSTICS").expect("explicit diagnostics require an output directory");
let corpus = std::path::PathBuf::from(std::env::var_os("LIGHTCRAFT_CORPUS").expect("diagnostics require a corpus"));
let output = diagnostic_run_dir(std::path::Path::new(&output)).unwrap();
eprintln!("CR3 diagnostic output: {}", output.display());
let mut report = std::fs::File::create(output.join("geometry.tsv")).unwrap();
writeln!(report, "file\tmodel\torientation\tprofile_warp\tgeometry_accepted\tplain_alignment\tchosen_alignment\tplain_structure\tchosen_structure\tplain_pairs\tchosen_pairs\tplain_look\tchosen_look\tframed_gate_scores\toriginal_gate_scores\tstatus\treason\tartifact_id").unwrap();
let raw_dir = corpus.join("raw");
let mut paths: Vec<_> = std::fs::read_dir(&raw_dir)
.unwrap_or_else(|e| panic!("{}: {e}", raw_dir.display()))
.map(|entry| entry.unwrap_or_else(|e| panic!("{}: {e}", raw_dir.display())).path())
.filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("cr3")))
.collect();
paths.sort();
assert!(!paths.is_empty(), "diagnostic corpus must contain CR3 files");
for path in paths {
let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
let mut raw = lightcraft_raw::decode(&bytes).unwrap();
let correction = crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(&bytes));
let lens = lens_geometry(&raw.opcodes.list3);
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw));
// Compare geometry with identical source-position vignetting on both routes.
let plain_correction = correction.map(|mut lens| {
lens.warp = None;
lens
});
let plain = super::look_fit::look_proxies(&raw, &bytes, &transform, lens.as_ref(), plain_correction.as_ref());
let chosen = super::look_fit::look_proxies(&raw, &bytes, &transform, lens.as_ref(), correction.as_ref());
let name = path.file_name().unwrap();
let profile_warp = correction.as_ref().is_some_and(|l| l.warp.is_some());
let Some((plain, chosen)) = diagnostic_proxies_or_report(name, &raw, profile_warp, plain, chosen, &mut report).unwrap() else {
continue;
};
let framed_scores = super::proxy::geometry_framed_scores();
let original_scores = if profile_warp { super::proxy::geometry_gate_scores() } else { None };
let accepted = plain.0.data.iter().flatten().zip(chosen.0.data.iter().flatten()).any(|(a, b)| a.to_bits() != b.to_bits());
let pairs = |v: &(Rgb32f, Rgb32f, Vec<bool>)| {
let sensor = without_clipped(&v.0, &v.2).unwrap_or_else(|| v.0.clone());
collect_pairs(&sensor, &v.1, 0.05, None, false).map_or(0, |v| v.0.len())
};
let before = fit_preview(&raw, &bytes, &transform, lens.as_ref(), plain_correction.as_ref()).0.is_some();
let after = fit_preview(&raw, &bytes, &transform, lens.as_ref(), correction.as_ref()).0.is_some();
let id = diagnostic_artifact_id(name);
for (label, image) in [("plain", &plain.0), ("chosen", &chosen.0), ("jpeg", &chosen.1)] {
let to_srgb = lightcraft_color::SRGB.from_xyz().mul(&REC2020.to_xyz());
let pixels: Vec<u8> = image
.data
.iter()
.flat_map(|p| {
to_srgb.apply_f32(*p).map(|v| {
let v = if v.is_finite() { v.max(0.0) } else { 0.0 };
let v = if v <= 0.0031308 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 };
(v.clamp(0.0, 1.0) * 255.0).round() as u8
})
})
.collect();
let image = lightcraft_codecs::EncodeImage::new(image.width as u32, image.height as u32, 3, lightcraft_codecs::Samples::U8(&pixels));
std::fs::write(output.join(format!("{id}-{label}.png")), lightcraft_codecs::encode_png(&image, &Default::default()).unwrap()).unwrap();
}
writeln!(
report,
"{}\t{}\t{:?}\t{}\t{accepted}\t{:.6}\t{:.6}\t{}\t{}\t{}\t{}\t{before}\t{after}\t{framed_scores:?}\t{original_scores:?}\tmeasured\t\t{id}",
diagnostic_tsv_field(&name.to_string_lossy()),
diagnostic_tsv_field(raw.metadata.model.as_deref().unwrap_or("")),
raw.orientation,
profile_warp,
alignment(&plain.0, &plain.1),
alignment(&chosen.0, &chosen.1),
structure_agrees(&plain.0, &plain.1),
structure_agrees(&chosen.0, &chosen.1),
pairs(&plain),
pairs(&chosen)
)
.unwrap();
}
}
/// Keep the accepted CR3 framing fallback when a proposed profile warp fails its paired comparison.
#[test]
fn cr3_rejected_profile_preserves_accepted_framing_fallback() {
let mut raw = profile_geometry_raw(&profile_geometry_scene(416, 288), [1.25, 1.0, 0.8]);
raw.format = RawFormat::Cr3;
let transform = lightcraft_raw::color::camera_transform(&raw, D65);
assert!(transform.matrix_is_fallback);
let mut sensor = sensor_proxy(&raw, 2, 384).unwrap();
assert_eq!((sensor.width, sensor.height), (384, 256));
sensor.map_in_place(|p| {
transform.matrix.apply_f32(std::array::from_fn(|i| p[i] * transform.wb[i] * 2f32.powf(transform.baseline_exposure as f32)))
});
let lens = synthetic_profile_lens();
let mut target = profile_geometry_target(&sensor, &Default::default(), Cr3Framing { scale: 0.95, offset: [0.006, -0.004] });
target.map_in_place(|p| p.map(|v| v.powf(0.7)));
let file = profile_geometry_file(&target, craft_tiff::IfdBuilder::new());
let original_only = align_profile_geometry(&sensor, &Rgb32f::new(384, 256), &target, &lens, lightcraft_geom::Orientation::Normal);
assert!(original_only.is_some(), "this moderate wrong-lens proposal clears original-only gates, so the framed guard is necessary");
let (plain, reference, mask) = proxies(&raw, &file, &transform, PROXY, 0.0, None, None).unwrap();
let (fallback, fallback_reference, fallback_mask) = proxies(&raw, &file, &transform, PROXY, 0.0, None, Some(&lens)).unwrap();
let mut comparison = plain.clone();
comparison.map_in_place(|p| p.map(|v| v.powf(0.7)));
assert!(geometry_rms(&comparison, &reference) < 0.009, "existing framing fallback still aligns this JPEG");
assert!(
plain.data.iter().flatten().zip(fallback.data.iter().flatten()).all(|(a, b)| a.to_bits() == b.to_bits()),
"wrong lens must be rejected before established framing"
);
assert_eq!(reference.data, fallback_reference.data);
assert_eq!(mask, fallback_mask);
let plain_samples = profile_samples(&raw, &file, None, None).unwrap();
assert!(!plain_samples.colour.is_empty() && !plain_samples.tone.is_empty());
let mut correction = lens;
correction.vignette =
Some(lightcraft_develop::EmbeddedVignette { k: [0.15, 0.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.5, 0.5), radius: 0.6 });
correction.source = lightcraft_develop::LensSource::Database;
let no_warp = lightcraft_develop::EmbeddedLens { warp: None, ..correction };
let measured = super::look_fit::look_proxies(&raw, &file, &transform, None, Some(&no_warp)).unwrap();
let rejected = super::look_fit::look_proxies(&raw, &file, &transform, None, Some(&correction)).unwrap();
assert_eq!(measured.0.data, rejected.0.data, "rejection preserves the database-vignette measurement on the original framing");
assert_eq!(measured.2, rejected.2);
let rejected_warp = correction.warp;
for (case, warp) in [("rejected warp", rejected_warp), ("absent warp", None)] {
correction.warp = warp;
let samples = profile_samples(&raw, &file, None, Some(&correction)).unwrap();
assert!(
samples.colour == plain_samples.colour && samples.tone == plain_samples.tone,
"{case} must preserve both original pooled inputs with a nonzero vignette"
);
}
}
/// The guarded fit is assessed on real sensor data, never on the JPEG fallback. A corpus
/// download or an unfinished codec cannot make this test claim a successful RAW calibration.
#[test]
@@ -1505,9 +2086,13 @@ fn corpus_cr3_gets_a_framing_aligned_camera_look() {
.map(std::path::PathBuf::from)
.unwrap_or_else(|| std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"))
.join("raw/cr3-canon-r100-raw.cr3");
let Ok(bytes) = std::fs::read(&path) else {
lightcraft_testkit::skip!(Corpus, "{} absent", path.display());
return;
let bytes = match std::fs::read(&path) {
Ok(bytes) => bytes,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
lightcraft_testkit::skip!(Corpus, "{} absent", path.display());
return;
}
Err(e) => panic!("{}: {e}", path.display()),
};
let raw = match lightcraft_raw::decode(&bytes) {
Ok(raw) => raw,
@@ -3620,7 +4205,7 @@ fn the_vignetting_gain_of_a_framed_proxy_is_taken_where_its_pixels_come_from() {
let vignette = EmbeddedVignette { k: [2.0, 1.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.5, 0.5), radius: 0.6 };
let (w, h) = (96, 64);
let framing = Cr3Framing { scale: 0.92, offset: [0.02, -0.015] };
let frame = ProxyFrame { orientation: lightcraft_geom::Orientation::Normal, framing: Some(framing) };
let frame = ProxyFrame { orientation: lightcraft_geom::Orientation::Normal, framing: Some(framing), lens: None };
let gains = vignetting_gains(&Rgb32f::new(w, h), &vignette, frame);
for i in [0, w - 1, w * h / 2 + w / 3, w * h - 1] {
let (x, y) = framing.source((i % w) as f32 + 0.5, (i / w) as f32 + 0.5, w, h);
@@ -3762,7 +4347,7 @@ fn camera_vignetting_amount_follows_a_cr3_proxys_framing() {
}
let clipped = vec![false; w * h];
let measure = |reference: &Rgb32f, framing: Option<Cr3Framing>| {
camera_vignetting_amount(&sensor, reference, &clipped, &vignette, ProxyFrame { orientation: Orientation::Normal, framing })
camera_vignetting_amount(&sensor, reference, &clipped, &vignette, ProxyFrame { orientation: Orientation::Normal, framing, lens: None })
};
for shown in [0.0f32, 0.75, 1.0] {
let mut reference = sensor.clone();
+1 -1
View File
@@ -324,7 +324,7 @@ fn thinned<T>(items: Vec<T>) -> impl Iterator<Item = T> {
impl Pool {
/// Add one raw file's colour pairs and tone samples. A photo too dark or colourless for colour pairs still gives
/// its tone samples (the shadows the pooled curve needs) without counting toward the profile's photos. `Ok(None)`
/// when the file can't contribute (not an ARW, NEF or RAF without colour matrices, no usable or a black-and-white
/// when the file can't contribute (not a supported RAW without colour matrices, no usable or a black-and-white
/// camera JPEG).
pub fn add(&mut self, bytes: &[u8]) -> Result<Option<Added>, String> {
let mut raw = lightcraft_raw::decode(bytes).map_err(|e| e.to_string())?;
+5 -3
View File
@@ -167,12 +167,13 @@ fn analyze(s: &mut Session, p: &Value) -> Result<Value> {
/// takes over, and the rest of the selection stays selected.
fn keep_active_shown(s: &mut Session) {
let vis = s.visible_cloned();
let vis_set: std::collections::HashSet<PhotoId> = vis.iter().copied().collect();
if let Some(a) = s.selection.active
&& !vis.contains(&a)
&& !vis_set.contains(&a)
&& let Some(st) = s.catalog.stack_of(a)
{
let top = vis.iter().copied().find(|p| st.photos.contains(p)).unwrap_or(st.top());
s.selection.ids.retain(|id| vis.contains(id));
s.selection.ids.retain(|id| vis_set.contains(id));
if !s.selection.ids.contains(&top) {
s.selection.ids.push(top);
}
@@ -239,8 +240,9 @@ fn move_to_burst(s: &mut Session, p: &Value) -> Result<Value> {
old.entry(g).or_insert_with(|| index.get(&g).cloned().unwrap_or_default());
}
let mut new = old.clone();
let moved: std::collections::HashSet<PhotoId> = ids.iter().copied().collect();
for members in new.values_mut() {
members.retain(|m| !ids.contains(m));
members.retain(|m| !moved.contains(m));
}
if let Some(g) = target {
let members = new.entry(g).or_default();
+73 -23
View File
@@ -7,7 +7,7 @@
//! validated before they become folder names, and nothing outside a model's own folder is ever touched.
use std::path::{Path, PathBuf};
use std::sync::{Arc, PoisonError, mpsc};
use std::sync::{Arc, mpsc};
use lightcraft_catalog::PhotoId;
use lightcraft_denoise::archive;
@@ -29,6 +29,13 @@ fn models_dir(s: &Session, cmd: &str) -> Result<PathBuf> {
s.denoise.models_dir.clone().ok_or_else(|| bad(cmd, "this build has nowhere to keep denoise models (the desktop app does)"))
}
/// Remember the pre-upgrade default before a change can replace its settings or weights.
fn model_change_dir(s: &Session, cmd: &str) -> Result<PathBuf> {
let dir = models_dir(s, cmd)?;
crate::denoise::ensure_legacy_settings(&dir).map_err(EngineError::Other)?;
Ok(dir)
}
/// What a command says about a model.
fn row(m: &DenoiserManifest, download_host: Option<String>, installed: bool, selected: bool, accepted: &Value) -> Value {
json!({
@@ -240,11 +247,7 @@ fn activate_install(s: &mut Session, result: &Value, model: Arc<dyn crate::denoi
}
s.denoise.touch();
s.denoise_refresh_active(true);
if let Some(a) = &s.denoise.active
&& a.id == id
{
*a.model.lock().unwrap_or_else(PoisonError::into_inner) = Some(model);
}
s.denoise_keep_model(id, model);
let mut v = result.clone();
v["installed"]["selected"] = json!(st.model.as_deref() == Some(id));
v["model"] = json!(st.model);
@@ -256,7 +259,7 @@ fn start_install(s: &mut Session, src: PathBuf, id: String, activate: bool, veri
if s.denoise.install.is_some() {
return Err(bad(C, "another model is being installed"));
}
let dir = models_dir(s, C)?;
let dir = model_change_dir(s, C)?;
let loader = s.denoise.loader.clone();
let run_on = s.denoise.settings.run_on();
let at = (s.clock)();
@@ -299,7 +302,7 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
let (result, model) = install_file(
&s.denoise.loader,
InstallFile {
dir: &models_dir(s, C)?,
dir: &model_change_dir(s, C)?,
run_on: s.denoise.settings.run_on(),
accepted_at: (s.clock)(),
command: C,
@@ -447,7 +450,7 @@ fn test(s: &mut Session, p: &Value) -> Result<Value> {
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "denoise.models.remove";
let id = str_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
let dir = models_dir(s, C)?;
let dir = model_change_dir(s, C)?;
if !lightcraft_denoise::licence::valid_id(id) {
return Err(bad(C, "not a model id"));
}
@@ -469,7 +472,7 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
fn select(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "denoise.models.select";
let dir = models_dir(s, C)?;
let dir = model_change_dir(s, C)?;
let id = match p.get("id") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_str().ok_or_else(|| bad(C, "`id` must be a model id or null"))?.to_string()),
@@ -518,9 +521,7 @@ fn settings(s: &mut Session, p: &Value) -> Result<Value> {
// a choice of where denoise runs is also a go-ahead to try the card again: a set-up that crashed or gave up
// before is forgotten, and the loaded model sets the card up afresh for the next photo
forget_gpu_set_ups(&dir);
if let Some(a) = &s.denoise.active {
*a.model.lock().unwrap_or_else(PoisonError::into_inner) = None;
}
s.denoise_forget_loaded_models();
}
s.denoise.touch();
s.denoise_refresh_active(true);
@@ -554,13 +555,50 @@ fn status_json(s: &Session, photo: Option<PhotoId>) -> Value {
v
}
fn target_photo(s: &Session, p: &Value, command: &str) -> Result<PhotoId> {
super::photo_id(p, command)?.or_else(|| s.active()).ok_or_else(|| bad(command, "select a raw photo"))
}
fn photo_info(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "denoise.photo.info";
let id = target_photo(s, p, C)?;
s.denoise_refresh_active(false);
let settings = s.develop_of(id).ok_or_else(|| bad(C, "no such photo"))?;
let saved = settings.enhance.denoise_model.as_ref();
let pin = saved.cloned().unwrap_or_else(|| s.denoise_assignment_pin());
let manifests = s.denoise_manifests();
let name = manifests.iter().find(|m| m.id == pin.id).map_or(pin.id.as_str(), |m| m.name.as_str());
let models: Vec<_> = manifests.iter().map(|m| json!({"id": m.id, "name": m.name, "version": m.version, "available": true})).collect();
Ok(json!({
"id": id.0, "assigned": saved.is_some(), "models": models,
"model": {"id": pin.id, "name": name, "version": pin.version, "sha256": pin.sha256, "available": s.denoise_validate_pin(&pin)}
}))
}
fn photo_model(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "denoise.photo.model";
let id = target_photo(s, p, C)?;
let model = str_param(p, "model").ok_or_else(|| bad(C, "missing `model`"))?;
s.denoise_refresh_active(true);
let pin = s.denoise_pin(model).map_err(EngineError::Other)?;
let photo = s.catalog.photo(id).ok_or_else(|| bad(C, "no such photo"))?;
if !crate::denoise::eligible(photo) {
return Err(bad(C, "AI Denoise applies to raw photos developed from their sensor data"));
}
if photo.develop.enhance.denoise_model.as_ref() != Some(&pin) {
s.end_interaction()?;
let mut settings = (*s.develop_of(id).ok_or_else(|| bad(C, "no such photo"))?).clone();
settings.enhance.denoise_model = Some(pin);
let op = s.develop_op(id, settings, "Denoise Model").ok_or_else(|| bad(C, "no such photo"))?;
s.commit("Denoise Model", op)?;
}
photo_info(s, &json!({"id": id.0}))
}
/// A per-photo switch, independent of the selection and Auto Sync. Turning on starts at 50%.
fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "denoise.toggle";
let id = match p.get("id") {
Some(v) => PhotoId(v.as_u64().ok_or_else(|| bad(C, "`id` must be a photo id"))?),
None => s.active().ok_or_else(|| bad(C, "select a raw photo"))?,
};
let id = target_photo(s, p, C)?;
let photo = s.catalog.photo(id).ok_or_else(|| bad(C, "no such photo"))?;
if !crate::denoise::eligible(photo) {
return Err(bad(C, "AI Denoise applies to raw photos developed from their sensor data"));
@@ -570,19 +608,21 @@ fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
Some(v) => v.as_bool().ok_or_else(|| bad(C, "`enabled` must be true or false"))?,
None => !d.enhance.denoise_enabled(),
};
let assign = on && d.enhance.denoise_model.is_none();
if on {
if !d.enhance.denoise.is_finite() {
return Err(bad(C, "the photo has an invalid Denoise amount"));
}
s.denoise_refresh_active(true);
if s.denoise.active.is_none() {
return Err(bad(C, "AI Denoise needs a model: install one in Settings > AI Denoise"));
if assign {
d.enhance.denoise_model = Some(s.denoise_assignment_pin());
}
s.denoise_validate_settings(&d).map_err(EngineError::Other)?;
}
// The switch is its own setting: the Amount stays where it is (0 included) when it is flipped, so flipping compares
// with and without. A photo that never had an Amount starts at 50 the first time.
let amount = if on && d.enhance.denoise_on.is_none() && d.enhance.denoise <= 0.0 { 50.0 } else { d.enhance.denoise };
if d.enhance.denoise != amount || d.enhance.denoise_on != Some(on) {
if assign || d.enhance.denoise != amount || d.enhance.denoise_on != Some(on) {
s.end_interaction()?;
d.enhance.denoise = amount;
d.enhance.denoise_on = Some(on);
@@ -655,22 +695,32 @@ fn clear(s: &mut Session, _: &Value) -> Result<Value> {
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(query "denoise.photo.info", "Photo Denoise Model", [], None, "{id?} → the assigned or default denoiser and available models", always, photo_info),
cmd!(
"denoise.photo.model",
"Choose Photo Denoise Model",
[],
None,
"{id?, model} → remember an installed denoiser or builtin for this raw photo",
always,
photo_model
),
cmd!(query "denoise.models.list", "Denoise Models", [], None, "{} → {dir, productsDir, model, runtime, auto, cacheGb, threads, runOn, models: [{id, name, version, licence{name, commercial, url, notice}, provenance, source, sizeBytes, sha256, tile, known, downloadHost, installed, selected, accepted}]}", always, list),
cmd!(query "denoise.models.inspect", "Inspect Denoise Model", [], None, "{path} → model terms from an adjacent manifest; never executes the file", always, inspect),
cmd!(query "denoise.models.install", "Install Denoise Model", [], None, "{path, acknowledged: true, activate?: true, background?: false} → {installed, model} or {started} — install a denoise model from a file: an .onnx with a denoise-model.json beside it, or an archive LightCraft knows (the darktable `.dtmodel`). `acknowledged` must be true: the user has been shown the model's licence and accepted it. Unless `activate` is false it becomes the model in use", always, install),
cmd!(query "denoise.models.install", "Install Denoise Model", [], None, "{path, acknowledged: true, activate?: true, background?: false} → {installed, model} or {started} — install a denoise model from a file: an .onnx with a denoise-model.json beside it, or an archive LightCraft knows (the darktable `.dtmodel`). `acknowledged` must be true: the user has been shown the model's licence and accepted it. Unless `activate` is false it becomes the default for new denoise edits", always, install),
cmd!(query "denoise.models.download", "Download Denoise Model", [], None, "{id, acknowledged: true} → {started, from} — fetch a model LightCraft has a pinned address for (see `downloadHost` in the list) in the background over HTTPS with lightcraft-fetch. `acknowledged` must be true: the user has been shown the model's terms and accepted them. It is checked against its size and SHA-256, installed and chosen by itself; `denoise.models.downloads` shows how far it is", always, download),
cmd!(query "denoise.models.downloads", "Denoise Model Downloads", [], None, "{} → {running, downloads: [{id, state: running | done | installed | failed | cancelled, bytes, total, error, from}]} — also installs any download that has arrived", always, downloads),
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 uses the built-in denoiser", always, select),
cmd!(query "denoise.models.select", "Choose Denoise Model", [], None, "{id: installed model | null} → {model} — choose the default for new denoise edits; 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; uses the built-in denoiser when no model is chosen",
"{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; remembers the current default on first use",
always,
toggle
),
+81 -12
View File
@@ -8,14 +8,16 @@
//! `%APPDATA%`. If that folder can't be written (read-only medium, Program Files), a warning is logged
//! and the platform folder is used.
//! 3. The platform convention: macOS `~/Library/Application Support/LightCraft`, Windows
//! `%APPDATA%\LightCraft`, Linux `$XDG_CONFIG_HOME/lightcraft` or `~/.config/lightcraft`.
//! `%APPDATA%\LightCraft`, Linux `$XDG_CONFIG_HOME/lightcraft` or `~/.config/lightcraft`. An empty or
//! relative `HOME`, `APPDATA` or `XDG_CONFIG_HOME` is ignored, so the folder is never under the launch
//! directory; with no usable one there is no settings folder.
//!
//! Hosts that have a file system (the desktop app, the CLI, the MCP server) share these defaults so a model
//! installed from one is there for the others. Nothing here is applied automatically: a [`Session`] has no
//! face-, denoise- or SAM 3 model folder until a host asks for one ([`Session::with_default_face_models`],
//! [`Session::with_default_denoise_models`], [`Session::with_default_sam3_model`]), so tests stay hermetic.
use std::ffi::OsString;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
@@ -79,6 +81,9 @@ fn config_dir_from(
}
/// `portable` is asked only without an override, so an isolated run never probes beside the executable.
/// An empty or relative `HOME`, `APPDATA` or `XDG_CONFIG_HOME` is ignored (an unusable `XDG_CONFIG_HOME`
/// gives way to `HOME`): it would put the settings folder, and the logs and crash log in it, under
/// whatever directory LightCraft was started in (issue #2572).
fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option<OsString>, portable: impl FnOnce() -> Option<PathBuf>) -> Option<PathBuf> {
if let Some(dir) = env("LIGHTCRAFT_CONFIG_DIR") {
return (!dir.is_empty()).then(|| PathBuf::from(dir));
@@ -86,12 +91,30 @@ fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option<OsString>, p
if let Some(dir) = portable() {
return Some(dir);
}
// Only a fully qualified folder: an empty or relative one would be under the launch directory,
// and on Windows `\foo` or `C:foo` would follow the current drive or its folder (#2572).
let folder = |name: &str| env(name).filter(|dir| fully_qualified(platform, dir)).map(PathBuf::from);
match platform {
Platform::Mac => env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/LightCraft")),
Platform::Windows => env("APPDATA").map(|a| PathBuf::from(a).join("LightCraft")),
Platform::Other => {
env("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))).map(|c| c.join("lightcraft"))
}
Platform::Mac => folder("HOME").map(|h| h.join("Library/Application Support/LightCraft")),
Platform::Windows => folder("APPDATA").map(|a| a.join("LightCraft")),
Platform::Other => folder("XDG_CONFIG_HOME").or_else(|| folder("HOME").map(|h| h.join(".config"))).map(|c| c.join("lightcraft")),
}
}
/// Whether `dir` names one folder whatever the current drive and directory, by `platform`'s rules
/// rather than the host's, so each arm is tested the same on every host: on Windows a drive path
/// (`C:\…`) or a UNC or device path (`\\server\share`, `\\?\…`), elsewhere a path from `/`.
fn fully_qualified(platform: Platform, dir: &OsStr) -> bool {
let text = dir.to_string_lossy();
let b = text.as_bytes();
let sep = |c: &u8| *c == b'\\' || *c == b'/';
match platform {
Platform::Windows => match (b.first(), b.get(1), b.get(2)) {
(Some(drive), Some(b':'), Some(c)) => drive.is_ascii_alphabetic() && sep(c),
(Some(a), Some(c), Some(d)) => sep(a) && sep(c) && !sep(d),
_ => false,
},
Platform::Mac | Platform::Other => b.first() == Some(&b'/'),
}
}
@@ -247,7 +270,8 @@ mod config_tests {
assert!(data.is_dir());
assert_eq!(std::fs::read_dir(&data).unwrap().count(), 0, "the write probe is removed");
let found = portable_dir_in(&exe).unwrap();
let actual = config_dir_with(Platform::Windows, |name| (name == "APPDATA").then(|| OsString::from("/roaming")), || found);
let actual =
config_dir_with(Platform::Windows, |name| (name == "APPDATA").then(|| OsString::from(r"C:\Users\me\AppData\Roaming")), || found);
assert_eq!(actual, Some(data));
let _ = std::fs::remove_dir_all(&exe);
}
@@ -307,16 +331,16 @@ mod config_tests {
assert_eq!(actual, Some(root.join("Settings")));
}
assert_eq!(
config_dir_from(None, Platform::Windows, |name| (name == "APPDATA").then(|| OsString::from("/roaming")), || None),
Some(PathBuf::from("/roaming/LightCraft"))
config_dir_from(None, Platform::Windows, |name| (name == "APPDATA").then(|| OsString::from(r"C:\Roaming")), || None),
Some(PathBuf::from(r"C:\Roaming").join("LightCraft"))
);
}
#[test]
fn config_unset_override_keeps_platform_defaults() {
let vars = [("HOME", "/user"), ("APPDATA", "/roaming"), ("XDG_CONFIG_HOME", "/xdg")];
let vars = [("HOME", "/user"), ("APPDATA", r"C:\Users\me\AppData\Roaming"), ("XDG_CONFIG_HOME", "/xdg")];
assert_eq!(resolve(Platform::Mac, &vars), Some(PathBuf::from("/user/Library/Application Support/LightCraft")));
assert_eq!(resolve(Platform::Windows, &vars), Some(PathBuf::from("/roaming/LightCraft")));
assert_eq!(resolve(Platform::Windows, &vars), Some(PathBuf::from(r"C:\Users\me\AppData\Roaming").join("LightCraft")));
assert_eq!(resolve(Platform::Other, &vars), Some(PathBuf::from("/xdg/lightcraft")));
assert_eq!(resolve(Platform::Other, &[("HOME", "/user")]), Some(PathBuf::from("/user/.config/lightcraft")));
for platform in [Platform::Mac, Platform::Windows, Platform::Other] {
@@ -324,6 +348,51 @@ mod config_tests {
}
}
/// #2572 review: an empty or relative `HOME`, `APPDATA` or `XDG_CONFIG_HOME` would put the settings
/// folder (and the crash log and logs in it) under the launch directory, where another user could
/// have planted the folder and a link. Such a value is ignored: an unusable `XDG_CONFIG_HOME` falls
/// back to `HOME`, and with neither usable there is no settings folder.
#[test]
fn config_ignores_empty_or_relative_platform_folders() {
for bad in ["", "relative", "./here", "../up"] {
assert_eq!(resolve(Platform::Mac, &[("HOME", bad)]), None, "HOME={bad:?}");
assert_eq!(resolve(Platform::Other, &[("HOME", bad)]), None, "HOME={bad:?}");
assert_eq!(resolve(Platform::Windows, &[("APPDATA", bad), ("HOME", "/user")]), None, "APPDATA={bad:?}");
assert_eq!(resolve(Platform::Other, &[("XDG_CONFIG_HOME", bad)]), None, "XDG_CONFIG_HOME={bad:?}");
assert_eq!(resolve(Platform::Other, &[("XDG_CONFIG_HOME", bad), ("HOME", bad)]), None, "both {bad:?}");
assert_eq!(
resolve(Platform::Other, &[("XDG_CONFIG_HOME", bad), ("HOME", "/user")]),
Some(PathBuf::from("/user/.config/lightcraft")),
"XDG_CONFIG_HOME={bad:?} falls back to HOME"
);
assert_eq!(
resolve(Platform::Other, &[("XDG_CONFIG_HOME", "/xdg"), ("HOME", bad)]),
Some(PathBuf::from("/xdg/lightcraft")),
"a usable XDG_CONFIG_HOME doesn't need HOME"
);
}
}
/// #2572 review: on Windows `APPDATA` must be fully qualified. `\foo` and `/foo` follow the current
/// drive and `C:foo` that drive's current folder, so the launch drive could choose the folder.
#[test]
fn windows_appdata_must_be_fully_qualified() {
for good in [r"C:\Users\me\AppData\Roaming", "D:/Data", r"\\server\share\Roaming", r"\\?\C:\Users\me\AppData\Roaming"] {
assert_eq!(resolve(Platform::Windows, &[("APPDATA", good)]), Some(PathBuf::from(good).join("LightCraft")), "APPDATA={good:?}");
}
for bad in [r"\foo", "/roaming", "C:foo", "C:", "c", r"\\"] {
assert_eq!(resolve(Platform::Windows, &[("APPDATA", bad)]), None, "APPDATA={bad:?}");
}
}
/// The explicit profile keeps its own policy: a relative `LIGHTCRAFT_CONFIG_DIR` is the user's choice.
#[test]
fn config_override_may_still_be_relative() {
for platform in [Platform::Mac, Platform::Windows, Platform::Other] {
assert_eq!(resolve(platform, &[("LIGHTCRAFT_CONFIG_DIR", "isolated"), ("HOME", "")]), Some(PathBuf::from("isolated")));
}
}
#[cfg(unix)]
#[test]
fn config_override_preserves_non_unicode_paths() {
+5 -2
View File
@@ -26,7 +26,7 @@ use lightcraft_denoise::bayer::Layout;
use lightcraft_denoise::manifest::DenoiserManifest;
use lightcraft_denoise::run::{Control, Params, TileRunner, denoise_bayer};
use lightcraft_denoise::{Error as RunError, product};
use lightcraft_develop::DevelopSettings;
use lightcraft_develop::{DenoiseModelPin, DevelopSettings};
use lightcraft_preview::Hasher128;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -60,7 +60,10 @@ pub(crate) use products::eligible;
#[cfg(test)]
pub(crate) use products::{JobSpec, MakeError, Progress, make_product};
pub use settings::{DEFAULT_CACHE_GB, DIR, EXT};
pub(crate) use settings::{Settings, forget_gpu_set_ups, installed_models, read_capped, read_settings, write_atomic, write_settings};
pub(crate) use settings::{
Settings, capture_legacy_pin, ensure_legacy_settings, forget_gpu_set_ups, installed_models, read_capped, read_settings, write_atomic,
write_settings,
};
pub(crate) use state::State;
pub use state::{Pace, PhotoState};
+28 -3
View File
@@ -4,9 +4,9 @@ use super::gpu::{GPU_CRASHED, GPU_MAX_FALLBACKS, GPU_PARALLEL, GPU_SLOW, GPU_STU
use super::settings::{installed_models, read_settings};
#[cfg(feature = "denoise")]
use super::state::Pace;
use super::{Arc, DenoiserManifest, Mutex, Path, TileRunner, Value, json};
use super::{Arc, DenoiserManifest, Mutex, Path, PoisonError, TileRunner, Value, json};
#[cfg(feature = "denoise")]
use super::{AtomicBool, AtomicUsize, OnceLock, Ordering, PathBuf, PoisonError, RunError};
use super::{AtomicBool, AtomicUsize, OnceLock, Ordering, PathBuf, RunError};
/// Stack of the threads that run the model (the runtime recurses through its graph).
pub(super) const STACK: usize = 16 << 20;
@@ -439,4 +439,29 @@ pub fn serving(dir: Option<&Path>, id: Option<&str>, run_on: RunOn) -> Result<Se
}
/// A model that is loaded on first use and kept, shared by the background job and the exports.
pub(crate) type ModelSlot = Arc<Mutex<Option<Arc<dyn Model>>>>;
type CachedNetwork = Mutex<Option<Arc<dyn Model>>>;
pub(crate) type ModelSlot = Arc<CachedNetwork>;
/// Only the most recently loaded network stays resident between jobs. Concurrent inference owns its own Arc.
#[derive(Default)]
pub(crate) struct WarmModel(Mutex<std::sync::Weak<CachedNetwork>>);
impl WarmModel {
pub(super) fn keep(&self, slot: &ModelSlot, model: Arc<dyn Model>) {
let mut last = self.0.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(previous) = last.upgrade()
&& !Arc::ptr_eq(&previous, slot)
{
previous.lock().unwrap_or_else(PoisonError::into_inner).take();
}
*slot.lock().unwrap_or_else(PoisonError::into_inner) = Some(model);
*last = Arc::downgrade(slot);
}
pub(super) fn forget(&self) {
let mut last = self.0.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(slot) = std::mem::take(&mut *last).upgrade() {
slot.lock().unwrap_or_else(PoisonError::into_inner).take();
}
}
}
+18 -2
View File
@@ -9,13 +9,21 @@ use super::{
/// Samples at or above this (white = 1) are clipped: the model leaves them as the camera recorded them.
const CLIP: f32 = 0.99;
/// The model in use.
/// An installed model and the shared slot used by jobs for this installation.
#[derive(Clone)]
pub(crate) struct Active {
pub id: String,
pub manifest: DenoiserManifest,
pub onnx: PathBuf,
pub fingerprint: String,
pub model: ModelSlot,
pub(super) file_stamp: Option<(u64, SystemTime)>,
}
impl Active {
pub(super) fn pin(&self) -> super::DenoiseModelPin {
super::DenoiseModelPin { id: self.id.clone(), version: self.manifest.version.clone(), sha256: self.manifest.sha256.clone() }
}
}
// ---------------------------------------------------------------------------------------------------------------------
@@ -93,6 +101,7 @@ pub(crate) struct JobSpec {
pub onnx: PathBuf,
pub model: ModelSlot,
pub loader: Loader,
pub warm_model: Arc<super::model::WarmModel>,
/// Tiles run at once.
pub parallel: usize,
/// Where the model runs (the setting).
@@ -140,8 +149,15 @@ pub(super) fn loaded(spec: &JobSpec) -> Result<Arc<dyn Model>, MakeError> {
if let Some(m) = spec.model.lock().unwrap_or_else(PoisonError::into_inner).clone() {
return Ok(m);
}
if let Some(expected) = &spec.manifest.sha256 {
let hash =
lightcraft_denoise::hash::sha256_file(&spec.onnx).map_err(|e| MakeError::Failed(format!("could not verify denoise model: {e}")))?;
if hash != *expected {
return Err(MakeError::Failed("the installed denoise model no longer matches its recorded SHA-256".into()));
}
}
let m = (spec.loader)(&spec.onnx, &spec.manifest).map_err(|e| MakeError::Failed(format!("the denoise model could not be loaded: {e}")))?;
*spec.model.lock().unwrap_or_else(PoisonError::into_inner) = Some(m.clone());
spec.warm_model.keep(&spec.model, m.clone());
Ok(m)
}
+189 -58
View File
@@ -4,11 +4,11 @@ use super::builtin::{builtin_card, builtin_marker};
use super::model::Model;
use super::model::STACK;
use super::products::{Active, JobSpec, MakeError, Progress, eligible, make_product, product_key, product_path, products_in};
use super::settings::{DIR, SETTINGS_TTL, installed_models, read_settings};
use super::settings::{DIR, SETTINGS_TTL, builtin_pin, configured_pin, installed_models, read_settings};
use super::state::{AUTO_LOOK, Failure, MAX_QUEUE, Outcome, Pace, PhotoState, Running};
use super::{
Arc, DenoiseSpec, DevelopSettings, HashMap, HashSet, MakeProduct, Mutex, Ordering, PairLoader, Path, PathBuf, Photo, PhotoId, PoisonError,
Selection, Session, Source, Value, json, product,
Arc, DenoiseModelPin, DenoiseSpec, DenoiserManifest, DevelopSettings, HashMap, HashSet, MakeProduct, Mutex, Ordering, PairLoader, Path, PathBuf,
Photo, PhotoId, PoisonError, Selection, Session, Source, Value, json, product,
};
impl Session {
@@ -31,43 +31,125 @@ impl Session {
self.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join(DIR))
}
/// Read which model is in use (at most every couple of seconds): the manifest and file of the model the settings
/// name, if it is installed.
/// Refresh the installed models and the default without disturbing photos that still resolve to the same identity.
pub(crate) fn denoise_refresh_active(&mut self, force: bool) {
let fresh = self.denoise.active_seen.is_some_and(|t| t.elapsed() < SETTINGS_TTL);
if fresh && !force {
if !force && self.denoise.active_seen.is_some_and(|t| t.elapsed() < SETTINGS_TTL) {
return;
}
self.denoise.active_seen = Some(web_time::Instant::now());
self.denoise.settings = self.denoise.models_dir.as_deref().map(read_settings).unwrap_or_default();
let chosen = self.denoise.models_dir.as_deref().and_then(|dir| {
let id = self.denoise.settings.model.clone()?;
installed_models(dir).into_iter().find(|i| i.manifest.id == id)
});
// 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)
}
let dir = self.denoise.models_dir.as_deref();
self.denoise.settings = dir.map(read_settings).unwrap_or_default();
let mut models = std::collections::BTreeMap::new();
let m = lightcraft_denoise::builtin::manifest();
let builtin = Active {
id: m.id.clone(),
onnx: dir.map(|d| d.join(&m.id)).unwrap_or_default(),
fingerprint: format!("{}@{}", m.id, m.version),
manifest: m,
model: Default::default(),
file_stamp: None,
};
if self.denoise.active.as_ref().is_some_and(|a| a.fingerprint == fingerprint) {
return;
models.insert(builtin.id.clone(), builtin);
for mut i in dir.map(installed_models).unwrap_or_default() {
let file_stamp = std::fs::metadata(&i.onnx).ok().and_then(|m| Some((m.len(), m.modified().ok()?)));
let previous =
self.denoise.registry.get(&i.manifest.id).filter(|a| a.onnx == i.onnx && a.file_stamp == file_stamp && file_stamp.is_some());
let pin = match i.pin(previous.and_then(|a| a.manifest.sha256.as_deref())) {
Ok(pin) => pin,
Err(why) => {
log::warn!("could not identify denoiser {}: {why}", i.manifest.id);
continue;
}
};
// Identical weights can be applied with different tiling or output scaling.
let fingerprint = json!([pin, i.manifest.domain, i.manifest.tile, i.manifest.overlap, i.manifest.gain]).to_string();
i.manifest.sha256 = pin.sha256;
let model = previous.filter(|a| a.manifest == i.manifest).map(|a| a.model.clone()).unwrap_or_default();
let a = Active { id: pin.id, manifest: i.manifest, onnx: i.onnx, fingerprint, model, file_stamp };
models.insert(a.id.clone(), a);
}
// another model: what was made with the old one is not this one's, and what failed may work now
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();
let default_id = self.denoise.settings.model.as_deref().unwrap_or(lightcraft_denoise::builtin::ID);
let default = models.get(default_id).or_else(|| models.get(lightcraft_denoise::builtin::ID)).cloned();
let changed = self.denoise.active.as_ref().map(|a| &a.fingerprint) != default.as_ref().map(|a| &a.fingerprint)
|| models.len() != self.denoise.registry.len()
|| models
.iter()
.any(|(id, a)| self.denoise.registry.get(id).is_none_or(|old| old.fingerprint != a.fingerprint || old.file_stamp != a.file_stamp));
self.denoise.active = default;
self.denoise.registry = models;
if changed {
self.denoise.failed.clear();
if let Some(r) = &self.denoise.running
&& self.catalog.photo(r.photo).and_then(|p| self.denoise_spec(p)).is_none_or(|(_, key)| key != r.key)
{
r.progress.cancel_now();
}
self.denoise_reindex();
self.denoise.generation += 1;
}
self.denoise.queue.clear();
self.denoise.failed.clear();
self.denoise.dirty = true;
}
pub(crate) fn denoise_assignment_pin(&self) -> DenoiseModelPin {
if self.denoise.active_seen.is_some()
&& let Some(active) = &self.denoise.active
{
return active.pin();
}
let Some(dir) = self.denoise.models_dir.as_deref() else { return builtin_pin() };
configured_pin(dir, &read_settings(dir)).unwrap_or_else(|_| builtin_pin())
}
pub(crate) fn denoise_forget_loaded_models(&self) {
self.denoise.warm_model.forget();
}
pub(crate) fn denoise_keep_model(&self, id: &str, model: Arc<dyn super::Model>) {
if let Some(a) = self.denoise.registry.get(id) {
self.denoise.warm_model.keep(&a.model, model);
}
}
pub(crate) fn denoise_manifests(&self) -> Vec<DenoiserManifest> {
self.denoise.registry.values().map(|a| a.manifest.clone()).collect()
}
pub(crate) fn denoise_pin(&self, id: &str) -> Result<DenoiseModelPin, String> {
self.denoise.registry.get(id).map(Active::pin).ok_or_else(|| format!("denoise model `{id}` is not installed"))
}
pub(crate) fn denoise_validate_pin(&self, pin: &DenoiseModelPin) -> bool {
self.denoise_pinned(pin).is_some()
}
fn denoise_pinned(&self, pin: &DenoiseModelPin) -> Option<&Active> {
self.denoise.registry.get(&pin.id).filter(|a| a.manifest.version == pin.version && a.manifest.sha256 == pin.sha256)
}
pub(crate) fn denoise_validate_settings(&self, settings: &DevelopSettings) -> Result<(), String> {
self.denoise_resolve(settings).map(|_| ())
}
pub(crate) fn denoise_photo_changed(&mut self, id: PhotoId) {
self.denoise_cancel(Some(id), false);
self.media.denoise.remove(id);
self.media.forget(id);
self.denoise.failed.remove(&id);
self.denoise_check_photo(id);
self.denoise.generation += 1;
}
fn denoise_resolve(&self, settings: &DevelopSettings) -> Result<&Active, String> {
let Some(pin) = &settings.enhance.denoise_model else {
return self.denoise.active.as_ref().ok_or_else(|| "no denoiser is available".into());
};
self.denoise_pinned(pin).ok_or_else(|| {
let hash = pin.sha256.as_ref().map(|h| format!(" (SHA-256 {h})")).unwrap_or_default();
format!("Denoise model `{}` version {}{hash} is unavailable. Reinstall that model or choose another for this photo.", pin.id, pin.version)
})
}
fn denoise_spec(&self, p: &Photo) -> Option<(DenoiseSpec, String)> {
let (dir, active) = (self.denoise_products_dir()?, self.denoise.active.as_ref()?);
let (dir, active) = (self.denoise_products_dir()?, self.denoise_resolve(&p.develop).ok()?);
let key = product_key(&active.fingerprint, p);
Some((DenoiseSpec { product: product_path(&dir, &key), key: key.clone(), make: None }, key))
}
@@ -80,17 +162,20 @@ impl Session {
self.denoise.reindexed = Some((self.catalog.revision, web_time::Instant::now()));
let running = self.denoise.running.as_ref().map(|r| r.photo);
let mut now: HashMap<PhotoId, DenoiseSpec> = HashMap::new();
if let (Some(dir), Some(active)) = (self.denoise_products_dir(), self.denoise.active.as_ref()) {
self.denoise.products.clear();
if let Some(dir) = self.denoise_products_dir() {
let names: HashSet<String> =
products_in(&dir).into_iter().filter_map(|(p, _, _)| p.file_stem().and_then(|s| s.to_str()).map(str::to_string)).collect();
if !names.is_empty() {
for p in self.catalog.photos().filter(|p| eligible(p) && running != Some(p.id)) {
let Ok(active) = self.denoise_resolve(&p.develop) else { continue };
let key = product_key(&active.fingerprint, p);
if names.contains(&key) {
now.insert(p.id, DenoiseSpec { product: product_path(&dir, &key), key, make: None });
}
}
}
self.denoise.products = names;
}
let mut changed = false;
for id in self.media.denoise.ids() {
@@ -118,11 +203,11 @@ impl Session {
/// file is on disk while the job still counts as running. Finding it here would make the photo Ready while the session
/// is busy with it (#719); [`Self::denoise_poll`] makes it Ready in the pump that takes the job's result instead.
fn denoise_check_photo(&mut self, id: PhotoId) {
if self.denoise.running.as_ref().is_some_and(|r| r.photo == id) {
return;
}
let Some(p) = self.catalog.photo(id).cloned() else { return };
let Some((spec, _)) = self.denoise_spec(&p) else { return };
if self.denoise.running.as_ref().is_some_and(|r| r.photo == id && r.key == spec.key) {
return;
}
match self.media.denoise.spec(id) {
Some(have) if have.key != spec.key => {
self.media.denoise.remove(id);
@@ -131,6 +216,7 @@ impl Session {
}
None if spec.product.is_file() && product::is_current(&spec.product, &spec.key) => {
// made by an export, or by another session
self.denoise.products.insert(spec.key.clone());
self.media.denoise.set(id, spec);
self.media.forget(id);
self.denoise.generation += 1;
@@ -149,22 +235,25 @@ impl Session {
// the model in use has not been looked at yet (just started)
return PhotoState::Idle;
}
if let Err(why) = self.denoise_resolve(&p.develop) {
return PhotoState::Failed { why, unsupported: false };
}
if self.denoise_products_dir().is_none() {
return PhotoState::Failed {
why: "AI Denoise keeps its pictures in the library folder, and this session has none.".into(),
unsupported: true,
};
}
if self.media.denoise.spec(id).is_some() {
let key = self.denoise_spec(p).map(|s| s.1);
if self.media.denoise.spec(id).is_some_and(|s| Some(&s.key) == key.as_ref()) {
return PhotoState::Ready;
}
if let Some(r) = self.denoise.running.as_ref().filter(|r| r.photo == id) {
if let Some(r) = self.denoise.running.as_ref().filter(|r| r.photo == id && Some(&r.key) == key.as_ref()) {
return PhotoState::Running { done: r.progress.done.load(Ordering::Relaxed), total: r.progress.total.load(Ordering::Relaxed) };
}
if let Some(ahead) = self.denoise.queue.iter().position(|q| *q == id) {
return PhotoState::Queued { ahead: ahead + usize::from(self.denoise.running.is_some()) };
}
let key = self.denoise_spec(p).map(|s| s.1);
match self.denoise.failed.get(&id) {
Some(f) if Some(&f.key) == key.as_ref() => PhotoState::Failed { why: f.why.clone(), unsupported: f.unsupported },
_ => PhotoState::Idle,
@@ -181,13 +270,15 @@ impl Session {
let mut added = 0;
for id in ids {
let Some(p) = self.catalog.photo(*id).cloned() else { continue };
if !eligible(&p) || self.media.denoise.spec(*id).is_some() || self.denoise.queue.contains(id) {
continue;
}
if self.denoise.running.as_ref().is_some_and(|r| r.photo == *id) || self.denoise.queue.len() >= MAX_QUEUE {
if !eligible(&p) || self.denoise.queue.contains(id) || self.denoise.queue.len() >= MAX_QUEUE {
continue;
}
let Some((_, key)) = self.denoise_spec(&p) else { continue };
if self.denoise.running.as_ref().is_some_and(|r| r.photo == *id && r.key == key)
|| self.media.denoise.spec(*id).is_some_and(|spec| spec.key == key)
{
continue;
}
if retry {
self.denoise.failed.remove(id);
} else if self.denoise.failed.get(id).is_some_and(|f| f.key == key) {
@@ -232,19 +323,21 @@ impl Session {
.collect()
}
fn denoise_job_spec(&self, p: &Photo, parallel: usize) -> Option<JobSpec> {
fn denoise_job_spec(&self, p: &Photo, settings: &DevelopSettings, parallel: usize) -> Option<JobSpec> {
let Source::File { path } = &p.source else { return None };
let (spec, _) = self.denoise_spec(p)?;
let active = self.denoise.active.as_ref()?;
let active = self.denoise_resolve(settings).ok()?;
let key = product_key(&active.fingerprint, p);
let product = product_path(&self.denoise_products_dir()?, &key);
Some(JobSpec {
path: path.clone(),
read: self.media.file_bytes.clone(),
product: spec.product,
key: spec.key,
product,
key,
manifest: active.manifest.clone(),
onnx: active.onnx.clone(),
model: active.model.clone(),
loader: self.denoise.loader.clone(),
warm_model: self.denoise.warm_model.clone(),
parallel,
run_on: self.denoise.settings.run_on(),
})
@@ -254,10 +347,10 @@ impl Session {
fn denoise_start_next(&mut self, parallel: usize) {
while let Some(id) = self.denoise.queue.pop_front() {
let Some(p) = self.catalog.photo(id).cloned() else { continue };
if !eligible(&p) || self.media.denoise.spec(id).is_some() {
if !eligible(&p) {
continue;
}
let Some(spec) = self.denoise_job_spec(&p, parallel) else { continue };
let Some(spec) = self.denoise_job_spec(&p, &p.develop, parallel) else { continue };
// another session or an export may have made it since it was queued
if product::is_current(&spec.product, &spec.key) {
self.denoise_check_photo(id);
@@ -267,6 +360,8 @@ impl Session {
let outcome: Arc<Mutex<Option<Outcome>>> = Arc::new(Mutex::new(None));
let (key, product) = (spec.key.clone(), spec.product.clone());
let (worker_progress, worker_outcome) = (progress.clone(), outcome.clone());
#[cfg(test)]
let outcome_ready = self.denoise.next_outcome_ready.take();
let started = std::thread::Builder::new().name("denoise".into()).stack_size(STACK).spawn(move || {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| make_product(&spec, Some(&worker_progress))));
let o = match result {
@@ -277,6 +372,10 @@ impl Session {
Err(_) => Outcome::Failed("the denoiser stopped unexpectedly".into(), false),
};
*worker_outcome.lock().unwrap_or_else(PoisonError::into_inner) = Some(o);
#[cfg(test)]
if let Some(ready) = outcome_ready {
let _ = ready.send(());
}
});
match started {
Ok(_) => {
@@ -296,6 +395,10 @@ impl Session {
let Some(r) = &self.denoise.running else { return };
let Some(outcome) = r.outcome.lock().unwrap_or_else(PoisonError::into_inner).take() else { return };
let Some(r) = self.denoise.running.take() else { return };
if self.catalog.photo(r.photo).and_then(|p| self.denoise_spec(p)).is_none_or(|(_, key)| key != r.key) {
self.denoise.generation += 1;
return;
}
match outcome {
Outcome::Done => {
self.denoise.made += 1;
@@ -350,12 +453,16 @@ impl Session {
}
if std::fs::remove_file(&path).is_ok() {
total = total.saturating_sub(size);
if let Some(key) = path.file_stem().and_then(|s| s.to_str()) {
self.denoise.products.remove(key);
}
gone.insert(path);
}
}
if gone.is_empty() {
return;
}
self.denoise.eviction_epoch += 1;
for id in self.media.denoise.ids() {
if self.media.denoise.spec(id).is_some_and(|s| gone.contains(&s.product)) {
self.media.denoise.remove(id);
@@ -378,7 +485,10 @@ impl Session {
}
}
self.denoise.failed.clear();
self.denoise.touch();
if files > 0 {
self.denoise.eviction_epoch += 1;
}
self.denoise_reindex();
(files, bytes)
}
@@ -473,6 +583,16 @@ impl Session {
}
}
pub(crate) fn denoise_note_product(&mut self, key: &str) {
// A render can arrive after its product was evicted or the library's cache was cleared.
if !self.denoise.products.contains(key)
&& let Some(dir) = self.denoise_products_dir()
&& product::is_current(&product_path(&dir, key), key)
{
self.denoise.products.insert(key.to_owned());
}
}
pub(crate) fn denoise_made(&self) -> u64 {
self.denoise.made
}
@@ -491,20 +611,31 @@ impl Session {
return Ok(None);
}
let Some(p) = self.catalog.photo(id).cloned() else { return Ok(None) };
self.denoise_refresh_active(false);
self.denoise_check_photo(id);
self.denoise_for_settings(&p, settings, true)
}
/// Resolve the settings supplied by a snapshot or an export, independently of the catalog's live edit.
pub(crate) fn denoise_for_settings(
&self,
p: &Photo,
settings: &DevelopSettings,
make_missing: bool,
) -> Result<Option<(DenoiseSpec, PairLoader)>, String> {
let Some(loader) = self.media.denoise.loader.clone() else { return Ok(None) };
if !eligible(&p) {
if settings.denoise_amount() <= 0.0 || !eligible(p) {
return Ok(None);
}
self.denoise_refresh_active(false);
let name = &p.file_name;
if self.denoise.active.is_none() {
return Err(format!("{name}: Denoise is on for this photo but no denoise model is chosen; choose one in Settings, or set Denoise to 0"));
let active = self.denoise_resolve(settings).map_err(|why| format!("{name}: {why}"))?;
let dir = self.denoise_products_dir().ok_or_else(|| format!("{name}: Denoise needs a library on disk to keep its pictures in"))?;
if !make_missing {
let key = product_key(&active.fingerprint, p);
return Ok(self.denoise.products.contains(&key).then(|| (DenoiseSpec { product: product_path(&dir, &key), key, make: None }, loader)));
}
if self.denoise_products_dir().is_none() {
return Err(format!("{name}: Denoise needs a library on disk to keep its pictures in"));
}
self.denoise_check_photo(id);
let Some(job) = self.denoise_job_spec(&p, Pace::Full.parallel(std::thread::available_parallelism().map_or(1, |n| n.get()), None)) else {
let Some(job) = self.denoise_job_spec(p, settings, Pace::Full.parallel(std::thread::available_parallelism().map_or(1, |n| n.get()), None))
else {
return Ok(None);
};
let label = name.clone();
+70 -9
View File
@@ -2,7 +2,7 @@
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};
use super::{DenoiseModelPin, DenoiserManifest, Deserialize, Duration, Path, PathBuf, Serialize, Value};
/// Extension of a product file.
pub const EXT: &str = "lcdn";
@@ -24,8 +24,11 @@ pub(super) const SETTINGS_TTL: Duration = Duration::from_secs(2);
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub(crate) struct Settings {
/// The installed model in use; `None`: denoise is off.
/// Default for new assignments. A missing model or no choice uses the built-in denoiser.
pub model: Option<String>,
/// The old global choice, preserved for libraries opened after another library changes the default.
#[serde(skip_serializing_if = "Option::is_none")]
pub legacy_model: Option<DenoiseModelPin>,
/// Photos with a Denoise amount above 0 that are being looked at (active, selected) get their picture made without
/// being asked (`None`: yes).
pub auto: Option<bool>,
@@ -64,8 +67,60 @@ pub(crate) fn read_capped(path: &Path, max: usize) -> Option<Vec<u8>> {
(buf.len() <= max).then_some(buf)
}
fn read_settings_checked(dir: &Path) -> Result<Settings, String> {
use std::io::{ErrorKind, Read};
const MAX_BYTES: usize = 4096;
let path = dir.join("settings.json");
let file = match std::fs::File::open(&path) {
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Settings::default()),
other => other.map_err(|e| format!("could not open {}: {e}", path.display()))?,
};
let mut bytes = Vec::new();
file.take(MAX_BYTES as u64 + 1).read_to_end(&mut bytes).map_err(|e| format!("could not read {}: {e}", path.display()))?;
if bytes.len() > MAX_BYTES {
return Err(format!("{} exceeds the denoise settings limit of {MAX_BYTES} bytes", path.display()));
}
serde_json::from_slice(&bytes).map_err(|e| format!("could not read {}: {e}", path.display()))
}
pub(crate) fn read_settings(dir: &Path) -> Settings {
read_capped(&dir.join("settings.json"), 4096).and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
read_settings_checked(dir).unwrap_or_default()
}
pub(super) fn builtin_pin() -> DenoiseModelPin {
let m = lightcraft_denoise::builtin::manifest();
DenoiseModelPin { id: m.id, version: m.version, sha256: None }
}
pub(super) fn configured_pin(dir: &Path, settings: &Settings) -> Result<DenoiseModelPin, String> {
if let Some(id) = &settings.model
&& let Some(model) = installed_models(dir).into_iter().find(|model| model.manifest.id == *id)
{
return model.pin(None);
}
// The pre-pin engine also used its built-in denoiser if the chosen model had gone away.
Ok(builtin_pin())
}
/// Capture the pre-feature model before migrating a library or changing the installed models/default.
pub(crate) fn ensure_legacy_settings(dir: &Path) -> Result<Settings, String> {
let mut settings = read_settings_checked(dir).map_err(|e| {
format!(
"{e}. Check read permissions or restore this file from a backup, then retry. \
To reset denoise settings, rename only settings.json and retry. \
Older edits without a saved model will then use the built-in denoiser."
)
})?;
if settings.legacy_model.is_none() {
settings.legacy_model = Some(configured_pin(dir, &settings)?);
write_settings(dir, &settings)?;
}
Ok(settings)
}
pub(crate) fn capture_legacy_pin(dir: Option<&Path>) -> Result<DenoiseModelPin, String> {
let Some(dir) = dir else { return Ok(builtin_pin()) };
ensure_legacy_settings(dir)?.legacy_model.ok_or_else(|| "could not preserve the legacy denoise model".into())
}
/// Write a file next to its final name and rename it into place.
@@ -92,12 +147,18 @@ pub(crate) struct Installed {
}
impl Installed {
/// Names the model file the cache is made with: a hash of the file as installed, so another file with the same id
/// never finds this one's products.
pub fn fingerprint(&self) -> String {
let sha = self.accepted.get("sha256").and_then(Value::as_str).or(self.manifest.sha256.as_deref()).unwrap_or("");
let len = std::fs::metadata(&self.onnx).map(|m| m.len()).unwrap_or(0);
format!("{}@{}:{len}", self.manifest.id, sha)
fn recorded_hash(&self) -> Option<&str> {
self.manifest.sha256.as_deref().or_else(|| self.accepted.get("sha256").and_then(Value::as_str))
}
/// The installer records the hash even for custom manifests that do not name one.
/// A manually provisioned folder may only have the weights and their manifest.
pub(super) fn pin(&self, previous_hash: Option<&str>) -> Result<DenoiseModelPin, String> {
let sha = match self.recorded_hash().or(previous_hash) {
Some(hash) => hash.to_owned(),
None => lightcraft_denoise::hash::sha256_file(&self.onnx).map_err(|e| format!("{}: {e}", self.onnx.display()))?,
};
Ok(DenoiseModelPin { id: self.manifest.id.clone(), version: self.manifest.version.clone(), sha256: Some(sha) })
}
}
+24
View File
@@ -103,7 +103,15 @@ pub(crate) struct State {
pub(crate) install: Option<crate::cmd::denoise::InstallJob>,
/// How a model is loaded (tests put another in).
pub loader: Loader,
pub(super) warm_model: Arc<super::model::WarmModel>,
/// Effective default, sharing its loaded model with the registry.
pub(crate) active: Option<Active>,
pub(super) registry: std::collections::BTreeMap<String, Active>,
/// Product names in this library, including those used only by a saved version.
pub(super) products: super::HashSet<String>,
/// Advances when cached products are deleted, so a late plain fallback cannot stand in
/// for a denoised texture after its product is made again.
pub(super) eviction_epoch: u64,
pub(super) active_seen: Option<web_time::Instant>,
/// `settings.json` as last read (with the model choice).
pub(crate) settings: Settings,
@@ -113,6 +121,9 @@ pub(crate) struct State {
pub(super) reindexed: Option<(u64, web_time::Instant)>,
pub(super) queue: VecDeque<PhotoId>,
pub(super) running: Option<Running>,
/// Signals once the next worker's outcome is available to the frame pump.
#[cfg(test)]
pub(crate) next_outcome_ready: Option<std::sync::mpsc::Sender<()>>,
pub(super) failed: HashMap<PhotoId, Failure>,
/// Counts every change of what is ready, so the interface knows to draw again.
pub generation: u64,
@@ -129,13 +140,19 @@ impl Default for State {
downloads: Downloads::default(),
install: None,
loader: default_loader(),
warm_model: Default::default(),
active: None,
registry: Default::default(),
products: Default::default(),
eviction_epoch: 0,
active_seen: None,
settings: Settings::default(),
dirty: true,
reindexed: None,
queue: VecDeque::new(),
running: None,
#[cfg(test)]
next_outcome_ready: None,
failed: HashMap::new(),
generation: 0,
made: 0,
@@ -154,12 +171,19 @@ impl Drop for State {
}
impl State {
/// Only transient keys of renders asking for a product follow its cache's lifetime.
/// The disk cache is content-addressed and keeps its keys across evictions.
pub(crate) fn texture_epoch(&self, denoise_salt: u64) -> u64 {
if denoise_salt == 0 { 0 } else { self.eviction_epoch.rotate_left(17) }
}
/// The library was replaced: nothing carries over (photo ids are per library).
pub fn library_changed(&mut self) {
if let Some(r) = self.running.take() {
r.progress.cancel_now();
}
self.queue.clear();
self.products.clear();
self.failed.clear();
self.dirty = true;
self.generation += 1;
+18
View File
@@ -238,12 +238,29 @@ pub(crate) fn start_from_file(s: &Session, p: &mut Photo, file: FileFacts, now:
Some(sc)
}
impl Session {
/// An older sidecar or preset can enable denoise without naming a model. Remember
/// the effective default for those settings, including the intermediate import looks.
pub(crate) fn pin_import_denoisers(&self, photo: &mut Photo, default: &mut Option<lightcraft_develop::DenoiseModelPin>) {
if !crate::denoise::eligible(photo) {
return;
}
for settings in photo.settings_holders_mut() {
if settings.enhance.needs_denoise_model() {
let pin = default.get_or_insert_with(|| self.denoise_assignment_pin());
std::sync::Arc::make_mut(settings).enhance.denoise_model = Some(pin.clone());
}
}
}
}
/// The catalog half of an import: add the photos [`ImportJob::prepare`] readied (one undoable op;
/// a Move's sources are removed once it is saved). On a failed commit a Move's placed files are
/// taken back.
pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepared: Prepared) -> crate::Result<ImportReport> {
let now = now.to_string();
let mut report = ImportReport { scanned: prepared.scanned, skipped: prepared.skipped, ..Default::default() };
let mut default_denoiser = None;
let mut ops = Vec::new();
// Move: placed at the destination, sources untouched until the records are committed
// (with its backup: where it was made, or why it wasn't, so the source stays)
@@ -379,6 +396,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare
p.history.push(lightcraft_catalog::HistoryStep { label: "Import adjustments".into(), settings: d });
}
report.imported.push(id.0);
s.pin_import_denoisers(&mut p, &mut default_denoiser);
p.local = opts.local;
if opts.local {
// the state as browsed: a later change keeps the record from being forgotten
+1 -1
View File
@@ -10,7 +10,7 @@ pub fn import_defaults(p: &Photo) -> lightcraft_develop::DevelopSettings {
/// Does the photo still look as the camera rendered it (its embedded camera preview is then a
/// fair stand-in)? Not when a default preset changed it on import.
pub fn has_import_look(p: &Photo) -> bool {
*p.develop == p.camera_defaults()
p.develop.matches_default_look(p.camera_defaults())
}
/// User defaults applied on import (Settings → Import; saved in the library's `prefs.json`).
+27 -2
View File
@@ -791,6 +791,7 @@ impl Session {
// Retain only cache IDs while the catalog consumes the operation. Cloning an import
// batch here also cloned every photo, although commit already keeps the journal copy.
let mut invalidated = Vec::new();
let mut denoise_changed = Vec::new();
// photos whose file was replaced: the faces made from the old pixels go too (issue #1524)
let mut replaced = Vec::new();
let mut pending = vec![&op];
@@ -800,6 +801,11 @@ impl Session {
invalidated.push(*id);
replaced.push(*id);
}
Op::SetDevelop { id, settings, .. }
if self.catalog.photo(*id).is_some_and(|p| p.develop.enhance.denoise_model != settings.enhance.denoise_model) =>
{
denoise_changed.push(*id);
}
Op::SetFile { id, .. } | Op::Relink { id, .. } | Op::RemovePhoto { id } => invalidated.push(*id),
Op::AddPhoto { photo } => invalidated.push(photo.id),
Op::Batch { ops } => pending.extend(ops),
@@ -811,6 +817,9 @@ impl Session {
if applied.is_err() && !matches!(applied, Err(CatalogError::PartlyApplied { .. })) {
return applied.map_err(Into::into);
}
for id in denoise_changed {
self.denoise_photo_changed(id);
}
for id in invalidated {
self.media.forget(id);
}
@@ -915,7 +924,7 @@ impl Session {
/// Apply without recording undo (interactive previews).
fn apply_silent(&mut self, op: Op) -> Result<()> {
self.catalog.apply(op)?;
self.apply_catalog(op)?;
Ok(())
}
@@ -1122,7 +1131,8 @@ impl Session {
/// Change a photo's develop settings. During an interaction the change is previewed without an
/// undo step; otherwise it is committed with a history entry.
pub fn set_develop(&mut self, id: PhotoId, settings: DevelopSettings, label: &str) -> Result<()> {
pub fn set_develop(&mut self, id: PhotoId, mut settings: DevelopSettings, label: &str) -> Result<()> {
self.pin_denoiser(id, &mut settings);
let now = (self.clock)();
// Auto Sync carries the edit as asked; each photo then fits its own crop (review of #1990)
let requested = settings;
@@ -1201,6 +1211,13 @@ impl Session {
for k in ["spots", "red_eye", "version", "process"] {
o.remove(k);
}
// Automatic assignment follows each photo's own choice. Explicit Detail copy/paste can carry it.
if let Some(enhance) = o.get_mut("enhance").and_then(Value::as_object_mut) {
enhance.remove("denoise_model");
if enhance.is_empty() {
o.remove("enhance");
}
}
// AI Defringe is per photo, like AI Denoise's switch: its switch and Amount stay with the photo they were set on
if let Some(optics) = o.get_mut("optics").and_then(Value::as_object_mut) {
optics.remove("ai_defringe");
@@ -1242,10 +1259,18 @@ impl Session {
&& !label.starts_with("Restore ")
}
/// Amount edits, presets and the first toggle all remember which denoiser made the picture.
fn pin_denoiser(&self, id: PhotoId, settings: &mut DevelopSettings) {
if settings.enhance.needs_denoise_model() && self.catalog.photo(id).is_some_and(|photo| denoise::eligible(photo)) {
settings.enhance.denoise_model = Some(self.denoise_assignment_pin());
}
}
/// The op that sets a photo's develop settings and appends a History entry (for batches).
pub fn develop_op(&self, id: PhotoId, settings: DevelopSettings, label: &str) -> Option<Op> {
self.catalog.photo(id)?;
let mut settings = settings;
self.pin_denoiser(id, &mut settings);
// old masks (on the corrected frame) go onto the photo, from the frame they were drawn on:
// masks this edit kept, under the photo's settings before it (a geometry edit then moves
// the photo, not them); masks it brought in (paste, sync, a preset, a history step, a
+3 -1
View File
@@ -620,6 +620,9 @@ impl Session {
log::error!("library: {e} (every change is in its snapshot)");
}
}
let (mut journal, mut catalog, report) = Journal::open_with_legacy_denoise(catalog, || {
crate::denoise::capture_legacy_pin(self.denoise.models_dir.as_deref()).map_err(lightcraft_catalog::CatalogError::Io)
})?;
self.media.smart_dir = on_disk.then(|| crate::smart::dir(&dir));
// Photo ids belong to one library; denoise work must not carry into the next.
self.denoise.library_changed();
@@ -627,7 +630,6 @@ impl Session {
// what was learned about the old library's faces is saved, and none of it carries over (photo ids are per library)
#[cfg(not(target_arch = "wasm32"))]
self.faces.library_changed();
let (mut journal, mut catalog, report) = Journal::open(catalog)?;
// A loaded catalog counts revisions from 0, like every other one. Caches (sidebar counts,
// keyword tree, the grid's list…) are keyed on the revision, so give each library loaded
// in this process its own range: otherwise an empty library opened after one that was
+2
View File
@@ -1278,6 +1278,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co
let copy_masters: HashSet<_> = data.photos.iter().map(|p| number(&p.image, "masterImage")).filter(|id| *id != 0).collect();
let refused: HashSet<_> = data.photos.iter().filter(|p| matches!(p.original, Original::Refused(_))).map(|p| p.source_id).collect();
let mut planned: HashMap<PhotoId, Photo> = HashMap::new();
let mut default_denoiser = None;
for src in photos {
let master = number(&src.image, "masterImage");
if master == 0 && missing_sources.contains(&key(&src.path)) {
@@ -1439,6 +1440,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co
if keep_develop {
(p.develop, p.edited) = previous_develop;
}
s.pin_import_denoisers(&mut p, &mut default_denoiser);
// Missing files bypass normal-file preparation, including its Local promotion.
// Import still joins the library, and a virtual copy must inherit that membership.
let was_local = p.local;
+9 -1
View File
@@ -485,10 +485,18 @@ impl RenderJob {
}
_ => None,
};
if let Some((cache, key)) = &self.cache {
// A product can disappear after this job gets its key. Show the plain fallback, but
// keep it out of the slots reserved for the denoised render.
let missing_denoise = self.settings.denoise_amount() > 0.0
&& source.denoised.is_none()
&& matches!(&self.source, SourceRef::File { denoise: Some(_), .. });
if let Some((cache, key)) = &self.cache
&& !missing_denoise
{
cache.put_at(self.cache_generation, *key, Arc::new(rendered.image.clone()));
}
if let Some((cache, key)) = &self.view_cache
&& !missing_denoise
&& self.request.quality == Quality::Full
&& (display.is_none() || srgb.is_some())
{
+47 -19
View File
@@ -26,6 +26,24 @@ impl crate::Session {
Some(job)
}
/// A historical edit may need a different denoised source than the one indexed for the live edit.
fn snapshot_source(&mut self, p: &Photo, settings: &Arc<DevelopSettings>, level: SourceLevel) -> (SourceRef, u64) {
let mut q = p.clone();
q.develop = settings.clone();
if settings.denoise_amount() > 0.0 && settings.enhance.denoise_model != p.develop.enhance.denoise_model {
self.denoise_refresh_active(false);
let wanted = self.denoise_for_settings(&q, settings, self.denoise_auto()).ok().flatten();
let salt = wanted.as_ref().map_or(0, |(s, _)| Hasher128::new().str(&s.key).finish().0 as u64 | 1);
let mut source = self.media.source_ref_uncached(&q, level);
if let SourceRef::File { denoise, .. } = &mut source {
*denoise = wanted;
}
(source, salt)
} else {
(self.media.source_ref(&q, level), self.media.denoise_salt(p.id, settings))
}
}
fn build_job(
&mut self,
id: PhotoId,
@@ -43,12 +61,10 @@ impl crate::Session {
source_edge_needed(&p, &settings, apply_crop, max_w.max(max_h))
});
// the Before side develops with the Before settings' camera profile (or none), not the edit's
let source = if before {
let mut q = (*p).clone();
q.develop = settings.clone();
self.media.source_ref(&q, level)
let (source, denoise_salt) = if before {
self.snapshot_source(&p, &settings, level)
} else {
self.media.source_ref(&p, level)
(self.media.source_ref(&p, level), self.media.denoise_salt(id, &settings))
};
let request = RenderRequest { apply_crop, ..RenderRequest::fit(max_w, max_h) };
// the photo id is part of the key: two photos with the same settings and size must not
@@ -63,7 +79,7 @@ impl crate::Session {
if before { settings.hash64() ^ crate::files::hot_pixel_key(&settings) } else { self.media.settings_hashes.get(id, &settings) };
// AI Defringe's correction, when it is on and made: its key is part of the render's
let ai_defringe = if before { None } else { self.aidefringe_for_render(&p, &settings, false).ok().flatten() };
let salt = self.media.denoise_salt(id, &settings) ^ ai_defringe.as_ref().map_or(0, |a| a.key().rotate_left(11));
let salt = denoise_salt ^ ai_defringe.as_ref().map_or(0, |a| a.key().rotate_left(11));
let profile_salt = self.media.camera_profile_salt(&settings.profile.id);
let lens = super::quick::lens_key(&p);
let key = settings_hash
@@ -74,6 +90,7 @@ impl crate::Session {
^ id.0.wrapping_mul(0x9e37_79b9_7f4a_7c15)
^ content.rotate_left(17)
^ salt
^ self.denoise.texture_epoch(denoise_salt)
^ profile_salt.rotate_left(29)
^ lens.rotate_left(37)
^ decoder.rotate_left(43);
@@ -129,12 +146,10 @@ impl crate::Session {
let mut job = self.render_job(id, max_w, max_h, false, apply_crop)?;
// the source as these settings develop it: another camera profile (or none) decodes anew
let mut p = (**self.catalog.photo(id)?).clone();
let own_profile = self.media.camera_profile_of(&p).map(|c| c.0);
p.develop = Arc::new(settings.clone());
if self.media.camera_profile_of(&p).map(|c| c.0) != own_profile {
job.source = self.media.source_ref(&p, job.level);
}
job.settings = Arc::new(settings.clone());
let (source, denoise_salt) = self.snapshot_source(&p, &job.settings, job.level);
job.source = source;
p.develop = job.settings.clone();
job.ai_defringe = self.aidefringe_for_render(&p, settings, false).ok().flatten();
// (the imported camera profile's file is in the key, as in `render_job`'s: a profile file replaced under the
// same id is a new picture)
@@ -143,6 +158,8 @@ impl crate::Session {
let lens = self.catalog.photo(id).map_or(0, |p| super::quick::lens_key(p));
let decoder = super::quick::decoder_key(&p);
job.key = settings.hash64()
^ denoise_salt
^ self.denoise.texture_epoch(denoise_salt)
^ crate::files::hot_pixel_key(settings)
^ ((max_w as u64) << 40)
^ ((max_h as u64) << 20)
@@ -201,13 +218,18 @@ impl crate::Session {
let mut p = (**self.catalog.photo(id)?).clone();
let edge = edge.clamp(16, SourceLevel::Thumb.max_edge());
let level = SourceLevel::Thumb;
// decoded as these settings develop it (their camera profile, or none)
p.develop = Arc::new(settings.clone());
let source = self.media.source_ref(&p, level);
let settings = Arc::new(settings.clone());
let (source, denoise_salt) = self.snapshot_source(&p, &settings, level);
p.develop = settings.clone();
// with AI Defringe's correction when these settings use it and it is made
let ai_defringe = self.aidefringe_for_render(&p, settings, false).ok().flatten();
let ck =
Self::with_ai_defringe(Self::variant_key(&p, settings, edge, self.media.camera_profile_salt(&settings.profile.id)), ai_defringe.as_ref());
let ai_defringe = self.aidefringe_for_render(&p, &settings, false).ok().flatten();
let mut ck = Self::with_ai_defringe(
Self::variant_key(&p, &settings, edge, self.media.camera_profile_salt(&settings.profile.id)),
ai_defringe.as_ref(),
);
if denoise_salt != 0 {
ck = Hasher128::new().u64(ck.0 as u64).u64((ck.0 >> 64) as u64).str("denoise").u64(denoise_salt).finish();
}
Some(RenderJob {
request_id: 0,
cache_generation: self.media.rendered.generation(),
@@ -217,9 +239,9 @@ impl crate::Session {
source,
origin: p.source.clone(),
info: source_info(&p),
settings: Arc::new(settings.clone()),
settings,
request: RenderRequest { apply_crop: true, ..RenderRequest::fit(edge, edge) },
key: (ck.0 as u64) ^ ((ck.0 >> 64) as u64),
key: (ck.0 as u64) ^ ((ck.0 >> 64) as u64) ^ self.denoise.texture_epoch(denoise_salt),
cache: Some((self.media.rendered.clone(), ck)),
stages: None,
view_cache: None,
@@ -541,6 +563,12 @@ impl crate::Session {
if let Some(src) = &r.loaded
&& r.source_key.is_none_or(|key| self.catalog.photo(r.photo).is_some_and(|p| super::quick::source_identity(p) == key))
{
if let Some(twin) = &src.denoised {
self.denoise_note_product(&twin.product_key);
}
if src.denoised.as_ref().map(|t| &t.product_key) != self.media.denoise.spec(r.photo).map(|s| &s.key) {
return;
}
if let Some(info) = &src.info {
self.learn_as_shot_wb(r.photo, info);
}
+6 -3
View File
@@ -1,6 +1,7 @@
use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo};
/// Bump when the pipeline's output changes, to invalidate cached thumbnails.
/// 90: use accepted lens geometry when fitting a CR3 camera look against the embedded JPEG (#3138).
/// 89: a fitted matrix whose rows aren't led by their own channel is refused (#3973).
/// 88: use eligible external lens profiles for camera-preview colour alignment (#2675).
/// 87: a lens database's vignetting correction reaches the look fit only in the share the camera JPEG shows
@@ -8,7 +9,7 @@ use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb
/// 86: pushed shadows keep the camera profile's colour and tone (#2092).
/// 85: raw decoding keeps negative channels (#2278).
/// 84: full-size raw demosaic runs on the white-balanced mosaic with a clip mask (#1328).
pub const RENDER_CACHE_VERSION: u64 = 89;
pub const RENDER_CACHE_VERSION: u64 = 90;
/// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache).
pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512];
@@ -136,6 +137,8 @@ pub type PairLoader = Arc<dyn Fn(&str, usize, &DenoiseSpec, RawDecode<'_>) -> Re
/// A photo's denoised picture next to its plain one, and the last mix of the two that was asked for.
pub struct Twin {
/// Which product a render actually decoded, so a delayed render cannot replace a different model's source.
pub(super) product_key: String,
pub image: Arc<Rgb32f>,
/// The Amount (in thousandths) and the picture mixed for it, so dragging other sliders keeps one source picture.
mix: std::sync::Mutex<Option<(u32, Arc<Rgb32f>)>>,
@@ -143,7 +146,7 @@ pub struct Twin {
impl Twin {
pub fn new(image: Arc<Rgb32f>) -> Twin {
Twin { image, mix: std::sync::Mutex::new(None) }
Twin { image, product_key: String::new(), mix: std::sync::Mutex::new(None) }
}
/// Bytes reserved for the twin and its lazy mix, before either cache cost can grow.
@@ -343,7 +346,7 @@ impl SourceRef {
image: Arc::new(image),
info: Some(info),
camera_tone: None,
denoised: twin.map(|t| Arc::new(Twin::new(Arc::new(t)))),
denoised: twin.map(|t| Arc::new(Twin { product_key: spec.key.clone(), ..Twin::new(Arc::new(t)) })),
camera_profile: made_with.clone(),
outliers: *outliers,
from_proxy: false,
@@ -42,6 +42,34 @@ fn camera_previews_are_kept_for_a_revisit_and_full_size_ones_are_not() {
assert!(s.embedded_full_job(PhotoId(1), 8192).is_none(), "an edit is shown rendered");
}
#[test]
fn an_inactive_denoiser_choice_keeps_the_embedded_raw_preview() {
use lightcraft_develop::DenoiseModelPin;
let mut s = crate::Session::new();
s.media.preview_loader = Some(Arc::new(|_, _| Some(Rgba8::new(16, 16))));
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;
let mut picked = raw.camera_defaults();
picked.enhance.denoise_model = Some(DenoiseModelPin { id: "example".into(), version: "1".into(), sha256: None });
raw.develop = Arc::new(picked.clone());
let id = raw.id;
s.catalog.apply(Op::AddPhoto { photo: Box::new(raw.clone()) }).unwrap();
assert!(s.embedded_thumb_is_final(&raw));
assert_eq!(s.embedded_full_job(id, 8192).unwrap().run().quick, Some(QuickSource::Embedded));
let mut preset = picked.clone();
preset.light.exposure = 0.5;
raw.import_look = Some(Arc::new(preset.clone()));
raw.develop = Arc::new(preset);
assert!(!raw.is_edited());
assert!(!s.embedded_thumb_is_final(&raw), "the camera preview does not include the preset");
picked.enhance.denoise = 60.0;
s.catalog.apply(Op::SetDevelop { id, settings: Arc::new(picked), label: "AI Denoise".into(), edited: None }).unwrap();
assert!(s.embedded_full_job(id, 8192).is_none(), "active denoising requires a render");
}
/// 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]
+61 -6
View File
@@ -154,7 +154,7 @@ impl MergeJob {
let p = sub(0.25, 0.9);
let fit = fit_in_memory(pano, pixels(&frames), crate::memory::total_ram());
let r = lightcraft_merge::stitch(frames, &fit, &p).map_err(err)?;
let info = pano_info(&r, &self.sources, pano, &fit);
let info = pano_info(&r, &self.sources, 1, pano, &fit);
(
r.image,
r.color,
@@ -199,7 +199,7 @@ impl MergeJob {
let p = sub(0.6, 0.9);
let fit = fit_in_memory(pano, pixels(&merged), crate::memory::total_ram());
let r = lightcraft_merge::stitch(merged, &fit, &p).map_err(err)?;
let mut info = pano_info(&r, &self.sources, pano, &fit);
let mut info = pano_info(&r, &self.sources, b, pano, &fit);
info["bracket"] = json!(b);
(
r.image,
@@ -239,7 +239,7 @@ impl MergeJob {
/// `asked` is what the command asked for, `fit` what ran (held to memory): when the panorama came
/// out smaller than the photos' own resolution, `limit` says why (`memory`, `size`: Lightroom's
/// 512 MP / 65,000 px, or `asked`).
fn pano_info(r: &lightcraft_merge::PanoResult, sources: &[(PhotoId, String)], asked: &PanoOptions, fit: &PanoOptions) -> Value {
fn pano_info(r: &lightcraft_merge::PanoResult, sources: &[(PhotoId, String)], bracket: usize, asked: &PanoOptions, fit: &PanoOptions) -> Value {
let megapixels = (r.image.width * r.image.height) as f64 / 1e6;
let native = r.native_megapixels;
let why = if fit.max_megapixels < asked.max_megapixels && fit.max_megapixels < native {
@@ -250,9 +250,9 @@ fn pano_info(r: &lightcraft_merge::PanoResult, sources: &[(PhotoId, String)], as
"size"
};
let limit = (megapixels < native * 0.98).then_some(why);
json!({
let mut info = pano_source_info(&r.used, &r.pairs, sources, bracket);
let geometry = json!({
"projection": r.projection,
"used": r.used.iter().filter_map(|&i| sources.get(i).map(|s| s.0.0)).collect::<Vec<_>>(),
"fov": [r.fov.0, r.fov.1],
"rmsPx": r.rms,
"gains": r.gains,
@@ -260,7 +260,43 @@ fn pano_info(r: &lightcraft_merge::PanoResult, sources: &[(PhotoId, String)], as
"megapixels": megapixels,
"nativeMegapixels": native,
"limit": limit,
})
});
if let (Some(info), Some(geometry)) = (info.as_object_mut(), geometry.as_object()) {
info.extend(geometry.clone());
}
info
}
/// Stitch indices refer to frames (HDR brackets), while callers need individual source IDs.
/// Keep source order and report only the observed outcome, not an inferred scene cause.
fn pano_source_info(
used_frames: &[usize],
pairs: &[lightcraft_merge::pano::camera::PairDiagnostic],
sources: &[(PhotoId, String)],
bracket: usize,
) -> Value {
let bracket = bracket.max(1);
let mut used = Vec::new();
let mut omitted = Vec::new();
for (i, (id, path)) in sources.iter().enumerate() {
if used_frames.contains(&(i / bracket)) {
used.push(id.0);
} else {
omitted.push(json!({"id": id.0, "path": path, "reason": "notRegistered"}));
}
}
let ids = |i: usize| sources.chunks(bracket).nth(i).unwrap_or_default().iter().map(|s| s.0.0).collect::<Vec<_>>();
let pairs: Vec<Value> = pairs
.iter()
.map(|p| {
json!({
"a": ids(p.i), "b": ids(p.j), "matches": p.matches, "inliers": p.inliers, "status": p.status,
})
})
.collect();
let frames = sources.len().div_ceil(bracket);
let total_pairs = frames.saturating_mul(frames.saturating_sub(1)) / 2;
json!({"used": used, "omitted": omitted, "pairs": pairs, "pairsTruncated": pairs.len() < total_pairs})
}
/// Peak memory of a panorama per pixel of its output (bytes), measured as the peak resident size
@@ -517,3 +553,22 @@ impl Session {
self.finish_merge(&job, out)
}
}
#[cfg(test)]
mod inclusion_tests {
use super::*;
#[test]
fn source_ids_keep_their_order_across_nonconsecutive_brackets() {
let sources = [71, 9, 401, 3, 6, 12].map(|id| (PhotoId(id), format!("{id}.png")));
let info = pano_source_info(&[2, 0], &[], &sources, 2);
assert_eq!(info["used"], json!([71, 9, 6, 12]));
assert_eq!(
info["omitted"],
json!([
{"id": 401, "path": "401.png", "reason": "notRegistered"},
{"id": 3, "path": "3.png", "reason": "notRegistered"},
])
);
}
}
+16 -3
View File
@@ -344,9 +344,9 @@ fn a_proxy_from_the_previous_look_version_is_stale() {
let path = dir.join("p.lcsp");
std::fs::write(&path, &bytes).unwrap();
assert!(!is_stale(&path), "this build's own proxy is up to date");
// Both the pre-Nikon look and the previous integration's look remain readable offline
// and are rebuilt when the original is available. Keep the lens provenance current.
for version in [13, 14] {
// Look 27 already recorded the lens identity, but did not align CR3 fits with lens geometry.
// Like the earlier proxies, it remains readable offline and is rebuilt from the online original.
for version in [13, 14, 27] {
let mut older = head.clone();
older[LOOK_FIELD] = serde_json::json!(version);
let mut old = MAGIC.to_vec();
@@ -463,6 +463,19 @@ fn explicit_lens_identity_is_kept_by_encoder_and_scan_marker() {
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn folder_marker_replaces_lens_fingerprints_in_either_direction_and_preserves_newer_provenance() {
let dir = temp("lens-marker-upgrade");
let fit = u64::from(crate::camera_preview::LOOK_VERSION);
let enc = ENCODE_VERSION;
for (look, encoding, old_key, expected_key) in [(fit, enc, 2, 5), (fit, enc, 99, 5), (fit, enc + 1, 99, 99)] {
std::fs::write(dir.join(LOOK_MARKER), format!("{look} {encoding} {old_key} 71")).unwrap();
mark_look_checked_with_lens_key(&dir, 5).unwrap();
assert_eq!(marker(&dir, LOOK_MARKER), [look, encoding, expected_key, 71]);
}
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_scan_cannot_clear_pending_behind_a_newer_marker_for_another_database() {
let dir = temp("lens-marker-pending");
+318 -9
View File
@@ -223,6 +223,129 @@ fn set_amount(s: &mut Session, amount: f64) {
s.execute("develop.set", &json!({"control": "enhance.denoise", "value": amount})).unwrap();
}
#[test]
fn capturing_the_legacy_model_leaves_unreadable_settings_intact() {
let dir = temp_dir("denoise-invalid-settings");
let path = dir.join("settings.json");
let check_error = || {
let error = crate::denoise::capture_legacy_pin(Some(&dir)).unwrap_err();
assert!(error.contains(path.to_string_lossy().as_ref()), "{error}");
assert!(error.contains("backup") && error.contains("rename") && error.contains("built-in denoiser"), "{error}");
};
for bytes in [b"{broken".to_vec(), b"{\"model\":7}".to_vec(), vec![b' '; 4097]] {
std::fs::write(&path, &bytes).unwrap();
check_error();
assert_eq!(std::fs::read(&path).unwrap(), bytes);
}
// A directory in place of the file causes an I/O error even when the test runs as root.
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
check_error();
assert!(path.is_dir());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn before_and_hover_render_their_own_denoiser_without_replacing_the_live_source() {
let mut x = setup("denoise-before", true);
let id = photo(&x.s);
x.s.execute("denoise.settings", &json!({"runOn": "cpu"})).unwrap();
set_amount(&mut x.s, 100.0);
pump_until_ready(&mut x.s, 1);
let original = x.s.render_now(id, 160, 160).unwrap().image;
let saved = x.s.develop_of(id).unwrap();
x.s.execute("beforeAfter.setBefore", &json!({"source": "current"})).unwrap();
x.s.execute("denoise.photo.model", &json!({"model": "builtin"})).unwrap();
x.s.execute("denoise.clear", &json!({})).unwrap();
pump_until_ready(&mut x.s, 1);
let current = x.s.render_now(id, 160, 160).unwrap().image;
assert_ne!(original.data, current.data);
x.s.execute("denoise.settings", &json!({"auto": false})).unwrap();
let missing_variant = x.s.variant_job(id, &saved, 160).unwrap();
let missing_key = missing_variant.key;
assert_ne!(missing_variant.run().rendered.unwrap().image.data, original.data);
x.s.execute("denoise.settings", &json!({"auto": true})).unwrap();
let runs = x.runs.load(Ordering::Relaxed);
let before = x.s.render_job(id, 160, 160, true, true).unwrap().run();
assert!(x.runs.load(Ordering::Relaxed) > runs, "the historical model remade its missing product");
assert_eq!(before.rendered.as_ref().unwrap().image.data, original.data);
x.s.accept(&before);
let hover = x.s.preview_job(id, 160, 160, true, &saved).unwrap().run();
assert_eq!(hover.rendered.as_ref().unwrap().image.data, original.data);
x.s.accept(&hover);
x.s.execute("denoise.settings", &json!({"auto": false})).unwrap();
let variant = x.s.variant_job(id, &saved, 160).unwrap();
assert_ne!(variant.key, missing_key, "a plain placeholder cannot stand in for the finished version thumbnail");
assert_eq!(variant.run().rendered.unwrap().image.data, original.data);
assert_eq!(x.s.render_now(id, 160, 160).unwrap().image.data, current.data);
drop(x.s);
let _ = std::fs::remove_dir_all(x.dir);
}
#[test]
fn a_late_render_cannot_restore_an_evicted_historical_product() {
let mut x = setup("denoise-late-product", true);
let id = photo(&x.s);
set_amount(&mut x.s, 100.0);
pump_until_ready(&mut x.s, 1);
let saved = x.s.develop_of(id).unwrap();
let product = x.s.media.denoise.spec(id).unwrap().product.clone();
let late = x.s.render_job(id, 160, 160, false, true).unwrap().run();
assert!(late.loaded.as_ref().unwrap().denoised.is_some());
x.s.execute("denoise.settings", &json!({"auto": false})).unwrap();
x.s.execute("denoise.photo.model", &json!({"model": "builtin"})).unwrap();
let ready = x.s.variant_job(id, &saved, 160).unwrap().key;
x.s.denoise_evict_to(0, None);
let missing = x.s.variant_job(id, &saved, 160).unwrap().key;
assert_ne!(missing, ready);
x.s.accept(&late);
assert_eq!(x.s.variant_job(id, &saved, 160).unwrap().key, missing, "accept cannot resurrect an evicted product");
std::fs::write(&product, b"incomplete product").unwrap();
x.s.accept(&late);
assert_eq!(x.s.variant_job(id, &saved, 160).unwrap().key, missing, "the file must match its product key");
assert!(x.s.media.denoise.spec(id).is_none());
drop(x.s);
let _ = std::fs::remove_dir_all(x.dir);
}
#[test]
fn a_pending_variant_cannot_cache_plain_pixels_as_denoised() {
let mut x = setup("denoise-pending-variant", true);
let id = photo(&x.s);
let plain = x.s.develop_of(id).unwrap();
set_amount(&mut x.s, 100.0);
pump_until_ready(&mut x.s, 1);
let saved = x.s.develop_of(id).unwrap();
x.s.execute("denoise.settings", &json!({"auto": false})).unwrap();
x.s.execute("denoise.photo.model", &json!({"model": "builtin"})).unwrap();
let plain_key = x.s.variant_job(id, &plain, 160).unwrap().key;
let expected = x.s.preview_job(id, 160, 160, true, &saved).unwrap().run().rendered.unwrap().image;
let pending = x.s.variant_job(id, &saved, 160).unwrap();
let old_texture = pending.key;
let (cache, key) = pending.cache.clone().unwrap();
let generation = pending.cache_generation;
assert_eq!(x.s.execute("denoise.clear", &json!({})).unwrap()["deleted"], 1);
let fallback = pending.run();
assert!(fallback.loaded.unwrap().denoised.is_none());
assert_ne!(fallback.rendered.unwrap().image.data, expected.data);
assert!(cache.get_at(generation, key).is_none(), "the plain fallback must not occupy the denoised thumbnail's key");
x.s.execute("denoise.settings", &json!({"auto": true})).unwrap();
let made = x.s.preview_job(id, 160, 160, true, &saved).unwrap().run();
x.s.accept(&made);
x.s.execute("denoise.settings", &json!({"auto": false})).unwrap();
let restored = x.s.variant_job(id, &saved, 160).unwrap();
assert_ne!(restored.key, old_texture, "the frontend must request a new texture after the product is remade");
assert_eq!(restored.cache.as_ref().unwrap().1, key, "the disk thumbnail still identifies the same pixels");
assert_eq!(restored.run().rendered.unwrap().image.data, expected.data);
assert_eq!(x.s.variant_job(id, &plain, 160).unwrap().key, plain_key);
drop(x.s);
let _ = std::fs::remove_dir_all(x.dir);
}
#[test]
fn a_model_is_installed_chosen_and_removed_with_the_terms_accepted() {
let mut x = setup("model", false);
@@ -384,17 +507,16 @@ fn what_was_made_is_found_again_by_a_new_session_and_a_new_model_starts_over() {
assert_eq!(s2.denoise_photo_state(id), PhotoState::Ready);
assert_eq!(x.runs.load(Ordering::Relaxed), made, "nothing was made again");
// another model's pictures are different pictures
// Installing another default preserves the assigned photo's picture.
let onnx = model_files(&x.dir, "other");
s2.execute("denoise.models.install", &json!({"path": onnx.to_string_lossy(), "acknowledged": true})).unwrap();
s2.denoise_pump(crate::denoise::Pace::Pause);
assert!(
matches!(s2.denoise_photo_state(id), PhotoState::Queued { .. }),
"the first model's picture is not this model's: it is to be made: {:?}",
s2.denoise_photo_state(id)
);
// and choosing the first again finds its picture where it was
s2.execute("denoise.models.select", &json!({"id": "stand-in"})).unwrap();
assert_eq!(s2.denoise_photo_state(id), PhotoState::Ready);
s2.execute("denoise.photo.model", &json!({"id":id.0,"model":"other"})).unwrap();
s2.denoise_pump(crate::denoise::Pace::Pause);
assert!(matches!(s2.denoise_photo_state(id), PhotoState::Queued { .. }));
// Choosing the original per-photo model finds its product again.
s2.execute("denoise.photo.model", &json!({"id":id.0,"model": "stand-in"})).unwrap();
s2.denoise_pump(crate::denoise::Pace::Pause);
assert_eq!(s2.denoise_photo_state(id), PhotoState::Ready);
let _ = std::fs::remove_dir_all(&x.dir);
@@ -428,8 +550,11 @@ 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 built-in denoiser makes the picture instead (the stand-in is not asked)
// A default change preserves the existing edit and its product.
x.s.execute("denoise.models.select", &json!({"id": null})).unwrap();
assert_eq!(decode(&export_photo(&mut x.s, id, &o, 1).unwrap().bytes), again);
// An explicit photo edit switches to BM3D.
x.s.execute("denoise.photo.model", &json!({"id":id.0,"model":"builtin"})).unwrap();
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);
@@ -532,6 +657,7 @@ fn files_that_cannot_be_denoised_fail_with_a_reason_and_never_a_panic() {
manifest: manifest("stand-in"),
onnx: dir.join("model.onnx"),
model: Default::default(),
warm_model: Default::default(),
loader: dim_loader(&Arc::new(AtomicUsize::new(0))),
parallel: 2,
run_on: RunOn::Auto,
@@ -602,6 +728,7 @@ fn two_threads_making_the_same_picture_make_it_once() {
manifest: manifest("stand-in"),
onnx: dir.join("model.onnx"),
model: Default::default(),
warm_model: Default::default(),
loader: dim_loader(&runs),
parallel: 2,
run_on: RunOn::Auto,
@@ -927,3 +1054,185 @@ fn without_a_models_folder_the_cache_still_obeys_the_default_limit() {
}
let _ = std::fs::remove_dir_all(&x.dir);
}
#[test]
fn a_preset_enabling_denoise_at_zero_remembers_the_current_model() {
let mut x = setup("preset-denoise-at-zero", true);
let id = photo(&x.s);
let preset = x.dir.join("enabled.lcpreset");
let settings = json!({"id":"enabled", "name":"Enabled", "group":"Test", "settings":{"enhance":{"denoise_on":true,"denoise":0}}});
std::fs::write(&preset, settings.to_string()).unwrap();
x.s.execute("preset.import", &json!({"paths":[preset]})).unwrap();
x.s.execute("preset.apply", &json!({"id":"enabled","ids":[id.0]})).unwrap();
let edit = x.s.develop_of(id).unwrap();
assert!(edit.enhance.denoise_enabled() && edit.denoise_amount() == 0.0);
x.s.execute("denoise.models.select", &json!({"id":null})).unwrap();
x.s.execute("develop.set", &json!({"control":"enhance.denoise","value":20,"ids":[id.0]})).unwrap();
let info = x.s.execute("denoise.photo.info", &json!({"id":id.0})).unwrap();
assert_eq!(info["model"]["id"], "stand-in", "raising the amount uses the model chosen when the preset enabled denoise");
drop(x.s);
let _ = std::fs::remove_dir_all(x.dir);
}
#[test]
fn changing_the_default_keeps_an_edited_photos_export() {
let mut x = setup("pinned-export", true);
let id = photo(&x.s);
set_amount(&mut x.s, 100.0);
let opts = ExportOptions::default();
let original = export_photo(&mut x.s, id, &opts, 1).unwrap().bytes;
x.s.execute("denoise.models.select", &json!({"id": null})).unwrap();
let after = export_photo(&mut x.s, id, &opts, 1).unwrap().bytes;
assert!(original == after, "changing the default changed a previous edit's export");
drop(x.s);
let _ = std::fs::remove_dir_all(x.dir);
}
#[test]
fn photo_model_choice_is_undoable_and_default_changes_do_not_reinterpret_it() {
let mut x = setup("per-photo-choice", true);
let id = photo(&x.s);
let info = x.s.execute("denoise.photo.info", &json!({"id":id.0})).unwrap();
assert_eq!(info["assigned"], false);
assert!(info["models"].as_array().unwrap().iter().any(|m| m["id"] == "builtin" && m["available"] == true));
let chosen = x.s.execute("denoise.photo.model", &json!({"id":id.0,"model":"stand-in"})).unwrap();
assert_eq!(chosen["assigned"], true);
assert_eq!(chosen["model"]["sha256"].as_str().unwrap().len(), 64);
assert!(!x.s.develop_of(id).unwrap().enhance.denoise_enabled(), "choosing does not enable");
x.s.execute("denoise.models.select", &json!({"id":null})).unwrap();
assert_eq!(x.s.execute("denoise.photo.info", &json!({"id":id.0})).unwrap()["model"]["id"], "stand-in");
x.s.undo_step().unwrap();
assert!(x.s.develop_of(id).unwrap().enhance.denoise_model.is_none());
x.s.redo_step().unwrap();
x.s.execute("denoise.toggle", &json!({"id":id.0,"enabled":true})).unwrap();
assert_eq!(x.s.develop_of(id).unwrap().enhance.denoise_model.as_ref().unwrap().id, "stand-in");
let snapshot = (*x.s.develop_of(id).unwrap()).clone();
x.s.execute("denoise.photo.model", &json!({"id":id.0,"model":"builtin"})).unwrap();
let (old, _) = x.s.denoise_for_export(id, &snapshot).unwrap().unwrap();
let current = (*x.s.develop_of(id).unwrap()).clone();
let (new, _) = x.s.denoise_for_export(id, &current).unwrap().unwrap();
assert_ne!(old.key, new.key, "export resolves supplied snapshot, not current photo");
x.s.execute("denoise.models.remove", &json!({"id":"stand-in"})).unwrap();
assert!(matches!(x.s.denoise_for_export(id,&snapshot),Err(e) if e.contains("unavailable")));
assert!(x.s.denoise_for_export(id, &current).is_ok(), "an available per-photo model survives unavailable global default");
x.s.close_library().unwrap();
let _ = std::fs::remove_dir_all(x.dir);
}
#[test]
fn mixed_queue_uses_each_photos_pin_and_changed_versions_never_fall_back() {
let mut x = setup("per-photo-mixed", true);
let first = photo(&x.s);
x.s.execute("denoise.toggle", &json!({"id":first.0,"enabled":true})).unwrap();
let next = x.dir.join("originals/second.dng");
std::fs::write(&next, ramp_dng(194, 160, "RGGB")).unwrap();
x.s.execute("library.import", &json!({"paths":[next]})).unwrap();
let second = x.s.catalog.photos().find(|p| p.id != first).unwrap().id;
let model = model_files(&x.dir, "other-model");
x.s.execute("denoise.models.install", &json!({"path":model,"acknowledged":true})).unwrap();
x.s.execute("denoise.toggle", &json!({"id":second.0,"enabled":true})).unwrap();
assert_eq!(x.s.develop_of(first).unwrap().enhance.denoise_model.as_ref().unwrap().id, "stand-in");
assert_eq!(x.s.develop_of(second).unwrap().enhance.denoise_model.as_ref().unwrap().id, "other-model");
x.s.execute("denoise.queue", &json!({"ids":[first.0,second.0]})).unwrap();
pump_until_ready(&mut x.s, 2);
assert_ne!(x.s.media.denoise.spec(first).unwrap().key, x.s.media.denoise.spec(second).unwrap().key);
let snapshot = (*x.s.develop_of(first).unwrap()).clone();
let path = x.dir.join("denoise-models/stand-in/denoise-model.json");
let mut manifest: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
manifest["version"] = json!("2");
std::fs::write(path, serde_json::to_vec(&manifest).unwrap()).unwrap();
x.s.denoise_refresh_active(true);
assert_eq!(x.s.execute("denoise.photo.info", &json!({"id":first.0})).unwrap()["model"]["available"], false);
assert!(matches!(x.s.denoise_photo_state(first), PhotoState::Failed { unsupported: false, .. }));
assert!(x.s.denoise_for_export(first, &snapshot).is_err());
assert_eq!(x.s.denoise_photo_state(second), PhotoState::Ready);
x.s.close_library().unwrap();
let _ = std::fs::remove_dir_all(x.dir);
}
fn watch_next_denoise_outcome(s: &mut Session) -> std::sync::mpsc::Receiver<()> {
let (tx, rx) = std::sync::mpsc::channel();
s.denoise.next_outcome_ready = Some(tx);
rx
}
#[test]
fn changing_photo_pin_rejects_a_previous_model_job_in_flight() {
use std::sync::{Mutex, mpsc};
let timeout = denoise_ready_timeout();
let mut x = setup("per-photo-inflight", true);
let id = photo(&x.s);
set_amount(&mut x.s, 80.0);
x.s.execute("denoise.settings", &json!({"auto":false})).unwrap();
*x.s.denoise.active.as_ref().unwrap().model.lock().unwrap() = None;
let (entered_tx, entered_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel::<()>();
let release_rx = Mutex::new(release_rx);
let runs = x.runs.clone();
x.s.denoise.loader = Arc::new(move |_, _| {
entered_tx.send(()).map_err(|e| e.to_string())?;
release_rx.lock().unwrap().recv_timeout(timeout).map_err(|e| e.to_string())?;
Ok(Arc::new(Dim { runs: runs.clone() }) as Arc<dyn Model>)
});
let finished = watch_next_denoise_outcome(&mut x.s);
x.s.execute("denoise.queue", &json!({"ids":[id.0]})).unwrap();
x.s.execute("denoise.pump", &json!({"pace":"full"})).unwrap();
entered_rx.recv_timeout(timeout).unwrap();
let (product, oldkey) = x.s.denoise_running_product().unwrap();
x.s.execute("denoise.photo.model", &json!({"id":id.0,"model":"builtin"})).unwrap();
release_tx.send(()).unwrap();
finished.recv_timeout(timeout).expect("cancelled worker did not report its outcome");
x.s.denoise_pump(crate::denoise::Pace::Pause);
assert!(x.s.denoise_running_json().is_null());
assert!(!lightcraft_denoise::product::is_current(&product, &oldkey), "cancellation during loading must prevent the old product write");
assert_ne!(x.s.media.denoise.spec(id).map(|s| s.key.as_str()), Some(oldkey.as_str()));
assert_eq!(x.s.denoise_made(), 0, "old model result cannot count as the new photo edit");
assert_eq!(x.s.denoise_photo_state(id), PhotoState::Idle);
x.s.undo_step().unwrap();
assert_eq!(x.s.develop_of(id).unwrap().enhance.denoise_model.as_ref().unwrap().id, "stand-in");
x.s.close_library().unwrap();
let _ = std::fs::remove_dir_all(x.dir);
}
#[test]
fn changing_photo_pin_discards_a_finished_result_before_the_next_pump() {
let mut x = setup("per-photo-unpolled", true);
let id = photo(&x.s);
set_amount(&mut x.s, 80.0);
x.s.execute("denoise.settings", &json!({"auto":false})).unwrap();
let finished = watch_next_denoise_outcome(&mut x.s);
x.s.execute("denoise.queue", &json!({"ids":[id.0]})).unwrap();
x.s.denoise_pump(crate::denoise::Pace::Full);
let (product, oldkey) = x.s.denoise_running_product().unwrap();
finished.recv_timeout(denoise_ready_timeout()).expect("worker did not report its outcome");
assert!(lightcraft_denoise::product::is_current(&product, &oldkey), "the old model successfully wrote a real product");
x.s.execute("denoise.photo.model", &json!({"id":id.0,"model":"builtin"})).unwrap();
x.s.denoise_pump(crate::denoise::Pace::Pause);
assert!(x.s.denoise_running_json().is_null());
assert_eq!(x.s.denoise_made(), 0, "a completed result for the old model must be discarded");
assert_eq!(x.s.denoise_photo_state(id), PhotoState::Idle);
assert_ne!(x.s.media.denoise.spec(id).map(|s| s.key.as_str()), Some(oldkey.as_str()));
x.s.close_library().unwrap();
let _ = std::fs::remove_dir_all(x.dir);
}
#[test]
fn changed_installed_bytes_fail_sha_verification_instead_of_using_another_model() {
let mut x = setup("per-photo-sha", true);
let id = photo(&x.s);
set_amount(&mut x.s, 70.0);
let snapshot = (*x.s.develop_of(id).unwrap()).clone();
let path = x.dir.join("denoise-models/stand-in/model.onnx");
let mut bytes = std::fs::read(&path).unwrap();
bytes[0] ^= 1;
std::fs::write(path, bytes).unwrap();
x.s.denoise_refresh_active(true);
let (spec, _) = x.s.denoise_for_export(id, &snapshot).unwrap().unwrap();
assert!(matches!((spec.make.unwrap())(),Err(e) if e.contains("SHA-256")));
x.s.execute("denoise.models.select", &json!({"id":null})).unwrap();
let (spec, _) = x.s.denoise_for_export(id, &snapshot).unwrap().unwrap();
assert!(matches!((spec.make.unwrap())(),Err(e) if e.contains("SHA-256")), "an available BM3D default cannot replace this model");
x.s.close_library().unwrap();
let _ = std::fs::remove_dir_all(x.dir);
}
+36
View File
@@ -4504,6 +4504,42 @@ fn session_with_raw_probe() -> Session {
s
}
#[test]
fn importing_denoise_settings_pins_the_default_and_keeps_an_explicit_sidecar_model() {
use lightcraft_catalog::{Photo, Source};
use lightcraft_develop::DenoiseModelPin;
let src = temp_dir("denoise-import-pins");
let mut s = session_with_raw_probe();
let default = s.denoise_assignment_pin();
let custom = DenoiseModelPin { id: "sidecar-model".into(), version: "2".into(), sha256: Some("a".repeat(64)) };
let preset = s.execute("preset.saveRecipe", &json!({"name":"RAW denoise","recipe":[{"id":"enhance.denoise","value":25}]})).unwrap();
s.import_defaults.raw_preset = Some(preset["id"].as_str().unwrap().to_string());
for (seed, saved) in [(1, None), (2, Some(custom.clone()))] {
let name = format!("raw-{seed}.png");
let path = src.join(&name);
write_png(&path, seed);
let mut source = Photo::new(PhotoId(1), Source::File { path: name.clone() }, &name, "DNG", 48, 32, CLOCK);
let edit = std::sync::Arc::make_mut(&mut source.develop);
edit.enhance.denoise = 65.0;
edit.enhance.denoise_on = Some(false);
edit.enhance.denoise_model = saved.clone();
std::fs::write(path.with_extension("xmp"), crate::sidecar::sidecar_packet(&source, &s.catalog)).unwrap();
let result = s.execute("library.import", &json!({"paths":[path],"local":true,"recipe":[{"id":"light.exposure","value":0.5}]})).unwrap();
assert_eq!(result["sidecars"], 1);
let p = s.catalog.photo(PhotoId(result["imported"][0].as_u64().unwrap())).unwrap();
let expected = saved.as_ref().unwrap_or(&default);
assert_eq!(p.develop.enhance.denoise_model.as_ref(), Some(expected));
assert_eq!(p.develop.enhance.denoise_on, Some(false));
assert_eq!(p.history.last().unwrap().settings.enhance.denoise_model.as_ref(), Some(expected));
assert_eq!(p.import_look.as_ref().unwrap().enhance.denoise_model.as_ref(), Some(&default));
assert!(p.untouched_local(), "the browse baseline must include the imported selections");
}
let _ = std::fs::remove_dir_all(src);
}
fn import_one(s: &mut Session, path: &Path, recipe: Value) -> lightcraft_catalog::PhotoId {
let r = s.execute("library.import", &json!({"paths": [path.to_string_lossy()], "recipe": recipe})).unwrap();
lightcraft_catalog::PhotoId(r["imported"][0].as_u64().unwrap_or_else(|| panic!("{path:?} not imported: {r}")))
+50
View File
@@ -237,6 +237,56 @@ fn panorama_command_with_auto_crop() {
let _ = std::fs::remove_dir_all(&dir);
}
/// Issue #1765: keep source IDs and order, including every exposure of an HDR position.
/// The first position has no features. The other two overlap. Check preview and final output.
#[test]
fn panorama_reports_omitted_source_photos() {
for bracket in [1, 2] {
let dir = temp_dir(&format!("1765-{bracket}"));
let mut images = vec![lightcraft_raster::Rgb32f::from_fn(400, 300, |_, _| [0.2; 3])];
images.extend(lightcraft_merge::synth::pano_views(400, 300, 350.0, &[-15.0, 15.0]).unwrap());
let mut paths = Vec::new();
for (i, image) in images.iter().enumerate() {
for exposure in 0..bracket {
let img = image.map(|p| p.map(|v| v * (1.0 + exposure as f32 * 0.1))).to_srgb8();
let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &Default::default()).unwrap();
let path = dir.join(format!("position-{i}-exposure-{exposure}.png"));
std::fs::write(&path, png).unwrap();
paths.push(path.to_string_lossy().to_string());
}
}
if let Ok(dump) = std::env::var("LC_MERGE_DUMP") {
let dest = std::path::Path::new(&dump).join(format!("1765-{bracket}"));
std::fs::create_dir_all(&dest).unwrap();
for path in &paths {
std::fs::copy(path, dest.join(std::path::Path::new(path).file_name().unwrap())).unwrap();
}
}
let mut s = Session::new().with_fs();
let ids = import(&mut s, paths.clone());
let cmd = if bracket == 1 { "merge.panorama" } else { "merge.hdrPanorama" };
for preview in [true, false] {
let r = s.execute(cmd, &json!({"ids": ids, "bracket": bracket, "align": false, "autoSettings": false, "preview": preview})).unwrap();
assert_eq!(r["used"], json!(ids[bracket..]), "{r}");
let omitted = r["omitted"].as_array().expect("explicit omitted photos");
assert_eq!(omitted.len(), bracket);
for (i, entry) in omitted.iter().enumerate() {
assert_eq!(entry["id"], ids[i]);
assert_eq!(entry["path"], paths[i]);
assert_eq!(entry["reason"], "notRegistered");
}
let pairs = r["pairs"].as_array().expect("pair verification diagnostics");
assert_eq!(r["pairsTruncated"], false);
assert_eq!(pairs.len(), 3);
assert_eq!(pairs[0]["a"], json!(ids[..bracket]));
assert_eq!(pairs[0]["b"], json!(ids[bracket..2 * bracket]));
assert_eq!(pairs[0]["status"], "insufficientMatches");
assert_eq!(pairs[2]["status"], "accepted");
}
let _ = std::fs::remove_dir_all(&dir);
}
}
/// HDR for Each Bracket Set: two stacks of brackets → two merged DNGs, each next to its first photo; photos that form
/// no set are refused.
#[test]
+5
View File
@@ -32,12 +32,17 @@ default = []
denoise = ["dep:lightcraft-denoise", "lightcraft-denoise/runtime"]
# SAM 3's vision backbone on the GPU (`sam3`); the engine's `sam` feature turns it on
sam = ["dep:lightcraft-segment"]
# `shared_device`, for other crates' tests: only ever turned on from [dev-dependencies] (it overrides
# the switch that keeps the GPU off, so the app must not have it)
test-support = []
[dev-dependencies]
# tests record why they skip (`cargo xtask ci` lists the skips)
lightcraft-testkit = { workspace = true }
lightcraft-scenes = { workspace = true }
lightcraft-raw = { workspace = true }
# this crate's integration tests use `shared_device` too (tests/shared_device.rs)
lightcraft-gpu = { workspace = true, features = ["test-support"] }
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
# the SAM 3 backbone test and benchmark compare against the candle backbone
+83 -41
View File
@@ -590,42 +590,43 @@ impl Gpu {
self.over_limit(size);
return Buf { buf: Some(Tracked::new(self.placeholder())), len };
}
let recycled = {
let mut f = self.free.lock().unwrap_or_else(|e| e.into_inner());
// the smallest pooled buffer that holds `size` with at most 25 % to spare: photos of
// slightly different sizes reuse each other's buffers instead of piling up new ones
let b = f
.iter()
.enumerate()
.filter(|(_, b)| b.0.size() >= size && b.0.size() <= size + size / 4)
.min_by_key(|(_, b)| b.0.size())
.map(|(i, _)| i)
.map(|i| f.swap_remove(i));
if let Some(b) = &b {
POOLED.fetch_sub(b.0.size(), Ordering::Relaxed);
}
b
};
let buf = recycled.unwrap_or_else(|| {
Tracked::new(self.device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
}))
});
let buf =
self.take_pooled(size, wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST).unwrap_or_else(|| {
Tracked::new(self.device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
}))
});
Buf { buf: Some(buf), len }
}
/// Take the smallest pooled buffer of exactly `usage` that holds `size` with at most 25 % to
/// spare: photos of slightly different sizes reuse each other's buffers instead of piling up
/// new ones. Storage and readback (staging) buffers share the pool but never each other's use.
fn take_pooled(&self, size: u64, usage: wgpu::BufferUsages) -> Option<Tracked> {
let mut f = self.free.lock().unwrap_or_else(|e| e.into_inner());
let i = f
.iter()
.enumerate()
.filter(|(_, b)| b.0.usage() == usage && b.0.size() >= size && b.0.size() <= size + size / 4)
.min_by_key(|(_, b)| b.0.size())
.map(|(i, _)| i)?;
let b = f.swap_remove(i);
POOLED.fetch_sub(b.0.size(), Ordering::Relaxed);
Some(b)
}
/// Submit command buffers, then make the buffers this thread dropped before reusable.
/// Nothing is submitted once this render has failed: the render is discarded and recomputed
/// on the CPU, and the failure contract says no further GPU work runs after a fatal failure.
pub fn submit(&self, cmds: impl IntoIterator<Item = wgpu::CommandBuffer>) {
if !failed() {
self.queue.submit(cmds);
}
/// Nothing is submitted once this render has failed (the render is discarded and recomputed
/// on the CPU, and the failure contract says no further GPU work runs after a fatal failure):
/// the result is then `None`, otherwise the submission's index.
pub fn submit(&self, cmds: impl IntoIterator<Item = wgpu::CommandBuffer>) -> Option<wgpu::SubmissionIndex> {
let index = if failed() { None } else { Some(self.queue.submit(cmds)) };
let retired = take_retired();
self.pool(retired);
index
}
/// Put reusable buffers into the free pool (trimmed to its limit).
@@ -868,15 +869,22 @@ impl Gpu {
return zeros();
}
let size = (len * 4) as u64;
let staging = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("readback"),
size: size.max(4),
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
// a pooled staging buffer when one fits: a fresh ~96 MB one per export costs more than the copy
let usage = wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST;
let staging = self.take_pooled(size.max(4), usage).unwrap_or_else(|| {
Tracked::new(self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("readback"),
size: size.max(4),
usage,
mapped_at_creation: false,
}))
});
enc.copy_buffer_to_buffer(src.raw(), 0, &staging, 0, size);
self.submit([enc.finish()]);
let slice = staging.slice(..size);
enc.copy_buffer_to_buffer(src.raw(), 0, &staging.0, 0, size);
let Some(index) = self.submit([enc.finish()]) else {
// the render failed between the check above and the submit: nothing was submitted
return zeros();
};
let slice = staging.0.slice(..size);
let (tx, rx) = std::sync::mpsc::channel();
slice.map_async(wgpu::MapMode::Read, move |r| {
let _ = tx.send(r);
@@ -887,8 +895,9 @@ impl Gpu {
};
// A lost device makes the wait fail ([`Gpu::poll`] turns wgpu's panic into the error) and
// the map callback never run: checking both keeps this from blocking forever (or handing
// back an unwritten buffer as the image).
if let Err(e) = self.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(READBACK_TIMEOUT) }) {
// back an unwritten buffer as the image). The wait is for this submission only: the queue
// is ordered, so it also covers earlier ones, but not later ones from other threads.
if let Err(e) = self.poll(wgpu::PollType::Wait { submission_index: Some(index), timeout: Some(READBACK_TIMEOUT) }) {
return failed(e);
}
// another thread's poll may be the one that runs the callback: allow it a moment
@@ -913,7 +922,10 @@ impl Gpu {
}
});
drop(data);
staging.unmap();
staging.0.unmap();
// only a buffer that mapped and read cleanly goes back: after any failure above its map
// state is unknown, so it is dropped instead
self.pool([staging]);
out
}
}
@@ -1335,6 +1347,36 @@ mod tests {
let back: Vec<[u32; 3]> = g.finish_and_read(g.encoder(), &b, data.len());
assert!(back.len() == 1 << 20 && back.as_flattened() == data.as_slice());
}
/// Readback staging buffers are pooled and reused, and never handed out as storage buffers.
#[test]
fn readback_staging_buffers_are_pooled_apart_from_storage() {
// (serialised with the tests that change the pool limit, which would trim the pool under it)
let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let Some(g) = crate::device() else {
lightcraft_testkit::skip!(Gpu, "no GPU device");
return;
};
let len = 1_234_567usize;
let want = (len * 4) as u64;
let mapped = wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST;
// only the staging buffers this readback could reuse (`take_pooled`'s size band), so another
// test's readback of a different size on the shared device doesn't change the count
let count = || {
let f = g.free.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
f.iter().filter(|b| b.0.usage() == mapped && b.0.size() >= want && b.0.size() <= want + want / 4).count()
};
let data: Vec<u32> = (0..len as u32).map(|i| i.wrapping_mul(2_654_435_761)).collect();
let b = g.upload(&data);
let back: Vec<u32> = g.finish_and_read(g.encoder(), &b, len);
assert!(back == data);
assert!(count() >= 1, "the staging buffer went back to the pool");
let before = count();
let back: Vec<u32> = g.finish_and_read(g.encoder(), &b, len);
assert!(back == data, "a reused staging buffer reads back exactly");
assert!(count() <= before, "the second readback reused a pooled buffer instead of adding one");
assert!(g.buffer(len).raw().usage().contains(wgpu::BufferUsages::STORAGE), "a storage request got a staging buffer");
}
/// An upload after this render has failed keeps the failure contract (`Gpu::submit` skips the
/// submission, so nothing further runs on the GPU): the caller gets the placeholder with the
/// requested length instead of a staging buffer holding a copy of the data for a submission
+110 -1
View File
@@ -291,6 +291,11 @@ fn env_disabled() -> bool {
#[cfg(not(target_arch = "wasm32"))]
static GPU: std::sync::OnceLock<Result<ctx::Gpu, String>> = std::sync::OnceLock::new();
/// A [`warm_up`] thread in flight. [`warm_up`] enters it before the thread exists, so
/// [`wait_warm_up`] sees the warm-up from the moment [`warm_up`] returns.
#[cfg(not(target_arch = "wasm32"))]
static WARM_UP: exit::Gate = exit::Gate::new();
/// Set while [`adopt_window_device`] is about to run or running: [`device`] and [`warm_up`] then
/// don't create a device of their own (review of PR #1065: the settings' warm-up raced the
/// adoption thread and could win, so the window's device went unused).
@@ -320,6 +325,13 @@ pub(crate) fn device() -> Option<&'static ctx::Gpu> {
if WINDOW_PENDING.load(Ordering::Acquire) {
return None;
}
create_device()
}
/// Create the device (once; later calls return the first outcome), or `None` when creating it
/// failed or the process is ending.
#[cfg(not(target_arch = "wasm32"))]
fn create_device() -> Option<&'static ctx::Gpu> {
// creating the device is a long call into the driver: not once the process is ending
let _work = exit::enter()?;
GPU.get_or_init(|| {
@@ -342,6 +354,57 @@ pub(crate) fn existing_device() -> Option<&'static ctx::Gpu> {
GPU.get().and_then(|g| g.as_ref().ok())
}
/// For tests (hidden, like [`inject_fault`]): the render device and its queue, so a test that needs
/// a device draws on this one instead of creating another. Creating another Vulkan instance while
/// this device is in use on another thread crashes Vulkan loaders before 1.4.345
/// (KhronosGroup/Vulkan-Loader#1863: `vkEnumeratePhysicalDevices` unloads drivers, and frees loader
/// state, that a device call on another thread is walking).
///
/// Unlike a render, this creates the device while GPU rendering is turned off by the preference
/// (which other tests switch: `app.gpu`), and waits while the window's device is being adopted. So
/// `None` means no render device can exist in this process any more: the environment switches the
/// GPU off, creating the device failed, or the process is ending. Only then may a test create a
/// device of its own without racing this one.
///
/// What the caller does on the device is its own: [`wait_idle`] doesn't count it, and an error
/// outside the caller's error scopes stops GPU rendering for the whole process.
///
/// When the process is ending ([`shutting_down`]) a test must not create a device of its own either:
/// it would be created during teardown.
///
/// The wait for the window's device has a deadline (60 s): past it this panics rather than return
/// `None`, which would let the test create a device that races the window's.
///
/// Never call this from the app: it overrides the switch that keeps the GPU off, including after a
/// launch that crashed while creating the device (#136). So it exists only in this crate's tests and
/// with the `test-support` feature, which only dev-dependencies turn on.
#[doc(hidden)]
#[cfg(all(not(target_arch = "wasm32"), any(test, feature = "test-support")))]
#[allow(clippy::panic, reason = "a window device that stays pending fails the test that waits for it")]
pub fn shared_device() -> Option<(wgpu::Device, wgpu::Queue)> {
if env_disabled() {
return None;
}
// (the adoption clears it whatever the outcome, and the window's device may become this one;
// it creates a device and builds the kernels, which can take a while on a slow or busy machine)
const WAIT: std::time::Duration = std::time::Duration::from_secs(60);
let deadline = std::time::Instant::now() + WAIT;
while WINDOW_PENDING.load(Ordering::Acquire) && GPU.get().is_none() {
if std::time::Instant::now() >= deadline {
panic!(
"gpu::shared_device: the window's device was still pending after {WAIT:?} \
(set_window_device_pending(true) without an adoption or set_window_device_pending(false))"
);
}
std::thread::sleep(std::time::Duration::from_millis(1));
}
let g = match GPU.get() {
Some(g) => g.as_ref().ok(),
None => create_device(),
};
g.map(|g| (g.device.clone(), g.queue.clone()))
}
/// Create the device and compile the kernels on a background thread now (once the window is up),
/// so the first render doesn't wait ~0.3–0.4 s for it and the UI thread never does. Does nothing
/// while GPU rendering is turned off. Repeated calls start one thread at most.
@@ -349,10 +412,16 @@ pub fn warm_up() {
#[cfg(not(target_arch = "wasm32"))]
if !env_disabled() && ENABLED.load(Ordering::SeqCst) && GPU.get().is_none() && !WINDOW_PENDING.load(Ordering::Acquire) {
static STARTED: AtomicBool = AtomicBool::new(false);
// In flight from here, before `STARTED` is set and before the thread exists: a host that ends
// the process right after any `warm_up` returns (this one, or a concurrent call that finds
// the thread starting) must find it with `wait_warm_up`. A closed gate starts nothing; a call
// that starts nothing drops its token again, and a failed spawn drops it with the closure.
let Some(in_flight) = WARM_UP.enter() else { return };
if STARTED.swap(true, Ordering::SeqCst) {
return;
}
let spawned = std::thread::Builder::new().name("lc-gpu-init".into()).spawn(|| {
let spawned = std::thread::Builder::new().name("lc-gpu-init".into()).spawn(move || {
let _in_flight = in_flight;
loop {
let _ = device();
if GPU.get().is_some() || shutting_down() || env_disabled() {
@@ -387,6 +456,46 @@ pub fn ready() -> bool {
}
}
/// Wait up to `timeout` for a [`warm_up`] thread to finish (the device created, or given up).
/// `true`: none is running. That thread loads the driver, and a process that ends meanwhile crashes
/// inside it (issue #620): a host that ends the process without [`begin_shutdown`] and
/// [`wait_idle`] (a test, a headless run) waits for it first.
pub fn wait_warm_up(timeout: std::time::Duration) -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
WARM_UP.wait_idle(timeout)
}
#[cfg(target_arch = "wasm32")]
{
let _ = timeout;
true
}
}
/// The guard [`hold_warm_up_for_test`] returns: the substitute warm-up, held until it is dropped.
#[cfg(not(target_arch = "wasm32"))]
struct WarmUpHold(Option<exit::Work<'static>>);
/// A substitute device warm-up in flight, held until the returned guard is dropped — the same
/// gate the real [`warm_up`] enters, so a caller can prove a warm-up is pending and that a wait
/// waits for it, without a GPU, a device or a race. Test support for one test,
/// `tests::gpu_warm_up::dropping_the_app_waits_for_a_warm_up_that_is_in_flight` in
/// lightcraft-ui-egui (a `#[cfg(test)]` helper here would not be visible to that crate's test
/// build); not for production code — a real warm-up is started with [`warm_up`]. `None` only
/// when the process is ending, when no warm-up can be in flight anyway.
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub fn hold_warm_up_for_test() -> Option<impl Drop> {
WARM_UP.enter().map(|work| WarmUpHold(Some(work)))
}
#[cfg(not(target_arch = "wasm32"))]
impl Drop for WarmUpHold {
fn drop(&mut self) {
drop(self.0.take());
}
}
/// Whether a usable GPU adapter exists and GPU rendering is enabled (creates the device on first
/// use).
pub fn available() -> bool {
+57 -12
View File
@@ -254,6 +254,30 @@ impl<'a> Cx<'a> {
);
}
/// The rectangle `r` ([x0, y0, x1, y1), in pixels) of `b`, an interleaved RGB image `img_w` pixels
/// wide, read back (one row copy recorded per row, into a buffer of just the rectangle).
pub fn read_rect(&mut self, b: &Buf, img_w: usize, r: [usize; 4]) -> Rgb32f {
let (cw, ch) = (r[2] - r[0], r[3] - r[1]);
let out = self.gpu.buffer(cw * ch * 3);
let enc = self.enc.get_or_insert_with(|| self.gpu.encoder());
for y in 0..ch {
let from = (((r[1] + y) * img_w + r[0]) * 3 * 4) as u64;
enc.copy_buffer_to_buffer(b.raw(), from, out.raw(), (y * cw * 3 * 4) as u64, (cw * 3 * 4) as u64);
}
self.read_rgb(&out, cw, ch)
}
/// `src`, a compact image of the rectangle `r`, written into `dst`, an interleaved RGB image
/// `img_w` pixels wide (one row copy recorded per row).
pub fn write_rect(&mut self, src: &Buf, dst: &Buf, img_w: usize, r: [usize; 4]) {
let (cw, ch) = (r[2] - r[0], r[3] - r[1]);
let enc = self.enc.get_or_insert_with(|| self.gpu.encoder());
for y in 0..ch {
let to = (((r[1] + y) * img_w + r[0]) * 3 * 4) as u64;
enc.copy_buffer_to_buffer(src.raw(), (y * cw * 3 * 4) as u64, dst.raw(), to, (cw * 3 * 4) as u64);
}
}
pub fn read_rgb(&mut self, b: &Buf, w: usize, h: usize) -> Rgb32f {
Rgb32f { width: w, height: h, data: self.read(b, w * h * 3) }
}
@@ -1093,17 +1117,35 @@ fn defringe(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf {
}
/// Spot removal (`spots::apply`), spot by spot on `img` in place: each spot reads the image as
/// the earlier ones left it.
/// the earlier ones left it. Process V14's heal (a membrane solve per spot) has no kernel yet: each
/// of its spots runs on the CPU on the rectangle it reads, the only part of the image that crosses
/// to the host and back; the rest of the render stays on the device.
fn spots(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf {
use lightcraft_pipeline::spots;
let (w, h) = (plan.w, plan.h);
let method = spots::HealMethod::of(&plan.settings);
if method == spots::HealMethod::Pinned && !plan.settings.spots.is_empty() {
// process V14's heal (a membrane solve per spot) has no kernel yet: the spots run on the CPU
// between the device stages, the rest of the render stays on the device
let mut host = cx.read_rgb(&img, w, h);
spots::apply(&mut host, &plan.settings.spots, &plan.frame, plan.px_per_long, method);
return cx.gpu.upload(rgb_words(&host));
if method == spots::HealMethod::Pinned {
for spot in &plan.settings.spots {
let Some(l) = spots::layout(spot, &plan.frame, w, h, plan.px_per_long) else { continue };
let Some(&first) = l.pts.first() else { continue };
let offset = match l.offset {
Some(o) => o,
None => auto_source(cx, &img, w, h, first, l.r),
};
let r = spots::spot_reads(&l, offset, method, w, h);
let mut crop = cx.read_rect(&img, w, r);
let (bx, by, bw, bh) = (l.bx, l.by, l.bw, l.bh);
spots::apply_spot(&mut crop, (r[0], r[1]), l, offset, method);
// only the spot's box changed
let mut words = Vec::with_capacity(bw * bh * 3);
for y in by..by + bh {
let row = ((y - r[1]) * crop.width + (bx - r[0])) * 3;
words.extend_from_slice(&rgb_words(&crop)[row..row + bw * 3]);
}
let up = cx.gpu.upload(&words);
cx.write_rect(&up, &img, w, [bx, by, bx + bw, by + bh]);
}
return img;
}
for spot in &plan.settings.spots {
let Some(l) = spots::layout(spot, &plan.frame, w, h, plan.px_per_long) else { continue };
@@ -1493,11 +1535,13 @@ fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, pla
/// Most brush dabs the mask kernel evaluates per pixel (more: the CPU rasterizes the brush).
const MAX_DABS: usize = 4096;
/// The `shape` kernel's brush data for `dabs`: stroke records (12 words: dab offset, dab count,
/// r, hard, flow, density, erase, bbox x0 y0 x1 y1, auto) then the dab centres.
/// The `shape` kernel's brush data for `dabs`: stroke records (13 words: dab offset, dab count,
/// r, hard, flow, density, erase, bbox x0 y0 x1 y1, auto, the edge feathered by stroke (process
/// V16, [`lightcraft_pipeline::masks::stroke_feather`])) then each dab's centre and the flow it
/// adds (3 words; the stroke's flow before process V15, [`lightcraft_pipeline::masks::BrushDabs::dab`]).
fn brush_aux(dabs: &[&lightcraft_pipeline::masks::BrushDabs], erase: bool) -> Vec<f32> {
let mut aux = Vec::new();
let mut off = 12 * dabs.len();
let mut off = 13 * dabs.len();
for d in dabs {
let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
for q in &d.dabs {
@@ -1506,10 +1550,11 @@ fn brush_aux(dabs: &[&lightcraft_pipeline::masks::BrushDabs], erase: bool) -> Ve
aux.extend([off as f32, d.dabs.len() as f32, d.r as f32, d.hard as f32, d.flow, d.density, (erase && d.erase) as u8 as f32]);
aux.extend([x0, y0, x1, y1].map(|v| v as f32));
aux.push(d.auto as u8 as f32);
off += 2 * d.dabs.len();
aux.push(d.feather_by_stroke as u8 as f32);
off += 3 * d.dabs.len();
}
for d in dabs {
aux.extend(d.dabs.iter().flat_map(|q| [q.x as f32, q.y as f32]));
aux.extend(d.dabs.iter().enumerate().flat_map(|(i, q)| [q.x as f32, q.y as f32, d.dab(i).2]));
}
aux
}
+28 -10
View File
@@ -77,14 +77,16 @@ fn shape(@builtin(global_invocation_id) g: vec3<u32>) {
}
v = 1.0 - sstep(tol * 0.5, tol, best);
} else if (kind == 4u) {
// stroke record: dab offset, dab count, r, hard, flow, density, erase, bbox x0 y0 x1 y1, auto
// stroke record: dab offset, dab count, r, hard, flow, density, erase, bbox x0 y0 x1 y1, auto,
// the edge feathered by stroke (process V16: build-up times the highest dab falloff)
let px = f32(g.x) + 0.5;
let py = f32(g.y) + 0.5;
let lp = log_l[i];
let chp = chroma_at(i);
for (var k = 0u; k < pu(10u); k++) {
let o = 12u * k;
let o = 13u * k;
let auto_mask = aux[o + 11u] != 0.0;
let by_stroke = aux[o + 12u] != 0.0;
if (px < aux[o + 7u] || py < aux[o + 8u] || px > aux[o + 9u] || py > aux[o + 10u]) {
continue;
}
@@ -92,11 +94,13 @@ fn shape(@builtin(global_invocation_id) g: vec3<u32>) {
let cnt = u32(aux[o + 1u]);
let r = aux[o + 2u];
let hard = aux[o + 3u];
let flow = aux[o + 4u];
var keep = 1.0;
var edge = 0.0;
for (var j = 0u; j < cnt; j++) {
let dx = px - aux[off + 2u * j];
let dy = py - aux[off + 2u * j + 1u];
// dab record: centre x, y and the flow it adds (the stroke's before process V15)
let dx = px - aux[off + 3u * j];
let dy = py - aux[off + 3u * j + 1u];
let flow = aux[off + 3u * j + 2u];
let dd = sqrt(dx * dx + dy * dy);
if (dd > r) {
continue;
@@ -105,15 +109,29 @@ fn shape(@builtin(global_invocation_id) g: vec3<u32>) {
if (dd > hard) {
a = 1.0 - sstep(hard, r, dd);
}
var sim = 1.0;
if (auto_mask) {
let rx = min(u32(max(floor(aux[off + 2u * j]), 0.0)), w - 1u);
let ry = min(u32(max(floor(aux[off + 2u * j + 1u]), 0.0)), h - 1u);
let rx = min(u32(max(floor(aux[off + 3u * j]), 0.0)), w - 1u);
let ry = min(u32(max(floor(aux[off + 3u * j + 1u]), 0.0)), h - 1u);
let ri = ry * w + rx;
a *= auto_similarity(lp, chp, log_l[ri], chroma_at(ri));
sim = auto_similarity(lp, chp, log_l[ri], chroma_at(ri));
}
if (by_stroke) {
// masks::feather_dab (never an Auto Mask stroke): the build-up grows by the flow,
// the edge keeps the highest falloff; a dab with no Flow changes neither
if (flow > 0.0) {
keep *= 1.0 - flow;
edge = max(edge, a);
}
} else {
keep *= 1.0 - a * sim * flow;
}
keep *= 1.0 - a * flow;
}
let sa = min(1.0 - keep, aux[o + 5u]);
var sa = min(1.0 - keep, aux[o + 5u]);
if (by_stroke) {
// masks::stroke_coverage
sa = min((1.0 - keep) * edge, aux[o + 5u]);
}
if (aux[o + 6u] != 0.0) {
v = v * (1.0 - sa);
} else {
+83 -2
View File
@@ -511,6 +511,86 @@ fn cases() -> Vec<(&'static str, Edit)> {
},
];
}),
("masks (brush, process V15: flow per radius travelled)", |s| {
s.process = lightcraft_develop::Process::V15.version();
let stroke = BrushStroke {
points: vec![Point::new(0.1, 0.3), Point::new(0.5, 0.4), Point::new(0.8, 0.35)],
size: 0.04,
flow: 25.0,
..Default::default()
};
s.masks = vec![Mask {
components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: MaskShape::Brush { strokes: vec![stroke] } }],
adjust: lightcraft_develop::LocalAdjustments { exposure: -1.0, ..Default::default() },
..Default::default()
}];
}),
("masks (brush, process V16: a soft stroke feathered as one dab)", |s| {
s.process = lightcraft_develop::Process::V16.version();
let stroke = |flow: f64, erase: bool, y: f64| BrushStroke {
points: vec![Point::new(0.1, y), Point::new(0.5, y + 0.1), Point::new(0.8, y + 0.05)],
size: 0.06,
feather: 100.0,
flow,
erase,
..Default::default()
};
s.masks = vec![Mask {
components: vec![MaskComponent {
name: None,
op: MaskOp::Add,
invert: false,
shape: MaskShape::Brush { strokes: vec![stroke(100.0, false, 0.3), stroke(50.0, false, 0.55), stroke(100.0, true, 0.45)] },
}],
adjust: lightcraft_develop::LocalAdjustments { exposure: -1.0, ..Default::default() },
..Default::default()
}];
}),
("masks (brush, process V16: an Auto Mask stroke keeps V15 accumulation)", |s| {
s.process = lightcraft_develop::Process::V16.version();
let stroke = BrushStroke {
points: vec![Point::new(0.1, 0.3), Point::new(0.5, 0.45), Point::new(0.85, 0.4)],
size: 0.06,
feather: 100.0,
flow: 40.0,
auto_mask: true,
..Default::default()
};
s.masks = vec![Mask {
components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: MaskShape::Brush { strokes: vec![stroke] } }],
adjust: lightcraft_develop::LocalAdjustments { exposure: -1.0, ..Default::default() },
..Default::default()
}];
}),
("masks (brush, process V15: a soft stroke's dabs accumulated)", |s| {
s.process = lightcraft_develop::Process::V15.version();
let stroke = BrushStroke {
points: vec![Point::new(0.1, 0.3), Point::new(0.5, 0.4), Point::new(0.8, 0.35)],
size: 0.06,
feather: 100.0,
flow: 100.0,
..Default::default()
};
s.masks = vec![Mask {
components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: MaskShape::Brush { strokes: vec![stroke] } }],
adjust: lightcraft_develop::LocalAdjustments { exposure: -1.0, ..Default::default() },
..Default::default()
}];
}),
("masks (brush, process V14: flow per dab)", |s| {
s.process = lightcraft_develop::Process::V14.version();
let stroke = BrushStroke {
points: vec![Point::new(0.1, 0.3), Point::new(0.5, 0.4), Point::new(0.8, 0.35)],
size: 0.04,
flow: 25.0,
..Default::default()
};
s.masks = vec![Mask {
components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: MaskShape::Brush { strokes: vec![stroke] } }],
adjust: lightcraft_develop::LocalAdjustments { exposure: -1.0, ..Default::default() },
..Default::default()
}];
}),
("masks (brush + ranges)", |s| {
let stroke = BrushStroke {
points: vec![Point::new(0.1, 0.3), Point::new(0.5, 0.4), Point::new(0.8, 0.35)],
@@ -1527,8 +1607,8 @@ fn soft_proofs_match() {
/// Spot removal on the device: Clone, Heal and Remove (automatic source, scored on the device),
/// brushed strokes, overlapping spots (each reads what the earlier ones left), feather 0 and
/// spots cut by the image edge; on process V13 by the device kernels, on V14 (the pinned heal) on the
/// CPU between the device stages.
/// spots cut by the image edge and sources past it; on process V13 by the device kernels, on V14 (the
/// pinned heal) by each spot's box read back, healed on the CPU and written back.
#[test]
fn spots_match() {
if !gpu() {
@@ -1552,6 +1632,7 @@ fn spots_match() {
("remove near the edge (auto)", vec![spot(SpotMode::Remove, &[(0.04, 0.5)], 0.03, 50.0, None)]),
("brushed heal stroke", vec![spot(SpotMode::Heal, &[(0.2, 0.7), (0.3, 0.72), (0.4, 0.69)], 0.02, 30.0, Some((0.0, -0.15)))]),
("feather 0, half opacity", vec![Spot { opacity: 50.0, ..spot(SpotMode::Clone, &[(0.7, 0.3)], 0.04, 0.0, Some((-0.2, 0.0))) }]),
("source past the edge", vec![spot(SpotMode::Heal, &[(0.1, 0.5)], 0.04, 50.0, Some((-0.2, 0.0)))]),
("cut by the edge", vec![spot(SpotMode::Heal, &[(0.99, 0.02)], 0.05, 50.0, Some((-0.2, 0.2)))]),
(
"overlapping, auto after manual",
+32
View File
@@ -0,0 +1,32 @@
//! Review of PR #4992: a test that needs a device takes the render device (`shared_device`) and
//! creates one of its own only when no render device can exist in the process (a second Vulkan
//! instance races the render device: Vulkan-Loader#1863). Another test turning GPU rendering off,
//! or the window's device being adopted, must not make `shared_device` say there is none while a
//! render could still create it. One test in its own process: the switches are process-wide.
use std::time::Duration;
#[test]
fn the_shared_device_is_settled_while_gpu_rendering_is_off_or_the_window_device_pending() {
lightcraft_gpu::set_window_device_pending(true);
lightcraft_gpu::set_enabled(false);
let t0 = std::time::Instant::now();
let adoption = std::thread::spawn(|| {
std::thread::sleep(Duration::from_millis(200));
// (the adoption couldn't start)
lightcraft_gpu::set_window_device_pending(false);
});
let shared = lightcraft_gpu::shared_device();
let waited = t0.elapsed();
adoption.join().unwrap();
if lightcraft_gpu::env_off_reason().is_none() {
assert!(waited >= Duration::from_millis(200), "waited for the window's device ({waited:?})");
}
// created, or failed for good, or switched off by the environment: no render device can appear later
assert!(lightcraft_gpu::ready(), "the render device is settled");
lightcraft_gpu::set_enabled(true);
assert_eq!(shared.is_some(), lightcraft_gpu::available(), "the device renders use");
if shared.is_none() {
lightcraft_testkit::skip!(Gpu, "no GPU device: {:?}", lightcraft_gpu::unavailable_reason());
}
}
+1
View File
@@ -19,3 +19,4 @@ lightcraft-scenes = { workspace = true }
serde = { workspace = true }
thiserror = { workspace = true }
rayon = { workspace = true }
log = { workspace = true }
+168 -11
View File
@@ -163,23 +163,25 @@ fn harris(lvl: &Plane) -> Vec<(f32, f32, f32)> {
}
/// Adaptive non-maximal suppression: indices (into `pts`, sorted by decreasing strength) of the `max`
/// points with the largest suppression radii.
/// points with the largest suppression radii. The nearest stronger point is found by searching
/// rings of a uniform grid outward from each point, which gives exactly the brute-force result in
/// near-linear time.
fn anms(pts: &[Keypoint], max: usize) -> Vec<usize> {
if pts.len() <= max {
return (0..pts.len()).collect();
}
let mut pmax = Vec::with_capacity(pts.len());
let mut run = f32::NEG_INFINITY;
for p in pts {
pmax.push(run);
run = run.max(p.strength);
}
let grid = AnmsGrid::new(pts);
let radii: Vec<f32> = (0..pts.len())
.into_par_iter()
.map(|i| {
let p = pts[i];
let mut best = f32::INFINITY;
for q in &pts[..i] {
if q.strength * 0.9 > p.strength {
let d = (q.x - p.x).powi(2) + (q.y - p.y).powi(2);
best = best.min(d);
}
}
best
.map(|i| match (pts.get(i), pmax.get(i)) {
(Some(p), Some(m)) if m * 0.9 > p.strength => grid.nearest_stronger(pts, i, p),
_ => f32::INFINITY,
})
.collect();
let mut idx: Vec<usize> = (0..pts.len()).collect();
@@ -188,6 +190,103 @@ fn anms(pts: &[Keypoint], max: usize) -> Vec<usize> {
idx
}
/// Uniform grid over the finite points; each cell lists its point indices in ascending order.
struct AnmsGrid {
minx: f64,
miny: f64,
cell: f64,
gw: usize,
gh: usize,
cells: Vec<Vec<usize>>,
}
impl AnmsGrid {
fn new(pts: &[Keypoint]) -> Self {
let finite = || pts.iter().filter(|p| p.x.is_finite() && p.y.is_finite());
let (mut minx, mut miny, mut maxx, mut maxy) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for p in finite() {
minx = minx.min(p.x as f64);
maxx = maxx.max(p.x as f64);
miny = miny.min(p.y as f64);
maxy = maxy.max(p.y as f64);
}
if minx > maxx {
(minx, miny, maxx, maxy) = (0.0, 0.0, 0.0, 0.0);
}
let (w, h, n) = (maxx - minx, maxy - miny, pts.len().max(1) as f64);
let mut cell = (w * h / n * 2.0).sqrt().max(1.0);
while ((w / cell).floor() + 1.0) * ((h / cell).floor() + 1.0) > 4.0 * n {
cell *= 1.5;
}
let (gw, gh) = ((w / cell) as usize + 1, (h / cell) as usize + 1);
let mut g = AnmsGrid { minx, miny, cell, gw, gh, cells: vec![Vec::new(); gw * gh] };
for (i, p) in pts.iter().enumerate() {
if p.x.is_finite() && p.y.is_finite() {
let (cx, cy) = g.locate(p);
if let Some(c) = g.cells.get_mut(cy * gw + cx) {
c.push(i);
}
}
}
g
}
fn locate(&self, p: &Keypoint) -> (usize, usize) {
let cx = (((p.x as f64 - self.minx) / self.cell) as usize).min(self.gw - 1);
let cy = (((p.y as f64 - self.miny) / self.cell) as usize).min(self.gh - 1);
(cx, cy)
}
/// Squared distance from `p` (= `pts[i]`) to the nearest earlier point with `strength * 0.9 > p.strength`.
fn nearest_stronger(&self, pts: &[Keypoint], i: usize, p: &Keypoint) -> f32 {
let mut best = f32::INFINITY;
if !(p.x.is_finite() && p.y.is_finite()) {
return best;
}
let (cx, cy) = self.locate(p);
let (cx, cy) = (cx as isize, cy as isize);
let rmax = cx.max(self.gw as isize - 1 - cx).max(cy).max(self.gh as isize - 1 - cy);
let scan = |x: isize, y: isize, best: &mut f32| {
if x < 0 || y < 0 || x >= self.gw as isize || y >= self.gh as isize {
return;
}
let Some(list) = self.cells.get(y as usize * self.gw + x as usize) else { return };
for &j in list.get(..list.partition_point(|&j| j < i)).unwrap_or(&[]) {
let Some(q) = pts.get(j) else { continue };
if q.strength * 0.9 > p.strength {
let d = (q.x - p.x).powi(2) + (q.y - p.y).powi(2);
*best = best.min(d);
}
}
};
for r in 0..=rmax {
if r == 0 {
scan(cx, cy, &mut best);
} else {
// (only the ring's edges that lie inside the grid: a long thin grid would otherwise
// walk the out-of-grid edges cell by cell on every ring)
let (xs, ys) = ((cx - r).max(0)..=(cx + r).min(self.gw as isize - 1), (cy - r + 1).max(0)..=(cy + r - 1).min(self.gh as isize - 1));
for y in [cy - r, cy + r].into_iter().filter(|y| (0..self.gh as isize).contains(y)) {
for x in xs.clone() {
scan(x, y, &mut best);
}
}
for x in [cx - r, cx + r].into_iter().filter(|x| (0..self.gw as isize).contains(x)) {
for y in ys.clone() {
scan(x, y, &mut best);
}
}
}
// points in rings beyond `r` are at least `r * cell` away; 1 px absorbs rounding in the cell assignment
let m = (r as f64 * self.cell - 1.0).max(0.0);
if best as f64 <= m * m {
break;
}
}
best
}
}
fn descriptor(img: &Plane, x: f32, y: f32, angle: f32) -> Option<[f32; DESC_LEN]> {
let (s, c) = angle.sin_cos();
let mut d = [0f32; DESC_LEN];
@@ -291,6 +390,64 @@ mod tests {
})
}
fn anms_reference(pts: &[Keypoint], max: usize) -> Vec<usize> {
if pts.len() <= max {
return (0..pts.len()).collect();
}
let radii: Vec<f32> = (0..pts.len())
.map(|i| {
let p = pts[i];
let mut best = f32::INFINITY;
for q in &pts[..i] {
if q.strength * 0.9 > p.strength {
let d = (q.x - p.x).powi(2) + (q.y - p.y).powi(2);
best = best.min(d);
}
}
best
})
.collect();
let mut idx: Vec<usize> = (0..pts.len()).collect();
idx.sort_by(|&a, &b| radii[b].total_cmp(&radii[a]).then(a.cmp(&b)));
idx.truncate(max);
idx
}
#[test]
fn grid_anms_matches_quadratic_reference() {
let mut state = 0x9E37_79B9_7F4A_7C15u64;
let mut rnd = move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
(state >> 40) as f32 / (1u64 << 24) as f32
};
let kp = |x: f32, y: f32, strength: f32| Keypoint { x, y, level: 0, angle: 0.0, strength };
let mut sets: Vec<(Vec<Keypoint>, usize)> = Vec::new();
sets.push(((0..3000).map(|_| kp(rnd() * 2000.0, rnd() * 1500.0, rnd())).collect(), 400));
let centres: Vec<(f32, f32)> = (0..6).map(|_| (rnd() * 2000.0, rnd() * 1500.0)).collect();
sets.push((
(0..3000)
.map(|k| {
let (cx, cy) = centres[k % centres.len()];
let g = |r: f32| (r - 0.5) * 60.0;
kp(cx + g(rnd() + rnd()), cy + g(rnd() + rnd()), rnd())
})
.collect(),
400,
));
sets.push(((0..3000).map(|_| kp((rnd() * 40.0).floor(), (rnd() * 30.0).floor(), rnd())).collect(), 400));
sets.push(((0..3000).map(|_| kp(rnd() * 2000.0, rnd() * 1500.0, (rnd() * 4.0).floor() + 1.0)).collect(), 400));
// one row of points: a grid one cell tall, where the rings' top and bottom edges are outside it
sets.push(((0..3000).map(|i| kp(32.0 + 4.0 * i as f32, 32.0, rnd())).collect(), 400));
sets.push(((0..50).map(|_| kp(rnd() * 100.0, rnd() * 100.0, rnd())).collect(), 400));
sets.push(((0..500).map(|_| kp(rnd() * 2000.0, rnd() * 1500.0, rnd())).collect(), 0));
for (mut pts, max) in sets {
pts.sort_by(|a, b| b.strength.total_cmp(&a.strength));
assert_eq!(anms(&pts, max), anms_reference(&pts, max));
}
}
#[test]
fn shifted_images_match_with_the_shift() {
let a = pattern(400, 300, 0.0, 0.0);
+10 -3
View File
@@ -28,7 +28,7 @@ pub enum DngSamples {
Half,
/// 32-bit floating point, Deflate + floating-point predictor.
Float,
/// 16-bit integer, Deflate + horizontal predictor (panoramas of normal-range photos).
/// 16-bit integer, lossless JPEG tiles (panoramas of normal-range photos).
U16,
}
@@ -117,7 +117,12 @@ pub fn write_linear_dng(
metadata: meta,
lens_metadata: Default::default(),
};
let compression = DngCompression::Deflate { tile: 256, half: samples == DngSamples::Half };
// Common raw readers accept Deflate only for floating-point data, so integer data uses lossless JPEG.
let compression = match samples {
DngSamples::U16 => DngCompression::Lj92 { tile: 256 },
DngSamples::Half => DngCompression::Deflate { tile: 256, half: true },
DngSamples::Float => DngCompression::Deflate { tile: 256, half: false },
};
lightcraft_raw::write_dng(&raw, &DngWriteOptions { compression, ..Default::default() }).map_err(|e| MergeError::Output(e.to_string()))
}
@@ -153,6 +158,8 @@ mod tests {
assert!((red[c] / k - want[c]).abs() < 5e-3, "{red:?} vs {want:?}");
}
let u16 = write_linear_dng(&img, &color, Orientation::Normal, &Metadata::default(), 0.0, DngSamples::U16, &[]).unwrap();
assert!(lightcraft_raw::decode(&u16).is_ok());
let raw16 = lightcraft_raw::decode(&u16).unwrap();
assert_eq!((raw16.width, raw16.height, raw16.cpp), (80, 60, 3));
assert!(matches!(raw16.data, lightcraft_raw::RawData::U16(_)));
}
}
+14 -5
View File
@@ -72,8 +72,10 @@ pub struct PanoResult {
pub crop: Option<[f64; 4]>,
/// The projection used (never `Auto`).
pub projection: Projection,
/// Indices (into the inputs) of the frames in the panorama; the others didn't connect.
/// Indices (into the inputs) of the frames with recovered cameras in this panorama.
pub used: Vec<usize>,
/// Measurements for the first [`camera::MAX_PAIR_DIAGNOSTICS`] input pairs, including rejected pairs.
pub pairs: Vec<camera::PairDiagnostic>,
/// Cameras of the inputs (`None` = not used), in their full-resolution pixels, straightened.
pub cameras: Vec<Option<Camera>>,
/// Per-input exposure gains applied.
@@ -176,6 +178,11 @@ struct Tile {
/// Register the frames: cameras for the connected set.
pub fn register(frames: &[Frame], progress: &Progress) -> Result<(Vec<Option<Camera>>, f64, f64)> {
let (cameras, before, after, _) = register_impl(frames, progress, false)?;
Ok((cameras, before, after))
}
fn register_impl(frames: &[Frame], progress: &Progress, report_pairs: bool) -> Result<(Vec<Option<Camera>>, f64, f64, Vec<camera::PairDiagnostic>)> {
let n = frames.len();
let work: Vec<(crate::features::Features, f64)> = frames
.par_iter()
@@ -188,10 +195,11 @@ pub fn register(frames: &[Frame], progress: &Progress) -> Result<(Vec<Option<Cam
check(progress, 0.2, "Matching")?;
let feats: Vec<_> = work.iter().map(|(f, _)| f.clone()).collect();
let scales: Vec<f64> = work.iter().map(|(_, s)| *s).collect();
let pairs = camera::match_pairs(&feats, &scales);
let (pairs, diagnostics) =
if report_pairs { camera::match_pairs_with_diagnostics(&feats, &scales) } else { (camera::match_pairs(&feats, &scales), Vec::new()) };
let ids = camera::largest_component(n, &pairs);
if ids.len() < 2 {
return Err(MergeError::NoOverlap("the photos don't overlap enough to be stitched".into()));
return Err(MergeError::NoOverlap("could not align at least two photos for a panorama".into()));
}
check(progress, 0.3, "Aligning")?;
// focal length: EXIF 35 mm equivalent, else the homographies, else ~50° horizontal
@@ -220,7 +228,7 @@ pub fn register(frames: &[Frame], progress: &Progress) -> Result<(Vec<Option<Cam
let adj = camera::bundle_adjust(&cams, &pairs, anchor, 60);
let mut cams = adj.cameras;
camera::straighten(&mut cams);
Ok((cams, adj.rms_before, adj.rms))
Ok((cams, adj.rms_before, adj.rms, diagnostics))
}
/// A frame's focal length in pixels, from EXIF's 35 mm equivalent.
@@ -239,7 +247,7 @@ pub fn stitch(mut frames: Vec<Frame>, opts: &PanoOptions, progress: &Progress) -
return Err(MergeError::TooMany(n, MAX_FRAMES));
}
check(progress, 0.01, "Finding features")?;
let (cams, rms_before, rms) = register(&frames, progress)?;
let (cams, rms_before, rms, pairs) = register_impl(&frames, progress, true)?;
let used: Vec<usize> = (0..n).filter(|&i| cams[i].is_some()).collect();
let fov = fov(&frames, &cams);
let projection = match opts.projection {
@@ -408,6 +416,7 @@ pub fn stitch(mut frames: Vec<Frame>, opts: &PanoOptions, progress: &Progress) -
crop,
projection,
used,
pairs,
cameras: cams,
gains,
rms_before,
+95 -28
View File
@@ -58,37 +58,104 @@ pub struct PairMatch {
pub levels: Vec<u8>,
}
/// Why a pair did or did not pass registration verification. This is not a scene diagnosis.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub enum PairStatus {
InsufficientMatches,
NoModel,
Rejected,
Accepted,
}
/// Verification measurements at the working resolution (long edge at most 1000 pixels).
#[derive(Clone, Debug, serde::Serialize)]
pub struct PairDiagnostic {
pub i: usize,
pub j: usize,
pub matches: usize,
/// Unknown when RANSAC could not return a model with at least 12 inliers.
pub inliers: Option<usize>,
pub status: PairStatus,
}
/// Maximum pair records returned with a stitch. Full measurements are available in debug logs.
pub const MAX_PAIR_DIAGNOSTICS: usize = 1024;
/// Generate pairs lazily so comparing frames with no usable features needs no quadratic storage.
fn input_pairs(n: usize) -> impl ParallelIterator<Item = (usize, usize)> {
(0..n).into_par_iter().flat_map_iter(move |i| ((i + 1)..n).map(move |j| (i, j)))
}
/// Match every pair of images. `feats[k]` are in work coordinates scaled by `scales[k]`.
pub fn match_pairs(feats: &[Features], scales: &[f64]) -> Vec<PairMatch> {
let mut pairs: Vec<_> = input_pairs(feats.len()).filter_map(|(i, j)| match_pair(feats, scales, i, j, |_, _, _| {})).collect();
pairs.sort_unstable_by_key(|p| (p.i, p.j));
pairs
}
/// As [`match_pairs`], with measurements for the first [`MAX_PAIR_DIAGNOSTICS`] pairs in input
/// order. All comparisons still run and any additional outcomes appear only in the debug log.
pub fn match_pairs_with_diagnostics(feats: &[Features], scales: &[f64]) -> (Vec<PairMatch>, Vec<PairDiagnostic>) {
let n = feats.len();
// the pairs are generated lazily: materialising all n(n−1)/2 up front is quadratic memory, including
// when every comparison comes up empty (no usable features)
let mut out: Vec<PairMatch> = (0..n)
.into_par_iter()
.flat_map_iter(|i| ((i + 1)..n).map(move |j| (i, j)))
.filter_map(|(i, j)| {
let m = features::match_features(&feats[i], &feats[j], 0.8);
if m.len() < 12 {
return None;
}
let a: Vec<Point> = m.iter().map(|(p, _)| Point::new(feats[i].points[*p].x as f64, feats[i].points[*p].y as f64)).collect();
let b: Vec<Point> = m.iter().map(|(_, q)| Point::new(feats[j].points[*q].x as f64, feats[j].points[*q].y as f64)).collect();
let fit = ransac::ransac(Model::Homography, &a, &b, 3.0, 12, (i * 1000 + j) as u64)?;
// Brown & Lowe's probabilistic verification
if (fit.inliers.len() as f64) <= 8.0 + 0.3 * m.len() as f64 {
return None;
}
let (si, sj) = (scales[i], scales[j]);
let pts = fit.inliers.iter().map(|&k| (Point::new(a[k].x / si, a[k].y / si), Point::new(b[k].x / sj, b[k].y / sj))).collect();
let levels = fit.inliers.iter().map(|&k| feats[i].points[m[k].0].level.max(feats[j].points[m[k].1].level)).collect();
// conjugate to full resolution: H_full = S_j⁻¹ · H · S_i
let s_i = Homography([si, 0.0, 0.0, 0.0, si, 0.0, 0.0, 0.0, 1.0]);
let s_j_inv = Homography([1.0 / sj, 0.0, 0.0, 0.0, 1.0 / sj, 0.0, 0.0, 0.0, 1.0]);
Some(PairMatch { i, j, h: s_j_inv.mul(&fit.h).mul(&s_i), pts, levels })
})
.collect();
out.sort_by_key(|p| (p.i, p.j));
out
let (mut pairs, mut diagnostics) = input_pairs(n)
.fold(
|| (Vec::new(), Vec::new()),
|(mut pairs, mut diagnostics), (i, j)| {
pairs.extend(match_pair(feats, scales, i, j, |matches, inliers, status| {
log::debug!("panorama pair {i}-{j}: matches={matches}, inliers={inliers:?}, status={status:?}");
// The preceding rows have n-1, n-2, …, n-i pairs. A row with
// i >= the cap cannot contribute because each preceding row has a pair.
if i < MAX_PAIR_DIAGNOSTICS {
let preceding = i.saturating_mul(n - 1).saturating_sub(i * i.saturating_sub(1) / 2);
if preceding.saturating_add(j - i - 1) < MAX_PAIR_DIAGNOSTICS {
diagnostics.push(PairDiagnostic { i, j, matches, inliers, status });
}
}
}));
(pairs, diagnostics)
},
)
.reduce(
|| (Vec::new(), Vec::new()),
|(mut pairs, mut diagnostics), (right_pairs, right_diagnostics)| {
pairs.extend(right_pairs);
diagnostics.extend(right_diagnostics);
(pairs, diagnostics)
},
);
pairs.sort_unstable_by_key(|p| (p.i, p.j));
diagnostics.sort_unstable_by_key(|d| (d.i, d.j));
(pairs, diagnostics)
}
fn match_pair(feats: &[Features], scales: &[f64], i: usize, j: usize, report: impl FnOnce(usize, Option<usize>, PairStatus)) -> Option<PairMatch> {
let m = features::match_features(&feats[i], &feats[j], 0.8);
if m.len() < 12 {
report(m.len(), None, PairStatus::InsufficientMatches);
return None;
}
let a: Vec<Point> = m.iter().map(|(p, _)| Point::new(feats[i].points[*p].x as f64, feats[i].points[*p].y as f64)).collect();
let b: Vec<Point> = m.iter().map(|(_, q)| Point::new(feats[j].points[*q].x as f64, feats[j].points[*q].y as f64)).collect();
let Some(fit) = ransac::ransac(Model::Homography, &a, &b, 3.0, 12, (i * 1000 + j) as u64) else {
report(m.len(), None, PairStatus::NoModel);
return None;
};
let inliers = fit.inliers.len();
// Brown & Lowe's probabilistic verification. Issue #1765 demonstrates false
// negatives here, but lowering only the slope also admits coherent wrong matches.
if (inliers as f64) <= 8.0 + 0.3 * m.len() as f64 {
report(m.len(), Some(inliers), PairStatus::Rejected);
return None;
}
report(m.len(), Some(inliers), PairStatus::Accepted);
let (si, sj) = (scales[i], scales[j]);
let pts = fit.inliers.iter().map(|&k| (Point::new(a[k].x / si, a[k].y / si), Point::new(b[k].x / sj, b[k].y / sj))).collect();
let levels = fit.inliers.iter().map(|&k| feats[i].points[m[k].0].level.max(feats[j].points[m[k].1].level)).collect();
// conjugate to full resolution: H_full = S_j⁻¹ · H · S_i
let s_i = Homography([si, 0.0, 0.0, 0.0, si, 0.0, 0.0, 0.0, 1.0]);
let s_j_inv = Homography([1.0 / sj, 0.0, 0.0, 0.0, 1.0 / sj, 0.0, 0.0, 0.0, 1.0]);
Some(PairMatch { i, j, h: s_j_inv.mul(&fit.h).mul(&s_i), pts, levels })
}
/// The largest connected component of the match graph (sorted image indices).
+26
View File
@@ -258,6 +258,32 @@ fn a_stitch_of_more_than_the_frame_cap_is_refused_up_front() {
assert!(err.to_string().contains("refused"), "the frame cap errors, it does not begin the quadratic match: {err}");
}
#[test]
fn moving_texture_registration_remains_conservative() {
let e = env();
let rs: Vec<M3> = [-22.0, 0.0, 21.0].into_iter().map(|yaw| rot(yaw, 0.0, 0.0)).collect();
let clean: Vec<Frame> = rs.iter().map(|r| shoot(&e, r, 800.0, 800, 600, 1.0)).collect();
let (cameras, _, rms) = lightcraft_merge::pano::register(&clean, &no_progress).unwrap();
assert_eq!(cameras.iter().flatten().count(), 3);
eprintln!("three clean frames: used=3, rms={rms:.4}");
let mut moving = clean;
for (i, frame) in moving.iter_mut().enumerate() {
// An original textured band changes independently between exposures. Keep the
// surrounding scene fixed to the known cameras. This is not a waterfall model.
let mut rng = lightcraft_merge::ransac::Rng::new(1765 + i as u64);
let cells: Vec<f32> = (0..80 * 36).map(|_| rng.unit() as f32).collect();
for y in 120..480 {
for x in 0..800 {
let v = cells[(y - 120) / 10 * 80 + x / 10] * 0.7 + 0.1;
frame.image.set(x, y, [v; 3]);
}
}
}
let result = lightcraft_merge::pano::register(&moving, &no_progress);
eprintln!("three moving-texture frames: {result:?}");
assert!(matches!(result, Err(lightcraft_merge::MergeError::NoOverlap(_))));
}
/// Issue #1455: a panorama came out at 40 MP whatever its photos' resolution. It now keeps their
/// own resolution unless a size is asked for (up to Lightroom's 512 MP); a size scales it down,
/// and a NaN one (from an agent) is no size at all, not a 0.1 MP thumbnail.
+143
View File
@@ -0,0 +1,143 @@
//! Issue #1765: deterministic correspondences isolate verification from feature detection.
//! These are original procedural fixtures, not the reporter's waterfall photos.
use lightcraft_geom::{Homography, Point};
use lightcraft_merge::features::{Features, Keypoint, match_features};
use lightcraft_merge::pano::camera::match_pairs;
use lightcraft_merge::ransac::{Model, Rng, ransac};
fn correspondences(n: usize, inliers: usize, seed: u64, h: Homography) -> [Features; 2] {
let mut rng = Rng::new(seed);
let mut a = Features::default();
let mut b = Features::default();
for k in 0..n {
let p = Point::new(80.0 + rng.unit() * 640.0, 60.0 + rng.unit() * 480.0);
let q = if k < inliers { h.apply(p) } else { Point::new(rng.unit() * 800.0, rng.unit() * 600.0) };
let desc = std::array::from_fn(|_| rng.unit() as f32);
for (f, p) in [(&mut a, p), (&mut b, q)] {
f.points.push(Keypoint { x: p.x as f32, y: p.y as f32, level: 0, angle: 0.0, strength: 1.0 });
f.desc.push(desc);
}
}
[a, b]
}
fn fit(f: &[Features; 2]) -> Option<lightcraft_merge::ransac::Fit> {
let matches = match_features(&f[0], &f[1], 0.8);
assert_eq!(matches.len(), f[0].len());
let points = |side: usize| -> Vec<Point> {
matches
.iter()
.map(|&(i, j)| {
let p = f[side].points[if side == 0 { i } else { j }];
Point::new(p.x as f64, p.y as f64)
})
.collect()
};
ransac(Model::Homography, &points(0), &points(1), 3.0, 12, 1)
}
#[test]
fn moving_scene_regime_is_rejected_despite_a_recovered_homography() {
let h = Homography([1.0, 0.01, 23.0, -0.01, 1.0, 7.0, 0.00001, -0.00002, 1.0]);
for (n, inliers) in [(104, 31), (136, 36), (100, 30), (140, 30)] {
let f = correspondences(n, inliers, 1765, h);
let recovered = fit(&f).expect("RANSAC recovers the known transform");
assert!(recovered.rms < 0.001);
for p in [Point::new(100.0, 100.0), Point::new(700.0, 500.0)] {
assert!(lightcraft_merge::ransac::transfer_error2(&recovered.h, p, h.apply(p)) < 0.001);
}
// Keep the conservative gate until a policy distinguishes this from a coherent moving
// object or a repeated patch. Lowering only the fraction does not establish that.
assert!(match_pairs(&f, &[1.0; 2]).is_empty());
assert!(recovered.inliers.len() as f64 > 8.0 + 0.15 * n as f64, "the proposed lower slope admits it");
}
}
#[test]
fn a_repeated_patch_can_pass_the_lower_slope_with_the_wrong_camera_motion() {
// A copied, textured panel covers the image: 36 distinctive features agree with a false
// 160 px translation. All other correspondences disagree. Spatial spread cannot tell a
// repeated panel from static scene support using these observations alone.
let false_motion = Homography([1.0, 0.0, 160.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);
let f = correspondences(136, 36, 1765, false_motion);
let r = fit(&f).unwrap();
eprintln!("repeated panel: {}/136, rms={:.6}, lower slope accepts=true", r.inliers.len(), r.rms);
assert!(r.rms < 0.001);
assert!(r.inliers.len() as f64 > 8.0 + 0.15 * 136.0);
assert!(match_pairs(&f, &[1.0; 2]).is_empty());
}
#[test]
fn unrelated_low_overlap_duplicates_and_ambiguous_descriptors() {
let h = Homography([1.0, 0.0, 30.0, 0.0, 1.0, 12.0, 0.0, 0.0, 1.0]);
for seed in 1..=8 {
for inliers in [0, 8] {
let f = correspondences(120, inliers, seed, h);
assert!(match_pairs(&f, &[1.0; 2]).is_empty(), "seed {seed}, {inliers} inliers");
}
}
let identity = Homography([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);
let mut f = correspondences(100, 100, 1765, identity);
assert_eq!(match_pairs(&f, &[1.0; 2]).len(), 1, "duplicates remain one verified pair");
for side in &mut f {
side.desc.fill([1.0; 64]);
}
assert!(match_pairs(&f, &[1.0; 2]).is_empty(), "identical repeating descriptors are ambiguous");
}
#[test]
fn translated_camera_with_multiple_depths_does_not_establish_a_panorama() {
// Pinhole cameras with f=800, translated horizontally by 0.2 world units. Points
// span depths 1..5, so their parallax is 32..160 px and no rotation explains them.
let identity = Homography([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);
let mut f = correspondences(136, 136, 1765, identity);
let mut rng = Rng::new(987);
for p in &mut f[1].points {
p.x -= (160.0 / (1.0 + 4.0 * rng.unit())) as f32;
}
let r = fit(&f);
eprintln!(
"translated camera, varying depths: fit={:?}, accepted={}",
r.as_ref().map(|r| (r.inliers.len(), r.rms)),
!match_pairs(&f, &[1.0; 2]).is_empty()
);
assert!(match_pairs(&f, &[1.0; 2]).is_empty());
assert!(r.unwrap().inliers.len() as f64 > 8.0 + 0.15 * 136.0, "the lower slope accepts genuine parallax");
}
#[test]
fn diagnostics_keep_rejected_and_unmatched_pairs_in_input_order() {
use lightcraft_merge::pano::camera::{PairStatus, match_pairs_with_diagnostics};
let h = Homography([1.0, 0.0, 23.0, 0.0, 1.0, 7.0, 0.0, 0.0, 1.0]);
let [a, b] = correspondences(104, 31, 1765, h);
let (pairs, diagnostics) = match_pairs_with_diagnostics(&[a, b, Features::default()], &[1.0; 3]);
assert!(pairs.is_empty());
assert_eq!(diagnostics.iter().map(|d| (d.i, d.j)).collect::<Vec<_>>(), [(0, 1), (0, 2), (1, 2)]);
let rejected = &diagnostics[0];
assert_eq!(rejected.status, PairStatus::Rejected);
assert!(rejected.inliers.is_some_and(|n| (n as f64) <= 8.0 + 0.3 * rejected.matches as f64));
assert_eq!((diagnostics[1].matches, diagnostics[1].inliers, diagnostics[1].status), (0, None, PairStatus::InsufficientMatches));
let f = correspondences(120, 0, 1, h);
let (_, diagnostics) = match_pairs_with_diagnostics(&f, &[1.0; 2]);
assert_eq!((diagnostics[0].inliers, diagnostics[0].status), (None, PairStatus::NoModel));
}
#[test]
fn diagnostics_are_bounded_without_skipping_late_matches() {
use lightcraft_merge::pano::{
MAX_FRAMES,
camera::{MAX_PAIR_DIAGNOSTICS, PairMatch, match_pairs_with_diagnostics},
};
let mut features = vec![Features::default(); MAX_FRAMES - 2];
let identity = Homography([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);
features.extend(correspondences(32, 32, 1765, identity));
let scales = vec![1.0; features.len()];
let (matches, diagnostics) = match_pairs_with_diagnostics(&features, &scales);
let expected = (0..features.len()).flat_map(|i| ((i + 1)..features.len()).map(move |j| (i, j)));
assert!(diagnostics.iter().map(|d| (d.i, d.j)).eq(expected.take(MAX_PAIR_DIAGNOSTICS)));
let indices = |pairs: &[PairMatch]| pairs.iter().map(|p| (p.i, p.j)).collect::<Vec<_>>();
assert_eq!(indices(&matches), [(features.len() - 2, features.len() - 1)]);
assert_eq!(indices(&matches), indices(&match_pairs(&features, &scales)));
}
+85 -11
View File
@@ -62,6 +62,51 @@ pub struct Vig {
pub style: VignetteStyle,
}
/// A vignette's falloff over the summed per-axis terms, with the band edges raised to the power once.
#[derive(Clone, Copy, Debug)]
struct VigFalloff {
power: f32,
kx: f32,
ky: f32,
start: f32,
end: f32,
s0: f32,
s1: f32,
}
impl VigFalloff {
fn new(v: &Vig, aspect: f32) -> Self {
let sx = 1.0 + (aspect - 1.0) * v.aspect_mix;
let sy = 1.0 + (1.0 / aspect - 1.0) * v.aspect_mix;
let m = sx.max(sy);
let end = v.start + v.width;
Self { power: v.power, kx: sx.max(1.0) / m, ky: sy.max(1.0) / m, start: v.start, end, s0: term(v.start, v.power), s1: term(end, v.power) }
}
/// One axis's share of the distance for a normalised coordinate `c` in -1..1 (`horizontal` picks the axis).
fn axis(&self, c: f32, horizontal: bool) -> f32 {
term((c * if horizontal { self.kx } else { self.ky }).abs(), self.power)
}
/// The vignette strength 0..1 from the summed axis terms.
fn falloff(&self, s: f32) -> f32 {
if s <= self.s0 {
0.0
} else if s >= self.s1 {
1.0
} else {
let dist = if self.power == 2.0 { s.sqrt() } else { s.powf(1.0 / self.power) };
smooth(self.start, self.end, dist)
}
}
}
/// `a` raised to the vignette power, for `a >= 0`.
#[inline]
fn term(a: f32, p: f32) -> f32 {
if p == 2.0 { a * a } else { a.powf(p) }
}
fn vignette(s: &DevelopSettings) -> Option<Vig> {
let v = &s.vignette;
(v.amount != 0.0).then(|| {
@@ -103,10 +148,10 @@ impl GrainModel {
seed: g.seed,
})
}),
Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 if draft => {
Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 | Process::V15 | Process::V16 if draft => {
crate::crystal::CrystalGrain::draft(g, px_per_long).map(GrainModel::Crystal)
}
Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 => {
Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 | Process::V15 | Process::V16 => {
crate::crystal::CrystalGrain::new(g, px_per_long).map(GrainModel::Crystal)
}
}
@@ -418,7 +463,7 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap {
},
// V4, with a raw's tone curve rolling off into white in stops: a camera curve past its last
// knot, the generic curve from half a stop below its white point instead of clipping (issue #1632)
Process::V5 | Process::V6 | Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 => {
Process::V5 | Process::V6 | Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 | Process::V15 | Process::V16 => {
match info.camera_tone.as_ref().filter(|_| info.raw) {
Some(curve) => ToneMap::camera_rolloff_hdr(curve, 0.0, l.whites, 0.0, peak),
None if info.raw => ToneMap::rolloff_hdr(l.contrast, l.whites, l.blacks, peak),
@@ -526,7 +571,12 @@ pub(crate) fn finish_with<T: Copy + Default + Send>(
let peak = fp.peak;
let hdr = peak > 1.0;
let mut out = vec![T::default(); w * h];
// the vignette splits into a column term and a row term, so each is computed once
let vig_fall = vig.as_ref().map(|v| VigFalloff::new(v, aspect));
let vig_cols: Vec<f32> =
vig_fall.as_ref().map_or_else(Vec::new, |f| (0..w).map(|x| f.axis((vx + x as f32 + 0.5) / vw * 2.0 - 1.0, true)).collect());
for_rows(&mut out, w, |y, row| {
let vig_row = vig_fall.as_ref().map_or(0.0, |f| f.axis((vy + y as f32 + 0.5) / vh * 2.0 - 1.0, false));
// the crystal grain of the whole row at once when its pixels are axis-aligned
let crystal_row = crystal_row(fp, y, row.len());
for (x, px) in row.iter_mut().enumerate() {
@@ -578,14 +628,8 @@ pub(crate) fn finish_with<T: Copy + Default + Send>(
}
// --- vignette (display linear, post-crop)
if let Some(v) = vig {
let u = (vx + x as f32 + 0.5) / vw * 2.0 - 1.0;
let vv = (vy + y as f32 + 0.5) / vh * 2.0 - 1.0;
let sx = 1.0 + (aspect - 1.0) * v.aspect_mix;
let sy = 1.0 + (1.0 / aspect - 1.0) * v.aspect_mix;
let (ax, ay) = ((u * sx.max(1.0) / sx.max(sy)).abs(), (vv * sy.max(1.0) / sx.max(sy)).abs());
let dist = (ax.powf(v.power) + ay.powf(v.power)).powf(1.0 / v.power);
let t = smooth(v.start, v.start + v.width, dist);
if let (Some(v), Some(f)) = (vig, &vig_fall) {
let t = f.falloff(vig_cols.get(x).copied().unwrap_or(0.0) + vig_row);
if t > 0.0 {
let lum = luminance_2020(d).clamp(0.0, 1.0);
if v.amount < 0.0 {
@@ -935,6 +979,36 @@ mod tests {
Process::ALL.into_iter().filter(|p| *p < Process::V13)
}
#[test]
fn separable_vignette_matches_the_direct_formula() {
let (vx, vy, vw, vh) = (0.0f32, 0.0f32, 61.0f32, 41.0f32);
let (mut zero, mut mid, mut one) = (false, false, false);
let vigs = [(2.0, 1.0, 0.25, 0.6), (2.0, 0.5, 0.3, 0.8), (5.0, 1.0, 0.3, 0.5), (5.0, 0.0, 0.4, 0.7)];
for aspect in [1.5f32, 0.6] {
for (power, aspect_mix, start, width) in vigs {
let v = Vig { amount: -0.5, start, width, aspect_mix, power, highlights: 0.0, style: VignetteStyle::default() };
let f = VigFalloff::new(&v, aspect);
for y in 0..vh as usize {
for x in 0..vw as usize {
let u = (vx + x as f32 + 0.5) / vw * 2.0 - 1.0;
let vv = (vy + y as f32 + 0.5) / vh * 2.0 - 1.0;
let sx = 1.0 + (aspect - 1.0) * v.aspect_mix;
let sy = 1.0 + (1.0 / aspect - 1.0) * v.aspect_mix;
let (ax, ay) = ((u * sx.max(1.0) / sx.max(sy)).abs(), (vv * sy.max(1.0) / sx.max(sy)).abs());
let dist = (ax.powf(v.power) + ay.powf(v.power)).powf(1.0 / v.power);
let t_ref = smooth(v.start, v.start + v.width, dist);
let t = f.falloff(f.axis(u, true) + f.axis(vv, false));
assert!((t - t_ref).abs() < 1e-4, "{power} {aspect} at {x},{y}: {t} vs {t_ref}");
zero |= t == 0.0;
one |= t == 1.0;
mid |= t > 0.0 && t < 1.0;
}
}
}
}
assert!(zero && mid && one, "the grid covers the whole falloff");
}
#[test]
fn tone_sliders_ease_off_from_v13_only() {
for v in [-100.0, -52.0, 0.0, 13.0, 100.0, 250.0] {
+7
View File
@@ -37,9 +37,14 @@ pub struct Frame {
/// `lightcraft_develop::Mask::on_photo`); otherwise they are normalized coordinates of this
/// frame's transformed image, like spots and the crop.
pub masks_on_photo: bool,
/// Brush Flow is coverage per brush radius travelled (process V15, [`crate::masks::flow_per_radius`]),
/// not per dab.
pub brush_flow_per_radius: bool,
/// Filter of the area downscale ahead of the bilinear resample ([`Frame::sample`]); see
/// [`crate::Downscale`].
pub downscale: Filter,
/// A brush stroke's edge is feathered as one dab's is (process V16, [`crate::masks::stroke_feather`]).
pub brush_stroke_feather: bool,
}
/// Where a windowed [`Frame`]'s pixels sit in the full output: its offset and the full output's
@@ -85,7 +90,9 @@ impl Frame {
warp: (!warp.is_identity()).then_some(warp),
view: None,
masks_on_photo: false,
brush_flow_per_radius: crate::masks::flow_per_radius(s),
downscale: Filter::Mitchell,
brush_stroke_feather: crate::masks::stroke_feather(s),
};
if apply_crop {
f.constrain_to_image(s.geometry.constrain_crop);
+174 -29
View File
@@ -489,18 +489,18 @@ fn blur(img: &mut Rgb32f, coc: &[f32], r: f32, boost: f32, origin: (usize, usize
let w = img.width;
// highlights brightened before they are spread (the bokeh), the rest as it is
let gain = |c: [f32; 3]| 1.0 + BOOST_GAIN * boost * smooth(0.5, 1.0, lightcraft_color::luminance_2020(c));
let levels: Vec<Level> = (1..=LEVELS).map(|k| crate::timed("lens blur level", || level(img, coc, k, r, &gain, origin))).collect();
let levels = levels(img, coc, r, &gain, origin);
// each pixel between the two levels around its circle of confusion (level 0: the image)
let src = img.clone();
crate::for_rows(&mut img.data, w, |y, row| {
for (x, px) in row.iter_mut().enumerate() {
let i = y * w + x;
let t = coc.get(i).copied().unwrap_or(0.0) * LEVELS as f32;
let k = (t.floor().max(0.0) as usize).min(LEVELS - 1);
let fr = (t - k as f32).clamp(0.0, 1.0);
let cur = *px;
let at = |k: usize| match k {
0 => src.data.get(i).copied().unwrap_or(*px),
k => levels.get(k - 1).map_or(*px, |l| l.sample(x, y)),
0 => cur,
k => levels.get(k - 1).map_or(cur, |l| l.sample(x, y)),
};
let (a, b) = (at(k), at(k + 1));
*px = std::array::from_fn(|c| a[c] + (b[c] - a[c]) * fr);
@@ -524,37 +524,123 @@ impl Level {
}
}
/// Level `k` of [`LEVELS`] (radius `k / LEVELS · r` pixels): the disc blur of the pixels at least
/// that far out of focus.
fn level(img: &Rgb32f, coc: &[f32], k: usize, r: f32, gain: &(impl Fn([f32; 3]) -> f32 + Sync), origin: (usize, usize)) -> Level {
/// Rows of the image per band of the one-pass level fill (at least; a band is never shorter than
/// the coarsest level's cells).
const BAND_ROWS: usize = 64;
/// One level's grid: radius `radius` pixels, cells `f` pixels wide, `lw × lh` of them, taking the
/// pixels whose circle of confusion lies in `lo..hi`.
struct Grid {
radius: f32,
f: usize,
shift: (usize, usize),
lw: usize,
lh: usize,
lo: f32,
hi: f32,
}
/// What a band of image rows adds to one level: the cell rows from `cy_lo` on it touches.
#[derive(Default)]
struct BandCells {
cy_lo: usize,
cells: Vec<[f32; 4]>,
}
/// The [`LEVELS`] levels (level `k`, from 1: radius `k / LEVELS · r` pixels, the disc blur of the
/// pixels at least that far out of focus), filled in one pass over `img`: each pixel is read and
/// its `gain` computed once, then added to every level's cells.
fn levels(img: &Rgb32f, coc: &[f32], r: f32, gain: &(impl Fn([f32; 3]) -> f32 + Sync), origin: (usize, usize)) -> Vec<Level> {
crate::timed("lens blur levels", || levels_banded(img, coc, r, gain, origin, BAND_ROWS))
}
/// [`levels`] with bands of at least `min_band` rows. Bands are fixed by the rows (aligned to the
/// whole output's), not by the threads, so the sums come out the same on any machine.
fn levels_banded(img: &Rgb32f, coc: &[f32], r: f32, gain: &(impl Fn([f32; 3]) -> f32 + Sync), origin: (usize, usize), min_band: usize) -> Vec<Level> {
let (w, h) = (img.width, img.height);
let radius = r * k as f32 / LEVELS as f32;
let (f, shift, lw, lh) = level_grid(w, h, radius, origin);
let (grid_w, grid_h) = (w.saturating_add(shift.0), h.saturating_add(shift.1));
// a pixel counts in this level when its own circle of confusion reaches it
let (lo, hi) = ((k - 1) as f32 / LEVELS as f32, k as f32 / LEVELS as f32);
let mut cells = vec![[0f32; 4]; lw * lh];
crate::for_rows(&mut cells, lw, |cy, row| {
for (cx, cell) in row.iter_mut().enumerate() {
let mut acc = [0f32; 4];
for vy in cy * f..((cy + 1) * f).min(grid_h) {
for vx in cx * f..((cx + 1) * f).min(grid_w) {
let (Some(x), Some(y)) = (vx.checked_sub(shift.0), vy.checked_sub(shift.1)) else { continue };
let i = y * w + x;
let (Some(c), Some(d)) = (img.data.get(i), coc.get(i)) else { continue };
// (a non-finite pixel would spread over the whole disc: left out)
if !c.iter().all(|v| v.is_finite()) {
continue;
let grids: Vec<Grid> = (1..=LEVELS)
.map(|k| {
let radius = r * k as f32 / LEVELS as f32;
let (f, shift, lw, lh) = level_grid(w, h, radius, origin);
Grid { radius, f, shift, lw, lh, lo: (k - 1) as f32 / LEVELS as f32, hi: k as f32 / LEVELS as f32 }
})
.collect();
let band = grids.iter().map(|g| g.f).max().unwrap_or(1).max(min_band).max(1);
// where the first band's boundary falls above row 0 (the bands follow the whole output's rows)
let above = origin.1 % band;
let count = if h == 0 { 0 } else { (h - 1 + above) / band + 1 };
let mut bands: Vec<Vec<BandCells>> = (0..count).map(|_| Vec::new()).collect();
crate::for_rows(&mut bands, 1, |bi, slot| {
let Some(slot) = slot.first_mut() else { return };
let y0 = (bi * band).saturating_sub(above);
let y1 = ((bi + 1) * band).saturating_sub(above).min(h);
*slot = grids
.iter()
.map(|g| {
let cy_lo = (y0 + g.shift.1) / g.f;
let cy_hi = (y1.saturating_sub(1) + g.shift.1) / g.f;
BandCells { cy_lo, cells: vec![[0f32; 4]; g.lw.saturating_mul(cy_hi.saturating_sub(cy_lo) + 1)] }
})
.collect();
// each pixel's gain, once for all the levels (NaN: left out, a non-finite pixel would
// spread over the whole disc)
let mut gains = vec![f32::NAN; w];
for y in y0..y1 {
let Some(pixels) = img.data.get(y * w..(y + 1) * w) else { continue };
let cocs = coc.get(y * w..).unwrap_or(&[]);
for (g0, c) in gains.iter_mut().zip(pixels) {
*g0 = if c.iter().all(|v| v.is_finite()) { gain(*c) } else { f32::NAN };
}
for (g, bc) in grids.iter().zip(slot.iter_mut()) {
let Some(base) = ((y + g.shift.1) / g.f).checked_sub(bc.cy_lo).map(|r| r * g.lw) else { continue };
let Some(row) = bc.cells.get_mut(base..base + g.lw) else { continue };
let (mut cx, mut rem) = (g.shift.0 / g.f, g.shift.0 % g.f);
for ((c, d), g0) in pixels.iter().zip(cocs).zip(&gains) {
if !g0.is_nan()
&& let Some(cell) = row.get_mut(cx)
{
let wt = FOCUS_WEIGHT + smooth(g.lo, g.hi, *d);
let gw = g0 * wt;
*cell = [cell[0] + c[0] * gw, cell[1] + c[1] * gw, cell[2] + c[2] * gw, cell[3] + wt];
}
rem += 1;
if rem == g.f {
rem = 0;
cx += 1;
}
let wt = FOCUS_WEIGHT + smooth(lo, hi, *d);
let g = gain(*c) * wt;
acc = [acc[0] + c[0] * g, acc[1] + c[1] * g, acc[2] + c[2] * g, acc[3] + wt];
}
}
*cell = acc;
}
});
Level { img: disc(&cells, lw, lh, radius / f as f32), f, shift }
// each level's band partials, in band order, moved out so a level's are freed once it is summed
let mut parts: Vec<Vec<BandCells>> = (0..grids.len()).map(|_| Vec::with_capacity(bands.len())).collect();
for band in bands {
for (level, bc) in parts.iter_mut().zip(band) {
level.push(bc);
}
}
grids
.iter()
.zip(parts)
.map(|(g, parts)| {
let mut cells = vec![[0f32; 4]; g.lw * g.lh];
// one past the last cell row a band's partial holds
let end = |bc: &BandCells| bc.cy_lo + bc.cells.len().checked_div(g.lw).unwrap_or(0);
// a cell row is the sum of what the bands (in order) added to it; the bands' cell rows
// only grow, so the ones that reach row `cy` (one or two) are found by bisection
crate::for_rows(&mut cells, g.lw, |cy, row| {
let first = parts.partition_point(|bc| end(bc) <= cy);
for bc in parts.get(first..).unwrap_or(&[]).iter().take_while(|bc| bc.cy_lo <= cy) {
let Some(part) = cy.checked_sub(bc.cy_lo).and_then(|r| bc.cells.get(r * g.lw..(r + 1) * g.lw)) else { continue };
for (cell, p) in row.iter_mut().zip(part) {
*cell = std::array::from_fn(|c| cell[c] + p[c]);
}
}
});
drop(parts);
Level { img: disc(&cells, g.lw, g.lh, g.radius / g.f as f32), f: g.f, shift: g.shift }
})
.collect()
}
/// Grid scale and dimensions for one disc level, bounded even when a window's grid is offset.
@@ -1085,6 +1171,65 @@ mod tests {
assert!(subject_point(&Rgb32f::new(0, 0), &s, None).is_none());
}
/// One level gathered cell by cell, as the one-pass fill replaced it: the reference for [`levels_banded`].
fn level_reference(img: &Rgb32f, coc: &[f32], k: usize, r: f32, gain: &(impl Fn([f32; 3]) -> f32 + Sync), origin: (usize, usize)) -> Level {
let (w, h) = (img.width, img.height);
let radius = r * k as f32 / LEVELS as f32;
let (f, shift, lw, lh) = level_grid(w, h, radius, origin);
let (grid_w, grid_h) = (w.saturating_add(shift.0), h.saturating_add(shift.1));
// a pixel counts in this level when its own circle of confusion reaches it
let (lo, hi) = ((k - 1) as f32 / LEVELS as f32, k as f32 / LEVELS as f32);
let mut cells = vec![[0f32; 4]; lw * lh];
crate::for_rows(&mut cells, lw, |cy, row| {
for (cx, cell) in row.iter_mut().enumerate() {
let mut acc = [0f32; 4];
for vy in cy * f..((cy + 1) * f).min(grid_h) {
for vx in cx * f..((cx + 1) * f).min(grid_w) {
let (Some(x), Some(y)) = (vx.checked_sub(shift.0), vy.checked_sub(shift.1)) else { continue };
let i = y * w + x;
let (Some(c), Some(d)) = (img.data.get(i), coc.get(i)) else { continue };
// (a non-finite pixel would spread over the whole disc: left out)
if !c.iter().all(|v| v.is_finite()) {
continue;
}
let wt = FOCUS_WEIGHT + smooth(lo, hi, *d);
let g = gain(*c) * wt;
acc = [acc[0] + c[0] * g, acc[1] + c[1] * g, acc[2] + c[2] * g, acc[3] + wt];
}
}
*cell = acc;
}
});
Level { img: disc(&cells, lw, lh, radius / f as f32), f, shift }
}
/// The one-pass fill of all four levels matches gathering each level on its own: bands that
/// cut cells, a window origin, a non-finite pixel and a varying circle of confusion included.
#[test]
fn one_pass_levels_match_gathering_each_level_alone() {
let (w, h) = (300, 200);
let mut img = scene(w, h, 150, 100);
img.set(40, 30, [3.0, 2.0, 1.0]);
img.set(251, 177, [6.0; 3]);
img.set(120, 60, [f32::NAN, 0.5, 0.5]);
let coc: Vec<f32> = (0..w * h).map(|i| ((i % w) as f32 / w as f32 + (i / w) as f32 / h as f32) / 2.0).collect();
let (r, origin) = (200.0, (37, 53));
let gain = |c: [f32; 3]| 1.0 + BOOST_GAIN * 0.7 * smooth(0.5, 1.0, lightcraft_color::luminance_2020(c));
let merged = levels_banded(&img, &coc, r, &gain, origin, 7);
assert_eq!(merged.len(), LEVELS);
let mut scales = Vec::new();
for (i, m) in merged.iter().enumerate() {
let alone = level_reference(&img, &coc, i + 1, r, &gain, origin);
assert_eq!((m.f, m.shift), (alone.f, alone.shift), "level {}", i + 1);
assert_eq!(m.img.data.len(), alone.img.data.len());
for (a, b) in m.img.data.iter().flatten().zip(alone.img.data.iter().flatten()) {
assert!((a - b).abs() <= 1e-5 * a.abs().max(b.abs()) + 1e-6, "level {}: {a} vs {b}", i + 1);
}
scales.push(m.f);
}
assert!(scales.windows(2).all(|p| p[0] < p[1]), "the levels share a grid: {scales:?}");
}
/// Hostile settings and images: no panic, no NaN.
#[test]
fn hostile_input_never_panics() {
+127 -9
View File
@@ -517,11 +517,25 @@ pub struct BrushDabs {
pub auto: bool,
/// Pen pressure (0..1) of each dab, parallel to `dabs`; empty when the stroke has no pressure data (full pressure).
pub pressure: Vec<f32>,
/// What each dab adds under process V15 ([`travel_flow`], pressure applied), parallel to `dabs`;
/// empty before V15, where every dab adds the stroke's flow.
pub flows: Vec<f32>,
/// The stroke's edge is feathered as one dab's is (process V16, [`stroke_feather`]), unless it
/// is an Auto Mask stroke: its edge follows the photo's, not the feather, and it keeps V15's
/// accumulation, which its colour weighting stays stable under.
pub feather_by_stroke: bool,
}
impl BrushDabs {
/// Radius, hard core and flow of dab `i`, pen pressure applied ([`pressure_radius`], [`pressure_flow`]).
/// Radius, hard core and flow of dab `i`, pen pressure applied ([`pressure_radius`], [`pressure_flow`]);
/// under process V15 the flow is what the dab adds for the distance it travelled ([`travel_flow`]).
pub fn dab(&self, i: usize) -> (f64, f64, f32) {
let (r, hard, flow) = self.pressed(i);
(r, hard, self.flows.get(i).copied().unwrap_or(flow))
}
/// [`Self::dab`] with the stroke's flow for every dab, as before process V15.
fn pressed(&self, i: usize) -> (f64, f64, f32) {
match self.pressure.get(i) {
Some(&p) => {
let r = pressure_radius(self.r, p);
@@ -530,6 +544,75 @@ impl BrushDabs {
None => (self.r, self.hard, self.flow),
}
}
/// Give every dab what it adds for the distance it travelled ([`travel_flow`], process V15).
fn flow_by_travel(mut self) -> BrushDabs {
let flows = (0..self.dabs.len())
.map(|i| {
let (r, _, flow) = self.pressed(i);
// the first dab counts one radius: a click paints its flow, as before
let dist = match (i.checked_sub(1).and_then(|j| self.dabs.get(j)), self.dabs.get(i)) {
(Some(a), Some(b)) => a.dist(*b),
_ => r,
};
travel_flow(flow, dist, r)
})
.collect();
self.flows = flows;
self
}
}
/// Whether a brush stroke's edge is feathered as one dab's is (process V16 on): its coverage is
/// [`stroke_coverage`] of its Flow build-up and its dabs' highest falloff, not every dab's falloff
/// accumulated ([`accumulate`]), which piles the soft edges of overlapping dabs up into a hard one.
pub fn stroke_feather(s: &lightcraft_develop::DevelopSettings) -> bool {
s.process.process() >= lightcraft_develop::Process::V16
}
/// One dab's paint at a pixel of a stroke under [`stroke_feather`]: the Flow build-up `build` grows
/// by the dab's `flow` wherever the dab reaches, and the edge `edge` keeps the highest falloff
/// `falloff`. A dab with no Flow (at pen pressure 0) paints nothing and shapes nothing. (Auto Mask
/// strokes don't take this: [`BrushDabs::feather_by_stroke`].)
#[inline]
pub fn feather_dab(build: &mut f32, edge: &mut f32, falloff: f32, flow: f32) {
if flow.is_nan() || flow <= 0.0 {
return;
}
*build = accumulate(*build, 1.0, flow, 1.0);
*edge = edge.max(falloff);
}
/// A stroke's coverage under [`stroke_feather`] from its Flow build-up and its edge
/// ([`feather_dab`]), up to its density. At Flow 100 the build-up is full wherever a dab reaches,
/// so a stroke's edge falls off over the feather exactly as one dab's does; below it, the build-up
/// is [`travel_flow`]'s, as under V15, shaped by the same edge.
#[inline]
pub fn stroke_coverage(build: f32, edge: f32, density: f32) -> f32 {
(build * edge).min(density)
}
/// Whether brush Flow is the coverage a stroke adds per brush radius it travels (process V15 on), as
/// in Lightroom, rather than what every dab adds whatever the spacing of the dabs.
pub fn flow_per_radius(s: &lightcraft_develop::DevelopSettings) -> bool {
s.process.process() >= lightcraft_develop::Process::V15
}
/// What one dab adds to a stroke's coverage when Flow is coverage per brush radius travelled
/// (process V15): `1 − (1 − flow)^(dist / r)` for a dab `dist` past the previous one, brush radius
/// `r`. A stroke then covers a point it passes over for a length `L` by `1 − (1 − flow)^(L / r)`
/// however densely its dabs lie: a straight stroke's centre (`L` = 2 r) by 44 % at Flow 25, 75 % at
/// Flow 50 and fully at 100, as Lightroom Classic's strokes measure on a grey card (#4045).
pub fn travel_flow(flow: f32, dist: f64, r: f64) -> f32 {
if flow.is_nan() || flow <= 0.0 {
return 0.0;
}
if flow >= 1.0 {
return 1.0;
}
// (a degenerate radius or distance counts one radius; a long jump at most saturates)
let t = if r > 0.0 && dist.is_finite() { (dist / r).clamp(0.0, 64.0) } else { 1.0 };
1.0 - (1.0 - flow).powf(t as f32)
}
/// The radius of a dab of a brush of radius `r` (pixels) painted at pen pressure `p` (0..1): from a tenth of the
@@ -610,7 +693,7 @@ pub fn brush_dabs_within(s: &BrushStroke, frame: &Frame, w: usize, h: usize, max
prev_p = pq;
}
}
BrushDabs {
let bd = BrushDabs {
dabs,
r,
hard,
@@ -619,7 +702,10 @@ pub fn brush_dabs_within(s: &BrushStroke, frame: &Frame, w: usize, h: usize, max
erase: s.erase,
auto: s.auto_mask,
pressure,
}
flows: Vec::new(),
feather_by_stroke: frame.brush_stroke_feather && !s.auto_mask,
};
if frame.brush_flow_per_radius { bd.flow_by_travel() } else { bd }
}
/// Distance between consecutive dabs of a brush of radius `r` (pixels): a quarter of the radius,
@@ -844,6 +930,21 @@ pub fn brush_over_budget(strokes: &[BrushStroke], frame: &Frame, w: usize, h: us
false
}
/// The pixels stroke `bd`'s dabs can reach in a `w × h` output, `(x0, y0, x1, y1)` (end
/// exclusive, empty when it has no dabs): its dabs' centres ± its radius (pen pressure only shrinks it).
fn stroke_bounds(bd: &BrushDabs, w: usize, h: usize) -> (usize, usize, usize, usize) {
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for d in bd.dabs.iter().filter(|d| d.x.is_finite() && d.y.is_finite()) {
(x0, y0, x1, y1) = (x0.min(d.x - bd.r), y0.min(d.y - bd.r), x1.max(d.x + bd.r), y1.max(d.y + bd.r));
}
if x0 > x1 || y0 > y1 {
return (0, 0, 0, 0);
}
let clip = |v: f64, n: usize| v.clamp(0.0, n as f64) as usize;
let (x0, y0) = (clip(x0.floor(), w), clip(y0.floor(), h));
(x0, y0, clip(x1.ceil(), w).max(x0), clip(y1.ceil(), h).max(y0))
}
/// Stamp brush strokes into `out` (max-combine; erase strokes subtract). Auto Mask strokes weight
/// each dab by [`auto_similarity`] to the pixel under its centre and are refined with
/// [`guided_cross`] on log luminance.
@@ -862,6 +963,10 @@ fn rasterize_brush(strokes: &[BrushStroke], frame: &Frame, w: usize, h: usize, i
room = room.saturating_sub(bd.dabs.len());
let (dens, erase, auto) = (bd.density, bd.erase, bd.auto);
let mut stroke_alpha = Plane::new(w, h);
// process V16: the Flow build-up goes in `stroke_alpha`, the edge in `edge` (`feather_dab`)
// (the edge plane covers only the stroke's bounds: a short stroke on a big render is small)
let bounds = stroke_bounds(&bd, w, h);
let mut edge = bd.feather_by_stroke.then(|| Plane::new(bounds.2 - bounds.0, bounds.3 - bounds.1));
for (k, d) in bd.dabs.iter().enumerate() {
let (r, hard, flow) = bd.dab(k);
let refc = auto.then(|| {
@@ -876,14 +981,27 @@ fn rasterize_brush(strokes: &[BrushStroke], frame: &Frame, w: usize, h: usize, i
if dd > r {
continue;
}
let mut a = dab_alpha(dd, r, hard);
let i = y * w + x;
if let Some((rl, rch)) = refc {
a *= auto_similarity(log_l.data[i], chromaticity(img.data[i]), rl, rch);
}
let sim = refc.map_or(1.0, |(rl, rch)| auto_similarity(log_l.data[i], chromaticity(img.data[i]), rl, rch));
let falloff = dab_alpha(dd, r, hard);
let v = &mut stroke_alpha.data[i];
// flow accumulates within a stroke up to density
*v = accumulate(*v, a, flow, dens);
let ei = y.saturating_sub(bounds.1) * (bounds.2 - bounds.0) + x.saturating_sub(bounds.0);
match edge.as_mut().and_then(|e| e.data.get_mut(ei)) {
Some(e) => feather_dab(v, e, falloff, flow),
// flow accumulates within a stroke up to density
None => *v = accumulate(*v, falloff * sim, flow, dens),
}
}
}
}
if let Some(edge) = &edge {
// in place, within the bounds (outside them nothing was painted)
let ew = bounds.2 - bounds.0;
for y in bounds.1..bounds.3 {
for x in bounds.0..bounds.2 {
if let (Some(v), Some(e)) = (stroke_alpha.data.get_mut(y * w + x), edge.data.get((y - bounds.1) * ew + (x - bounds.0))) {
*v = stroke_coverage(*v, *e, dens);
}
}
}
}
+214
View File
@@ -456,6 +456,72 @@ fn holding_the_brush_still_adds_no_coverage() {
assert_eq!(brush_dabs(&paused, &f, w, h).dabs, brush_dabs(&smooth, &f, w, h).dabs);
}
/// A straight Feather 0 stroke of radius 20 px along row 50 of a 400 × 100 frame on `process`.
fn straight_stroke(process: lightcraft_develop::Process, flow: f64, points: Vec<Point>) -> Plane {
let (w, h) = (400, 100);
let d = DevelopSettings { process: process.version(), ..Default::default() };
let f = Frame::new(w, h, &d, true);
let s = BrushStroke { points, size: 0.05, feather: 0.0, flow, ..Default::default() };
shape_alpha(&MaskShape::Brush { strokes: vec![s] }, &f, w, h, &Rgb32f::new(w, h), &Plane::new(w, h), 0.0, None)
}
/// Process V15: Flow is the coverage a stroke adds per brush radius it travels, as Lightroom
/// Classic's strokes measure on a grey card (Feather 0, straight strokes, #4045): a point the brush
/// passes over for a length `L` is covered by `1 − (1 − flow)^(L / r)`, so the centre of a stroke
/// (L = 2 r) by 41 % at Flow 25, 76 % at 50 and fully at 100 (Lightroom), and a point 0.6 radii off
/// the centre line less. Process V14 adds the flow per dab, r/4 apart: 90 % at Flow 25.
#[test]
fn flow_is_coverage_per_radius_travelled_as_in_lightroom() {
use lightcraft_develop::Process;
let line = vec![Point::new(0.1, 0.5), Point::new(0.9, 0.5)];
for (flow, lightroom) in [(25.0, 0.41), (50.0, 0.76), (100.0, 1.0)] {
let a = straight_stroke(Process::V15, flow, line.clone());
let keep = 1.0 - flow as f32 / 100.0;
let centre = a.get(200, 50);
assert!((centre - (1.0 - keep.powi(2))).abs() < 0.03, "Flow {flow}: centre {centre}");
assert!((centre - lightroom).abs() < 0.05, "Flow {flow}: Lightroom covers {lightroom}, here {centre}");
// pixel row 62 is 12.5 px = 0.625 r off the line, under the brush for 2·√(1 − 0.625²) radii
let chord = 2.0 * (1.0 - 0.625f32 * 0.625).sqrt();
let off = a.get(200, 62);
assert!((off - (1.0 - keep.powf(chord))).abs() < 0.05, "Flow {flow}: 0.6 r off the line {off}");
assert!(off <= centre + 1e-6);
}
let old = straight_stroke(Process::V14, 25.0, line).get(200, 50);
assert!(old > 0.85, "V14 keeps the flow per dab: {old}");
}
/// Process V15: a stroke covers the same however densely its samples lie (a slow drag samples
/// every pixel, a fast one far apart); before V15 a slow stroke laid more dabs and built up more.
#[test]
fn flow_does_not_depend_on_how_fast_the_stroke_was_painted() {
use lightcraft_develop::Process;
let fast = vec![Point::new(0.1, 0.5), Point::new(0.9, 0.5)];
// one sample per output pixel
let slow: Vec<Point> = (40..=360).map(|x| Point::new(x as f64 / 400.0, 0.5)).collect();
let (f, s) = (straight_stroke(Process::V15, 25.0, fast.clone()).get(200, 50), straight_stroke(Process::V15, 25.0, slow.clone()).get(200, 50));
assert!((f - s).abs() < 0.02, "fast {f} vs slow {s}");
let (f8, s8) = (straight_stroke(Process::V14, 25.0, fast).get(200, 50), straight_stroke(Process::V14, 25.0, slow).get(200, 50));
assert!(s8 > f8, "before V15 a slow stroke builds up more: {f8} vs {s8}");
}
/// A click (one dab) paints its flow on every process; Flow 100 paints fully.
#[test]
fn a_click_paints_its_flow() {
use lightcraft_develop::Process;
for p in [Process::V14, Process::V15] {
let a = straight_stroke(p, 40.0, vec![Point::new(0.5, 0.5)]);
assert!((a.get(200, 50) - 0.4).abs() < 1e-4, "{p:?}: {}", a.get(200, 50));
}
assert_eq!(travel_flow(1.0, 0.25, 1.0), 1.0);
assert_eq!(travel_flow(0.0, 1.0, 1.0), 0.0);
assert_eq!(travel_flow(f32::NAN, 1.0, 1.0), 0.0);
assert!((travel_flow(0.25, 1.0, 1.0) - 0.25).abs() < 1e-6, "one radius adds the flow");
assert!((travel_flow(0.25, 0.0, 0.0) - 0.25).abs() < 1e-6, "a degenerate radius counts one radius");
assert!((travel_flow(0.25, f64::INFINITY, 1.0) - 0.25).abs() < 1e-6);
assert!(travel_flow(0.25, 1e12, 1.0) > 0.999 && travel_flow(0.25, 1e12, 1.0) <= 1.0);
assert!(travel_flow(0.25, -5.0, 1.0) == 0.0, "no distance adds nothing");
}
/// Flow builds up by passes: going back over an area in the same stroke adds coverage.
#[test]
fn a_second_pass_builds_up_with_low_flow() {
@@ -685,3 +751,151 @@ fn intersect_first_component_selects_its_shape() {
let a = evaluate_one(&m, &f, 100, 100, &img, &l, 0.0, None);
assert!(a.get(50, 50) > 0.99 && a.get(5, 5) < 0.01, "intersect first: {} {}", a.get(50, 50), a.get(5, 5));
}
/// A straight stroke of radius 20 px along y = 50 of a 400 × 100 frame on `process`.
fn feathered_stroke(process: lightcraft_develop::Process, flow: f64, feather: f64) -> Plane {
feathered_stroke_on(&DevelopSettings { process: process.version(), ..Default::default() }, flow, feather)
}
/// [`feathered_stroke`] on settings that were saved and reopened.
fn feathered_stroke_on(d: &DevelopSettings, flow: f64, feather: f64) -> Plane {
let (w, h) = (400, 100);
let f = Frame::new(w, h, d, true);
let s = BrushStroke { points: vec![Point::new(0.1, 0.5), Point::new(0.9, 0.5)], size: 0.05, feather, flow, ..Default::default() };
shape_alpha(&MaskShape::Brush { strokes: vec![s] }, &f, w, h, &Rgb32f::new(w, h), &Plane::new(w, h), 0.0, None)
}
/// Process V16: at Flow 100 a stroke's edge falls off over the feather exactly as one dab's does;
/// V1 to V15 accumulate the soft edges of overlapping dabs (r/4 apart) into a nearly hard one.
#[test]
fn a_stroke_is_feathered_as_one_dab_is() {
use lightcraft_develop::Process;
let r = 20.0;
for feather in [100.0, 50.0] {
let hard = r * (1.0 - feather / 100.0);
let new = feathered_stroke(Process::V16, 100.0, feather);
let old = feathered_stroke(Process::V15, 100.0, feather);
// rows below the line: pixel centre y + 0.5 is that far from it
for row in 50..72 {
let dd = row as f64 + 0.5 - 50.0;
let want = dab_alpha(dd, r, hard);
let got = new.get(200, row);
assert!((got - want).abs() < 0.02, "Feather {feather}: {dd} px off the line, {got} where one dab paints {want}");
assert!(old.get(200, row) >= got - 1e-6, "V15 is never the softer");
}
// halfway out at Feather 100 one dab paints 0.5; V15's stroke about 0.9
if feather == 100.0 {
assert!((new.get(200, 60) - 0.5).abs() < 0.05, "{}", new.get(200, 60));
assert!(old.get(200, 60) > 0.85, "V15 keeps its hard edge: {}", old.get(200, 60));
}
}
}
/// Process V16 below Flow 100: the centre builds up by Flow per radius travelled whatever the
/// feather, as a hard brush's does under V15 (`1 − (1 − flow)²` for a straight stroke, 44 % at Flow 25,
/// as Lightroom Classic measures, #4045), and the feather shapes only the edge. Under V15 a soft
/// brush's falloff also weakened its centre (25 % at Flow 25), as each dab's flow was scaled by it.
#[test]
fn below_full_flow_the_centre_builds_up_whatever_the_feather_and_the_edge_falls_off() {
use lightcraft_develop::Process;
for flow in [25.0, 50.0] {
let new = feathered_stroke(Process::V16, flow, 100.0);
let hard = feathered_stroke(Process::V16, flow, 0.0);
let want = 1.0 - (1.0 - flow as f32 / 100.0).powi(2);
let n = new.get(200, 50);
assert!((n - want).abs() < 0.03, "Flow {flow}: centre {n}, {want} by Flow per radius travelled");
assert!((n - hard.get(200, 50)).abs() < 0.03, "Flow {flow}: as a hard brush's centre");
for row in 51..72 {
assert!(new.get(200, row) <= new.get(200, row - 1) + 1e-6, "Flow {flow}: falls off away from the line (row {row})");
assert!(new.get(200, row) <= hard.get(200, row) + 1e-6, "Flow {flow}: never more than the hard brush (row {row})");
}
}
let old = feathered_stroke(Process::V15, 25.0, 100.0).get(200, 50);
assert!(old < 0.3, "V15's soft brush is weaker at its centre: {old}");
}
/// A hard brush (Feather 0) paints the same on V15 and V16.
#[test]
fn a_hard_brush_is_unchanged_by_the_stroke_feather() {
use lightcraft_develop::Process;
for flow in [25.0, 100.0] {
assert_eq!(feathered_stroke(Process::V16, flow, 0.0).data, feathered_stroke(Process::V15, flow, 0.0).data, "Flow {flow}");
}
}
/// Process V16: a dab with no Flow (pen pressure 0) neither builds up nor sets the edge.
#[test]
fn a_dab_with_no_flow_shapes_nothing() {
let (mut build, mut edge) = (0.2, 0.3);
feather_dab(&mut build, &mut edge, 1.0, 0.0);
assert_eq!((build, edge), (0.2, 0.3));
feather_dab(&mut build, &mut edge, 0.6, 0.5);
assert!((build - 0.6).abs() < 1e-6 && (edge - 0.6).abs() < 1e-6, "{build} {edge}");
}
/// An Auto Mask stroke keeps V15's accumulation on V16: its edge follows the photo, not the feather.
#[test]
fn an_auto_mask_stroke_keeps_v9_accumulation() {
use lightcraft_develop::Process;
let (w, h) = (400, 100);
let img = Rgb32f::new(w, h);
let paint = |p: Process| {
let d = DevelopSettings { process: p.version(), ..Default::default() };
let f = Frame::new(w, h, &d, true);
let s = BrushStroke {
points: vec![Point::new(0.1, 0.5), Point::new(0.9, 0.5)],
size: 0.05,
feather: 100.0,
auto_mask: true,
..Default::default()
};
assert!(!brush_dabs(&s, &f, w, h).feather_by_stroke);
shape_alpha(&MaskShape::Brush { strokes: vec![s] }, &f, w, h, &img, &Plane::new(w, h), 0.0, None)
};
assert_eq!(paint(Process::V16).data, paint(Process::V15).data);
}
/// Process V16's edge plane covers only the stroke's bounds: a stroke across the corner of the
/// frame and one in the middle paint as a full-frame plane would (nothing outside the bounds).
#[test]
fn the_stroke_bounds_hold_every_dab() {
let (w, h) = (400, 100);
let d = DevelopSettings::default();
let f = Frame::new(w, h, &d, true);
for points in [vec![Point::new(-0.05, -0.1), Point::new(0.1, 0.2)], vec![Point::new(0.4, 0.5), Point::new(0.6, 0.55)]] {
let s = BrushStroke { points, size: 0.05, feather: 100.0, ..Default::default() };
let bd = brush_dabs(&s, &f, w, h);
let (x0, y0, x1, y1) = stroke_bounds(&bd, w, h);
assert!(x0 <= x1 && y0 <= y1 && x1 <= w && y1 <= h);
let a = shape_alpha(&MaskShape::Brush { strokes: vec![s] }, &f, w, h, &Rgb32f::new(w, h), &Plane::new(w, h), 0.0, None);
for y in 0..h {
for x in 0..w {
if !(x0..x1).contains(&x) || !(y0..y1).contains(&y) {
assert_eq!(a.get(x, y), 0.0, "({x}, {y}) outside {:?}", (x0, y0, x1, y1));
}
}
}
assert!(a.data.iter().any(|v| *v > 0.5), "it painted");
}
assert_eq!(stroke_bounds(&brush_dabs(&BrushStroke::default(), &f, w, h), w, h), (0, 0, 0, 0), "no dabs");
}
/// A saved photo keeps its brush look: strokes saved on V8 (or 9), V10 (11, 12), V13 or V14 reopen
/// on that process and render Flow per dab with every dab's falloff accumulated, as before V15; V15
/// keeps the accumulated edge; only V16 feathers the stroke as one dab.
#[test]
fn a_saved_process_keeps_its_brush_look() {
let saved = |n: u32| DevelopSettings::from_json(&serde_json::json!({ "process": n })).unwrap();
for (flow, feather) in [(100.0, 100.0), (25.0, 100.0), (50.0, 60.0)] {
let before = feathered_stroke_on(&saved(14), flow, feather);
for n in [8, 9, 10, 11, 12, 13] {
assert_eq!(feathered_stroke_on(&saved(n), flow, feather).data, before.data, "saved V{n}: Flow {flow}, Feather {feather}");
}
let per_radius = feathered_stroke_on(&saved(15), flow, feather);
let by_stroke = feathered_stroke_on(&saved(16), flow, feather);
if flow < 100.0 {
assert_ne!(per_radius.data, before.data, "V15 builds up Flow per radius travelled (Flow {flow})");
}
assert_ne!(by_stroke.data, per_radius.data, "V16 feathers the stroke (Flow {flow}, Feather {feather})");
}
}
+152 -70
View File
@@ -436,84 +436,120 @@ fn pinned_distances(l: &SpotLayout, method: HealMethod) -> Vec<f32> {
/// is [`HealMethod::of`] the photo's settings.
pub fn apply(img: &mut Rgb32f, spots: &[Spot], frame: &Frame, ppl: f64, method: HealMethod) {
let (w, h) = (img.width, img.height);
let pinned = method == HealMethod::Pinned;
for spot in spots {
let Some(l) = layout(spot, frame, w, h, ppl) else {
continue;
};
// (empty unless the pinned heal will use it: a box too big for its working memory gets the
// averaged heal without the plane being built)
let dist = pinned_distances(&l, method);
let pinned_heal = !dist.is_empty();
let SpotLayout { r, pts, offset, bx: bx0, by: by0, bw, bh, inner, opacity, heal, fill } = l;
let Some(&first) = pts.first() else { continue };
let offset = offset.unwrap_or_else(|| auto_source(img, first, r));
// (V14 reads whole pixels: between them, bilinear sampling averages the source's grain away)
let offset = if pinned { (offset.0.round(), offset.1.round()) } else { offset };
// alpha of the stroke and the source patch in the box
let mut alpha = vec![0.0f32; bw * bh];
let mut src = vec![[0.0f32; 3]; bw * bh];
let mut tgt = vec![[0.0f32; 3]; bw * bh];
for y in 0..bh {
for x in 0..bw {
let (px, py) = ((bx0 + x) as f32 + 0.5, (by0 + y) as f32 + 0.5);
let d = dist.get(y * bw + x).copied().unwrap_or_else(|| distance(&pts, px, py));
alpha[y * bw + x] = (1.0 - smooth(inner, r, d)) * opacity;
src[y * bw + x] = img.sample_bilinear(px + offset.0, py + offset.1);
tgt[y * bw + x] = img.get(bx0 + x, by0 + y);
}
let Some(&first) = l.pts.first() else { continue };
let offset = l.offset.unwrap_or_else(|| auto_source(img, first, l.r));
apply_spot(img, (0, 0), l, offset, method);
}
}
/// The pixels [`apply_spot`] reads for `l` with source `offset` in a `w × h` output: the spot's box
/// and its source patch (whole pixels under [`HealMethod::Pinned`], also the bilinear neighbour
/// otherwise), clamped to the image, as [x0, y0, x1, y1). A source past the image's edge reads the
/// edge pixel, which the clamped rectangle holds, so a crop of it renders as the whole image does.
pub fn spot_reads(l: &SpotLayout, offset: (f32, f32), method: HealMethod, w: usize, h: usize) -> [usize; 4] {
let whole = [0, 0, w, h];
let t = [l.bx, l.by, l.bx + l.bw, l.by + l.bh].map(|v| v as f64);
let reach = |d: f32| {
let d = f64::from(d);
match method {
HealMethod::Pinned => (d.round(), d.round()),
HealMethod::Averaged => (d.floor(), d.ceil() + 1.0),
}
if fill {
fill_box(&mut src, &tgt, &alpha, bw, bh);
};
let ((x0, x1), (y0, y1)) = (reach(offset.0), reach(offset.1));
let s = [t[0] + x0, t[1] + y0, t[2] + x1, t[3] + y1];
if !s.iter().all(|v| v.is_finite()) {
return whole;
}
// (a pixel more on every side)
let r = [t[0].min(s[0]) - 1.0, t[1].min(s[1]) - 1.0, t[2].max(s[2]) + 1.0, t[3].max(s[3]) + 1.0];
// Where the source lies past the image's edge, this clamps to the edge itself: `sample_bilinear`
// clamps its coordinate to the image and reads the edge pixel there, and so does a crop that
// starts or ends on that edge.
let clamp = |v: f64, hi: usize| v.clamp(0.0, hi as f64) as usize;
[clamp(r[0], w), clamp(r[1], h), clamp(r[2], w), clamp(r[3], h)]
}
/// One spot of [`apply`] on `img`, a crop of the output whose pixel (0, 0) is output pixel `origin`;
/// `l` is in output pixels and `offset` is the resolved source offset (auto-chosen already when the
/// spot's is `None`). The crop must hold [`spot_reads`] of the spot.
pub fn apply_spot(img: &mut Rgb32f, origin: (usize, usize), l: SpotLayout, offset: (f32, f32), method: HealMethod) {
let pinned = method == HealMethod::Pinned;
// (empty unless the pinned heal will use it: a box too big for its working memory gets the
// averaged heal without the plane being built)
let dist = pinned_distances(&l, method);
let pinned_heal = !dist.is_empty();
let SpotLayout { r, pts, bx: bx0, by: by0, bw, bh, inner, opacity, heal, fill, .. } = l;
// (V14 reads whole pixels: between them, bilinear sampling averages the source's grain away)
let offset = if pinned { (offset.0.round(), offset.1.round()) } else { offset };
let (ox, oy) = origin;
// alpha of the stroke and the source patch in the box
let mut alpha = vec![0.0f32; bw * bh];
let mut src = vec![[0.0f32; 3]; bw * bh];
let mut tgt = vec![[0.0f32; 3]; bw * bh];
for y in 0..bh {
for x in 0..bw {
let (px, py) = ((bx0 + x) as f32 + 0.5, (by0 + y) as f32 + 0.5);
let d = dist.get(y * bw + x).copied().unwrap_or_else(|| distance(&pts, px, py));
alpha[y * bw + x] = (1.0 - smooth(inner, r, d)) * opacity;
src[y * bw + x] = img.sample_bilinear(px + offset.0 - ox as f32, py + offset.1 - oy as f32);
tgt[y * bw + x] = img.get(bx0 + x - ox, by0 + y - oy);
}
let healed = if pinned_heal { pinned::heal(&pinned::Patch { w: bw, h: bh, src: &src, tgt: &tgt, dist: &dist, r }) } else { None };
let pinned_here = healed.is_some();
if let Some(healed) = healed {
src = healed;
}
let low = if heal && !pinned_here {
// Tone correction from the spot's *surroundings* only: normalized convolution of
// (target − source) over pixels outside the stroke (a membrane-like interpolation).
let outside: Vec<f32> = alpha.iter().map(|a| if *a < 0.02 { 1.0 } else { 0.0 }).collect();
let diff = Rgb32f {
width: bw,
height: bh,
data: tgt.iter().zip(&src).zip(&outside).map(|((t, s), m)| [(t[0] - s[0]) * m, (t[1] - s[1]) * m, (t[2] - s[2]) * m]).collect(),
};
let wts = lightcraft_raster::Plane { width: bw, height: bh, data: outside };
let sigma = (r * 0.6).max(1.0);
let (bd, bm) = (lightcraft_raster::blur::gaussian(&diff, sigma), lightcraft_raster::blur::gaussian(&wts, sigma));
Some(Rgb32f {
width: bw,
height: bh,
data: bd
.data
.iter()
.zip(&bm.data)
.map(|(d, m)| {
let m = m.max(1e-4);
[d[0] / m, d[1] / m, d[2] / m]
})
.collect(),
})
} else {
None
}
if fill {
fill_box(&mut src, &tgt, &alpha, bw, bh);
}
let healed = if pinned_heal { pinned::heal(&pinned::Patch { w: bw, h: bh, src: &src, tgt: &tgt, dist: &dist, r }) } else { None };
let pinned_here = healed.is_some();
if let Some(healed) = healed {
src = healed;
}
let low = if heal && !pinned_here {
// Tone correction from the spot's *surroundings* only: normalized convolution of
// (target − source) over pixels outside the stroke (a membrane-like interpolation).
let outside: Vec<f32> = alpha.iter().map(|a| if *a < 0.02 { 1.0 } else { 0.0 }).collect();
let diff = Rgb32f {
width: bw,
height: bh,
data: tgt.iter().zip(&src).zip(&outside).map(|((t, s), m)| [(t[0] - s[0]) * m, (t[1] - s[1]) * m, (t[2] - s[2]) * m]).collect(),
};
for y in 0..bh {
for x in 0..bw {
let i = y * bw + x;
let a = alpha[i];
if a <= 0.0 {
continue;
}
let mut v = src[i];
if let Some(l) = &low {
let d = l.data[i];
v = [v[0] + d[0], v[1] + d[1], v[2] + d[2]];
}
let t = tgt[i];
img.set(bx0 + x, by0 + y, [t[0] + (v[0] - t[0]) * a, t[1] + (v[1] - t[1]) * a, t[2] + (v[2] - t[2]) * a].map(|c| c.max(0.0)));
let wts = lightcraft_raster::Plane { width: bw, height: bh, data: outside };
let sigma = (r * 0.6).max(1.0);
let (bd, bm) = (lightcraft_raster::blur::gaussian(&diff, sigma), lightcraft_raster::blur::gaussian(&wts, sigma));
Some(Rgb32f {
width: bw,
height: bh,
data: bd
.data
.iter()
.zip(&bm.data)
.map(|(d, m)| {
let m = m.max(1e-4);
[d[0] / m, d[1] / m, d[2] / m]
})
.collect(),
})
} else {
None
};
for y in 0..bh {
for x in 0..bw {
let i = y * bw + x;
let a = alpha[i];
if a <= 0.0 {
continue;
}
let mut v = src[i];
if let Some(l) = &low {
let d = l.data[i];
v = [v[0] + d[0], v[1] + d[1], v[2] + d[2]];
}
let t = tgt[i];
img.set(bx0 + x - ox, by0 + y - oy, [t[0] + (v[0] - t[0]) * a, t[1] + (v[1] - t[1]) * a, t[2] + (v[2] - t[2]) * a].map(|c| c.max(0.0)));
}
}
}
@@ -595,6 +631,52 @@ mod tests {
}
}
/// Each spot on a crop of what [`spot_reads`] says it reads gives the same pixels in its box as
/// [`apply`] on the whole image: Heal and Clone, either heal, and a spot cut by the edge whose
/// source lies past it.
#[test]
fn a_spot_on_its_reads_matches_the_whole_image() {
let (w, h) = (96, 64);
let frame = Frame::new(w, h, &DevelopSettings::default(), true);
let ppl = frame.px_per_long(w);
let spot = |mode, x: f64, y: f64, off: (f64, f64)| Spot {
mode,
points: vec![Point::new(x, y)],
size: 6.0 / w as f64,
feather: 50.0,
opacity: 100.0,
source_offset: Some(Point::new(off.0, off.1)),
};
let spots = [
spot(SpotMode::Heal, 0.5, 0.5, (0.17, 0.06)),
spot(SpotMode::Clone, 0.3, 0.4, (-0.11, 0.13)),
spot(SpotMode::Heal, 0.99, 0.02, (-0.2, 0.2)),
spot(SpotMode::Heal, 0.03, 0.9, (-0.4, 0.3)),
];
for method in BOTH {
for spot in &spots {
let original = Rgb32f::from_fn(w, h, |x, y| {
[0.2 + (x * 7 % 13) as f32 / 40.0, 0.1 + (y * 5 % 11) as f32 / 30.0, 0.3 + ((x + y) % 5) as f32 / 20.0]
});
let mut whole = original.clone();
apply(&mut whole, std::slice::from_ref(spot), &frame, ppl, method);
let l = layout(spot, &frame, w, h, ppl).expect("on the image");
let offset = l.offset.expect("manual source");
let [x0, y0, x1, y1] = spot_reads(&l, offset, method, w, h);
let mut crop = Rgb32f::from_fn(x1 - x0, y1 - y0, |x, y| original.get(x0 + x, y0 + y));
let (bx, by, bw, bh) = (l.bx, l.by, l.bw, l.bh);
apply_spot(&mut crop, (x0, y0), l, offset, method);
let mut pasted = original.clone();
for y in by..by + bh {
for x in bx..bx + bw {
pasted.set(x, y, crop.get(x - x0, y - y0));
}
}
assert_eq!(pasted.data, whole.data, "{:?} spot at {:?} ({method:?})", spot.mode, spot.points[0]);
}
}
}
/// Vertical stripes (period `period` px) with a black blot over the middle.
fn striped_with_blot(w: usize, h: usize, period: usize) -> Rgb32f {
let mut img = Rgb32f::from_fn(w, h, |x, _| if (x / period).is_multiple_of(2) { [0.2; 3] } else { [0.7; 3] });
+4 -2
View File
@@ -301,8 +301,10 @@ mod tests {
for p in [Process::V8, Process::V10, Process::V13] {
assert_eq!(HealMethod::of(&on(p)), HealMethod::Averaged, "{p:?}");
}
assert_eq!(HealMethod::of(&on(Process::V14)), HealMethod::Pinned);
assert_eq!(Process::LATEST, Process::V14);
// V14 and every later process keep the pinned heal
for p in Process::ALL.into_iter().filter(|p| *p >= Process::V14) {
assert_eq!(HealMethod::of(&on(p)), HealMethod::Pinned, "{p:?}");
}
assert_eq!(HealMethod::of(&DevelopSettings::default()), HealMethod::Pinned, "new photos get the latest process");
}
+3 -1
View File
@@ -35,7 +35,9 @@ fn processes_before_v7_keep_the_value_noise() {
Process::V1 | Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 => {
assert!(matches!(model, Some(GrainModel::Value(_))), "{p:?}")
}
Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 => assert!(matches!(model, Some(GrainModel::Crystal(_))), "{p:?}"),
Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 | Process::V15 | Process::V16 => {
assert!(matches!(model, Some(GrainModel::Crystal(_))), "{p:?}")
}
}
assert!(GrainModel::new(&on(p, 0.0), 2000.0, false).is_none(), "{p:?}: no grain at Amount 0");
}
+2 -1
View File
@@ -44,7 +44,8 @@ lightcraft-denoise = { workspace = true, features = ["runtime"] }
lightcraft-codecs = { workspace = true }
lightcraft-faces = { workspace = true }
lightcraft-merge = { workspace = true }
# a device for the GPU-resident view test (`render.rs`)
# a device for the GPU-resident view test (`render.rs`): the render device (`shared_device`)
lightcraft-gpu = { workspace = true, features = ["test-support"] }
pollster = { workspace = true }
[build-dependencies]
+15
View File
@@ -821,6 +821,21 @@ impl LightcraftApp {
}
}
/// The app's first frame starts the GPU device warm-up (`app.gpu`), on a thread that loads the
/// driver. A process that ends while it does crashes inside the driver (issue #620; in CI, tests
/// killed by SIGSEGV after they had passed). The window ends through [`LightcraftApp::shutdown`],
/// which decides that itself; any other end (a test returning, a headless run) passes through here
/// first, so it waits for the warm-up, bounded. (Native only: there is no warm-up thread on the web,
/// and the web host moves fields out of the app.)
#[cfg(not(target_arch = "wasm32"))]
impl Drop for LightcraftApp {
fn drop(&mut self) {
if !lightcraft_engine::gpu::shutting_down() {
let _ = lightcraft_engine::gpu::wait_warm_up(std::time::Duration::from_secs(30));
}
}
}
/// "Found 3 faces in 2 photos" for a `faces.detect` result.
pub(crate) fn detect_summary(v: &Value) -> String {
let photos = v["photos"].as_array().map(Vec::as_slice).unwrap_or_default();
+103 -9
View File
@@ -9,7 +9,9 @@
use egui::{Color32, ColorImage, Pos2, Rect, TextureHandle, TextureOptions, pos2};
use lightcraft_geom::Point;
use lightcraft_pipeline::masks::{accumulate, dab_alpha, pressure_flow, pressure_radius, push_dabs_counted, push_pressures};
use lightcraft_pipeline::masks::{
accumulate, dab_alpha, feather_dab, pressure_flow, pressure_radius, push_dabs_counted, push_pressures, stroke_coverage, travel_flow,
};
/// The largest live-stroke buffer edge (pixels); a bigger canvas is painted at a lower resolution.
const MAX_SIDE: usize = 4096;
@@ -28,6 +30,12 @@ pub struct LiveParams {
/// Flow and density, 0..1.
pub flow: f32,
pub density: f32,
/// Flow is coverage per brush radius travelled (process V15, `masks::flow_per_radius`), as the
/// committed stroke paints it.
pub per_radius: bool,
/// The stroke's edge is feathered as one dab's is (process V16, `masks::stroke_feather`), as
/// the committed stroke paints it.
pub by_stroke: bool,
/// Overlay colour and its opacity (0..1) at full coverage.
pub color: [u8; 3],
pub opacity: f32,
@@ -39,6 +47,9 @@ pub struct LiveStroke {
w: usize,
h: usize,
alpha: Vec<f32>,
/// Under `by_stroke`, the Flow build-up and the edge `alpha` is made of (`masks::feather_dab`).
build: Vec<f32>,
edge: Vec<f32>,
/// Samples stamped so far, and the last one (buffer pixels).
placed: usize,
/// Total dabs emitted across every stamp, including the first sample.
@@ -46,6 +57,8 @@ pub struct LiveStroke {
last: Option<Point>,
/// The pen pressure of the last stamped sample.
last_pressure: f32,
/// The last dab painted (buffer pixels): how far the next one travelled.
last_dab: Option<Point>,
/// Buffer pixels painted since the last upload: (x0, y0, x1, y1), exclusive ends.
dirty: Option<(usize, usize, usize, usize)>,
texture: Option<TextureHandle>,
@@ -56,7 +69,21 @@ impl LiveStroke {
let scale = buffer_scale(params.clip, params.scale);
let params = LiveParams { scale, ..params };
let (w, h) = buffer_size(params.clip, scale);
LiveStroke { params, w, h, alpha: vec![0.0; w * h], placed: 0, emitted: 0, last: None, last_pressure: 1.0, dirty: None, texture: None }
LiveStroke {
params,
w,
h,
alpha: vec![0.0; w * h],
build: if params.by_stroke { vec![0.0; w * h] } else { Vec::new() },
edge: if params.by_stroke { vec![0.0; w * h] } else { Vec::new() },
placed: 0,
emitted: 0,
last: None,
last_pressure: 1.0,
last_dab: None,
dirty: None,
texture: None,
}
}
/// Stroke coverage (0..1) at buffer pixel `(x, y)`; 0 outside.
@@ -80,7 +107,7 @@ impl LiveStroke {
if new.is_empty() {
return false;
}
let LiveParams { clip, scale, r, hard, flow, density, .. } = self.params;
let LiveParams { clip, scale, r, hard, flow, density, per_radius, by_stroke, .. } = self.params;
let (r, hard) = ((r * scale) as f64, (hard * scale) as f64);
let mut dabs = Vec::new();
let mut pressures = Vec::new();
@@ -105,6 +132,10 @@ impl LiveStroke {
let r = pressure_radius(base.0, p);
let hard = if base.0 > 0.0 { base.1 * r / base.0 } else { base.1 };
let flow = pressure_flow(flow, p);
// the first dab counts one radius, as the committed stroke's does
let travelled = self.last_dab.map_or(r, |a| a.dist(d));
self.last_dab = Some(d);
let flow = if per_radius { travel_flow(flow, travelled, r) } else { flow };
let x0 = (d.x - r).floor().clamp(0.0, self.w as f64) as usize;
let x1 = (d.x + r).ceil().clamp(0.0, self.w as f64) as usize;
let y0 = (d.y - r).floor().clamp(0.0, self.h as f64) as usize;
@@ -113,13 +144,29 @@ impl LiveStroke {
continue;
}
for y in y0..y1 {
let Some(row) = self.alpha.get_mut(y * self.w + x0..y * self.w + x1) else { continue };
for (x, v) in (x0..x1).zip(row.iter_mut()) {
let dd = Point::new(x as f64 + 0.5, y as f64 + 0.5).dist(d);
if dd > r {
continue;
let span = y * self.w + x0..y * self.w + x1;
let Some(row) = self.alpha.get_mut(span.clone()) else { continue };
let (build, edge) = (self.build.get_mut(span.clone()), self.edge.get_mut(span));
match (build, edge) {
(Some(build), Some(edge)) if by_stroke => {
for (x, ((v, b), e)) in (x0..x1).zip(row.iter_mut().zip(build.iter_mut()).zip(edge.iter_mut())) {
let dd = Point::new(x as f64 + 0.5, y as f64 + 0.5).dist(d);
if dd > r {
continue;
}
feather_dab(b, e, dab_alpha(dd, r, hard), flow);
*v = stroke_coverage(*b, *e, density);
}
}
_ => {
for (x, v) in (x0..x1).zip(row.iter_mut()) {
let dd = Point::new(x as f64 + 0.5, y as f64 + 0.5).dist(d);
if dd > r {
continue;
}
*v = accumulate(*v, dab_alpha(dd, r, hard), flow, density);
}
}
*v = accumulate(*v, dab_alpha(dd, r, hard), flow, density);
}
}
self.dirty = Some(match self.dirty {
@@ -220,12 +267,34 @@ mod tests {
hard: 5.0,
flow: 1.0,
density: 1.0,
per_radius: true,
by_stroke: false,
color: [230, 30, 40],
opacity: 0.5,
}
}
/// Issue #517: two samples far apart (a fast stroke) paint a continuous band between them,
/// Process V15: the live stroke adds Flow per brush radius travelled, as the committed one does,
/// so a slow drag (a sample every point) and a fast one cover a point the same; a stroke's centre
/// at Flow 25 is covered by 1 − 0.75² (Feather 0 here). Before V15 the slow drag built up more.
#[test]
fn flow_per_radius_does_not_depend_on_the_drag_speed() {
let p = LiveParams { flow: 0.25, hard: 10.0, ..params() };
let paint = |per_radius: bool, step: usize| {
let mut s = LiveStroke::new(LiveParams { per_radius, ..p });
let pts: Vec<Pos2> = (20..=380).step_by(step).map(|x| pos2(x as f32, 100.0)).collect();
for n in 1..=pts.len() {
s.stamp(&pts[..n], &[]);
}
s.coverage(200, 100)
};
let (fast, slow) = (paint(true, 360), paint(true, 1));
assert!((fast - 0.4375).abs() < 0.03, "{fast}");
assert!((fast - slow).abs() < 0.02, "fast {fast} vs slow {slow}");
assert!(paint(false, 1) > paint(false, 360), "before V15 a slow drag builds up more");
}
/// not two separate dabs.
#[test]
fn a_fast_segment_is_painted_continuously() {
@@ -241,6 +310,31 @@ mod tests {
assert_eq!(s.coverage(200, 111), 0.0);
}
/// Process V16 (`by_stroke`): the live stroke's edge falls off over the feather as one dab's
/// does, as the committed stroke's does (`masks::stroke_coverage`), where accumulating every
/// dab piles the soft edges up; stamped a frame at a time it is the same.
#[test]
fn by_stroke_the_live_edge_is_feathered_as_one_dab() {
let soft = LiveParams { hard: 0.0, by_stroke: true, ..params() };
let mut s = LiveStroke::new(soft);
s.stamp(&[pos2(20.0, 100.0), pos2(380.0, 100.0)], &[]);
for dy in 0..10 {
let want = dab_alpha(dy as f64 + 0.5, 10.0, 0.0);
let got = s.coverage(200, 100 + dy);
assert!((got - want).abs() < 0.02, "{dy} px off the line: {got}, one dab paints {want}");
}
let mut old = LiveStroke::new(LiveParams { by_stroke: false, ..soft });
old.stamp(&[pos2(20.0, 100.0), pos2(380.0, 100.0)], &[]);
assert!(old.coverage(200, 105) > s.coverage(200, 105) + 0.2, "{} vs {}", old.coverage(200, 105), s.coverage(200, 105));
let pts = [pos2(30.0, 40.0), pos2(200.0, 150.0), pos2(390.0, 20.0)];
let (mut once, mut steps) = (LiveStroke::new(LiveParams { flow: 0.4, ..soft }), LiveStroke::new(LiveParams { flow: 0.4, ..soft }));
once.stamp(&pts, &[]);
for n in 1..=pts.len() {
steps.stamp(&pts[..n], &[]);
}
assert_eq!(once.alpha, steps.alpha);
}
/// Painting the samples one frame at a time gives the same coverage as all at once (what the
/// committed stroke does).
#[test]
+3
View File
@@ -868,6 +868,7 @@ fn dialog_title(app: &LightcraftApp, dlg: &Dialog) -> String {
Dialog::SlideshowExport { .. } => "Export Slideshow",
Dialog::Print => "Print",
Dialog::Merge { opts } => opts.title(),
Dialog::MergeResult { .. } => "Photo Merge Result",
Dialog::Settings { .. } => "Settings",
Dialog::ConfirmDelete { .. } => "Delete Photos",
Dialog::MovePhotos { .. } => "Move Photos",
@@ -1015,6 +1016,7 @@ fn fixed_ok_label(app: &LightcraftApp, dlg: &Dialog, informational: bool) -> &'s
| Dialog::WhatsNew
| Dialog::ManageEffects { .. }
| Dialog::ViewOptions
| Dialog::MergeResult { .. }
| Dialog::LightroomResult { .. }
| Dialog::DenoiseModel { .. }
| Dialog::FaceModel { .. } => "Close",
@@ -2126,6 +2128,7 @@ fn dialog_content(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, body_m
Dialog::ContactSheet { .. } => contact_sheet_body(app, ui, dlg),
Dialog::Export { .. } => export_body(app, ui, t, dlg),
Dialog::Merge { opts } => crate::merge::body(app, ui, opts),
Dialog::MergeResult { summary, omitted } => crate::merge::result_body(ui, summary, omitted),
Dialog::Import { opts } => crate::import::body(app, ui, opts),
// (Settings is never taller than `body_max`, so the scroll area round it never
// scrolls: its tab bar stays put and its pages scroll by themselves)
+6 -3
View File
@@ -263,8 +263,11 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result<serde_jso
Dialog::DeleteEffects { names } => app.run("mask.deleteEffect", json!({"names": names})),
Dialog::RemoveFolder { path, disk, .. } => app.run("library.removeFolder", json!({"path": path, "disk": disk})),
d @ Dialog::SynchronizeFolder { .. } => crate::sync::confirm(app, d),
Dialog::About | Dialog::Shortcuts | Dialog::Settings { .. } | Dialog::ManageEffects { .. } | Dialog::ViewOptions => {
Ok(serde_json::Value::Null)
}
Dialog::About
| Dialog::Shortcuts
| Dialog::Settings { .. }
| Dialog::ManageEffects { .. }
| Dialog::ViewOptions
| Dialog::MergeResult { .. } => Ok(serde_json::Value::Null),
}
}
+1
View File
@@ -213,5 +213,6 @@ pub(super) fn only_shows(dlg: &Dialog) -> bool {
| Dialog::Welcome { .. }
| Dialog::ManageEffects { .. }
| Dialog::ViewOptions
| Dialog::MergeResult { .. }
) || matches!(dlg, Dialog::SynchronizeFolder { counts: Some(c), .. } if c.up_to_date())
}
+104 -19
View File
@@ -123,6 +123,8 @@ pub struct MergeState {
pub ids: Vec<PhotoId>,
/// HDR for Each Bracket Set: the sets still to merge after the running one.
pub batch: std::collections::VecDeque<Vec<PhotoId>>,
/// A finished panorama's list of omitted photos, waiting for the dialog open when it finished to close.
pub pending_result: Option<crate::state::Dialog>,
}
impl MergeState {
@@ -167,22 +169,28 @@ pub fn last_options(app: &LightcraftApp, command: &str) -> MergeDialog {
MergeDialog { command: command.into(), ..saved.unwrap_or_default() }
}
/// Open the merge dialog for the selection, with the options of the last merge of this kind.
pub fn open(app: &mut LightcraftApp, command: &str) -> Result<Value, String> {
let ids = app.session.selected();
if ids.len() < 2 {
return Err("select at least 2 photos to merge".into());
}
/// Set the photos the dialog merges. A preview of other photos is dropped and its task cancelled: the dialog compares
/// a preview's options only, so it would go on describing the photos it was made from.
fn set_ids(app: &mut LightcraftApp, ids: Vec<PhotoId>) {
app.merge.ids = ids;
app.merge.error = None;
// a preview that failed before is tried again, or the dialog would show neither a preview nor its error (#2708)
app.merge.failed_options = None;
app.merge.preview = None;
app.merge.preview_pixels = None;
app.merge.zoom = None;
if let Some(t) = app.merge.preview_task.take() {
t.cancel.store(true, Ordering::Relaxed);
}
}
/// Open the merge dialog for the selection, with the options of the last merge of this kind.
pub fn open(app: &mut LightcraftApp, command: &str) -> Result<Value, String> {
let ids = app.session.selected();
if ids.len() < 2 {
return Err("select at least 2 photos to merge".into());
}
set_ids(app, ids);
app.merge.error = None;
// a preview that failed before is tried again, or the dialog would show neither a preview nor its error (#2708)
app.merge.failed_options = None;
app.ui.dialog = Some(crate::state::Dialog::Merge { opts: last_options(app, command) });
Ok(json!({"photos": app.merge.ids.len()}))
}
@@ -216,7 +224,7 @@ pub fn start_last(app: &mut LightcraftApp, command: &str) -> Result<Value, Strin
if ids.len() < 2 {
return Err("select at least 2 photos to merge".into());
}
app.merge.ids = ids;
set_ids(app, ids);
let opts = last_options(app, command);
start_final(app, &opts)
}
@@ -241,7 +249,7 @@ pub fn start_batch(app: &mut LightcraftApp, p: &Value) -> Result<Value, String>
/// Start the next bracket set of a batch, if any.
fn next_in_batch(app: &mut LightcraftApp) -> Result<(), String> {
let Some(ids) = app.merge.batch.pop_front() else { return Ok(()) };
app.merge.ids = ids;
set_ids(app, ids);
let opts = last_options(app, "merge.hdr");
start_final(app, &opts).map(|_| ())
}
@@ -320,11 +328,7 @@ pub fn poll(app: &mut LightcraftApp, ctx: &egui::Context) {
"HDR"
});
match r.map_err(lightcraft_engine::EngineError::Other).and_then(|out| app.session.finish_merge(&t.job, out)) {
Ok(v) => {
let message = added_message(what, &v);
app.merge.last_result = Some(v);
app.toast(ctx, message);
}
Ok(v) => finished(app, ctx, what, v),
Err(_) if t.cancel.load(Ordering::Relaxed) => {
// cancelling one merge of a batch stops the batch
app.merge.batch.clear();
@@ -354,13 +358,47 @@ pub fn poll(app: &mut LightcraftApp, ctx: &egui::Context) {
}
}
}
// (never over a dialog the user has open: it waits until that one closes)
if app.ui.dialog.is_none()
&& let Some(dialog) = app.merge.pending_result.take()
{
app.ui.dialog = Some(dialog);
}
}
/// A merge finished and was added (`what`: "Panorama", …; `info`: its result): say so, and when it left photos out,
/// name them in a dialog that stays until closed (shown by [`poll`] once no other dialog is open).
pub(crate) fn finished(app: &mut LightcraftApp, ctx: &egui::Context, what: &str, info: Value) {
let message = added_message(what, &info);
if let Some(dialog) = result_dialog(&message, &info) {
app.merge.pending_result = Some(dialog);
}
app.merge.last_result = Some(info);
app.toast(ctx, message);
}
/// The dialog that names the photos a finished panorama left out, from that result's own source paths (the
/// preview registered smaller copies, so it can leave out other photos). `None` when it left none out.
fn result_dialog(message: &str, info: &Value) -> Option<crate::state::Dialog> {
let omitted: Vec<String> = info["omitted"].as_array()?.iter().filter_map(|p| p["path"].as_str().map(str::to_string)).collect();
(!omitted.is_empty()).then(|| crate::state::Dialog::MergeResult { summary: message.to_string(), omitted })
}
/// The body of the result dialog: the completion message (a live region: the dialog opens when a background merge
/// finishes, away from where the user is) and the omitted files' names.
pub fn result_body(ui: &mut egui::Ui, summary: &str, omitted: &[String]) {
let t = crate::theme::Tokens::get(ui.ctx());
let r = ui.add(egui::Label::new(egui::RichText::new(summary).strong().color(t.caution)).wrap());
ui.ctx().accesskit_node_builder(r.id, |node| node.set_live(egui::accesskit::Live::Polite));
ui.label(crate::i18n::tr("LightCraft could not align these photos with the included set, so the panorama leaves them out."));
omitted_names(ui, omitted.iter().map(String::as_str));
}
/// The message for a finished merge (`what`: "Panorama", …; `info`: its result): a panorama
/// smaller than its photos' resolution says why (issue #1455).
fn added_message(what: &str, info: &Value) -> String {
let size = |k: &str| info[k].as_f64().map(|mp| format!("{mp:.0} MP"));
match (info["limit"].as_str(), size("megapixels"), size("nativeMegapixels")) {
let message = match (info["limit"].as_str(), size("megapixels"), size("nativeMegapixels")) {
(Some("memory"), Some(mp), Some(full)) => crate::i18n::tr_format!(
"{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has",
what = what,
@@ -374,7 +412,33 @@ fn added_message(what: &str, info: &Value) -> String {
full = full
),
_ => crate::i18n::tr_format!("{what} merge added", what = what),
}
};
if info["used"].is_array() && info["omitted"].is_array() { format!("{message}\n{}", inclusion_summary(info)) } else { message }
}
fn inclusion_summary(info: &Value) -> String {
let used = info["used"].as_array().map_or(0, Vec::len);
let omitted = info["omitted"].as_array().map_or(0, Vec::len);
crate::i18n::tr_format!("{used} of {total} photos included", used = used, total = used.saturating_add(omitted))
}
/// Names come from this result's source paths, not the current selection or an older preview.
fn omitted_photos(ui: &mut egui::Ui, info: &Value) {
let Some(omitted) = info["omitted"].as_array().filter(|v| !v.is_empty()) else { return };
let t = crate::theme::Tokens::get(ui.ctx());
ui.label(egui::RichText::new(inclusion_summary(info)).strong().color(t.caution));
ui.label(crate::i18n::tr("LightCraft could not align these photos with the included set. Review the preview before merging."));
omitted_names(ui, omitted.iter().filter_map(|photo| photo["path"].as_str()));
}
/// The omitted photos' file names, scrolling past a few; each one's full path on hover.
fn omitted_names<'a>(ui: &mut egui::Ui, paths: impl Iterator<Item = &'a str>) {
egui::ScrollArea::vertical().id_salt("merge-omitted").max_height(76.0).show(ui, |ui| {
for path in paths {
let name = std::path::Path::new(path).file_name().and_then(|s| s.to_str()).unwrap_or(path);
ui.add(egui::Label::new(name).wrap()).on_hover_text(path);
}
});
}
fn last_failed_matches(app: &LightcraftApp, opts: &MergeDialog) -> bool {
@@ -437,6 +501,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, opts: &mut MergeDialog)
ui.horizontal_top(|ui| {
// preview
ui.vertical(|ui| {
ui.set_width(520.0);
let box_size = egui::vec2(520.0, 360.0);
let (rect, _) = ui.allocate_exact_size(box_size, egui::Sense::hover());
ui.painter().rect_filled(rect, 4.0, t.canvas);
@@ -473,7 +538,9 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, opts: &mut MergeDialog)
if let Some(e) = &app.merge.error {
ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, e, t.font(13.0), t.text);
}
let info = app.merge.preview.as_ref().map(|p| p.3.clone());
// A previous preview may stay visible while the options change. Only describe
// inclusions once this preview is current and its replacement has finished.
let info = app.merge.preview.as_ref().filter(|p| p.2 == *opts && app.merge.preview_task.is_none()).map(|p| &p.3);
if let Some(info) = info {
let txt = if opts.is_pano() {
crate::i18n::tr_format!(
@@ -489,6 +556,9 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, opts: &mut MergeDialog)
crate::i18n::tr_format!("{} photos · exposures {} EV", ev.len(), ev.join(" / "))
};
ui.label(egui::RichText::new(txt).color(t.text_dim));
if opts.is_pano() {
omitted_photos(ui, info);
}
}
});
ui.add_space(12.0);
@@ -792,6 +862,21 @@ mod tests {
assert!((r.center().y - area().center().y).abs() < 0.5 && r.left() < area().left() && r.right() >= area().right(), "{r:?}");
}
#[test]
fn completed_panorama_reports_its_actual_inclusion_count() {
for (what, used, omitted) in
[("Panorama", vec![71, 9], vec![401]), ("HDR panorama", vec![71, 9, 401, 3], vec![6, 12]), ("Panorama", vec![1, 2], vec![])]
{
let info = json!({"used": used, "omitted": omitted.iter().map(|id| json!({"id": id})).collect::<Vec<_>>()});
let message = added_message(what, &info);
let mut lines = message.lines();
assert_eq!(lines.next(), Some(added_message(what, &Value::Null).as_str()));
let count = lines.next().expect("the completion message reports inclusion");
let numbers = count.split_whitespace().filter_map(|word| word.parse::<usize>().ok());
assert!(numbers.eq([used.len(), used.len() + omitted.len()]), "{count}");
}
}
/// Issue #1455: a panorama held to the computer's memory, or to the largest size, says so.
#[test]
fn a_smaller_panorama_says_why() {
+109 -13
View File
@@ -1,5 +1,5 @@
//! AI denoise in the interface: the line under the Detail panel's Denoise slider (what the picture is doing), the
//! Settings ▸ Denoise tab (the model and the cache) and the per-frame pump that keeps the engine's background work going.
//! AI denoise in the interface: the method and progress under Detail, the defaults and models in Settings,
//! and the per-frame pump that keeps the engine's background work going.
//!
//! The Amount slider is an ordinary develop control (`enhance.denoise`); everything here is about the cleaned picture the
//! slider mixes in. It is cached data made in the background for the photos being looked at, and never a file in the
@@ -35,6 +35,8 @@ pub struct Ui {
/// Models the user pressed Download for that have not been installed yet.
dl_watch: Vec<String>,
list: Option<(u64, f64, Value)>,
/// The active photo's methods, invalidated by edits and model changes.
photo_info: Option<(PhotoId, u64, u64, f64, Value)>,
/// Why the last file picked with Install from file… was refused, shown under the button.
rejected: Option<String>,
}
@@ -112,7 +114,7 @@ fn models(app: &mut LightcraftApp, _ctx: &egui::Context) -> Value {
}
/// Follows the downloads the user started: keeps redrawing while one runs (the progress bar), and says so when a
/// model has been installed and is in use (the engine does all of that by itself).
/// model has been installed and set as the default (the engine does all of that by itself).
fn watch_downloads(app: &mut LightcraftApp, ctx: &egui::Context) {
if app.caches.denoise.dl_watch.is_empty() {
return;
@@ -134,7 +136,7 @@ fn watch_downloads(app: &mut LightcraftApp, ctx: &egui::Context) {
for id in installed {
let _ = app.session.execute("denoise.models.downloadCancel", &json!({"id": id}));
app.caches.denoise.epoch += 1;
let text = tr("The denoise model is installed and in use: the AI Denoise Amount slider under Detail now works");
let text = tr("The denoise model is installed. Choose a method for an individual photo under Detail.");
app.ui.status = text.into();
app.toast(ctx, text);
}
@@ -164,6 +166,100 @@ pub fn detail_toggle(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, on
});
}
fn photo_info(app: &mut LightcraftApp, id: PhotoId) -> Value {
let now = app.tick_now();
let (revision, epoch) = (app.session.catalog.revision, app.caches.denoise.epoch);
if let Some((photo, rev, e, at, info)) = &app.caches.denoise.photo_info
&& *photo == id
&& *rev == revision
&& *e == epoch
&& now - at < REFRESH_SECS
{
return info.clone();
}
let info = app.session.execute("denoise.photo.info", &json!({"id": id.0})).unwrap_or(Value::Null);
app.caches.denoise.photo_info = Some((id, revision, epoch, now, info.clone()));
info
}
fn method_name(model: &Value, id: &str) -> String {
if id == "builtin" {
return tr("Built-in").into();
}
let name = model["name"].as_str().filter(|name| !name.trim().is_empty()).unwrap_or(id);
match model["version"].as_str().filter(|version| !version.is_empty()) {
Some(version) => tr_format!("{name} ({version})", name = name, version = version),
None => name.to_string(),
}
}
/// The chosen method is an edit for this photo, including while AI Denoise is off.
/// Returns whether to show the rendering status below the Amount slider.
pub fn detail_model(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) -> bool {
let info = photo_info(app, id);
let model = &info["model"];
let Some(current) = model["id"].as_str() else { return true };
let available = model["available"] == true;
let name = method_name(model, current);
let text = if available { name } else { tr_format!("{name} (unavailable)", name = name) };
let label = tr("Denoise Method");
let t = Tokens::get(ui.ctx());
egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 2, bottom: 4 }).show(ui, |ui| {
ui.add(egui::Label::new(RichText::new(label).color(t.text_label)).wrap());
let salt = ("denoise-photo-model", id.0);
let trigger = ui.make_persistent_id(egui::IdSalt::new(salt));
let width = ui.available_width();
let was_open = craft_ui::ComboBox::is_open(ui.ctx(), trigger);
let combo = crate::widgets::combo_box(salt).width(width).truncate().selected_text(text.as_str()).show_ui(ui, |ui| {
ui.set_max_width(width);
for row in info["models"].as_array().into_iter().flatten() {
let Some(method) = row["id"].as_str() else { continue };
let selected = available && method == current;
let item = ui.add(egui::Button::selectable(selected, method_name(row, method)).min_size(egui::vec2(0.0, 24.0)).wrap());
ui.ctx().accesskit_node_builder(item.id, |node| {
node.set_role(egui::accesskit::Role::ListBoxOption);
node.clear_toggled();
node.set_selected(selected);
});
register(ui, format!("denoise:method:{method}"), item.rect);
if item.clicked() {
ui.close();
return Some(method);
}
}
None
});
if was_open && ui.input(|i| i.key_pressed(egui::Key::Escape)) {
combo.response.request_focus();
}
let open = craft_ui::ComboBox::is_open(ui.ctx(), combo.response.id);
ui.ctx().accesskit_node_builder(combo.response.id, |node| {
node.set_label(label);
node.set_expanded(open);
});
register(ui, "denoise:method", combo.response.rect);
if let Some(method) = combo.inner.flatten() {
combo.response.request_focus();
if let Err(e) = app.run("denoise.photo.model", json!({"id": id.0, "model": method})) {
app.toast_error(ui.ctx(), sentence(&e));
}
app.caches.denoise.photo_info = None;
ui.ctx().request_repaint();
}
if !available {
let warning = ui.add(
egui::Label::new(
RichText::new(tr("The saved method is unavailable. Choose an installed method or reinstall the saved model."))
.color(t.text_label),
)
.wrap(),
);
ui.ctx().accesskit_node_builder(warning.id, |node| node.set_live(egui::accesskit::Live::Polite));
}
});
available
}
/// The bar under the Denoise slider while a photo's picture is made: at most 240 px wide, and
/// sweeping while the number of tiles is not known yet. The percentage is `progress::percent`, as the
/// bar's accessible value is: 100 % only once done.
@@ -261,8 +357,9 @@ pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {
Your files are never changed and no extra files are made in your library: the cleaned picture is cached data that is made again when needed.",
);
let runtime = list["runtime"].as_bool() == Some(true);
hint(ui, t, "The default applies when a photo is first denoised. Photos with a saved method keep it.");
if list["model"].is_null() {
hint(ui, t, "In use: the built-in denoiser. It needs nothing installed, so turning AI Denoise on just works.");
hint(ui, t, "Default for new denoising: the built-in denoiser.");
}
if !runtime {
hint(ui, t, "This build cannot run your own denoise models.");
@@ -308,9 +405,6 @@ pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {
let dl = downloads.iter().find(|d| d["id"] == m["id"]);
model_row(app, ui, t, m, dl, runtime);
}
if all.iter().all(|m| m["selected"] != true) && all.iter().any(|m| m["installed"] == true) {
hint(ui, t, "The built-in denoiser is in use: press Use on a model to use that instead.");
}
hint(ui, t, "Works on raw files from cameras with a standard (Bayer) sensor. Other files keep their normal noise reduction.");
work_section(app, ui, t, &list);
}
@@ -575,7 +669,7 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value,
ui.label(RichText::new(size).color(t.text_dim));
}
if selected {
ui.label(RichText::new(tr("in use")).color(t.accent));
ui.label(RichText::new(tr("default")).color(t.accent));
} else if installed {
ui.label(RichText::new(tr("installed")).color(t.text_dim));
}
@@ -629,13 +723,13 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value,
app.caches.denoise.epoch += 1;
}
if selected {
let r = model_button(ui, &format!("denoise:off:{id}"), "Stop using");
let r = model_button(ui, &format!("denoise:off:{id}"), "Use Built-in");
if r.clicked() {
let _ = app.run("denoise.models.select", json!({"id": null}));
app.caches.denoise.epoch += 1;
}
} else {
let r = model_button(ui, &format!("denoise:use:{id}"), "Use");
let r = model_button(ui, &format!("denoise:use:{id}"), "Set as Default");
if r.clicked() {
let _ = app.run("denoise.models.select", json!({"id": id}));
app.caches.denoise.epoch += 1;
@@ -663,7 +757,7 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value,
if !host.is_empty() {
let label = if dl_state == Some("failed") { "Try again" } else { "Download" };
let tip = tr_format!(
"Shows the model's terms, then downloads {} from {host}, installs it and starts using it. Nothing else is sent.",
"Shows the model's terms, then downloads {} from {host}, installs it and sets it as the default. Nothing else is sent.",
mb(m["sizeBytes"].as_u64()),
host = host
);
@@ -824,7 +918,7 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info
let download = info["download"].is_string();
if download {
let host = info["host"].as_str().unwrap_or("its own repository");
let after = if info["domain"] == "denoise" { "starts using it for AI Denoise" } else { "makes AI Denoise available" };
let after = if info["domain"] == "denoise" { "sets it as the default for AI Denoise" } else { "makes AI Denoise available" };
ui.add(
egui::Label::new(
RichText::new(tr_format!(
@@ -836,6 +930,8 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info
)
.wrap(),
);
} else if info["domain"] == "denoise" && info["alreadyInstalled"] != true {
hint(ui, t, "Installs this model and sets it as the default for AI Denoise.");
}
let commercial = m["licence"]["commercial"].as_str().unwrap_or("unknown");
ui.label(RichText::new(licence_line(m)).font(t.semibold(12.5)).color(if commercial == "yes" { t.text } else { t.caution }));
+1 -1
View File
@@ -782,7 +782,7 @@ fn tool_interaction(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Res
RightPanel::Remove => remove_overlay(app, ui, resp, map, d),
RightPanel::RedEye => eye_overlay(app, ui, resp, map, d),
RightPanel::Edit if app.ui.tool == "lensBlurShape" => lens_blur_shape_overlay(app, ui, resp, map, d),
RightPanel::Edit if app.ui.tool.starts_with("lensBlur") => lens_blur_brush_overlay(app, ui, resp, map),
RightPanel::Edit if app.ui.tool.starts_with("lensBlur") => lens_blur_brush_overlay(app, ui, resp, map, d),
_ => {
// side by side / stacked: Before shows the same frame, so a click in its view (white
// balance, colour samples, targeted adjustment) means the same point of the photo.
@@ -84,7 +84,7 @@ pub(super) fn lens_blur_shape_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui
/// Lens Blur Brush Refinement on the photo: the brush circle (size and feather), the stroke being
/// painted (green: Focus, red: Blur), committed as `lensBlur.brushStroke` when the drag ends.
/// ⌥ (Alt) erases what the brush painted.
pub(super) fn lens_blur_brush_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, map: &CanvasMap) {
pub(super) fn lens_blur_brush_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, map: &CanvasMap, d: &DevelopSettings) {
let long = (map.rect.width().max(map.rect.height())) as f64;
let clip = app.canvas_rect.unwrap_or(map.rect);
let p = &ui.painter_at(clip);
@@ -122,6 +122,10 @@ pub(super) fn lens_blur_brush_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui
hard: r * (1.0 - (app.ui.brush_feather / 100.0).clamp(0.0, 1.0)),
flow: (app.ui.brush_flow / 100.0).clamp(0.0, 1.0),
density: (app.ui.lens_blur_brush_amount / 100.0).clamp(0.0, 1.0),
// (its strokes render as a mask brush does: Flow per radius travelled from V15, the edge by stroke from V16,
// except an Auto Mask stroke, which keeps V15's accumulation as the committed one does)
per_radius: lightcraft_pipeline::masks::flow_per_radius(d),
by_stroke: lightcraft_pipeline::masks::stroke_feather(d) && !app.ui.brush_auto_mask,
color: if focus { [70, 200, 120] } else { [230, 70, 70] },
opacity: 0.45,
};
@@ -749,6 +749,9 @@ fn brush_tool(
hard: r * (1.0 - (app.ui.brush_feather / 100.0).clamp(0.0, 1.0)),
flow: (app.ui.brush_flow / 100.0).clamp(0.0, 1.0),
density: 1.0,
per_radius: lightcraft_pipeline::masks::flow_per_radius(d),
// (an Auto Mask stroke keeps V15's accumulation, as the committed one does)
by_stroke: lightcraft_pipeline::masks::stroke_feather(d) && !app.ui.brush_auto_mask,
color: app.ui.mask_overlay_color,
opacity: opacity.clamp(0.0, 1.0),
};
+4 -1
View File
@@ -429,8 +429,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {
let applicable = !matches!(app.session.denoise_photo_state(id), lightcraft_engine::denoise::PhotoState::NotApplicable);
let on = d.enhance.denoise_enabled();
super::denoise::detail_toggle(app, ui, id, on, applicable);
let method_available = applicable && super::denoise::detail_model(app, ui, id);
control(app, ui, d, "enhance.denoise", applicable && on);
super::denoise::detail_status(app, ui, id, if on { d.enhance.denoise } else { 0.0 });
if method_available {
super::denoise::detail_status(app, ui, id, if on { d.enhance.denoise } else { 0.0 });
}
sub_title(ui, crate::i18n::tr("Noise Reduction"));
for c in ["detail.nrLuminance", "detail.nrDetail", "detail.nrContrast", "detail.nrColor", "detail.nrColorDetail", "detail.nrColorSmoothness"]
{
+54 -23
View File
@@ -490,22 +490,44 @@ impl ScreenTextures for TestScreen {
/// from the GPU has its pixels. Before, a mid-drag `ui.screenshot {"headless": true}` showed the
/// photo as a white rectangle: the GPU-resident draft left no CPU copy (review of PR #1065).
/// The test fixture with a small GPU texture (5 × 3 known texels) and a [`TestScreen`] that
/// records the ids it frees; `None` without a GPU adapter.
/// records the ids it frees; `Err` (why the test is skipped) without a GPU adapter, or when the
/// process is ending.
#[cfg(not(target_arch = "wasm32"))]
#[allow(clippy::type_complexity)]
fn gpu_drawn_fixture(
freed: std::sync::Arc<std::sync::Mutex<Vec<egui::TextureId>>>,
) -> Option<(crate::LightcraftApp, std::rc::Rc<std::cell::RefCell<Work>>, egui::Context, lightcraft_engine::media::ScreenFrame)> {
) -> Result<(crate::LightcraftApp, std::rc::Rc<std::cell::RefCell<Work>>, egui::Context, lightcraft_engine::media::ScreenFrame), &'static str> {
use lightcraft_engine::gpu::wgpu;
let device = (|| {
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
desc.backends = lightcraft_engine::gpu::backend::window_backends();
desc.backend_options = lightcraft_engine::gpu::backend::backend_options();
let instance = wgpu::Instance::new(desc);
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?;
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("test window"), ..Default::default() })).ok()
})();
let (device, queue) = device?;
// The render device (created if need be, also while another test has turned GPU rendering
// off), or, only when no render device can exist in this process (the environment switches the
// GPU off, or creating it failed), one device of our own for the whole process, never dropped.
// A Vulkan instance created while other tests render on the render device on other threads
// crashed Vulkan loaders before 1.4.345 with SIGSEGV (Vulkan-Loader#1863:
// `vkEnumeratePhysicalDevices` unloads drivers that another thread's device call is walking).
static OWN: std::sync::OnceLock<Option<(wgpu::Device, wgpu::Queue)>> = std::sync::OnceLock::new();
let (device, queue) = match lightcraft_gpu::shared_device() {
Some(shared) => shared,
// (`gpu::begin_shutdown`: a device of our own would be created during teardown)
None if lightcraft_gpu::shutting_down() => return Err("the process is ending: no device is created any more"),
None => OWN
.get_or_init(|| {
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
desc.backends = lightcraft_engine::gpu::backend::window_backends();
desc.backend_options = lightcraft_engine::gpu::backend::backend_options();
let instance = wgpu::Instance::new(desc);
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?;
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("test window"), ..Default::default() })).ok()
})
.clone()
.ok_or("no GPU adapter")?,
};
// (an error outside a scope on the render device stops GPU rendering for every test in the
// process: this one's are caught here, on this thread)
let scopes = [
device.push_error_scope(wgpu::ErrorFilter::Validation),
device.push_error_scope(wgpu::ErrorFilter::OutOfMemory),
device.push_error_scope(wgpu::ErrorFilter::Internal),
];
let (w, h) = (5usize, 3usize);
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: None,
@@ -524,9 +546,14 @@ fn gpu_drawn_fixture(
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w as u32 * 4), rows_per_image: Some(h as u32) },
wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 },
);
for scope in scopes.into_iter().rev() {
if let Some(e) = pollster::block_on(scope.pop()) {
panic!("the test texture: {e}");
}
}
let (mut app, work, ctx) = fixture();
app.renderer.set_screen_textures(Box::new(TestScreen(device, queue, freed)));
Some((app, work, ctx, lightcraft_engine::media::ScreenFrame { texture, width: w, height: h }))
Ok((app, work, ctx, lightcraft_engine::media::ScreenFrame { texture, width: w, height: h }))
}
/// A headless screenshot (driven by the control channel: `keep_pixels`) of a view drawn straight
@@ -535,9 +562,12 @@ fn gpu_drawn_fixture(
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_headless_screenshot_reads_back_a_view_drawn_from_the_gpu() {
let Some((mut app, work, ctx, frame)) = gpu_drawn_fixture(Default::default()) else {
lightcraft_testkit::skip!(Gpu, "no GPU adapter");
return;
let (mut app, work, ctx, frame) = match gpu_drawn_fixture(Default::default()) {
Ok(fixture) => fixture,
Err(why) => {
lightcraft_testkit::skip!(Gpu, "{why}");
return;
}
};
let (w, h) = (frame.width, frame.height);
assert!(app.renderer.keep_pixels);
@@ -563,9 +593,12 @@ fn a_headless_screenshot_reads_back_a_view_drawn_from_the_gpu() {
#[test]
fn releasing_a_slot_frees_its_gpu_texture() {
let freed = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let Some((mut app, work, ctx, frame)) = gpu_drawn_fixture(freed.clone()) else {
lightcraft_testkit::skip!(Gpu, "no GPU adapter");
return;
let (mut app, work, ctx, frame) = match gpu_drawn_fixture(freed.clone()) {
Ok(fixture) => fixture,
Err(why) => {
lightcraft_testkit::skip!(Gpu, "{why}");
return;
}
};
let job = app.session.render_job(PhotoId(1), 64, 64, false, true).unwrap().draft();
app.renderer.request(Slot::Main, job, 100);
@@ -1655,9 +1688,8 @@ fn curve_input_native_worker_keeps_request_identity_through_failure_and_recovery
assert!(app.renderer.pool.wait(timeout));
app.renderer.poll(&ctx, &mut app.session);
let message = app.renderer.failure_messages.last().unwrap();
// The diagnostic quotes the path with Debug, escaping Windows separators.
assert!(message.contains(&format!("file {replacement:?}")), "{message}");
assert!(!message.contains(&format!("file {later:?}")), "the catalog changed after submission: {message}");
assert!(message.contains(&format!("{:?}", replacement.to_str().unwrap())), "{message}");
assert!(!message.contains(&format!("{:?}", later.to_str().unwrap())), "the catalog changed after submission: {message}");
assert!(!app.renderer.requests.contains_key(&slot));
assert!(!app.renderer.is_pending(slot));
app.session.media.file_loader =
@@ -1718,8 +1750,7 @@ fn curve_input_relink_retries_current_file_with_retained_content_hash() {
app.renderer.poll(&ctx, &mut app.session);
assert_eq!(paths.recv_timeout(timeout).unwrap(), original.to_str().unwrap());
assert!(app.renderer.failure_of(slot, id).is_some());
let message = app.renderer.failure_messages.last().unwrap();
assert!(message.contains(&format!("file {original:?}")), "{message}");
assert!(app.renderer.failure_messages.last().unwrap().contains(&format!("{:?}", original.to_str().unwrap())));
assert!(app.renderer.curve_histogram.is_none());
app.session.execute("photo.relink", &serde_json::json!({"id": id.0, "path": replacement})).unwrap();
+6
View File
@@ -44,6 +44,12 @@ pub enum Dialog {
details: Vec<String>,
first: Option<u64>,
},
/// A finished panorama that left photos out: its message and the omitted files' paths, taken from the final
/// result (the preview registered smaller copies and can leave out other photos).
MergeResult {
summary: String,
omitted: Vec<String>,
},
/// File ▸ Print…: the Print module. Its state is the session's (`print.*`); the page on show
/// and the selected cell are [`UiState::print`].
Print,
+1
View File
@@ -60,6 +60,7 @@ mod filmstrip_drag;
mod find_similar;
mod focus_point;
mod folder_drop;
mod gpu_warm_up;
mod grading;
mod grid;
mod grid_badges;
+72
View File
@@ -425,6 +425,78 @@ fn final_merge_shows_a_row_and_cancels() {
let _ = std::fs::remove_dir_all(dir);
}
/// Merging other photos while the dialog is open ("with Last Settings", or the next set of an HDR batch) drops the
/// dialog's preview of the photos it had: the preview is kept while its options match, and the dialog went on
/// describing the old photos (their count and omitted files) for the new ones.
#[test]
fn merging_other_photos_drops_the_dialogs_preview() {
let (mut h, dir) = bracket("merge-ids");
let all = h.app.session.selected();
crate::merge::open(&mut h.app, "merge.hdr").unwrap();
assert!(h.step_until(T, |h| h.app.merge.preview.is_some()), "the dialog previews the three photos");
let ev = |h: &Headless| h.app.merge.preview.as_ref().and_then(|p| p.3["ev"].as_array().map(Vec::len));
assert_eq!(ev(&h), Some(3));
h.app.session.execute("library.select", &json!({"ids": &all[..2]})).unwrap();
crate::merge::start_last(&mut h.app, "merge.hdr").unwrap();
assert_eq!(h.app.merge.ids, all[..2].to_vec());
assert!(h.app.merge.preview.is_none() && h.app.merge.preview_pixels.is_none(), "no preview of the three photos left");
let rows = h.app.session.activity.list();
let merging = rows.iter().find(|r| r.kind == "merge").map(|r| r.id).unwrap();
h.app.session.activity.cancel(merging).unwrap();
assert!(h.step_until(T, |h| h.app.merge.final_task.is_none() && h.app.merge.preview.is_some()));
assert_eq!(ev(&h), Some(2), "the dialog previews the photos it now merges");
let _ = std::fs::remove_dir_all(dir);
}
/// PR #2492 review: the final merge registers the full-size photos again, so it can leave out other photos than the
/// preview did. The completion names the final result's omitted files (to a screen reader too, announced where the
/// user is), waits for a dialog the user has open, and a panorama that left nothing out shows no list.
#[test]
fn a_finished_panorama_names_the_photos_it_left_out() {
let mut h = demo();
let ctx = h.view.ctx.clone();
// the preview left out another photo than the final merge does
let tex = ctx.load_texture("t", egui::ColorImage::new([1, 1], vec![egui::Color32::BLACK]), Default::default());
let preview_info = json!({"used": [1, 3], "omitted": [{"id": 2, "path": "/photos/Preview-only.png"}]});
h.app.merge.preview = Some((tex, [1, 1], crate::merge::MergeDialog::for_command("merge.panorama"), preview_info));
// a dialog the user has open is not replaced
h.app.ui.dialog = Some(crate::state::Dialog::About);
let final_info = json!({"id": 9, "used": [1, 2], "omitted": [{"id": 3, "path": "/photos/Final-only.png"}]});
crate::merge::finished(&mut h.app, &ctx, "Panorama", final_info);
h.step();
assert_eq!(h.app.ui.dialog, Some(crate::state::Dialog::About));
h.app.ui.dialog = None;
h.step();
h.step();
let painted = h.painted_text().join("\n");
assert!(painted.contains("Final-only.png"), "the final omitted name is listed");
assert!(!painted.contains("Preview-only.png"), "not the preview's");
// what a screen reader gets: a dialog, the name, a polite live region, and a button to close it
ctx.enable_accesskit();
let raw = crate::headless::HeadlessView::raw_input(h.size, h.pixels_per_point, h.time, Vec::new());
let app = &mut h.app;
let mut out = ctx.run_ui(raw, |ui| {
app.logic(ui.ctx());
app.ui(ui);
});
let tree = out.platform_output.accesskit_update.take().expect("an accessibility tree");
let nodes: Vec<_> = tree.nodes.iter().map(|(_, n)| n).collect();
let named =
|role: egui::accesskit::Role, text: &str| nodes.iter().any(|n| n.role() == role && n.label().or(n.value()).is_some_and(|l| l.contains(text)));
let title = nodes.iter().find(|n| n.role() == egui::accesskit::Role::Dialog).and_then(|n| n.label()).expect("a dialog node");
assert!(painted.contains(title), "the dialog is named by its visible title");
assert!(named(egui::accesskit::Role::Label, "Final-only.png"));
assert!(nodes.iter().any(|n| n.live() == Some(egui::accesskit::Live::Polite)), "the result is announced");
assert!(h.app.widgets.iter().any(|(w, _)| w == "button:dialogOk"), "it closes from a button");
// a panorama that left nothing out: the message only
h.app.ui.dialog = None;
crate::merge::finished(&mut h.app, &ctx, "Panorama", json!({"id": 10, "used": [1, 2], "omitted": []}));
h.step();
h.step();
assert_eq!(h.app.ui.dialog, None);
assert!(!h.painted_text().iter().any(|t| t.contains("Final-only.png")));
}
/// The merge dialog opens with the options of the last merge of its kind (per kind), and "with Last
/// Settings" uses them; a kind never merged opens with the defaults.
#[test]
+44
View File
@@ -0,0 +1,44 @@
//! A test is a process of its own under nextest, and that process ends as soon as the test
//! returns. The app's first frame starts the GPU device warm-up on a thread of its own; a process
//! that ends while that thread is still loading the driver crashes there (issue #620; in CI,
//! tests killed by SIGSEGV after they had passed). So dropping the app waits for a warm-up that
//! is still in flight. This exercises that wait with a substitute warm-up held on the same gate,
//! so it needs no GPU, no device and no race.
use std::sync::mpsc;
use std::time::Duration;
use crate::{LightcraftApp, Services};
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn dropping_the_app_waits_for_a_warm_up_that_is_in_flight() {
// In flight from here until `hold` is dropped (test support in the gpu crate, on the gate the
// real warm-up enters)
let hold = lightcraft_engine::gpu::hold_warm_up_for_test().expect("the warm-up gate is open in a test");
assert!(!lightcraft_engine::gpu::wait_warm_up(Duration::ZERO), "the substitute warm-up is in flight");
let (tx, rx) = mpsc::channel::<&'static str>();
let dropping = std::thread::spawn(move || {
// Built here, not moved in: `LightcraftApp` is not `Send` (its host-service callbacks are
// not), and this test does not need it to be. An app that never ran a frame has nothing of
// its own pending, so the only thing that can hold up its drop is the warm-up wait.
let app = LightcraftApp::new(lightcraft_engine::Session::new(), Services { png: None, ..Default::default() });
tx.send("dropping").unwrap();
drop(app);
tx.send("dropped").unwrap();
});
assert_eq!(rx.recv_timeout(Duration::from_secs(30)).unwrap(), "dropping");
// The drop has not returned while the warm-up is held. The one second is only the
// observation window for that — the thread is already past "dropping", sent after the
// construction and just before the drop, so an unwaiting drop would have torn the app down
// and returned well inside it — and the proof is the step after: releasing the hold is what
// lets the drop return.
assert_eq!(
rx.recv_timeout(Duration::from_secs(1)),
Err(mpsc::RecvTimeoutError::Timeout),
"dropping the app returned while a warm-up was in flight"
);
drop(hold);
assert_eq!(rx.recv_timeout(Duration::from_secs(30)).unwrap(), "dropped");
dropping.join().unwrap();
}
+28
View File
@@ -2180,6 +2180,34 @@ fn a_fast_brush_stroke_shows_without_gaps_before_the_button_is_released() {
}
}
/// Process V15 (and V16, the same for this Feather 0 brush): a Flow 25 stroke shows while the button
/// is held as it will once committed, both adding Flow per brush radius travelled (#4045): partly
/// covered along its centre, not almost fully.
#[test]
fn a_low_flow_stroke_shows_as_it_will_be_committed() {
let mut h = detail("panel.masking");
h.settle(SETTLE);
exec(&mut h, "tool.brush", json!({"new": true}));
let r = h.request("ui.set", json!({"brushSize": 0.03, "brushFeather": 0.0, "brushFlow": 25.0}), T);
assert_eq!(r["ok"], true, "{r}");
let y = 0.4;
let (photo, held) = hold_fast_stroke(&mut h, y);
let col = h.app.ui.mask_overlay_color.map(|v| v as f32);
let op = h.app.ui.mask_overlay_opacity / 100.0;
// the tint along the centreline: about 1 − 0.75² of full coverage, not the 90 % of a flow per dab
let cover: Vec<f32> = photo.iter().zip(&held).map(|(p, l)| (l[0] - p[0]) / ((col[0] - p[0]) * op)).collect();
let mid = cover[cover.len() / 2];
assert!((mid - 0.4375).abs() < 0.08, "live coverage {mid}");
pointer(&mut h, json!([{"kind": "up", "x": 0.85, "y": y}]));
// (the committed mask's pin sits on the stroke)
h.app.ui.mask_pins = false;
h.settle(SETTLE);
let done = stroke_centreline(&h, y);
for (l, k) in held.iter().zip(&done) {
assert!((0..3).all(|i| (l[i] - k[i]).abs() < 24.0), "live {l:?} vs committed {k:?}");
}
}
/// What the photo shows along the centreline of [`hold_fast_stroke`]'s stroke at height `y`, away
/// from the cursor ring at its end.
fn stroke_centreline(h: &Headless, y: f32) -> Vec<[f32; 3]> {
+89
View File
@@ -255,6 +255,95 @@ fn screen_reader_increment_moves_a_slider() {
assert!(after > before, "{before} -> {after}");
}
/// A keyboard user can replace an unavailable saved version, including when the new version has the same model ID.
#[test]
fn keyboard_can_replace_the_unavailable_denoiser_for_one_photo() {
use lightcraft_catalog::{MediaKind, Op, Photo, PhotoId, Source};
use serde_json::json;
const ID: &str = "night-landscape";
const NAME: &str = "NightLandscapeHighISOSmoothingForFullFrameCamerasWithFineDetailPreservation";
let root = std::env::temp_dir().join(format!("lc-ui-denoise-method-{}", std::process::id()));
let model_dir = root.join("models").join(ID);
std::fs::create_dir_all(&model_dir).unwrap();
let onnx = lightcraft_denoise::synthetic::smoothing_onnx();
let sha256 = lightcraft_denoise::hash::sha256_hex(&onnx);
std::fs::write(model_dir.join("model.onnx"), onnx).unwrap();
std::fs::write(model_dir.join("installed.json"), json!({"sha256": sha256}).to_string()).unwrap();
let install_version = |version: &str| {
let manifest =
json!({"id": ID, "name": NAME, "version": version, "domain": "bayerToRgb", "tile": 64, "overlap": 16, "gain": {"kind": "none"}});
std::fs::write(model_dir.join("denoise-model.json"), manifest.to_string()).unwrap();
};
install_version("1");
let mut session = lightcraft_engine::Session::new();
session.set_denoise_models_dir(Some(root.join("models")));
let photos = [PhotoId(1), PhotoId(2)];
for id in photos {
let name = format!("IMG_{}.dng", id.0);
let mut photo =
Photo::new(id, Source::File { path: root.join(&name).to_string_lossy().into_owned() }, &name, "DNG", 6000, 4000, "2026-10-01T00:00:00");
photo.kind = MediaKind::Raw;
session.commit("Test photo", Op::AddPhoto { photo: Box::new(photo) }).unwrap();
}
session.execute("library.select", &json!({"ids": [photos[0].0]})).unwrap();
session.execute("denoise.photo.model", &json!({"id": photos[0].0, "model": ID})).unwrap();
install_version("2");
session.set_denoise_models_dir(Some(root.join("models")));
let mut app = LightcraftApp::new(session, Services::default());
app.headless_host = true;
app.ui.language = lightcraft_ui_egui::i18n::Locale::En;
app.ui.view = ViewMode::Detail;
app.ui.right = RightPanel::Edit;
app.ui.right_width = lightcraft_ui_egui::state::RIGHT_WIDTH.min;
app.ui.open_sections = vec!["detail".into()];
let mut builder = Harness::builder().with_size(vec2(1000.0, 900.0));
if lightcraft_engine::CRAFT_FONTS.is_empty() {
builder = builder.allow_missing_glyphs();
}
let mut h = builder.build_ui_state(
|ui, app: &mut LightcraftApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(8);
let combo = h.get_by_role_and_label(Role::ComboBox, "Denoise Method");
assert!(combo.value().is_some_and(|value| value.contains(NAME) && value.contains("(1)") && value.contains("unavailable")));
combo.focus();
h.run_steps(2);
assert!(h.get_by_role_and_label(Role::ComboBox, "Denoise Method").is_focused());
h.key_press(egui::Key::Enter);
h.run_steps(4);
assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Denoise Method").accesskit_node().data().is_expanded(), Some(true));
let replacement = format!("{NAME} (2)");
let option = h.get_by_role_and_label(Role::ListBoxOption, &replacement);
assert_eq!(option.accesskit_node().data().is_selected(), Some(false));
for _ in 0..3 {
if h.get_by_role_and_label(Role::ListBoxOption, &replacement).is_focused() {
break;
}
h.key_press(egui::Key::ArrowDown);
h.run_steps(3);
}
assert!(h.get_by_role_and_label(Role::ListBoxOption, &replacement).is_focused());
h.key_press(egui::Key::Enter);
h.run_steps(4);
let combo = h.get_by_role_and_label(Role::ComboBox, "Denoise Method");
assert!(combo.is_focused() && combo.value().as_deref() == Some(replacement.as_str()));
let after = h.state().session.develop_of(photos[0]).unwrap();
assert_eq!(after.enhance.denoise_model.as_ref().unwrap().version, "2");
assert!(!after.enhance.denoise_enabled(), "choosing a method leaves the off switch alone");
h.state_mut().run("library.select", json!({"ids": [photos[1].0]})).unwrap();
h.run_steps(4);
assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Denoise Method").value().as_deref(), Some("Built-in"));
assert!(h.state().session.develop_of(photos[1]).unwrap().enhance.denoise_model.is_none());
drop(h);
std::fs::remove_dir_all(root).unwrap();
}
/// The canvas tools' settings (crop angle and offsets, spot size, mask amount) are reachable with
/// Tab alone, and the arrow keys then adjust them.
#[test]
+8 -9
View File
@@ -24,7 +24,7 @@ One third of the pixels are held out from both fits. The combined model must red
**Lens-corrected camera JPEGs.** Some raws carry the camera's own lens correction (Fujifilm and Panasonic tables, the ILCE-7RM4A, Nikon's NikonNEFInfo) and the camera often applies it to its JPEG. Nikon Z lenses always do, and that JPEG can be zoomed in by up to 9% to fill the frame. The fit used to pair the uncorrected sensor with the corrected JPEG, so near the edges it compared pixels from different parts of the scene. Now the sensor proxy is also warped with the file's correction (`into_lens_geometry`, pixels that land outside the picture are dropped), and the fit uses whichever of the two lines up better with the JPEG, going by the correlation of their high-passed log luminance. Files whose JPEG isn't corrected keep the plain proxy. On the 29 CC0 corpus raws with a warp the alignment goes up by 0.13 on average (Panasonic GX80 0.41 to 0.83, Fujifilm X-T20 0.44 to 0.95). Mean ΔE against the camera JPEG over the 35 corpus raws of those formats goes from 3.73 to 3.61, and on 299 private Z 6II photos with Nikon's correction read it goes from 3.22 to 2.68.
**Resolved profiles and remaining camera framing.** For file-local fitting without a camera matrix or an in-file opcode warp, the resolved lens profile can additionally propose a corrected sensor proxy. Its green-plane map is evaluated through the same `Warp::corrected_to_source` used by the renderer, in the developed default crop; oriented profiles are re-expressed in sensor coordinates first. The existing bounded framing search (scale 0.9–1.1, translation at most two pixels on a fixed 96-pixel proxy) may then align the camera JPEG's remaining crop. At least 192 edges are required. Both training and held-out edge directions must agree by at least 0.90 and improve by at least 0.04 over the **original unwarped** geometry, with at least 80% usable edges in each split. For each proposal candidate, the original and candidate scores use the exact intersection of valid edges with the same reference weights, during both training selection and held-out confirmation. Lens correction alone can pass with identity framing. Weak, unrelated or already aligned previews keep the original route; absent profiles, CR3 and the established opcode-warp route retain their existing behaviour.
**Resolved profiles and remaining camera framing.** For file-local fitting without a camera matrix or an in-file opcode warp, the resolved lens profile can additionally propose a corrected sensor proxy. Its green-plane map is evaluated through the same `Warp::corrected_to_source` used by the renderer, in the developed default crop; oriented profiles are re-expressed in sensor coordinates first. The existing bounded framing search (scale 0.9–1.1, translation at most two pixels on a fixed 96-pixel proxy) may then align the camera JPEG's remaining crop. At least 192 edges are required. Both training and held-out edge directions must agree by at least 0.90 and improve by at least 0.04 over the **original unwarped** geometry, with at least 80% usable edges in each split. For each proposal candidate, the original and candidate scores use the exact intersection of valid edges with the same reference weights, during both training selection and held-out confirmation. Lens correction alone can pass with identity framing. Weak, unrelated or already aligned previews keep the original route. CR3 also compares the candidate against its accepted framing, as described under [Canon CR3](#canon-cr3). Files with an in-file opcode warp keep their existing route.
This changes calibration correspondences only, including `calibrate`'s pooled pairs and the colour tags used by merge/DNG conversion. It is independent of the user's Optics switch and does not bake geometric correction into the rendered RAW. Sensor and clipping mask follow the same sampling maps; invalid borders cannot train the look. Matrix, hue/saturation, tone fitting and their colour-error acceptance gates are unchanged. A physically plausible lens correction alone is not assumed to match a camera JPEG: geometry must establish the correspondence before it is used. Cached renders and camera looks have new versions so online originals rebuild their calibration. Cameras without a safely resolved geometric profile receive no new guarantee of colour accuracy.
@@ -110,9 +110,11 @@ These are camera-JPEG look estimates, **not measured spectral calibration or Lig
### Canon CR3
CR3 uses the same colour gates and relative WB. Its sensor and JPEG proxies are first oriented identically. Canon can crop its JPEG differently from the sensor; no lens distortion correction is applied to the sensor proxy, so a strongly distortion-corrected JPEG can fail the gates. A fixed 96-pixel proxy measures this remaining framing from luminance-gradient directions: scale is limited to 0.9–1.1 and translation to two proxy pixels. At least 192 edges are required; two thirds train the framing and the remaining third must independently reach direction agreement ≥0.90 with an improvement ≥0.04. At least 80% of each edge set must remain usable. Weak, flat, unrelated or already aligned references keep the sensor framing. This alignment affects training correspondences only; the RAW render still uses the actual sensor pixels.
CR3 uses the same colour gates and relative WB. Its sensor and JPEG proxies are first oriented identically. Canon can crop or radially correct its JPEG. LightCraft first estimates the framing of the unwarped sensor proxy. A fixed 96-pixel proxy measures this remaining framing from luminance-gradient directions: scale is limited to 0.9–1.1 and translation to two proxy pixels. At least 192 edges are required; two thirds train the framing and the remaining third must independently reach direction agreement ≥0.90 with an improvement ≥0.04. At least 80% of each edge set must remain usable. Weak, flat, unrelated or already aligned references keep the sensor framing. This alignment affects training correspondences only; the RAW render still uses the actual sensor pixels.
On the public CC0 EOS R100 / RF-S 18–45 mm sample, the measured framing scale was 0.968. Held-out edge agreement rose from 0.7291 to 0.9194, and the unchanged colour gates accepted the fit (held-out RMS 0.10625 → 0.07704). The corpus test asserts acceptance after decoding the sensor RAW, and synthetic tests cover nonlinear camera tone, known crop/translation and unrelated references. The matrix, tone and hue/saturation table are estimated from the file; no third-party camera matrix or decoder calibration source is copied.
When the camera matrix is a fallback and the file carries no warp, a resolved lens profile can supply an alternative. On both edge sets it must improve on the original geometry and match or beat the accepted framing. Each comparison uses the same valid edges and weights on both sides. The clipping mask follows the sensor through both sampling passes. An absent or rejected profile keeps the framing result. See [CR3 profile correspondence geometry](cr3-profile-alignment.md).
On the public CC0 EOS R100 / RF-S 18–45 mm sample, the framing-only measurement gave a scale of 0.968. Held-out edge agreement rose from 0.7291 to 0.9194, and the unchanged colour gates accepted the fit (held-out RMS 0.10625 → 0.07704). The corpus test asserts acceptance after decoding the sensor RAW, and synthetic tests cover nonlinear camera tone, known crop/translation and unrelated references. The matrix, tone and hue/saturation table are estimated from the file; no third-party camera matrix or decoder calibration source is copied.
This is a per-file camera-look estimate, **not measured spectral calibration or Lightroom parity**. Camera local tone, picture styles, noise reduction and lens warps cannot all be reproduced by a global matrix/curve; same-aspect crops may evade the aspect check. Skin, mixed-light scenes and saturated highlights can still differ from a supplied JPEG. Broader Sony, Nikon and Canon model/lighting coverage, chart-based calibration, absolute WB and other manufacturers remain unverified. Rejected fits and other RAW formats retain their existing behaviour.
@@ -152,11 +154,10 @@ share the JPEG shows (`camera_vignetting_amount`): the camera's tone curve is mo
sensor ranks its pixels' luminance most like the JPEG wins (0 to 100 % in 5 % steps). The ranks are compared within
classes of similar sensor chromaticity (near-neutral and eight hue sectors), weighted by their pixel counts: a camera
that renders some hues brighter than others would otherwise read as vignetting where those hues gather toward the
corners. A CR3 proxy moved to its JPEG's framing gets the gain of the position each pixel shows, and a DNG's tone fit
corners. A CR3 proxy moved to its JPEG's framing gets the gain of the sensor position each pixel shows, including any accepted profile warp. A DNG's tone fit
(`fit_dng_tone`) takes a database profile in the measured share too. The whole correction is kept when nothing can
be measured: proxies of different sizes, fewer than 256 usable pixels (pixels clipped on the sensor or in the camera
JPEG, black and non-finite ones are left out, as are chromaticity classes under 32 pixels), a lens-warped sensor proxy (the gain would no longer be at each
pixel's source position); shares that rank alike keep the larger one. Within a class the camera's rendering is taken as alike, so two
JPEG, black and non-finite ones are left out, as are chromaticity classes under 32 pixels), a lens-warped sensor proxy whose source positions are unavailable; shares that rank alike keep the larger one. Within a class the camera's rendering is taken as alike, so two
saturations of one hue that it renders differently, one gathered toward the corners, can still read as vignetting.
With the whole profile, an ILCE-7M3 frame at f/2 with an FE 28mm F2 (lensfun: corners at 16 % of the centre) fitted
0.062 held-out RMS instead of 0.027 and rendered darker and orange. Its camera JPEG, with vignetting correction Auto
@@ -288,9 +289,7 @@ is recorded here yet. Whether they should come before the file-local fit for the
A smart preview keeps the result of the fit twice: the colour matrix is baked into its pixels and the tone and chroma curves are stored in its header. When the fit changes, a preview built earlier keeps the old look until it is rebuilt, and the render cache version does not reach it (renders are keyed on the library's files, proxies are files of their own).
This independent proposal applies directly to upstream main; it requires no prior merge of the separate CR3 proposal #3138. CR3 retains upstream framing and its existing per-file source-position vignetting. The newly added Pool/DNG profile lookup excludes CR3, including a resolved profile that carries both warp and nonzero vignetting.
The synchronized geometry-gated external-profile correspondence fit uses `LOOK_VERSION = 27` and `RENDER_CACHE_VERSION = 88`, after upstream versions 26 and 87, invalidating both stale smart-preview looks and rendered thumbnails. The private-file observations above were recorded on the original proposal.
Version 27 introduced resolved-profile geometry for non-CR3 files. Version 28 extends it to eligible CR3s for file-local fits, pooled calibration and merge/DNG colour tags. Render cache version 89 invalidates thumbnails fitted with the earlier geometry. Existing Smart Previews keep the lens database identity recorded when their originals were decoded.
The fit therefore has a version, `LOOK_VERSION` in `crates/engine/src/camera_preview.rs`, and every smart preview records the version that wrote it in its header line (`look_version`). **Bump the constant in any change that makes the fit give a different result for the same file**: the matrix, hue/saturation, tone or chroma fit, their gates and fallbacks, or how a camera profile feeds them. Changes that leave the fitted look alone don't need it. A header without the field (everything built before it existed) counts as version 0, and so does a value that is not a non-negative integer; a value from a newer build is left alone.
+2 -1
View File
@@ -57,7 +57,8 @@ mode ([mcp.md](mcp.md)) is a thin layer over this channel. Implementation:
Set `LIGHTCRAFT_CONFIG_DIR` to a fresh directory to isolate UI preferences, app logs, the emergency
panic log, the GPU initialization marker, camera profiles and default model folders. The nonempty
value is used as the complete settings directory. Unset retains the normal platform paths; an explicit
empty value disables the settings directory, while the emergency panic log retains its system-temp path.
empty value disables the settings directory, and with it the emergency panic log (panics then go to
standard error only).
Explicit model-directory environment variables still take precedence over their defaults.
Also pass `--library DIR` with a separate scratch library: the configuration override does not change
the default photo-library location. Do not use `--memory` or `LIGHTCRAFT_NO_PREFS` when testing persistence.
+87
View File
@@ -0,0 +1,87 @@
# CR3 profile correspondence geometry
A Canon CR3 can pair different scene points when the camera corrects radial distortion in its
embedded JPEG. During colour calibration, LightCraft compares a resolved lens profile with the
framing it already estimated from the unwarped sensor. The selected geometry determines which
sensor and JPEG samples train the look. The RAW decoder and the Optics setting still determine
how LightCraft renders the photograph.
A resolved external lens profile may propose geometry only for file-local colour calibration
and pooled camera-profile samples, with a fallback camera matrix and no in-file lens warp. The sensor, sensor clip mask, and embedded JPEG are
oriented together before evaluating the already oriented lens profile. White balance and
baseline exposure are applied exactly once before geometry assessment.
The existing fixed-proxy edge test, bounded framing search (scale 0.9–1.1 and translation up to
two proxy pixels), minimum edge coverage, 0.9 agreement, and independent held-out improvement
of at least 0.04 are retained. Geometry uses luminance edge directions, without fitting RGB
values. Accepted geometry moves the sensor and clip mask together; invalid borders remain NaN.
CR3 proposals must also preserve or improve agreement against the existing framed fallback
on both training and held-out edges, compared on the exact intersection of valid edges with
the same reference weights. The published minimum 0.04 improvement over the unframed sensor
is retained separately, using the exact intersection of original and candidate edges and the same
reference weights for each candidate during training and for the held-out check. The fallback
comparison adds no extra improvement threshold. Rejected or absent geometry takes the existing
CR3 framing path. All subsequent colour,
tone, hue/saturation, clipping, and held-out acceptance gates stay unchanged.
The proposal reaches file-local colour and tone, pooled colour pairs and tone samples, and colour tags
for merge/DNG conversion. The DNG colour fit uses the external profile for correspondence geometry
without its vignette gains: the unchanged sensor samples and the DNG writer do not carry that
database shading correction. The file-local fit measures the share of database shading visible in the JPEG
after registration, using each pixel’s source position under the selected framing and warp. Pooled fits apply
the profile’s vignette to the candidate warp. Its edge agreement must match or beat the framing
estimated from the original, unshaded sensor on both splits. A missing or rejected warp preserves
the unshaded colour pairs and tone samples from that framing.
The loaded database semantic identity also invalidates camera render/view keys, Smart-preview
headers and scan markers. Fresh original decodes retain the photo’s hot-pixel setting; offline
proxies remain readable and cannot be relabelled as freshly fitted pixels.
Embedded vignetting is still applied at the source before geometry.
Profile resolution follows the [shared lens lookup rules](lens-profiles.md). With neither a
lens model nor a lens specification, a CR3 can propose the only profile on its camera’s exact,
lowercase-initial fixed mount. An ambiguous mount or an unmatched specification keeps the
framing fallback. A fixed-mount match must pass the same JPEG edge checks as a named lens or
an explicit specification alias. The lookup uses the downloaded database or `LIGHTCRAFT_LENSFUN_DIR`
override and supports reloading. When the camera database has no crop factor, the lookup can
derive the frame crop factor by dividing the 35 mm-equivalent focal length by the actual focal
length. Applying a lens profile requires a known calibration crop factor from the database.
Synthetic tests cover lens-only and lens-plus-framing acceptance, unrelated/flat/already aligned
rejection, crop-relative profile orientation at multiple resolutions, clip-mask contributions,
and the complete CR3 correspondence route for EXIF orientations 1–8 with non-unity white balance.
The opt-in `corpus_cr3_profile_geometry_diagnostics` test creates a fresh numbered directory
under `LIGHTCRAFT_CR3_DIAGNOSTICS` for each run. Its `geometry.tsv` lists each measured file
after all three proxy PNGs have been written. The final `artifact_id` column gives their shared
filename prefix, followed by `-plain.png`, `-chosen.png`, or `-jpeg.png`.
The plain diagnostic route removes only the proposed profile warp. Both routes use the same lens vignetting data.
It reads CR3 files from `$LIGHTCRAFT_CORPUS/raw` and the normal configured lens database.
The TSV includes `status` and `reason` columns. `measured` means both proxy calls returned
images; acceptance or rejection is recorded separately in the existing measurement columns.
If either call returns no proxy, the row records `missing_plain_proxy`,
`missing_chosen_proxy`, or `missing_both_proxies`, leaves all measurement fields empty,
and exports no PNGs for that file. The diagnostic continues with the next CR3. The reason
does not attribute a cause: the proxy API returns only `None`, which can cover unavailable
previews or sensor proxies. An unavailable row is not a passed geometry or colour check.
The PNGs show linear proxy RGB converted to sRGB, without a camera tone curve; they are geometry
inspection aids, not developed image fidelity comparisons. The public-sample assessment below covers both a selected warp and a retained fallback.
Its results apply to those samples and camera settings.
## Historical public-sample assessment
The pre-synchronization assessment used 22 SHA-256-verified, individually CC0-listed raw.pixls.us CR3 files using lensfun
XML data at `43f9e001`. In that assessment, the R100 RAW/C-RAW pair with RF-S18–45 at 18 mm accepts the
new geometry. The other 20 files retain pixel-identical 1600-pixel renders with optics
on/off, including eight R6 Mark II full-frame/crop, RAW/C-RAW and Dual-Pixel variants
of one scene. All 22 retain identical renders without a lens database.
With the same independent baseline-derived radial registration applied to both
outputs, mean DE76 at 768×512 versus the embedded JPEG improves 4.54 to 3.79 (R100 RAW)
and 4.15 to 3.79 (C-RAW) with optics on. Unregistered whole-frame error slightly worsens
because optical framing still differs. This is a modest calibration benefit and does
not remove the photograph's visible lens distortion. The camera JPEG is not a
colorimetric reference. Four 24 MP files (R100 RAW/C-RAW and R6 II full-frame RAW/C-RAW)
render on CPU/Metal within 1/255 per channel, with optics on/off.
The sample set does not establish all-camera correctness. R6 II’s eight variants
share one scene, not eight independent scenes. Pooled-profile and DNG-tag forwarding
are tested synthetically; this is not a real multi-camera calibration or DNG roundtrip.
+14 -3
View File
@@ -6,6 +6,17 @@ preserves Amount and mixes none of the cleaned picture. It affects only the requ
photo, independently of Auto Sync, and is undoable. Manual luminance and colour noise
reduction remain separate controls.
**Denoise Method** chooses the built-in denoiser or an installed model for the active photo.
You can choose a method with AI Denoise switched off. The first time you use AI
Denoise on a photo, it remembers the current default. The choice travels with its
edit history and saved versions. Changing the default later leaves those edits
alone. If the chosen model is missing, reinstall that version or choose another
method for the photo before exporting with AI Denoise. On an older library's
first upgrade, previous denoise edits are assigned the denoiser that the old
version would use. Existing built-in products can be reused. External models
rebuild their cached pictures on demand because older products did not identify
the manifest version or processing parameters.
## The built-in denoiser
AI Denoise needs no set-up. Unless you choose a model of your own (below), it runs the
@@ -132,8 +143,7 @@ ISO 6400 up.
## Models and terms (optional)
**No model weights are bundled.** Choosing a model replaces the built-in denoiser; **Stop using**
(or removing the model) goes back to it. Models live in the per-user `denoise-models` folder
**No model weights are bundled.** Choosing a model in Settings makes it the default for new edits. Models live in the per-user `denoise-models` folder
(override with `LIGHTCRAFT_DENOISE_MODELS`). Settings provides **Install from file…**
for a user-supplied ONNX file with a `denoise-model.json` beside it. The default build
offers no model downloads. The separate `rawnind-model` Cargo feature enables the
@@ -287,7 +297,8 @@ the tile's samples as little-endian half floats, byte-shuffled (low bytes, then
## Commands and limits
UI, CLI, control channel and MCP dispatch `denoise.toggle`, `denoise.settings`,
UI, CLI, control channel and MCP dispatch `denoise.toggle`, `denoise.photo.info`,
`denoise.photo.model`, `denoise.settings`,
`denoise.queue`, `.cancel`, `.status`, `.pump`, `.clear`, and `denoise.models.*`
(`list`, `install`, `download`, `downloads`, `downloadCancel`, `test`, `remove`,
`select`). The develop control is `enhance.denoise`.
+5 -3
View File
@@ -42,6 +42,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app
| 25 | **File writes**: AVIF import; Render to DNG as a catalog command (lossy DNG and the Render to DNG export format landed) (PSD export landed with Edit in PhotoCraft, #953) | file-format-parity.md | interchange edge cases | 19–34 | [file-format-parity](file-format-parity.md) |
| 26 | **Performance at scale**: flags, ratings and edits are written and synced to the catalog log by a thread of its own, so a key never waits for a busy drive (a 300 ms sync: 0.2 ms per flag, was 305 ms), and a write that fails is held, retried and counted as unsaved, never dropped (PERF-STEP-STALL); 85k-photo library opens in 1.7–4.7 s; 100k grid test pending; colour NR at half resolution; at 100k photos stack and album lookups are indexed (an "In a Stack" or "Album" smart album counts in ~14 ms, was 0.6–2.7 s); culling a wedding: first photos of a 2,933-raw folder in 0.9 s and camera JPEGs ready ahead of each step, but a full-size 45 MP camera JPEG still takes ~150 ms to decode (held-arrow stepping at a 2,560 px loupe can outrun it), the 100 % view of the raw itself still takes ~5 s to render (the camera JPEG is shown at 100 % meanwhile, ~0.9 s), and browsing or importing still reads and hashes every raw whole (~10 ms a file on SSD, ~1 s a 25 MB file from a NAS); the loupe uses built previews and photos are prepared ahead and the whole view in the background (face detection, AI masks and denoise are not yet part of that preparation) | ROADMAP log, gpu-pipeline.md | large-catalog users | 15–30 | [target-app-parity](target-app-parity.md#by-dimension) |
| 27 | **Windows / Linux runtime coverage**: the Windows x64 installer is verified on Windows 11 (0.9.1: install and upgrade end on the completion page, a custom folder is kept, Launch works, removal is clean), but uninstalling from Settings → Apps ends with no confirmation (#892, #931); GPU path proven on Apple and on one AMD GPU on Linux (Radeon 8060S, Vulkan); NVIDIA, Intel and DX12 unverified; Windows DirectComposition VRR workaround implemented, monitor verification pending; the Linux riscv64 tarball (new in 0.6.0, #844) is cross-compiled and never run beyond a QEMU smoke test | ROADMAP, issues, `release.yml` | non-Mac users find bugs first | 13–27 | [hardware-parity](hardware-parity.md) |
| 32 | **Panorama verification in moving scenes** (LR-MERGE-PANO, LR-MERGE-HDRPANO): genuine overlaps can fail the inlier-fraction gate; omitted source photos are now reported | #1765; original procedural known-homography and parallax tests in `crates/merge/tests/pair_verification.rs`; the [waterfall raws](https://github.com/storytold/lightcraft/issues/1765#issuecomment-7026674014) still register as two groups | panoramas may omit part of the scene | not estimated | [merge](merge.md#panorama-inclusion-diagnostics) |
| 29 | **HDR merge leftovers** (LR-MERGE-HDR): AI Denoise doesn't run on merged (linear) DNGs; JPEG brackets are treated as linear (no camera response curve); every frame is held as 32-bit float, ~0.86 GB per 67 MP frame (half-float frames would halve it) | tested on Sony A7R VI brackets 2026-10-14 ([merge.md](merge.md)); Lightroom's Denoise supports HDR DNGs | HDR shooters who denoise their merges, merge JPEGs, or merge 7+ frames of high-resolution raws on 16 GB machines | 10–20 (+ denoise linear-RGB contract, gap 11) | [merge](merge.md) |
| 28 | **Small Classic shortcuts and keys**: Tab (hide the side panels; Tab moves the keyboard focus here) and F5. Rating `[` `]`, flag cycling (`` ` ``), `\` (Filter Bar), ⌘L (Enable Filters), ⌘⌥⇧C / ⌘⌥⇧V (Copy / Paste Metadata), F1 help, F6 / F7 / F8 (filmstrip, left panel, right panel) and ⇧Tab (all panels) are bound; the grid-cycle key is shown beside both grid rows in View (#2500) | [ui-parity](ui-parity.md#shortcuts) | Classic muscle memory | 2–4 | [ui-parity](ui-parity.md) |
| 30 | **Multi-select metadata editing in the UI**: `photo.setMeta` already iterates all selected photos, so the engine applies changes to every target. The Info panel's Show Metadata For choice (Target Photo / Selected Photos) shows the values the selected photos share and marks each field where they differ as Mixed; the All Metadata dialog still shows one photo's values with no "mixed" indication | standard in Lightroom Classic's multi-select Info panel | anyone editing metadata on a batch (copyright, keywords, custom fields) | 1–3 | [ui-parity](ui-parity.md) |
@@ -57,7 +58,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w
- **File format:** 2, 6, 7, 10, 13, 20, 25 (raw ones in [raw-parity.md](raw-parity.md))
- **Hardware:** 14, 17, 22, 27
- **Localization:** 21
- **Quality / fidelity:** 1, 3
- **Quality / fidelity:** 1, 3, 32
- **Stability and platforms:** 9, 26, 27
## Closed recently (kept for calibration)
@@ -143,6 +144,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w
| 2026-10-19 | minor | Gap 9 shrinks: `.github/workflows/ci.yml` runs `cargo xtask ci` on Linux x64 for every PR and push to main; macOS and Windows remain |
| 2026-10-19 | minor | Gap 21: Indonesian (`id`) shipped with every catalog message but What's New; four new languages left (Hindi, Arabic, Korean, Vietnamese), 135–239 h |
| 2026-10-19 | minor | Gap 27: the released 0.9.1 x64 MSI is tested on Windows 11 Pro 24H2 (a fresh install and an upgrade from 0.8.0 end on the completion page, so #790 is fixed; the upgrade keeps a custom folder; Launch starts the app; removal leaves nothing behind); uninstalling from Settings → Apps still ends with no confirmation (#892, #931); hours unchanged |
| 2026-10-21 | minor | Gap 32 records unresolved panorama verification (#1765); included counts and omitted filenames are now reported |
| 2026-10-18 | patch | Gap 1: six X-Trans CMOS 4 Fujifilm bodies (X-T30 …) take the X-T3's spectral matrices instead of the neutral matrix |
| 2026-10-15 | minor | Gap 15 shrinks: the Page panel's Page Options (Page Numbers, Page Info, Crop Marks) print on Single Image and Contact Sheet pages; identity plate, watermark, photo info, Cut Guides, direct printing and JPEG output remain |
| 2026-10-14 | minor | Gap 4 follow-up: the diagnostic overlays (Visualize Spots, Point Color range, HDR range) render zoom windows too; soft proofing runs on the GPU |
@@ -205,6 +207,6 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w
| 2026-10-25 | minor | Gap 1: first chart-calibrated model, the Canon EOS D60 (ColorChecker Classic under tungsten and sun, `crates/raw/src/chart_table.rs`); the gap stays open, hours unchanged |
| 2026-11-05 | minor | Gap 9: a Windows leg runs clippy and the tests of the crates with Windows-only code when a pull request or push changes that code, or a pull request is labelled `full-ci`; gap not closed (macOS, GPU tests) |
## Proposed external-profile correspondence geometry
## External-profile correspondence geometry
Camera colour calibration remains open. PR #2675 proposes geometry-gated external-profile alignment for file-local RAW colour fitting and pooled calibration, plus unique exact-mount lookup for unnamed fixed lenses. It preserves in-file geometry and the established CR3 framing path, applies source-position vignetting before geometry, and uses held-out edge agreement rather than RGB error to accept a candidate. Historical private-file observations and their limits are recorded in [Camera preview colour](camera-preview-colour.md); they are not a claim of validation of this rebased source.
Camera colour calibration remains open. LightCraft checks resolved lens geometry against held-out JPEG edges for file-local and pooled fits. It can resolve an unnamed fixed lens through a unique exact mount (#2675). For CR3 the profile must also match or improve on the accepted framing. The public Canon results and their limits are recorded in [CR3 profile alignment](cr3-profile-alignment.md). The historical fixed-lens results are in [Camera preview colour](camera-preview-colour.md).
+5 -1
View File
@@ -113,7 +113,11 @@ after settings and library are saved): `gpu::begin_shutdown()` — from then on
on the CPU — then the render pool stops (queued jobs dropped, running ones waited for) and
`gpu::wait_idle` waits for GPU work on other threads (export, denoise, the device warm-up). One
deadline of 2 s covers it all; past it the app quits anyway. A job pool that is dropped (headless
hosts, tests) waits for its running jobs the same way (`JobPool::shutdown`, `crates/preview/src/pool.rs`).
hosts, tests) waits for its running jobs the same way (`JobPool::shutdown`, `crates/preview/src/pool.rs`),
and a dropped `LightcraftApp` waits, bounded, for a device warm-up still loading the driver
(`gpu::wait_warm_up`; the warm-up counts from the moment `gpu::warm_up` is called) unless `shutdown`
already ran. Without that, a test process ending a few milliseconds after its first frame crashed or
hung inside the Vulkan loader as it opened the driver.
**Crash sentinel.** The desktop app writes `gpu-init.marker` into its settings folder (next to
`ui.json`: `%APPDATA%\LightCraft`, `~/Library/Application Support/LightCraft`,
+3 -2
View File
@@ -94,8 +94,9 @@ A raw whose look is fitted to its own camera JPEG (Sony, Nikon, Pentax, Olympus
matrix, and a DNG whose tone is fitted to its preview, [camera-preview-colour.md](camera-preview-colour.md)) has that fit made on the sensor with only the
share of a profile's vignetting correction its camera JPEG shows, measured per photo: the profile describes the
lens, not what the camera did to its JPEG relative to the raw (a Sony JPEG with shading compensation Auto can show
none of it). When the share can't be measured (too few usable pixels, or a lens-warped sensor proxy) the fit keeps
the whole correction. The render still applies the profile at the Vignetting amount.
none of it). With an accepted CR3 lens warp, the fit follows the JPEG framing and warp back to the sensor
position for each gain. It keeps the whole correction when the share cannot be measured, for example when too few
usable pixels remain or the warp's source positions are unavailable. The render still applies the profile at the Vignetting amount.
Normalisation follows lensfun's documentation: distortion and TCA radii are 1 at half the shorter side of the
calibration frame (its `cropfactor` and `aspect-ratio`), vignetting radii 1 at its corner; the optical centre is
+42 -3
View File
@@ -24,6 +24,41 @@ All algorithms are our own implementations from published papers (cited in the m
among the files, e.g. a whole folder);
`lightcraft-cli synth-merge hdr|panorama -o DIR` writes synthetic inputs (procedural scene).
## Panorama inclusion diagnostics
Panorama and HDR panorama results include `used` (source photo IDs, in source order),
`omitted` (`{id, path, reason: "notRegistered"}`), and `pairs`. Each pair has `a` and `b`
(source photo ID arrays), `matches`, `inliers` (null if no fit was returned), and `status`:
`insufficientMatches`, `noModel`, `rejected`, or `accepted`. HDR panorama expands each
stitched bracket to all of its source photos. The result keeps the first 1,024 pairs in
input order. `pairsTruncated` is true when there are more pairs. All pairs are still
verified, and the `used` and `omitted` lists cover every source photo. A preview and a full
merge can use different photos because they run at different resolutions.
The preview lists omitted filenames and the included count. The completion message uses
the final merge's count. When the final merge omits photos, a Photo Merge Result dialog lists
the final result's omitted filenames, because they can differ from the preview's: the preview
registers copies at most 1,024 pixels on the long side, and the final merge registers the
full-size photos again. Pair measurements also appear at debug log level, including when
registration fails entirely. An accepted pair can belong to a component that is not used.
`notRegistered` means the photo has no camera in the final registered set. It does not
establish missing overlap, moving water, or parallax as the cause.
Issue [#1765](https://github.com/storytold/lightcraft/issues/1765) and @aterveus's
[logging prototype](https://github.com/aterveus/lightcraft/commit/49054c2b94) prompted these
diagnostics. Their [lower-slope experiment](https://github.com/aterveus/lightcraft/commit/e7ed794c72)
identified a useful test regime. The verification threshold remains `inliers > 8 + 0.3 * matches`:
original procedural correspondence tests recover known homographies with 30 to 36 inliers
among 100 to 140 matches, then reproduce their rejection. A slope of 0.15 also accepts the
tests' coherent wrong panel match and translated-camera parallax. Spatial spread and a
small reprojection error alone do not distinguish all of these cases.
The [waterfall registration report](https://github.com/storytold/lightcraft/issues/1765#issuecomment-7026674014)
found two groups in the original raws. No pair between the groups reached the minimum
inlier count for a model, so changing the verification slope would leave those groups
apart. A separate three-frame moving-texture experiment fails registration, while its
clean control registers all three frames.
## What it does
**HDR** (`hdr.rs`): frames ordered by EXIF exposure (or median luminance); the middle one is the
@@ -58,9 +93,10 @@ Warp: a separable stretch of the smoothed valid-area edges to the canvas edges.
largest rectangle of image data (set as the develop crop, so it stays adjustable). Fill Edges:
push–pull diffusion. Output: 16-bit integer DNG (16-bit float for HDR panoramas).
**DNG output** (`output.rs`): LinearRaw, 3 samples, Deflate tiles; values scaled below 1.0 with the
scale in `BaselineExposure`; raw sources keep their DNG colour tags (camera RGB), other sources get
`ColorMatrix1`/`ForwardMatrix1` of their RGB space.
**DNG output** (`output.rs`): LinearRaw, 3 samples; Deflate tiles for float samples, lossless JPEG
tiles for 16-bit integer; values scaled below 1.0 with the scale in `BaselineExposure`; raw sources
keep their DNG colour tags (camera RGB), other sources get `ColorMatrix1`/`ForwardMatrix1` of their
RGB space.
## Measured (synthetic tests, `cargo test -p lightcraft-merge`)
@@ -75,6 +111,9 @@ scale in `BaselineExposure`; raw sources keep their DNG colour tags (camera RGB)
## Limits (known gaps)
- Pair verification can reject genuine overlaps in moving scenes (#1765). Omitted photos are
reported, but a safer acceptance policy still needs validation on real inputs.
- No lens-distortion model in the panorama bundle adjustment (rectilinear lenses assumed); no
360° wrap-around; flat (translating-camera) scans are fitted with the rotation model. Panoramas and HDR
panoramas carry no lens corrections, nor does an HDR whose frames don't share an orientation (they are turned
File diff suppressed because one or more lines are too long
+6 -2
View File
@@ -19,9 +19,11 @@ stronger Light sliders, issue #196) without changing a single photo someone has
| **V8** | V7 plus: Highlights and Shadows take their edge-aware filter of log luminance without its fine detail (`local::detail_free`: each value clamped between its separable median at the V2 radius and the median of a 3× wider neighbourhood) instead of V2's plain median (`local::base_keeps_gaps`), so the gaps in dark lettering on a bright panel are not lifted into bright blocks (issue #3460). CPU (`local::tone_base`) and GPU (`render::tone_base`) branch on it; the base plane is keyed by process. Renders without Highlights or Shadows (global or local) are the same as V7's. |
| **V9** *(none)* | No process has this number: a saved 9 renders as V8, and Update to Current Process moves it to the latest. |
| **V10** | V8 plus: checked Bradford white-balance fallback (`craft_color_transform::cct::wb_matrix`, returning `Mat3::IDENTITY` when a source illuminant's Bradford blue cone response `s[2] <= 0.0`, `craft-libs#587`). V1 to V8 keep the legacy Bradford result for saved edits (`local::wb_matrix_for`). |
| **V11**, **V12** *(none)* | No process has 11; 12 is left to the open pull request that claims it (#4047). A photo saved with either renders as V10, and Update to Current Process moves it to the latest. |
| **V11**, **V12** *(none)* | No process has 11 or 12. A photo saved with either renders as V10, and Update to Current Process moves it to the latest. |
| **V13** | V10 plus: global Shadows eases off at large amounts (`finish::tone_slider`): the strength the local tone operator takes is `a / (1 + 1.33·abs(a))` for `a` = slider / 100, so the easing grows with the amount (slope 1 at 0; +10 acts at 0.88 of V6's) and ±100 acts at 0.43 of V6's. Fitted to 56 Lightroom exports of real portrait edits of Canon raws (Shadows +40 to +100), against which V6 rendered the darkest tones about 6 L* too light. Global Highlights stays linear: on the same edits V6 renders the brightest tones about 5 L* too dark, but single-slider exports show Lightroom's response to Highlights alone close to linear and dependent on the frame's content (#3923), which a fixed easing would not follow. Masks keep their linear amounts; Shadows amounts between 0 and +40 had no exports to check. CPU and GPU take the strength from `FinishParams`. Renders with Shadows at 0 are the same as V10's unless Texture is negative or the Global wheel is set. Also from V13: a negative global Texture smooths at 0.67 of V6's strength (`finish::texture_slider`; at −27, V6 left the 1–8 px detail of four full-size Lightroom exports of Canon EOS R6 edits at 0.87–0.94 of theirs, and 0.67 brings it to 0.94–1.02); and the global colour-grading wheel tints at 0.45 of the other wheels at the same saturation (`colorops::global_wheel`; V6 left photos graded Global 10 and 16 about +2 b* warmer than the exports). Positive Texture, the shadows, midtones and highlights wheels and masks are unchanged. |
| **V14** (the latest) | V13 plus: Heal spots, and Remove spots with their automatic source, are pinned to the photo on the spot's edge (`spots::pinned`, [heal-pinned.md](heal-pinned.md)). The patch is the source times `e^P`, `P` the membrane fill (`lightcraft_inpaint::membrane_fill`) of the log ratio of photo to source, known only on the ring of pixels touching the spot and blurred there over the outside only (1.5 px), so the patch meets its surroundings at the edge, takes nothing from features that don't touch it, and carries the source's texture at its contrast relative to the new light. The source's fine detail (log luminance minus a 1.5 px blur) is scaled to the detail around the spot, by the ratio of medians around the spot (1.05 to 2 radii) and inside the source (0.9 radii), within 0.5 to 2×. Every spot, Clone included, reads its source at whole pixels (read between pixels, bilinear sampling halved the grain). V1 to V13 keep the source plus a Gaussian-weighted average of the difference around the spot (σ 0.6 radii) in linear light. A Heal or Remove spot whose working box holds more than `MAX_SPOT_SPAN² / 2` pixels (about 33.5 million; 8.4 million on the web) is too big for the pinned heal's working memory and gets the V13 averaged correction instead, still reading its source at whole pixels. Fill is unchanged. CPU and GPU branch on `spots::HealMethod`; the GPU renderer reads the image back for the spot stage on V14 photos with spots and keeps the rest of the render on the device. Renders without Heal, Remove or Clone spots are the same as V13's. |
| **V14** | V13 plus: Heal spots, and Remove spots with their automatic source, are pinned to the photo on the spot's edge (`spots::pinned`, [heal-pinned.md](heal-pinned.md)). The patch is the source times `e^P`, `P` the membrane fill (`lightcraft_inpaint::membrane_fill`) of the log ratio of photo to source, known only on the ring of pixels touching the spot and blurred there over the outside only (1.5 px), so the patch meets its surroundings at the edge, takes nothing from features that don't touch it, and carries the source's texture at its contrast relative to the new light. The source's fine detail (log luminance minus a 1.5 px blur) is scaled to the detail around the spot, by the ratio of medians around the spot (1.05 to 2 radii) and inside the source (0.9 radii), within 0.5 to 2×. Every spot, Clone included, reads its source at whole pixels (read between pixels, bilinear sampling halved the grain). V1 to V13 keep the source plus a Gaussian-weighted average of the difference around the spot (σ 0.6 radii) in linear light. A Heal or Remove spot whose working box holds more than `MAX_SPOT_SPAN² / 2` pixels (about 33.5 million; 8.4 million on the web) is too big for the pinned heal's working memory and gets the V13 averaged correction instead, still reading its source at whole pixels. Fill is unchanged. CPU and GPU branch on `spots::HealMethod`; the GPU renderer reads the image back for the spot stage on V14 photos with spots and keeps the rest of the render on the device. Renders without Heal, Remove or Clone spots are the same as V13's. |
| **V15** | V14 plus: brush Flow is the coverage a stroke adds per brush radius it travels, as in Lightroom Classic (#4045): each dab adds `1 − (1 − flow)^(d / r)` for a dab `d` past the previous one (the first dab counts one radius, so a click paints its flow), `masks::travel_flow`. A point a stroke passes over for a length `L` is then covered by `1 − (1 − flow)^(L / r)` however densely the dabs lie: a straight stroke's centre by 44 % at Flow 25 and 75 % at Flow 50, where Lightroom Classic measures 41 % and 76 % on a grey card. V1 to V14 add the full flow per dab (r/4 apart on a fast drag, closer on a slow one): 90 % at Flow 25 on a fast stroke, more on a slow one. CPU (`masks::brush_dabs_within`), GPU (a flow per dab in the `shape` kernel's brush data) and the live stroke (`brush_live`, the masking and Lens Blur brushes) all branch on `masks::flow_per_radius`. Renders without brush strokes, or with Flow 100 only, are the same as V14's. |
| **V16** (the latest) | V15 plus: a brush stroke's edge is feathered as one dab's is. Each stroke keeps its Flow build-up (every dab that reaches a pixel adds its flow, `masks::feather_dab`) apart from its edge (the highest falloff of those dabs), and covers their product up to Density (`masks::stroke_coverage`). V1 to V15 accumulate each dab's falloff times its flow, so the soft edges of dabs r/4 apart piled up: at Feather 100 and Flow 100 a straight stroke covered 0.90 halfway out from its centre line, where one dab covers 0.50; V16 covers 0.50. Below Flow 100 the centre now builds up by Flow per radius travelled whatever the Feather (a straight stroke's 44 % at Flow 25), where V15 also weakened a soft brush's centre (25 %). CPU (`masks::rasterize_brush`), GPU (a stroke-record word in the `shape` kernel's brush data) and the live stroke (`brush_live`, the masking and Lens Blur brushes) branch on `masks::stroke_feather`. Auto Mask strokes keep V15's accumulation (their edge follows the photo's edges, not the feather). Renders without brush strokes, or with Feather 0 or Auto Mask brushes only, are the same as V15's; a saved V1 to V15 photo keeps its strokes until Update to Current Process. |
## The rule
@@ -131,6 +133,8 @@ extra field and retain their existing cached renders. No cache-version bump is n
| Date | Change | Summary |
|---|---|---|
| 2026-12-02 | minor | V16: a brush stroke's edge is feathered as one dab's is; V1 to V15 keep the accumulated soft edges |
| 2026-11-24 | minor | V15: brush Flow per brush radius travelled, as in Lightroom Classic; V1 to V14 keep the flow per dab. 12 is no longer claimed |
| 2026-11-08 | minor | V8: the Highlights/Shadows base keeps the gaps in dark lettering (#3460) |
| 2026-11-07 | minor | V7: film grain from crystal layers ([grain.md](grain.md)); V1 to V6 keep their value noise |
| 2026-11-23 | minor | V13 (11 and 12 left to open claims): global Shadows eases off at large amounts, negative Texture and the global grading wheel act less, fitted to Lightroom exports; Highlights stays linear |
+3 -2
View File
@@ -12,7 +12,7 @@ have their own documents: [raw-parity.md](raw-parity.md), [file-format-parity.md
| Number | Value | Kind |
|---|---:|---|
| **Feature breadth**, checklist | **83.2%** of 543 in-scope rows (P0 97.5%, P1 94.4%, P2 56.7%) | **measured**: recount of [parity-checklist.md](parity-checklist.md) rows (✅ 1, 🟡 ½, 🚫 left out), the same rule `cargo xtask parity` uses |
| **Feature breadth**, checklist | **83.2%** of 546 in-scope rows (P0 97.5%, P1 94.2%, P2 56.7%) | **measured**: recount of [parity-checklist.md](parity-checklist.md) rows (✅ 1, 🟡 ½, 🚫 left out), the same rule `cargo xtask parity` uses |
| **Feature breadth**, weighted by use | **~77%** | estimated: feature-area table below |
| **Ready for real work** (full target) | **~62%** (range 57–67%) | estimated: weighted sum over the dimensions with written weights, see [below](#ready-for-real-work-mainstream-practitioner-and-essentials-user) |
| **Mainstream practitioner** | **~51%** (range 46–56%) | estimated: weekly areas of a working photographer, depth 74.5% × 0.804 × colour 0.85 |
@@ -75,7 +75,7 @@ from the checklist sections and the deep-dive documents.
| Remove, heal, Enhance (denoise, Raw Details, Super Resolution, Lens Blur) | 7% | 45% | 30% | 70–130 h | checklist I 75%, P 0% |
| Presets, profiles, versions, history, sync | 5% | 95% | 85% | 8–15 h | |
| Export | 6% | 89% | 75% | 15–30 h | checklist S 88.9% |
| Merge and HDR | 3% | 85% | 60% | 20–35 h | merge 88% (HDR merge 🟡: AI Denoise on merged DNGs, JPEG response, memory; gap 29), HDR 70% (no HDR display) |
| Merge and HDR | 3% | 85% | 60% | 20–35 h | merge 63% (HDR limitations, gap 29; panorama and HDR panorama verification in moving scenes, gap 31), HDR 70% (no HDR display) |
| Views, compare, zoom, culling | 5% | 90% | 70% | 15–30 h | zoom detail P0 gap |
| Classic output modules (Map, Book, Slideshow, Print, Web, publish, tethering) | 4% | 15% | 10% | 90–150 h | Classic extras 48% counts many small keys; the modules themselves are mostly ⬜ |
| Video | 1% | 0% | 0% | 25–45 h | catalogued only |
@@ -310,6 +310,7 @@ P2 items 12–25 h; look tuning, performance, packaging, hardening 25–45 h.
| 2026-10-22 | minor | Tone Curve input histogram (#987); headline counts and readiness estimates unchanged. See [the stage contract](tone-curve-input.md). |
| 2026-10-19 | minor | Localization ~55% → ~64% (mean of the 12 key languages): Indonesian (`id`) catalog, every message but What's New; full target 61.2% → 61.5% (still ~61%) |
| 2026-10-19 | patch | Platforms: the Windows installer is no longer listed as unverified (the 0.9.1 x64 MSI is tested on Windows 11; a confirmation after uninstalling from Settings → Apps, #892, remains); #790 noted as fixed in 0.9.1; percentages and hours unchanged |
| 2026-10-21 | minor | Panorama and HDR panorama marked partial (#1765): omitted photos are reported; verification remains unresolved. Checklist recount 83.5% to 83.3% (543 rows); refreshed the stale headline from the checklist. Readiness estimates unchanged |
| 2026-10-17 | minor | Object / Describe masks: SAM 3's text detector mask decoder also on the GPU outside macOS; status unchanged |
| 2026-10-17 | minor | Object / Describe masks: SAM 3's necks and text detector's encoder also on the GPU outside macOS; status unchanged |
| 2026-10-17 | minor | Object / Describe masks: SAM 3's image encoder runs on the GPU through wgpu on Windows and Linux (CPU fallback); status and numbers unchanged |
+24
View File
@@ -1,5 +1,19 @@
# What's new in LightCraft
## Unreleased
### Brush Feather works on strokes (process 16)
- A brush stroke's edge now fades over the Feather you set. Overlapping dabs used to pile their soft edges up into an
almost hard one: at Feather 100 and Flow 100, halfway out from a stroke's centre line was 90 % covered, and is
now 50 %, as one dab is. Below Flow 100 a soft brush's centre builds up as a hard one's does, and Feather shapes only
the edge. Auto Mask strokes, whose edge follows the photo's, are unchanged. New photos (and Reset) get it;
photos you already edited keep their brushes until Photo ▸ Update to Current Process.
### Brush Flow as in Lightroom (process 15)
- Flow now builds up the way it does in Lightroom: one stroke at Flow 25 covers a little under half, at Flow 50 about
three quarters, where it used to cover 90 % and more, and a slow stroke covers the same as a fast one (issue #4045).
New photos (and Reset) get it; photos you already edited keep their brushes until Photo ▸ Update to Current Process.
## 2026-10-31
### Filter for unrated photos
@@ -1000,6 +1014,16 @@
## 2026-10-22
### The crash log moved to the settings folder
- The desktop app keeps `lightcraft-panics.log` in its settings folder now, next to `logs/`, instead of the system
temp folder (issue #2572). On Linux and FreeBSD every user shares that folder, so someone else could create the
file first to read what LightCraft wrote there, or plant a link that made it write into another file. A `--memory`
session, `LIGHTCRAFT_NO_PREFS` and an empty `LIGHTCRAFT_CONFIG_DIR` keep no crash log; panics still go to standard
error.
- An empty or relative `HOME`, `APPDATA` or `XDG_CONFIG_HOME` no longer puts the settings folder (and the crash log
and logs in it) under the folder LightCraft was started from: it is ignored (`XDG_CONFIG_HOME` then gives way to
`HOME`), and with no usable one there is no settings folder: panics then go to standard error only.
### Exports don't create a photo's sidecar
- Saving an export, a preset or any other file as `IMG_1.xmp` or `IMG_1.jpg.xmp` in the folder of the library photo
`IMG_1.jpg` is now refused when no sidecar is there yet, as writing over an existing one already was. The library