From 8a1baef44db530293d985b85864a01252b194e52 Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:22:12 +0200 Subject: [PATCH 01/63] Desktop: the panic log is kept in the settings folder, never the shared temp folder (#2572) By default the desktop app appended panics to lightcraft-panics.log in the system temp folder, a fixed name that every user shares on Linux and FreeBSD, so another user could create the file first to read the panic messages or plant a link that made LightCraft append to one of the victim's files. The emergency crash log now lives in the settings folder next to logs/, where an isolated LIGHTCRAFT_CONFIG_DIR profile already kept it. A --memory session, LIGHTCRAFT_NO_PREFS and an empty LIGHTCRAFT_CONFIG_DIR keep no crash file, like every other settings-folder file, and report panics on standard error only. The panic hooks are now installed once the arguments are read, so --version, --help and a usage error never create a portable LightCraftData folder for the crash log. --- README.md | 3 +- README.zh-hans.md | 3 +- README.zh-hant.md | 3 +- apps/lightcraft/src/logging.rs | 4 +- apps/lightcraft/src/main.rs | 99 +++++++++++++++++++++++++++++----- docs/control-protocol.md | 3 +- docs/whats-new.md | 9 ++++ 7 files changed, 105 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index c8db5a50ac..e7d1dbfb8c 100644 --- a/README.md +++ b/README.md @@ -474,7 +474,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 824913f140..0b3ebb77c1 100644 --- a/README.zh-hans.md +++ b/README.zh-hans.md @@ -409,7 +409,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 a17505f3f4..d5665dfb2f 100644 --- a/README.zh-hant.md +++ b/README.zh-hant.md @@ -435,7 +435,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/apps/lightcraft/src/logging.rs b/apps/lightcraft/src/logging.rs index 6239aded67..0873614179 100644 --- a/apps/lightcraft/src/logging.rs +++ b/apps/lightcraft/src/logging.rs @@ -329,8 +329,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 95739b3e97..db4c9cdc9e 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -834,19 +834,38 @@ fn control_port_from(what: &str, value: Option) -> Option { port } -/// An isolated profile keeps the emergency crash log with its other app data. With no -/// override (or an empty override), retain the historical system-temp location. -fn panic_log_path_with(env: impl Fn(&str) -> Option, temp: std::path::PathBuf) -> std::path::PathBuf { - env("LIGHTCRAFT_CONFIG_DIR").filter(|value| !value.is_empty()).map(std::path::PathBuf::from).unwrap_or(temp).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")) +} + +/// The panic hooks: the engine guard's (standard error, and the crash log when there is one), then +/// the log file's. +fn install_panic_hooks(logger: Option<&'static logging::AppLogger>, in_memory: bool) { + if let Some(path) = panic_log_path(in_memory) { + lightcraft_engine::guard::install_hook(path); + } + if let Some(logger) = logger { + logging::record_panics(logger); + } } fn main() -> eframe::Result { // First, so every start-up record is kept for the log file (`logging`). let logger = logging::install(); - lightcraft_engine::guard::install_hook(panic_log_path_with(|name| std::env::var_os(name), std::env::temp_dir())); - if let Some(logger) = logger { - logging::record_panics(logger); - } alloc_release::install(); let mut control_port = control_port_from("LIGHTCRAFT_CONTROL_PORT", std::env::var("LIGHTCRAFT_CONTROL_PORT").ok().filter(|v| !v.is_empty())); let mut files = Vec::new(); @@ -875,6 +894,10 @@ fn main() -> eframe::Result { _ => files.push(a), } } + // 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; @@ -1557,11 +1580,61 @@ mod tests { 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()), std::path::PathBuf::from("isolated/lightcraft-panics.log")); - assert_eq!(panic_log_path_with(|_| None, temp.clone()), temp.join("lightcraft-panics.log")); - assert_eq!(panic_log_path_with(|_| Some("".into()), temp.clone()), 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); + } + + /// #2572: a panic is kept in `lightcraft-panics.log` in the settings folder, never in the system + /// temp folder (shared by every user on Linux and FreeBSD), and a `--memory` session keeps it + /// nowhere. The hook is process-wide, so the panic happens in a child (this test binary again) + /// with its own temp and home folders and no `LIGHTCRAFT_CONFIG_DIR`. + #[test] + fn a_panic_is_kept_in_the_settings_folder_not_the_temp_folder() { + if let Some(mode) = std::env::var_os("LIGHTCRAFT_TEST_PANIC_LOG") { + let settings = config_dir().unwrap(); + std::fs::create_dir_all(&settings).unwrap(); + println!("settings folder {}", settings.display()); + install_panic_hooks(None, mode == "memory"); + assert!(std::thread::spawn(|| panic!("lc-2572 probe")).join().is_err()); + return; + } + let scratch = std::env::temp_dir().join(format!("lightcraft-panic-log-{}", std::process::id())); + for memory in [false, true] { + let _ = std::fs::remove_dir_all(&scratch); + let (temp, home) = (scratch.join("temp"), scratch.join("home")); + std::fs::create_dir_all(&temp).unwrap(); + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "config_path_tests::a_panic_is_kept_in_the_settings_folder_not_the_temp_folder", "--nocapture"]) + .env("LIGHTCRAFT_TEST_PANIC_LOG", if memory { "memory" } else { "1" }) + .env_remove("LIGHTCRAFT_CONFIG_DIR") + .env_remove("LIGHTCRAFT_NO_PREFS") + .env("TMPDIR", &temp) + .env("TMP", &temp) + .env("TEMP", &temp) + .env("HOME", &home) + .env("XDG_CONFIG_HOME", home.join(".config")) + .env("APPDATA", home.join("AppData")) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success(), "{stdout}{}", String::from_utf8_lossy(&out.stderr)); + // Anywhere in a line: with one test thread (`RUST_TEST_THREADS=1`, as `xtask ci` sets on a + // small machine) libtest prints the test's name first, on the same line. + let settings = stdout.lines().find_map(|l| l.split_once("settings folder ").map(|(_, p)| p)).expect("the child didn't run the test"); + let kept = std::fs::read_to_string(std::path::Path::new(settings).join("lightcraft-panics.log")).unwrap_or_default(); + assert_eq!(kept.contains("lc-2572 probe"), !memory, "--memory {memory}: {kept:?} in {settings}"); + assert!(!temp.join("lightcraft-panics.log").exists(), "--memory {memory}: the panic was kept in the temp folder"); + } + let _ = std::fs::remove_dir_all(&scratch); } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index dd41bcdb81..673e82da48 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -45,7 +45,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/whats-new.md b/docs/whats-new.md index cffff83e2b..4da20ae1bd 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,14 @@ # What's new in LightCraft +## 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. + ## 2026-10-21 ### Sharper resampling in HDR and panorama merges From c739e1bf889baa336cc7099a9018925a7ae9b467 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Tue, 27 Oct 2026 08:15:00 +0100 Subject: [PATCH 02/63] LR-CI: fix Rust 1.95 lints and standard-font menu hints --- apps/lightcraft/src/editors.rs | 2 +- apps/lightcraft/src/launch.rs | 4 ++-- apps/lightcraft/src/native_menu.rs | 4 +--- crates/engine/src/cmd/export.rs | 2 +- crates/engine/src/cmd/face_detect.rs | 2 +- crates/engine/src/cmd/face_models.rs | 2 +- crates/engine/src/cmd/geocode.rs | 2 +- crates/engine/src/denoise/model.rs | 2 +- crates/engine/src/lib.rs | 2 +- crates/engine/src/segment/worker.rs | 2 +- crates/ui-egui/locales/cs-formats.json | 10 +++++----- crates/ui-egui/locales/cs.json | 8 ++++---- crates/ui-egui/locales/de-formats.json | 10 +++++----- crates/ui-egui/locales/de.json | 6 +++--- crates/ui-egui/locales/es-formats.json | 10 +++++----- crates/ui-egui/locales/es.json | 6 +++--- crates/ui-egui/locales/fi-formats.json | 10 +++++----- crates/ui-egui/locales/fi.json | 8 ++++---- crates/ui-egui/locales/fr-formats.json | 10 +++++----- crates/ui-egui/locales/fr.json | 6 +++--- crates/ui-egui/locales/id-formats.json | 10 +++++----- crates/ui-egui/locales/id.json | 8 ++++---- crates/ui-egui/locales/it-formats.json | 10 +++++----- crates/ui-egui/locales/it.json | 8 ++++---- crates/ui-egui/locales/ja-formats.json | 10 +++++----- crates/ui-egui/locales/ja.json | 6 +++--- crates/ui-egui/locales/ka-formats.json | 10 +++++----- crates/ui-egui/locales/ka.json | 6 +++--- crates/ui-egui/locales/pl-formats.json | 10 +++++----- crates/ui-egui/locales/pl.json | 4 ++-- crates/ui-egui/locales/pt-br-formats.json | 10 +++++----- crates/ui-egui/locales/pt-br.json | 6 +++--- crates/ui-egui/locales/ru-formats.json | 10 +++++----- crates/ui-egui/locales/ru.json | 6 +++--- crates/ui-egui/locales/sv-formats.json | 10 +++++----- crates/ui-egui/locales/sv.json | 8 ++++---- crates/ui-egui/locales/uk-formats.json | 10 +++++----- crates/ui-egui/locales/uk.json | 6 +++--- crates/ui-egui/locales/vi-formats.json | 10 +++++----- crates/ui-egui/locales/vi.json | 6 +++--- crates/ui-egui/locales/zh-hans-formats.json | 10 +++++----- crates/ui-egui/locales/zh-hans.json | 6 +++--- crates/ui-egui/locales/zh-hant-formats.json | 10 +++++----- crates/ui-egui/locales/zh-hant.json | 6 +++--- crates/ui-egui/src/dialogs/import/task.rs | 2 +- crates/ui-egui/src/dialogs/rules_editor/rules_move.rs | 2 +- crates/ui-egui/src/dialogs/settings/general.rs | 2 +- crates/ui-egui/src/dialogs/settings/libraries.rs | 2 +- crates/ui-egui/src/menus/files.rs | 2 +- crates/ui-egui/src/menus/run.rs | 2 +- crates/ui-egui/src/panels/compare.rs | 2 +- crates/ui-egui/src/panels/detail/masks.rs | 2 +- crates/ui-egui/src/panels/grid.rs | 2 +- crates/ui-egui/src/panels/keywording.rs | 2 +- crates/ui-egui/src/panels/mask_effects.rs | 2 +- 55 files changed, 162 insertions(+), 164 deletions(-) diff --git a/apps/lightcraft/src/editors.rs b/apps/lightcraft/src/editors.rs index 3ca748f473..87f2cb6144 100644 --- a/apps/lightcraft/src/editors.rs +++ b/apps/lightcraft/src/editors.rs @@ -120,7 +120,7 @@ fn launcher(app: &str) -> Result { return Ok(if cfg!(target_os = "macos") { Launcher::MacApp(app.to_string()) } else { Launcher::Program(PathBuf::from(app)) }); } find_photocraft().ok_or_else(|| { - "PhotoCraft isn't installed. Get it from getartcraft.com/apps/photocraft, or give where it is in Settings ▸ External Editing.".to_string() + "PhotoCraft isn't installed. Get it from getartcraft.com/apps/photocraft, or give where it is in Settings → External Editing.".to_string() }) } diff --git a/apps/lightcraft/src/launch.rs b/apps/lightcraft/src/launch.rs index a7b8904d62..95a8d452eb 100644 --- a/apps/lightcraft/src/launch.rs +++ b/apps/lightcraft/src/launch.rs @@ -45,7 +45,7 @@ pub(crate) fn launch_imports_in(args: &[String], cwd: Option<&std::path::Path>, Some(LaunchPath::Refused { path, why }) => { log::warn!("not importing {path} given at launch: {why}"); notices - .push(format!("{path} was not imported: it is {why}. To import from it, choose a folder inside it with File ▸ Import Photos…")); + .push(format!("{path} was not imported: it is {why}. To import from it, choose a folder inside it with File → Import Photos…")); } None => {} } @@ -85,7 +85,7 @@ pub(crate) fn stopped_text(error: &str, lost: Option<&str>) -> String { match lost { Some(reason) => format!( "{error}. The graphics driver reset the GPU ({reason}). LightCraft renders on the CPU from its next start; \ - Settings ▸ Performance ▸ Use the GPU for rendering turns the GPU back on" + Settings → Performance → Use the GPU for rendering turns the GPU back on" ), None => error.to_string(), } diff --git a/apps/lightcraft/src/native_menu.rs b/apps/lightcraft/src/native_menu.rs index a5a14e2088..0a14918a81 100644 --- a/apps/lightcraft/src/native_menu.rs +++ b/apps/lightcraft/src/native_menu.rs @@ -489,9 +489,7 @@ impl NativeMenu { // events never reach `shortcuts::handle`, so this is the one guard for AppKit's // accelerators and clicks: while the blocking library window or a quit/settings notice // owns input, a queued command is dropped (Quit stays for the existing confirmation). - let (cmd, params) = if key == QUIT { - (key, serde_json::json!({})) - } else if key == "app.about" || key == SETTINGS { + let (cmd, params) = if key == QUIT || key == "app.about" || key == SETTINGS { (key, serde_json::json!({})) } else if let Some(it) = self.items.get(&key) { (it.cmd.clone(), it.params.clone()) diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rs index 949c08f1ba..9af0606d9d 100644 --- a/crates/engine/src/cmd/export.rs +++ b/crates/engine/src/cmd/export.rs @@ -38,7 +38,7 @@ impl Session { } // the preset's depth is judged against the format written, known only now (`path`); a // depth the call passes itself is the caller's, and validated as such - if !p.get("bitDepth").is_some_and(|d| !d.is_null()) { + if p.get("bitDepth").is_none_or(|d| d.is_null()) { crate::export::ExportOptions::drop_unfit_depth(&mut out, fallback); } Ok(out) diff --git a/crates/engine/src/cmd/face_detect.rs b/crates/engine/src/cmd/face_detect.rs index 711bebb102..611a841033 100644 --- a/crates/engine/src/cmd/face_detect.rs +++ b/crates/engine/src/cmd/face_detect.rs @@ -313,7 +313,7 @@ pub fn specs() -> Vec { "Face Models on the GPU", [], None, - "{cpuOnly?: bool} → {cpuOnly, detection, recognition}: where the face models run, each as {checking, device, why} (null until it is loaded). The GPU is used only after a background check shows it gives the CPU's results faster; `cpuOnly: true` keeps every face model on the CPU (Settings ▸ Faces), `false` checks the GPU again", + "{cpuOnly?: bool} → {cpuOnly, detection, recognition}: where the face models run, each as {checking, device, why} (null until it is loaded). The GPU is used only after a background check shows it gives the CPU's results faster; `cpuOnly: true` keeps every face model on the CPU (Settings → Faces), `false` checks the GPU again", always, gpu ), diff --git a/crates/engine/src/cmd/face_models.rs b/crates/engine/src/cmd/face_models.rs index 1ea39d04c1..dc7bbe0ee0 100644 --- a/crates/engine/src/cmd/face_models.rs +++ b/crates/engine/src/cmd/face_models.rs @@ -511,7 +511,7 @@ fn enable(s: &mut Session, p: &Value) -> Result { let usable = st.embedder.as_deref().is_some_and(|id| installed_models(&dir).iter().any(|i| i.manifest.id == id && i.manifest.role == Role::Embedder)); if on && !usable { - return Err(bad(C, "choose a recognition model first (Settings ▸ Faces ▸ Use)")); + return Err(bad(C, "choose a recognition model first (Settings → Faces → Use)")); } st.enabled = on; write_settings(&dir, &st)?; diff --git a/crates/engine/src/cmd/geocode.rs b/crates/engine/src/cmd/geocode.rs index feb9b033e9..9d924003b1 100644 --- a/crates/engine/src/cmd/geocode.rs +++ b/crates/engine/src/cmd/geocode.rs @@ -141,7 +141,7 @@ fn reverse(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "none of these photos has a GPS position")); } let dir = dataset_dir(p).ok_or_else(|| bad(C, "no settings folder: give `dataset`"))?; - let names = s.place_names.load(&dir).map_err(|e| bad(C, format!("{e}: download the place names first (Photo ▸ Download Place Names)")))?; + let names = s.place_names.load(&dir).map_err(|e| bad(C, format!("{e}: download the place names first (Photo → Download Place Names)")))?; // a large selection shows in the activity stack and can be stopped let task = (todo.len() > 1).then(|| s.activity.start("geocode", "Looking up places", Cancel::Yes)); let mut ops = Vec::new(); diff --git a/crates/engine/src/denoise/model.rs b/crates/engine/src/denoise/model.rs index 28ff953bfb..243a6c9a2e 100644 --- a/crates/engine/src/denoise/model.rs +++ b/crates/engine/src/denoise/model.rs @@ -409,7 +409,7 @@ pub fn serving(dir: Option<&Path>, id: Option<&str>, run_on: RunOn) -> Result i.to_string(), None => read_settings(&dir).model.ok_or_else(|| { - format!("no denoise model is selected in {} (install one in Settings ▸ AI Denoise, or name it with --model)", dir.display()) + format!("no denoise model is selected in {} (install one in Settings → AI Denoise, or name it with --model)", dir.display()) })?, }; let installed = installed_models(&dir) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index acaa180700..4bd4cc9ceb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -115,7 +115,7 @@ pub enum EngineError { /// The folder (or file) asked for is a Lightroom Classic catalog or part of one, not a /// LightCraft library (issue #891): nothing was created or opened. `catalog`: the `.lrcat` /// to import with `library.importLightroom`, when one was found. - #[error("{} is a Lightroom Classic catalog, not a LightCraft library; import it into a LightCraft library with File ▸ Import Lightroom Catalog…{}", path.display(), catalog.as_ref().map_or(String::new(), |c| format!(" ({})", c.display())))] + #[error("{} is a Lightroom Classic catalog, not a LightCraft library; import it into a LightCraft library with File → Import Lightroom Catalog…{}", path.display(), catalog.as_ref().map_or(String::new(), |c| format!(" ({})", c.display())))] LightroomCatalog { path: std::path::PathBuf, catalog: Option }, /// The work was cancelled (by the person, an agent or a newer request): not a failure. #[error("{0}")] diff --git a/crates/engine/src/segment/worker.rs b/crates/engine/src/segment/worker.rs index efbb1c21c4..11914039e3 100644 --- a/crates/engine/src/segment/worker.rs +++ b/crates/engine/src/segment/worker.rs @@ -379,7 +379,7 @@ fn render(job: &mut Job) -> Result { Err(e) => { return Err(match &job.missing { Some(path) => format!( - "This photo's file is missing (moved or deleted), so it can't be analyzed for AI masks: {path}. Library ▸ Find Missing Photos can relink it." + "This photo's file is missing (moved or deleted), so it can't be analyzed for AI masks: {path}. Library → Find Missing Photos can relink it." ), None => format!("couldn't render the photo for AI masks: {e}"), }); diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 1eb882f09d..b3fcbd6aa4 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -35,7 +35,7 @@ "Added “{keyword}” to {n} photo{}": "K fotografiím přidáno „{keyword}“: {n}{:.0}", "Adding photos… {} of {}": "Přidávání fotografií… {} z {}", "All {n} selected photos move by the same amount.": "Všech {n} vybraných fotografií se posune o stejnou hodnotu.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Již v knihovně, v nedávno odstraněných: vybrané fotografie: {}{:.0} · pravé tlačítko → Obnovit, nebo Trvale odstranit pro nový import", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Již v knihovně, v nedávno odstraněných: vybrané fotografie: {}{:.0} · pravé tlačítko → Obnovit, nebo Trvale odstranit pro nový import", "Already in the library: {} photo{} selected in All Photos": "Již v knihovně: ve všech fotografiích vybráno: {}{:.0}", "Auto ({})": "Automaticky ({})", "Auto Import: added {} photo{}": "Automatický import: přidáno fotografií: {}{:.0}", @@ -80,7 +80,7 @@ "Imported {n} point curve preset{}": "Importovaná přednastavení bodové křivky: {n}{:.0}", "Imported {n} preset{}": "Importovaná přednastavení: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Importovaná přednastavení: {n}{0:.0}, nečitelné soubory: {f}{1:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Importované profily: {profiles}{:.0} (Prohlížeč profilů → jejich skupiny)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Importované profily: {profiles}{:.0} (Prohlížeč profilů → jejich skupiny)", "Imported {} photo{}": "Importováno fotografií: {}{:.0}", "In line for AI Denoise ({ahead} ahead)…": "Ve frontě na redukci šumu pomocí AI (před vámi: {ahead})…", "Insert at the cursor (also written {})": "Vložit na pozici kurzoru (také se zapisuje {})", @@ -206,7 +206,7 @@ "{n} photo{}": "fotografií: {n}{:.0}", "{n} photo{} match · updates automatically as photos change": "Odpovídající fotografie: {n}{:.0} · aktualizuje se automaticky při změnách fotografií", "{n} photo{} now · updates automatically as photos change": "Aktuální fotografie: {n}{:.0} · aktualizuje se automaticky při změnách fotografií", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Podobné fotografie: {n}{:.0} · Zobrazení → Zrušit filtry zobrazí všechny", + "{n} similar photo{} · View → Clear Filters to see all": "Podobné fotografie: {n}{:.0} · Zobrazení → Zrušit filtry zobrazí všechny", "{n} tasks are still running: {names}. Quitting stops them.": "Stále běží úlohy: {n}: {names}. Ukončení aplikace je zastaví.", "{n} {noun}": "{noun}: {n}", "{pct} %": "{pct} %", @@ -252,7 +252,7 @@ "Create the keyword “{name}”": "Vytvořit klíčové slovo „{name}“", "new, inside {parent}": "nové, pod {parent}", "Keywords of {n} selected photos": "Klíčová slova vybraných fotografií (počet: {n})", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Klíčové slovo „{name}“ bylo odebráno z fotografií v počtu {n}. Úpravy → Zpět jej vrátí.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Klíčové slovo „{name}“ bylo odebráno z fotografií v počtu {n}. Úpravy → Zpět jej vrátí.", "Inside: {names}": "Uvnitř: {names}", " in {g} group{}": " ve skupinách: {g}{:.0}", " · kept, not applied: {}": " · zachováno, nepoužito: {}", @@ -263,7 +263,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Odstranit přednastavení efektů v počtu {n}{:.0}? Tuto akci nelze vrátit zpět.", "Effect: {name}": "Efekt: {name}", "Exported {} effect preset{}": "Exportováno přednastavení efektů: {0}{1:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Importováno efektů masek: {e}{:.0} (Maskování → Efekt)", + "Imported {e} mask effect{} (Masking → Effect)": "Importováno efektů masek: {e}{:.0} (Maskování → Efekt)", "Update “{name}” with Current Settings": "Aktualizovat „{name}“ podle aktuálního nastavení", "{n} preset{}": "Přednastavení: {n}{:.0}", "{count} more warnings.": "Další varování: {count}.", diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 52ca94a524..401c7054df 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -1358,7 +1358,7 @@ "Photo Grid": "Mřížka fotografií", "Photo Grid (G)": "Mřížka fotografií (G)", "Photo Merge": "Sloučení fotografií", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Fotografie → Upravit v → Upravit v PhotoCraft (⇧⌘E nebo pravé tlačítko na fotografii) vykreslí kopii s vašimi úpravami, přidá ji do sady s originálem a otevře v PhotoCraft. Po uložení se kopie zde aktualizuje. Do PSD ukládá PhotoCraft přímo. Umístění ponechte prázdné, pokud nepoužíváte přenosnou kopii.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Fotografie → Upravit v → Upravit v PhotoCraft (⇧⌘E nebo pravé tlačítko na fotografii) vykreslí kopii s vašimi úpravami, přidá ji do sady s originálem a otevře v PhotoCraft. Po uložení se kopie zde aktualizuje. Do PSD ukládá PhotoCraft přímo. Umístění ponechte prázdné, pokud nepoužíváte přenosnou kopii.", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Fotografie → Upravit v externím editoru (⇧⌘E) vykreslí 16bitovou kopii TIFF, přidá ji do sady s originálem a otevře v této aplikaci (název aplikace v macOS, jinde cesta k programu).", "PhotoCraft": "PhotoCraft", "Photos": "Fotografie", @@ -1544,7 +1544,7 @@ "Remove location info": "Odebrat informace o poloze", "Remove missing photos from the library": "Odebrat chybějící fotografie z knihovny", "Remove shortcut": "Odebrat zkratku", - "Remove this face box (undo with Edit ▸ Undo)": "Odebrat tento rámeček obličeje (vrátit přes Úpravy → Zpět)", + "Remove this face box (undo with Edit → Undo)": "Odebrat tento rámeček obličeje (vrátit přes Úpravy → Zpět)", "Remove this filter": "Odebrat tento filtr", "Remove this group": "Odebrat tuto skupinu", "Remove this rule": "Odebrat toto pravidlo", @@ -1584,7 +1584,7 @@ "Reset all curves: point curves (all channels) and parametric (double-click a channel to reset only that one)": "Obnoví všechny křivky: bodové (všechny kanály) i parametrickou (dvojklik na kanál obnoví pouze tento kanál)", "Reset all edits": "Obnovit všechny úpravy", "Reset all edits (Cmd+Shift+R)": "Obnovit všechny úpravy (Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Inteligentní alba se aktualizují automaticky: změňte jejich pravidla nebo použijte Fotografie → Odstranit fotografii", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Inteligentní alba se aktualizují automaticky: změňte jejich pravidla nebo použijte Fotografie → Odstranit fotografii", "LightCraft stopped": "LightCraft se neočekávaně ukončil", "Zoom to Focus Point": "Přiblížit na zaostřovací bod", "Focus": "Zaostření", @@ -1630,7 +1630,7 @@ "Revert": "Vrátit změny", "Review": "Zkontrolovat", "Review Import": "Zkontrolovat import", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Pravé tlačítko na fotografii → Nastavit jako referenční fotografii, pak Zobrazení → Referenční zobrazení (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Pravé tlačítko na fotografii → Nastavit jako referenční fotografii, pak Zobrazení → Referenční zobrazení (Shift+R)", "Right-click a preset to delete it": "Přednastavení odstraníte kliknutím pravým tlačítkem", "Rights Usage Terms": "Podmínky použití práv", "Rotate": "Otočit", diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 79390f1364..b8ba3e3fef 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -25,7 +25,7 @@ "Added {what} to {name}": "{what} zu {name} hinzugefügt", "Adding photos… {} of {}": "Fotos werden hinzugefügt… {} von {}", "All {n} selected photos move by the same amount.": "Alle {n} ausgewählten Fotos werden um denselben Betrag verschoben.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Bereits in der Bibliothek unter „Zuletzt gelöscht“: {} Foto{} ausgewählt · Rechtsklick → Wiederherstellen, oder endgültig löschen, um neu zu importieren", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Bereits in der Bibliothek unter „Zuletzt gelöscht“: {} Foto{} ausgewählt · Rechtsklick → Wiederherstellen, oder endgültig löschen, um neu zu importieren", "Already in the library: {} photo{} selected in All Photos": "Bereits in der Bibliothek: {} Foto{} in „Alle Fotos“ ausgewählt", "Auto ({})": "Automatisch ({})", "Auto Import: added {} photo{}": "Automatischer Import: {} Foto{} hinzugefügt", @@ -72,7 +72,7 @@ "Imported {n} point curve preset{}": "Importierte Punktkurvenvorgaben: {n}{:.0}", "Imported {n} preset{}": "Importierte Vorgaben: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Importierte Vorgaben: {n}{0:.0}, nicht lesbare Dateien: {f}{1:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Importierte Profile: {profiles}{:.0} (Profilbrowser → jeweilige Gruppen)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Importierte Profile: {profiles}{:.0} (Profilbrowser → jeweilige Gruppen)", "Imported {} photo{}": "{} Foto{} importiert", "Insert at the cursor (also written {})": "An Cursorposition einfügen (auch als {} geschrieben)", "Label Set: {name}": "Farbmarkierungssatz: {name}", @@ -195,7 +195,7 @@ "… and {more} more": "… und {more} weitere", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft kann diese RAW-Variante noch nicht dekodieren ({}). Du bearbeitest die eingebettete JPEG-Vorschau der Kamera. Sie enthält bereits deren Bildstil (z. B. Monochrom) und Weißabgleich.", "Filtered: {label}": "Gefiltert: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Ähnliche Fotos: {n}{:.0} · Ansicht → Filter löschen zeigt alle Fotos", + "{n} similar photo{} · View → Clear Filters to see all": "Ähnliche Fotos: {n}{:.0} · Ansicht → Filter löschen zeigt alle Fotos", "Moved; {} photo(s) relinked": "Verschoben; {} Foto(s) neu verknüpft", "{} label (click more labels to show any of them)": "Farbmarkierung {} (weitere Farbmarkierungen auswählen, um alle passenden Fotos zu zeigen)", ", {} star{}": ", Sterne: {}{:.0}", @@ -242,7 +242,7 @@ "Create the keyword “{name}”": "Stichwort „{name}“ erstellen", "new, inside {parent}": "neu, in {parent}", "Keywords of {n} selected photos": "Stichwörter von {n} ausgewählten Fotos", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "„{name}“ von {n} Fotos entfernt. Bearbeiten → Rückgängig stellt es wieder her.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "„{name}“ von {n} Fotos entfernt. Bearbeiten → Rückgängig stellt es wieder her.", "1 task is still running: {names}. Quitting stops it.": "1 Aufgabe läuft noch: {names}. Beenden bricht sie ab.", "{n} tasks are still running: {names}. Quitting stops them.": "{n} Aufgaben laufen noch: {names}. Beenden bricht sie ab.", "{what} merge cancelled": "{what}-Zusammenfügung abgebrochen", @@ -262,7 +262,7 @@ "Delete {n} effect preset{}? This can't be undone.": "{n} Effektvorgabe(n) löschen?{:.0} Dies kann nicht rückgängig gemacht werden.", "Effect: {name}": "Effekt: {name}", "Exported {} effect preset{}": "Exportierte Effektvorgaben: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "{e} Maskeneffekt(e) importiert{:.0} (Maskieren → Effekt)", + "Imported {e} mask effect{} (Masking → Effect)": "{e} Maskeneffekt(e) importiert{:.0} (Maskieren → Effekt)", "Update “{name}” with Current Settings": "„{name}“ mit aktuellen Einstellungen aktualisieren", "{n} preset{}": "{n} Vorgabe(n){:.0}", "{name} opened in the other editor": "{name} im anderen Editor geöffnet", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index e2205db782..c34fed81f1 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -1239,7 +1239,7 @@ "Remove from survey": "Aus Übersicht entfernen", "Remove location info": "Ortsinformationen entfernen", "Remove shortcut": "Tastenkürzel entfernen", - "Remove this face box (undo with Edit ▸ Undo)": "Diesen Gesichtsrahmen entfernen (rückgängig über Bearbeiten → Rückgängig)", + "Remove this face box (undo with Edit → Undo)": "Diesen Gesichtsrahmen entfernen (rückgängig über Bearbeiten → Rückgängig)", "Remove this filter": "Diesen Filter entfernen", "Remove this group": "Diese Gruppe entfernen", "Remove this rule": "Diese Regel entfernen", @@ -1295,7 +1295,7 @@ "Revert": "Zurück zum letzten Stand", "Review": "Überprüfung", "Review Import": "Import überprüfen", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Rechtsklick auf ein Foto → Als Referenzfoto festlegen, dann Ansicht → Referenzansicht (Umschalt+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Rechtsklick auf ein Foto → Als Referenzfoto festlegen, dann Ansicht → Referenzansicht (Umschalt+R)", "Right-click a preset to delete it": "Rechtsklick auf eine Vorgabe, um sie zu löschen", "Rights Usage Terms": "Nutzungsbedingungen", "Rotate": "Drehen", @@ -2313,7 +2313,7 @@ "Same folder as original photo": "Im selben Ordner wie das Originalfoto", "Tidying the thumbnail cache": "Miniaturcache wird aufgeräumt", "Reset all edits (Cmd+Shift+R)": "Alle Bearbeitungen zurücksetzen (⌘⇧R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Smart-Alben aktualisieren sich selbst: Ändere ihre Regeln oder verwende Foto → Foto löschen", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Smart-Alben aktualisieren sich selbst: Ändere ihre Regeln oder verwende Foto → Foto löschen", "LightCraft stopped": "LightCraft wurde beendet", "Zoom to Focus Point": "Auf Fokuspunkt zoomen", "Focus": "Fokus", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 33e5f52fc6..3b483ecb56 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -25,7 +25,7 @@ "Added {what} to {name}": "{what} añadido a {name}", "Adding photos… {} of {}": "Añadiendo fotos… {} de {}", "All {n} selected photos move by the same amount.": "Las {n} fotos seleccionadas se desplazan la misma cantidad.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Ya en la biblioteca, en Eliminadas recientemente: {0} foto{1} seleccionada{1} · clic derecho → Restaurar, o Eliminar definitivamente para importar de nuevo", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Ya en la biblioteca, en Eliminadas recientemente: {0} foto{1} seleccionada{1} · clic derecho → Restaurar, o Eliminar definitivamente para importar de nuevo", "Already in the library: {} photo{} selected in All Photos": "Ya en la biblioteca: {0} foto{1} seleccionada{1} en Todas las fotos", "Auto ({})": "Automático ({})", "Auto Import: added {} photo{}": "Importación automática: {0} foto{1} añadida{1}", @@ -72,7 +72,7 @@ "Imported {n} point curve preset{}": "{n} ajuste{0} preestablecido{0} de curva de puntos importado{0}", "Imported {n} preset{}": "{n} ajuste{0} preestablecido{0} importado{0}", "Imported {n} preset{}, {f} file{} not readable": "{n} ajuste{0} preestablecido{0} importado{0}, {f} archivo{1} ilegible{1}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Perfiles importados: {profiles}{:.0} (Explorador de perfiles → sus grupos)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Perfiles importados: {profiles}{:.0} (Explorador de perfiles → sus grupos)", "Imported {} photo{}": "{0} foto{1} importada{1}", "Insert at the cursor (also written {})": "Insertar en el cursor (también se escribe {})", "Label Set: {name}": "Conjunto de etiquetas: {name}", @@ -195,7 +195,7 @@ "… and {more} more": "… y {more} más", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft aún no puede decodificar esta variante RAW ({}). Se está editando la vista previa JPEG incrustada de la cámara, que ya incluye el estilo de imagen de la cámara (p. ej. Monocromo) y el balance de blancos.", "Filtered: {label}": "Filtrado: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Fotos similares: {n}{:.0} · Vista → Borrar filtros para ver todas", + "{n} similar photo{} · View → Clear Filters to see all": "Fotos similares: {n}{:.0} · Vista → Borrar filtros para ver todas", "Moved; {} photo(s) relinked": "Movida; {} foto(s) vinculada(s) de nuevo", "{} label (click more labels to show any of them)": "Etiqueta {} (hacer clic en más etiquetas para mostrar cualquiera de ellas)", ", {} star{}": ", {} estrella{}", @@ -242,7 +242,7 @@ "Create the keyword “{name}”": "Crear la palabra clave “{name}”", "new, inside {parent}": "nueva, dentro de {parent}", "Keywords of {n} selected photos": "Palabras clave de {n} fotos seleccionadas", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "“{name}” quitada de {n} fotos. Editar → Deshacer la devuelve.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "“{name}” quitada de {n} fotos. Editar → Deshacer la devuelve.", "1 task is still running: {names}. Quitting stops it.": "1 tarea sigue en curso: {names}. Salir la detiene.", "{n} tasks are still running: {names}. Quitting stops them.": "{n} tareas siguen en curso: {names}. Salir las detiene.", "{what} merge cancelled": "Combinación {what} cancelada", @@ -262,7 +262,7 @@ "Delete {n} effect preset{}? This can't be undone.": "¿Eliminar {n} ajuste(s) preestablecido(s) de efecto?{:.0} No se puede deshacer.", "Effect: {name}": "Efecto: {name}", "Exported {} effect preset{}": "Ajustes de efecto exportados: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "{e} efecto(s) de máscara importado(s){:.0} (Máscaras → Efecto)", + "Imported {e} mask effect{} (Masking → Effect)": "{e} efecto(s) de máscara importado(s){:.0} (Máscaras → Efecto)", "Update “{name}” with Current Settings": "Actualizar «{name}» con los ajustes actuales", "{n} preset{}": "{n} ajuste(s){:.0}", "{name} opened in the other editor": "{name} abierto en el otro editor", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 888af077ff..e8c062a679 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -1246,7 +1246,7 @@ "Remove from survey": "Quitar de Encuesta", "Remove location info": "Quitar información de ubicación", "Remove shortcut": "Quitar método abreviado", - "Remove this face box (undo with Edit ▸ Undo)": "Quitar este recuadro de cara (deshacer con Editar → Deshacer)", + "Remove this face box (undo with Edit → Undo)": "Quitar este recuadro de cara (deshacer con Editar → Deshacer)", "Remove this filter": "Quitar este filtro", "Remove this group": "Quitar este grupo", "Remove this rule": "Quitar esta regla", @@ -1302,7 +1302,7 @@ "Revert": "Revertir", "Review": "Revisión", "Review Import": "Revisar importación", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Clic derecho en una foto → Definir como foto de referencia y, después, Vista → Vista de referencia (Mayús+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Clic derecho en una foto → Definir como foto de referencia y, después, Vista → Vista de referencia (Mayús+R)", "Right-click a preset to delete it": "Clic derecho en un ajuste preestablecido para eliminarlo", "Rights Usage Terms": "Condiciones de uso de los derechos", "Rotate": "Rotar", @@ -2316,7 +2316,7 @@ "Same folder as original photo": "Misma carpeta que la foto original", "Tidying the thumbnail cache": "Ordenando la caché de miniaturas", "Reset all edits (Cmd+Shift+R)": "Restablecer todas las ediciones (Cmd+Mayús+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Los álbumes inteligentes se actualizan solos: cambie sus reglas o use Foto → Eliminar foto", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Los álbumes inteligentes se actualizan solos: cambie sus reglas o use Foto → Eliminar foto", "LightCraft stopped": "LightCraft se detuvo", "Focus Point": "Punto de enfoque", "Zoom to Focus Point": "Zoom al punto de enfoque", diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 1daab3dab9..ff7a292083 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -39,7 +39,7 @@ "Added “{keyword}” to {n} photo{}": "Avainsana ”{keyword}” lisätty kuviin: {n}{:.0}", "Adding photos… {} of {}": "Lisätään kuvia… {} / {}", "All {n} selected photos move by the same amount.": "Kaikkia valittuja kuvia ({n}) siirretään saman verran.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Jo kirjastossa, Äskettäin poistetuissa: valittuja kuvia {}{:.0} · napsauta hiiren kakkospainikkeella → Palauta tai Poista pysyvästi tuodaksesi uudelleen", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Jo kirjastossa, Äskettäin poistetuissa: valittuja kuvia {}{:.0} · napsauta hiiren kakkospainikkeella → Palauta tai Poista pysyvästi tuodaksesi uudelleen", "Already in the library: {} photo{} selected in All Photos": "Jo kirjastossa (Kaikki kuvat): valittuja kuvia {}{:.0}", "Already in “{}”": "Jo kohteessa ”{}”", "Applied {name}": "{name} käytetty", @@ -93,12 +93,12 @@ "Import cancelled · {} photo{} added": "Tuonti peruttu · lisättyjä kuvia: {}{:.0}", "Import failed: {e}": "Tuonti epäonnistui: {e}", "Import warnings ({n}):\n{warnings}": "Tuontivaroitukset ({n}):\n{warnings}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Tuotuja maskitehosteita: {e}{:.0} (Maskaus → Tehoste)", + "Imported {e} mask effect{} (Masking → Effect)": "Tuotuja maskitehosteita: {e}{:.0} (Maskaus → Tehoste)", "Imported {name}": "{name} tuotu", "Imported {n} point curve preset{}": "Tuotuja pistekäyrän esiasetuksia: {n}{:.0}", "Imported {n} preset{}": "Tuotuja esiasetuksia: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Tuotuja esiasetuksia: {n}{:.0}, ei luettavissa olevia tiedostoja: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Tuotuja profiileja: {profiles}{:.0} (Profiiliselain → niiden ryhmät)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Tuotuja profiileja: {profiles}{:.0} (Profiiliselain → niiden ryhmät)", "Imported {} photo{}": "Tuotuja kuvia: {}{:.0}", "In line for AI Denoise ({ahead} ahead)…": "Jonossa tekoälykohinanpoistoon ({ahead} edellä)…", "Insert at the cursor (also written {})": "Lisää kohdistimen kohtaan (kirjoitetaan myös {})", @@ -157,7 +157,7 @@ "Remove “{}” from Favorites": "Poista ”{}” suosikeista", "Removed from {}": "Poistettu kohteesta {}", "Removed {what} from {name}": "{what} poistettu kohteesta {name}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "”{name}” poistettu {n} kuvalta. Muokkaa → Kumoa palauttaa sen.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "”{name}” poistettu {n} kuvalta. Muokkaa → Kumoa palauttaa sen.", "Rename {n} Photos…": "Nimeä uudelleen {n} kuvaa…", "Rename “{name}”": "Nimeä uudelleen ”{name}”", "Renames {n} face{} across the library. The files are not changed.": "Nimeää uudelleen kasvoja koko kirjastossa: {n}{:.0}. Tiedostoja ei muuteta.", @@ -249,7 +249,7 @@ "{n} preset{}": "Esiasetuksia: {n}{:.0}", "{n} raws can now be developed from their raw data": "Raw-kuvia, jotka voidaan nyt kehittää raakadatastaan: {n}", "{n} selected photos · {pages} pages": "Valittuja kuvia: {n} · sivuja: {pages}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Samankaltaisia kuvia: {n}{:.0} · Näytä → Tyhjennä suodattimet näyttääksesi kaikki", + "{n} similar photo{} · View → Clear Filters to see all": "Samankaltaisia kuvia: {n}{:.0} · Näytä → Tyhjennä suodattimet näyttääksesi kaikki", "{n} tasks are still running: {names}. Quitting stops them.": "Käynnissä olevia tehtäviä: {n}: {names}. Lopettaminen pysäyttää ne.", "{n} {noun}": "{n} {noun}", "{pct} %": "{pct} %", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index e0a8c622a3..753c3ee93d 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -1414,7 +1414,7 @@ "Photo Grid": "Kuvaruudukko", "Photo Grid (G)": "Kuvaruudukko (G)", "Photo Merge": "Kuvien yhdistäminen", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Kuva → Muokkaa ohjelmassa → Muokkaa PhotoCraftissa (⇧⌘E tai napsauta kuvaa hiiren kakkospainikkeella) renderöi kopion muokkauksineen, pinoaa sen alkuperäisen kanssa ja avaa sen PhotoCraftissa. Tallenna siellä, niin kopio päivittyy täällä. PSD-muodossa PhotoCraft tallentaa suoraan siihen. Jätä sijainti tyhjäksi, ellet käytä kannettavaa kopiota.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Kuva → Muokkaa ohjelmassa → Muokkaa PhotoCraftissa (⇧⌘E tai napsauta kuvaa hiiren kakkospainikkeella) renderöi kopion muokkauksineen, pinoaa sen alkuperäisen kanssa ja avaa sen PhotoCraftissa. Tallenna siellä, niin kopio päivittyy täällä. PSD-muodossa PhotoCraft tallentaa suoraan siihen. Jätä sijainti tyhjäksi, ellet käytä kannettavaa kopiota.", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Kuva → Muokkaa ulkoisessa muokkausohjelmassa (⇧⌘E) renderöi 16-bittisen TIFF-kopion, pinoaa sen alkuperäisen kanssa ja avaa sen täällä (macOS:ssä sovelluksen nimi, muualla ohjelman polku).", "PhotoCraft": "PhotoCraft", "Photos": "Kuvat", @@ -1613,7 +1613,7 @@ "Remove missing photos from the library": "Poista puuttuvat kuvat kirjastosta", "Remove region": "Poista alue", "Remove shortcut": "Poista pikakuvake", - "Remove this face box (undo with Edit ▸ Undo)": "Poista tämä kasvorajaus (kumoa kohdasta Muokkaa → Kumoa)", + "Remove this face box (undo with Edit → Undo)": "Poista tämä kasvorajaus (kumoa kohdasta Muokkaa → Kumoa)", "Remove this filter": "Poista tämä suodatin", "Remove this group": "Poista tämä ryhmä", "Remove this rule": "Poista tämä sääntö", @@ -1677,7 +1677,7 @@ "Review": "Tarkistus", "Review Import": "Tarkista tuonti", "Right": "Oikea", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Napsauta kuvaa hiiren kakkospainikkeella → Aseta vertailukuvaksi, sitten Näytä → Vertailunäkymä (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Napsauta kuvaa hiiren kakkospainikkeella → Aseta vertailukuvaksi, sitten Näytä → Vertailunäkymä (Shift+R)", "Right-click a preset to delete it": "Poista esiasetus napsauttamalla sitä hiiren kakkospainikkeella", "Rights Usage Terms": "Oikeuksien käyttöehdot", "Rotate": "Kierrä", @@ -1888,7 +1888,7 @@ "Smart Album Rule Fields": "Älyalbumin sääntökentät", "Smart Preview Status": "Älyesikatselun tila", "Smart Previews Location": "Älyesikatseluiden sijainti", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Älyalbumit päivittyvät automaattisesti: muuta niiden sääntöjä tai käytä Kuva → Poista kuva", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Älyalbumit päivittyvät automaattisesti: muuta niiden sääntöjä tai käytä Kuva → Poista kuva", "Smart preview available": "Älyesikatselu saatavilla", "Smart previews": "Älyesikatselut", "Smart previews folder changed": "Älyesikatseluiden kansio muuttui", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 294273781e..8ea5098ccc 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -25,7 +25,7 @@ "Added {what} to {name}": "{what} ajouté à {name}", "Adding photos… {} of {}": "Ajout des photos… {} sur {}", "All {n} selected photos move by the same amount.": "Les {n} photos sélectionnées se déplacent de la même valeur.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Déjà dans la bibliothèque, dans « Supprimés récemment » : {} photo{} sélectionnée(s) · clic droit → Restaurer, ou Supprimer définitivement pour importer à nouveau", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Déjà dans la bibliothèque, dans « Supprimés récemment » : {} photo{} sélectionnée(s) · clic droit → Restaurer, ou Supprimer définitivement pour importer à nouveau", "Already in the library: {} photo{} selected in All Photos": "Déjà dans la bibliothèque : {} photo{} sélectionnée(s) dans Toutes les photos", "Auto ({})": "Automatique ({})", "Auto Import: added {} photo{}": "Importation automatique : {} photo{} ajoutée(s)", @@ -65,7 +65,7 @@ "Imported {n} point curve preset{}": "{n} préréglage{} de courbe à points importé(s)", "Imported {n} preset{}": "{n} préréglage{} importé(s)", "Imported {n} preset{}, {f} file{} not readable": "{n} préréglage{} importé(s), {f} fichier{} illisible(s)", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "{profiles} profil{} importé(s) (Navigateur de profils → leurs groupes)", + "Imported {profiles} profile{} (Profile browser → their groups)": "{profiles} profil{} importé(s) (Navigateur de profils → leurs groupes)", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "Les fichiers annexes XMP de {n} photos n'ont pas pu être écrits (leur dossier est-il hors ligne ?). LightCraft continue d'essayer.", "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "Le profil XMP « {profile} » n’a pas été appliqué à {path} ; les couleurs peuvent différer de Lightroom.", "Lightroom geometry was not preserved for {path}; {mode} will be recalculated.": "La géométrie Lightroom de {path} n’a pas été conservée ; {mode} sera recalculé.", @@ -195,7 +195,7 @@ "… and {more} more": "… et {more} de plus", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft ne peut pas encore décoder cette variante RAW ({}). Vous modifiez l’aperçu JPEG intégré de l’appareil photo, qui inclut déjà le style d’image (par ex. monochrome) et la balance des blancs de l’appareil.", "Filtered: {label}": "Filtré : {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} photo{} similaire(s) · Affichage → Effacer les filtres pour tout voir", + "{n} similar photo{} · View → Clear Filters to see all": "{n} photo{} similaire(s) · Affichage → Effacer les filtres pour tout voir", "Moved; {} photo(s) relinked": "Déplacé ; {} photo(s) de nouveau associée(s)", "{} label (click more labels to show any of them)": "Étiquette {} (cliquez sur « autres étiquettes » pour afficher celles de votre choix)", ", {} star{}": ", {} étoile{}", @@ -242,7 +242,7 @@ "Create the keyword “{name}”": "Créer le mot-clé « {name} »", "new, inside {parent}": "nouveau, dans {parent}", "Keywords of {n} selected photos": "Mots-clés de {n} photos sélectionnées", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "« {name} » retiré de {n} photos. Modifier → Annuler le rétablit.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "« {name} » retiré de {n} photos. Modifier → Annuler le rétablit.", "1 task is still running: {names}. Quitting stops it.": "1 tâche est encore en cours : {names}. Quitter l'arrête.", "{n} tasks are still running: {names}. Quitting stops them.": "{n} tâches sont encore en cours : {names}. Quitter les arrête.", "{what} merge cancelled": "Fusion {what} annulée", @@ -262,7 +262,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Supprimer {n} paramètre(s) prédéfini(s) d’effet ?{:.0} Cette action est irréversible.", "Effect: {name}": "Effet : {name}", "Exported {} effect preset{}": "Paramètres d’effet exportés : {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "{e} effet(s) de masque importé(s){:.0} (Masquage → Effet)", + "Imported {e} mask effect{} (Masking → Effect)": "{e} effet(s) de masque importé(s){:.0} (Masquage → Effet)", "Update “{name}” with Current Settings": "Mettre à jour « {name} » avec les réglages actuels", "{n} preset{}": "{n} paramètre(s){:.0}", "{name} opened in the other editor": "{name} ouvert dans l’autre éditeur", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 3278d6ccda..37cac132f8 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -1180,7 +1180,7 @@ "Remove from survey": "Retirer de la vue multiple", "Remove location info": "Supprimer les informations de lieu", "Remove shortcut": "Supprimer le raccourci", - "Remove this face box (undo with Edit ▸ Undo)": "Retirer ce cadre de visage (annuler avec Édition → Annuler)", + "Remove this face box (undo with Edit → Undo)": "Retirer ce cadre de visage (annuler avec Édition → Annuler)", "Remove this filter": "Retirer ce filtre", "Remove this group": "Retirer ce groupe", "Remove this rule": "Retirer cette règle", @@ -1230,7 +1230,7 @@ "Revert": "Rétablir l'original", "Review": "Révision", "Review Import": "Vérifier l'importation", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Clic droit sur une photo → Définir comme photo de référence, puis Affichage → Vue de référence (Maj+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Clic droit sur une photo → Définir comme photo de référence, puis Affichage → Vue de référence (Maj+R)", "Right-click a preset to delete it": "Clic droit sur un préréglage pour le supprimer", "Rights Usage Terms": "Conditions d'utilisation des droits", "Rotate": "Pivoter", @@ -2312,7 +2312,7 @@ "Same folder as original photo": "Même dossier que la photo d’origine", "Tidying the thumbnail cache": "Rangement du cache des miniatures", "Reset all edits (Cmd+Shift+R)": "Réinitialiser toutes les retouches (Cmd+Maj+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Les albums intelligents se mettent à jour d'eux-mêmes : modifiez leurs règles ou utilisez Photo → Supprimer la photo", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Les albums intelligents se mettent à jour d'eux-mêmes : modifiez leurs règles ou utilisez Photo → Supprimer la photo", "LightCraft stopped": "LightCraft s’est arrêté", "Focus Point": "Point de mise au point", "Zoom to Focus Point": "Zoomer sur le point de mise au point", diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 7fc3255221..12d0d443e9 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -120,7 +120,7 @@ "Adding photos… {} of {}": "Menambahkan foto… {} dari {}", " ({} in Recently Deleted)": " ({} di Baru dihapus)", "Already in the library: {} photo{} selected in All Photos": "Sudah ada di pustaka: {} foto{:.0} dipilih di Semua foto", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Sudah ada di pustaka, di Baru dihapus: {} foto{:.0} dipilih · klik kanan → Pulihkan, atau Hapus permanen untuk mengimpor ulang", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Sudah ada di pustaka, di Baru dihapus: {} foto{:.0} dipilih · klik kanan → Pulihkan, atau Hapus permanen untuk mengimpor ulang", "Auto ({})": "Otomatis ({})", "Build 1:1 Previews ({scope})": "Buat pratinjau 1:1 ({scope})", "Build Smart Previews ({scope})": "Buat pratinjau pintar ({scope})", @@ -169,7 +169,7 @@ "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "Geometri Lightroom untuk {path} tidak dipertahankan; transformasi Tegakkan terpandu yang tersimpan tidak didukung.", "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "Geometri Lightroom untuk {path} tidak dipertahankan; transformasi Tegakkan yang tersimpan tidak didukung.", "XMP adjustments were not imported for {path}: {fields}.": "Penyesuaian XMP untuk {path} tidak diimpor: {fields}.", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "{profiles} profil diimpor{:.0} (Penjelajah profil → grup masing-masing)", + "Imported {profiles} profile{} (Profile browser → their groups)": "{profiles} profil diimpor{:.0} (Penjelajah profil → grup masing-masing)", "Insert at the cursor (also written {})": "Sisipkan di posisi kursor (dapat juga ditulis {})", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0. Font: {} (OFL). Ikon: orisinal.", "Painting “{k}”: click photos to add or remove it · Esc stops": "Menerapkan “{k}”: klik foto untuk menambahkan atau menghapusnya · Esc untuk berhenti", @@ -199,7 +199,7 @@ "{} — show their photos": "{} — tampilkan foto orang ini", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft belum dapat mendekode varian raw ini ({}). Anda sedang mengedit pratinjau JPEG bawaan kamera, yang sudah menyertakan gaya gambar kamera (mis. Monokrom) dan keseimbangan putihnya.", "Filtered: {label}": "Difilter: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} foto serupa{:.0} · Tampilan → Hapus filter untuk melihat semua", + "{n} similar photo{} · View → Clear Filters to see all": "{n} foto serupa{:.0} · Tampilan → Hapus filter untuk melihat semua", "Moved; {} photo(s) relinked": "Dipindahkan; {} foto ditautkan ulang", "{} label (click more labels to show any of them)": "Label {} (klik label lain untuk ikut menampilkan foto berlabel tersebut)", ", {} star{}": ", {} bintang{:.0}", @@ -245,7 +245,7 @@ "Create the keyword “{name}”": "Buat kata kunci “{name}”", "new, inside {parent}": "baru, di dalam {parent}", "Keywords of {n} selected photos": "Kata kunci {n} foto yang dipilih", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "“{name}” dihapus dari {n} foto. Edit → Urungkan akan mengembalikannya.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "“{name}” dihapus dari {n} foto. Edit → Urungkan akan mengembalikannya.", "1 task is still running: {names}. Quitting stops it.": "1 tugas masih berjalan: {names}. Jika keluar sekarang, tugas ini akan dihentikan.", "{n} tasks are still running: {names}. Quitting stops them.": "{n} tugas masih berjalan: {names}. Jika keluar sekarang, semua tugas ini akan dihentikan.", "{what} merge cancelled": "Penggabungan {what} dibatalkan", @@ -265,7 +265,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Hapus {n} preset efek{:.0}? Tindakan ini tidak dapat diurungkan.", "Effect: {name}": "Efek: {name}", "Exported {} effect preset{}": "{} preset efek diekspor{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "{e} efek masker{:.0} diimpor (Masker → Efek)", + "Imported {e} mask effect{} (Masking → Effect)": "{e} efek masker{:.0} diimpor (Masker → Efek)", "Update “{name}” with Current Settings": "Perbarui “{name}” dengan pengaturan saat ini", "{n} preset{}": "{n} preset{:.0}", "{name} opened in the other editor": "{name} dibuka di editor lain", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 0d6da9b8fb..6badf6b77e 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -1397,7 +1397,7 @@ "Photo Grid": "Grid foto", "Photo Grid (G)": "Grid foto (G)", "Photo Merge": "Gabung foto", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Edit di → Edit di PhotoCraft (⇧⌘E, atau klik kanan foto) merender salinan beserta hasil edit Anda, menumpuknya dengan foto asli, lalu membukanya di PhotoCraft. Simpan di sana, dan salinan di sini ikut diperbarui. Jika berformat PSD, PhotoCraft menyimpan langsung ke file tersebut. Kosongkan lokasi kecuali Anda menggunakan salinan portabel.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Edit di → Edit di PhotoCraft (⇧⌘E, atau klik kanan foto) merender salinan beserta hasil edit Anda, menumpuknya dengan foto asli, lalu membukanya di PhotoCraft. Simpan di sana, dan salinan di sini ikut diperbarui. Jika berformat PSD, PhotoCraft menyimpan langsung ke file tersebut. Kosongkan lokasi kecuali Anda menggunakan salinan portabel.", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Foto → Edit di editor eksternal (⇧⌘E) membuat salinan TIFF 16-bit, menumpuknya dengan file asli, lalu membukanya dengan program yang diisi di sini (nama aplikasi di macOS, jalur program di sistem lain).", "PhotoCraft": "PhotoCraft", "Photos": "Foto", @@ -1601,7 +1601,7 @@ "Remove location info": "Hapus info lokasi", "Remove missing photos from the library": "Keluarkan foto yang hilang dari pustaka", "Remove shortcut": "Hapus pintasan", - "Remove this face box (undo with Edit ▸ Undo)": "Hapus kotak wajah ini (urungkan lewat Edit → Urungkan)", + "Remove this face box (undo with Edit → Undo)": "Hapus kotak wajah ini (urungkan lewat Edit → Urungkan)", "Remove this filter": "Hapus filter ini", "Remove this group": "Hapus grup ini", "Remove this rule": "Hapus aturan ini", @@ -1668,7 +1668,7 @@ "Review": "Tinjauan", "Review Import": "Tinjau impor", "Right": "Kanan", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Klik kanan foto → Jadikan foto referensi, lalu Tampilan → Tampilan referensi (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Klik kanan foto → Jadikan foto referensi, lalu Tampilan → Tampilan referensi (Shift+R)", "Right-click a preset to delete it": "Klik kanan preset untuk menghapusnya", "Rights Usage Terms": "Ketentuan penggunaan", "Rotate": "Putar", @@ -1887,7 +1887,7 @@ "Smart Album Rule Fields": "Kolom aturan album pintar", "Smart Preview Status": "Status pratinjau pintar", "Smart Previews Location": "Lokasi pratinjau pintar", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Album pintar diperbarui secara otomatis: ubah aturannya, atau gunakan Foto → Hapus foto", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Album pintar diperbarui secara otomatis: ubah aturannya, atau gunakan Foto → Hapus foto", "Smart preview available": "Pratinjau pintar tersedia", "Smart previews": "Pratinjau pintar", "Smart previews folder changed": "Folder pratinjau pintar diubah", diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 7efae90e94..649f2c811f 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -25,7 +25,7 @@ "Added {what} to {name}": "Aggiunto a {name}: {what}", "Adding photos… {} of {}": "Aggiunta delle foto… {} di {}", "All {n} selected photos move by the same amount.": "Tutte le {n} foto selezionate si spostano della stessa quantità.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Già nella libreria, in Eliminate di recente: foto selezionate {}{:.0} · clic destro → Ripristina, oppure Elimina definitivamente per importarle da capo", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Già nella libreria, in Eliminate di recente: foto selezionate {}{:.0} · clic destro → Ripristina, oppure Elimina definitivamente per importarle da capo", "Already in the library: {} photo{} selected in All Photos": "Già nella libreria (selezionate in Tutte le foto): {}{:.0}", "Auto ({})": "Automatico ({})", "Auto Import: added {} photo{}": "Importazione automatica · foto aggiunte: {}{:.0}", @@ -70,7 +70,7 @@ "Imported {n} point curve preset{}": "Preset di curva a punti importati: {n}{:.0}", "Imported {n} preset{}": "Preset importati: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Preset importati: {n}{:.0}, file illeggibili: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Profili importati: {profiles}{:.0} (Browser dei profili → i loro gruppi)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Profili importati: {profiles}{:.0} (Browser dei profili → i loro gruppi)", "Imported {} photo{}": "Foto importate: {}{:.0}", "Insert at the cursor (also written {})": "Inserisci al cursore (si scrive anche {})", "Label Set: {name}": "Set di etichette: {name}", @@ -192,7 +192,7 @@ "… and {more} more": "… e altre {more}", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft non sa ancora decodificare questa variante raw ({}). Stai modificando l'anteprima JPEG incorporata dalla fotocamera, che contiene già lo stile immagine della fotocamera (ad es. Monocromatico) e il bilanciamento del bianco.", "Filtered: {label}": "Filtrate: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Foto simili: {n}{:.0} · Visualizza → Cancella filtri per vederle tutte", + "{n} similar photo{} · View → Clear Filters to see all": "Foto simili: {n}{:.0} · Visualizza → Cancella filtri per vederle tutte", "Moved; {} photo(s) relinked": "Spostata; foto ricollegate: {}", "{} label (click more labels to show any of them)": "Etichetta {} (fai clic su altre etichette per mostrarne una qualsiasi)", ", {} star{}": ", stelle: {}{:.0}", @@ -264,7 +264,7 @@ "Keywords of {n} selected photos": "Parole chiave delle foto selezionate: {n}", "new, inside {parent}": "nuova, dentro {parent}", "Delete these {n} effect presets?": "Eliminare questi preset effetto ({n})?", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Imported {e} mask effect{} (Masking → Effect)", + "Imported {e} mask effect{} (Masking → Effect)": "Imported {e} mask effect{} (Masking → Effect)", "{photos} catalog records processed; {collections} collections.": "Record del catalogo elaborati: {photos}; raccolte: {collections}.", "Skipped {problem}": "Saltato: {problem}", "Updated {name}": "{name} aggiornato", @@ -282,7 +282,7 @@ " · kept, not applied: {}": " · conservato, non applicato: {}", "Delete the effect preset “{name}”?": "Eliminare il preset effetto “{name}”?", "{n} raws can now be developed from their raw data": "Raw che ora si possono sviluppare dai loro dati raw: {n}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", "Inside: {names}": "Al suo interno: {names}", "Template preview: {name}": "Anteprima del modello: {name}", "{n} photos in view · {slides} slides · {time}": "Foto nella vista: {n} · diapositive: {slides} · {time}", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index e159fd47d1..b5e05dfb1a 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -1191,7 +1191,7 @@ "Remove from survey": "Rimuovi dalla panoramica", "Remove location info": "Rimuovi le informazioni sulla posizione", "Remove shortcut": "Rimuovi scorciatoia", - "Remove this face box (undo with Edit ▸ Undo)": "Rimuovi questo riquadro del volto (annulla con Modifica → Annulla)", + "Remove this face box (undo with Edit → Undo)": "Rimuovi questo riquadro del volto (annulla con Modifica → Annulla)", "Remove this filter": "Rimuovi questo filtro", "Remove this group": "Rimuovi questo gruppo", "Remove this rule": "Rimuovi questa regola", @@ -1228,7 +1228,7 @@ "Reset all curves: point curves (all channels) and parametric (double-click a channel to reset only that one)": "Reimposta tutte le curve: curve a punti (tutti i canali) e parametrica (doppio clic su un canale per reimpostare solo quello)", "Reset all edits": "Ripristina tutte le modifiche", "Reset all edits (Cmd+Shift+R)": "Reimposta tutte le modifiche (Cmd+Maiusc+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Gli album smart si aggiornano da soli: cambia le loro regole, oppure usa Foto → Elimina foto", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Gli album smart si aggiornano da soli: cambia le loro regole, oppure usa Foto → Elimina foto", "LightCraft stopped": "LightCraft si è chiuso", "Zoom to Focus Point": "Zoom sul punto di messa a fuoco", "Focus": "Messa a fuoco", @@ -1266,7 +1266,7 @@ "Revert": "Ripristina", "Review": "Revisione", "Review Import": "Rivedi importazione", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Clic destro su una foto → Imposta come foto di riferimento, poi Visualizza → Vista di riferimento (Maiusc+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Clic destro su una foto → Imposta come foto di riferimento, poi Visualizza → Vista di riferimento (Maiusc+R)", "Right-click a preset to delete it": "Clic destro su un preset per eliminarlo", "Rights Usage Terms": "Condizioni d'uso dei diritti", "Rotate": "Ruota", @@ -1838,7 +1838,7 @@ "Monitor profile": "Profilo monitor", "None (the display is treated as sRGB)": "Nessuno (lo schermo viene trattato come sRGB)", "Other editor": "Altro editor", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Modifica in → Modifica in PhotoCraft (⇧⌘E, o clic destro su una foto) esegue il rendering di una copia con le tue modifiche, la impila con l'originale e la apre in PhotoCraft. Salva lì e la copia si aggiorna qui. Come PSD, PhotoCraft salva direttamente su di essa. Lascia vuota la posizione a meno che tu non usi una copia portatile.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Modifica in → Modifica in PhotoCraft (⇧⌘E, o clic destro su una foto) esegue il rendering di una copia con le tue modifiche, la impila con l'originale e la apre in PhotoCraft. Salva lì e la copia si aggiorna qui. Come PSD, PhotoCraft salva direttamente su di essa. Lascia vuota la posizione a meno che tu non usi una copia portatile.", "PhotoCraft": "PhotoCraft", "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "Le foto vengono mostrate attraverso il profilo ICC del monitor, così i colori sono corretti su schermi calibrati e a gamut esteso, e la vista Dettaglio usa tutto il gamut dello schermo. Istogramma, cache delle anteprime ed esportazioni non cambiano.", "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Le foto restano in Tutte le foto. Eliminando una cartella si eliminano anche i suoi album. Puoi annullare l'operazione.", diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 99c14bf16d..9e242f8b54 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -120,7 +120,7 @@ "Adding photos… {} of {}": "写真を追加中:{1}枚中{0}枚", " ({} in Recently Deleted)": "(うち{}枚は最近削除した写真)", "Already in the library: {} photo{} selected in All Photos": "ライブラリに登録済み:すべての写真で{}枚を選択しました{:.0}", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "ライブラリの「最近削除した写真」にあります:{}枚を選択しました{:.0}・右クリック → 復元、または完全に削除してから読み込み直し", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "ライブラリの「最近削除した写真」にあります:{}枚を選択しました{:.0}・右クリック → 復元、または完全に削除してから読み込み直し", "Auto ({})": "自動 ({})", "Build 1:1 Previews ({scope})": "1:1プレビューを作成({scope})", "Build Smart Previews ({scope})": "スマートプレビューを作成({scope})", @@ -169,7 +169,7 @@ "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "{path} の Lightroom ジオメトリは保持されませんでした。ガイド付き Upright の保存された変換はサポートされていません。", "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "{path} の Lightroom ジオメトリは保持されませんでした。保存された Upright の変換はサポートされていません。", "XMP adjustments were not imported for {path}: {fields}.": "{path} の XMP 調整は読み込まれませんでした:{fields}。", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "{profiles}個のプロファイルを読み込みました{:.0}(プロファイルブラウザー → 各グループ)", + "Imported {profiles} profile{} (Profile browser → their groups)": "{profiles}個のプロファイルを読み込みました{:.0}(プロファイルブラウザー → 各グループ)", "Insert at the cursor (also written {})": "カーソル位置に挿入({}とも表記可)", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0。フォント:{}(OFL)。アイコン:オリジナル", "Painting “{k}”: click photos to add or remove it · Esc stops": "「{k}」を適用中:写真をクリックして付け外し・Escで終了", @@ -199,7 +199,7 @@ "{} — show their photos": "{} — この人物の写真を表示", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraftはこのRAWの形式({})をまだデコードできません。カメラの埋め込みJPEGプレビューを編集しています。このプレビューには、カメラのピクチャースタイル(モノクロなど)とホワイトバランスがすでに反映されています", "Filtered: {label}": "フィルター適用中:{label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "似た写真{n}枚{:.0}・すべて表示するには「表示 → フィルターを解除」", + "{n} similar photo{} · View → Clear Filters to see all": "似た写真{n}枚{:.0}・すべて表示するには「表示 → フィルターを解除」", "Moved; {} photo(s) relinked": "移動しました。{}枚の写真の参照先を更新しました", "{} label (click more labels to show any of them)": "{}ラベル(ほかのラベルもクリックすると、いずれかに一致する写真を表示)", ", {} star{}": "、星{}つ{:.0}", @@ -246,7 +246,7 @@ "Create the keyword “{name}”": "キーワード「{name}」を作成", "new, inside {parent}": "新規、{parent} の中", "Keywords of {n} selected photos": "選択した写真{n}枚のキーワード", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "「{name}」を写真{n}枚から削除しました。「編集」→「取り消す」で元に戻せます。", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "「{name}」を写真{n}枚から削除しました。「編集」→「取り消す」で元に戻せます。", "1 task is still running: {names}. Quitting stops it.": "1件のタスクが実行中です:{names}。終了すると停止します。", "{n} tasks are still running: {names}. Quitting stops them.": "{n}件のタスクが実行中です:{names}。終了すると停止します。", "{what} merge cancelled": "{what}合成をキャンセルしました", @@ -266,7 +266,7 @@ "Delete {n} effect preset{}? This can't be undone.": "効果プリセット{n}件を削除しますか?{:.0}元に戻せません。", "Effect: {name}": "効果:{name}", "Exported {} effect preset{}": "効果プリセットを{}件書き出しました{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "マスク効果を{e}件読み込みました{:.0}(マスク → 効果)", + "Imported {e} mask effect{} (Masking → Effect)": "マスク効果を{e}件読み込みました{:.0}(マスク → 効果)", "Update “{name}” with Current Settings": "「{name}」を現在の設定で更新", "{n} preset{}": "{n}件のプリセット{:.0}", "{name} opened in the other editor": "{name}を別のエディタで開きました", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index e1834555bd..9c36318f12 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -720,7 +720,7 @@ "Remove a filter above, or choose Clear all": "上のフィルターを解除するか、「すべて解除」を選択してください", "Remove from Target Album": "追加先アルバムから除去", "Remove shortcut": "ショートカットを削除", - "Remove this face box (undo with Edit ▸ Undo)": "この顔の枠を除去(「編集 → 取り消す」で元に戻せます)", + "Remove this face box (undo with Edit → Undo)": "この顔の枠を除去(「編集 → 取り消す」で元に戻せます)", "Rename Component": "構成要素の名前を変更", "Rename Folder": "フォルダ名を変更", "Rename Mask": "マスク名を変更", @@ -1180,7 +1180,7 @@ "Reverse the order": "逆順にする", "Review": "レビュー", "Review Import": "読み込み内容を確認", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "写真を右クリックして参照写真に設定し、「表示 → 参照表示」(⇧R)を選択してください", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "写真を右クリックして参照写真に設定し、「表示 → 参照表示」(⇧R)を選択してください", "Right-click a preset to delete it": "プリセットを右クリックして削除", "Rights Usage Terms": "利用条件", "Rotate": "回転", @@ -2314,7 +2314,7 @@ "Same folder as original photo": "元の写真と同じフォルダー", "Tidying the thumbnail cache": "サムネールキャッシュを整理中", "Reset all edits (Cmd+Shift+R)": "すべての編集をリセット(⌘⇧R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "スマートアルバムは自動で更新されます。ルールを変更するか、写真 → 写真を削除を使ってください", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "スマートアルバムは自動で更新されます。ルールを変更するか、写真 → 写真を削除を使ってください", "LightCraft stopped": "LightCraftが終了しました", "Focus Point": "フォーカスポイント", "Zoom to Focus Point": "フォーカスポイントにズーム", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 4603682618..0c1e068134 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -35,7 +35,7 @@ "Added “{keyword}” to {n} photo{}": "„{keyword}“ დაემატა ფოტოს: {n}{:.0}", "Adding photos… {} of {}": "ფოტოების დამატება… {} / {}", "All {n} selected photos move by the same amount.": "მონიშნული ფოტოები ({n}) ერთი და იმავე სიდიდით გადაინაცვლებს.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "უკვე ბიბლიოთეკაშია, ახლახან წაშლილებში: მონიშნულია ფოტო: {}{:.0} · მარჯვენა დაწკაპუნება → აღდგენა, ან სამუდამოდ წაშლა თავიდან იმპორტისთვის", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "უკვე ბიბლიოთეკაშია, ახლახან წაშლილებში: მონიშნულია ფოტო: {}{:.0} · მარჯვენა დაწკაპუნება → აღდგენა, ან სამუდამოდ წაშლა თავიდან იმპორტისთვის", "Already in the library: {} photo{} selected in All Photos": "უკვე ბიბლიოთეკაშია: „ყველა ფოტოში“ მონიშნულია ფოტო: {}{:.0}", "Auto ({})": "ავტომატური ({})", "Auto Import: added {} photo{}": "ავტოიმპორტი: დაემატა ფოტო: {}{:.0}", @@ -80,7 +80,7 @@ "Imported {n} point curve preset{}": "იმპორტირებულია წერტილოვანი მრუდის პრესეტი: {n}{:.0}", "Imported {n} preset{}": "იმპორტირებულია პრესეტი: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "იმპორტირებულია პრესეტი: {n}{:.0}, ვერ იკითხება ფაილი: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "იმპორტირებულია პროფილი: {profiles}{:.0} (პროფილების ბრაუზერი → მათი ჯგუფები)", + "Imported {profiles} profile{} (Profile browser → their groups)": "იმპორტირებულია პროფილი: {profiles}{:.0} (პროფილების ბრაუზერი → მათი ჯგუფები)", "Imported {} photo{}": "იმპორტირებულია ფოტო: {}{:.0}", "In line for AI Denoise ({ahead} ahead)…": "AI ხმაურის მოცილების რიგში (წინ არის: {ahead})…", "Insert at the cursor (also written {})": "კურსორის ადგილას ჩასმა (ასევე იწერება როგორც {})", @@ -205,7 +205,7 @@ "{n} photo{}": "ფოტო: {n}{:.0}", "{n} photo{} match · updates automatically as photos change": "შესაბამისი ფოტო: {n}{:.0} · ავტომატურად განახლდება ფოტოების ცვლილებისას", "{n} photo{} now · updates automatically as photos change": "ახლა ფოტო: {n}{:.0} · ავტომატურად განახლდება ფოტოების ცვლილებისას", - "{n} similar photo{} · View ▸ Clear Filters to see all": "მსგავსი ფოტო: {n}{:.0} · ყველას სანახავად: ხედი → ფილტრების გასუფთავება", + "{n} similar photo{} · View → Clear Filters to see all": "მსგავსი ფოტო: {n}{:.0} · ყველას სანახავად: ხედი → ფილტრების გასუფთავება", "{n} tasks are still running: {names}. Quitting stops them.": "ჯერ კიდევ მიმდინარეობს ამოცანები ({n}): {names}. გასვლა მათ შეწყვეტს.", "{n} {noun}": "{noun}: {n}", "{pct} %": "{pct} %", @@ -262,12 +262,12 @@ "Effect: {name}": "Effect: {name}", "Exported to {path}": "Exported to {path}", "Exported {} effect preset{}": "Exported {} effect preset{}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Imported {e} mask effect{} (Masking → Effect)", + "Imported {e} mask effect{} (Masking → Effect)": "Imported {e} mask effect{} (Masking → Effect)", "Imported {name}": "Imported {name}", "Keywords of {n} selected photos": "Keywords of {n} selected photos", "LightCraft stopped unexpectedly: {e}": "LightCraft stopped unexpectedly: {e}", "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}": "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", "Inside: {names}": "შიგნით: {names}", "Renames {n} face{} across the library. The files are not changed.": "Renames {n} face{} across the library. The files are not changed.", "Saved template {name}": "Saved template {name}", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 32c4077001..51d07f59cc 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -1484,7 +1484,7 @@ "Photo Merge": "ფოტოების გაერთიანება", "Photo Merge of Canon CR2 (and other raws whose colour LightCraft fits from the camera's own JPEG, such as NEF and": "Canon CR2-ის (და სხვა RAW ფაილების, რომელთა ფერსაც LightCraft კამერის საკუთარი JPEG-იდან არგებს, როგორიცაა NEF და", "Photo menu. The filmstrip has the photo context menu too. Adding a file again that is in Recently Deleted no": "„ფოტო“ მენიუში. კადრების ზოლსაც აქვს ფოტოს კონტექსტური მენიუ. ახლახან წაშლილში მყოფი ფაილის ხელახლა დამატება აღარ", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "ფოტო → რედაქტირება სხვა პროგრამაში → რედაქტირება PhotoCraft-ში (⇧⌘E, ან მარჯვენა დაწკაპუნება ფოტოზე) არენდერებს ასლს თქვენი ცვლილებებით, ორიგინალთან ერთ დასტაში აერთიანებს და PhotoCraft-ში ხსნის. იქ შენახვისას ასლი აქაც განახლდება. PSD-ის შემთხვევაში PhotoCraft პირდაპირ მასში ინახავს. მდებარეობა ცარიელი დატოვეთ, თუ პორტატულ ასლს არ იყენებთ.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "ფოტო → რედაქტირება სხვა პროგრამაში → რედაქტირება PhotoCraft-ში (⇧⌘E, ან მარჯვენა დაწკაპუნება ფოტოზე) არენდერებს ასლს თქვენი ცვლილებებით, ორიგინალთან ერთ დასტაში აერთიანებს და PhotoCraft-ში ხსნის. იქ შენახვისას ასლი აქაც განახლდება. PSD-ის შემთხვევაში PhotoCraft პირდაპირ მასში ინახავს. მდებარეობა ცარიელი დატოვეთ, თუ პორტატულ ასლს არ იყენებთ.", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "ფოტო → რედაქტირება გარე რედაქტორში (⇧⌘E) ქმნის 16-ბიტიან TIFF ასლს, ორიგინალთან ერთად დასტაში აერთიანებს და აქ ხსნის (macOS-ზე აპის სახელი, სხვაგან — პროგრამის მისამართი).", "Photos": "ფოტოები", "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "ფოტოები თქვენი მონიტორის ICC პროფილით ნაჩვენებია, ამიტომ ფერები სწორია ფართო ფერთა გამისა და დაკალიბრებულ ეკრანებზე, ხოლო დეტალური ხედი ეკრანის მთელ ფერთა გამას იყენებს. ჰისტოგრამაზე, წინასწარი ხედების ქეშებსა და ექსპორტზე ეს გავლენას არ ახდენს.", @@ -1689,7 +1689,7 @@ "Remove location info": "მდებარეობის ინფორმაციის წაშლა", "Remove missing photos from the library": "დაკარგული ფოტოების ბიბლიოთეკიდან ამოშლა", "Remove shortcut": "მალსახმობის წაშლა", - "Remove this face box (undo with Edit ▸ Undo)": "ამ სახის ჩარჩოს წაშლა (დაბრუნება: რედაქტირება → დაბრუნება)", + "Remove this face box (undo with Edit → Undo)": "ამ სახის ჩარჩოს წაშლა (დაბრუნება: რედაქტირება → დაბრუნება)", "Remove this filter": "ამ ფილტრის მოშორება", "Remove this group": "ამ ჯგუფის წაშლა", "Remove this rule": "ამ წესის წაშლა", @@ -1754,7 +1754,7 @@ "Right-click a folder (or a disk other than the startup disk) in the sidebar's Folders section ▸ Synchronize": "მარჯვენა დაწკაპუნება საქაღალდეზე (ან სასტარტოს გარდა სხვა დისკზე) გვერდითი ზოლის საქაღალდეების სექციაში → საქაღალდის", "Right-click a folder ▸ New ▸ Create Album… / Create Smart Album… / Create Smart Album from Filter… / Create Folder…": "მარჯვენა დაწკაპუნება საქაღალდეზე → ახალი → ალბომის შექმნა… / სმარტ-ალბომის შექმნა… / სმარტ-ალბომის შექმნა ფილტრიდან… / საქაღალდის შექმნა…", "Right-click a photo ▸ Edit In ▸ Edit in PhotoCraft (or Photo ▸ Edit In, ⇧⌘E) renders a copy with your edits, stacks it": "მარჯვენა დაწკაპუნება ფოტოზე → რედაქტირება სხვა პროგრამაში → რედაქტირება PhotoCraft-ში (ან ფოტო → რედაქტირება სხვა პროგრამაში, ⇧⌘E) არენდერებს ასლს თქვენი ცვლილებებით, ათავსებს მას", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "დაწკაპეთ ფოტოზე მარჯვენა ღილაკით → ეტალონურ ფოტოდ დაყენება, შემდეგ ხედი → ეტალონური ხედი (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "დაწკაპეთ ფოტოზე მარჯვენა ღილაკით → ეტალონურ ფოტოდ დაყენება, შემდეგ ხედი → ეტალონური ხედი (Shift+R)", "Right-click a preset to delete it": "პრესეტის წასაშლელად დაწკაპეთ მასზე მარჯვენა ღილაკით", "Right-click ▸ Put New Keywords Inside This Keyword: new keywords, made with + or typed in the box above, go inside": "მარჯვენა დაწკაპუნება → ახალი საკვანძო სიტყვების ამ საკვანძო სიტყვაში ჩასმა: + ღილაკით ან ზემოთ ველში აკრეფილი ახალი საკვანძო სიტყვები", "Rights Usage Terms": "უფლებების გამოყენების პირობები", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 20c7f840d6..76fcc28a22 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -25,7 +25,7 @@ "Added {what} to {name}": "Dodano {what} do {name}", "Adding photos… {} of {}": "Dodawanie zdjęć… {} z {}", "All {n} selected photos move by the same amount.": "Wszystkie {n} zaznaczone zdjęcia zostaną przesunięte o tę samą wartość.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Już w bibliotece, w Ostatnio usuniętych — zaznaczone zdjęcia: {}{:.0} · kliknij prawym przyciskiem → Przywróć albo Usuń trwale, aby zaimportować ponownie", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Już w bibliotece, w Ostatnio usuniętych — zaznaczone zdjęcia: {}{:.0} · kliknij prawym przyciskiem → Przywróć albo Usuń trwale, aby zaimportować ponownie", "Already in the library: {} photo{} selected in All Photos": "Już w bibliotece — zaznaczone zdjęcia we Wszystkich zdjęciach: {}{:.0}", "Auto ({})": "Automatycznie ({})", "Auto Import: added {} photo{}": "Automatyczny import — dodane zdjęcia: {}{:.0}", @@ -63,7 +63,7 @@ "Imported {n} point curve preset{}": "Zaimportowane ustawienia krzywej punktowej: {n}{:.0}", "Imported {n} preset{}": "Zaimportowane ustawienia wstępne: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Zaimportowane ustawienia wstępne: {n}{:.0}, nieczytelne pliki: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Zaimportowane profile: {profiles}{:.0} (Przeglądarka profili → odpowiednie grupy)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Zaimportowane profile: {profiles}{:.0} (Przeglądarka profili → odpowiednie grupy)", "Imported {} photo{}": "Zaimportowane zdjęcia: {}{:.0}", "Insert at the cursor (also written {})": "Wstaw w miejscu kursora (zostanie też zapisane {})", "Label Set: {name}": "Zestaw etykiet: {name}", @@ -183,7 +183,7 @@ "… and {more} more": "… i jeszcze {more}", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft nie obsługuje jeszcze tego wariantu RAW ({}). Edytujesz podgląd JPEG osadzony przez aparat, zawierający już styl obrazu aparatu (np. monochromatyczny) i balans bieli.", "Filtered: {label}": "Filtrowanie: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Podobne zdjęcia: {n}{:.0} · Widok → Wyczyść filtry, aby zobaczyć wszystkie", + "{n} similar photo{} · View → Clear Filters to see all": "Podobne zdjęcia: {n}{:.0} · Widok → Wyczyść filtry, aby zobaczyć wszystkie", "Moved; {} photo(s) relinked": "Przeniesiono; ponownie powiązane zdjęcia: {}", "{} label (click more labels to show any of them)": "{} etykieta (kliknij kolejne etykiety, aby wyświetlić dowolną z nich)", ", {} star{}": ", gwiazdki: {}{:.0}", @@ -257,7 +257,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Usunąć ustawienia efektów ({n})?{:.0} Tej operacji nie można cofnąć.", "Effect: {name}": "Efekt: {name}", "Exported {} effect preset{}": "Wyeksportowane ustawienia efektów: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Zaimportowane efekty masek: {e}{:.0} (Maskowanie → Efekt)", + "Imported {e} mask effect{} (Masking → Effect)": "Zaimportowane efekty masek: {e}{:.0} (Maskowanie → Efekt)", "Update “{name}” with Current Settings": "Zaktualizuj „{name}” bieżącymi ustawieniami", "{n} preset{}": "Ustawienia: {n}{:.0}", "{count} more warnings.": "Pozostałe ostrzeżenia: {count}.", @@ -284,7 +284,7 @@ "Create the keyword “{name}”": "Utwórz słowo kluczowe „{name}”", "new, inside {parent}": "nowe, w {parent}", "Keywords of {n} selected photos": "Słowa kluczowe zaznaczonych zdjęć ({n})", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Usunięto „{name}” ze zdjęć ({n}). Edytuj → Cofnij przywraca.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Usunięto „{name}” ze zdjęć ({n}). Edytuj → Cofnij przywraca.", "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}": "LightCraft nieoczekiwanie zakończył działanie: {e}\n\nSzczegóły są w pliku dziennika: {path}", "LightCraft stopped unexpectedly: {e}": "LightCraft nieoczekiwanie zakończył działanie: {e}", "Renames {n} face{} across the library. The files are not changed.": "Zmienia nazwę twarzy w całej bibliotece (twarze: {n}).{:.0} Pliki nie są zmieniane.", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index adac22e62a..50f3df22e7 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -1152,7 +1152,7 @@ "Remove from survey": "Usuń z widoku przeglądu", "Remove location info": "Usuń informacje o lokalizacji", "Remove shortcut": "Usuń skrót klawiszowy", - "Remove this face box (undo with Edit ▸ Undo)": "Usuń tę ramkę twarzy (cofnij przez Edycja → Cofnij)", + "Remove this face box (undo with Edit → Undo)": "Usuń tę ramkę twarzy (cofnij przez Edycja → Cofnij)", "Remove this filter": "Usuń ten filtr", "Remove this group": "Usuń tę grupę", "Remove this rule": "Usuń tę regułę", @@ -1205,7 +1205,7 @@ "Revert": "Cofnij zmiany", "Review": "Przegląd", "Review Import": "Sprawdź import", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Kliknij zdjęcie prawym przyciskiem → Ustaw jako zdjęcie referencyjne, a potem Widok → Widok referencyjny (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Kliknij zdjęcie prawym przyciskiem → Ustaw jako zdjęcie referencyjne, a potem Widok → Widok referencyjny (Shift+R)", "Right-click a preset to delete it": "Kliknij ustawienie wstępne prawym przyciskiem, aby je usunąć", "Rights Usage Terms": "Warunki korzystania z praw", "Rotate": "Obróć", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index f17f2c0fd4..70a5446654 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -15,7 +15,7 @@ "Added {n} photo{} to “{}”": "{n} foto{0} adicionada{0} a “{1}”", "Adding photos… {} of {}": "Adicionando fotos… {} de {}", "All {n} selected photos move by the same amount.": "Todas as {n} fotos selecionadas se movem pela mesma quantidade.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Já na biblioteca, em Excluídos recentemente: {0} foto{1} selecionada{1} · clique com o botão direito → Restaurar, ou Excluir permanentemente para importar de novo", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Já na biblioteca, em Excluídos recentemente: {0} foto{1} selecionada{1} · clique com o botão direito → Restaurar, ou Excluir permanentemente para importar de novo", "Already in the library: {} photo{} selected in All Photos": "Já na biblioteca: {0} foto{1} selecionada{1} em Todas as fotos", "Already in “{}”": "Já está em “{}”", "Auto ({})": "Automático ({})", @@ -169,7 +169,7 @@ "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "A geometria do Lightroom não foi preservada para {path}; a transformação salva do Upright guiado não é compatível.", "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "A geometria do Lightroom não foi preservada para {path}; a transformação salva do Upright não é compatível.", "XMP adjustments were not imported for {path}: {fields}.": "Os ajustes XMP não foram importados para {path}: {fields}.", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "{profiles} perfil(is) importado(s){:.0} (Navegador de perfis → seus grupos)", + "Imported {profiles} profile{} (Profile browser → their groups)": "{profiles} perfil(is) importado(s){:.0} (Navegador de perfis → seus grupos)", "Insert at the cursor (also written {})": "Inserir no cursor (também escrito {})", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0. Fontes: {} (OFL). Ícones: originais.", "Painting “{k}”: click photos to add or remove it · Esc stops": "Aplicando “{k}”: clique nas fotos para adicionar ou remover · Esc para", @@ -199,7 +199,7 @@ "{} — show their photos": "{} — mostrar as fotos desta pessoa", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "O LightCraft ainda não consegue decodificar esta variante RAW ({}). Você está editando a prévia JPEG incorporada da câmera, que já inclui o estilo de imagem da câmera (p. ex. Monocromático) e o balanço de branco.", "Filtered: {label}": "Filtrado: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} foto{0} semelhante{0} · Exibir → Limpar filtros para ver todas", + "{n} similar photo{} · View → Clear Filters to see all": "{n} foto{0} semelhante{0} · Exibir → Limpar filtros para ver todas", "Moved; {} photo(s) relinked": "Movida; {} foto(s) vinculada(s) novamente", "{} label (click more labels to show any of them)": "Rótulo {} (clique em mais rótulos para mostrar qualquer um deles)", ", {} star{}": ", {} estrela{}", @@ -246,7 +246,7 @@ "Create the keyword “{name}”": "Criar a palavra-chave “{name}”", "new, inside {parent}": "nova, dentro de {parent}", "Keywords of {n} selected photos": "Palavras-chave de {n} fotos selecionadas", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "“{name}” removida de {n} fotos. Editar → Desfazer a traz de volta.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "“{name}” removida de {n} fotos. Editar → Desfazer a traz de volta.", "1 task is still running: {names}. Quitting stops it.": "1 tarefa ainda está em andamento: {names}. Sair a interrompe.", "{n} tasks are still running: {names}. Quitting stops them.": "{n} tarefas ainda estão em andamento: {names}. Sair as interrompe.", "{what} merge cancelled": "{what} mesclagem cancelada", @@ -266,7 +266,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Excluir {n} predefinição(ões) de efeito?{:.0} Não é possível desfazer.", "Effect: {name}": "Efeito: {name}", "Exported {} effect preset{}": "Predefinições de efeito exportadas: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "{e} efeito(s) de máscara importado(s){:.0} (Máscaras → Efeito)", + "Imported {e} mask effect{} (Masking → Effect)": "{e} efeito(s) de máscara importado(s){:.0} (Máscaras → Efeito)", "Update “{name}” with Current Settings": "Atualizar “{name}” com as configurações atuais", "{n} preset{}": "{n} predefinição(ões){:.0}", "{name} opened in the other editor": "{name} aberto no outro editor", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index e84fb7615b..6776423451 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1200,7 +1200,7 @@ "Remove from survey": "Remover da inspeção", "Remove location info": "Remover informações de local", "Remove shortcut": "Remover atalho", - "Remove this face box (undo with Edit ▸ Undo)": "Remover esta caixa de rosto (desfaça com Editar → Desfazer)", + "Remove this face box (undo with Edit → Undo)": "Remover esta caixa de rosto (desfaça com Editar → Desfazer)", "Remove this filter": "Remover este filtro", "Remove this group": "Remover este grupo", "Remove this rule": "Remover esta regra", @@ -1253,7 +1253,7 @@ "Revert": "Reverter", "Review": "Revisão", "Review Import": "Revisar importação", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Clique com o botão direito em uma foto → Definir como foto de referência, depois Exibir → Exibição de referência (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Clique com o botão direito em uma foto → Definir como foto de referência, depois Exibir → Exibição de referência (Shift+R)", "Right-click a preset to delete it": "Clique com o botão direito em uma predefinição para excluí-la", "Rights Usage Terms": "Termos de uso dos direitos", "Rotate": "Girar", @@ -2154,7 +2154,7 @@ "Same folder as original photo": "Mesma pasta da foto original", "Tidying the thumbnail cache": "Organizando o cache de miniaturas", "Reset all edits (Cmd+Shift+R)": "Redefinir todas as edições (Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Álbuns inteligentes se atualizam sozinhos: altere as regras ou use Foto → Excluir foto", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Álbuns inteligentes se atualizam sozinhos: altere as regras ou use Foto → Excluir foto", "LightCraft stopped": "O LightCraft parou", "Focus Point": "Ponto de foco", "Zoom to Focus Point": "Zoom no ponto de foco", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 76b7af4276..48f3ce0ff6 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -27,7 +27,7 @@ "Added {what} to {name}": "{what}: добавлено в {name}", "Adding photos… {} of {}": "Добавление фото… {} из {}", "All {n} selected photos move by the same amount.": "Все выбранные фото ({n}) сдвигаются на одно и то же значение.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Уже в библиотеке, в «Недавно удалённых»: выбрано фото: {}{:.0} · щёлкните правой кнопкой → Восстановить или Удалить навсегда, чтобы импортировать заново", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Уже в библиотеке, в «Недавно удалённых»: выбрано фото: {}{:.0} · щёлкните правой кнопкой → Восстановить или Удалить навсегда, чтобы импортировать заново", "Already in the library: {} photo{} selected in All Photos": "Уже в библиотеке: выбрано фото в разделе «Все фото»: {}{:.0}", "Auto ({})": "Авто ({})", "Auto Import: added {} photo{}": "Автоимпорт: добавлено фото: {}{:.0}", @@ -75,7 +75,7 @@ "Imported {n} point curve preset{}": "Импортировано пресетов точечной кривой: {n}{:.0}", "Imported {n} preset{}": "Импортировано пресетов: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Импортировано пресетов: {n}{:.0}, не читается файлов: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Импортировано профилей: {profiles}{:.0} (Обозреватель профилей → их группы)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Импортировано профилей: {profiles}{:.0} (Обозреватель профилей → их группы)", "Imported {} photo{}": "Импортировано фото: {}{:.0}", "Insert at the cursor (also written {})": "Вставить в позицию курсора (также пишется как {})", "Label Set: {name}": "Набор меток: {name}", @@ -169,7 +169,7 @@ "{n} photo{} match · updates automatically as photos change": "Подходящих фото: {n}{:.0} · обновляется автоматически при изменении фото", "{n} photo{} now · updates automatically as photos change": "Сейчас фото: {n}{:.0} · обновляется автоматически при изменении фото", "{n} selected photos · {pages} pages": "Выбрано фото: {n} · страниц: {pages}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Похожих фото: {n}{:.0} · Вид → Сбросить фильтры, чтобы увидеть все", + "{n} similar photo{} · View → Clear Filters to see all": "Похожих фото: {n}{:.0} · Вид → Сбросить фильтры, чтобы увидеть все", "{pid} (missing)": "{pid} (отсутствует)", "{sel_n} selected · {counted}": "Выбрано: {sel_n} · {counted}", "{stage}… {:.0}%": "{stage}… {:.0}%", @@ -242,7 +242,7 @@ "Create the keyword “{name}”": "Создать ключевое слово «{name}»", "new, inside {parent}": "новое, внутри {parent}", "Keywords of {n} selected photos": "Ключевые слова выбранных фото: {n}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "«{name}» убрано с фото: {n}. Правка → Отменить вернёт его.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "«{name}» убрано с фото: {n}. Правка → Отменить вернёт его.", "1 task is still running: {names}. Quitting stops it.": "Ещё выполняется задача: {names}. Выход прервёт её.", "{n} tasks are still running: {names}. Quitting stops them.": "Ещё выполняется задач: {n} — {names}. Выход прервёт их.", "{what} merge cancelled": "{what}: слияние отменено", @@ -262,7 +262,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Удалить пресеты эффектов ({n})?{:.0} Это нельзя отменить.", "Effect: {name}": "Эффект: {name}", "Exported {} effect preset{}": "Экспортировано пресетов эффектов: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Импортировано эффектов маски: {e}{:.0} (Маски → Эффект)", + "Imported {e} mask effect{} (Masking → Effect)": "Импортировано эффектов маски: {e}{:.0} (Маски → Эффект)", "Update “{name}” with Current Settings": "Обновить «{name}» текущими настройками", "{n} preset{}": "Пресетов: {n}{:.0}", "{name} opened in the other editor": "{name} открыт в другом редакторе", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 306804df04..b0ca6b2b9b 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -1040,7 +1040,7 @@ "Retouch": "Ретушь", "Revert": "Вернуть", "Review Import": "Проверить импорт", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Щёлкните фото правой кнопкой → Назначить эталонным фото, затем Вид → Режим эталона (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Щёлкните фото правой кнопкой → Назначить эталонным фото, затем Вид → Режим эталона (Shift+R)", "Right-click a preset to delete it": "Щёлкните пресет правой кнопкой, чтобы удалить его", "Rights Usage Terms": "Условия использования прав", "Rotate": "Повернуть", @@ -1975,7 +1975,7 @@ "Remove a filter above, or choose Clear all": "Уберите фильтр выше или выберите «Очистить всё»", "Remove from Library…": "Убрать из библиотеки…", "Remove from Target Album": "Убрать из целевого альбома", - "Remove this face box (undo with Edit ▸ Undo)": "Удалить эту рамку лица (отмена: Правка → Отменить)", + "Remove this face box (undo with Edit → Undo)": "Удалить эту рамку лица (отмена: Правка → Отменить)", "Rename Component": "Переименовать компонент", "Rename Folder… and Move Folder To… (Local) can be undone and redone (issue #97): the folder moves back on disk with": "Переименование папки… и перемещение папки в… («Локальное») можно отменить и повторить (проблема #97): папка возвращается на диске вместе с", "Rename Photos never overwrites another photo when only the letter case changes (issue #95): on case-sensitive": "Переименование фото никогда не перезаписывает другое фото, когда меняется только регистр букв (проблема #95): на томах с учётом регистра", @@ -2307,7 +2307,7 @@ "Same folder as original photo": "Та же папка, что и у оригинала", "Tidying the thumbnail cache": "Упорядочивание кэша миниатюр", "Reset all edits (Cmd+Shift+R)": "Сбросить все правки (Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Смарт-альбомы обновляются сами: измените их правила или выберите Фото → Удалить фото", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Смарт-альбомы обновляются сами: измените их правила или выберите Фото → Удалить фото", "LightCraft stopped": "LightCraft остановился", "Focus Point": "Точка фокусировки", "Zoom to Focus Point": "Увеличить по точке фокусировки", diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 9a71a0288c..dfc3b4779a 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -39,7 +39,7 @@ "Added “{keyword}” to {n} photo{}": "Lade till ”{keyword}” på {n} foto{}", "Adding photos… {} of {}": "Lägger till foton… {} av {}", "All {n} selected photos move by the same amount.": "Alla {n} markerade foton flyttas lika mycket.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Finns redan i biblioteket, i Nyligen raderade: {} foto{} markerade · högerklicka → Återställ, eller Radera permanent för att importera på nytt", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Finns redan i biblioteket, i Nyligen raderade: {} foto{} markerade · högerklicka → Återställ, eller Radera permanent för att importera på nytt", "Already in the library: {} photo{} selected in All Photos": "Finns redan i biblioteket: {} foto{} markerade i Alla foton", "Applied {name}": "Tillämpade {name}", "Apply to “{mask}” on Selected Photos": "Använd på ”{mask}” i markerade foton", @@ -91,12 +91,12 @@ "Import cancelled · {} photo{} added": "Importen avbröts · {} foto{} tillagda", "Import failed: {e}": "Importen misslyckades: {e}", "Import warnings ({n}):\n{warnings}": "Importvarningar ({n}):\n{warnings}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Importerade {e} maskeffekt{} (Maskering → Effekt)", + "Imported {e} mask effect{} (Masking → Effect)": "Importerade {e} maskeffekt{} (Maskering → Effekt)", "Imported {name}": "Importerade {name}", "Imported {n} point curve preset{}": "Importerade {n} punktkurvförinställning{}", "Imported {n} preset{}": "Importerade {n} förinställning{}", "Imported {n} preset{}, {f} file{} not readable": "Importerade {n} förinställning{}, {f} fil{} kunde inte läsas", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Importerade {profiles} profil{} (Profilbläddrare → deras grupper)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Importerade {profiles} profil{} (Profilbläddrare → deras grupper)", "Imported {} photo{}": "Importerade {} foto{}", "In line for AI Denoise ({ahead} ahead)…": "I kö för AI-brusreducering ({ahead} före)…", "Insert at the cursor (also written {})": "Infoga vid textmarkören (skrivs även {})", @@ -153,7 +153,7 @@ "Remove “{}” from Favorites": "Ta bort ”{}” från Favoriter", "Removed from {}": "Borttaget från {}", "Removed {what} from {name}": "Tog bort {what} från {name}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Tog bort ”{name}” från {n} foton. Redigera → Ångra lägger tillbaka det.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Tog bort ”{name}” från {n} foton. Redigera → Ångra lägger tillbaka det.", "Rename {n} Photos…": "Byt namn på {n} foton…", "Rename “{name}”": "Byt namn på ”{name}”", "Renames {n} face{} across the library. The files are not changed.": "Byter namn på {n} ansikte{} i hela biblioteket. Filerna ändras inte.", @@ -241,7 +241,7 @@ "{n} photo{} now · updates automatically as photos change": "{n} foto{} just nu · uppdateras automatiskt när fotona ändras", "{n} preset{}": "{n} förinställning{}", "{n} raws can now be developed from their raw data": "{n} raw-filer kan nu framkallas från sina rådata", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} likartade foto{} · Visa → Rensa filter för att se alla", + "{n} similar photo{} · View → Clear Filters to see all": "{n} likartade foto{} · Visa → Rensa filter för att se alla", "{n} tasks are still running: {names}. Quitting stops them.": "{n} uppgifter körs fortfarande: {names}. Om du avslutar stoppas de.", "{n} {noun}": "{n} {noun}", "{pct} %": "{pct} %", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 66e69b7ba5..2e65108cdf 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -1546,7 +1546,7 @@ "Photo Merge": "Fotosammanfogning", "photo waiting": "foto väntar", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Foto → Redigera i externt program (⇧⌘E) renderar en 16-bitars TIFF-kopia, staplar den med originalet och öppnar den här (ett appnamn på macOS, en programsökväg på andra system).", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Redigera i → Redigera i PhotoCraft (⇧⌘E, eller högerklicka på ett foto) renderar en kopia med dina ändringar, staplar den med originalet och öppnar den i PhotoCraft. Spara där så uppdateras kopian här. Som PSD sparar PhotoCraft direkt tillbaka till den. Lämna platsen tom om du inte använder en portabel kopia.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Redigera i → Redigera i PhotoCraft (⇧⌘E, eller högerklicka på ett foto) renderar en kopia med dina ändringar, staplar den med originalet och öppnar den i PhotoCraft. Spara där så uppdateras kopian här. Som PSD sparar PhotoCraft direkt tillbaka till den. Lämna platsen tom om du inte använder en portabel kopia.", "PhotoCraft": "PhotoCraft", "Photos": "Foton", "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "Foton visas genom bildskärmens ICC-profil, så att färgerna blir rätt på kalibrerade skärmar och skärmar med brett färgomfång, och vyn Detalj använder skärmens hela färgomfång. Histogrammet, förhandsgranskningscacharna och exporter påverkas inte.", @@ -1757,7 +1757,7 @@ "Remove missing photos from the library": "Ta bort saknade foton från biblioteket", "Remove region": "Ta bort region", "Remove shortcut": "Ta bort kortkommando", - "Remove this face box (undo with Edit ▸ Undo)": "Ta bort den här ansiktsrutan (ångra med Redigera → Ångra)", + "Remove this face box (undo with Edit → Undo)": "Ta bort den här ansiktsrutan (ångra med Redigera → Ångra)", "Remove this filter": "Ta bort det här filtret", "Remove this group": "Ta bort den här gruppen", "Remove this rule": "Ta bort den här regeln", @@ -1826,7 +1826,7 @@ "Review": "Granskning", "Review Import": "Granska import", "Right": "Höger", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Högerklicka på ett foto → Ange som referensfoto, sedan Visa → Referensvy (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Högerklicka på ett foto → Ange som referensfoto, sedan Visa → Referensvy (Shift+R)", "Right-click a preset to delete it": "Högerklicka på en förinställning för att radera den", "Rights Usage Terms": "Villkor för användningsrätt", "Rotate": "Rotera", @@ -2044,7 +2044,7 @@ "Smart Album Rule Fields": "Regelfält för smarta album", "smart album value|No": "Nej", "smart album value|Yes": "Ja", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Smarta album uppdateras automatiskt: ändra deras regler eller använd Foto → Radera foto", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Smarta album uppdateras automatiskt: ändra deras regler eller använd Foto → Radera foto", "Smart albums with a rule editor: match all / any / none, nested groups, 26 fields.": "Smarta album med regelredigerare: matcha alla/någon/ingen, nästlade grupper, 26 fält.", "Smart preview available": "Smart förhandsgranskning tillgänglig", "Smart Preview Status": "Status för smart förhandsgranskning", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 36022ac1a2..f937619cc6 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -25,7 +25,7 @@ "Added {what} to {name}": "{what}: додано до {name}", "Adding photos… {} of {}": "Додавання фото… {} з {}", "All {n} selected photos move by the same amount.": "Усі вибрані фото ({n}) зміщуються на однакове значення.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Уже в бібліотеці, у нещодавно видалених: вибрано фото: {}{:.0} · права кнопка → Відновити або Видалити назавжди, щоб імпортувати заново", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Уже в бібліотеці, у нещодавно видалених: вибрано фото: {}{:.0} · права кнопка → Відновити або Видалити назавжди, щоб імпортувати заново", "Already in the library: {} photo{} selected in All Photos": "Уже в бібліотеці: вибрано фото в усіх фото: {}{:.0}", "Auto ({})": "Автоматично ({})", "Auto Import: added {} photo{}": "Автоімпорт: додано фото: {}{:.0}", @@ -65,7 +65,7 @@ "Imported {n} point curve preset{}": "Імпортовано наборів налаштувань точкової кривої: {n}{:.0}", "Imported {n} preset{}": "Імпортовано наборів налаштувань: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Імпортовано наборів налаштувань: {n}{:.0}, файлів не читається: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Імпортовано профілів: {profiles}{:.0} (Оглядач профілів → їхні групи)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Імпортовано профілів: {profiles}{:.0} (Оглядач профілів → їхні групи)", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "Не вдалося записати XMP-файли {n} фото (папка недоступна?). LightCraft продовжує спроби.", "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "Профіль XMP «{profile}» не застосовано до {path}; кольори можуть відрізнятися від Lightroom.", "Lightroom geometry was not preserved for {path}; {mode} will be recalculated.": "Геометрію Lightroom для {path} не збережено; режим {mode} буде перераховано.", @@ -195,7 +195,7 @@ "… and {more} more": "… і ще {more}", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft ще не може декодувати цей варіант RAW ({}). Ви редагуєте вбудований JPEG-перегляд камери, який уже містить її стиль зображення (наприклад, монохромний) і баланс білого.", "Filtered: {label}": "Відфільтровано: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Подібних фото: {n}{:.0} · Вигляд → Скинути фільтри, щоб побачити всі", + "{n} similar photo{} · View → Clear Filters to see all": "Подібних фото: {n}{:.0} · Вигляд → Скинути фільтри, щоб побачити всі", "Moved; {} photo(s) relinked": "Переміщено; повторно пов’язано фото: {}", "{} label (click more labels to show any of them)": "Мітка «{}» (клацніть інші мітки, щоб показати фото з будь-якою з них)", ", {} star{}": ", зірок: {}{:.0}", @@ -242,7 +242,7 @@ "Create the keyword “{name}”": "Створити ключове слово «{name}»", "new, inside {parent}": "нове, всередині {parent}", "Keywords of {n} selected photos": "Ключові слова вибраних фото: {n}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "«{name}» вилучено з фото: {n}. Редагування → Скасувати поверне його.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "«{name}» вилучено з фото: {n}. Редагування → Скасувати поверне його.", "1 task is still running: {names}. Quitting stops it.": "1 завдання ще виконується: {names}. Вихід зупинить його.", "{n} tasks are still running: {names}. Quitting stops them.": "Ще виконуються завдання ({n}): {names}. Вихід зупинить їх.", "{what} merge cancelled": "Об’єднання {what} скасовано", @@ -262,7 +262,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Видалити пресети ефектів ({n})?{:.0} Це не можна скасувати.", "Effect: {name}": "Ефект: {name}", "Exported {} effect preset{}": "Експортовано пресетів ефектів: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Імпортовано ефектів маски: {e}{:.0} (Маски → Ефект)", + "Imported {e} mask effect{} (Masking → Effect)": "Імпортовано ефектів маски: {e}{:.0} (Маски → Ефект)", "Update “{name}” with Current Settings": "Оновити «{name}» поточними налаштуваннями", "{n} preset{}": "Пресетів: {n}{:.0}", "{name} opened in the other editor": "{name} відкрито в іншому редакторі", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index ee694ed4fe..02b7d11442 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -930,7 +930,7 @@ "Remove a filter above, or choose Clear all": "Видаліть фільтр вище або виберіть «Очистити все»", "Remove from Target Album": "Вилучити з цільового альбому", "Remove shortcut": "Видалити скорочення", - "Remove this face box (undo with Edit ▸ Undo)": "Видалити цю рамку обличчя (скасувати через Редагування → Скасувати)", + "Remove this face box (undo with Edit → Undo)": "Видалити цю рамку обличчя (скасувати через Редагування → Скасувати)", "Rename Component": "Перейменувати компонент", "Rename Folder": "Перейменувати теку", "Rename Mask": "Перейменувати маску", @@ -1273,7 +1273,7 @@ "Restore them": "Відновити їх", "Retouch": "Ретушування", "Review Import": "Перевірити імпорт", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Клацніть фото правою кнопкою → Задати як еталонне фото, потім Вигляд → Еталонне подання (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Клацніть фото правою кнопкою → Задати як еталонне фото, потім Вигляд → Еталонне подання (Shift+R)", "Right-click a preset to delete it": "Клацніть набір налаштувань правою кнопкою, щоб видалити його", "Rights Usage Terms": "Умови використання прав", "Rotate Crop": "Обертати кадрування", @@ -2312,7 +2312,7 @@ "Same folder as original photo": "Та сама папка, що й оригінал", "Tidying the thumbnail cache": "Упорядкування кешу мініатюр", "Reset all edits (Cmd+Shift+R)": "Скинути всі зміни (Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Розумні альбоми оновлюються самі: змініть їхні правила або виберіть Фото → Видалити фото", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Розумні альбоми оновлюються самі: змініть їхні правила або виберіть Фото → Видалити фото", "LightCraft stopped": "LightCraft зупинився", "Focus Point": "Точка фокусування", "Zoom to Focus Point": "Збільшити до точки фокусування", diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index d5e28bff06..8ac30e33d7 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -39,7 +39,7 @@ "Added “{keyword}” to {n} photo{}": "Đã thêm «{keyword}» vào {n} ảnh{:.0}", "Adding photos… {} of {}": "Đang thêm ảnh… {} / {}", "All {n} selected photos move by the same amount.": "Tất cả {n} ảnh đã chọn dịch chuyển cùng một lượng.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Đã có trong thư viện, trong Đã xóa gần đây: đã chọn {} ảnh{:.0} · nhấp chuột phải → Khôi phục, hoặc Xóa vĩnh viễn để nhập lại", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Đã có trong thư viện, trong Đã xóa gần đây: đã chọn {} ảnh{:.0} · nhấp chuột phải → Khôi phục, hoặc Xóa vĩnh viễn để nhập lại", "Already in the library: {} photo{} selected in All Photos": "Đã có trong thư viện: đã chọn {} ảnh{:.0} trong Tất cả ảnh", "Already in “{}”": "Already in “{}”", "Applied {name}": "Applied {name}", @@ -93,12 +93,12 @@ "Import cancelled · {} photo{} added": "Đã hủy nhập · đã thêm {} ảnh{:.0}", "Import failed: {e}": "Nhập thất bại: {e}", "Import warnings ({n}):\n{warnings}": "Cảnh báo khi nhập ({n}):\n{warnings}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Imported {e} mask effect{} (Masking → Effect)", + "Imported {e} mask effect{} (Masking → Effect)": "Imported {e} mask effect{} (Masking → Effect)", "Imported {name}": "Imported {name}", "Imported {n} point curve preset{}": "Đã nhập {n} thiết lập sẵn đường cong điểm{:.0}", "Imported {n} preset{}": "Đã nhập {n} thiết lập sẵn{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Đã nhập {n} thiết lập sẵn{:.0}, {f} tệp{:.0} không đọc được", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Đã nhập {profiles} hồ sơ{:.0} (Trình duyệt hồ sơ → nhóm của chúng)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Đã nhập {profiles} hồ sơ{:.0} (Trình duyệt hồ sơ → nhóm của chúng)", "Imported {} photo{}": "Đã nhập {} ảnh{:.0}", "In line for AI Denoise ({ahead} ahead)…": "Đang xếp hàng Khử nhiễu AI (trước bạn: {ahead})…", "Insert at the cursor (also written {})": "Chèn tại con trỏ (cũng ghi là {})", @@ -157,7 +157,7 @@ "Remove “{}” from Favorites": "Gỡ «{}» khỏi Yêu thích", "Removed from {}": "Đã gỡ khỏi {}", "Removed {what} from {name}": "Đã gỡ {what} khỏi {name}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", "Rename {n} Photos…": "Đổi tên {n} ảnh…", "Rename “{name}”": "Đổi tên «{name}»", "Renames {n} face{} across the library. The files are not changed.": "Renames {n} face{} across the library. The files are not changed.", @@ -249,7 +249,7 @@ "{n} preset{}": "{n} preset{}", "{n} raws can now be developed from their raw data": "{n} raws can now be developed from their raw data", "{n} selected photos · {pages} pages": "{n} selected photos · {pages} pages", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} ảnh tương tự{:.0} · Xem → Xóa bộ lọc để thấy tất cả", + "{n} similar photo{} · View → Clear Filters to see all": "{n} ảnh tương tự{:.0} · Xem → Xóa bộ lọc để thấy tất cả", "{n} tasks are still running: {names}. Quitting stops them.": "Còn {n} tác vụ đang chạy: {names}. Thoát sẽ dừng chúng.", "{n} {noun}": "{noun}: {n}", "{pct} %": "{pct} %", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index e4fb8feb81..43080922b4 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -1291,7 +1291,7 @@ "Photo Grid (G)": "Lưới ảnh (G)", "Photo Merge": "Ghép ảnh", "Photo menu. The filmstrip has the photo context menu too. Adding a file again that is in Recently Deleted no": "Menu Ảnh. Dải phim cũng có menu ngữ cảnh ảnh. Thêm lại tệp đang ở Đã xóa gần đây không", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Ảnh → Chỉnh trong → Chỉnh trong PhotoCraft (⇧⌘E, hoặc nhấp phải ảnh) kết xuất bản sao kèm chỉnh sửa, xếp chồng với bản gốc và mở trong PhotoCraft. Lưu ở đó thì bản sao cập nhật tại đây. Dạng PSD, PhotoCraft lưu thẳng lại. Để trống vị trí trừ khi dùng bản portable.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Ảnh → Chỉnh trong → Chỉnh trong PhotoCraft (⇧⌘E, hoặc nhấp phải ảnh) kết xuất bản sao kèm chỉnh sửa, xếp chồng với bản gốc và mở trong PhotoCraft. Lưu ở đó thì bản sao cập nhật tại đây. Dạng PSD, PhotoCraft lưu thẳng lại. Để trống vị trí trừ khi dùng bản portable.", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Ảnh → Chỉnh trong trình soạn ngoài (⇧⌘E) kết xuất bản sao TIFF 16 bit, xếp chồng với bản gốc và mở tại đây (tên app trên macOS, đường dẫn chương trình ở nơi khác).", "PhotoCraft": "PhotoCraft", "Photos": "Ảnh", @@ -1484,7 +1484,7 @@ "Remove location info": "Xóa thông tin vị trí", "Remove missing photos from the library": "Gỡ ảnh mất khỏi thư viện", "Remove shortcut": "Gỡ lối tắt", - "Remove this face box (undo with Edit ▸ Undo)": "Gỡ khung khuôn mặt này (hoàn tác bằng Chỉnh sửa → Hoàn tác)", + "Remove this face box (undo with Edit → Undo)": "Gỡ khung khuôn mặt này (hoàn tác bằng Chỉnh sửa → Hoàn tác)", "Remove this filter": "Gỡ bộ lọc này", "Remove this group": "Gỡ nhóm này", "Remove this rule": "Gỡ quy tắc này", @@ -1543,7 +1543,7 @@ "Revert": "Hoàn tác", "Review": "Xem lại", "Review Import": "Xem lại nhập", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Nhấp phải ảnh → Đặt làm ảnh tham chiếu, rồi Xem → Chế độ tham chiếu (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Nhấp phải ảnh → Đặt làm ảnh tham chiếu, rồi Xem → Chế độ tham chiếu (Shift+R)", "Right-click a preset to delete it": "Nhấp phải thiết lập sẵn để xóa", "Rights Usage Terms": "Điều khoản sử dụng quyền", "Rotate": "Xoay", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 7406c39b86..9950129cef 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -120,7 +120,7 @@ "Adding photos… {} of {}": "正在添加照片… 第 {0} 张,共 {1} 张", " ({} in Recently Deleted)": "(其中 {0} 张在“最近删除”中)", "Already in the library: {} photo{} selected in All Photos": "已在图库中:已在“所有照片”中选择 {0} 张照片{1:.0}", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "已在图库的“最近删除”中:已选择 {0} 张照片{1:.0} · 右键单击 → 恢复,或永久删除后重新导入", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "已在图库的“最近删除”中:已选择 {0} 张照片{1:.0} · 右键单击 → 恢复,或永久删除后重新导入", "Auto ({})": "自动({})", "Build 1:1 Previews ({scope})": "生成 1:1 预览({scope})", "Build Smart Previews ({scope})": "生成智能预览({scope})", @@ -169,7 +169,7 @@ "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "未保留 {path} 的 Lightroom 几何信息;不支持保存的引导 Upright 变换。", "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "未保留 {path} 的 Lightroom 几何信息;不支持保存的 Upright 变换。", "XMP adjustments were not imported for {path}: {fields}.": "未导入 {path} 的 XMP 调整:{fields}。", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "已导入 {profiles} 个配置文件{0:.0}(配置文件浏览器 → 各自的分组)", + "Imported {profiles} profile{} (Profile browser → their groups)": "已导入 {profiles} 个配置文件{0:.0}(配置文件浏览器 → 各自的分组)", "Insert at the cursor (also written {})": "在光标处插入(也可写作 {0})", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0。字体:{0}(OFL)。图标:原创。", "Painting “{k}”: click photos to add or remove it · Esc stops": "正在应用“{k}”:单击照片以添加或移除 · 按 Esc 停止", @@ -199,7 +199,7 @@ "{} — show their photos": "{0} — 显示其照片", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft 暂时无法解码这种 RAW 变体({0})。你正在编辑相机内嵌的 JPEG 预览,其中已包含相机的照片风格(如单色)和白平衡。", "Filtered: {label}": "已筛选:{label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} 张相似照片{0:.0} · 选择“视图 → 清除过滤器”可查看全部", + "{n} similar photo{} · View → Clear Filters to see all": "{n} 张相似照片{0:.0} · 选择“视图 → 清除过滤器”可查看全部", "Moved; {} photo(s) relinked": "已移动;已重新链接 {0} 张照片", "{} label (click more labels to show any of them)": "{0}标签(单击更多标签可显示符合其中任一标签的照片)", ", {} star{}": ",{0} 星{1:.0}", @@ -246,7 +246,7 @@ "Create the keyword “{name}”": "创建关键字“{name}”", "new, inside {parent}": "新关键字,位于 {parent} 内", "Keywords of {n} selected photos": "所选 {n} 张照片的关键字", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "已从 {n} 张照片中移除“{name}”。编辑 → 撤销可恢复。", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "已从 {n} 张照片中移除“{name}”。编辑 → 撤销可恢复。", "1 task is still running: {names}. Quitting stops it.": "仍有 1 个任务在运行:{names}。退出将停止它。", "{n} tasks are still running: {names}. Quitting stops them.": "仍有 {n} 个任务在运行:{names}。退出将停止它们。", "{what} merge cancelled": "已取消 {what} 合并", @@ -266,7 +266,7 @@ "Delete {n} effect preset{}? This can't be undone.": "删除 {n} 个效果预设?{:.0}此操作无法撤销。", "Effect: {name}": "效果:{name}", "Exported {} effect preset{}": "已导出 {} 个效果预设{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "已导入 {e} 个蒙版效果{:.0}(蒙版 → 效果)", + "Imported {e} mask effect{} (Masking → Effect)": "已导入 {e} 个蒙版效果{:.0}(蒙版 → 效果)", "Update “{name}” with Current Settings": "用当前设置更新“{name}”", "{n} preset{}": "{n} 个预设{:.0}", "{name} opened in the other editor": "已在其他编辑器中打开 {name}", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 270af8a625..237bdd9604 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -662,7 +662,7 @@ "Remove a filter above, or choose Clear all": "请移除上方的某个筛选条件,或选择“全部清除”", "Remove from Target Album": "从目标相册中移除", "Remove shortcut": "移除快捷键", - "Remove this face box (undo with Edit ▸ Undo)": "移除此人脸框(可通过“编辑 → 撤销”恢复)", + "Remove this face box (undo with Edit → Undo)": "移除此人脸框(可通过“编辑 → 撤销”恢复)", "Rename Component": "重命名组件", "Reorder Masks": "重新排序蒙版", "Reset All": "全部重置", @@ -1237,7 +1237,7 @@ "Revert": "恢复", "Review": "审阅", "Review Import": "查看导入内容", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "右键单击照片 » 设为参考照片,然后选择“视图 → 参考视图”(Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "右键单击照片 » 设为参考照片,然后选择“视图 → 参考视图”(Shift+R)", "Right-click a preset to delete it": "右键单击预设即可将其删除", "Rights Usage Terms": "使用条款", "Rotate": "旋转", @@ -2147,7 +2147,7 @@ "Same folder as original photo": "与原始照片相同的文件夹", "Tidying the thumbnail cache": "正在整理缩略图缓存", "Reset all edits (Cmd+Shift+R)": "重置所有编辑 (Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "智能相册会自动更新:请更改其规则,或使用“照片 → 删除照片”", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "智能相册会自动更新:请更改其规则,或使用“照片 → 删除照片”", "LightCraft stopped": "LightCraft 已停止", "Zoom to Focus Point": "缩放至对焦点", "Focus": "对焦", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index d5c4eb279a..85b252c516 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -141,7 +141,7 @@ "… and {more} more": "…以及另外 {more} 個", " ({} in Recently Deleted)": "(其中 {} 張在「最近刪除」中)", "Already in the library: {} photo{} selected in All Photos": "已在照片庫中:已在「所有照片」中選取 {} 張照片{:.0}", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "已在照片庫的「最近刪除」中:已選取 {} 張照片{:.0} · 按右鍵 → 還原,或永久刪除後重新匯入", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "已在照片庫的「最近刪除」中:已選取 {} 張照片{:.0} · 按右鍵 → 還原,或永久刪除後重新匯入", "Remove “{name}” and its {count} photo{} from the library?": "要將「{name}」及其 {count} 張照片從照片庫移除嗎?{:.0}", " ({unsure} with several look-alike files: use Locate)": "(其中 {unsure} 張有多個相似檔案:請使用「尋找」)", " · {:.0}% clipped": " · {:.0}% 剪裁", @@ -169,7 +169,7 @@ "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "未保留 {path} 的 Lightroom 幾何資料;不支援儲存的引導 Upright 轉換。", "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "未保留 {path} 的 Lightroom 幾何資料;不支援儲存的 Upright 轉換。", "XMP adjustments were not imported for {path}: {fields}.": "未匯入 {path} 的 XMP 調整:{fields}。", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "已匯入 {profiles} 個描述檔{:.0}(描述檔瀏覽器 → 各自的群組)", + "Imported {profiles} profile{} (Profile browser → their groups)": "已匯入 {profiles} 個描述檔{:.0}(描述檔瀏覽器 → 各自的群組)", "Insert at the cursor (also written {})": "在游標處插入(也可寫成 {})", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0。字型:{}(OFL)。圖示:原創。", "Painting “{k}”: click photos to add or remove it · Esc stops": "正在套用「{k}」:點擊照片即可加入或移除 · 按 Esc 停止", @@ -199,7 +199,7 @@ "{} — show their photos": "{} — 顯示其照片", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft 目前還無法解碼這種 RAW 變體({})。你正在編輯相機內嵌的 JPEG 預覽,其中已包含相機的相片風格(例如單色)與白平衡。", "Filtered: {label}": "已篩選:{label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} 張相似照片{:.0} · 選擇「檢視 → 清除篩選條件」可查看全部", + "{n} similar photo{} · View → Clear Filters to see all": "{n} 張相似照片{:.0} · 選擇「檢視 → 清除篩選條件」可查看全部", "Moved; {} photo(s) relinked": "已移動;已重新連結 {} 張照片", "{} label (click more labels to show any of them)": "{}標籤(點擊更多標籤可顯示符合其中任一標籤的照片)", ", {} star{}": ",{} 顆星{:.0}", @@ -246,7 +246,7 @@ "Create the keyword “{name}”": "建立關鍵字「{name}」", "new, inside {parent}": "新關鍵字,位於 {parent} 內", "Keywords of {n} selected photos": "選取的 {n} 張照片的關鍵字", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "已從 {n} 張照片移除「{name}」。編輯 → 復原可恢復。", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "已從 {n} 張照片移除「{name}」。編輯 → 復原可恢復。", "1 task is still running: {names}. Quitting stops it.": "仍有 1 個工作在執行:{names}。結束將停止它。", "{n} tasks are still running: {names}. Quitting stops them.": "仍有 {n} 個工作在執行:{names}。結束將停止它們。", "{what} merge cancelled": "已取消{what}合併", @@ -266,7 +266,7 @@ "Delete {n} effect preset{}? This can't be undone.": "刪除 {n} 個效果預設集?{:.0}此動作無法復原。", "Effect: {name}": "效果:{name}", "Exported {} effect preset{}": "已匯出 {} 個效果預設集{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "已匯入 {e} 個遮色片效果{:.0}(遮色片 → 效果)", + "Imported {e} mask effect{} (Masking → Effect)": "已匯入 {e} 個遮色片效果{:.0}(遮色片 → 效果)", "Update “{name}” with Current Settings": "以目前設定更新「{name}」", "{n} preset{}": "{n} 個預設集{:.0}", "{name} opened in the other editor": "已在其他編輯器中開啟 {name}", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 0408e23ec8..44bab3b57e 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -663,7 +663,7 @@ "Remove a filter above, or choose Clear all": "請移除上方的某個篩選條件,或選擇「全部清除」", "Remove from Target Album": "從目標相簿移除", "Remove shortcut": "移除快速鍵", - "Remove this face box (undo with Edit ▸ Undo)": "移除此臉部框(可用「編輯 → 復原」還原)", + "Remove this face box (undo with Edit → Undo)": "移除此臉部框(可用「編輯 → 復原」還原)", "Rename Component": "重新命名元件", "Reorder Masks": "重新排序遮色片", "Reset All": "全部重設", @@ -1238,7 +1238,7 @@ "Revert": "回復至上次儲存", "Review": "審閱", "Review Import": "檢視匯入", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "在照片上按右鍵 → 設為參考照片,再選擇「檢視 → 參考檢視」(Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "在照片上按右鍵 → 設為參考照片,再選擇「檢視 → 參考檢視」(Shift+R)", "Right-click a preset to delete it": "在預設集上按右鍵即可刪除", "Rights Usage Terms": "使用權利條款", "Rotate": "旋轉", @@ -2115,7 +2115,7 @@ "Same folder as original photo": "與原始照片相同的資料夾", "Tidying the thumbnail cache": "正在整理縮圖快取", "Reset all edits (Cmd+Shift+R)": "重設所有編輯(Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "智慧型相簿會自動更新:請變更其規則,或使用「照片 → 刪除照片」", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "智慧型相簿會自動更新:請變更其規則,或使用「照片 → 刪除照片」", "LightCraft stopped": "LightCraft 已停止", "Focus Point": "對焦點", "Zoom to Focus Point": "縮放至對焦點", diff --git a/crates/ui-egui/src/dialogs/import/task.rs b/crates/ui-egui/src/dialogs/import/task.rs index bcef55b11e..fa7869dcd8 100644 --- a/crates/ui-egui/src/dialogs/import/task.rs +++ b/crates/ui-egui/src/dialogs/import/task.rs @@ -534,7 +534,7 @@ fn show_existing(app: &mut LightcraftApp, ctx: &egui::Context, existing: &[u64]) crate::i18n::tr_format!("Already in the library: {} photo{} selected in All Photos", n, plural) } else { crate::i18n::tr_format!( - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh", n, plural ) diff --git a/crates/ui-egui/src/dialogs/rules_editor/rules_move.rs b/crates/ui-egui/src/dialogs/rules_editor/rules_move.rs index de5ccc2efd..8506a28267 100644 --- a/crates/ui-egui/src/dialogs/rules_editor/rules_move.rs +++ b/crates/ui-egui/src/dialogs/rules_editor/rules_move.rs @@ -154,7 +154,7 @@ pub fn move_node(rs: &mut RuleSet, from: &[usize], dest: &[usize]) -> Option chain.len() && dest.starts_with(&chain)) && list_at(&next, &chain).is_some_and(|l| l.rules.is_empty()) { + while !(chain.is_empty() || dest.len() > chain.len() && dest.starts_with(&chain)) && list_at(&next, &chain).is_some_and(|l| l.rules.is_empty()) { remove_at(&mut next, &chain)?; if !shift_after_removal(&mut dest, &chain) { return None; diff --git a/crates/ui-egui/src/dialogs/settings/general.rs b/crates/ui-egui/src/dialogs/settings/general.rs index 21b94f150f..ff7559fc93 100644 --- a/crates/ui-egui/src/dialogs/settings/general.rs +++ b/crates/ui-egui/src/dialogs/settings/general.rs @@ -87,7 +87,7 @@ pub(super) fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens ui, t, crate::i18n::tr( - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.", ), ); row(ui, t, crate::i18n::tr("Other editor"), |ui| { diff --git a/crates/ui-egui/src/dialogs/settings/libraries.rs b/crates/ui-egui/src/dialogs/settings/libraries.rs index 389f79f11d..12884910bd 100644 --- a/crates/ui-egui/src/dialogs/settings/libraries.rs +++ b/crates/ui-egui/src/dialogs/settings/libraries.rs @@ -160,7 +160,7 @@ pub fn new_library(app: &mut LightcraftApp, p: &Value) -> Result None => location, }; if lightcraft_engine::library::is_library(&dir) { - return Err(format!("{}: there is a library here already; open it with File ▸ Open Library…", dir.display())); + return Err(format!("{}: there is a library here already; open it with File → Open Library…", dir.display())); } if dir.is_file() { return Err(format!("{}: is a file; a library is a folder", dir.display())); diff --git a/crates/ui-egui/src/menus/files.rs b/crates/ui-egui/src/menus/files.rs index 52389d9305..adbb2d8c59 100644 --- a/crates/ui-egui/src/menus/files.rs +++ b/crates/ui-egui/src/menus/files.rs @@ -8,7 +8,7 @@ pub fn delete_in_album(app: &mut LightcraftApp, ctx: &egui::Context) -> bool { let lightcraft_engine::LibrarySource::Album(aid) = app.session.source else { return false }; let Some(album) = app.session.catalog.album(aid) else { return false }; if album.is_smart() { - app.toast(ctx, crate::i18n::tr("Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo")); + app.toast(ctx, crate::i18n::tr("Smart albums update automatically: change their rules, or use Photo → Delete Photo")); return true; } if app.session.selected().is_empty() { diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index c550ff0d4d..204d38dedc 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1678,7 +1678,7 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option 0 { parts.push(crate::i18n::tr_format!( - "Imported {profiles} profile{} (Profile browser ▸ their groups)", + "Imported {profiles} profile{} (Profile browser → their groups)", if profiles == 1 { "" } else { "s" }, profiles = profiles )); diff --git a/crates/ui-egui/src/panels/compare.rs b/crates/ui-egui/src/panels/compare.rs index 829500da47..b137cdfb05 100644 --- a/crates/ui-egui/src/panels/compare.rs +++ b/crates/ui-egui/src/panels/compare.rs @@ -601,7 +601,7 @@ pub fn show_reference(app: &mut LightcraftApp, ui: &mut egui::Ui) { let canvas = area_and_filmstrip(app, ui); let reference = app.ui.reference.map(PhotoId).filter(|r| live(app, *r)); let (Some(r), Some(active)) = (reference, app.session.active()) else { - super::empty_message(ui, canvas, "No reference photo", "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)"); + super::empty_message(ui, canvas, "No reference photo", "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)"); return; }; let area = canvas.shrink(18.0); diff --git a/crates/ui-egui/src/panels/detail/masks.rs b/crates/ui-egui/src/panels/detail/masks.rs index 073de8aa27..e8fa1f21ca 100644 --- a/crates/ui-egui/src/panels/detail/masks.rs +++ b/crates/ui-egui/src/panels/detail/masks.rs @@ -113,7 +113,7 @@ pub(super) fn region_overlay( let cross = Stroke::new(1.4, if resp.hovered() { Color32::WHITE } else { Color32::from_gray(210) }); p.line_segment([c - vec2(m, m), c + vec2(m, m)], cross); p.line_segment([c - vec2(m, -m), c + vec2(m, -m)], cross); - if resp.on_hover_text(crate::i18n::tr("Remove this face box (undo with Edit ▸ Undo)")).clicked() { + if resp.on_hover_text(crate::i18n::tr("Remove this face box (undo with Edit → Undo)")).clicked() { edit = Some(RegionEdit::Remove(index)); } } diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index 262979cc5f..36c9ca342a 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -1250,7 +1250,7 @@ pub fn context_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { app.ui.view = crate::state::ViewMode::PhotoGrid; app.toast( ui.ctx(), - crate::i18n::tr_format!("{n} similar photo{} · View ▸ Clear Filters to see all", if n == 1 { "" } else { "s" }, n = n), + crate::i18n::tr_format!("{n} similar photo{} · View → Clear Filters to see all", if n == 1 { "" } else { "s" }, n = n), ); } Err(e) => app.toast(ui.ctx(), e), diff --git a/crates/ui-egui/src/panels/keywording.rs b/crates/ui-egui/src/panels/keywording.rs index 4861d4c6fa..53c69661d8 100644 --- a/crates/ui-egui/src/panels/keywording.rs +++ b/crates/ui-egui/src/panels/keywording.rs @@ -134,7 +134,7 @@ fn remove(app: &mut LightcraftApp, ctx: &egui::Context, chip: &Chip) { let name = chip.path.replace('|', " › "); app.toast_for( ctx, - crate::i18n::tr_format!("Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.", name = name, n = chip.have), + crate::i18n::tr_format!("Removed “{name}” from {n} photos. Edit → Undo puts it back.", name = name, n = chip.have), 6.0, ); } diff --git a/crates/ui-egui/src/panels/mask_effects.rs b/crates/ui-egui/src/panels/mask_effects.rs index 86f3796b9f..1ecdd6fd37 100644 --- a/crates/ui-egui/src/panels/mask_effects.rs +++ b/crates/ui-egui/src/panels/mask_effects.rs @@ -688,7 +688,7 @@ pub fn manage_body( pub fn import_toast(v: &Value) -> String { let rows: Vec<&Value> = v["effects"].as_array().or_else(|| v["imported"].as_array()).into_iter().flatten().collect(); let n = rows.len(); - let mut msg = crate::i18n::tr_format!("Imported {e} mask effect{} (Masking ▸ Effect)", if n == 1 { "" } else { "s" }, e = n); + let mut msg = crate::i18n::tr_format!("Imported {e} mask effect{} (Masking → Effect)", if n == 1 { "" } else { "s" }, e = n); let mut groups: Vec<&str> = rows.iter().filter_map(|r| r["group"].as_str()).filter(|g| !g.is_empty()).collect(); groups.sort_unstable(); groups.dedup(); From 8975b2efabdc8b7d22bb111c49ad5a395c897817 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Tue, 27 Oct 2026 08:22:49 +0100 Subject: [PATCH 03/63] LR-PROF-CAMERACOLOR: align CR3 calibration with resolved lens profiles --- crates/engine/src/camera_preview.rs | 6 +- crates/engine/src/camera_preview/colour.rs | 21 +- crates/engine/src/camera_preview/look_fit.rs | 14 +- crates/engine/src/camera_preview/mono.rs | 10 +- crates/engine/src/camera_preview/proxy.rs | 166 +++++++- crates/engine/src/camera_preview/tests.rs | 409 ++++++++++++++++++- crates/engine/src/camera_profiles.rs | 9 +- crates/engine/src/media/source.rs | 2 +- docs/camera-preview-colour.md | 13 +- docs/cr3-profile-alignment.md | 58 +++ docs/gaps.md | 5 +- docs/parity-checklist.md | 5 +- 12 files changed, 677 insertions(+), 41 deletions(-) create mode 100644 docs/cr3-profile-alignment.md diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index 1fc172548f..7e6544e8cd 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -50,7 +50,8 @@ use pairs::{ pub(crate) use proxy::LensGeometry; #[cfg(test)] use proxy::{ - Cr3Framing, MIN_PREVIEW_FRACTION, alignment, estimate_cr3_framing, into_lens_geometry, proxies, reference_at, sensor_proxy, structure_agrees, + Cr3Framing, MIN_PREVIEW_FRACTION, align_profile_geometry, alignment, estimate_cr3_framing, into_lens_geometry, proxies, reference_at, + resample_correspondence, sensor_proxy, structure_agrees, }; pub(crate) use proxy::{fit_profile, lens_geometry, profile_pairs}; #[cfg(test)] @@ -79,7 +80,8 @@ use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights}; /// a tone-only fallback for near-black scenes with too few colour pairs (#1587); DNG tone fitting uses a /// lens-corrected proxy when the file carries lens opcodes; validated A7CR distortion, including the lens data /// stored with each smart preview. -pub const LOOK_VERSION: u32 = 12; +/// 14: geometry-gated external lens and camera framing, including CR3, for JPEG correspondences. +pub const LOOK_VERSION: u32 = 14; #[derive(Clone, Debug)] pub(crate) struct CameraLook { diff --git a/crates/engine/src/camera_preview/colour.rs b/crates/engine/src/camera_preview/colour.rs index a33a5c7a57..318916ca1f 100644 --- a/crates/engine/src/camera_preview/colour.rs +++ b/crates/engine/src/camera_preview/colour.rs @@ -42,7 +42,8 @@ pub(crate) fn file_local_look(format: RawFormat) -> bool { /// as-shot white, the camera transform at it and the fitted look. /// `lens` is the file's own lens-correction warp ([`lens_geometry`], read before the caller removes it from /// `OpcodeList3`): the camera applied it to its JPEG, so the sensor proxy is warped the same way before pairing. -/// `embedded` is the file's embedded lens vignetting, for the DNG tone fit. +/// `embedded` is the resolved lens in the oriented default crop: geometry may align +/// CR3 calibration correspondences; vignetting is used by the DNG tone fit. pub(crate) fn starting_colour( raw: &mut RawImage, bytes: &[u8], @@ -51,13 +52,13 @@ pub(crate) fn starting_colour( ) -> (Xy, CameraTransform, Option) { let (xy, t, look) = starting_colour_with( raw, - |raw, t| fit_preview(raw, bytes, t, lens), - |raw, t| monochrome_look(raw, bytes, t, lens), + |raw, t| fit_preview(raw, bytes, t, lens, embedded), + |raw, t| monochrome_look(raw, bytes, t, lens, embedded), |raw, t| { if !file_local_look(raw.format) { return None; } - let (sensor, reference, clipped) = proxies(raw, bytes, t, PROXY, 0.0, lens)?; + let (sensor, reference, clipped) = proxies(raw, bytes, t, PROXY, 0.0, lens, embedded)?; fit_dark_tone(&sensor, &reference, &clipped) }, ); @@ -130,11 +131,21 @@ pub(crate) fn starting_colour_tags(raw: &mut RawImage, bytes: &[u8]) -> Option, +) -> Option { + let correction = correction.filter(|_| raw.format == RawFormat::Cr3); // the white the source shows, decided before `starting_colour` may fill in measured matrices let scale = crate::files::WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata); let white = scale.dng_white(&raw.color, lightcraft_raw::color::as_shot_white_xy(raw)); // (a merge frame arrives without its lens warp: `lightcraft_merge` removes it before calling) - let (_, t, look) = starting_colour(raw, bytes, None, None); + let (_, t, look) = starting_colour(raw, bytes, None, correction); dng_colour(&raw.color, &white, &t, look.as_ref()) } diff --git a/crates/engine/src/camera_preview/look_fit.rs b/crates/engine/src/camera_preview/look_fit.rs index c1588093b3..d23fee3844 100644 --- a/crates/engine/src/camera_preview/look_fit.rs +++ b/crates/engine/src/camera_preview/look_fit.rs @@ -6,11 +6,17 @@ use super::tone::{HighlightCheck, highlights}; use super::*; /// The look fitted to the file's camera JPEG, and whether that JPEG is black and white ([`monochrome`]). -pub(crate) fn fit_preview(raw: &RawImage, bytes: &[u8], transform: &CameraTransform, lens: Option<&LensGeometry>) -> (Option, bool) { +pub(crate) fn fit_preview( + raw: &RawImage, + bytes: &[u8], + transform: &CameraTransform, + lens: Option<&LensGeometry>, + correction: Option<&lightcraft_develop::EmbeddedLens>, +) -> (Option, bool) { if !transform.matrix_is_fallback || !file_local_look(raw.format) { return (None, false); } - let Some((sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, 0.0, lens) else { return (None, false) }; + let Some((sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, 0.0, lens, correction) else { return (None, false) }; let black_and_white = monochrome(&reference); // A camera profile pooled from many photos knows colours this photo shows too little of; // try its colour first and fit tone/chroma per photo (picture styles vary). @@ -207,7 +213,9 @@ pub(super) fn fit_dng_tone( } None }; - let Some((mut sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, MIN_PREVIEW_FRACTION, None) else { return refuse("preview") }; + let Some((mut sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, MIN_PREVIEW_FRACTION, None, None) else { + return refuse("preview"); + }; // As the loader renders it: the profile's tables around the baseline exposure. let xy = lightcraft_raw::color::as_shot_white_xy(raw); if let Some(tables) = lightcraft_raw::profile::ProfileTables::new(&raw.color.profile, lightcraft_raw::color::illuminant_weight(&raw.color, xy)) { diff --git a/crates/engine/src/camera_preview/mono.rs b/crates/engine/src/camera_preview/mono.rs index cfac90c340..30099c7b08 100644 --- a/crates/engine/src/camera_preview/mono.rs +++ b/crates/engine/src/camera_preview/mono.rs @@ -34,11 +34,17 @@ pub(super) fn monochrome(reference: &Rgb32f) -> bool { /// `transform` is the colour the photo gets otherwise (the spectral matrices or the fallback's); the look keeps it and /// adds the tone curve alone ([`fit_tone_only_with`]), as [`fit_look_with`] tries the photo's own colour after a profile's. The /// chroma curve stays neutral: the JPEG has no colourfulness to learn. -pub(super) fn monochrome_look(raw: &RawImage, bytes: &[u8], transform: &CameraTransform, lens: Option<&LensGeometry>) -> Option { +pub(super) fn monochrome_look( + raw: &RawImage, + bytes: &[u8], + transform: &CameraTransform, + lens: Option<&LensGeometry>, + correction: Option<&lightcraft_develop::EmbeddedLens>, +) -> Option { if !file_local_look(raw.format) { return None; } - let (sensor, reference, clipped) = proxies(raw, bytes, transform, PROXY, 0.0, lens)?; + let (sensor, reference, clipped) = proxies(raw, bytes, transform, PROXY, 0.0, lens, correction)?; if !monochrome(&reference) { return None; } diff --git a/crates/engine/src/camera_preview/proxy.rs b/crates/engine/src/camera_preview/proxy.rs index 81f170a87d..f511375676 100644 --- a/crates/engine/src/camera_preview/proxy.rs +++ b/crates/engine/src/camera_preview/proxy.rs @@ -90,6 +90,7 @@ pub(super) fn proxies( size: usize, min_fraction: f64, lens: Option<&LensGeometry>, + correction: Option<&lightcraft_develop::EmbeddedLens>, ) -> Option<(Rgb32f, Rgb32f, Vec)> { let edge = (2 * size).max(384) as u32; let decoded = crate::files::decode_raw_preview( @@ -139,9 +140,14 @@ pub(super) fn proxies( clipped = clipped.into_oriented(raw.orientation); reference = reference.into_oriented(raw.orientation); sensor.map_in_place(to_working); - // Canon's JPEG can be cropped differently from the sensor. Estimate only that common - // framing from edge directions, independently of the subsequent colour fit. - (sensor, clipped) = align_cr3_framing(sensor, clipped, &reference); + // Judge the external warp against the established CR3 framing fallback, not + // against unregistered sensor pixels. This preserves an already better fit. + let (fallback, fallback_mask) = align_cr3_framing(sensor.clone(), clipped.clone(), &reference); + let proposed = + correction.filter(|correction| transform.matrix_is_fallback && lens.is_none() && correction.warp.is_some()).and_then(|correction| { + align_profile_geometry_against(&sensor, &clipped, &reference, correction, lightcraft_geom::Orientation::Normal, Some(&fallback)) + }); + (sensor, clipped) = proposed.unwrap_or((fallback, fallback_mask)); } let mut sensor = fit(&sensor, size, size, Filter::Box); let mut reference_small = reference_at(&reference, &sensor); @@ -180,7 +186,7 @@ pub(super) struct Cr3Framing { } impl Cr3Framing { - const IDENTITY: Self = Self { scale: 1.0, offset: [0.0; 2] }; + pub(super) const IDENTITY: Self = Self { scale: 1.0, offset: [0.0; 2] }; pub(super) fn source(self, x: f32, y: f32, w: usize, h: usize) -> (f32, f32) { let (w, h) = (w as f32, h as f32); @@ -193,6 +199,33 @@ impl Cr3Framing { /// A separate third of the edges must confirm a substantial improvement and a close match. /// A weak, flat or unrelated preview leaves the sensor framing unchanged. pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Option { + estimate_framing_against(sensor, reference, sensor, None) +} + +#[cfg(test)] +thread_local! { + static LAST_GEOMETRY_SCORES: std::cell::Cell> = const { std::cell::Cell::new(None) }; + static LAST_FRAMED_SCORES: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +pub(super) fn geometry_gate_scores() -> Option<[f64; 4]> { + LAST_GEOMETRY_SCORES.get() +} + +#[cfg(test)] +pub(super) fn geometry_framed_scores() -> Option<[f64; 4]> { + LAST_FRAMED_SCORES.get() +} + +/// Judge a proposed lens warp and bounded framing against the original sensor on fixed +/// training and independent held-out edges. Lens-only correction may be sufficient. +fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: &Rgb32f, framed: Option<&Rgb32f>) -> Option { + #[cfg(test)] + { + LAST_GEOMETRY_SCORES.set(None); + LAST_FRAMED_SCORES.set(None); + } if sensor.width.checked_mul(sensor.height)? != sensor.data.len() || reference.width.checked_mul(reference.height)? != reference.data.len() { return None; } @@ -205,7 +238,17 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio if (reference.width, reference.height) != (w, h) { return None; } + let original = fit(original, PROXY, PROXY, Filter::Box); + if (original.width, original.height) != (w, h) || original.data.len() != sensor.data.len() { + return None; + } + let framed = framed.map(|image| fit(image, PROXY, PROXY, Filter::Box)); + if framed.as_ref().is_some_and(|image| (image.width, image.height) != (w, h) || image.data.len() != sensor.data.len()) { + return None; + } + let mut framed_gradients = framed.as_ref().map(|_| Rgb32f::new(w, h)); let mut gradients = Rgb32f::new(w, h); + let mut original_gradients = Rgb32f::new(w, h); let mut edges = Vec::new(); for y in 1..h - 1 { for x in 1..w - 1 { @@ -217,6 +260,12 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio }; let d = derivative(&sensor); gradients.data[y * w + x] = [d[0], d[1], 0.0]; + let d = derivative(&original); + original_gradients.data[y * w + x] = [d[0], d[1], 0.0]; + if let (Some(image), Some(gradients)) = (&framed, &mut framed_gradients) { + let d = derivative(image); + gradients.data[y * w + x] = [d[0], d[1], 0.0]; + } let d = derivative(&reference); let magnitude = d[0].hypot(d[1]); let value = luminance_2020(reference.data[y * w + x]); @@ -228,7 +277,7 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio if edges.len() < 192 { return None; } - let score = |framing: Cr3Framing, held_out: bool| -> Option { + let score = |gradients: &Rgb32f, framing: Cr3Framing, held_out: bool, support: Option<(&Rgb32f, Cr3Framing)>| -> Option { let (mut agreement, mut weight, mut valid, mut total) = (0.0, 0.0, 0usize, 0usize); for &(x, y, target, magnitude, holdout) in &edges { if holdout != held_out { @@ -244,6 +293,19 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio if !length.is_finite() || length <= 0.01 { continue; } + // Comparing against framed CR3 fallback uses exactly the same valid + // edges on both sides, including the same reference weights. + if let Some((other, map)) = support { + let (ox, oy) = map.source(x, y, w, h); + if ox < 1.5 || oy < 1.5 || ox > w as f32 - 1.5 || oy > h as f32 - 1.5 { + continue; + } + let p = other.sample_bilinear(ox, oy); + let length = p[0].hypot(p[1]); + if !length.is_finite() || length <= 0.01 { + continue; + } + } let k = f64::from(magnitude.min(0.25)); agreement += k * f64::from((sample[0] * target[0] + sample[1] * target[1]) / (length * magnitude)); weight += k; @@ -251,15 +313,15 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio } (valid >= 64 && valid * 5 >= total * 4 && weight > 0.0).then_some(agreement / weight) }; - let before = score(Cr3Framing::IDENTITY, false)?; - let mut best = (before, Cr3Framing::IDENTITY); + let before = score(&original_gradients, Cr3Framing::IDENTITY, false, None)?; + let mut best = (score(&gradients, Cr3Framing::IDENTITY, false, None).unwrap_or(-1.0), Cr3Framing::IDENTITY); // At most 10% zoom and two proxy pixels of translation; a coarse search followed by one // local refinement prevents unbounded optimisation on the photograph's contents. for s in -10..=10 { for tx in -4..=4 { for ty in -4..=4 { let framing = Cr3Framing { scale: 1.0 + s as f32 * 0.01, offset: [tx as f32 * 0.5 / w as f32, ty as f32 * 0.5 / h as f32] }; - if let Some(value) = score(framing, false) + if let Some(value) = score(&gradients, framing, false, None) && value > best.0 { best = (value, framing); @@ -278,7 +340,7 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio if !(0.9..=1.1).contains(&framing.scale) || framing.offset[0].abs() > 2.0 / w as f32 || framing.offset[1].abs() > 2.0 / h as f32 { continue; } - if let Some(value) = score(framing, false) + if let Some(value) = score(&gradients, framing, false, None) && value > best.0 { best = (value, framing); @@ -286,12 +348,25 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio } } } - let (held_before, held_after) = (score(Cr3Framing::IDENTITY, true)?, score(best.1, true)?); + let (held_before, held_after) = (score(&original_gradients, Cr3Framing::IDENTITY, true, None)?, score(&gradients, best.1, true, None)?); + #[cfg(test)] + LAST_GEOMETRY_SCORES.set(Some([before, best.0, held_before, held_after])); if best.0 < 0.9 || best.0 < before + 0.04 || held_after < 0.9 || held_after < held_before + 0.04 { return None; } + if let Some(framed) = &framed_gradients { + let before = score(framed, Cr3Framing::IDENTITY, false, Some((&gradients, best.1)))?; + let after = score(&gradients, best.1, false, Some((framed, Cr3Framing::IDENTITY)))?; + let held_before = score(framed, Cr3Framing::IDENTITY, true, Some((&gradients, best.1)))?; + let held_after = score(&gradients, best.1, true, Some((framed, Cr3Framing::IDENTITY)))?; + #[cfg(test)] + LAST_FRAMED_SCORES.set(Some([before, after, held_before, held_after])); + if after < before || held_after < held_before { + return None; + } + } if lightcraft_pipeline::profiling() { - eprintln!("[profile] CR3 JPEG framing {:?}, held-out edge agreement {held_before:.4} -> {held_after:.4}", best.1); + eprintln!("[profile] camera JPEG framing {:?}, held-out edge agreement {held_before:.4} -> {held_after:.4}", best.1); } Some(best.1) } @@ -311,15 +386,80 @@ fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rg (apply(&sensor), apply(&clipped)) } +/// Apply a shared source map to colour or a nonnegative clip mask. Invalid borders +/// stay NaN; any bilinear contribution from a clipped source stays positive. +pub(super) fn resample_correspondence(image: &Rgb32f, source: impl Fn(f64, f64) -> lightcraft_geom::Point) -> Rgb32f { + let (w, h) = (image.width, image.height); + let mut out = Rgb32f::new(w, h); + if w == 0 || h == 0 { + return out; + } + for (i, pixel) in out.data.iter_mut().enumerate() { + let p = source((i % w) as f64 + 0.5, (i / w) as f64 + 0.5); + *pixel = if p.x.is_finite() && p.y.is_finite() && p.x >= 0.5 && p.y >= 0.5 && p.x <= w as f64 - 0.5 && p.y <= h as f64 - 0.5 { + image.sample_bilinear(p.x as f32, p.y as f32) + } else { + [f32::NAN; 3] + }; + } + out +} + +/// Propose correspondence geometry only. A resolved lens describes the oriented +/// default crop; undo its orientation to match this un-oriented sensor proxy. +#[cfg(test)] +pub(super) fn align_profile_geometry( + sensor: &Rgb32f, + clipped: &Rgb32f, + reference: &Rgb32f, + correction: &lightcraft_develop::EmbeddedLens, + orientation: lightcraft_geom::Orientation, +) -> Option<(Rgb32f, Rgb32f)> { + align_profile_geometry_against(sensor, clipped, reference, correction, orientation, None) +} + +fn align_profile_geometry_against( + sensor: &Rgb32f, + clipped: &Rgb32f, + reference: &Rgb32f, + correction: &lightcraft_develop::EmbeddedLens, + orientation: lightcraft_geom::Orientation, + baseline: Option<&Rgb32f>, +) -> Option<(Rgb32f, Rgb32f)> { + if correction.warp.is_none() || (sensor.width, sensor.height) != (clipped.width, clipped.height) { + return None; + } + let (w, h) = (sensor.width as f64, sensor.height as f64); + let (ow, oh) = if orientation.swaps_axes() { (h, w) } else { (w, h) }; + let correction = lightcraft_pipeline::optics::reorient_lens(correction, orientation.inverse(), ow, oh); + let mut warp = lightcraft_pipeline::optics::Warp::identity(w, h); + warp.lens = Some(correction); + warp.lens_dist = 1.0; + let source = |x, y| warp.corrected_to_source(lightcraft_geom::Point::new(x, y), 1); + let candidate = resample_correspondence(sensor, source); + let framing = estimate_framing_against(&candidate, reference, sensor, baseline)?; + let mask = resample_correspondence(clipped, source); + let frame = |x: f64, y: f64| { + let (x, y) = framing.source(x as f32, y as f32, sensor.width, sensor.height); + lightcraft_geom::Point::new(f64::from(x), f64::from(y)) + }; + Some((resample_correspondence(&candidate, frame), resample_correspondence(&mask, frame))) +} + /// Colour training pairs of one raw for a camera profile: white-balanced camera RGB (with the /// baseline exposure) → its camera JPEG (linear Rec.2020). `None` for formats with their own /// colour matrices, other files or unusable previews. -pub(crate) fn profile_pairs(raw: &RawImage, bytes: &[u8], lens: Option<&LensGeometry>) -> Option> { +pub(crate) fn profile_pairs( + raw: &RawImage, + bytes: &[u8], + lens: Option<&LensGeometry>, + correction: Option<&lightcraft_develop::EmbeddedLens>, +) -> Option> { if !file_local_look(raw.format) || lightcraft_raw::color::has_matrix(&raw.color) { return None; } let transform = lightcraft_raw::color::camera_transform(raw, lightcraft_raw::color::as_shot_white_xy(raw)); - let (sensor, reference, clipped) = proxies(raw, bytes, &transform, PROFILE_PROXY, 0.0, lens)?; + let (sensor, reference, clipped) = proxies(raw, bytes, &transform, PROFILE_PROXY, 0.0, lens, correction)?; let to_camera = transform.matrix.inverse()?; // clipped sensor pixels don't record the scene's colour (see `fit_look`) let sensor = without_clipped(&sensor, &clipped).unwrap_or(sensor); diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index d8442589dc..2f582b0930 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -661,7 +661,7 @@ fn corpus_lens_corrected_jpegs_pair_with_the_warped_sensor() { raw.opcodes.list3.retain(|op| !op.is_lens_correction()); let t = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); let (Some((plain, reference, _)), Some((chosen, chosen_reference, _))) = - (proxies(&raw, &bytes, &t, PROXY, 0.0, None), proxies(&raw, &bytes, &t, PROXY, 0.0, Some(&lens))) + (proxies(&raw, &bytes, &t, PROXY, 0.0, None, None), proxies(&raw, &bytes, &t, PROXY, 0.0, Some(&lens), None)) else { continue; }; @@ -928,7 +928,7 @@ fn corpus_cr3_gets_a_framing_aligned_camera_look() { assert_eq!(raw.format, RawFormat::Cr3); assert_eq!(raw.info().developed_size(), (6000, 4000)); let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); - let look = fit_preview(&raw, &bytes, &transform, None).0; + let look = fit_preview(&raw, &bytes, &transform, None, None).0; eprintln!("R100 guarded colour fit accepted: {}", look.is_some()); assert!(look.is_some(), "this R100 corpus photo has enough matching colour after camera-framing alignment"); let (_, info) = crate::files::load_bytes(&bytes, 400).unwrap(); @@ -965,7 +965,7 @@ fn corpus_uses_the_bundled_profile(file: &str, model: &str) { let lens = lens_geometry(&raw.opcodes.list3); raw.opcodes.list3.retain(|op| !op.is_lens_correction()); let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); - let look = fit_preview(&raw, &bytes, &transform, lens.as_ref()).0.expect("fit accepted"); + let look = fit_preview(&raw, &bytes, &transform, lens.as_ref(), None).0.expect("fit accepted"); let expected = bundled.matrix().mul(&transform.matrix.inverse().unwrap()); for (row, want) in look.matrix.0.iter().zip(expected.0) { for (got, want) in row.iter().zip(want) { @@ -1346,9 +1346,9 @@ fn corpus_arw_with_dro_is_lowered_to_the_dro_off_tone() { let mut raw = lightcraft_raw::decode(&bytes).unwrap(); raw.opcodes.list3.retain(|op| !op.is_lens_correction()); let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); - let look = fit_preview(&raw, &bytes, &transform, None).0.expect("a camera look"); + let look = fit_preview(&raw, &bytes, &transform, None, None).0.expect("a camera look"); // the look fitted to the JPEG, as before this change - let (sensor, reference, clipped) = proxies(&raw, &bytes, &transform, PROXY, 0.0, None).unwrap(); + let (sensor, reference, clipped) = proxies(&raw, &bytes, &transform, PROXY, 0.0, None, None).unwrap(); let profile = raw.metadata.model.as_deref().and_then(crate::camera_profiles::get); let colour = profile.as_ref().and_then(|p| Some((p.matrix().mul(&transform.matrix.inverse()?), p.hue_sat.clone()))); let fitted = fit_look(&sensor, &reference, &clipped, colour).unwrap(); @@ -2033,12 +2033,12 @@ fn monochrome_look_reads_the_files_black_and_white_jpeg() { tiff }; let t = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); - let look = monochrome_look(&raw, &file([1.0; 3]), &t, None).expect("a tone curve from the black-and-white JPEG"); + let look = monochrome_look(&raw, &file([1.0; 3]), &t, None, None).expect("a tone curve from the black-and-white JPEG"); assert!(look.matrix == Mat3::IDENTITY && look.hue_sat.is_none(), "on the transform's colour"); let curve = ToneMap::camera(&look.tone, 0.0, 0.0, 0.0); let mid = curve.apply(0.25); assert!((mid - (1.0 - (-0.75f32).exp())).abs() < 0.05, "the camera's curve at 0.25: {mid}"); - assert!(monochrome_look(&raw, &file([1.0, 0.9, 0.8]), &t, None).is_none(), "a tinted JPEG is not black and white"); + assert!(monochrome_look(&raw, &file([1.0, 0.9, 0.8]), &t, None, None).is_none(), "a tinted JPEG is not black and white"); } /// The black-and-white fit has the partial look's checks: a JPEG of another picture, or one the default curve @@ -2427,3 +2427,398 @@ fn a_narrow_black_and_white_curve_that_darkens_the_bright_areas_is_refused() { assert!(sky > 0.8, "an accepted curve must not darken what the camera renders at 0.93: {sky}"); } } + +fn profile_geometry_scene(w: usize, h: usize) -> Rgb32f { + let mut sensor = Rgb32f::new(w, h); + for (i, p) in sensor.data.iter_mut().enumerate() { + let (x, y) = ((i % w) as f32 * 192.0 / w as f32, (i / w) as f32 * 128.0 / h as f32); + let v = 0.35 + 0.13 * (x * 0.15 + y * 0.22).sin() + 0.1 * (x * 0.33 - y * 0.14).sin() + 0.07 * (x * 0.09 - y * 0.31).cos(); + *p = [v * (0.9 + 0.15 * (y * 0.023).sin()), v, v * (0.9 + 0.15 * (x * 0.019).cos())]; + } + sensor +} + +fn synthetic_profile_lens() -> lightcraft_develop::EmbeddedLens { + lightcraft_develop::EmbeddedLens { + warp: Some(lightcraft_develop::EmbeddedWarp { + planes: [[1.04, -0.24, 0.08, 0.0, 0.0, 0.0]; 3], + center: lightcraft_geom::Point::new(0.48, 0.53), + radius: 0.61, + }), + ..Default::default() + } +} + +fn profile_geometry_target(sensor: &Rgb32f, lens: &lightcraft_develop::EmbeddedLens, framing: Cr3Framing) -> Rgb32f { + let mut warp = lightcraft_pipeline::optics::Warp::identity(sensor.width as f64, sensor.height as f64); + warp.lens = Some(*lens); + warp.lens_dist = 1.0; + let warped = resample_correspondence(sensor, |x, y| warp.corrected_to_source(lightcraft_geom::Point::new(x, y), 1)); + resample_correspondence(&warped, |x, y| { + let (x, y) = framing.source(x as f32, y as f32, sensor.width, sensor.height); + lightcraft_geom::Point::new(f64::from(x), f64::from(y)) + }) +} + +fn geometry_rms(a: &Rgb32f, b: &Rgb32f) -> f64 { + let mut error = 0.0; + let mut n = 0; + for (a, b) in a.data.iter().zip(&b.data) { + for (&a, &b) in a.iter().zip(b) { + if a.is_finite() && b.is_finite() { + error += f64::from(a - b).powi(2); + n += 1; + } + } + } + assert!(n > 256); + (error / f64::from(n)).sqrt() +} + +#[test] +fn external_profile_geometry_aligns_lens_and_framing_before_colour() { + let sensor = profile_geometry_scene(384, 256); + let lens = synthetic_profile_lens(); + let expected = profile_geometry_target(&sensor, &lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }); + let mut jpeg = expected.clone(); + jpeg.map_in_place(|p| p.map(|v| v.powf(0.7))); + let mask = Rgb32f::new(sensor.width, sensor.height); + let (aligned, _) = align_profile_geometry(&sensor, &mask, &jpeg, &lens, lightcraft_geom::Orientation::Normal) + .expect("lens and bounded framing pass independent geometry gates"); + assert!(geometry_rms(&aligned, &expected) < 0.008, "the training sensor is correctly registered despite a nonlinear camera tone"); + assert!(geometry_rms(&sensor, &expected) > 0.05, "synthetic mismatch is material"); +} + +#[test] +fn external_profile_geometry_accepts_lens_only_and_rejects_unrelated_or_already_aligned() { + let sensor = profile_geometry_scene(384, 256); + let lens = synthetic_profile_lens(); + let expected = profile_geometry_target(&sensor, &lens, Cr3Framing::IDENTITY); + let mask = Rgb32f::new(sensor.width, sensor.height); + let (aligned, _) = align_profile_geometry(&sensor, &mask, &expected, &lens, lightcraft_geom::Orientation::Normal) + .expect("lens alone aligns; no improvement over its own framing is required"); + assert!(geometry_rms(&aligned, &expected) < 0.001); + assert!( + align_profile_geometry(&sensor, &mask, &sensor, &lens, lightcraft_geom::Orientation::Normal).is_none(), + "already aligned original is preserved" + ); + let mut unrelated = sensor.clone(); + for (i, p) in unrelated.data.iter_mut().enumerate() { + let (x, y) = ((i % sensor.width) as f32, (i / sensor.width) as f32); + *p = [0.35 + 0.13 * (x * 0.41 - y * 0.07).sin() + 0.1 * (x * 0.04 + y * 0.39).cos(); 3]; + } + assert!(align_profile_geometry(&sensor, &mask, &unrelated, &lens, lightcraft_geom::Orientation::Normal).is_none()); + unrelated.data.fill([0.2; 3]); + assert!(align_profile_geometry(&sensor, &mask, &unrelated, &lens, lightcraft_geom::Orientation::Normal).is_none()); + assert!( + align_profile_geometry(&sensor, &mask, &expected, &Default::default(), lightcraft_geom::Orientation::Normal).is_none(), + "no geometric profile leaves the established path alone" + ); +} + +#[test] +fn external_profile_geometry_preserves_oriented_default_crop_and_resolution() { + let lens = synthetic_profile_lens(); + for (w, h) in [(192, 128), (384, 256)] { + // This is the developed default crop: no active-area offset is applied a second time. + let sensor = profile_geometry_scene(w, h); + let target = profile_geometry_target(&sensor, &lens, Cr3Framing::IDENTITY); + let mask = Rgb32f::new(w, h); + for exif in 1..=8 { + let orientation = lightcraft_geom::Orientation::from_exif(exif); + let oriented = lightcraft_pipeline::optics::reorient_lens(&lens, orientation, w as f64, h as f64); + let (aligned, _) = + align_profile_geometry(&sensor, &mask, &target, &oriented, orientation).expect("oriented resolved lens maps back to the sensor crop"); + assert!(geometry_rms(&aligned, &target) < 0.001, "orientation {exif}, {w}x{h}"); + } + } +} + +#[test] +fn cr3_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() { + use lightcraft_raw::{BlackLevel, RawData, Rect}; + let (w, h) = (416, 288); + let scene = profile_geometry_scene(w, h); + let mut raw = raw_of(RawFormat::Cr3, "Synthetic", "Uncalibrated", Default::default()); + raw.width = w; + raw.height = h; + raw.cpp = 3; + raw.data = RawData::F32(scene.data.iter().flatten().copied().collect()); + raw.black = BlackLevel::uniform(0.0); + raw.white = vec![1.0]; + raw.active_area = Rect::new(0, 0, w, h); + raw.crop = Rect::new(16, 16, 384, 256); + raw.linearized = true; + raw.wb_multipliers = Some([1.0; 3]); + let transform = lightcraft_raw::color::camera_transform(&raw, D65); + assert!(transform.matrix_is_fallback); + let mut sensor = sensor_proxy(&raw, 2, 384).unwrap(); + assert_eq!((sensor.width, sensor.height), (384, 256)); + sensor.map_in_place(|p| transform.matrix.apply_f32(p)); + let lens = synthetic_profile_lens(); + let mut target = profile_geometry_target(&sensor, &lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }); + target.map_in_place(|p| p.map(|v| v.powf(0.7))); + let to_srgb = lightcraft_color::SRGB.from_xyz().mul(&REC2020.to_xyz()); + let srgb = |v: f32| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + let pixels: Vec = target.data.iter().flat_map(|p| to_srgb.apply_f32(*p).map(|v| (srgb(v).clamp(0.0, 1.0) * 255.0).round() as u8)).collect(); + let image = lightcraft_codecs::EncodeImage::new(384, 256, 3, lightcraft_codecs::Samples::U8(&pixels)); + let jpeg = lightcraft_codecs::encode_jpeg(&image, 98, lightcraft_codecs::ChromaSubsampling::S444, &Default::default()).unwrap(); + let mut file = b"II*\0\x08\0\0\0\x02\0".to_vec(); + for (tag, value) in [(0x0201u16, 38u32), (0x0202, jpeg.len() as u32)] { + file.extend(tag.to_le_bytes()); + file.extend(4u16.to_le_bytes()); + file.extend(1u32.to_le_bytes()); + file.extend(value.to_le_bytes()); + } + file.extend(0u32.to_le_bytes()); + file.extend(jpeg); + // This follow-up is CR3-only: even a coherent lens proposal cannot change + // correspondences for other formats or leak into their pooled profile pairs. + for format in [RawFormat::Cr2, RawFormat::Arw, RawFormat::Nef, RawFormat::Raf, RawFormat::Rw2, RawFormat::Dng] { + let mut other = raw.clone(); + other.format = format; + let plain = proxies(&other, &file, &transform, PROXY, 0.0, None, None).unwrap(); + let proposed = proxies(&other, &file, &transform, PROXY, 0.0, None, Some(&lens)).unwrap(); + let bits = |image: &Rgb32f| image.data.iter().flatten().map(|v| v.to_bits()).collect::>(); + assert_eq!(bits(&plain.0), bits(&proposed.0), "{format:?}: sensor stays identical"); + assert_eq!(bits(&plain.1), bits(&proposed.1), "{format:?}: JPEG stays identical"); + assert_eq!(plain.2, proposed.2, "{format:?}: clipping stays identical"); + assert_eq!( + profile_pairs(&other, &file, None, None), + profile_pairs(&other, &file, None, Some(&lens)), + "{format:?}: pooled pairs stay identical" + ); + let mut plain_tags = other.clone(); + let mut proposed_tags = other; + assert_eq!( + super::colour::starting_colour_tags_with_correction(&mut plain_tags, &file, None), + super::colour::starting_colour_tags_with_correction(&mut proposed_tags, &file, Some(&lens)), + "{format:?}: merge/DNG colour tags stay identical" + ); + } + let (plain, reference, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, None).unwrap(); + let (mut aligned, _, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, Some(&lens)).unwrap(); + let mut plain_render = plain; + plain_render.map_in_place(|p| p.map(|v| v.powf(0.7))); + aligned.map_in_place(|p| p.map(|v| v.powf(0.7))); + assert!( + geometry_rms(&aligned, &reference) < geometry_rms(&plain_render, &reference) * 0.3, + "the file-local route uses the resolved crop-relative correction" + ); + let error = |pairs: Vec<([f64; 3], [f64; 3])>| { + let sum: f64 = pairs.iter().map(|(x, y)| transform.matrix.apply(*x).iter().zip(y).map(|(x, y)| (x.powf(0.7) - y).powi(2)).sum::()).sum(); + sum / pairs.len() as f64 + }; + let before = error(profile_pairs(&raw, &file, None, None).unwrap()); + let after = error(profile_pairs(&raw, &file, None, Some(&lens)).unwrap()); + assert!(after < before * 0.1, "pooled colour calibration uses the same geometry: {before} -> {after}"); + // Merge / DNG conversion must encode the same calibrated colour as opening the RAW. + let mut opened = raw.clone(); + let (_, t, look) = starting_colour(&mut opened, &file, None, Some(&lens)); + assert!(look.is_some(), "the synthetic corrected preview supplies a camera look"); + let scale = crate::files::WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata); + let white = scale.dng_white(&raw.color, lightcraft_raw::color::as_shot_white_xy(&raw)); + let expected_tags = dng_colour(&raw.color, &white, &t, look.as_ref()).unwrap(); + let tags = super::colour::starting_colour_tags_with_correction(&mut raw, &file, Some(&lens)).unwrap(); + assert_eq!(tags, expected_tags, "DNG tags use the resolved correspondence geometry too"); +} + +#[test] +fn correspondence_mask_keeps_every_contributing_clipped_sample_and_invalid_border() { + let mut mask = Rgb32f::new(8, 6); + mask.data[2 * 8 + 3] = [1.0; 3]; + let result = resample_correspondence(&mask, |x, y| lightcraft_geom::Point::new(x + 0.75, y + 0.5)); + assert!(result.data[8 + 2][0] > 0.0 && result.data[8 + 3][0] > 0.0); + assert!(result.data[2 * 8 + 2][0] > 0.0 && result.data[2 * 8 + 3][0] > 0.0); + assert_eq!(result.data[0][0], 0.0); + assert!(result.data[7][0].is_nan() && result.data[5 * 8][0].is_nan()); + // The final box reduction retains fractional positive masks as clipped too. + let reduced = resize(&result, 4, 3, Filter::Box); + assert!(reduced.data.iter().any(|p| p[0] > 0.0)); +} + +#[test] +fn cr3_profile_geometry_shares_orientation_and_applies_white_balance_once() { + use lightcraft_raw::{BlackLevel, RawData, Rect}; + let (w, h) = (416, 288); + let scene = profile_geometry_scene(w, h); + let mut raw = raw_of(RawFormat::Cr3, "Synthetic", "Uncalibrated", Default::default()); + raw.width = w; + raw.height = h; + raw.cpp = 3; + raw.data = RawData::F32(scene.data.iter().flatten().copied().collect()); + raw.black = BlackLevel::uniform(0.0); + raw.white = vec![1.0]; + raw.active_area = Rect::new(0, 0, w, h); + raw.crop = Rect::new(16, 16, 384, 256); + raw.linearized = true; + raw.wb_multipliers = Some([1.25, 1.0, 0.8]); + let transform = lightcraft_raw::color::camera_transform(&raw, D65); + assert!(transform.matrix_is_fallback); + let mut sensor = sensor_proxy(&raw, 2, 384).unwrap(); + assert_eq!((sensor.width, sensor.height), (384, 256)); + sensor.map_in_place(|p| { + transform.matrix.apply_f32(std::array::from_fn(|i| p[i] * transform.wb[i] * 2f32.powf(transform.baseline_exposure as f32))) + }); + let lens = synthetic_profile_lens(); + let mut target = profile_geometry_target(&sensor, &lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }); + target.map_in_place(|p| p.map(|v| v.powf(0.7))); + let to_srgb = lightcraft_color::SRGB.from_xyz().mul(&REC2020.to_xyz()); + let srgb = |v: f32| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + let pixels: Vec = target.data.iter().flat_map(|p| to_srgb.apply_f32(*p).map(|v| (srgb(v).clamp(0.0, 1.0) * 255.0).round() as u8)).collect(); + let image = lightcraft_codecs::EncodeImage::new(384, 256, 3, lightcraft_codecs::Samples::U8(&pixels)); + let jpeg = lightcraft_codecs::encode_jpeg(&image, 98, lightcraft_codecs::ChromaSubsampling::S444, &Default::default()).unwrap(); + let mut file = b"II*\0\x08\0\0\0\x02\0".to_vec(); + for (tag, value) in [(0x0201u16, 38u32), (0x0202, jpeg.len() as u32)] { + file.extend(tag.to_le_bytes()); + file.extend(4u16.to_le_bytes()); + file.extend(1u32.to_le_bytes()); + file.extend(value.to_le_bytes()); + } + file.extend(0u32.to_le_bytes()); + file.extend(jpeg); + for exif in 1..=8 { + let orientation = lightcraft_geom::Orientation::from_exif(exif); + raw.orientation = orientation; + let oriented_lens = lightcraft_pipeline::optics::reorient_lens(&lens, orientation, 384.0, 256.0); + let (aligned, reference, _) = proxies(&raw, &file, &transform, PROFILE_PROXY, 0.0, None, Some(&oriented_lens)).unwrap(); + let mut displayed = aligned.clone(); + displayed.map_in_place(|p| p.map(|v| v.powf(0.7))); + assert!(geometry_rms(&displayed, &reference) < 0.009, "orientation {exif}: WB exactly once and matching frames"); + let oriented_target = target.clone().into_oriented(orientation); + let expected = reference_at(&oriented_target, &aligned); + assert!(geometry_rms(&displayed, &expected) < 0.009, "orientation {exif}: absolute oriented ground truth"); + // Missing geometry must take the same established CR3 framing path as a rejected profile. + let (plain, plain_ref, plain_clip) = proxies(&raw, &file, &transform, PROXY, 0.0, None, None).unwrap(); + let (fallback, fallback_ref, fallback_clip) = proxies(&raw, &file, &transform, PROXY, 0.0, None, Some(&Default::default())).unwrap(); + assert_eq!(plain.data, fallback.data); + assert_eq!(plain_ref.data, fallback_ref.data); + assert_eq!(plain_clip, fallback_clip); + } +} + +/// Opt-in diagnostic only: never opens the app or changes a catalogue. It exports the actual +/// selected correspondences, and reports rejection as rejection rather than decoder success. +#[test] +#[ignore = "explicit local corpus diagnostic; requires LIGHTCRAFT_CR3_DIAGNOSTICS and LIGHTCRAFT_CORPUS"] +fn corpus_cr3_profile_geometry_diagnostics() { + let output = std::env::var_os("LIGHTCRAFT_CR3_DIAGNOSTICS").expect("explicit diagnostics require an output directory"); + let corpus = std::path::PathBuf::from(std::env::var_os("LIGHTCRAFT_CORPUS").expect("diagnostics require a corpus")); + let output = std::path::PathBuf::from(output); + std::fs::create_dir_all(&output).unwrap(); + let mut report = String::from( + "file\tmodel\torientation\tprofile_warp\tgeometry_accepted\tplain_alignment\tchosen_alignment\tplain_structure\tchosen_structure\tplain_pairs\tchosen_pairs\tplain_look\tchosen_look\tframed_gate_scores\toriginal_gate_scores\n", + ); + let mut paths: Vec<_> = std::fs::read_dir(corpus.join("raw")) + .unwrap() + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("cr3"))) + .collect(); + paths.sort(); + assert!(!paths.is_empty(), "diagnostic corpus must contain CR3 files"); + for path in paths { + let bytes = std::fs::read(&path).unwrap(); + let mut raw = lightcraft_raw::decode(&bytes).unwrap(); + let correction = crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(&bytes)); + let lens = lens_geometry(&raw.opcodes.list3); + raw.opcodes.list3.retain(|op| !op.is_lens_correction()); + let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); + let plain = proxies(&raw, &bytes, &transform, PROXY, 0.0, lens.as_ref(), None).unwrap(); + let chosen = proxies(&raw, &bytes, &transform, PROXY, 0.0, lens.as_ref(), correction.as_ref()).unwrap(); + let framed_scores = super::proxy::geometry_framed_scores(); + let original_scores = super::proxy::geometry_gate_scores(); + let accepted = plain.0.data.iter().flatten().zip(chosen.0.data.iter().flatten()).any(|(a, b)| a.to_bits() != b.to_bits()); + let pairs = |v: &(Rgb32f, Rgb32f, Vec)| { + let sensor = without_clipped(&v.0, &v.2).unwrap_or_else(|| v.0.clone()); + collect_pairs(&sensor, &v.1, 0.05, None, false).map_or(0, |v| v.0.len()) + }; + let before = fit_preview(&raw, &bytes, &transform, lens.as_ref(), None).0.is_some(); + let after = fit_preview(&raw, &bytes, &transform, lens.as_ref(), correction.as_ref()).0.is_some(); + let name = path.file_name().unwrap().to_string_lossy(); + report.push_str(&format!( + "{name}\t{}\t{:?}\t{}\t{accepted}\t{:.6}\t{:.6}\t{}\t{}\t{}\t{}\t{before}\t{after}\t{framed_scores:?}\t{original_scores:?}\n", + raw.metadata.model.as_deref().unwrap_or(""), + raw.orientation, + correction.as_ref().is_some_and(|l| l.warp.is_some()), + alignment(&plain.0, &plain.1), + alignment(&chosen.0, &chosen.1), + structure_agrees(&plain.0, &plain.1), + structure_agrees(&chosen.0, &chosen.1), + pairs(&plain), + pairs(&chosen) + )); + for (label, image) in [("plain", &plain.0), ("chosen", &chosen.0), ("jpeg", &chosen.1)] { + let to_srgb = lightcraft_color::SRGB.from_xyz().mul(&REC2020.to_xyz()); + let pixels: Vec = image + .data + .iter() + .flat_map(|p| { + to_srgb.apply_f32(*p).map(|v| { + let v = if v.is_finite() { v.max(0.0) } else { 0.0 }; + let v = if v <= 0.0031308 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + (v.clamp(0.0, 1.0) * 255.0).round() as u8 + }) + }) + .collect(); + let image = lightcraft_codecs::EncodeImage::new(image.width as u32, image.height as u32, 3, lightcraft_codecs::Samples::U8(&pixels)); + std::fs::write(output.join(format!("{name}-{label}.png")), lightcraft_codecs::encode_png(&image, &Default::default()).unwrap()).unwrap(); + } + std::fs::write(output.join("geometry.tsv"), &report).unwrap(); + } +} + +#[test] +fn cr3_rejected_profile_preserves_accepted_framing_fallback() { + use lightcraft_raw::{BlackLevel, RawData, Rect}; + let (w, h) = (416, 288); + let scene = profile_geometry_scene(w, h); + let mut raw = raw_of(RawFormat::Cr3, "Synthetic", "Uncalibrated", Default::default()); + raw.width = w; + raw.height = h; + raw.cpp = 3; + raw.data = RawData::F32(scene.data.iter().flatten().copied().collect()); + raw.black = BlackLevel::uniform(0.0); + raw.white = vec![1.0]; + raw.active_area = Rect::new(0, 0, w, h); + raw.crop = Rect::new(16, 16, 384, 256); + raw.linearized = true; + raw.wb_multipliers = Some([1.25, 1.0, 0.8]); + let transform = lightcraft_raw::color::camera_transform(&raw, D65); + assert!(transform.matrix_is_fallback); + let mut sensor = sensor_proxy(&raw, 2, 384).unwrap(); + assert_eq!((sensor.width, sensor.height), (384, 256)); + sensor.map_in_place(|p| { + transform.matrix.apply_f32(std::array::from_fn(|i| p[i] * transform.wb[i] * 2f32.powf(transform.baseline_exposure as f32))) + }); + let lens = synthetic_profile_lens(); + let mut target = profile_geometry_target(&sensor, &Default::default(), Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }); + target.map_in_place(|p| p.map(|v| v.powf(0.7))); + let to_srgb = lightcraft_color::SRGB.from_xyz().mul(&REC2020.to_xyz()); + let srgb = |v: f32| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + let pixels: Vec = target.data.iter().flat_map(|p| to_srgb.apply_f32(*p).map(|v| (srgb(v).clamp(0.0, 1.0) * 255.0).round() as u8)).collect(); + let image = lightcraft_codecs::EncodeImage::new(384, 256, 3, lightcraft_codecs::Samples::U8(&pixels)); + let jpeg = lightcraft_codecs::encode_jpeg(&image, 98, lightcraft_codecs::ChromaSubsampling::S444, &Default::default()).unwrap(); + let mut file = b"II*\0\x08\0\0\0\x02\0".to_vec(); + for (tag, value) in [(0x0201u16, 38u32), (0x0202, jpeg.len() as u32)] { + file.extend(tag.to_le_bytes()); + file.extend(4u16.to_le_bytes()); + file.extend(1u32.to_le_bytes()); + file.extend(value.to_le_bytes()); + } + file.extend(0u32.to_le_bytes()); + file.extend(jpeg); + let original_only = align_profile_geometry(&sensor, &Rgb32f::new(384, 256), &target, &lens, lightcraft_geom::Orientation::Normal); + assert!(original_only.is_some(), "this moderate wrong-lens proposal clears original-only gates, so the framed guard is necessary"); + let (plain, reference, mask) = proxies(&raw, &file, &transform, PROXY, 0.0, None, None).unwrap(); + let (fallback, fallback_reference, fallback_mask) = proxies(&raw, &file, &transform, PROXY, 0.0, None, Some(&lens)).unwrap(); + let mut comparison = plain.clone(); + comparison.map_in_place(|p| p.map(|v| v.powf(0.7))); + assert!(geometry_rms(&comparison, &reference) < 0.009, "existing framing fallback still aligns this JPEG"); + assert!( + plain.data.iter().flatten().zip(fallback.data.iter().flatten()).all(|(a, b)| a.to_bits() == b.to_bits()), + "wrong lens must be rejected before established framing" + ); + assert_eq!(reference.data, fallback_reference.data); + assert_eq!(mask, fallback_mask); +} diff --git a/crates/engine/src/camera_profiles.rs b/crates/engine/src/camera_profiles.rs index 9e6d2094ee..046f37c6b0 100644 --- a/crates/engine/src/camera_profiles.rs +++ b/crates/engine/src/camera_profiles.rs @@ -198,15 +198,20 @@ const PAIRS_PER_FILE: usize = 4000; impl Pool { /// Add one raw file's colour pairs. `Ok(None)` when the file can't contribute (not an ARW, - /// NEF or RAF without colour matrices, no usable camera JPEG, too little colour). + /// NEF, RAF, CR2/CR3 or another file-local format without colour matrices, no usable camera JPEG, too little colour). pub fn add(&mut self, bytes: &[u8]) -> Result, String> { let mut raw = lightcraft_raw::decode(bytes).map_err(|e| e.to_string())?; // colour only: geometric lens corrections would stop the sensor proxy from binning (the pairs still follow // the warp the camera applied to its JPEG) + let correction = if raw.format == lightcraft_raw::RawFormat::Cr3 { + crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(bytes)) + } else { + None + }; let lens = crate::camera_preview::lens_geometry(&raw.opcodes.list3); raw.opcodes.list3.retain(|op| !op.is_lens_correction()); let Some(model) = raw.metadata.model.as_deref().map(str::trim).filter(|m| !m.is_empty()) else { return Ok(None) }; - let Some(pairs) = crate::camera_preview::profile_pairs(&raw, bytes, lens.as_ref()) else { return Ok(None) }; + let Some(pairs) = crate::camera_preview::profile_pairs(&raw, bytes, lens.as_ref(), correction.as_ref()) else { return Ok(None) }; let step = pairs.len().div_ceil(PAIRS_PER_FILE).max(1); let entry = self.models.entry(model.to_owned()).or_default(); entry.0 += 1; diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index 51c54c60a9..b8c1ec1542 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -1,7 +1,7 @@ use super::*; /// Bump when the pipeline's output changes, to invalidate cached thumbnails. -pub const RENDER_CACHE_VERSION: u64 = 70; +pub const RENDER_CACHE_VERSION: u64 = 71; /// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache). pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512]; diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index 7a1235ab35..9b0079405c 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -98,9 +98,18 @@ These are camera-JPEG look estimates, **not measured spectral calibration or Lig ### Canon CR3 -CR3 uses the same colour gates and relative WB. Its sensor and JPEG proxies are first oriented identically. Canon can crop its JPEG differently from the sensor; no lens distortion correction is applied to the sensor proxy, so a strongly distortion-corrected JPEG can fail the gates. A fixed 96-pixel proxy measures this remaining framing from luminance-gradient directions: scale is limited to 0.9–1.1 and translation to two proxy pixels. At least 192 edges are required; two thirds train the framing and the remaining third must independently reach direction agreement ≥0.90 with an improvement ≥0.04. At least 80% of each edge set must remain usable. Weak, flat, unrelated or already aligned references keep the sensor framing. This alignment affects training correspondences only; the RAW render still uses the actual sensor pixels. +For CR3 with a fallback camera matrix and no in-file geometric warp, a resolved lens +profile can also propose the correspondence geometry. It must pass the existing +training/held-out direction gates and must not reduce agreement against the established +framing fallback on either split. Sensor, clipping mask and JPEG share orientation; +white balance is applied once. Rejected or missing profiles retain the framing path. +This changes calibration pairs, not the optics baked into the rendered RAW, and does +not enable profile-based correspondences for other RAW formats. +See [CR3 profile correspondence geometry](cr3-profile-alignment.md) for guards and scope. -On the public CC0 EOS R100 / RF-S 18–45 mm sample, the measured framing scale was 0.968. Held-out edge agreement rose from 0.7291 to 0.9194, and the unchanged colour gates accepted the fit (held-out RMS 0.10625 → 0.07704). The corpus test asserts acceptance after decoding the sensor RAW, and synthetic tests cover nonlinear camera tone, known crop/translation and unrelated references. The matrix, tone and hue/saturation table are estimated from the file; no third-party camera matrix or decoder calibration source is copied. +CR3 uses the same colour gates and relative WB. Its sensor and JPEG proxies are first oriented identically. Canon can crop its JPEG differently from the sensor; without an accepted lens-profile proposal, a strongly distortion-corrected JPEG can still fail the gates. A fixed 96-pixel proxy measures this remaining framing from luminance-gradient directions: scale is limited to 0.9–1.1 and translation to two proxy pixels. At least 192 edges are required; two thirds train the framing and the remaining third must independently reach direction agreement ≥0.90 with an improvement ≥0.04. At least 80% of each edge set must remain usable. Weak, flat, unrelated or already aligned references keep the sensor framing. This alignment affects training correspondences only; the RAW render still uses the actual sensor pixels. + +Before the profile-based proposal, the public CC0 EOS R100 / RF-S 18–45 mm sample had a measured framing scale of 0.968. Held-out edge agreement rose from 0.7291 to 0.9194, and the unchanged colour gates accepted the fit (held-out RMS 0.10625 → 0.07704). The corpus test asserts acceptance after decoding the sensor RAW, and synthetic tests cover nonlinear camera tone, known crop/translation and unrelated references. The matrix, tone and hue/saturation table are estimated from the file; no third-party camera matrix or decoder calibration source is copied. This is a per-file camera-look estimate, **not measured spectral calibration or Lightroom parity**. Camera local tone, picture styles, noise reduction and lens warps cannot all be reproduced by a global matrix/curve; same-aspect crops may evade the aspect check. Skin, mixed-light scenes and saturated highlights can still differ from a supplied JPEG. Broader Sony, Nikon and Canon model/lighting coverage, chart-based calibration, absolute WB and other manufacturers remain unverified. Rejected fits and other RAW formats retain their existing behaviour. diff --git a/docs/cr3-profile-alignment.md b/docs/cr3-profile-alignment.md new file mode 100644 index 0000000000..ce9086d433 --- /dev/null +++ b/docs/cr3-profile-alignment.md @@ -0,0 +1,58 @@ +# CR3 profile correspondence geometry + +CR3 colour calibration can propose a resolved lens profile’s geometry before collecting +sensor/JPEG training pairs. It reuses the guarded correspondence algorithm proposed in +#2675, with an additional comparison against CR3’s existing framing fallback. +It does not change CR3 decoding or the lens warp applied when developing the photograph. + +A resolved external lens profile may propose geometry only for file-local colour calibration, +with a fallback camera matrix and no in-file lens warp. The sensor, sensor clip mask, and embedded JPEG are +oriented together before evaluating the already oriented lens profile. White balance and +baseline exposure are applied exactly once before geometry assessment. + +The existing fixed-proxy edge test, bounded framing search (scale 0.9–1.1 and translation up to +two proxy pixels), minimum edge coverage, 0.9 agreement, and independent held-out improvement +of at least 0.04 are retained. Geometry uses luminance edge directions, without fitting RGB +values. Accepted geometry moves the sensor and clip mask together; invalid borders remain NaN. +CR3 proposals must also preserve or improve agreement against the existing framed fallback +on both training and held-out edges, compared on the exact intersection of valid edges with +the same reference weights. The published minimum 0.04 improvement over the unframed sensor +is retained separately; the fallback comparison adds no extra improvement threshold. Rejected or absent geometry takes the existing CR3 framing path. All subsequent colour, +tone, hue/saturation, clipping, and held-out acceptance gates stay unchanged. + +The proposal reaches file-local colour and tone, pooled camera-profile pairs, and colour tags +for merge/DNG conversion. Cache versions advance to look 14 and render 71. No camera allowlist, +new profile matching rules, or weaker acceptance gate is introduced. Other RAW formats +retain their existing correspondence behaviour. The non-CR3 and fixed-mount changes +proposed by #2675 are separate work. + +Synthetic tests cover lens-only and lens-plus-framing acceptance, unrelated/flat/already aligned +rejection, crop-relative profile orientation at multiple resolutions, clip-mask contributions, +and the complete CR3 correspondence route for EXIF orientations 1–8 with non-unity white balance. +The opt-in `corpus_cr3_profile_geometry_diagnostics` test exports `geometry.tsv` and plain, +selected, and JPEG proxy PNGs when `LIGHTCRAFT_CR3_DIAGNOSTICS` names an output directory. +It reads CR3 files from `$LIGHTCRAFT_CORPUS/raw` and the normal configured lens database. +The PNGs show linear proxy RGB converted to sRGB, without a camera tone curve; they are geometry +inspection aids, not developed image fidelity comparisons. Real-sample assessment and unchanged +fallback controls are required before any publication. This experiment does not establish +camera-wide colour parity or validate arbitrary Canon lenses, picture styles, or CRX modes. + +## Public-sample assessment + +On 22 SHA-256-verified, individually CC0-listed raw.pixls.us CR3 files using lensfun +XML data at `43f9e001`, the R100 RAW/C-RAW pair with RF-S18–45 at 18 mm accepts the +new geometry. The other 20 files retain pixel-identical 1600-pixel renders with optics +on/off, including eight R6 Mark II full-frame/crop, RAW/C-RAW and Dual-Pixel variants +of one scene. All 22 retain identical renders without a lens database. + +With the same independent baseline-derived radial registration applied to both +outputs, mean DE76 at 768×512 versus the embedded JPEG improves 4.54 to 3.79 (R100 RAW) +and 4.15 to 3.79 (C-RAW) with optics on. Unregistered whole-frame error slightly worsens +because optical framing still differs. This is a modest calibration benefit and does +not remove the photograph's visible lens distortion. The camera JPEG is not a +colorimetric reference. Four 24 MP files (R100 RAW/C-RAW and R6 II full-frame RAW/C-RAW) +render on CPU/Metal within 1/255 per channel, with optics on/off. + +The sample set does not establish all-camera correctness. R6 II’s eight variants +share one scene, not eight independent scenes. Pooled-profile and DNG-tag forwarding +are tested synthetically; this is not a real multi-camera calibration or DNG roundtrip. diff --git a/docs/gaps.md b/docs/gaps.md index 42d9d437b6..155609b5f7 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps: where LightCraft falls short of Lightroom -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-24 · **Change:** minor (gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 551 models verified; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-27 · **Change:** minor (gap 1: bounded CR3 profile correspondences, broader calibration still open; earlier: gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 551 models verified; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF) Every known shortfall, one entry each, ranked by user impact (how many Lightroom users hit it, and how hard it blocks them), then by effort. **Agents pick work from the top** (the first entry nobody is @@ -15,7 +15,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | # | Gap | Evidence | User impact | Hours | Doc | |---:|---|---|---|---:|---| -| 1 B | **Camera colour is estimated, not measured** (LR-PROF-CAMERACOLOR). Raws start from a per-file fit to the camera JPEG, 5 bundled profiles or 52 spectral matrices (plus same-sensor bodies, e.g. the X-T30 through the X-T3); others use a neutral matrix (a black-and-white camera JPEG gives its tone curve only, #577; dark JPEG tones also guide the toe, #1307) | ΔE vs camera JPEG 2.9–10 after fitting (raw-parity.md); 0 chart-calibrated models vs 1,500 Adobe Standard profiles | every raw shooter sees colour that is close but not Lightroom's; some get neutral-matrix colour | 50–90 | [raw-parity](raw-parity.md#colour) | +| 1 B | **Camera colour is estimated, not measured** (LR-PROF-CAMERACOLOR). Raws start from a per-file fit to the camera JPEG, 5 bundled profiles or 52 spectral matrices (plus same-sensor bodies, e.g. the X-T30 through the X-T3); others use a neutral matrix (a black-and-white camera JPEG gives its tone curve only, #577; dark JPEG tones also guide the toe, #1307) | ΔE vs camera JPEG 2.9–10 after fitting (raw-parity.md); 0 chart-calibrated models vs 1,500 Adobe Standard profiles | every raw shooter sees colour that is close but not Lightroom's; some get neutral-matrix colour | 50–90 | [raw-parity](raw-parity.md#colour) CR3 profile correspondence alignment is guarded against its framing fallback; limited public-sample coverage does not close this gap ([scope](cr3-profile-alignment.md)). | | 2 B | **CR3 variants no public file uses** (LR-IMP-FORMATS): `crx.rs` refuses vertical-tile C-RAW, partial-subband and other plane coding, multi-tile 0x200 and adaptive low-frequency gains, and those files fall back to the preview. All 110 CC0 CR3s on raw.pixls.us (31 folders) decode from sensor data, so none of these variants has a public sample; 26 CR3 bodies are verified (M50 / R100 / R8 exact, R5 Mark II pinned, 22 more pinned on one CC0 file each and checked against the camera JPEG, [cr3.md](cr3.md#further-bodies-one-cc0-file-each)). HEIF stills are `.HIF` files, not CR3; no CR3 sRAW / mRAW sample exists | measured: Canon's share whose camera fully works 73% → 94% (raw-parity.md); 18 of 22 popular Canon bodies write CR3, all 18 now verified | +0.3 points of photographers; the variants surface only as user files that open as a preview | 10–25 | [raw-parity](raw-parity.md#remaining-work-ranked-by-photographers-unlocked-per-hour) | | 3 B | **Render fidelity unmeasured** (LR-BEHAV-RENDER-FIDELITY): tone, highlights, texture / clarity / dehaze, NR and sharpening are tuned by eye | no side-by-side suite; a retune needs a new process version (only V1 exists) | edits imported from Lightroom look different; the look "isn't Lightroom's" | 30–60 | [raw-parity](raw-parity.md), [process-versions](process-versions.md) | | 4 | ~~Original-pixel detail at 100%~~ (LR-VIEW-ZOOM): closed 2026-10-12, see Closed recently | checklist row ✅ | — | 0 | [ui-parity](ui-parity.md) | @@ -84,6 +84,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | Gap 1: CR3 profile correspondence alignment guarded against the existing framing fallback; limited real-file evidence, camera-colour gap remains open | | 2026-10-24 | minor | Gap 28: ⌘⌥⇧C / ⌘⌥⇧V (Ctrl+Alt+Shift+C / V on Windows and Linux) copy and paste metadata; no key leaves the entry; hours unchanged | | 2026-10-24 | minor | Gap 30 shrinks: the Info panel's Show Metadata For (Target Photo / Selected Photos, `view.infoSelectedPhotos`) shows the selected photos' shared values and marks fields that differ as Mixed; the All Metadata dialog remains; 1–3 h (was 4–8) | | 2026-10-23 | minor | Gap 13: before a Lightroom catalog import the app asks whether it merges into the open library or goes into a new one (opt-out in Settings, #2672); hours unchanged | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 90cfc248f6..0d9bf01c55 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (LR-PROF-CAMERACOLOR: CR3 guarded profile correspondences, partial status unchanged; earlier: LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -236,7 +236,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-PROF-ADOBE | Standard raw looks (own equivalents) | P0 | ✅ | `crates/engine/src/presets.rs` (`PROFILES`), `crates/pipeline/src/profiles.rs` | six own looks: Color, Neutral, Vivid, Landscape, Portrait, Monochrome | | LR-PROF-ADAPTIVE | Adaptive profiles | P2 | ⬜ | | | | LR-PROF-CAMERA | Camera-matching looks | P2 | ⬜ | | | -| LR-PROF-CAMERACOLOR | Camera colour calibration (own) | P0 | 🟡 | `crates/raw/src/color.rs`, `crates/raw/src/profile.rs`, `crates/raw/src/gaintable.rs`, `crates/engine/src/camera_preview.rs` | DNG files use the colour matrices and the camera-profile look they carry (`ProfileHueSatMap`, `ProfileLookTable`, `ProfileToneCurve`, read from the file at run time per DNG spec ch. 6 — Lightroom-converted DNGs rendered flat and muted without them, issue #138). A DNG whose profile defines no tone curve (absent or identity `ProfileToneCurve`, with or without a `LookTable`, as Adobe Standard in Lightroom-written DNGs) gets its tone fitted to its embedded preview when that is at least 10% of the raw's long edge and 384 px (Lightroom's 1024 px previews qualify): two Lightroom Classic 15.1 lossy ILCE-7CM2 DNGs went from about 0.8 EV darker and flat to within 3% of Lightroom's mean linear RGB. A DNG's `ProfileGainTableMap` / `ProfileGainTableMap2` (Apple ProRAW's local tone map; both versions, DNG 1.7 precedence, the file's byte order with a big-endian fallback) is read and written back by DNG export and not rendered by default, as Lightroom Classic renders ProRAW without it (measured on one CC0 iPhone 12 Pro ProRAW); the Profile option "Camera local tone mapping" (`profile.camera_local_tone`, per photo, off by default, `crates/pipeline/src/local_tone.rs`) renders it as the camera does, per output pixel in the scene-linear stage (CPU, also under the GPU path); Sony ARW, Nikon NEF, Panasonic RW2, Fujifilm RAF, Canon CR3 and CR2, Pentax PEF, Samsung SRW and Olympus ORF get a guarded file-local fit to their own embedded JPEG — chromaticity matrix + hue/saturation/value table + tone and chroma curves, relative WB — or, with a bundled or local per-model profile pooled from many photos (`lightcraft-cli calibrate`, ARW, NEF and RAF so far, `crates/engine/src/camera_profiles.rs`), the profile's colour and only their own tone/chroma curves (on 29 held-out ILCE-7M4 photos mean ΔE vs the camera JPEG 3.54 → 3.10; bundled ILCE-7CR from 125 photos: 26 held-out 4.07 → 3.29, and every one of the 131 photos accepted, 8 of which fell back to neutral without it; bundled ILCA-99M2 from 144 photos: 30 held-out 5.11 → 4.87, 25 of them closer); the tone fit also uses dark JPEG samples excluded from colour training, so deep shadows follow the camera toe (#1307); near-black frames with too few colour pairs can take a guarded tone-only fallback on their existing source colour (#1587); Sony ARWs shot with DRO on (maker note `0xb025`, on by default) keep that colour but their tone curve is lowered to Sony's curve without DRO, whose lifted shadows are in the camera JPEG only (issue #244: 8 ILCE-7CR photos +6.4 → +0.8 L* from Lightroom's default, median ΔE 7.5 → 3.3); 52 models without a profile whose JPEG fit fails (or that have no usable JPEG) start from DNG-style matrices fitted to their measured spectral sensitivities instead of the neutral fallback (`crates/raw/src/spectral.rs`, rawtoaces-data v1.1.0, Apache-2.0, aliases included; not yet measured against the camera JPEG); ARW: on 10 public raw.pixls.us samples from 8 bodies 7 fits were accepted, mean ΔE vs the camera JPEG 17–26 → 3–10; NEF: 13 of 13 decodable samples (D750, D780, D850, D7500, Z 50 and local D7500 shots) accepted, ΔE 13–46 → 3–8 (issue #150); RW2 / RWL: 140 of 174 public samples accepted, from 93 of the 114 bodies with a preview, median ΔE 5.0 with matching lightness (13 of the 14 corpus files with a preview: ΔE 9.6–27 → 2.8–8.9; most rejections are compacts and kit zooms whose camera JPEG is distortion-corrected); a fit that fails the gates on all pixels is retried away from edges, where a lens-corrected camera JPEG still lines up (issue #232: the six distortion-corrected public ILCE-7RM2 samples ΔE 16.6–16.9 → 3.7–3.8, the corpus GX80 19.1 → 7.9); RAF: bundled X-H2S/X-T4 profiles from 201/545 photos; on 150 withheld files mean ΔE improves slightly over per-file fitting (X-H2S 1.70 → 1.62, X-T4 2.43 → 2.34); 23 of 24 references from 13 bodies accepted, including the dark X-H2S samples (8.74 → 2.25); ORF: the 3 decodable corpus files (E-1, E-400, XZ-2) accepted (`docs/camera-preview-colour.md`); a raw whose camera JPEG is black and white (a monochrome picture style) takes only the JPEG's tone curve, on the camera profile's, spectral or neutral colour (issue #577); this is not measured camera calibration; other raws and rejected fits use a neutral fallback (camera RGB ≈ linear sRGB, `matrix_is_fallback`) with as-shot white balance, so colours are muted and not accurate. Needs our own per-camera calibration: matrices the files carry themselves (e.g. Olympus `ColorMatrix`), fitting each camera to its own embedded JPEG, then chart shots. Adobe matrices / DCPs are never used. Biggest image-quality gap today; ILCE-7RM6: per-file fit now runs on previews above 64 MP, a pooled profile (46 photos) was tried and not bundled (withheld ΔE 5.71 → 6.40, 11 of 15 regressed), kept with smart previews (see docs/camera-preview-colour.md); the fit pairs the sensor moved into the file's lens-warp geometry when that lines up better with a lens-corrected camera JPEG (29 CC0 raws: alignment +0.13, mean ΔE 3.73 → 3.61); bundled NIKON Z 6_2 profile (296 photos; 59 held-back photos mean ΔE 2.73 → 2.54) NIKON Z 8 profile (261 photos; 55 held back 2.55 → 2.33) and NIKON D5300 profile (264 photos; 53 held back 2.86 → 2.66) | +| LR-PROF-CAMERACOLOR | Camera colour calibration (own) | P0 | 🟡 | `crates/raw/src/color.rs`, `crates/raw/src/profile.rs`, `crates/raw/src/gaintable.rs`, `crates/engine/src/camera_preview.rs` | DNG files use the colour matrices and the camera-profile look they carry (`ProfileHueSatMap`, `ProfileLookTable`, `ProfileToneCurve`, read from the file at run time per DNG spec ch. 6 — Lightroom-converted DNGs rendered flat and muted without them, issue #138). A DNG whose profile defines no tone curve (absent or identity `ProfileToneCurve`, with or without a `LookTable`, as Adobe Standard in Lightroom-written DNGs) gets its tone fitted to its embedded preview when that is at least 10% of the raw's long edge and 384 px (Lightroom's 1024 px previews qualify): two Lightroom Classic 15.1 lossy ILCE-7CM2 DNGs went from about 0.8 EV darker and flat to within 3% of Lightroom's mean linear RGB. A DNG's `ProfileGainTableMap` / `ProfileGainTableMap2` (Apple ProRAW's local tone map; both versions, DNG 1.7 precedence, the file's byte order with a big-endian fallback) is read and written back by DNG export and not rendered by default, as Lightroom Classic renders ProRAW without it (measured on one CC0 iPhone 12 Pro ProRAW); the Profile option "Camera local tone mapping" (`profile.camera_local_tone`, per photo, off by default, `crates/pipeline/src/local_tone.rs`) renders it as the camera does, per output pixel in the scene-linear stage (CPU, also under the GPU path); Sony ARW, Nikon NEF, Panasonic RW2, Fujifilm RAF, Canon CR3 and CR2, Pentax PEF, Samsung SRW and Olympus ORF get a guarded file-local fit to their own embedded JPEG — chromaticity matrix + hue/saturation/value table + tone and chroma curves, relative WB — or, with a bundled or local per-model profile pooled from many photos (`lightcraft-cli calibrate`, ARW, NEF and RAF so far, `crates/engine/src/camera_profiles.rs`), the profile's colour and only their own tone/chroma curves (on 29 held-out ILCE-7M4 photos mean ΔE vs the camera JPEG 3.54 → 3.10; bundled ILCE-7CR from 125 photos: 26 held-out 4.07 → 3.29, and every one of the 131 photos accepted, 8 of which fell back to neutral without it; bundled ILCA-99M2 from 144 photos: 30 held-out 5.11 → 4.87, 25 of them closer); the tone fit also uses dark JPEG samples excluded from colour training, so deep shadows follow the camera toe (#1307); near-black frames with too few colour pairs can take a guarded tone-only fallback on their existing source colour (#1587); Sony ARWs shot with DRO on (maker note `0xb025`, on by default) keep that colour but their tone curve is lowered to Sony's curve without DRO, whose lifted shadows are in the camera JPEG only (issue #244: 8 ILCE-7CR photos +6.4 → +0.8 L* from Lightroom's default, median ΔE 7.5 → 3.3); 52 models without a profile whose JPEG fit fails (or that have no usable JPEG) start from DNG-style matrices fitted to their measured spectral sensitivities instead of the neutral fallback (`crates/raw/src/spectral.rs`, rawtoaces-data v1.1.0, Apache-2.0, aliases included; not yet measured against the camera JPEG); ARW: on 10 public raw.pixls.us samples from 8 bodies 7 fits were accepted, mean ΔE vs the camera JPEG 17–26 → 3–10; NEF: 13 of 13 decodable samples (D750, D780, D850, D7500, Z 50 and local D7500 shots) accepted, ΔE 13–46 → 3–8 (issue #150); RW2 / RWL: 140 of 174 public samples accepted, from 93 of the 114 bodies with a preview, median ΔE 5.0 with matching lightness (13 of the 14 corpus files with a preview: ΔE 9.6–27 → 2.8–8.9; most rejections are compacts and kit zooms whose camera JPEG is distortion-corrected); a fit that fails the gates on all pixels is retried away from edges, where a lens-corrected camera JPEG still lines up (issue #232: the six distortion-corrected public ILCE-7RM2 samples ΔE 16.6–16.9 → 3.7–3.8, the corpus GX80 19.1 → 7.9); RAF: bundled X-H2S/X-T4 profiles from 201/545 photos; on 150 withheld files mean ΔE improves slightly over per-file fitting (X-H2S 1.70 → 1.62, X-T4 2.43 → 2.34); 23 of 24 references from 13 bodies accepted, including the dark X-H2S samples (8.74 → 2.25); ORF: the 3 decodable corpus files (E-1, E-400, XZ-2) accepted (`docs/camera-preview-colour.md`); a raw whose camera JPEG is black and white (a monochrome picture style) takes only the JPEG's tone curve, on the camera profile's, spectral or neutral colour (issue #577); this is not measured camera calibration; other raws and rejected fits use a neutral fallback (camera RGB ≈ linear sRGB, `matrix_is_fallback`) with as-shot white balance, so colours are muted and not accurate. Needs our own per-camera calibration: matrices the files carry themselves (e.g. Olympus `ColorMatrix`), fitting each camera to its own embedded JPEG, then chart shots. Adobe matrices / DCPs are never used. Biggest image-quality gap today; ILCE-7RM6: per-file fit now runs on previews above 64 MP, a pooled profile (46 photos) was tried and not bundled (withheld ΔE 5.71 → 6.40, 11 of 15 regressed), kept with smart previews (see docs/camera-preview-colour.md); the fit pairs the sensor moved into the file's lens-warp geometry when that lines up better with a lens-corrected camera JPEG (29 CC0 raws: alignment +0.13, mean ΔE 3.73 → 3.61); bundled NIKON Z 6_2 profile (296 photos; 59 held-back photos mean ΔE 2.73 → 2.54) NIKON Z 8 profile (261 photos; 55 held back 2.55 → 2.33) and NIKON D5300 profile (264 photos; 53 held back 2.86 → 2.66) CR3 calibration pairs may use guarded resolved-profile geometry with non-regression against its framing fallback ([scope](cr3-profile-alignment.md)); other formats and partial status stay unchanged. | | LR-PROF-CREATIVE | Creative profiles (own) | P2 | ✅ | `cmd:develop.profile`, `crates/pipeline/src/profiles.rs` | 16 own looks in Film / Cinematic / Muted / B&W (tone + point-curve fades, colour grading, mixer / B&W mix); scale with `ctl:profile.amount`; sliders untouched | | LR-PROF-LEGACY | Legacy profiles | P2 | ⬜ | | | | LR-PROF-NONRAW | Profiles for non-raw files | P0 | ✅ | `cmd:develop.profile` | same looks apply to JPEG/TIFF | @@ -799,6 +799,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | LR-PROF-CAMERACOLOR: CR3 profile geometry with independent original-edge gates and non-regression against its framing fallback; other formats and partial status unchanged | | 2026-10-25 | patch | LR-BEHAV-TITLEBAR: the top bar's title-bar gestures come from craft-window's `title_bar`: a double-click follows the system setting, and a press on a button, the search field or a panel floating over the bar never moves the window; status counts unchanged | | 2026-10-24 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 (`keyword.nextSet`, `keyword.previousSet`) go to the next / previous keyword set; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | minor | KEYC-METADATA: ⌘K / Ctrl+K (`panel.addKeywords`, Add Keywords) shows the Keywords panel, opens Keywording and puts the cursor in the Add keyword box; status counts unchanged (KEYC-METADATA stays 🟡) | From 8f3412ce1545e4091299301b8cf20689435b88ff Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:10:36 +0100 Subject: [PATCH 04/63] LR-CI: document functions touched by readiness fixes --- apps/lightcraft/src/editors.rs | 1 + apps/lightcraft/src/launch.rs | 2 ++ crates/engine/src/cmd/face_detect.rs | 1 + crates/engine/src/cmd/face_models.rs | 1 + crates/engine/src/cmd/geocode.rs | 2 ++ crates/ui-egui/src/dialogs/settings/general.rs | 1 + crates/ui-egui/src/panels/grid.rs | 1 + 7 files changed, 9 insertions(+) diff --git a/apps/lightcraft/src/editors.rs b/apps/lightcraft/src/editors.rs index 87f2cb6144..35c76b508e 100644 --- a/apps/lightcraft/src/editors.rs +++ b/apps/lightcraft/src/editors.rs @@ -111,6 +111,7 @@ fn windows_default_command(path: &str) -> Command { c } +/// Resolve an external editor name to its platform launcher, reporting when PhotoCraft is missing. fn launcher(app: &str) -> Result { let app = app.trim(); if app.is_empty() { diff --git a/apps/lightcraft/src/launch.rs b/apps/lightcraft/src/launch.rs index 95a8d452eb..f5479671be 100644 --- a/apps/lightcraft/src/launch.rs +++ b/apps/lightcraft/src/launch.rs @@ -36,6 +36,8 @@ pub(crate) fn launch_imports(args: &[String]) -> (Vec, Vec) { launch_imports_in(args, cwd.as_deref(), home.as_deref()) } +/// Split launch arguments into importable paths and refusal notices. Relative paths use `cwd`; +/// `home` identifies the whole home folder, which must not be imported. pub(crate) fn launch_imports_in(args: &[String], cwd: Option<&std::path::Path>, home: Option<&std::path::Path>) -> (Vec, Vec) { use lightcraft_engine::import::{LaunchPath, launch_path}; let (mut files, mut notices) = (Vec::new(), Vec::new()); diff --git a/crates/engine/src/cmd/face_detect.rs b/crates/engine/src/cmd/face_detect.rs index 611a841033..a5be585b8f 100644 --- a/crates/engine/src/cmd/face_detect.rs +++ b/crates/engine/src/cmd/face_detect.rs @@ -297,6 +297,7 @@ fn detect(s: &mut Session, p: &Value) -> Result { Ok(json!({"detector": LABEL, "applied": applied, "photos": results, "ms": started.elapsed().as_secs_f64() * 1000.0})) } +/// Describe the face detection and face-model device query commands. pub fn specs() -> Vec { vec![ cmd!( diff --git a/crates/engine/src/cmd/face_models.rs b/crates/engine/src/cmd/face_models.rs index dc7bbe0ee0..53cd01aea4 100644 --- a/crates/engine/src/cmd/face_models.rs +++ b/crates/engine/src/cmd/face_models.rs @@ -501,6 +501,7 @@ fn select(s: &mut Session, p: &Value) -> Result { Ok(json!({"embedder": st.embedder})) } +/// Enable or disable face recognition, requiring an installed recognition model when enabling it. fn enable(s: &mut Session, p: &Value) -> Result { const C: &str = "faces.enable"; let dir = models_dir(s, C)?; diff --git a/crates/engine/src/cmd/geocode.rs b/crates/engine/src/cmd/geocode.rs index 9d924003b1..3ed25454ae 100644 --- a/crates/engine/src/cmd/geocode.rs +++ b/crates/engine/src/cmd/geocode.rs @@ -119,6 +119,8 @@ fn fill(meta: &mut lightcraft_catalog::Meta, place: &lightcraft_geocode::Place, } } +/// Populate place metadata for targeted photos with valid GPS coordinates using the local database. +/// Existing fields are preserved unless `overwrite` is requested. fn reverse(s: &mut Session, p: &Value) -> Result { const C: &str = "metadata.reverseGeocode"; let overwrite = bool_or(p, "overwrite", false); diff --git a/crates/ui-egui/src/dialogs/settings/general.rs b/crates/ui-egui/src/dialogs/settings/general.rs index ff7559fc93..e2f8d14415 100644 --- a/crates/ui-egui/src/dialogs/settings/general.rs +++ b/crates/ui-egui/src/dialogs/settings/general.rs @@ -3,6 +3,7 @@ use super::*; // ------------------------------------------------------------------------------------- General +/// Draw the General settings tab, including language and library-location controls. pub(super) fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { row(ui, t, crate::i18n::tr("Language"), |ui| { let languages: Vec<_> = crate::i18n::Locale::for_picker().into_iter().map(|language| (language, language.name())).collect(); diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index 36c9ca342a..10b15363c7 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -1214,6 +1214,7 @@ pub fn toggle_stack(app: &mut LightcraftApp, ctx: &egui::Context, id: PhotoId) { } } +/// Draw the photo's grid context menu and dispatch the selected action. pub fn context_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if !app.session.selection.contains(id) { let _ = app.run("library.select", json!({"ids": [id.0]})); From 49f4cd6e2d41f6dc18070dc38c8524d3683fe36a Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:46:35 +0100 Subject: [PATCH 05/63] LR-PROF-CAMERACOLOR: report unavailable CR3 diagnostic proxies Keep the opt-in geometry diagnostic usable on mixed CR3 corpora when plain or profile-selected proxies are unavailable. Record the missing side with empty measurements, preserve measured rows and continue. Add a synthetic regression for actual unavailable sensor proxies with spectral colour data, all missing combinations and subsequent usable results. Document the TSV status/reason columns without changing any production calibration or acceptance gates. --- crates/engine/src/camera_preview/tests.rs | 119 +++++++++++++++++++++- docs/cr3-profile-alignment.md | 7 ++ 2 files changed, 121 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index c397619275..f67b217738 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -2708,6 +2708,109 @@ fn cr3_profile_geometry_shares_orientation_and_applies_white_balance_once() { } } +/// Sensor, JPEG and clipping samples returned by the diagnostic proxy calls. +type DiagnosticProxy = (Rgb32f, Rgb32f, Vec); + +/// Preserve missing-proxy cases in the diagnostic TSV without inventing geometry or fit results. +/// `proxies` exposes no rejection reason, so the row records only which call returned `None`. +fn diagnostic_proxies_or_report( + name: &str, + raw: &RawImage, + profile_warp: bool, + plain: Option, + chosen: Option, + report: &mut String, +) -> Option<(DiagnosticProxy, DiagnosticProxy)> { + let status = match (plain, chosen) { + (Some(plain), Some(chosen)) => return Some((plain, chosen)), + (None, Some(_)) => "missing_plain_proxy", + (Some(_), None) => "missing_chosen_proxy", + (None, None) => "missing_both_proxies", + }; + let mut fields = vec![String::new(); 17]; + fields[0] = name.to_owned(); + fields[1] = raw.metadata.model.clone().unwrap_or_default(); + fields[2] = format!("{:?}", raw.orientation); + fields[3] = profile_warp.to_string(); + fields[15] = status.to_owned(); + fields[16] = "proxies returned None; underlying cause unavailable".to_owned(); + report.push_str(&fields.join("\t")); + report.push('\n'); + None +} + +/// Build a small RGB CR3-shaped raw and embedded JPEG without opening any real photo. +fn diagnostic_proxy_fixture() -> (RawImage, Vec) { + let (w, h) = (96, 64); + let scene = profile_geometry_scene(w, h); + let mut raw = raw_of(RawFormat::Cr3, "Synthetic", "Uncalibrated", Default::default()); + raw.width = w; + raw.height = h; + raw.cpp = 3; + raw.data = lightcraft_raw::RawData::F32(scene.data.iter().flatten().copied().collect()); + raw.black = lightcraft_raw::BlackLevel::uniform(0.0); + raw.white = vec![1.0]; + raw.active_area = lightcraft_raw::Rect::new(0, 0, w, h); + raw.crop = raw.active_area; + raw.linearized = true; + raw.wb_multipliers = Some([1.0; 3]); + let pixels: Vec = scene.data.iter().flatten().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8).collect(); + let image = lightcraft_codecs::EncodeImage::new(w as u32, h as u32, 3, lightcraft_codecs::Samples::U8(&pixels)); + let jpeg = lightcraft_codecs::encode_jpeg(&image, 98, lightcraft_codecs::ChromaSubsampling::S444, &Default::default()).unwrap(); + let mut file = b"II*\0\x08\0\0\0\x02\0".to_vec(); + for (tag, value) in [(0x0201u16, 38u32), (0x0202, jpeg.len() as u32)] { + file.extend(tag.to_le_bytes()); + file.extend(4u16.to_le_bytes()); + file.extend(1u32.to_le_bytes()); + file.extend(value.to_le_bytes()); + } + file.extend(0u32.to_le_bytes()); + file.extend(jpeg); + (raw, file) +} + +/// Exercise the corpus diagnostic's actual proxy-result handling across missing and available inputs. +#[test] +fn cr3_diagnostics_report_missing_proxies_and_continue() { + let (mut raw, bytes) = diagnostic_proxy_fixture(); + let transform = lightcraft_raw::color::camera_transform(&raw, D65); + let available = proxies(&raw, &bytes, &transform, PROXY, 0.0, None, None).unwrap(); + // A valid spectral transform does not guarantee a usable sensor proxy. This synthetic + // single-channel raw lacks a CFA, so the established proxy path deliberately returns None. + let camera = lightcraft_raw::spectral::find(Some("Canon"), "Canon EOS R8").unwrap(); + raw.color.color_matrix = camera.color_matrix.map(Some); + raw.color.forward_matrix = camera.forward_matrix.map(Some); + raw.color.illuminant = [17, 21]; + raw.cpp = 1; + raw.data = lightcraft_raw::RawData::U16(vec![0; raw.width * raw.height]); + let calibrated = lightcraft_raw::color::camera_transform(&raw, D65); + assert!(!calibrated.matrix_is_fallback); + let missing = proxies(&raw, &bytes, &calibrated, PROXY, 0.0, None, None); + assert!(missing.is_none()); + let mut report = String::new(); + for (plain, chosen, status) in [ + (missing.clone(), missing.clone(), "missing_both_proxies"), + (missing.clone(), Some(available.clone()), "missing_plain_proxy"), + (Some(available.clone()), missing, "missing_chosen_proxy"), + ] { + assert!(diagnostic_proxies_or_report(status, &raw, true, plain, chosen, &mut report).is_none()); + } + let (plain, chosen) = diagnostic_proxies_or_report("available", &raw, false, Some(available.clone()), Some(available.clone()), &mut report) + .expect("a later usable file must still reach measurement and image export"); + let bits = |image: &Rgb32f| image.data.iter().flatten().map(|v| v.to_bits()).collect::>(); + assert_eq!(bits(&plain.0), bits(&available.0)); + assert_eq!(chosen.1.data, available.1.data); + let rows: Vec<_> = report.lines().collect(); + assert_eq!(rows.len(), 3, "available proxies must not create an unavailable row"); + for row in rows { + let fields: Vec<_> = row.split('\t').collect(); + assert_eq!(fields.len(), 17); + assert_eq!(fields[0], fields[15], "all three missing cases retain distinct statuses"); + assert!(fields[4..15].iter().all(|v| v.is_empty()), "unavailable metrics, gates and fits stay empty"); + assert_eq!(fields[16], "proxies returned None; underlying cause unavailable"); + } +} + /// Opt-in diagnostic only: never opens the app or changes a catalogue. It exports the actual /// selected correspondences, and reports rejection as rejection rather than decoder success. #[test] @@ -2718,7 +2821,7 @@ fn corpus_cr3_profile_geometry_diagnostics() { let output = std::path::PathBuf::from(output); std::fs::create_dir_all(&output).unwrap(); let mut report = String::from( - "file\tmodel\torientation\tprofile_warp\tgeometry_accepted\tplain_alignment\tchosen_alignment\tplain_structure\tchosen_structure\tplain_pairs\tchosen_pairs\tplain_look\tchosen_look\tframed_gate_scores\toriginal_gate_scores\n", + "file\tmodel\torientation\tprofile_warp\tgeometry_accepted\tplain_alignment\tchosen_alignment\tplain_structure\tchosen_structure\tplain_pairs\tchosen_pairs\tplain_look\tchosen_look\tframed_gate_scores\toriginal_gate_scores\tstatus\treason\n", ); let mut paths: Vec<_> = std::fs::read_dir(corpus.join("raw")) .unwrap() @@ -2735,8 +2838,15 @@ fn corpus_cr3_profile_geometry_diagnostics() { let lens = lens_geometry(&raw.opcodes.list3); raw.opcodes.list3.retain(|op| !op.is_lens_correction()); let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); - let plain = proxies(&raw, &bytes, &transform, PROXY, 0.0, lens.as_ref(), None).unwrap(); - let chosen = proxies(&raw, &bytes, &transform, PROXY, 0.0, lens.as_ref(), correction.as_ref()).unwrap(); + let plain = proxies(&raw, &bytes, &transform, PROXY, 0.0, lens.as_ref(), None); + let chosen = proxies(&raw, &bytes, &transform, PROXY, 0.0, lens.as_ref(), correction.as_ref()); + let name = path.file_name().unwrap().to_string_lossy(); + let Some((plain, chosen)) = + diagnostic_proxies_or_report(&name, &raw, correction.as_ref().is_some_and(|l| l.warp.is_some()), plain, chosen, &mut report) + else { + std::fs::write(output.join("geometry.tsv"), &report).unwrap(); + continue; + }; let framed_scores = super::proxy::geometry_framed_scores(); let original_scores = super::proxy::geometry_gate_scores(); let accepted = plain.0.data.iter().flatten().zip(chosen.0.data.iter().flatten()).any(|(a, b)| a.to_bits() != b.to_bits()); @@ -2746,9 +2856,8 @@ fn corpus_cr3_profile_geometry_diagnostics() { }; let before = fit_preview(&raw, &bytes, &transform, lens.as_ref(), None).0.is_some(); let after = fit_preview(&raw, &bytes, &transform, lens.as_ref(), correction.as_ref()).0.is_some(); - let name = path.file_name().unwrap().to_string_lossy(); report.push_str(&format!( - "{name}\t{}\t{:?}\t{}\t{accepted}\t{:.6}\t{:.6}\t{}\t{}\t{}\t{}\t{before}\t{after}\t{framed_scores:?}\t{original_scores:?}\n", + "{name}\t{}\t{:?}\t{}\t{accepted}\t{:.6}\t{:.6}\t{}\t{}\t{}\t{}\t{before}\t{after}\t{framed_scores:?}\t{original_scores:?}\tmeasured\t\n", raw.metadata.model.as_deref().unwrap_or(""), raw.orientation, correction.as_ref().is_some_and(|l| l.warp.is_some()), diff --git a/docs/cr3-profile-alignment.md b/docs/cr3-profile-alignment.md index ce9086d433..847d112d02 100644 --- a/docs/cr3-profile-alignment.md +++ b/docs/cr3-profile-alignment.md @@ -32,6 +32,13 @@ and the complete CR3 correspondence route for EXIF orientations 1–8 with non-u The opt-in `corpus_cr3_profile_geometry_diagnostics` test exports `geometry.tsv` and plain, selected, and JPEG proxy PNGs when `LIGHTCRAFT_CR3_DIAGNOSTICS` names an output directory. It reads CR3 files from `$LIGHTCRAFT_CORPUS/raw` and the normal configured lens database. +The TSV appends `status` and `reason` columns. `measured` means both proxy calls returned +images; acceptance or rejection is recorded separately in the existing measurement columns. +If either call returns no proxy, the row records `missing_plain_proxy`, +`missing_chosen_proxy`, or `missing_both_proxies`, leaves all measurement fields empty, +and exports no PNGs for that file. The diagnostic continues with the next CR3. The reason +does not attribute a cause: the proxy API returns only `None`, which can cover unavailable +previews or sensor proxies. An unavailable row is not a passed geometry or colour check. The PNGs show linear proxy RGB converted to sRGB, without a camera tone curve; they are geometry inspection aids, not developed image fidelity comparisons. Real-sample assessment and unchanged fallback controls are required before any publication. This experiment does not establish From 23d1b404352a7676a55d88252fa6c762f918728a Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Wed, 21 Oct 2026 22:42:21 +0200 Subject: [PATCH 06/63] LR-MERGE-PANO: report omitted photos and pair verification outcomes Report used and omitted source photos in source order, expand HDR brackets, and retain pair verification measurements. Show current-preview omissions and use the final result's own inclusion count on completion. Keep the matching threshold unchanged. Procedural counterexamples show that lowering only its slope also accepts wrong matches and parallax. Related to #1765. The original waterfall registration remains unresolved. Credit @aterveus for the issue, pair measurements and prototype experiments. Co-Authored-By: GPT-6 Astra --- Cargo.lock | 1 + ROADMAP.md | 9 +- crates/engine/src/merge.rs | 65 +++++++++- crates/engine/src/tests/merge.rs | 49 ++++++++ crates/merge/Cargo.toml | 1 + crates/merge/src/pano.rs | 18 ++- crates/merge/src/pano/camera.rs | 68 +++++++++-- crates/merge/tests/it/pano.rs | 26 ++++ crates/merge/tests/pair_verification.rs | 125 ++++++++++++++++++++ crates/ui-egui/locales/cs-formats.json | 1 + crates/ui-egui/locales/cs.json | 1 + crates/ui-egui/locales/de-formats.json | 1 + crates/ui-egui/locales/de.json | 1 + crates/ui-egui/locales/es-formats.json | 1 + crates/ui-egui/locales/es.json | 1 + crates/ui-egui/locales/fi-formats.json | 1 + crates/ui-egui/locales/fi.json | 1 + crates/ui-egui/locales/fr-formats.json | 1 + crates/ui-egui/locales/fr.json | 1 + crates/ui-egui/locales/id-formats.json | 1 + crates/ui-egui/locales/id.json | 1 + crates/ui-egui/locales/it-formats.json | 1 + crates/ui-egui/locales/it.json | 1 + crates/ui-egui/locales/ja-formats.json | 1 + crates/ui-egui/locales/ja.json | 1 + crates/ui-egui/locales/ka-formats.json | 1 + crates/ui-egui/locales/ka.json | 1 + crates/ui-egui/locales/pl-formats.json | 1 + crates/ui-egui/locales/pl.json | 1 + crates/ui-egui/locales/pt-br-formats.json | 1 + crates/ui-egui/locales/pt-br.json | 1 + crates/ui-egui/locales/ru-formats.json | 1 + crates/ui-egui/locales/ru.json | 1 + crates/ui-egui/locales/sv-formats.json | 1 + crates/ui-egui/locales/sv.json | 1 + crates/ui-egui/locales/uk-formats.json | 1 + crates/ui-egui/locales/uk.json | 1 + crates/ui-egui/locales/vi-formats.json | 1 + crates/ui-egui/locales/vi.json | 1 + crates/ui-egui/locales/zh-hans-formats.json | 1 + crates/ui-egui/locales/zh-hans.json | 1 + crates/ui-egui/locales/zh-hant-formats.json | 1 + crates/ui-egui/locales/zh-hant.json | 1 + crates/ui-egui/src/dialogs/merge.rs | 44 ++++++- docs/gaps.md | 4 +- docs/merge.md | 31 +++++ docs/parity-checklist.md | 11 +- docs/target-app-parity.md | 7 +- 48 files changed, 457 insertions(+), 36 deletions(-) create mode 100644 crates/merge/tests/pair_verification.rs diff --git a/Cargo.lock b/Cargo.lock index 4611917545..3b9c45b27c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3833,6 +3833,7 @@ dependencies = [ "lightcraft-raster", "lightcraft-raw", "lightcraft-scenes", + "log", "rayon", "serde", "thiserror 2.0.21", diff --git a/ROADMAP.md b/ROADMAP.md index 6802f92342..d8af9d69f5 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.3%** of 543 rows (P0 98.3%, P1 94.4%, P2 56.2%) | measured: [parity-checklist.md](docs/parity-checklist.md) recount | | **Feature breadth** (weighted by use) | **~77%** | estimated | | **Ready for real work** (full target) | **~61%** (56–66%) | 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.3%) | 600–1,100 h | [target-app-parity](docs/target-app-parity.md#features) | | ↳ RAW cameras, colour, lens profiles | ~60% | 83% of 1,446 Adobe models decode, 38% 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) | @@ -119,6 +119,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. The original waterfall case (#1765) remains unverified. + - 2026-10-14: Camera-coverage sweep verifies 30 more models on 40 CC0 files, with file and sensor hashes pinned (`docs/raw/coverage.py`: 515 → 545 verified). Eleven candidates excluded after rechecking identity, provenance and camera-image agreement. Phone and drone DNG tone differences remain tracked in #1277. @@ -193,6 +197,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-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-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 | | 2026-10-14 | minor | Localization ~52% → ~55% (mean of the 12 key languages): de, es, fr, ja and uk catalogs filled | diff --git a/crates/engine/src/merge.rs b/crates/engine/src/merge.rs index 76bcfd7f29..d3718f056d 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,41 @@ 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(); + json!({"used": used, "omitted": omitted, "pairs": pairs}) } /// Peak memory of a panorama per pixel of its output (bytes), measured as the peak resident size @@ -473,3 +507,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/merge.rs b/crates/engine/src/tests/merge.rs index ed524ae3d2..fa9c4bde16 100644 --- a/crates/engine/src/tests/merge.rs +++ b/crates/engine/src/tests/merge.rs @@ -177,6 +177,55 @@ 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!(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 ba7e1c63f4..73d48d36fd 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 all 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_with_diagnostics(frames, progress)?; + Ok((cameras, before, after)) +} + +fn register_with_diagnostics(frames: &[Frame], progress: &Progress) -> Result<(Vec>, f64, f64, Vec)> { let n = frames.len(); let work: Vec<(crate::features::Features, f64)> = frames .par_iter() @@ -188,10 +195,10 @@ 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) = camera::match_pairs_with_diagnostics(&feats, &scales); 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 +227,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_with_diagnostics(&frames, progress)?; let used: Vec = (0..n).filter(|&i| cams[i].is_some()).collect(); let fov = fov(&frames, &cams); let projection = match opts.projection { @@ -395,6 +402,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..0ca7310407 100644 --- a/crates/merge/src/pano/camera.rs +++ b/crates/merge/src/pano/camera.rs @@ -58,37 +58,83 @@ 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, +} + /// Match every pair of images. `feats[k]` are in work coordinates scaled by `scales[k]`. pub fn match_pairs(feats: &[Features], scales: &[f64]) -> Vec { + match_pairs_with_diagnostics(feats, scales).0 +} + +/// As [`match_pairs`], retaining rejected pairs as well as accepted ones, in input-pair order. +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) + // Generate input pairs lazily, without a second quadratic vector of pair indices. + let mut results: Vec<(Option, PairDiagnostic)> = (0..n) .into_par_iter() .flat_map_iter(|i| ((i + 1)..n).map(move |j| (i, j))) - .filter_map(|(i, j)| { + .map(|(i, j)| { let m = features::match_features(&feats[i], &feats[j], 0.8); + let mut diagnostic = PairDiagnostic { i, j, matches: m.len(), inliers: None, status: PairStatus::InsufficientMatches }; if m.len() < 12 { - return None; + return (None, diagnostic); } 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 + let Some(fit) = ransac::ransac(Model::Homography, &a, &b, 3.0, 12, (i * 1000 + j) as u64) else { + diagnostic.status = PairStatus::NoModel; + return (None, diagnostic); + }; + diagnostic.inliers = Some(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 (fit.inliers.len() as f64) <= 8.0 + 0.3 * m.len() as f64 { - return None; + diagnostic.status = PairStatus::Rejected; + return (None, diagnostic); } + diagnostic.status = 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 }) + (Some(PairMatch { i, j, h: s_j_inv.mul(&fit.h).mul(&s_i), pts, levels }), diagnostic) }) .collect(); - out.sort_by_key(|p| (p.i, p.j)); - out + results.sort_by_key(|(_, d)| (d.i, d.j)); + let (mut out, mut diagnostics) = (Vec::new(), Vec::with_capacity(results.len())); + for (pair, diagnostic) in results { + log::debug!( + "panorama pair {}-{}: matches={}, inliers={:?}, status={:?}", + diagnostic.i, + diagnostic.j, + diagnostic.matches, + diagnostic.inliers, + diagnostic.status + ); + out.extend(pair); + diagnostics.push(diagnostic); + } + (out, diagnostics) } /// 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 aeecde64cf..38c0b4d84f 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..ccca10dcc2 --- /dev/null +++ b/crates/merge/tests/pair_verification.rs @@ -0,0 +1,125 @@ +//! 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_eq!(recovered.inliers.len(), inliers); + 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); + } + eprintln!("known homography: {inliers}/{n}, rms={:.6}, accepted={}", recovered.rms, !match_pairs(&f, &[1.0; 2]).is_empty()); + // 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!(inliers 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_eq!(r.inliers.len(), 36); + 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)]); + assert_eq!((diagnostics[0].matches, diagnostics[0].inliers, diagnostics[0].status), (104, Some(31), PairStatus::Rejected)); + 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)); +} diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 1eb882f09d..d4798c880b 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "Zahrnuto {used} z {total} fotografií", " ({unsure} with several look-alike files: use Locate)": " ({unsure} s několika podobnými soubory: použijte Najít umístění)", " ({} in Recently Deleted)": " ({} v nedávno odstraněných)", " · {:.0}% clipped": " · {:.0}% oříznutých tónů", diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 52ca94a524..4d5072e2cb 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft nedokázal tyto fotografie zarovnat se zahrnutou sadou. Před sloučením zkontrolujte náhled.", " (library default)": " (výchozí nastavení knihovny)", " (inverted)": " (invertováno)", " · best of its burst": " · nejlepší ze série", diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 79390f1364..8fdb34d492 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "{used} von {total} Fotos enthalten", " ({unsure} with several look-alike files: use Locate)": " ({unsure} mit mehreren ähnlichen Dateien: „Fehlende Datei suchen“ verwenden)", " ({} in Recently Deleted)": " ({} in „Zuletzt gelöscht“)", " · {:.0}% clipped": " · {:.0}% beschnitten", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index e2205db782..7872c12a98 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft konnte diese Fotos nicht an den enthaltenen Fotos ausrichten. Prüfen Sie die Vorschau vor dem Zusammenfügen.", " (library default)": " (Bibliotheksstandard)", " (inverted)": " (umgekehrt)", " · best of its burst": " · bestes Foto der Serie", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 33e5f52fc6..756c59eee8 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "Se incluyen {used} de {total} fotos", " ({unsure} with several look-alike files: use Locate)": " ({unsure} con varios archivos parecidos: usar Localizar)", " ({} in Recently Deleted)": " ({} en Eliminadas recientemente)", " · {:.0}% clipped": " · {:.0}% recortado", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 888af077ff..baa9112fec 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft no pudo alinear estas fotos con el conjunto incluido. Revise la vista previa antes de combinar.", " (library default)": " (predeterminado de la biblioteca)", " (inverted)": " (invertida)", " · best of its burst": " · la mejor de su ráfaga", diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 1daab3dab9..302e93822a 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "{used} / {total} kuvaa mukana", " ({unsure} with several look-alike files: use Locate)": " ({unsure} usealla samannäköisellä tiedostolla: käytä Paikanna)", " ({} in Recently Deleted)": " ({} Äskettäin poistetuissa)", " in {g} group{}": " · ryhmiä: {g}{:.0}", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index e0a8c622a3..3ac4fd473c 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft ei voinut kohdistaa näitä kuvia mukaan otettuihin kuviin. Tarkista esikatselu ennen yhdistämistä.", " (library default)": " (kirjaston oletus)", " (inverted)": " (käänteinen)", " · best of its burst": " · sarjan paras", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 294273781e..6e85647aa4 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "{used} photos sur {total} incluses", " ({unsure} with several look-alike files: use Locate)": " ({unsure} avec plusieurs fichiers similaires : utilisez Localiser)", " ({} in Recently Deleted)": " ({} dans « Supprimés récemment »)", " · {:.0}% clipped": " · {:.0}% écrêté", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 3278d6ccda..7bca7020c8 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft n'a pas pu aligner ces photos avec les photos incluses. Vérifiez l'aperçu avant de fusionner.", " (library default)": " (valeur par défaut de la bibliothèque)", " (inverted)": " (inversée)", " · best of its burst": " · la meilleure de sa rafale", diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 7fc3255221..6ba3e50db0 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "{used} dari {total} foto disertakan", " · {skipped} skipped (file exists)": " · {skipped} dilewati (file sudah ada)", " · {} duplicate{} skipped": " · {} duplikat dilewati{:.0}", " · {} failed: {}": " · {} gagal: {}", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 0d6da9b8fb..7023a6cb52 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft tidak dapat menyelaraskan foto-foto ini dengan foto yang disertakan. Periksa pratinjau sebelum menggabungkan.", " (library default)": " (bawaan pustaka)", " (inverted)": " (dibalik)", " · best of its burst": " · terbaik dari bidikan beruntunnya", diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 7efae90e94..f66e882446 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "Incluse {used} foto su {total}", " ({unsure} with several look-alike files: use Locate)": " ({unsure} con diversi file simili: usa Trova)", " ({} in Recently Deleted)": " ({} in Eliminate di recente)", " · {:.0}% clipped": " · {:.0}% tagliato", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index e159fd47d1..64f577c53d 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft non ha potuto allineare queste foto con quelle incluse. Controlla l'anteprima prima di unire.", " (library default)": " (predefinito della libreria)", " (inverted)": " (invertita)", " · best of its burst": " · la migliore della sua raffica", diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 99c14bf16d..b998ce2863 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "{total} 枚中 {used} 枚を使用", " · {skipped} skipped (file exists)": "・{skipped}件は同名ファイルのためスキップ", " · {} duplicate{} skipped": "・重複{}枚をスキップ{:.0}", " · {} failed: {}": "・{}件失敗:{}", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index e1834555bd..4040b8eeb8 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft はこれらの写真を使用する写真に位置合わせできませんでした。結合前にプレビューを確認してください。", " (library default)": " (ライブラリの既定)", " (inverted)": " (反転)", " · best of its burst": " · 連写内のベスト", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 4603682618..7c8d455633 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "ჩართულია {used} ფოტო {total}-დან", " ({unsure} with several look-alike files: use Locate)": " ({unsure} რამდენიმე მსგავსი ფაილით: გამოიყენეთ „მოძებნა“)", " ({} in Recently Deleted)": " ({} ახლახან წაშლილებში)", " · {:.0}% clipped": " · {:.0}% მოკვეთილია", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 32c4077001..b0fed23e8d 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft-მა ვერ გაასწორა ეს ფოტოები ჩართულ ფოტოებთან. გაერთიანებამდე შეამოწმეთ გადახედვა.", " (library default)": " (ბიბლიოთეკის ნაგულისხმევი)", " (inverted)": " (ინვერსიული)", " · best of its burst": " · საუკეთესო თავის სერიაში", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 20c7f840d6..fc1cbdd9a2 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "Uwzględniono {used} z {total} zdjęć", " ({unsure} with several look-alike files: use Locate)": " ({unsure} wśród kilku podobnych plików: użyj polecenia Zlokalizuj)", " ({} in Recently Deleted)": " ({} w Ostatnio usuniętych)", " · {:.0}% clipped": " · {:.0}% prześwietlonych obszarów", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index adac22e62a..5dc61070a5 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft nie mógł wyrównać tych zdjęć z uwzględnionym zestawem. Sprawdź podgląd przed scaleniem.", " (library default)": " (domyślne ustawienie biblioteki)", " (inverted)": " (odwrócona)", " · best of its burst": " · najlepsze zdjęcie z serii", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index f17f2c0fd4..6efa42ce2e 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "{used} de {total} fotos incluídas", " ({} in Recently Deleted)": " ({} em Excluídos recentemente)", " · {skipped} skipped (file exists)": " · {skipped} ignorada(s) (arquivo existente)", " · {} duplicate{} skipped": " · {} duplicada(s) ignorada(s){:.0}", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index e84fb7615b..5f272ed28b 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "O LightCraft não conseguiu alinhar estas fotos com o conjunto incluído. Revise a prévia antes de mesclar.", " (library default)": " (padrão da biblioteca)", " (inverted)": " (invertida)", " · best of its burst": " · melhor da sequência", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 76b7af4276..5f3ce081a0 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "Включено {used} из {total} фотографий", " ({unsure} with several look-alike files: use Locate)": " (из них с несколькими похожими файлами: {unsure} — используйте «Найти фото»)", " ({} in Recently Deleted)": " ({} в «Недавно удалённых»)", " · {:.0}% clipped": " · обрезано: {:.0}%", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 306804df04..9a2b7d3a3d 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft не удалось выровнять эти фотографии с включёнными. Проверьте предпросмотр перед объединением.", "+ Group": "+ Группа", "+ Rule": "+ Условие", "0: nothing is rejected.": "0: ничего не отклоняется.", diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 9a71a0288c..9a5e74e463 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "{used} av {total} foton inkluderade", " ({unsure} with several look-alike files: use Locate)": " ({unsure} med flera likadana filer: använd Leta upp)", " ({} in Recently Deleted)": " ({} i Nyligen raderade)", " in {g} group{}": " i {g} grupp{}", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 66e69b7ba5..67a83186bb 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft kunde inte justera dessa foton mot de inkluderade fotona. Granska förhandsvisningen innan du slår samman.", " (library default)": " (bibliotekets standard)", " (inverted)": " (inverterad)", " · best of its burst": " · bäst i sin bildserie", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 36022ac1a2..cffb1ee3ac 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "Включено {used} із {total} фотографій", " ({unsure} with several look-alike files: use Locate)": " ({unsure} із кількома схожими файлами: використайте «Знайти»)", " ({} in Recently Deleted)": " ({} у нещодавно видалених)", " · {:.0}% clipped": " · {:.0}% відсічено", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index ee694ed4fe..6c98a00aac 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft не вдалося вирівняти ці фотографії з включеними. Перевірте попередній перегляд перед об'єднанням.", "% of all commits": "% усіх комітів", "A pen's pressure sets the size and flow of the brush": "Натиск пера задає розмір і потік пензля", "150 dpi · sRGB · current edits · fit without cropping": "150 dpi · sRGB · поточні правки · вписано без обрізання", diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index d5e28bff06..7025d7d7d2 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "Đã đưa vào {used} trong tổng số {total} ảnh", " ({unsure} with several look-alike files: use Locate)": " ({unsure} có nhiều tệp trông giống nhau: dùng Định vị)", " ({} in Recently Deleted)": " ({} trong Đã xóa gần đây)", " in {g} group{}": " in {g} group{}", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index e4fb8feb81..bdfe258e3a 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft không thể căn chỉnh các ảnh này với những ảnh được đưa vào. Hãy xem lại bản xem trước trước khi ghép.", " (library default)": " (mặc định thư viện)", " (inverted)": " (đã đảo)", " · best of its burst": " · đẹp nhất trong cụm", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 7406c39b86..621742f3fe 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "已包含 {total} 张照片中的 {used} 张", " · {skipped} skipped (file exists)": " · 已跳过 {skipped} 个(文件已存在)", " · {} duplicate{} skipped": " · 已跳过 {0} 个重复项{1:.0}", " · {} failed: {}": " · {0} 个失败:{1}", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 270af8a625..46abc823d1 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft 无法将这些照片与已包含的照片对齐。合并前请检查预览。", " (library default)": " (图库默认值)", " (inverted)": " (已反相)", " · best of its burst": " · 连拍中的最佳照片", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index d5c4eb279a..ab093248fc 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -1,4 +1,5 @@ { + "{used} of {total} photos included": "已包含 {total} 張照片中的 {used} 張", " · {skipped} skipped (file exists)": " · 已略過 {skipped} 個(檔案已存在)", " · {} duplicate{} skipped": " · 已略過 {} 張重複照片{:.0}", " · {} failed: {}": " · {} 個失敗:{}", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 0408e23ec8..27f2948b6d 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -1,4 +1,5 @@ { + "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft 無法將這些照片與已包含的照片對齊。合併前請檢查預覽。", " (library default)": " (照片庫預設值)", " (inverted)": " (已反轉)", " · best of its burst": " · 連拍中的最佳照片", diff --git a/crates/ui-egui/src/dialogs/merge.rs b/crates/ui-egui/src/dialogs/merge.rs index 4dc744b6d2..2c4037e396 100644 --- a/crates/ui-egui/src/dialogs/merge.rs +++ b/crates/ui-egui/src/dialogs/merge.rs @@ -348,7 +348,7 @@ pub fn poll(app: &mut LightcraftApp, ctx: &egui::Context) { /// 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, @@ -362,7 +362,29 @@ fn added_message(what: &str, info: &Value) -> String { full = full ), _ => crate::i18n::tr_format!("{what} merge added", what = what), - } + }; + if info["omitted"].as_array().is_some_and(|v| !v.is_empty()) { 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.")); + egui::ScrollArea::vertical().id_salt("merge-omitted").max_height(76.0).show(ui, |ui| { + for photo in omitted { + let Some(path) = photo["path"].as_str() else { continue }; + 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 { @@ -425,6 +447,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); @@ -449,7 +472,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.clone()); if let Some(info) = info { let txt = if opts.is_pano() { crate::i18n::tr_format!( @@ -465,6 +490,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); @@ -593,6 +621,16 @@ 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() { + let info = json!({"used": [71, 9], "omitted": [{"id": 401, "path": "waterfall-3.png", "reason": "notRegistered"}]}); + assert_eq!(added_message("Panorama", &info), "Panorama merge added\n2 of 3 photos included"); + // All exposures are individual photos in the HDR panorama result. + let hdr = json!({"used": [71, 9, 401, 3], "omitted": [{"id": 6}, {"id": 12}]}); + assert_eq!(added_message("HDR panorama", &hdr), "HDR panorama merge added\n4 of 6 photos included"); + assert_eq!(added_message("Panorama", &json!({"used": [1, 2], "omitted": []})), "Panorama merge added"); + } + /// 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/docs/gaps.md b/docs/gaps.md index 42d9d437b6..abb0c6bf5b 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**: 85k-photo library opens in 1.7–4.7 s; 100k grid test pending; colour NR at half resolution; at 100k photos stack and album lookups are indexed (an "In a Stack" or "Album" smart album counts in ~14 ms, was 0.6–2.7 s) | ROADMAP log, gpu-pipeline.md | large-catalog users | 15–30 | [target-app-parity](target-app-parity.md#by-dimension) | | 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; 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) | +| 31 | **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`; waterfall originals unavailable | panoramas may omit part of the scene | not estimated without real fixtures | [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 / ⇧Tab (hide the side panels / all panels; Tab moves the keyboard focus here) and F5. Rating `[` `]`, flag cycling (`` ` ``), `\` (Filter Bar), ⌘L (Enable Filters), ⌘⌥⇧C / ⌘⌥⇧V (Copy / Paste Metadata), F1 help, F6 / F7 / F8 (filmstrip, left panel, right panel) are bound; the grid-cycle key is shown beside both grid rows in View (#2500) | [ui-parity](ui-parity.md#shortcuts) | Classic muscle memory | 2–4 | [ui-parity](ui-parity.md) | | 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) | @@ -56,7 +57,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, 31 - **Stability and platforms:** 9, 26, 27 ## Closed recently (kept for calibration) @@ -99,6 +100,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 31 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 e2183583a5..31bb26a468 100644 --- a/docs/merge.md +++ b/docs/merge.md @@ -24,6 +24,34 @@ 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. These fields describe this run; 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. 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. + +This is a diagnostic improvement, not a fix for the reporter's waterfall registration. +The original waterfall photos were unavailable. A three-frame, 800 by 600 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 @@ -75,6 +103,9 @@ scale in `BaselineExposure`; raw sources keep their DNG colour tags (camera RGB) ## Limits (known gaps) +- Pair verification can reject genuine overlaps in moving scenes (#1765). Omitted photos are + reported, but a safer acceptance policy still needs validation on real inputs. + - No lens-distortion model in the panorama bundle adjustment (rectilinear lenses assumed); no 360° wrap-around; flat (translating-camera) scans are fitted with the rotation model. Panoramas and HDR panoramas carry no lens corrections, nor does an HDR whose frames don't share an orientation (they are turned diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 90cfc248f6..02c96f0cc9 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -40,7 +40,7 @@ cited here still exists. Formerly docs/parity.md. | L. Presets (PRE) | 6 | 0 | 1 | 1 | 2/2 (100%) | 2/2 (100%) | | M. Versions & history (VER) | 5 | 0 | 0 | 0 | 1/1 (100%) | 3/3 (100%) | | N. Copy / paste / sync (SYNC) | 5 | 0 | 0 | 0 | 3/3 (100%) | 1/1 (100%) | -| O. Merge (MERGE) | 3 | 1 | 0 | 0 | — | — | +| O. Merge (MERGE) | 1 | 3 | 0 | 0 | — | — | | P. Enhance (ENH) | 0 | 0 | 2 | 0 | — | — | | Q. HDR (HDR) | 2 | 3 | 0 | 0 | — | — | | R. Video (VID) | 0 | 0 | 5 | 1 | — | 0/2 (0%) | @@ -53,9 +53,9 @@ cited here still exists. Formerly docs/parity.md. | Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 78 | 4 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | | Lightroom Classic extras | 41 | 25 | 21 | 8 | — | 24/26 (92%) | -| **Total** | 421 | 65 | 57 | 35 | 196/203 (97%) | 146/161 (91%) | +| **Total** | 419 | 67 | 57 | 35 | 196/203 (97%) | 146/161 (91%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.5%** of 543 in-scope rows — P0 98.3% of 203 · P1 94.4% of 161 · P2 56.7% of 178. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.3%** of 543 in-scope rows — P0 98.3% of 203 · P1 94.4% of 161 · P2 56.2% of 178. ## Top gaps and shortcut notes @@ -353,8 +353,8 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| | LR-MERGE-HDR | HDR merge | P2 | 🟡 | `cmd:merge.hdr`, `cmd:dialog.mergeHdr`, `crates/merge/src/frame.rs` (`Frame::lens`), `crates/merge/src/hdr.rs` | auto align (Lanczos-3 warp), deghost None–High + overlay, click-to-zoom preview (drag pans; the zoom stays while options change), auto settings, float DNG, Create Stack; the DNG keeps the reference frame's embedded lens corrections (tested by `hdr_merge_keeps_the_reference_frames_lens_corrections`); raws without colour matrices of their own (CR2, NEF, ARW…) keep the colour they open with, written as DNG tags (`starting_colour_tags`; the look's chroma curve has no tag; panoramas too), issue #965; the DNG's `AsShotNeutral` is the median of the inputs' vendor white-balance multipliers, issue #1144. Tested on real Sony A7R VI brackets (67 MP, 2026-10-14): frames agree with the merged radiance within ~1 % in all channels, exposure steps match EXIF within 0.03 EV. A clipped highlight of the reference that moved in other frames (a star at 200 mm) stays instead of becoming a black hole, and deghost (≤ 2048 px maps) catches a brighter frame's ghost in a dark sky (`a_clipped_star_of_the_reference_is_not_erased_by_frames_where_it_moved`, `deghost_removes_a_bright_frames_ghost_in_a_dark_sky`). 🟡 because: AI Denoise doesn't run on merged DNGs (Bayer only; Lightroom's does), JPEG brackets are treated as linear (no camera response curve), and every frame is held as 32-bit float (~0.86 GB per 67 MP frame, so 7 frames need ~7 GB); gap 29 | -| LR-MERGE-PANO | Panorama | P2 | ✅ | `cmd:merge.panorama`, `cmd:dialog.mergePanorama` | spherical/cylindrical/perspective + auto (projected with Lanczos-3), boundary warp, auto crop, fill edges (diffusion), DNG whose `AsShotNeutral` is the median of its frames' as-shot white balance (vendor multipliers for CR2, NEF, ARW…), issue #1144; no lens model / 360° wrap | -| LR-MERGE-HDRPANO | HDR panorama | P2 | ✅ | `cmd:merge.hdrPanorama`, `cmd:dialog.mergeHdrPanorama` | brackets grouped by EXIF | +| LR-MERGE-PANO | Panorama | P2 | 🟡 | `cmd:merge.panorama`, `cmd:dialog.mergePanorama` | spherical/cylindrical/perspective + auto (projected with Lanczos-3), boundary warp, auto crop, fill edges (diffusion), DNG whose `AsShotNeutral` is the median of its frames' as-shot white balance (vendor multipliers for CR2, NEF, ARW…), issue #1144; no lens model / 360° wrap; omitted source IDs and filenames reported; genuine moving-scene overlaps can still be rejected (#1765, gap 31) | +| LR-MERGE-HDRPANO | HDR panorama | P2 | 🟡 | `cmd:merge.hdrPanorama`, `cmd:dialog.mergeHdrPanorama` | brackets grouped by EXIF; included/omitted IDs expand each bracket to all source photos; shares the unresolved panorama verification limit (#1765, gap 31) | | LR-MERGE-HEADLESS | Merge with last settings | P2 | ✅ | `cmd:merge.hdrLast`, `cmd:merge.panoramaLast`, `cmd:merge.hdrPanoramaLast`, `cmd:merge.hdrBatch`, `crates/catalog/src/stacks.rs` (`bracket_sets`) | no dialog; the options of the last merge of that kind (defaults the first time), kept in the library's prefs.json so they survive a restart; the HDR / Panorama / HDR Panorama dialogs open with them too (`merge_dialog_remembers_the_last_settings_per_kind`). HDR for Each Bracket Set merges a batch like Lightroom's merge of stacks: one HDR per stack among the photos, then per bracket (photos taken less than a second apart, after the shutter time, at exposures ≥ ½ EV apart; bursts at one exposure are skipped), one after the other in the activity stack (cancelling one stops the rest; a failed set doesn't); CLI `merge hdr-batch FILES…` | ## P. Enhance (ENH) @@ -823,6 +823,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-20 | minor | LR-PRE-PANEL: the preset applied to a photo is marked again (with its Amount slider) on returning to the photo, until the photo is edited further (#2392); status unchanged (✅) | | 2026-10-20 | minor | LR-MASK-OVERLAY: creating, picking, duplicating or adding to a mask shows the overlay a mask slider hid (#1800); status unchanged (✅) | | 2026-10-20 | patch | LRC-LIB-COMPARE, LR-VIEW-SURVEY: in Compare and Survey the Info panel's stars and colour labels and the Set Color Label menu act on the active photo only (they labelled the whole selection), and the panes show the colour label (#2398); statuses unchanged | +| 2026-10-21 | minor | LR-MERGE-PANO and LR-MERGE-HDRPANO marked partial: omissions are reported, but moving-scene verification remains unresolved (#1765) | | 2026-10-20 | patch | LR-VIEW-ZOOM: the 20 ms rule clears a slow-drag verdict only on a drag timed at full size; a drag that drafts small leaves it unchanged, as the code does; status unchanged | | 2026-10-19 | minor | LR-CROP-ASPECT: Lock Aspect Ratio is its own row in Help ▸ Keyboard Shortcuts (`crop.lockAspect`, default A, sharing A with Visualize Spots as a contextual pair); statuses unchanged (✅) (`tests_keymap` `lock_aspect_ratio_is_a_listed_row_on_a`, `a_is_the_aspect_lock_under_crop_and_visualize_spots_elsewhere`) | | 2026-10-19 | patch | LR-LIB-RATING: a rating, flag or label that takes the active photo out of the view makes the photo after it active instead of leaving an unseen photo active (→ then went to the view's first photo), and Shift / Auto Advance doesn't step past it (#2312); status unchanged (✅) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d72c165c41..db2e3e6fc0 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 | **81.6%** of 532 in-scope rows (P0 98.0%, P1 95.2%, P2 50.0%) | **measured**: recount of [parity-checklist.md](parity-checklist.md) rows (✅ 1, 🟡 ½, 🚫 left out), the same rule `cargo xtask parity` uses | +| **Feature breadth**, checklist | **83.3%** of 543 in-scope rows (P0 98.3%, P1 94.4%, P2 56.2%) | **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) | **~61%** (range 56–66%) | 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.0% × 0.804 × colour 0.85 | @@ -46,7 +46,7 @@ phase #85, duplicate Local entries #22, black GPU exports on an Intel iGPU #78). | Dimension | Breadth | Ready for real work | Remaining | Doc | |---|---:|---:|---:|---| -| Features (weighted areas below) | ~77% (checklist 81.1%, measured) | ~61% | 600–1,100 h | [Features](#features) | +| Features (weighted areas below) | ~77% (checklist 83.3%, measured) | ~61% | 600–1,100 h | [Features](#features) | | ↳ RAW cameras, colour and lens profiles (part of features) | 83% of Adobe's 1,446 models decode (38% verified), measured | ~56% | 255–480 h | [raw-parity.md](raw-parity.md) | | UI/UX fidelity | ~85% | ~70% | 32–54 h | [ui-parity.md](ui-parity.md) | | File formats (non-raw: images, sidecars, presets, catalogs) | ~85% | ~70% | 30–55 h | [file-format-parity.md](file-format-parity.md) | @@ -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 | @@ -303,6 +303,7 @@ P2 items 12–25 h; look tuning, performance, packaging, hardening 25–45 h. | 2026-10-19 | patch | Stability note: tests run in CI on Linux x64 (every PR) as well as FreeBSD; macOS and Windows remain (gap 9) | | 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-14 | minor | Localization ~52% → ~55% (mean of the 12 key languages): de, es, fr, ja and uk catalogs filled | | 2026-10-12 | minor | UI/UX remaining 34–58 h → 32–54 h (canvas tools by keyboard); headline numbers unchanged | | 2026-10-14 | minor | Merge and HDR: merge 100% → 88% (LR-MERGE-HDR ✅ → 🟡 after testing on real 67 MP brackets; gap 29); area percentages unchanged | From 580a13e303bcffb5210dfa7781351845e95ee8bd Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Thu, 29 Oct 2026 00:43:36 +0100 Subject: [PATCH 07/63] LR-MERGE-PANO: borrow preview diagnostics during redraw Keep the summary and omission display while avoiding a clone of every pair record. The five merge dialog tests and touched-crate clippy pass. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/merge.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/merge.rs b/crates/ui-egui/src/dialogs/merge.rs index 2c4037e396..7bdcc48ca5 100644 --- a/crates/ui-egui/src/dialogs/merge.rs +++ b/crates/ui-egui/src/dialogs/merge.rs @@ -474,7 +474,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, opts: &mut MergeDialog) } // 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.clone()); + 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!( @@ -491,7 +491,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, opts: &mut MergeDialog) }; ui.label(egui::RichText::new(txt).color(t.text_dim)); if opts.is_pano() { - omitted_photos(ui, &info); + omitted_photos(ui, info); } } }); From bb6864066459c0fa56d9dba05e328e5611f2c721 Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:40:17 +0100 Subject: [PATCH 08/63] Review: ignore an empty or relative HOME, APPDATA or XDG_CONFIG_HOME for the settings folder (#2572) --- crates/engine/src/config.rs | 50 ++++++++++++++++++++++++++++++++----- docs/whats-new.md | 3 +++ 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/config.rs b/crates/engine/src/config.rs index b3ded1fbd7..efdd4afa2a 100644 --- a/crates/engine/src/config.rs +++ b/crates/engine/src/config.rs @@ -8,7 +8,9 @@ //! `%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 @@ -48,6 +50,9 @@ pub fn config_dir() -> Option { } /// `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)); @@ -55,12 +60,12 @@ fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option, p if let Some(dir) = portable() { return Some(dir); } + // Only a rooted folder: an empty or relative one would be under the launch directory (#2572). + let folder = |name: &str| env(name).map(PathBuf::from).filter(|dir| dir.has_root()); 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")), } } @@ -253,6 +258,39 @@ 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" + ); + } + } + + /// 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/docs/whats-new.md b/docs/whats-new.md index f7eaf1f436..dd71269062 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -90,6 +90,9 @@ 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. ### Reliability - Opening a library no longer writes through a link left at the lock's owner note (`catalog.lock.owner`): the link From d1d55c4a2d18c1abc45a613af0ac84aa7dea388d Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:26:19 +0100 Subject: [PATCH 09/63] Review: on Windows the settings folder needs a fully qualified APPDATA (#2572) A rooted but drive-relative APPDATA such as \foo or /foo, or C:foo, follows the current drive or its current folder, so the launch drive could still choose where the settings folder and crash log go. APPDATA must now be a drive path like C:\... or a UNC or device path; HOME and XDG_CONFIG_HOME must start with /. The check follows each platform's rules rather than the host's, and the Windows tests use real Windows paths. --- crates/engine/src/config.rs | 43 +++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/config.rs b/crates/engine/src/config.rs index efdd4afa2a..116a886824 100644 --- a/crates/engine/src/config.rs +++ b/crates/engine/src/config.rs @@ -17,7 +17,7 @@ //! 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; @@ -60,8 +60,9 @@ fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option, p if let Some(dir) = portable() { return Some(dir); } - // Only a rooted folder: an empty or relative one would be under the launch directory (#2572). - let folder = |name: &str| env(name).map(PathBuf::from).filter(|dir| dir.has_root()); + // 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 => folder("HOME").map(|h| h.join("Library/Application Support/LightCraft")), Platform::Windows => folder("APPDATA").map(|a| a.join("LightCraft")), @@ -69,6 +70,23 @@ fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option, p } } +/// 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'/'), + } +} + /// This process's portable data folder, if a marker sits beside its executable and the folder can be /// written. Resolved once: the check creates the folder and writes a probe file. fn portable_dir() -> Option { @@ -197,7 +215,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); } @@ -248,9 +267,9 @@ mod config_tests { #[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] { @@ -283,6 +302,18 @@ mod config_tests { } } + /// #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() { From 779a36e7152df400c999e4e585777d664886ddfb Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Sat, 31 Oct 2026 16:13:04 +0100 Subject: [PATCH 10/63] LC-MERGE: always report final panorama inclusion counts Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/merge.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/merge.rs b/crates/ui-egui/src/dialogs/merge.rs index 415f189771..f846fcbd33 100644 --- a/crates/ui-egui/src/dialogs/merge.rs +++ b/crates/ui-egui/src/dialogs/merge.rs @@ -368,7 +368,7 @@ fn added_message(what: &str, info: &Value) -> String { ), _ => crate::i18n::tr_format!("{what} merge added", what = what), }; - if info["omitted"].as_array().is_some_and(|v| !v.is_empty()) { format!("{message}\n{}", inclusion_summary(info)) } else { message } + if info["used"].is_array() && info["omitted"].is_array() { format!("{message}\n{}", inclusion_summary(info)) } else { message } } fn inclusion_summary(info: &Value) -> String { @@ -633,7 +633,7 @@ mod tests { // All exposures are individual photos in the HDR panorama result. let hdr = json!({"used": [71, 9, 401, 3], "omitted": [{"id": 6}, {"id": 12}]}); assert_eq!(added_message("HDR panorama", &hdr), "HDR panorama merge added\n4 of 6 photos included"); - assert_eq!(added_message("Panorama", &json!({"used": [1, 2], "omitted": []})), "Panorama merge added"); + assert_eq!(added_message("Panorama", &json!({"used": [1, 2], "omitted": []})), "Panorama merge added\n2 of 2 photos included"); } /// Issue #1455: a panorama held to the computer's memory, or to the largest size, says so. From 3a8dbe9ccbe7d2017c4d869235e4b51f7e8138cc Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:21:06 +0100 Subject: [PATCH 11/63] LR-PROF-CAMERACOLOR: exercise as-shot WB with vignetted CR3 geometry Build the orientation fixture with the same as-shot transform used by pooled calibration, and assert the fixture actually exercises nonuniform channel gains. Production code remains unchanged. Co-authored-by: Codex --- crates/engine/src/camera_preview/tests.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index c67826b263..256b6facfc 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -2841,7 +2841,9 @@ fn cr3_vignetting_precedes_profile_geometry_in_every_orientation() { fn check_cr3_profile_geometry_orientation(vignetted: bool) { use lightcraft_raw::{BlackLevel, RawData, Rect}; let (w, h) = (416, 288); - let scene = profile_geometry_scene(w, h); + let mut scene = profile_geometry_scene(w, h); + // Leave headroom for nonuniform WB and source-position vignetting in the generated JPEG. + scene.map_in_place(|p| p.map(|v| v * 0.3)); let mut raw = raw_of(RawFormat::Cr3, "Synthetic", "Uncalibrated", Default::default()); raw.width = w; raw.height = h; @@ -2853,7 +2855,8 @@ fn check_cr3_profile_geometry_orientation(vignetted: bool) { raw.crop = Rect::new(16, 16, 384, 256); raw.linearized = true; raw.wb_multipliers = Some([1.25, 1.0, 0.8]); - let transform = lightcraft_raw::color::camera_transform(&raw, D65); + let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); + assert!(transform.wb.windows(2).any(|v| (v[0] - v[1]).abs() > 0.01), "the fixture must exercise nonuniform as-shot WB"); assert!(transform.matrix_is_fallback); let mut sensor = sensor_proxy(&raw, 2, 384).unwrap(); assert_eq!((sensor.width, sensor.height), (384, 256)); @@ -2870,6 +2873,13 @@ fn check_cr3_profile_geometry_orientation(vignetted: bool) { target.map_in_place(|p| p.map(|v| v.powf(0.7))); let to_srgb = lightcraft_color::SRGB.from_xyz().mul(&REC2020.to_xyz()); let srgb = |v: f32| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + let jpeg_range = target + .data + .iter() + .filter(|p| p.iter().all(|v| v.is_finite())) + .flat_map(|p| to_srgb.apply_f32(*p)) + .fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), v| (lo.min(v), hi.max(v))); + assert!(jpeg_range.0 >= 0.0 && jpeg_range.1 <= 1.0, "the generated reference must not clip: {jpeg_range:?}"); let pixels: Vec = target.data.iter().flat_map(|p| to_srgb.apply_f32(*p).map(|v| (srgb(v).clamp(0.0, 1.0) * 255.0).round() as u8)).collect(); let image = lightcraft_codecs::EncodeImage::new(384, 256, 3, lightcraft_codecs::Samples::U8(&pixels)); let jpeg = lightcraft_codecs::encode_jpeg(&image, 98, lightcraft_codecs::ChromaSubsampling::S444, &Default::default()).unwrap(); @@ -2896,7 +2906,8 @@ fn check_cr3_profile_geometry_orientation(vignetted: bool) { ); let mut displayed = aligned.clone(); displayed.map_in_place(|p| p.map(|v| v.powf(0.7))); - assert!(geometry_rms(&displayed, &reference) < 0.009, "orientation {exif}: WB exactly once and matching frames"); + let rms = geometry_rms(&displayed, &reference); + assert!(rms < 0.009, "orientation {exif}: WB exactly once and matching frames: {rms}"); let oriented_target = target.clone().into_oriented(orientation); let expected = reference_at(&oriented_target, &aligned); assert!(geometry_rms(&displayed, &expected) < 0.009, "orientation {exif}: absolute oriented ground truth"); From 71ceb01b5cdb2345592f895d3f85f8bb279d075c Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:31:15 +0100 Subject: [PATCH 12/63] LR-PROF-CAMERACOLOR: compare geometry proposals on common edges Judge every profile proposal against the original on the same edge intersection during search and holdout validation. Keep the established framing-only path and thresholds; prevent framing-only diagnostic score provenance. Co-authored-by: Codex --- crates/engine/src/camera_preview/proxy.rs | 50 +++++++++++++++++------ crates/engine/src/camera_preview/tests.rs | 34 +++++++++++++++ docs/cr3-profile-alignment.md | 9 ++-- 3 files changed, 77 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/camera_preview/proxy.rs b/crates/engine/src/camera_preview/proxy.rs index 837f1ee70e..c9403e83a6 100644 --- a/crates/engine/src/camera_preview/proxy.rs +++ b/crates/engine/src/camera_preview/proxy.rs @@ -202,7 +202,7 @@ impl Cr3Framing { /// A separate third of the edges must confirm a substantial improvement and a close match. /// A weak, flat or unrelated preview leaves the sensor framing unchanged. pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Option { - estimate_framing_against(sensor, reference, sensor, None) + estimate_framing_against(sensor, reference, None, None) } #[cfg(test)] @@ -227,7 +227,7 @@ pub(super) fn geometry_framed_scores() -> Option<[f64; 4]> { /// Judge a proposed lens warp and bounded framing against the original sensor on fixed /// training and independent held-out edges. Lens-only correction may be sufficient. -fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: &Rgb32f, framed: Option<&Rgb32f>) -> Option { +fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: Option<&Rgb32f>, framed: Option<&Rgb32f>) -> Option { #[cfg(test)] { LAST_GEOMETRY_SCORES.set(None); @@ -236,6 +236,8 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: &Rgb3 if sensor.width.checked_mul(sensor.height)? != sensor.data.len() || reference.width.checked_mul(reference.height)? != reference.data.len() { return None; } + let proposal = original.is_some(); + let original = original.unwrap_or(sensor); let sensor = fit(sensor, PROXY, PROXY, Filter::Box); let (w, h) = (sensor.width, sensor.height); if w < 16 || h < 16 { @@ -300,8 +302,8 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: &Rgb3 if !length.is_finite() || length <= 0.01 { continue; } - // Comparing against framed CR3 fallback uses exactly the same valid - // edges on both sides, including the same reference weights. + // Pairwise comparisons use exactly the same valid edges on both sides, + // including the same reference weights. if let Some((other, map)) = support { let (ox, oy) = map.source(x, y, w, h); if ox < 1.5 || oy < 1.5 || ox > w as f32 - 1.5 || oy > h as f32 - 1.5 { @@ -320,18 +322,26 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: &Rgb3 } (valid >= 64 && valid * 5 >= total * 4 && weight > 0.0).then_some(agreement / weight) }; + // Only profile proposals use common-support improvement during candidate selection. + // The public CR3 framing fallback retains its original independent-support search. let before = score(&original_gradients, Cr3Framing::IDENTITY, false, None)?; - let mut best = (score(&gradients, Cr3Framing::IDENTITY, false, None).unwrap_or(-1.0), Cr3Framing::IDENTITY); + let training = |framing| -> Option<(f64, f64)> { + let after = score(&gradients, framing, false, proposal.then_some((&original_gradients, Cr3Framing::IDENTITY)))?; + let before = if proposal { score(&original_gradients, Cr3Framing::IDENTITY, false, Some((&gradients, framing)))? } else { before }; + (!proposal || (after >= 0.9 && after >= before + 0.04)).then_some((before, after)) + }; + let initial = training(Cr3Framing::IDENTITY); + let mut best = (initial.map_or(-1.0, |v| v.1), Cr3Framing::IDENTITY, initial.map_or(before, |v| v.0)); // At most 10% zoom and two proxy pixels of translation; a coarse search followed by one // local refinement prevents unbounded optimisation on the photograph's contents. for s in -10..=10 { for tx in -4..=4 { for ty in -4..=4 { let framing = Cr3Framing { scale: 1.0 + s as f32 * 0.01, offset: [tx as f32 * 0.5 / w as f32, ty as f32 * 0.5 / h as f32] }; - if let Some(value) = score(&gradients, framing, false, None) + if let Some((before, value)) = training(framing) && value > best.0 { - best = (value, framing); + best = (value, framing, before); } } } @@ -347,18 +357,26 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: &Rgb3 if !(0.9..=1.1).contains(&framing.scale) || framing.offset[0].abs() > 2.0 / w as f32 || framing.offset[1].abs() > 2.0 / h as f32 { continue; } - if let Some(value) = score(&gradients, framing, false, None) + if let Some((before, value)) = training(framing) && value > best.0 { - best = (value, framing); + best = (value, framing, before); } } } } - let (held_before, held_after) = (score(&original_gradients, Cr3Framing::IDENTITY, true, None)?, score(&gradients, best.1, true, None)?); + if proposal && best.0 < 0.9 { + return None; + } + let (held_before, held_after) = ( + score(&original_gradients, Cr3Framing::IDENTITY, true, proposal.then_some((&gradients, best.1)))?, + score(&gradients, best.1, true, proposal.then_some((&original_gradients, Cr3Framing::IDENTITY)))?, + ); #[cfg(test)] - LAST_GEOMETRY_SCORES.set(Some([before, best.0, held_before, held_after])); - if best.0 < 0.9 || best.0 < before + 0.04 || held_after < 0.9 || held_after < held_before + 0.04 { + if proposal { + LAST_GEOMETRY_SCORES.set(Some([best.2, best.0, held_before, held_after])); + } + if best.0 < 0.9 || best.0 < best.2 + 0.04 || held_after < 0.9 || held_after < held_before + 0.04 { return None; } if let Some(framed) = &framed_gradients { @@ -378,6 +396,12 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: &Rgb3 Some(best.1) } +/// Exercise the proposal gate independently of lens-map construction in regressions. +#[cfg(test)] +pub(super) fn estimate_profile_framing(candidate: &Rgb32f, reference: &Rgb32f, original: &Rgb32f) -> Option { + estimate_framing_against(candidate, reference, Some(original), None) +} + /// The sensor proxy and its clip mask (same size), both moved to the camera JPEG's framing. fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rgb32f, Rgb32f) { let Some(framing) = estimate_cr3_framing(&sensor, reference) else { return (sensor, clipped) }; @@ -446,7 +470,7 @@ fn align_profile_geometry_against( warp.lens_dist = 1.0; let source = |x, y| warp.corrected_to_source(lightcraft_geom::Point::new(x, y), 1); let candidate = resample_correspondence(sensor, source); - let framing = estimate_framing_against(&candidate, reference, sensor, baseline)?; + let framing = estimate_framing_against(&candidate, reference, Some(sensor), baseline)?; let mask = resample_correspondence(clipped, source); let frame = |x: f64, y: f64| { let (x, y) = framing.source(x as f32, y as f32, sensor.width, sensor.height); diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index 256b6facfc..e0976ea446 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -2618,6 +2618,40 @@ fn profile_geometry_scene(w: usize, h: usize) -> Rgb32f { sensor } +#[test] +fn external_profile_geometry_cannot_improve_by_dropping_disagreeing_borders() { + // At the scoring resolution, about 14% of side-strip edges disagree. A candidate + // that merely discards those strips has no improvement on their common support. + let reference = profile_geometry_scene(96, 64); + let mut original = reference.clone(); + let mut candidate = reference.clone(); + for y in 0..reference.height { + for x in 0..reference.width { + if !(7..89).contains(&x) { + let i = y * reference.width + x; + original.data[i] = reference.data[i].map(|v| 0.8 - v); + candidate.data[i] = [f32::NAN; 3]; + } + } + } + assert!( + super::proxy::estimate_profile_framing(&candidate, &reference, &original).is_none(), + "discarding mismatched edges must not manufacture the required 0.04 improvement" + ); +} + +#[test] +fn cr3_framing_only_does_not_report_profile_gate_scores() { + let original = profile_geometry_scene(384, 256); + let candidate = profile_geometry_target(&original, &synthetic_profile_lens(), Cr3Framing::IDENTITY); + // Seed real proposal diagnostics, then ensure the framing-only call clears them. + assert!(super::proxy::estimate_profile_framing(&candidate, &candidate, &original).is_some()); + assert!(super::proxy::geometry_gate_scores().is_some()); + let _ = estimate_cr3_framing(&original, &original); + assert!(super::proxy::geometry_gate_scores().is_none()); + assert!(super::proxy::geometry_framed_scores().is_none()); +} + /// Return a deliberately strong radial warp for synthetic correspondence tests. fn synthetic_profile_lens() -> lightcraft_develop::EmbeddedLens { lightcraft_develop::EmbeddedLens { diff --git a/docs/cr3-profile-alignment.md b/docs/cr3-profile-alignment.md index c3937d5fe5..62ddbf80b3 100644 --- a/docs/cr3-profile-alignment.md +++ b/docs/cr3-profile-alignment.md @@ -5,8 +5,8 @@ sensor/JPEG training pairs. It reuses the guarded correspondence algorithm propo #2675, with an additional comparison against CR3’s existing framing fallback. It does not change CR3 decoding or the lens warp applied when developing the photograph. -A resolved external lens profile may propose geometry only for file-local colour calibration, -with a fallback camera matrix and no in-file lens warp. The sensor, sensor clip mask, and embedded JPEG are +A resolved external lens profile may propose geometry only for file-local colour calibration +and pooled camera-profile pairs, with a fallback camera matrix and no in-file lens warp. The sensor, sensor clip mask, and embedded JPEG are oriented together before evaluating the already oriented lens profile. White balance and baseline exposure are applied exactly once before geometry assessment. @@ -17,7 +17,10 @@ values. Accepted geometry moves the sensor and clip mask together; invalid borde CR3 proposals must also preserve or improve agreement against the existing framed fallback on both training and held-out edges, compared on the exact intersection of valid edges with the same reference weights. The published minimum 0.04 improvement over the unframed sensor -is retained separately; the fallback comparison adds no extra improvement threshold. Rejected or absent geometry takes the existing CR3 framing path. All subsequent colour, +is retained separately, using the exact intersection of original and candidate edges and the same +reference weights for each candidate during training and for the held-out check. The fallback +comparison adds no extra improvement threshold. Rejected or absent geometry takes the existing +CR3 framing path. All subsequent colour, tone, hue/saturation, clipping, and held-out acceptance gates stay unchanged. The proposal reaches file-local colour and tone, pooled camera-profile pairs, and colour tags From eee56f12c2f2b88b40d12a5ce0c47c8c332749fa Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:12:23 +0100 Subject: [PATCH 13/63] LR-PROF-CAMERACOLOR: verify CR3 geometry mask coverage Retain and check the complete expected valid crop and returned masks in both profile-geometry acceptance tests, including finite aligned samples so RMS cannot hide NaN losses. Explicitly guard the diagnostic original-score read with the profile-warp flag while retaining framed-score flow. The pooled eligibility wording and common-support margin fix are already present. Focused geometry tests and full cargo xtask ci pass with Rust 1.95.0, Apple M5 Max Metal and WASM. Temporary output-loss and mask-loss counterexamples are caught by the strengthened tests. Production geometry and acceptance thresholds are unchanged. Co-authored-by: Codex --- crates/engine/src/camera_preview/tests.rs | 31 ++++++++++++++++++----- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index e0976ea446..8cc4b2ebe6 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -2676,6 +2676,20 @@ fn profile_geometry_target(sensor: &Rgb32f, lens: &lightcraft_develop::EmbeddedL }) } +/// Check the full known valid crop, so the RMS cannot hide lost samples behind NaNs. +fn assert_profile_geometry_mask(aligned: &Rgb32f, aligned_mask: &Rgb32f, expected_mask: &Rgb32f) { + assert_eq!((aligned.width, aligned.height), (expected_mask.width, expected_mask.height)); + assert_eq!((aligned_mask.width, aligned_mask.height), (expected_mask.width, expected_mask.height)); + assert_eq!(aligned.data.len(), expected_mask.data.len()); + assert_eq!(aligned_mask.data.len(), expected_mask.data.len()); + for (i, ((pixel, mask), expected)) in aligned.data.iter().zip(&aligned_mask.data).zip(&expected_mask.data).enumerate() { + // The barrel warp and inward framing used below keep the entire crop valid. + assert_eq!(*expected, [0.0; 3], "ground-truth crop must be valid and unclipped at {i}"); + assert!(pixel.iter().all(|v| v.is_finite()), "alignment lost a valid ground-truth sample at {i}"); + assert_eq!(*mask, *expected, "valid aligned pixels must retain the zero clip mask at {i}"); + } +} + /// Measure RMS colour error over finite, mutually valid proxy samples. fn geometry_rms(a: &Rgb32f, b: &Rgb32f) -> f64 { let mut error = 0.0; @@ -2701,8 +2715,10 @@ fn external_profile_geometry_aligns_lens_and_framing_before_colour() { let mut jpeg = expected.clone(); jpeg.map_in_place(|p| p.map(|v| v.powf(0.7))); let mask = Rgb32f::new(sensor.width, sensor.height); - let (aligned, _) = align_profile_geometry(&sensor, &mask, &jpeg, &lens, lightcraft_geom::Orientation::Normal) + let expected_mask = profile_geometry_target(&mask, &lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }); + let (aligned, aligned_mask) = align_profile_geometry(&sensor, &mask, &jpeg, &lens, lightcraft_geom::Orientation::Normal) .expect("lens and bounded framing pass independent geometry gates"); + assert_profile_geometry_mask(&aligned, &aligned_mask, &expected_mask); assert!(geometry_rms(&aligned, &expected) < 0.008, "the training sensor is correctly registered despite a nonlinear camera tone"); assert!(geometry_rms(&sensor, &expected) > 0.05, "synthetic mismatch is material"); } @@ -2714,8 +2730,10 @@ fn external_profile_geometry_accepts_lens_only_and_rejects_unrelated_or_already_ let lens = synthetic_profile_lens(); let expected = profile_geometry_target(&sensor, &lens, Cr3Framing::IDENTITY); let mask = Rgb32f::new(sensor.width, sensor.height); - let (aligned, _) = align_profile_geometry(&sensor, &mask, &expected, &lens, lightcraft_geom::Orientation::Normal) + let expected_mask = profile_geometry_target(&mask, &lens, Cr3Framing::IDENTITY); + let (aligned, aligned_mask) = align_profile_geometry(&sensor, &mask, &expected, &lens, lightcraft_geom::Orientation::Normal) .expect("lens alone aligns; no improvement over its own framing is required"); + assert_profile_geometry_mask(&aligned, &aligned_mask, &expected_mask); assert!(geometry_rms(&aligned, &expected) < 0.001); assert!( align_profile_geometry(&sensor, &mask, &sensor, &lens, lightcraft_geom::Orientation::Normal).is_none(), @@ -3092,14 +3110,13 @@ fn corpus_cr3_profile_geometry_diagnostics() { let plain = proxies(&raw, &bytes, &transform, PROXY, 0.0, lens.as_ref(), plain_correction.as_ref()); let chosen = proxies(&raw, &bytes, &transform, PROXY, 0.0, lens.as_ref(), correction.as_ref()); let name = path.file_name().unwrap().to_string_lossy(); - let Some((plain, chosen)) = - diagnostic_proxies_or_report(&name, &raw, correction.as_ref().is_some_and(|l| l.warp.is_some()), plain, chosen, &mut report) - else { + let profile_warp = correction.as_ref().is_some_and(|l| l.warp.is_some()); + let Some((plain, chosen)) = diagnostic_proxies_or_report(&name, &raw, profile_warp, plain, chosen, &mut report) else { std::fs::write(output.join("geometry.tsv"), &report).unwrap(); continue; }; let framed_scores = super::proxy::geometry_framed_scores(); - let original_scores = super::proxy::geometry_gate_scores(); + let original_scores = if profile_warp { super::proxy::geometry_gate_scores() } else { None }; let accepted = plain.0.data.iter().flatten().zip(chosen.0.data.iter().flatten()).any(|(a, b)| a.to_bits() != b.to_bits()); let pairs = |v: &(Rgb32f, Rgb32f, Vec)| { let sensor = without_clipped(&v.0, &v.2).unwrap_or_else(|| v.0.clone()); @@ -3111,7 +3128,7 @@ fn corpus_cr3_profile_geometry_diagnostics() { "{name}\t{}\t{:?}\t{}\t{accepted}\t{:.6}\t{:.6}\t{}\t{}\t{}\t{}\t{before}\t{after}\t{framed_scores:?}\t{original_scores:?}\tmeasured\t\n", raw.metadata.model.as_deref().unwrap_or(""), raw.orientation, - correction.as_ref().is_some_and(|l| l.warp.is_some()), + profile_warp, alignment(&plain.0, &plain.1), alignment(&chosen.0, &chosen.1), structure_agrees(&plain.0, &plain.1), From e6ff85d30d069e5757b751d489c9bc76b5adc09f Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Tue, 3 Nov 2026 15:47:27 +0100 Subject: [PATCH 14/63] LR-MERGE-PANO: drop the dialog's preview when its photos change Merge with Last Settings and the next set of an HDR batch replaced the dialog's photos but kept its preview, which is kept while its options match: an open dialog went on showing the old photos' count and omitted files. Setting the photos now drops that preview and cancels its task, as opening the dialog does. Reported by CodeRabbit. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/merge.rs | 28 +++++++++++++++++----------- crates/ui-egui/src/tests/activity.rs | 23 +++++++++++++++++++++++ 2 files changed, 40 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs/merge.rs b/crates/ui-egui/src/dialogs/merge.rs index f846fcbd33..ccdd866ce0 100644 --- a/crates/ui-egui/src/dialogs/merge.rs +++ b/crates/ui-egui/src/dialogs/merge.rs @@ -160,22 +160,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 +215,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(|_| ()) } diff --git a/crates/ui-egui/src/tests/activity.rs b/crates/ui-egui/src/tests/activity.rs index b353405ffc..0b1a7654e4 100644 --- a/crates/ui-egui/src/tests/activity.rs +++ b/crates/ui-egui/src/tests/activity.rs @@ -410,6 +410,29 @@ 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); +} + /// 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] From b0cb23acb643e8eaeb3aaedac2589ed29c12abd9 Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Thu, 5 Nov 2026 10:37:08 +0100 Subject: [PATCH 15/63] LR-MERGE-PANO: refresh the parity summary after the merge Co-Authored-By: Claude Opus 5.5 --- docs/parity-checklist.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index a665491d5a..0c45468b42 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -31,7 +31,7 @@ cited here still exists. Formerly docs/parity.md. | C. Views & navigation (VIEW) | 16 | 1 | 1 | 0 | 9/9 (100%) | 4/4 (100%) | | D. Search & filter (FILT) | 11 | 1 | 1 | 0 | 4/4 (100%) | 4/4 (100%) | | E. Metadata (META) | 5 | 1 | 0 | 0 | 2/2 (100%) | 2/2 (100%) | -| F. Edit panel — global adjustments (EDIT) | 40 | 6 | 3 | 1 | 24/28 (86%) | 13/14 (93%) | +| F. Edit panel — global adjustments (EDIT) | 41 | 5 | 3 | 1 | 25/28 (89%) | 13/14 (93%) | | G. Profiles (PROF) | 7 | 1 | 3 | 0 | 3/4 (75%) | 3/3 (100%) | | H. Crop & rotate (CROP) | 10 | 1 | 0 | 1 | 8/8 (100%) | 2/3 (67%) | | I. Remove / healing (REM) | 8 | 1 | 2 | 2 | 4/4 (100%) | 2/3 (67%) | @@ -53,9 +53,9 @@ cited here still exists. Formerly docs/parity.md. | Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 78 | 4 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | | Lightroom Classic extras | 41 | 25 | 21 | 8 | — | 24/26 (92%) | -| **Total** | 417 | 69 | 57 | 35 | 192/203 (95%) | 146/161 (91%) | +| **Total** | 416 | 70 | 57 | 35 | 193/203 (95%) | 146/161 (91%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.1%** of 543 in-scope rows — P0 97.3% of 203 · P1 94.4% of 161 · P2 56.7% of 178. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.1%** of 543 in-scope rows — P0 97.5% of 203 · P1 94.4% of 161 · P2 56.2% of 178. ## Top gaps and shortcut notes From 3e0a2a09c9cb5a5a3a607ccfb0f9600c36ebd5b2 Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Thu, 5 Nov 2026 16:00:17 +0100 Subject: [PATCH 16/63] LR-MERGE-PANO: refresh the parity summary after the merge Co-Authored-By: Claude Opus 5.5 --- docs/parity-checklist.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index ecaf35868f..4c3ae0a007 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -31,7 +31,7 @@ cited here still exists. Formerly docs/parity.md. | C. Views & navigation (VIEW) | 16 | 1 | 1 | 0 | 9/9 (100%) | 4/4 (100%) | | D. Search & filter (FILT) | 11 | 1 | 1 | 0 | 4/4 (100%) | 4/4 (100%) | | E. Metadata (META) | 5 | 1 | 0 | 0 | 2/2 (100%) | 2/2 (100%) | -| F. Edit panel — global adjustments (EDIT) | 41 | 5 | 3 | 1 | 25/28 (89%) | 13/14 (93%) | +| F. Edit panel — global adjustments (EDIT) | 42 | 5 | 3 | 1 | 25/28 (89%) | 14/15 (93%) | | G. Profiles (PROF) | 7 | 1 | 3 | 0 | 3/4 (75%) | 3/3 (100%) | | H. Crop & rotate (CROP) | 10 | 1 | 0 | 1 | 8/8 (100%) | 2/3 (67%) | | I. Remove / healing (REM) | 8 | 1 | 2 | 2 | 4/4 (100%) | 2/3 (67%) | @@ -53,9 +53,9 @@ cited here still exists. Formerly docs/parity.md. | Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 78 | 4 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | | Lightroom Classic extras | 41 | 26 | 21 | 8 | — | 24/27 (89%) | -| **Total** | 417 | 70 | 57 | 35 | 192/203 (95%) | 146/162 (90%) | +| **Total** | 417 | 71 | 57 | 35 | 193/203 (95%) | 147/163 (90%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.1%** of 544 in-scope rows — P0 97.3% of 203 · P1 94.1% of 162 · P2 56.7% of 178. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.0%** of 545 in-scope rows — P0 97.5% of 203 · P1 94.2% of 163 · P2 56.2% of 178. ## Top gaps and shortcut notes From 25d29d7bb3f74039a106722c14539d02a30dad60 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:03:41 +0100 Subject: [PATCH 17/63] LR-PROF-CAMERACOLOR: publish known activity totals before worker dispatch A delayed Find Similar worker left its visible task total at zero although the search plan already knew the count. Initialize tracked activity progress synchronously before spawning the worker; Find Similar, Missing Photos and Reload pass the work counts they already computed without file-system IO. Subsequent progress and cancellation still run through the existing handle. A per-app test-only gate holds the next worker before its first instruction. The regression fails deterministically on the old initialization (0 instead of 12) and verifies the known count, no UI-thread IO, exact reads and cleanup. Existing assertions/timeouts remain unchanged. All three caller suites and all eight local CI gates pass with Rust 1.95.0, actual Metal and WASM on the exact committed tree. No workflow, cache, calibration or photo-data changes. Co-authored-by: Codex --- crates/ui-egui/src/find_similar.rs | 3 +-- crates/ui-egui/src/missing_sweep.rs | 3 +-- crates/ui-egui/src/reload.rs | 3 +-- crates/ui-egui/src/tasks.rs | 13 +++++++++++- crates/ui-egui/src/tests/find_similar.rs | 26 ++++++++++++++++++++++++ 5 files changed, 41 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/find_similar.rs b/crates/ui-egui/src/find_similar.rs index d96424317c..77d80a23b7 100644 --- a/crates/ui-egui/src/find_similar.rs +++ b/crates/ui-egui/src/find_similar.rs @@ -41,7 +41,6 @@ fn start(app: &mut LightcraftApp, p: &Value, end: impl FnOnce(&mut LightcraftApp let (flag, stopped) = (cancel.clone(), cancel.clone()); let work = move |task: lightcraft_engine::activity::TaskHandle| { let total = count as u64; - task.progress(0, total); lightcraft_engine::guard::catch(LABEL, || similar::measure(reads, &flag, &|done| task.progress(done as u64, total))) }; let done = move |app: &mut LightcraftApp, ctx: &egui::Context, found: Result, String>| { @@ -62,7 +61,7 @@ fn start(app: &mut LightcraftApp, p: &Value, end: impl FnOnce(&mut LightcraftApp }; end(app, ctx, ended); }; - crate::tasks::spawn_tracked(app, LABEL, similar::KIND, cancel, work, done)?; + crate::tasks::spawn_tracked(app, LABEL, similar::KIND, cancel, count as u64, work, done)?; Ok(count) } diff --git a/crates/ui-egui/src/missing_sweep.rs b/crates/ui-egui/src/missing_sweep.rs index 1afd0a2806..d78990d28b 100644 --- a/crates/ui-egui/src/missing_sweep.rs +++ b/crates/ui-egui/src/missing_sweep.rs @@ -90,7 +90,6 @@ pub fn ask(app: &mut LightcraftApp, reply: Sender) -> Outcome { let cancel = Arc::new(AtomicBool::new(false)); let flag = cancel.clone(); let work = move |task: lightcraft_engine::activity::TaskHandle| { - task.progress(0, total); // (a panic is this check's failure, answered to the callers: they would wait for it in vain) lightcraft_engine::guard::catch("Missing Photos", || { missing::sweep(files, |f| exists(f), || flag.load(Ordering::Relaxed), |done| task.progress(done as u64, total)) @@ -113,7 +112,7 @@ pub fn ask(app: &mut LightcraftApp, reply: Sender) -> Outcome { app.missing.kept = Some(Kept { library, snapshot, at: Instant::now(), answer }); } }; - if let Err(e) = crate::tasks::spawn_tracked(app, LABEL, KIND, cancel, work, done) { + if let Err(e) = crate::tasks::spawn_tracked(app, LABEL, KIND, cancel, total, work, done) { app.missing.fail(library, &e); } Outcome::Later diff --git a/crates/ui-egui/src/reload.rs b/crates/ui-egui/src/reload.rs index 8748bfd655..8eef14fb9d 100644 --- a/crates/ui-egui/src/reload.rs +++ b/crates/ui-egui/src/reload.rs @@ -46,7 +46,6 @@ pub fn command(app: &mut LightcraftApp, p: &Value) -> Option Option, /// Repaints the window when a task finishes (set every frame). pub(crate) repaint: Option, + /// Pause the next worker before its first instruction, without relying on OS scheduling. + #[cfg(test)] + pub(crate) next_worker_start: Option>, } impl Tasks { @@ -57,16 +60,18 @@ pub fn spawn( /// [`spawn`] for a task with progress that can stop: its row (`kind`, `label`) adopts `cancel`, /// the flag `work` checks, so the row's ✕ and `activity.cancel` stop it; `work` reports progress -/// through the handle it is given. +/// through the handle it is given. `total` is published before the worker starts (0 if unknown). pub fn spawn_tracked( app: &mut LightcraftApp, label: &str, kind: &'static str, cancel: std::sync::Arc, + total: u64, work: impl FnOnce(lightcraft_engine::activity::TaskHandle) -> T + Send + 'static, done: impl FnOnce(&mut LightcraftApp, &egui::Context, T) + Send + 'static, ) -> Result<(), String> { let guard = app.session.activity.start(kind, label, lightcraft_engine::activity::Cancel::Flag(cancel)); + guard.progress(0, total); let handle = guard.handle(); start(app, label, Some(guard), move || work(handle), done) } @@ -81,7 +86,13 @@ fn start( ) -> Result<(), String> { let (tx, rx) = channel::(); let repaint = app.tasks.repaint.clone(); + #[cfg(test)] + let gate = app.tasks.next_worker_start.take(); let job = move || { + #[cfg(test)] + if let Some(gate) = gate { + let _ = gate.recv(); + } let t = work(); let _ = tx.send(Box::new(move |app: &mut LightcraftApp, ctx: &egui::Context| done(app, ctx, t))); if let Some(c) = repaint { diff --git a/crates/ui-egui/src/tests/find_similar.rs b/crates/ui-egui/src/tests/find_similar.rs index f68fb5e2e8..1da2f633a5 100644 --- a/crates/ui-egui/src/tests/find_similar.rs +++ b/crates/ui-egui/src/tests/find_similar.rs @@ -121,6 +121,32 @@ fn a_search_from_the_menu_reads_off_the_ui_thread_and_the_window_goes_on() { assert!(toast.starts_with(&format!("{shown} similar photos")), "{toast}"); } +/// A worker may not be scheduled before the next frames: the known work count is published by +/// the command itself, rather than depending on a first worker instruction. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn the_known_total_is_visible_before_the_worker_can_start() { + let (mut h, drive) = app_on_a_slow_drive(GUARD); + let (resume, paused) = std::sync::mpsc::channel(); + h.app.tasks.next_worker_start = Some(paused); + let started = h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); + let before = rows(&h); + let read_before = drive.reads.load(Ordering::SeqCst); + // Always release and drain the worker before asserting, including the negative counterprobe. + drive.open.store(true, Ordering::SeqCst); + resume.send(()).unwrap(); + until_done(&mut h); + assert_eq!(started, json!({"background": true, "count": PHOTOS})); + assert_eq!(before.len(), 1); + assert_eq!((before[0].done, before[0].total), (0, PHOTOS)); + assert_eq!(before[0].label, LABEL); + assert!(before[0].cancellable); + assert_eq!(read_before, 0, "the worker was stopped before measuring any photo"); + assert_eq!(drive.on_ui.load(Ordering::SeqCst), 0); + assert_eq!(drive.reads.load(Ordering::SeqCst), PHOTOS as usize); + assert!(rows(&h).is_empty()); +} + /// One search at a time: the menu row is off while one runs and on again after it, and a second /// request is refused without touching the first. #[test] From b6a8353a5bacdf7e0e1ff01847934e624732028d Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Thu, 5 Nov 2026 23:24:05 +0100 Subject: [PATCH 18/63] LR-MERGE-PANO: refresh the parity summary after the merge Co-Authored-By: Claude Opus 5.5 --- docs/parity-checklist.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 6ab8174fd2..7e174ddf9b 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -31,7 +31,7 @@ cited here still exists. Formerly docs/parity.md. | C. Views & navigation (VIEW) | 16 | 1 | 1 | 0 | 9/9 (100%) | 4/4 (100%) | | D. Search & filter (FILT) | 11 | 1 | 1 | 0 | 4/4 (100%) | 4/4 (100%) | | E. Metadata (META) | 5 | 1 | 0 | 0 | 2/2 (100%) | 2/2 (100%) | -| F. Edit panel — global adjustments (EDIT) | 41 | 5 | 3 | 1 | 25/28 (89%) | 13/14 (93%) | +| F. Edit panel — global adjustments (EDIT) | 42 | 5 | 3 | 1 | 25/28 (89%) | 14/15 (93%) | | G. Profiles (PROF) | 7 | 1 | 3 | 0 | 3/4 (75%) | 3/3 (100%) | | H. Crop & rotate (CROP) | 10 | 1 | 0 | 1 | 8/8 (100%) | 2/3 (67%) | | I. Remove / healing (REM) | 8 | 1 | 2 | 2 | 4/4 (100%) | 2/3 (67%) | @@ -51,11 +51,11 @@ cited here still exists. Formerly docs/parity.md. | W. Cloud & AI infrastructure (CLOUD / AI) | 1 | 0 | 1 | 2 | — | — | | X. Cross-cutting behaviours (BEHAV) | 23 | 6 | 1 | 1 | 8/8 (100%) | 7/10 (70%) | | Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | -| Z. Keyboard shortcuts (desktop) | 78 | 4 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | +| Z. Keyboard shortcuts (desktop) | 77 | 5 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | | Lightroom Classic extras | 41 | 26 | 21 | 8 | — | 24/27 (89%) | -| **Total** | 417 | 71 | 57 | 35 | 193/203 (95%) | 147/163 (90%) | +| **Total** | 416 | 72 | 57 | 35 | 193/203 (95%) | 147/163 (90%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.0%** of 545 in-scope rows — P0 97.5% of 203 · P1 94.2% of 163 · P2 56.2% of 178. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **82.9%** of 545 in-scope rows — P0 97.5% of 203 · P1 94.2% of 163 · P2 55.9% of 178. ## Top gaps and shortcut notes From 9eb05fa1063aa9e4bd2d632546ec3d8a9cd2339f Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Sun, 8 Nov 2026 10:07:07 +0100 Subject: [PATCH 19/63] LR-PROF-CAMERACOLOR: avoid CR3 correspondence buffer clones Estimate the established framing fallback from borrowed sensor data and defer its mask resampling until fallback selection. Preserve both distinct geometry searches and all original/fallback training and held-out gates. Add deterministic allocation, pixel, search-budget and successful-selection regressions. Reintroducing source clones fails the allocation assertion. Full cargo xtask ci passes all nine gates with Rust 1.95.0, actual Metal and WASM; capability skips are recorded separately. Co-authored-by: Codex --- crates/engine/src/camera_preview/proxy.rs | 69 ++++++++++++++++------- crates/engine/src/camera_preview/tests.rs | 44 +++++++++++++++ 2 files changed, 92 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/camera_preview/proxy.rs b/crates/engine/src/camera_preview/proxy.rs index c9403e83a6..1bf7be0c3e 100644 --- a/crates/engine/src/camera_preview/proxy.rs +++ b/crates/engine/src/camera_preview/proxy.rs @@ -143,14 +143,8 @@ pub(super) fn proxies( clipped = clipped.into_oriented(raw.orientation); reference = reference.into_oriented(raw.orientation); sensor.map_in_place(to_working); - // Judge the external warp against the established CR3 framing fallback, not - // against unregistered sensor pixels. This preserves an already better fit. - let (fallback, fallback_mask) = align_cr3_framing(sensor.clone(), clipped.clone(), &reference); - let proposed = - embedded.filter(|correction| transform.matrix_is_fallback && lens.is_none() && correction.warp.is_some()).and_then(|correction| { - align_profile_geometry_against(&sensor, &clipped, &reference, correction, lightcraft_geom::Orientation::Normal, Some(&fallback)) - }); - (sensor, clipped) = proposed.unwrap_or((fallback, fallback_mask)); + let correction = embedded.filter(|correction| transform.matrix_is_fallback && lens.is_none() && correction.warp.is_some()); + (sensor, clipped) = align_cr3_geometry(sensor, clipped, &reference, correction); } let mut sensor = fit(&sensor, size, size, Filter::Box); let mut reference_small = reference_at(&reference, &sensor); @@ -207,10 +201,17 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio #[cfg(test)] thread_local! { + static FRAMING_SEARCHES: std::cell::Cell = const { std::cell::Cell::new(0) }; static LAST_GEOMETRY_SCORES: std::cell::Cell> = const { std::cell::Cell::new(None) }; static LAST_FRAMED_SCORES: std::cell::Cell> = const { std::cell::Cell::new(None) }; } +/// Read and reset this thread's framing-search budget, independent of elapsed time. +#[cfg(test)] +pub(super) fn take_framing_search_count() -> usize { + FRAMING_SEARCHES.replace(0) +} + /// Return this test thread's last `[train_before, train_after, held_before, held_after]` /// scores against the original sensor geometry. #[cfg(test)] @@ -230,6 +231,7 @@ pub(super) fn geometry_framed_scores() -> Option<[f64; 4]> { fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: Option<&Rgb32f>, framed: Option<&Rgb32f>) -> Option { #[cfg(test)] { + FRAMING_SEARCHES.set(FRAMING_SEARCHES.get() + 1); LAST_GEOMETRY_SCORES.set(None); LAST_FRAMED_SCORES.set(None); } @@ -402,19 +404,44 @@ pub(super) fn estimate_profile_framing(candidate: &Rgb32f, reference: &Rgb32f, o estimate_framing_against(candidate, reference, Some(original), None) } -/// The sensor proxy and its clip mask (same size), both moved to the camera JPEG's framing. -fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rgb32f, Rgb32f) { - let Some(framing) = estimate_cr3_framing(&sensor, reference) else { return (sensor, clipped) }; - let apply = |image: &Rgb32f| { - let (w, h) = (image.width, image.height); - let mut aligned = Rgb32f::new(w, h); - for (i, pixel) in aligned.data.iter_mut().enumerate() { - let (x, y) = framing.source((i % w) as f32 + 0.5, (i / w) as f32 + 0.5, w, h); - *pixel = if x >= 0.5 && y >= 0.5 && x <= w as f32 - 0.5 && y <= h as f32 - 0.5 { image.sample_bilinear(x, y) } else { [f32::NAN; 3] }; - } - aligned - }; - (apply(&sensor), apply(&clipped)) +/// Choose CR3 correspondence without copying the unregistered sensor or mask. The +/// unwarped fallback and warped proposal need separate searches: their pixels and +/// support rules differ, and the proposal must preserve the accepted fallback. +pub(super) fn align_cr3_geometry( + sensor: Rgb32f, + clipped: Rgb32f, + reference: &Rgb32f, + correction: Option<&lightcraft_develop::EmbeddedLens>, +) -> (Rgb32f, Rgb32f) { + let framing = estimate_cr3_framing(&sensor, reference); + let fallback = framing.map(|framing| apply_cr3_framing(&sensor, framing)); + if let Some(proposed) = correction.and_then(|correction| { + align_profile_geometry_against( + &sensor, + &clipped, + reference, + correction, + lightcraft_geom::Orientation::Normal, + Some(fallback.as_ref().unwrap_or(&sensor)), + ) + }) { + return proposed; + } + // The mask is needed only if the fallback wins; when no framing is accepted, + // return both original allocations unchanged. + let clipped = if let Some(framing) = framing { apply_cr3_framing(&clipped, framing) } else { clipped }; + (fallback.unwrap_or(sensor), clipped) +} + +/// Move one image to the accepted camera framing, preserving invalid border samples. +fn apply_cr3_framing(image: &Rgb32f, framing: Cr3Framing) -> Rgb32f { + let (w, h) = (image.width, image.height); + let mut aligned = Rgb32f::new(w, h); + for (i, pixel) in aligned.data.iter_mut().enumerate() { + let (x, y) = framing.source((i % w) as f32 + 0.5, (i / w) as f32 + 0.5, w, h); + *pixel = if x >= 0.5 && y >= 0.5 && x <= w as f32 - 0.5 && y <= h as f32 - 0.5 { image.sample_bilinear(x, y) } else { [f32::NAN; 3] }; + } + aligned } /// Apply a shared source map to colour or a nonnegative clip mask. Invalid borders diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index ef04045c08..042d37b188 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -2678,6 +2678,50 @@ fn cr3_framing_only_does_not_report_profile_gate_scores() { assert!(super::proxy::geometry_framed_scores().is_none()); } +/// Rejected registration must preserve both input allocations and pixel bits. A +/// missing/ineligible warp uses only the fallback search; an eligible warp adds +/// exactly one search on different (warped) pixels, never repeats either search. +#[test] +fn cr3_unchanged_geometry_preserves_allocations_and_bounds_search_work() { + for (correction, searches) in [(None, 1), (Some(Default::default()), 1), (Some(synthetic_profile_lens()), 2)] { + let sensor = profile_geometry_scene(384, 256); + let reference = sensor.clone(); + let mut mask = Rgb32f::new(sensor.width, sensor.height); + mask.data[17] = [1.0; 3]; + let sensor_ptr = sensor.data.as_ptr(); + let mask_ptr = mask.data.as_ptr(); + let mask_bits: Vec<_> = mask.data.iter().map(|p| p.map(f32::to_bits)).collect(); + super::proxy::take_framing_search_count(); + let (aligned, aligned_mask) = super::proxy::align_cr3_geometry(sensor, mask, &reference, correction.as_ref()); + assert_eq!(super::proxy::take_framing_search_count(), searches, "bounded search budget for missing or rejected geometry"); + assert_eq!(aligned.data.as_ptr(), sensor_ptr, "no accepted framing or warp: retain sensor allocation"); + assert_eq!(aligned_mask.data.as_ptr(), mask_ptr, "no accepted framing or warp: retain mask allocation"); + assert_eq!(aligned.data, reference.data); + assert_eq!(aligned_mask.data.iter().map(|p| p.map(f32::to_bits)).collect::>(), mask_bits); + } +} + +/// Exercise selection through the same orchestration as file-local and pooled +/// fitting, including the proposal's comparisons with the framed fallback. +#[test] +fn cr3_geometry_selects_matching_profile_with_one_search_per_geometry() { + let sensor = profile_geometry_scene(384, 256); + let lens = synthetic_profile_lens(); + let framing = Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }; + let expected = profile_geometry_target(&sensor, &lens, framing); + let mut reference = expected.clone(); + reference.map_in_place(|p| p.map(|v| v.powf(0.7))); + let mask = Rgb32f::new(sensor.width, sensor.height); + let expected_mask = profile_geometry_target(&mask, &lens, framing); + super::proxy::take_framing_search_count(); + let (aligned, aligned_mask) = super::proxy::align_cr3_geometry(sensor, mask, &reference, Some(&lens)); + assert_eq!(super::proxy::take_framing_search_count(), 2); + assert!(super::proxy::geometry_gate_scores().is_some(), "proposal passed original geometry gates"); + assert!(super::proxy::geometry_framed_scores().is_some(), "proposal was compared with fallback on both splits"); + assert_profile_geometry_mask(&aligned, &aligned_mask, &expected_mask); + assert!(geometry_rms(&aligned, &expected) < 0.008, "matching proposal selected despite nonlinear JPEG tone"); +} + /// Return a deliberately strong radial warp for synthetic correspondence tests. fn synthetic_profile_lens() -> lightcraft_develop::EmbeddedLens { lightcraft_develop::EmbeddedLens { From 26a8f4e706ee52d1fb96448593356873e5f1f2ac Mon Sep 17 00:00:00 2001 From: Dimitrij Denissenko Date: Tue, 10 Nov 2026 09:07:59 +0000 Subject: [PATCH 20/63] LR-MASK-BRUSH: Flow as in Lightroom (process V8): coverage per brush radius travelled Measured in Lightroom Classic on a grey card (#4045), a stroke's centre is covered by 41 % at Flow 25 and 76 % at Flow 50; here every dab added the full flow, r/4 apart (closer on a slow drag), so 90 % and over 99 %. From process V8 a dab adds 1 - (1 - flow)^(d / r) for its distance d from the previous dab, so a point a stroke passes over for a length L is covered by 1 - (1 - flow)^(L / r) however densely the dabs lie: 44 % and 75 %. CPU, GPU (a flow per dab in the brush data) and the live stroke alike; V1 to V7 render as before. --- crates/develop/src/settings.rs | 9 +++- crates/gpu/src/render.rs | 7 +-- crates/gpu/src/wgsl/mask.wgsl | 11 ++-- crates/gpu/tests/it/equivalence.rs | 14 +++++ crates/pipeline/src/finish.rs | 6 +-- crates/pipeline/src/geometry.rs | 4 ++ crates/pipeline/src/light_v3.rs | 2 +- crates/pipeline/src/local.rs | 2 +- crates/pipeline/src/masks.rs | 58 ++++++++++++++++++-- crates/pipeline/src/masks/tests.rs | 66 +++++++++++++++++++++++ crates/pipeline/src/tests_grain.rs | 2 +- crates/ui-egui/src/brush_live.rs | 48 +++++++++++++++-- crates/ui-egui/src/panels/detail/masks.rs | 1 + crates/ui-egui/src/tests/masking.rs | 27 ++++++++++ docs/parity-checklist.md | 3 +- docs/process-versions.md | 4 +- docs/whats-new.md | 5 ++ 17 files changed, 245 insertions(+), 24 deletions(-) diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index 85bb3b90f2..8a6a7168b5 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -99,12 +99,16 @@ pub enum Process { /// V6, with film grain from a stack of crystal layers (after Aurélien Pierre's model): resolution /// independent, fading out at black and white; V1 to V6 keep their value noise. V7, + /// V7, with brush Flow as the coverage a stroke adds per brush radius it travels, as in + /// Lightroom: a dab adds `1 − (1 − flow)^(distance from the previous dab / radius)`, so a + /// stroke's strength no longer depends on how densely its dabs lie; V1 to V7 add `flow` per dab. + V8, } impl Process { /// Every process, oldest first. - pub const ALL: [Process; 7] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6, Process::V7]; - pub const LATEST: Process = Process::V7; + pub const ALL: [Process; 8] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6, Process::V7, Process::V8]; + pub const LATEST: Process = Process::V8; pub const fn version(self) -> ProcessVersion { match self { @@ -115,6 +119,7 @@ impl Process { Process::V5 => ProcessVersion(5), Process::V6 => ProcessVersion(6), Process::V7 => ProcessVersion(7), + Process::V8 => ProcessVersion(8), } } } diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 4d658c3ca0..12254a475f 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -1459,7 +1459,8 @@ fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, pla const MAX_DABS: usize = 4096; /// The `shape` kernel's brush data for `dabs`: stroke records (12 words: dab offset, dab count, -/// r, hard, flow, density, erase, bbox x0 y0 x1 y1, auto) then the dab centres. +/// r, hard, flow, density, erase, bbox x0 y0 x1 y1, auto) then each dab's centre and the flow it +/// adds (3 words; the stroke's flow before process V8, [`lightcraft_pipeline::masks::BrushDabs::dab`]). fn brush_aux(dabs: &[&lightcraft_pipeline::masks::BrushDabs], erase: bool) -> Vec { let mut aux = Vec::new(); let mut off = 12 * dabs.len(); @@ -1471,10 +1472,10 @@ fn brush_aux(dabs: &[&lightcraft_pipeline::masks::BrushDabs], erase: bool) -> Ve aux.extend([off as f32, d.dabs.len() as f32, d.r as f32, d.hard as f32, d.flow, d.density, (erase && d.erase) as u8 as f32]); aux.extend([x0, y0, x1, y1].map(|v| v as f32)); aux.push(d.auto as u8 as f32); - off += 2 * d.dabs.len(); + off += 3 * d.dabs.len(); } for d in dabs { - aux.extend(d.dabs.iter().flat_map(|q| [q.x as f32, q.y as f32])); + aux.extend(d.dabs.iter().enumerate().flat_map(|(i, q)| [q.x as f32, q.y as f32, d.dab(i).2])); } aux } diff --git a/crates/gpu/src/wgsl/mask.wgsl b/crates/gpu/src/wgsl/mask.wgsl index c2d15b64a2..6157b5f866 100644 --- a/crates/gpu/src/wgsl/mask.wgsl +++ b/crates/gpu/src/wgsl/mask.wgsl @@ -92,11 +92,12 @@ fn shape(@builtin(global_invocation_id) g: vec3) { let cnt = u32(aux[o + 1u]); let r = aux[o + 2u]; let hard = aux[o + 3u]; - let flow = aux[o + 4u]; var keep = 1.0; for (var j = 0u; j < cnt; j++) { - let dx = px - aux[off + 2u * j]; - let dy = py - aux[off + 2u * j + 1u]; + // dab record: centre x, y and the flow it adds (the stroke's before process V8) + let dx = px - aux[off + 3u * j]; + let dy = py - aux[off + 3u * j + 1u]; + let flow = aux[off + 3u * j + 2u]; let dd = sqrt(dx * dx + dy * dy); if (dd > r) { continue; @@ -106,8 +107,8 @@ fn shape(@builtin(global_invocation_id) g: vec3) { a = 1.0 - sstep(hard, r, dd); } if (auto_mask) { - let rx = min(u32(max(floor(aux[off + 2u * j]), 0.0)), w - 1u); - let ry = min(u32(max(floor(aux[off + 2u * j + 1u]), 0.0)), h - 1u); + let rx = min(u32(max(floor(aux[off + 3u * j]), 0.0)), w - 1u); + let ry = min(u32(max(floor(aux[off + 3u * j + 1u]), 0.0)), h - 1u); let ri = ry * w + rx; a *= auto_similarity(lp, chp, log_l[ri], chroma_at(ri)); } diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 427afe424d..15550cfb74 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -434,6 +434,20 @@ fn cases() -> Vec<(&'static str, Edit)> { }, ]; }), + ("masks (brush, process V7: flow per dab)", |s| { + s.process = lightcraft_develop::Process::V7.version(); + let stroke = BrushStroke { + points: vec![Point::new(0.1, 0.3), Point::new(0.5, 0.4), Point::new(0.8, 0.35)], + size: 0.04, + flow: 25.0, + ..Default::default() + }; + s.masks = vec![Mask { + components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: MaskShape::Brush { strokes: vec![stroke] } }], + adjust: lightcraft_develop::LocalAdjustments { exposure: -1.0, ..Default::default() }, + ..Default::default() + }]; + }), ("masks (brush + ranges)", |s| { let stroke = BrushStroke { points: vec![Point::new(0.1, 0.3), Point::new(0.5, 0.4), Point::new(0.8, 0.35)], diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index 3bce268a68..a4ec7ddec3 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -148,8 +148,8 @@ impl GrainModel { seed: g.seed, }) }), - Process::V7 if draft => crate::crystal::CrystalGrain::draft(g, px_per_long).map(GrainModel::Crystal), - Process::V7 => crate::crystal::CrystalGrain::new(g, px_per_long).map(GrainModel::Crystal), + Process::V7 | Process::V8 if draft => crate::crystal::CrystalGrain::draft(g, px_per_long).map(GrainModel::Crystal), + Process::V7 | Process::V8 => crate::crystal::CrystalGrain::new(g, px_per_long).map(GrainModel::Crystal), } } } @@ -407,7 +407,7 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap { }, // V4, with a raw's tone curve rolling off into white in stops: a camera curve past its last // knot, the generic curve from half a stop below its white point instead of clipping (issue #1632) - Process::V5 | Process::V6 | Process::V7 => match info.camera_tone.as_ref().filter(|_| info.raw) { + Process::V5 | Process::V6 | Process::V7 | Process::V8 => match info.camera_tone.as_ref().filter(|_| info.raw) { Some(curve) => ToneMap::camera_rolloff_hdr(curve, 0.0, l.whites, 0.0, peak), None if info.raw => ToneMap::rolloff_hdr(l.contrast, l.whites, l.blacks, peak), None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak), diff --git a/crates/pipeline/src/geometry.rs b/crates/pipeline/src/geometry.rs index 5d8a07489a..3ed3268474 100644 --- a/crates/pipeline/src/geometry.rs +++ b/crates/pipeline/src/geometry.rs @@ -37,6 +37,9 @@ pub struct Frame { /// `lightcraft_develop::Mask::on_photo`); otherwise they are normalized coordinates of this /// frame's transformed image, like spots and the crop. pub masks_on_photo: bool, + /// Brush Flow is coverage per brush radius travelled (process V8, [`crate::masks::flow_per_radius`]), + /// not per dab. + pub brush_flow_per_radius: bool, } /// Where a windowed [`Frame`]'s pixels sit in the full output: its offset and the full output's @@ -82,6 +85,7 @@ impl Frame { warp: (!warp.is_identity()).then_some(warp), view: None, masks_on_photo: false, + brush_flow_per_radius: crate::masks::flow_per_radius(s), }; if apply_crop { f.constrain_to_image(s.geometry.constrain_crop); diff --git a/crates/pipeline/src/light_v3.rs b/crates/pipeline/src/light_v3.rs index a7db45ec06..5f3e0f9bf2 100644 --- a/crates/pipeline/src/light_v3.rs +++ b/crates/pipeline/src/light_v3.rs @@ -284,7 +284,7 @@ pub fn applies(s: &DevelopSettings, info: &SourceInfo) -> bool { let camera_look = info.raw && info.camera_tone.is_some(); match s.process.process() { Process::V1 | Process::V2 | Process::V3 => false, - Process::V4 | Process::V5 | Process::V6 | Process::V7 => camera_look, + Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 => camera_look, } } diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index 5fb9ad84ce..0401c31533 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -375,7 +375,7 @@ pub fn base_detail_radius(px_per_long: f64) -> usize { pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize { match s.process.process() { Process::V1 => 0, - Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 | Process::V7 => base_detail_radius(px_per_long), + Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 => base_detail_radius(px_per_long), } } diff --git a/crates/pipeline/src/masks.rs b/crates/pipeline/src/masks.rs index b40e3dcd97..a30ecf7e4a 100644 --- a/crates/pipeline/src/masks.rs +++ b/crates/pipeline/src/masks.rs @@ -511,11 +511,21 @@ pub struct BrushDabs { pub auto: bool, /// Pen pressure (0..1) of each dab, parallel to `dabs`; empty when the stroke has no pressure data (full pressure). pub pressure: Vec, + /// What each dab adds under process V8 ([`travel_flow`], pressure applied), parallel to `dabs`; + /// empty before V8, where every dab adds the stroke's flow. + pub flows: Vec, } impl BrushDabs { - /// Radius, hard core and flow of dab `i`, pen pressure applied ([`pressure_radius`], [`pressure_flow`]). + /// Radius, hard core and flow of dab `i`, pen pressure applied ([`pressure_radius`], [`pressure_flow`]); + /// under process V8 the flow is what the dab adds for the distance it travelled ([`travel_flow`]). pub fn dab(&self, i: usize) -> (f64, f64, f32) { + let (r, hard, flow) = self.pressed(i); + (r, hard, self.flows.get(i).copied().unwrap_or(flow)) + } + + /// [`Self::dab`] with the stroke's flow for every dab, as before process V8. + fn pressed(&self, i: usize) -> (f64, f64, f32) { match self.pressure.get(i) { Some(&p) => { let r = pressure_radius(self.r, p); @@ -524,6 +534,46 @@ impl BrushDabs { None => (self.r, self.hard, self.flow), } } + + /// Give every dab what it adds for the distance it travelled ([`travel_flow`], process V8). + fn flow_by_travel(mut self) -> BrushDabs { + let flows = (0..self.dabs.len()) + .map(|i| { + let (r, _, flow) = self.pressed(i); + // the first dab counts one radius: a click paints its flow, as before + let dist = match (i.checked_sub(1).and_then(|j| self.dabs.get(j)), self.dabs.get(i)) { + (Some(a), Some(b)) => a.dist(*b), + _ => r, + }; + travel_flow(flow, dist, r) + }) + .collect(); + self.flows = flows; + self + } +} + +/// Whether brush Flow is the coverage a stroke adds per brush radius it travels (process V8 on), as +/// in Lightroom, rather than what every dab adds whatever the spacing of the dabs. +pub fn flow_per_radius(s: &lightcraft_develop::DevelopSettings) -> bool { + s.process.process() >= lightcraft_develop::Process::V8 +} + +/// What one dab adds to a stroke's coverage when Flow is coverage per brush radius travelled +/// (process V8): `1 − (1 − flow)^(dist / r)` for a dab `dist` past the previous one, brush radius +/// `r`. A stroke then covers a point it passes over for a length `L` by `1 − (1 − flow)^(L / r)` +/// however densely its dabs lie: a straight stroke's centre (`L` = 2 r) by 44 % at Flow 25, 75 % at +/// Flow 50 and fully at 100, as Lightroom Classic's strokes measure on a grey card (#4045). +pub fn travel_flow(flow: f32, dist: f64, r: f64) -> f32 { + if flow.is_nan() || flow <= 0.0 { + return 0.0; + } + if flow >= 1.0 { + return 1.0; + } + // (a degenerate radius or distance counts one radius; a long jump at most saturates) + let t = if r > 0.0 && dist.is_finite() { (dist / r).clamp(0.0, 64.0) } else { 1.0 }; + 1.0 - (1.0 - flow).powf(t as f32) } /// The radius of a dab of a brush of radius `r` (pixels) painted at pen pressure `p` (0..1): from a tenth of the @@ -604,7 +654,7 @@ pub fn brush_dabs_within(s: &BrushStroke, frame: &Frame, w: usize, h: usize, max prev_p = pq; } } - BrushDabs { + let bd = BrushDabs { dabs, r, hard, @@ -613,7 +663,9 @@ pub fn brush_dabs_within(s: &BrushStroke, frame: &Frame, w: usize, h: usize, max erase: s.erase, auto: s.auto_mask, pressure, - } + flows: Vec::new(), + }; + if frame.brush_flow_per_radius { bd.flow_by_travel() } else { bd } } /// Distance between consecutive dabs of a brush of radius `r` (pixels): a quarter of the radius, diff --git a/crates/pipeline/src/masks/tests.rs b/crates/pipeline/src/masks/tests.rs index b57f9f6688..649e5cc30a 100644 --- a/crates/pipeline/src/masks/tests.rs +++ b/crates/pipeline/src/masks/tests.rs @@ -456,6 +456,72 @@ fn holding_the_brush_still_adds_no_coverage() { assert_eq!(brush_dabs(&paused, &f, w, h).dabs, brush_dabs(&smooth, &f, w, h).dabs); } +/// A straight Feather 0 stroke of radius 20 px along row 50 of a 400 × 100 frame on `process`. +fn straight_stroke(process: lightcraft_develop::Process, flow: f64, points: Vec) -> Plane { + let (w, h) = (400, 100); + let d = DevelopSettings { process: process.version(), ..Default::default() }; + let f = Frame::new(w, h, &d, true); + let s = BrushStroke { points, size: 0.05, feather: 0.0, flow, ..Default::default() }; + shape_alpha(&MaskShape::Brush { strokes: vec![s] }, &f, w, h, &Rgb32f::new(w, h), &Plane::new(w, h), 0.0, None) +} + +/// Process V8: Flow is the coverage a stroke adds per brush radius it travels, as Lightroom +/// Classic's strokes measure on a grey card (Feather 0, straight strokes, #4045): a point the brush +/// passes over for a length `L` is covered by `1 − (1 − flow)^(L / r)`, so the centre of a stroke +/// (L = 2 r) by 41 % at Flow 25, 76 % at 50 and fully at 100 (Lightroom), and a point 0.6 radii off +/// the centre line less. Process V7 adds the flow per dab, r/4 apart: 90 % at Flow 25. +#[test] +fn flow_is_coverage_per_radius_travelled_as_in_lightroom() { + use lightcraft_develop::Process; + let line = vec![Point::new(0.1, 0.5), Point::new(0.9, 0.5)]; + for (flow, lightroom) in [(25.0, 0.41), (50.0, 0.76), (100.0, 1.0)] { + let a = straight_stroke(Process::V8, flow, line.clone()); + let keep = 1.0 - flow as f32 / 100.0; + let centre = a.get(200, 50); + assert!((centre - (1.0 - keep.powi(2))).abs() < 0.03, "Flow {flow}: centre {centre}"); + assert!((centre - lightroom).abs() < 0.05, "Flow {flow}: Lightroom covers {lightroom}, here {centre}"); + // pixel row 62 is 12.5 px = 0.625 r off the line, under the brush for 2·√(1 − 0.625²) radii + let chord = 2.0 * (1.0 - 0.625f32 * 0.625).sqrt(); + let off = a.get(200, 62); + assert!((off - (1.0 - keep.powf(chord))).abs() < 0.05, "Flow {flow}: 0.6 r off the line {off}"); + assert!(off <= centre + 1e-6); + } + let old = straight_stroke(Process::V7, 25.0, line).get(200, 50); + assert!(old > 0.85, "V7 keeps the flow per dab: {old}"); +} + +/// Process V8: a stroke covers the same however densely its samples lie (a slow drag samples +/// every pixel, a fast one far apart); before V8 a slow stroke laid more dabs and built up more. +#[test] +fn flow_does_not_depend_on_how_fast_the_stroke_was_painted() { + use lightcraft_develop::Process; + let fast = vec![Point::new(0.1, 0.5), Point::new(0.9, 0.5)]; + // one sample per output pixel + let slow: Vec = (40..=360).map(|x| Point::new(x as f64 / 400.0, 0.5)).collect(); + let (f, s) = (straight_stroke(Process::V8, 25.0, fast.clone()).get(200, 50), straight_stroke(Process::V8, 25.0, slow.clone()).get(200, 50)); + assert!((f - s).abs() < 0.02, "fast {f} vs slow {s}"); + let (f7, s7) = (straight_stroke(Process::V7, 25.0, fast).get(200, 50), straight_stroke(Process::V7, 25.0, slow).get(200, 50)); + assert!(s7 > f7, "before V8 a slow stroke builds up more: {f7} vs {s7}"); +} + +/// A click (one dab) paints its flow on every process; Flow 100 paints fully. +#[test] +fn a_click_paints_its_flow() { + use lightcraft_develop::Process; + for p in [Process::V7, Process::V8] { + let a = straight_stroke(p, 40.0, vec![Point::new(0.5, 0.5)]); + assert!((a.get(200, 50) - 0.4).abs() < 1e-4, "{p:?}: {}", a.get(200, 50)); + } + assert_eq!(travel_flow(1.0, 0.25, 1.0), 1.0); + assert_eq!(travel_flow(0.0, 1.0, 1.0), 0.0); + assert_eq!(travel_flow(f32::NAN, 1.0, 1.0), 0.0); + assert!((travel_flow(0.25, 1.0, 1.0) - 0.25).abs() < 1e-6, "one radius adds the flow"); + assert!((travel_flow(0.25, 0.0, 0.0) - 0.25).abs() < 1e-6, "a degenerate radius counts one radius"); + assert!((travel_flow(0.25, f64::INFINITY, 1.0) - 0.25).abs() < 1e-6); + assert!(travel_flow(0.25, 1e12, 1.0) > 0.999 && travel_flow(0.25, 1e12, 1.0) <= 1.0); + assert!(travel_flow(0.25, -5.0, 1.0) == 0.0, "no distance adds nothing"); +} + /// Flow builds up by passes: going back over an area in the same stroke adds coverage. #[test] fn a_second_pass_builds_up_with_low_flow() { diff --git a/crates/pipeline/src/tests_grain.rs b/crates/pipeline/src/tests_grain.rs index 14172a516c..9dc4892453 100644 --- a/crates/pipeline/src/tests_grain.rs +++ b/crates/pipeline/src/tests_grain.rs @@ -35,7 +35,7 @@ fn processes_before_v7_keep_the_value_noise() { Process::V1 | Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 => { assert!(matches!(model, Some(GrainModel::Value(_))), "{p:?}") } - Process::V7 => assert!(matches!(model, Some(GrainModel::Crystal(_))), "{p:?}"), + Process::V7 | Process::V8 => assert!(matches!(model, Some(GrainModel::Crystal(_))), "{p:?}"), } assert!(GrainModel::new(&on(p, 0.0), 2000.0, false).is_none(), "{p:?}: no grain at Amount 0"); } diff --git a/crates/ui-egui/src/brush_live.rs b/crates/ui-egui/src/brush_live.rs index 1d31d44d28..19d25f2a8f 100644 --- a/crates/ui-egui/src/brush_live.rs +++ b/crates/ui-egui/src/brush_live.rs @@ -9,7 +9,7 @@ use egui::{Color32, ColorImage, Pos2, Rect, TextureHandle, TextureOptions, pos2}; use lightcraft_geom::Point; -use lightcraft_pipeline::masks::{accumulate, dab_alpha, pressure_flow, pressure_radius, push_dabs_counted, push_pressures}; +use lightcraft_pipeline::masks::{accumulate, dab_alpha, pressure_flow, pressure_radius, push_dabs_counted, push_pressures, travel_flow}; /// The largest live-stroke buffer edge (pixels); a bigger canvas is painted at a lower resolution. const MAX_SIDE: usize = 4096; @@ -28,6 +28,9 @@ pub struct LiveParams { /// Flow and density, 0..1. pub flow: f32, pub density: f32, + /// Flow is coverage per brush radius travelled (process V8, `masks::flow_per_radius`), as the + /// committed stroke paints it. + pub per_radius: bool, /// Overlay colour and its opacity (0..1) at full coverage. pub color: [u8; 3], pub opacity: f32, @@ -46,6 +49,8 @@ pub struct LiveStroke { last: Option, /// The pen pressure of the last stamped sample. last_pressure: f32, + /// The last dab painted (buffer pixels): how far the next one travelled. + last_dab: Option, /// Buffer pixels painted since the last upload: (x0, y0, x1, y1), exclusive ends. dirty: Option<(usize, usize, usize, usize)>, texture: Option, @@ -56,7 +61,19 @@ impl LiveStroke { let scale = buffer_scale(params.clip, params.scale); let params = LiveParams { scale, ..params }; let (w, h) = buffer_size(params.clip, scale); - LiveStroke { params, w, h, alpha: vec![0.0; w * h], placed: 0, emitted: 0, last: None, last_pressure: 1.0, dirty: None, texture: None } + LiveStroke { + params, + w, + h, + alpha: vec![0.0; w * h], + placed: 0, + emitted: 0, + last: None, + last_pressure: 1.0, + last_dab: None, + dirty: None, + texture: None, + } } /// Stroke coverage (0..1) at buffer pixel `(x, y)`; 0 outside. @@ -80,7 +97,7 @@ impl LiveStroke { if new.is_empty() { return false; } - let LiveParams { clip, scale, r, hard, flow, density, .. } = self.params; + let LiveParams { clip, scale, r, hard, flow, density, per_radius, .. } = self.params; let (r, hard) = ((r * scale) as f64, (hard * scale) as f64); let mut dabs = Vec::new(); let mut pressures = Vec::new(); @@ -105,6 +122,10 @@ impl LiveStroke { let r = pressure_radius(base.0, p); let hard = if base.0 > 0.0 { base.1 * r / base.0 } else { base.1 }; let flow = pressure_flow(flow, p); + // the first dab counts one radius, as the committed stroke's does + let travelled = self.last_dab.map_or(r, |a| a.dist(d)); + self.last_dab = Some(d); + let flow = if per_radius { travel_flow(flow, travelled, r) } else { flow }; let x0 = (d.x - r).floor().clamp(0.0, self.w as f64) as usize; let x1 = (d.x + r).ceil().clamp(0.0, self.w as f64) as usize; let y0 = (d.y - r).floor().clamp(0.0, self.h as f64) as usize; @@ -220,12 +241,33 @@ mod tests { hard: 5.0, flow: 1.0, density: 1.0, + per_radius: true, color: [230, 30, 40], opacity: 0.5, } } /// Issue #517: two samples far apart (a fast stroke) paint a continuous band between them, + /// Process V8: the live stroke adds Flow per brush radius travelled, as the committed one does, + /// so a slow drag (a sample every point) and a fast one cover a point the same; a stroke's centre + /// at Flow 25 is covered by 1 − 0.75² (Feather 0 here). Before V8 the slow drag built up more. + #[test] + fn flow_per_radius_does_not_depend_on_the_drag_speed() { + let p = LiveParams { flow: 0.25, hard: 10.0, ..params() }; + let paint = |per_radius: bool, step: usize| { + let mut s = LiveStroke::new(LiveParams { per_radius, ..p }); + let pts: Vec = (20..=380).step_by(step).map(|x| pos2(x as f32, 100.0)).collect(); + for n in 1..=pts.len() { + s.stamp(&pts[..n], &[]); + } + s.coverage(200, 100) + }; + let (fast, slow) = (paint(true, 360), paint(true, 1)); + assert!((fast - 0.4375).abs() < 0.03, "{fast}"); + assert!((fast - slow).abs() < 0.02, "fast {fast} vs slow {slow}"); + assert!(paint(false, 1) > paint(false, 360), "before V8 a slow drag builds up more"); + } + /// not two separate dabs. #[test] fn a_fast_segment_is_painted_continuously() { diff --git a/crates/ui-egui/src/panels/detail/masks.rs b/crates/ui-egui/src/panels/detail/masks.rs index ebcb35e611..06891373c1 100644 --- a/crates/ui-egui/src/panels/detail/masks.rs +++ b/crates/ui-egui/src/panels/detail/masks.rs @@ -716,6 +716,7 @@ fn brush_tool( hard: r * (1.0 - (app.ui.brush_feather / 100.0).clamp(0.0, 1.0)), flow: (app.ui.brush_flow / 100.0).clamp(0.0, 1.0), density: 1.0, + per_radius: lightcraft_pipeline::masks::flow_per_radius(d), color: app.ui.mask_overlay_color, opacity: opacity.clamp(0.0, 1.0), }; diff --git a/crates/ui-egui/src/tests/masking.rs b/crates/ui-egui/src/tests/masking.rs index f7fbc60536..72aa10cca6 100644 --- a/crates/ui-egui/src/tests/masking.rs +++ b/crates/ui-egui/src/tests/masking.rs @@ -2021,6 +2021,33 @@ fn a_fast_brush_stroke_shows_without_gaps_before_the_button_is_released() { } } +/// Process V8: a Flow 25 stroke shows while the button is held as it will once committed, both +/// adding Flow per brush radius travelled (#4045): partly covered along its centre, not almost fully. +#[test] +fn a_low_flow_stroke_shows_as_it_will_be_committed() { + let mut h = detail("panel.masking"); + h.settle(SETTLE); + exec(&mut h, "tool.brush", json!({"new": true})); + let r = h.request("ui.set", json!({"brushSize": 0.03, "brushFeather": 0.0, "brushFlow": 25.0}), T); + assert_eq!(r["ok"], true, "{r}"); + let y = 0.4; + let (photo, held) = hold_fast_stroke(&mut h, y); + let col = h.app.ui.mask_overlay_color.map(|v| v as f32); + let op = h.app.ui.mask_overlay_opacity / 100.0; + // the tint along the centreline: about 1 − 0.75² of full coverage, not the 90 % of a flow per dab + let cover: Vec = photo.iter().zip(&held).map(|(p, l)| (l[0] - p[0]) / ((col[0] - p[0]) * op)).collect(); + let mid = cover[cover.len() / 2]; + assert!((mid - 0.4375).abs() < 0.08, "live coverage {mid}"); + pointer(&mut h, json!([{"kind": "up", "x": 0.85, "y": y}])); + // (the committed mask's pin sits on the stroke) + h.app.ui.mask_pins = false; + h.settle(SETTLE); + let done = stroke_centreline(&h, y); + for (l, k) in held.iter().zip(&done) { + assert!((0..3).all(|i| (l[i] - k[i]).abs() < 24.0), "live {l:?} vs committed {k:?}"); + } +} + /// What the photo shows along the centreline of [`hold_fast_stroke`]'s stroke at height `y`, away /// from the cursor ring at its end. fn stroke_centreline(h: &Headless, y: f32) -> Vec<[f32; 3]> { diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 471263c055..098f54d002 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -298,7 +298,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-MASK-OBJECTS | Object selection | P2 | 🟡 | `cmd:mask.add` (`object`, `prompt`), `cmd:mask.objectPoint`, `cmd:mask.refineDetail`, `cmd:segment.prepare`, `cmd:segment.model.status`, `cmd:segment.model.download`, `cmd:segment.model.cancel`, `cmd:app.openSamModelFolder`, `crates/segment`, `crates/engine/src/segment.rs` | SAM 3 in pure Rust (candle; Metal on macOS, CPU elsewhere): Object tile → click to include, ⌥-click to leave out; Describe tile → a text prompt selects every instance ("sky", "the red car"); both also as Add/Subtract/Intersect components; + / − under the selected mask; comma lists (`car, road`); a zoomed-in detail pass for 5–10× finer edges on small objects; per-selection Edge (hard ↔ soft); the stored grid is enlarged along the photo's edges (a guided filter of its logits by log luminance, so no outline spills onto the background under a raised Exposure, #3272). The model runs on its own worker thread (the UI never waits; panics become errors; a job that fails on the Mac's GPU runs again on the CPU, which then serves the rest of the session, #1974), is unloaded after 10 min idle, and is optional: the segmentation is stored with the mask (288² logits), so renders and exports never need it. Weights are never bundled (SAM License): without them the app offers a consented background download (mirrors, resume, timeouts, SHA-256) — **but no default download location is configured yet** (users set `LIGHTCRAFT_SAM3_MIRRORS` or install by hand: the dialog names the three files, opens the configured model folder with the host opener, preserves setup on an open error, and links docs/ai-masks.md; Meta's original checkpoint installed in place of the Hugging Face one is named as such, #3378). Not verified against Lightroom's Select Object; no brush/box object mode; the first click on a photo waits for its analysis (~4 s on an M4 Pro, much longer on CPU) | | LR-MASK-PEOPLE | People parts | P2 | ⬜ | | shape exists (no UI): uses the photo's person / skin / hair / teeth / glasses mattes when it carries them (DNG semantic masks), else the subject heuristic | | LR-MASK-LANDSCAPE | Landscape classes | P2 | ⬜ | | shape exists, evaluates empty | -| LR-MASK-BRUSH | Brush mask | P0 | 🟡 | `cmd:tool.brush`, `cmd:mask.brushStroke` (`autoMask`), `crates/pipeline/src/masks.rs`, `crates/ui-egui/src/brush_live.rs` | size/feather/flow/density/erase; Create New Mask starts a separate brush in paint mode; the stroke shows while the button is held with the committed stroke's dab spacing, feather and flow, so fast strokes have no gaps (#517); with the mask overlay hidden (O / the eye, or after a mask slider hid it) or a colour overlay at opacity 0 it is not tinted while painting either, so dodging and burning is judged on the photo, and its effect shows once the stroke is committed (#2549); coverage builds up by passes, not hold time (holding the brush still adds nothing, live or committed, #518); oversized path segments skip intermediate dabs instead of allocating a million samples; Auto Mask: dabs weighted by similarity to the colour under the dab centre, refined by a guided filter on luminance (CPU + GPU); ⇧-click draws a straight stroke from where the last stroke ended (`connect`), tapering size, feather and flow from that stroke's values when they changed; no A/B brushes; pen pressure (Brush ▸ Pen Pressure, on by default; `pressure` per point in `mask.brushStroke`) scales each dab's size (a tenth to all of it) and flow, live and committed alike, where winit reports a pen force (Windows; not macOS / Linux tablets yet); no tilt | +| LR-MASK-BRUSH | Brush mask | P0 | 🟡 | `cmd:tool.brush`, `cmd:mask.brushStroke` (`autoMask`), `crates/pipeline/src/masks.rs`, `crates/ui-egui/src/brush_live.rs` | size/feather/flow/density/erase; Create New Mask starts a separate brush in paint mode; the stroke shows while the button is held with the committed stroke's dab spacing, feather and flow, so fast strokes have no gaps (#517); with the mask overlay hidden (O / the eye, or after a mask slider hid it) or a colour overlay at opacity 0 it is not tinted while painting either, so dodging and burning is judged on the photo, and its effect shows once the stroke is committed (#2549); coverage builds up by passes, not hold time (holding the brush still adds nothing, live or committed, #518); from process V8 Flow is the coverage a stroke adds per brush radius travelled, as in Lightroom Classic (a stroke's centre: 44 % at Flow 25, 75 % at 50; measured in Lightroom 41 % and 76 %), whatever the drag speed; oversized path segments skip intermediate dabs instead of allocating a million samples; Auto Mask: dabs weighted by similarity to the colour under the dab centre, refined by a guided filter on luminance (CPU + GPU); ⇧-click draws a straight stroke from where the last stroke ended (`connect`), tapering size, feather and flow from that stroke's values when they changed; no A/B brushes; pen pressure (Brush ▸ Pen Pressure, on by default; `pressure` per point in `mask.brushStroke`) scales each dab's size (a tenth to all of it) and flow, live and committed alike, where winit reports a pen force (Windows; not macOS / Linux tablets yet); no tilt | | LR-MASK-LINEAR | Linear gradient | P0 | ✅ | `cmd:tool.linear`, `cmd:mask.update`, `crates/pipeline/src/mask_space.rs` | gradients, brushes and AI selections stay on the photo's content when lens corrections, Upright, Transform or Rotate Left / Right change (`Mask.on_photo`; CPU and GPU) | | LR-MASK-RADIAL | Radial gradient | P0 | ✅ | `cmd:tool.radial`, `cmd:mask.update`, `crates/ui-egui/src/panels/detail.rs` | drag the selected ellipse's body or centre pin to move; edge grips resize, outer grip rotates; rotated and compound radial components, hidden pins, outside hit rejection and one-step undo tested | | LR-MASK-COLORRANGE | Colour range | P1 | ✅ | `cmd:mask.add` (`colorRange`), `cmd:mask.sampleColor`, `cmd:mask.update`, `crates/pipeline/src/lib.rs` (`color_range_sample`) | Color tile → click the photo to sample (⇧-click adds, up to 5; samples taken in the space the mask compares in, respecting section eyes and the requested HDR/SDR rendition), Pick button, Refine slider; at most 64 samples (`MAX_COLOR_RANGE_SAMPLES`, render cost is pixels × samples) however the mask arrives: `mask.add` / `mask.update`, a sidecar's `lc:settings`, a preset, `develop.merge`, `render --settings` or the catalog and history keep the first 64 (issue #2556) | @@ -802,6 +802,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | LR-MASK-BRUSH: process V8 makes Flow coverage per brush radius travelled, as Lightroom Classic's strokes measure on a grey card, live and committed, CPU and GPU (`masks::travel_flow`; `flow_is_coverage_per_radius_travelled_as_in_lightroom`); a stroke no longer builds up more when painted slowly; status unchanged (🟡: no A/B brushes) | | 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | | 2026-11-04 | minor | Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. See [ORF status](orf-compression.md). | | 2026-10-28 | minor | KEY-HIDEPINS ✅ → 🟡: in the Masking panel an unmodified H toggles the mask pins (`view.maskPins`, the View ▸ Show Mask Pins switch) instead of opening Remove; the toggle yields only to an explicit assignment of H itself, a Remove key reassigned to anything else still opens Remove there, and outside Masking — and the full-screen preview, where no panel shows — H keeps its own binding (Remove, by default). Remove's spot pins keep ⇧H as their only hide toggle (`tests/keymap` `h_toggles_the_mask_pins_while_masking`, `a_remapped_remove_key_still_opens_remove_while_masking`, `h_still_toggles_the_pins_when_remove_moves_to_another_key`) | diff --git a/docs/process-versions.md b/docs/process-versions.md index b27367ed6f..cdf7f6c4a2 100644 --- a/docs/process-versions.md +++ b/docs/process-versions.md @@ -15,7 +15,8 @@ stronger Light sliders, issue #196) without changing a single photo someone has | **V4** | V3 plus calibrated global Contrast (per channel) and Blacks (per-channel/luminance mix) on raws with a camera tone curve. Whites behaves exactly as V2, both signs; its calibration is a planned follow-up. Other sources and local adjustments retain V2 operators. See [calibrated Light operators](light-v3.md). | | **V5** | V4 plus: a raw's tone curve rolls off into white in stops instead of reaching it within about a stop of the sensor's white, so raising Exposure keeps the highlights the sensor recorded (issue #1632). **Camera curve** (the look fitted to the embedded JPEG, or a DNG's `ProfileToneCurve`; `CameraTone`): past its last knot `CameraTone::apply_rolloff` closes the gap to white by `gap / (1 + c·(2^t − 1))` at `t` stops past the knot, with `c` matching the curve's slope there and the gap halving every stop in the end (`tone::ROLLOFF_STOPS`); `ToneMap::camera_rolloff_hdr` builds the table from it. Under V1 to V4 the curve past its last knot (fitted only to camera JPEG tones below 0.85, so 1 to 3 stops below the sensor's white on most photos) closes on white exponentially in linear light: the sensor's white renders at 8-bit 246 to 254 at Exposure 0 and 254 to 255 from Exposure +1. On the 11 CC0 corpus files with a fitted look (8 Sony, 2 Nikon, 1 Fujifilm) it now renders at 239 to 250 at Exposure 0 and 247 to 253 at +1. A DNG curve that reaches white at the sensor's white renders as before. **Generic curve** (raws without a camera curve, `ToneMap::rolloff_hdr`): from half a stop below its white point (`tone::GENERIC_KNEE_STOPS`) the same shoulder takes over, with the extended Reinhard curve's value and slope at the join, where V1 to V4 clip at the white point (scene 1.18 at default settings, ¼ stop above the sensor's white). The sensor's white renders at about 235, 248 and 252 at Exposure 0, +1 and +2 (V1 to V4: 239, 255, 255; the CC0 Canon R8 file and 6 CC0 DNGs without a camera curve). Content past the old clip point, such as a clipped sky, now renders up to 15 codes below white at Exposure 0 and reaches 255 about 5 stops past the sensor's white. Below the last knot or the join, JPEGs and other display-referred sources, and the camera fit itself are unchanged; CPU and GPU share the tone LUT. | | **V6** | V5 plus: colour noise reduction filters the linear colour differences R−Y and B−Y with the joint method (issue #815, `docs/nr-color-joint.md`): edge-aware weights from a denoised guide shared by both differences, anisotropic diffusion over scales, a brake for isolated colour specks; Y is kept exactly. V1 to V5 keep the blurred chromaticity (`local::denoise`). CPU (`local::denoise`) and GPU (`render::denoise`) branch on `local::joint_colour_nr`. Renders with Color 0 are the same as V2's. | -| **V7** (the latest) | V6 plus: film grain from crystal layers ([grain.md](grain.md), `crates/pipeline/src/crystal.rs`), after Aurélien Pierre's model: resolution independent (a preview is the export's grain box-downscaled), fading out at black and white, calibrated to Lightroom Classic's strength and width at mid grey. V1 to V6 keep their two-octave value noise exactly (`finish::ValueGrain`; on the GPU `F_GRAIN_MODEL` 0); `finish::GrainModel::new` picks the model per process. Renders without grain don't depend on this. | +| **V7** | V6 plus: film grain from crystal layers ([grain.md](grain.md), `crates/pipeline/src/crystal.rs`), after Aurélien Pierre's model: resolution independent (a preview is the export's grain box-downscaled), fading out at black and white, calibrated to Lightroom Classic's strength and width at mid grey. V1 to V6 keep their two-octave value noise exactly (`finish::ValueGrain`; on the GPU `F_GRAIN_MODEL` 0); `finish::GrainModel::new` picks the model per process. Renders without grain don't depend on this. | +| **V8** (the latest) | V7 plus: brush Flow is the coverage a stroke adds per brush radius it travels, as in Lightroom Classic (#4045): each dab adds `1 − (1 − flow)^(d / r)` for a dab `d` past the previous one (the first dab counts one radius, so a click paints its flow), `masks::travel_flow`. A point a stroke passes over for a length `L` is then covered by `1 − (1 − flow)^(L / r)` however densely the dabs lie: a straight stroke's centre by 44 % at Flow 25 and 75 % at Flow 50, where Lightroom Classic measures 41 % and 76 % on a grey card. V1 to V7 add the full flow per dab (r/4 apart on a fast drag, closer on a slow one): 90 % at Flow 25 on a fast stroke, more on a slow one. CPU (`masks::brush_dabs_within`), GPU (a flow per dab in the `shape` kernel's brush data) and the live stroke (`brush_live`) all branch on `masks::flow_per_radius`. Renders without brush masks, or with Flow 100 only, are the same as V7's. | ## The rule @@ -111,6 +112,7 @@ extra field and retain their existing cached renders. No cache-version bump is n | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | V8: brush Flow per brush radius travelled, as in Lightroom Classic; V1 to V7 keep the flow per dab | | 2026-11-07 | minor | V7: film grain from crystal layers ([grain.md](grain.md)); V1 to V6 keep their value noise | | 2026-11-05 | minor | V5: a raw's tone curve rolls off into white in stops, so raising Exposure keeps recorded highlights (#1632) | | 2026-10-12 | minor | Calibrated Contrast and Blacks, V2 Whites, resolved-process cache keys and number coordination | diff --git a/docs/whats-new.md b/docs/whats-new.md index 56fc27ed79..dff197e848 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -2,6 +2,11 @@ ## Unreleased +### Brush Flow as in Lightroom (process V8) +- Flow now builds up the way it does in Lightroom: one stroke at Flow 25 covers a little under half, at Flow 50 about + three quarters, where it used to cover 90 % and more, and a slow stroke covers the same as a fast one (issue #4045). + New photos (and Reset) get it; photos you already edited keep their brushes until Photo ▸ Update to Current Process. + ### Film grain that looks like film (process V7) - Grain now comes from a simulated emulsion of crystal layers (after Aurélien Pierre's model): dense, soft and cloudy rather than dots on top of the photo. It fades out towards black and white as on a print, so shadows keep their depth From fb2085c77e4f53ead86c34b832bb0b31dd3d86f4 Mon Sep 17 00:00:00 2001 From: Dimitrij Denissenko Date: Tue, 10 Nov 2026 10:09:08 +0000 Subject: [PATCH 21/63] LR-MASK-BRUSH: GPU equivalence of a Flow 25 brush on process V8 (review of #4047) --- crates/gpu/tests/it/equivalence.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 15550cfb74..780f31a130 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -434,6 +434,20 @@ fn cases() -> Vec<(&'static str, Edit)> { }, ]; }), + ("masks (brush, process V8: flow per radius travelled)", |s| { + s.process = lightcraft_develop::Process::V8.version(); + let stroke = BrushStroke { + points: vec![Point::new(0.1, 0.3), Point::new(0.5, 0.4), Point::new(0.8, 0.35)], + size: 0.04, + flow: 25.0, + ..Default::default() + }; + s.masks = vec![Mask { + components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: MaskShape::Brush { strokes: vec![stroke] } }], + adjust: lightcraft_develop::LocalAdjustments { exposure: -1.0, ..Default::default() }, + ..Default::default() + }]; + }), ("masks (brush, process V7: flow per dab)", |s| { s.process = lightcraft_develop::Process::V7.version(); let stroke = BrushStroke { From 2a8f8da3cf177d884bd00c3a002c8e21dc344b87 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:12:01 +0100 Subject: [PATCH 22/63] LR-PROF-CAMERACOLOR: fit CR3 DNG tags without external shading Exclude database vignette gains from the CR3 DNG colour fit because unchanged sensor samples and serialized opcodes do not carry that external correction. Retain correspondence geometry and the existing file-local and pooled fitting behaviour. Extend the procedural end-to-end regression to distinguish vignetted fitting, verify the stored DNG colour contract, and decode the written output. The regression fails against the previous implementation. Full cargo xtask ci passes with Rust 1.95.0, actual Metal and WASM; capability skips remain separate. Co-authored-by: Codex --- crates/engine/src/camera_preview/colour.rs | 7 +++++-- crates/engine/src/camera_preview/tests.rs | 24 ++++++++++++++++++++++ docs/cr3-profile-alignment.md | 5 ++++- 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/camera_preview/colour.rs b/crates/engine/src/camera_preview/colour.rs index c0017d1b10..151f9b2aa1 100644 --- a/crates/engine/src/camera_preview/colour.rs +++ b/crates/engine/src/camera_preview/colour.rs @@ -137,17 +137,20 @@ pub(crate) fn starting_colour_tags(raw: &mut RawImage, bytes: &[u8]) -> Option, ) -> Option { - let correction = correction.filter(|_| raw.format == RawFormat::Cr3); + let correction = + correction.filter(|_| raw.format == RawFormat::Cr3).map(|correction| lightcraft_develop::EmbeddedLens { vignette: None, ..*correction }); // the white the source shows, decided before `starting_colour` may fill in measured matrices let scale = crate::files::WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata); let white = scale.dng_white(&raw.color, lightcraft_raw::color::as_shot_white_xy(raw)); // (a merge frame arrives without its lens warp: `lightcraft_merge` removes it before calling) - let (_, t, look) = starting_colour(raw, bytes, None, correction); + let (_, t, look) = starting_colour(raw, bytes, None, correction.as_ref()); dng_colour(&raw.color, &white, &t, look.as_ref()) } diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index 042d37b188..cbe37bd3ad 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -2931,6 +2931,30 @@ fn cr3_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() { let expected_tags = dng_colour(&raw.color, &white, &t, look.as_ref()).unwrap(); let tags = super::colour::starting_colour_tags_with_correction(&mut raw, &file, Some(&lens)).unwrap(); assert_eq!(tags, expected_tags, "DNG tags use the resolved correspondence geometry too"); + + // External shading is not written into a DNG of these unchanged sensor samples. + // Its colour model must therefore be fitted to the same samples as the warp-only route. + let mut vignetted = lens; + vignetted.vignette = + Some(lightcraft_develop::EmbeddedVignette { k: [1.0, 0.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.45, 0.55), radius: 0.6 }); + let mut full_fit = raw.clone(); + let (_, full_transform, full_look) = starting_colour(&mut full_fit, &file, None, Some(&vignetted)); + assert_ne!( + dng_colour(&full_fit.color, &white, &full_transform, full_look.as_ref()), + Some(expected_tags.clone()), + "the fixture must distinguish corrected shading from the uncorrected DNG samples" + ); + let actual = super::colour::starting_colour_tags_with_correction(&mut raw, &file, Some(&vignetted)).unwrap(); + assert_eq!(actual, expected_tags, "DNG colour fitting must exclude external vignette gains"); + let mut expected_dng = raw.clone(); + expected_dng.color = expected_tags; + let mut actual_dng = raw; + actual_dng.color = actual; + let options = lightcraft_raw::DngWriteOptions::default(); + let bytes = lightcraft_raw::write_dng(&actual_dng, &options).unwrap(); + assert_eq!(bytes, lightcraft_raw::write_dng(&expected_dng, &options).unwrap(), "the saved DNG keeps the warp-only colour contract"); + let reopened = lightcraft_raw::decode(&bytes).unwrap(); + assert!(reopened.opcodes.list3.is_empty(), "no external shading opcode is silently introduced"); } /// Keep clipped contributors in the resampled mask and mark out-of-frame samples invalid. diff --git a/docs/cr3-profile-alignment.md b/docs/cr3-profile-alignment.md index 28349a11bd..e49b762f01 100644 --- a/docs/cr3-profile-alignment.md +++ b/docs/cr3-profile-alignment.md @@ -25,7 +25,10 @@ CR3 framing path. All subsequent colour, tone, hue/saturation, clipping, and held-out acceptance gates stay unchanged. The proposal reaches file-local colour and tone, pooled camera-profile pairs, and colour tags -for merge/DNG conversion. Cache versions advance from upstream look 13/render 76 to look 14/render 77. +for merge/DNG conversion. The DNG colour fit uses the external profile for correspondence geometry +without its vignette gains: the unchanged sensor samples and the DNG writer do not carry that +database shading correction. File-local and pooled fits retain source-position vignetting. +Cache versions advance from upstream look 13/render 76 to look 14/render 77. The loaded database semantic identity also invalidates camera render/view keys, Smart-preview headers and scan markers. Fresh original decodes retain the photo’s hot-pixel setting; offline proxies remain readable and cannot be relabelled as freshly fitted pixels. From 368376552cb1409691a13f576062e4a64d4163de Mon Sep 17 00:00:00 2001 From: tecari0 <121329615+tecari0@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:34:57 -0800 Subject: [PATCH 23/63] LR-MASK-BRUSH: a brush stroke is feathered as one dab is (process V10) A stroke accumulated every dab's falloff times its flow, and its dabs lie r/4 apart, so their soft edges piled up into a nearly hard one: at Feather 100 and Flow 100, halfway out from a straight stroke's centre line was 0.90 covered, where one dab covers 0.50. Process V10 keeps a stroke's Flow build-up (each dab that reaches a pixel adds its flow, masks::feather_dab) apart from its edge (the highest falloff of those dabs) and covers their product up to Density (masks::stroke_coverage). At Flow 100 a stroke's edge then falls off over the feather exactly as one dab's; below it the centre builds up by Flow per radius travelled (V9) whatever the feather. CPU, GPU (a 13th stroke-record word in the shape kernel) and the live stroke share the helpers. V1 to V9 render as before; Feather 0 brushes render as on V9. Stacked on #4047 (V9). Co-Authored-By: Claude Opus 5.5 --- crates/develop/src/settings.rs | 11 ++- crates/gpu/src/render.rs | 8 ++- crates/gpu/src/wgsl/mask.wgsl | 21 ++++-- crates/gpu/tests/it/equivalence.rs | 36 ++++++++++ crates/pipeline/src/finish.rs | 8 ++- crates/pipeline/src/geometry.rs | 3 + crates/pipeline/src/light_v3.rs | 2 +- crates/pipeline/src/local.rs | 2 +- crates/pipeline/src/masks.rs | 39 ++++++++++- crates/pipeline/src/masks/tests.rs | 67 ++++++++++++++++++ crates/pipeline/src/tests_grain.rs | 2 +- crates/ui-egui/src/brush_live.rs | 68 ++++++++++++++++--- crates/ui-egui/src/panels/detail/lens_blur.rs | 3 +- crates/ui-egui/src/panels/detail/masks.rs | 1 + docs/parity-checklist.md | 3 +- docs/process-versions.md | 4 +- docs/whats-new.md | 6 ++ 17 files changed, 255 insertions(+), 29 deletions(-) diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index dcb902be10..dd920fc5cb 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -106,13 +106,17 @@ pub enum Process { /// Lightroom: a dab adds `1 − (1 − flow)^(distance from the previous dab / radius)`, so a /// stroke's strength no longer depends on how densely its dabs lie; V1 to V8 add `flow` per dab. V9, + /// V9, with a brush stroke's edge feathered as one dab's is: a stroke's coverage is its Flow + /// build-up times the highest falloff of the dabs that reach a point, so overlapping dabs no + /// longer pile their soft edges up into a hard one; V1 to V9 accumulate each dab's falloff. + V10, } impl Process { /// Every process, oldest first. - pub const ALL: [Process; 9] = - [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6, Process::V7, Process::V8, Process::V9]; - pub const LATEST: Process = Process::V9; + pub const ALL: [Process; 10] = + [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6, Process::V7, Process::V8, Process::V9, Process::V10]; + pub const LATEST: Process = Process::V10; pub const fn version(self) -> ProcessVersion { match self { @@ -125,6 +129,7 @@ impl Process { Process::V7 => ProcessVersion(7), Process::V8 => ProcessVersion(8), Process::V9 => ProcessVersion(9), + Process::V10 => ProcessVersion(10), } } } diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index ea05b45094..b55b28642a 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -1485,12 +1485,13 @@ fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, pla /// Most brush dabs the mask kernel evaluates per pixel (more: the CPU rasterizes the brush). const MAX_DABS: usize = 4096; -/// The `shape` kernel's brush data for `dabs`: stroke records (12 words: dab offset, dab count, -/// r, hard, flow, density, erase, bbox x0 y0 x1 y1, auto) then each dab's centre and the flow it +/// The `shape` kernel's brush data for `dabs`: stroke records (13 words: dab offset, dab count, +/// r, hard, flow, density, erase, bbox x0 y0 x1 y1, auto, the edge feathered by stroke (process +/// V10, [`lightcraft_pipeline::masks::stroke_feather`])) then each dab's centre and the flow it /// adds (3 words; the stroke's flow before process V9, [`lightcraft_pipeline::masks::BrushDabs::dab`]). fn brush_aux(dabs: &[&lightcraft_pipeline::masks::BrushDabs], erase: bool) -> Vec { let mut aux = Vec::new(); - let mut off = 12 * dabs.len(); + let mut off = 13 * dabs.len(); for d in dabs { let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); for q in &d.dabs { @@ -1499,6 +1500,7 @@ fn brush_aux(dabs: &[&lightcraft_pipeline::masks::BrushDabs], erase: bool) -> Ve aux.extend([off as f32, d.dabs.len() as f32, d.r as f32, d.hard as f32, d.flow, d.density, (erase && d.erase) as u8 as f32]); aux.extend([x0, y0, x1, y1].map(|v| v as f32)); aux.push(d.auto as u8 as f32); + aux.push(d.feather_by_stroke as u8 as f32); off += 3 * d.dabs.len(); } for d in dabs { diff --git a/crates/gpu/src/wgsl/mask.wgsl b/crates/gpu/src/wgsl/mask.wgsl index e058f6bf6d..82a6838861 100644 --- a/crates/gpu/src/wgsl/mask.wgsl +++ b/crates/gpu/src/wgsl/mask.wgsl @@ -77,14 +77,16 @@ fn shape(@builtin(global_invocation_id) g: vec3) { } v = 1.0 - sstep(tol * 0.5, tol, best); } else if (kind == 4u) { - // stroke record: dab offset, dab count, r, hard, flow, density, erase, bbox x0 y0 x1 y1, auto + // stroke record: dab offset, dab count, r, hard, flow, density, erase, bbox x0 y0 x1 y1, auto, + // the edge feathered by stroke (process V10: build-up times the highest dab falloff) let px = f32(g.x) + 0.5; let py = f32(g.y) + 0.5; let lp = log_l[i]; let chp = chroma_at(i); for (var k = 0u; k < pu(10u); k++) { - let o = 12u * k; + let o = 13u * k; let auto_mask = aux[o + 11u] != 0.0; + let by_stroke = aux[o + 12u] != 0.0; if (px < aux[o + 7u] || py < aux[o + 8u] || px > aux[o + 9u] || py > aux[o + 10u]) { continue; } @@ -93,6 +95,7 @@ fn shape(@builtin(global_invocation_id) g: vec3) { let r = aux[o + 2u]; let hard = aux[o + 3u]; var keep = 1.0; + var edge = 0.0; for (var j = 0u; j < cnt; j++) { // dab record: centre x, y and the flow it adds (the stroke's before process V9) let dx = px - aux[off + 3u * j]; @@ -112,9 +115,19 @@ fn shape(@builtin(global_invocation_id) g: vec3) { let ri = ry * w + rx; a *= auto_similarity(lp, chp, log_l[ri], chroma_at(ri)); } - keep *= 1.0 - a * flow; + if (by_stroke) { + // masks::feather_dab: the build-up grows by the flow, the edge keeps the highest falloff + keep *= 1.0 - flow; + edge = max(edge, a); + } else { + keep *= 1.0 - a * flow; + } + } + var sa = min(1.0 - keep, aux[o + 5u]); + if (by_stroke) { + // masks::stroke_coverage + sa = min((1.0 - keep) * edge, aux[o + 5u]); } - let sa = min(1.0 - keep, aux[o + 5u]); if (aux[o + 6u] != 0.0) { v = v * (1.0 - sa); } else { diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 2c4c2b1357..2b9f82ef12 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -448,6 +448,42 @@ fn cases() -> Vec<(&'static str, Edit)> { ..Default::default() }]; }), + ("masks (brush, process V10: a soft stroke feathered as one dab)", |s| { + s.process = lightcraft_develop::Process::V10.version(); + let stroke = |flow: f64, erase: bool, y: f64| BrushStroke { + points: vec![Point::new(0.1, y), Point::new(0.5, y + 0.1), Point::new(0.8, y + 0.05)], + size: 0.06, + feather: 100.0, + flow, + erase, + ..Default::default() + }; + s.masks = vec![Mask { + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Brush { strokes: vec![stroke(100.0, false, 0.3), stroke(50.0, false, 0.55), stroke(100.0, true, 0.45)] }, + }], + adjust: lightcraft_develop::LocalAdjustments { exposure: -1.0, ..Default::default() }, + ..Default::default() + }]; + }), + ("masks (brush, process V9: a soft stroke's dabs accumulated)", |s| { + s.process = lightcraft_develop::Process::V9.version(); + let stroke = BrushStroke { + points: vec![Point::new(0.1, 0.3), Point::new(0.5, 0.4), Point::new(0.8, 0.35)], + size: 0.06, + feather: 100.0, + flow: 100.0, + ..Default::default() + }; + s.masks = vec![Mask { + components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: MaskShape::Brush { strokes: vec![stroke] } }], + adjust: lightcraft_develop::LocalAdjustments { exposure: -1.0, ..Default::default() }, + ..Default::default() + }]; + }), ("masks (brush, process V8: flow per dab)", |s| { s.process = lightcraft_develop::Process::V8.version(); let stroke = BrushStroke { diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index b3d0408bc2..ce4103f805 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -148,8 +148,10 @@ impl GrainModel { seed: g.seed, }) }), - Process::V7 | Process::V8 | Process::V9 if draft => crate::crystal::CrystalGrain::draft(g, px_per_long).map(GrainModel::Crystal), - Process::V7 | Process::V8 | Process::V9 => crate::crystal::CrystalGrain::new(g, px_per_long).map(GrainModel::Crystal), + Process::V7 | Process::V8 | Process::V9 | Process::V10 if draft => { + crate::crystal::CrystalGrain::draft(g, px_per_long).map(GrainModel::Crystal) + } + Process::V7 | Process::V8 | Process::V9 | Process::V10 => crate::crystal::CrystalGrain::new(g, px_per_long).map(GrainModel::Crystal), } } } @@ -407,7 +409,7 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap { }, // V4, with a raw's tone curve rolling off into white in stops: a camera curve past its last // knot, the generic curve from half a stop below its white point instead of clipping (issue #1632) - Process::V5 | Process::V6 | Process::V7 | Process::V8 | Process::V9 => match info.camera_tone.as_ref().filter(|_| info.raw) { + Process::V5 | Process::V6 | Process::V7 | Process::V8 | Process::V9 | Process::V10 => match info.camera_tone.as_ref().filter(|_| info.raw) { Some(curve) => ToneMap::camera_rolloff_hdr(curve, 0.0, l.whites, 0.0, peak), None if info.raw => ToneMap::rolloff_hdr(l.contrast, l.whites, l.blacks, peak), None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak), diff --git a/crates/pipeline/src/geometry.rs b/crates/pipeline/src/geometry.rs index b51f36d233..81010e190f 100644 --- a/crates/pipeline/src/geometry.rs +++ b/crates/pipeline/src/geometry.rs @@ -40,6 +40,8 @@ pub struct Frame { /// Brush Flow is coverage per brush radius travelled (process V9, [`crate::masks::flow_per_radius`]), /// not per dab. pub brush_flow_per_radius: bool, + /// A brush stroke's edge is feathered as one dab's is (process V10, [`crate::masks::stroke_feather`]). + pub brush_stroke_feather: bool, } /// Where a windowed [`Frame`]'s pixels sit in the full output: its offset and the full output's @@ -86,6 +88,7 @@ impl Frame { view: None, masks_on_photo: false, brush_flow_per_radius: crate::masks::flow_per_radius(s), + brush_stroke_feather: crate::masks::stroke_feather(s), }; if apply_crop { f.constrain_to_image(s.geometry.constrain_crop); diff --git a/crates/pipeline/src/light_v3.rs b/crates/pipeline/src/light_v3.rs index da245e7995..ccf031ca5b 100644 --- a/crates/pipeline/src/light_v3.rs +++ b/crates/pipeline/src/light_v3.rs @@ -284,7 +284,7 @@ pub fn applies(s: &DevelopSettings, info: &SourceInfo) -> bool { let camera_look = info.raw && info.camera_tone.is_some(); match s.process.process() { Process::V1 | Process::V2 | Process::V3 => false, - Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 | Process::V9 => camera_look, + Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 | Process::V9 | Process::V10 => camera_look, } } diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index be3fb758f9..73ffe65256 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -375,7 +375,7 @@ pub fn base_detail_radius(px_per_long: f64) -> usize { pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize { match s.process.process() { Process::V1 => 0, - Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 | Process::V9 => { + Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 | Process::V9 | Process::V10 => { base_detail_radius(px_per_long) } } diff --git a/crates/pipeline/src/masks.rs b/crates/pipeline/src/masks.rs index 2dc7e236f4..d93d7ee33a 100644 --- a/crates/pipeline/src/masks.rs +++ b/crates/pipeline/src/masks.rs @@ -520,6 +520,8 @@ pub struct BrushDabs { /// What each dab adds under process V9 ([`travel_flow`], pressure applied), parallel to `dabs`; /// empty before V9, where every dab adds the stroke's flow. pub flows: Vec, + /// The stroke's edge is feathered as one dab's is (process V10, [`stroke_feather`]). + pub feather_by_stroke: bool, } impl BrushDabs { @@ -559,6 +561,30 @@ impl BrushDabs { } } +/// Whether a brush stroke's edge is feathered as one dab's is (process V10 on): its coverage is +/// [`stroke_coverage`] of its Flow build-up and its dabs' highest falloff, not every dab's falloff +/// accumulated ([`accumulate`]), which piles the soft edges of overlapping dabs up into a hard one. +pub fn stroke_feather(s: &lightcraft_develop::DevelopSettings) -> bool { + s.process.process() >= lightcraft_develop::Process::V10 +} + +/// One dab's paint at a pixel of a stroke under [`stroke_feather`]: the Flow build-up `build` grows +/// by the dab's `flow` wherever the dab reaches, and the edge `edge` keeps the highest falloff `a`. +#[inline] +pub fn feather_dab(build: &mut f32, edge: &mut f32, a: f32, flow: f32) { + *build = accumulate(*build, 1.0, flow, 1.0); + *edge = edge.max(a); +} + +/// A stroke's coverage under [`stroke_feather`] from its Flow build-up and its edge +/// ([`feather_dab`]), up to its density. At Flow 100 the build-up is full wherever a dab reaches, +/// so a stroke's edge falls off over the feather exactly as one dab's does; below it, the build-up +/// is [`travel_flow`]'s, as under V9, shaped by the same edge. +#[inline] +pub fn stroke_coverage(build: f32, edge: f32, density: f32) -> f32 { + (build * edge).min(density) +} + /// Whether brush Flow is the coverage a stroke adds per brush radius it travels (process V9 on), as /// in Lightroom, rather than what every dab adds whatever the spacing of the dabs. pub fn flow_per_radius(s: &lightcraft_develop::DevelopSettings) -> bool { @@ -670,6 +696,7 @@ pub fn brush_dabs_within(s: &BrushStroke, frame: &Frame, w: usize, h: usize, max auto: s.auto_mask, pressure, flows: Vec::new(), + feather_by_stroke: frame.brush_stroke_feather, }; if frame.brush_flow_per_radius { bd.flow_by_travel() } else { bd } } @@ -882,6 +909,8 @@ fn rasterize_brush(strokes: &[BrushStroke], frame: &Frame, w: usize, h: usize, i let bd = brush_dabs(s, frame, w, h); let (dens, erase, auto) = (bd.density, bd.erase, bd.auto); let mut stroke_alpha = Plane::new(w, h); + // process V10: the Flow build-up goes in `stroke_alpha`, the edge in `edge` (`feather_dab`) + let mut edge = bd.feather_by_stroke.then(|| Plane::new(w, h)); for (k, d) in bd.dabs.iter().enumerate() { let (r, hard, flow) = bd.dab(k); let refc = auto.then(|| { @@ -902,11 +931,17 @@ fn rasterize_brush(strokes: &[BrushStroke], frame: &Frame, w: usize, h: usize, i a *= auto_similarity(log_l.data[i], chromaticity(img.data[i]), rl, rch); } let v = &mut stroke_alpha.data[i]; - // flow accumulates within a stroke up to density - *v = accumulate(*v, a, flow, dens); + match edge.as_mut().and_then(|e| e.data.get_mut(i)) { + Some(e) => feather_dab(v, e, a, flow), + // flow accumulates within a stroke up to density + None => *v = accumulate(*v, a, flow, dens), + } } } } + if let Some(edge) = &edge { + stroke_alpha = stroke_alpha.zip_map(edge, |b, e| stroke_coverage(b, e, dens)); + } if auto { let (sigma, eps) = auto_refine(bd.r); let q = guided_cross(log_l, &stroke_alpha, sigma, eps); diff --git a/crates/pipeline/src/masks/tests.rs b/crates/pipeline/src/masks/tests.rs index 2f125bc56f..bb1b6c7810 100644 --- a/crates/pipeline/src/masks/tests.rs +++ b/crates/pipeline/src/masks/tests.rs @@ -706,3 +706,70 @@ fn intersect_first_component_selects_its_shape() { let a = evaluate_one(&m, &f, 100, 100, &img, &l, 0.0, None); assert!(a.get(50, 50) > 0.99 && a.get(5, 5) < 0.01, "intersect first: {} {}", a.get(50, 50), a.get(5, 5)); } + +/// A straight stroke of radius 20 px along y = 50 of a 400 × 100 frame on `process`. +fn feathered_stroke(process: lightcraft_develop::Process, flow: f64, feather: f64) -> Plane { + let (w, h) = (400, 100); + let d = DevelopSettings { process: process.version(), ..Default::default() }; + let f = Frame::new(w, h, &d, true); + let s = BrushStroke { points: vec![Point::new(0.1, 0.5), Point::new(0.9, 0.5)], size: 0.05, feather, flow, ..Default::default() }; + shape_alpha(&MaskShape::Brush { strokes: vec![s] }, &f, w, h, &Rgb32f::new(w, h), &Plane::new(w, h), 0.0, None) +} + +/// Process V10: at Flow 100 a stroke's edge falls off over the feather exactly as one dab's does; +/// V1 to V9 accumulate the soft edges of overlapping dabs (r/4 apart) into a nearly hard one. +#[test] +fn a_stroke_is_feathered_as_one_dab_is() { + use lightcraft_develop::Process; + let r = 20.0; + for feather in [100.0, 50.0] { + let hard = r * (1.0 - feather / 100.0); + let new = feathered_stroke(Process::V10, 100.0, feather); + let old = feathered_stroke(Process::V9, 100.0, feather); + // rows below the line: pixel centre y + 0.5 is that far from it + for row in 50..72 { + let dd = row as f64 + 0.5 - 50.0; + let want = dab_alpha(dd, r, hard); + let got = new.get(200, row); + assert!((got - want).abs() < 0.02, "Feather {feather}: {dd} px off the line, {got} where one dab paints {want}"); + assert!(old.get(200, row) >= got - 1e-6, "V9 is never the softer"); + } + // halfway out at Feather 100 one dab paints 0.5; V9's stroke about 0.9 + if feather == 100.0 { + assert!((new.get(200, 60) - 0.5).abs() < 0.05, "{}", new.get(200, 60)); + assert!(old.get(200, 60) > 0.85, "V9 keeps its hard edge: {}", old.get(200, 60)); + } + } +} + +/// Process V10 below Flow 100: the centre builds up by Flow per radius travelled whatever the +/// feather, as a hard brush's does under V9 (`1 − (1 − flow)²` for a straight stroke, 44 % at Flow 25, +/// as Lightroom Classic measures, #4045), and the feather shapes only the edge. Under V9 a soft +/// brush's falloff also weakened its centre (25 % at Flow 25), as each dab's flow was scaled by it. +#[test] +fn below_full_flow_the_centre_builds_up_whatever_the_feather_and_the_edge_falls_off() { + use lightcraft_develop::Process; + for flow in [25.0, 50.0] { + let new = feathered_stroke(Process::V10, flow, 100.0); + let hard = feathered_stroke(Process::V10, flow, 0.0); + let want = 1.0 - (1.0 - flow as f32 / 100.0).powi(2); + let n = new.get(200, 50); + assert!((n - want).abs() < 0.03, "Flow {flow}: centre {n}, {want} by Flow per radius travelled"); + assert!((n - hard.get(200, 50)).abs() < 0.03, "Flow {flow}: as a hard brush's centre"); + for row in 51..72 { + assert!(new.get(200, row) <= new.get(200, row - 1) + 1e-6, "Flow {flow}: falls off away from the line (row {row})"); + assert!(new.get(200, row) <= hard.get(200, row) + 1e-6, "Flow {flow}: never more than the hard brush (row {row})"); + } + } + let old = feathered_stroke(Process::V9, 25.0, 100.0).get(200, 50); + assert!(old < 0.3, "V9's soft brush is weaker at its centre: {old}"); +} + +/// A hard brush (Feather 0) paints the same on V9 and V10. +#[test] +fn a_hard_brush_is_unchanged_by_the_stroke_feather() { + use lightcraft_develop::Process; + for flow in [25.0, 100.0] { + assert_eq!(feathered_stroke(Process::V10, flow, 0.0).data, feathered_stroke(Process::V9, flow, 0.0).data, "Flow {flow}"); + } +} diff --git a/crates/pipeline/src/tests_grain.rs b/crates/pipeline/src/tests_grain.rs index 4da1820d36..b9b83217be 100644 --- a/crates/pipeline/src/tests_grain.rs +++ b/crates/pipeline/src/tests_grain.rs @@ -35,7 +35,7 @@ fn processes_before_v7_keep_the_value_noise() { Process::V1 | Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 => { assert!(matches!(model, Some(GrainModel::Value(_))), "{p:?}") } - Process::V7 | Process::V8 | Process::V9 => assert!(matches!(model, Some(GrainModel::Crystal(_))), "{p:?}"), + Process::V7 | Process::V8 | Process::V9 | Process::V10 => assert!(matches!(model, Some(GrainModel::Crystal(_))), "{p:?}"), } assert!(GrainModel::new(&on(p, 0.0), 2000.0, false).is_none(), "{p:?}: no grain at Amount 0"); } diff --git a/crates/ui-egui/src/brush_live.rs b/crates/ui-egui/src/brush_live.rs index 466348eb1d..7a996643f7 100644 --- a/crates/ui-egui/src/brush_live.rs +++ b/crates/ui-egui/src/brush_live.rs @@ -9,7 +9,9 @@ use egui::{Color32, ColorImage, Pos2, Rect, TextureHandle, TextureOptions, pos2}; use lightcraft_geom::Point; -use lightcraft_pipeline::masks::{accumulate, dab_alpha, pressure_flow, pressure_radius, push_dabs_counted, push_pressures, travel_flow}; +use lightcraft_pipeline::masks::{ + accumulate, dab_alpha, feather_dab, pressure_flow, pressure_radius, push_dabs_counted, push_pressures, stroke_coverage, travel_flow, +}; /// The largest live-stroke buffer edge (pixels); a bigger canvas is painted at a lower resolution. const MAX_SIDE: usize = 4096; @@ -31,6 +33,9 @@ pub struct LiveParams { /// Flow is coverage per brush radius travelled (process V9, `masks::flow_per_radius`), as the /// committed stroke paints it. pub per_radius: bool, + /// The stroke's edge is feathered as one dab's is (process V10, `masks::stroke_feather`), as + /// the committed stroke paints it. + pub by_stroke: bool, /// Overlay colour and its opacity (0..1) at full coverage. pub color: [u8; 3], pub opacity: f32, @@ -42,6 +47,9 @@ pub struct LiveStroke { w: usize, h: usize, alpha: Vec, + /// Under `by_stroke`, the Flow build-up and the edge `alpha` is made of (`masks::feather_dab`). + build: Vec, + edge: Vec, /// Samples stamped so far, and the last one (buffer pixels). placed: usize, /// Total dabs emitted across every stamp, including the first sample. @@ -66,6 +74,8 @@ impl LiveStroke { w, h, alpha: vec![0.0; w * h], + build: if params.by_stroke { vec![0.0; w * h] } else { Vec::new() }, + edge: if params.by_stroke { vec![0.0; w * h] } else { Vec::new() }, placed: 0, emitted: 0, last: None, @@ -97,7 +107,7 @@ impl LiveStroke { if new.is_empty() { return false; } - let LiveParams { clip, scale, r, hard, flow, density, per_radius, .. } = self.params; + let LiveParams { clip, scale, r, hard, flow, density, per_radius, by_stroke, .. } = self.params; let (r, hard) = ((r * scale) as f64, (hard * scale) as f64); let mut dabs = Vec::new(); let mut pressures = Vec::new(); @@ -134,13 +144,29 @@ impl LiveStroke { continue; } for y in y0..y1 { - let Some(row) = self.alpha.get_mut(y * self.w + x0..y * self.w + x1) else { continue }; - for (x, v) in (x0..x1).zip(row.iter_mut()) { - let dd = Point::new(x as f64 + 0.5, y as f64 + 0.5).dist(d); - if dd > r { - continue; + let span = y * self.w + x0..y * self.w + x1; + let Some(row) = self.alpha.get_mut(span.clone()) else { continue }; + let (build, edge) = (self.build.get_mut(span.clone()), self.edge.get_mut(span)); + match (build, edge) { + (Some(build), Some(edge)) if by_stroke => { + for (x, ((v, b), e)) in (x0..x1).zip(row.iter_mut().zip(build.iter_mut()).zip(edge.iter_mut())) { + let dd = Point::new(x as f64 + 0.5, y as f64 + 0.5).dist(d); + if dd > r { + continue; + } + feather_dab(b, e, dab_alpha(dd, r, hard), flow); + *v = stroke_coverage(*b, *e, density); + } + } + _ => { + for (x, v) in (x0..x1).zip(row.iter_mut()) { + let dd = Point::new(x as f64 + 0.5, y as f64 + 0.5).dist(d); + if dd > r { + continue; + } + *v = accumulate(*v, dab_alpha(dd, r, hard), flow, density); + } } - *v = accumulate(*v, dab_alpha(dd, r, hard), flow, density); } } self.dirty = Some(match self.dirty { @@ -242,6 +268,7 @@ mod tests { flow: 1.0, density: 1.0, per_radius: true, + by_stroke: false, color: [230, 30, 40], opacity: 0.5, } @@ -283,6 +310,31 @@ mod tests { assert_eq!(s.coverage(200, 111), 0.0); } + /// Process V10 (`by_stroke`): the live stroke's edge falls off over the feather as one dab's + /// does, as the committed stroke's does (`masks::stroke_coverage`), where accumulating every + /// dab piles the soft edges up; stamped a frame at a time it is the same. + #[test] + fn by_stroke_the_live_edge_is_feathered_as_one_dab() { + let soft = LiveParams { hard: 0.0, by_stroke: true, ..params() }; + let mut s = LiveStroke::new(soft); + s.stamp(&[pos2(20.0, 100.0), pos2(380.0, 100.0)], &[]); + for dy in 0..10 { + let want = dab_alpha(dy as f64 + 0.5, 10.0, 0.0); + let got = s.coverage(200, 100 + dy); + assert!((got - want).abs() < 0.02, "{dy} px off the line: {got}, one dab paints {want}"); + } + let mut old = LiveStroke::new(LiveParams { by_stroke: false, ..soft }); + old.stamp(&[pos2(20.0, 100.0), pos2(380.0, 100.0)], &[]); + assert!(old.coverage(200, 105) > s.coverage(200, 105) + 0.2, "{} vs {}", old.coverage(200, 105), s.coverage(200, 105)); + let pts = [pos2(30.0, 40.0), pos2(200.0, 150.0), pos2(390.0, 20.0)]; + let (mut once, mut steps) = (LiveStroke::new(LiveParams { flow: 0.4, ..soft }), LiveStroke::new(LiveParams { flow: 0.4, ..soft })); + once.stamp(&pts, &[]); + for n in 1..=pts.len() { + steps.stamp(&pts[..n], &[]); + } + assert_eq!(once.alpha, steps.alpha); + } + /// Painting the samples one frame at a time gives the same coverage as all at once (what the /// committed stroke does). #[test] diff --git a/crates/ui-egui/src/panels/detail/lens_blur.rs b/crates/ui-egui/src/panels/detail/lens_blur.rs index 1f5cf3d8d1..f57c812935 100644 --- a/crates/ui-egui/src/panels/detail/lens_blur.rs +++ b/crates/ui-egui/src/panels/detail/lens_blur.rs @@ -122,8 +122,9 @@ pub(super) fn lens_blur_brush_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui hard: r * (1.0 - (app.ui.brush_feather / 100.0).clamp(0.0, 1.0)), flow: (app.ui.brush_flow / 100.0).clamp(0.0, 1.0), density: (app.ui.lens_blur_brush_amount / 100.0).clamp(0.0, 1.0), - // (its strokes render as a mask brush does, Flow per radius travelled from V9) + // (its strokes render as a mask brush does: Flow per radius travelled from V9, the edge by stroke from V10) per_radius: lightcraft_pipeline::masks::flow_per_radius(d), + by_stroke: lightcraft_pipeline::masks::stroke_feather(d), color: if focus { [70, 200, 120] } else { [230, 70, 70] }, opacity: 0.45, }; diff --git a/crates/ui-egui/src/panels/detail/masks.rs b/crates/ui-egui/src/panels/detail/masks.rs index 5b75e31e29..e94b9d2bbb 100644 --- a/crates/ui-egui/src/panels/detail/masks.rs +++ b/crates/ui-egui/src/panels/detail/masks.rs @@ -717,6 +717,7 @@ fn brush_tool( flow: (app.ui.brush_flow / 100.0).clamp(0.0, 1.0), density: 1.0, per_radius: lightcraft_pipeline::masks::flow_per_radius(d), + by_stroke: lightcraft_pipeline::masks::stroke_feather(d), color: app.ui.mask_overlay_color, opacity: opacity.clamp(0.0, 1.0), }; diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 6738321334..bc3b2ca114 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -298,7 +298,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-MASK-OBJECTS | Object selection | P2 | 🟡 | `cmd:mask.add` (`object`, `prompt`), `cmd:mask.objectPoint`, `cmd:mask.refineDetail`, `cmd:segment.prepare`, `cmd:segment.model.status`, `cmd:segment.model.download`, `cmd:segment.model.cancel`, `cmd:app.openSamModelFolder`, `crates/segment`, `crates/engine/src/segment.rs` | SAM 3 in pure Rust (candle; Metal on macOS, CPU elsewhere): Object tile → click to include, ⌥-click to leave out; Describe tile → a text prompt selects every instance ("sky", "the red car"); both also as Add/Subtract/Intersect components; + / − under the selected mask; comma lists (`car, road`); a zoomed-in detail pass for 5–10× finer edges on small objects; per-selection Edge (hard ↔ soft); the stored grid is enlarged along the photo's edges (a guided filter of its logits by log luminance, so no outline spills onto the background under a raised Exposure, #3272). The model runs on its own worker thread (the UI never waits; panics become errors; a job that fails on the Mac's GPU runs again on the CPU, which then serves the rest of the session, #1974), is unloaded after 10 min idle, and is optional: the segmentation is stored with the mask (288² logits), so renders and exports never need it. Weights are never bundled (SAM License): without them the app offers a consented background download (mirrors, resume, timeouts, SHA-256) — **but no default download location is configured yet** (users set `LIGHTCRAFT_SAM3_MIRRORS` or install by hand: the dialog names the three files, opens the configured model folder with the host opener, preserves setup on an open error, and links docs/ai-masks.md; Meta's original checkpoint installed in place of the Hugging Face one is named as such, #3378). Not verified against Lightroom's Select Object; no brush/box object mode; the first click on a photo waits for its analysis (~4 s on an M4 Pro, much longer on CPU) | | LR-MASK-PEOPLE | People parts | P2 | ⬜ | | shape exists (no UI): uses the photo's person / skin / hair / teeth / glasses mattes when it carries them (DNG semantic masks), else the subject heuristic | | LR-MASK-LANDSCAPE | Landscape classes | P2 | ⬜ | | shape exists, evaluates empty | -| LR-MASK-BRUSH | Brush mask | P0 | 🟡 | `cmd:tool.brush`, `cmd:mask.brushStroke` (`autoMask`), `crates/pipeline/src/masks.rs`, `crates/ui-egui/src/brush_live.rs` | size/feather/flow/density/erase; Create New Mask starts a separate brush in paint mode; the stroke shows while the button is held with the committed stroke's dab spacing, feather and flow, so fast strokes have no gaps (#517); with the mask overlay hidden (O / the eye, or after a mask slider hid it) or a colour overlay at opacity 0 it is not tinted while painting either, so dodging and burning is judged on the photo, and its effect shows once the stroke is committed (#2549); coverage builds up by passes, not hold time (holding the brush still adds nothing, live or committed, #518); from process V9 Flow is the coverage a stroke adds per brush radius travelled, as in Lightroom Classic (a stroke's centre: 44 % at Flow 25, 75 % at 50; measured in Lightroom 41 % and 76 %), whatever the drag speed; oversized path segments skip intermediate dabs instead of allocating a million samples; Auto Mask: dabs weighted by similarity to the colour under the dab centre, refined by a guided filter on luminance (CPU + GPU); ⇧-click draws a straight stroke from where the last stroke ended (`connect`), tapering size, feather and flow from that stroke's values when they changed; no A/B brushes; pen pressure (Brush ▸ Pen Pressure, on by default; `pressure` per point in `mask.brushStroke`) scales each dab's size (a tenth to all of it) and flow, live and committed alike, where winit reports a pen force (Windows; not macOS / Linux tablets yet); no tilt | +| LR-MASK-BRUSH | Brush mask | P0 | 🟡 | `cmd:tool.brush`, `cmd:mask.brushStroke` (`autoMask`), `crates/pipeline/src/masks.rs`, `crates/ui-egui/src/brush_live.rs` | size/feather/flow/density/erase; a stroke's edge falls off over its Feather as one dab's does (process V10, `masks::stroke_coverage`; V1 to V9 pile overlapping soft edges up); Create New Mask starts a separate brush in paint mode; the stroke shows while the button is held with the committed stroke's dab spacing, feather and flow, so fast strokes have no gaps (#517); with the mask overlay hidden (O / the eye, or after a mask slider hid it) or a colour overlay at opacity 0 it is not tinted while painting either, so dodging and burning is judged on the photo, and its effect shows once the stroke is committed (#2549); coverage builds up by passes, not hold time (holding the brush still adds nothing, live or committed, #518); from process V9 Flow is the coverage a stroke adds per brush radius travelled, as in Lightroom Classic (a stroke's centre: 44 % at Flow 25, 75 % at 50; measured in Lightroom 41 % and 76 %), whatever the drag speed; oversized path segments skip intermediate dabs instead of allocating a million samples; Auto Mask: dabs weighted by similarity to the colour under the dab centre, refined by a guided filter on luminance (CPU + GPU); ⇧-click draws a straight stroke from where the last stroke ended (`connect`), tapering size, feather and flow from that stroke's values when they changed; no A/B brushes; pen pressure (Brush ▸ Pen Pressure, on by default; `pressure` per point in `mask.brushStroke`) scales each dab's size (a tenth to all of it) and flow, live and committed alike, where winit reports a pen force (Windows; not macOS / Linux tablets yet); no tilt | | LR-MASK-LINEAR | Linear gradient | P0 | ✅ | `cmd:tool.linear`, `cmd:mask.update`, `crates/pipeline/src/mask_space.rs` | gradients, brushes and AI selections stay on the photo's content when lens corrections, Upright, Transform or Rotate Left / Right change (`Mask.on_photo`; CPU and GPU) | | LR-MASK-RADIAL | Radial gradient | P0 | ✅ | `cmd:tool.radial`, `cmd:mask.update`, `crates/ui-egui/src/panels/detail.rs` | drag the selected ellipse's body or centre pin to move; edge grips resize, outer grip rotates; rotated and compound radial components, hidden pins, outside hit rejection and one-step undo tested | | LR-MASK-COLORRANGE | Colour range | P1 | ✅ | `cmd:mask.add` (`colorRange`), `cmd:mask.sampleColor`, `cmd:mask.update`, `crates/pipeline/src/lib.rs` (`color_range_sample`) | Color tile → click the photo to sample (⇧-click adds, up to 5; samples taken in the space the mask compares in, respecting section eyes and the requested HDR/SDR rendition), Pick button, Refine slider; at most 64 samples (`MAX_COLOR_RANGE_SAMPLES`, render cost is pixels × samples) however the mask arrives: `mask.add` / `mask.update`, a sidecar's `lc:settings`, a preset, `develop.merge`, `render --settings` or the catalog and history keep the first 64 (issue #2556) | @@ -803,6 +803,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| | 2026-11-10 | minor | LR-MASK-BRUSH: process V9 makes Flow coverage per brush radius travelled, as Lightroom Classic's strokes measure on a grey card, live and committed, CPU and GPU (`masks::travel_flow`; `flow_is_coverage_per_radius_travelled_as_in_lightroom`); a stroke no longer builds up more when painted slowly; status unchanged (🟡: no A/B brushes) | +| 2026-11-17 | minor | LR-MASK-BRUSH: a stroke's edge is feathered as one dab's is (process V10); status unchanged | | 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | | 2026-11-05 | minor | LR-EDIT-LENSBLUR: ⬜ → 🟡 (Lens Blur section: Apply, Blur Amount, Boost, focus on the subject or a mask; no depth map yet); LR-MASK-SLIDERS: a Lens Blur block in every mask (selection or outside, Amount, Boost, Transition); KEY-SECTIONS: ⌘6 opens Lens Blur | | 2026-11-04 | minor | Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. See [ORF status](orf-compression.md). | diff --git a/docs/process-versions.md b/docs/process-versions.md index 78ee0b30c0..479dd7bdda 100644 --- a/docs/process-versions.md +++ b/docs/process-versions.md @@ -17,7 +17,8 @@ stronger Light sliders, issue #196) without changing a single photo someone has | **V6** | V5 plus: colour noise reduction filters the linear colour differences R−Y and B−Y with the joint method (issue #815, `docs/nr-color-joint.md`): edge-aware weights from a denoised guide shared by both differences, anisotropic diffusion over scales, a brake for isolated colour specks; Y is kept exactly. V1 to V5 keep the blurred chromaticity (`local::denoise`). CPU (`local::denoise`) and GPU (`render::denoise`) branch on `local::joint_colour_nr`. Renders with Color 0 are the same as V2's. | | **V7** | V6 plus: film grain from crystal layers ([grain.md](grain.md), `crates/pipeline/src/crystal.rs`), after Aurélien Pierre's model: resolution independent (a preview is the export's grain box-downscaled), fading out at black and white, calibrated to Lightroom Classic's strength and width at mid grey. V1 to V6 keep their two-octave value noise exactly (`finish::ValueGrain`; on the GPU `F_GRAIN_MODEL` 0); `finish::GrainModel::new` picks the model per process. Renders without grain don't depend on this. | | **V8** | V7 plus: Highlights and Shadows take their edge-aware filter of log luminance without its fine detail (`local::detail_free`: each value clamped between its separable median at the V2 radius and the median of a 3× wider neighbourhood) instead of V2's plain median (`local::base_keeps_gaps`), so the gaps in dark lettering on a bright panel are not lifted into bright blocks (issue #3460). CPU (`local::tone_base`) and GPU (`render::tone_base`) branch on it; the base plane is keyed by process. Renders without Highlights or Shadows (global or local) are the same as V7's. | -| **V9** (the latest) | V8 plus: brush Flow is the coverage a stroke adds per brush radius it travels, as in Lightroom Classic (#4045): each dab adds `1 − (1 − flow)^(d / r)` for a dab `d` past the previous one (the first dab counts one radius, so a click paints its flow), `masks::travel_flow`. A point a stroke passes over for a length `L` is then covered by `1 − (1 − flow)^(L / r)` however densely the dabs lie: a straight stroke's centre by 44 % at Flow 25 and 75 % at Flow 50, where Lightroom Classic measures 41 % and 76 % on a grey card. V1 to V8 add the full flow per dab (r/4 apart on a fast drag, closer on a slow one): 90 % at Flow 25 on a fast stroke, more on a slow one. CPU (`masks::brush_dabs_within`), GPU (a flow per dab in the `shape` kernel's brush data) and the live stroke (`brush_live`) all branch on `masks::flow_per_radius`. Renders without brush masks, or with Flow 100 only, are the same as V8's. | +| **V9** | V8 plus: brush Flow is the coverage a stroke adds per brush radius it travels, as in Lightroom Classic (#4045): each dab adds `1 − (1 − flow)^(d / r)` for a dab `d` past the previous one (the first dab counts one radius, so a click paints its flow), `masks::travel_flow`. A point a stroke passes over for a length `L` is then covered by `1 − (1 − flow)^(L / r)` however densely the dabs lie: a straight stroke's centre by 44 % at Flow 25 and 75 % at Flow 50, where Lightroom Classic measures 41 % and 76 % on a grey card. V1 to V8 add the full flow per dab (r/4 apart on a fast drag, closer on a slow one): 90 % at Flow 25 on a fast stroke, more on a slow one. CPU (`masks::brush_dabs_within`), GPU (a flow per dab in the `shape` kernel's brush data) and the live stroke (`brush_live`) all branch on `masks::flow_per_radius`. Renders without brush masks, or with Flow 100 only, are the same as V8's. | +| **V10** (the latest) | V9 plus: a brush stroke's edge is feathered as one dab's is. Each stroke keeps its Flow build-up (every dab that reaches a pixel adds its flow, `masks::feather_dab`) apart from its edge (the highest falloff of those dabs), and covers their product up to Density (`masks::stroke_coverage`). V1 to V9 accumulate each dab's falloff times its flow, so the soft edges of dabs r/4 apart piled up: at Feather 100 and Flow 100 a straight stroke covered 0.90 halfway out from its centre line, where one dab covers 0.50; V10 covers 0.50. Below Flow 100 the centre now builds up by Flow per radius travelled whatever the Feather (a straight stroke's 44 % at Flow 25), where V9 also weakened a soft brush's centre (25 %). CPU (`masks::rasterize_brush`), GPU (a stroke-record word in the `shape` kernel's brush data) and the live stroke (`brush_live`) branch on `masks::stroke_feather`. Renders without brush masks, or with Feather 0 brushes only, are the same as V9's. | ## The rule @@ -127,6 +128,7 @@ extra field and retain their existing cached renders. No cache-version bump is n | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | V10: a brush stroke's edge is feathered as one dab's is; V1 to V9 keep the accumulated soft edges | | 2026-11-11 | minor | V9: brush Flow per brush radius travelled, as in Lightroom Classic; V1 to V8 keep the flow per dab | | 2026-11-08 | minor | V8: the Highlights/Shadows base keeps the gaps in dark lettering (#3460) | | 2026-11-07 | minor | V7: film grain from crystal layers ([grain.md](grain.md)); V1 to V6 keep their value noise | diff --git a/docs/whats-new.md b/docs/whats-new.md index bd33f1a6ba..221672c6b0 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -2,6 +2,12 @@ ## Unreleased +### Brush Feather works on strokes (process V10) +- A brush stroke's edge now fades over the Feather you set. Overlapping dabs used to pile their soft edges up into an + almost hard one: at Feather 100, halfway out from a stroke's centre line was 90 % covered, and is now 50 %, as one + dab is. A soft brush at low Flow also builds up at its centre as a hard one does. New photos (and Reset) get it; + photos you already edited keep their brushes until Photo ▸ Update to Current Process. + ### Brush Flow as in Lightroom (process V9) - Flow now builds up the way it does in Lightroom: one stroke at Flow 25 covers a little under half, at Flow 50 about three quarters, where it used to cover 90 % and more, and a slow stroke covers the same as a fast one (issue #4045). From 3135bd9251f67a1adf26606ca4d33a5d35da7819 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:18:42 +0100 Subject: [PATCH 24/63] LR-PROF-CAMERACOLOR: keep CR3 diagnostic reports unambiguous --- crates/engine/src/camera_preview/tests.rs | 102 +++++++++++++++++++--- 1 file changed, 91 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index a9dc3c6133..6de43acaf1 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -3070,32 +3070,51 @@ fn check_cr3_profile_geometry_orientation(vignetted: bool) { /// Sensor, JPEG and clipping samples returned by the diagnostic proxy calls. type DiagnosticProxy = (Rgb32f, Rgb32f, Vec); +/// Keep diagnostic TSV fields single-line and reversible, including literal backslashes. +fn diagnostic_tsv_field(value: &str) -> String { + value.replace('\\', "\\\\").replace('\t', "\\t").replace('\r', "\\r").replace('\n', "\\n") +} + +/// Remove only this source's three owned output files; filesystem errors must stop the diagnostic. +fn remove_diagnostic_pngs(output: &std::path::Path, name: &str) -> std::io::Result<()> { + for label in ["plain", "chosen", "jpeg"] { + match std::fs::remove_file(output.join(format!("{name}-{label}.png"))) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + } + Ok(()) +} + /// Preserve missing-proxy cases in the diagnostic TSV without inventing geometry or fit results. /// `proxies` exposes no rejection reason, so the row records only which call returned `None`. fn diagnostic_proxies_or_report( + output: &std::path::Path, name: &str, raw: &RawImage, profile_warp: bool, plain: Option, chosen: Option, report: &mut String, -) -> Option<(DiagnosticProxy, DiagnosticProxy)> { +) -> std::io::Result> { let status = match (plain, chosen) { - (Some(plain), Some(chosen)) => return Some((plain, chosen)), + (Some(plain), Some(chosen)) => return Ok(Some((plain, chosen))), (None, Some(_)) => "missing_plain_proxy", (Some(_), None) => "missing_chosen_proxy", (None, None) => "missing_both_proxies", }; + remove_diagnostic_pngs(output, name)?; let mut fields = vec![String::new(); 17]; - fields[0] = name.to_owned(); - fields[1] = raw.metadata.model.clone().unwrap_or_default(); + fields[0] = diagnostic_tsv_field(name); + fields[1] = diagnostic_tsv_field(raw.metadata.model.as_deref().unwrap_or("")); fields[2] = format!("{:?}", raw.orientation); fields[3] = profile_warp.to_string(); fields[15] = status.to_owned(); fields[16] = "proxies returned None; underlying cause unavailable".to_owned(); report.push_str(&fields.join("\t")); report.push('\n'); - None + Ok(None) } /// Build a small RGB CR3-shaped raw and embedded JPEG without opening any real photo. @@ -3131,6 +3150,7 @@ fn diagnostic_proxy_fixture() -> (RawImage, Vec) { /// Exercise the corpus diagnostic's actual proxy-result handling across missing and available inputs. #[test] fn cr3_diagnostics_report_missing_proxies_and_continue() { + let output = std::env::temp_dir().join(format!("lc-cr3-missing-{}", std::process::id())); let (mut raw, bytes) = diagnostic_proxy_fixture(); let transform = lightcraft_raw::color::camera_transform(&raw, D65); let available = proxies(&raw, &bytes, &transform, PROXY, 0.0, None, None).unwrap(); @@ -3152,10 +3172,12 @@ fn cr3_diagnostics_report_missing_proxies_and_continue() { (missing.clone(), Some(available.clone()), "missing_plain_proxy"), (Some(available.clone()), missing, "missing_chosen_proxy"), ] { - assert!(diagnostic_proxies_or_report(status, &raw, true, plain, chosen, &mut report).is_none()); + assert!(diagnostic_proxies_or_report(&output, status, &raw, true, plain, chosen, &mut report).unwrap().is_none()); } - let (plain, chosen) = diagnostic_proxies_or_report("available", &raw, false, Some(available.clone()), Some(available.clone()), &mut report) - .expect("a later usable file must still reach measurement and image export"); + let (plain, chosen) = + diagnostic_proxies_or_report(&output, "available", &raw, false, Some(available.clone()), Some(available.clone()), &mut report) + .unwrap() + .expect("a later usable file must still reach measurement and image export"); let bits = |image: &Rgb32f| image.data.iter().flatten().map(|v| v.to_bits()).collect::>(); assert_eq!(bits(&plain.0), bits(&available.0)); assert_eq!(chosen.1.data, available.1.data); @@ -3170,6 +3192,63 @@ fn cr3_diagnostics_report_missing_proxies_and_continue() { } } +/// Tabs, line endings and literal escape sequences remain distinguishable without changing the TSV schema. +#[test] +fn cr3_diagnostics_escape_text_fields_in_missing_rows() { + let name = "A\tB\nC\rD\\t.CR3"; + let model = "Camera\tmodel\nline\rreturn\\n"; + assert_eq!(diagnostic_tsv_field(name), r"A\tB\nC\rD\\t.CR3"); + assert_eq!(diagnostic_tsv_field(model), r"Camera\tmodel\nline\rreturn\\n"); + let (mut raw, _) = diagnostic_proxy_fixture(); + raw.metadata.model = Some(model.into()); + let output = std::env::temp_dir().join(format!("lc-cr3-tsv-{}", std::process::id())); + let mut report = String::new(); + assert!(diagnostic_proxies_or_report(&output, name, &raw, false, None, None, &mut report).unwrap().is_none()); + assert_eq!(report.lines().count(), 1); + let fields: Vec<_> = report.trim_end_matches('\n').split('\t').collect(); + assert_eq!(fields.len(), 17); + assert_eq!(fields[0], diagnostic_tsv_field(name)); + assert_eq!(fields[1], diagnostic_tsv_field(model)); + assert_eq!(fields[15], "missing_both_proxies"); + assert_eq!(fields[16], "proxies returned None; underlying cause unavailable"); +} + +/// A missing-proxy rerun removes old owned PNGs and preserves unrelated files and directories. +#[test] +fn cr3_diagnostics_missing_rerun_removes_stale_pngs() { + let output = std::env::temp_dir().join(format!("lc-cr3-rerun-{}", std::process::id())); + std::fs::create_dir_all(&output).unwrap(); + let pixels = [23u8, 41, 59]; + let image = lightcraft_codecs::EncodeImage::new(1, 1, 3, lightcraft_codecs::Samples::U8(&pixels)); + let png = lightcraft_codecs::encode_png(&image, &Default::default()).unwrap(); + for label in ["plain", "chosen", "jpeg"] { + std::fs::write(output.join(format!("A.CR3-{label}.png")), &png).unwrap(); + } + std::fs::write(output.join("other.png"), &png).unwrap(); + std::fs::create_dir_all(output.join("other-directory")).unwrap(); + let (raw, _) = diagnostic_proxy_fixture(); + let mut report = String::new(); + assert!(diagnostic_proxies_or_report(&output, "A.CR3", &raw, true, None, None, &mut report).unwrap().is_none()); + std::fs::write(output.join("geometry.tsv"), &report).unwrap(); + assert_eq!(std::fs::read_to_string(output.join("geometry.tsv")).unwrap(), report); + let fields: Vec<_> = report.trim_end_matches('\n').split('\t').collect(); + assert_eq!(fields.len(), 17); + assert_eq!(fields[0], "A.CR3"); + assert_eq!(fields[15], "missing_both_proxies"); + for label in ["plain", "chosen", "jpeg"] { + assert!(!output.join(format!("A.CR3-{label}.png")).exists(), "no earlier PNG can appear current"); + } + assert_eq!(std::fs::read(output.join("other.png")).unwrap(), png); + assert!(output.join("other-directory").is_dir()); + // A directory occupying an owned filename is an error, never a request for recursive deletion. + std::fs::create_dir(output.join("A.CR3-plain.png")).unwrap(); + let before = report.clone(); + assert!(diagnostic_proxies_or_report(&output, "A.CR3", &raw, true, None, None, &mut report).is_err()); + assert_eq!(report, before, "failed cleanup must not publish a misleading missing-result row"); + assert!(output.join("A.CR3-plain.png").is_dir()); + std::fs::remove_dir_all(output).unwrap(); +} + /// Opt-in diagnostic only: never opens the app or changes a catalogue. It exports the actual /// selected correspondences, and reports rejection as rejection rather than decoder success. #[test] @@ -3206,7 +3285,7 @@ fn corpus_cr3_profile_geometry_diagnostics() { let chosen = proxies(&raw, &bytes, &transform, PROXY, 0.0, lens.as_ref(), correction.as_ref()); let name = path.file_name().unwrap().to_string_lossy(); let profile_warp = correction.as_ref().is_some_and(|l| l.warp.is_some()); - let Some((plain, chosen)) = diagnostic_proxies_or_report(&name, &raw, profile_warp, plain, chosen, &mut report) else { + let Some((plain, chosen)) = diagnostic_proxies_or_report(&output, &name, &raw, profile_warp, plain, chosen, &mut report).unwrap() else { std::fs::write(output.join("geometry.tsv"), &report).unwrap(); continue; }; @@ -3220,8 +3299,9 @@ fn corpus_cr3_profile_geometry_diagnostics() { let before = fit_preview(&raw, &bytes, &transform, lens.as_ref(), plain_correction.as_ref()).0.is_some(); let after = fit_preview(&raw, &bytes, &transform, lens.as_ref(), correction.as_ref()).0.is_some(); report.push_str(&format!( - "{name}\t{}\t{:?}\t{}\t{accepted}\t{:.6}\t{:.6}\t{}\t{}\t{}\t{}\t{before}\t{after}\t{framed_scores:?}\t{original_scores:?}\tmeasured\t\n", - raw.metadata.model.as_deref().unwrap_or(""), + "{}\t{}\t{:?}\t{}\t{accepted}\t{:.6}\t{:.6}\t{}\t{}\t{}\t{}\t{before}\t{after}\t{framed_scores:?}\t{original_scores:?}\tmeasured\t\n", + diagnostic_tsv_field(&name), + diagnostic_tsv_field(raw.metadata.model.as_deref().unwrap_or("")), raw.orientation, profile_warp, alignment(&plain.0, &plain.1), From 115bace396b3f3c460f6573362caca0958e49f8d Mon Sep 17 00:00:00 2001 From: tecari0 <121329615+tecari0@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:44:56 -0800 Subject: [PATCH 25/63] LR-MASK-BRUSH: V10 review fixes (no-Flow dabs, stroke bounds, Auto Mask) - A dab with no Flow (at pen pressure 0) no longer sets the stroke's edge: it could make a light pen stroke stronger. - The edge plane covers only the stroke's bounds and is combined in place, instead of a full-frame plane per stroke (about 92 MiB on 24 MP). - Auto Mask strokes keep V9's accumulation: their edge follows the photo's, not the feather, and V10's build-up made their colour weighting count for far dabs too (a rejected dab added Flow, and a window render drifted from the whole frame by up to 10 LSB). - whats-new and the LR-MASK-BRUSH row say the 90 % to 50 % example is at Flow 100, and that Auto Mask strokes are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/gpu/src/wgsl/mask.wgsl | 14 ++++-- crates/gpu/tests/it/equivalence.rs | 16 ++++++ crates/pipeline/src/masks.rs | 59 +++++++++++++++++------ crates/pipeline/src/masks/tests.rs | 57 ++++++++++++++++++++++ crates/ui-egui/src/panels/detail/masks.rs | 3 +- crates/ui-egui/src/tests/masking.rs | 5 +- docs/parity-checklist.md | 2 +- docs/process-versions.md | 2 +- docs/whats-new.md | 5 +- 9 files changed, 137 insertions(+), 26 deletions(-) diff --git a/crates/gpu/src/wgsl/mask.wgsl b/crates/gpu/src/wgsl/mask.wgsl index 82a6838861..5aeaa5f447 100644 --- a/crates/gpu/src/wgsl/mask.wgsl +++ b/crates/gpu/src/wgsl/mask.wgsl @@ -109,18 +109,22 @@ fn shape(@builtin(global_invocation_id) g: vec3) { if (dd > hard) { a = 1.0 - sstep(hard, r, dd); } + var sim = 1.0; if (auto_mask) { let rx = min(u32(max(floor(aux[off + 3u * j]), 0.0)), w - 1u); let ry = min(u32(max(floor(aux[off + 3u * j + 1u]), 0.0)), h - 1u); let ri = ry * w + rx; - a *= auto_similarity(lp, chp, log_l[ri], chroma_at(ri)); + sim = auto_similarity(lp, chp, log_l[ri], chroma_at(ri)); } if (by_stroke) { - // masks::feather_dab: the build-up grows by the flow, the edge keeps the highest falloff - keep *= 1.0 - flow; - edge = max(edge, a); + // masks::feather_dab (never an Auto Mask stroke): the build-up grows by the flow, + // the edge keeps the highest falloff; a dab with no Flow changes neither + if (flow > 0.0) { + keep *= 1.0 - flow; + edge = max(edge, a); + } } else { - keep *= 1.0 - a * flow; + keep *= 1.0 - a * sim * flow; } } var sa = min(1.0 - keep, aux[o + 5u]); diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 2b9f82ef12..3d130d4300 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -469,6 +469,22 @@ fn cases() -> Vec<(&'static str, Edit)> { ..Default::default() }]; }), + ("masks (brush, process V10: an Auto Mask stroke keeps V9 accumulation)", |s| { + s.process = lightcraft_develop::Process::V10.version(); + let stroke = BrushStroke { + points: vec![Point::new(0.1, 0.3), Point::new(0.5, 0.45), Point::new(0.85, 0.4)], + size: 0.06, + feather: 100.0, + flow: 40.0, + auto_mask: true, + ..Default::default() + }; + s.masks = vec![Mask { + components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: MaskShape::Brush { strokes: vec![stroke] } }], + adjust: lightcraft_develop::LocalAdjustments { exposure: -1.0, ..Default::default() }, + ..Default::default() + }]; + }), ("masks (brush, process V9: a soft stroke's dabs accumulated)", |s| { s.process = lightcraft_develop::Process::V9.version(); let stroke = BrushStroke { diff --git a/crates/pipeline/src/masks.rs b/crates/pipeline/src/masks.rs index d93d7ee33a..2295390fe2 100644 --- a/crates/pipeline/src/masks.rs +++ b/crates/pipeline/src/masks.rs @@ -520,7 +520,9 @@ pub struct BrushDabs { /// What each dab adds under process V9 ([`travel_flow`], pressure applied), parallel to `dabs`; /// empty before V9, where every dab adds the stroke's flow. pub flows: Vec, - /// The stroke's edge is feathered as one dab's is (process V10, [`stroke_feather`]). + /// The stroke's edge is feathered as one dab's is (process V10, [`stroke_feather`]), unless it + /// is an Auto Mask stroke: its edge follows the photo's, not the feather, and it keeps V9's + /// accumulation, which its colour weighting stays stable under. pub feather_by_stroke: bool, } @@ -569,11 +571,16 @@ pub fn stroke_feather(s: &lightcraft_develop::DevelopSettings) -> bool { } /// One dab's paint at a pixel of a stroke under [`stroke_feather`]: the Flow build-up `build` grows -/// by the dab's `flow` wherever the dab reaches, and the edge `edge` keeps the highest falloff `a`. +/// by the dab's `flow` wherever the dab reaches, and the edge `edge` keeps the highest falloff +/// `falloff`. A dab with no Flow (at pen pressure 0) paints nothing and shapes nothing. (Auto Mask +/// strokes don't take this: [`BrushDabs::feather_by_stroke`].) #[inline] -pub fn feather_dab(build: &mut f32, edge: &mut f32, a: f32, flow: f32) { +pub fn feather_dab(build: &mut f32, edge: &mut f32, falloff: f32, flow: f32) { + if flow.is_nan() || flow <= 0.0 { + return; + } *build = accumulate(*build, 1.0, flow, 1.0); - *edge = edge.max(a); + *edge = edge.max(falloff); } /// A stroke's coverage under [`stroke_feather`] from its Flow build-up and its edge @@ -696,7 +703,7 @@ pub fn brush_dabs_within(s: &BrushStroke, frame: &Frame, w: usize, h: usize, max auto: s.auto_mask, pressure, flows: Vec::new(), - feather_by_stroke: frame.brush_stroke_feather, + feather_by_stroke: frame.brush_stroke_feather && !s.auto_mask, }; if frame.brush_flow_per_radius { bd.flow_by_travel() } else { bd } } @@ -898,6 +905,21 @@ fn guided_cross_fast(guide: &Plane, p: &mut Plane, sigma: f32, eps: f32, weight: }); } +/// The pixels stroke `bd`'s dabs can reach in a `w × h` output, `(x0, y0, x1, y1)` (end +/// exclusive, empty when it has no dabs): its dabs' centres ± its radius (pen pressure only shrinks it). +fn stroke_bounds(bd: &BrushDabs, w: usize, h: usize) -> (usize, usize, usize, usize) { + let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for d in bd.dabs.iter().filter(|d| d.x.is_finite() && d.y.is_finite()) { + (x0, y0, x1, y1) = (x0.min(d.x - bd.r), y0.min(d.y - bd.r), x1.max(d.x + bd.r), y1.max(d.y + bd.r)); + } + if x0 > x1 || y0 > y1 { + return (0, 0, 0, 0); + } + let clip = |v: f64, n: usize| v.clamp(0.0, n as f64) as usize; + let (x0, y0) = (clip(x0.floor(), w), clip(y0.floor(), h)); + (x0, y0, clip(x1.ceil(), w).max(x0), clip(y1.ceil(), h).max(y0)) +} + /// Stamp brush strokes into `out` (max-combine; erase strokes subtract). Auto Mask strokes weight /// each dab by [`auto_similarity`] to the pixel under its centre and are refined with /// [`guided_cross`] on log luminance. @@ -910,7 +932,9 @@ fn rasterize_brush(strokes: &[BrushStroke], frame: &Frame, w: usize, h: usize, i let (dens, erase, auto) = (bd.density, bd.erase, bd.auto); let mut stroke_alpha = Plane::new(w, h); // process V10: the Flow build-up goes in `stroke_alpha`, the edge in `edge` (`feather_dab`) - let mut edge = bd.feather_by_stroke.then(|| Plane::new(w, h)); + // (the edge plane covers only the stroke's bounds: a short stroke on a big render is small) + let bounds = stroke_bounds(&bd, w, h); + let mut edge = bd.feather_by_stroke.then(|| Plane::new(bounds.2 - bounds.0, bounds.3 - bounds.1)); for (k, d) in bd.dabs.iter().enumerate() { let (r, hard, flow) = bd.dab(k); let refc = auto.then(|| { @@ -925,22 +949,29 @@ fn rasterize_brush(strokes: &[BrushStroke], frame: &Frame, w: usize, h: usize, i if dd > r { continue; } - let mut a = dab_alpha(dd, r, hard); let i = y * w + x; - if let Some((rl, rch)) = refc { - a *= auto_similarity(log_l.data[i], chromaticity(img.data[i]), rl, rch); - } + let sim = refc.map_or(1.0, |(rl, rch)| auto_similarity(log_l.data[i], chromaticity(img.data[i]), rl, rch)); + let falloff = dab_alpha(dd, r, hard); let v = &mut stroke_alpha.data[i]; - match edge.as_mut().and_then(|e| e.data.get_mut(i)) { - Some(e) => feather_dab(v, e, a, flow), + let ei = y.saturating_sub(bounds.1) * (bounds.2 - bounds.0) + x.saturating_sub(bounds.0); + match edge.as_mut().and_then(|e| e.data.get_mut(ei)) { + Some(e) => feather_dab(v, e, falloff, flow), // flow accumulates within a stroke up to density - None => *v = accumulate(*v, a, flow, dens), + None => *v = accumulate(*v, falloff * sim, flow, dens), } } } } if let Some(edge) = &edge { - stroke_alpha = stroke_alpha.zip_map(edge, |b, e| stroke_coverage(b, e, dens)); + // in place, within the bounds (outside them nothing was painted) + let ew = bounds.2 - bounds.0; + for y in bounds.1..bounds.3 { + for x in bounds.0..bounds.2 { + if let (Some(v), Some(e)) = (stroke_alpha.data.get_mut(y * w + x), edge.data.get((y - bounds.1) * ew + (x - bounds.0))) { + *v = stroke_coverage(*v, *e, dens); + } + } + } } if auto { let (sigma, eps) = auto_refine(bd.r); diff --git a/crates/pipeline/src/masks/tests.rs b/crates/pipeline/src/masks/tests.rs index bb1b6c7810..04bfc4dc31 100644 --- a/crates/pipeline/src/masks/tests.rs +++ b/crates/pipeline/src/masks/tests.rs @@ -773,3 +773,60 @@ fn a_hard_brush_is_unchanged_by_the_stroke_feather() { assert_eq!(feathered_stroke(Process::V10, flow, 0.0).data, feathered_stroke(Process::V9, flow, 0.0).data, "Flow {flow}"); } } + +/// Process V10: a dab with no Flow (pen pressure 0) neither builds up nor sets the edge. +#[test] +fn a_dab_with_no_flow_shapes_nothing() { + let (mut build, mut edge) = (0.2, 0.3); + feather_dab(&mut build, &mut edge, 1.0, 0.0); + assert_eq!((build, edge), (0.2, 0.3)); + feather_dab(&mut build, &mut edge, 0.6, 0.5); + assert!((build - 0.6).abs() < 1e-6 && (edge - 0.6).abs() < 1e-6, "{build} {edge}"); +} + +/// An Auto Mask stroke keeps V9's accumulation on V10: its edge follows the photo, not the feather. +#[test] +fn an_auto_mask_stroke_keeps_v9_accumulation() { + use lightcraft_develop::Process; + let (w, h) = (400, 100); + let img = Rgb32f::new(w, h); + let paint = |p: Process| { + let d = DevelopSettings { process: p.version(), ..Default::default() }; + let f = Frame::new(w, h, &d, true); + let s = BrushStroke { + points: vec![Point::new(0.1, 0.5), Point::new(0.9, 0.5)], + size: 0.05, + feather: 100.0, + auto_mask: true, + ..Default::default() + }; + assert!(!brush_dabs(&s, &f, w, h).feather_by_stroke); + shape_alpha(&MaskShape::Brush { strokes: vec![s] }, &f, w, h, &img, &Plane::new(w, h), 0.0, None) + }; + assert_eq!(paint(Process::V10).data, paint(Process::V9).data); +} + +/// Process V10's edge plane covers only the stroke's bounds: a stroke across the corner of the +/// frame and one in the middle paint as a full-frame plane would (nothing outside the bounds). +#[test] +fn the_stroke_bounds_hold_every_dab() { + let (w, h) = (400, 100); + let d = DevelopSettings::default(); + let f = Frame::new(w, h, &d, true); + for points in [vec![Point::new(-0.05, -0.1), Point::new(0.1, 0.2)], vec![Point::new(0.4, 0.5), Point::new(0.6, 0.55)]] { + let s = BrushStroke { points, size: 0.05, feather: 100.0, ..Default::default() }; + let bd = brush_dabs(&s, &f, w, h); + let (x0, y0, x1, y1) = stroke_bounds(&bd, w, h); + assert!(x0 <= x1 && y0 <= y1 && x1 <= w && y1 <= h); + let a = shape_alpha(&MaskShape::Brush { strokes: vec![s] }, &f, w, h, &Rgb32f::new(w, h), &Plane::new(w, h), 0.0, None); + for y in 0..h { + for x in 0..w { + if !(x0..x1).contains(&x) || !(y0..y1).contains(&y) { + assert_eq!(a.get(x, y), 0.0, "({x}, {y}) outside {:?}", (x0, y0, x1, y1)); + } + } + } + assert!(a.data.iter().any(|v| *v > 0.5), "it painted"); + } + assert_eq!(stroke_bounds(&brush_dabs(&BrushStroke::default(), &f, w, h), w, h), (0, 0, 0, 0), "no dabs"); +} diff --git a/crates/ui-egui/src/panels/detail/masks.rs b/crates/ui-egui/src/panels/detail/masks.rs index e94b9d2bbb..effb141f27 100644 --- a/crates/ui-egui/src/panels/detail/masks.rs +++ b/crates/ui-egui/src/panels/detail/masks.rs @@ -717,7 +717,8 @@ fn brush_tool( flow: (app.ui.brush_flow / 100.0).clamp(0.0, 1.0), density: 1.0, per_radius: lightcraft_pipeline::masks::flow_per_radius(d), - by_stroke: lightcraft_pipeline::masks::stroke_feather(d), + // (an Auto Mask stroke keeps V9's accumulation, as the committed one does) + by_stroke: lightcraft_pipeline::masks::stroke_feather(d) && !app.ui.brush_auto_mask, color: app.ui.mask_overlay_color, opacity: opacity.clamp(0.0, 1.0), }; diff --git a/crates/ui-egui/src/tests/masking.rs b/crates/ui-egui/src/tests/masking.rs index 3b4559c9a7..4246b79260 100644 --- a/crates/ui-egui/src/tests/masking.rs +++ b/crates/ui-egui/src/tests/masking.rs @@ -2021,8 +2021,9 @@ fn a_fast_brush_stroke_shows_without_gaps_before_the_button_is_released() { } } -/// Process V9: a Flow 25 stroke shows while the button is held as it will once committed, both -/// adding Flow per brush radius travelled (#4045): partly covered along its centre, not almost fully. +/// Process V9 (and V10, the same for this Feather 0 brush): a Flow 25 stroke shows while the button +/// is held as it will once committed, both adding Flow per brush radius travelled (#4045): partly +/// covered along its centre, not almost fully. #[test] fn a_low_flow_stroke_shows_as_it_will_be_committed() { let mut h = detail("panel.masking"); diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index bc3b2ca114..7f416dc499 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -298,7 +298,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-MASK-OBJECTS | Object selection | P2 | 🟡 | `cmd:mask.add` (`object`, `prompt`), `cmd:mask.objectPoint`, `cmd:mask.refineDetail`, `cmd:segment.prepare`, `cmd:segment.model.status`, `cmd:segment.model.download`, `cmd:segment.model.cancel`, `cmd:app.openSamModelFolder`, `crates/segment`, `crates/engine/src/segment.rs` | SAM 3 in pure Rust (candle; Metal on macOS, CPU elsewhere): Object tile → click to include, ⌥-click to leave out; Describe tile → a text prompt selects every instance ("sky", "the red car"); both also as Add/Subtract/Intersect components; + / − under the selected mask; comma lists (`car, road`); a zoomed-in detail pass for 5–10× finer edges on small objects; per-selection Edge (hard ↔ soft); the stored grid is enlarged along the photo's edges (a guided filter of its logits by log luminance, so no outline spills onto the background under a raised Exposure, #3272). The model runs on its own worker thread (the UI never waits; panics become errors; a job that fails on the Mac's GPU runs again on the CPU, which then serves the rest of the session, #1974), is unloaded after 10 min idle, and is optional: the segmentation is stored with the mask (288² logits), so renders and exports never need it. Weights are never bundled (SAM License): without them the app offers a consented background download (mirrors, resume, timeouts, SHA-256) — **but no default download location is configured yet** (users set `LIGHTCRAFT_SAM3_MIRRORS` or install by hand: the dialog names the three files, opens the configured model folder with the host opener, preserves setup on an open error, and links docs/ai-masks.md; Meta's original checkpoint installed in place of the Hugging Face one is named as such, #3378). Not verified against Lightroom's Select Object; no brush/box object mode; the first click on a photo waits for its analysis (~4 s on an M4 Pro, much longer on CPU) | | LR-MASK-PEOPLE | People parts | P2 | ⬜ | | shape exists (no UI): uses the photo's person / skin / hair / teeth / glasses mattes when it carries them (DNG semantic masks), else the subject heuristic | | LR-MASK-LANDSCAPE | Landscape classes | P2 | ⬜ | | shape exists, evaluates empty | -| LR-MASK-BRUSH | Brush mask | P0 | 🟡 | `cmd:tool.brush`, `cmd:mask.brushStroke` (`autoMask`), `crates/pipeline/src/masks.rs`, `crates/ui-egui/src/brush_live.rs` | size/feather/flow/density/erase; a stroke's edge falls off over its Feather as one dab's does (process V10, `masks::stroke_coverage`; V1 to V9 pile overlapping soft edges up); Create New Mask starts a separate brush in paint mode; the stroke shows while the button is held with the committed stroke's dab spacing, feather and flow, so fast strokes have no gaps (#517); with the mask overlay hidden (O / the eye, or after a mask slider hid it) or a colour overlay at opacity 0 it is not tinted while painting either, so dodging and burning is judged on the photo, and its effect shows once the stroke is committed (#2549); coverage builds up by passes, not hold time (holding the brush still adds nothing, live or committed, #518); from process V9 Flow is the coverage a stroke adds per brush radius travelled, as in Lightroom Classic (a stroke's centre: 44 % at Flow 25, 75 % at 50; measured in Lightroom 41 % and 76 %), whatever the drag speed; oversized path segments skip intermediate dabs instead of allocating a million samples; Auto Mask: dabs weighted by similarity to the colour under the dab centre, refined by a guided filter on luminance (CPU + GPU); ⇧-click draws a straight stroke from where the last stroke ended (`connect`), tapering size, feather and flow from that stroke's values when they changed; no A/B brushes; pen pressure (Brush ▸ Pen Pressure, on by default; `pressure` per point in `mask.brushStroke`) scales each dab's size (a tenth to all of it) and flow, live and committed alike, where winit reports a pen force (Windows; not macOS / Linux tablets yet); no tilt | +| LR-MASK-BRUSH | Brush mask | P0 | 🟡 | `cmd:tool.brush`, `cmd:mask.brushStroke` (`autoMask`), `crates/pipeline/src/masks.rs`, `crates/ui-egui/src/brush_live.rs` | size/feather/flow/density/erase; at Flow 100 a stroke's edge falls off over its Feather as one dab's does, and below it the Flow build-up is shaped by that falloff (process V10, `masks::stroke_coverage`; V1 to V9 pile overlapping soft edges up); Create New Mask starts a separate brush in paint mode; the stroke shows while the button is held with the committed stroke's dab spacing, feather and flow, so fast strokes have no gaps (#517); with the mask overlay hidden (O / the eye, or after a mask slider hid it) or a colour overlay at opacity 0 it is not tinted while painting either, so dodging and burning is judged on the photo, and its effect shows once the stroke is committed (#2549); coverage builds up by passes, not hold time (holding the brush still adds nothing, live or committed, #518); from process V9 Flow is the coverage a stroke adds per brush radius travelled, as in Lightroom Classic (a stroke's centre: 44 % at Flow 25, 75 % at 50; measured in Lightroom 41 % and 76 %), whatever the drag speed; oversized path segments skip intermediate dabs instead of allocating a million samples; Auto Mask: dabs weighted by similarity to the colour under the dab centre, refined by a guided filter on luminance (CPU + GPU); ⇧-click draws a straight stroke from where the last stroke ended (`connect`), tapering size, feather and flow from that stroke's values when they changed; no A/B brushes; pen pressure (Brush ▸ Pen Pressure, on by default; `pressure` per point in `mask.brushStroke`) scales each dab's size (a tenth to all of it) and flow, live and committed alike, where winit reports a pen force (Windows; not macOS / Linux tablets yet); no tilt | | LR-MASK-LINEAR | Linear gradient | P0 | ✅ | `cmd:tool.linear`, `cmd:mask.update`, `crates/pipeline/src/mask_space.rs` | gradients, brushes and AI selections stay on the photo's content when lens corrections, Upright, Transform or Rotate Left / Right change (`Mask.on_photo`; CPU and GPU) | | LR-MASK-RADIAL | Radial gradient | P0 | ✅ | `cmd:tool.radial`, `cmd:mask.update`, `crates/ui-egui/src/panels/detail.rs` | drag the selected ellipse's body or centre pin to move; edge grips resize, outer grip rotates; rotated and compound radial components, hidden pins, outside hit rejection and one-step undo tested | | LR-MASK-COLORRANGE | Colour range | P1 | ✅ | `cmd:mask.add` (`colorRange`), `cmd:mask.sampleColor`, `cmd:mask.update`, `crates/pipeline/src/lib.rs` (`color_range_sample`) | Color tile → click the photo to sample (⇧-click adds, up to 5; samples taken in the space the mask compares in, respecting section eyes and the requested HDR/SDR rendition), Pick button, Refine slider; at most 64 samples (`MAX_COLOR_RANGE_SAMPLES`, render cost is pixels × samples) however the mask arrives: `mask.add` / `mask.update`, a sidecar's `lc:settings`, a preset, `develop.merge`, `render --settings` or the catalog and history keep the first 64 (issue #2556) | diff --git a/docs/process-versions.md b/docs/process-versions.md index 479dd7bdda..d78f920cb2 100644 --- a/docs/process-versions.md +++ b/docs/process-versions.md @@ -18,7 +18,7 @@ stronger Light sliders, issue #196) without changing a single photo someone has | **V7** | V6 plus: film grain from crystal layers ([grain.md](grain.md), `crates/pipeline/src/crystal.rs`), after Aurélien Pierre's model: resolution independent (a preview is the export's grain box-downscaled), fading out at black and white, calibrated to Lightroom Classic's strength and width at mid grey. V1 to V6 keep their two-octave value noise exactly (`finish::ValueGrain`; on the GPU `F_GRAIN_MODEL` 0); `finish::GrainModel::new` picks the model per process. Renders without grain don't depend on this. | | **V8** | V7 plus: Highlights and Shadows take their edge-aware filter of log luminance without its fine detail (`local::detail_free`: each value clamped between its separable median at the V2 radius and the median of a 3× wider neighbourhood) instead of V2's plain median (`local::base_keeps_gaps`), so the gaps in dark lettering on a bright panel are not lifted into bright blocks (issue #3460). CPU (`local::tone_base`) and GPU (`render::tone_base`) branch on it; the base plane is keyed by process. Renders without Highlights or Shadows (global or local) are the same as V7's. | | **V9** | V8 plus: brush Flow is the coverage a stroke adds per brush radius it travels, as in Lightroom Classic (#4045): each dab adds `1 − (1 − flow)^(d / r)` for a dab `d` past the previous one (the first dab counts one radius, so a click paints its flow), `masks::travel_flow`. A point a stroke passes over for a length `L` is then covered by `1 − (1 − flow)^(L / r)` however densely the dabs lie: a straight stroke's centre by 44 % at Flow 25 and 75 % at Flow 50, where Lightroom Classic measures 41 % and 76 % on a grey card. V1 to V8 add the full flow per dab (r/4 apart on a fast drag, closer on a slow one): 90 % at Flow 25 on a fast stroke, more on a slow one. CPU (`masks::brush_dabs_within`), GPU (a flow per dab in the `shape` kernel's brush data) and the live stroke (`brush_live`) all branch on `masks::flow_per_radius`. Renders without brush masks, or with Flow 100 only, are the same as V8's. | -| **V10** (the latest) | V9 plus: a brush stroke's edge is feathered as one dab's is. Each stroke keeps its Flow build-up (every dab that reaches a pixel adds its flow, `masks::feather_dab`) apart from its edge (the highest falloff of those dabs), and covers their product up to Density (`masks::stroke_coverage`). V1 to V9 accumulate each dab's falloff times its flow, so the soft edges of dabs r/4 apart piled up: at Feather 100 and Flow 100 a straight stroke covered 0.90 halfway out from its centre line, where one dab covers 0.50; V10 covers 0.50. Below Flow 100 the centre now builds up by Flow per radius travelled whatever the Feather (a straight stroke's 44 % at Flow 25), where V9 also weakened a soft brush's centre (25 %). CPU (`masks::rasterize_brush`), GPU (a stroke-record word in the `shape` kernel's brush data) and the live stroke (`brush_live`) branch on `masks::stroke_feather`. Renders without brush masks, or with Feather 0 brushes only, are the same as V9's. | +| **V10** (the latest) | V9 plus: a brush stroke's edge is feathered as one dab's is. Each stroke keeps its Flow build-up (every dab that reaches a pixel adds its flow, `masks::feather_dab`) apart from its edge (the highest falloff of those dabs), and covers their product up to Density (`masks::stroke_coverage`). V1 to V9 accumulate each dab's falloff times its flow, so the soft edges of dabs r/4 apart piled up: at Feather 100 and Flow 100 a straight stroke covered 0.90 halfway out from its centre line, where one dab covers 0.50; V10 covers 0.50. Below Flow 100 the centre now builds up by Flow per radius travelled whatever the Feather (a straight stroke's 44 % at Flow 25), where V9 also weakened a soft brush's centre (25 %). CPU (`masks::rasterize_brush`), GPU (a stroke-record word in the `shape` kernel's brush data) and the live stroke (`brush_live`) branch on `masks::stroke_feather`. Auto Mask strokes keep V9's accumulation (their edge follows the photo's edges, not the feather). Renders without brush masks, or with Feather 0 or Auto Mask brushes only, are the same as V9's. | ## The rule diff --git a/docs/whats-new.md b/docs/whats-new.md index 221672c6b0..69910c778f 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -4,8 +4,9 @@ ### Brush Feather works on strokes (process V10) - A brush stroke's edge now fades over the Feather you set. Overlapping dabs used to pile their soft edges up into an - almost hard one: at Feather 100, halfway out from a stroke's centre line was 90 % covered, and is now 50 %, as one - dab is. A soft brush at low Flow also builds up at its centre as a hard one does. New photos (and Reset) get it; + almost hard one: at Feather 100 and Flow 100, halfway out from a stroke's centre line was 90 % covered, and is + now 50 %, as one dab is. A soft brush at low Flow also builds up at its centre as a hard one does. Auto Mask strokes, whose edge + follows the photo's, are unchanged. New photos (and Reset) get it; photos you already edited keep their brushes until Photo ▸ Update to Current Process. ### Brush Flow as in Lightroom (process V9) From a6809855a46f595ddff7a58dd4797a57c62837ad Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:08:27 +0100 Subject: [PATCH 26/63] Keep the loaded camera profile fingerprint across lens reloads --- crates/engine/src/camera_profiles.rs | 62 +++++++++++++++------------- 1 file changed, 34 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/camera_profiles.rs b/crates/engine/src/camera_profiles.rs index e292ff549b..e6b55d01ff 100644 --- a/crates/engine/src/camera_profiles.rs +++ b/crates/engine/src/camera_profiles.rs @@ -173,6 +173,8 @@ fn cache() -> &'static Mutex { /// The profile for camera `model`: from [`dir`], else built in; read once per process. pub fn get(model: &str) -> Option> { + // Capture the process fingerprint before a profile can enter the lookup cache. + stable_profile_key(); get_from(model, dir().as_deref()) } @@ -232,29 +234,23 @@ fn get_from(model: &str, directory: Option<&Path>) -> Option> profile } -/// Changes when the profiles folder's contents change (per process): part of the render cache -/// keys, so thumbnails rendered before a profile existed are not reused after. Includes the -/// loaded lens database: its geometry determines which sensor/JPEG samples fit the camera look. +/// Identity of the camera-profile lookup cache and of the currently loaded lens database. +/// The camera profiles already loaded by this process outlive file changes on disk. A lens +/// reload changes only the lens part of the key used by thumbnails and rendered views. pub fn cache_key() -> u64 { - static KEY: Mutex> = Mutex::new(None); - let lens_key = crate::lens_profiles::cache_key(); - let mut key = KEY.lock().unwrap_or_else(PoisonError::into_inner); - if let Some((previous_lens, value)) = *key - && previous_lens == lens_key - { - return value; - } - let value = cache_key_with_lens(dir().as_deref(), lens_key); - *key = Some((lens_key, value)); - value + cache_key_with_lens(stable_profile_key(), crate::lens_profiles::cache_key()) +} + +fn stable_profile_key() -> u64 { + static KEY: OnceLock = OnceLock::new(); + *KEY.get_or_init(|| cache_key_for(dir().as_deref())) +} + +fn cache_key_with_lens(profile_key: u64, lens_key: u64) -> u64 { + lightcraft_preview::Hasher128::new().str("camera-profiles-with-lens-v2").u64(profile_key).u64(lens_key).finish().0 as u64 } -#[cfg(test)] fn cache_key_for(directory: Option<&Path>) -> u64 { - cache_key_with_lens(directory, 0) -} - -fn cache_key_with_lens(directory: Option<&Path>, lens_key: u64) -> u64 { let entries = directory.and_then(|d| std::fs::read_dir(d).ok()); let mut files: Vec<(String, u64, std::time::Duration)> = entries .into_iter() @@ -269,7 +265,6 @@ fn cache_key_with_lens(directory: Option<&Path>, lens_key: u64) -> u64 { .collect(); files.sort(); let mut h = lightcraft_preview::Hasher128::new(); - h.str("camera-profiles-with-lens-v1").u64(lens_key); for (name, len, modified) in &files { h.str(name).u64(*len).u64(modified.as_secs()).u64(u64::from(modified.subsec_nanos())); } @@ -379,10 +374,14 @@ mod tests { assert!(crate::lens_profiles::database().is_some(), "fixture database was loaded by the public loader"); let lens_key = crate::lens_profiles::cache_key(); assert_ne!(lens_key, 0); - let directory = dir(); - assert_eq!(cache_key(), cache_key_with_lens(directory.as_deref(), lens_key)); - assert_ne!(cache_key(), cache_key_with_lens(directory.as_deref(), 0), "public camera key must forward the loaded lens key"); + let directory = dir().unwrap(); + let profile = profile(); + save(&profile, &directory).unwrap(); + assert_eq!(get(&profile.model).as_deref(), Some(&profile)); + let profile_key = cache_key_for(Some(&directory)); let first = cache_key(); + assert_eq!(first, cache_key_with_lens(profile_key, lens_key)); + assert_ne!(first, cache_key_with_lens(profile_key, 0), "public camera key must forward the loaded lens key"); // The culling path now reuses rendered views before decoding. Their identity // must follow the same loaded lens snapshot as camera fitting and thumbnails. let mut session = crate::Session::with_demo(); @@ -391,14 +390,21 @@ mod tests { let (views, view_key) = view.view_cache.as_ref().unwrap(); views.put_memory(*view_key, std::sync::Arc::new(lightcraft_raster::Rgba8::from_fn(64, 64, |_, _| [7, 19, 31, 255]))); assert!(session.loupe_job(id, 64, 64, true).unwrap().cached_view().is_some()); - let file = directory.unwrap().join("lens.xml"); + let mut replacement = profile.clone(); + replacement.samples *= 100; + save(&replacement, &directory).unwrap(); + assert_ne!(cache_key_for(Some(&directory)), profile_key, "a fresh process sees a different camera profile fingerprint"); + assert_eq!(get(&profile.model).as_deref(), Some(&profile), "the loaded profile stays cached"); + + let file = directory.join("lens.xml"); let xml = std::fs::read_to_string(&file).unwrap(); std::fs::write(&file, xml.replace("-0.03", "-0.05")).unwrap(); assert_eq!(cache_key(), first, "unreloaded files do not change the loaded database"); crate::lens_profiles::replaced(); assert_ne!(cache_key(), first, "camera keys follow runtime lens replacements too"); + let new_lens_key = crate::lens_profiles::cache_key(); + assert_eq!(cache_key(), cache_key_with_lens(profile_key, new_lens_key)); assert!(session.loupe_job(id, 64, 64, true).unwrap().cached_view().is_none(), "a view from the old snapshot is not reused"); - assert_eq!(cache_key(), cache_key_with_lens(dir().as_deref(), crate::lens_profiles::cache_key())); std::fs::write(&file, xml).unwrap(); crate::lens_profiles::reload(); assert_eq!(cache_key(), first, "restored semantic data restores the camera key"); @@ -453,9 +459,9 @@ mod tests { #[test] fn lens_database_identity_invalidates_camera_render_cache() { - assert_ne!(cache_key_with_lens(None, 0), cache_key_with_lens(None, 123)); - assert_ne!(cache_key_with_lens(None, 123), cache_key_with_lens(None, 456)); - assert_eq!(cache_key_with_lens(None, 123), cache_key_with_lens(None, 123)); + assert_ne!(cache_key_with_lens(1234, 0), cache_key_with_lens(1234, 123)); + assert_ne!(cache_key_with_lens(1234, 123), cache_key_with_lens(1234, 456)); + assert_eq!(cache_key_with_lens(1234, 123), cache_key_with_lens(1234, 123)); } #[test] From 971deb7169cc1f438b9c3e88608ef6812b66c328 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:50:54 +0100 Subject: [PATCH 27/63] Preserve pooled CR3 color pairs when profile geometry falls back --- crates/engine/src/camera_preview/proxy.rs | 58 +++++++++++++++++++---- crates/engine/src/camera_preview/tests.rs | 25 ++++++++-- docs/cr3-profile-alignment.md | 3 +- 3 files changed, 74 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/camera_preview/proxy.rs b/crates/engine/src/camera_preview/proxy.rs index 1bf7be0c3e..d9686b68f4 100644 --- a/crates/engine/src/camera_preview/proxy.rs +++ b/crates/engine/src/camera_preview/proxy.rs @@ -80,6 +80,11 @@ pub(super) fn structure_agrees(sensor: &Rgb32f, reference: &Rgb32f) -> bool { at_zero >= MIN_STRUCTURE && shift.0.abs() <= 1 && shift.1.abs() <= 1 } +enum ProxyLens<'a> { + PerFile(Option<&'a lightcraft_develop::EmbeddedLens>), + Pooled(Option<&'a lightcraft_develop::EmbeddedLens>), +} + /// Same-size proxies of the sensor (white-balanced, baseline exposure, through `transform`'s /// matrix: the generic camera ≈ sRGB model) and of the file's embedded camera JPEG (linear Rec.2020), /// and per proxy pixel whether any sensor sample it covers is clipped. `embedded`'s vignetting correction is applied to @@ -93,6 +98,18 @@ pub(super) fn proxies( min_fraction: f64, lens: Option<&LensGeometry>, embedded: Option<&lightcraft_develop::EmbeddedLens>, +) -> Option<(Rgb32f, Rgb32f, Vec)> { + proxies_with_lens(raw, bytes, transform, size, min_fraction, lens, ProxyLens::PerFile(embedded)) +} + +fn proxies_with_lens( + raw: &RawImage, + bytes: &[u8], + transform: &CameraTransform, + size: usize, + min_fraction: f64, + lens: Option<&LensGeometry>, + profile: ProxyLens<'_>, ) -> Option<(Rgb32f, Rgb32f, Vec)> { let edge = (2 * size).max(384) as u32; let decoded = crate::files::decode_raw_preview( @@ -128,7 +145,13 @@ pub(super) fn proxies( let k = (crop.width.max(crop.height).div_ceil(edge as usize).max(2)).div_ceil(2) * 2; let mut sensor = sensor_proxy(raw, k, edge as usize)?; let mut clipped = clip_mask(&sensor); - correct_vignetting(&mut sensor, embedded, raw.orientation); + let embedded = match profile { + ProxyLens::PerFile(embedded) => { + correct_vignetting(&mut sensor, embedded, raw.orientation); + embedded + } + ProxyLens::Pooled(embedded) => embedded, + }; // The camera may have corrected its JPEG with the lens warp the file carries (Nikon Z lenses always, at up to 9 % // zoom; other cameras when their correction setting is on): the sensor moved into that geometry is a candidate, // kept below when it lines up with the JPEG better than the uncorrected one. @@ -139,12 +162,21 @@ pub(super) fn proxies( let to_working = |p: [f32; 3]| transform.matrix.apply_f32(std::array::from_fn(|i| p[i] * transform.wb[i] * gain)); if raw.format == RawFormat::Cr3 { // Orient the camera JPEG and the sensor identically before collecting pixel correspondences. + let correction = embedded.filter(|correction| transform.matrix_is_fallback && lens.is_none() && correction.warp.is_some()); + // A pooled fit historically used an unshaded framing fallback. Apply database shading + // only to the proposed sensor, at the source position before orientation and the warp. + let pooled_candidate = correction.filter(|c| matches!(profile, ProxyLens::Pooled(_)) && c.vignette.is_some()).map(|correction| { + let mut candidate = sensor.clone(); + correct_vignetting(&mut candidate, Some(correction), raw.orientation); + let mut candidate = candidate.into_oriented(raw.orientation); + candidate.map_in_place(to_working); + candidate + }); sensor = sensor.into_oriented(raw.orientation); clipped = clipped.into_oriented(raw.orientation); reference = reference.into_oriented(raw.orientation); sensor.map_in_place(to_working); - let correction = embedded.filter(|correction| transform.matrix_is_fallback && lens.is_none() && correction.warp.is_some()); - (sensor, clipped) = align_cr3_geometry(sensor, clipped, &reference, correction); + (sensor, clipped) = align_cr3_geometry(sensor, clipped, &reference, correction, pooled_candidate.as_ref()); } let mut sensor = fit(&sensor, size, size, Filter::Box); let mut reference_small = reference_at(&reference, &sensor); @@ -412,21 +444,31 @@ pub(super) fn align_cr3_geometry( clipped: Rgb32f, reference: &Rgb32f, correction: Option<&lightcraft_develop::EmbeddedLens>, + candidate_sensor: Option<&Rgb32f>, ) -> (Rgb32f, Rgb32f) { - let framing = estimate_cr3_framing(&sensor, reference); - let fallback = framing.map(|framing| apply_cr3_framing(&sensor, framing)); + let frame = |source: &Rgb32f| { + let framing = estimate_cr3_framing(source, reference); + (framing, framing.map(|framing| apply_cr3_framing(source, framing))) + }; + // Score the warp against the same shading on the original and framed baselines. + let source = candidate_sensor.unwrap_or(&sensor); + let (mut framing, mut fallback) = frame(source); if let Some(proposed) = correction.and_then(|correction| { align_profile_geometry_against( - &sensor, + source, &clipped, reference, correction, lightcraft_geom::Orientation::Normal, - Some(fallback.as_ref().unwrap_or(&sensor)), + Some(fallback.as_ref().unwrap_or(source)), ) }) { return proposed; } + if candidate_sensor.is_some() { + // The pooled proposal was rejected. Restore the framing selected on the original samples. + (framing, fallback) = frame(&sensor); + } // The mask is needed only if the fallback wins; when no framing is accepted, // return both original allocations unchanged. let clipped = if let Some(framing) = framing { apply_cr3_framing(&clipped, framing) } else { clipped }; @@ -519,7 +561,7 @@ pub(crate) fn profile_pairs( return None; } let transform = lightcraft_raw::color::camera_transform(raw, lightcraft_raw::color::as_shot_white_xy(raw)); - let (sensor, reference, clipped) = proxies(raw, bytes, &transform, PROFILE_PROXY, 0.0, lens, correction)?; + let (sensor, reference, clipped) = proxies_with_lens(raw, bytes, &transform, PROFILE_PROXY, 0.0, lens, ProxyLens::Pooled(correction))?; let to_camera = transform.matrix.inverse()?; // clipped sensor pixels don't record the scene's colour (see `fit_look`) let sensor = without_clipped(&sensor, &clipped).unwrap_or(sensor); diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index 6de43acaf1..15e4b43cef 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -2693,7 +2693,7 @@ fn cr3_unchanged_geometry_preserves_allocations_and_bounds_search_work() { let mask_ptr = mask.data.as_ptr(); let mask_bits: Vec<_> = mask.data.iter().map(|p| p.map(f32::to_bits)).collect(); super::proxy::take_framing_search_count(); - let (aligned, aligned_mask) = super::proxy::align_cr3_geometry(sensor, mask, &reference, correction.as_ref()); + let (aligned, aligned_mask) = super::proxy::align_cr3_geometry(sensor, mask, &reference, correction.as_ref(), None); assert_eq!(super::proxy::take_framing_search_count(), searches, "bounded search budget for missing or rejected geometry"); assert_eq!(aligned.data.as_ptr(), sensor_ptr, "no accepted framing or warp: retain sensor allocation"); assert_eq!(aligned_mask.data.as_ptr(), mask_ptr, "no accepted framing or warp: retain mask allocation"); @@ -2715,7 +2715,7 @@ fn cr3_geometry_selects_matching_profile_with_one_search_per_geometry() { let mask = Rgb32f::new(sensor.width, sensor.height); let expected_mask = profile_geometry_target(&mask, &lens, framing); super::proxy::take_framing_search_count(); - let (aligned, aligned_mask) = super::proxy::align_cr3_geometry(sensor, mask, &reference, Some(&lens)); + let (aligned, aligned_mask) = super::proxy::align_cr3_geometry(sensor, mask, &reference, Some(&lens), None); assert_eq!(super::proxy::take_framing_search_count(), 2); assert!(super::proxy::geometry_gate_scores().is_some(), "proposal passed original geometry gates"); assert!(super::proxy::geometry_framed_scores().is_some(), "proposal was compared with fallback on both splits"); @@ -3043,7 +3043,15 @@ fn check_cr3_profile_geometry_orientation(vignetted: bool) { let orientation = lightcraft_geom::Orientation::from_exif(exif); raw.orientation = orientation; let oriented_lens = lightcraft_pipeline::optics::reorient_lens(&lens, orientation, 384.0, 256.0); - let (aligned, reference, _) = proxies(&raw, &file, &transform, PROFILE_PROXY, 0.0, None, Some(&oriented_lens)).unwrap(); + let (aligned, reference, clipped) = proxies(&raw, &file, &transform, PROFILE_PROXY, 0.0, None, Some(&oriented_lens)).unwrap(); + if vignetted && exif == 6 { + let sensor = without_clipped(&aligned, &clipped).unwrap_or_else(|| aligned.clone()); + let to_camera = transform.matrix.inverse().unwrap(); + let expected: Vec<_> = + collect_pairs(&sensor, &reference, 0.05, None, false).unwrap().0.into_iter().map(|(x, y)| (to_camera.apply(x), y)).collect(); + let pairs = profile_pairs(&raw, &file, None, Some(&oriented_lens)).unwrap(); + assert!(pairs == expected, "an accepted pooled warp keeps the source-position vignette in a rotated crop"); + } let mut no_warp = oriented_lens; no_warp.warp = None; let (baseline, _, _) = proxies(&raw, &file, &transform, PROFILE_PROXY, 0.0, None, Some(&no_warp)).unwrap(); @@ -3385,4 +3393,15 @@ fn cr3_rejected_profile_preserves_accepted_framing_fallback() { ); assert_eq!(reference.data, fallback_reference.data); assert_eq!(mask, fallback_mask); + + let plain_pairs = profile_pairs(&raw, &file, None, None).expect("the uncorrected fallback contributes colour pairs"); + let mut correction = lens; + correction.vignette = + Some(lightcraft_develop::EmbeddedVignette { k: [0.15, 0.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.5, 0.5), radius: 0.6 }); + let rejected_warp = correction.warp; + for (case, warp) in [("rejected warp", rejected_warp), ("absent warp", None)] { + correction.warp = warp; + let pairs = profile_pairs(&raw, &file, None, Some(&correction)).expect("the fallback still contributes colour pairs"); + assert!(pairs == plain_pairs, "{case} must preserve the original pooled samples with a nonzero vignette"); + } } diff --git a/docs/cr3-profile-alignment.md b/docs/cr3-profile-alignment.md index be694df49a..5744d55d19 100644 --- a/docs/cr3-profile-alignment.md +++ b/docs/cr3-profile-alignment.md @@ -27,7 +27,8 @@ tone, hue/saturation, clipping, and held-out acceptance gates stay unchanged. The proposal reaches file-local colour and tone, pooled camera-profile pairs, and colour tags for merge/DNG conversion. The DNG colour fit uses the external profile for correspondence geometry without its vignette gains: the unchanged sensor samples and the DNG writer do not carry that -database shading correction. File-local and pooled fits retain source-position vignetting. +database shading correction. File-local fits retain source-position vignetting. Pooled fits apply the profile’s vignette +to an accepted warp and keep the original unshaded colour pairs when the warp is absent or rejected. Cache versions advance from upstream look 14/render 77 to look 15/render 78. The loaded database semantic identity also invalidates camera render/view keys, Smart-preview headers and scan markers. Fresh original decodes retain the photo’s hot-pixel setting; offline From d74ac26c5eceeead69833bce50f2d53a8b953763 Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Sun, 22 Nov 2026 17:08:13 +0100 Subject: [PATCH 28/63] LR-MERGE-PANO: bound pair diagnostics --- ROADMAP.md | 6 +- crates/engine/src/merge.rs | 4 +- crates/engine/src/tests/merge.rs | 1 + crates/merge/src/pano.rs | 11 ++- crates/merge/src/pano/camera.rs | 121 ++++++++++++++---------- crates/merge/tests/pair_verification.rs | 28 +++++- crates/ui-egui/src/dialogs/merge.rs | 17 ++-- docs/gaps.md | 2 +- docs/merge.md | 14 ++- docs/target-app-parity.md | 2 +- 10 files changed, 129 insertions(+), 77 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 226d593d53..fb64576dc7 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) | **83.3%** of 543 rows (P0 98.3%, P1 94.4%, P2 56.2%) | 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 83.3%) | 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) | @@ -124,7 +124,7 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/ 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. The original waterfall case (#1765) remains unverified. + 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`); diff --git a/crates/engine/src/merge.rs b/crates/engine/src/merge.rs index d3718f056d..91e7046374 100644 --- a/crates/engine/src/merge.rs +++ b/crates/engine/src/merge.rs @@ -294,7 +294,9 @@ fn pano_source_info( }) }) .collect(); - json!({"used": used, "omitted": omitted, "pairs": pairs}) + 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 diff --git a/crates/engine/src/tests/merge.rs b/crates/engine/src/tests/merge.rs index fa9c4bde16..e94f393694 100644 --- a/crates/engine/src/tests/merge.rs +++ b/crates/engine/src/tests/merge.rs @@ -216,6 +216,7 @@ fn panorama_reports_omitted_source_photos() { 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])); diff --git a/crates/merge/src/pano.rs b/crates/merge/src/pano.rs index fe90c68e9e..7f5dd171e0 100644 --- a/crates/merge/src/pano.rs +++ b/crates/merge/src/pano.rs @@ -74,7 +74,7 @@ pub struct PanoResult { pub projection: Projection, /// Indices (into the inputs) of the frames with recovered cameras in this panorama. pub used: Vec, - /// Measurements for all input pairs, including rejected pairs. + /// 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>, @@ -178,11 +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_with_diagnostics(frames, progress)?; + let (cameras, before, after, _) = register_impl(frames, progress, false)?; Ok((cameras, before, after)) } -fn register_with_diagnostics(frames: &[Frame], progress: &Progress) -> Result<(Vec>, f64, f64, Vec)> { +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() @@ -195,7 +195,8 @@ fn register_with_diagnostics(frames: &[Frame], progress: &Progress) -> Result<(V check(progress, 0.2, "Matching")?; let feats: Vec<_> = work.iter().map(|(f, _)| f.clone()).collect(); let scales: Vec = work.iter().map(|(_, s)| *s).collect(); - let (pairs, diagnostics) = camera::match_pairs_with_diagnostics(&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("could not align at least two photos for a panorama".into())); @@ -246,7 +247,7 @@ pub fn stitch(mut frames: Vec, opts: &PanoOptions, progress: &Progress) - return Err(MergeError::TooMany(n, MAX_FRAMES)); } check(progress, 0.01, "Finding features")?; - let (cams, rms_before, rms, pairs) = register_with_diagnostics(&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 { diff --git a/crates/merge/src/pano/camera.rs b/crates/merge/src/pano/camera.rs index 0ca7310407..4960bcbcdf 100644 --- a/crates/merge/src/pano/camera.rs +++ b/crates/merge/src/pano/camera.rs @@ -79,62 +79,83 @@ pub struct PairDiagnostic { pub status: PairStatus, } -/// Match every pair of images. `feats[k]` are in work coordinates scaled by `scales[k]`. -pub fn match_pairs(feats: &[Features], scales: &[f64]) -> Vec { - match_pairs_with_diagnostics(feats, scales).0 +/// 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))) } -/// As [`match_pairs`], retaining rejected pairs as well as accepted ones, in input-pair order. +/// 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(); - // Generate input pairs lazily, without a second quadratic vector of pair indices. - let mut results: Vec<(Option, PairDiagnostic)> = (0..n) - .into_par_iter() - .flat_map_iter(|i| ((i + 1)..n).map(move |j| (i, j))) - .map(|(i, j)| { - let m = features::match_features(&feats[i], &feats[j], 0.8); - let mut diagnostic = PairDiagnostic { i, j, matches: m.len(), inliers: None, status: PairStatus::InsufficientMatches }; - if m.len() < 12 { - return (None, diagnostic); - } - 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 { - diagnostic.status = PairStatus::NoModel; - return (None, diagnostic); - }; - diagnostic.inliers = Some(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 (fit.inliers.len() as f64) <= 8.0 + 0.3 * m.len() as f64 { - diagnostic.status = PairStatus::Rejected; - return (None, diagnostic); - } - diagnostic.status = 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 }), diagnostic) - }) - .collect(); - results.sort_by_key(|(_, d)| (d.i, d.j)); - let (mut out, mut diagnostics) = (Vec::new(), Vec::with_capacity(results.len())); - for (pair, diagnostic) in results { - log::debug!( - "panorama pair {}-{}: matches={}, inliers={:?}, status={:?}", - diagnostic.i, - diagnostic.j, - diagnostic.matches, - diagnostic.inliers, - diagnostic.status + 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) + }, ); - out.extend(pair); - diagnostics.push(diagnostic); + 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; } - (out, diagnostics) + 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/pair_verification.rs b/crates/merge/tests/pair_verification.rs index ccca10dcc2..a85b24f9e6 100644 --- a/crates/merge/tests/pair_verification.rs +++ b/crates/merge/tests/pair_verification.rs @@ -43,16 +43,14 @@ fn moving_scene_regime_is_rejected_despite_a_recovered_homography() { 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_eq!(recovered.inliers.len(), inliers); 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); } - eprintln!("known homography: {inliers}/{n}, rms={:.6}, accepted={}", recovered.rms, !match_pairs(&f, &[1.0; 2]).is_empty()); // 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!(inliers as f64 > 8.0 + 0.15 * n as f64, "the proposed lower slope admits it"); + assert!(recovered.inliers.len() as f64 > 8.0 + 0.15 * n as f64, "the proposed lower slope admits it"); } } @@ -65,7 +63,6 @@ fn a_repeated_patch_can_pass_the_lower_slope_with_the_wrong_camera_motion() { 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_eq!(r.inliers.len(), 36); 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()); @@ -117,9 +114,30 @@ fn diagnostics_keep_rejected_and_unmatched_pairs_in_input_order() { 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)]); - assert_eq!((diagnostics[0].matches, diagnostics[0].inliers, diagnostics[0].status), (104, Some(31), PairStatus::Rejected)); + 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/merge.rs b/crates/ui-egui/src/dialogs/merge.rs index ccdd866ce0..4425adbb6f 100644 --- a/crates/ui-egui/src/dialogs/merge.rs +++ b/crates/ui-egui/src/dialogs/merge.rs @@ -634,12 +634,17 @@ mod tests { #[test] fn completed_panorama_reports_its_actual_inclusion_count() { - let info = json!({"used": [71, 9], "omitted": [{"id": 401, "path": "waterfall-3.png", "reason": "notRegistered"}]}); - assert_eq!(added_message("Panorama", &info), "Panorama merge added\n2 of 3 photos included"); - // All exposures are individual photos in the HDR panorama result. - let hdr = json!({"used": [71, 9, 401, 3], "omitted": [{"id": 6}, {"id": 12}]}); - assert_eq!(added_message("HDR panorama", &hdr), "HDR panorama merge added\n4 of 6 photos included"); - assert_eq!(added_message("Panorama", &json!({"used": [1, 2], "omitted": []})), "Panorama merge added\n2 of 2 photos included"); + 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. diff --git a/docs/gaps.md b/docs/gaps.md index 9ad9b93444..207c70bb53 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -42,7 +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) | -| 31 | **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`; waterfall originals unavailable | panoramas may omit part of the scene | not estimated without real fixtures | [merge](merge.md#panorama-inclusion-diagnostics) | +| 31 | **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 / ⇧Tab (hide the side panels / all panels; Tab moves the keyboard focus here) and F5. Rating `[` `]`, flag cycling (`` ` ``), `\` (Filter Bar), ⌘L (Enable Filters), ⌘⌥⇧C / ⌘⌥⇧V (Copy / Paste Metadata), F1 help, F6 / F7 / F8 (filmstrip, left panel, right panel) are bound; the grid-cycle key is shown beside both grid rows in View (#2500) | [ui-parity](ui-parity.md#shortcuts) | Classic muscle memory | 2–4 | [ui-parity](ui-parity.md) | | 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) | diff --git a/docs/merge.md b/docs/merge.md index 31bb26a468..81c338eece 100644 --- a/docs/merge.md +++ b/docs/merge.md @@ -30,8 +30,10 @@ Panorama and HDR panorama results include `used` (source photo IDs, in source or `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. These fields describe this run; a preview -and a full merge can use different photos because they run at different resolutions. +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. Pair measurements also appear at debug log level, including when @@ -48,9 +50,11 @@ among 100 to 140 matches, then reproduce their rejection. A slope of 0.15 also a tests' coherent wrong panel match and translated-camera parallax. Spatial spread and a small reprojection error alone do not distinguish all of these cases. -This is a diagnostic improvement, not a fix for the reporter's waterfall registration. -The original waterfall photos were unavailable. A three-frame, 800 by 600 moving-texture -experiment fails registration, while its clean control registers all three frames. +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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 84d9beb490..2d91dc7804 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 | From e2a6bc909215bd6250e7817d214cc781332e4a73 Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Sun, 22 Nov 2026 18:49:16 +0100 Subject: [PATCH 29/63] LR-MERGE-PANO: name the final merge's omitted photos The final merge registers the full-size photos again, so it can leave out other photos than the preview did. When it omits photos, a Photo Merge Result dialog lists the final result's omitted file names, using the preview's list. It waits for a dialog the user already has open, and its message is a polite live region. Nothing changes when no photo is omitted. --- crates/ui-egui/locales/cs.json | 2 ++ crates/ui-egui/locales/de.json | 2 ++ crates/ui-egui/locales/es.json | 2 ++ crates/ui-egui/locales/fi.json | 2 ++ crates/ui-egui/locales/fr.json | 2 ++ crates/ui-egui/locales/id.json | 2 ++ crates/ui-egui/locales/it.json | 2 ++ crates/ui-egui/locales/ja.json | 2 ++ crates/ui-egui/locales/ka.json | 2 ++ crates/ui-egui/locales/pl.json | 2 ++ crates/ui-egui/locales/pt-br.json | 2 ++ crates/ui-egui/locales/ru.json | 2 ++ crates/ui-egui/locales/sv.json | 2 ++ crates/ui-egui/locales/uk.json | 2 ++ crates/ui-egui/locales/vi.json | 2 ++ crates/ui-egui/locales/zh-hans.json | 2 ++ crates/ui-egui/locales/zh-hant.json | 2 ++ crates/ui-egui/src/dialogs.rs | 3 ++ crates/ui-egui/src/dialogs/confirm.rs | 9 +++-- crates/ui-egui/src/dialogs/frame.rs | 1 + crates/ui-egui/src/dialogs/merge.rs | 50 +++++++++++++++++++++++---- crates/ui-egui/src/state/dialog.rs | 6 ++++ crates/ui-egui/src/tests/activity.rs | 49 ++++++++++++++++++++++++++ docs/merge.md | 5 ++- 24 files changed, 146 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index ee76c1f12d..edc03609f1 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "Výsledek sloučení fotografií", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft nedokázal tyto fotografie zarovnat s ostatními, proto je panorama vynechává.", "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft nedokázal tyto fotografie zarovnat se zahrnutou sadou. Před sloučením zkontrolujte náhled.", " (library default)": " (výchozí nastavení knihovny)", " (inverted)": " (invertováno)", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 016e346fdd..2fa64dcd47 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "Ergebnis der Fotozusammenführung", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft konnte diese Fotos nicht an den enthaltenen Fotos ausrichten, daher lässt das Panorama sie aus.", "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft konnte diese Fotos nicht an den enthaltenen Fotos ausrichten. Prüfen Sie die Vorschau vor dem Zusammenfügen.", " (library default)": " (Bibliotheksstandard)", " (inverted)": " (umgekehrt)", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 365496a01b..5835f47a93 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "Resultado de la combinación de fotos", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft no pudo alinear estas fotos con las incluidas, así que la panorámica las omite.", "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft no pudo alinear estas fotos con el conjunto incluido. Revise la vista previa antes de combinar.", " (library default)": " (predeterminado de la biblioteca)", " (inverted)": " (invertida)", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 8c331dc342..ab194c5baa 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "Kuvien yhdistämisen tulos", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft ei voinut kohdistaa näitä kuvia mukaan otettuihin kuviin, joten panoraama jättää ne pois.", "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft ei voinut kohdistaa näitä kuvia mukaan otettuihin kuviin. Tarkista esikatselu ennen yhdistämistä.", " (library default)": " (kirjaston oletus)", " (inverted)": " (käänteinen)", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 18cafa809d..fc014789b1 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "Résultat de la fusion de photos", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft n'a pas pu aligner ces photos sur celles incluses : le panorama les laisse de côté.", "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft n'a pas pu aligner ces photos avec les photos incluses. Vérifiez l'aperçu avant de fusionner.", " (library default)": " (valeur par défaut de la bibliothèque)", " (inverted)": " (inversée)", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 2f314cb463..4a0227f881 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "Hasil Penggabungan Foto", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft tidak dapat menyelaraskan foto-foto ini dengan foto yang disertakan, sehingga panorama tidak memuatnya.", "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft tidak dapat menyelaraskan foto-foto ini dengan foto yang disertakan. Periksa pratinjau sebelum menggabungkan.", " (library default)": " (bawaan pustaka)", " (inverted)": " (dibalik)", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 8dbe9890b3..0221ffc6bb 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "Risultato dell'unione di foto", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft non ha potuto allineare queste foto con quelle incluse, quindi il panorama le esclude.", "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft non ha potuto allineare queste foto con quelle incluse. Controlla l'anteprima prima di unire.", " (library default)": " (predefinito della libreria)", " (inverted)": " (invertita)", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index c579d40460..2224ca2d80 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "写真の結合結果", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft はこれらの写真を使用する写真に位置合わせできなかったため、パノラマには含まれていません。", "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft はこれらの写真を使用する写真に位置合わせできませんでした。結合前にプレビューを確認してください。", " (library default)": " (ライブラリの既定)", " (inverted)": " (反転)", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 8ebc90bc81..ca0da51c78 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "ფოტოების გაერთიანების შედეგი", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft-მა ვერ გაასწორა ეს ფოტოები ჩართულ ფოტოებთან, ამიტომ პანორამა მათ არ შეიცავს.", "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft-მა ვერ გაასწორა ეს ფოტოები ჩართულ ფოტოებთან. გაერთიანებამდე შეამოწმეთ გადახედვა.", " (library default)": " (ბიბლიოთეკის ნაგულისხმევი)", " (inverted)": " (ინვერსიული)", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 0a1b24b83b..ede93a493a 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "Wynik scalania zdjęć", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft nie mógł wyrównać tych zdjęć z pozostałymi, więc panorama je pomija.", "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft nie mógł wyrównać tych zdjęć z uwzględnionym zestawem. Sprawdź podgląd przed scaleniem.", " (library default)": " (domyślne ustawienie biblioteki)", " (inverted)": " (odwrócona)", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index e2dbedf500..cf7ff65a34 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "Resultado da mesclagem de fotos", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "O LightCraft não conseguiu alinhar estas fotos com as incluídas, então o panorama as deixa de fora.", "LightCraft could not align these photos with the included set. Review the preview before merging.": "O LightCraft não conseguiu alinhar estas fotos com o conjunto incluído. Revise a prévia antes de mesclar.", " (library default)": " (padrão da biblioteca)", " (inverted)": " (invertida)", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 547f3b901f..d16196d000 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "Результат объединения фото", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft не удалось совместить эти фото с остальными, поэтому панорама их не включает.", "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft не удалось выровнять эти фотографии с включёнными. Проверьте предпросмотр перед объединением.", "+ Group": "+ Группа", "+ Rule": "+ Условие", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 2f074cf98d..365053dcf0 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "Resultat av fotosammanslagning", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft kunde inte justera de här fotona mot de inkluderade, så panoramat utelämnar dem.", "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft kunde inte justera dessa foton mot de inkluderade fotona. Granska förhandsvisningen innan du slår samman.", " (library default)": " (bibliotekets standard)", " (inverted)": " (inverterad)", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 4cf03c6212..3a44eb868b 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "Результат об'єднання фото", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft не вдалося вирівняти ці фото з рештою, тому панорама їх не містить.", "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft не вдалося вирівняти ці фотографії з включеними. Перевірте попередній перегляд перед об'єднанням.", "% of all commits": "% усіх комітів", "A pen's pressure sets the size and flow of the brush": "Натиск пера задає розмір і потік пензля", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 0e199a8543..5b3337c186 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "Kết quả ghép ảnh", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft không thể căn chỉnh các ảnh này với những ảnh được dùng, nên ảnh toàn cảnh bỏ qua chúng.", "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft không thể căn chỉnh các ảnh này với những ảnh được đưa vào. Hãy xem lại bản xem trước trước khi ghép.", " (library default)": " (mặc định thư viện)", " (inverted)": " (đã đảo)", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 0f26f9ce92..8762091462 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "照片合并结果", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft 无法将这些照片与已包含的照片对齐,因此全景图未包含它们。", "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft 无法将这些照片与已包含的照片对齐。合并前请检查预览。", " (library default)": " (图库默认值)", " (inverted)": " (已反相)", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index a13643b9c3..3e5a5616a4 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -1,4 +1,6 @@ { + "Photo Merge Result": "照片合併結果", + "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft 無法將這些照片與已包含的照片對齊,因此全景圖未包含它們。", "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft 無法將這些照片與已包含的照片對齊。合併前請檢查預覽。", " (library default)": " (照片庫預設值)", " (inverted)": " (已反轉)", diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 91d9dd2611..41c29a88e9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -472,6 +472,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", @@ -619,6 +620,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", @@ -2123,6 +2125,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 b0d816d25c..8687d2d2c9 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -247,8 +247,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 d6e8ea8120..c860094678 100644 --- a/crates/ui-egui/src/dialogs/frame.rs +++ b/crates/ui-egui/src/dialogs/frame.rs @@ -211,5 +211,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 4425adbb6f..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 { @@ -319,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(); @@ -353,6 +351,40 @@ 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 @@ -389,9 +421,13 @@ fn omitted_photos(ui: &mut egui::Ui, info: &Value) { 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 photo in omitted { - let Some(path) = photo["path"].as_str() else { continue }; + 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); } diff --git a/crates/ui-egui/src/state/dialog.rs b/crates/ui-egui/src/state/dialog.rs index 77f80a280c..e0d182fd7b 100644 --- a/crates/ui-egui/src/state/dialog.rs +++ b/crates/ui-egui/src/state/dialog.rs @@ -33,6 +33,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 0b1a7654e4..27b0628fd3 100644 --- a/crates/ui-egui/src/tests/activity.rs +++ b/crates/ui-egui/src/tests/activity.rs @@ -433,6 +433,55 @@ fn merging_other_photos_drops_the_dialogs_preview() { 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/docs/merge.md b/docs/merge.md index 81c338eece..7f2d7e1323 100644 --- a/docs/merge.md +++ b/docs/merge.md @@ -36,7 +36,10 @@ verified, and the `used` and `omitted` lists cover every source photo. A preview 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. Pair measurements also appear at debug log level, including when +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. From d51c3da2cc108178f72d3004a47bdf2c2b3a0939 Mon Sep 17 00:00:00 2001 From: Dimitrij Denissenko Date: Tue, 24 Nov 2026 18:40:21 +0000 Subject: [PATCH 30/63] Heal: the pinned heal is checked on V14 and every later process, not only while V14 is the latest the_process_picks_the_heal asserted Process::LATEST == V14; V15 (brush Flow) is newer and keeps the pinned heal. --- crates/pipeline/src/spots/pinned.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/pipeline/src/spots/pinned.rs b/crates/pipeline/src/spots/pinned.rs index 983afe014d..8d4e36bd43 100644 --- a/crates/pipeline/src/spots/pinned.rs +++ b/crates/pipeline/src/spots/pinned.rs @@ -301,8 +301,10 @@ mod tests { for p in [Process::V8, Process::V10, Process::V13] { assert_eq!(HealMethod::of(&on(p)), HealMethod::Averaged, "{p:?}"); } - assert_eq!(HealMethod::of(&on(Process::V14)), HealMethod::Pinned); - assert_eq!(Process::LATEST, Process::V14); + // V14 and every later process keep the pinned heal + for p in Process::ALL.into_iter().filter(|p| *p >= Process::V14) { + assert_eq!(HealMethod::of(&on(p)), HealMethod::Pinned, "{p:?}"); + } assert_eq!(HealMethod::of(&DevelopSettings::default()), HealMethod::Pinned, "new photos get the latest process"); } From e7f55d58700ea260ed37eff8cfb2f5e657d1f470 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:21:24 +0100 Subject: [PATCH 31/63] Keep Smart Preview scans valid across LensDB changes --- crates/engine/src/cmd/previews.rs | 47 +++++++++++++++++++++++++++++-- crates/engine/src/smart.rs | 34 ++++++++++++++++++---- crates/engine/src/smart/tests.rs | 24 ++++++++++++++-- crates/engine/src/tests/import.rs | 3 +- 4 files changed, 97 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index b4d510a1b4..d05244dc6e 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -728,6 +728,7 @@ fn smart_run( if !parent.is_dir() { std::fs::create_dir(parent).map_err(|e| format!("{}: {e}", parent.display()))?; } + crate::smart::invalidate_look_check_for_write(dir, lens_key)?; lightcraft_catalog::safe_file::write_atomic(&path, &b).map_err(|e| format!("{}: {e}", path.display())) }); match r { @@ -863,8 +864,11 @@ pub(crate) fn refresh_stale_smart_previews(s: &mut Session) -> Option) { - let generation = crate::lens_profiles::generation(); - let lens_key = crate::lens_profiles::cache_key(); + // Wait for any writer that decoded with the previous database before inspecting the files. + let (generation, lens_key) = { + let _one = SMART_WRITE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + (crate::lens_profiles::generation(), crate::lens_profiles::cache_key()) + }; let stale: Vec = jobs .into_iter() .map(|(id, path, source, ages)| (id, crate::smart::existing_file_path(dir, path), source, ages)) @@ -885,6 +889,7 @@ fn refresh_stale(dir: &std::path::Path, jobs: Vec) { } } } + let _one = SMART_WRITE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); if crate::lens_profiles::generation() != generation { return; } @@ -1409,5 +1414,43 @@ mod smart_provenance_tests { crate::smart::mark_look_checked_with_lens_key(&dir, 0).unwrap(); } } + // A reload between originals can leave some proxies written by B before the scan returns. + // Returning to A must scan those proxies even if A had already checked the folder. + std::fs::write(&database, DB).unwrap(); + crate::lens_profiles::reload(); + let key_a = crate::lens_profiles::cache_key(); + crate::smart::mark_look_checked_with_lens_key(&dir, key_a).unwrap(); + let (first, second) = (dir.join("first.lcsp"), dir.join("second.lcsp")); + let older = crate::smart::encode_with_lens_key(&image, None, 0).unwrap(); + std::fs::write(&first, &older).unwrap(); + std::fs::write(&second, &older).unwrap(); + let src = |session: &mut crate::Session| session.media.origin_ref(&Source::File { path: "test.arw".into() }, SourceLevel::Preview.max_edge()); + let (db_path, pixels) = (database.clone(), image.clone()); + let mut session = crate::Session::new(); + session.media.file_loader = Some(Arc::new(move |_, _, _| { + std::fs::write(&db_path, DB.replace("-0.03", "-0.05")).map_err(|e| e.to_string())?; + crate::lens_profiles::reload(); + Ok((pixels.clone(), Default::default())) + })); + let first_source = src(&mut session); + session.media.file_loader = Some(Arc::new(move |_, _, _| Ok((image.clone(), Default::default())))); + let second_source = src(&mut session); + let ages = Ages { look: true, source: true }; + super::refresh_stale( + &dir, + vec![(PhotoId(1), first.clone(), Some(first_source), ages), (PhotoId(2), second.clone(), Some(second_source.clone()), ages)], + ); + assert_eq!(std::fs::read(&first).unwrap(), older, "a reload during decode preserves the first proxy"); + assert_ne!(crate::lens_profiles::cache_key(), key_a); + assert!(!crate::smart::is_stale_for(&second, true), "the next original was decoded with the new database"); + + std::fs::write(&database, DB).unwrap(); + crate::lens_profiles::reload(); + assert_eq!(crate::lens_profiles::cache_key(), key_a); + assert!(crate::smart::is_stale_for(&second, true)); + assert!(!crate::smart::look_checked(&dir), "the aborted scan must invalidate A's old folder marker"); + super::refresh_stale(&dir, vec![(PhotoId(2), second.clone(), Some(second_source), ages)]); + assert!(!crate::smart::is_stale_for(&second, true)); + assert!(crate::smart::look_checked(&dir), "a stable scan makes the folder current again"); } } diff --git a/crates/engine/src/smart.rs b/crates/engine/src/smart.rs index 3512e41bec..9291cc1ef3 100644 --- a/crates/engine/src/smart.rs +++ b/crates/engine/src/smart.rs @@ -549,6 +549,9 @@ pub fn source_stale(path: &Path) -> bool { /// proxies were last checked at, plus the loaded lens database identity ([`look_checked`]). const LOOK_MARKER: &str = "look-version"; +/// A proxy was written with another LensDB after the recorded folder scan. +const LOOK_PENDING: &str = "look-scan-pending"; + /// The marker file in a smart previews folder: the [`SOURCE_VERSION`] its raws' proxies were last checked at. const SOURCE_MARKER: &str = "source-version"; @@ -582,17 +585,16 @@ fn mark(dir: &Path, name: &str, versions: &[u64], lens_key: Option) -> Resu } /// Whether the smart previews folder `dir` has been checked for out-of-date proxies at this build's -/// camera-look fit version and encode version (or newer ones). A missing or unreadable marker counts -/// as not, as does one without the loaded lens database identity. Changes to that identity force -/// another scan, so unchanged fit/encode versions cannot hide stale fitted previews. +/// camera-look fit version and encode version (or newer ones), and at the loaded lens database +/// identity. A proxy written with a different database after the scan also forces another scan. pub fn look_checked(dir: &Path) -> bool { - marker_is_current(&marker(dir, LOOK_MARKER), crate::lens_profiles::cache_key()) + !dir.join(LOOK_PENDING).try_exists().unwrap_or(true) && marker_is_current(&marker(dir, LOOK_MARKER), crate::lens_profiles::cache_key()) } fn marker_is_current(versions: &[u64], lens_key: u64) -> bool { let [look, enc, rest @ ..] = versions else { return false }; let fit = u64::from(crate::camera_preview::LOOK_VERSION); - *look >= fit && *enc >= ENCODE_VERSION && (*look > fit || *enc > ENCODE_VERSION || rest.first() == Some(&lens_key)) + *look >= fit && *enc >= ENCODE_VERSION && rest.first() == Some(&lens_key) } /// Whether the smart previews folder `dir` has been checked for raws' proxies from an older raw decode at this @@ -608,7 +610,27 @@ pub fn mark_look_checked(dir: &Path) -> Result<(), String> { /// Stamp the identity captured before scanning, so a later database is never marked checked. pub(crate) fn mark_look_checked_with_lens_key(dir: &Path, lens_key: u64) -> Result<(), String> { - mark(dir, LOOK_MARKER, &[u64::from(crate::camera_preview::LOOK_VERSION), ENCODE_VERSION], Some(lens_key)) + mark(dir, LOOK_MARKER, &[u64::from(crate::camera_preview::LOOK_VERSION), ENCODE_VERSION], Some(lens_key))?; + if marker_is_current(&marker(dir, LOOK_MARKER), lens_key) { + let pending = dir.join(LOOK_PENDING); + match std::fs::remove_file(&pending) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(format!("{}: {e}", pending.display())), + } + } + Ok(()) +} + +/// Invalidate an earlier LensDB scan before replacing a proxy, under the preview writer's lock. +/// Keep the recorded versions and identity for newer builds. Only a stable scan can clear the flag. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn invalidate_look_check_for_write(dir: &Path, lens_key: u64) -> Result<(), String> { + let pending = dir.join(LOOK_PENDING); + if !pending.exists() && marker(dir, LOOK_MARKER).get(2) != Some(&lens_key) { + lightcraft_catalog::safe_file::write_atomic(&pending, b"").map_err(|e| format!("{}: {e}", pending.display()))?; + } + Ok(()) } /// Record that the raws' proxies in `dir` were checked at this build's [`SOURCE_VERSION`] (a newer one recorded stays). diff --git a/crates/engine/src/smart/tests.rs b/crates/engine/src/smart/tests.rs index 3eb12d9224..550019f0cc 100644 --- a/crates/engine/src/smart/tests.rs +++ b/crates/engine/src/smart/tests.rs @@ -411,8 +411,9 @@ fn lens_database_changes_rebuild_fitted_smart_previews_and_scan_markers() { newer[field] = serde_json::json!(newer[field].as_u64().unwrap() + 1); assert!(!header_is_stale(&newer, true, 123), "a different database does not downgrade newer proxies"); } - assert!(marker_is_current(&[fit + 1, ENCODE_VERSION, 456], 123)); - assert!(marker_is_current(&[fit, ENCODE_VERSION + 1, 456], 123)); + assert!(!marker_is_current(&[fit + 1, ENCODE_VERSION, 456], 123)); + assert!(marker_is_current(&[fit + 1, ENCODE_VERSION, 456], 456)); + assert!(!marker_is_current(&[fit, ENCODE_VERSION + 1, 456], 123)); } #[test] @@ -465,3 +466,22 @@ fn folder_marker_replaces_lens_fingerprints_in_either_direction_and_preserves_ne } std::fs::remove_dir_all(dir).unwrap(); } + +#[test] +fn a_scan_cannot_clear_pending_behind_a_newer_marker_for_another_database() { + let dir = temp("lens-marker-pending"); + let fit = u64::from(crate::camera_preview::LOOK_VERSION); + let key = crate::lens_profiles::cache_key(); + let other_key = key.wrapping_add(1); + std::fs::write(dir.join(LOOK_MARKER), format!("{} {ENCODE_VERSION} {key} 71", fit + 1)).unwrap(); + assert!(look_checked(&dir)); + + invalidate_look_check_for_write(&dir, other_key).unwrap(); + mark_look_checked_with_lens_key(&dir, other_key).unwrap(); + assert_eq!(marker(&dir, LOOK_MARKER), [fit + 1, ENCODE_VERSION, key, 71]); + assert!(!look_checked(&dir), "newer provenance for this key cannot cover a later write under a different key"); + + mark_look_checked_with_lens_key(&dir, key).unwrap(); + assert!(look_checked(&dir), "a stable scan with the recorded key clears pending"); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 0f2cdb17cf..f04a93b12e 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -3045,7 +3045,8 @@ fn smart_preview_look_marker_is_read_safely() { (format!("{cur} {enc}\n"), false), (format!("{cur} {enc} {lens}\n"), true), (format!("{cur} {enc} {}\n", lens.wrapping_add(1)), false), - (format!(" {} {}\n", cur + 1, enc + 1), true), + (format!(" {} {}\n", cur + 1, enc + 1), false), + (format!(" {} {} {lens}\n", cur + 1, enc + 1), true), ] { std::fs::write(dir.join("look-version"), &text).unwrap(); assert_eq!(crate::smart::look_checked(&dir), checked, "{text:?}"); From 5e4e4f236ad31ab600035985555bcaffabfdb269 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:10:10 +0100 Subject: [PATCH 32/63] Keep CR3 diagnostic PNGs keyed by the native filename --- crates/engine/src/camera_preview/tests.rs | 46 ++++++++++++++++++----- 1 file changed, 37 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index 8b9b0281f6..8d1c1e08c0 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -3387,10 +3387,37 @@ fn diagnostic_tsv_field(value: &str) -> String { value.replace('\\', "\\\\").replace('\t', "\\t").replace('\r', "\\r").replace('\n', "\\n") } -/// Remove only this source's three owned output files; filesystem errors must stop the diagnostic. -fn remove_diagnostic_pngs(output: &std::path::Path, name: &str) -> std::io::Result<()> { +/// Derive the PNG path from the native filename. Lossy text is used only for display in geometry.tsv. +fn diagnostic_png_path(output: &std::path::Path, name: &std::ffi::OsStr, label: &str) -> std::path::PathBuf { + let mut png = name.to_owned(); + png.push(format!("-{label}.png")); + output.join(png) +} + +#[cfg(any(unix, windows))] +#[test] +fn cr3_diagnostics_preserve_distinct_native_filenames() { + #[cfg(unix)] + let names = { + use std::os::unix::ffi::OsStrExt; + [b"A\x80.CR3", b"A\x81.CR3"].map(|bytes| std::ffi::OsStr::from_bytes(bytes).to_owned()) + }; + #[cfg(windows)] + let names = { + use std::os::windows::ffi::OsStringExt; + [0xd800, 0xd801].map(|unit| std::ffi::OsString::from_wide(&[65, unit, 46, 67, 82, 51])) + }; + let output = std::path::Path::new("diagnostics"); + assert_eq!(names[0].to_string_lossy(), names[1].to_string_lossy()); for label in ["plain", "chosen", "jpeg"] { - match std::fs::remove_file(output.join(format!("{name}-{label}.png"))) { + assert_ne!(diagnostic_png_path(output, &names[0], label), diagnostic_png_path(output, &names[1], label)); + } +} + +/// Remove only this source's three owned output files; filesystem errors must stop the diagnostic. +fn remove_diagnostic_pngs(output: &std::path::Path, name: &std::ffi::OsStr) -> std::io::Result<()> { + for label in ["plain", "chosen", "jpeg"] { + match std::fs::remove_file(diagnostic_png_path(output, name, label)) { Ok(()) => {} Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => return Err(error), @@ -3403,13 +3430,14 @@ fn remove_diagnostic_pngs(output: &std::path::Path, name: &str) -> std::io::Resu /// `proxies` exposes no rejection reason, so the row records only which call returned `None`. fn diagnostic_proxies_or_report( output: &std::path::Path, - name: &str, + name: impl AsRef, raw: &RawImage, profile_warp: bool, plain: Option, chosen: Option, report: &mut String, ) -> std::io::Result> { + let name = name.as_ref(); let status = match (plain, chosen) { (Some(plain), Some(chosen)) => return Ok(Some((plain, chosen))), (None, Some(_)) => "missing_plain_proxy", @@ -3418,7 +3446,7 @@ fn diagnostic_proxies_or_report( }; remove_diagnostic_pngs(output, name)?; let mut fields = vec![String::new(); 17]; - fields[0] = diagnostic_tsv_field(name); + fields[0] = diagnostic_tsv_field(&name.to_string_lossy()); fields[1] = diagnostic_tsv_field(raw.metadata.model.as_deref().unwrap_or("")); fields[2] = format!("{:?}", raw.orientation); fields[3] = profile_warp.to_string(); @@ -3595,9 +3623,9 @@ fn corpus_cr3_profile_geometry_diagnostics() { }); let plain = super::look_fit::look_proxies(&raw, &bytes, &transform, lens.as_ref(), plain_correction.as_ref()); let chosen = super::look_fit::look_proxies(&raw, &bytes, &transform, lens.as_ref(), correction.as_ref()); - let name = path.file_name().unwrap().to_string_lossy(); + let name = path.file_name().unwrap(); let profile_warp = correction.as_ref().is_some_and(|l| l.warp.is_some()); - let Some((plain, chosen)) = diagnostic_proxies_or_report(&output, &name, &raw, profile_warp, plain, chosen, &mut report).unwrap() else { + let Some((plain, chosen)) = diagnostic_proxies_or_report(&output, name, &raw, profile_warp, plain, chosen, &mut report).unwrap() else { std::fs::write(output.join("geometry.tsv"), &report).unwrap(); continue; }; @@ -3612,7 +3640,7 @@ fn corpus_cr3_profile_geometry_diagnostics() { let after = fit_preview(&raw, &bytes, &transform, lens.as_ref(), correction.as_ref()).0.is_some(); report.push_str(&format!( "{}\t{}\t{:?}\t{}\t{accepted}\t{:.6}\t{:.6}\t{}\t{}\t{}\t{}\t{before}\t{after}\t{framed_scores:?}\t{original_scores:?}\tmeasured\t\n", - diagnostic_tsv_field(&name), + diagnostic_tsv_field(&name.to_string_lossy()), diagnostic_tsv_field(raw.metadata.model.as_deref().unwrap_or("")), raw.orientation, profile_warp, @@ -3637,7 +3665,7 @@ fn corpus_cr3_profile_geometry_diagnostics() { }) .collect(); let image = lightcraft_codecs::EncodeImage::new(image.width as u32, image.height as u32, 3, lightcraft_codecs::Samples::U8(&pixels)); - std::fs::write(output.join(format!("{name}-{label}.png")), lightcraft_codecs::encode_png(&image, &Default::default()).unwrap()).unwrap(); + std::fs::write(diagnostic_png_path(&output, name, label), lightcraft_codecs::encode_png(&image, &Default::default()).unwrap()).unwrap(); } std::fs::write(output.join("geometry.tsv"), &report).unwrap(); } From da832f055f78d91f739de3628366ce6d335790d7 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:02:13 +0100 Subject: [PATCH 33/63] Preserve valid CR3 correspondence samples at invalid borders --- crates/engine/src/camera_preview/proxy.rs | 15 +++++++++++- crates/engine/src/camera_preview/tests.rs | 28 +++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/camera_preview/proxy.rs b/crates/engine/src/camera_preview/proxy.rs index 8caae74a2a..bae342dfce 100644 --- a/crates/engine/src/camera_preview/proxy.rs +++ b/crates/engine/src/camera_preview/proxy.rs @@ -500,7 +500,7 @@ pub(super) fn resample_correspondence(image: &Rgb32f, source: impl Fn(f64, f64) for (i, pixel) in out.data.iter_mut().enumerate() { let p = source((i % w) as f64 + 0.5, (i / w) as f64 + 0.5); *pixel = if p.x.is_finite() && p.y.is_finite() && p.x >= 0.5 && p.y >= 0.5 && p.x <= w as f64 - 0.5 && p.y <= h as f64 - 0.5 { - image.sample_bilinear(p.x as f32, p.y as f32) + sample_correspondence(image, p.x - 0.5, p.y - 0.5) } else { [f32::NAN; 3] }; @@ -508,6 +508,19 @@ pub(super) fn resample_correspondence(image: &Rgb32f, source: impl Fn(f64, f64) out } +/// Bilinear sampling inside the image, with integer coordinates at pixel centres. +fn sample_correspondence(image: &Rgb32f, x: f64, y: f64) -> [f32; 3] { + let blend = |a: [f32; 3], b: [f32; 3], t: f64| std::array::from_fn(|i| (f64::from(a[i]) * (1.0 - t) + f64::from(b[i]) * t) as f32); + // The first warp can leave a NaN border. Read a neighbour only when it contributes. + let (x0, y0) = (x.floor() as usize, y.floor() as usize); + let row = |y| { + let left = image.get(x0, y); + if x.fract() == 0.0 { left } else { blend(left, image.get(x0 + 1, y), x.fract()) } + }; + let top = row(y0); + if y.fract() == 0.0 { top } else { blend(top, row(y0 + 1), y.fract()) } +} + /// Propose correspondence geometry only. A resolved lens describes the oriented /// default crop; undo its orientation to match this un-oriented sensor proxy. #[cfg(test)] diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index 8d1c1e08c0..c629711f08 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -3234,6 +3234,34 @@ fn cr3_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() { assert!(reopened.opcodes.list3.is_empty(), "no external shading opcode is silently introduced"); } +/// A second warp must ignore invalid taps with zero weight and propagate invalid taps with positive weight. +#[test] +fn correspondence_samples_use_only_neighbours_with_nonzero_weight() { + let valid = [0.25, 0.5, 1.0]; + let mut image = Rgb32f::new(2, 2); + image.data.fill([f32::NAN; 3]); + image.set(0, 0, valid); + let sample = |image: &Rgb32f, x, y| resample_correspondence(image, |_, _| lightcraft_geom::Point::new(x, y)).get(0, 0); + assert_eq!(sample(&image, 0.5, 0.5), valid); + assert!(sample(&image, 1.0, 1.0).iter().all(|v| v.is_nan())); + // These coordinates still have a positive neighbour weight even though casting them to f32 rounds to the centre. + let next = 0.5f64.next_up(); + for (x, y) in [(next, 0.5), (0.5, next)] { + assert!(sample(&image, x, y).iter().all(|v| v.is_nan())); + } + let mut mask = Rgb32f::new(2, 2); + mask.set(0, 0, [1.0; 3]); + let almost_next_centre = 1.5f64.next_down(); + for (x, y) in [(almost_next_centre, 0.5), (0.5, almost_next_centre)] { + assert!(sample(&mask, x, y)[0] > 0.0, "a clipped neighbour with positive weight must count"); + } + for (x, y) in [(1, 0), (0, 1)] { + let mut axis = image.clone(); + axis.set(x, y, valid.map(|v| 3.0 * v)); + assert_eq!(sample(&axis, 0.5 + x as f64 * 0.5, 0.5 + y as f64 * 0.5), valid.map(|v| 2.0 * v)); + } +} + /// Keep clipped contributors in the resampled mask and mark out-of-frame samples invalid. #[test] fn correspondence_mask_keeps_every_contributing_clipped_sample_and_invalid_border() { From c28824a72be96495ae8f674cf28c7127ebc34b49 Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Fri, 27 Nov 2026 03:51:37 +0100 Subject: [PATCH 34/63] Crash log: main's Nightly profile comes through the settings folder; a Windows test path is fully qualified --- crates/engine/src/config.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/config.rs b/crates/engine/src/config.rs index 57bfe99ef2..c5ed4c6ad4 100644 --- a/crates/engine/src/config.rs +++ b/crates/engine/src/config.rs @@ -331,8 +331,8 @@ 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")) ); } From 0f1cc4fdc79af02fa84d60db88e5019e5fadb4c5 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:20:26 +0100 Subject: [PATCH 35/63] Prepare the selected settings directory before crash logging --- apps/lightcraft/src/launch.rs | 118 +++++++++++++++++++++++++--------- 1 file changed, 88 insertions(+), 30 deletions(-) diff --git a/apps/lightcraft/src/launch.rs b/apps/lightcraft/src/launch.rs index b5dfed3fc5..81f3dca90b 100644 --- a/apps/lightcraft/src/launch.rs +++ b/apps/lightcraft/src/launch.rs @@ -123,10 +123,24 @@ fn panic_log_path_with(in_memory: bool, no_prefs: bool, config: impl FnOnce() -> 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) { + 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 { @@ -197,47 +211,91 @@ mod config_path_tests { assert_eq!(panic_log_path_with(true, false, unasked), None); } - /// #2572: a panic is kept in `lightcraft-panics.log` in the settings folder, never in the system - /// temp folder (shared by every user on Linux and FreeBSD), and a `--memory` session keeps it - /// nowhere. The hook is process-wide, so the panic happens in a child (this test binary again) - /// with its own temp and home folders and no `LIGHTCRAFT_CONFIG_DIR`. + /// 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 a_panic_is_kept_in_the_settings_folder_not_the_temp_folder() { - if let Some(mode) = std::env::var_os("LIGHTCRAFT_TEST_PANIC_LOG") { - let settings = config_dir().unwrap(); - std::fs::create_dir_all(&settings).unwrap(); - println!("settings folder {}", settings.display()); + 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())); - for memory in [false, true] { - let _ = std::fs::remove_dir_all(&scratch); - let (temp, home) = (scratch.join("temp"), scratch.join("home")); + 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 out = std::process::Command::new(std::env::current_exe().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", if memory { "memory" } else { "1" }) - .env_remove("LIGHTCRAFT_CONFIG_DIR") + .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) - .env("HOME", &home) - .env("XDG_CONFIG_HOME", home.join(".config")) - .env("APPDATA", home.join("AppData")) - .output() - .unwrap(); - let stdout = String::from_utf8_lossy(&out.stdout); - assert!(out.status.success(), "{stdout}{}", String::from_utf8_lossy(&out.stderr)); - // Anywhere in a line: with one test thread (`RUST_TEST_THREADS=1`, as `xtask ci` sets on a - // small machine) libtest prints the test's name first, on the same line. - let settings = stdout.lines().find_map(|l| l.split_once("settings folder ").map(|(_, p)| p)).expect("the child didn't run the test"); - let kept = std::fs::read_to_string(std::path::Path::new(settings).join("lightcraft-panics.log")).unwrap_or_default(); - assert_eq!(kept.contains("lc-2572 probe"), !memory, "--memory {memory}: {kept:?} in {settings}"); - assert!(!temp.join("lightcraft-panics.log").exists(), "--memory {memory}: the panic was kept in the temp folder"); + .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)); } - let _ = std::fs::remove_dir_all(&scratch); + std::fs::remove_dir_all(&scratch).unwrap(); } } From b7c38772c1f8fafc1c76b95cca3d6282400ffc5c Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:35:55 +0100 Subject: [PATCH 36/63] Align CR3 camera preview samples against the resolved lens and framing fallback --- crates/engine/src/camera_preview/colour.rs | 7 +- crates/engine/src/camera_preview/look_fit.rs | 21 +- crates/engine/src/camera_preview/proxy.rs | 250 +++++-- crates/engine/src/camera_preview/tests.rs | 658 +++++++++++++++++-- crates/engine/src/camera_profiles.rs | 2 +- docs/camera-preview-colour.md | 17 +- docs/cr3-profile-alignment.md | 80 +++ docs/gaps.md | 4 +- docs/parity-checklist.md | 6 +- 9 files changed, 910 insertions(+), 135 deletions(-) create mode 100644 docs/cr3-profile-alignment.md diff --git a/crates/engine/src/camera_preview/colour.rs b/crates/engine/src/camera_preview/colour.rs index 055713991f..4d4d941e52 100644 --- a/crates/engine/src/camera_preview/colour.rs +++ b/crates/engine/src/camera_preview/colour.rs @@ -126,11 +126,8 @@ pub(super) fn starting_colour_with( (xy, t, look.or_else(|| dark(raw, &t))) } -/// Additional profile resolution for this proposal's pooled/DNG routes; CR3 keeps Main's route. +/// Resolve the file or database correction before the pooled and DNG colour fits remove lens opcodes. pub(crate) fn correspondence_correction(raw: &RawImage, bytes: &[u8]) -> Option { - if raw.format == RawFormat::Cr3 { - return None; - } crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(bytes)) } @@ -152,7 +149,7 @@ pub(super) fn starting_colour_tags_with_correction( bytes: &[u8], correction: Option<&lightcraft_develop::EmbeddedLens>, ) -> Option { - let correction = correction.filter(|_| raw.format != RawFormat::Cr3).map(|correction| lightcraft_develop::EmbeddedLens { + let correction = correction.map(|correction| lightcraft_develop::EmbeddedLens { vignette: crate::files::embedded_lens(&raw.info()).and_then(|lens| lens.vignette), ..*correction }); diff --git a/crates/engine/src/camera_preview/look_fit.rs b/crates/engine/src/camera_preview/look_fit.rs index 8c7ea7d81f..5439850bb0 100644 --- a/crates/engine/src/camera_preview/look_fit.rs +++ b/crates/engine/src/camera_preview/look_fit.rs @@ -325,7 +325,7 @@ pub(super) fn database_vignetting( reference: &Rgb32f, clipped: &[bool], vignette: &lightcraft_develop::EmbeddedVignette, - frame: ProxyFrame, + frame: ProxyFrame<'_>, ) { let amount = camera_vignetting_amount(sensor, reference, clipped, vignette, frame); apply_vignetting(sensor, vignette, frame, amount); @@ -338,15 +338,17 @@ pub(super) fn database_vignetting( /// moved to its camera JPEG's framing, [`super::proxy::framed_proxies`]) takes each pixel to the position it shows, and /// `orientation` maps that position to the oriented frame. #[derive(Clone, Copy, Debug)] -pub(super) struct ProxyFrame { +pub(super) struct ProxyFrame<'a> { pub(super) orientation: lightcraft_geom::Orientation, pub(super) framing: Option, + /// Accepted lens warp in the oriented CR3 crop, applied after the JPEG framing. + pub(super) lens: Option<&'a lightcraft_develop::EmbeddedLens>, } -impl ProxyFrame { +impl ProxyFrame<'_> { /// A proxy whose pixels are where they were sampled, in the frame `orientation` maps to the oriented one. pub(super) fn new(orientation: lightcraft_geom::Orientation) -> Self { - Self { orientation, framing: None } + Self { orientation, framing: None, lens: None } } } @@ -404,7 +406,7 @@ pub(super) fn camera_vignetting_amount( reference: &Rgb32f, clipped: &[bool], vignette: &lightcraft_develop::EmbeddedVignette, - frame: ProxyFrame, + frame: ProxyFrame<'_>, ) -> f64 { vignetting_amount_from_gains(sensor, reference, clipped, vignetting_gains(sensor, vignette, frame)) } @@ -450,10 +452,11 @@ pub(super) fn vignetting_amount_from_gains(sensor: &Rgb32f, reference: &Rgb32f, /// The render's vignetting gain (`optics::embedded_vignette_gain`) at each pixel of `sensor`, at the position `frame` /// gives it in the oriented, cropped frame `vignette` is in. -pub(super) fn vignetting_gains(sensor: &Rgb32f, vignette: &lightcraft_develop::EmbeddedVignette, frame: ProxyFrame) -> Vec { +pub(super) fn vignetting_gains(sensor: &Rgb32f, vignette: &lightcraft_develop::EmbeddedVignette, frame: ProxyFrame<'_>) -> Vec { let (w, h) = (sensor.width as f64, sensor.height as f64); let (ow, oh) = if frame.orientation.swaps_axes() { (h, w) } else { (w, h) }; let width = sensor.width.max(1); + let warp = frame.lens.map(|lens| super::proxy::profile_warp(lens, ow, oh)); (0..sensor.data.len()) .map(|i| { let (px, py) = ((i % width) as f64 + 0.5, (i / width) as f64 + 0.5); @@ -465,13 +468,15 @@ pub(super) fn vignetting_gains(sensor: &Rgb32f, vignette: &lightcraft_develop::E None => (px, py), }; let (x, y) = frame.orientation.map(px, py, w, h); - lightcraft_pipeline::optics::embedded_vignette_gain(vignette, lightcraft_geom::Point::new(x, y), ow, oh) + let point = lightcraft_geom::Point::new(x, y); + let point = warp.as_ref().map_or(point, |warp| warp.corrected_to_source(point, 1)); + lightcraft_pipeline::optics::embedded_vignette_gain(vignette, point, ow, oh) }) .collect() } /// Multiply `sensor` by `amount` of `vignette`'s correction, as the Vignetting amount slider scales it. -pub(super) fn apply_vignetting(sensor: &mut Rgb32f, vignette: &lightcraft_develop::EmbeddedVignette, frame: ProxyFrame, amount: f64) { +pub(super) fn apply_vignetting(sensor: &mut Rgb32f, vignette: &lightcraft_develop::EmbeddedVignette, frame: ProxyFrame<'_>, amount: f64) { let gains = vignetting_gains(sensor, vignette, frame); for (p, g) in sensor.data.iter_mut().zip(gains) { let gain = (1.0 + (g - 1.0) * amount) as f32; diff --git a/crates/engine/src/camera_preview/proxy.rs b/crates/engine/src/camera_preview/proxy.rs index 8a66bf5259..c82072397a 100644 --- a/crates/engine/src/camera_preview/proxy.rs +++ b/crates/engine/src/camera_preview/proxy.rs @@ -85,6 +85,13 @@ pub(super) fn structure_agrees(sensor: &Rgb32f, reference: &Rgb32f) -> bool { at_zero >= MIN_STRUCTURE && shift.0.abs() <= 1 && shift.1.abs() <= 1 } +/// Per-file fits measure database shading against the camera JPEG. A pooled CR3 +/// fit applies shading only to its warp proposal and retains its unshaded fallback. +pub(super) enum ProxyLens<'a> { + PerFile(Option<&'a lightcraft_develop::EmbeddedLens>), + Pooled(Option<&'a lightcraft_develop::EmbeddedLens>), +} + /// Same-size proxies of the sensor (white-balanced, baseline exposure, through `transform`'s /// matrix: the generic camera ≈ sRGB model) and of the file's embedded camera JPEG (linear Rec.2020), /// and per proxy pixel whether any sensor sample it covers is clipped. `embedded`'s vignetting correction is applied to @@ -98,20 +105,20 @@ pub(super) fn proxies( lens: Option<&LensGeometry>, embedded: Option<&lightcraft_develop::EmbeddedLens>, ) -> Option<(Rgb32f, Rgb32f, Vec)> { - framed_proxies(raw, bytes, transform, size, min_fraction, lens, embedded).map(|(sensor, reference, clipped, _)| (sensor, reference, clipped)) + framed_proxies(raw, bytes, transform, size, min_fraction, lens, ProxyLens::PerFile(embedded)) + .map(|(sensor, reference, clipped, _)| (sensor, reference, clipped)) } -/// [`proxies`], and the CR3 framing the sensor proxy was moved to ([`estimate_cr3_framing`]; `None` when it was not -/// moved): a pixel of the returned CR3 sensor proxy shows the oriented sensor at `framing.source` of its position. -pub(super) fn framed_proxies( +/// [`proxies`], and the mapping from the selected proxy to its oriented sensor, used for database vignetting. +pub(super) fn framed_proxies<'a>( raw: &RawImage, bytes: &[u8], transform: &CameraTransform, size: usize, min_fraction: f64, lens: Option<&LensGeometry>, - embedded: Option<&lightcraft_develop::EmbeddedLens>, -) -> Option<(Rgb32f, Rgb32f, Vec, Option)> { + profile: ProxyLens<'a>, +) -> Option<(Rgb32f, Rgb32f, Vec, ProxyFrame<'a>)> { let edge = (2 * size).max(384) as u32; let decoded = crate::files::decode_raw_preview( bytes, @@ -146,11 +153,15 @@ pub(super) fn framed_proxies( let k = (crop.width.max(crop.height).div_ceil(edge as usize).max(2)).div_ceil(2) * 2; let mut sensor = sensor_proxy(raw, k, edge as usize)?; let mut clipped = clip_mask(&sensor); - let mut framing = None; + let mut frame = ProxyFrame::new(raw.orientation); + let embedded = match profile { + ProxyLens::PerFile(lens) | ProxyLens::Pooled(lens) => lens, + }; + let cr3_pool = raw.format == RawFormat::Cr3 && matches!(profile, ProxyLens::Pooled(_)); // A database describes the lens; only the share of its shading correction visible in the JPEG // belongs in the fit. File-owned corrections describe what the camera applied to this image. let database_vignette = embedded.filter(|e| e.source == lightcraft_develop::LensSource::Database && lens.is_none()).and_then(|e| e.vignette); - if database_vignette.is_none() { + if !cr3_pool && database_vignette.is_none() { correct_vignetting(&mut sensor, embedded, raw.orientation); } // The camera may have corrected its JPEG with the lens warp the file carries (Nikon Z lenses always, at up to 9 % @@ -162,8 +173,8 @@ pub(super) fn framed_proxies( let gain = 2f32.powf(transform.baseline_exposure as f32); let to_working = |p: [f32; 3]| transform.matrix.apply_f32(std::array::from_fn(|i| p[i] * transform.wb[i] * gain)); // External profiles describe the developed default crop, unlike OpcodeList3's active-area warp. - // Keep the established CR3/in-file routes; only an uncalibrated file with no in-file warp - // may propose this additional correspondence geometry. Its acceptance uses edges, never RGB error. + // For non-CR3 files a database warp may compete with the uncorrected sensor only in the absence + // of an in-file warp. CR3 also compares its proposal against the framing-only fallback below. let aligned_external = embedded .filter(|correction| { raw.format != RawFormat::Cr3 @@ -185,13 +196,21 @@ pub(super) fn framed_proxies( } if raw.format == RawFormat::Cr3 { // Orient the camera JPEG and the sensor identically before collecting pixel correspondences. + let correction = embedded.filter(|correction| transform.matrix_is_fallback && lens.is_none() && correction.warp.is_some()); + // A pooled fit historically used an unshaded framing fallback. Apply database shading + // only to the proposed sensor, at the source position before orientation and the warp. + let pooled_candidate = correction.filter(|c| cr3_pool && c.vignette.is_some()).map(|correction| { + let mut candidate = sensor.clone(); + correct_vignetting(&mut candidate, Some(correction), raw.orientation); + let mut candidate = candidate.into_oriented(raw.orientation); + candidate.map_in_place(to_working); + candidate + }); sensor = sensor.into_oriented(raw.orientation); clipped = clipped.into_oriented(raw.orientation); reference = reference.into_oriented(raw.orientation); sensor.map_in_place(to_working); - // Canon's JPEG can be cropped differently from the sensor. Estimate only that common - // framing from edge directions, independently of the subsequent colour fit. - (sensor, clipped, framing) = align_cr3_framing(sensor, clipped, &reference); + (sensor, clipped, frame) = align_cr3_geometry(sensor, clipped, &reference, correction, pooled_candidate.as_ref()); } let mut sensor = fit(&sensor, size, size, Filter::Box); let mut reference_small = reference_at(&reference, &sensor); @@ -210,12 +229,10 @@ pub(super) fn framed_proxies( if raw.format != RawFormat::Cr3 && !external_applied { sensor.map_in_place(to_working); } - if let Some(vignette) = database_vignette.filter(|_| !external_applied) { - // CR3 is now in the JPEG’s oriented frame. Other proxies are still in sensor orientation. - let orientation = if raw.format == RawFormat::Cr3 { lightcraft_geom::Orientation::Normal } else { raw.orientation }; - database_vignetting(&mut sensor, &reference, &clipped, &vignette, ProxyFrame { orientation, framing }); + if let Some(vignette) = database_vignette.filter(|_| !external_applied && !cr3_pool) { + database_vignetting(&mut sensor, &reference, &clipped, &vignette, frame); } - Some((sensor, reference, clipped, framing)) + Some((sensor, reference, clipped, frame)) } fn clipped_pixels(mask: &Rgb32f, sensor: &Rgb32f) -> Vec { @@ -252,12 +269,45 @@ impl Cr3Framing { /// A separate third of the edges must confirm a substantial improvement and a close match. /// A weak, flat or unrelated preview leaves the sensor framing unchanged. pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Option { - estimate_framing_against(sensor, reference, None) + estimate_framing_against(sensor, reference, None, None) } -/// Score both a proposed lens geometry and its bounded framing against the original sensor. -/// The identity framing is a valid candidate: lens correction alone may already align the JPEG. -fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: Option<&Rgb32f>) -> Option { +#[cfg(test)] +thread_local! { + static FRAMING_SEARCHES: std::cell::Cell = const { std::cell::Cell::new(0) }; + static LAST_GEOMETRY_SCORES: std::cell::Cell> = const { std::cell::Cell::new(None) }; + static LAST_FRAMED_SCORES: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Read and reset this thread's framing-search budget, independent of elapsed time. +#[cfg(test)] +pub(super) fn take_framing_search_count() -> usize { + FRAMING_SEARCHES.replace(0) +} + +/// Return this test thread's last `[train_before, train_after, held_before, held_after]` +/// scores against the original sensor geometry. +#[cfg(test)] +pub(super) fn geometry_gate_scores() -> Option<[f64; 4]> { + LAST_GEOMETRY_SCORES.get() +} + +/// Return this test thread's last `[train_before, train_after, held_before, held_after]` +/// scores comparing the CR3 proposal with the established framing fallback. +#[cfg(test)] +pub(super) fn geometry_framed_scores() -> Option<[f64; 4]> { + LAST_FRAMED_SCORES.get() +} + +/// Judge a proposed lens warp and bounded framing against the original sensor on fixed +/// training and independent held-out edges. Lens-only correction may be sufficient. +fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: Option<&Rgb32f>, framed: Option<&Rgb32f>) -> Option { + #[cfg(test)] + { + FRAMING_SEARCHES.set(FRAMING_SEARCHES.get() + 1); + LAST_GEOMETRY_SCORES.set(None); + LAST_FRAMED_SCORES.set(None); + } if sensor.width.checked_mul(sensor.height)? != sensor.data.len() || reference.width.checked_mul(reference.height)? != reference.data.len() { return None; } @@ -276,6 +326,11 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: Optio if (original.width, original.height) != (w, h) || original.data.len() != sensor.data.len() { return None; } + let framed = framed.map(|image| fit(image, PROXY, PROXY, Filter::Box)); + if framed.as_ref().is_some_and(|image| (image.width, image.height) != (w, h) || image.data.len() != sensor.data.len()) { + return None; + } + let mut framed_gradients = framed.as_ref().map(|_| Rgb32f::new(w, h)); let mut gradients = Rgb32f::new(w, h); let mut original_gradients = Rgb32f::new(w, h); let mut edges = Vec::new(); @@ -291,6 +346,10 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: Optio gradients.data[y * w + x] = [d[0], d[1], 0.0]; let d = derivative(&original); original_gradients.data[y * w + x] = [d[0], d[1], 0.0]; + if let (Some(image), Some(gradients)) = (&framed, &mut framed_gradients) { + let d = derivative(image); + gradients.data[y * w + x] = [d[0], d[1], 0.0]; + } let d = derivative(&reference); let magnitude = d[0].hypot(d[1]); let value = luminance_2020(reference.data[y * w + x]); @@ -391,9 +450,24 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: Optio score(&original_gradients, Cr3Framing::IDENTITY, true, proposal.then_some((&gradients, best.1)))?, score(&gradients, best.1, true, proposal.then_some((&original_gradients, Cr3Framing::IDENTITY)))?, ); + #[cfg(test)] + if proposal { + LAST_GEOMETRY_SCORES.set(Some([best.2, best.0, held_before, held_after])); + } if best.0 < 0.9 || best.0 < best.2 + 0.04 || held_after < 0.9 || held_after < held_before + 0.04 { return None; } + if let Some(framed) = &framed_gradients { + let before = score(framed, Cr3Framing::IDENTITY, false, Some((&gradients, best.1)))?; + let after = score(&gradients, best.1, false, Some((framed, Cr3Framing::IDENTITY)))?; + let held_before = score(framed, Cr3Framing::IDENTITY, true, Some((&gradients, best.1)))?; + let held_after = score(&gradients, best.1, true, Some((framed, Cr3Framing::IDENTITY)))?; + #[cfg(test)] + LAST_FRAMED_SCORES.set(Some([before, after, held_before, held_after])); + if after < before || held_after < held_before { + return None; + } + } if lightcraft_pipeline::profiling() { eprintln!("[profile] camera JPEG framing {:?}, held-out edge agreement {held_before:.4} -> {held_after:.4}", best.1); } @@ -403,29 +477,62 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: Optio /// Exercise the proposal gate independently of lens-map construction in regressions. #[cfg(test)] pub(super) fn estimate_profile_framing(candidate: &Rgb32f, reference: &Rgb32f, original: &Rgb32f) -> Option { - estimate_framing_against(candidate, reference, Some(original)) + estimate_framing_against(candidate, reference, Some(original), None) } -/// The sensor proxy and its clip mask (same size), both moved to the camera JPEG's framing, and that framing (`None` -/// when they stay as they are). -fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rgb32f, Rgb32f, Option) { - let Some(framing) = estimate_cr3_framing(&sensor, reference) else { return (sensor, clipped, None) }; - let apply = |image: &Rgb32f| { - let (w, h) = (image.width, image.height); - let mut aligned = Rgb32f::new(w, h); - for (i, pixel) in aligned.data.iter_mut().enumerate() { - let (x, y) = framing.source((i % w) as f32 + 0.5, (i / w) as f32 + 0.5, w, h); - *pixel = if x >= 0.5 && y >= 0.5 && x <= w as f32 - 0.5 && y <= h as f32 - 0.5 { image.sample_bilinear(x, y) } else { [f32::NAN; 3] }; - } - aligned +/// Choose CR3 correspondence without copying the unregistered sensor or mask. The +/// unwarped fallback and warped proposal need separate searches: their pixels and +/// support rules differ, and the proposal must preserve the accepted fallback. +pub(super) fn align_cr3_geometry<'a>( + sensor: Rgb32f, + clipped: Rgb32f, + reference: &Rgb32f, + correction: Option<&'a lightcraft_develop::EmbeddedLens>, + candidate_sensor: Option<&Rgb32f>, +) -> (Rgb32f, Rgb32f, ProxyFrame<'a>) { + let frame = |source: &Rgb32f| { + let framing = estimate_cr3_framing(source, reference); + (framing, framing.map(|framing| apply_cr3_framing(source, framing))) }; - (apply(&sensor), apply(&clipped), Some(framing)) + // Score the warp against the same shading on the original and framed baselines. + let source = candidate_sensor.unwrap_or(&sensor); + let (mut framing, mut fallback) = frame(source); + let orientation = lightcraft_geom::Orientation::Normal; + if let Some(lens) = correction + && let Some((aligned, mask, framing)) = + align_profile_geometry_against(source, &clipped, reference, lens, orientation, Some(fallback.as_ref().unwrap_or(source))) + { + return (aligned, mask, ProxyFrame { orientation, framing: Some(framing), lens: Some(lens) }); + } + if candidate_sensor.is_some() { + // The pooled proposal was rejected. Restore the framing selected on the original samples. + (framing, fallback) = frame(&sensor); + } + // The mask is needed only if the fallback wins; when no framing is accepted, + // return both original allocations unchanged. + let clipped = if let Some(framing) = framing { apply_cr3_framing(&clipped, framing) } else { clipped }; + (fallback.unwrap_or(sensor), clipped, ProxyFrame { orientation, framing, lens: None }) +} + +/// Move one image to the accepted camera framing, preserving invalid border samples. +fn apply_cr3_framing(image: &Rgb32f, framing: Cr3Framing) -> Rgb32f { + let (w, h) = (image.width, image.height); + let mut aligned = Rgb32f::new(w, h); + for (i, pixel) in aligned.data.iter_mut().enumerate() { + let (x, y) = framing.source((i % w) as f32 + 0.5, (i / w) as f32 + 0.5, w, h); + *pixel = if x >= 0.5 && y >= 0.5 && x <= w as f32 - 0.5 && y <= h as f32 - 0.5 { image.sample_bilinear(x, y) } else { [f32::NAN; 3] }; + } + aligned } /// Resample a correspondence image with a common source map. Nonfinite/outside coordinates /// become NaN so they cannot contribute colour or tone training pairs. A nonnegative clip mask /// uses the same bilinear map: any clipped contributing sample remains strictly positive. -pub(super) fn resample_correspondence(image: &Rgb32f, source: impl Fn(f64, f64) -> lightcraft_geom::Point) -> Rgb32f { +pub(super) fn resample_correspondence( + image: &Rgb32f, + source: impl Fn(f64, f64) -> lightcraft_geom::Point, + sample: fn(&Rgb32f, f64, f64) -> [f32; 3], +) -> Rgb32f { let (w, h) = (image.width, image.height); let mut out = Rgb32f::new(w, h); if w == 0 || h == 0 { @@ -434,7 +541,7 @@ pub(super) fn resample_correspondence(image: &Rgb32f, source: impl Fn(f64, f64) for (i, pixel) in out.data.iter_mut().enumerate() { let p = source((i % w) as f64 + 0.5, (i / w) as f64 + 0.5); *pixel = if p.x.is_finite() && p.y.is_finite() && p.x >= 0.5 && p.y >= 0.5 && p.x <= w as f64 - 0.5 && p.y <= h as f64 - 0.5 { - sample_correspondence(image, p.x as f32 - 0.5, p.y as f32 - 0.5) + sample(image, p.x, p.y) } else { [f32::NAN; 3] }; @@ -442,10 +549,11 @@ pub(super) fn resample_correspondence(image: &Rgb32f, source: impl Fn(f64, f64) out } -/// Bilinear interpolation inside the image, with integer coordinates at pixel centres. +/// Bilinear interpolation at the established non-CR3 proxy's f32 precision. /// At an exact coordinate the two bounds coincide. An invalid neighbour with zero weight /// must not turn a usable training pixel or its clip mask into NaN. -fn sample_correspondence(image: &Rgb32f, x: f32, y: f32) -> [f32; 3] { +pub(super) fn sample_correspondence(image: &Rgb32f, x: f64, y: f64) -> [f32; 3] { + let (x, y) = (x as f32 - 0.5, y as f32 - 0.5); let row = |y| -> [f32; 3] { let left = image.get(x.floor() as usize, y); let right = image.get(x.ceil() as usize, y); @@ -456,6 +564,20 @@ fn sample_correspondence(image: &Rgb32f, x: f32, y: f32) -> [f32; 3] { std::array::from_fn(|i| top[i] + (bottom[i] - top[i]) * y.fract()) } +/// Two-stage CR3 registration keeps f64 source coordinates so a positive neighbour weight survives near pixel centres. +pub(super) fn sample_cr3_correspondence(image: &Rgb32f, x: f64, y: f64) -> [f32; 3] { + let (x, y) = (x - 0.5, y - 0.5); + let blend = |a: [f32; 3], b: [f32; 3], t: f64| std::array::from_fn(|i| (f64::from(a[i]) * (1.0 - t) + f64::from(b[i]) * t) as f32); + // The first warp can leave a NaN border. Read a neighbour only when it contributes. + let (x0, y0) = (x.floor() as usize, y.floor() as usize); + let row = |y| { + let left = image.get(x0, y); + if x.fract() == 0.0 { left } else { blend(left, image.get(x0 + 1, y), x.fract()) } + }; + let top = row(y0); + if y.fract() == 0.0 { top } else { blend(top, row(y0 + 1), y.fract()) } +} + /// A resolved profile is a proposal for camera-JPEG geometry, never an instruction to change /// the rendered RAW's optics. The lens is already relative to the oriented default crop; /// re-express it in this un-oriented sensor proxy's frame before using its green-plane warp. @@ -467,27 +589,43 @@ pub(super) fn align_profile_geometry( correction: &lightcraft_develop::EmbeddedLens, orientation: lightcraft_geom::Orientation, ) -> Option<(Rgb32f, Rgb32f)> { + align_profile_geometry_against(sensor, clipped, reference, correction, orientation, None).map(|(sensor, mask, _)| (sensor, mask)) +} + +/// Propose lens geometry plus bounded framing and require the original training/held-out gates. +/// When supplied, the framed CR3 baseline must also be preserved or improved on both splits. +fn align_profile_geometry_against( + sensor: &Rgb32f, + clipped: &Rgb32f, + reference: &Rgb32f, + correction: &lightcraft_develop::EmbeddedLens, + orientation: lightcraft_geom::Orientation, + cr3_baseline: Option<&Rgb32f>, +) -> Option<(Rgb32f, Rgb32f, Cr3Framing)> { if correction.warp.is_none() || (sensor.width, sensor.height) != (clipped.width, clipped.height) { return None; } let (w, h) = (sensor.width as f64, sensor.height as f64); let (ow, oh) = if orientation.swaps_axes() { (h, w) } else { (w, h) }; let correction = lightcraft_pipeline::optics::reorient_lens(correction, orientation.inverse(), ow, oh); - let mut warp = lightcraft_pipeline::optics::Warp::identity(w, h); - warp.lens = Some(correction); - warp.lens_dist = 1.0; + let warp = profile_warp(&correction, w, h); let source = |x, y| warp.corrected_to_source(lightcraft_geom::Point::new(x, y), 1); - let candidate = resample_correspondence(sensor, source); - let framing = estimate_framing_against(&candidate, reference, Some(sensor))?; - let mask = resample_correspondence(clipped, source); + let sample = if cr3_baseline.is_some() { sample_cr3_correspondence } else { sample_correspondence }; + let candidate = resample_correspondence(sensor, source, sample); + let framing = estimate_framing_against(&candidate, reference, Some(sensor), cr3_baseline)?; + let mask = resample_correspondence(clipped, source, sample); let frame = |x: f64, y: f64| { let (x, y) = framing.source(x as f32, y as f32, sensor.width, sensor.height); lightcraft_geom::Point::new(f64::from(x), f64::from(y)) }; - let mask = resample_correspondence(&mask, frame); - let aligned = resample_correspondence(&candidate, frame); + let mask = resample_correspondence(&mask, frame, sample); + let aligned = resample_correspondence(&candidate, frame, sample); + // CR3 shading is handled by the caller on the selected geometry. + if cr3_baseline.is_some() { + return Some((aligned, mask, framing)); + } let Some(vignette) = correction.vignette.filter(|_| correction.source == lightcraft_develop::LensSource::Database) else { - return Some((aligned, mask)); + return Some((aligned, mask, framing)); }; // Estimate shading only after the edges agree. Each gain belongs to the source position reached @@ -501,12 +639,20 @@ pub(super) fn align_profile_geometry( }); let amount = vignetting_amount_from_gains(&small, &reference_at(reference, &small), &clipped_pixels(&mask, &small), gains); if amount == 0.0 { - return Some((aligned, mask)); + return Some((aligned, mask, framing)); } // Apply the measured share before interpolation, exactly where the sensor samples came from. let mut shaded = sensor.clone(); apply_vignetting(&mut shaded, &vignette, ProxyFrame::new(lightcraft_geom::Orientation::Normal), amount); - Some((resample_correspondence(&resample_correspondence(&shaded, source), frame), mask)) + Some((resample_correspondence(&resample_correspondence(&shaded, source, sample), frame, sample), mask, framing)) +} + +/// Green-plane mapping from corrected pixels to their sensor positions at this proxy size. +pub(super) fn profile_warp(lens: &lightcraft_develop::EmbeddedLens, w: f64, h: f64) -> lightcraft_pipeline::optics::Warp { + let mut warp = lightcraft_pipeline::optics::Warp::identity(w, h); + warp.lens = Some(*lens); + warp.lens_dist = 1.0; + warp } /// What one photo contributes to a camera profile ([`profile_samples`]), in white-balanced camera RGB. @@ -531,7 +677,7 @@ pub(crate) fn profile_samples( return None; } let transform = lightcraft_raw::color::camera_transform(raw, lightcraft_raw::color::as_shot_white_xy(raw)); - let (sensor, reference, clipped) = proxies(raw, bytes, &transform, PROFILE_PROXY, 0.0, lens, correction)?; + let (sensor, reference, clipped, _) = framed_proxies(raw, bytes, &transform, PROFILE_PROXY, 0.0, lens, ProxyLens::Pooled(correction))?; let to_camera = transform.matrix.inverse()?; // clipped sensor pixels don't record the scene's colour (see `fit_look`) let sensor = without_clipped(&sensor, &clipped).unwrap_or(sensor); diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index ee64e5e80a..cc09d42c86 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -1,4 +1,4 @@ -use super::proxy::{align_profile_geometry, resample_correspondence}; +use super::proxy::{align_profile_geometry, resample_correspondence, sample_correspondence, sample_cr3_correspondence}; use super::tone::{ELASTICITY_BLACK, MAX_TONE_ELASTICITY, TONE_REPAIR_ELASTICITY, limit_elasticity}; use super::*; use lightcraft_raw::profile::{HsvTableApply, ProfileLookHueSat}; @@ -1016,13 +1016,27 @@ fn correspondence_samples_use_only_neighbours_with_nonzero_weight() { let mut image = Rgb32f::new(2, 2); image.data.fill([f32::NAN; 3]); image.set(0, 0, valid); - let sample = |image: &Rgb32f, x, y| resample_correspondence(image, |_, _| lightcraft_geom::Point::new(x, y)).get(0, 0); - assert_eq!(sample(&image, 0.5, 0.5), valid); - assert!(sample(&image, 1.0, 1.0).iter().all(|v| v.is_nan())); - for (x, y) in [(1, 0), (0, 1)] { - let mut axis = image.clone(); - axis.set(x, y, valid.map(|v| 3.0 * v)); - assert_eq!(sample(&axis, 0.5 + x as f64 * 0.5, 0.5 + y as f64 * 0.5), valid.map(|v| 2.0 * v)); + for interpolation in [sample_correspondence, sample_cr3_correspondence] { + let sample = |image: &Rgb32f, x, y| resample_correspondence(image, |_, _| lightcraft_geom::Point::new(x, y), interpolation).get(0, 0); + assert_eq!(sample(&image, 0.5, 0.5), valid); + assert!(sample(&image, 1.0, 1.0).iter().all(|v| v.is_nan())); + for (x, y) in [(1, 0), (0, 1)] { + let mut axis = image.clone(); + axis.set(x, y, valid.map(|v| 3.0 * v)); + assert_eq!(sample(&axis, 0.5 + x as f64 * 0.5, 0.5 + y as f64 * 0.5), valid.map(|v| 2.0 * v)); + } + } + let sample = |image: &Rgb32f, x, y| resample_correspondence(image, |_, _| lightcraft_geom::Point::new(x, y), sample_cr3_correspondence).get(0, 0); + // These coordinates still have a positive neighbour weight even though casting them to f32 rounds to the centre. + let next = 0.5f64.next_up(); + for (x, y) in [(next, 0.5), (0.5, next)] { + assert!(sample(&image, x, y).iter().all(|v| v.is_nan())); + } + let mut mask = Rgb32f::new(2, 2); + mask.set(0, 0, [1.0; 3]); + let almost_next_centre = 1.5f64.next_down(); + for (x, y) in [(almost_next_centre, 0.5), (0.5, almost_next_centre)] { + assert!(sample(&mask, x, y)[0] > 0.0, "a clipped neighbour with positive weight must count"); } } @@ -1042,11 +1056,15 @@ fn profile_geometry_target(sensor: &Rgb32f, lens: &lightcraft_develop::EmbeddedL let mut warp = lightcraft_pipeline::optics::Warp::identity(sensor.width as f64, sensor.height as f64); warp.lens = Some(*lens); warp.lens_dist = 1.0; - let warped = resample_correspondence(sensor, |x, y| warp.corrected_to_source(lightcraft_geom::Point::new(x, y), 1)); - resample_correspondence(&warped, |x, y| { - let (x, y) = framing.source(x as f32, y as f32, sensor.width, sensor.height); - lightcraft_geom::Point::new(f64::from(x), f64::from(y)) - }) + let warped = resample_correspondence(sensor, |x, y| warp.corrected_to_source(lightcraft_geom::Point::new(x, y), 1), sample_correspondence); + resample_correspondence( + &warped, + |x, y| { + let (x, y) = framing.source(x as f32, y as f32, sensor.width, sensor.height); + lightcraft_geom::Point::new(f64::from(x), f64::from(y)) + }, + sample_correspondence, + ) } fn geometry_rms(a: &Rgb32f, b: &Rgb32f) -> f64 { @@ -1399,20 +1417,8 @@ fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() exif.set(tags::LENS_MODEL, Value::Ascii("Synthetic 18mm".into())); ifd.set_child(tags::EXIF_IFD, exif); let file = profile_geometry_file(&target, ifd); - // Standalone non-CR3 scope: a coherent profile must not alter Main's CR3 framing route. let mut cr3 = raw.clone(); cr3.format = RawFormat::Cr3; - let baseline = proxies(&cr3, &file, &transform, PROXY, 0.0, None, None).unwrap(); - let proposed = proxies(&cr3, &file, &transform, PROXY, 0.0, None, Some(&lens)).unwrap(); - let bits = |image: &Rgb32f| image.data.iter().flatten().map(|v| v.to_bits()).collect::>(); - assert_eq!(bits(&baseline.0), bits(&proposed.0), "CR3 sensor keeps Main framing"); - assert_eq!(bits(&baseline.1), bits(&proposed.1), "CR3 reference is unchanged"); - assert_eq!(baseline.2, proposed.2, "CR3 clipping is unchanged"); - let cr3_samples = |correction: Option<&lightcraft_develop::EmbeddedLens>| { - let samples = profile_samples(&cr3, &file, None, correction).expect("CR3 colour and tone samples"); - (samples.colour, samples.tone) - }; - assert!(cr3_samples(None) == cr3_samples(Some(&lens)), "CR3 pooled samples preserve the original framing"); let (plain, reference, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, None).unwrap(); let (mut aligned, _, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, Some(&lens)).unwrap(); let mut plain_render = plain; @@ -1448,8 +1454,7 @@ fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() assert_file_owned_dng_vignette_contract(&mut raw, &file, &lens, &white, &expected_tags); - // A real configured profile with nonzero vignetting must still be available to Main's - // per-file CR3 path, while this proposal's new Pool/DNG lookup stays excluded. + // Resolve a real configured CR3 profile through the shared Pool/DNG lookup. let vignetted_db = DB.replace("", r#""#); let path = std::path::PathBuf::from(std::env::var_os(crate::lens_profiles::ENV).unwrap()).join("synthetic.xml"); @@ -1457,37 +1462,18 @@ fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() crate::lens_profiles::reload(); let resolved = crate::lens_profiles::for_raw(&cr3.info(), || lightcraft_meta::extract(&file)).unwrap(); assert!(resolved.warp.is_some() && resolved.vignette.is_some(), "fixture resolves both corrections"); - let mut main_lens = resolved; - main_lens.warp = None; - let main_proxy = proxies(&cr3, &file, &transform, PROXY, 0.0, None, Some(&main_lens)).unwrap(); - let actual_proxy = proxies(&cr3, &file, &transform, PROXY, 0.0, None, Some(&resolved)).unwrap(); - assert_eq!(bits(&main_proxy.0), bits(&actual_proxy.0), "CR3 keeps Main's vignetting and framing, ignoring the new radial proposal"); - let (mut unshaded, reference, clipped, framing) = super::proxy::framed_proxies(&cr3, &file, &transform, PROXY, 0.0, None, None).unwrap(); - let frame = ProxyFrame { orientation: lightcraft_geom::Orientation::Normal, framing }; - let vignette = resolved.vignette.as_ref().unwrap(); - let share = camera_vignetting_amount(&unshaded, &reference, &clipped, vignette, frame); - let gains = vignetting_gains(&unshaded, vignette, frame); - for (p, gain) in unshaded.data.iter_mut().zip(gains) { - *p = p.map(|v| v * (1.0 + (gain - 1.0) * share) as f32); - } - assert_eq!(bits(&unshaded), bits(&actual_proxy.0), "CR3 uses the share measured at the framed sensor positions"); - assert_eq!(main_proxy.2, actual_proxy.2, "CR3 masks keep Main semantics"); - assert!(cr3_samples(Some(&main_lens)) == cr3_samples(Some(&resolved)), "the database warp must not change pooled CR3 samples"); - assert!(correspondence_correction(&cr3, &file).is_none(), "the actual shared Pool/DNG lookup excludes CR3"); - let expected = super::colour::starting_colour_tags_with_correction(&mut cr3.clone(), &file, None); - assert_eq!(starting_colour_tags(&mut cr3.clone(), &file), expected, "public DNG lookup keeps Main's CR3 route"); - assert_eq!( - super::colour::starting_colour_tags_with_correction(&mut cr3, &file, Some(&resolved)), - expected, - "injected CR3 correction cannot bypass DNG scope" - ); + assert_eq!(correspondence_correction(&cr3, &file), Some(resolved)); + let warp_only = lightcraft_develop::EmbeddedLens { vignette: None, ..resolved }; + let expected = super::colour::starting_colour_tags_with_correction(&mut cr3.clone(), &file, Some(&warp_only)); + assert_ne!(expected, super::colour::starting_colour_tags_with_correction(&mut cr3.clone(), &file, None)); + assert_eq!(starting_colour_tags(&mut cr3, &file), expected, "public CR3 DNG lookup keeps the warp and excludes database shading"); } #[test] fn correspondence_mask_keeps_every_contributing_clipped_sample_and_invalid_border() { let mut mask = Rgb32f::new(8, 6); mask.data[2 * 8 + 3] = [1.0; 3]; - let result = resample_correspondence(&mask, |x, y| lightcraft_geom::Point::new(x + 0.75, y + 0.5)); + let result = resample_correspondence(&mask, |x, y| lightcraft_geom::Point::new(x + 0.75, y + 0.5), sample_correspondence); assert!(result.data[8 + 2][0] > 0.0 && result.data[8 + 3][0] > 0.0); assert!(result.data[2 * 8 + 2][0] > 0.0 && result.data[2 * 8 + 3][0] > 0.0); assert_eq!(result.data[0][0], 0.0); @@ -1497,6 +1483,570 @@ fn correspondence_mask_keeps_every_contributing_clipped_sample_and_invalid_borde assert!(reduced.data[1][0] > 0.0 && reduced.data[5][0] > 0.0); } +#[test] +fn cr3_framing_only_does_not_report_profile_gate_scores() { + let original = profile_geometry_scene(384, 256); + let candidate = profile_geometry_target(&original, &synthetic_profile_lens(), Cr3Framing::IDENTITY); + // Seed real proposal diagnostics, then ensure the framing-only call clears them. + assert!(super::proxy::estimate_profile_framing(&candidate, &candidate, &original).is_some()); + assert!(super::proxy::geometry_gate_scores().is_some()); + let _ = estimate_cr3_framing(&original, &original); + assert!(super::proxy::geometry_gate_scores().is_none()); + assert!(super::proxy::geometry_framed_scores().is_none()); +} + +/// Rejected registration must preserve both input allocations and pixel bits. A +/// missing/ineligible warp uses only the fallback search; an eligible warp adds +/// exactly one search on different (warped) pixels, never repeats either search. +#[test] +fn cr3_unchanged_geometry_preserves_allocations_and_bounds_search_work() { + for (correction, searches) in [(None, 1), (Some(Default::default()), 1), (Some(synthetic_profile_lens()), 2)] { + let sensor = profile_geometry_scene(384, 256); + let reference = sensor.clone(); + let mut mask = Rgb32f::new(sensor.width, sensor.height); + mask.data[17] = [1.0; 3]; + let sensor_ptr = sensor.data.as_ptr(); + let mask_ptr = mask.data.as_ptr(); + let mask_bits: Vec<_> = mask.data.iter().map(|p| p.map(f32::to_bits)).collect(); + super::proxy::take_framing_search_count(); + let (aligned, aligned_mask, frame) = super::proxy::align_cr3_geometry(sensor, mask, &reference, correction.as_ref(), None); + assert!(frame.lens.is_none(), "rejected geometry must leave no lens mapping"); + assert_eq!(super::proxy::take_framing_search_count(), searches, "bounded search budget for missing or rejected geometry"); + assert_eq!(aligned.data.as_ptr(), sensor_ptr, "no accepted framing or warp: retain sensor allocation"); + assert_eq!(aligned_mask.data.as_ptr(), mask_ptr, "no accepted framing or warp: retain mask allocation"); + assert_eq!(aligned.data, reference.data); + assert_eq!(aligned_mask.data.iter().map(|p| p.map(f32::to_bits)).collect::>(), mask_bits); + } +} + +/// Exercise selection through the same orchestration as file-local and pooled +/// fitting, including the proposal's comparisons with the framed fallback. +#[test] +fn cr3_geometry_selects_matching_profile_with_one_search_per_geometry() { + let sensor = profile_geometry_scene(384, 256); + let lens = synthetic_profile_lens(); + let framing = Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }; + let expected = profile_geometry_target(&sensor, &lens, framing); + let mut reference = expected.clone(); + reference.map_in_place(|p| p.map(|v| v.powf(0.7))); + let mask = Rgb32f::new(sensor.width, sensor.height); + let expected_mask = profile_geometry_target(&mask, &lens, framing); + super::proxy::take_framing_search_count(); + let (aligned, aligned_mask, frame) = super::proxy::align_cr3_geometry(sensor, mask, &reference, Some(&lens), None); + assert_eq!(frame.lens, Some(&lens)); + assert!(frame.framing.is_some()); + assert_eq!(super::proxy::take_framing_search_count(), 2); + assert!(super::proxy::geometry_gate_scores().is_some(), "proposal passed original geometry gates"); + assert!(super::proxy::geometry_framed_scores().is_some(), "proposal was compared with fallback on both splits"); + assert_profile_geometry_mask(&aligned, &aligned_mask, &expected_mask); + assert!(geometry_rms(&aligned, &expected) < 0.008, "matching proposal selected despite nonlinear JPEG tone"); +} + +/// Check the full known valid crop, so the RMS cannot hide lost samples behind NaNs. +fn assert_profile_geometry_mask(aligned: &Rgb32f, aligned_mask: &Rgb32f, expected_mask: &Rgb32f) { + assert_eq!((aligned.width, aligned.height), (expected_mask.width, expected_mask.height)); + assert_eq!((aligned_mask.width, aligned_mask.height), (expected_mask.width, expected_mask.height)); + assert_eq!(aligned.data.len(), expected_mask.data.len()); + assert_eq!(aligned_mask.data.len(), expected_mask.data.len()); + for (i, ((pixel, mask), expected)) in aligned.data.iter().zip(&aligned_mask.data).zip(&expected_mask.data).enumerate() { + // The barrel warp and inward framing used below keep the entire crop valid. + assert_eq!(*expected, [0.0; 3], "ground-truth crop must be valid and unclipped at {i}"); + assert!(pixel.iter().all(|v| v.is_finite()), "alignment lost a valid ground-truth sample at {i}"); + assert_eq!(*mask, *expected, "valid aligned pixels must retain the zero clip mask at {i}"); + } +} + +/// Forward accepted CR3 geometry through file-local fits, pooled pairs and DNG colour tags, +/// using the same default-cropped sensor samples. +#[test] +fn cr3_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() { + let mut raw = profile_geometry_raw(&profile_geometry_scene(416, 288), [1.0; 3]); + raw.format = RawFormat::Cr3; + let transform = lightcraft_raw::color::camera_transform(&raw, D65); + assert!(transform.matrix_is_fallback); + let mut sensor = sensor_proxy(&raw, 2, 384).unwrap(); + assert_eq!((sensor.width, sensor.height), (384, 256)); + sensor.map_in_place(|p| transform.matrix.apply_f32(p)); + let lens = synthetic_profile_lens(); + let mut target = profile_geometry_target(&sensor, &lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }); + target.map_in_place(|p| p.map(|v| v.powf(0.7))); + let file = profile_geometry_file(&target, craft_tiff::IfdBuilder::new()); + let (plain, reference, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, None).unwrap(); + let (mut aligned, _, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, Some(&lens)).unwrap(); + let mut plain_render = plain; + plain_render.map_in_place(|p| p.map(|v| v.powf(0.7))); + aligned.map_in_place(|p| p.map(|v| v.powf(0.7))); + assert!( + geometry_rms(&aligned, &reference) < geometry_rms(&plain_render, &reference) * 0.3, + "the file-local route uses the resolved crop-relative correction" + ); + let error = |pairs: Vec<([f64; 3], [f64; 3])>| { + let sum: f64 = pairs.iter().map(|(x, y)| transform.matrix.apply(*x).iter().zip(y).map(|(x, y)| (x.powf(0.7) - y).powi(2)).sum::()).sum(); + sum / pairs.len() as f64 + }; + let plain_samples = profile_samples(&raw, &file, None, None).unwrap(); + let aligned_samples = profile_samples(&raw, &file, None, Some(&lens)).unwrap(); + let tone_error = |samples: &[([f64; 3], f64)]| { + assert!(!samples.is_empty()); + samples + .iter() + .map(|(x, y)| { + let rgb = transform.matrix.apply(*x).map(|v| v.powf(0.7)); + (luma(rgb) - y).powi(2) + }) + .sum::() + / samples.len() as f64 + }; + assert!(tone_error(&aligned_samples.tone) < tone_error(&plain_samples.tone) * 0.1, "pooled tone samples use the selected geometry"); + let before = error(plain_samples.colour); + let after = error(aligned_samples.colour); + assert!(after < before * 0.1, "pooled colour calibration uses the same geometry: {before} -> {after}"); + // Merge / DNG conversion must encode the same calibrated colour as opening the RAW. + let mut opened = raw.clone(); + let (_, t, look) = starting_colour(&mut opened, &file, None, Some(&lens)); + assert!(look.is_some(), "the synthetic corrected preview supplies a camera look"); + let scale = crate::files::WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata); + let white = scale.dng_white(&raw.color, lightcraft_raw::color::as_shot_white_xy(&raw)); + let expected_tags = dng_colour(&raw.color, &white, &t, look.as_ref()).unwrap(); + let tags = super::colour::starting_colour_tags_with_correction(&mut raw, &file, Some(&lens)).unwrap(); + assert_eq!(tags, expected_tags, "DNG tags use the resolved correspondence geometry too"); + + assert_external_dng_vignette_contract(&raw, &sensor, &lens, &white); +} + +/// Apply oriented CR3 geometry once, with white balance applied once, across all EXIF orientations. +#[test] +fn cr3_profile_geometry_shares_orientation_and_applies_white_balance_once() { + check_cr3_profile_geometry_orientation(false); +} + +/// Keep the upstream source-position vignetting correction before CR3 profile geometry. +#[test] +fn cr3_vignetting_precedes_profile_geometry_in_every_orientation() { + check_cr3_profile_geometry_orientation(true); +} + +fn check_cr3_profile_geometry_orientation(vignetted: bool) { + let mut scene = profile_geometry_scene(416, 288); + scene.map_in_place(|p| p.map(|v| v * 0.3)); + let mut raw = profile_geometry_raw(&scene, [1.25, 1.0, 0.8]); + raw.format = RawFormat::Cr3; + let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); + assert!(transform.wb.windows(2).any(|v| (v[0] - v[1]).abs() > 0.01), "the fixture must exercise nonuniform as-shot WB"); + assert!(transform.matrix_is_fallback); + let mut sensor = sensor_proxy(&raw, 2, 384).unwrap(); + assert_eq!((sensor.width, sensor.height), (384, 256)); + let mut lens = synthetic_profile_lens(); + // A file-owned vignette is applied in full; a database vignette is measured separately below. + lens.source = lightcraft_develop::LensSource::File; + if vignetted { + lens.vignette = + Some(lightcraft_develop::EmbeddedVignette { k: [1.0, 0.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.45, 0.55), radius: 0.6 }); + } + super::look_fit::correct_vignetting(&mut sensor, Some(&lens), lightcraft_geom::Orientation::Normal); + sensor.map_in_place(|p| { + transform.matrix.apply_f32(std::array::from_fn(|i| p[i] * transform.wb[i] * 2f32.powf(transform.baseline_exposure as f32))) + }); + let mut target = profile_geometry_target(&sensor, &lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }); + target.map_in_place(|p| p.map(|v| v.powf(0.7))); + let to_srgb = lightcraft_color::SRGB.from_xyz().mul(&REC2020.to_xyz()); + let jpeg_range = target + .data + .iter() + .filter(|p| p.iter().all(|v| v.is_finite())) + .flat_map(|p| to_srgb.apply_f32(*p)) + .fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), v| (lo.min(v), hi.max(v))); + assert!(jpeg_range.0 >= 0.0 && jpeg_range.1 <= 1.0, "the generated reference must not clip: {jpeg_range:?}"); + let file = profile_geometry_file(&target, craft_tiff::IfdBuilder::new()); + for exif in 1..=8 { + let orientation = lightcraft_geom::Orientation::from_exif(exif); + raw.orientation = orientation; + let oriented_lens = lightcraft_pipeline::optics::reorient_lens(&lens, orientation, 384.0, 256.0); + let (aligned, reference, clipped) = proxies(&raw, &file, &transform, PROFILE_PROXY, 0.0, None, Some(&oriented_lens)).unwrap(); + if vignetted && exif == 6 { + let sensor = without_clipped(&aligned, &clipped).unwrap_or_else(|| aligned.clone()); + let to_camera = transform.matrix.inverse().unwrap(); + let expected = samples_from_proxies(&sensor, &reference, &to_camera).unwrap(); + let samples = profile_samples(&raw, &file, None, Some(&oriented_lens)).unwrap(); + assert!(!expected.colour.is_empty() && !expected.tone.is_empty()); + assert!( + samples.colour == expected.colour && samples.tone == expected.tone, + "both pooled inputs keep the source-position vignette of the accepted warp in a rotated crop" + ); + + // The JPEG was generated with half this database gain. Measure it through the normal per-file path. + let mut database = oriented_lens; + database.source = lightcraft_develop::LensSource::Database; + let vignette = database.vignette.as_mut().unwrap(); + vignette.k[0] *= 2.0; + let vignette = *vignette; + let warp_only = lightcraft_develop::EmbeddedLens { vignette: None, ..database }; + let (unshaded, jpeg, mask, frame) = + super::proxy::framed_proxies(&raw, &file, &transform, PROXY, 0.0, None, super::proxy::ProxyLens::PerFile(Some(&warp_only))).unwrap(); + assert!(frame.lens.is_some(), "the lens warp wins before measuring its shading"); + let framing = frame.framing.unwrap(); + let amount = camera_vignetting_amount(&unshaded, &jpeg, &mask, &vignette, frame); + assert!((0.3..=0.7).contains(&amount), "partially corrected JPEG, measured {amount}"); + let (measured, _, _) = super::look_fit::look_proxies(&raw, &file, &transform, None, Some(&database)).unwrap(); + let (w, h) = (unshaded.width, unshaded.height); + let mut warp = lightcraft_pipeline::optics::Warp::identity(w as f64, h as f64); + warp.lens = Some(database); + warp.lens_dist = 1.0; + for (i, (before, after)) in unshaded.data.iter().zip(&measured.data).enumerate() { + let (x, y) = framing.source((i % w) as f32 + 0.5, (i / w) as f32 + 0.5, w, h); + let source = warp.corrected_to_source(lightcraft_geom::Point::new(f64::from(x), f64::from(y)), 1); + let gain = lightcraft_pipeline::optics::embedded_vignette_gain(&vignette, source, w as f64, h as f64); + let expected = before.map(|v| v * (1.0 + amount * (gain - 1.0)) as f32); + assert_eq!(*after, expected, "database shading uses the selected sensor position at pixel {i}"); + } + } + let mut no_warp = oriented_lens; + no_warp.warp = None; + let (baseline, _, _) = proxies(&raw, &file, &transform, PROFILE_PROXY, 0.0, None, Some(&no_warp)).unwrap(); + assert!( + aligned.data.iter().flatten().zip(baseline.data.iter().flatten()).any(|(a, b)| a.to_bits() != b.to_bits()), + "orientation {exif}: profile geometry must be accepted with identical vignetting on both routes" + ); + let mut displayed = aligned.clone(); + displayed.map_in_place(|p| p.map(|v| v.powf(0.7))); + let rms = geometry_rms(&displayed, &reference); + assert!(rms < 0.009, "orientation {exif}: WB exactly once and matching frames: {rms}"); + let oriented_target = target.clone().into_oriented(orientation); + let expected = reference_at(&oriented_target, &aligned); + assert!(geometry_rms(&displayed, &expected) < 0.009, "orientation {exif}: absolute oriented ground truth"); + // Missing geometry must take the same established CR3 framing path as a rejected profile. + let (plain, plain_ref, plain_clip) = proxies(&raw, &file, &transform, PROXY, 0.0, None, None).unwrap(); + let (fallback, fallback_ref, fallback_clip) = proxies(&raw, &file, &transform, PROXY, 0.0, None, Some(&Default::default())).unwrap(); + assert_eq!(plain.data, fallback.data); + assert_eq!(plain_ref.data, fallback_ref.data); + assert_eq!(plain_clip, fallback_clip); + } +} + +/// Sensor, JPEG and clipping samples returned by the diagnostic proxy calls. +type DiagnosticProxy = (Rgb32f, Rgb32f, Vec); + +/// Keep diagnostic TSV fields single-line and reversible, including literal backslashes. +fn diagnostic_tsv_field(value: &str) -> String { + value.replace('\\', "\\\\").replace('\t', "\\t").replace('\r', "\\r").replace('\n', "\\n") +} + +/// Derive the PNG path from the native filename. Lossy text is used only for display in geometry.tsv. +fn diagnostic_png_path(output: &std::path::Path, name: &std::ffi::OsStr, label: &str) -> std::path::PathBuf { + let mut png = name.to_owned(); + png.push(format!("-{label}.png")); + output.join(png) +} + +#[cfg(any(unix, windows))] +#[test] +fn cr3_diagnostics_preserve_distinct_native_filenames() { + #[cfg(unix)] + let names = { + use std::os::unix::ffi::OsStrExt; + [b"A\x80.CR3", b"A\x81.CR3"].map(|bytes| std::ffi::OsStr::from_bytes(bytes).to_owned()) + }; + #[cfg(windows)] + let names = { + use std::os::windows::ffi::OsStringExt; + [0xd800, 0xd801].map(|unit| std::ffi::OsString::from_wide(&[65, unit, 46, 67, 82, 51])) + }; + let output = std::path::Path::new("diagnostics"); + assert_eq!(names[0].to_string_lossy(), names[1].to_string_lossy()); + for label in ["plain", "chosen", "jpeg"] { + assert_ne!(diagnostic_png_path(output, &names[0], label), diagnostic_png_path(output, &names[1], label)); + } +} + +/// Remove only this source's three owned output files; filesystem errors must stop the diagnostic. +fn remove_diagnostic_pngs(output: &std::path::Path, name: &std::ffi::OsStr) -> std::io::Result<()> { + for label in ["plain", "chosen", "jpeg"] { + match std::fs::remove_file(diagnostic_png_path(output, name, label)) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + } + Ok(()) +} + +/// Preserve missing-proxy cases in the diagnostic TSV without inventing geometry or fit results. +/// `proxies` exposes no rejection reason, so the row records only which call returned `None`. +fn diagnostic_proxies_or_report( + output: &std::path::Path, + name: impl AsRef, + raw: &RawImage, + profile_warp: bool, + plain: Option, + chosen: Option, + report: &mut String, +) -> std::io::Result> { + let name = name.as_ref(); + let status = match (plain, chosen) { + (Some(plain), Some(chosen)) => return Ok(Some((plain, chosen))), + (None, Some(_)) => "missing_plain_proxy", + (Some(_), None) => "missing_chosen_proxy", + (None, None) => "missing_both_proxies", + }; + remove_diagnostic_pngs(output, name)?; + let mut fields = vec![String::new(); 17]; + fields[0] = diagnostic_tsv_field(&name.to_string_lossy()); + fields[1] = diagnostic_tsv_field(raw.metadata.model.as_deref().unwrap_or("")); + fields[2] = format!("{:?}", raw.orientation); + fields[3] = profile_warp.to_string(); + fields[15] = status.to_owned(); + fields[16] = "proxies returned None; underlying cause unavailable".to_owned(); + report.push_str(&fields.join("\t")); + report.push('\n'); + Ok(None) +} + +/// Build a small RGB CR3-shaped raw and embedded JPEG without opening any real photo. +fn diagnostic_proxy_fixture() -> (RawImage, Vec) { + let scene = profile_geometry_scene(96, 64); + let mut raw = profile_geometry_raw(&scene, [1.0; 3]); + raw.format = RawFormat::Cr3; + raw.crop = raw.active_area; + let file = profile_geometry_file(&scene, craft_tiff::IfdBuilder::new()); + (raw, file) +} + +/// Exercise the corpus diagnostic's actual proxy-result handling across missing and available inputs. +#[test] +fn cr3_diagnostics_report_missing_proxies_and_continue() { + let output = std::env::temp_dir().join(format!("lc-cr3-missing-{}", std::process::id())); + let (mut raw, bytes) = diagnostic_proxy_fixture(); + let transform = lightcraft_raw::color::camera_transform(&raw, D65); + let available = proxies(&raw, &bytes, &transform, PROXY, 0.0, None, None).unwrap(); + // A valid spectral transform does not guarantee a usable sensor proxy. This synthetic + // single-channel raw lacks a CFA, so the established proxy path deliberately returns None. + let camera = lightcraft_raw::spectral::find(Some("Canon"), "Canon EOS R8").unwrap(); + raw.color.color_matrix = camera.color_matrix.map(Some); + raw.color.forward_matrix = camera.forward_matrix.map(Some); + raw.color.illuminant = [17, 21]; + raw.cpp = 1; + raw.data = lightcraft_raw::RawData::U16(vec![0; raw.width * raw.height]); + let calibrated = lightcraft_raw::color::camera_transform(&raw, D65); + assert!(!calibrated.matrix_is_fallback); + let missing = proxies(&raw, &bytes, &calibrated, PROXY, 0.0, None, None); + assert!(missing.is_none()); + let mut report = String::new(); + for (plain, chosen, status) in [ + (missing.clone(), missing.clone(), "missing_both_proxies"), + (missing.clone(), Some(available.clone()), "missing_plain_proxy"), + (Some(available.clone()), missing, "missing_chosen_proxy"), + ] { + assert!(diagnostic_proxies_or_report(&output, status, &raw, true, plain, chosen, &mut report).unwrap().is_none()); + } + let (plain, chosen) = + diagnostic_proxies_or_report(&output, "available", &raw, false, Some(available.clone()), Some(available.clone()), &mut report) + .unwrap() + .expect("a later usable file must still reach measurement and image export"); + let bits = |image: &Rgb32f| image.data.iter().flatten().map(|v| v.to_bits()).collect::>(); + assert_eq!(bits(&plain.0), bits(&available.0)); + assert_eq!(chosen.1.data, available.1.data); + let rows: Vec<_> = report.lines().collect(); + assert_eq!(rows.len(), 3, "available proxies must not create an unavailable row"); + for row in rows { + let fields: Vec<_> = row.split('\t').collect(); + assert_eq!(fields.len(), 17); + assert_eq!(fields[0], fields[15], "all three missing cases retain distinct statuses"); + assert!(fields[4..15].iter().all(|v| v.is_empty()), "unavailable metrics, gates and fits stay empty"); + assert_eq!(fields[16], "proxies returned None; underlying cause unavailable"); + } +} + +/// Tabs, line endings and literal escape sequences remain distinguishable without changing the TSV schema. +#[test] +fn cr3_diagnostics_escape_text_fields_in_missing_rows() { + let name = "A\tB\nC\rD\\t.CR3"; + let model = "Camera\tmodel\nline\rreturn\\n"; + assert_eq!(diagnostic_tsv_field(name), r"A\tB\nC\rD\\t.CR3"); + assert_eq!(diagnostic_tsv_field(model), r"Camera\tmodel\nline\rreturn\\n"); + let (mut raw, _) = diagnostic_proxy_fixture(); + raw.metadata.model = Some(model.into()); + let output = std::env::temp_dir().join(format!("lc-cr3-tsv-{}", std::process::id())); + let mut report = String::new(); + assert!(diagnostic_proxies_or_report(&output, name, &raw, false, None, None, &mut report).unwrap().is_none()); + assert_eq!(report.lines().count(), 1); + let fields: Vec<_> = report.trim_end_matches('\n').split('\t').collect(); + assert_eq!(fields.len(), 17); + assert_eq!(fields[0], diagnostic_tsv_field(name)); + assert_eq!(fields[1], diagnostic_tsv_field(model)); + assert_eq!(fields[15], "missing_both_proxies"); + assert_eq!(fields[16], "proxies returned None; underlying cause unavailable"); +} + +/// A missing-proxy rerun removes old owned PNGs and preserves unrelated files and directories. +#[test] +fn cr3_diagnostics_missing_rerun_removes_stale_pngs() { + let output = std::env::temp_dir().join(format!("lc-cr3-rerun-{}", std::process::id())); + std::fs::create_dir_all(&output).unwrap(); + let pixels = [23u8, 41, 59]; + let image = lightcraft_codecs::EncodeImage::new(1, 1, 3, lightcraft_codecs::Samples::U8(&pixels)); + let png = lightcraft_codecs::encode_png(&image, &Default::default()).unwrap(); + for label in ["plain", "chosen", "jpeg"] { + std::fs::write(output.join(format!("A.CR3-{label}.png")), &png).unwrap(); + } + std::fs::write(output.join("other.png"), &png).unwrap(); + std::fs::create_dir_all(output.join("other-directory")).unwrap(); + let (raw, _) = diagnostic_proxy_fixture(); + let mut report = String::new(); + assert!(diagnostic_proxies_or_report(&output, "A.CR3", &raw, true, None, None, &mut report).unwrap().is_none()); + std::fs::write(output.join("geometry.tsv"), &report).unwrap(); + assert_eq!(std::fs::read_to_string(output.join("geometry.tsv")).unwrap(), report); + let fields: Vec<_> = report.trim_end_matches('\n').split('\t').collect(); + assert_eq!(fields.len(), 17); + assert_eq!(fields[0], "A.CR3"); + assert_eq!(fields[15], "missing_both_proxies"); + for label in ["plain", "chosen", "jpeg"] { + assert!(!output.join(format!("A.CR3-{label}.png")).exists(), "no earlier PNG can appear current"); + } + assert_eq!(std::fs::read(output.join("other.png")).unwrap(), png); + assert!(output.join("other-directory").is_dir()); + // A directory occupying an owned filename is an error, never a request for recursive deletion. + std::fs::create_dir(output.join("A.CR3-plain.png")).unwrap(); + let before = report.clone(); + assert!(diagnostic_proxies_or_report(&output, "A.CR3", &raw, true, None, None, &mut report).is_err()); + assert_eq!(report, before, "failed cleanup must not publish a misleading missing-result row"); + assert!(output.join("A.CR3-plain.png").is_dir()); + std::fs::remove_dir_all(output).unwrap(); +} + +/// Opt-in diagnostic only: never opens the app or changes a catalogue. It exports the actual +/// selected correspondences, and reports rejection as rejection rather than decoder success. +#[test] +#[ignore = "explicit local corpus diagnostic; requires LIGHTCRAFT_CR3_DIAGNOSTICS and LIGHTCRAFT_CORPUS"] +fn corpus_cr3_profile_geometry_diagnostics() { + let output = std::env::var_os("LIGHTCRAFT_CR3_DIAGNOSTICS").expect("explicit diagnostics require an output directory"); + let corpus = std::path::PathBuf::from(std::env::var_os("LIGHTCRAFT_CORPUS").expect("diagnostics require a corpus")); + let output = std::path::PathBuf::from(output); + std::fs::create_dir_all(&output).unwrap(); + let mut report = String::from( + "file\tmodel\torientation\tprofile_warp\tgeometry_accepted\tplain_alignment\tchosen_alignment\tplain_structure\tchosen_structure\tplain_pairs\tchosen_pairs\tplain_look\tchosen_look\tframed_gate_scores\toriginal_gate_scores\tstatus\treason\n", + ); + let mut paths: Vec<_> = std::fs::read_dir(corpus.join("raw")) + .unwrap() + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("cr3"))) + .collect(); + paths.sort(); + assert!(!paths.is_empty(), "diagnostic corpus must contain CR3 files"); + for path in paths { + let bytes = std::fs::read(&path).unwrap(); + let mut raw = lightcraft_raw::decode(&bytes).unwrap(); + let correction = crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(&bytes)); + let lens = lens_geometry(&raw.opcodes.list3); + raw.opcodes.list3.retain(|op| !op.is_lens_correction()); + let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); + // Compare geometry with identical source-position vignetting on both routes. + let plain_correction = correction.map(|mut lens| { + lens.warp = None; + lens + }); + let plain = super::look_fit::look_proxies(&raw, &bytes, &transform, lens.as_ref(), plain_correction.as_ref()); + let chosen = super::look_fit::look_proxies(&raw, &bytes, &transform, lens.as_ref(), correction.as_ref()); + let name = path.file_name().unwrap(); + let profile_warp = correction.as_ref().is_some_and(|l| l.warp.is_some()); + let Some((plain, chosen)) = diagnostic_proxies_or_report(&output, name, &raw, profile_warp, plain, chosen, &mut report).unwrap() else { + std::fs::write(output.join("geometry.tsv"), &report).unwrap(); + continue; + }; + let framed_scores = super::proxy::geometry_framed_scores(); + let original_scores = if profile_warp { super::proxy::geometry_gate_scores() } else { None }; + let accepted = plain.0.data.iter().flatten().zip(chosen.0.data.iter().flatten()).any(|(a, b)| a.to_bits() != b.to_bits()); + let pairs = |v: &(Rgb32f, Rgb32f, Vec)| { + let sensor = without_clipped(&v.0, &v.2).unwrap_or_else(|| v.0.clone()); + collect_pairs(&sensor, &v.1, 0.05, None, false).map_or(0, |v| v.0.len()) + }; + let before = fit_preview(&raw, &bytes, &transform, lens.as_ref(), plain_correction.as_ref()).0.is_some(); + let after = fit_preview(&raw, &bytes, &transform, lens.as_ref(), correction.as_ref()).0.is_some(); + report.push_str(&format!( + "{}\t{}\t{:?}\t{}\t{accepted}\t{:.6}\t{:.6}\t{}\t{}\t{}\t{}\t{before}\t{after}\t{framed_scores:?}\t{original_scores:?}\tmeasured\t\n", + diagnostic_tsv_field(&name.to_string_lossy()), + diagnostic_tsv_field(raw.metadata.model.as_deref().unwrap_or("")), + raw.orientation, + profile_warp, + alignment(&plain.0, &plain.1), + alignment(&chosen.0, &chosen.1), + structure_agrees(&plain.0, &plain.1), + structure_agrees(&chosen.0, &chosen.1), + pairs(&plain), + pairs(&chosen) + )); + for (label, image) in [("plain", &plain.0), ("chosen", &chosen.0), ("jpeg", &chosen.1)] { + let to_srgb = lightcraft_color::SRGB.from_xyz().mul(&REC2020.to_xyz()); + let pixels: Vec = image + .data + .iter() + .flat_map(|p| { + to_srgb.apply_f32(*p).map(|v| { + let v = if v.is_finite() { v.max(0.0) } else { 0.0 }; + let v = if v <= 0.0031308 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + (v.clamp(0.0, 1.0) * 255.0).round() as u8 + }) + }) + .collect(); + let image = lightcraft_codecs::EncodeImage::new(image.width as u32, image.height as u32, 3, lightcraft_codecs::Samples::U8(&pixels)); + std::fs::write(diagnostic_png_path(&output, name, label), lightcraft_codecs::encode_png(&image, &Default::default()).unwrap()).unwrap(); + } + std::fs::write(output.join("geometry.tsv"), &report).unwrap(); + } +} + +/// Keep the accepted CR3 framing fallback when a proposed profile warp fails its paired comparison. +#[test] +fn cr3_rejected_profile_preserves_accepted_framing_fallback() { + let mut raw = profile_geometry_raw(&profile_geometry_scene(416, 288), [1.25, 1.0, 0.8]); + raw.format = RawFormat::Cr3; + let transform = lightcraft_raw::color::camera_transform(&raw, D65); + assert!(transform.matrix_is_fallback); + let mut sensor = sensor_proxy(&raw, 2, 384).unwrap(); + assert_eq!((sensor.width, sensor.height), (384, 256)); + sensor.map_in_place(|p| { + transform.matrix.apply_f32(std::array::from_fn(|i| p[i] * transform.wb[i] * 2f32.powf(transform.baseline_exposure as f32))) + }); + let lens = synthetic_profile_lens(); + let mut target = profile_geometry_target(&sensor, &Default::default(), Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }); + target.map_in_place(|p| p.map(|v| v.powf(0.7))); + let file = profile_geometry_file(&target, craft_tiff::IfdBuilder::new()); + let original_only = align_profile_geometry(&sensor, &Rgb32f::new(384, 256), &target, &lens, lightcraft_geom::Orientation::Normal); + assert!(original_only.is_some(), "this moderate wrong-lens proposal clears original-only gates, so the framed guard is necessary"); + let (plain, reference, mask) = proxies(&raw, &file, &transform, PROXY, 0.0, None, None).unwrap(); + let (fallback, fallback_reference, fallback_mask) = proxies(&raw, &file, &transform, PROXY, 0.0, None, Some(&lens)).unwrap(); + let mut comparison = plain.clone(); + comparison.map_in_place(|p| p.map(|v| v.powf(0.7))); + assert!(geometry_rms(&comparison, &reference) < 0.009, "existing framing fallback still aligns this JPEG"); + assert!( + plain.data.iter().flatten().zip(fallback.data.iter().flatten()).all(|(a, b)| a.to_bits() == b.to_bits()), + "wrong lens must be rejected before established framing" + ); + assert_eq!(reference.data, fallback_reference.data); + assert_eq!(mask, fallback_mask); + + let plain_samples = profile_samples(&raw, &file, None, None).unwrap(); + assert!(!plain_samples.colour.is_empty() && !plain_samples.tone.is_empty()); + let mut correction = lens; + correction.vignette = + Some(lightcraft_develop::EmbeddedVignette { k: [0.15, 0.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.5, 0.5), radius: 0.6 }); + correction.source = lightcraft_develop::LensSource::Database; + let no_warp = lightcraft_develop::EmbeddedLens { warp: None, ..correction }; + let measured = super::look_fit::look_proxies(&raw, &file, &transform, None, Some(&no_warp)).unwrap(); + let rejected = super::look_fit::look_proxies(&raw, &file, &transform, None, Some(&correction)).unwrap(); + assert_eq!(measured.0.data, rejected.0.data, "rejection preserves the database-vignette measurement on the original framing"); + assert_eq!(measured.2, rejected.2); + let rejected_warp = correction.warp; + for (case, warp) in [("rejected warp", rejected_warp), ("absent warp", None)] { + correction.warp = warp; + let samples = profile_samples(&raw, &file, None, Some(&correction)).unwrap(); + assert!( + samples.colour == plain_samples.colour && samples.tone == plain_samples.tone, + "{case} must preserve both original pooled inputs with a nonzero vignette" + ); + } +} + /// The guarded fit is assessed on real sensor data, never on the JPEG fallback. A corpus /// download or an unfinished codec cannot make this test claim a successful RAW calibration. #[test] @@ -3596,7 +4146,7 @@ fn the_vignetting_gain_of_a_framed_proxy_is_taken_where_its_pixels_come_from() { let vignette = EmbeddedVignette { k: [2.0, 1.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.5, 0.5), radius: 0.6 }; let (w, h) = (96, 64); let framing = Cr3Framing { scale: 0.92, offset: [0.02, -0.015] }; - let frame = ProxyFrame { orientation: lightcraft_geom::Orientation::Normal, framing: Some(framing) }; + let frame = ProxyFrame { orientation: lightcraft_geom::Orientation::Normal, framing: Some(framing), lens: None }; let gains = vignetting_gains(&Rgb32f::new(w, h), &vignette, frame); for i in [0, w - 1, w * h / 2 + w / 3, w * h - 1] { let (x, y) = framing.source((i % w) as f32 + 0.5, (i / w) as f32 + 0.5, w, h); @@ -3738,7 +4288,7 @@ fn camera_vignetting_amount_follows_a_cr3_proxys_framing() { } let clipped = vec![false; w * h]; let measure = |reference: &Rgb32f, framing: Option| { - camera_vignetting_amount(&sensor, reference, &clipped, &vignette, ProxyFrame { orientation: Orientation::Normal, framing }) + camera_vignetting_amount(&sensor, reference, &clipped, &vignette, ProxyFrame { orientation: Orientation::Normal, framing, lens: None }) }; for shown in [0.0f32, 0.75, 1.0] { let mut reference = sensor.clone(); diff --git a/crates/engine/src/camera_profiles.rs b/crates/engine/src/camera_profiles.rs index 0a21cae9c1..66fd57b87a 100644 --- a/crates/engine/src/camera_profiles.rs +++ b/crates/engine/src/camera_profiles.rs @@ -321,7 +321,7 @@ fn thinned(items: Vec) -> impl Iterator { impl Pool { /// Add one raw file's colour pairs and tone samples. A photo too dark or colourless for colour pairs still gives /// its tone samples (the shadows the pooled curve needs) without counting toward the profile's photos. `Ok(None)` - /// when the file can't contribute (not an ARW, NEF or RAF without colour matrices, no usable or a black-and-white + /// when the file can't contribute (not a supported RAW without colour matrices, no usable or a black-and-white /// camera JPEG). pub fn add(&mut self, bytes: &[u8]) -> Result, String> { let mut raw = lightcraft_raw::decode(bytes).map_err(|e| e.to_string())?; diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index 8d86976535..60a39d2b67 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -24,7 +24,7 @@ One third of the pixels are held out from both fits. The combined model must red **Lens-corrected camera JPEGs.** Some raws carry the camera's own lens correction (Fujifilm and Panasonic tables, the ILCE-7RM4A, Nikon's NikonNEFInfo) and the camera often applies it to its JPEG. Nikon Z lenses always do, and that JPEG can be zoomed in by up to 9% to fill the frame. The fit used to pair the uncorrected sensor with the corrected JPEG, so near the edges it compared pixels from different parts of the scene. Now the sensor proxy is also warped with the file's correction (`into_lens_geometry`, pixels that land outside the picture are dropped), and the fit uses whichever of the two lines up better with the JPEG, going by the correlation of their high-passed log luminance. Files whose JPEG isn't corrected keep the plain proxy. On the 29 CC0 corpus raws with a warp the alignment goes up by 0.13 on average (Panasonic GX80 0.41 to 0.83, Fujifilm X-T20 0.44 to 0.95). Mean ΔE against the camera JPEG over the 35 corpus raws of those formats goes from 3.73 to 3.61, and on 299 private Z 6II photos with Nikon's correction read it goes from 3.22 to 2.68. -**Resolved profiles and remaining camera framing.** For file-local fitting without a camera matrix or an in-file opcode warp, the resolved lens profile can additionally propose a corrected sensor proxy. Its green-plane map is evaluated through the same `Warp::corrected_to_source` used by the renderer, in the developed default crop; oriented profiles are re-expressed in sensor coordinates first. The existing bounded framing search (scale 0.9–1.1, translation at most two pixels on a fixed 96-pixel proxy) may then align the camera JPEG's remaining crop. At least 192 edges are required. Both training and held-out edge directions must agree by at least 0.90 and improve by at least 0.04 over the **original unwarped** geometry, with at least 80% usable edges in each split. For each proposal candidate, the original and candidate scores use the exact intersection of valid edges with the same reference weights, during both training selection and held-out confirmation. Lens correction alone can pass with identity framing. Weak, unrelated or already aligned previews keep the original route; absent profiles, CR3 and the established opcode-warp route retain their existing behaviour. +**Resolved profiles and remaining camera framing.** For file-local fitting without a camera matrix or an in-file opcode warp, the resolved lens profile can additionally propose a corrected sensor proxy. Its green-plane map is evaluated through the same `Warp::corrected_to_source` used by the renderer, in the developed default crop; oriented profiles are re-expressed in sensor coordinates first. The existing bounded framing search (scale 0.9–1.1, translation at most two pixels on a fixed 96-pixel proxy) may then align the camera JPEG's remaining crop. At least 192 edges are required. Both training and held-out edge directions must agree by at least 0.90 and improve by at least 0.04 over the **original unwarped** geometry, with at least 80% usable edges in each split. For each proposal candidate, the original and candidate scores use the exact intersection of valid edges with the same reference weights, during both training selection and held-out confirmation. Lens correction alone can pass with identity framing. Weak, unrelated or already aligned previews keep the original route. CR3 also compares the candidate against its accepted framing, as described under [Canon CR3](#canon-cr3). Files with an in-file opcode warp keep their existing route. This changes calibration correspondences only, including `calibrate`'s pooled pairs and the colour tags used by merge/DNG conversion. It is independent of the user's Optics switch and does not bake geometric correction into the rendered RAW. Sensor and clipping mask follow the same sampling maps; invalid borders cannot train the look. Matrix, hue/saturation, tone fitting and their colour-error acceptance gates are unchanged. A physically plausible lens correction alone is not assumed to match a camera JPEG: geometry must establish the correspondence before it is used. Cached renders and camera looks have new versions so online originals rebuild their calibration. Cameras without a safely resolved geometric profile receive no new guarantee of colour accuracy. @@ -110,9 +110,11 @@ These are camera-JPEG look estimates, **not measured spectral calibration or Lig ### Canon CR3 -CR3 uses the same colour gates and relative WB. Its sensor and JPEG proxies are first oriented identically. Canon can crop its JPEG differently from the sensor; no lens distortion correction is applied to the sensor proxy, so a strongly distortion-corrected JPEG can fail the gates. A fixed 96-pixel proxy measures this remaining framing from luminance-gradient directions: scale is limited to 0.9–1.1 and translation to two proxy pixels. At least 192 edges are required; two thirds train the framing and the remaining third must independently reach direction agreement ≥0.90 with an improvement ≥0.04. At least 80% of each edge set must remain usable. Weak, flat, unrelated or already aligned references keep the sensor framing. This alignment affects training correspondences only; the RAW render still uses the actual sensor pixels. +CR3 uses the same colour gates and relative WB. Its sensor and JPEG proxies are first oriented identically. Canon can crop or radially correct its JPEG. LightCraft first estimates the framing of the unwarped sensor proxy. A fixed 96-pixel proxy measures this remaining framing from luminance-gradient directions: scale is limited to 0.9–1.1 and translation to two proxy pixels. At least 192 edges are required; two thirds train the framing and the remaining third must independently reach direction agreement ≥0.90 with an improvement ≥0.04. At least 80% of each edge set must remain usable. Weak, flat, unrelated or already aligned references keep the sensor framing. This alignment affects training correspondences only; the RAW render still uses the actual sensor pixels. -On the public CC0 EOS R100 / RF-S 18–45 mm sample, the measured framing scale was 0.968. Held-out edge agreement rose from 0.7291 to 0.9194, and the unchanged colour gates accepted the fit (held-out RMS 0.10625 → 0.07704). The corpus test asserts acceptance after decoding the sensor RAW, and synthetic tests cover nonlinear camera tone, known crop/translation and unrelated references. The matrix, tone and hue/saturation table are estimated from the file; no third-party camera matrix or decoder calibration source is copied. +When the camera matrix is a fallback and the file carries no warp, a resolved lens profile can supply an alternative. On both edge sets it must improve on the original geometry and match or beat the accepted framing. Each comparison uses the same valid edges and weights on both sides. The clipping mask follows the sensor through both sampling passes. An absent or rejected profile keeps the framing result. See [CR3 profile correspondence geometry](cr3-profile-alignment.md). + +On the public CC0 EOS R100 / RF-S 18–45 mm sample, the framing-only measurement gave a scale of 0.968. Held-out edge agreement rose from 0.7291 to 0.9194, and the unchanged colour gates accepted the fit (held-out RMS 0.10625 → 0.07704). The corpus test asserts acceptance after decoding the sensor RAW, and synthetic tests cover nonlinear camera tone, known crop/translation and unrelated references. The matrix, tone and hue/saturation table are estimated from the file; no third-party camera matrix or decoder calibration source is copied. This is a per-file camera-look estimate, **not measured spectral calibration or Lightroom parity**. Camera local tone, picture styles, noise reduction and lens warps cannot all be reproduced by a global matrix/curve; same-aspect crops may evade the aspect check. Skin, mixed-light scenes and saturated highlights can still differ from a supplied JPEG. Broader Sony, Nikon and Canon model/lighting coverage, chart-based calibration, absolute WB and other manufacturers remain unverified. Rejected fits and other RAW formats retain their existing behaviour. @@ -152,11 +154,10 @@ share the JPEG shows (`camera_vignetting_amount`): the camera's tone curve is mo sensor ranks its pixels' luminance most like the JPEG wins (0 to 100 % in 5 % steps). The ranks are compared within classes of similar sensor chromaticity (near-neutral and eight hue sectors), weighted by their pixel counts: a camera that renders some hues brighter than others would otherwise read as vignetting where those hues gather toward the -corners. A CR3 proxy moved to its JPEG's framing gets the gain of the position each pixel shows, and a DNG's tone fit +corners. A CR3 proxy moved to its JPEG's framing gets the gain of the sensor position each pixel shows, including any accepted profile warp. A DNG's tone fit (`fit_dng_tone`) takes a database profile in the measured share too. The whole correction is kept when nothing can be measured: proxies of different sizes, fewer than 256 usable pixels (pixels clipped on the sensor or in the camera -JPEG, black and non-finite ones are left out, as are chromaticity classes under 32 pixels), a lens-warped sensor proxy (the gain would no longer be at each -pixel's source position); shares that rank alike keep the larger one. Within a class the camera's rendering is taken as alike, so two +JPEG, black and non-finite ones are left out, as are chromaticity classes under 32 pixels), a lens-warped sensor proxy whose source positions are unavailable; shares that rank alike keep the larger one. Within a class the camera's rendering is taken as alike, so two saturations of one hue that it renders differently, one gathered toward the corners, can still read as vignetting. With the whole profile, an ILCE-7M3 frame at f/2 with an FE 28mm F2 (lensfun: corners at 16 % of the centre) fitted 0.062 held-out RMS instead of 0.027 and rendered darker and orange. Its camera JPEG, with vignetting correction Auto @@ -288,10 +289,6 @@ is recorded here yet. Whether they should come before the file-local fit for the A smart preview keeps the result of the fit twice: the colour matrix is baked into its pixels and the tone and chroma curves are stored in its header. When the fit changes, a preview built earlier keeps the old look until it is rebuilt, and the render cache version does not reach it (renders are keyed on the library's files, proxies are files of their own). -This independent proposal applies directly to upstream main; it requires no prior merge of the separate CR3 proposal #3138. CR3 retains upstream framing and its existing per-file source-position vignetting. The newly added Pool/DNG profile lookup excludes CR3, including a resolved profile that carries both warp and nonzero vignetting. - -The synchronized geometry-gated external-profile correspondence fit uses `LOOK_VERSION = 27` and `RENDER_CACHE_VERSION = 88`, after upstream versions 26 and 87, invalidating both stale smart-preview looks and rendered thumbnails. The private-file observations above were recorded on the original proposal. - The fit therefore has a version, `LOOK_VERSION` in `crates/engine/src/camera_preview.rs`, and every smart preview records the version that wrote it in its header line (`look_version`). **Bump the constant in any change that makes the fit give a different result for the same file**: the matrix, hue/saturation, tone or chroma fit, their gates and fallbacks, or how a camera profile feeds them. Changes that leave the fitted look alone don't need it. A header without the field (everything built before it existed) counts as version 0, and so does a value that is not a non-negative integer; a value from a newer build is left alone. A proxy older than the constant is brought up to date by the existing Build Smart Previews path (`smart_run`), which also repairs damaged proxies: diff --git a/docs/cr3-profile-alignment.md b/docs/cr3-profile-alignment.md new file mode 100644 index 0000000000..a06f462049 --- /dev/null +++ b/docs/cr3-profile-alignment.md @@ -0,0 +1,80 @@ +# CR3 profile correspondence geometry + +A Canon CR3 can pair different scene points when the camera corrects radial distortion in its +embedded JPEG. During colour calibration, LightCraft compares a resolved lens profile with the +framing it already estimated from the unwarped sensor. The selected geometry determines which +sensor and JPEG samples train the look. The RAW decoder and the Optics setting still determine +how LightCraft renders the photograph. + +A resolved external lens profile may propose geometry only for file-local colour calibration +and pooled camera-profile samples, with a fallback camera matrix and no in-file lens warp. The sensor, sensor clip mask, and embedded JPEG are +oriented together before evaluating the already oriented lens profile. White balance and +baseline exposure are applied exactly once before geometry assessment. + +The existing fixed-proxy edge test, bounded framing search (scale 0.9–1.1 and translation up to +two proxy pixels), minimum edge coverage, 0.9 agreement, and independent held-out improvement +of at least 0.04 are retained. Geometry uses luminance edge directions, without fitting RGB +values. Accepted geometry moves the sensor and clip mask together; invalid borders remain NaN. +CR3 proposals must also preserve or improve agreement against the existing framed fallback +on both training and held-out edges, compared on the exact intersection of valid edges with +the same reference weights. The published minimum 0.04 improvement over the unframed sensor +is retained separately, using the exact intersection of original and candidate edges and the same +reference weights for each candidate during training and for the held-out check. The fallback +comparison adds no extra improvement threshold. Rejected or absent geometry takes the existing +CR3 framing path. All subsequent colour, +tone, hue/saturation, clipping, and held-out acceptance gates stay unchanged. + +The proposal reaches file-local colour and tone, pooled colour pairs and tone samples, and colour tags +for merge/DNG conversion. The DNG colour fit uses the external profile for correspondence geometry +without its vignette gains: the unchanged sensor samples and the DNG writer do not carry that +database shading correction. The file-local fit measures the share of database shading visible in the JPEG +after registration, using each pixel’s source position under the selected framing and warp. Pooled fits apply +the profile’s vignette to an accepted warp. A missing or rejected warp preserves both the unshaded colour +pairs and the tone samples from the original framing. +The loaded database semantic identity also invalidates camera render/view keys, Smart-preview +headers and scan markers. Fresh original decodes retain the photo’s hot-pixel setting; offline +proxies remain readable and cannot be relabelled as freshly fitted pixels. +Embedded vignetting is still applied at the source before geometry. No camera allowlist, +new profile matching rules, or weaker acceptance gate is introduced. Other RAW formats continue to use the existing correspondence and fixed-mount lookup rules. + +Profile resolution uses the shared lens resolver, including the downloaded database or +`LIGHTCRAFT_LENSFUN_DIR` override and its reload support. Unknown crop factors remain +unknown under the upstream optional-crop API; this change adds no crop-factor fallback. + +Synthetic tests cover lens-only and lens-plus-framing acceptance, unrelated/flat/already aligned +rejection, crop-relative profile orientation at multiple resolutions, clip-mask contributions, +and the complete CR3 correspondence route for EXIF orientations 1–8 with non-unity white balance. +The opt-in `corpus_cr3_profile_geometry_diagnostics` test exports `geometry.tsv` and plain, +selected, and JPEG proxy PNGs when `LIGHTCRAFT_CR3_DIAGNOSTICS` names an output directory. +The plain diagnostic route removes only the proposed profile warp. Both routes use the same lens vignetting data. +It reads CR3 files from `$LIGHTCRAFT_CORPUS/raw` and the normal configured lens database. +The TSV appends `status` and `reason` columns. `measured` means both proxy calls returned +images; acceptance or rejection is recorded separately in the existing measurement columns. +If either call returns no proxy, the row records `missing_plain_proxy`, +`missing_chosen_proxy`, or `missing_both_proxies`, leaves all measurement fields empty, +and exports no PNGs for that file. The diagnostic continues with the next CR3. The reason +does not attribute a cause: the proxy API returns only `None`, which can cover unavailable +previews or sensor proxies. An unavailable row is not a passed geometry or colour check. +The PNGs show linear proxy RGB converted to sRGB, without a camera tone curve; they are geometry +inspection aids, not developed image fidelity comparisons. The public-sample assessment below covers both a selected warp and a retained fallback. +Its results apply to those samples and camera settings. + +## Historical public-sample assessment + +The pre-synchronization assessment used 22 SHA-256-verified, individually CC0-listed raw.pixls.us CR3 files using lensfun +XML data at `43f9e001`. In that assessment, the R100 RAW/C-RAW pair with RF-S18–45 at 18 mm accepts the +new geometry. The other 20 files retain pixel-identical 1600-pixel renders with optics +on/off, including eight R6 Mark II full-frame/crop, RAW/C-RAW and Dual-Pixel variants +of one scene. All 22 retain identical renders without a lens database. + +With the same independent baseline-derived radial registration applied to both +outputs, mean DE76 at 768×512 versus the embedded JPEG improves 4.54 to 3.79 (R100 RAW) +and 4.15 to 3.79 (C-RAW) with optics on. Unregistered whole-frame error slightly worsens +because optical framing still differs. This is a modest calibration benefit and does +not remove the photograph's visible lens distortion. The camera JPEG is not a +colorimetric reference. Four 24 MP files (R100 RAW/C-RAW and R6 II full-frame RAW/C-RAW) +render on CPU/Metal within 1/255 per channel, with optics on/off. + +The sample set does not establish all-camera correctness. R6 II’s eight variants +share one scene, not eight independent scenes. Pooled-profile and DNG-tag forwarding +are tested synthetically; this is not a real multi-camera calibration or DNG roundtrip. diff --git a/docs/gaps.md b/docs/gaps.md index 339caaeee5..f5c30225af 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -200,6 +200,6 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-25 | minor | Gap 1: first chart-calibrated model, the Canon EOS D60 (ColorChecker Classic under tungsten and sun, `crates/raw/src/chart_table.rs`); the gap stays open, hours unchanged | | 2026-11-05 | minor | Gap 9: a Windows leg runs clippy and the tests of the crates with Windows-only code when a pull request or push changes that code, or a pull request is labelled `full-ci`; gap not closed (macOS, GPU tests) | -## Proposed external-profile correspondence geometry +## External-profile correspondence geometry -Camera colour calibration remains open. PR #2675 proposes geometry-gated external-profile alignment for file-local RAW colour fitting and pooled calibration, plus unique exact-mount lookup for unnamed fixed lenses. It preserves in-file geometry and the established CR3 framing path, applies source-position vignetting before geometry, and uses held-out edge agreement rather than RGB error to accept a candidate. Historical private-file observations and their limits are recorded in [Camera preview colour](camera-preview-colour.md); they are not a claim of validation of this rebased source. +Camera colour calibration remains open. LightCraft checks resolved lens geometry against held-out JPEG edges for file-local and pooled fits. It can resolve an unnamed fixed lens through a unique exact mount (#2675). For CR3 the profile must also match or improve on the accepted framing. The public Canon results and their limits are recorded in [CR3 profile alignment](cr3-profile-alignment.md). The historical fixed-lens results are in [Camera preview colour](camera-preview-colour.md). diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 772db1671f..7bf7649559 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -243,7 +243,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-PROF-ADOBE | Standard raw looks (own equivalents) | P0 | ✅ | `crates/engine/src/presets.rs` (`PROFILES`), `crates/pipeline/src/profiles.rs` | six own looks: Color, Neutral, Vivid, Landscape, Portrait, Monochrome | | LR-PROF-ADAPTIVE | Adaptive profiles | P2 | ⬜ | | | | LR-PROF-CAMERA | Camera-matching looks | P2 | ⬜ | | | -| LR-PROF-CAMERACOLOR | Camera colour calibration (own) | P0 | 🟡 | `crates/raw/src/color.rs`, `crates/raw/src/profile.rs`, `crates/raw/src/gaintable.rs`, `crates/engine/src/camera_preview.rs` | DNG files use the colour matrices and the camera-profile look they carry (`ProfileHueSatMap`, `ProfileLookTable`, `ProfileToneCurve`, read from the file at run time per DNG spec ch. 6 — Lightroom-converted DNGs rendered flat and muted without them, issue #138). A DNG whose profile defines no tone curve (absent or identity `ProfileToneCurve`, with or without a `LookTable`, as Adobe Standard in Lightroom-written DNGs) gets its tone fitted to its embedded preview when that is at least 10% of the raw's long edge and 384 px (Lightroom's 1024 px previews qualify): two Lightroom Classic 15.1 lossy ILCE-7CM2 DNGs went from about 0.8 EV darker and flat to within 3% of Lightroom's mean linear RGB. A DNG's `ProfileGainTableMap` / `ProfileGainTableMap2` (Apple ProRAW's local tone map; both versions, DNG 1.7 precedence, the file's byte order with a big-endian fallback) is read and written back by DNG export and not rendered by default, as Lightroom Classic renders ProRAW without it (measured on one CC0 iPhone 12 Pro ProRAW); the Profile option "Camera local tone mapping" (`profile.camera_local_tone`, per photo, off by default, `crates/pipeline/src/local_tone.rs`) renders it as the camera does, per output pixel in the scene-linear stage (CPU, also under the GPU path); Sony ARW, Nikon NEF, Panasonic RW2, Fujifilm RAF, Canon CR3 and CR2, Pentax PEF, Samsung SRW and Olympus ORF get a guarded file-local fit to their own embedded JPEG — chromaticity matrix + hue/saturation/value table + tone and chroma curves, relative WB — or, with a bundled or local per-model profile pooled from many photos (`lightcraft-cli calibrate`, ARW, NEF and RAF so far, `crates/engine/src/camera_profiles.rs`), the profile's colour and only their own tone/chroma curves (on 29 held-out ILCE-7M4 photos mean ΔE vs the camera JPEG 3.54 → 3.10; bundled ILCE-7CR from 125 photos: 26 held-out 4.07 → 3.29, and every one of the 131 photos accepted, 8 of which fell back to neutral without it; bundled ILCA-99M2 from 144 photos: 30 held-out 5.11 → 4.87, 25 of them closer); the tone fit also uses dark JPEG samples excluded from colour training, so deep shadows follow the camera toe (#1307); near-black frames with too few colour pairs can take a guarded tone-only fallback on their existing source colour (#1587); Sony ARWs shot with DRO on (maker note `0xb025`, on by default) keep that colour but their tone curve is lowered to Sony's curve without DRO, whose lifted shadows are in the camera JPEG only (issue #244: 8 ILCE-7CR photos +6.4 → +0.8 L* from Lightroom's default, median ΔE 7.5 → 3.3); 52 models without a profile whose JPEG fit fails (or that have no usable JPEG) start from DNG-style matrices fitted to their measured spectral sensitivities instead of the neutral fallback (`crates/raw/src/spectral.rs`, rawtoaces-data v1.1.0, Apache-2.0, aliases included; not yet measured against the camera JPEG); the Canon EOS D60 (CRW) has DNG-style matrices of our own, fitted to ColorChecker Classic shots under a tungsten bulb and direct sun (`crates/raw/src/chart_table.rs`, `clean-room/crw/10-chart-calibration.md`; CIEDE2000 on the chart mean 2.4 / 1.7, 2.7 / 2.0 leaving each patch out), which give its white balance a Kelvin scale (the camera's own presets read Tungsten 3,264 K, Daylight 5,603 K, Cloudy 6,612 K) while its look stays the JPEG fit; ARW: on 10 public raw.pixls.us samples from 8 bodies 7 fits were accepted, mean ΔE vs the camera JPEG 17–26 → 3–10; NEF: 13 of 13 decodable samples (D750, D780, D850, D7500, Z 50 and local D7500 shots) accepted, ΔE 13–46 → 3–8 (issue #150); RW2 / RWL: 140 of 174 public samples accepted, from 93 of the 114 bodies with a preview, median ΔE 5.0 with matching lightness (13 of the 14 corpus files with a preview: ΔE 9.6–27 → 2.8–8.9; most rejections are compacts and kit zooms whose camera JPEG is distortion-corrected); a fit that fails the gates on all pixels is retried away from edges, where a lens-corrected camera JPEG still lines up (issue #232: the six distortion-corrected public ILCE-7RM2 samples ΔE 16.6–16.9 → 3.7–3.8, the corpus GX80 19.1 → 7.9); RAF: bundled X-H2S/X-T4 profiles from 201/545 photos; on 150 withheld files mean ΔE improves slightly over per-file fitting (X-H2S 1.70 → 1.62, X-T4 2.43 → 2.34); 23 of 24 references from 13 bodies accepted, including the dark X-H2S samples (8.74 → 2.25); ORF: the 3 decodable corpus files (E-1, E-400, XZ-2) accepted (`docs/camera-preview-colour.md`); a raw whose camera JPEG is black and white (a monochrome picture style) takes only the JPEG's tone curve, on the camera profile's, spectral or neutral colour (issue #577); this is not measured camera calibration; other raws and rejected fits use a neutral fallback (camera RGB ≈ linear sRGB, `matrix_is_fallback`) with as-shot white balance, so colours are muted and not accurate. Needs our own per-camera calibration: matrices the files carry themselves (e.g. Olympus `ColorMatrix`), fitting each camera to its own embedded JPEG, then chart shots. Adobe matrices / DCPs are never shipped or used (a user can import their own `.dcp`, LR-PROF-IMPORT). Biggest image-quality gap today; ILCE-7RM6: per-file fit now runs on previews above 64 MP, a pooled profile (46 photos) was tried and not bundled (withheld ΔE 5.71 → 6.40, 11 of 15 regressed), kept with smart previews (see docs/camera-preview-colour.md); the fit pairs the sensor moved into the file's lens-warp geometry when that lines up better with a lens-corrected camera JPEG (29 CC0 raws: alignment +0.13, mean ΔE 3.73 → 3.61); bundled NIKON Z 6_2 profile (296 photos; 59 held-back photos mean ΔE 2.73 → 2.54) NIKON Z 8 profile (261 photos; 55 held back 2.55 → 2.33) and NIKON D5300 profile (264 photos; 53 held back 2.86 → 2.66); PR #2675 proposes geometry-gated external-profile alignment for eligible non-CR3 file-local RAW colour fits and pooled calibration, plus unique exact-mount lookup for unnamed fixed lenses; in-file geometry and the established CR3 framing path are preserved | +| LR-PROF-CAMERACOLOR | Camera colour calibration (own) | P0 | 🟡 | `crates/raw/src/color.rs`, `crates/raw/src/profile.rs`, `crates/raw/src/gaintable.rs`, `crates/engine/src/camera_preview.rs` | DNG files use the colour matrices and the camera-profile look they carry (`ProfileHueSatMap`, `ProfileLookTable`, `ProfileToneCurve`, read from the file at run time per DNG spec ch. 6 — Lightroom-converted DNGs rendered flat and muted without them, issue #138). A DNG whose profile defines no tone curve (absent or identity `ProfileToneCurve`, with or without a `LookTable`, as Adobe Standard in Lightroom-written DNGs) gets its tone fitted to its embedded preview when that is at least 10% of the raw's long edge and 384 px (Lightroom's 1024 px previews qualify): two Lightroom Classic 15.1 lossy ILCE-7CM2 DNGs went from about 0.8 EV darker and flat to within 3% of Lightroom's mean linear RGB. A DNG's `ProfileGainTableMap` / `ProfileGainTableMap2` (Apple ProRAW's local tone map; both versions, DNG 1.7 precedence, the file's byte order with a big-endian fallback) is read and written back by DNG export and not rendered by default, as Lightroom Classic renders ProRAW without it (measured on one CC0 iPhone 12 Pro ProRAW); the Profile option "Camera local tone mapping" (`profile.camera_local_tone`, per photo, off by default, `crates/pipeline/src/local_tone.rs`) renders it as the camera does, per output pixel in the scene-linear stage (CPU, also under the GPU path); Sony ARW, Nikon NEF, Panasonic RW2, Fujifilm RAF, Canon CR3 and CR2, Pentax PEF, Samsung SRW and Olympus ORF get a guarded file-local fit to their own embedded JPEG — chromaticity matrix + hue/saturation/value table + tone and chroma curves, relative WB — or, with a bundled or local per-model profile pooled from many photos (`lightcraft-cli calibrate`, ARW, NEF and RAF so far, `crates/engine/src/camera_profiles.rs`), the profile's colour and only their own tone/chroma curves (on 29 held-out ILCE-7M4 photos mean ΔE vs the camera JPEG 3.54 → 3.10; bundled ILCE-7CR from 125 photos: 26 held-out 4.07 → 3.29, and every one of the 131 photos accepted, 8 of which fell back to neutral without it; bundled ILCA-99M2 from 144 photos: 30 held-out 5.11 → 4.87, 25 of them closer); the tone fit also uses dark JPEG samples excluded from colour training, so deep shadows follow the camera toe (#1307); near-black frames with too few colour pairs can take a guarded tone-only fallback on their existing source colour (#1587); Sony ARWs shot with DRO on (maker note `0xb025`, on by default) keep that colour but their tone curve is lowered to Sony's curve without DRO, whose lifted shadows are in the camera JPEG only (issue #244: 8 ILCE-7CR photos +6.4 → +0.8 L* from Lightroom's default, median ΔE 7.5 → 3.3); 52 models without a profile whose JPEG fit fails (or that have no usable JPEG) start from DNG-style matrices fitted to their measured spectral sensitivities instead of the neutral fallback (`crates/raw/src/spectral.rs`, rawtoaces-data v1.1.0, Apache-2.0, aliases included; not yet measured against the camera JPEG); the Canon EOS D60 (CRW) has DNG-style matrices of our own, fitted to ColorChecker Classic shots under a tungsten bulb and direct sun (`crates/raw/src/chart_table.rs`, `clean-room/crw/10-chart-calibration.md`; CIEDE2000 on the chart mean 2.4 / 1.7, 2.7 / 2.0 leaving each patch out), which give its white balance a Kelvin scale (the camera's own presets read Tungsten 3,264 K, Daylight 5,603 K, Cloudy 6,612 K) while its look stays the JPEG fit; ARW: on 10 public raw.pixls.us samples from 8 bodies 7 fits were accepted, mean ΔE vs the camera JPEG 17–26 → 3–10; NEF: 13 of 13 decodable samples (D750, D780, D850, D7500, Z 50 and local D7500 shots) accepted, ΔE 13–46 → 3–8 (issue #150); RW2 / RWL: 140 of 174 public samples accepted, from 93 of the 114 bodies with a preview, median ΔE 5.0 with matching lightness (13 of the 14 corpus files with a preview: ΔE 9.6–27 → 2.8–8.9; most rejections are compacts and kit zooms whose camera JPEG is distortion-corrected); a fit that fails the gates on all pixels is retried away from edges, where a lens-corrected camera JPEG still lines up (issue #232: the six distortion-corrected public ILCE-7RM2 samples ΔE 16.6–16.9 → 3.7–3.8, the corpus GX80 19.1 → 7.9); RAF: bundled X-H2S/X-T4 profiles from 201/545 photos; on 150 withheld files mean ΔE improves slightly over per-file fitting (X-H2S 1.70 → 1.62, X-T4 2.43 → 2.34); 23 of 24 references from 13 bodies accepted, including the dark X-H2S samples (8.74 → 2.25); ORF: the 3 decodable corpus files (E-1, E-400, XZ-2) accepted (`docs/camera-preview-colour.md`); a raw whose camera JPEG is black and white (a monochrome picture style) takes only the JPEG's tone curve, on the camera profile's, spectral or neutral colour (issue #577); this is not measured camera calibration; other raws and rejected fits use a neutral fallback (camera RGB ≈ linear sRGB, `matrix_is_fallback`) with as-shot white balance, so colours are muted and not accurate. Needs our own per-camera calibration: matrices the files carry themselves (e.g. Olympus `ColorMatrix`), fitting each camera to its own embedded JPEG, then chart shots. Adobe matrices / DCPs are never shipped or used (a user can import their own `.dcp`, LR-PROF-IMPORT). Biggest image-quality gap today; ILCE-7RM6: per-file fit now runs on previews above 64 MP, a pooled profile (46 photos) was tried and not bundled (withheld ΔE 5.71 → 6.40, 11 of 15 regressed), kept with smart previews (see docs/camera-preview-colour.md); the fit pairs the sensor moved into the file's lens-warp geometry when that lines up better with a lens-corrected camera JPEG (29 CC0 raws: alignment +0.13, mean ΔE 3.73 → 3.61); bundled NIKON Z 6_2 profile (296 photos; 59 held-back photos mean ΔE 2.73 → 2.54) NIKON Z 8 profile (261 photos; 55 held back 2.55 → 2.33) and NIKON D5300 profile (264 photos; 53 held back 2.86 → 2.66); eligible file-local and pooled fits can use resolved lens geometry verified against the camera JPEG, including unique exact-mount lookup for unnamed fixed lenses (#2675). For CR3 the candidate must also match or beat the established framing on training and held-out edges ([CR3 profile alignment](cr3-profile-alignment.md)) | | LR-PROF-CREATIVE | Creative profiles (own) | P2 | ✅ | `cmd:develop.profile`, `crates/pipeline/src/profiles.rs` | 16 own looks in Film / Cinematic / Muted / B&W (tone + point-curve fades, colour grading, mixer / B&W mix); scale with `ctl:profile.amount`; sliders untouched | | LR-PROF-LEGACY | Legacy profiles | P2 | ⬜ | | | | LR-PROF-NONRAW | Profiles for non-raw files | P0 | ✅ | `cmd:develop.profile` | same looks apply to JPEG/TIFF | @@ -1112,6 +1112,6 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-27 | patch | MENU-HELP-FEEDBACK: on macOS the Help menu no longer shows the system's `Send Feedback` row beside Send Feedback… | | 2026-10-17 | minor | LR-LIB-SMARTALBUM, LR-LIB-PEOPLE, LR-VIEW-FOCUSPOINT, LR-VIEW-BEFOREAFTER, LR-VIEW-SLIDESHOW, LR-BEHAV-SIDEBAR-HIDE, MENU-VIEW-PHOTOCOUNT, MENU-VIEW-SIDEBARSECTIONS, KEY-MASKCOLOR, LRC-LIB-METADATA, LRC-MAP-TRACKLOG, LRC-SS-PLAYBACK, LRC-SS-EXPORT, LRC-DEV-VIEWOPTIONS: menu bar reorganised; the rows now cite the new paths (View ▸ Loupe Overlay, Before/After, Mask Overlay, Slideshow, Sort; Window for panel toggles; Photo ▸ Metadata); no command changed and no status changed | -## Proposed external-profile correspondence geometry +## External-profile correspondence geometry -LR-PROF-CAMERACOLOR remains partial; summary counts and status are unchanged. PR #2675 proposes geometry-gated external-profile alignment for file-local RAW colour fitting and pooled calibration, plus unique exact-mount lookup for unnamed fixed lenses. It preserves in-file geometry and the established CR3 framing path, applies source-position vignetting before geometry, and uses held-out edge agreement rather than RGB error to accept a candidate. Historical private-file observations and their limits are recorded in [Camera preview colour](camera-preview-colour.md); they are not a claim of validation of this rebased source. +LR-PROF-CAMERACOLOR remains partial; summary counts and status are unchanged. LightCraft checks resolved lens geometry against held-out JPEG edges for file-local and pooled fits. It can resolve an unnamed fixed lens through a unique exact mount (#2675). For CR3 the profile must also match or improve on the accepted framing. The public Canon results and their limits are recorded in [CR3 profile alignment](cr3-profile-alignment.md). The historical fixed-lens results are in [Camera preview colour](camera-preview-colour.md). From 3295921b8632bdc499e233858a09dc3c2260868e Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:36:03 +0100 Subject: [PATCH 37/63] Refresh Smart Previews and cached renders after the CR3 look changes --- crates/engine/src/camera_preview.rs | 3 ++- crates/engine/src/media/source.rs | 3 ++- crates/engine/src/smart/tests.rs | 19 ++++++++++++++++--- docs/camera-preview-colour.md | 2 ++ 4 files changed, 22 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index ca383ba81c..9d1d3df823 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -95,7 +95,8 @@ use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights}; /// (`camera_vignetting_amount`, ranked within chromaticity classes), not whole: JPEGs that show less of it fitted looks too /// dark, with skewed colour. The same for a DNG's tone fit; a CR3 proxy gets the gain where its framed pixels come from. /// 27: geometry-gated external lens and camera framing for JPEG calibration correspondences. -pub const LOOK_VERSION: u32 = 27; +/// 28: resolved lens geometry can align CR3 camera-JPEG colour and tone samples against the existing framing fallback. +pub const LOOK_VERSION: u32 = 28; #[derive(Clone, Debug)] pub(crate) struct CameraLook { diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index ca03d12718..dca6ceb670 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -1,13 +1,14 @@ use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo}; /// Bump when the pipeline's output changes, to invalidate cached thumbnails. +/// 89: use accepted lens geometry when fitting a CR3 camera look against the embedded JPEG (#3138). /// 88: use eligible external lens profiles for camera-preview colour alignment (#2675). /// 87: a lens database's vignetting correction reaches the look fit only in the share the camera JPEG shows /// (#3943, which had reserved 83: taken after 86, so a later bump counting up from here can't meet an older cache). /// 86: pushed shadows keep the camera profile's colour and tone (#2092). /// 85: raw decoding keeps negative channels (#2278). /// 84: full-size raw demosaic runs on the white-balanced mosaic with a clip mask (#1328). -pub const RENDER_CACHE_VERSION: u64 = 88; +pub const RENDER_CACHE_VERSION: u64 = 89; /// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache). pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512]; diff --git a/crates/engine/src/smart/tests.rs b/crates/engine/src/smart/tests.rs index 3dffba8032..e1b5320ba5 100644 --- a/crates/engine/src/smart/tests.rs +++ b/crates/engine/src/smart/tests.rs @@ -344,9 +344,9 @@ fn a_proxy_from_the_previous_look_version_is_stale() { let path = dir.join("p.lcsp"); std::fs::write(&path, &bytes).unwrap(); assert!(!is_stale(&path), "this build's own proxy is up to date"); - // Both the pre-Nikon look and the previous integration's look remain readable offline - // and are rebuilt when the original is available. Keep the lens provenance current. - for version in [13, 14] { + // Look 27 already recorded the lens identity, but did not align CR3 fits with lens geometry. + // Like the earlier proxies, it remains readable offline and is rebuilt from the online original. + for version in [13, 14, 27] { let mut older = head.clone(); older[LOOK_FIELD] = serde_json::json!(version); let mut old = MAGIC.to_vec(); @@ -463,6 +463,19 @@ fn explicit_lens_identity_is_kept_by_encoder_and_scan_marker() { std::fs::remove_dir_all(dir).unwrap(); } +#[test] +fn folder_marker_replaces_lens_fingerprints_in_either_direction_and_preserves_newer_provenance() { + let dir = temp("lens-marker-upgrade"); + let fit = u64::from(crate::camera_preview::LOOK_VERSION); + let enc = ENCODE_VERSION; + for (look, encoding, old_key, expected_key) in [(fit, enc, 2, 5), (fit, enc, 99, 5), (fit, enc + 1, 99, 99)] { + std::fs::write(dir.join(LOOK_MARKER), format!("{look} {encoding} {old_key} 71")).unwrap(); + mark_look_checked_with_lens_key(&dir, 5).unwrap(); + assert_eq!(marker(&dir, LOOK_MARKER), [look, encoding, expected_key, 71]); + } + std::fs::remove_dir_all(dir).unwrap(); +} + #[test] fn a_scan_cannot_clear_pending_behind_a_newer_marker_for_another_database() { let dir = temp("lens-marker-pending"); diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index 60a39d2b67..bdf0e91b0d 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -289,6 +289,8 @@ is recorded here yet. Whether they should come before the file-local fit for the A smart preview keeps the result of the fit twice: the colour matrix is baked into its pixels and the tone and chroma curves are stored in its header. When the fit changes, a preview built earlier keeps the old look until it is rebuilt, and the render cache version does not reach it (renders are keyed on the library's files, proxies are files of their own). +Version 27 introduced resolved-profile geometry for non-CR3 files. Version 28 extends it to eligible CR3s for file-local fits, pooled calibration and merge/DNG colour tags. Render cache version 89 invalidates thumbnails fitted with the earlier geometry. Existing Smart Previews keep the lens database identity recorded when their originals were decoded. + The fit therefore has a version, `LOOK_VERSION` in `crates/engine/src/camera_preview.rs`, and every smart preview records the version that wrote it in its header line (`look_version`). **Bump the constant in any change that makes the fit give a different result for the same file**: the matrix, hue/saturation, tone or chroma fit, their gates and fallbacks, or how a camera profile feeds them. Changes that leave the fitted look alone don't need it. A header without the field (everything built before it existed) counts as version 0, and so does a value that is not a non-negative integer; a value from a newer build is left alone. A proxy older than the constant is brought up to date by the existing Build Smart Previews path (`smart_run`), which also repairs damaged proxies: From 055fba8e0f7f56ed02663dccd16a9c1df18cc928 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:56:18 +0100 Subject: [PATCH 38/63] Clarify CR3 shading and surface corpus fixture read errors --- crates/engine/src/camera_preview/tests.rs | 20 ++++++++++++-------- docs/lens-profiles.md | 5 +++-- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index cc09d42c86..3ae9ae19e1 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -1925,16 +1925,16 @@ fn corpus_cr3_profile_geometry_diagnostics() { let mut report = String::from( "file\tmodel\torientation\tprofile_warp\tgeometry_accepted\tplain_alignment\tchosen_alignment\tplain_structure\tchosen_structure\tplain_pairs\tchosen_pairs\tplain_look\tchosen_look\tframed_gate_scores\toriginal_gate_scores\tstatus\treason\n", ); - let mut paths: Vec<_> = std::fs::read_dir(corpus.join("raw")) - .unwrap() - .flatten() - .map(|e| e.path()) + let raw_dir = corpus.join("raw"); + let mut paths: Vec<_> = std::fs::read_dir(&raw_dir) + .unwrap_or_else(|e| panic!("{}: {e}", raw_dir.display())) + .map(|entry| entry.unwrap_or_else(|e| panic!("{}: {e}", raw_dir.display())).path()) .filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("cr3"))) .collect(); paths.sort(); assert!(!paths.is_empty(), "diagnostic corpus must contain CR3 files"); for path in paths { - let bytes = std::fs::read(&path).unwrap(); + let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); let mut raw = lightcraft_raw::decode(&bytes).unwrap(); let correction = crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(&bytes)); let lens = lens_geometry(&raw.opcodes.list3); @@ -2055,9 +2055,13 @@ fn corpus_cr3_gets_a_framing_aligned_camera_look() { .map(std::path::PathBuf::from) .unwrap_or_else(|| std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus")) .join("raw/cr3-canon-r100-raw.cr3"); - let Ok(bytes) = std::fs::read(&path) else { - lightcraft_testkit::skip!(Corpus, "{} absent", path.display()); - return; + let bytes = match std::fs::read(&path) { + Ok(bytes) => bytes, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + lightcraft_testkit::skip!(Corpus, "{} absent", path.display()); + return; + } + Err(e) => panic!("{}: {e}", path.display()), }; let raw = match lightcraft_raw::decode(&bytes) { Ok(raw) => raw, diff --git a/docs/lens-profiles.md b/docs/lens-profiles.md index cab2a86870..c316178793 100644 --- a/docs/lens-profiles.md +++ b/docs/lens-profiles.md @@ -94,8 +94,9 @@ A raw whose look is fitted to its own camera JPEG (Sony, Nikon, Pentax, Olympus matrix, and a DNG whose tone is fitted to its preview, [camera-preview-colour.md](camera-preview-colour.md)) has that fit made on the sensor with only the share of a profile's vignetting correction its camera JPEG shows, measured per photo: the profile describes the lens, not what the camera did to its JPEG relative to the raw (a Sony JPEG with shading compensation Auto can show -none of it). When the share can't be measured (too few usable pixels, or a lens-warped sensor proxy) the fit keeps -the whole correction. The render still applies the profile at the Vignetting amount. +none of it). With an accepted CR3 lens warp, the fit follows the JPEG framing and warp back to the sensor +position for each gain. It keeps the whole correction when the share cannot be measured, for example when too few +usable pixels remain or the warp's source positions are unavailable. The render still applies the profile at the Vignetting amount. Normalisation follows lensfun's documentation: distortion and TCA radii are 1 at half the shorter side of the calibration frame (its `cropfactor` and `aspect-ratio`), vignetting radii 1 at its corner; the optical centre is From 5c1987548a115ff59f13cebddc97a32656f90f6b Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:18:13 +0100 Subject: [PATCH 39/63] LR-EDIT-DETAIL-DENOISE: Choose and remember the denoiser per photo --- crates/catalog/src/journal.rs | 57 ++++- crates/catalog/src/lib.rs | 27 ++- crates/catalog/src/model.rs | 4 +- crates/catalog/src/tests_format_version.rs | 127 ++++++++++- crates/develop/src/lib.rs | 55 ++++- crates/develop/src/presets.rs | 2 + crates/develop/src/settings.rs | 13 +- crates/engine/src/cmd/denoise.rs | 96 +++++++-- crates/engine/src/denoise.rs | 7 +- crates/engine/src/denoise/model.rs | 31 ++- crates/engine/src/denoise/products.rs | 20 +- crates/engine/src/denoise/session.rs | 233 ++++++++++++++++----- crates/engine/src/denoise/settings.rs | 72 ++++++- crates/engine/src/denoise/state.rs | 9 + crates/engine/src/import/commit.rs | 19 ++ crates/engine/src/lib.rs | 32 ++- crates/engine/src/library.rs | 4 +- crates/engine/src/lightroom_catalog.rs | 2 + crates/engine/src/media/session.rs | 62 ++++-- crates/engine/src/media/source.rs | 6 +- crates/engine/src/tests/denoise.rs | 209 +++++++++++++++++- crates/engine/src/tests/import.rs | 36 ++++ crates/ui-egui/src/panels/denoise.rs | 122 +++++++++-- crates/ui-egui/src/panels/edit.rs | 5 +- crates/ui-egui/tests/it/accessibility.rs | 89 ++++++++ docs/denoise.md | 17 +- 26 files changed, 1192 insertions(+), 164 deletions(-) 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..164f67b650 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,31 @@ 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| { + let e = &settings.enhance; + // An off switch can still hold an amount the user may turn back on. + e.denoise_model.is_none() && (e.denoise > 0.0 || e.denoise_enabled()) + }; + 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..83f56a4cc1 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)) 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..c8fc52e0a9 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,13 +131,14 @@ 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 } @@ -202,6 +213,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 +569,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..9f37f0c6b4 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, } 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/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..8eb5b452a9 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,6 +447,9 @@ 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); } } @@ -378,7 +478,7 @@ impl Session { } } self.denoise.failed.clear(); - self.denoise.touch(); + self.denoise_reindex(); (files, bytes) } @@ -473,6 +573,12 @@ impl Session { } } + pub(crate) fn denoise_note_product(&mut self, key: &str) { + if !self.denoise.products.contains(key) { + self.denoise.products.insert(key.to_owned()); + } + } + pub(crate) fn denoise_made(&self) -> u64 { self.denoise.made } @@ -491,20 +597,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..795e9e4016 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,53 @@ 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}; + 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(4097).read_to_end(&mut bytes).map_err(|e| format!("could not read {}: {e}", path.display()))?; + if bytes.len() > 4096 { + return Err(format!("{} exceeds the denoise settings size limit", 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)?; + 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 +140,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..ce6bd49adc 100644 --- a/crates/engine/src/denoise/state.rs +++ b/crates/engine/src/denoise/state.rs @@ -103,7 +103,12 @@ 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, pub(super) active_seen: Option, /// `settings.json` as last read (with the model choice). pub(crate) settings: Settings, @@ -129,7 +134,10 @@ impl Default for State { downloads: Downloads::default(), install: None, loader: default_loader(), + warm_model: Default::default(), active: None, + registry: Default::default(), + products: Default::default(), active_seen: None, settings: Settings::default(), dirty: true, @@ -160,6 +168,7 @@ impl State { 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 863f39cfd8..1694b35a21 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -197,12 +197,30 @@ 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() { + let enhance = &settings.enhance; + if enhance.denoise_model.is_none() && (enhance.denoise > 0.0 || enhance.denoise_enabled()) { + 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 let mut placed: Vec = Vec::new(); @@ -335,6 +353,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/lib.rs b/crates/engine/src/lib.rs index 6042b51c8e..d6275cbee7 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,21 @@ 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.denoise_model.is_none() + && settings.enhance.denoise > 0.0 + && 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/session.rs b/crates/engine/src/media/session.rs index 7201039b49..6451b3e885 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 @@ -128,12 +144,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) @@ -142,6 +156,7 @@ 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 ^ crate::files::hot_pixel_key(settings) ^ ((max_w as u64) << 40) ^ ((max_h as u64) << 20) @@ -200,13 +215,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(), @@ -216,7 +236,7 @@ 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), cache: Some((self.media.rendered.clone(), ck)), @@ -538,6 +558,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 ca03d12718..f8c639ffab 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -135,6 +135,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)>>, @@ -142,7 +144,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. @@ -342,7 +344,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/tests/denoise.rs b/crates/engine/src/tests/denoise.rs index 0639030408..d01378c1cc 100644 --- a/crates/engine/src/tests/denoise.rs +++ b/crates/engine/src/tests/denoise.rs @@ -223,6 +223,56 @@ 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"); + for bytes in [b"{broken".to_vec(), b"{\"model\":7}".to_vec(), vec![b' '; 4097]] { + std::fs::write(&path, &bytes).unwrap(); + assert!(crate::denoise::capture_legacy_pin(Some(&dir)).is_err()); + assert_eq!(std::fs::read(&path).unwrap(), bytes); + } + 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_model_is_installed_chosen_and_removed_with_the_terms_accepted() { let mut x = setup("model", false); @@ -384,17 +434,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 +477,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 +584,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 +655,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 +981,140 @@ fn without_a_models_folder_the_cache_still_obeys_the_default_limit() { } 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/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/tests/it/accessibility.rs b/crates/ui-egui/tests/it/accessibility.rs index df24b17832..283848c4d2 100644 --- a/crates/ui-egui/tests/it/accessibility.rs +++ b/crates/ui-egui/tests/it/accessibility.rs @@ -190,6 +190,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/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`. From c3c19e14162596bba2a27ee60641742b7fc1d2c2 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:55:58 +0100 Subject: [PATCH 40/63] LR-EDIT-DETAIL-DENOISE: Preserve model choices and refresh evicted previews --- crates/catalog/src/lib.rs | 6 +- crates/catalog/src/model.rs | 33 +++++++- crates/develop/src/lib.rs | 8 ++ crates/develop/src/settings.rs | 5 ++ crates/engine/src/denoise/session.rs | 10 ++- crates/engine/src/denoise/state.rs | 10 +++ crates/engine/src/import/commit.rs | 3 +- crates/engine/src/import/defaults.rs | 2 +- crates/engine/src/lib.rs | 5 +- crates/engine/src/media/render.rs | 10 ++- crates/engine/src/media/session.rs | 4 +- .../engine/src/media/thumbnail_hash_tests.rs | 28 +++++++ crates/engine/src/tests/denoise.rs | 83 +++++++++++++++++++ 13 files changed, 191 insertions(+), 16 deletions(-) diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 164f67b650..f243cb02cb 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -753,11 +753,7 @@ impl Catalog { /// 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| { - let e = &settings.enhance; - // An off switch can still hold an amount the user may turn back on. - e.denoise_model.is_none() && (e.denoise > 0.0 || e.denoise_enabled()) - }; + 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()?; diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 83f56a4cc1..4b41a51012 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -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/develop/src/lib.rs b/crates/develop/src/lib.rs index c8fc52e0a9..4b51fc19d1 100644 --- a/crates/develop/src/lib.rs +++ b/crates/develop/src/lib.rs @@ -142,6 +142,14 @@ impl DevelopSettings { 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) } diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index 9f37f0c6b4..5bfb880f65 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -1513,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/denoise/session.rs b/crates/engine/src/denoise/session.rs index 8eb5b452a9..1704268456 100644 --- a/crates/engine/src/denoise/session.rs +++ b/crates/engine/src/denoise/session.rs @@ -456,6 +456,7 @@ impl Session { 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); @@ -478,6 +479,9 @@ impl Session { } } self.denoise.failed.clear(); + if files > 0 { + self.denoise.eviction_epoch += 1; + } self.denoise_reindex(); (files, bytes) } @@ -574,7 +578,11 @@ impl Session { } pub(crate) fn denoise_note_product(&mut self, key: &str) { - if !self.denoise.products.contains(key) { + // 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()); } } diff --git a/crates/engine/src/denoise/state.rs b/crates/engine/src/denoise/state.rs index ce6bd49adc..7b780e4a22 100644 --- a/crates/engine/src/denoise/state.rs +++ b/crates/engine/src/denoise/state.rs @@ -109,6 +109,9 @@ pub(crate) struct State { 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, @@ -138,6 +141,7 @@ impl Default for State { active: None, registry: Default::default(), products: Default::default(), + eviction_epoch: 0, active_seen: None, settings: Settings::default(), dirty: true, @@ -162,6 +166,12 @@ 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() { diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 1694b35a21..151c6a745d 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -205,8 +205,7 @@ impl Session { return; } for settings in photo.settings_holders_mut() { - let enhance = &settings.enhance; - if enhance.denoise_model.is_none() && (enhance.denoise > 0.0 || enhance.denoise_enabled()) { + 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()); } 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 d6275cbee7..a5e96752f0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1234,10 +1234,7 @@ impl Session { /// 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.denoise_model.is_none() - && settings.enhance.denoise > 0.0 - && self.catalog.photo(id).is_some_and(|photo| denoise::eligible(photo)) - { + 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()); } } diff --git a/crates/engine/src/media/render.rs b/crates/engine/src/media/render.rs index 7da1bef151..e190e38ed2 100644 --- a/crates/engine/src/media/render.rs +++ b/crates/engine/src/media/render.rs @@ -445,10 +445,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 6451b3e885..95a63c8281 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -90,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); @@ -157,6 +158,7 @@ impl crate::Session { 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) @@ -238,7 +240,7 @@ impl crate::Session { info: source_info(&p), 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, 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/tests/denoise.rs b/crates/engine/src/tests/denoise.rs index d01378c1cc..5f84fe76d7 100644 --- a/crates/engine/src/tests/denoise.rs +++ b/crates/engine/src/tests/denoise.rs @@ -273,6 +273,69 @@ fn before_and_hover_render_their_own_denoiser_without_replacing_the_live_source( 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); @@ -982,6 +1045,26 @@ 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); From 75852a37bdd8b037b868edab723f3bb6e0c6c034 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:43:31 +0100 Subject: [PATCH 41/63] Explain how to recover unreadable denoise settings --- crates/engine/src/denoise/settings.rs | 15 +++++++++++---- crates/engine/src/tests/denoise.rs | 12 +++++++++++- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/denoise/settings.rs b/crates/engine/src/denoise/settings.rs index 795e9e4016..5783ea9c33 100644 --- a/crates/engine/src/denoise/settings.rs +++ b/crates/engine/src/denoise/settings.rs @@ -69,15 +69,16 @@ pub(crate) fn read_capped(path: &Path, max: usize) -> Option> { 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(4097).read_to_end(&mut bytes).map_err(|e| format!("could not read {}: {e}", path.display()))?; - if bytes.len() > 4096 { - return Err(format!("{} exceeds the denoise settings size limit", path.display())); + 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())) } @@ -103,7 +104,13 @@ pub(super) fn configured_pin(dir: &Path, settings: &Settings) -> Result Result { - let mut settings = read_settings_checked(dir)?; + 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)?; diff --git a/crates/engine/src/tests/denoise.rs b/crates/engine/src/tests/denoise.rs index 5f84fe76d7..b164c7c77d 100644 --- a/crates/engine/src/tests/denoise.rs +++ b/crates/engine/src/tests/denoise.rs @@ -227,11 +227,21 @@ fn set_amount(s: &mut Session, amount: f64) { 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(); - assert!(crate::denoise::capture_legacy_pin(Some(&dir)).is_err()); + 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); } From fe4d602b70a4b89c6a71cd08e7784f3ecb395c8d Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Mon, 30 Nov 2026 00:26:44 +0100 Subject: [PATCH 42/63] LR-MERGE-PANO: keep the panorama result strings English-only here Rule 16: feature PRs add English only, and translations go to storytold/craft-i18n. This drops the four translated rows (three messages and one count format) the branch added to the 17 app-local catalogs. The English source strings and call sites stay; a language without a row shows the English text. --- crates/ui-egui/locales/cs-formats.json | 1 - crates/ui-egui/locales/cs.json | 3 --- crates/ui-egui/locales/de-formats.json | 1 - crates/ui-egui/locales/de.json | 3 --- crates/ui-egui/locales/es-formats.json | 1 - crates/ui-egui/locales/es.json | 3 --- crates/ui-egui/locales/fi-formats.json | 1 - crates/ui-egui/locales/fi.json | 3 --- crates/ui-egui/locales/fr-formats.json | 1 - crates/ui-egui/locales/fr.json | 3 --- crates/ui-egui/locales/id-formats.json | 1 - crates/ui-egui/locales/id.json | 3 --- crates/ui-egui/locales/it-formats.json | 1 - crates/ui-egui/locales/it.json | 3 --- crates/ui-egui/locales/ja-formats.json | 1 - crates/ui-egui/locales/ja.json | 3 --- crates/ui-egui/locales/ka-formats.json | 1 - crates/ui-egui/locales/ka.json | 3 --- crates/ui-egui/locales/pl-formats.json | 1 - crates/ui-egui/locales/pl.json | 3 --- crates/ui-egui/locales/pt-br-formats.json | 1 - crates/ui-egui/locales/pt-br.json | 3 --- crates/ui-egui/locales/ru-formats.json | 1 - crates/ui-egui/locales/ru.json | 3 --- crates/ui-egui/locales/sv-formats.json | 1 - crates/ui-egui/locales/sv.json | 3 --- crates/ui-egui/locales/uk-formats.json | 1 - crates/ui-egui/locales/uk.json | 3 --- crates/ui-egui/locales/vi-formats.json | 1 - crates/ui-egui/locales/vi.json | 3 --- crates/ui-egui/locales/zh-hans-formats.json | 1 - crates/ui-egui/locales/zh-hans.json | 3 --- crates/ui-egui/locales/zh-hant-formats.json | 1 - crates/ui-egui/locales/zh-hant.json | 3 --- 34 files changed, 68 deletions(-) diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 3ff57caa99..77c37c84fc 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "Zahrnuto {used} z {total} fotografií", " ({unsure} with several look-alike files: use Locate)": " ({unsure} s několika podobnými soubory: použijte Najít umístění)", " ({} in Recently Deleted)": " ({} v nedávno odstraněných)", " · {:.0}% clipped": " · {:.0}% oříznutých tónů", diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index edc03609f1..ea10219217 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "Výsledek sloučení fotografií", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft nedokázal tyto fotografie zarovnat s ostatními, proto je panorama vynechává.", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft nedokázal tyto fotografie zarovnat se zahrnutou sadou. Před sloučením zkontrolujte náhled.", " (library default)": " (výchozí nastavení knihovny)", " (inverted)": " (invertováno)", " · best of its burst": " · nejlepší ze série", diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 3bae86d34a..7e78396a1c 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "{used} von {total} Fotos enthalten", " ({unsure} with several look-alike files: use Locate)": " ({unsure} mit mehreren ähnlichen Dateien: „Fehlende Datei suchen“ verwenden)", " ({} in Recently Deleted)": " ({} in „Zuletzt gelöscht“)", " · {:.0}% clipped": " · {:.0}% beschnitten", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 2fa64dcd47..bc67606eb6 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "Ergebnis der Fotozusammenführung", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft konnte diese Fotos nicht an den enthaltenen Fotos ausrichten, daher lässt das Panorama sie aus.", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft konnte diese Fotos nicht an den enthaltenen Fotos ausrichten. Prüfen Sie die Vorschau vor dem Zusammenfügen.", " (library default)": " (Bibliotheksstandard)", " (inverted)": " (umgekehrt)", " · best of its burst": " · bestes Foto der Serie", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 4f6aa86b94..eb5edf4866 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "Se incluyen {used} de {total} fotos", " ({unsure} with several look-alike files: use Locate)": " ({unsure} con varios archivos parecidos: usar Localizar)", " ({} in Recently Deleted)": " ({} en Eliminadas recientemente)", " · {:.0}% clipped": " · {:.0}% recortado", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 5835f47a93..c34057bdfe 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "Resultado de la combinación de fotos", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft no pudo alinear estas fotos con las incluidas, así que la panorámica las omite.", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft no pudo alinear estas fotos con el conjunto incluido. Revise la vista previa antes de combinar.", " (library default)": " (predeterminado de la biblioteca)", " (inverted)": " (invertida)", " · best of its burst": " · la mejor de su ráfaga", diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index d7bdb70df0..31f6c32b5d 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "{used} / {total} kuvaa mukana", " ({unsure} with several look-alike files: use Locate)": " ({unsure} usealla samannäköisellä tiedostolla: käytä Paikanna)", " ({} in Recently Deleted)": " ({} Äskettäin poistetuissa)", " in {g} group{}": " · ryhmiä: {g}{:.0}", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index ab194c5baa..59cc611cd6 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "Kuvien yhdistämisen tulos", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft ei voinut kohdistaa näitä kuvia mukaan otettuihin kuviin, joten panoraama jättää ne pois.", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft ei voinut kohdistaa näitä kuvia mukaan otettuihin kuviin. Tarkista esikatselu ennen yhdistämistä.", " (library default)": " (kirjaston oletus)", " (inverted)": " (käänteinen)", " · best of its burst": " · sarjan paras", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index e6ee6e62bf..ba6bcc7b0f 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "{used} photos sur {total} incluses", " ({unsure} with several look-alike files: use Locate)": " ({unsure} avec plusieurs fichiers similaires : utilisez Localiser)", " ({} in Recently Deleted)": " ({} dans « Supprimés récemment »)", " · {:.0}% clipped": " · {:.0}% écrêté", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index fc014789b1..31e6814b6d 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "Résultat de la fusion de photos", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft n'a pas pu aligner ces photos sur celles incluses : le panorama les laisse de côté.", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft n'a pas pu aligner ces photos avec les photos incluses. Vérifiez l'aperçu avant de fusionner.", " (library default)": " (valeur par défaut de la bibliothèque)", " (inverted)": " (inversée)", " · best of its burst": " · la meilleure de sa rafale", diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index e7c49b0c9d..7bd027cc35 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "{used} dari {total} foto disertakan", " · {skipped} skipped (file exists)": " · {skipped} dilewati (file sudah ada)", " · {} duplicate{} skipped": " · {} duplikat dilewati{:.0}", " · {} failed: {}": " · {} gagal: {}", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 4a0227f881..52705328cc 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "Hasil Penggabungan Foto", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft tidak dapat menyelaraskan foto-foto ini dengan foto yang disertakan, sehingga panorama tidak memuatnya.", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft tidak dapat menyelaraskan foto-foto ini dengan foto yang disertakan. Periksa pratinjau sebelum menggabungkan.", " (library default)": " (bawaan pustaka)", " (inverted)": " (dibalik)", " · best of its burst": " · terbaik dari bidikan beruntunnya", diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 7b47a9eb84..922bac810d 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "Incluse {used} foto su {total}", " ({unsure} with several look-alike files: use Locate)": " ({unsure} con diversi file simili: usa Trova)", " ({} in Recently Deleted)": " ({} in Eliminate di recente)", " · {:.0}% clipped": " · {:.0}% tagliato", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 0221ffc6bb..5b0ccc0cee 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "Risultato dell'unione di foto", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft non ha potuto allineare queste foto con quelle incluse, quindi il panorama le esclude.", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft non ha potuto allineare queste foto con quelle incluse. Controlla l'anteprima prima di unire.", " (library default)": " (predefinito della libreria)", " (inverted)": " (invertita)", " · best of its burst": " · la migliore della sua raffica", diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 1c7f5a496b..9f7dd3fe7c 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "{total} 枚中 {used} 枚を使用", " · {skipped} skipped (file exists)": "・{skipped}件は同名ファイルのためスキップ", " · {} duplicate{} skipped": "・重複{}枚をスキップ{:.0}", " · {} failed: {}": "・{}件失敗:{}", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 2224ca2d80..97c15dd019 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "写真の結合結果", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft はこれらの写真を使用する写真に位置合わせできなかったため、パノラマには含まれていません。", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft はこれらの写真を使用する写真に位置合わせできませんでした。結合前にプレビューを確認してください。", " (library default)": " (ライブラリの既定)", " (inverted)": " (反転)", " · best of its burst": " · 連写内のベスト", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 1add895f4c..b13dc07d30 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "ჩართულია {used} ფოტო {total}-დან", " ({unsure} with several look-alike files: use Locate)": " ({unsure} რამდენიმე მსგავსი ფაილით: გამოიყენეთ „მოძებნა“)", " ({} in Recently Deleted)": " ({} ახლახან წაშლილებში)", " · {:.0}% clipped": " · {:.0}% მოკვეთილია", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index ca0da51c78..30769b60fa 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "ფოტოების გაერთიანების შედეგი", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft-მა ვერ გაასწორა ეს ფოტოები ჩართულ ფოტოებთან, ამიტომ პანორამა მათ არ შეიცავს.", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft-მა ვერ გაასწორა ეს ფოტოები ჩართულ ფოტოებთან. გაერთიანებამდე შეამოწმეთ გადახედვა.", " (library default)": " (ბიბლიოთეკის ნაგულისხმევი)", " (inverted)": " (ინვერსიული)", " · best of its burst": " · საუკეთესო თავის სერიაში", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 6ab483f219..f03219ae1e 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "Uwzględniono {used} z {total} zdjęć", " ({unsure} with several look-alike files: use Locate)": " ({unsure} wśród kilku podobnych plików: użyj polecenia Zlokalizuj)", " ({} in Recently Deleted)": " ({} w Ostatnio usuniętych)", " · {:.0}% clipped": " · {:.0}% prześwietlonych obszarów", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index ede93a493a..dbc29a1941 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "Wynik scalania zdjęć", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft nie mógł wyrównać tych zdjęć z pozostałymi, więc panorama je pomija.", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft nie mógł wyrównać tych zdjęć z uwzględnionym zestawem. Sprawdź podgląd przed scaleniem.", " (library default)": " (domyślne ustawienie biblioteki)", " (inverted)": " (odwrócona)", " · best of its burst": " · najlepsze zdjęcie z serii", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index 9d9be5ab30..762eed671a 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "{used} de {total} fotos incluídas", " ({} in Recently Deleted)": " ({} em Excluídos recentemente)", " · {skipped} skipped (file exists)": " · {skipped} ignorada(s) (arquivo existente)", " · {} duplicate{} skipped": " · {} duplicada(s) ignorada(s){:.0}", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index cf7ff65a34..3aedd82906 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "Resultado da mesclagem de fotos", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "O LightCraft não conseguiu alinhar estas fotos com as incluídas, então o panorama as deixa de fora.", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "O LightCraft não conseguiu alinhar estas fotos com o conjunto incluído. Revise a prévia antes de mesclar.", " (library default)": " (padrão da biblioteca)", " (inverted)": " (invertida)", " · best of its burst": " · melhor da sequência", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index f79bfcd445..24134de944 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "Включено {used} из {total} фотографий", " ({unsure} with several look-alike files: use Locate)": " (из них с несколькими похожими файлами: {unsure} — используйте «Найти фото»)", " ({} in Recently Deleted)": " ({} в «Недавно удалённых»)", " · {:.0}% clipped": " · обрезано: {:.0}%", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index d16196d000..b3df02470e 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "Результат объединения фото", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft не удалось совместить эти фото с остальными, поэтому панорама их не включает.", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft не удалось выровнять эти фотографии с включёнными. Проверьте предпросмотр перед объединением.", "+ Group": "+ Группа", "+ Rule": "+ Условие", "0: nothing is rejected.": "0: ничего не отклоняется.", diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 89e0048b02..e205ea56a9 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "{used} av {total} foton inkluderade", " ({unsure} with several look-alike files: use Locate)": " ({unsure} med flera likadana filer: använd Leta upp)", " ({} in Recently Deleted)": " ({} i Nyligen raderade)", " in {g} group{}": " i {g} grupp{}", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 365053dcf0..94b9e30333 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "Resultat av fotosammanslagning", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft kunde inte justera de här fotona mot de inkluderade, så panoramat utelämnar dem.", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft kunde inte justera dessa foton mot de inkluderade fotona. Granska förhandsvisningen innan du slår samman.", " (library default)": " (bibliotekets standard)", " (inverted)": " (inverterad)", " · best of its burst": " · bäst i sin bildserie", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 74eefe20bd..d30091f2d2 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "Включено {used} із {total} фотографій", " ({unsure} with several look-alike files: use Locate)": " ({unsure} із кількома схожими файлами: використайте «Знайти»)", " ({} in Recently Deleted)": " ({} у нещодавно видалених)", " · {:.0}% clipped": " · {:.0}% відсічено", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 3a44eb868b..09b78fab1e 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "Результат об'єднання фото", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft не вдалося вирівняти ці фото з рештою, тому панорама їх не містить.", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft не вдалося вирівняти ці фотографії з включеними. Перевірте попередній перегляд перед об'єднанням.", "% of all commits": "% усіх комітів", "A pen's pressure sets the size and flow of the brush": "Натиск пера задає розмір і потік пензля", "150 dpi · sRGB · current edits · fit without cropping": "150 dpi · sRGB · поточні правки · вписано без обрізання", diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index b59023e4b1..d6c686c3b5 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "Đã đưa vào {used} trong tổng số {total} ảnh", " ({unsure} with several look-alike files: use Locate)": " ({unsure} có nhiều tệp trông giống nhau: dùng Định vị)", " ({} in Recently Deleted)": " ({} trong Đã xóa gần đây)", " in {g} group{}": " in {g} group{}", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 5b3337c186..af27e9aa0a 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "Kết quả ghép ảnh", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft không thể căn chỉnh các ảnh này với những ảnh được dùng, nên ảnh toàn cảnh bỏ qua chúng.", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft không thể căn chỉnh các ảnh này với những ảnh được đưa vào. Hãy xem lại bản xem trước trước khi ghép.", " (library default)": " (mặc định thư viện)", " (inverted)": " (đã đảo)", " · best of its burst": " · đẹp nhất trong cụm", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index d4316ce211..1d5f27c576 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "已包含 {total} 张照片中的 {used} 张", " · {skipped} skipped (file exists)": " · 已跳过 {skipped} 个(文件已存在)", " · {} duplicate{} skipped": " · 已跳过 {0} 个重复项{1:.0}", " · {} failed: {}": " · {0} 个失败:{1}", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 8762091462..ca13d782a5 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "照片合并结果", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft 无法将这些照片与已包含的照片对齐,因此全景图未包含它们。", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft 无法将这些照片与已包含的照片对齐。合并前请检查预览。", " (library default)": " (图库默认值)", " (inverted)": " (已反相)", " · best of its burst": " · 连拍中的最佳照片", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 1469c42155..51fb1109ae 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -1,5 +1,4 @@ { - "{used} of {total} photos included": "已包含 {total} 張照片中的 {used} 張", " · {skipped} skipped (file exists)": " · 已略過 {skipped} 個(檔案已存在)", " · {} duplicate{} skipped": " · 已略過 {} 張重複照片{:.0}", " · {} failed: {}": " · {} 個失敗:{}", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 3e5a5616a4..f3dfc422ec 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -1,7 +1,4 @@ { - "Photo Merge Result": "照片合併結果", - "LightCraft could not align these photos with the included set, so the panorama leaves them out.": "LightCraft 無法將這些照片與已包含的照片對齊,因此全景圖未包含它們。", - "LightCraft could not align these photos with the included set. Review the preview before merging.": "LightCraft 無法將這些照片與已包含的照片對齊。合併前請檢查預覽。", " (library default)": " (照片庫預設值)", " (inverted)": " (已反轉)", " · best of its burst": " · 連拍中的最佳照片", From f599af1dd0091bfbf980eac4c212748c67ce28f9 Mon Sep 17 00:00:00 2001 From: FredApps Date: Mon, 30 Nov 2026 04:50:19 +0100 Subject: [PATCH 43/63] docs: give panorama verification its own gap number --- docs/gaps.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index f927415e5b..cbd4d8e312 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -42,7 +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) | -| 31 | **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) | +| 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) | @@ -58,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, 31 +- **Quality / fidelity:** 1, 3, 32 - **Stability and platforms:** 9, 26, 27 ## Closed recently (kept for calibration) @@ -139,7 +139,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 31 records unresolved panorama verification (#1765); included counts and omitted filenames are now reported | +| 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 | From 47d29d7775968185a073df9eb2979e6fe9a16257 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Tue, 1 Dec 2026 12:52:50 +0530 Subject: [PATCH 44/63] perf(catalog,cull): look photo ids up in hash sets instead of lists remove_from_stacks_ops and ungroup_ops checked every stacked photo against the passed slice, and culling's keep_active_shown and move_to_burst checked the selection and burst members against Vecs: quadratic for large deletes, selections and moves. Fixes #4947 Fixes #4948 --- crates/catalog/src/stacks.rs | 2 ++ crates/engine/src/cmd/cull.rs | 8 +++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/catalog/src/stacks.rs b/crates/catalog/src/stacks.rs index 2fcc723683..c1530e438b 100644 --- a/crates/catalog/src/stacks.rs +++ b/crates/catalog/src/stacks.rs @@ -132,11 +132,13 @@ impl Catalog { /// Ops that dissolve every stack containing one of `photos`. pub fn ungroup_ops(&self, photos: &[PhotoId]) -> Vec { + let photos: HashSet = photos.iter().copied().collect(); self.stacks.values().filter(|s| s.photos.iter().any(|p| photos.contains(p))).map(|s| Op::RemoveStack { id: s.id }).collect() } /// Ops that take `photos` out of their stacks (a stack left with one photo is dissolved). pub fn remove_from_stacks_ops(&self, photos: &[PhotoId]) -> Vec { + let photos: HashSet = photos.iter().copied().collect(); self.stacks .values() .filter(|s| s.photos.iter().any(|p| photos.contains(p))) diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 325b7ffb52..af5ed21f20 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -167,12 +167,13 @@ fn analyze(s: &mut Session, p: &Value) -> Result { /// takes over, and the rest of the selection stays selected. fn keep_active_shown(s: &mut Session) { let vis = s.visible_cloned(); + let vis_set: std::collections::HashSet = vis.iter().copied().collect(); if let Some(a) = s.selection.active - && !vis.contains(&a) + && !vis_set.contains(&a) && let Some(st) = s.catalog.stack_of(a) { let top = vis.iter().copied().find(|p| st.photos.contains(p)).unwrap_or(st.top()); - s.selection.ids.retain(|id| vis.contains(id)); + s.selection.ids.retain(|id| vis_set.contains(id)); if !s.selection.ids.contains(&top) { s.selection.ids.push(top); } @@ -239,8 +240,9 @@ fn move_to_burst(s: &mut Session, p: &Value) -> Result { old.entry(g).or_insert_with(|| index.get(&g).cloned().unwrap_or_default()); } let mut new = old.clone(); + let moved: std::collections::HashSet = ids.iter().copied().collect(); for members in new.values_mut() { - members.retain(|m| !ids.contains(m)); + members.retain(|m| !moved.contains(m)); } if let Some(g) = target { let members = new.entry(g).or_default(); From 24d4de51d51360095fc8aaa23628c9d9e00fdf0b Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Tue, 1 Dec 2026 15:30:09 +0530 Subject: [PATCH 45/63] perf(lens-blur): drop the full-image copy in blur (#4949) --- crates/pipeline/src/lens_blur.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/pipeline/src/lens_blur.rs b/crates/pipeline/src/lens_blur.rs index f518eb5de7..0571333377 100644 --- a/crates/pipeline/src/lens_blur.rs +++ b/crates/pipeline/src/lens_blur.rs @@ -491,16 +491,16 @@ fn blur(img: &mut Rgb32f, coc: &[f32], r: f32, boost: f32, origin: (usize, usize let gain = |c: [f32; 3]| 1.0 + BOOST_GAIN * boost * smooth(0.5, 1.0, lightcraft_color::luminance_2020(c)); let levels: Vec = (1..=LEVELS).map(|k| crate::timed("lens blur level", || level(img, coc, k, r, &gain, origin))).collect(); // each pixel between the two levels around its circle of confusion (level 0: the image) - let src = img.clone(); crate::for_rows(&mut img.data, w, |y, row| { for (x, px) in row.iter_mut().enumerate() { let i = y * w + x; let t = coc.get(i).copied().unwrap_or(0.0) * LEVELS as f32; let k = (t.floor().max(0.0) as usize).min(LEVELS - 1); let fr = (t - k as f32).clamp(0.0, 1.0); + let cur = *px; let at = |k: usize| match k { - 0 => src.data.get(i).copied().unwrap_or(*px), - k => levels.get(k - 1).map_or(*px, |l| l.sample(x, y)), + 0 => cur, + k => levels.get(k - 1).map_or(cur, |l| l.sample(x, y)), }; let (a, b) = (at(k), at(k + 1)); *px = std::array::from_fn(|c| a[c] + (b[c] - a[c]) * fr); From f5861f5fa806a8915655dcd5cff49494038d6ce9 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Tue, 1 Dec 2026 15:32:18 +0530 Subject: [PATCH 46/63] perf(lens-blur): build all four blur levels in one pass over the image (#4949) --- crates/pipeline/src/lens_blur.rs | 185 ++++++++++++++++++++++++++----- 1 file changed, 159 insertions(+), 26 deletions(-) diff --git a/crates/pipeline/src/lens_blur.rs b/crates/pipeline/src/lens_blur.rs index 0571333377..2e9e2775a6 100644 --- a/crates/pipeline/src/lens_blur.rs +++ b/crates/pipeline/src/lens_blur.rs @@ -489,7 +489,7 @@ fn blur(img: &mut Rgb32f, coc: &[f32], r: f32, boost: f32, origin: (usize, usize let w = img.width; // highlights brightened before they are spread (the bokeh), the rest as it is let gain = |c: [f32; 3]| 1.0 + BOOST_GAIN * boost * smooth(0.5, 1.0, lightcraft_color::luminance_2020(c)); - let levels: Vec = (1..=LEVELS).map(|k| crate::timed("lens blur level", || level(img, coc, k, r, &gain, origin))).collect(); + let levels = levels(img, coc, r, &gain, origin); // each pixel between the two levels around its circle of confusion (level 0: the image) crate::for_rows(&mut img.data, w, |y, row| { for (x, px) in row.iter_mut().enumerate() { @@ -524,37 +524,111 @@ impl Level { } } -/// Level `k` of [`LEVELS`] (radius `k / LEVELS · r` pixels): the disc blur of the pixels at least -/// that far out of focus. -fn level(img: &Rgb32f, coc: &[f32], k: usize, r: f32, gain: &(impl Fn([f32; 3]) -> f32 + Sync), origin: (usize, usize)) -> Level { +/// Rows of the image per band of the one-pass level fill (at least; a band is never shorter than +/// the coarsest level's cells). +const BAND_ROWS: usize = 64; + +/// One level's grid: radius `radius` pixels, cells `f` pixels wide, `lw × lh` of them, taking the +/// pixels whose circle of confusion lies in `lo..hi`. +struct Grid { + radius: f32, + f: usize, + shift: (usize, usize), + lw: usize, + lh: usize, + lo: f32, + hi: f32, +} + +/// What a band of image rows adds to one level: the cell rows from `cy_lo` on it touches. +#[derive(Default)] +struct BandCells { + cy_lo: usize, + cells: Vec<[f32; 4]>, +} + +/// The [`LEVELS`] levels (level `k`, from 1: radius `k / LEVELS · r` pixels, the disc blur of the +/// pixels at least that far out of focus), filled in one pass over `img`: each pixel is read and +/// its `gain` computed once, then added to every level's cells. +fn levels(img: &Rgb32f, coc: &[f32], r: f32, gain: &(impl Fn([f32; 3]) -> f32 + Sync), origin: (usize, usize)) -> Vec { + crate::timed("lens blur levels", || levels_banded(img, coc, r, gain, origin, BAND_ROWS)) +} + +/// [`levels`] with bands of at least `min_band` rows. Bands are fixed by the rows (aligned to the +/// whole output's), not by the threads, so the sums come out the same on any machine. +fn levels_banded(img: &Rgb32f, coc: &[f32], r: f32, gain: &(impl Fn([f32; 3]) -> f32 + Sync), origin: (usize, usize), min_band: usize) -> Vec { let (w, h) = (img.width, img.height); - let radius = r * k as f32 / LEVELS as f32; - let (f, shift, lw, lh) = level_grid(w, h, radius, origin); - let (grid_w, grid_h) = (w.saturating_add(shift.0), h.saturating_add(shift.1)); - // a pixel counts in this level when its own circle of confusion reaches it - let (lo, hi) = ((k - 1) as f32 / LEVELS as f32, k as f32 / LEVELS as f32); - let mut cells = vec![[0f32; 4]; lw * lh]; - crate::for_rows(&mut cells, lw, |cy, row| { - for (cx, cell) in row.iter_mut().enumerate() { - let mut acc = [0f32; 4]; - for vy in cy * f..((cy + 1) * f).min(grid_h) { - for vx in cx * f..((cx + 1) * f).min(grid_w) { - let (Some(x), Some(y)) = (vx.checked_sub(shift.0), vy.checked_sub(shift.1)) else { continue }; - let i = y * w + x; - let (Some(c), Some(d)) = (img.data.get(i), coc.get(i)) else { continue }; - // (a non-finite pixel would spread over the whole disc: left out) - if !c.iter().all(|v| v.is_finite()) { - continue; + let grids: Vec = (1..=LEVELS) + .map(|k| { + let radius = r * k as f32 / LEVELS as f32; + let (f, shift, lw, lh) = level_grid(w, h, radius, origin); + Grid { radius, f, shift, lw, lh, lo: (k - 1) as f32 / LEVELS as f32, hi: k as f32 / LEVELS as f32 } + }) + .collect(); + let band = grids.iter().map(|g| g.f).max().unwrap_or(1).max(min_band).max(1); + // where the first band's boundary falls above row 0 (the bands follow the whole output's rows) + let above = origin.1 % band; + let count = if h == 0 { 0 } else { (h - 1 + above) / band + 1 }; + let mut bands: Vec> = (0..count).map(|_| Vec::new()).collect(); + crate::for_rows(&mut bands, 1, |bi, slot| { + let Some(slot) = slot.first_mut() else { return }; + let y0 = (bi * band).saturating_sub(above); + let y1 = ((bi + 1) * band).saturating_sub(above).min(h); + *slot = grids + .iter() + .map(|g| { + let cy_lo = (y0 + g.shift.1) / g.f; + let cy_hi = (y1.saturating_sub(1) + g.shift.1) / g.f; + BandCells { cy_lo, cells: vec![[0f32; 4]; g.lw.saturating_mul(cy_hi.saturating_sub(cy_lo) + 1)] } + }) + .collect(); + // each pixel's gain, once for all the levels (NaN: left out, a non-finite pixel would + // spread over the whole disc) + let mut gains = vec![f32::NAN; w]; + for y in y0..y1 { + let Some(pixels) = img.data.get(y * w..(y + 1) * w) else { continue }; + let cocs = coc.get(y * w..).unwrap_or(&[]); + for (g0, c) in gains.iter_mut().zip(pixels) { + *g0 = if c.iter().all(|v| v.is_finite()) { gain(*c) } else { f32::NAN }; + } + for (g, bc) in grids.iter().zip(slot.iter_mut()) { + let Some(base) = ((y + g.shift.1) / g.f).checked_sub(bc.cy_lo).map(|r| r * g.lw) else { continue }; + let Some(row) = bc.cells.get_mut(base..base + g.lw) else { continue }; + let (mut cx, mut rem) = (g.shift.0 / g.f, g.shift.0 % g.f); + for ((c, d), g0) in pixels.iter().zip(cocs).zip(&gains) { + if !g0.is_nan() + && let Some(cell) = row.get_mut(cx) + { + let wt = FOCUS_WEIGHT + smooth(g.lo, g.hi, *d); + let gw = g0 * wt; + *cell = [cell[0] + c[0] * gw, cell[1] + c[1] * gw, cell[2] + c[2] * gw, cell[3] + wt]; + } + rem += 1; + if rem == g.f { + rem = 0; + cx += 1; } - let wt = FOCUS_WEIGHT + smooth(lo, hi, *d); - let g = gain(*c) * wt; - acc = [acc[0] + c[0] * g, acc[1] + c[1] * g, acc[2] + c[2] * g, acc[3] + wt]; } } - *cell = acc; } }); - Level { img: disc(&cells, lw, lh, radius / f as f32), f, shift } + grids + .iter() + .enumerate() + .map(|(k, g)| { + let mut cells = vec![[0f32; 4]; g.lw * g.lh]; + // a cell row is the sum of what the bands (in order) added to it + crate::for_rows(&mut cells, g.lw, |cy, row| { + for bc in bands.iter().filter_map(|b| b.get(k)) { + let Some(part) = cy.checked_sub(bc.cy_lo).and_then(|r| bc.cells.get(r * g.lw..(r + 1) * g.lw)) else { continue }; + for (cell, p) in row.iter_mut().zip(part) { + *cell = std::array::from_fn(|c| cell[c] + p[c]); + } + } + }); + Level { img: disc(&cells, g.lw, g.lh, g.radius / g.f as f32), f: g.f, shift: g.shift } + }) + .collect() } /// Grid scale and dimensions for one disc level, bounded even when a window's grid is offset. @@ -1085,6 +1159,65 @@ mod tests { assert!(subject_point(&Rgb32f::new(0, 0), &s, None).is_none()); } + /// One level gathered cell by cell, as the one-pass fill replaced it: the reference for [`levels_banded`]. + fn level_reference(img: &Rgb32f, coc: &[f32], k: usize, r: f32, gain: &(impl Fn([f32; 3]) -> f32 + Sync), origin: (usize, usize)) -> Level { + let (w, h) = (img.width, img.height); + let radius = r * k as f32 / LEVELS as f32; + let (f, shift, lw, lh) = level_grid(w, h, radius, origin); + let (grid_w, grid_h) = (w.saturating_add(shift.0), h.saturating_add(shift.1)); + // a pixel counts in this level when its own circle of confusion reaches it + let (lo, hi) = ((k - 1) as f32 / LEVELS as f32, k as f32 / LEVELS as f32); + let mut cells = vec![[0f32; 4]; lw * lh]; + crate::for_rows(&mut cells, lw, |cy, row| { + for (cx, cell) in row.iter_mut().enumerate() { + let mut acc = [0f32; 4]; + for vy in cy * f..((cy + 1) * f).min(grid_h) { + for vx in cx * f..((cx + 1) * f).min(grid_w) { + let (Some(x), Some(y)) = (vx.checked_sub(shift.0), vy.checked_sub(shift.1)) else { continue }; + let i = y * w + x; + let (Some(c), Some(d)) = (img.data.get(i), coc.get(i)) else { continue }; + // (a non-finite pixel would spread over the whole disc: left out) + if !c.iter().all(|v| v.is_finite()) { + continue; + } + let wt = FOCUS_WEIGHT + smooth(lo, hi, *d); + let g = gain(*c) * wt; + acc = [acc[0] + c[0] * g, acc[1] + c[1] * g, acc[2] + c[2] * g, acc[3] + wt]; + } + } + *cell = acc; + } + }); + Level { img: disc(&cells, lw, lh, radius / f as f32), f, shift } + } + + /// The one-pass fill of all four levels matches gathering each level on its own: bands that + /// cut cells, a window origin, a non-finite pixel and a varying circle of confusion included. + #[test] + fn one_pass_levels_match_gathering_each_level_alone() { + let (w, h) = (300, 200); + let mut img = scene(w, h, 150, 100); + img.set(40, 30, [3.0, 2.0, 1.0]); + img.set(251, 177, [6.0; 3]); + img.set(120, 60, [f32::NAN, 0.5, 0.5]); + let coc: Vec = (0..w * h).map(|i| ((i % w) as f32 / w as f32 + (i / w) as f32 / h as f32) / 2.0).collect(); + let (r, origin) = (200.0, (37, 53)); + let gain = |c: [f32; 3]| 1.0 + BOOST_GAIN * 0.7 * smooth(0.5, 1.0, lightcraft_color::luminance_2020(c)); + let merged = levels_banded(&img, &coc, r, &gain, origin, 7); + assert_eq!(merged.len(), LEVELS); + let mut scales = Vec::new(); + for (i, m) in merged.iter().enumerate() { + let alone = level_reference(&img, &coc, i + 1, r, &gain, origin); + assert_eq!((m.f, m.shift), (alone.f, alone.shift), "level {}", i + 1); + assert_eq!(m.img.data.len(), alone.img.data.len()); + for (a, b) in m.img.data.iter().flatten().zip(alone.img.data.iter().flatten()) { + assert!((a - b).abs() <= 1e-5 * a.abs().max(b.abs()) + 1e-6, "level {}: {a} vs {b}", i + 1); + } + scales.push(m.f); + } + assert!(scales.windows(2).all(|p| p[0] < p[1]), "the levels share a grid: {scales:?}"); + } + /// Hostile settings and images: no panic, no NaN. #[test] fn hostile_input_never_panics() { From ea1ecaef3d14b00ee2712a866d3d5763862802f4 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Tue, 1 Dec 2026 18:10:12 +0530 Subject: [PATCH 47/63] fix(merge): write 16-bit integer merge DNGs as lossless JPEG tiles (#4838) LibRaw, rawspeed and RawTherapee accept Deflate DNG tiles only for floating-point data, so panorama and synth-merge DNGs (16-bit integer, Deflate) did not open there. Integer merge output now uses lossless JPEG tiles; HDR and float output keep Deflate. --- crates/merge/src/output.rs | 13 ++++++++++--- docs/merge.md | 7 ++++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/crates/merge/src/output.rs b/crates/merge/src/output.rs index 2d0a523f4b..30d2d5c41d 100644 --- a/crates/merge/src/output.rs +++ b/crates/merge/src/output.rs @@ -28,7 +28,7 @@ pub enum DngSamples { Half, /// 32-bit floating point, Deflate + floating-point predictor. Float, - /// 16-bit integer, Deflate + horizontal predictor (panoramas of normal-range photos). + /// 16-bit integer, lossless JPEG tiles (panoramas of normal-range photos). U16, } @@ -117,7 +117,12 @@ pub fn write_linear_dng( metadata: meta, lens_metadata: Default::default(), }; - let compression = DngCompression::Deflate { tile: 256, half: samples == DngSamples::Half }; + // Common raw readers accept Deflate only for floating-point data, so integer data uses lossless JPEG. + let compression = match samples { + DngSamples::U16 => DngCompression::Lj92 { tile: 256 }, + DngSamples::Half => DngCompression::Deflate { tile: 256, half: true }, + DngSamples::Float => DngCompression::Deflate { tile: 256, half: false }, + }; lightcraft_raw::write_dng(&raw, &DngWriteOptions { compression, ..Default::default() }).map_err(|e| MergeError::Output(e.to_string())) } @@ -153,6 +158,8 @@ mod tests { assert!((red[c] / k - want[c]).abs() < 5e-3, "{red:?} vs {want:?}"); } let u16 = write_linear_dng(&img, &color, Orientation::Normal, &Metadata::default(), 0.0, DngSamples::U16, &[]).unwrap(); - assert!(lightcraft_raw::decode(&u16).is_ok()); + let raw16 = lightcraft_raw::decode(&u16).unwrap(); + assert_eq!((raw16.width, raw16.height, raw16.cpp), (80, 60, 3)); + assert!(matches!(raw16.data, lightcraft_raw::RawData::U16(_))); } } diff --git a/docs/merge.md b/docs/merge.md index e2183583a5..197ea3f32e 100644 --- a/docs/merge.md +++ b/docs/merge.md @@ -58,9 +58,10 @@ Warp: a separable stretch of the smoothed valid-area edges to the canvas edges. largest rectangle of image data (set as the develop crop, so it stays adjustable). Fill Edges: push–pull diffusion. Output: 16-bit integer DNG (16-bit float for HDR panoramas). -**DNG output** (`output.rs`): LinearRaw, 3 samples, Deflate tiles; values scaled below 1.0 with the -scale in `BaselineExposure`; raw sources keep their DNG colour tags (camera RGB), other sources get -`ColorMatrix1`/`ForwardMatrix1` of their RGB space. +**DNG output** (`output.rs`): LinearRaw, 3 samples; Deflate tiles for float samples, lossless JPEG +tiles for 16-bit integer; values scaled below 1.0 with the scale in `BaselineExposure`; raw sources +keep their DNG colour tags (camera RGB), other sources get `ColorMatrix1`/`ForwardMatrix1` of their +RGB space. ## Measured (synthetic tests, `cargo test -p lightcraft-merge`) From 6efd21c440f04e660a05f1ba201c8889788f928e Mon Sep 17 00:00:00 2001 From: Terra854 Date: Wed, 2 Dec 2026 09:53:57 +0800 Subject: [PATCH 48/63] #4988: assert escaped paths in curve histogram diagnostics --- crates/ui-egui/src/render/thumbnail_tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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(); From c5bd44a1f75632596f3b1e8f58aa80c017cf6402 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Wed, 2 Dec 2026 08:47:58 +0530 Subject: [PATCH 49/63] GPU readback: pool staging buffers and wait only for this render's submission (#4958) finish_and_read took a fresh MAP_READ staging buffer for every readback (~96 MB for a 24 MP export) and waited for everything on the queue. Staging buffers now share the free pool with storage buffers, matched on usage so neither is handed out as the other, and are returned after a clean copy-out (dropped after any failure). Gpu::submit returns the SubmissionIndex and the readback waits only on it; the 60 s timeout, the 10 s callback grace period and the lost-device handling are kept. --- crates/gpu/src/ctx.rs | 120 +++++++++++++++++++++++++++--------------- 1 file changed, 79 insertions(+), 41 deletions(-) diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index d2344fc77f..5135ebaa80 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -590,42 +590,43 @@ impl Gpu { self.over_limit(size); return Buf { buf: Some(Tracked::new(self.placeholder())), len }; } - let recycled = { - let mut f = self.free.lock().unwrap_or_else(|e| e.into_inner()); - // the smallest pooled buffer that holds `size` with at most 25 % to spare: photos of - // slightly different sizes reuse each other's buffers instead of piling up new ones - let b = f - .iter() - .enumerate() - .filter(|(_, b)| b.0.size() >= size && b.0.size() <= size + size / 4) - .min_by_key(|(_, b)| b.0.size()) - .map(|(i, _)| i) - .map(|i| f.swap_remove(i)); - if let Some(b) = &b { - POOLED.fetch_sub(b.0.size(), Ordering::Relaxed); - } - b - }; - let buf = recycled.unwrap_or_else(|| { - Tracked::new(self.device.create_buffer(&wgpu::BufferDescriptor { - label: None, - size, - usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - })) - }); + let buf = + self.take_pooled(size, wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST).unwrap_or_else(|| { + Tracked::new(self.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + })) + }); Buf { buf: Some(buf), len } } + /// Take the smallest pooled buffer of exactly `usage` that holds `size` with at most 25 % to + /// spare: photos of slightly different sizes reuse each other's buffers instead of piling up + /// new ones. Storage and readback (staging) buffers share the pool but never each other's use. + fn take_pooled(&self, size: u64, usage: wgpu::BufferUsages) -> Option { + let mut f = self.free.lock().unwrap_or_else(|e| e.into_inner()); + let i = f + .iter() + .enumerate() + .filter(|(_, b)| b.0.usage() == usage && b.0.size() >= size && b.0.size() <= size + size / 4) + .min_by_key(|(_, b)| b.0.size()) + .map(|(i, _)| i)?; + let b = f.swap_remove(i); + POOLED.fetch_sub(b.0.size(), Ordering::Relaxed); + Some(b) + } + /// Submit command buffers, then make the buffers this thread dropped before reusable. - /// Nothing is submitted once this render has failed: the render is discarded and recomputed - /// on the CPU, and the failure contract says no further GPU work runs after a fatal failure. - pub fn submit(&self, cmds: impl IntoIterator) { - if !failed() { - self.queue.submit(cmds); - } + /// Nothing is submitted once this render has failed (the render is discarded and recomputed + /// on the CPU, and the failure contract says no further GPU work runs after a fatal failure): + /// the result is then `None`, otherwise the submission's index. + pub fn submit(&self, cmds: impl IntoIterator) -> Option { + let index = if failed() { None } else { Some(self.queue.submit(cmds)) }; let retired = take_retired(); self.pool(retired); + index } /// Put reusable buffers into the free pool (trimmed to its limit). @@ -868,15 +869,22 @@ impl Gpu { return zeros(); } let size = (len * 4) as u64; - let staging = self.device.create_buffer(&wgpu::BufferDescriptor { - label: Some("readback"), - size: size.max(4), - usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, + // a pooled staging buffer when one fits: a fresh ~96 MB one per export costs more than the copy + let usage = wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST; + let staging = self.take_pooled(size.max(4), usage).unwrap_or_else(|| { + Tracked::new(self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("readback"), + size: size.max(4), + usage, + mapped_at_creation: false, + })) }); - enc.copy_buffer_to_buffer(src.raw(), 0, &staging, 0, size); - self.submit([enc.finish()]); - let slice = staging.slice(..size); + enc.copy_buffer_to_buffer(src.raw(), 0, &staging.0, 0, size); + let Some(index) = self.submit([enc.finish()]) else { + // the render failed between the check above and the submit: nothing was submitted + return zeros(); + }; + let slice = staging.0.slice(..size); let (tx, rx) = std::sync::mpsc::channel(); slice.map_async(wgpu::MapMode::Read, move |r| { let _ = tx.send(r); @@ -887,8 +895,9 @@ impl Gpu { }; // A lost device makes the wait fail ([`Gpu::poll`] turns wgpu's panic into the error) and // the map callback never run: checking both keeps this from blocking forever (or handing - // back an unwritten buffer as the image). - if let Err(e) = self.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(READBACK_TIMEOUT) }) { + // back an unwritten buffer as the image). The wait is for this submission only: the queue + // is ordered, so it also covers earlier ones, but not later ones from other threads. + if let Err(e) = self.poll(wgpu::PollType::Wait { submission_index: Some(index), timeout: Some(READBACK_TIMEOUT) }) { return failed(e); } // another thread's poll may be the one that runs the callback: allow it a moment @@ -913,7 +922,10 @@ impl Gpu { } }); drop(data); - staging.unmap(); + staging.0.unmap(); + // only a buffer that mapped and read cleanly goes back: after any failure above its map + // state is unknown, so it is dropped instead + self.pool([staging]); out } } @@ -1335,6 +1347,32 @@ mod tests { let back: Vec<[u32; 3]> = g.finish_and_read(g.encoder(), &b, data.len()); assert!(back.len() == 1 << 20 && back.as_flattened() == data.as_slice()); } + /// Readback staging buffers are pooled and reused, and never handed out as storage buffers. + #[test] + fn readback_staging_buffers_are_pooled_apart_from_storage() { + let Some(g) = crate::device() else { + lightcraft_testkit::skip!(Gpu, "no GPU device"); + return; + }; + let len = 1_234_567usize; + let want = (len * 4) as u64; + let mapped = wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST; + let count = || { + let f = g.free.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + f.iter().filter(|b| b.0.usage() == mapped && b.0.size() >= want).count() + }; + let data: Vec = (0..len as u32).map(|i| i.wrapping_mul(2_654_435_761)).collect(); + let b = g.upload(&data); + let back: Vec = g.finish_and_read(g.encoder(), &b, len); + assert!(back == data); + assert!(count() >= 1, "the staging buffer went back to the pool"); + let before = count(); + let back: Vec = g.finish_and_read(g.encoder(), &b, len); + assert!(back == data, "a reused staging buffer reads back exactly"); + assert!(count() <= before, "the second readback reused a pooled buffer instead of adding one"); + assert!(g.buffer(len).raw().usage().contains(wgpu::BufferUsages::STORAGE), "a storage request got a staging buffer"); + } + /// An upload after this render has failed keeps the failure contract (`Gpu::submit` skips the /// submission, so nothing further runs on the GPU): the caller gets the placeholder with the /// requested length instead of a staging buffer holding a copy of the data for a submission From 73781f93ff4fe52082ebe08fb85b3e041d36161d Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Wed, 2 Dec 2026 10:22:21 +0530 Subject: [PATCH 50/63] Vignette: separate the CPU distance into column and row terms (#4950) Each pixel did three powf. The column term is now a table of image width and the row term is computed once per row, which leaves one powf per pixel only inside the transition band, and none for the default power 2 (sqrt). Same output up to float rounding. --- crates/pipeline/src/finish.rs | 90 +++++++++++++++++++++++++++++++---- 1 file changed, 82 insertions(+), 8 deletions(-) diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index bad24796f0..d6980fa1c4 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -62,6 +62,51 @@ pub struct Vig { pub style: VignetteStyle, } +/// A vignette's falloff over the summed per-axis terms, with the band edges raised to the power once. +#[derive(Clone, Copy, Debug)] +struct VigFalloff { + power: f32, + kx: f32, + ky: f32, + start: f32, + end: f32, + s0: f32, + s1: f32, +} + +impl VigFalloff { + fn new(v: &Vig, aspect: f32) -> Self { + let sx = 1.0 + (aspect - 1.0) * v.aspect_mix; + let sy = 1.0 + (1.0 / aspect - 1.0) * v.aspect_mix; + let m = sx.max(sy); + let end = v.start + v.width; + Self { power: v.power, kx: sx.max(1.0) / m, ky: sy.max(1.0) / m, start: v.start, end, s0: term(v.start, v.power), s1: term(end, v.power) } + } + + /// One axis's share of the distance for a normalised coordinate `c` in -1..1 (`horizontal` picks the axis). + fn axis(&self, c: f32, horizontal: bool) -> f32 { + term((c * if horizontal { self.kx } else { self.ky }).abs(), self.power) + } + + /// The vignette strength 0..1 from the summed axis terms. + fn falloff(&self, s: f32) -> f32 { + if s <= self.s0 { + 0.0 + } else if s >= self.s1 { + 1.0 + } else { + let dist = if self.power == 2.0 { s.sqrt() } else { s.powf(1.0 / self.power) }; + smooth(self.start, self.end, dist) + } + } +} + +/// `a` raised to the vignette power, for `a >= 0`. +#[inline] +fn term(a: f32, p: f32) -> f32 { + if p == 2.0 { a * a } else { a.powf(p) } +} + fn vignette(s: &DevelopSettings) -> Option { let v = &s.vignette; (v.amount != 0.0).then(|| { @@ -526,7 +571,12 @@ pub(crate) fn finish_with( let peak = fp.peak; let hdr = peak > 1.0; let mut out = vec![T::default(); w * h]; + // the vignette splits into a column term and a row term, so each is computed once + let vig_fall = vig.as_ref().map(|v| VigFalloff::new(v, aspect)); + let vig_cols: Vec = + vig_fall.as_ref().map_or_else(Vec::new, |f| (0..w).map(|x| f.axis((vx + x as f32 + 0.5) / vw * 2.0 - 1.0, true)).collect()); for_rows(&mut out, w, |y, row| { + let vig_row = vig_fall.as_ref().map_or(0.0, |f| f.axis((vy + y as f32 + 0.5) / vh * 2.0 - 1.0, false)); // the crystal grain of the whole row at once when its pixels are axis-aligned let crystal_row = crystal_row(fp, y, row.len()); for (x, px) in row.iter_mut().enumerate() { @@ -578,14 +628,8 @@ pub(crate) fn finish_with( } // --- vignette (display linear, post-crop) - if let Some(v) = vig { - let u = (vx + x as f32 + 0.5) / vw * 2.0 - 1.0; - let vv = (vy + y as f32 + 0.5) / vh * 2.0 - 1.0; - let sx = 1.0 + (aspect - 1.0) * v.aspect_mix; - let sy = 1.0 + (1.0 / aspect - 1.0) * v.aspect_mix; - let (ax, ay) = ((u * sx.max(1.0) / sx.max(sy)).abs(), (vv * sy.max(1.0) / sx.max(sy)).abs()); - let dist = (ax.powf(v.power) + ay.powf(v.power)).powf(1.0 / v.power); - let t = smooth(v.start, v.start + v.width, dist); + if let (Some(v), Some(f)) = (vig, &vig_fall) { + let t = f.falloff(vig_cols.get(x).copied().unwrap_or(0.0) + vig_row); if t > 0.0 { let lum = luminance_2020(d).clamp(0.0, 1.0); if v.amount < 0.0 { @@ -935,6 +979,36 @@ mod tests { Process::ALL.into_iter().filter(|p| *p < Process::V13) } + #[test] + fn separable_vignette_matches_the_direct_formula() { + let (vx, vy, vw, vh) = (0.0f32, 0.0f32, 61.0f32, 41.0f32); + let (mut zero, mut mid, mut one) = (false, false, false); + let vigs = [(2.0, 1.0, 0.25, 0.6), (2.0, 0.5, 0.3, 0.8), (5.0, 1.0, 0.3, 0.5), (5.0, 0.0, 0.4, 0.7)]; + for aspect in [1.5f32, 0.6] { + for (power, aspect_mix, start, width) in vigs { + let v = Vig { amount: -0.5, start, width, aspect_mix, power, highlights: 0.0, style: VignetteStyle::default() }; + let f = VigFalloff::new(&v, aspect); + for y in 0..vh as usize { + for x in 0..vw as usize { + let u = (vx + x as f32 + 0.5) / vw * 2.0 - 1.0; + let vv = (vy + y as f32 + 0.5) / vh * 2.0 - 1.0; + let sx = 1.0 + (aspect - 1.0) * v.aspect_mix; + let sy = 1.0 + (1.0 / aspect - 1.0) * v.aspect_mix; + let (ax, ay) = ((u * sx.max(1.0) / sx.max(sy)).abs(), (vv * sy.max(1.0) / sx.max(sy)).abs()); + let dist = (ax.powf(v.power) + ay.powf(v.power)).powf(1.0 / v.power); + let t_ref = smooth(v.start, v.start + v.width, dist); + let t = f.falloff(f.axis(u, true) + f.axis(vv, false)); + assert!((t - t_ref).abs() < 1e-4, "{power} {aspect} at {x},{y}: {t} vs {t_ref}"); + zero |= t == 0.0; + one |= t == 1.0; + mid |= t > 0.0 && t < 1.0; + } + } + } + } + assert!(zero && mid && one, "the grid covers the whole falloff"); + } + #[test] fn tone_sliders_ease_off_from_v13_only() { for v in [-100.0, -52.0, 0.0, 13.0, 100.0, 250.0] { From 312b2dc8bb5fa5d08358750e0defbcc0ac0358e7 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Wed, 2 Dec 2026 11:08:57 +0530 Subject: [PATCH 51/63] BM3D (CPU): transform each block once per plane, not once per group (#4951) The CPU collaborative filter ran the 2-D DCT on every member of every group, so a block was transformed each time it joined a group, and the Wiener step transformed the pilot's blocks again for every group. Each block's coefficients are now worked out the first time a group asks for them and reused. The output is bit-for-bit the same. Co-Authored-By: Claude --- crates/denoise-core/src/bm3d.rs | 117 +++++++++++++++++++++++++++----- 1 file changed, 101 insertions(+), 16 deletions(-) diff --git a/crates/denoise-core/src/bm3d.rs b/crates/denoise-core/src/bm3d.rs index 4419e8b921..e8578f7e46 100644 --- a/crates/denoise-core/src/bm3d.rs +++ b/crates/denoise-core/src/bm3d.rs @@ -203,22 +203,77 @@ struct Scratch { col_tmp: Vec, } -/// A group (`m` blocks of `n × n`, one after the other in `buf`) to the transform domain, or back. -fn group_transform(tf: &Transform, buf: &mut [f32], m: usize, s: &mut Scratch, forward: bool) { +/// A group (`m` blocks of `n × n`, one after the other in `buf`) back from the transform domain. +fn group_inverse(tf: &Transform, buf: &mut [f32], m: usize, s: &mut Scratch) { let nn = tf.n * tf.n; s.tmp.resize(nn, 0.0); - if !forward { - haar_columns(buf, m, nn, s, false); - } + haar_columns(buf, m, nn, s, false); for blk in buf.chunks_exact_mut(nn) { - if forward { - tf.forward(blk, &mut s.tmp); - } else { - tf.inverse(blk, &mut s.tmp); + tf.inverse(blk, &mut s.tmp); + } +} + +/// The 2-D DCT of the blocks of one plane, each worked out the first time a group asks for it: a block joins many +/// groups, and its coefficients do not depend on the group. +#[derive(Default)] +struct BlockCoeffs { + /// The coefficients of block `i`, at `i * n * n`. + data: Vec, + /// Whether block `i` is in `data` yet. + done: Vec, + /// Blocks along a side of the plane. + nb: usize, +} + +impl BlockCoeffs { + /// Forget the blocks, for a plane of `t × t` cells that holds blocks of `n × n`. + fn reset(&mut self, t: usize, n: usize) { + self.nb = (t + 1).saturating_sub(n); + let count = self.nb * self.nb; + self.done.clear(); + self.done.resize(count, false); + if self.data.len() < count * n * n { + self.data = vec![0.0; count * n * n]; } } - if forward { - haar_columns(buf, m, nn, s, true); + + /// A group (`members` are the blocks' top-left cells) in the transform domain: the blocks' DCTs one after the other + /// in `out`, then the Haar transform across them. + fn group(&mut self, tf: &Transform, plane: &[f32], t: usize, members: &[u32], out: &mut Vec, s: &mut Scratch) { + let n = tf.n; + let nn = n * n; + s.tmp.resize(nn, 0.0); + out.clear(); + for &pos in members { + let (x, y) = (pos as usize % t.max(1), pos as usize / t.max(1)); + let idx = y * self.nb + x; + if x < self.nb && y < self.nb { + let hit = self.done.get(idx).copied().unwrap_or(false); + if let (Some(slot), false) = (self.data.get_mut(idx * nn..(idx + 1) * nn), hit) { + for (j, dst) in slot.chunks_exact_mut(n).enumerate() { + let at = pos as usize + j * t; + match plane.get(at..at + n) { + Some(row) => dst.copy_from_slice(row), + None => dst.fill(0.0), + } + } + tf.forward(slot, &mut s.tmp); + if let Some(d) = self.done.get_mut(idx) { + *d = true; + } + } + if let Some(slot) = self.data.get(idx * nn..(idx + 1) * nn) { + out.extend_from_slice(slot); + continue; + } + } + // a block outside the plane's grid: not cached + let mut one = Vec::new(); + gather(plane, t, n, &[pos], &mut one); + tf.forward(&mut one, &mut s.tmp); + out.extend_from_slice(&one); + } + haar_columns(out, members.len(), nn, s, true); } } @@ -376,16 +431,18 @@ fn collaborate(y: &[Vec], pilot: Option<&[Vec]>, groups: &[Vec], let lambda = lambda * sigma; let mut s = Scratch::default(); let (mut buf, mut pbuf) = (Vec::new(), Vec::new()); + let (mut cache, mut pcache) = (BlockCoeffs::default(), BlockCoeffs::default()); let mut out = Vec::with_capacity(y.len()); for plane in y { let mut num = vec![0f32; t * t]; let mut den = vec![0f32; t * t]; let c = out.len(); let pilot_plane = pilot.and_then(|pl| pl.get(c)); + cache.reset(t, n); + pcache.reset(t, n); for members in groups { let m = members.len(); - gather(plane, t, n, members, &mut buf); - group_transform(tf, &mut buf, m, &mut s, true); + cache.group(tf, plane, t, members, &mut buf, &mut s); let weight = match pilot_plane { None => { let mut kept = 0usize; @@ -399,8 +456,7 @@ fn collaborate(y: &[Vec], pilot: Option<&[Vec]>, groups: &[Vec], 1.0 / kept.max(1) as f32 } Some(pl) => { - gather(pl, t, n, members, &mut pbuf); - group_transform(tf, &mut pbuf, m, &mut s, true); + pcache.group(tf, pl, t, members, &mut pbuf, &mut s); let mut energy = 0f32; for (v, &q) in buf.iter_mut().zip(&pbuf) { let w = q * q / (q * q + sigma * sigma); @@ -410,7 +466,7 @@ fn collaborate(y: &[Vec], pilot: Option<&[Vec]>, groups: &[Vec], 1.0 / energy.max(1e-3) } }; - group_transform(tf, &mut buf, m, &mut s, false); + group_inverse(tf, &mut buf, m, &mut s); for (&pos, blk) in members.iter().zip(buf.chunks_exact(n * n)) { for (j, row) in blk.chunks_exact(n).enumerate() { let at = pos as usize + j * t; @@ -523,6 +579,35 @@ mod tests { .collect() } + /// The cached group transform gives bit for bit what gathering the blocks and transforming each one does, for + /// matched groups, repeated blocks and the last block of the grid, whatever order the blocks are asked for. + #[test] + fn the_cached_group_transform_matches_transforming_each_block() { + let (t, n) = (24, 8); + let nb = t + 1 - n; + let tf = Transform::new(n); + let planes = noisy(t, 3.0, 11); + let plane = &planes[0]; + let mut groups = match_groups(plane, t, n, 3, 6, 8, 2.0 * 2.0); + groups.push(vec![5, 5, 7, 5]); + groups.push(vec![(nb * t + nb - 1) as u32, 0, (nb * t + nb - 1) as u32, (nb - 1) as u32]); + let (mut cache, mut s) = (BlockCoeffs::default(), Scratch::default()); + cache.reset(t, n); + let (mut got, mut want) = (Vec::new(), Vec::new()); + for members in groups.iter().chain(groups.iter().rev()) { + let m = members.len(); + cache.group(&tf, plane, t, members, &mut got, &mut s); + gather(plane, t, n, members, &mut want); + let mut tmp = vec![0f32; n * n]; + for blk in want.chunks_exact_mut(n * n) { + tf.forward(blk, &mut tmp); + } + haar_columns(&mut want, m, n * n, &mut s, true); + assert_eq!(got.len(), want.len()); + assert!(got.iter().zip(&want).all(|(a, b)| a.to_bits() == b.to_bits()), "group {members:?}"); + } + } + /// The deviation of the planes' values around `level`. fn spread(planes: &[Vec], level: f32) -> f32 { let all: Vec = planes.iter().flatten().copied().collect(); From ee824f37fd6afff1dd29daf5779a8ebbae1d8a85 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:51:08 +0700 Subject: [PATCH 52/63] LR-MASK-BRUSH: the Lens Blur brush preview keeps an Auto Mask stroke's V15 accumulation (review) --- crates/ui-egui/src/panels/detail/lens_blur.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/detail/lens_blur.rs b/crates/ui-egui/src/panels/detail/lens_blur.rs index 765fc8289a..171d10e799 100644 --- a/crates/ui-egui/src/panels/detail/lens_blur.rs +++ b/crates/ui-egui/src/panels/detail/lens_blur.rs @@ -122,9 +122,10 @@ pub(super) fn lens_blur_brush_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui hard: r * (1.0 - (app.ui.brush_feather / 100.0).clamp(0.0, 1.0)), flow: (app.ui.brush_flow / 100.0).clamp(0.0, 1.0), density: (app.ui.lens_blur_brush_amount / 100.0).clamp(0.0, 1.0), - // (its strokes render as a mask brush does: Flow per radius travelled from V15, the edge by stroke from V16) + // (its strokes render as a mask brush does: Flow per radius travelled from V15, the edge by stroke from V16, + // except an Auto Mask stroke, which keeps V15's accumulation as the committed one does) per_radius: lightcraft_pipeline::masks::flow_per_radius(d), - by_stroke: lightcraft_pipeline::masks::stroke_feather(d), + by_stroke: lightcraft_pipeline::masks::stroke_feather(d) && !app.ui.brush_auto_mask, color: if focus { [70, 200, 120] } else { [230, 70, 70] }, opacity: 0.45, }; From 8e55f56f47adf2c4db17b2c6a7c63b1281b9110e Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Wed, 2 Dec 2026 11:49:08 +0530 Subject: [PATCH 53/63] perf(merge): grid ring search for ANMS point thinning (#4953) ANMS compared every keypoint with every stronger one (O(n^2), n up to 12,000). Bucket the points into a uniform grid and search rings of cells outward until no unsearched cell can hold a closer stronger point. Points with no stronger predecessor skip the search. The result is identical; a test checks it against the old quadratic version. --- crates/merge/src/features.rs | 172 ++++++++++++++++++++++++++++++++--- 1 file changed, 161 insertions(+), 11 deletions(-) diff --git a/crates/merge/src/features.rs b/crates/merge/src/features.rs index 9bf770a69f..70d5690de8 100644 --- a/crates/merge/src/features.rs +++ b/crates/merge/src/features.rs @@ -163,23 +163,25 @@ fn harris(lvl: &Plane) -> Vec<(f32, f32, f32)> { } /// Adaptive non-maximal suppression: indices (into `pts`, sorted by decreasing strength) of the `max` -/// points with the largest suppression radii. +/// points with the largest suppression radii. The nearest stronger point is found by searching +/// rings of a uniform grid outward from each point, which gives exactly the brute-force result in +/// near-linear time. fn anms(pts: &[Keypoint], max: usize) -> Vec { if pts.len() <= max { return (0..pts.len()).collect(); } + let mut pmax = Vec::with_capacity(pts.len()); + let mut run = f32::NEG_INFINITY; + for p in pts { + pmax.push(run); + run = run.max(p.strength); + } + let grid = AnmsGrid::new(pts); let radii: Vec = (0..pts.len()) .into_par_iter() - .map(|i| { - let p = pts[i]; - let mut best = f32::INFINITY; - for q in &pts[..i] { - if q.strength * 0.9 > p.strength { - let d = (q.x - p.x).powi(2) + (q.y - p.y).powi(2); - best = best.min(d); - } - } - best + .map(|i| match (pts.get(i), pmax.get(i)) { + (Some(p), Some(m)) if m * 0.9 > p.strength => grid.nearest_stronger(pts, i, p), + _ => f32::INFINITY, }) .collect(); let mut idx: Vec = (0..pts.len()).collect(); @@ -188,6 +190,98 @@ fn anms(pts: &[Keypoint], max: usize) -> Vec { idx } +/// Uniform grid over the finite points; each cell lists its point indices in ascending order. +struct AnmsGrid { + minx: f64, + miny: f64, + cell: f64, + gw: usize, + gh: usize, + cells: Vec>, +} + +impl AnmsGrid { + fn new(pts: &[Keypoint]) -> Self { + let finite = || pts.iter().filter(|p| p.x.is_finite() && p.y.is_finite()); + let (mut minx, mut miny, mut maxx, mut maxy) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for p in finite() { + minx = minx.min(p.x as f64); + maxx = maxx.max(p.x as f64); + miny = miny.min(p.y as f64); + maxy = maxy.max(p.y as f64); + } + if minx > maxx { + (minx, miny, maxx, maxy) = (0.0, 0.0, 0.0, 0.0); + } + let (w, h, n) = (maxx - minx, maxy - miny, pts.len().max(1) as f64); + let mut cell = (w * h / n * 2.0).sqrt().max(1.0); + while ((w / cell).floor() + 1.0) * ((h / cell).floor() + 1.0) > 4.0 * n { + cell *= 1.5; + } + let (gw, gh) = ((w / cell) as usize + 1, (h / cell) as usize + 1); + let mut g = AnmsGrid { minx, miny, cell, gw, gh, cells: vec![Vec::new(); gw * gh] }; + for (i, p) in pts.iter().enumerate() { + if p.x.is_finite() && p.y.is_finite() { + let (cx, cy) = g.locate(p); + if let Some(c) = g.cells.get_mut(cy * gw + cx) { + c.push(i); + } + } + } + g + } + + fn locate(&self, p: &Keypoint) -> (usize, usize) { + let cx = (((p.x as f64 - self.minx) / self.cell) as usize).min(self.gw - 1); + let cy = (((p.y as f64 - self.miny) / self.cell) as usize).min(self.gh - 1); + (cx, cy) + } + + /// Squared distance from `p` (= `pts[i]`) to the nearest earlier point with `strength * 0.9 > p.strength`. + fn nearest_stronger(&self, pts: &[Keypoint], i: usize, p: &Keypoint) -> f32 { + let mut best = f32::INFINITY; + if !(p.x.is_finite() && p.y.is_finite()) { + return best; + } + let (cx, cy) = self.locate(p); + let (cx, cy) = (cx as isize, cy as isize); + let rmax = cx.max(self.gw as isize - 1 - cx).max(cy).max(self.gh as isize - 1 - cy); + let scan = |x: isize, y: isize, best: &mut f32| { + if x < 0 || y < 0 || x >= self.gw as isize || y >= self.gh as isize { + return; + } + let Some(list) = self.cells.get(y as usize * self.gw + x as usize) else { return }; + for &j in list.get(..list.partition_point(|&j| j < i)).unwrap_or(&[]) { + let Some(q) = pts.get(j) else { continue }; + if q.strength * 0.9 > p.strength { + let d = (q.x - p.x).powi(2) + (q.y - p.y).powi(2); + *best = best.min(d); + } + } + }; + for r in 0..=rmax { + if r == 0 { + scan(cx, cy, &mut best); + } else { + for x in (cx - r).max(0)..=(cx + r).min(self.gw as isize - 1) { + scan(x, cy - r, &mut best); + scan(x, cy + r, &mut best); + } + for y in (cy - r + 1).max(0)..=(cy + r - 1).min(self.gh as isize - 1) { + scan(cx - r, y, &mut best); + scan(cx + r, y, &mut best); + } + } + // points in rings beyond `r` are at least `r * cell` away; 1 px absorbs rounding in the cell assignment + let m = (r as f64 * self.cell - 1.0).max(0.0); + if best as f64 <= m * m { + break; + } + } + best + } +} + fn descriptor(img: &Plane, x: f32, y: f32, angle: f32) -> Option<[f32; DESC_LEN]> { let (s, c) = angle.sin_cos(); let mut d = [0f32; DESC_LEN]; @@ -291,6 +385,62 @@ mod tests { }) } + fn anms_reference(pts: &[Keypoint], max: usize) -> Vec { + if pts.len() <= max { + return (0..pts.len()).collect(); + } + let radii: Vec = (0..pts.len()) + .map(|i| { + let p = pts[i]; + let mut best = f32::INFINITY; + for q in &pts[..i] { + if q.strength * 0.9 > p.strength { + let d = (q.x - p.x).powi(2) + (q.y - p.y).powi(2); + best = best.min(d); + } + } + best + }) + .collect(); + let mut idx: Vec = (0..pts.len()).collect(); + idx.sort_by(|&a, &b| radii[b].total_cmp(&radii[a]).then(a.cmp(&b))); + idx.truncate(max); + idx + } + + #[test] + fn grid_anms_matches_quadratic_reference() { + let mut state = 0x9E37_79B9_7F4A_7C15u64; + let mut rnd = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state >> 40) as f32 / (1u64 << 24) as f32 + }; + let kp = |x: f32, y: f32, strength: f32| Keypoint { x, y, level: 0, angle: 0.0, strength }; + let mut sets: Vec<(Vec, usize)> = Vec::new(); + sets.push(((0..3000).map(|_| kp(rnd() * 2000.0, rnd() * 1500.0, rnd())).collect(), 400)); + let centres: Vec<(f32, f32)> = (0..6).map(|_| (rnd() * 2000.0, rnd() * 1500.0)).collect(); + sets.push(( + (0..3000) + .map(|k| { + let (cx, cy) = centres[k % centres.len()]; + let g = |r: f32| (r - 0.5) * 60.0; + kp(cx + g(rnd() + rnd()), cy + g(rnd() + rnd()), rnd()) + }) + .collect(), + 400, + )); + sets.push(((0..3000).map(|_| kp((rnd() * 40.0).floor(), (rnd() * 30.0).floor(), rnd())).collect(), 400)); + sets.push(((0..3000).map(|_| kp(rnd() * 2000.0, rnd() * 1500.0, (rnd() * 4.0).floor() + 1.0)).collect(), 400)); + sets.push(((0..50).map(|_| kp(rnd() * 100.0, rnd() * 100.0, rnd())).collect(), 400)); + sets.push(((0..500).map(|_| kp(rnd() * 2000.0, rnd() * 1500.0, rnd())).collect(), 0)); + for (mut pts, max) in sets { + pts.sort_by(|a, b| b.strength.total_cmp(&a.strength)); + assert_eq!(anms(&pts, max), anms_reference(&pts, max)); + } + } + #[test] fn shifted_images_match_with_the_shift() { let a = pattern(400, 300, 0.0, 0.0); From 1e5d8294b81bd9c72821d044c7a149b774314cd8 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:29:56 +0100 Subject: [PATCH 54/63] Compare pooled CR3 warps with the unshaded fallback and isolate diagnostic runs --- crates/engine/src/camera_preview/proxy.rs | 16 +- crates/engine/src/camera_preview/tests.rs | 195 +++++++++++----------- docs/cr3-profile-alignment.md | 13 +- 3 files changed, 114 insertions(+), 110 deletions(-) diff --git a/crates/engine/src/camera_preview/proxy.rs b/crates/engine/src/camera_preview/proxy.rs index c82072397a..5079e400c9 100644 --- a/crates/engine/src/camera_preview/proxy.rs +++ b/crates/engine/src/camera_preview/proxy.rs @@ -490,24 +490,18 @@ pub(super) fn align_cr3_geometry<'a>( correction: Option<&'a lightcraft_develop::EmbeddedLens>, candidate_sensor: Option<&Rgb32f>, ) -> (Rgb32f, Rgb32f, ProxyFrame<'a>) { - let frame = |source: &Rgb32f| { - let framing = estimate_cr3_framing(source, reference); - (framing, framing.map(|framing| apply_cr3_framing(source, framing))) - }; - // Score the warp against the same shading on the original and framed baselines. + // The pooled proposal may include database shading. Its framing-only competitor + // must use the original sensor, exactly as it will be returned if the warp loses. + let framing = estimate_cr3_framing(&sensor, reference); + let fallback = framing.map(|framing| apply_cr3_framing(&sensor, framing)); let source = candidate_sensor.unwrap_or(&sensor); - let (mut framing, mut fallback) = frame(source); let orientation = lightcraft_geom::Orientation::Normal; if let Some(lens) = correction && let Some((aligned, mask, framing)) = - align_profile_geometry_against(source, &clipped, reference, lens, orientation, Some(fallback.as_ref().unwrap_or(source))) + align_profile_geometry_against(source, &clipped, reference, lens, orientation, Some(fallback.as_ref().unwrap_or(&sensor))) { return (aligned, mask, ProxyFrame { orientation, framing: Some(framing), lens: Some(lens) }); } - if candidate_sensor.is_some() { - // The pooled proposal was rejected. Restore the framing selected on the original samples. - (framing, fallback) = frame(&sensor); - } // The mask is needed only if the fallback wins; when no framing is accepted, // return both original allocations unchanged. let clipped = if let Some(framing) = framing { apply_cr3_framing(&clipped, framing) } else { clipped }; diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index bdab7b681c..1dd070e9c6 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -1542,6 +1542,28 @@ fn cr3_geometry_selects_matching_profile_with_one_search_per_geometry() { assert!(geometry_rms(&aligned, &expected) < 0.008, "matching proposal selected despite nonlinear JPEG tone"); } +#[test] +fn cr3_pooled_warp_must_match_the_unshaded_framing() { + let sensor = profile_geometry_scene(192, 128); + let mask = Rgb32f::new(sensor.width, sensor.height); + let mut lens = synthetic_profile_lens(); + lens.vignette = + Some(lightcraft_develop::EmbeddedVignette { k: [3.0, 0.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.5, 0.5), radius: 0.6 }); + let mut shaded = sensor.clone(); + correct_vignetting(&mut shaded, Some(&lens), lightcraft_geom::Orientation::Normal); + // The JPEG corrects only 53% of the profile distortion. The full proposal beats the + // vignette-corrected framing on both edge sets, but loses to the actual unshaded fallback. + let mut jpeg_lens = lens; + jpeg_lens.warp.as_mut().unwrap().planes = [[1.0212, -0.1272, 0.0424, 0.0, 0.0, 0.0]; 3]; + let reference = profile_geometry_target(&sensor, &jpeg_lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }); + let (fallback, _, _) = super::proxy::align_cr3_geometry(sensor.clone(), mask.clone(), &reference, None, None); + let (selected, _, frame) = super::proxy::align_cr3_geometry(sensor, mask, &reference, Some(&lens), Some(&shaded)); + assert!(frame.lens.is_none(), "the full warp is worse than the unshaded fallback"); + let [train_before, train_after, held_before, held_after] = super::proxy::geometry_framed_scores().unwrap(); + assert!(train_after < train_before && held_after < held_before); + assert_eq!(selected.data, fallback.data); +} + /// Check the full known valid crop, so the RMS cannot hide lost samples behind NaNs. fn assert_profile_geometry_mask(aligned: &Rgb32f, aligned_mask: &Rgb32f, expected_mask: &Rgb32f) { assert_eq!((aligned.width, aligned.height), (expected_mask.width, expected_mask.height)); @@ -1731,11 +1753,23 @@ fn diagnostic_tsv_field(value: &str) -> String { value.replace('\\', "\\\\").replace('\t', "\\t").replace('\r', "\\r").replace('\n', "\\n") } -/// Derive the PNG path from the native filename. Lossy text is used only for display in geometry.tsv. -fn diagnostic_png_path(output: &std::path::Path, name: &std::ffi::OsStr, label: &str) -> std::path::PathBuf { - let mut png = name.to_owned(); - png.push(format!("-{label}.png")); - output.join(png) +/// Keep the PNG component bounded even when the native input name is already at its filesystem limit. +fn diagnostic_artifact_id(name: &std::ffi::OsStr) -> String { + lightcraft_denoise_core::hash::sha256_hex(name.as_encoded_bytes()) +} + +/// Atomically claim an empty directory so a failed or concurrent run cannot alter earlier output. +fn diagnostic_run_dir(root: &std::path::Path) -> std::io::Result { + std::fs::create_dir_all(root)?; + let mut run = 1u64; + loop { + let path = root.join(format!("run-{run}")); + match std::fs::create_dir(&path) { + Ok(()) => return Ok(path), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => run += 1, + Err(error) => return Err(error), + } + } } #[cfg(any(unix, windows))] @@ -1751,35 +1785,19 @@ fn cr3_diagnostics_preserve_distinct_native_filenames() { use std::os::windows::ffi::OsStringExt; [0xd800, 0xd801].map(|unit| std::ffi::OsString::from_wide(&[65, unit, 46, 67, 82, 51])) }; - let output = std::path::Path::new("diagnostics"); assert_eq!(names[0].to_string_lossy(), names[1].to_string_lossy()); - for label in ["plain", "chosen", "jpeg"] { - assert_ne!(diagnostic_png_path(output, &names[0], label), diagnostic_png_path(output, &names[1], label)); - } -} - -/// Remove only this source's three owned output files; filesystem errors must stop the diagnostic. -fn remove_diagnostic_pngs(output: &std::path::Path, name: &std::ffi::OsStr) -> std::io::Result<()> { - for label in ["plain", "chosen", "jpeg"] { - match std::fs::remove_file(diagnostic_png_path(output, name, label)) { - Ok(()) => {} - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(error), - } - } - Ok(()) + assert_ne!(diagnostic_artifact_id(&names[0]), diagnostic_artifact_id(&names[1])); } /// Preserve missing-proxy cases in the diagnostic TSV without inventing geometry or fit results. /// `proxies` exposes no rejection reason, so the row records only which call returned `None`. fn diagnostic_proxies_or_report( - output: &std::path::Path, name: impl AsRef, raw: &RawImage, profile_warp: bool, plain: Option, chosen: Option, - report: &mut String, + report: &mut impl std::io::Write, ) -> std::io::Result> { let name = name.as_ref(); let status = match (plain, chosen) { @@ -1788,16 +1806,15 @@ fn diagnostic_proxies_or_report( (Some(_), None) => "missing_chosen_proxy", (None, None) => "missing_both_proxies", }; - remove_diagnostic_pngs(output, name)?; - let mut fields = vec![String::new(); 17]; + let mut fields = vec![String::new(); 18]; fields[0] = diagnostic_tsv_field(&name.to_string_lossy()); fields[1] = diagnostic_tsv_field(raw.metadata.model.as_deref().unwrap_or("")); fields[2] = format!("{:?}", raw.orientation); fields[3] = profile_warp.to_string(); fields[15] = status.to_owned(); fields[16] = "proxies returned None; underlying cause unavailable".to_owned(); - report.push_str(&fields.join("\t")); - report.push('\n'); + fields[17] = diagnostic_artifact_id(name); + writeln!(report, "{}", fields.join("\t"))?; Ok(None) } @@ -1814,7 +1831,6 @@ fn diagnostic_proxy_fixture() -> (RawImage, Vec) { /// Exercise the corpus diagnostic's actual proxy-result handling across missing and available inputs. #[test] fn cr3_diagnostics_report_missing_proxies_and_continue() { - let output = std::env::temp_dir().join(format!("lc-cr3-missing-{}", std::process::id())); let (mut raw, bytes) = diagnostic_proxy_fixture(); let transform = lightcraft_raw::color::camera_transform(&raw, D65); let available = proxies(&raw, &bytes, &transform, PROXY, 0.0, None, None).unwrap(); @@ -1830,33 +1846,34 @@ fn cr3_diagnostics_report_missing_proxies_and_continue() { assert!(!calibrated.matrix_is_fallback); let missing = proxies(&raw, &bytes, &calibrated, PROXY, 0.0, None, None); assert!(missing.is_none()); - let mut report = String::new(); + let mut report = Vec::new(); for (plain, chosen, status) in [ (missing.clone(), missing.clone(), "missing_both_proxies"), (missing.clone(), Some(available.clone()), "missing_plain_proxy"), (Some(available.clone()), missing, "missing_chosen_proxy"), ] { - assert!(diagnostic_proxies_or_report(&output, status, &raw, true, plain, chosen, &mut report).unwrap().is_none()); + assert!(diagnostic_proxies_or_report(status, &raw, true, plain, chosen, &mut report).unwrap().is_none()); } - let (plain, chosen) = - diagnostic_proxies_or_report(&output, "available", &raw, false, Some(available.clone()), Some(available.clone()), &mut report) - .unwrap() - .expect("a later usable file must still reach measurement and image export"); + let (plain, chosen) = diagnostic_proxies_or_report("available", &raw, false, Some(available.clone()), Some(available.clone()), &mut report) + .unwrap() + .expect("a later usable file must still reach measurement and image export"); let bits = |image: &Rgb32f| image.data.iter().flatten().map(|v| v.to_bits()).collect::>(); assert_eq!(bits(&plain.0), bits(&available.0)); assert_eq!(chosen.1.data, available.1.data); + let report = String::from_utf8(report).unwrap(); let rows: Vec<_> = report.lines().collect(); assert_eq!(rows.len(), 3, "available proxies must not create an unavailable row"); for row in rows { let fields: Vec<_> = row.split('\t').collect(); - assert_eq!(fields.len(), 17); + assert_eq!(fields.len(), 18); + assert_eq!(fields[17], diagnostic_artifact_id(fields[0].as_ref())); assert_eq!(fields[0], fields[15], "all three missing cases retain distinct statuses"); assert!(fields[4..15].iter().all(|v| v.is_empty()), "unavailable metrics, gates and fits stay empty"); assert_eq!(fields[16], "proxies returned None; underlying cause unavailable"); } } -/// Tabs, line endings and literal escape sequences remain distinguishable without changing the TSV schema. +/// Tabs, line endings and literal escape sequences remain distinguishable in the TSV. #[test] fn cr3_diagnostics_escape_text_fields_in_missing_rows() { let name = "A\tB\nC\rD\\t.CR3"; @@ -1865,52 +1882,40 @@ fn cr3_diagnostics_escape_text_fields_in_missing_rows() { assert_eq!(diagnostic_tsv_field(model), r"Camera\tmodel\nline\rreturn\\n"); let (mut raw, _) = diagnostic_proxy_fixture(); raw.metadata.model = Some(model.into()); - let output = std::env::temp_dir().join(format!("lc-cr3-tsv-{}", std::process::id())); - let mut report = String::new(); - assert!(diagnostic_proxies_or_report(&output, name, &raw, false, None, None, &mut report).unwrap().is_none()); + let mut report = Vec::new(); + assert!(diagnostic_proxies_or_report(name, &raw, false, None, None, &mut report).unwrap().is_none()); + let report = String::from_utf8(report).unwrap(); assert_eq!(report.lines().count(), 1); let fields: Vec<_> = report.trim_end_matches('\n').split('\t').collect(); - assert_eq!(fields.len(), 17); + assert_eq!(fields.len(), 18); assert_eq!(fields[0], diagnostic_tsv_field(name)); assert_eq!(fields[1], diagnostic_tsv_field(model)); assert_eq!(fields[15], "missing_both_proxies"); assert_eq!(fields[16], "proxies returned None; underlying cause unavailable"); } -/// A missing-proxy rerun removes old owned PNGs and preserves unrelated files and directories. +/// Reusing an output root for missing or incomplete measurements preserves every earlier run. #[test] -fn cr3_diagnostics_missing_rerun_removes_stale_pngs() { - let output = std::env::temp_dir().join(format!("lc-cr3-rerun-{}", std::process::id())); - std::fs::create_dir_all(&output).unwrap(); - let pixels = [23u8, 41, 59]; - let image = lightcraft_codecs::EncodeImage::new(1, 1, 3, lightcraft_codecs::Samples::U8(&pixels)); - let png = lightcraft_codecs::encode_png(&image, &Default::default()).unwrap(); - for label in ["plain", "chosen", "jpeg"] { - std::fs::write(output.join(format!("A.CR3-{label}.png")), &png).unwrap(); - } - std::fs::write(output.join("other.png"), &png).unwrap(); - std::fs::create_dir_all(output.join("other-directory")).unwrap(); +fn cr3_diagnostics_isolate_reruns_and_bound_png_names() { + let root = crate::tests_xmp::temp_dir("cr3-diagnostic-rerun"); + let previous = diagnostic_run_dir(&root).unwrap(); + let name = format!("{}.CR3", "x".repeat(251)); + let id = diagnostic_artifact_id(name.as_ref()); + let png_name = format!("{id}-chosen.png"); + std::fs::write(previous.join(&png_name), b"previous image").unwrap(); + std::fs::write(previous.join("geometry.tsv"), b"previous report").unwrap(); + + let current = diagnostic_run_dir(&root).unwrap(); let (raw, _) = diagnostic_proxy_fixture(); - let mut report = String::new(); - assert!(diagnostic_proxies_or_report(&output, "A.CR3", &raw, true, None, None, &mut report).unwrap().is_none()); - std::fs::write(output.join("geometry.tsv"), &report).unwrap(); - assert_eq!(std::fs::read_to_string(output.join("geometry.tsv")).unwrap(), report); - let fields: Vec<_> = report.trim_end_matches('\n').split('\t').collect(); - assert_eq!(fields.len(), 17); - assert_eq!(fields[0], "A.CR3"); - assert_eq!(fields[15], "missing_both_proxies"); - for label in ["plain", "chosen", "jpeg"] { - assert!(!output.join(format!("A.CR3-{label}.png")).exists(), "no earlier PNG can appear current"); - } - assert_eq!(std::fs::read(output.join("other.png")).unwrap(), png); - assert!(output.join("other-directory").is_dir()); - // A directory occupying an owned filename is an error, never a request for recursive deletion. - std::fs::create_dir(output.join("A.CR3-plain.png")).unwrap(); - let before = report.clone(); - assert!(diagnostic_proxies_or_report(&output, "A.CR3", &raw, true, None, None, &mut report).is_err()); - assert_eq!(report, before, "failed cleanup must not publish a misleading missing-result row"); - assert!(output.join("A.CR3-plain.png").is_dir()); - std::fs::remove_dir_all(output).unwrap(); + let report_path = current.join("geometry.tsv"); + let mut report = std::fs::File::create(&report_path).unwrap(); + assert!(diagnostic_proxies_or_report(&name, &raw, true, None, None, &mut report).unwrap().is_none()); + let row = std::fs::read_to_string(report_path).unwrap(); + assert_eq!(row.trim_end().split('\t').next_back(), Some(id.as_str())); + assert!(!current.join(&png_name).exists()); + assert_eq!(std::fs::read(previous.join(&png_name)).unwrap(), b"previous image"); + assert_eq!(std::fs::read(previous.join("geometry.tsv")).unwrap(), b"previous report"); + std::fs::remove_dir_all(root).unwrap(); } /// Opt-in diagnostic only: never opens the app or changes a catalogue. It exports the actual @@ -1918,13 +1923,14 @@ fn cr3_diagnostics_missing_rerun_removes_stale_pngs() { #[test] #[ignore = "explicit local corpus diagnostic; requires LIGHTCRAFT_CR3_DIAGNOSTICS and LIGHTCRAFT_CORPUS"] fn corpus_cr3_profile_geometry_diagnostics() { + use std::io::Write; + let output = std::env::var_os("LIGHTCRAFT_CR3_DIAGNOSTICS").expect("explicit diagnostics require an output directory"); let corpus = std::path::PathBuf::from(std::env::var_os("LIGHTCRAFT_CORPUS").expect("diagnostics require a corpus")); - let output = std::path::PathBuf::from(output); - std::fs::create_dir_all(&output).unwrap(); - let mut report = String::from( - "file\tmodel\torientation\tprofile_warp\tgeometry_accepted\tplain_alignment\tchosen_alignment\tplain_structure\tchosen_structure\tplain_pairs\tchosen_pairs\tplain_look\tchosen_look\tframed_gate_scores\toriginal_gate_scores\tstatus\treason\n", - ); + let output = diagnostic_run_dir(std::path::Path::new(&output)).unwrap(); + eprintln!("CR3 diagnostic output: {}", output.display()); + let mut report = std::fs::File::create(output.join("geometry.tsv")).unwrap(); + writeln!(report, "file\tmodel\torientation\tprofile_warp\tgeometry_accepted\tplain_alignment\tchosen_alignment\tplain_structure\tchosen_structure\tplain_pairs\tchosen_pairs\tplain_look\tchosen_look\tframed_gate_scores\toriginal_gate_scores\tstatus\treason\tartifact_id").unwrap(); let raw_dir = corpus.join("raw"); let mut paths: Vec<_> = std::fs::read_dir(&raw_dir) .unwrap_or_else(|e| panic!("{}: {e}", raw_dir.display())) @@ -1949,8 +1955,7 @@ fn corpus_cr3_profile_geometry_diagnostics() { let chosen = super::look_fit::look_proxies(&raw, &bytes, &transform, lens.as_ref(), correction.as_ref()); let name = path.file_name().unwrap(); let profile_warp = correction.as_ref().is_some_and(|l| l.warp.is_some()); - let Some((plain, chosen)) = diagnostic_proxies_or_report(&output, name, &raw, profile_warp, plain, chosen, &mut report).unwrap() else { - std::fs::write(output.join("geometry.tsv"), &report).unwrap(); + let Some((plain, chosen)) = diagnostic_proxies_or_report(name, &raw, profile_warp, plain, chosen, &mut report).unwrap() else { continue; }; let framed_scores = super::proxy::geometry_framed_scores(); @@ -1962,19 +1967,7 @@ fn corpus_cr3_profile_geometry_diagnostics() { }; let before = fit_preview(&raw, &bytes, &transform, lens.as_ref(), plain_correction.as_ref()).0.is_some(); let after = fit_preview(&raw, &bytes, &transform, lens.as_ref(), correction.as_ref()).0.is_some(); - report.push_str(&format!( - "{}\t{}\t{:?}\t{}\t{accepted}\t{:.6}\t{:.6}\t{}\t{}\t{}\t{}\t{before}\t{after}\t{framed_scores:?}\t{original_scores:?}\tmeasured\t\n", - diagnostic_tsv_field(&name.to_string_lossy()), - diagnostic_tsv_field(raw.metadata.model.as_deref().unwrap_or("")), - raw.orientation, - profile_warp, - alignment(&plain.0, &plain.1), - alignment(&chosen.0, &chosen.1), - structure_agrees(&plain.0, &plain.1), - structure_agrees(&chosen.0, &chosen.1), - pairs(&plain), - pairs(&chosen) - )); + let id = diagnostic_artifact_id(name); for (label, image) in [("plain", &plain.0), ("chosen", &chosen.0), ("jpeg", &chosen.1)] { let to_srgb = lightcraft_color::SRGB.from_xyz().mul(&REC2020.to_xyz()); let pixels: Vec = image @@ -1989,9 +1982,23 @@ fn corpus_cr3_profile_geometry_diagnostics() { }) .collect(); let image = lightcraft_codecs::EncodeImage::new(image.width as u32, image.height as u32, 3, lightcraft_codecs::Samples::U8(&pixels)); - std::fs::write(diagnostic_png_path(&output, name, label), lightcraft_codecs::encode_png(&image, &Default::default()).unwrap()).unwrap(); + std::fs::write(output.join(format!("{id}-{label}.png")), lightcraft_codecs::encode_png(&image, &Default::default()).unwrap()).unwrap(); } - std::fs::write(output.join("geometry.tsv"), &report).unwrap(); + writeln!( + report, + "{}\t{}\t{:?}\t{}\t{accepted}\t{:.6}\t{:.6}\t{}\t{}\t{}\t{}\t{before}\t{after}\t{framed_scores:?}\t{original_scores:?}\tmeasured\t\t{id}", + diagnostic_tsv_field(&name.to_string_lossy()), + diagnostic_tsv_field(raw.metadata.model.as_deref().unwrap_or("")), + raw.orientation, + profile_warp, + alignment(&plain.0, &plain.1), + alignment(&chosen.0, &chosen.1), + structure_agrees(&plain.0, &plain.1), + structure_agrees(&chosen.0, &chosen.1), + pairs(&plain), + pairs(&chosen) + ) + .unwrap(); } } diff --git a/docs/cr3-profile-alignment.md b/docs/cr3-profile-alignment.md index a06f462049..bdf64a2a90 100644 --- a/docs/cr3-profile-alignment.md +++ b/docs/cr3-profile-alignment.md @@ -29,8 +29,9 @@ for merge/DNG conversion. The DNG colour fit uses the external profile for corre without its vignette gains: the unchanged sensor samples and the DNG writer do not carry that database shading correction. The file-local fit measures the share of database shading visible in the JPEG after registration, using each pixel’s source position under the selected framing and warp. Pooled fits apply -the profile’s vignette to an accepted warp. A missing or rejected warp preserves both the unshaded colour -pairs and the tone samples from the original framing. +the profile’s vignette to the candidate warp. Its edge agreement must match or beat the framing +estimated from the original, unshaded sensor on both splits. A missing or rejected warp preserves +the unshaded colour pairs and tone samples from that framing. The loaded database semantic identity also invalidates camera render/view keys, Smart-preview headers and scan markers. Fresh original decodes retain the photo’s hot-pixel setting; offline proxies remain readable and cannot be relabelled as freshly fitted pixels. @@ -44,11 +45,13 @@ unknown under the upstream optional-crop API; this change adds no crop-factor fa Synthetic tests cover lens-only and lens-plus-framing acceptance, unrelated/flat/already aligned rejection, crop-relative profile orientation at multiple resolutions, clip-mask contributions, and the complete CR3 correspondence route for EXIF orientations 1–8 with non-unity white balance. -The opt-in `corpus_cr3_profile_geometry_diagnostics` test exports `geometry.tsv` and plain, -selected, and JPEG proxy PNGs when `LIGHTCRAFT_CR3_DIAGNOSTICS` names an output directory. +The opt-in `corpus_cr3_profile_geometry_diagnostics` test creates a fresh numbered directory +under `LIGHTCRAFT_CR3_DIAGNOSTICS` for each run. Its `geometry.tsv` lists each measured file +after all three proxy PNGs have been written. The final `artifact_id` column gives their shared +filename prefix, followed by `-plain.png`, `-chosen.png`, or `-jpeg.png`. The plain diagnostic route removes only the proposed profile warp. Both routes use the same lens vignetting data. It reads CR3 files from `$LIGHTCRAFT_CORPUS/raw` and the normal configured lens database. -The TSV appends `status` and `reason` columns. `measured` means both proxy calls returned +The TSV includes `status` and `reason` columns. `measured` means both proxy calls returned images; acceptance or rejection is recorded separately in the existing measurement columns. If either call returns no proxy, the row records `missing_plain_proxy`, `missing_chosen_proxy`, or `missing_both_proxies`, leaves all measurement fields empty, From 395402ead353ca236a49795a6e5d9db2a7a398c7 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Wed, 2 Dec 2026 13:16:05 +0530 Subject: [PATCH 55/63] GPU render: V14 heal spots read back only what each spot reads (#4960) Under process V14 the GPU renderer read the whole image back, ran the spots on the CPU and uploaded the whole image again: about 120 ms of transfer on a 24 MP export, even for one spot. Each spot now reads back only the rectangle it reads (its box and its source patch, `spots::spot_reads`), is healed on the CPU by the same code as the CPU renderer (`spots::apply_spot`, split out of `spots::apply`), and only its box is written back. The V13 path is unchanged. --- crates/gpu/src/render.rs | 56 +++++++- crates/gpu/tests/it/equivalence.rs | 5 +- crates/pipeline/src/spots.rs | 222 ++++++++++++++++++++--------- 3 files changed, 204 insertions(+), 79 deletions(-) diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 31489ba476..4f94600e1a 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -254,6 +254,30 @@ impl<'a> Cx<'a> { ); } + /// The rectangle `r` ([x0, y0, x1, y1), in pixels) of `b`, an interleaved RGB image `img_w` pixels + /// wide, read back (one row copy recorded per row, into a buffer of just the rectangle). + pub fn read_rect(&mut self, b: &Buf, img_w: usize, r: [usize; 4]) -> Rgb32f { + let (cw, ch) = (r[2] - r[0], r[3] - r[1]); + let out = self.gpu.buffer(cw * ch * 3); + let enc = self.enc.get_or_insert_with(|| self.gpu.encoder()); + for y in 0..ch { + let from = (((r[1] + y) * img_w + r[0]) * 3 * 4) as u64; + enc.copy_buffer_to_buffer(b.raw(), from, out.raw(), (y * cw * 3 * 4) as u64, (cw * 3 * 4) as u64); + } + self.read_rgb(&out, cw, ch) + } + + /// `src`, a compact image of the rectangle `r`, written into `dst`, an interleaved RGB image + /// `img_w` pixels wide (one row copy recorded per row). + pub fn write_rect(&mut self, src: &Buf, dst: &Buf, img_w: usize, r: [usize; 4]) { + let (cw, ch) = (r[2] - r[0], r[3] - r[1]); + let enc = self.enc.get_or_insert_with(|| self.gpu.encoder()); + for y in 0..ch { + let to = (((r[1] + y) * img_w + r[0]) * 3 * 4) as u64; + enc.copy_buffer_to_buffer(src.raw(), (y * cw * 3 * 4) as u64, dst.raw(), to, (cw * 3 * 4) as u64); + } + } + pub fn read_rgb(&mut self, b: &Buf, w: usize, h: usize) -> Rgb32f { Rgb32f { width: w, height: h, data: self.read(b, w * h * 3) } } @@ -1093,17 +1117,35 @@ fn defringe(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf { } /// Spot removal (`spots::apply`), spot by spot on `img` in place: each spot reads the image as -/// the earlier ones left it. +/// the earlier ones left it. Process V14's heal (a membrane solve per spot) has no kernel yet: each +/// of its spots runs on the CPU on the rectangle it reads, the only part of the image that crosses +/// to the host and back; the rest of the render stays on the device. fn spots(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf { use lightcraft_pipeline::spots; let (w, h) = (plan.w, plan.h); let method = spots::HealMethod::of(&plan.settings); - if method == spots::HealMethod::Pinned && !plan.settings.spots.is_empty() { - // process V14's heal (a membrane solve per spot) has no kernel yet: the spots run on the CPU - // between the device stages, the rest of the render stays on the device - let mut host = cx.read_rgb(&img, w, h); - spots::apply(&mut host, &plan.settings.spots, &plan.frame, plan.px_per_long, method); - return cx.gpu.upload(rgb_words(&host)); + if method == spots::HealMethod::Pinned { + for spot in &plan.settings.spots { + let Some(l) = spots::layout(spot, &plan.frame, w, h, plan.px_per_long) else { continue }; + let Some(&first) = l.pts.first() else { continue }; + let offset = match l.offset { + Some(o) => o, + None => auto_source(cx, &img, w, h, first, l.r), + }; + let r = spots::spot_reads(&l, offset, method, w, h); + let mut crop = cx.read_rect(&img, w, r); + let (bx, by, bw, bh) = (l.bx, l.by, l.bw, l.bh); + spots::apply_spot(&mut crop, (r[0], r[1]), l, offset, method); + // only the spot's box changed + let mut words = Vec::with_capacity(bw * bh * 3); + for y in by..by + bh { + let row = ((y - r[1]) * crop.width + (bx - r[0])) * 3; + words.extend_from_slice(&rgb_words(&crop)[row..row + bw * 3]); + } + let up = cx.gpu.upload(&words); + cx.write_rect(&up, &img, w, [bx, by, bx + bw, by + bh]); + } + return img; } for spot in &plan.settings.spots { let Some(l) = spots::layout(spot, &plan.frame, w, h, plan.px_per_long) else { continue }; diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index a36bff5def..cb7707caef 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -1527,8 +1527,8 @@ fn soft_proofs_match() { /// Spot removal on the device: Clone, Heal and Remove (automatic source, scored on the device), /// brushed strokes, overlapping spots (each reads what the earlier ones left), feather 0 and -/// spots cut by the image edge; on process V13 by the device kernels, on V14 (the pinned heal) on the -/// CPU between the device stages. +/// spots cut by the image edge and sources past it; on process V13 by the device kernels, on V14 (the +/// pinned heal) by each spot's box read back, healed on the CPU and written back. #[test] fn spots_match() { if !gpu() { @@ -1552,6 +1552,7 @@ fn spots_match() { ("remove near the edge (auto)", vec![spot(SpotMode::Remove, &[(0.04, 0.5)], 0.03, 50.0, None)]), ("brushed heal stroke", vec![spot(SpotMode::Heal, &[(0.2, 0.7), (0.3, 0.72), (0.4, 0.69)], 0.02, 30.0, Some((0.0, -0.15)))]), ("feather 0, half opacity", vec![Spot { opacity: 50.0, ..spot(SpotMode::Clone, &[(0.7, 0.3)], 0.04, 0.0, Some((-0.2, 0.0))) }]), + ("source past the edge", vec![spot(SpotMode::Heal, &[(0.1, 0.5)], 0.04, 50.0, Some((-0.2, 0.0)))]), ("cut by the edge", vec![spot(SpotMode::Heal, &[(0.99, 0.02)], 0.05, 50.0, Some((-0.2, 0.2)))]), ( "overlapping, auto after manual", diff --git a/crates/pipeline/src/spots.rs b/crates/pipeline/src/spots.rs index 80acb439a5..1f31d782ea 100644 --- a/crates/pipeline/src/spots.rs +++ b/crates/pipeline/src/spots.rs @@ -436,84 +436,120 @@ fn pinned_distances(l: &SpotLayout, method: HealMethod) -> Vec { /// is [`HealMethod::of`] the photo's settings. pub fn apply(img: &mut Rgb32f, spots: &[Spot], frame: &Frame, ppl: f64, method: HealMethod) { let (w, h) = (img.width, img.height); - let pinned = method == HealMethod::Pinned; for spot in spots { let Some(l) = layout(spot, frame, w, h, ppl) else { continue; }; - // (empty unless the pinned heal will use it: a box too big for its working memory gets the - // averaged heal without the plane being built) - let dist = pinned_distances(&l, method); - let pinned_heal = !dist.is_empty(); - let SpotLayout { r, pts, offset, bx: bx0, by: by0, bw, bh, inner, opacity, heal, fill } = l; - let Some(&first) = pts.first() else { continue }; - let offset = offset.unwrap_or_else(|| auto_source(img, first, r)); - // (V14 reads whole pixels: between them, bilinear sampling averages the source's grain away) - let offset = if pinned { (offset.0.round(), offset.1.round()) } else { offset }; - // alpha of the stroke and the source patch in the box - let mut alpha = vec![0.0f32; bw * bh]; - let mut src = vec![[0.0f32; 3]; bw * bh]; - let mut tgt = vec![[0.0f32; 3]; bw * bh]; - for y in 0..bh { - for x in 0..bw { - let (px, py) = ((bx0 + x) as f32 + 0.5, (by0 + y) as f32 + 0.5); - let d = dist.get(y * bw + x).copied().unwrap_or_else(|| distance(&pts, px, py)); - alpha[y * bw + x] = (1.0 - smooth(inner, r, d)) * opacity; - src[y * bw + x] = img.sample_bilinear(px + offset.0, py + offset.1); - tgt[y * bw + x] = img.get(bx0 + x, by0 + y); - } + let Some(&first) = l.pts.first() else { continue }; + let offset = l.offset.unwrap_or_else(|| auto_source(img, first, l.r)); + apply_spot(img, (0, 0), l, offset, method); + } +} + +/// The pixels [`apply_spot`] reads for `l` with source `offset` in a `w × h` output: the spot's box +/// and its source patch (whole pixels under [`HealMethod::Pinned`], also the bilinear neighbour +/// otherwise), clamped to the image, as [x0, y0, x1, y1). A source past the image's edge reads the +/// edge pixel, which the clamped rectangle holds, so a crop of it renders as the whole image does. +pub fn spot_reads(l: &SpotLayout, offset: (f32, f32), method: HealMethod, w: usize, h: usize) -> [usize; 4] { + let whole = [0, 0, w, h]; + let t = [l.bx, l.by, l.bx + l.bw, l.by + l.bh].map(|v| v as f64); + let reach = |d: f32| { + let d = f64::from(d); + match method { + HealMethod::Pinned => (d.round(), d.round()), + HealMethod::Averaged => (d.floor(), d.ceil() + 1.0), } - if fill { - fill_box(&mut src, &tgt, &alpha, bw, bh); + }; + let ((x0, x1), (y0, y1)) = (reach(offset.0), reach(offset.1)); + let s = [t[0] + x0, t[1] + y0, t[2] + x1, t[3] + y1]; + if !s.iter().all(|v| v.is_finite()) { + return whole; + } + // (a pixel more on every side) + let r = [t[0].min(s[0]) - 1.0, t[1].min(s[1]) - 1.0, t[2].max(s[2]) + 1.0, t[3].max(s[3]) + 1.0]; + // Where the source lies past the image's edge, this clamps to the edge itself: `sample_bilinear` + // clamps its coordinate to the image and reads the edge pixel there, and so does a crop that + // starts or ends on that edge. + let clamp = |v: f64, hi: usize| v.clamp(0.0, hi as f64) as usize; + [clamp(r[0], w), clamp(r[1], h), clamp(r[2], w), clamp(r[3], h)] +} + +/// One spot of [`apply`] on `img`, a crop of the output whose pixel (0, 0) is output pixel `origin`; +/// `l` is in output pixels and `offset` is the resolved source offset (auto-chosen already when the +/// spot's is `None`). The crop must hold [`spot_reads`] of the spot. +pub fn apply_spot(img: &mut Rgb32f, origin: (usize, usize), l: SpotLayout, offset: (f32, f32), method: HealMethod) { + let pinned = method == HealMethod::Pinned; + // (empty unless the pinned heal will use it: a box too big for its working memory gets the + // averaged heal without the plane being built) + let dist = pinned_distances(&l, method); + let pinned_heal = !dist.is_empty(); + let SpotLayout { r, pts, bx: bx0, by: by0, bw, bh, inner, opacity, heal, fill, .. } = l; + // (V14 reads whole pixels: between them, bilinear sampling averages the source's grain away) + let offset = if pinned { (offset.0.round(), offset.1.round()) } else { offset }; + let (ox, oy) = origin; + // alpha of the stroke and the source patch in the box + let mut alpha = vec![0.0f32; bw * bh]; + let mut src = vec![[0.0f32; 3]; bw * bh]; + let mut tgt = vec![[0.0f32; 3]; bw * bh]; + for y in 0..bh { + for x in 0..bw { + let (px, py) = ((bx0 + x) as f32 + 0.5, (by0 + y) as f32 + 0.5); + let d = dist.get(y * bw + x).copied().unwrap_or_else(|| distance(&pts, px, py)); + alpha[y * bw + x] = (1.0 - smooth(inner, r, d)) * opacity; + src[y * bw + x] = img.sample_bilinear(px + offset.0 - ox as f32, py + offset.1 - oy as f32); + tgt[y * bw + x] = img.get(bx0 + x - ox, by0 + y - oy); } - let healed = if pinned_heal { pinned::heal(&pinned::Patch { w: bw, h: bh, src: &src, tgt: &tgt, dist: &dist, r }) } else { None }; - let pinned_here = healed.is_some(); - if let Some(healed) = healed { - src = healed; - } - let low = if heal && !pinned_here { - // Tone correction from the spot's *surroundings* only: normalized convolution of - // (target − source) over pixels outside the stroke (a membrane-like interpolation). - let outside: Vec = alpha.iter().map(|a| if *a < 0.02 { 1.0 } else { 0.0 }).collect(); - let diff = Rgb32f { - width: bw, - height: bh, - data: tgt.iter().zip(&src).zip(&outside).map(|((t, s), m)| [(t[0] - s[0]) * m, (t[1] - s[1]) * m, (t[2] - s[2]) * m]).collect(), - }; - let wts = lightcraft_raster::Plane { width: bw, height: bh, data: outside }; - let sigma = (r * 0.6).max(1.0); - let (bd, bm) = (lightcraft_raster::blur::gaussian(&diff, sigma), lightcraft_raster::blur::gaussian(&wts, sigma)); - Some(Rgb32f { - width: bw, - height: bh, - data: bd - .data - .iter() - .zip(&bm.data) - .map(|(d, m)| { - let m = m.max(1e-4); - [d[0] / m, d[1] / m, d[2] / m] - }) - .collect(), - }) - } else { - None + } + if fill { + fill_box(&mut src, &tgt, &alpha, bw, bh); + } + let healed = if pinned_heal { pinned::heal(&pinned::Patch { w: bw, h: bh, src: &src, tgt: &tgt, dist: &dist, r }) } else { None }; + let pinned_here = healed.is_some(); + if let Some(healed) = healed { + src = healed; + } + let low = if heal && !pinned_here { + // Tone correction from the spot's *surroundings* only: normalized convolution of + // (target − source) over pixels outside the stroke (a membrane-like interpolation). + let outside: Vec = alpha.iter().map(|a| if *a < 0.02 { 1.0 } else { 0.0 }).collect(); + let diff = Rgb32f { + width: bw, + height: bh, + data: tgt.iter().zip(&src).zip(&outside).map(|((t, s), m)| [(t[0] - s[0]) * m, (t[1] - s[1]) * m, (t[2] - s[2]) * m]).collect(), }; - for y in 0..bh { - for x in 0..bw { - let i = y * bw + x; - let a = alpha[i]; - if a <= 0.0 { - continue; - } - let mut v = src[i]; - if let Some(l) = &low { - let d = l.data[i]; - v = [v[0] + d[0], v[1] + d[1], v[2] + d[2]]; - } - let t = tgt[i]; - img.set(bx0 + x, by0 + y, [t[0] + (v[0] - t[0]) * a, t[1] + (v[1] - t[1]) * a, t[2] + (v[2] - t[2]) * a].map(|c| c.max(0.0))); + let wts = lightcraft_raster::Plane { width: bw, height: bh, data: outside }; + let sigma = (r * 0.6).max(1.0); + let (bd, bm) = (lightcraft_raster::blur::gaussian(&diff, sigma), lightcraft_raster::blur::gaussian(&wts, sigma)); + Some(Rgb32f { + width: bw, + height: bh, + data: bd + .data + .iter() + .zip(&bm.data) + .map(|(d, m)| { + let m = m.max(1e-4); + [d[0] / m, d[1] / m, d[2] / m] + }) + .collect(), + }) + } else { + None + }; + for y in 0..bh { + for x in 0..bw { + let i = y * bw + x; + let a = alpha[i]; + if a <= 0.0 { + continue; } + let mut v = src[i]; + if let Some(l) = &low { + let d = l.data[i]; + v = [v[0] + d[0], v[1] + d[1], v[2] + d[2]]; + } + let t = tgt[i]; + img.set(bx0 + x - ox, by0 + y - oy, [t[0] + (v[0] - t[0]) * a, t[1] + (v[1] - t[1]) * a, t[2] + (v[2] - t[2]) * a].map(|c| c.max(0.0))); } } } @@ -595,6 +631,52 @@ mod tests { } } + /// Each spot on a crop of what [`spot_reads`] says it reads gives the same pixels in its box as + /// [`apply`] on the whole image: Heal and Clone, either heal, and a spot cut by the edge whose + /// source lies past it. + #[test] + fn a_spot_on_its_reads_matches_the_whole_image() { + let (w, h) = (96, 64); + let frame = Frame::new(w, h, &DevelopSettings::default(), true); + let ppl = frame.px_per_long(w); + let spot = |mode, x: f64, y: f64, off: (f64, f64)| Spot { + mode, + points: vec![Point::new(x, y)], + size: 6.0 / w as f64, + feather: 50.0, + opacity: 100.0, + source_offset: Some(Point::new(off.0, off.1)), + }; + let spots = [ + spot(SpotMode::Heal, 0.5, 0.5, (0.17, 0.06)), + spot(SpotMode::Clone, 0.3, 0.4, (-0.11, 0.13)), + spot(SpotMode::Heal, 0.99, 0.02, (-0.2, 0.2)), + spot(SpotMode::Heal, 0.03, 0.9, (-0.4, 0.3)), + ]; + for method in BOTH { + for spot in &spots { + let original = Rgb32f::from_fn(w, h, |x, y| { + [0.2 + (x * 7 % 13) as f32 / 40.0, 0.1 + (y * 5 % 11) as f32 / 30.0, 0.3 + ((x + y) % 5) as f32 / 20.0] + }); + let mut whole = original.clone(); + apply(&mut whole, std::slice::from_ref(spot), &frame, ppl, method); + let l = layout(spot, &frame, w, h, ppl).expect("on the image"); + let offset = l.offset.expect("manual source"); + let [x0, y0, x1, y1] = spot_reads(&l, offset, method, w, h); + let mut crop = Rgb32f::from_fn(x1 - x0, y1 - y0, |x, y| original.get(x0 + x, y0 + y)); + let (bx, by, bw, bh) = (l.bx, l.by, l.bw, l.bh); + apply_spot(&mut crop, (x0, y0), l, offset, method); + let mut pasted = original.clone(); + for y in by..by + bh { + for x in bx..bx + bw { + pasted.set(x, y, crop.get(x - x0, y - y0)); + } + } + assert_eq!(pasted.data, whole.data, "{:?} spot at {:?} ({method:?})", spot.mode, spot.points[0]); + } + } + } + /// Vertical stripes (period `period` px) with a black blot over the middle. fn striped_with_blot(w: usize, h: usize, period: usize) -> Rgb32f { let mut img = Rgb32f::from_fn(w, h, |x, _| if (x / period).is_multiple_of(2) { [0.2; 3] } else { [0.7; 3] }); From 4a4391816d25d7bef505b2c6db6e9ab0d07c116e Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Wed, 2 Dec 2026 08:58:54 +0100 Subject: [PATCH 56/63] Synchronize denoiser model-change tests with worker completion --- crates/engine/src/denoise/session.rs | 6 ++++ crates/engine/src/denoise/state.rs | 5 +++ crates/engine/src/tests/denoise.rs | 47 +++++++++++++++++++++------- 3 files changed, 47 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/denoise/session.rs b/crates/engine/src/denoise/session.rs index 1704268456..42721bf038 100644 --- a/crates/engine/src/denoise/session.rs +++ b/crates/engine/src/denoise/session.rs @@ -360,6 +360,8 @@ impl Session { let outcome: Arc>> = Arc::new(Mutex::new(None)); let (key, product) = (spec.key.clone(), spec.product.clone()); let (worker_progress, worker_outcome) = (progress.clone(), outcome.clone()); + #[cfg(test)] + let outcome_ready = self.denoise.next_outcome_ready.take(); let started = std::thread::Builder::new().name("denoise".into()).stack_size(STACK).spawn(move || { let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| make_product(&spec, Some(&worker_progress)))); let o = match result { @@ -370,6 +372,10 @@ impl Session { Err(_) => Outcome::Failed("the denoiser stopped unexpectedly".into(), false), }; *worker_outcome.lock().unwrap_or_else(PoisonError::into_inner) = Some(o); + #[cfg(test)] + if let Some(ready) = outcome_ready { + let _ = ready.send(()); + } }); match started { Ok(_) => { diff --git a/crates/engine/src/denoise/state.rs b/crates/engine/src/denoise/state.rs index 7b780e4a22..b8a169d2c6 100644 --- a/crates/engine/src/denoise/state.rs +++ b/crates/engine/src/denoise/state.rs @@ -121,6 +121,9 @@ pub(crate) struct State { pub(super) reindexed: Option<(u64, web_time::Instant)>, pub(super) queue: VecDeque, pub(super) running: Option, + /// Signals once the next worker's outcome is available to the frame pump. + #[cfg(test)] + pub(crate) next_outcome_ready: Option>, pub(super) failed: HashMap, /// Counts every change of what is ready, so the interface knows to draw again. pub generation: u64, @@ -148,6 +151,8 @@ impl Default for State { reindexed: None, queue: VecDeque::new(), running: None, + #[cfg(test)] + next_outcome_ready: None, failed: HashMap::new(), generation: 0, made: 0, diff --git a/crates/engine/src/tests/denoise.rs b/crates/engine/src/tests/denoise.rs index b164c7c77d..8f8bee230b 100644 --- a/crates/engine/src/tests/denoise.rs +++ b/crates/engine/src/tests/denoise.rs @@ -1151,10 +1151,16 @@ fn mixed_queue_uses_each_photos_pin_and_changed_versions_never_fall_back() { let _ = std::fs::remove_dir_all(x.dir); } +fn watch_next_denoise_outcome(s: &mut Session) -> std::sync::mpsc::Receiver<()> { + let (tx, rx) = std::sync::mpsc::channel(); + s.denoise.next_outcome_ready = Some(tx); + rx +} + #[test] fn changing_photo_pin_rejects_a_previous_model_job_in_flight() { use std::sync::{Mutex, mpsc}; - use std::time::Duration; + let timeout = denoise_ready_timeout(); let mut x = setup("per-photo-inflight", true); let id = photo(&x.s); set_amount(&mut x.s, 80.0); @@ -1166,23 +1172,20 @@ fn changing_photo_pin_rejects_a_previous_model_job_in_flight() { 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())?; + release_rx.lock().unwrap().recv_timeout(timeout).map_err(|e| e.to_string())?; Ok(Arc::new(Dim { runs: runs.clone() }) as Arc) }); + let finished = watch_next_denoise_outcome(&mut x.s); x.s.execute("denoise.queue", &json!({"ids":[id.0]})).unwrap(); x.s.execute("denoise.pump", &json!({"pace":"full"})).unwrap(); - entered_rx.recv_timeout(Duration::from_secs(10)).unwrap(); - let oldkey = x.s.denoise_running_product().unwrap().1; + entered_rx.recv_timeout(timeout).unwrap(); + let (product, oldkey) = x.s.denoise_running_product().unwrap(); x.s.execute("denoise.photo.model", &json!({"id":id.0,"model":"builtin"})).unwrap(); release_tx.send(()).unwrap(); - 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)); - } + finished.recv_timeout(timeout).expect("cancelled worker did not report its outcome"); + x.s.denoise_pump(crate::denoise::Pace::Pause); assert!(x.s.denoise_running_json().is_null()); + assert!(!lightcraft_denoise::product::is_current(&product, &oldkey), "cancellation during loading must prevent the old product write"); assert_ne!(x.s.media.denoise.spec(id).map(|s| s.key.as_str()), Some(oldkey.as_str())); assert_eq!(x.s.denoise_made(), 0, "old model result cannot count as the new photo edit"); assert_eq!(x.s.denoise_photo_state(id), PhotoState::Idle); @@ -1192,6 +1195,28 @@ fn changing_photo_pin_rejects_a_previous_model_job_in_flight() { let _ = std::fs::remove_dir_all(x.dir); } +#[test] +fn changing_photo_pin_discards_a_finished_result_before_the_next_pump() { + let mut x = setup("per-photo-unpolled", true); + let id = photo(&x.s); + set_amount(&mut x.s, 80.0); + x.s.execute("denoise.settings", &json!({"auto":false})).unwrap(); + let finished = watch_next_denoise_outcome(&mut x.s); + x.s.execute("denoise.queue", &json!({"ids":[id.0]})).unwrap(); + x.s.denoise_pump(crate::denoise::Pace::Full); + let (product, oldkey) = x.s.denoise_running_product().unwrap(); + finished.recv_timeout(denoise_ready_timeout()).expect("worker did not report its outcome"); + assert!(lightcraft_denoise::product::is_current(&product, &oldkey), "the old model successfully wrote a real product"); + x.s.execute("denoise.photo.model", &json!({"id":id.0,"model":"builtin"})).unwrap(); + x.s.denoise_pump(crate::denoise::Pace::Pause); + assert!(x.s.denoise_running_json().is_null()); + assert_eq!(x.s.denoise_made(), 0, "a completed result for the old model must be discarded"); + assert_eq!(x.s.denoise_photo_state(id), PhotoState::Idle); + assert_ne!(x.s.media.denoise.spec(id).map(|s| s.key.as_str()), Some(oldkey.as_str())); + x.s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(x.dir); +} + #[test] fn changed_installed_bytes_fail_sha_verification_instead_of_using_another_model() { let mut x = setup("per-photo-sha", true); From a5c5311dd23994d972c29b15c1efd3f3b849b8f8 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:16:16 +0100 Subject: [PATCH 57/63] Verify fixed-mount CR3 correspondence through the shared lens lookup --- crates/engine/src/camera_preview/tests.rs | 46 +++++++++++++++++------ docs/cr3-profile-alignment.md | 12 +++--- 2 files changed, 42 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index 1dd070e9c6..02478d3b40 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -1363,8 +1363,8 @@ fn assert_file_owned_dng_vignette_contract( #[test] fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() { const DB: &str = r#" - SyntheticUncalibratedT1.5 - SyntheticSynthetic 18mmT1.5 + SyntheticUncalibratedcompact1.5 + SyntheticSynthetic 18mm18mm f/3.5compact1.5 "#; const CHILD: &str = "LIGHTCRAFT_TEST_COLOUR_TAG_LOOKUP_CHILD"; @@ -1409,14 +1409,19 @@ fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() let mut target = profile_geometry_target(&sensor, &lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }); target.map_in_place(|p| p.map(|v| v.powf(0.7))); use craft_tiff::{IfdBuilder, Value, tags}; - let mut ifd = IfdBuilder::new(); - ifd.set(tags::MAKE, Value::Ascii("Synthetic".into())); - ifd.set(tags::MODEL, Value::Ascii("Uncalibrated".into())); - let mut exif = IfdBuilder::new(); - exif.set(tags::FOCAL_LENGTH, Value::Rational(vec![(18, 1)])); - exif.set(tags::LENS_MODEL, Value::Ascii("Synthetic 18mm".into())); - ifd.set_child(tags::EXIF_IFD, exif); - let file = profile_geometry_file(&target, ifd); + let shot = |jpeg: &Rgb32f, identity: Option<(u16, Value)>| { + let mut ifd = IfdBuilder::new(); + ifd.set(tags::MAKE, Value::Ascii("Synthetic".into())); + ifd.set(tags::MODEL, Value::Ascii("Uncalibrated".into())); + let mut exif = IfdBuilder::new(); + exif.set(tags::FOCAL_LENGTH, Value::Rational(vec![(18, 1)])); + if let Some((tag, value)) = identity { + exif.set(tag, value); + } + ifd.set_child(tags::EXIF_IFD, exif); + profile_geometry_file(jpeg, ifd) + }; + let file = shot(&target, Some((tags::LENS_MODEL, Value::Ascii("Synthetic 18mm".into())))); let mut cr3 = raw.clone(); cr3.format = RawFormat::Cr3; let (plain, reference, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, None).unwrap(); @@ -1466,7 +1471,26 @@ fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() let warp_only = lightcraft_develop::EmbeddedLens { vignette: None, ..resolved }; let expected = super::colour::starting_colour_tags_with_correction(&mut cr3.clone(), &file, Some(&warp_only)); assert_ne!(expected, super::colour::starting_colour_tags_with_correction(&mut cr3.clone(), &file, None)); - assert_eq!(starting_colour_tags(&mut cr3, &file), expected, "public CR3 DNG lookup keeps the warp and excludes database shading"); + assert_eq!(starting_colour_tags(&mut cr3.clone(), &file), expected, "public CR3 DNG lookup keeps the warp and excludes database shading"); + + // Both the unique fixed mount and an explicit specification alias identify this same lens. + let spec = |aperture| Some((tags::LENS_SPECIFICATION, Value::Rational(vec![(18, 1), (18, 1), (aperture, 10), (aperture, 10)]))); + for identity in [None, spec(35)] { + let variant = shot(&target, identity); + assert_eq!(correspondence_correction(&cr3, &variant), Some(resolved)); + assert_eq!(starting_colour_tags(&mut cr3.clone(), &variant), expected); + } + assert!(correspondence_correction(&cr3, &shot(&target, spec(28))).is_none(), "an unmatched specification prevents mount fallback"); + + // The unnamed lens still resolves when the JPEG uses plain sensor geometry. Its warp and + // database shading must then leave the pooled samples identical to the no-profile fallback. + let plain_file = shot(&sensor, None); + let correction = correspondence_correction(&cr3, &plain_file).unwrap(); + let fallback = profile_samples(&cr3, &plain_file, None, None).unwrap(); + let selected = profile_samples(&cr3, &plain_file, None, Some(&correction)).unwrap(); + assert!(!fallback.colour.is_empty() && !fallback.tone.is_empty()); + assert_eq!(selected.colour, fallback.colour); + assert_eq!(selected.tone, fallback.tone); } #[test] diff --git a/docs/cr3-profile-alignment.md b/docs/cr3-profile-alignment.md index bdf64a2a90..44e5811309 100644 --- a/docs/cr3-profile-alignment.md +++ b/docs/cr3-profile-alignment.md @@ -35,12 +35,14 @@ the unshaded colour pairs and tone samples from that framing. The loaded database semantic identity also invalidates camera render/view keys, Smart-preview headers and scan markers. Fresh original decodes retain the photo’s hot-pixel setting; offline proxies remain readable and cannot be relabelled as freshly fitted pixels. -Embedded vignetting is still applied at the source before geometry. No camera allowlist, -new profile matching rules, or weaker acceptance gate is introduced. Other RAW formats continue to use the existing correspondence and fixed-mount lookup rules. +Embedded vignetting is still applied at the source before geometry. -Profile resolution uses the shared lens resolver, including the downloaded database or -`LIGHTCRAFT_LENSFUN_DIR` override and its reload support. Unknown crop factors remain -unknown under the upstream optional-crop API; this change adds no crop-factor fallback. +Profile resolution follows the [shared lens lookup rules](lens-profiles.md). With neither a +lens model nor a lens specification, a CR3 can propose the only profile on its camera’s exact, +lowercase-initial fixed mount. An ambiguous mount or an unmatched specification keeps the +framing fallback. A fixed-mount match must pass the same JPEG edge checks as a named lens or +an explicit specification alias. The lookup uses the downloaded database or `LIGHTCRAFT_LENSFUN_DIR` +override and supports reloading. Unknown crop factors remain unknown. Synthetic tests cover lens-only and lens-plus-framing acceptance, unrelated/flat/already aligned rejection, crop-relative profile orientation at multiple resolutions, clip-mask contributions, From 95fa91445bf2a24287d477378d1e97ecc3385602 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:44:31 +0100 Subject: [PATCH 58/63] Distinguish frame and calibration crop factors in CR3 lookup --- docs/cr3-profile-alignment.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/cr3-profile-alignment.md b/docs/cr3-profile-alignment.md index 44e5811309..23e72e81e9 100644 --- a/docs/cr3-profile-alignment.md +++ b/docs/cr3-profile-alignment.md @@ -42,7 +42,9 @@ lens model nor a lens specification, a CR3 can propose the only profile on its c lowercase-initial fixed mount. An ambiguous mount or an unmatched specification keeps the framing fallback. A fixed-mount match must pass the same JPEG edge checks as a named lens or an explicit specification alias. The lookup uses the downloaded database or `LIGHTCRAFT_LENSFUN_DIR` -override and supports reloading. Unknown crop factors remain unknown. +override and supports reloading. When the camera database has no crop factor, the lookup can +derive the frame crop factor by dividing the 35 mm-equivalent focal length by the actual focal +length. Applying a lens profile requires a known calibration crop factor from the database. Synthetic tests cover lens-only and lens-plus-framing acceptance, unrelated/flat/already aligned rejection, crop-relative profile orientation at multiple resolutions, clip-mask contributions, From 29ab3f7916eaa9a822cb16458e93738c2d83ac95 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:11:58 +0100 Subject: [PATCH 59/63] merge: ANMS ring search skips ring edges outside the grid (#4953) --- crates/merge/src/features.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/merge/src/features.rs b/crates/merge/src/features.rs index 70d5690de8..9e2083637f 100644 --- a/crates/merge/src/features.rs +++ b/crates/merge/src/features.rs @@ -263,13 +263,18 @@ impl AnmsGrid { if r == 0 { scan(cx, cy, &mut best); } else { - for x in (cx - r).max(0)..=(cx + r).min(self.gw as isize - 1) { - scan(x, cy - r, &mut best); - scan(x, cy + r, &mut best); + // (only the ring's edges that lie inside the grid: a long thin grid would otherwise + // walk the out-of-grid edges cell by cell on every ring) + let (xs, ys) = ((cx - r).max(0)..=(cx + r).min(self.gw as isize - 1), (cy - r + 1).max(0)..=(cy + r - 1).min(self.gh as isize - 1)); + for y in [cy - r, cy + r].into_iter().filter(|y| (0..self.gh as isize).contains(y)) { + for x in xs.clone() { + scan(x, y, &mut best); + } } - for y in (cy - r + 1).max(0)..=(cy + r - 1).min(self.gh as isize - 1) { - scan(cx - r, y, &mut best); - scan(cx + r, y, &mut best); + for x in [cx - r, cx + r].into_iter().filter(|x| (0..self.gw as isize).contains(x)) { + for y in ys.clone() { + scan(x, y, &mut best); + } } } // points in rings beyond `r` are at least `r * cell` away; 1 px absorbs rounding in the cell assignment @@ -433,6 +438,8 @@ mod tests { )); sets.push(((0..3000).map(|_| kp((rnd() * 40.0).floor(), (rnd() * 30.0).floor(), rnd())).collect(), 400)); sets.push(((0..3000).map(|_| kp(rnd() * 2000.0, rnd() * 1500.0, (rnd() * 4.0).floor() + 1.0)).collect(), 400)); + // one row of points: a grid one cell tall, where the rings' top and bottom edges are outside it + sets.push(((0..3000).map(|i| kp(32.0 + 4.0 * i as f32, 32.0, rnd())).collect(), 400)); sets.push(((0..50).map(|_| kp(rnd() * 100.0, rnd() * 100.0, rnd())).collect(), 400)); sets.push(((0..500).map(|_| kp(rnd() * 2000.0, rnd() * 1500.0, rnd())).collect(), 0)); for (mut pts, max) in sets { From 8bae0315c71cada6c46b7cb03ec516d16b2de62c Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:12:39 +0100 Subject: [PATCH 60/63] gpu: readback pool test counts only reusable staging buffers and holds the device test lock (#4958) --- crates/gpu/src/ctx.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index 5135ebaa80..ca4200927c 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -1350,6 +1350,8 @@ mod tests { /// Readback staging buffers are pooled and reused, and never handed out as storage buffers. #[test] fn readback_staging_buffers_are_pooled_apart_from_storage() { + // (serialised with the tests that change the pool limit, which would trim the pool under it) + let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let Some(g) = crate::device() else { lightcraft_testkit::skip!(Gpu, "no GPU device"); return; @@ -1357,9 +1359,11 @@ mod tests { let len = 1_234_567usize; let want = (len * 4) as u64; let mapped = wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST; + // only the staging buffers this readback could reuse (`take_pooled`'s size band), so another + // test's readback of a different size on the shared device doesn't change the count let count = || { let f = g.free.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - f.iter().filter(|b| b.0.usage() == mapped && b.0.size() >= want).count() + f.iter().filter(|b| b.0.usage() == mapped && b.0.size() >= want && b.0.size() <= want + want / 4).count() }; let data: Vec = (0..len as u32).map(|i| i.wrapping_mul(2_654_435_761)).collect(); let b = g.upload(&data); From 7c133410f12b4adb04a932742e9877313f01e047 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:13:07 +0100 Subject: [PATCH 61/63] lens blur: sum each cell row from only the bands that reach it, and free each level's partials once summed (#4949) --- crates/pipeline/src/lens_blur.rs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/crates/pipeline/src/lens_blur.rs b/crates/pipeline/src/lens_blur.rs index 2e9e2775a6..4d03b9e0bd 100644 --- a/crates/pipeline/src/lens_blur.rs +++ b/crates/pipeline/src/lens_blur.rs @@ -612,20 +612,32 @@ fn levels_banded(img: &Rgb32f, coc: &[f32], r: f32, gain: &(impl Fn([f32; 3]) -> } } }); + // each level's band partials, in band order, moved out so a level's are freed once it is summed + let mut parts: Vec> = (0..grids.len()).map(|_| Vec::with_capacity(bands.len())).collect(); + for band in bands { + for (level, bc) in parts.iter_mut().zip(band) { + level.push(bc); + } + } grids .iter() - .enumerate() - .map(|(k, g)| { + .zip(parts) + .map(|(g, parts)| { let mut cells = vec![[0f32; 4]; g.lw * g.lh]; - // a cell row is the sum of what the bands (in order) added to it + // one past the last cell row a band's partial holds + let end = |bc: &BandCells| bc.cy_lo + bc.cells.len().checked_div(g.lw).unwrap_or(0); + // a cell row is the sum of what the bands (in order) added to it; the bands' cell rows + // only grow, so the ones that reach row `cy` (one or two) are found by bisection crate::for_rows(&mut cells, g.lw, |cy, row| { - for bc in bands.iter().filter_map(|b| b.get(k)) { + let first = parts.partition_point(|bc| end(bc) <= cy); + for bc in parts.get(first..).unwrap_or(&[]).iter().take_while(|bc| bc.cy_lo <= cy) { let Some(part) = cy.checked_sub(bc.cy_lo).and_then(|r| bc.cells.get(r * g.lw..(r + 1) * g.lw)) else { continue }; for (cell, p) in row.iter_mut().zip(part) { *cell = std::array::from_fn(|c| cell[c] + p[c]); } } }); + drop(parts); Level { img: disc(&cells, g.lw, g.lh, g.radius / g.f as f32), f: g.f, shift: g.shift } }) .collect() From e944599ef4d663d00255348720babba8a3749cfd Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Wed, 2 Dec 2026 08:34:06 -0600 Subject: [PATCH 62/63] Share one GPU device in the thumbnail tests (#4992) * Share one GPU device in the thumbnail tests gpu_drawn_fixture created a new wgpu instance, adapter and device for every test. Its vkEnumeratePhysicalDevices unloads drivers that expose no device, while another test thread's render calls vkSetDebugUtilsObjectNameEXT on the process-wide device; Vulkan loaders before 1.4.345 then walk freed loader state and crash with SIGSEGV (KhronosGroup/Vulkan-Loader#1863). The fixture now reuses the render device (gpu::shared_device), or one process-wide device that is never dropped. render::thumbnail_tests looped 200 times (2 test threads): 31/200 SIGSEGV before, 0/200 after. * Keep the thumbnail tests' fallback device from racing the render device gpu::shared_device returned None while the render device could still be created later (GPU rendering turned off by another test through app.gpu, the window's device pending), and gpu_drawn_fixture then created a Vulkan instance of its own while another thread's render could create and use the render device: the Vulkan-Loader#1863 race again. shared_device now creates the render device whatever the preference, and waits while the window's device is being adopted, so None means no render device can exist in this process any more (switched off by the environment, creation failed, or the process is ending). The fixture creates its own device only when the environment switches the GPU off or creating the device failed: once the process is ending it skips the test rather than create a device during teardown. The wait for the window's device has a 60 s deadline and then panics, since returning None would let the fixture race the window's device. shared_device overrides the switch that keeps the GPU off (also after a launch that crashed creating the device, #136), so the app must not have it: it now exists only in the gpu crate's tests and with a new test-support feature, off by default, which only dev-dependencies turn on (ui-egui's, and the gpu crate's own for tests/shared_device.rs). The app's and the workspace's normal builds don't have it. The fixture's texture work runs inside error scopes, so an error in it fails the test instead of stopping GPU rendering for every test in the process. tests/shared_device.rs: with GPU rendering off and the window's device pending, shared_device waits for the adoption and settles the render device. render::thumbnail_tests looped 100 times (2 test threads): 100/100 passed; with LIGHTCRAFT_GPU=0 (the fixture's own device) 50/50 passed. --- Cargo.lock | 2 + crates/gpu/Cargo.toml | 5 ++ crates/gpu/src/lib.rs | 58 ++++++++++++++++ crates/gpu/tests/shared_device.rs | 32 +++++++++ crates/ui-egui/Cargo.toml | 3 +- crates/ui-egui/src/render/thumbnail_tests.rs | 69 +++++++++++++++----- 6 files changed, 150 insertions(+), 19 deletions(-) create mode 100644 crates/gpu/tests/shared_device.rs diff --git a/Cargo.lock b/Cargo.lock index cfde6aecf5..28011d3b5c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4288,6 +4288,7 @@ dependencies = [ "lightcraft-develop", "lightcraft-faces", "lightcraft-geom", + "lightcraft-gpu", "lightcraft-pipeline", "lightcraft-raster", "lightcraft-raw", @@ -4496,6 +4497,7 @@ dependencies = [ "lightcraft-engine", "lightcraft-faces", "lightcraft-geom", + "lightcraft-gpu", "lightcraft-merge", "lightcraft-meta", "lightcraft-pipeline", diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml index 689d0e64ed..4512242e6f 100644 --- a/crates/gpu/Cargo.toml +++ b/crates/gpu/Cargo.toml @@ -32,12 +32,17 @@ default = [] denoise = ["dep:lightcraft-denoise", "lightcraft-denoise/runtime"] # SAM 3's vision backbone on the GPU (`sam3`); the engine's `sam` feature turns it on sam = ["dep:lightcraft-segment"] +# `shared_device`, for other crates' tests: only ever turned on from [dev-dependencies] (it overrides +# the switch that keeps the GPU off, so the app must not have it) +test-support = [] [dev-dependencies] # tests record why they skip (`cargo xtask ci` lists the skips) lightcraft-testkit = { workspace = true } lightcraft-scenes = { workspace = true } lightcraft-raw = { workspace = true } +# this crate's integration tests use `shared_device` too (tests/shared_device.rs) +lightcraft-gpu = { workspace = true, features = ["test-support"] } [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] # the SAM 3 backbone test and benchmark compare against the candle backbone diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 4fbef07c78..0b1e581ae8 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -320,6 +320,13 @@ pub(crate) fn device() -> Option<&'static ctx::Gpu> { if WINDOW_PENDING.load(Ordering::Acquire) { return None; } + create_device() +} + +/// Create the device (once; later calls return the first outcome), or `None` when creating it +/// failed or the process is ending. +#[cfg(not(target_arch = "wasm32"))] +fn create_device() -> Option<&'static ctx::Gpu> { // creating the device is a long call into the driver: not once the process is ending let _work = exit::enter()?; GPU.get_or_init(|| { @@ -342,6 +349,57 @@ pub(crate) fn existing_device() -> Option<&'static ctx::Gpu> { GPU.get().and_then(|g| g.as_ref().ok()) } +/// For tests (hidden, like [`inject_fault`]): the render device and its queue, so a test that needs +/// a device draws on this one instead of creating another. Creating another Vulkan instance while +/// this device is in use on another thread crashes Vulkan loaders before 1.4.345 +/// (KhronosGroup/Vulkan-Loader#1863: `vkEnumeratePhysicalDevices` unloads drivers, and frees loader +/// state, that a device call on another thread is walking). +/// +/// Unlike a render, this creates the device while GPU rendering is turned off by the preference +/// (which other tests switch: `app.gpu`), and waits while the window's device is being adopted. So +/// `None` means no render device can exist in this process any more: the environment switches the +/// GPU off, creating the device failed, or the process is ending. Only then may a test create a +/// device of its own without racing this one. +/// +/// What the caller does on the device is its own: [`wait_idle`] doesn't count it, and an error +/// outside the caller's error scopes stops GPU rendering for the whole process. +/// +/// When the process is ending ([`shutting_down`]) a test must not create a device of its own either: +/// it would be created during teardown. +/// +/// The wait for the window's device has a deadline (60 s): past it this panics rather than return +/// `None`, which would let the test create a device that races the window's. +/// +/// Never call this from the app: it overrides the switch that keeps the GPU off, including after a +/// launch that crashed while creating the device (#136). So it exists only in this crate's tests and +/// with the `test-support` feature, which only dev-dependencies turn on. +#[doc(hidden)] +#[cfg(all(not(target_arch = "wasm32"), any(test, feature = "test-support")))] +#[allow(clippy::panic, reason = "a window device that stays pending fails the test that waits for it")] +pub fn shared_device() -> Option<(wgpu::Device, wgpu::Queue)> { + if env_disabled() { + return None; + } + // (the adoption clears it whatever the outcome, and the window's device may become this one; + // it creates a device and builds the kernels, which can take a while on a slow or busy machine) + const WAIT: std::time::Duration = std::time::Duration::from_secs(60); + let deadline = std::time::Instant::now() + WAIT; + while WINDOW_PENDING.load(Ordering::Acquire) && GPU.get().is_none() { + if std::time::Instant::now() >= deadline { + panic!( + "gpu::shared_device: the window's device was still pending after {WAIT:?} \ + (set_window_device_pending(true) without an adoption or set_window_device_pending(false))" + ); + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let g = match GPU.get() { + Some(g) => g.as_ref().ok(), + None => create_device(), + }; + g.map(|g| (g.device.clone(), g.queue.clone())) +} + /// Create the device and compile the kernels on a background thread now (once the window is up), /// so the first render doesn't wait ~0.3–0.4 s for it and the UI thread never does. Does nothing /// while GPU rendering is turned off. Repeated calls start one thread at most. diff --git a/crates/gpu/tests/shared_device.rs b/crates/gpu/tests/shared_device.rs new file mode 100644 index 0000000000..0de25c2538 --- /dev/null +++ b/crates/gpu/tests/shared_device.rs @@ -0,0 +1,32 @@ +//! Review of PR #4992: a test that needs a device takes the render device (`shared_device`) and +//! creates one of its own only when no render device can exist in the process (a second Vulkan +//! instance races the render device: Vulkan-Loader#1863). Another test turning GPU rendering off, +//! or the window's device being adopted, must not make `shared_device` say there is none while a +//! render could still create it. One test in its own process: the switches are process-wide. + +use std::time::Duration; + +#[test] +fn the_shared_device_is_settled_while_gpu_rendering_is_off_or_the_window_device_pending() { + lightcraft_gpu::set_window_device_pending(true); + lightcraft_gpu::set_enabled(false); + let t0 = std::time::Instant::now(); + let adoption = std::thread::spawn(|| { + std::thread::sleep(Duration::from_millis(200)); + // (the adoption couldn't start) + lightcraft_gpu::set_window_device_pending(false); + }); + let shared = lightcraft_gpu::shared_device(); + let waited = t0.elapsed(); + adoption.join().unwrap(); + if lightcraft_gpu::env_off_reason().is_none() { + assert!(waited >= Duration::from_millis(200), "waited for the window's device ({waited:?})"); + } + // created, or failed for good, or switched off by the environment: no render device can appear later + assert!(lightcraft_gpu::ready(), "the render device is settled"); + lightcraft_gpu::set_enabled(true); + assert_eq!(shared.is_some(), lightcraft_gpu::available(), "the device renders use"); + if shared.is_none() { + lightcraft_testkit::skip!(Gpu, "no GPU device: {:?}", lightcraft_gpu::unavailable_reason()); + } +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 83a18de446..2bce6a814e 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -42,7 +42,8 @@ lightcraft-denoise = { workspace = true, features = ["runtime"] } lightcraft-codecs = { workspace = true } lightcraft-faces = { workspace = true } lightcraft-merge = { workspace = true } -# a device for the GPU-resident view test (`render.rs`) +# a device for the GPU-resident view test (`render.rs`): the render device (`shared_device`) +lightcraft-gpu = { workspace = true, features = ["test-support"] } pollster = { workspace = true } [build-dependencies] diff --git a/crates/ui-egui/src/render/thumbnail_tests.rs b/crates/ui-egui/src/render/thumbnail_tests.rs index e167edf315..bc66c3982d 100644 --- a/crates/ui-egui/src/render/thumbnail_tests.rs +++ b/crates/ui-egui/src/render/thumbnail_tests.rs @@ -490,22 +490,44 @@ impl ScreenTextures for TestScreen { /// from the GPU has its pixels. Before, a mid-drag `ui.screenshot {"headless": true}` showed the /// photo as a white rectangle: the GPU-resident draft left no CPU copy (review of PR #1065). /// The test fixture with a small GPU texture (5 × 3 known texels) and a [`TestScreen`] that -/// records the ids it frees; `None` without a GPU adapter. +/// records the ids it frees; `Err` (why the test is skipped) without a GPU adapter, or when the +/// process is ending. #[cfg(not(target_arch = "wasm32"))] #[allow(clippy::type_complexity)] fn gpu_drawn_fixture( freed: std::sync::Arc>>, -) -> Option<(crate::LightcraftApp, std::rc::Rc>, egui::Context, lightcraft_engine::media::ScreenFrame)> { +) -> Result<(crate::LightcraftApp, std::rc::Rc>, egui::Context, lightcraft_engine::media::ScreenFrame), &'static str> { use lightcraft_engine::gpu::wgpu; - let device = (|| { - let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); - desc.backends = lightcraft_engine::gpu::backend::window_backends(); - desc.backend_options = lightcraft_engine::gpu::backend::backend_options(); - let instance = wgpu::Instance::new(desc); - let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; - pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("test window"), ..Default::default() })).ok() - })(); - let (device, queue) = device?; + // The render device (created if need be, also while another test has turned GPU rendering + // off), or, only when no render device can exist in this process (the environment switches the + // GPU off, or creating it failed), one device of our own for the whole process, never dropped. + // A Vulkan instance created while other tests render on the render device on other threads + // crashed Vulkan loaders before 1.4.345 with SIGSEGV (Vulkan-Loader#1863: + // `vkEnumeratePhysicalDevices` unloads drivers that another thread's device call is walking). + static OWN: std::sync::OnceLock> = std::sync::OnceLock::new(); + let (device, queue) = match lightcraft_gpu::shared_device() { + Some(shared) => shared, + // (`gpu::begin_shutdown`: a device of our own would be created during teardown) + None if lightcraft_gpu::shutting_down() => return Err("the process is ending: no device is created any more"), + None => OWN + .get_or_init(|| { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = lightcraft_engine::gpu::backend::window_backends(); + desc.backend_options = lightcraft_engine::gpu::backend::backend_options(); + let instance = wgpu::Instance::new(desc); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; + pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("test window"), ..Default::default() })).ok() + }) + .clone() + .ok_or("no GPU adapter")?, + }; + // (an error outside a scope on the render device stops GPU rendering for every test in the + // process: this one's are caught here, on this thread) + let scopes = [ + device.push_error_scope(wgpu::ErrorFilter::Validation), + device.push_error_scope(wgpu::ErrorFilter::OutOfMemory), + device.push_error_scope(wgpu::ErrorFilter::Internal), + ]; let (w, h) = (5usize, 3usize); let texture = device.create_texture(&wgpu::TextureDescriptor { label: None, @@ -524,9 +546,14 @@ fn gpu_drawn_fixture( wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w as u32 * 4), rows_per_image: Some(h as u32) }, wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 }, ); + for scope in scopes.into_iter().rev() { + if let Some(e) = pollster::block_on(scope.pop()) { + panic!("the test texture: {e}"); + } + } let (mut app, work, ctx) = fixture(); app.renderer.set_screen_textures(Box::new(TestScreen(device, queue, freed))); - Some((app, work, ctx, lightcraft_engine::media::ScreenFrame { texture, width: w, height: h })) + Ok((app, work, ctx, lightcraft_engine::media::ScreenFrame { texture, width: w, height: h })) } /// A headless screenshot (driven by the control channel: `keep_pixels`) of a view drawn straight @@ -535,9 +562,12 @@ fn gpu_drawn_fixture( #[cfg(not(target_arch = "wasm32"))] #[test] fn a_headless_screenshot_reads_back_a_view_drawn_from_the_gpu() { - let Some((mut app, work, ctx, frame)) = gpu_drawn_fixture(Default::default()) else { - lightcraft_testkit::skip!(Gpu, "no GPU adapter"); - return; + let (mut app, work, ctx, frame) = match gpu_drawn_fixture(Default::default()) { + Ok(fixture) => fixture, + Err(why) => { + lightcraft_testkit::skip!(Gpu, "{why}"); + return; + } }; let (w, h) = (frame.width, frame.height); assert!(app.renderer.keep_pixels); @@ -563,9 +593,12 @@ fn a_headless_screenshot_reads_back_a_view_drawn_from_the_gpu() { #[test] fn releasing_a_slot_frees_its_gpu_texture() { let freed = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); - let Some((mut app, work, ctx, frame)) = gpu_drawn_fixture(freed.clone()) else { - lightcraft_testkit::skip!(Gpu, "no GPU adapter"); - return; + let (mut app, work, ctx, frame) = match gpu_drawn_fixture(freed.clone()) { + Ok(fixture) => fixture, + Err(why) => { + lightcraft_testkit::skip!(Gpu, "{why}"); + return; + } }; let job = app.session.render_job(PhotoId(1), 64, 64, false, true).unwrap().draft(); app.renderer.request(Slot::Main, job, 100); From e3e76fd0f0a07af1c6d9d2009433721724357b3c Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Wed, 2 Dec 2026 08:34:26 -0600 Subject: [PATCH 63/63] Wait for the GPU warm-up before a test or headless process ends (#620) (#4697) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * LR-BEHAV-GPU: no GPU warm-up is still loading the driver when a test or headless process ends (issue #620) The first frame starts the GPU device warm-up on a thread of its own. A process that ended a few milliseconds later, as every test does under nextest, could exit while that thread was inside the Vulkan loader's dlopen of the driver, running libLLVM's initializers: a SIGSEGV after the test had passed, or a hang. Only the window's exit (LightcraftApp::shutdown) waited for GPU work. warm_up now counts as in flight from the moment it is called, before its thread exists, and wait_warm_up waits for it. Dropping a LightcraftApp waits for it, bounded, unless shutdown already ran. * LR-BEHAV-GPU: warm_up counts as in flight before it marks itself started (issue #620) A second warm_up call racing the first could find it marked started and return before the first had entered the gate, so a host dropping its app right after that second call saw no warm-up in flight. The gate is now entered first, a call that starts nothing drops its entry, and a closed gate starts nothing. * LR-BEHAV-GPU: the app waits for the GPU warm-up when dropped on native builds only (issue #620) The web build has no warm-up thread (warm_up and wait_warm_up do nothing there), and the web host replaces the app's UI state by moving it out of the app, which a Drop impl forbids (E0509 in the wasm check). * LR-BEHAV-GPU: a deterministic test for the app's warm-up wait on drop (issue #620) Fred's review of #4697: the first regression test could pass without exercising the wait — ready() || !enabled() also holds when the warm-up finished or never started, and no pending warm-up was ever established. The gpu crate exposes doc-hidden test support, hold_warm_up_for_test(), entering the same gate the real warm_up enters: a substitute warm-up the caller holds. The test proves it is in flight (wait_warm_up(ZERO) is false), builds an app that never ran a frame on another thread (the app is not Send — its host-service callbacks are not — so it is built there), and verifies with channel synchronization that dropping the app does not return while the hold is kept, and returns once it is released. Without the wait in Drop for LightcraftApp it fails at that assertion; with it, it passes. No GPU, no device, no timing beyond a one-second observation window whose proof is the release. --------- Co-authored-by: skylartaylor --- crates/gpu/src/lib.rs | 53 ++++++++++++++++++++++++- crates/ui-egui/src/app.rs | 15 +++++++ crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/gpu_warm_up.rs | 44 ++++++++++++++++++++ docs/gpu-pipeline.md | 6 ++- 5 files changed, 117 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/src/tests/gpu_warm_up.rs diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 0b1e581ae8..c7840f55f4 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -291,6 +291,11 @@ fn env_disabled() -> bool { #[cfg(not(target_arch = "wasm32"))] static GPU: std::sync::OnceLock> = std::sync::OnceLock::new(); +/// A [`warm_up`] thread in flight. [`warm_up`] enters it before the thread exists, so +/// [`wait_warm_up`] sees the warm-up from the moment [`warm_up`] returns. +#[cfg(not(target_arch = "wasm32"))] +static WARM_UP: exit::Gate = exit::Gate::new(); + /// Set while [`adopt_window_device`] is about to run or running: [`device`] and [`warm_up`] then /// don't create a device of their own (review of PR #1065: the settings' warm-up raced the /// adoption thread and could win, so the window's device went unused). @@ -407,10 +412,16 @@ pub fn warm_up() { #[cfg(not(target_arch = "wasm32"))] if !env_disabled() && ENABLED.load(Ordering::SeqCst) && GPU.get().is_none() && !WINDOW_PENDING.load(Ordering::Acquire) { static STARTED: AtomicBool = AtomicBool::new(false); + // In flight from here, before `STARTED` is set and before the thread exists: a host that ends + // the process right after any `warm_up` returns (this one, or a concurrent call that finds + // the thread starting) must find it with `wait_warm_up`. A closed gate starts nothing; a call + // that starts nothing drops its token again, and a failed spawn drops it with the closure. + let Some(in_flight) = WARM_UP.enter() else { return }; if STARTED.swap(true, Ordering::SeqCst) { return; } - let spawned = std::thread::Builder::new().name("lc-gpu-init".into()).spawn(|| { + let spawned = std::thread::Builder::new().name("lc-gpu-init".into()).spawn(move || { + let _in_flight = in_flight; loop { let _ = device(); if GPU.get().is_some() || shutting_down() || env_disabled() { @@ -445,6 +456,46 @@ pub fn ready() -> bool { } } +/// Wait up to `timeout` for a [`warm_up`] thread to finish (the device created, or given up). +/// `true`: none is running. That thread loads the driver, and a process that ends meanwhile crashes +/// inside it (issue #620): a host that ends the process without [`begin_shutdown`] and +/// [`wait_idle`] (a test, a headless run) waits for it first. +pub fn wait_warm_up(timeout: std::time::Duration) -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + WARM_UP.wait_idle(timeout) + } + #[cfg(target_arch = "wasm32")] + { + let _ = timeout; + true + } +} + +/// The guard [`hold_warm_up_for_test`] returns: the substitute warm-up, held until it is dropped. +#[cfg(not(target_arch = "wasm32"))] +struct WarmUpHold(Option>); + +/// A substitute device warm-up in flight, held until the returned guard is dropped — the same +/// gate the real [`warm_up`] enters, so a caller can prove a warm-up is pending and that a wait +/// waits for it, without a GPU, a device or a race. Test support for one test, +/// `tests::gpu_warm_up::dropping_the_app_waits_for_a_warm_up_that_is_in_flight` in +/// lightcraft-ui-egui (a `#[cfg(test)]` helper here would not be visible to that crate's test +/// build); not for production code — a real warm-up is started with [`warm_up`]. `None` only +/// when the process is ending, when no warm-up can be in flight anyway. +#[cfg(not(target_arch = "wasm32"))] +#[doc(hidden)] +pub fn hold_warm_up_for_test() -> Option { + WARM_UP.enter().map(|work| WarmUpHold(Some(work))) +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for WarmUpHold { + fn drop(&mut self) { + drop(self.0.take()); + } +} + /// Whether a usable GPU adapter exists and GPU rendering is enabled (creates the device on first /// use). pub fn available() -> bool { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 0222d940ca..3bfe7e0587 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -775,6 +775,21 @@ impl LightcraftApp { } } +/// The app's first frame starts the GPU device warm-up (`app.gpu`), on a thread that loads the +/// driver. A process that ends while it does crashes inside the driver (issue #620; in CI, tests +/// killed by SIGSEGV after they had passed). The window ends through [`LightcraftApp::shutdown`], +/// which decides that itself; any other end (a test returning, a headless run) passes through here +/// first, so it waits for the warm-up, bounded. (Native only: there is no warm-up thread on the web, +/// and the web host moves fields out of the app.) +#[cfg(not(target_arch = "wasm32"))] +impl Drop for LightcraftApp { + fn drop(&mut self) { + if !lightcraft_engine::gpu::shutting_down() { + let _ = lightcraft_engine::gpu::wait_warm_up(std::time::Duration::from_secs(30)); + } + } +} + /// "Found 3 faces in 2 photos" for a `faces.detect` result. pub(crate) fn detect_summary(v: &Value) -> String { let photos = v["photos"].as_array().map(Vec::as_slice).unwrap_or_default(); diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index cbfaa30fc6..3b6c2edcc5 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -55,6 +55,7 @@ mod filmstrip_drag; mod find_similar; mod focus_point; mod folder_drop; +mod gpu_warm_up; mod grading; mod grid; mod grid_badges; diff --git a/crates/ui-egui/src/tests/gpu_warm_up.rs b/crates/ui-egui/src/tests/gpu_warm_up.rs new file mode 100644 index 0000000000..ddea42e74d --- /dev/null +++ b/crates/ui-egui/src/tests/gpu_warm_up.rs @@ -0,0 +1,44 @@ +//! A test is a process of its own under nextest, and that process ends as soon as the test +//! returns. The app's first frame starts the GPU device warm-up on a thread of its own; a process +//! that ends while that thread is still loading the driver crashes there (issue #620; in CI, +//! tests killed by SIGSEGV after they had passed). So dropping the app waits for a warm-up that +//! is still in flight. This exercises that wait with a substitute warm-up held on the same gate, +//! so it needs no GPU, no device and no race. + +use std::sync::mpsc; +use std::time::Duration; + +use crate::{LightcraftApp, Services}; + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn dropping_the_app_waits_for_a_warm_up_that_is_in_flight() { + // In flight from here until `hold` is dropped (test support in the gpu crate, on the gate the + // real warm-up enters) + let hold = lightcraft_engine::gpu::hold_warm_up_for_test().expect("the warm-up gate is open in a test"); + assert!(!lightcraft_engine::gpu::wait_warm_up(Duration::ZERO), "the substitute warm-up is in flight"); + let (tx, rx) = mpsc::channel::<&'static str>(); + let dropping = std::thread::spawn(move || { + // Built here, not moved in: `LightcraftApp` is not `Send` (its host-service callbacks are + // not), and this test does not need it to be. An app that never ran a frame has nothing of + // its own pending, so the only thing that can hold up its drop is the warm-up wait. + let app = LightcraftApp::new(lightcraft_engine::Session::new(), Services { png: None, ..Default::default() }); + tx.send("dropping").unwrap(); + drop(app); + tx.send("dropped").unwrap(); + }); + assert_eq!(rx.recv_timeout(Duration::from_secs(30)).unwrap(), "dropping"); + // The drop has not returned while the warm-up is held. The one second is only the + // observation window for that — the thread is already past "dropping", sent after the + // construction and just before the drop, so an unwaiting drop would have torn the app down + // and returned well inside it — and the proof is the step after: releasing the hold is what + // lets the drop return. + assert_eq!( + rx.recv_timeout(Duration::from_secs(1)), + Err(mpsc::RecvTimeoutError::Timeout), + "dropping the app returned while a warm-up was in flight" + ); + drop(hold); + assert_eq!(rx.recv_timeout(Duration::from_secs(30)).unwrap(), "dropped"); + dropping.join().unwrap(); +} diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index 5f9b12c888..6c71af7085 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -113,7 +113,11 @@ after settings and library are saved): `gpu::begin_shutdown()` — from then on on the CPU — then the render pool stops (queued jobs dropped, running ones waited for) and `gpu::wait_idle` waits for GPU work on other threads (export, denoise, the device warm-up). One deadline of 2 s covers it all; past it the app quits anyway. A job pool that is dropped (headless -hosts, tests) waits for its running jobs the same way (`JobPool::shutdown`, `crates/preview/src/pool.rs`). +hosts, tests) waits for its running jobs the same way (`JobPool::shutdown`, `crates/preview/src/pool.rs`), +and a dropped `LightcraftApp` waits, bounded, for a device warm-up still loading the driver +(`gpu::wait_warm_up`; the warm-up counts from the moment `gpu::warm_up` is called) unless `shutdown` +already ran. Without that, a test process ending a few milliseconds after its first frame crashed or +hung inside the Vulkan loader as it opened the driver. **Crash sentinel.** The desktop app writes `gpu-init.marker` into its settings folder (next to `ui.json`: `%APPDATA%\LightCraft`, `~/Library/Application Support/LightCraft`,