diff --git a/Cargo.lock b/Cargo.lock index 2fa44bb74f..cfde6aecf5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4339,6 +4339,7 @@ dependencies = [ "lightcraft-raster", "lightcraft-raw", "lightcraft-scenes", + "log", "rayon", "serde", "thiserror 2.0.21", diff --git a/README.md b/README.md index 432cd16104..d44d42ef17 100644 --- a/README.md +++ b/README.md @@ -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). diff --git a/README.zh-hans.md b/README.zh-hans.md index 054f2c1e81..19acb941f6 100644 --- a/README.zh-hans.md +++ b/README.zh-hans.md @@ -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)。 diff --git a/README.zh-hant.md b/README.zh-hant.md index c8079956f0..da578c10af 100644 --- a/README.zh-hant.md +++ b/README.zh-hant.md @@ -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)。 diff --git a/ROADMAP.md b/ROADMAP.md index 960b1fa0ec..5194bb7399 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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 | diff --git a/apps/lightcraft/src/launch.rs b/apps/lightcraft/src/launch.rs index 953ca43eb9..81f3dca90b 100644 --- a/apps/lightcraft/src/launch.rs +++ b/apps/lightcraft/src/launch.rs @@ -105,19 +105,47 @@ pub(crate) fn control_port_from(what: &str, value: Option) -> Option Option, - temp: std::path::PathBuf, - profile: Option, -) -> 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 { + 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) -> Option { + 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 { + 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 { 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(); } } diff --git a/apps/lightcraft/src/logging.rs b/apps/lightcraft/src/logging.rs index 70d06a8c48..7202939f16 100644 --- a/apps/lightcraft/src/logging.rs +++ b/apps/lightcraft/src/logging.rs @@ -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| { diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 1d4642035b..643d8c9937 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -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)] @@ -440,16 +440,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 /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 @@ -479,6 +469,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; diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index 0d0987d6f4..39225b1a61 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -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 { + 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) -> 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) -> 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, + resolve: impl FnOnce() -> Result, + ) -> 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 { diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 61e5a04670..f243cb02cb 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -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) -> 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))?; diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 42bf566359..4b41a51012 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -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> { + /// Every stored develop state, including the import look, history and versions. + pub fn settings_holders_mut(&mut self) -> impl Iterator> { 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; diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index c123b97181..43ab99fa1a 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -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::(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"); } diff --git a/crates/develop/src/lib.rs b/crates/develop/src/lib.rs index 1bd8e686de..4b51fc19d1 100644 --- a/crates/develop/src/lib.rs +++ b/crates/develop/src/lib.rs @@ -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 { 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 diff --git a/crates/develop/src/presets.rs b/crates/develop/src/presets.rs index 8ce6fc5c0f..0f4b21c8c7 100644 --- a/crates/develop/src/presets.rs +++ b/crates/develop/src/presets.rs @@ -257,6 +257,8 @@ fn interpolate_object(base: Option<&Map>, patch: &Map 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), }; diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index eb53c3a843..5bfb880f65 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -1488,12 +1488,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, +} + +#[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, + #[serde(skip_serializing_if = "Option::is_none")] + pub denoise_model: Option, pub raw_details: bool, pub super_resolution: bool, } @@ -1502,6 +1513,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) diff --git a/crates/engine/src/cmd/denoise.rs b/crates/engine/src/cmd/denoise.rs index 52686a5a15..599f8daf5b 100644 --- a/crates/engine/src/cmd/denoise.rs +++ b/crates/engine/src/cmd/denoise.rs @@ -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 { 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 { + 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, installed: bool, selected: bool, accepted: &Value) -> Value { json!({ @@ -240,11 +247,7 @@ fn activate_install(s: &mut Session, result: &Value, model: Arc Result { 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 { fn remove(s: &mut Session, p: &Value) -> Result { 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 { fn select(s: &mut Session, p: &Value) -> Result { 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 { // 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) -> Value { v } +fn target_photo(s: &Session, p: &Value, command: &str) -> Result { + 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 { + 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 { + 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 { 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 { 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 { pub fn specs() -> Vec { 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 ), diff --git a/crates/engine/src/config.rs b/crates/engine/src/config.rs index 7d010774d5..c5ed4c6ad4 100644 --- a/crates/engine/src/config.rs +++ b/crates/engine/src/config.rs @@ -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, portable: impl FnOnce() -> Option) -> Option { 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, 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() { diff --git a/crates/engine/src/denoise.rs b/crates/engine/src/denoise.rs index 1eb2544d4b..a99314919c 100644 --- a/crates/engine/src/denoise.rs +++ b/crates/engine/src/denoise.rs @@ -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}; diff --git a/crates/engine/src/denoise/model.rs b/crates/engine/src/denoise/model.rs index 70dea39ffe..332b7fb95f 100644 --- a/crates/engine/src/denoise/model.rs +++ b/crates/engine/src/denoise/model.rs @@ -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>>>; +type CachedNetwork = Mutex>>; +pub(crate) type ModelSlot = Arc; + +/// Only the most recently loaded network stays resident between jobs. Concurrent inference owns its own Arc. +#[derive(Default)] +pub(crate) struct WarmModel(Mutex>); + +impl WarmModel { + pub(super) fn keep(&self, slot: &ModelSlot, model: Arc) { + 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(); + } + } +} diff --git a/crates/engine/src/denoise/products.rs b/crates/engine/src/denoise/products.rs index 8aab9a2a4d..deb0bd03a0 100644 --- a/crates/engine/src/denoise/products.rs +++ b/crates/engine/src/denoise/products.rs @@ -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, /// Tiles run at once. pub parallel: usize, /// Where the model runs (the setting). @@ -140,8 +149,15 @@ pub(super) fn loaded(spec: &JobSpec) -> Result, 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) } diff --git a/crates/engine/src/denoise/session.rs b/crates/engine/src/denoise/session.rs index b01a669bb5..1704268456 100644 --- a/crates/engine/src/denoise/session.rs +++ b/crates/engine/src/denoise/session.rs @@ -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) { + if let Some(a) = self.denoise.registry.get(id) { + self.denoise.warm_model.keep(&a.model, model); + } + } + + pub(crate) fn denoise_manifests(&self) -> Vec { + self.denoise.registry.values().map(|a| a.manifest.clone()).collect() + } + + pub(crate) fn denoise_pin(&self, id: &str) -> Result { + 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 = 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 = 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 { + fn denoise_job_spec(&self, p: &Photo, settings: &DevelopSettings, parallel: usize) -> Option { 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); @@ -296,6 +389,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 +447,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 +479,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 +577,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 +605,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, 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(); diff --git a/crates/engine/src/denoise/settings.rs b/crates/engine/src/denoise/settings.rs index 247007cbd8..5783ea9c33 100644 --- a/crates/engine/src/denoise/settings.rs +++ b/crates/engine/src/denoise/settings.rs @@ -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, + /// 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, /// 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, @@ -64,8 +67,60 @@ pub(crate) fn read_capped(path: &Path, max: usize) -> Option> { (buf.len() <= max).then_some(buf) } +fn read_settings_checked(dir: &Path) -> Result { + 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 { + 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 { + 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 { + 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 { + 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) }) } } diff --git a/crates/engine/src/denoise/state.rs b/crates/engine/src/denoise/state.rs index 027ce0a43f..7b780e4a22 100644 --- a/crates/engine/src/denoise/state.rs +++ b/crates/engine/src/denoise/state.rs @@ -103,7 +103,15 @@ pub(crate) struct State { pub(crate) install: Option, /// How a model is loaded (tests put another in). pub loader: Loader, + pub(super) warm_model: Arc, + /// Effective default, sharing its loaded model with the registry. pub(crate) active: Option, + pub(super) registry: std::collections::BTreeMap, + /// Product names in this library, including those used only by a saved version. + pub(super) products: super::HashSet, + /// 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, /// `settings.json` as last read (with the model choice). pub(crate) settings: Settings, @@ -129,7 +137,11 @@ 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, @@ -154,12 +166,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; diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 86827a93ed..450b77f5db 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -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) { + 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 { 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 diff --git a/crates/engine/src/import/defaults.rs b/crates/engine/src/import/defaults.rs index 72e4019d22..5f710b1d4e 100644 --- a/crates/engine/src/import/defaults.rs +++ b/crates/engine/src/import/defaults.rs @@ -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`). diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6042b51c8e..a5e96752f0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -764,6 +764,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]; @@ -773,6 +774,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), @@ -784,6 +790,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); } @@ -888,7 +897,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(()) } @@ -1095,7 +1104,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; @@ -1174,6 +1184,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"); @@ -1215,10 +1232,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 { 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 diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 2664526102..effc5d5e42 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -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 diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 914c70c7c9..4f4cf0b2cb 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -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 = 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; diff --git a/crates/engine/src/media/render.rs b/crates/engine/src/media/render.rs index a7f21c8a49..87f1ba5bdf 100644 --- a/crates/engine/src/media/render.rs +++ b/crates/engine/src/media/render.rs @@ -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()) { diff --git a/crates/engine/src/media/session.rs b/crates/engine/src/media/session.rs index 1c71afdd63..7c69f949ae 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -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, 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); } diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index e330fe6982..e54d351cba 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -136,6 +136,8 @@ pub type PairLoader = Arc) -> 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, /// The Amount (in thousandths) and the picture mixed for it, so dragging other sliders keeps one source picture. mix: std::sync::Mutex)>>, @@ -143,7 +145,7 @@ pub struct Twin { impl Twin { pub fn new(image: Arc) -> 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 +345,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, diff --git a/crates/engine/src/media/thumbnail_hash_tests.rs b/crates/engine/src/media/thumbnail_hash_tests.rs index 9379288e26..009720a67c 100644 --- a/crates/engine/src/media/thumbnail_hash_tests.rs +++ b/crates/engine/src/media/thumbnail_hash_tests.rs @@ -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] diff --git a/crates/engine/src/merge.rs b/crates/engine/src/merge.rs index 70ad1328fb..944b6f5380 100644 --- a/crates/engine/src/merge.rs +++ b/crates/engine/src/merge.rs @@ -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::>(), "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::>(); + let pairs: Vec = 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"}, + ]) + ); + } +} diff --git a/crates/engine/src/tests/denoise.rs b/crates/engine/src/tests/denoise.rs index 0639030408..b164c7c77d 100644 --- a/crates/engine/src/tests/denoise.rs +++ b/crates/engine/src/tests/denoise.rs @@ -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,160 @@ 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, ¤t).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, ¤t).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); +} + +#[test] +fn changing_photo_pin_rejects_a_previous_model_job_in_flight() { + use std::sync::{Mutex, mpsc}; + use std::time::Duration; + 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(Duration::from_secs(10)).map_err(|e| e.to_string())?; + Ok(Arc::new(Dim { runs: runs.clone() }) as Arc) + }); + x.s.execute("denoise.queue", &json!({"ids":[id.0]})).unwrap(); + x.s.execute("denoise.pump", &json!({"pace":"full"})).unwrap(); + entered_rx.recv_timeout(Duration::from_secs(10)).unwrap(); + let oldkey = x.s.denoise_running_product().unwrap().1; + x.s.execute("denoise.photo.model", &json!({"id":id.0,"model":"builtin"})).unwrap(); + release_tx.send(()).unwrap(); + for _ in 0..1000 { + x.s.denoise_pump(crate::denoise::Pace::Pause); + if x.s.denoise_running_json().is_null() { + break; + } + std::thread::sleep(Duration::from_millis(2)); + } + assert!(x.s.denoise_running_json().is_null()); + 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 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); +} diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index db12052da0..3b65dbae9a 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -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}"))) diff --git a/crates/engine/src/tests/merge.rs b/crates/engine/src/tests/merge.rs index 2d82c20570..d3a6a8bc42 100644 --- a/crates/engine/src/tests/merge.rs +++ b/crates/engine/src/tests/merge.rs @@ -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] diff --git a/crates/merge/Cargo.toml b/crates/merge/Cargo.toml index 296f06beb3..584e82ba65 100644 --- a/crates/merge/Cargo.toml +++ b/crates/merge/Cargo.toml @@ -19,3 +19,4 @@ lightcraft-scenes = { workspace = true } serde = { workspace = true } thiserror = { workspace = true } rayon = { workspace = true } +log = { workspace = true } diff --git a/crates/merge/src/pano.rs b/crates/merge/src/pano.rs index da3388d3a6..7f5dd171e0 100644 --- a/crates/merge/src/pano.rs +++ b/crates/merge/src/pano.rs @@ -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, + /// Measurements for the first [`camera::MAX_PAIR_DIAGNOSTICS`] input pairs, including rejected pairs. + pub pairs: Vec, /// Cameras of the inputs (`None` = not used), in their full-resolution pixels, straightened. pub cameras: Vec>, /// 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>, 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>, f64, f64, Vec)> { 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 = work.iter().map(|(f, _)| f.clone()).collect(); let scales: Vec = 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, 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 = (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, opts: &PanoOptions, progress: &Progress) - crop, projection, used, + pairs, cameras: cams, gains, rms_before, diff --git a/crates/merge/src/pano/camera.rs b/crates/merge/src/pano/camera.rs index 4589f88db3..4960bcbcdf 100644 --- a/crates/merge/src/pano/camera.rs +++ b/crates/merge/src/pano/camera.rs @@ -58,37 +58,104 @@ pub struct PairMatch { pub levels: Vec, } +/// 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, + 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 { + (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 { + 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, Vec) { 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 = (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 = m.iter().map(|(p, _)| Point::new(feats[i].points[*p].x as f64, feats[i].points[*p].y as f64)).collect(); - let b: Vec = 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, PairStatus)) -> Option { + 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 = m.iter().map(|(p, _)| Point::new(feats[i].points[*p].x as f64, feats[i].points[*p].y as f64)).collect(); + let b: Vec = 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). diff --git a/crates/merge/tests/it/pano.rs b/crates/merge/tests/it/pano.rs index d356cd2b95..64b965cb16 100644 --- a/crates/merge/tests/it/pano.rs +++ b/crates/merge/tests/it/pano.rs @@ -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 = [-22.0, 0.0, 21.0].into_iter().map(|yaw| rot(yaw, 0.0, 0.0)).collect(); + let clean: Vec = 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 = (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. diff --git a/crates/merge/tests/pair_verification.rs b/crates/merge/tests/pair_verification.rs new file mode 100644 index 0000000000..a85b24f9e6 --- /dev/null +++ b/crates/merge/tests/pair_verification.rs @@ -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 { + let matches = match_features(&f[0], &f[1], 0.8); + assert_eq!(matches.len(), f[0].len()); + let points = |side: usize| -> Vec { + 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::>(), [(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::>(); + assert_eq!(indices(&matches), [(features.len() - 2, features.len() - 1)]); + assert_eq!(indices(&matches), indices(&match_pairs(&features, &scales))); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 25736c0aac..36edc72af7 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -482,6 +482,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", @@ -629,6 +630,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", @@ -2228,6 +2230,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) diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index df689f5c7b..5e343e993d 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -263,8 +263,11 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result 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), } } diff --git a/crates/ui-egui/src/dialogs/frame.rs b/crates/ui-egui/src/dialogs/frame.rs index 51c91e6f72..3b60cc831e 100644 --- a/crates/ui-egui/src/dialogs/frame.rs +++ b/crates/ui-egui/src/dialogs/frame.rs @@ -277,5 +277,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()) } diff --git a/crates/ui-egui/src/dialogs/merge.rs b/crates/ui-egui/src/dialogs/merge.rs index c9303b4981..b353d6523c 100644 --- a/crates/ui-egui/src/dialogs/merge.rs +++ b/crates/ui-egui/src/dialogs/merge.rs @@ -116,6 +116,8 @@ pub struct MergeState { pub ids: Vec, /// HDR for Each Bracket Set: the sets still to merge after the running one. pub batch: std::collections::VecDeque>, + /// A finished panorama's list of omitted photos, waiting for the dialog open when it finished to close. + pub pending_result: Option, } impl MergeState { @@ -160,22 +162,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 { - 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) { 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 { + 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()})) } @@ -209,7 +217,7 @@ pub fn start_last(app: &mut LightcraftApp, command: &str) -> Result Result /// 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(|_| ()) } @@ -313,11 +321,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(); @@ -347,13 +351,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 { + let omitted: Vec = 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, @@ -367,7 +405,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) { + 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 { @@ -430,6 +494,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, resp) = ui.allocate_exact_size(box_size, egui::Sense::click_and_drag()); ui.painter().rect_filled(rect, 4.0, t.canvas); @@ -454,7 +519,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!( @@ -470,6 +537,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); @@ -598,6 +668,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::>()}); + 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::().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() { diff --git a/crates/ui-egui/src/panels/denoise.rs b/crates/ui-egui/src/panels/denoise.rs index c9eb0bfa5d..68ec0c209d 100644 --- a/crates/ui-egui/src/panels/denoise.rs +++ b/crates/ui-egui/src/panels/denoise.rs @@ -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, 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, } @@ -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); } @@ -153,6 +155,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. @@ -250,8 +346,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."); @@ -301,9 +398,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); } @@ -463,7 +557,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)); } @@ -518,14 +612,14 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, app.caches.denoise.epoch += 1; } if selected { - let r = ui.button(tr("Stop using")); + let r = ui.button(tr("Use Built-in")); register(ui, format!("denoise:off:{id}"), r.rect); if r.clicked() { let _ = app.run("denoise.models.select", json!({"id": null})); app.caches.denoise.epoch += 1; } } else { - let r = ui.button(tr("Use")); + let r = ui.button(tr("Set as Default")); register(ui, format!("denoise:use:{id}"), r.rect); if r.clicked() { let _ = app.run("denoise.models.select", json!({"id": id})); @@ -557,7 +651,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 ); @@ -719,7 +813,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!( @@ -731,6 +825,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 })); diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index 2bbb312f9e..f5862542ec 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -312,8 +312,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"] { diff --git a/crates/ui-egui/src/render/thumbnail_tests.rs b/crates/ui-egui/src/render/thumbnail_tests.rs index 3f6fd81982..e167edf315 100644 --- a/crates/ui-egui/src/render/thumbnail_tests.rs +++ b/crates/ui-egui/src/render/thumbnail_tests.rs @@ -1655,8 +1655,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(); - assert!(message.contains(replacement.to_str().unwrap()), "{message}"); - assert!(!message.contains(later.to_str().unwrap()), "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 = @@ -1717,7 +1717,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()); - assert!(app.renderer.failure_messages.last().unwrap().contains(original.to_str().unwrap())); + 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(); diff --git a/crates/ui-egui/src/state/dialog.rs b/crates/ui-egui/src/state/dialog.rs index 2a2837ea7e..bfbe195a88 100644 --- a/crates/ui-egui/src/state/dialog.rs +++ b/crates/ui-egui/src/state/dialog.rs @@ -44,6 +44,12 @@ pub enum Dialog { details: Vec, first: Option, }, + /// 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, + }, /// File ▸ Print…: the Print module. Its state is the session's (`print.*`); the page on show /// and the selected cell are [`UiState::print`]. Print, diff --git a/crates/ui-egui/src/tests/activity.rs b/crates/ui-egui/src/tests/activity.rs index 0f46af39c4..fde2f11be0 100644 --- a/crates/ui-egui/src/tests/activity.rs +++ b/crates/ui-egui/src/tests/activity.rs @@ -417,6 +417,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] diff --git a/crates/ui-egui/tests/it/accessibility.rs b/crates/ui-egui/tests/it/accessibility.rs index 13e4688e5f..014e178fb0 100644 --- a/crates/ui-egui/tests/it/accessibility.rs +++ b/crates/ui-egui/tests/it/accessibility.rs @@ -247,6 +247,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] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9afd7b451b..546deb451c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -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. diff --git a/docs/denoise.md b/docs/denoise.md index cfba062c10..a633917aff 100644 --- a/docs/denoise.md +++ b/docs/denoise.md @@ -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`. diff --git a/docs/gaps.md b/docs/gaps.md index e1a8e67130..762d03acf0 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -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 | diff --git a/docs/merge.md b/docs/merge.md index 197ea3f32e..f452eab13d 100644 --- a/docs/merge.md +++ b/docs/merge.md @@ -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 @@ -76,6 +111,9 @@ RGB space. ## 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 92d65310d7..ac1e11a6fa 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -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 | diff --git a/docs/whats-new.md b/docs/whats-new.md index 308043cadc..493fb19906 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1000,6 +1000,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