From 2eef428d407a6954bd692466508dca9de622f498 Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Fri, 16 Oct 2026 08:31:57 +0200 Subject: [PATCH 01/98] Import: preserve embedded rating, flag and label from file metadata --- crates/engine/src/files.rs | 19 +++++++++++++++++++ crates/engine/src/import.rs | 9 +++++++++ crates/engine/src/media.rs | 4 ++++ crates/engine/src/sidecar.rs | 13 +++++-------- crates/engine/src/tests_import.rs | 20 ++++++++++++++++++++ 5 files changed, 57 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index dd246cf848..88e96c416c 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -137,6 +137,13 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { let content_hash = Some(lightcraft_preview::hash_bytes(bytes).to_string()); let m = lightcraft_meta::extract(bytes); let (meta, captured) = meta_of(&m); + let (rating, flag) = match m.rating { + Some(r) if r < 0 => (0, lightcraft_catalog::Flag::Reject), + Some(r) => (r.clamp(0, 5) as u8, lightcraft_catalog::Flag::None), + None => (0, lightcraft_catalog::Flag::None), + }; + let label = m.label.as_deref().and_then(|l| lightcraft_catalog::ColorLabel::parse(l.trim())); + let label_text = m.label.clone(); if lightcraft_raw::probe(bytes).is_some() { let raw = match lightcraft_raw::probe_info(bytes).map_err(|e| preview_reason(bytes, e)) { Ok(r) => r, @@ -151,6 +158,10 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { file_size: bytes.len() as u64, captured, meta, + rating, + flag, + label, + label_text, as_shot_wb: None, content_hash, xmp: lightcraft_meta::embedded(bytes).xmp, @@ -178,6 +189,10 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { captured, file_modified: None, meta, + rating, + flag, + label, + label_text, as_shot_wb, content_hash, xmp: lightcraft_meta::embedded(bytes).xmp, @@ -210,6 +225,10 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { captured, file_modified: None, meta, + rating, + flag, + label, + label_text, as_shot_wb: None, content_hash, embedded_lens: None, diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 9aa847b01f..8cecda6f56 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -1091,6 +1091,12 @@ impl ImportJob { let mut q = Photo::new(PhotoId(0), Source::File { path: path.clone() }, &own, &info.format, 0, 0, &self.now); q.captured = info.captured.clone(); q.meta = info.meta.clone(); + q.rating = info.rating; + q.flag = info.flag; + q.label = info.label; + if let Some(sc) = &sidecar { + crate::sidecar::merge_into(&mut q, sc, &self.now); + } let name = opts.rename.as_deref().filter(|t| !t.trim().is_empty()).map(|t| { let n = crate::rename::expand(t, &q, self.seq); self.seq += 1; @@ -1415,6 +1421,9 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare p.file_size = info.file_size; p.captured = info.captured; p.meta = info.meta; + p.rating = info.rating; + p.flag = info.flag; + p.label = info.label_text.as_deref().and_then(|t| s.catalog.label_from_name(t)).or(info.label); p.as_shot_wb = info.as_shot_wb; p.content_hash = info.content_hash; p.embedded_lens = info.embedded_lens; diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 22d76528d6..681b0bd5ce 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -1658,6 +1658,10 @@ pub struct ProbeInfo { /// metadata would otherwise all land under "Unknown Date"). pub file_modified: Option, pub meta: lightcraft_catalog::Meta, + pub rating: u8, + pub flag: lightcraft_catalog::Flag, + pub label: Option, + pub label_text: Option, pub as_shot_wb: Option<(f64, f64)>, /// Hash of the file's bytes (hex), for duplicate detection. When it is a 32-digit /// [`lightcraft_preview::hash_bytes`] of the whole file (as the native probe computes it), diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index ea06d69a75..f3c47edc07 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -498,19 +498,16 @@ fn file_path(p: &Photo) -> Option<&str> { } } -/// The XMP packet that describes a photo on disk: its sidecar, else (raw/DNG) the embedded XMP. -pub fn read_packet(original: &str, kind: MediaKind, naming: SidecarNaming) -> Option<(String, PathBuf)> { +/// The XMP packet that describes a photo on disk: its sidecar, else the file's embedded XMP. +pub fn read_packet(original: &str, _kind: MediaKind, naming: SidecarNaming) -> Option<(String, PathBuf)> { if let Some(sc) = find_sidecar(original, naming) && let Ok(s) = std::fs::read_to_string(&sc) { return Some((s, sc)); } - if kind == MediaKind::Raw { - let bytes = std::fs::read(original).ok()?; - let x = lightcraft_meta::embedded(&bytes).xmp?; - return Some((x, PathBuf::from(original))); - } - None + let bytes = std::fs::read(original).ok()?; + let x = lightcraft_meta::embedded(&bytes).xmp?; + Some((x, PathBuf::from(original))) } /// Photo ids touched by an op (for auto-write). diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs index 3d6469deb0..25e7bae42d 100644 --- a/crates/engine/src/tests_import.rs +++ b/crates/engine/src/tests_import.rs @@ -1748,3 +1748,23 @@ fn presets_apply_the_imported_profile_they_name() { assert_eq!(apply(&mut s, "Portra Soft").profile.id, "lc.vivid"); let _ = std::fs::remove_dir_all(&src); } + +#[test] +fn import_preserves_embedded_rating_and_label() { + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("embedded-rating-test"); + let px = [128u8; 40 * 30 * 3]; + let xmp = r#""#; + let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("photo.jpg"), &bytes).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.join("photo.jpg").to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 1); + let p = s.catalog.photos().next().unwrap(); + assert_eq!(p.rating, 5); + assert_eq!(p.label, Some(lightcraft_catalog::ColorLabel::Blue)); + + let _ = std::fs::remove_dir_all(&src); +} From 97dd58a74877f934d8bf705883daf15ccaa81ba2 Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Fri, 16 Oct 2026 20:59:31 -0400 Subject: [PATCH 02/98] LR-PROF-CAMERACOLOR: dark photos keep their camera profile's colour A photo whose camera JPEG is too dark (or too colourless) for any look to fit dropped its camera profile's colour for the neutral fallback. It now keeps the profile's colour, with the JPEG's tone curve when one fits, else the default raw tone curve (CameraTone::default_raw). On NIKON D780 frames 3.7 EV under, pushed back up, colourfulness goes from 37% of the properly exposed frame's to 88-99%. LOOK_VERSION 10, RENDER_CACHE_VERSION 65. --- crates/engine/src/camera_preview.rs | 55 +++++++++++++++++++++++------ crates/engine/src/media.rs | 2 +- crates/pipeline/src/tone.rs | 22 ++++++++++++ docs/camera-preview-colour.md | 8 +++-- docs/parity-checklist.md | 3 +- docs/whats-new.md | 7 ++++ 6 files changed, 81 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index 614c58c60c..d7d1b26f30 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -34,7 +34,8 @@ use lightcraft_raw::{ /// 7: the sensor proxy follows the file's lens warp when the camera JPEG is lens-corrected. /// 8: the bundled NIKON Z 6_2 profile. /// 9: the bundled NIKON Z 8 and NIKON D5300 profiles. -pub const LOOK_VERSION: u32 = 9; +/// 10: a photo no look fits keeps its camera profile's colour instead of the neutral fallback. +pub const LOOK_VERSION: u32 = 10; #[derive(Clone, Debug)] pub(crate) struct CameraLook { @@ -270,17 +271,12 @@ pub(crate) fn fit_preview(raw: &RawImage, bytes: &[u8], transform: &CameraTransf // try its colour first and fit tone/chroma per photo (picture styles vary). 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 look = match fit_look(&sensor, &reference, &clipped, colour.clone()) { - Some(look) => look, - // A black-and-white JPEG has no colour to fit: the profile's colour and the JPEG's tone curve - // (`monochrome_look` does it without a profile). - None if colour.is_some() && black_and_white => { - let unclipped = without_clipped(&sensor, &clipped); - let Some(look) = fit_tone_only(unclipped.as_ref().unwrap_or(&sensor), &reference, colour) else { return (None, true) }; - look - } - None => return (None, black_and_white), + let fitted = fit_look(&sensor, &reference, &clipped, colour.clone()); + let tone_only = |colour| { + let unclipped = without_clipped(&sensor, &clipped); + fit_tone_only(unclipped.as_ref().unwrap_or(&sensor), &reference, Some(colour)) }; + let Some(look) = with_profile_colour(fitted, colour, tone_only) else { return (None, black_and_white) }; // Sony's Dynamic Range Optimizer (on by default) brightens the camera JPEG's darker regions, // not the raw: keep the colour fitted to the JPEG, take the tone curve without DRO. let dro = lightcraft_raw::embedded_preview_dynamic_range_optimized(bytes) == Some(true); @@ -298,6 +294,23 @@ pub(crate) fn fit_preview(raw: &RawImage, bytes: &[u8], transform: &CameraTransf (Some(look), black_and_white) } +/// `fitted`, the photo's own look, or when no look fits it (a black-and-white JPEG has no colour; a dark one too few +/// colour pairs) its camera profile's `colour`: with the JPEG's tone curve when [`fit_tone_only`] finds one +/// (`monochrome_look` does it without a profile), else the default raw tone curve. Dropping the profile there for the +/// neutral fallback left a NIKON D780 frame 3.7 EV under, pushed back up, at 37% of its properly exposed twin's chroma +/// (88-99% with the profile's colour). +fn with_profile_colour( + fitted: Option, + colour: Option<(Mat3, Option)>, + tone_only: impl FnOnce((Mat3, Option)) -> Option, +) -> Option { + if fitted.is_some() { + return fitted; + } + let colour = colour?; + tone_only(colour.clone()).or_else(|| Some(CameraLook { matrix: colour.0, tone: CameraTone::default_raw()?, hue_sat: colour.1 })) +} + /// Sensor level (normalised, white = 1) at or above which a raw channel counts as clipped, as in /// the render's highlight reconstruction. const SENSOR_CLIP: f32 = 0.99; @@ -3983,4 +3996,24 @@ mod tests { looked.profile.look_table = HsvTable::from_tags(&[1, 2, 1], &[0.0, 1.0, 1.0, 0.0, 1.0, 1.0], 0); assert!(looked.profile.look_table.is_some() && !eligible(RawFormat::Dng, looked), "a look table is the file's own rendering"); } + + #[test] + fn a_photo_no_look_fits_keeps_its_camera_profiles_colour() { + let colour = ( + Mat3([[1.8, -0.6, -0.2], [-0.3, 1.5, -0.2], [0.0, -0.4, 1.4]]), + dro_test_look(&std::array::from_fn(|i| 0.01 + i as f32 * 0.01), &|x| x).hue_sat, + ); + // too dark for any look, no tone either: the profile's colour, the default raw tone curve + let look = with_profile_colour(None, Some(colour.clone()), |_| None).expect("the profile's colour"); + assert_eq!((look.matrix, look.hue_sat.is_some()), (colour.0, true)); + assert_eq!(look.tone, CameraTone::default_raw().unwrap()); + // the JPEG's tone curve when it has one + let toned = dro_test_look(&std::array::from_fn(|i| 0.01 + i as f32 * 0.01), &|x| 0.9 * x); + let look = with_profile_colour(None, Some(colour.clone()), |c| Some(CameraLook { matrix: c.0, ..toned.clone() })).unwrap(); + assert_eq!((look.matrix, look.tone), (colour.0, toned.tone)); + // a photo's own look wins; without a profile there is nothing to keep (the neutral fallback follows) + let own = with_profile_colour(Some(toned.clone()), Some(colour), |_| unreachable!()).unwrap(); + assert_eq!(own.matrix, toned.matrix); + assert!(with_profile_colour(None, None, |_| unreachable!()).is_none()); + } } diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index e6c438ad72..1f079e5b27 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -62,7 +62,7 @@ impl SettingsHashes { } /// Bump when the pipeline's output changes, to invalidate cached thumbnails. -pub const RENDER_CACHE_VERSION: u64 = 65; +pub const RENDER_CACHE_VERSION: u64 = 66; /// 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/pipeline/src/tone.rs b/crates/pipeline/src/tone.rs index d4d2d129a7..c31b87e2ad 100644 --- a/crates/pipeline/src/tone.rs +++ b/crates/pipeline/src/tone.rs @@ -58,6 +58,18 @@ impl CameraTone { Some(Self { knots, chroma: NO_CHROMA }) } + /// The default raw tone curve ([`ToneMap::new`] at neutral settings) as camera-curve knots, about 1/3 EV apart + /// from 8 EV below grey to just under display white: for a camera look that knows a photo's colour but not its tone. + pub fn default_raw() -> Option { + const FROM_EV: f32 = -8.0; + const TO_EV: f32 = 2.6; + let map = ToneMap::new(0.0, 0.0, 0.0); + Self::new(std::array::from_fn(|i| { + let x = GREY * 2f32.powf(FROM_EV + (TO_EV - FROM_EV) * i as f32 / 31.0); + [x, map.apply(x)] + })) + } + /// The curve with chroma scales at display luminance 0, 1/7 … 1 (each finite, 0..=4). pub fn with_chroma(self, chroma: [f32; CHROMA_N]) -> Option { chroma.iter().all(|k| k.is_finite() && (0.0..=4.0).contains(k)).then_some(Self { chroma, ..self }) @@ -447,4 +459,14 @@ mod tests { assert!(ToneMap::new(0.0, 0.0, -60.0).apply(0.01) < base.apply(0.01)); assert!(ToneMap::new(0.0, 0.0, 60.0).apply(0.01) > base.apply(0.01)); } + + #[test] + fn default_raw_camera_tone_follows_the_default_tone_curve() { + let (camera, default) = (CameraTone::default_raw().unwrap(), ToneMap::new(0.0, 0.0, 0.0)); + for ev in [-8.0f32, -6.0, -4.0, -2.0, -1.0, 0.0, 1.0, 2.0, 2.5] { + let y = GREY * 2f32.powf(ev); + let (a, b) = (camera.apply(y), default.apply(y)); + assert!((a - b).abs() <= 0.01 * b.max(0.01), "{ev} EV: {a} vs {b}"); + } + } } diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index 463ccaed77..16ef19a6e1 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -113,7 +113,7 @@ A pooled profile was tried and is not bundled. Pooling the 46 photos (158,549 co One photo can show too little of a colour for its own fit to learn it: in a second shot of the lime shirt only a few dozen proxy pixels show it, next to a hillside of foliage at the same hue that the camera renders differently, and the shirt stayed yellow (hue 68° against the JPEG's 82°; a 192-pixel proxy only reached 74°). `lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS…` therefore pools the colour pairs of many ARWs, NEFs or RAFs per camera model — each against its own embedded JPEG, at a 192-pixel proxy, at most 4000 pairs per photo, files spread evenly over the folders — and fits one matrix (from white-balanced camera RGB, so no single photo's white point is baked in) and one hue/saturation/value table. Models need at least 5 usable photos. -Profiles are JSON files `.json` in `$LIGHTCRAFT_CAMERA_PROFILES`, else `/camera-profiles` (macOS `~/Library/Application Support/LightCraft/camera-profiles`); a local profile replaces a built-in one. Built-in profiles live in `assets/camera-profiles/` (listed in `assets/ATTRIBUTION.md`) and are compiled in, so the app, CLI and web build share them: ILCE-7M4, fitted to 597 photos (2.2 million colour pairs) shot in 2026, mostly with the Standard creative style and DRO Auto; ILCE-7CR, 125 photos, and ILCA-99M2, 144 photos (both below); X-H2S, 201 photos; X-T4, 545 photos; NIKON Z 6_2, 296 photos; NIKON Z 8, 261 photos; NIKON D5300, 264 photos (below). They hold aggregate colour statistics only. A photo of a profiled model takes its colour from the profile and fits only its own tone and chroma curves (picture styles vary per shot; with Sony's DRO on, that tone curve is then lowered as described below); the acceptance gates still apply. A rejected profile fit retries the photo's own colour and tone fit before falling back to neutral rendering. Files are read once per process and validated (version, bounded invertible matrix, table shape and finite data); a damaged file is ignored with a warning. The profiles folder's contents are part of the render cache keys, so thumbnails rendered before a profile existed are redone; smart previews built before keep their colour until rebuilt. +Profiles are JSON files `.json` in `$LIGHTCRAFT_CAMERA_PROFILES`, else `/camera-profiles` (macOS `~/Library/Application Support/LightCraft/camera-profiles`); a local profile replaces a built-in one. Built-in profiles live in `assets/camera-profiles/` (listed in `assets/ATTRIBUTION.md`) and are compiled in, so the app, CLI and web build share them: ILCE-7M4, fitted to 597 photos (2.2 million colour pairs) shot in 2026, mostly with the Standard creative style and DRO Auto; ILCE-7CR, 125 photos, and ILCA-99M2, 144 photos (both below); X-H2S, 201 photos; X-T4, 545 photos; NIKON Z 6_2, 296 photos; NIKON Z 8, 261 photos; NIKON D5300, 264 photos (below). They hold aggregate colour statistics only. A photo of a profiled model takes its colour from the profile and fits only its own tone and chroma curves (picture styles vary per shot; with Sony's DRO on, that tone curve is then lowered as described below); the acceptance gates still apply. A rejected profile fit retries the photo's own colour and tone fit; when no look fits at all, the photo keeps the profile's colour (below). Files are read once per process and validated (version, bounded invertible matrix, table shape and finite data); a damaged file is ignored with a warning. The profiles folder's contents are part of the render cache keys, so thumbnails rendered before a profile existed are redone; smart previews built before keep their colour until rebuilt. ### Sony ILCE-7CR @@ -135,7 +135,7 @@ Without a profile all 150 photos accept their own fit (ΔE 1.8–13.5). For vali With CR3 and CR2 input to `calibrate` (#1073), tried on one photographer's library (CR3, RAW and C-RAW, October 2025 to September 2026) and measured as above, against each file's own full-size embedded JPEG (6960 × 4640 R7, 6000 × 4000 R6 Mark II): - Held out: 40 photos per body from different shoots, every fifth withheld (8 per body), profiles fitted on the other 32 (30 R7 photos with 107,286 colour pairs, 28 R6 Mark II with 93,200; both with a hue/saturation table). On the withheld photos the profile changes little: R7 mean ΔE 2.52 → 2.57 (median 2.37 → 2.25; 3 better, 3 worse, 2 unchanged; largest regression +0.51 on an almost colourless photo), R6 Mark II 6.12 → 6.09 (median 5.73 → 5.50; 3 better, 4 worse, 1 unchanged; largest regression +0.48, best gain −0.67). Mean ΔL\* 0.00 (R7) and +0.57 (R6 Mark II) either way. Not bundled. -- The profile only replaces the colour inside an accepted per-photo fit (`fit_preview`), so a photo whose own fit is rejected renders the neutral fallback with or without it: 2 of the 16 withheld photos (one per body), plus one with a black-and-white camera JPEG, rendered identically both ways. Unlike the ILCE-7CR, where the profile rescued every rejected photo, here it cannot. +- When this was measured the profile only replaced the colour inside an accepted per-photo fit (`fit_preview`), so a photo whose own fit was rejected rendered the neutral fallback with or without it (since `LOOK_VERSION` 10 it keeps the profile's colour, below): 2 of the 16 withheld photos (one per body), plus one with a black-and-white camera JPEG, rendered identically both ways. Unlike the ILCE-7CR, where the profile rescued every rejected photo, here it cannot. - Library-wide (`--max 600` over 35,796 CR3s): 410 R7 photos (1.39 million pairs), 119 R6 Mark II (386k) and 38 EOS R100 (129k) gave profiles; 32 photos had no usable camera JPEG or colour (mostly moon, night and other near-colourless scenes) and one did not decode. The R6 Mark II writes its Exif model as "Canon EOS R6m2", the profile's file name too. - Decoding: 4 of the R6 Mark II C-RAW files tried (3 of 40 sampled, 1 of 119 in the library run) are refused with "unsupported raw variant: Canon CRX adaptive QP value 172" (or 175) and open preview-only. @@ -191,7 +191,9 @@ A raw starts from the first of these that is available (`camera_preview::startin 4. the model's spectral matrices, with LightCraft's default tone curve and no JPEG fit; 5. the neutral fallback. -When the file's JPEG is black and white, step 2 fits the tone curve alone with the profile's colour; without a profile, or when that fit fails, 4 and 5 take the tone curve fitted to it (see the black-and-white JPEG paragraph above). +When no look fits a photo of a profiled model (step 2 and 3 both fail: a black-and-white JPEG has no colour, a dark one too few colour pairs), it keeps the profile's colour, with the tone curve fitted alone to its JPEG when that passes the checks of the black-and-white JPEG paragraph above, else LightCraft's default tone curve (`with_profile_colour`). Without a profile, a black-and-white JPEG gives 4 and 5 the tone curve fitted to it. + +Before this, such a photo fell to 4 or 5 and the profile did nothing for it. Measured on two bracketed bursts of one NIKON D780 scene (a colourful woven runner in low sun, ISO 100, f/8, frames 1.1 to 3.7 EV under the burst's brightest, each rendered with Exposure raised by its measured offset and compared with the brightest frame, CIEDE2000 and chroma of the colourful areas), with a local profile pooled from 255 of the photographer's D780 photos: the five frames 2.8 EV or more under have no look (their camera JPEGs are nearly black) and rendered at 35-48% of the reference's chroma with hue off by up to 9° whether or not the profile existed; with the profile's colour kept they render at 88-99% of it, hue within 5°. Frames up to 2.3 EV under fit a look and are unchanged. The pushed frames remain 4-7 L\* darker than the reference: a dark photo's tone curve is fitted to its shadows only (or is the default curve), which the profile doesn't change. The spectral matrices only replace the neutral fallback: a photo whose JPEG fit is accepted (with or without a profile) renders exactly as before, and a covered model takes its spectral matrices only when that fit fails the diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 18863969ad..167082cc6a 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-16 · **Change:** patch (LR-PROF-CAMERACOLOR: raw decoding keeps negative channels) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** minor (LR-PROF-CAMERACOLOR: dark photos keep their camera profile's colour) · **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 @@ -69,6 +69,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| +| 2026-10-16 | minor | LR-PROF-CAMERACOLOR: a photo no look fits keeps its camera profile's colour instead of the neutral fallback; status unchanged (🟡) | | 2026-10-12 | minor | LR-IMP-FORMATS: Mamiya MEF decodes from sensor data and is imported (`vendor/mef.rs`) | | 2026-10-12 | minor | LR-IMP-FORMATS: Epson ERF decodes from sensor data (`vendor/erf.rs`), no longer preview-only | | LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with thumbnails and checkboxes (duplicates by path/content marked and unchecked; with several file types, a toggle per type checks or unchecks all of its files, e.g. the raws without the JPEGs beside them, issue #344) filling a resizable window (issue #337), transfer mode (add in place / copy / move, each explained), album (existing/new), preset, keywords; the folder scan runs on a background thread, shown in the activity stack with ✕ to cancel (a NAS folder no longer freezes the window); the import itself (probing, sidecars, copying / moving files) runs on a worker thread and its batches join the library between frames, shown in the activity stack with ✕ to cancel; one undo step. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lightcraft_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/lightcraft/src/dialog_filter.rs`, issue #342; 0.4.0 hid `.JPG` / `.NEF`, issue #705). The folder scan, Browse Folder, drag-and-drop and the sidecar lookup match extensions in any case (`crates/engine/src/tests_import.rs`) | diff --git a/docs/whats-new.md b/docs/whats-new.md index 441b4889bc..358e53673c 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -8,6 +8,13 @@ pushed up came out purple or magenta (a lens-cap frame pushed 4 EV rendered magenta; it is now black). Shadows pushed with Exposure or Shadows keep their real colour, most visibly with saturating camera profiles. +### Dark raws keep their camera profile's colour +- A raw whose camera JPEG is too dark (or too colourless) to fit a look to no longer drops its camera profile's + colour for the dull neutral fallback: it keeps the profile's colour, with the JPEG's tone curve when one fits, else + the default tone curve. Photos of profiled cameras that were underexposed and pushed back up keep their colour: on + NIKON D780 frames 3.7 EV under with a local profile, from about 40% of the properly exposed frame's colourfulness + to about 95%. Pushed shadows still come out somewhat darker than a properly exposed shot. + ## 2026-10-14 ### Model downloads time out on a name that doesn't resolve From d54ea1fa243b1412c0086b36c0cbb5cde569f51d Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Fri, 16 Oct 2026 21:00:18 -0400 Subject: [PATCH 03/98] LR-PROF-CAMERACOLOR: camera profiles carry a pooled tone curve lightcraft-cli calibrate also pools tone samples (camera RGB -> camera JPEG luminance, dark pixels included) and fits one curve per camera by quantile matching; profiles store it as an optional `tone` field (older profiles and builds still load). A photo keeps its own curve as far as its JPEG showed it and follows the pooled curve past that, faded over 1 EV (extend_tone), instead of the bounded shoulder that rendered underexposed photos pushed back up 4-7 L* too dark; a photo no look fits takes the pooled curve whole. On NIKON D780 brackets, pushed frames now match the properly exposed frame within 0.5 L*; on 120 held-out D780/D750/D90 photos rendered as shot the curve changes mean dE against the camera JPEG by at most 0.03. LOOK_VERSION 11. --- apps/lightcraft-cli/src/main.rs | 3 +- crates/engine/src/camera_preview.rs | 161 +++++++++++++++++++++++++-- crates/engine/src/camera_profiles.rs | 66 ++++++++--- docs/camera-preview-colour.md | 6 +- docs/parity-checklist.md | 3 +- docs/whats-new.md | 8 +- 6 files changed, 216 insertions(+), 31 deletions(-) diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rs index 01dae3055e..6e09e2a010 100644 --- a/apps/lightcraft-cli/src/main.rs +++ b/apps/lightcraft-cli/src/main.rs @@ -272,11 +272,12 @@ fn calibrate(args: &[String]) -> Result<(), String> { Ok(profile) => { let path = lightcraft_engine::camera_profiles::save(&profile, &dir)?; println!( - "{}: {} photos, {} colour pairs, hue/saturation table {} → {}", + "{}: {} photos, {} colour pairs, hue/saturation table {}, tone curve {} → {}", profile.model, profile.files, profile.samples, profile.hue_sat.is_some(), + profile.tone.is_some(), path.display() ); written += 1; diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index d7d1b26f30..f23fa27577 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -35,7 +35,8 @@ use lightcraft_raw::{ /// 8: the bundled NIKON Z 6_2 profile. /// 9: the bundled NIKON Z 8 and NIKON D5300 profiles. /// 10: a photo no look fits keeps its camera profile's colour instead of the neutral fallback. -pub const LOOK_VERSION: u32 = 10; +/// 11: a camera profile's pooled tone curve continues a photo's own past what its JPEG showed. +pub const LOOK_VERSION: u32 = 11; #[derive(Clone, Debug)] pub(crate) struct CameraLook { @@ -271,12 +272,18 @@ pub(crate) fn fit_preview(raw: &RawImage, bytes: &[u8], transform: &CameraTransf // try its colour first and fit tone/chroma per photo (picture styles vary). 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 pooled = profile.as_ref().and_then(|p| p.tone); let fitted = fit_look(&sensor, &reference, &clipped, colour.clone()); let tone_only = |colour| { let unclipped = without_clipped(&sensor, &clipped); fit_tone_only(unclipped.as_ref().unwrap_or(&sensor), &reference, Some(colour)) }; - let Some(look) = with_profile_colour(fitted, colour, tone_only) else { return (None, black_and_white) }; + let Some(look) = with_profile_colour(fitted, colour, pooled, tone_only) else { return (None, black_and_white) }; + // the camera's own curve past what this photo's JPEG showed + let look = match pooled { + Some(pooled) => CameraLook { tone: extend_tone(&look.tone, &pooled), ..look }, + None => look, + }; // Sony's Dynamic Range Optimizer (on by default) brightens the camera JPEG's darker regions, // not the raw: keep the colour fitted to the JPEG, take the tone curve without DRO. let dro = lightcraft_raw::embedded_preview_dynamic_range_optimized(bytes) == Some(true); @@ -296,19 +303,20 @@ pub(crate) fn fit_preview(raw: &RawImage, bytes: &[u8], transform: &CameraTransf /// `fitted`, the photo's own look, or when no look fits it (a black-and-white JPEG has no colour; a dark one too few /// colour pairs) its camera profile's `colour`: with the JPEG's tone curve when [`fit_tone_only`] finds one -/// (`monochrome_look` does it without a profile), else the default raw tone curve. Dropping the profile there for the +/// (`monochrome_look` does it without a profile), else the profile's pooled tone curve, else the default raw one. Dropping the profile there for the /// neutral fallback left a NIKON D780 frame 3.7 EV under, pushed back up, at 37% of its properly exposed twin's chroma /// (88-99% with the profile's colour). fn with_profile_colour( fitted: Option, colour: Option<(Mat3, Option)>, + pooled: Option, tone_only: impl FnOnce((Mat3, Option)) -> Option, ) -> Option { if fitted.is_some() { return fitted; } let colour = colour?; - tone_only(colour.clone()).or_else(|| Some(CameraLook { matrix: colour.0, tone: CameraTone::default_raw()?, hue_sat: colour.1 })) + tone_only(colour.clone()).or_else(|| Some(CameraLook { matrix: colour.0, tone: pooled.or_else(CameraTone::default_raw)?, hue_sat: colour.1 })) } /// Sensor level (normalised, white = 1) at or above which a raw channel counts as clipped, as in @@ -821,7 +829,17 @@ fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rg /// 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> { +/// What one photo contributes to a camera profile ([`profile_samples`]), in white-balanced camera RGB. +pub(crate) struct ProfileSamples { + /// Colour pairs: camera RGB → the camera JPEG's linear Rec.2020. + pub colour: Vec<([f64; 3], [f64; 3])>, + /// Tone samples: camera RGB → the camera JPEG's luminance, dark pixels included (as the photo's own toe fit takes + /// them, [`fit_tone_with_shadows`]). + pub tone: Vec<([f64; 3], f64)>, +} + +/// A raw's colour and tone samples for a pooled camera profile (`lightcraft-cli calibrate`). +pub(crate) fn profile_samples(raw: &RawImage, bytes: &[u8], lens: Option<&LensGeometry>) -> Option { if !file_local_look(raw.format) || lightcraft_raw::color::has_matrix(&raw.color) { return None; } @@ -831,7 +849,72 @@ pub(crate) fn profile_pairs(raw: &RawImage, bytes: &[u8], lens: Option<&LensGeom // clipped sensor pixels don't record the scene's colour (see `fit_look`) let sensor = without_clipped(&sensor, &clipped).unwrap_or(sensor); let (pairs, _) = collect_pairs(&sensor, &reference, 0.05, None, false)?; - Some(pairs.into_iter().map(|(x, y)| (to_camera.apply(x), y)).collect()) + let tone = sensor + .data + .iter() + .zip(&reference.data) + .filter(|(input, output)| tone_sample(**input, **output)) + .map(|(input, output)| (to_camera.apply(input.map(f64::from)), f64::from(luminance_2020(*output)))) + .collect(); + Some(ProfileSamples { colour: pairs.into_iter().map(|(x, y)| (to_camera.apply(x), y)).collect(), tone }) +} + +/// Whether a sensor/JPEG proxy pixel pair can teach the tone curve: every channel above the sensor floor, the JPEG +/// pixel about one 8-bit sRGB code above black (no flat black segment learnt from JPEG compression) and below the +/// highlights (clipped or rolled off). +fn tone_sample(input: [f32; 3], output: [f32; 3]) -> bool { + input.iter().all(|v| v.is_finite() && *v > 0.0001 && *v < 1.5) + && output.iter().all(|v| v.is_finite() && *v >= 0.0) + && (0.0003..0.85).contains(&luminance_2020(output)) +} + +/// A camera profile's tone curve from the tone samples pooled over its photos, through the profile's `matrix`: one +/// curve for the camera, from shadows that only dark photos show to highlights that only bright ones show. Quantile +/// matching ([`fit_tone`]) pools correctly because every photo went through the same camera curve (picture styles and +/// Active D-Lighting aside, which it averages). +pub(crate) fn fit_profile_tone(samples: &[([f64; 3], f64)], matrix: &Mat3) -> Option { + fit_tone(samples.iter().map(|(x, y)| (luma(matrix.apply(*x).map(|v| v.max(0.0))), *y)).filter(|(x, _)| *x > 0.0).collect()) +} + +/// `photo`'s tone curve where its JPEG taught it, `pooled`'s past that: from the photo's last knot it fades over +/// [`EXTEND_FADE_EV`] from its own level onto the camera's pooled curve, instead of the bounded shoulder +/// ([`CameraTone::apply`]) whose rate comes from the photo's last two knots. A dark photo's curve ends in the shadows, +/// and that shoulder rendered it, pushed back up, 4-7 L* darker than a properly exposed photo of the same scene. +/// `photo` unchanged when the pooled curve doesn't reach on past it. +fn extend_tone(photo: &CameraTone, pooled: &CameraTone) -> CameraTone { + /// EV over which the extension moves from the photo's level onto the pooled curve. + const EXTEND_FADE_EV: f32 = 1.0; + /// Knots per EV of the extension. + const EXTEND_KNOTS_PER_EV: f32 = 3.0; + let (own, camera) = (photo.knots(), pooled.knots()); + let (end, last) = (own[31], camera[31][0]); + let span = (last / end[0]).log2(); + if !(span.is_finite() && span > 0.2) { + return *photo; + } + let extra = ((span * EXTEND_KNOTS_PER_EV).round() as usize).clamp(2, 16); + let at_end = pooled.apply(end[0]); + let ratio = if at_end > 0.0 && end[1] > 0.0 { end[1] / at_end } else { 1.0 }; + let mut knots = [[0.0f32; 2]; 32]; + // the photo's own knots, evenly thinned to make room, always keeping its first and last + let kept = 32 - extra; + for (i, knot) in knots.iter_mut().take(kept).enumerate() { + *knot = own[i * 31 / (kept - 1)]; + } + for k in 1..=extra { + let ev = span * k as f32 / extra as f32; + let x = end[0] * ev.exp2(); + let t = (ev / EXTEND_FADE_EV).clamp(0.0, 1.0); + let w = t * t * (3.0 - 2.0 * t); + knots[kept + k - 1] = [x, pooled.apply(x) * ratio.powf(1.0 - w)]; + } + // monotone and below white whatever the two curves do + let mut floor = 0.0f32; + for knot in &mut knots { + knot[1] = knot[1].max(floor).min(0.999); + floor = knot[1]; + } + CameraTone::new(knots).and_then(|tone| tone.with_chroma(*photo.chroma())).unwrap_or(*photo) } /// A camera profile's colour model (matrix from white-balanced camera RGB, hue/saturation table) @@ -4004,16 +4087,74 @@ mod tests { dro_test_look(&std::array::from_fn(|i| 0.01 + i as f32 * 0.01), &|x| x).hue_sat, ); // too dark for any look, no tone either: the profile's colour, the default raw tone curve - let look = with_profile_colour(None, Some(colour.clone()), |_| None).expect("the profile's colour"); + let look = with_profile_colour(None, Some(colour.clone()), None, |_| None).expect("the profile's colour"); assert_eq!((look.matrix, look.hue_sat.is_some()), (colour.0, true)); assert_eq!(look.tone, CameraTone::default_raw().unwrap()); // the JPEG's tone curve when it has one let toned = dro_test_look(&std::array::from_fn(|i| 0.01 + i as f32 * 0.01), &|x| 0.9 * x); - let look = with_profile_colour(None, Some(colour.clone()), |c| Some(CameraLook { matrix: c.0, ..toned.clone() })).unwrap(); + let look = with_profile_colour(None, Some(colour.clone()), None, |c| Some(CameraLook { matrix: c.0, ..toned.clone() })).unwrap(); assert_eq!((look.matrix, look.tone), (colour.0, toned.tone)); // a photo's own look wins; without a profile there is nothing to keep (the neutral fallback follows) - let own = with_profile_colour(Some(toned.clone()), Some(colour), |_| unreachable!()).unwrap(); + let own = with_profile_colour(Some(toned.clone()), Some(colour), None, |_| unreachable!()).unwrap(); assert_eq!(own.matrix, toned.matrix); - assert!(with_profile_colour(None, None, |_| unreachable!()).is_none()); + assert!(with_profile_colour(None, None, None, |_| unreachable!()).is_none()); + } + + /// A camera curve: a toe, then a shoulder toward 0.95, the shape camera JPEG curves have. + fn camera_curve(x: f32) -> f32 { + 0.95 * (x / (x + 0.12)).powf(1.3) * 1.1 + } + + fn sampled(curve: impl Fn(f32) -> f32, from: f32, to: f32) -> CameraTone { + CameraTone::new(std::array::from_fn(|i| { + let x = from * (to / from).powf(i as f32 / 31.0); + [x, curve(x)] + })) + .unwrap() + } + + #[test] + fn a_dark_photos_curve_goes_on_along_the_cameras_pooled_one() { + let pooled = sampled(camera_curve, 0.0005, 0.9); + // a dark photo's JPEG showed the curve up to 0.02, 10% darker than the camera's (a picture style) + let photo = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.02).with_chroma([1.4, 1.2, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]).unwrap(); + let tone = extend_tone(&photo, &pooled); + assert_eq!(tone.chroma(), photo.chroma()); + // its own curve where its JPEG taught it, the pooled one from 1 EV past that, a monotone fade in between + for x in [0.001f32, 0.005, 0.01, 0.019] { + assert!((tone.apply(x) - photo.apply(x)).abs() < 0.02 * photo.apply(x), "{x}: {} vs {}", tone.apply(x), photo.apply(x)); + } + for x in [0.05f32, 0.1, 0.3, 0.8] { + assert!((tone.apply(x) - pooled.apply(x)).abs() < 0.01, "{x}: {} vs {}", tone.apply(x), pooled.apply(x)); + } + assert!(tone.knots().windows(2).all(|k| k[1][0] > k[0][0] && k[1][1] >= k[0][1])); + // a photo that already reaches as far keeps its curve + let bright = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.85); + assert_eq!(extend_tone(&bright, &pooled), bright); + } + + #[test] + fn a_pooled_tone_curve_spans_dark_and_bright_photos() { + // camera RGB grey (white balanced): a dark photo's pixels and a bright one's, through one camera curve + let matrix = Mat3::IDENTITY; + let samples: Vec<([f64; 3], f64)> = (0..4000) + .map(|i| { + let x = if i % 2 == 0 { 0.0005 * 40f64.powf((i / 2) as f64 / 2000.0) } else { 0.02 * 40f64.powf((i / 2) as f64 / 2000.0) }; + ([x; 3], f64::from(camera_curve(x as f32))) + }) + .collect(); + let tone = fit_profile_tone(&samples, &matrix).unwrap(); + for x in [0.001f32, 0.01, 0.05, 0.2, 0.6] { + assert!((tone.apply(x) - camera_curve(x)).abs() < 0.01 + 0.03 * camera_curve(x), "{x}: {} vs {}", tone.apply(x), camera_curve(x)); + } + assert!(fit_profile_tone(&samples[..64], &matrix).is_none(), "too few samples"); + } + + #[test] + fn a_photo_no_look_fits_takes_the_profiles_pooled_tone_curve() { + let colour = (Mat3::IDENTITY, None); + let pooled = sampled(camera_curve, 0.0005, 0.9); + let look = with_profile_colour(None, Some(colour), Some(pooled), |_| None).unwrap(); + assert_eq!(look.tone, pooled); } } diff --git a/crates/engine/src/camera_profiles.rs b/crates/engine/src/camera_profiles.rs index d13023b6e0..298c8311e9 100644 --- a/crates/engine/src/camera_profiles.rs +++ b/crates/engine/src/camera_profiles.rs @@ -11,6 +11,7 @@ //! `assets/camera-profiles/`). They are read once per process; a damaged or hostile file is //! ignored with a warning. They hold aggregate colour statistics only, never image content. use lightcraft_color::Mat3; +use lightcraft_pipeline::tone::CameraTone; use lightcraft_raw::profile::HsvTable; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -47,11 +48,21 @@ pub struct CameraProfile { matrix: [[f64; 3]; 3], /// Hue/saturation/value correction after `matrix` (linear ProPhoto RGB). pub hue_sat: Option, + /// The camera's tone curve pooled over the photos (scene luminance after `matrix` → the camera JPEG's): a photo + /// follows it past what its own JPEG shows, and takes it whole when its JPEG teaches no curve. Absent in profiles + /// fitted before it existed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tone: Option, } impl CameraProfile { pub fn new(model: &str, files: usize, samples: usize, matrix: Mat3, hue_sat: Option) -> CameraProfile { - CameraProfile { version: VERSION, model: model.to_owned(), files, samples, matrix: matrix.0, hue_sat } + CameraProfile { version: VERSION, model: model.to_owned(), files, samples, matrix: matrix.0, hue_sat, tone: None } + } + + /// The profile with its pooled tone curve. + pub fn with_tone(self, tone: Option) -> CameraProfile { + CameraProfile { tone, ..self } } pub fn matrix(&self) -> Mat3 { @@ -184,15 +195,28 @@ pub fn cache_key() -> u64 { }) } -/// Per camera model: the photos read and their pooled colour pairs. +/// Per camera model: the photos read and their pooled colour pairs and tone samples. #[derive(Default)] pub struct Pool { - models: HashMap)>, + models: HashMap, } -/// Most colour pairs kept per photo, so a few busy photos can't dominate a profile. +#[derive(Default)] +struct Model { + files: usize, + pairs: Vec<([f64; 3], [f64; 3])>, + tone: Vec<([f64; 3], f64)>, +} + +/// Most colour pairs (and, separately, tone samples) kept per photo, so a few busy photos can't dominate a profile. const PAIRS_PER_FILE: usize = 4000; +/// Every `n`-th item, `n` chosen to keep at most [`PAIRS_PER_FILE`]. +fn thinned(items: Vec) -> impl Iterator { + let step = items.len().div_ceil(PAIRS_PER_FILE).max(1); + items.into_iter().step_by(step) +} + 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). @@ -203,11 +227,11 @@ impl Pool { 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 step = pairs.len().div_ceil(PAIRS_PER_FILE).max(1); + let Some(samples) = crate::camera_preview::profile_samples(&raw, bytes, lens.as_ref()) else { return Ok(None) }; let entry = self.models.entry(model.to_owned()).or_default(); - entry.0 += 1; - entry.1.extend(pairs.into_iter().step_by(step)); + entry.files += 1; + entry.pairs.extend(thinned(samples.colour)); + entry.tone.extend(thinned(samples.tone)); Ok(Some(model.to_owned())) } @@ -217,26 +241,28 @@ impl Pool { models.sort_by(|a, b| a.0.cmp(b.0)); models .into_iter() - .filter(|(_, (files, _))| *files >= min_files) - .map(|(model, (files, pairs))| { - let (matrix, hue_sat) = crate::camera_preview::fit_profile(pairs).ok_or_else(|| format!("{model}: no usable colour fit"))?; - Ok(CameraProfile::new(model, *files, pairs.len(), matrix, hue_sat)) + .filter(|(_, m)| m.files >= min_files) + .map(|(model, m)| { + let (matrix, hue_sat) = crate::camera_preview::fit_profile(&m.pairs).ok_or_else(|| format!("{model}: no usable colour fit"))?; + let tone = crate::camera_preview::fit_profile_tone(&m.tone, &matrix); + Ok(CameraProfile::new(model, m.files, m.pairs.len(), matrix, hue_sat).with_tone(tone)) }) .collect() } /// Add another pool's photos and pairs (pools filled on separate threads). pub fn merge(&mut self, other: Pool) { - for (model, (files, pairs)) in other.models { + for (model, m) in other.models { let entry = self.models.entry(model).or_default(); - entry.0 += files; - entry.1.extend(pairs); + entry.files += m.files; + entry.pairs.extend(m.pairs); + entry.tone.extend(m.tone); } } /// Photos read per model. pub fn files(&self) -> Vec<(String, usize)> { - let mut v: Vec<_> = self.models.iter().map(|(m, (n, _))| (m.clone(), *n)).collect(); + let mut v: Vec<_> = self.models.iter().map(|(name, m)| (name.clone(), m.files)).collect(); v.sort(); v } @@ -276,6 +302,14 @@ mod tests { let mut p = profile(); p.version = 99; assert!(bad(p), "unknown version"); + // a pooled tone curve round-trips; a broken one (knots going backwards) is a damaged file + let toned = profile().with_tone(CameraTone::default_raw()); + let path = save(&toned, &dir).unwrap(); + assert_eq!(load(&path).unwrap(), toned); + let mut json: serde_json::Value = serde_json::to_value(&toned).unwrap(); + json["tone"]["knots"][3][0] = serde_json::json!(5.0); + std::fs::write(dir.join("bad.json"), serde_json::to_vec(&json).unwrap()).unwrap(); + assert!(load(&dir.join("bad.json")).is_err(), "invalid tone curve"); std::fs::write(dir.join("junk.json"), b"{not json").unwrap(); assert!(load(&dir.join("junk.json")).is_err()); assert!(load(&dir.join("missing.json")).is_err()); diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index 16ef19a6e1..40ac01ec29 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -193,7 +193,11 @@ A raw starts from the first of these that is available (`camera_preview::startin When no look fits a photo of a profiled model (step 2 and 3 both fail: a black-and-white JPEG has no colour, a dark one too few colour pairs), it keeps the profile's colour, with the tone curve fitted alone to its JPEG when that passes the checks of the black-and-white JPEG paragraph above, else LightCraft's default tone curve (`with_profile_colour`). Without a profile, a black-and-white JPEG gives 4 and 5 the tone curve fitted to it. -Before this, such a photo fell to 4 or 5 and the profile did nothing for it. Measured on two bracketed bursts of one NIKON D780 scene (a colourful woven runner in low sun, ISO 100, f/8, frames 1.1 to 3.7 EV under the burst's brightest, each rendered with Exposure raised by its measured offset and compared with the brightest frame, CIEDE2000 and chroma of the colourful areas), with a local profile pooled from 255 of the photographer's D780 photos: the five frames 2.8 EV or more under have no look (their camera JPEGs are nearly black) and rendered at 35-48% of the reference's chroma with hue off by up to 9° whether or not the profile existed; with the profile's colour kept they render at 88-99% of it, hue within 5°. Frames up to 2.3 EV under fit a look and are unchanged. The pushed frames remain 4-7 L\* darker than the reference: a dark photo's tone curve is fitted to its shadows only (or is the default curve), which the profile doesn't change. +Before this, such a photo fell to 4 or 5 and the profile did nothing for it. Measured on two bracketed bursts of one NIKON D780 scene (a colourful woven runner in low sun, ISO 100, f/8, frames 1.1 to 3.7 EV under the burst's brightest, each rendered with Exposure raised by its measured offset and compared with the brightest frame, CIEDE2000 and chroma of the colourful areas), with a local profile pooled from 255 of the photographer's D780 photos: the five frames 2.8 EV or more under have no look (their camera JPEGs are nearly black) and rendered at 35-48% of the reference's chroma with hue off by up to 9° whether or not the profile existed; with the profile's colour kept they render at 88-99% of it, hue within 5°. Frames up to 2.3 EV under fit a look and are unchanged. The pushed frames remain 4-7 L\* darker than the reference: a dark photo's tone curve is fitted to its shadows only (or is the default curve), which the profile's colour doesn't change (the pooled tone curve, next, does). + +**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85, at most 4,000 per photo), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`); a photo no look fits takes the pooled curve whole instead of the default one. + +On the same D780 brackets with the profile refitted with its tone curve (255 photos), the pushed frames match the reference's lightness: ΔL\* −0.2 to +0.5 for every frame (−1 to −7 before), median CIEDE2000 in the L\* 40-70 band 0.9-2.6 (2.0-13.5 before), hue within 5°. Colourfulness in the second burst comes out 16-28% above the reference in midtones. On 40 D780 photos the profile never saw, rendered unedited and compared with their camera JPEGs, the curve changes nothing that matters: mean ΔE 2.67 with the colour-only profile, 2.68 with the curve (2.77 without a profile), mean ΔL\* +0.71 → +0.73, one photo worse by more than 0.25 (0.38). The spectral matrices only replace the neutral fallback: a photo whose JPEG fit is accepted (with or without a profile) renders exactly as before, and a covered model takes its spectral matrices only when that fit fails the diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 167082cc6a..e14acb4fb3 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-16 · **Change:** minor (LR-PROF-CAMERACOLOR: dark photos keep their camera profile's colour) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** minor (LR-PROF-CAMERACOLOR: dark photos keep their camera profile's colour; pooled camera tone curves) · **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 @@ -69,6 +69,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| +| 2026-10-16 | minor | LR-PROF-CAMERACOLOR: camera profiles carry a pooled tone curve that continues each photo's own past its JPEG's range; status unchanged (🟡) | | 2026-10-16 | minor | LR-PROF-CAMERACOLOR: a photo no look fits keeps its camera profile's colour instead of the neutral fallback; status unchanged (🟡) | | 2026-10-12 | minor | LR-IMP-FORMATS: Mamiya MEF decodes from sensor data and is imported (`vendor/mef.rs`) | | 2026-10-12 | minor | LR-IMP-FORMATS: Epson ERF decodes from sensor data (`vendor/erf.rs`), no longer preview-only | diff --git a/docs/whats-new.md b/docs/whats-new.md index 358e53673c..33541ab65d 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -8,12 +8,16 @@ pushed up came out purple or magenta (a lens-cap frame pushed 4 EV rendered magenta; it is now black). Shadows pushed with Exposure or Shadows keep their real colour, most visibly with saturating camera profiles. -### Dark raws keep their camera profile's colour +### Dark raws keep their camera's colour and tone - A raw whose camera JPEG is too dark (or too colourless) to fit a look to no longer drops its camera profile's colour for the dull neutral fallback: it keeps the profile's colour, with the JPEG's tone curve when one fits, else the default tone curve. Photos of profiled cameras that were underexposed and pushed back up keep their colour: on NIKON D780 frames 3.7 EV under with a local profile, from about 40% of the properly exposed frame's colourfulness - to about 95%. Pushed shadows still come out somewhat darker than a properly exposed shot. + to about 95%. +- `lightcraft-cli calibrate` now also learns the camera's tone curve from all the photos it reads, and a profile + made with it carries the curve. A photo of that camera follows its own JPEG's curve as far as that JPEG shows it + and the camera's curve beyond, so an underexposed shot pushed back up matches a properly exposed one in + brightness instead of coming out 4–7 L* darker. Profiles made before keep working; refit them to get the curve. ## 2026-10-14 From 1105af1d9e6d144a67417f271d955d37b1f322e8 Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:00:19 -0400 Subject: [PATCH 04/98] LR-PROF-CAMERACOLOR: pooled tone fit keeps negative channels, as the render does fit_profile_tone clamped each channel at zero after the profile matrix before taking luminance. Raw decoding keeps negative channels and the camera curve gets their unclamped luminance, so saturated colours were fitted at a different input than they render at (a magenta with negative green read 30% brighter). Found by CodeRabbit on #2092. --- crates/engine/src/camera_preview.rs | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index f23fa27577..a913882fb0 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -871,9 +871,10 @@ fn tone_sample(input: [f32; 3], output: [f32; 3]) -> bool { /// A camera profile's tone curve from the tone samples pooled over its photos, through the profile's `matrix`: one /// curve for the camera, from shadows that only dark photos show to highlights that only bright ones show. Quantile /// matching ([`fit_tone`]) pools correctly because every photo went through the same camera curve (picture styles and -/// Active D-Lighting aside, which it averages). +/// Active D-Lighting aside, which it averages). Luminance is taken with negative channels kept, as the render feeds +/// the curve (raw decoding keeps them, `files::CameraColourModel`). pub(crate) fn fit_profile_tone(samples: &[([f64; 3], f64)], matrix: &Mat3) -> Option { - fit_tone(samples.iter().map(|(x, y)| (luma(matrix.apply(*x).map(|v| v.max(0.0))), *y)).filter(|(x, _)| *x > 0.0).collect()) + fit_tone(samples.iter().map(|(x, y)| (luma(matrix.apply(*x)), *y)).filter(|(x, _)| *x > 0.0).collect()) } /// `photo`'s tone curve where its JPEG taught it, `pooled`'s past that: from the photo's last knot it fades over @@ -4150,6 +4151,26 @@ mod tests { assert!(fit_profile_tone(&samples[..64], &matrix).is_none(), "too few samples"); } + #[test] + fn a_pooled_tone_curve_takes_luminance_with_negative_channels_as_the_render_does() { + // a saturating matrix sends this magenta's green channel negative; the render keeps it, so the curve's input + // is the unclamped luminance (clamped, the magenta samples read 30% brighter and pull the pooled quantiles) + let matrix = Mat3([[1.3, -0.2, -0.1], [-0.1, 1.2, -0.1], [-0.1, -0.5, 1.6]]); + let magenta = [0.9, 0.05, 0.9]; + assert!(matrix.apply(magenta)[1] < 0.0); + let samples: Vec<([f64; 3], f64)> = (0..4000) + .map(|i| { + let colour = if i % 2 == 0 { magenta } else { [1.0; 3] }; + let x = colour.map(|v| v * 0.001 * 500f64.powf(f64::from(i / 2) / 2000.0)); + (x, f64::from(camera_curve(luma(matrix.apply(x)) as f32))) + }) + .collect(); + let tone = fit_profile_tone(&samples, &matrix).unwrap(); + for x in [0.002f32, 0.02, 0.1, 0.3] { + assert!((tone.apply(x) - camera_curve(x)).abs() < 0.01 + 0.03 * camera_curve(x), "{x}: {} vs {}", tone.apply(x), camera_curve(x)); + } + } + #[test] fn a_photo_no_look_fits_takes_the_profiles_pooled_tone_curve() { let colour = (Mat3::IDENTITY, None); From 27d65b252bc568910cf53fd6ebebe2f99f5ab529 Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:00:21 -0400 Subject: [PATCH 05/98] LR-PROF-CAMERACOLOR: only a look with the profile's colour takes its pooled tone curve The pooled curve maps luminance through the profile's matrix. A photo whose own fit rejected the profile's colour renders through its own matrix, so continuing its curve along the pooled one gave it a highlight mapping fitted to other colours. Such a look now keeps its curve as fitted (with_pooled_tone). LOOK_VERSION 12. Found by CodeRabbit on #2093. --- crates/engine/src/camera_preview.rs | 33 ++++++++++++++++++++++++----- docs/camera-preview-colour.md | 2 +- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index a913882fb0..756ad32c77 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -36,7 +36,8 @@ use lightcraft_raw::{ /// 9: the bundled NIKON Z 8 and NIKON D5300 profiles. /// 10: a photo no look fits keeps its camera profile's colour instead of the neutral fallback. /// 11: a camera profile's pooled tone curve continues a photo's own past what its JPEG showed. -pub const LOOK_VERSION: u32 = 11; +/// 12: only a look with the profile's colour continues along its pooled tone curve. +pub const LOOK_VERSION: u32 = 12; #[derive(Clone, Debug)] pub(crate) struct CameraLook { @@ -273,6 +274,7 @@ pub(crate) fn fit_preview(raw: &RawImage, bytes: &[u8], transform: &CameraTransf 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 pooled = profile.as_ref().and_then(|p| p.tone); + let profile_matrix = colour.as_ref().map(|c| c.0); let fitted = fit_look(&sensor, &reference, &clipped, colour.clone()); let tone_only = |colour| { let unclipped = without_clipped(&sensor, &clipped); @@ -280,10 +282,7 @@ pub(crate) fn fit_preview(raw: &RawImage, bytes: &[u8], transform: &CameraTransf }; let Some(look) = with_profile_colour(fitted, colour, pooled, tone_only) else { return (None, black_and_white) }; // the camera's own curve past what this photo's JPEG showed - let look = match pooled { - Some(pooled) => CameraLook { tone: extend_tone(&look.tone, &pooled), ..look }, - None => look, - }; + let look = with_pooled_tone(look, profile_matrix, pooled); // Sony's Dynamic Range Optimizer (on by default) brightens the camera JPEG's darker regions, // not the raw: keep the colour fitted to the JPEG, take the tone curve without DRO. let dro = lightcraft_raw::embedded_preview_dynamic_range_optimized(bytes) == Some(true); @@ -301,6 +300,16 @@ pub(crate) fn fit_preview(raw: &RawImage, bytes: &[u8], transform: &CameraTransf (Some(look), black_and_white) } +/// `look` with its tone curve continued along the camera profile's `pooled` one ([`extend_tone`]), when the look +/// takes the profile's colour (`profile_matrix`). A look fitted with the photo's own matrix keeps its curve: the pooled +/// one maps luminance through the profile's matrix, which that photo's colours don't go through. +fn with_pooled_tone(look: CameraLook, profile_matrix: Option, pooled: Option) -> CameraLook { + match (pooled, profile_matrix) { + (Some(pooled), Some(matrix)) if look.matrix == matrix => CameraLook { tone: extend_tone(&look.tone, &pooled), ..look }, + _ => look, + } +} + /// `fitted`, the photo's own look, or when no look fits it (a black-and-white JPEG has no colour; a dark one too few /// colour pairs) its camera profile's `colour`: with the JPEG's tone curve when [`fit_tone_only`] finds one /// (`monochrome_look` does it without a profile), else the profile's pooled tone curve, else the default raw one. Dropping the profile there for the @@ -4171,6 +4180,20 @@ mod tests { } } + #[test] + fn only_a_look_with_the_profiles_colour_continues_along_its_pooled_curve() { + let profile = Mat3([[1.2, -0.1, -0.1], [-0.1, 1.1, 0.0], [0.0, -0.2, 1.2]]); + let pooled = sampled(camera_curve, 0.0005, 0.9); + let dark = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.02); + let with = |matrix| CameraLook { matrix, tone: dark, hue_sat: None }; + // the profile's colour: the curve goes on along the pooled one + assert_eq!(with_pooled_tone(with(profile), Some(profile), Some(pooled)).tone, extend_tone(&dark, &pooled)); + // the photo's own matrix (the profile's colour rejected): its curve as fitted + assert_eq!(with_pooled_tone(with(Mat3::IDENTITY), Some(profile), Some(pooled)).tone, dark); + assert_eq!(with_pooled_tone(with(profile), None, Some(pooled)).tone, dark); + assert_eq!(with_pooled_tone(with(profile), Some(profile), None).tone, dark); + } + #[test] fn a_photo_no_look_fits_takes_the_profiles_pooled_tone_curve() { let colour = (Mat3::IDENTITY, None); diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index 40ac01ec29..199160449b 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -195,7 +195,7 @@ When no look fits a photo of a profiled model (step 2 and 3 both fail: a black-a Before this, such a photo fell to 4 or 5 and the profile did nothing for it. Measured on two bracketed bursts of one NIKON D780 scene (a colourful woven runner in low sun, ISO 100, f/8, frames 1.1 to 3.7 EV under the burst's brightest, each rendered with Exposure raised by its measured offset and compared with the brightest frame, CIEDE2000 and chroma of the colourful areas), with a local profile pooled from 255 of the photographer's D780 photos: the five frames 2.8 EV or more under have no look (their camera JPEGs are nearly black) and rendered at 35-48% of the reference's chroma with hue off by up to 9° whether or not the profile existed; with the profile's colour kept they render at 88-99% of it, hue within 5°. Frames up to 2.3 EV under fit a look and are unchanged. The pushed frames remain 4-7 L\* darker than the reference: a dark photo's tone curve is fitted to its shadows only (or is the default curve), which the profile's colour doesn't change (the pooled tone curve, next, does). -**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85, at most 4,000 per photo), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`); a photo no look fits takes the pooled curve whole instead of the default one. +**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85, at most 4,000 per photo), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model whose look takes the profile's colour keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`); a look fitted with the photo's own matrix (the profile's colour rejected) keeps its curve as fitted, since the pooled one maps luminance through the profile's matrix (`with_pooled_tone`, `LOOK_VERSION` 12); a photo no look fits takes the pooled curve whole instead of the default one. On the same D780 brackets with the profile refitted with its tone curve (255 photos), the pushed frames match the reference's lightness: ΔL\* −0.2 to +0.5 for every frame (−1 to −7 before), median CIEDE2000 in the L\* 40-70 band 0.9-2.6 (2.0-13.5 before), hue within 5°. Colourfulness in the second burst comes out 16-28% above the reference in midtones. On 40 D780 photos the profile never saw, rendered unedited and compared with their camera JPEGs, the curve changes nothing that matters: mean ΔE 2.67 with the colour-only profile, 2.68 with the curve (2.77 without a profile), mean ΔL\* +0.71 → +0.73, one photo worse by more than 0.25 (0.38). From 174c56c9773c53e5d1548725c17e4a3175c35afd Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:00:23 -0400 Subject: [PATCH 06/98] LR-PROF-CAMERACOLOR: photos too dark for colour pairs still give the pooled curve their shadows profile_samples returned nothing when collect_pairs found no colour pairs, so the darkest photos, the ones that show the camera's toe, never reached the pooled tone curve. Their tone samples are now kept; Pool counts them apart from the colour fit's photos and calibrate reports them as tone only. A black-and-white camera JPEG (a monochrome picture style's own mix and curve) gives nothing, as before. Found by CodeRabbit on #2093. --- apps/lightcraft-cli/src/main.rs | 7 +++-- crates/engine/src/camera_preview.rs | 44 +++++++++++++++++++++++++--- crates/engine/src/camera_profiles.rs | 31 ++++++++++++++++---- docs/camera-preview-colour.md | 2 +- 4 files changed, 71 insertions(+), 13 deletions(-) diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rs index 6e09e2a010..47d85ed143 100644 --- a/apps/lightcraft-cli/src/main.rs +++ b/apps/lightcraft-cli/src/main.rs @@ -251,8 +251,11 @@ fn calibrate(args: &[String]) -> Result<(), String> { let result = std::fs::read(path).map_err(|e| e.to_string()).and_then(|bytes| pool.add(&bytes)); let n = done.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; match result { - Ok(Some(model)) => eprintln!("[{n}/{}] {} ({model})", files.len(), path.display()), - Ok(None) => eprintln!("[{n}/{}] {}: skipped (no usable camera JPEG or colour)", files.len(), path.display()), + Ok(Some(added)) if added.colour => eprintln!("[{n}/{}] {} ({})", files.len(), path.display(), added.model), + Ok(Some(added)) => { + eprintln!("[{n}/{}] {} ({}, tone only: too dark or colourless)", files.len(), path.display(), added.model) + } + Ok(None) => eprintln!("[{n}/{}] {}: skipped (no usable or a black-and-white camera JPEG)", files.len(), path.display()), Err(e) => eprintln!("[{n}/{}] {}: {e}", files.len(), path.display()), } } diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index 756ad32c77..b1cdee5890 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -840,7 +840,7 @@ fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rg /// colour matrices, other files or unusable previews. /// What one photo contributes to a camera profile ([`profile_samples`]), in white-balanced camera RGB. pub(crate) struct ProfileSamples { - /// Colour pairs: camera RGB → the camera JPEG's linear Rec.2020. + /// Colour pairs: camera RGB → the camera JPEG's linear Rec.2020 (empty when the photo has too little colour). pub colour: Vec<([f64; 3], [f64; 3])>, /// Tone samples: camera RGB → the camera JPEG's luminance, dark pixels included (as the photo's own toe fit takes /// them, [`fit_tone_with_shadows`]). @@ -857,15 +857,29 @@ pub(crate) fn profile_samples(raw: &RawImage, bytes: &[u8], lens: Option<&LensGe 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); - let (pairs, _) = collect_pairs(&sensor, &reference, 0.05, None, false)?; - let tone = sensor + samples_from_proxies(&sensor, &reference, &to_camera) +} + +/// [`profile_samples`] from a raw's sensor proxy (clipped pixels left out) and its camera JPEG's, `to_camera` taking the +/// sensor proxy back to white-balanced camera RGB. +fn samples_from_proxies(sensor: &Rgb32f, reference: &Rgb32f, to_camera: &Mat3) -> Option { + // a black-and-white JPEG went through a monochrome picture style's own mix and curve: nothing for the profile + if monochrome(reference) { + return None; + } + // a dark or colourless photo has no colour pairs but still shows the shadows the pooled curve needs + let colour = collect_pairs(sensor, reference, 0.05, None, false).map_or_else(Vec::new, |(pairs, _)| pairs); + let tone: Vec<_> = sensor .data .iter() .zip(&reference.data) .filter(|(input, output)| tone_sample(**input, **output)) .map(|(input, output)| (to_camera.apply(input.map(f64::from)), f64::from(luminance_2020(*output)))) .collect(); - Some(ProfileSamples { colour: pairs.into_iter().map(|(x, y)| (to_camera.apply(x), y)).collect(), tone }) + if colour.is_empty() && tone.is_empty() { + return None; + } + Some(ProfileSamples { colour: colour.into_iter().map(|(x, y)| (to_camera.apply(x), y)).collect(), tone }) } /// Whether a sensor/JPEG proxy pixel pair can teach the tone curve: every channel above the sensor floor, the JPEG @@ -4160,6 +4174,28 @@ mod tests { assert!(fit_profile_tone(&samples[..64], &matrix).is_none(), "too few samples"); } + #[test] + fn a_photo_too_dark_for_colour_pairs_still_gives_the_pooled_curve_its_shadows() { + // a scene of saturated colours, its camera JPEG a linear map of the sensor; `level` sets the exposure + let colours = [[0.9, 0.2, 0.1], [0.1, 0.8, 0.2], [0.2, 0.3, 0.9], [0.8, 0.7, 0.1], [0.6, 0.2, 0.7], [0.5, 0.5, 0.5]]; + let scene = |level: f32| { + let sensor = Rgb32f::from_fn(64, 64, |x, y| colours[(x / 8 + y / 8) % colours.len()].map(|v| v * level * (1.0 + (x % 8) as f32 / 16.0))); + let reference = Rgb32f::from_fn(64, 64, |x, y| sensor.data[y * 64 + x].map(|v| v * 0.8)); + (sensor, reference) + }; + let (sensor, reference) = scene(0.3); + let bright = samples_from_proxies(&sensor, &reference, &Mat3::IDENTITY).unwrap(); + assert!(!bright.colour.is_empty() && !bright.tone.is_empty()); + // every JPEG channel under the colour-pair floor, its luminance still above the tone floor + let (sensor, reference) = scene(0.003); + assert!(reference.data.iter().all(|p| p.iter().all(|v| *v < 0.004))); + let dark = samples_from_proxies(&sensor, &reference, &Mat3::IDENTITY).expect("tone samples from a dark photo"); + assert!(dark.colour.is_empty() && dark.tone.len() > 1000, "{} colour pairs, {} tone samples", dark.colour.len(), dark.tone.len()); + // a black-and-white camera JPEG gives nothing + let grey = Rgb32f::from_fn(64, 64, |x, y| [luminance_2020(reference.data[y * 64 + x]) * 100.0; 3]); + assert!(samples_from_proxies(&scene(0.3).0, &grey, &Mat3::IDENTITY).is_none()); + } + #[test] fn a_pooled_tone_curve_takes_luminance_with_negative_channels_as_the_render_does() { // a saturating matrix sends this magenta's green channel negative; the render keeps it, so the curve's input diff --git a/crates/engine/src/camera_profiles.rs b/crates/engine/src/camera_profiles.rs index 298c8311e9..8332fd93b6 100644 --- a/crates/engine/src/camera_profiles.rs +++ b/crates/engine/src/camera_profiles.rs @@ -203,11 +203,22 @@ pub struct Pool { #[derive(Default)] struct Model { + /// Photos that gave colour pairs (the colour fit's photo count). files: usize, + /// Photos that gave tone samples only (too dark or colourless for colour pairs). + tone_files: usize, pairs: Vec<([f64; 3], [f64; 3])>, tone: Vec<([f64; 3], f64)>, } +/// What [`Pool::add`] took from one raw file. +#[derive(Clone, Debug, PartialEq)] +pub struct Added { + pub model: String, + /// Whether it gave colour pairs; `false`: tone samples only, not counted toward a profile's photos. + pub colour: bool, +} + /// Most colour pairs (and, separately, tone samples) kept per photo, so a few busy photos can't dominate a profile. const PAIRS_PER_FILE: usize = 4000; @@ -218,9 +229,11 @@ fn thinned(items: Vec) -> impl Iterator { } 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). - pub fn add(&mut self, bytes: &[u8]) -> Result, String> { + /// 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 + /// camera JPEG). + 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) @@ -229,10 +242,15 @@ impl Pool { let Some(model) = raw.metadata.model.as_deref().map(str::trim).filter(|m| !m.is_empty()) else { return Ok(None) }; let Some(samples) = crate::camera_preview::profile_samples(&raw, bytes, lens.as_ref()) else { return Ok(None) }; let entry = self.models.entry(model.to_owned()).or_default(); - entry.files += 1; - entry.pairs.extend(thinned(samples.colour)); + let colour = !samples.colour.is_empty(); + if colour { + entry.files += 1; + entry.pairs.extend(thinned(samples.colour)); + } else { + entry.tone_files += 1; + } entry.tone.extend(thinned(samples.tone)); - Ok(Some(model.to_owned())) + Ok(Some(Added { model: model.to_owned(), colour })) } /// Fit a profile per model with at least `min_files` photos. @@ -255,6 +273,7 @@ impl Pool { for (model, m) in other.models { let entry = self.models.entry(model).or_default(); entry.files += m.files; + entry.tone_files += m.tone_files; entry.pairs.extend(m.pairs); entry.tone.extend(m.tone); } diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index 199160449b..c9ba6e90cb 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -195,7 +195,7 @@ When no look fits a photo of a profiled model (step 2 and 3 both fail: a black-a Before this, such a photo fell to 4 or 5 and the profile did nothing for it. Measured on two bracketed bursts of one NIKON D780 scene (a colourful woven runner in low sun, ISO 100, f/8, frames 1.1 to 3.7 EV under the burst's brightest, each rendered with Exposure raised by its measured offset and compared with the brightest frame, CIEDE2000 and chroma of the colourful areas), with a local profile pooled from 255 of the photographer's D780 photos: the five frames 2.8 EV or more under have no look (their camera JPEGs are nearly black) and rendered at 35-48% of the reference's chroma with hue off by up to 9° whether or not the profile existed; with the profile's colour kept they render at 88-99% of it, hue within 5°. Frames up to 2.3 EV under fit a look and are unchanged. The pushed frames remain 4-7 L\* darker than the reference: a dark photo's tone curve is fitted to its shadows only (or is the default curve), which the profile's colour doesn't change (the pooled tone curve, next, does). -**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85, at most 4,000 per photo), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model whose look takes the profile's colour keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`); a look fitted with the photo's own matrix (the profile's colour rejected) keeps its curve as fitted, since the pooled one maps luminance through the profile's matrix (`with_pooled_tone`, `LOOK_VERSION` 12); a photo no look fits takes the pooled curve whole instead of the default one. +**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85, at most 4,000 per photo; a photo too dark or colourless for colour pairs still gives these, without counting toward the profile's photos, and a black-and-white camera JPEG gives none), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model whose look takes the profile's colour keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`); a look fitted with the photo's own matrix (the profile's colour rejected) keeps its curve as fitted, since the pooled one maps luminance through the profile's matrix (`with_pooled_tone`, `LOOK_VERSION` 12); a photo no look fits takes the pooled curve whole instead of the default one. On the same D780 brackets with the profile refitted with its tone curve (255 photos), the pushed frames match the reference's lightness: ΔL\* −0.2 to +0.5 for every frame (−1 to −7 before), median CIEDE2000 in the L\* 40-70 band 0.9-2.6 (2.0-13.5 before), hue within 5°. Colourfulness in the second burst comes out 16-28% above the reference in midtones. On 40 D780 photos the profile never saw, rendered unedited and compared with their camera JPEGs, the curve changes nothing that matters: mean ΔE 2.67 with the colour-only profile, 2.68 with the curve (2.77 without a profile), mean ΔL\* +0.71 → +0.73, one photo worse by more than 0.25 (0.38). From 542bb59fbf7684abce2ba1d370e7ecf6c520fc28 Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:00:25 -0400 Subject: [PATCH 07/98] LR-PROF-CAMERACOLOR: continuing a photo's curve keeps it where its JPEG taught it To make room for the pooled extension in the curve's 32 knots, extend_tone kept every n-th knot of the photo's own curve, which could move the curve inside the range its JPEG showed (a sharp toe most). It now drops the knots the curve needs least, one at a time, within one 8-bit code (thinned_knots); with fewer extension knots if needed, or the photo's curve as fitted when even two don't fit. On a D750 bracket renders move by at most dE 0.09. LOOK_VERSION 13. Found by CodeRabbit on #2093. --- crates/engine/src/camera_preview.rs | 84 +++++++++++++++++++++++++++-- docs/camera-preview-colour.md | 2 +- 2 files changed, 80 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index b1cdee5890..f5e7d26baa 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -37,7 +37,8 @@ use lightcraft_raw::{ /// 10: a photo no look fits keeps its camera profile's colour instead of the neutral fallback. /// 11: a camera profile's pooled tone curve continues a photo's own past what its JPEG showed. /// 12: only a look with the profile's colour continues along its pooled tone curve. -pub const LOOK_VERSION: u32 = 12; +/// 13: continuing a photo's curve keeps it as it was where its JPEG taught it (`thinned_knots`). +pub const LOOK_VERSION: u32 = 13; #[derive(Clone, Debug)] pub(crate) struct CameraLook { @@ -916,14 +917,25 @@ fn extend_tone(photo: &CameraTone, pooled: &CameraTone) -> CameraTone { if !(span.is_finite() && span > 0.2) { return *photo; } - let extra = ((span * EXTEND_KNOTS_PER_EV).round() as usize).clamp(2, 16); + // the photo's own knots, the ones its curve needs least dropped to make room: as many extension knots as keep the + // curve within `THIN_TOLERANCE` where the JPEG taught it, at least 2, else the photo keeps its curve as it is + let Some((extra, own)) = + (2..=((span * EXTEND_KNOTS_PER_EV).round() as usize).clamp(2, 16)).rev().find_map(|extra| thinned_knots(own, 32 - extra).map(|k| (extra, k))) + else { + if lightcraft_pipeline::profiling() { + eprintln!("[profile] camera look: the photo's curve can't make room for the pooled one, kept as fitted"); + } + return *photo; + }; + if lightcraft_pipeline::profiling() { + eprintln!("[profile] camera look: pooled tone curve joined with {extra} knots past the photo's"); + } let at_end = pooled.apply(end[0]); let ratio = if at_end > 0.0 && end[1] > 0.0 { end[1] / at_end } else { 1.0 }; let mut knots = [[0.0f32; 2]; 32]; - // the photo's own knots, evenly thinned to make room, always keeping its first and last let kept = 32 - extra; - for (i, knot) in knots.iter_mut().take(kept).enumerate() { - *knot = own[i * 31 / (kept - 1)]; + for (knot, own) in knots.iter_mut().zip(&own) { + *knot = *own; } for k in 1..=extra { let ev = span * k as f32 / extra as f32; @@ -941,6 +953,37 @@ fn extend_tone(photo: &CameraTone, pooled: &CameraTone) -> CameraTone { CameraTone::new(knots).and_then(|tone| tone.with_chroma(*photo.chroma())).unwrap_or(*photo) } +/// Largest change, in gamma-encoded display values (1/2.2), that thinning a photo's curve for [`extend_tone`] may make +/// where its JPEG taught it: one 8-bit code. +const THIN_TOLERANCE: f32 = 1.0 / 255.0; + +/// `knots` thinned to `keep` (first and last kept), dropping one at a time the knot whose removal changes the curve +/// least (`CameraTone::apply` interpolates linearly, so the change peaks at a dropped knot); `None` when that change +/// would exceed [`THIN_TOLERANCE`]. +fn thinned_knots(knots: &[[f32; 2]; 32], keep: usize) -> Option> { + let encoded = |v: f32| v.max(0.0).powf(1.0 / 2.2); + // the change from leaving out every knot strictly between kept indices `a` and `b` + let gap = |a: usize, b: usize| { + let ([x0, y0], [x1, y1]) = (knots[a], knots[b]); + (a + 1..b) + .map(|i| { + let [x, y] = knots[i]; + let t = if x1 > x0 { (x - x0) / (x1 - x0) } else { 0.0 }; + (encoded(y0 + t * (y1 - y0)) - encoded(y)).abs() + }) + .fold(0.0f32, f32::max) + }; + let mut kept: Vec = (0..knots.len()).collect(); + while kept.len() > keep.max(2) { + let (i, change) = (1..kept.len() - 1).map(|i| (i, gap(kept[i - 1], kept[i + 1]))).min_by(|a, b| a.1.total_cmp(&b.1))?; + if change > THIN_TOLERANCE { + return None; + } + kept.remove(i); + } + Some(kept.into_iter().map(|i| knots[i]).collect()) +} + /// A camera profile's colour model (matrix from white-balanced camera RGB, hue/saturation table) /// fitted to pairs pooled from many photos. pub(crate) fn fit_profile(pairs: &[([f64; 3], [f64; 3])]) -> Option<(Mat3, Option)> { @@ -4157,6 +4200,37 @@ mod tests { assert_eq!(extend_tone(&bright, &pooled), bright); } + #[test] + fn extending_a_photos_curve_keeps_it_where_its_jpeg_taught_it() { + let pooled = sampled(camera_curve, 0.0005, 0.9); + let encoded = |v: f32| v.max(0.0).powf(1.0 / 2.2); + // a smooth dark curve, and one with a sharp toe (flat, then a steep rise over two knots) + let smooth = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.02); + let toe = CameraTone::new(std::array::from_fn(|i| { + let x = 0.0005 * 40f32.powf(i as f32 / 31.0); + [ + x, + if i < 9 { + 0.001 + 0.0001 * i as f32 + } else if i < 11 { + 0.004 + 0.012 * (i - 8) as f32 + } else { + 0.03 + 0.004 * (i - 10) as f32 + }, + ] + })) + .unwrap(); + for photo in [smooth, toe] { + let tone = extend_tone(&photo, &pooled); + for [x, _] in photo.knots() { + let change = (encoded(tone.apply(*x)) - encoded(photo.apply(*x))).abs(); + assert!(change <= THIN_TOLERANCE + 1e-5, "{x}: {} vs {} ({change})", tone.apply(*x), photo.apply(*x)); + } + } + // the smooth one still goes on along the pooled curve + assert!((extend_tone(&smooth, &pooled).apply(0.3) - pooled.apply(0.3)).abs() < 0.01); + } + #[test] fn a_pooled_tone_curve_spans_dark_and_bright_photos() { // camera RGB grey (white balanced): a dark photo's pixels and a bright one's, through one camera curve diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index c9ba6e90cb..db9844e12a 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -195,7 +195,7 @@ When no look fits a photo of a profiled model (step 2 and 3 both fail: a black-a Before this, such a photo fell to 4 or 5 and the profile did nothing for it. Measured on two bracketed bursts of one NIKON D780 scene (a colourful woven runner in low sun, ISO 100, f/8, frames 1.1 to 3.7 EV under the burst's brightest, each rendered with Exposure raised by its measured offset and compared with the brightest frame, CIEDE2000 and chroma of the colourful areas), with a local profile pooled from 255 of the photographer's D780 photos: the five frames 2.8 EV or more under have no look (their camera JPEGs are nearly black) and rendered at 35-48% of the reference's chroma with hue off by up to 9° whether or not the profile existed; with the profile's colour kept they render at 88-99% of it, hue within 5°. Frames up to 2.3 EV under fit a look and are unchanged. The pushed frames remain 4-7 L\* darker than the reference: a dark photo's tone curve is fitted to its shadows only (or is the default curve), which the profile's colour doesn't change (the pooled tone curve, next, does). -**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85, at most 4,000 per photo; a photo too dark or colourless for colour pairs still gives these, without counting toward the profile's photos, and a black-and-white camera JPEG gives none), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model whose look takes the profile's colour keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`); a look fitted with the photo's own matrix (the profile's colour rejected) keeps its curve as fitted, since the pooled one maps luminance through the profile's matrix (`with_pooled_tone`, `LOOK_VERSION` 12); a photo no look fits takes the pooled curve whole instead of the default one. +**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85, at most 4,000 per photo; a photo too dark or colourless for colour pairs still gives these, without counting toward the profile's photos, and a black-and-white camera JPEG gives none), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model whose look takes the profile's colour keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`; to make room in the curve's 32 knots it drops the photo's knots its curve needs least, by at most one 8-bit code where the JPEG taught it, using fewer extension knots or keeping the photo's curve as fitted otherwise: `thinned_knots`, `LOOK_VERSION` 13); a look fitted with the photo's own matrix (the profile's colour rejected) keeps its curve as fitted, since the pooled one maps luminance through the profile's matrix (`with_pooled_tone`, `LOOK_VERSION` 12); a photo no look fits takes the pooled curve whole instead of the default one. On the same D780 brackets with the profile refitted with its tone curve (255 photos), the pushed frames match the reference's lightness: ΔL\* −0.2 to +0.5 for every frame (−1 to −7 before), median CIEDE2000 in the L\* 40-70 band 0.9-2.6 (2.0-13.5 before), hue within 5°. Colourfulness in the second burst comes out 16-28% above the reference in midtones. On 40 D780 photos the profile never saw, rendered unedited and compared with their camera JPEGs, the curve changes nothing that matters: mean ΔE 2.67 with the colour-only profile, 2.68 with the curve (2.77 without a profile), mean ΔL\* +0.71 → +0.73, one photo worse by more than 0.25 (0.38). From 16cc541d0a0c02a6267c72a4f8505708da1e8464 Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:00:27 -0400 Subject: [PATCH 08/98] LR-PROF-CAMERACOLOR: revision rows out of the parity checklist's Import table Two revision rows from this PR, and two older LR-IMP-FORMATS ones, sat in the six-column A. Import table instead of the revision history. Found by CodeRabbit on #2092. --- docs/parity-checklist.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index e14acb4fb3..c7aa7e69c8 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-16 · **Change:** minor (LR-PROF-CAMERACOLOR: dark photos keep their camera profile's colour; pooled camera tone curves) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** patch (revision rows moved out of the Import table) · **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 @@ -69,10 +69,6 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| -| 2026-10-16 | minor | LR-PROF-CAMERACOLOR: camera profiles carry a pooled tone curve that continues each photo's own past its JPEG's range; status unchanged (🟡) | -| 2026-10-16 | minor | LR-PROF-CAMERACOLOR: a photo no look fits keeps its camera profile's colour instead of the neutral fallback; status unchanged (🟡) | -| 2026-10-12 | minor | LR-IMP-FORMATS: Mamiya MEF decodes from sensor data and is imported (`vendor/mef.rs`) | -| 2026-10-12 | minor | LR-IMP-FORMATS: Epson ERF decodes from sensor data (`vendor/erf.rs`), no longer preview-only | | LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with thumbnails and checkboxes (duplicates by path/content marked and unchecked; with several file types, a toggle per type checks or unchecks all of its files, e.g. the raws without the JPEGs beside them, issue #344) filling a resizable window (issue #337), transfer mode (add in place / copy / move, each explained), album (existing/new), preset, keywords; the folder scan runs on a background thread, shown in the activity stack with ✕ to cancel (a NAS folder no longer freezes the window); the import itself (probing, sidecars, copying / moving files) runs on a worker thread and its batches join the library between frames, shown in the activity stack with ✕ to cancel; one undo step. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lightcraft_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/lightcraft/src/dialog_filter.rs`, issue #342; 0.4.0 hid `.JPG` / `.NEF`, issue #705). The folder scan, Browse Folder, drag-and-drop and the sidecar lookup match extensions in any case (`crates/engine/src/tests_import.rs`) | | LR-IMP-DRAGDROP | Drop files/folders to import | P0 | ✅ | `crates/ui-egui/src/lib.rs` (dropped files → `cmd:library.import`) | dropping onto a specific album not supported | | LR-IMP-DUPES | Skip duplicates by content | P1 | ✅ | `crates/engine/src/import.rs`, `crates/engine/src/tests_import.rs` | | @@ -799,12 +795,17 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-18 | patch | Four revision rows (LR-PROF-CAMERACOLOR, LR-IMP-FORMATS) that had landed in the A. Import table moved here; no status changes | | 2026-10-14 | patch | LR-EXP-TYPE: opaque 8-bit PNG/TIFF/WebP use RGB; transparent exports retain alpha (#1670). Statuses and feature counts unchanged. | | 2026-10-15 | minor | LRC-PRINT-PAGE: Page Options (Page Numbers, Page Info, Crop Marks) on Single Image and Contact Sheet pages, in the Print dialog, `print.set` and templates; still 🟡 (no identity plate, watermark, photo info or Cut Guides) | | 2026-10-15 | minor | LR-IMP-FORMATS: Hasselblad 3FR and FFF show their uncompressed RGB preview (no JPEG in these files) in the grid and loupe until developed, and as the stand-in when a file fails to decode; status unchanged (🟡) | | 2026-10-15 | minor | LR-IMP-FORMATS: a Hasselblad FFF develops with the camera's colour matrix from the original 3FR header it embeds (tag `0xC51B`) instead of the neutral matrix; status unchanged (🟡) | +| 2026-10-16 | minor | LR-PROF-CAMERACOLOR: a photo no look fits keeps its camera profile's colour instead of the neutral fallback; status unchanged (🟡) | +| 2026-10-16 | minor | LR-PROF-CAMERACOLOR: camera profiles carry a pooled tone curve that continues each photo's own past its JPEG's range; status unchanged (🟡) | | 2026-10-16 | patch | LR-PROF-CAMERACOLOR: raw decoding keeps negative channels (noise near black) instead of clipping each at zero, which turned pushed shadows magenta; status unchanged (🟡) | | 2026-10-12 | minor | LR-EDIT-OPTICS-PROFILE: Sony ARW shading, CA and distortion tables decoded with settings and provenance (raw IFD, `SR2SubIFD` fallback); applied corrections unchanged (ILCE-7RM4A and ILCE-7RM6 distortion); status unchanged (🟡) | +| 2026-10-12 | minor | LR-IMP-FORMATS: Mamiya MEF decodes from sensor data and is imported (`vendor/mef.rs`) | +| 2026-10-12 | minor | LR-IMP-FORMATS: Epson ERF decodes from sensor data (`vendor/erf.rs`), no longer preview-only | | 2026-10-14 | minor | LR-IMP-CAMERA-COVERAGE: Camera-coverage sweep (#1327): 30 models verified on 40 CC0 files (coverage.py 515 → 545 verified); sensor verification does not establish colour parity (#1277); status unchanged (🟡) | | 2026-10-13 | minor | LR-MERGE-PANO: a panorama's DNG takes its `AsShotNeutral` from the median of its frames' vendor white-balance multipliers (CR2, NEF, ARW…) instead of the first frame's tags, and frames now carry the multipliers (issue #1144); status unchanged (✅) | | 2026-10-13 | minor | LR-MERGE-HDR: an HDR merge's DNG takes its `AsShotNeutral` from the median of its inputs' vendor white-balance multipliers instead of the reference frame's tags (issue #1144); status unchanged (🟡) | From ffede6c9f78ae4697f6135b4634df9f74a04ec0e Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Mon, 19 Oct 2026 15:02:55 +0200 Subject: [PATCH 09/98] Import: preserve embedded ratings, flags and labels via existing XMP sidecar pipeline - Apply embedded XMP to JPEG/TIFF during import via parse_sidecar and merge_into - Keep kind == Raw guard in sidecar::read_packet so non-raw originals are not read whole - Handle EXIF Rating tag (0x4746) including rejected (-1) rating in metadata extraction and writing - Add tests for embedded XMP rating & label, EXIF rating, and rejected (-1) ratings --- crates/engine/src/files.rs | 39 +++++++++------------ crates/engine/src/import.rs | 11 ++---- crates/engine/src/media.rs | 4 --- crates/engine/src/sidecar.rs | 13 ++++--- crates/engine/src/tests_import.rs | 57 +++++++++++++++++++++++++++++-- crates/meta/src/exif.rs | 13 ++++++- 6 files changed, 95 insertions(+), 42 deletions(-) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index c7fc994eee..81d41d0a09 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -125,6 +125,19 @@ pub fn embedded_lens(raw: &lightcraft_raw::RawInfo) -> Option Option { + match lightcraft_meta::embedded(bytes).xmp { + Some(x) if !x.contains("Rating") && m.rating.is_some() => { + let fresh = lightcraft_meta::write_xmp(m, None); + lightcraft_meta::merge_xmp(&x, &fresh, lightcraft_meta::MergeRules { owned_if_present: &["xmp:Rating"], ..Default::default() }) + .ok() + .or(Some(x)) + } + Some(x) => Some(x), + None => m.rating.map(|_| lightcraft_meta::write_xmp(m, None)), + } +} + fn ext_upper(name: &str) -> String { std::path::Path::new(name).extension().map(|e| e.to_string_lossy().to_uppercase()).unwrap_or_default() } @@ -137,13 +150,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { let content_hash = Some(lightcraft_preview::hash_bytes(bytes).to_string()); let m = lightcraft_meta::extract(bytes); let (meta, captured) = meta_of(&m); - let (rating, flag) = match m.rating { - Some(r) if r < 0 => (0, lightcraft_catalog::Flag::Reject), - Some(r) => (r.clamp(0, 5) as u8, lightcraft_catalog::Flag::None), - None => (0, lightcraft_catalog::Flag::None), - }; - let label = m.label.as_deref().and_then(|l| lightcraft_catalog::ColorLabel::parse(l.trim())); - let label_text = m.label.clone(); + let xmp = embedded_or_exif_xmp(bytes, &m); if lightcraft_raw::probe(bytes).is_some() { let raw = match lightcraft_raw::probe_info(bytes).map_err(|e| preview_reason(bytes, e)) { Ok(r) => r, @@ -158,13 +165,9 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { file_size: bytes.len() as u64, captured, meta, - rating, - flag, - label, - label_text, as_shot_wb: None, content_hash, - xmp: lightcraft_meta::embedded(bytes).xmp, + xmp, preview_only: Some(why), ..Default::default() }); @@ -189,13 +192,9 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { captured, file_modified: None, meta, - rating, - flag, - label, - label_text, as_shot_wb, content_hash, - xmp: lightcraft_meta::embedded(bytes).xmp, + xmp, preview_only: None, }); } @@ -225,14 +224,10 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { captured, file_modified: None, meta, - rating, - flag, - label, - label_text, as_shot_wb: None, content_hash, embedded_lens: None, - xmp: None, + xmp, preview_only: None, }) } diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 8cecda6f56..2b5d7aeda0 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -1060,12 +1060,13 @@ impl ImportJob { plan.slots.push(Slot::Item(PreparedItem::Duplicate { path, existing: *existing, reason: "content", hash: Some(h.clone()) })); continue; } - // the XMP sidecar (or a raw's embedded XMP), read before copying: its capture time files + // the XMP sidecar (or a file's embedded XMP), read before copying: its capture time files // and names the copy when the file itself has none let raw = info.kind == MediaKind::Raw; + let has_embedded_xmp = raw || matches!(info.format.as_str(), "JPEG" | "JPG" | "TIFF" | "TIF"); let packet = crate::sidecar::find_sidecar(&path, self.naming) .and_then(|f| std::fs::read_to_string(f).ok()) - .or_else(|| info.xmp.clone().filter(|_| raw)); + .or_else(|| info.xmp.clone().filter(|_| has_embedded_xmp)); let target = crate::crs::Target::for_file(info.kind, &info.format, info.preview_only.is_some(), &info.meta.camera); let sidecar = packet.and_then(|x| match crate::sidecar::parse_sidecar(&x, target) { Ok(sc) => Some(sc), @@ -1091,9 +1092,6 @@ impl ImportJob { let mut q = Photo::new(PhotoId(0), Source::File { path: path.clone() }, &own, &info.format, 0, 0, &self.now); q.captured = info.captured.clone(); q.meta = info.meta.clone(); - q.rating = info.rating; - q.flag = info.flag; - q.label = info.label; if let Some(sc) = &sidecar { crate::sidecar::merge_into(&mut q, sc, &self.now); } @@ -1421,9 +1419,6 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare p.file_size = info.file_size; p.captured = info.captured; p.meta = info.meta; - p.rating = info.rating; - p.flag = info.flag; - p.label = info.label_text.as_deref().and_then(|t| s.catalog.label_from_name(t)).or(info.label); p.as_shot_wb = info.as_shot_wb; p.content_hash = info.content_hash; p.embedded_lens = info.embedded_lens; diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 681b0bd5ce..22d76528d6 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -1658,10 +1658,6 @@ pub struct ProbeInfo { /// metadata would otherwise all land under "Unknown Date"). pub file_modified: Option, pub meta: lightcraft_catalog::Meta, - pub rating: u8, - pub flag: lightcraft_catalog::Flag, - pub label: Option, - pub label_text: Option, pub as_shot_wb: Option<(f64, f64)>, /// Hash of the file's bytes (hex), for duplicate detection. When it is a 32-digit /// [`lightcraft_preview::hash_bytes`] of the whole file (as the native probe computes it), diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 5ffa6b5042..cdee1e8942 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -500,16 +500,19 @@ fn file_path(p: &Photo) -> Option<&str> { } } -/// The XMP packet that describes a photo on disk: its sidecar, else the file's embedded XMP. -pub fn read_packet(original: &str, _kind: MediaKind, naming: SidecarNaming) -> Option<(String, PathBuf)> { +/// The XMP packet that describes a photo on disk: its sidecar, else (raw/DNG) the embedded XMP. +pub fn read_packet(original: &str, kind: MediaKind, naming: SidecarNaming) -> Option<(String, PathBuf)> { if let Some(sc) = find_sidecar(original, naming) && let Ok(s) = std::fs::read_to_string(&sc) { return Some((s, sc)); } - let bytes = std::fs::read(original).ok()?; - let x = lightcraft_meta::embedded(&bytes).xmp?; - Some((x, PathBuf::from(original))) + if kind == MediaKind::Raw { + let bytes = std::fs::read(original).ok()?; + let x = lightcraft_meta::embedded(&bytes).xmp?; + return Some((x, PathBuf::from(original))); + } + None } /// Photo ids touched by an op (for auto-write). diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs index e9f3365f41..2ac89d4661 100644 --- a/crates/engine/src/tests_import.rs +++ b/crates/engine/src/tests_import.rs @@ -1794,9 +1794,9 @@ fn presets_apply_the_imported_profile_they_name() { } #[test] -fn import_preserves_embedded_rating_and_label() { +fn import_preserves_embedded_xmp_rating_and_label() { use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; - let src = temp_dir("embedded-rating-test"); + let src = temp_dir("embedded-xmp-rating-test"); let px = [128u8; 40 * 30 * 3]; let xmp = r#""#; let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() }; @@ -1808,7 +1808,60 @@ fn import_preserves_embedded_rating_and_label() { assert_eq!(ids(&r, "imported"), 1); let p = s.catalog.photos().next().unwrap(); assert_eq!(p.rating, 5); + assert_eq!(p.flag, lightcraft_catalog::Flag::None); assert_eq!(p.label, Some(lightcraft_catalog::ColorLabel::Blue)); let _ = std::fs::remove_dir_all(&src); } + +#[test] +fn import_preserves_embedded_exif_rating() { + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("embedded-exif-rating-test"); + let px = [128u8; 40 * 30 * 3]; + let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { rating: Some(3), ..Default::default() }); + let meta = EncodeMeta { exif: Some(&exif), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("exif_rating.jpg"), &bytes).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.join("exif_rating.jpg").to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 1); + let p = s.catalog.photos().next().unwrap(); + assert_eq!(p.rating, 3); + assert_eq!(p.flag, lightcraft_catalog::Flag::None); + + let _ = std::fs::remove_dir_all(&src); +} + +#[test] +fn import_preserves_embedded_rejected_rating() { + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("embedded-rejected-rating-test"); + let px = [128u8; 40 * 30 * 3]; + + // Case 1: EXIF rating -1 + let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { rating: Some(-1), ..Default::default() }); + let meta = EncodeMeta { exif: Some(&exif), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("exif_rejected.jpg"), &bytes).unwrap(); + + // Case 2: XMP rating -1 + let xmp = r#""#; + let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("xmp_rejected.jpg"), &bytes).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 2); + let exif_p = s.catalog.photos().find(|p| p.file_name == "exif_rejected.jpg").unwrap(); + assert_eq!(exif_p.rating, 0); + assert_eq!(exif_p.flag, lightcraft_catalog::Flag::Reject); + + let xmp_p = s.catalog.photos().find(|p| p.file_name == "xmp_rejected.jpg").unwrap(); + assert_eq!(xmp_p.rating, 0); + assert_eq!(xmp_p.flag, lightcraft_catalog::Flag::Reject); + + let _ = std::fs::remove_dir_all(&src); +} diff --git a/crates/meta/src/exif.rs b/crates/meta/src/exif.rs index 2b2ea1d131..f2c9ceef4a 100644 --- a/crates/meta/src/exif.rs +++ b/crates/meta/src/exif.rs @@ -67,7 +67,10 @@ pub fn from_tiff(tiff: &Tiff) -> Metadata { m.lens_spec = nikon_lens_spec(exif, m.make.as_deref(), tiff.order); } m.orientation = ifd0.and_then(|i| i.u16(t::ORIENTATION)).filter(|v| (1..=8).contains(v)).map(Orientation::from_exif); - m.rating = ifd0.and_then(|i| i.i64(t::RATING)).map(|r| r.clamp(-1, 5) as i8); + m.rating = ifd0.and_then(|i| i.i64(t::RATING)).map(|r| { + let r = if r == 65535 || r == -1 { -1 } else { r }; + r.clamp(-1, 5) as i8 + }); m.exposure_time = pos(either(t::EXPOSURE_TIME).and_then(|v| v.get_f64(0))) .or_else(|| exif.and_then(|e| e.f64(t::SHUTTER_SPEED_VALUE)).filter(|v| v.abs() < 64.0).map(|tv| 2f64.powf(-tv))); @@ -444,6 +447,9 @@ pub fn write_exif(meta: &Metadata) -> Vec { ifd0.set(tag, v); } } + if let Some(r) = meta.rating { + ifd0.set(t::RATING, if r < 0 { Value::Short(vec![0xffff]) } else { Value::Short(vec![r as u16]) }); + } let mut ex = IfdBuilder::new(); ex.set(t::EXIF_VERSION, Value::Undefined(b"0232".to_vec())); let r = |v: Option| v.filter(|v| v.is_finite() && *v > 0.0).map(|v| Value::Rational(vec![rational(v)])); @@ -503,6 +509,7 @@ mod write_tests { focal_length: Some(35.0), lens_model: Some("35mm F2".into()), gps: Some(Gps { latitude: 43.7904, longitude: -110.6818, altitude: Some(2000.0) }), + rating: Some(4), ..Default::default() }; let back = read_exif(&write_exif(&m)); @@ -515,7 +522,11 @@ mod write_tests { assert!((back.f_number.unwrap() - 2.8).abs() < 1e-6); assert!((back.exposure_time.unwrap() - 0.004).abs() < 1e-9); assert_eq!(back.lens_model, m.lens_model); + assert_eq!(back.rating, Some(4)); let g = back.gps.unwrap(); assert!((g.latitude - 43.7904).abs() < 1e-5 && (g.longitude + 110.6818).abs() < 1e-5, "{g:?}"); + + let rejected = read_exif(&write_exif(&Metadata { rating: Some(-1), ..Default::default() })); + assert_eq!(rejected.rating, Some(-1)); } } From 7aeb1561ed574db776c9aae10166282307082ba7 Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Mon, 19 Oct 2026 15:25:25 +0200 Subject: [PATCH 10/98] Import: support embedded XMP in PNG/WebP and refine XMP rating detection - Check specifically for xmp:Rating property in embedded XMP before merging EXIF rating - Retain embedded XMP during import for PNG and WebP files - Add import tests for embedded-XMP PNG/WebP and EXIF rating with unrelated XMP text --- crates/engine/src/files.rs | 9 ++++- crates/engine/src/import.rs | 2 +- crates/engine/src/tests_import.rs | 55 +++++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 81d41d0a09..f51683755b 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -125,9 +125,16 @@ pub fn embedded_lens(raw: &lightcraft_raw::RawInfo) -> Option bool { + if x.contains("xmp:Rating") || x.contains("xap:Rating") || x.contains(":Rating=") || x.contains(":Rating>") || x.contains(":Rating ") { + return true; + } + lightcraft_meta::parse_xmp(x).ok().and_then(|d| d.metadata.rating).is_some() +} + fn embedded_or_exif_xmp(bytes: &[u8], m: &lightcraft_meta::Metadata) -> Option { match lightcraft_meta::embedded(bytes).xmp { - Some(x) if !x.contains("Rating") && m.rating.is_some() => { + Some(x) if !xmp_has_rating(&x) && m.rating.is_some() => { let fresh = lightcraft_meta::write_xmp(m, None); lightcraft_meta::merge_xmp(&x, &fresh, lightcraft_meta::MergeRules { owned_if_present: &["xmp:Rating"], ..Default::default() }) .ok() diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 2b5d7aeda0..96e8db7788 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -1063,7 +1063,7 @@ impl ImportJob { // the XMP sidecar (or a file's embedded XMP), read before copying: its capture time files // and names the copy when the file itself has none let raw = info.kind == MediaKind::Raw; - let has_embedded_xmp = raw || matches!(info.format.as_str(), "JPEG" | "JPG" | "TIFF" | "TIF"); + let has_embedded_xmp = raw || matches!(info.format.to_ascii_uppercase().as_str(), "JPEG" | "JPG" | "TIFF" | "TIF" | "PNG" | "WEBP"); let packet = crate::sidecar::find_sidecar(&path, self.naming) .and_then(|f| std::fs::read_to_string(f).ok()) .or_else(|| info.xmp.clone().filter(|_| has_embedded_xmp)); diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs index 2ac89d4661..1ab0b24b87 100644 --- a/crates/engine/src/tests_import.rs +++ b/crates/engine/src/tests_import.rs @@ -1865,3 +1865,58 @@ fn import_preserves_embedded_rejected_rating() { let _ = std::fs::remove_dir_all(&src); } + +#[test] +fn import_preserves_embedded_xmp_png_and_webp() { + use lightcraft_catalog::ColorLabel; + use lightcraft_codecs::{EncodeImage, EncodeMeta, Samples, encode_png, encode_webp_lossless}; + let src = temp_dir("embedded-xmp-png-webp-test"); + let px = [128u8; 40 * 30 * 3]; + + // PNG with embedded XMP rating and label + let png_xmp = r#""#; + let png_meta = EncodeMeta { xmp: Some(png_xmp), ..Default::default() }; + let png_bytes = encode_png(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), &png_meta).unwrap(); + std::fs::write(src.join("embedded.png"), &png_bytes).unwrap(); + + // WebP with embedded XMP rating and label + let webp_xmp = r#""#; + let webp_meta = EncodeMeta { xmp: Some(webp_xmp), ..Default::default() }; + let webp_bytes = encode_webp_lossless(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), &webp_meta).unwrap(); + std::fs::write(src.join("embedded.webp"), &webp_bytes).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 2); + + let png_photo = s.catalog.photos().find(|p| p.file_name == "embedded.png").unwrap(); + assert_eq!(png_photo.rating, 4); + assert_eq!(png_photo.label, Some(ColorLabel::Red)); + + let webp_photo = s.catalog.photos().find(|p| p.file_name == "embedded.webp").unwrap(); + assert_eq!(webp_photo.rating, 2); + assert_eq!(webp_photo.label, Some(ColorLabel::Blue)); + + let _ = std::fs::remove_dir_all(&src); +} + +#[test] +fn import_preserves_exif_rating_when_xmp_has_unrelated_rating_text() { + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("exif-rating-unrelated-xmp-test"); + let px = [128u8; 40 * 30 * 3]; + + let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { rating: Some(5), ..Default::default() }); + let xmp = r#"100Rating guide"#; + let meta = EncodeMeta { exif: Some(&exif), xmp: Some(xmp), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("iso_and_desc_rating.jpg"), &bytes).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.join("iso_and_desc_rating.jpg").to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 1); + let p = s.catalog.photos().next().unwrap(); + assert_eq!(p.rating, 5); + + let _ = std::fs::remove_dir_all(&src); +} From ef3d7bc67ff720d095fbe2ba6b5807d47838839e Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Mon, 19 Oct 2026 19:41:32 -0400 Subject: [PATCH 11/98] LR-PROF-CAMERACOLOR: document the pooled curve continuing a tone-only fit Co-Authored-By: Claude --- docs/camera-preview-colour.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index db9844e12a..8bfd2dc290 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -191,11 +191,11 @@ A raw starts from the first of these that is available (`camera_preview::startin 4. the model's spectral matrices, with LightCraft's default tone curve and no JPEG fit; 5. the neutral fallback. -When no look fits a photo of a profiled model (step 2 and 3 both fail: a black-and-white JPEG has no colour, a dark one too few colour pairs), it keeps the profile's colour, with the tone curve fitted alone to its JPEG when that passes the checks of the black-and-white JPEG paragraph above, else LightCraft's default tone curve (`with_profile_colour`). Without a profile, a black-and-white JPEG gives 4 and 5 the tone curve fitted to it. +When no look fits a photo of a profiled model (step 2 and 3 both fail: a black-and-white JPEG has no colour, a dark one too few colour pairs), it keeps the profile's colour, with the tone curve fitted alone to its JPEG when that passes the checks of the black-and-white JPEG paragraph above (continued along the profile's pooled tone curve when it has one, below), else the pooled tone curve whole, else LightCraft's default tone curve (`with_profile_colour`). Without a profile, a black-and-white JPEG gives 4 and 5 the tone curve fitted to it. Before this, such a photo fell to 4 or 5 and the profile did nothing for it. Measured on two bracketed bursts of one NIKON D780 scene (a colourful woven runner in low sun, ISO 100, f/8, frames 1.1 to 3.7 EV under the burst's brightest, each rendered with Exposure raised by its measured offset and compared with the brightest frame, CIEDE2000 and chroma of the colourful areas), with a local profile pooled from 255 of the photographer's D780 photos: the five frames 2.8 EV or more under have no look (their camera JPEGs are nearly black) and rendered at 35-48% of the reference's chroma with hue off by up to 9° whether or not the profile existed; with the profile's colour kept they render at 88-99% of it, hue within 5°. Frames up to 2.3 EV under fit a look and are unchanged. The pushed frames remain 4-7 L\* darker than the reference: a dark photo's tone curve is fitted to its shadows only (or is the default curve), which the profile's colour doesn't change (the pooled tone curve, next, does). -**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85, at most 4,000 per photo; a photo too dark or colourless for colour pairs still gives these, without counting toward the profile's photos, and a black-and-white camera JPEG gives none), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model whose look takes the profile's colour keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`; to make room in the curve's 32 knots it drops the photo's knots its curve needs least, by at most one 8-bit code where the JPEG taught it, using fewer extension knots or keeping the photo's curve as fitted otherwise: `thinned_knots`, `LOOK_VERSION` 13); a look fitted with the photo's own matrix (the profile's colour rejected) keeps its curve as fitted, since the pooled one maps luminance through the profile's matrix (`with_pooled_tone`, `LOOK_VERSION` 12); a photo no look fits takes the pooled curve whole instead of the default one. +**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85, at most 4,000 per photo; a photo too dark or colourless for colour pairs still gives these, without counting toward the profile's photos, and a black-and-white camera JPEG gives none), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model whose look takes the profile's colour keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`; to make room in the curve's 32 knots it drops the photo's knots its curve needs least, by at most one 8-bit code where the JPEG taught it, using fewer extension knots or keeping the photo's curve as fitted otherwise: `thinned_knots`, `LOOK_VERSION` 13); a look fitted with the photo's own matrix (the profile's colour rejected) keeps its curve as fitted, since the pooled one maps luminance through the profile's matrix (`with_pooled_tone`, `LOOK_VERSION` 12); a photo no look fits continues its tone-only curve along the pooled one in the same way, or takes the pooled curve whole instead of the default one when no tone-only curve passes. On the same D780 brackets with the profile refitted with its tone curve (255 photos), the pushed frames match the reference's lightness: ΔL\* −0.2 to +0.5 for every frame (−1 to −7 before), median CIEDE2000 in the L\* 40-70 band 0.9-2.6 (2.0-13.5 before), hue within 5°. Colourfulness in the second burst comes out 16-28% above the reference in midtones. On 40 D780 photos the profile never saw, rendered unedited and compared with their camera JPEGs, the curve changes nothing that matters: mean ΔE 2.67 with the colour-only profile, 2.68 with the curve (2.77 without a profile), mean ΔL\* +0.71 → +0.73, one photo worse by more than 0.25 (0.38). From a5e943364187b69a37a908ed7182a4e17a684ab1 Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Wed, 21 Oct 2026 07:31:07 +0200 Subject: [PATCH 12/98] Import: ignore embedded develop adjustments for rendered images - Clear parsed develop settings and warnings when XMP packet is embedded in a non-raw image (JPEG, TIFF, PNG, WebP) - Keep develop adjustments for raw/DNG files or external sidecars - Add test verifying that a JPEG with embedded rating and crs:Exposure2012 imports with rating and default develop state --- crates/engine/src/import.rs | 17 +++++++++++++---- crates/engine/src/tests_import.rs | 25 +++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 96e8db7788..5abf63cdad 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -1064,17 +1064,26 @@ impl ImportJob { // and names the copy when the file itself has none let raw = info.kind == MediaKind::Raw; let has_embedded_xmp = raw || matches!(info.format.to_ascii_uppercase().as_str(), "JPEG" | "JPG" | "TIFF" | "TIF" | "PNG" | "WEBP"); - let packet = crate::sidecar::find_sidecar(&path, self.naming) - .and_then(|f| std::fs::read_to_string(f).ok()) - .or_else(|| info.xmp.clone().filter(|_| has_embedded_xmp)); + let sidecar_file = crate::sidecar::find_sidecar(&path, self.naming).and_then(|f| std::fs::read_to_string(f).ok()); + let from_file = sidecar_file.is_none(); + let packet = sidecar_file.or_else(|| info.xmp.clone().filter(|_| has_embedded_xmp)); let target = crate::crs::Target::for_file(info.kind, &info.format, info.preview_only.is_some(), &info.meta.camera); - let sidecar = packet.and_then(|x| match crate::sidecar::parse_sidecar(&x, target) { + let mut sidecar = packet.and_then(|x| match crate::sidecar::parse_sidecar(&x, target) { Ok(sc) => Some(sc), Err(e) => { log::warn!("import {path}: XMP: {e}"); None } }); + // Embedded XMP on a rendered file (JPEG, TIFF, PNG, WebP) has develop adjustments + // already baked into the pixels; only raws/DNGs keep foreign develop settings from embedded XMP. + if from_file + && !raw + && let Some(sc) = &mut sidecar + { + sc.develop = None; + sc.warnings.clear(); + } if info.captured.is_none() { info.captured = sidecar.as_ref().and_then(|sc| sc.captured.clone()); } diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs index 1ab0b24b87..3993f81b15 100644 --- a/crates/engine/src/tests_import.rs +++ b/crates/engine/src/tests_import.rs @@ -1920,3 +1920,28 @@ fn import_preserves_exif_rating_when_xmp_has_unrelated_rating_text() { let _ = std::fs::remove_dir_all(&src); } + +#[test] +fn import_rendered_file_ignores_embedded_develop_settings() { + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("embedded-rendered-develop-test"); + let px = [128u8; 40 * 30 * 3]; + + // A JPEG with embedded XMP containing rating and crs:Exposure2012="+1.00" + let xmp = r#""#; + let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("rendered_with_crs.jpg"), &bytes).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.join("rendered_with_crs.jpg").to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 1); + let p = s.catalog.photos().next().unwrap(); + // Rating is imported from embedded XMP + assert_eq!(p.rating, 3); + // Develop settings from embedded XMP are ignored for rendered files (already baked into pixels) + assert_eq!(p.develop.light.exposure, 0.0); + assert_eq!(p.develop, std::sync::Arc::new(p.camera_defaults())); + + let _ = std::fs::remove_dir_all(&src); +} From d6575581ed03215164fc6cee0257986705a8a474 Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Thu, 22 Oct 2026 22:25:39 +0200 Subject: [PATCH 13/98] Import: use parsed XMP rating in xmp_has_rating --- crates/engine/src/files.rs | 3 --- crates/engine/src/tests_import.rs | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index ccd04c7756..6b9699a316 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -126,9 +126,6 @@ pub fn embedded_lens(raw: &lightcraft_raw::RawInfo) -> Option bool { - if x.contains("xmp:Rating") || x.contains("xap:Rating") || x.contains(":Rating=") || x.contains(":Rating>") || x.contains(":Rating ") { - return true; - } lightcraft_meta::parse_xmp(x).ok().and_then(|d| d.metadata.rating).is_some() } diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs index a7045863f8..3506df90f2 100644 --- a/crates/engine/src/tests_import.rs +++ b/crates/engine/src/tests_import.rs @@ -2208,7 +2208,7 @@ fn import_preserves_exif_rating_when_xmp_has_unrelated_rating_text() { let px = [128u8; 40 * 30 * 3]; let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { rating: Some(5), ..Default::default() }); - let xmp = r#"100Rating guide"#; + let xmp = r#"100Rating guide mentioning xmp:Rating"#; let meta = EncodeMeta { exif: Some(&exif), xmp: Some(xmp), ..Default::default() }; let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); std::fs::write(src.join("iso_and_desc_rating.jpg"), &bytes).unwrap(); From 2630748a3c3cffaaafb0b947294252bd2596eebb Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Thu, 22 Oct 2026 20:53:07 -0400 Subject: [PATCH 14/98] LR-PROF-CAMERACOLOR: camera-preview doc cites the renumbered LOOK_VERSIONs and the sensor-channel floor --- docs/camera-preview-colour.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index 67d7abd57e..a9ca311ea8 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -153,7 +153,7 @@ Without a profile all 150 photos accept their own fit (ΔE 1.8–13.5). For vali With CR3 and CR2 input to `calibrate` (#1073), tried on one photographer's library (CR3, RAW and C-RAW, October 2025 to September 2026) and measured as above, against each file's own full-size embedded JPEG (6960 × 4640 R7, 6000 × 4000 R6 Mark II): - Held out: 40 photos per body from different shoots, every fifth withheld (8 per body), profiles fitted on the other 32 (30 R7 photos with 107,286 colour pairs, 28 R6 Mark II with 93,200; both with a hue/saturation table). On the withheld photos the profile changes little: R7 mean ΔE 2.52 → 2.57 (median 2.37 → 2.25; 3 better, 3 worse, 2 unchanged; largest regression +0.51 on an almost colourless photo), R6 Mark II 6.12 → 6.09 (median 5.73 → 5.50; 3 better, 4 worse, 1 unchanged; largest regression +0.48, best gain −0.67). Mean ΔL\* 0.00 (R7) and +0.57 (R6 Mark II) either way. Not bundled. -- When this was measured the profile only replaced the colour inside an accepted per-photo fit (`fit_preview`), so a photo whose own fit was rejected rendered the neutral fallback with or without it (since `LOOK_VERSION` 11 it keeps the profile's colour, below): 2 of the 16 withheld photos (one per body), plus one with a black-and-white camera JPEG, rendered identically both ways. Unlike the ILCE-7CR, where the profile rescued every rejected photo, here it cannot. +- When this was measured the profile only replaced the colour inside an accepted per-photo fit (`fit_preview`), so a photo whose own fit was rejected rendered the neutral fallback with or without it (since `LOOK_VERSION` 13 it keeps the profile's colour, below): 2 of the 16 withheld photos (one per body), plus one with a black-and-white camera JPEG, rendered identically both ways. Unlike the ILCE-7CR, where the profile rescued every rejected photo, here it cannot. - Library-wide (`--max 600` over 35,796 CR3s): 410 R7 photos (1.39 million pairs), 119 R6 Mark II (386k) and 38 EOS R100 (129k) gave profiles; 32 photos had no usable camera JPEG or colour (mostly moon, night and other near-colourless scenes) and one did not decode. The R6 Mark II writes its Exif model as "Canon EOS R6m2", the profile's file name too. - Decoding: 4 of the R6 Mark II C-RAW files tried (3 of 40 sampled, 1 of 119 in the library run) are refused with "unsupported raw variant: Canon CRX adaptive QP value 172" (or 175) and open preview-only. @@ -213,7 +213,7 @@ When no look fits a photo of a profiled model (step 2 and 3 both fail: a black-a Before this, such a photo fell to 4 or 5 and the profile did nothing for it. Measured on two bracketed bursts of one NIKON D780 scene (a colourful woven runner in low sun, ISO 100, f/8, frames 1.1 to 3.7 EV under the burst's brightest, each rendered with Exposure raised by its measured offset and compared with the brightest frame, CIEDE2000 and chroma of the colourful areas), with a local profile pooled from 255 of the photographer's D780 photos: the five frames 2.8 EV or more under have no look (their camera JPEGs are nearly black) and rendered at 35-48% of the reference's chroma with hue off by up to 9° whether or not the profile existed; with the profile's colour kept they render at 88-99% of it, hue within 5°. Frames up to 2.3 EV under fit a look and are unchanged. The pushed frames remain 4-7 L\* darker than the reference: a dark photo's tone curve is fitted to its shadows only (or is the default curve), which the profile's colour doesn't change (the pooled tone curve, next, does). -**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85, at most 4,000 per photo; a photo too dark or colourless for colour pairs still gives these, without counting toward the profile's photos, and a black-and-white camera JPEG gives none), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model whose look takes the profile's colour keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`; to make room in the curve's 32 knots it drops the photo's knots its curve needs least, by at most one 8-bit code where the JPEG taught it, using fewer extension knots or keeping the photo's curve as fitted otherwise: `thinned_knots`, `LOOK_VERSION` 14); a look fitted with the photo's own matrix (the profile's colour rejected) keeps its curve as fitted, since the pooled one maps luminance through the profile's matrix (`with_pooled_tone`, `LOOK_VERSION` 13); a photo no look fits continues its tone-only curve along the pooled one in the same way, or takes the pooled curve whole instead of the default one when no tone-only curve passes. +**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose sensor channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85; the floor applies before the profile's matrix, so channels the matrix sends negative stay in the luminance, as in the render, at most 4,000 per photo; a photo too dark or colourless for colour pairs still gives these, without counting toward the profile's photos, and a black-and-white camera JPEG gives none), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model whose look takes the profile's colour keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`; to make room in the curve's 32 knots it drops the photo's knots its curve needs least, by at most one 8-bit code where the JPEG taught it, using fewer extension knots or keeping the photo's curve as fitted otherwise: `thinned_knots`, `LOOK_VERSION` 16); a look fitted with the photo's own matrix (the profile's colour rejected) keeps its curve as fitted, since the pooled one maps luminance through the profile's matrix (`with_pooled_tone`, `LOOK_VERSION` 13); a photo no look fits continues its tone-only curve along the pooled one in the same way, or takes the pooled curve whole instead of the default one when no tone-only curve passes. On the same D780 brackets with the profile refitted with its tone curve (255 photos), the pushed frames match the reference's lightness: ΔL\* −0.2 to +0.5 for every frame (−1 to −7 before), median CIEDE2000 in the L\* 40-70 band 0.9-2.6 (2.0-13.5 before), hue within 5°. Colourfulness in the second burst comes out 16-28% above the reference in midtones. On 40 D780 photos the profile never saw, rendered unedited and compared with their camera JPEGs, the curve changes nothing that matters: mean ΔE 2.67 with the colour-only profile, 2.68 with the curve (2.77 without a profile), mean ΔL\* +0.71 → +0.73, one photo worse by more than 0.25 (0.38). From 2deab608cfc25ec5885e37bcbf97954f52d4cf1f Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Thu, 22 Oct 2026 20:54:06 -0400 Subject: [PATCH 15/98] LR-PROF-CAMERACOLOR: camera-preview doc cites with_pooled_tone's renumbered LOOK_VERSION --- docs/camera-preview-colour.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index a9ca311ea8..f4f2091aff 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -213,7 +213,7 @@ When no look fits a photo of a profiled model (step 2 and 3 both fail: a black-a Before this, such a photo fell to 4 or 5 and the profile did nothing for it. Measured on two bracketed bursts of one NIKON D780 scene (a colourful woven runner in low sun, ISO 100, f/8, frames 1.1 to 3.7 EV under the burst's brightest, each rendered with Exposure raised by its measured offset and compared with the brightest frame, CIEDE2000 and chroma of the colourful areas), with a local profile pooled from 255 of the photographer's D780 photos: the five frames 2.8 EV or more under have no look (their camera JPEGs are nearly black) and rendered at 35-48% of the reference's chroma with hue off by up to 9° whether or not the profile existed; with the profile's colour kept they render at 88-99% of it, hue within 5°. Frames up to 2.3 EV under fit a look and are unchanged. The pushed frames remain 4-7 L\* darker than the reference: a dark photo's tone curve is fitted to its shadows only (or is the default curve), which the profile's colour doesn't change (the pooled tone curve, next, does). -**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose sensor channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85; the floor applies before the profile's matrix, so channels the matrix sends negative stay in the luminance, as in the render, at most 4,000 per photo; a photo too dark or colourless for colour pairs still gives these, without counting toward the profile's photos, and a black-and-white camera JPEG gives none), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model whose look takes the profile's colour keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`; to make room in the curve's 32 knots it drops the photo's knots its curve needs least, by at most one 8-bit code where the JPEG taught it, using fewer extension knots or keeping the photo's curve as fitted otherwise: `thinned_knots`, `LOOK_VERSION` 16); a look fitted with the photo's own matrix (the profile's colour rejected) keeps its curve as fitted, since the pooled one maps luminance through the profile's matrix (`with_pooled_tone`, `LOOK_VERSION` 13); a photo no look fits continues its tone-only curve along the pooled one in the same way, or takes the pooled curve whole instead of the default one when no tone-only curve passes. +**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose sensor channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85; the floor applies before the profile's matrix, so channels the matrix sends negative stay in the luminance, as in the render, at most 4,000 per photo; a photo too dark or colourless for colour pairs still gives these, without counting toward the profile's photos, and a black-and-white camera JPEG gives none), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model whose look takes the profile's colour keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`; to make room in the curve's 32 knots it drops the photo's knots its curve needs least, by at most one 8-bit code where the JPEG taught it, using fewer extension knots or keeping the photo's curve as fitted otherwise: `thinned_knots`, `LOOK_VERSION` 16); a look fitted with the photo's own matrix (the profile's colour rejected) keeps its curve as fitted, since the pooled one maps luminance through the profile's matrix (`with_pooled_tone`, `LOOK_VERSION` 15); a photo no look fits continues its tone-only curve along the pooled one in the same way, or takes the pooled curve whole instead of the default one when no tone-only curve passes. On the same D780 brackets with the profile refitted with its tone curve (255 photos), the pushed frames match the reference's lightness: ΔL\* −0.2 to +0.5 for every frame (−1 to −7 before), median CIEDE2000 in the L\* 40-70 band 0.9-2.6 (2.0-13.5 before), hue within 5°. Colourfulness in the second burst comes out 16-28% above the reference in midtones. On 40 D780 photos the profile never saw, rendered unedited and compared with their camera JPEGs, the curve changes nothing that matters: mean ΔE 2.67 with the colour-only profile, 2.68 with the curve (2.77 without a profile), mean ΔL\* +0.71 → +0.73, one photo worse by more than 0.25 (0.38). From ba6f22567daa37cd8af4c7f47ca52220021b6f8b Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:52:47 +0200 Subject: [PATCH 16/98] M12: SAM 3 mask decoder on the GPU (wgpu), and the docs for all of SAM 3 on the GPU Part 5 of 5 of #2167. The text detector's mask decoder runs on the GPU device of the image encoder: the prompt cross-attention of the memory (the DETR attention), the pixel decoder up to 288^2 (the necks' implicit-GEMM 3 x 3 convolution, a two-pass GroupNorm, ReLU), then the mask products. The instance projection is folded into the 200 mask embeddings on the CPU, and the semantic projection (#1963) is one more row, so the GPU returns the per-query masks and the semantic mask in one product. Its weights load on the first text prompt. The parity test checks the semantic mask too. docs/gpu-pipeline.md and docs/ai-masks.md describe every part, with the measured timings and accuracy, and what happens on an adapter that lacks the limits or whose device can't be created. Co-Authored-By: Claude Opus 5.5 --- crates/gpu/examples/sam3_backbone_bench.rs | 40 ++- crates/gpu/src/sam3.rs | 48 ++- crates/gpu/src/sam3/pixel.rs | 377 +++++++++++++++++++++ crates/gpu/src/sam3/pixel/tests.rs | 165 +++++++++ crates/gpu/src/wgsl/sam3_pixel.wgsl | 161 +++++++++ crates/gpu/tests/it/main.rs | 2 + crates/gpu/tests/it/sam3_mask_decoder.rs | 287 ++++++++++++++++ docs/ai-masks.md | 96 +++++- docs/gpu-pipeline.md | 160 +++++++++ docs/hardware-parity.md | 7 +- docs/parity-checklist.md | 8 +- docs/target-app-parity.md | 6 +- 12 files changed, 1334 insertions(+), 23 deletions(-) create mode 100644 crates/gpu/src/sam3/pixel.rs create mode 100644 crates/gpu/src/sam3/pixel/tests.rs create mode 100644 crates/gpu/src/wgsl/sam3_pixel.wgsl create mode 100644 crates/gpu/tests/it/sam3_mask_decoder.rs diff --git a/crates/gpu/examples/sam3_backbone_bench.rs b/crates/gpu/examples/sam3_backbone_bench.rs index 700c53c0a2..eec3de8314 100644 --- a/crates/gpu/examples/sam3_backbone_bench.rs +++ b/crates/gpu/examples/sam3_backbone_bench.rs @@ -5,10 +5,11 @@ //! //! The model directory is `LIGHTCRAFT_SAM3_DIR`, else `~/.config/lightcraft/models/sam3`. Prints the device and //! kernel creation, the weight upload, the first and the warm forward passes, each neck's first run (which builds -//! it) and warm runs, the CPU forward pass and how far the two outputs are apart. `--app` then times what the app -//! does per photo, with the model loaded as the app loads it (GPU backbone, necks and DETR encoder, the rest in candle on the CPU): encode, -//! click features, first click, first and second Describe (`--cpu-necks`: with the necks in candle, as before they -//! ran on the GPU). +//! it) and warm runs, the text detector's mask decoder (first and warm, on made-up inputs), the CPU forward pass and +//! how far the two outputs are apart. `--app` then times what the app does per photo, with the model loaded as the +//! app loads it (GPU backbone, necks, DETR encoder and mask decoder, the rest in candle on the CPU): encode, click +//! features, first click, first and second Describe (`--cpu-necks`: with the necks in candle, as before they ran on +//! the GPU; `--cpu-masks`: with the mask decoder in candle). use std::path::PathBuf; use std::time::Instant; @@ -35,6 +36,7 @@ fn main() -> Result<(), String> { let cpu = !args.iter().any(|a| a == "--no-cpu"); let app = args.iter().any(|a| a == "--app"); let cpu_necks = args.iter().any(|a| a == "--cpu-necks"); + let cpu_masks = args.iter().any(|a| a == "--cpu-masks"); let dir = model_dir().ok_or("no SAM 3 model: set LIGHTCRAFT_SAM3_DIR")?; let scene = &lightcraft_scenes::demo_library()[0]; @@ -75,6 +77,23 @@ fn main() -> Result<(), String> { } } println!("neck device memory: {:.0} MB", gpu.neck_bytes() as f64 / 1e6); + { + let (memory, text, valid) = (vec![0.1f32; 5184 * 256], vec![0.3f32; 32 * 256], vec![true; 32]); + let (l1, l0) = (vec![0.2f32; 256 * 144 * 144], vec![0.4f32; 256 * 288 * 288]); + let (rows, bias) = (vec![0.01f32; 200 * 256], vec![0.5f32; 200]); + match timed(runs, || gpu.mask_decoder(&memory, &text, &valid, [&l1, &l0], &rows, &bias).map(drop)) { + Ok((first, best, mean)) => { + let (w, b) = gpu.mask_decoder_bytes().unwrap_or_default(); + println!( + "mask decoder (200 queries): first {first:7.1} ms, warm {best:.1} ms (mean of {runs}: {mean:.1} ms); {:.0} MB weights, {:.0} MB work buffers", + w as f64 / 1e6, + b as f64 / 1e6 + ); + } + Err(e) => println!("mask decoder failed on the GPU: {e}"), + } + } + if cpu { let model = Sam3::load_on(&dir, candle_core::Device::Cpu).map_err(|e| e.to_string())?; let px = candle_core::Tensor::from_vec(pixels.clone(), (1, 3, INPUT, INPUT), &candle_core::Device::Cpu).map_err(|e| e.to_string())?; @@ -96,7 +115,7 @@ fn main() -> Result<(), String> { } drop(gpu); if app { - as_the_app(&dir, &rgb, (img.width, img.height), runs, cpu_necks)?; + as_the_app(&dir, &rgb, (img.width, img.height), runs, (cpu_necks, cpu_masks))?; } // no GPU work in flight when the process ends (issue #620) lightcraft_gpu::begin_shutdown(); @@ -124,10 +143,11 @@ fn ms(t: Instant) -> String { format!("{:.0} ms", t.elapsed().as_secs_f64() * 1e3) } -/// The model's GPU accelerator with the necks left to candle (`--cpu-necks`). +/// The model's GPU accelerator with the necks (`--cpu-necks`) or the mask decoder (`--cpu-masks`) left to candle. struct Heads { gpu: Box, necks: bool, + masks: bool, } impl BackboneAccel for Heads { @@ -144,7 +164,7 @@ impl BackboneAccel for Heads { self.gpu.runs_detr_encoder() } fn runs_mask_decoder(&self) -> bool { - self.gpu.runs_mask_decoder() + self.masks && self.gpu.runs_mask_decoder() } fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> Result>, String> { self.gpu.neck(which, backbone, n) @@ -166,9 +186,11 @@ impl BackboneAccel for Heads { } /// The model as the app loads it, timed per photo: encode, click features, a click, two Describes. -fn as_the_app(dir: &std::path::Path, rgb: &[u8], (w, h): (usize, usize), runs: usize, cpu_necks: bool) -> Result<(), String> { +fn as_the_app(dir: &std::path::Path, rgb: &[u8], (w, h): (usize, usize), runs: usize, (cpu_necks, cpu_masks): (bool, bool)) -> Result<(), String> { let t = Instant::now(); - let make = |r: &WeightReader| -> Result, String> { Ok(Box::new(Heads { gpu: sam3::backbone(r)?, necks: !cpu_necks })) }; + let make = |r: &WeightReader| -> Result, String> { + Ok(Box::new(Heads { gpu: sam3::backbone(r)?, necks: !cpu_necks, masks: !cpu_masks })) + }; let mut model = Sam3::load_accelerated(dir, candle_core::Device::Cpu, make).map_err(|e| e.to_string())?; println!("app: load {} on {}", ms(t), model.backbone_device()); let click = |x, y| lightcraft_segment::Click { x, y, positive: true }; diff --git a/crates/gpu/src/sam3.rs b/crates/gpu/src/sam3.rs index 2265533336..1c059268d7 100644 --- a/crates/gpu/src/sam3.rs +++ b/crates/gpu/src/sam3.rs @@ -17,8 +17,8 @@ //! per layer and reads the result back once. No subgroups or shader-f16 needed. The two necks that follow the //! backbone run on the same device, built when first asked for (`sam3/neck.rs`). //! -//! The same accelerator runs the text detector's DETR encoder (`sam3/detr.rs`); its weights load on the first text -//! prompt. The mask decoder stays in candle on the CPU. +//! The same accelerator runs the text detector's DETR encoder (`sam3/detr.rs`) and its mask decoder (`sam3/pixel.rs`); +//! their weights load on the first text prompt. //! //! The device is its own (like denoise's and faces'): it respects the same switches as GPU rendering //! (`LIGHTCRAFT_GPU`, `LIGHTCRAFT_GPU_BACKEND`, `LIGHTCRAFT_GPU_ADAPTER`, the GPU preference), the crash sentinel @@ -35,6 +35,7 @@ use wgpu::util::DeviceExt; mod detr; mod neck; +mod pixel; #[cfg(test)] mod tests; @@ -956,6 +957,8 @@ pub struct Sam3Gpu { detr: detr::Encoder, /// The feature pyramids, built on first use. necks: neck::Necks, + /// The detector's mask decoder, loaded on the first text prompt. + masks: pixel::MaskDecoder, } /// The SAM 3 backbone on the GPU with the checkpoint's weights uploaded, or why it can't run there (GPU off, missing, @@ -1051,7 +1054,18 @@ fn build_inner(dev: &'static Dev, weights: &WeightReader, precision: Precision) let recorded = g.record(); let detr = detr::Encoder::new(weights.clone()); let necks = neck::Necks::new(weights.clone()); - Ok(Sam3Gpu { dev, recorded, work: Mutex::new(Work { pixels, out: y, staging }), weight_bytes: ld.bytes, work_bytes, precision, detr, necks }) + let masks = pixel::MaskDecoder::new(weights.clone()); + Ok(Sam3Gpu { + dev, + recorded, + work: Mutex::new(Work { pixels, out: y, staging }), + weight_bytes: ld.bytes, + work_bytes, + precision, + detr, + necks, + masks, + }) } /// Run `f`, the work of `stage`, turning a panic into a broken device (with the stage's name). @@ -1078,6 +1092,11 @@ impl Sam3Gpu { self.detr.bytes() } + /// Bytes of device memory the mask decoder's weights and work buffers take, once a text prompt loaded them. + pub fn mask_decoder_bytes(&self) -> Option<(u64, u64)> { + self.masks.bytes() + } + fn run(&self, pixels: &[f32]) -> Result, String> { if pixels.len() != 3 * IMAGE * IMAGE { return Err(format!("{} pixel values, expected 3 × {IMAGE} × {IMAGE}", pixels.len())); @@ -1125,6 +1144,25 @@ impl BackboneAccel for Sam3Gpu { guarded("the SAM 3 DETR encoder", || self.detr.run(self.dev, image, pos, text, valid)) } + fn mask_decoder( + &self, + memory: &[f32], + text: &[f32], + valid: &[bool], + levels: [&[f32]; 2], + rows: &[f32], + bias: &[f32], + ) -> Result, String> { + if let Some(why) = broken_reason() { + return Err(format!("the GPU is not used any more: {why}")); + } + if let Some(why) = crate::switched_off() { + return Err(why); + } + let Some(_work) = crate::exit::enter() else { return Err("LightCraft is closing".into()) }; + guarded("the SAM 3 mask decoder", || self.masks.run(self.dev, memory, text, valid, levels, rows, bias)) + } + fn closing(&self) -> bool { crate::shutting_down() } @@ -1137,6 +1175,10 @@ impl BackboneAccel for Sam3Gpu { true } + fn runs_mask_decoder(&self) -> bool { + true + } + fn device(&self) -> String { let weights = match self.precision { Precision::F32 => "", diff --git a/crates/gpu/src/sam3/pixel.rs b/crates/gpu/src/sam3/pixel.rs new file mode 100644 index 0000000000..08d5f5b749 --- /dev/null +++ b/crates/gpu/src/sam3/pixel.rs @@ -0,0 +1,377 @@ +//! The mask decoder of SAM 3's text detector on the GPU (`lightcraft-segment`'s `detector.rs` is the reference): the +//! DETR encoder's memory (72 × 72 tokens of 256) attends to the prompt and is added to it (`prompt_cross_attn`, after +//! its layer norm), then the pixel decoder brings it up to 288 × 288 in two stages, each a nearest 2 × up-sampling plus +//! the detector neck's level of that size (144², then 288²) → 3 × 3 convolution → GroupNorm (8 groups, eps 1e-5) → +//! ReLU; last, every row of a `[r, 256]` matrix (with its bias) is a 1 × 1 projection of the decoder's output, an image +//! `[r, 288, 288]`. The detector passes its 200 mask embeddings with the instance projection folded in, so these are the +//! per-query mask logits. ~0.9–1.4 s per prompt on the CPU through candle, most of it the 288² convolution. +//! +//! Images are pixel rows (`[pixels, channels]`), as in the necks (`sam3/neck.rs`): the convolutions are the necks' +//! implicit GEMM, the projection the backbone's matrix product (`[pixels, 256] · [r, 256]ᵀ`, then `to_chw`), the +//! prompt attention the DETR encoder's kernels (`sam3/detr.rs`). `wgsl/sam3_pixel.wgsl` adds the up-sampling, which +//! adds the channels-first neck level as uploaded, and GroupNorm + ReLU: two-pass statistics per chunk of 256 pixels, +//! merged per group (the parallel variance formula), then applied in place. +//! +//! Loaded on the first prompt, like the encoder: kernels, 6 MB of weights, ~280 MB of work buffers. A prompt uploads +//! the memory, the prompt's tokens and padding bias, both neck levels (106 MB; they stay on the CPU with the image's +//! features, see `docs/gpu-pipeline.md`) and the rows, submits once and reads `r · 288²` numbers back. The dispatches +//! are recorded once per row count. + +use std::sync::{Mutex, OnceLock, PoisonError}; + +use lightcraft_segment::WeightReader; + +use super::detr::{self, Operand}; +use super::neck::{self, conv_weights, scoped}; +use super::{Dev, Graph, Precision, Recorded, buffer, pipeline, u32_of, upload}; + +#[cfg(test)] +mod tests; + +/// Where the decoder's weights are in the checkpoint. +const PREFIX: &str = "detector_model.mask_decoder"; +/// The memory's side (72 × 72 tokens), the width of everything, the prompt's tokens. +const GRID: usize = 72; +const WIDTH: usize = 256; +const TEXT: usize = 32; +const HEAD_DIM: usize = 32; +/// The decoder's stages (each doubles the side): 144², 288². +const STAGES: usize = 2; +/// The output's side. +const SIDE: usize = GRID << STAGES; +/// GroupNorm's groups and eps (`candle_nn::group_norm(8, 256, 1e-5)`), and PyTorch's layer norm eps. +const GROUPS: usize = 8; +const EPS: f32 = 1e-5; +/// Pixels per workgroup of the GroupNorm statistics. +const CHUNK: usize = 256; + +struct Kernels { + upsample_add: wgpu::ComputePipeline, + group_stats: wgpu::ComputePipeline, + group_merge: wgpu::ComputePipeline, + group_norm_relu: wgpu::ComputePipeline, +} + +static KERNELS: OnceLock> = OnceLock::new(); + +/// The decoder's own kernels, compiled on first use. +fn kernels(dev: &'static Dev) -> Result<&'static Kernels, String> { + KERNELS + .get_or_init(|| { + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let source = include_str!("../wgsl/sam3_pixel.wgsl"); + let pipe = |entry: &str| pipeline(&dev.device, &dev.pipeline_layout, "sam3 pixel", source, entry); + let k = Kernels { + upsample_add: pipe("upsample_add"), + group_stats: pipe("group_stats"), + group_merge: pipe("group_merge"), + group_norm_relu: pipe("group_norm_relu"), + }; + match pollster::block_on(validation.pop()) { + Some(e) => Err(format!("{}: the SAM 3 mask decoder kernels did not compile ({e})", dev.info.name)), + None => Ok(k), + } + }) + .as_ref() + .map_err(Clone::clone) +} + +/// Floats of the GroupNorm statistics of chunks for an image of `pixels`, `groups` groups. +fn partials_len(pixels: usize, groups: usize) -> usize { + pixels.div_ceil(CHUNK) * groups * 2 +} + +impl Graph { + /// Nearest up-sampling of the rows `src` (`[from², channels]`) to `to × to`, plus the channels-first image `skip` + /// (`[channels, to, to]`), into the rows `dst` (`[to², channels]`). + fn upsample_add( + &mut self, + k: &'static Kernels, + [src, skip, dst]: [&wgpu::Buffer; 3], + channels: usize, + (from, to): (usize, usize), + ) -> Result<(), String> { + if from == 0 || to < from || channels == 0 { + return Err("an up-sampling the SAM 3 kernel cannot do".into()); + } + let count = channels.checked_mul(to * to).ok_or("an image too large")?; + let (g, row) = self.flat(count.div_ceil(256))?; + let params = [u32_of(channels)?, u32_of(to)?, u32_of(from)?, 0, 0, 0, u32_of(count)?, row]; + self.push(&k.upsample_add, params, [src, skip, &self.dev.dummy, dst], g); + Ok(()) + } + + /// GroupNorm (`groups` groups of channels, eps) and ReLU in place on the rows `x` (`[pixels, channels]`, channels + /// ≤ 256), with the per-channel `gamma` and `beta`; `partials` (at least [`partials_len`] floats) and `stats` + /// (2 · groups) hold the statistics on the way. + #[allow(clippy::too_many_arguments)] + fn group_norm_relu( + &mut self, + k: &'static Kernels, + [x, gamma, beta]: [&wgpu::Buffer; 3], + [partials, stats]: [&wgpu::Buffer; 2], + (pixels, channels, groups): (usize, usize, usize), + eps: f32, + ) -> Result<(), String> { + if pixels == 0 || channels == 0 || channels > 256 || groups == 0 || !channels.is_multiple_of(groups) { + return Err("a GroupNorm the SAM 3 kernel cannot do".into()); + } + let dummy = &self.dev.dummy; + let chunks = pixels.div_ceil(CHUNK); + let (g, row) = self.flat(chunks)?; + let params = [u32_of(channels)?, u32_of(pixels)?, u32_of(CHUNK)?, u32_of(groups)?, 0, 0, 0, row]; + self.push(&k.group_stats, params, [x, dummy, dummy, partials], g); + let params = [u32_of(chunks)?, u32_of(pixels)?, u32_of(CHUNK)?, u32_of(groups)?, eps.to_bits(), u32_of(channels / groups)?, 0, 0]; + self.push(&k.group_merge, params, [partials, dummy, dummy, stats], [u32_of(groups)?, 1, 1]); + let count = pixels.checked_mul(channels).ok_or("an image too large")?; + let (g, row) = self.flat(count.div_ceil(256))?; + self.push(&k.group_norm_relu, [u32_of(channels)?, 0, 0, u32_of(groups)?, 0, 0, u32_of(count)?, row], [stats, gamma, beta, x], g); + Ok(()) + } +} + +/// The decoder's weights on the device: (weight, bias) pairs, the prompt attention's k | v concatenated, the +/// convolutions as rows `[cout, 3, 3, cin]`. +struct Weights { + ln: [wgpu::Buffer; 2], + q: [wgpu::Buffer; 2], + kv: [wgpu::Buffer; 2], + o: [wgpu::Buffer; 2], + convs: Vec<[wgpu::Buffer; 2]>, + norms: Vec<[wgpu::Buffer; 2]>, +} + +/// Reads the decoder's tensors, checking their shapes. +struct Loader<'a> { + weights: &'a WeightReader, + bytes: u64, +} + +impl Loader<'_> { + /// The tensors `names` (each of `shape`) concatenated along the first axis. + fn read(&mut self, names: &[String], shape: &[usize]) -> Result, String> { + let mut all = Vec::with_capacity(names.len() * shape.iter().product::()); + for name in names { + let full = format!("{PREFIX}.{name}"); + let (got, data) = self.weights.read(&full).map_err(|e| format!("{full}: {e}"))?; + if got != shape { + return Err(format!("{full}: shape {got:?}, expected {shape:?}")); + } + all.extend(data); + } + self.bytes += all.len() as u64 * 4; + Ok(all) + } + + /// A pair of `{name}.weight` (`[n, k]`, several concatenated along n) and `{name}.bias` (or a norm's scale and shift + /// with `k` 0), uploaded. + fn pair(&mut self, dev: &Dev, names: &[String], n: usize, k: usize) -> Result<[wgpu::Buffer; 2], String> { + let w: Vec = names.iter().map(|n| format!("{n}.weight")).collect(); + let b: Vec = names.iter().map(|n| format!("{n}.bias")).collect(); + let shape: &[usize] = if k == 0 { &[n] } else { &[n, k] }; + let label = names.first().map_or("weight", String::as_str); + Ok([upload(dev, label, &self.read(&w, shape)?), upload(dev, label, &self.read(&b, &[n])?)]) + } + + fn load(&mut self, dev: &Dev) -> Result { + let a = "prompt_cross_attn"; + let proj = |ps: &[&str]| -> Vec { ps.iter().map(|p| format!("{a}.{p}_proj")).collect() }; + let mut convs = Vec::with_capacity(STAGES); + let mut norms = Vec::with_capacity(STAGES); + for i in 0..STAGES { + let name = format!("pixel_decoder.conv_layers.{i}"); + let w = self.read(&[format!("{name}.weight")], &[WIDTH, WIDTH, 3, 3])?; + let b = self.read(&[format!("{name}.bias")], &[WIDTH])?; + convs.push(conv_weights(dev, &name, &w, &b, (WIDTH, WIDTH, 3))); + norms.push(self.pair(dev, &[format!("pixel_decoder.norms.{i}")], WIDTH, 0)?); + } + Ok(Weights { + ln: self.pair(dev, &["prompt_cross_attn_norm".to_string()], WIDTH, 0)?, + q: self.pair(dev, &proj(&["q"]), WIDTH, WIDTH)?, + kv: self.pair(dev, &proj(&["k", "v"]), WIDTH, WIDTH)?, + o: self.pair(dev, &proj(&["o"]), WIDTH, WIDTH)?, + convs, + norms, + }) + } +} + +/// The buffers a prompt writes and reads, and its dispatches (recorded for one row count). +struct Work { + /// The memory in, then the memory after the prompt attention. + x: wgpu::Buffer, + text: wgpu::Buffer, + /// The prompt attention's k | v of the prompt (`[32, 512]`), then its padding bias (32 floats). + text_kv: wgpu::Buffer, + /// The neck's levels as uploaded (`[256, 144, 144]`, `[256, 288, 288]`); the projection's channels-first result + /// ends in the second. + skip1: wgpu::Buffer, + skip0: wgpu::Buffer, + /// Two 288² images the steps alternate between (the prompt attention's smaller ones too). + a: wgpu::Buffer, + b: wgpu::Buffer, + rows: wgpu::Buffer, + row_bias: wgpu::Buffer, + partials: wgpu::Buffer, + stats: wgpu::Buffer, + staging: wgpu::Buffer, + recorded: Option<(usize, Recorded)>, +} + +impl Work { + fn new(dev: &Dev) -> Work { + let image = |label: &str| buffer(dev, label, SIDE * SIDE * WIDTH); + Work { + x: buffer(dev, "mask memory", GRID * GRID * WIDTH), + text: buffer(dev, "mask prompt", TEXT * WIDTH), + text_kv: buffer(dev, "mask prompt k|v", TEXT * 2 * WIDTH + TEXT), + skip1: buffer(dev, "mask level 1", WIDTH * (SIDE / 2) * (SIDE / 2)), + skip0: image("mask level 0"), + a: image("mask ping"), + b: image("mask pong"), + rows: buffer(dev, "mask rows", WIDTH * WIDTH), + row_bias: buffer(dev, "mask row bias", WIDTH), + partials: buffer(dev, "mask norm partials", partials_len(SIDE * SIDE, GROUPS)), + stats: buffer(dev, "mask norm stats", 2 * GROUPS), + staging: dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("mask read-back"), + size: (SIDE * SIDE * WIDTH * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }), + recorded: None, + } + } + + /// Bytes on the device: the read-back buffer is host memory on discrete GPUs and not counted. + fn bytes() -> u64 { + let floats = GRID * GRID * WIDTH + + TEXT * (3 * WIDTH + 1) + + WIDTH * (SIDE / 2) * (SIDE / 2) + + 3 * SIDE * SIDE * WIDTH + + WIDTH * (WIDTH + 1) + + partials_len(SIDE * SIDE, GROUPS) + + 2 * GROUPS; + (floats * 4) as u64 + } +} + +/// The dispatches of a prompt with `r` rows: everything after the uploads, the result in `work.skip0`. +fn record(dev: &'static Dev, w: &Weights, work: &Work, r: usize) -> Result { + let (kd, kn, k) = (detr::kernels(dev)?, neck::kernels(dev)?, kernels(dev)?); + let mut g = Graph::new(dev); + let tokens = GRID * GRID; + // the memory attends to the prompt (padding masked): x += o(attention(q(ln(x)), k | v(text))) + g.layernorm_torch([&work.x, &w.ln[0], &w.ln[1], &work.a], tokens, WIDTH)?; + g.matmul([&work.a, &w.q[0], &w.q[1], &work.b], (tokens, WIDTH, WIDTH), 1, false, false, Precision::F32)?; + g.matmul([&work.text, &w.kv[0], &w.kv[1], &work.text_kv], (TEXT, 2 * WIDTH, WIDTH), 1, false, false, Precision::F32)?; + let q = Operand { buffer: &work.b, stride: WIDTH, offset: 0 }; + let (tk, tv) = + (Operand { buffer: &work.text_kv, stride: 2 * WIDTH, offset: 0 }, Operand { buffer: &work.text_kv, stride: 2 * WIDTH, offset: WIDTH }); + g.attention_detr(kd, [q, tk, tv], Some(TEXT * 2 * WIDTH), &work.a, (tokens, TEXT, WIDTH / HEAD_DIM))?; + g.matmul([&work.a, &w.o[0], &w.o[1], &work.x], (tokens, WIDTH, WIDTH), 1, false, true, Precision::F32)?; + // the pixel decoder: up-sample + the neck's level → 3 × 3 convolution → GroupNorm → ReLU, at 144² and at 288² + let mut cur = &work.x; + let mut side = GRID; + for (i, skip) in [&work.skip1, &work.skip0].into_iter().enumerate() { + let (Some(conv), Some(norm)) = (w.convs.get(i), w.norms.get(i)) else { return Err("a pixel decoder stage without weights".into()) }; + g.upsample_add(k, [cur, skip, &work.a], WIDTH, (side, 2 * side))?; + side *= 2; + g.conv3(kn, [&work.a, &conv[0], &conv[1], &work.b], side, (WIDTH, WIDTH))?; + g.group_norm_relu(k, [&work.b, &norm[0], &norm[1]], [&work.partials, &work.stats], (side * side, WIDTH, GROUPS), EPS)?; + cur = &work.b; + } + // each row a 1 × 1 projection of the decoder's output: [pixels, r], then channels-first into the spent level 0 + g.matmul([&work.b, &work.rows, &work.row_bias, &work.a], (side * side, r, WIDTH), 1, false, false, Precision::F32)?; + g.channels_first(&work.a, &work.skip0, r, side, side)?; + Ok(g.record()) +} + +/// The decoder with its weights on the device. +struct Built { + weights: Weights, + /// One prompt at a time (they share the work buffers). + work: Mutex, + weight_bytes: u64, +} + +fn build(dev: &'static Dev, weights: &WeightReader) -> Result { + // every kernel compiles before anything is uploaded + detr::kernels(dev)?; + neck::kernels(dev)?; + kernels(dev)?; + scoped(dev, "the SAM 3 mask decoder", || { + let mut ld = Loader { weights, bytes: 0 }; + let w = ld.load(dev)?; + Ok(Built { weights: w, work: Mutex::new(Work::new(dev)), weight_bytes: ld.bytes }) + }) +} + +/// The mask decoder, built on first use from the checkpoint the backbone came from. +pub(super) struct MaskDecoder { + weights: WeightReader, + built: OnceLock>, +} + +impl MaskDecoder { + pub(super) fn new(weights: WeightReader) -> Self { + Self { weights, built: OnceLock::new() } + } + + /// Bytes of device memory the weights and the work buffers take, once built. + pub(super) fn bytes(&self) -> Option<(u64, u64)> { + self.built.get().and_then(|b| b.as_ref().ok()).map(|b| (b.weight_bytes, Work::bytes())) + } + + /// `[r, 288, 288]` for the encoder memory `[5184, 256]`, the prompt's tokens `[32, 256]` (`valid`: its real ones), + /// the detector neck's levels `[256, 144, 144]` and `[256, 288, 288]` (channels-first) and the rows `[r, 256]` + /// with their bias `[r]` (1 ≤ r ≤ 256). + #[allow(clippy::too_many_arguments)] + pub(super) fn run( + &self, + dev: &'static Dev, + memory: &[f32], + text: &[f32], + valid: &[bool], + [level1, level0]: [&[f32]; 2], + rows: &[f32], + row_bias: &[f32], + ) -> Result, String> { + let r = row_bias.len(); + let (l1, l0) = (WIDTH * (SIDE / 2) * (SIDE / 2), WIDTH * SIDE * SIDE); + if memory.len() != GRID * GRID * WIDTH || text.len() != TEXT * WIDTH || valid.len() != TEXT || level1.len() != l1 || level0.len() != l0 { + return Err(format!( + "{} memory, {} prompt values, {} prompt tokens and levels of {} and {} values, expected {GRID}² × {WIDTH}, {TEXT} × {WIDTH}, {TEXT}, {l1} and {l0}", + memory.len(), + text.len(), + valid.len(), + level1.len(), + level0.len() + )); + } + if r == 0 || r > WIDTH || rows.len() != r * WIDTH { + return Err(format!("{} row values and {r} biases, expected r × {WIDTH} and r (1 ≤ r ≤ {WIDTH})", rows.len())); + } + let b = self.built.get_or_init(|| build(dev, &self.weights)).as_ref().map_err(Clone::clone)?; + let bias: Vec = valid.iter().map(|&ok| if ok { 0.0 } else { f32::MIN }).collect(); + let mut work = b.work.lock().unwrap_or_else(PoisonError::into_inner); + if work.recorded.as_ref().is_none_or(|(n, _)| *n != r) { + let recorded = scoped(dev, "the SAM 3 mask decoder", || record(dev, &b.weights, &work, r))?; + work.recorded = Some((r, recorded)); + } + let q = &dev.queue; + q.write_buffer(&work.x, 0, bytemuck::cast_slice(memory)); + q.write_buffer(&work.text, 0, bytemuck::cast_slice(text)); + q.write_buffer(&work.text_kv, (TEXT * 2 * WIDTH * 4) as u64, bytemuck::cast_slice(&bias)); + q.write_buffer(&work.skip1, 0, bytemuck::cast_slice(level1)); + q.write_buffer(&work.skip0, 0, bytemuck::cast_slice(level0)); + q.write_buffer(&work.rows, 0, bytemuck::cast_slice(rows)); + q.write_buffer(&work.row_bias, 0, bytemuck::cast_slice(row_bias)); + let Some((_, recorded)) = &work.recorded else { return Err("the mask decoder was not recorded".into()) }; + let out = recorded.run("the SAM 3 mask decoder", dev, &work.skip0, &work.staging, r * SIDE * SIDE)?; + if !out.iter().fold(true, |ok, v| ok & v.is_finite()) { + return Err("the GPU mask decoder produced non-finite values".into()); + } + Ok(out) + } +} diff --git a/crates/gpu/src/sam3/pixel/tests.rs b/crates/gpu/src/sam3/pixel/tests.rs new file mode 100644 index 0000000000..ece1185c0e --- /dev/null +++ b/crates/gpu/src/sam3/pixel/tests.rs @@ -0,0 +1,165 @@ +//! The mask decoder's kernels against plain loops in f64: the up-sampling with the channels-first level added (odd +//! sides, cut-off workgroups), GroupNorm + ReLU (chunks cut off, a large mean, group sizes), and one whole pixel +//! decoder stage (up-sampling → 3 × 3 convolution at every border → GroupNorm → ReLU) on small images. The real +//! decoder against candle: `tests/it/sam3_mask_decoder.rs`. + +use super::super::neck::tests::{conv_ref, f32s, f64s}; +use super::super::tests::{gpu, read, values, worst}; +use super::*; + +fn pixel_kernels(d: &'static Dev) -> &'static Kernels { + kernels(d).unwrap() +} + +/// Nearest up-sampling of the rows `x` (`[from², c]`) to `to²`, plus the channels-first `skip` (`[c, to, to]`). +fn upsample_add_ref(x: &[f64], skip: &[f32], c: usize, (from, to): (usize, usize)) -> Vec { + let mut y = vec![0f64; to * to * c]; + for r in 0..to { + for col in 0..to { + // candle's upsample_nearest2d: floor(i · from / to) + let (sr, sc) = ((r as f64 * from as f64 / to as f64) as usize, (col as f64 * from as f64 / to as f64) as usize); + for ch in 0..c { + y[(r * to + col) * c + ch] = x[(sr * from + sc) * c + ch] + skip[ch * to * to + r * to + col] as f64; + } + } + } + y +} + +/// GroupNorm (centred two-pass variance, as candle's) and ReLU on the rows `x` (`[pixels, c]`). +fn group_norm_relu_ref(x: &[f64], c: usize, groups: usize, gamma: &[f32], beta: &[f32], eps: f64) -> Vec { + let pixels = x.len() / c; + let per = c / groups; + let mut y = x.to_vec(); + for g in 0..groups { + let at = |p: usize, i: usize| x[p * c + g * per + i]; + let n = (pixels * per) as f64; + let mean = (0..pixels).flat_map(|p| (0..per).map(move |i| (p, i))).map(|(p, i)| at(p, i)).sum::() / n; + let var = (0..pixels).flat_map(|p| (0..per).map(move |i| (p, i))).map(|(p, i)| (at(p, i) - mean).powi(2)).sum::() / n; + for p in 0..pixels { + for i in 0..per { + let ch = g * per + i; + let v = (x[p * c + ch] - mean) / (var + eps).sqrt() * gamma[ch] as f64 + beta[ch] as f64; + y[p * c + ch] = v.max(0.0); + } + } + } + y +} + +#[test] +fn up_sampling_adds_the_channels_first_level() { + let Some(d) = gpu() else { return }; + let k = pixel_kernels(d); + // the decoder's doublings, an odd one, and channels that leave the last workgroup part empty + for (case, (from, to, c)) in [(3usize, 6usize, 4usize), (5, 10, 12), (4, 7, 3), (1, 2, 256)].into_iter().enumerate() { + let x = values(from * from * c, 100 + case as u64, 1.0); + let skip = values(c * to * to, 110 + case as u64, 1.0); + let (bx, bs, by) = (upload(d, "x", &x), upload(d, "skip", &skip), buffer(d, "y", to * to * c)); + let mut g = Graph::new(d); + g.upsample_add(k, [&bx, &bs, &by], c, (from, to)).unwrap(); + let got = read(d, g, &by, to * to * c); + let err = worst(&got, &f32s(&upsample_add_ref(&f64s(&x), &skip, c, (from, to)))); + assert!(err < 1e-6, "case {case}: off by {err}"); + } +} + +#[test] +fn group_norm_and_relu_give_the_definition() { + let Some(d) = gpu() else { return }; + let k = pixel_kernels(d); + // one chunk cut short; several with the last cut short; the decoder's 256 channels in 8 groups over chunks of + // 256 pixels, around a mean far from 0 (where E[x²] − E[x]² in f32 would lose the variance) + for (case, (pixels, c, groups, offset)) in + [(37usize, 16usize, 4usize, 0f32), (700, 24, 3, 0.0), (1100, 256, 8, 0.0), (600, 256, 8, 50.0), (5, 8, 1, 0.0)].into_iter().enumerate() + { + let x: Vec = values(pixels * c, 120 + case as u64, 2.0).iter().map(|v| v + offset).collect(); + let gamma = values(c, 130 + case as u64, 1.5); + let beta = values(c, 140 + case as u64, 0.5); + // normed in place, then read back: a buffer that can be copied from + let bx = buffer(d, "x", pixels * c); + d.queue.write_buffer(&bx, 0, bytemuck::cast_slice(&x)); + let (bg, bb) = (upload(d, "gamma", &gamma), upload(d, "beta", &beta)); + let (partials, stats) = (buffer(d, "partials", partials_len(pixels, groups)), buffer(d, "stats", 2 * groups)); + let mut g = Graph::new(d); + g.group_norm_relu(k, [&bx, &bg, &bb], [&partials, &stats], (pixels, c, groups), EPS).unwrap(); + let got = read(d, g, &bx, pixels * c); + let want = f32s(&group_norm_relu_ref(&f64s(&x), c, groups, &gamma, &beta, f64::from(EPS))); + let err = worst(&got, &want); + assert!(err < 2e-5, "case {case} ({pixels} pixels, {c} channels, {groups} groups): off by {err}"); + assert!(got.iter().all(|v| *v >= 0.0), "case {case}: ReLU"); + } +} + +#[test] +fn a_small_pixel_decoder_stage_gives_the_definition() { + let Some(d) = gpu() else { return }; + let (k, kn) = (pixel_kernels(d), neck::kernels(d).unwrap()); + // two stages as in the decoder (3² → 6² → 12²), 16 channels in 4 groups + let (c, groups) = (16usize, 4usize); + let x = values(3 * 3 * c, 150, 1.0); + let mut want = f64s(&x); + let mut cur = upload(d, "x", &x); + let mut g = Graph::new(d); + let mut side = 3; + for stage in 0..2u64 { + let skip = values(c * 4 * side * side, 160 + stage, 1.0); + let (w, b) = (values(c * c * 9, 170 + stage, 0.3), values(c, 180 + stage, 0.3)); + let (gamma, beta) = (values(c, 190 + stage, 1.0), values(c, 200 + stage, 0.3)); + want = upsample_add_ref(&want, &skip, c, (side, 2 * side)); + side *= 2; + want = conv_ref(&want, side, (c, c, 3), &w, &b); + want = group_norm_relu_ref(&want, c, groups, &gamma, &beta, f64::from(EPS)); + + let up = buffer(d, "up", side * side * c); + let out = buffer(d, "out", side * side * c); + let [bw, bb] = conv_weights(d, "conv", &w, &b, (c, c, 3)); + let (bs, bg, bt) = (upload(d, "skip", &skip), upload(d, "gamma", &gamma), upload(d, "beta", &beta)); + let (partials, stats) = (buffer(d, "partials", partials_len(side * side, groups)), buffer(d, "stats", 2 * groups)); + g.upsample_add(k, [&cur, &bs, &up], c, (side / 2, side)).unwrap(); + g.conv3(kn, [&up, &bw, &bb, &out], side, (c, c)).unwrap(); + g.group_norm_relu(k, [&out, &bg, &bt], [&partials, &stats], (side * side, c, groups), EPS).unwrap(); + cur = out; + } + let got = read(d, g, &cur, side * side * c); + let err = worst(&got, &f32s(&want)); + assert!(err < 1e-4, "off by {err}"); +} + +#[test] +fn the_mask_decoder_kernels_refuse_what_they_cannot_do() { + let Some(d) = gpu() else { return }; + let k = pixel_kernels(d); + let b = buffer(d, "b", 16); + let mut g = Graph::new(d); + assert!(g.upsample_add(k, [&b, &b, &b], 4, (0, 2)).is_err(), "an empty image"); + assert!(g.upsample_add(k, [&b, &b, &b], 4, (4, 2)).is_err(), "down-sampling"); + assert!(g.group_norm_relu(k, [&b, &b, &b], [&b, &b], (4, 12, 8), EPS).is_err(), "channels not a multiple of the groups"); + assert!(g.group_norm_relu(k, [&b, &b, &b], [&b, &b], (4, 512, 8), EPS).is_err(), "more channels than threads"); + assert!(g.group_norm_relu(k, [&b, &b, &b], [&b, &b], (0, 8, 8), EPS).is_err(), "no pixels"); +} + +#[test] +fn the_decoder_refuses_inputs_of_the_wrong_size() { + let Some(d) = gpu() else { return }; + // checked before the checkpoint is read: an empty reader is never touched + let dir = std::env::temp_dir().join(format!("lc-sam3-pixel-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut st = 2u64.to_le_bytes().to_vec(); + st.extend_from_slice(b"{}"); + std::fs::write(dir.join("model.safetensors"), st).unwrap(); + std::fs::write(dir.join("vocab.json"), "{}").unwrap(); + std::fs::write(dir.join("merges.txt"), "").unwrap(); + let m = MaskDecoder::new(WeightReader::open(&dir).unwrap()); + let (mem, text, valid) = (vec![0f32; GRID * GRID * WIDTH], vec![0f32; TEXT * WIDTH], vec![true; TEXT]); + let (l1, l0) = (vec![0f32; WIDTH * 144 * 144], vec![0f32; WIDTH * SIDE * SIDE]); + let rows = vec![0f32; 3 * WIDTH]; + assert!(m.run(d, &mem[1..], &text, &valid, [&l1, &l0], &rows, &[0.0; 3]).is_err_and(|e| e.contains("expected"))); + assert!(m.run(d, &mem, &text, &valid, [&l0, &l1], &rows, &[0.0; 3]).is_err_and(|e| e.contains("expected"))); + assert!(m.run(d, &mem, &text, &valid, [&l1, &l0], &rows, &[0.0; 2]).is_err_and(|e| e.contains("row values"))); + assert!(m.run(d, &mem, &text, &valid, [&l1, &l0], &[], &[]).is_err_and(|e| e.contains("row values"))); + // the right sizes reach the checkpoint, which has no decoder + assert!(m.run(d, &mem, &text, &valid, [&l1, &l0], &rows, &[0.0; 3]).is_err_and(|e| e.contains("mask_decoder"))); + assert!(m.bytes().is_none()); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/gpu/src/wgsl/sam3_pixel.wgsl b/crates/gpu/src/wgsl/sam3_pixel.wgsl new file mode 100644 index 0000000000..bc6b972cfd --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_pixel.wgsl @@ -0,0 +1,161 @@ +// The small steps of the text detector's pixel decoder (`sam3/pixel.rs`) around its 3 x 3 convolutions: nearest +// up-sampling plus the neck level it is added to, and GroupNorm + ReLU (statistics per chunk of pixels, merged per +// group, then applied in place). +// +// Images are pixel rows (`[pixels, channels]`, row-major); the neck levels come channels-first, as uploaded. Same +// bindings and parameter block as `sam3_ops.wgsl`; flat dispatches cover `count` items, 256 per workgroup, workgroups +// in rows of `row`. + +struct P { + a: u32, + b: u32, + c: u32, + d: u32, + e: u32, + f: u32, + count: u32, + row: u32, +} + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var src: array; +@group(0) @binding(2) var aux: array; +@group(0) @binding(3) var aux2: array; +@group(0) @binding(4) var dst: array; + +fn flat_id(wg: vec3, lid: u32) -> u32 { + return (wg.y * p.row + wg.x) * 256u + lid; +} + +// Nearest up-sampling of the rows `src` (a: channels, c: side) to side b, plus the channels-first image `aux` +// (`[a, b, b]`): dst[row · b + col, ch] = src[(row · c / b) · c + col · c / b, ch] + aux[ch, row, col]. (candle's +// `upsample_nearest2d` takes floor(i · c / b), the same for the decoder's exact doublings.) +@compute @workgroup_size(256) +fn upsample_add(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let ch = g % p.a; + let pixel = g / p.a; + let row = pixel / p.b; + let col = pixel % p.b; + let at = row * p.c / p.b * p.c + col * p.c / p.b; + dst[g] = src[at * p.a + ch] + aux[ch * p.b * p.b + pixel]; +} + +var red: array; + +fn reduce(lid: u32, v: f32) -> f32 { + red[lid] = v; + workgroupBarrier(); + for (var s = 128u; s > 0u; s >>= 1u) { + if (lid < s) { + red[lid] += red[lid + s]; + } + workgroupBarrier(); + } + let total = red[0]; + workgroupBarrier(); + return total; +} + +// Thread `lid` holds channel lid's `v`: leaves the sum over each group's channels in red[group] (a: channels, +// d: groups). +fn group_sums(lid: u32, v: f32) { + red[lid] = v; + workgroupBarrier(); + let per = p.a / p.d; + var s = 0.0; + if (lid < p.d) { + for (var i = 0u; i < per; i++) { + s += red[lid * per + i]; + } + } + workgroupBarrier(); + if (lid < p.d) { + red[lid] = s; + } + workgroupBarrier(); +} + +// GroupNorm statistics of one chunk of pixels (a: channels ≤ 256, b: pixels, c: pixels per chunk, d: groups), one +// workgroup per chunk, thread = channel: each group's mean over the chunk and the sum of squared differences from +// it, at dst[(chunk · d + group) · 2 + 0 | 1]. Two passes over the chunk (the second from the cache), so a large mean +// costs no precision. +@compute @workgroup_size(256) +fn group_stats(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let chunk = wg.y * p.row + wg.x; + let first = chunk * p.c; + if (first >= p.b) { + return; + } + let last = min(first + p.c, p.b); + let live = lid < p.a; + let ch = min(lid, p.a - 1u); + let per = p.a / p.d; + let n = f32((last - first) * per); + var s = 0.0; + if (live) { + for (var px = first; px < last; px++) { + s += src[px * p.a + ch]; + } + } + group_sums(lid, s); + let mean = red[ch / per] / n; + let own = red[min(lid, p.d - 1u)] / n; + workgroupBarrier(); + var q = 0.0; + if (live) { + for (var px = first; px < last; px++) { + let d = src[px * p.a + ch] - mean; + q += d * d; + } + } + group_sums(lid, q); + if (lid < p.d) { + let o = (chunk * p.d + lid) * 2u; + dst[o] = own; + dst[o + 1u] = red[lid]; + } +} + +// The chunks' statistics merged, one workgroup per group (a: chunks, b: pixels, c: pixels per chunk, d: groups, +// e: eps bits, f: channels per group): dst[group · 2 + 0 | 1] = the group's mean and 1 / sqrt(variance + eps), the +// variance biased (over all of the group's numbers), as candle's GroupNorm. +@compute @workgroup_size(256) +fn group_merge(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = wg.x; + let total = f32(p.b * p.f); + var s = 0.0; + for (var i = lid; i < p.a; i += 256u) { + let n = f32(min(p.c, p.b - i * p.c) * p.f); + s += n * src[(i * p.d + g) * 2u]; + } + let mean = reduce(lid, s) / total; + var q = 0.0; + for (var i = lid; i < p.a; i += 256u) { + let n = f32(min(p.c, p.b - i * p.c) * p.f); + let o = (i * p.d + g) * 2u; + let d = src[o] - mean; + q += src[o + 1u] + n * d * d; + } + let variance = reduce(lid, q) / total; + if (lid == 0u) { + dst[g * 2u] = mean; + dst[g * 2u + 1u] = inverseSqrt(variance + bitcast(p.e)); + } +} + +// GroupNorm and ReLU in place on the rows `dst` (a: channels, d: groups) with the merged statistics `src`, the scale +// `aux` and the shift `aux2` (`[a]` each): dst = max((dst − mean) · rstd · aux + aux2, 0). +@compute @workgroup_size(256) +fn group_norm_relu(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let ch = g % p.a; + let group = ch / (p.a / p.d); + dst[g] = max((dst[g] - src[group * 2u]) * src[group * 2u + 1u] * aux[ch] + aux2[ch], 0.0); +} diff --git a/crates/gpu/tests/it/main.rs b/crates/gpu/tests/it/main.rs index 89aa46310a..cf52a4f72f 100644 --- a/crates/gpu/tests/it/main.rs +++ b/crates/gpu/tests/it/main.rs @@ -12,4 +12,6 @@ mod sam3_backbone; #[cfg(feature = "sam")] mod sam3_detr; #[cfg(feature = "sam")] +mod sam3_mask_decoder; +#[cfg(feature = "sam")] mod sam3_necks; diff --git a/crates/gpu/tests/it/sam3_mask_decoder.rs b/crates/gpu/tests/it/sam3_mask_decoder.rs new file mode 100644 index 0000000000..09520ebea9 --- /dev/null +++ b/crates/gpu/tests/it/sam3_mask_decoder.rs @@ -0,0 +1,287 @@ +//! The text detector's mask decoder on the GPU against the candle decoder (the reference), on one photo: the per-query +//! mask logits of all 200 queries, and the merged Describe mask, for a few prompts. Both models get the same backbone +//! output, necks and DETR encoder memory (one GPU accelerator, shared), so only the mask decoder differs. For the first +//! prompt, the instance features also against the decoder transcribed with candle's tensor ops in f64 (and in f32, to +//! show how far candle's own f32 decoder is from it). +//! +//! Needs the checkpoint: `LIGHTCRAFT_SAM3_DIR= cargo test --release -p lightcraft-gpu --features sam +//! --test it sam3_mask_decoder:: -- --nocapture`. The photo is a procedural one, or the input of a reference file made by +//! `tools/sam3_reference.py` (`LIGHTCRAFT_SAM3_REF=`). `LIGHTCRAFT_SAM3_PROMPTS` lists the prompts, +//! comma-separated (default "person,sky,the red car"). Skipped without a model or a GPU. + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Instant; + +use candle_core::{Device, Tensor}; +use lightcraft_gpu::sam3::{self, Precision, Sam3Gpu}; +use lightcraft_segment::{BackboneAccel, DetectorOutput, INPUT, NeckKind, Sam3, WeightReader}; + +fn values(t: &Tensor) -> Vec { + t.to_device(&Device::Cpu).unwrap().flatten_all().unwrap().to_vec1::().unwrap() +} + +/// Max |a − b|, that relative to max |b|, and mean |a − b|. +fn errors(name: &str, a: &[f32], b: &[f32]) -> (f32, f32, f64) { + assert_eq!(a.len(), b.len(), "{name}: length"); + let scale = b.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-6); + let max = a.iter().zip(b).fold(0f32, |m, (x, y)| m.max((x - y).abs())); + let mean = a.iter().zip(b).map(|(x, y)| f64::from((x - y).abs())).sum::() / a.len().max(1) as f64; + eprintln!(" {name}: max abs {max:.3e}, max rel {:.3e} (scale {scale:.2}), mean abs {mean:.3e}", max / scale); + (max, max / scale, mean) +} + +/// Intersection over union of two masks (logits > 0). +fn iou(a: &[f32], b: &[f32]) -> f32 { + // masks of different sizes are no match (`zip` would compare only the shorter's pixels) + assert_eq!(a.len(), b.len(), "mask sizes"); + let (mut both, mut either) = (0usize, 0usize); + for (x, y) in a.iter().zip(b) { + let (x, y) = (*x > 0.0, *y > 0.0); + both += usize::from(x && y); + either += usize::from(x || y); + } + if either == 0 { 1.0 } else { both as f32 / either as f32 } +} + +fn sigmoid(x: f32) -> f32 { + 1.0 / (1.0 + (-x).exp()) +} + +/// The Describe mask of `out` as `Sam3::segment_text` merges it at 0.5 (the per-pixel maximum over the instances +/// scoring above it), the instances, and the best-scoring query. +fn merged(out: &DetectorOutput, masks: &[f32]) -> (Vec, Vec, usize) { + let side = lightcraft_segment::MASK_SIDE * lightcraft_segment::MASK_SIDE; + let mut merged = vec![f32::MIN; side]; + let keep: Vec = (0..out.logits.len()).filter(|&i| sigmoid(out.logits[i]) * sigmoid(out.presence) > 0.5).collect(); + for i in &keep { + for (m, v) in merged.iter_mut().zip(&masks[i * side..(i + 1) * side]) { + *m = m.max(*v); + } + } + let best = (0..out.logits.len()).max_by(|a, b| out.logits[*a].total_cmp(&out.logits[*b])).unwrap(); + (merged, keep, best) +} + +/// The photo as preprocessed pixels `[1, 3, 1008, 1008]`. +fn photo() -> Tensor { + if let Some(path) = std::env::var_os("LIGHTCRAFT_SAM3_REF").map(PathBuf::from) { + let mut r = candle_core::safetensors::load(&path, &Device::Cpu).unwrap(); + return r.remove("pixel_values").unwrap(); + } + let img = lightcraft_scenes::demo_library()[0].render_fit(1600).to_srgb8(); + let rgb: Vec = img.data.iter().flat_map(|p| [p[0], p[1], p[2]]).collect(); + let px = lightcraft_segment::mask::preprocess(&rgb, img.width, img.height, INPUT).unwrap(); + Tensor::from_vec(px, (1, 3, INPUT, INPUT), &Device::Cpu).unwrap() +} + +/// The mask decoder transcribed with candle's tensor ops in `dtype` (f64: the arbiter between the two f32 decoders): +/// the instance features `[256, 288 · 288]` for the encoder memory `[5184, 256]`, the prompt `[32, 256]` (`valid`: its +/// real tokens) and the neck levels `[256, 144, 144]`, `[256, 288, 288]`. +fn decoder_ref(w: &WeightReader, memory: &Tensor, (text, valid): (&Tensor, &[bool]), [l1, l0]: [&Tensor; 2], dtype: candle_core::DType) -> Tensor { + let get = |name: &str| { + let (shape, data) = w.read(&format!("detector_model.mask_decoder.{name}")).unwrap(); + Tensor::from_vec(data, shape, &Device::Cpu).unwrap().to_dtype(dtype).unwrap() + }; + let lin = |x: &Tensor, name: &str| { + x.matmul(&get(&format!("{name}.weight")).t().unwrap()).unwrap().broadcast_add(&get(&format!("{name}.bias"))).unwrap() + }; + let (memory, text) = (memory.to_dtype(dtype).unwrap(), text.to_dtype(dtype).unwrap()); + // prompt attention: LN (eps 1e-5) → 8 heads of 32 over the prompt (padding masked) → output projection, added + let mean = memory.mean_keepdim(1).unwrap(); + let centred = memory.broadcast_sub(&mean).unwrap(); + let var = centred.sqr().unwrap().mean_keepdim(1).unwrap(); + let h = centred.broadcast_div(&(var + 1e-5).unwrap().sqrt().unwrap()).unwrap(); + let h = h.broadcast_mul(&get("prompt_cross_attn_norm.weight")).unwrap().broadcast_add(&get("prompt_cross_attn_norm.bias")).unwrap(); + let heads = |x: Tensor| x.reshape((x.dim(0).unwrap(), 8, 32)).unwrap().transpose(0, 1).unwrap().contiguous().unwrap(); + let q = heads(lin(&h, "prompt_cross_attn.q_proj")); + let k = heads(lin(&text, "prompt_cross_attn.k_proj")); + let v = heads(lin(&text, "prompt_cross_attn.v_proj")); + let bias: Vec = valid.iter().map(|&ok| if ok { 0.0 } else { f32::MIN }).collect(); + let bias = Tensor::from_vec(bias, (1, 1, 32), &Device::Cpu).unwrap().to_dtype(dtype).unwrap(); + let s = (q.matmul(&k.t().unwrap()).unwrap() * (32f64).powf(-0.5)).unwrap().broadcast_add(&bias).unwrap(); + let e = s.broadcast_sub(&s.max_keepdim(2).unwrap()).unwrap().exp().unwrap(); + let p = e.broadcast_div(&e.sum_keepdim(2).unwrap()).unwrap(); + let o = p.matmul(&v).unwrap().transpose(0, 1).unwrap().reshape((5184, 256)).unwrap(); + let mem = (memory + lin(&o, "prompt_cross_attn.o_proj")).unwrap(); + // the pixel decoder + let mut prev = mem.t().unwrap().reshape((1, 256, 72, 72)).unwrap(); + for (i, skip) in [l1, l0].into_iter().enumerate() { + let side = skip.dim(1).unwrap(); + prev = (prev.upsample_nearest2d(side, side).unwrap() + skip.to_dtype(dtype).unwrap().unsqueeze(0).unwrap()).unwrap(); + let c = format!("pixel_decoder.conv_layers.{i}"); + prev = prev + .conv2d(&get(&format!("{c}.weight")), 1, 1, 1, 1) + .unwrap() + .broadcast_add(&get(&format!("{c}.bias")).reshape((1, 256, 1, 1)).unwrap()) + .unwrap(); + let g = prev.reshape((8, 32 * side * side)).unwrap(); + let centred = g.broadcast_sub(&g.mean_keepdim(1).unwrap()).unwrap(); + let var = centred.sqr().unwrap().mean_keepdim(1).unwrap(); + let normed = centred.broadcast_div(&(var + 1e-5).unwrap().sqrt().unwrap()).unwrap().reshape((1, 256, side, side)).unwrap(); + let n = format!("pixel_decoder.norms.{i}"); + let (gamma, beta) = + (get(&format!("{n}.weight")).reshape((1, 256, 1, 1)).unwrap(), get(&format!("{n}.bias")).reshape((1, 256, 1, 1)).unwrap()); + prev = normed.broadcast_mul(&gamma).unwrap().broadcast_add(&beta).unwrap().relu().unwrap(); + } + let inst = prev.conv2d(&get("instance_projection.weight"), 0, 1, 1, 1).unwrap(); + inst.broadcast_add(&get("instance_projection.bias").reshape((1, 256, 1, 1)).unwrap()).unwrap().reshape((256, 288 * 288)).unwrap() +} + +/// One GPU accelerator for both models; the mask decoder only for one of them, the other gets a result of the wrong +/// size (and then runs the candle decoder; `asked` counts the calls). +struct Shared { + gpu: Arc, + masks: bool, + asked: Arc, +} + +impl BackboneAccel for Shared { + fn forward(&self, pixels: &[f32]) -> Result, String> { + self.gpu.forward(pixels) + } + + fn device(&self) -> String { + self.gpu.device() + } + + fn runs_necks(&self) -> bool { + true + } + + fn runs_detr_encoder(&self) -> bool { + true + } + + fn runs_mask_decoder(&self) -> bool { + true + } + + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> Result>, String> { + self.gpu.neck(which, backbone, n) + } + + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> Result, String> { + self.gpu.detr_encoder(image, pos, text, valid) + } + + fn mask_decoder( + &self, + memory: &[f32], + text: &[f32], + valid: &[bool], + levels: [&[f32]; 2], + rows: &[f32], + bias: &[f32], + ) -> Result, String> { + self.asked.fetch_add(1, Ordering::Relaxed); + if self.masks { self.gpu.mask_decoder(memory, text, valid, levels, rows, bias) } else { Ok(vec![0.0; 10]) } + } +} + +#[test] +fn the_gpu_mask_decoder_matches_the_candle_decoder() { + let Some(dir) = std::env::var_os("LIGHTCRAFT_SAM3_DIR").map(PathBuf::from).filter(|d| lightcraft_segment::is_model_dir(d)) else { + lightcraft_testkit::skip!(Model, "set LIGHTCRAFT_SAM3_DIR to the SAM 3 model directory"); + return; + }; + let adapter = match sam3::adapter() { + Ok(a) => a, + // a kernel that doesn't compile is a failure, not a missing GPU + Err(e) if e.contains("did not compile") => panic!("{e}"), + Err(e) => { + lightcraft_testkit::skip!(Gpu, "no GPU for the SAM 3 kernels ({e})"); + return; + } + }; + let gpu = Arc::new(sam3::load(&WeightReader::open(&dir).unwrap(), Precision::F32).unwrap()); + let (asked_cpu, asked_gpu) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); + let with = |masks: bool, asked: &Arc| { + let (gpu, asked) = (gpu.clone(), asked.clone()); + move |_: &WeightReader| -> Result, String> { Ok(Box::new(Shared { gpu, masks, asked })) } + }; + let mut cpu = Sam3::load_accelerated(&dir, Device::Cpu, with(false, &asked_cpu)).unwrap(); + let mut acc = Sam3::load_accelerated(&dir, Device::Cpu, with(true, &asked_gpu)).unwrap(); + let pixels = photo(); + let mut enc_cpu = cpu.encode_pixels(&pixels).unwrap(); + let mut enc_acc = acc.encode_pixels(&pixels).unwrap(); + + let prompts = std::env::var("LIGHTCRAFT_SAM3_PROMPTS").unwrap_or_else(|_| "person,sky,the red car".into()); + let prompts: Vec<&str> = prompts.split(',').map(str::trim).filter(|p| !p.is_empty()).collect(); + for (n, prompt) in prompts.iter().copied().enumerate() { + let t = Instant::now(); + let want = cpu.detect(&mut enc_cpu, prompt).unwrap(); + let cpu_time = t.elapsed(); + let t = Instant::now(); + let got = acc.detect(&mut enc_acc, prompt).unwrap(); + let gpu_time = t.elapsed(); + let first = if n == 0 { " (first prompt: with the detector neck and loading)" } else { "" }; + eprintln!("{prompt:?}: detector with the candle mask decoder {cpu_time:?}, with the GPU one {gpu_time:?}{first}"); + assert_eq!(acc.mask_fallback(), None, "the GPU mask decoder ran"); + assert!(cpu.mask_fallback().is_some_and(|w| w.contains("returned 10 values"))); + assert_eq!(acc.heads_device(), "CPU; the necks, the DETR encoder and the mask decoder on the GPU"); + assert_eq!(cpu.heads_device(), "CPU; the necks and the DETR encoder on the GPU"); + + if n == 0 { + // the instance features (the instance projection as the rows) against the f64 transcription, and how far + // the same transcription in f32 is from it + let reader = WeightReader::open(&dir).unwrap(); + let (_, valid) = lightcraft_segment::tokenizer::Tokenizer::load(&dir).unwrap().encode(prompt); + let levels = acc.neck_levels(NeckKind::Detector, &enc_acc).unwrap(); + let (l1, l0) = (levels[1].squeeze(0).unwrap(), levels[0].squeeze(0).unwrap()); + let (memory, text) = (got.memory.squeeze(0).unwrap(), got.text.squeeze(0).unwrap()); + let (_, rows) = reader.read("detector_model.mask_decoder.instance_projection.weight").unwrap(); + let (_, bias) = reader.read("detector_model.mask_decoder.instance_projection.bias").unwrap(); + let t = Instant::now(); + let ours = gpu.mask_decoder(&values(&memory), &values(&text), &valid, [&values(&l1), &values(&l0)], &rows, &bias).unwrap(); + eprintln!(" GPU instance features {:?}", t.elapsed()); + let t = Instant::now(); + let f64_ref: Vec = values( + &decoder_ref(&reader, &memory, (&text, &valid), [&l1, &l0], candle_core::DType::F64).to_dtype(candle_core::DType::F32).unwrap(), + ); + let f32_ref = values(&decoder_ref(&reader, &memory, (&text, &valid), [&l1, &l0], candle_core::DType::F32)); + eprintln!(" references {:?}", t.elapsed()); + let (_, rel, mean) = errors("instance features, GPU vs f64", &ours, &f64_ref); + errors("instance features, candle f32 vs f64", &f32_ref, &f64_ref); + assert!(rel < 1e-4 && mean < 1e-5, "the GPU instance features are off"); + } + + // the same memory and decoder for both: only the masks may differ, by candle's own error (its f32 decoder is + // ~400 × further from the f64 one than the GPU's, above) + let (_, logits, _) = errors("query logits", &got.logits, &want.logits); + assert!(logits < 1e-4, "the query logits moved"); + let (mg, mc) = (values(&got.masks), values(&want.masks)); + let (_, rel, mean) = errors("mask logits (200 queries), GPU vs candle", &mg, &mc); + assert!(rel < 1e-2 && mean < 0.1, "the GPU mask logits are off"); + let ((mask_g, kept_g, best_g), (mask_c, kept_c, best_c)) = (merged(&got, &mg), merged(&want, &mc)); + let side = lightcraft_segment::MASK_SIDE * lightcraft_segment::MASK_SIDE; + let best = iou(&mg[best_g * side..(best_g + 1) * side], &mc[best_c * side..(best_c + 1) * side]); + let i = iou(&mask_g, &mask_c); + eprintln!(" instances {} vs {}, Describe mask IoU {i:.5}, best query's mask IoU {best:.5}", kept_g.len(), kept_c.len()); + assert_eq!(kept_g, kept_c, "the same instances"); + assert!(i > 0.99 && best > 0.99, "describe mask IoU {i}, best query {best}"); + // the semantic mask (one more row of the GPU's mask product) + let (_, rel, mean) = errors("semantic mask logits, GPU vs candle", &got.semantic, &want.semantic); + let semantic = iou(&got.semantic, &want.semantic); + eprintln!(" semantic mask IoU {semantic:.5}"); + assert!(rel < 1e-2 && mean < 0.1 && semantic > 0.99, "the GPU semantic mask is off"); + } + // an accelerator whose decoder failed once isn't asked again + assert_eq!(asked_cpu.load(Ordering::Relaxed), 1); + assert_eq!(asked_gpu.load(Ordering::Relaxed), prompts.len()); + + // the decoder alone (with the uploads and the read-back) + let (memory, text) = (vec![0.1f32; 5184 * 256], vec![0.3f32; 32 * 256]); + let valid: Vec = (0..32).map(|i| i < 4).collect(); + let (l1, l0) = (vec![0.2f32; 256 * 144 * 144], vec![0.4f32; 256 * 288 * 288]); + let (rows, bias) = (vec![0.01f32; 200 * 256], vec![0.5f32; 200]); + let mut best = f64::MAX; + for _ in 0..5 { + let t = Instant::now(); + gpu.mask_decoder(&memory, &text, &valid, [&l1, &l0], &rows, &bias).unwrap(); + best = best.min(t.elapsed().as_secs_f64()); + } + let (w, b) = gpu.mask_decoder_bytes().unwrap(); + eprintln!("GPU mask decoder alone: {:.1} ms on {adapter}; {:.0} MB weights, {:.0} MB work buffers", best * 1e3, w as f64 / 1e6, b as f64 / 1e6); +} diff --git a/docs/ai-masks.md b/docs/ai-masks.md index 84e082163b..5e329ae298 100644 --- a/docs/ai-masks.md +++ b/docs/ai-masks.md @@ -2,8 +2,10 @@ LightCraft selects objects with **SAM 3** (Segment Anything with Concepts, Meta 2025), run in pure Rust by `crates/segment` on [candle](https://github.com/huggingface/candle): on the GPU -through Metal on macOS, on the CPU elsewhere (for now). If the Mac's GPU can't run it, it runs on -the CPU (see the worker below). +through Metal on macOS (if the Mac's GPU can't run it, it runs on the CPU, see the worker below); on Linux and Windows the image encoder (most of the work) runs on the GPU +through wgpu (Vulkan / DX12), with the two necks and the text detector's DETR encoder and mask +decoder, and the rest on the CPU, falling back to the CPU when there is no usable GPU +([Where it runs](#where-it-runs)). **The model is optional.** It is not part of LightCraft, and nothing requires it: without it, Object and Describe offer to download it, every other feature (and every existing mask, see @@ -34,7 +36,9 @@ In the Masking panel (M): The first Object or Describe on a photo analyzes it (the image encoder runs once per photo and look: ~3 s on an Apple M4 Pro, plus a one-time ~6 s for compiling GPU kernels and loading the -model after launch). That starts in the background as soon as you pick Object; after it, each +model after launch; ~0.6 s on an RTX 5070 under Linux, of which 0.45 s is the image encoder and +0.12 s the click features, plus ~1–2 s once for loading the model onto the GPU; 32–33 s with all +of it on a 12-core Ryzen CPU). That starts in the background as soon as you pick Object; after it, each click takes ~35 ms and each description ~0.6 s. Everything the model does runs on its own worker thread: the window stays responsive, a click shows its dot at once and the selection follows when it's computed ("Selecting…" / "Analyzing the photo…" under the mask tiles). The model is @@ -46,6 +50,76 @@ The result is stored with the mask: the model's 288 × 288 mask logits over the need the model, so masks survive moving the library to a machine without it, and the web build renders them. Editing the photo's look later does not recompute a mask (click again to update). +## Where it runs + +| | Image encoder (once per photo) | Click features, clicks, descriptions | +|---|---|---| +| macOS | GPU: Metal (candle) | GPU: Metal (candle) | +| Linux, Windows | GPU: wgpu compute on Vulkan / DX12 (`lightcraft-gpu`, module `sam3`) | the two necks and the text detector's DETR encoder and mask decoder on the GPU (wgpu); the click decoder, the text encoder and the DETR decoder on the CPU (candle) | +| no usable GPU, `LIGHTCRAFT_GPU=0` / `LIGHTCRAFT_GPU_BACKEND=off`, or the GPU failed; outside macOS also GPU rendering off | CPU (candle) | CPU (candle) | +| **CPU** chosen in Settings (any platform, macOS included) | CPU (candle) | CPU (candle) | + +Measured on Linux (AMD Ryzen 9 3900X, 12 cores / 24 threads; NVIDIA RTX 5070), release build, +the photo already rendered: + +| Step | CPU only | On the GPU | +|---|---|---| +| Image encoder (once per photo) | 30.2–31.2 s | 0.49–0.57 s (0.43–0.44 s of it on the GPU, see [gpu-pipeline.md](gpu-pipeline.md#sam-3-backbone-m12)) | +| Loading the model (once, and again after 10 min idle) | ~1.5 s | ~1.8 s (device and kernels 0.16–1 s, weight upload ~1.1 s) | +| A photo's whole analysis before its first click | 32.3–33.4 s | 0.56–0.69 s | +| Click features (once per photo, before the first click) | 2.1–2.3 s | 0.12–0.19 s (the tracker neck on the GPU, 38 ms) | +| A click | ~0.14 s | ~0.14 s (CPU) | +| First description on a photo (detector features + text) | 6.3–6.9 s | 0.5–0.8 s (1.3 s the very first time, with the detector loading) (the detector neck, the DETR encoder and the mask decoder on the GPU) | +| A further description | 4.4–4.5 s | ~0.7 s (the DETR encoder and the mask decoder on the GPU, 24 + 33 ms; the rest on the CPU) | +| A prompt used before (on this or an earlier photo; the latest 16 are kept) | ~4.35 s | 0.45–0.46 s (no text encoder) | + +(CPU: `cargo run -p lightcraft-segment --release --example sam3_bench -- `; GPU: +`LIGHTCRAFT_SAM3_DIR= cargo run -p lightcraft-gpu --release --features sam --example +sam3_backbone_bench -- --app`, and the desktop app's log lines, `SAM 3 loaded in …` and `SAM 3 +analyzed …`. What each GPU part takes: [gpu-pipeline.md](gpu-pipeline.md#sam-3-backbone-m12).) + +**Falling back.** When the GPU can't be used (no adapter, a software one, the driver refuses the +device, not enough memory) the model loads with the image encoder on the CPU. When the GPU fails +on a photo (device lost, an output of the wrong size or with NaN), that photo is analyzed again on +the CPU and the model stays there until it loads again (except while LightCraft is closing: then +the work ends with its error, and nothing starts on the CPU). Neither is an error: the log says why +(`SAM 3 backbone accelerator unavailable (…)`, `SAM 3 backbone failed on … (…)`), and so do +Settings and `segment.model.status`. + +**Forcing the CPU.** Choose **Settings ▸ Performance ▸ AI masks ▸ Run on: CPU** +(`segment.settings {"runOn": "cpu"}`; back with `"auto"`, the default). It puts all of SAM 3 on the +CPU on every platform, macOS included (candle's CPU device instead of Metal), for a GPU that can't +run the model, and leaves GPU rendering alone. The choice is kept in +`/models/sam3-settings.json` (`{"runOn": "cpu"}`) and `segment.model.status` reports it as +`runOn`. Automatic also gives way to the switches every GPU compute in LightCraft follows (AI +Denoise, faces): `LIGHTCRAFT_GPU=0` / `LIGHTCRAFT_GPU_BACKEND=off` at start (no GPU at all for the +process) put SAM 3 on the CPU on every platform, macOS included; **Settings ▸ Performance ▸ Use the +GPU for rendering** off (`app.gpu {"enabled": false}`) does so outside macOS, where it governs the +wgpu kernels, while on macOS candle keeps Metal. When a switch changes where it runs, a model +already loaded moves at its next request (it loads again). + +**Seeing where it runs.** Settings ▸ Performance ▸ AI masks shows what the image encoder runs on +(the GPU's name, "Metal GPU" or "CPU", with the reason when it is not on the GPU) and how long the +last photo took. `segment.model.status` → `backend` says the same for agents and scripts: + +```json +"backend": { + "device": "NVIDIA GeForce RTX 5070 (Vulkan)", + "runtime": "wgpu", + "heads": "CPU; the necks, the DETR encoder and the mask decoder on the GPU", + "fallback": null, + "encodeMs": 1234, + "analyzeMs": 3456 +} +``` + +`device` is what runs the image encoder (`null` until the model first loads), `runtime` `wgpu` +(LightCraft's kernels) or `candle`, `heads` what runs the rest, `fallback` why the encoder is not on +the GPU where it could be, `encodeMs` the last image encoder run and `analyzeMs` the last photo's +analysis before its first click (encoder and click features). The log (info level) has each load +(`SAM 3 loaded in …: the backbone on the …, the rest on the CPU; the necks, the DETR encoder and the +mask decoder on the GPU`) and each photo (`SAM 3 analyzed W×H in …: backbone … on the …, click features … on the …`). + ## Remote Metal inference Native builds with `sam` can keep the editor, RAW files, library, and exports local while @@ -64,7 +138,9 @@ ssh -N -T -o ExitOnForwardFailure=yes -L 127.0.0.1:8793:127.0.0.1:8793 user@your LIGHTCRAFT_SAM3_REMOTE=127.0.0.1:8793 lightcraft ``` -Object clicks, Describe prompts, and detail refinement use the remote worker. Only the +Object clicks, Describe prompts, and detail refinement use the remote worker. **Run on** (Settings +▸ Performance ▸ AI masks, `segment.settings`) only places local inference: the remote worker +always runs on the Mac's Metal device, whatever is chosen here. Only the rendered model input (long edge at most 1008 pixels) and prompts cross the tunnel. The worker caches the current photo; detail crops do not replace that cache. Returned masks stay in the local library, so later adjustments and exports work without the connection. @@ -190,11 +266,14 @@ Therefore: | `mask.objectPoint` | `{x, y, exclude?: bool, id?}` | one click on the selected mask's Object selection (≤ 64 clicks) | | `mask.refineDetail` | `{id?, component?}` | the zoomed-in detail pass → `{started}` | | `segment.prepare` | `{}` | load the model and analyze the active photo → `{busy}` | -| `segment.model.status` | `{}` | `{available, installed, remote, dir, loaded, busy, analyzing, sizeBytes, license, licenseUrl, mirrors, download}` | +| `segment.model.status` | `{}` | `{available, installed, remote, dir, loaded, busy, analyzing, runOn, backend, sizeBytes, license, licenseUrl, mirrors, download}` | +| `segment.settings` | `{runOn?: "auto" \| "cpu"}` | where SAM 3 runs ([Where it runs](#where-it-runs)) → `{runOn}` | | `segment.model.download` | `{acknowledged: true}` | start the download in the background → `{started}` | | `segment.model.cancel` | `{}` | stop it (it resumes next time) → `{cancelled}` | `remote` reports the configured endpoint, not its health. `installed` describes local weights only. +`backend` is where the model runs and how long the last photo took ([Where it runs](#where-it-runs)); `null` in a +build without AI masks. `download` is `{running, done, total, file, error, cancelled, finished}`: `cancelled` is true when the last download was cancelled (its `error` says so in words; decide on the flag). An AI mask command refused because the model is not installed (or still downloading) fails with an error that starts with "The SAM 3 model is @@ -225,6 +304,13 @@ wait and return the result (when built with the `sam` feature; the default CLI h memory map: `unsafe` stays in `lightcraft-sysmem`), only the tensors a path needs, and every tensor's byte range is checked against the file's length when it is opened (a truncated or damaged file is an error, never a crash). +- The image encoder can run outside candle: `lightcraft_segment::BackboneAccel` (pixels in, the + backbone's `[1024, 72, 72]` features out), built from the checkpoint through `WeightReader` and + given to `Sam3::load_accelerated`. `lightcraft-gpu` (feature `sam`, on with the engine's `sam`) + implements it in WGSL. `Sam3` checks every result (size, finite values) and drops the + accelerator for the candle backbone on the first failure; `Sam3::backbone_device` / + `accelerated` / `backbone_fallback` report it. The engine's worker picks the placement + (`Placement` in `worker.rs`). - The engine (`crates/engine/src/segment/`) owns one worker thread with the model and the last encoded photo; the session sends it jobs and receives results over channels, never holding a lock the model holds. Each job runs under `catch_unwind`: a panic inside candle becomes an diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index c55e12965e..af3bf7088c 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -328,6 +328,166 @@ A view's stages keep an uploaded source only up to 96 MB (a Preview-level source - Result (M4 Pro, 14 raws, loupe, 12 steps): peak RSS 1.9–2.3 GB → 0.83–0.99 GB, peak footprint 2.5–2.6 GB → 0.91–0.96 GB, heap peak 930 → ~600 MB; stepping median ~13 ms (unchanged). +## SAM 3 backbone (M12) +AI masks (Object, Subject, Describe) spend almost all of their time in SAM 3's vision backbone, a 32-layer ViT +(`crates/segment/src/vit.rs`, ~4.6 TFLOP plus attention per photo): ~37–40 s on the CPU through candle. With the +`sam` feature, `lightcraft_gpu::sam3::backbone(&WeightReader)` runs it with wgpu compute kernels instead and returns +a `lightcraft_segment::BackboneAccel` for `Sam3::load_accelerated`; the heads stay on candle (the necks: below). It has a +device of its own (like denoise and faces) with the same switches, crash sentinel, shutdown gate and +stop-after-a-device-error handling; any failure is an `Err` and the candle backbone runs instead. +- Same math as `vit.rs`: patch embedding (im2col + matrix product, 24 × 24 position table tiled), `ln_pre`, then per + layer LN → one q|k|v product (the three weights concatenated) → 2-D RoPE (`rope_tables`, recomputed bit for bit) + → attention over 24 × 24 windows, or all 5184 tokens in layers 7/15/23/31 → output projection + residual → LN → + MLP 1024 → 4736 → 1024 with GELU (erf form; A&S 7.1.26, |error| < 1.5e-7) + residual. +- Tokens stay in *window order* (window-major, row-major inside a window) from the patch embedding to the last + layer: a window is a contiguous range of keys, the position table repeats per window (a bias table indexed by + row % 576), and global attention does not depend on order (its RoPE table is stored in window order). The last + kernel writes the `[1024, 72, 72]` channels-first output. +- Kernels (`wgsl/sam3_*.wgsl`): `sam3_matmul` (Y = X · Wᵀ with the checkpoint's `[N, K]` weights as they are, + 64 × 64 tiles, 4 × 4 per thread, k in steps of 16 through padded workgroup memory, bias/GELU/residual in the + epilogue; written out per tile size with one variable per accumulator), `sam3_attention` (flash style: one query + per thread, keys and values 32 at a time through workgroup memory, online softmax; the 16 × 5184² scores of a + global layer never exist; also written out, since arrays indexed in loops spilled to local memory and ran 3.5 × + slower), `sam3_ops` (layer norm, RoPE in place with the 1/8 scale folded into q, im2col, the final reorder). No + subgroups and no shader-f16 needed. +- All 228 dispatches, their parameters (one uniform buffer) and bind groups are recorded once with the weights; a + forward pass writes the pixels, submits one command buffer per layer and reads the result back once. +- Limits requested: WebGPU downlevel defaults plus 98 MB storage bindings / buffers (the MLP's activations, + 5184 × 4736 floats) and 16 KB of workgroup memory. Device memory: 1.8 GB of f32 weights + 0.2 GB of work + buffers. When the f32 weights don't fit (out-of-memory while uploading), it retries with f16 weights (pairs + packed in u32, unpacked with `unpack2x16float`, products still in f32): 0.9 GB, but ~20 × the error (below). + An adapter short of a limit gets no device (`short_limits`, e.g. "max_storage_buffer_binding_size 67108864 < + 98205696"), nor does one whose device creation fails or panics (the crash sentinel keeps a driver crash from + repeating on the next start); SAM 3 then runs in candle on the CPU, and `segment.model.status` → `backend.fallback` + and Settings ▸ Performance ▸ AI masks say why. +- Measured (RTX 5070, Vulkan, `examples/sam3_backbone_bench.rs`): device + kernel compile 0.16–0.3 s (≈1 s with a + cold driver shader cache), weight upload 1.1 s, first forward 0.43–0.47 s, warm forward 0.43–0.44 s; candle on + the CPU 36–40 s. Matrix products ~13.5 TFLOP/s (~80 % of the time), attention ~12 TFLOP/s. f16 weights: 0.47 s + (no faster: the products are compute-bound), upload 2.9 s. +- Accuracy (`tests/it/sam3_backbone.rs`, a photo with a Hugging Face reference from `tools/sam3_reference.py`): GPU vs + CPU backbone max abs 5.3e-2 at a scale of 223 (max rel 2.4e-4), mean abs 2.2e-5; against Hugging Face the GPU is + as close as the CPU port (max rel 1.4e-4 vs 2.0e-4). Click masks and a Describe mask ("person") from either + backbone: IoU 1.0. With f16 weights: max rel 3.8e-3, mean abs 5.4e-4, mask IoU ≥ 0.9997. +- Tests: kernel unit tests against plain loops (`src/sam3/tests.rs`: cut-off tiles, K not a multiple of the tile, + windowed and global attention, LN, RoPE, im2col/reorder, f16 rounding), skipped without a GPU; the end-to-end + test runs with `LIGHTCRAFT_SAM3_DIR` set. Tested on NVIDIA (RTX 5070, Vulkan) and Apple silicon (M4 Pro, Metal + through wgpu: first forward 3.1 s, CPU 17.2 s; max rel 4.9e-5, masks IoU ≥ 0.99992). AMD, Intel and DX12 are untested. + +### SAM 3 necks +After the backbone, the click decoder needs the tracker neck (`tracker_neck`) and Describe the detector's +(`detector_model.vision_encoder.neck`): the same `Sam3VisionNeck` (`crates/segment/src/neck.rs`) with other weights, +three levels each (288², 144² and 72², 256 channels; the 36² level is used by neither head). In candle on the CPU +they took ~2.3 and ~2.6 s per photo, more than the GPU backbone. `BackboneAccel::neck` runs them with the backbone's +device (`crates/gpu/src/sam3/neck.rs`); `Sam3` turns the levels into candle tensors on its device, checks their +sizes and values, and on any `Err` warns once and runs that neck in candle from then on (the other neck and the +backbone stay on the GPU). +- Images are pixel rows (`[pixels, channels]`), so every step is the backbone's matrix kernel. A 2 × 2 stride-2 + transposed convolution is one product per input pixel, `[pixels, cin] · [cin, 4 · cout]` (PyTorch's + `[cin, cout, 2, 2]` weight laid out as `[(ky, kx, cout), cin]` on upload, the bias repeated 4 ×), GELU (erf) + between level 0's two in the epilogue. Its output rows hold each pixel's four outputs one after the other; `proj1` + (1 × 1) doesn't care about pixel order, so one reorder (`unshuffle` in `wgsl/sam3_neck.wgsl`) after it puts the + pixels of one or two up-samplings in row-major order. +- `proj2` (3 × 3, padding 1) is an implicit GEMM: the matrix kernel with another A-tile loader + (`wgsl/sam3_conv.wgsl`, spliced in place of the dense one between `// #if dense` marks of `sam3_matmul.wgsl`) that + reads the 9 · 256 numbers of a pixel's neighbourhood straight from the image (K ordered tap-major, so each vec4 is + four channels of one pixel; zero outside). The im2col matrix (764 MB at 288²) never exists. The weights go to + `[cout, ky, kx, cin]` on upload. The last step is `to_chw` with one window over the whole image. +- Built on first use, not with the backbone: the three kernels compile (≈0.2 s with a cold driver cache, a few ms + warm), the work buffers are made (pixel rows of the backbone, 21 MB, and two 85 MB buffers the steps alternate + between, shared by both necks), and the neck's weights (~27 MB) are read, laid out and uploaded (~0.1 s). Each + level is recorded once and is one submission with its own read-back (85 / 21 / 5 MB), so no buffer exceeds the + backbone's 98 MB limits and no limit is raised. Device memory: ~245 MB with both necks built. +- Measured (RTX 5070, Vulkan, `examples/sam3_backbone_bench.rs`; `--app` times the app's per-photo steps, + `--cpu-necks` the same with candle's necks): a neck 38 ms warm (level 0: 13 ms of products at ~12 TFLOP/s, the + rest mostly the 85 MB read-back), first use 0.08–0.12 s (0.4 s with a cold driver shader cache); candle 2.3–3.5 s. + Per photo in the app's order: click features (the tracker neck plus the tracker's two 1 × 1 convolutions, still + candle) 0.11–0.19 s instead of 2.0–2.3 s, so encode + click features 0.56–0.69 s instead of 2.4–2.9 s; the first + Describe 5.1–5.8 s instead of 7.0–7.4 s (the rest of it is the DETR encoder and decoder in candle). +- Accuracy (`tests/it/sam3_necks.rs`, both models fed the same GPU backbone output): every level of both necks within + max rel 2.1e-6, mean abs ≤ 7.7e-7 of candle; click and Describe masks IoU 1.0. +- Tests: kernel unit tests against plain f64 loops (`src/sam3/neck/tests.rs`: transposed convolutions + reorder + with odd sides, the 3 × 3 convolution at every border, single-pixel and odd sizes, cut-off tiles, the weight + layouts, a whole small neck against a transcription of `Neck::forward`); `crates/segment` tests the fallback + (wrong sizes, NaN) with a fake accelerator. + +### SAM 3 DETR encoder +Each text prompt (Describe; Subject's "person") runs the text detector (`crates/segment/src/detector.rs`), whose +DETR encoder fuses the prompt into the 72 × 72 image tokens: ~4–5 s of the ~5–7 s a prompt took on the CPU. The +same accelerator runs it (`BackboneAccel::detr_encoder`, `src/sam3/detr.rs`); `Detector::predict` uses its result +as the encoder memory and runs the rest in candle. Any failure (no such accelerator, out of memory, a wrong-sized +or non-finite result) is logged once and noted (`Sam3::detr_fallback`), and from then on candle runs the encoder +for that model. +- Same math as `detector.rs`, six layers over 5184 tokens of 256: LN (eps 1e-5, PyTorch's default) → self-attention + (8 heads of 32; q and k from the normed tokens plus their sine position encoding, v from the normed tokens; q | k + one product with the weights concatenated) → output projection + residual → LN → cross-attention to the prompt's + 32 tokens (k | v one product) with the key-padding bias → output projection + residual → LN → MLP 256 → 2048 → + 256 with ReLU + residual. +- Kernels: the backbone's matrix product (ReLU as a third epilogue activation) and layer norm (with eps 1e-5), and + `wgsl/sam3_detr.wgsl`: attention for heads of 32 (flash style, written out like the backbone's) whose q, k and v + come from separate buffers with their own strides and offsets, with an optional per-key bias stored after the + prompt's k | v (0 or f32::MIN, as candle's `padding_bias`; the running maximum starts at f32::MIN, so a padded key + weighs exactly nothing and an all-padding prompt averages, as candle's softmax does); and a sum (tokens + position). +- Loaded on the first prompt, not with the backbone: kernels, 38 MB of f32 weights, 80 MB of work buffers (model + load time and memory before the first Describe are unchanged). 84 dispatches, recorded once; a prompt writes the + tokens, their position encoding, the prompt's tokens and its padding bias, submits one command buffer per layer + and reads the memory back. +- Measured (RTX 5070, Vulkan; CPU busy with parallel builds, load ~7–10): the encoder 23–25 ms with uploads and + read-back (self-attention 2.2 ms a layer at 12 TFLOP/s, products 10–12 TFLOP/s), candle 4.6–5.7 s (3.9–4.4 s on + an idle CPU). A Describe on a photo already analyzed (second prompt) 6.6 s → 2.0 s. What remains, per prompt: + CLIP text encoder 0.27–0.46 s, DETR decoder 0.75–1.3 s (of it the box relative-position bias ~75 ms a layer), + mask head ~0.9–1.4 s (pixel decoder 3 × 3 convs at 144² and 288² ~0.75–1.2 s, 1 × 1 instance projection 0.12 s, + mask products 25 ms; now on the GPU, below). +- Accuracy (`tests/it/sam3_detr.rs`, the photo of `tools/sam3_reference.py`, prompts "person", "sky", "the red car"; + both models share one GPU backbone, so only the encoder differs): memory max rel 1.7e-6–4.2e-6, mean abs + 2.3e-6–7.7e-6; query logits max abs ≤ 2.5e-4; presence logits ≤ 2.3e-5 apart; boxes ≤ 1.2e-4; the same instances + and Describe mask IoU 1.0. Kernel unit tests (`src/sam3/detr/tests.rs`): self-attention with 8 × 32 heads and a + part-empty last workgroup, cross-attention to 32 keys with 0, 1, 5 and 32 real tokens, ReLU, the sum, the eps. + +### SAM 3 mask head +A prompt's masks come from the detector's mask decoder (`mask_decoder` in the checkpoint): the encoder memory attends +to the prompt (`prompt_cross_attn`, after its layer norm) and is added to it; the pixel decoder brings it from 72² to +288² in two stages, each nearest 2 × up-sampling + the detector neck's level of that size → 3 × 3 convolution → +GroupNorm (8 groups, eps 1e-5) → ReLU; the 1 × 1 instance projection follows, and each query's mask embedding (the +`mask_embedder` MLP on the decoder's queries) times that is its mask logits. ~0.7–1.4 s per prompt in candle on the +CPU, most of it the 288² convolution. `BackboneAccel::mask_decoder` runs it on the accelerator (`src/sam3/pixel.rs`); +any failure (out of memory, a wrong-sized or non-finite result) is logged once and noted (`Sam3::mask_fallback`), and +candle runs the decoder for that model from then on. +- Interface: the encoder memory, the prompt's tokens and which are real, both neck levels (channels-first, as + `Features` holds them) and `rows` `[r, 256]` with a bias `[r]` (r ≤ 256), each row a 1 × 1 projection of the pixel + decoder's output; it returns `[r, 288, 288]`. The detector folds the instance projection into its 200 mask + embeddings on the CPU (e · (W x + b) = (e W) x + e b: 13 MFLOP instead of the projection's 11 GFLOP), so one + product `[82944, 256] · [200, 256]ᵀ` on the GPU gives the masks and the CPU fallback stays the candle code as it was. + SAM 3's semantic segmentation head (the semantic mask Describe and Subject share out to their instances, #1963) is + another 1 × 1 read-out of the same output, so it is one more row: 201 rows, the last one the semantic mask. +- Kernels: the prompt attention is the DETR encoder's (torch-eps layer norm, products, attention with the padding + bias); the convolutions are the necks' implicit GEMM; `wgsl/sam3_pixel.wgsl` adds the up-sampling, which adds the + neck level as uploaded (channels-first, so no separate reorder), and GroupNorm + ReLU: two-pass statistics per + chunk of 256 pixels (thread = channel, so the loads are contiguous), merged per group with the parallel variance + formula, then normalized in place. The projection's `[pixels, r]` goes channels-first with `to_chw`. +- Loaded on the first prompt, like the encoder: kernels, 6 MB of weights, 282 MB of work buffers (and an 85 MB + read-back buffer in host memory). 17 dispatches, recorded once per row count; a prompt uploads the memory (5 MB), + the prompt, both neck levels (106 MB) and the rows, submits once and reads `r · 288²` numbers back (66 MB). + Keeping the levels on the device after `BackboneAccel::neck` would save the 106 MB upload (a few ms) but needs an + image identity in the interface and another 106 MB of device memory per photo; not done. +- Measured (RTX 5070, Vulkan, `examples/sam3_backbone_bench.rs`, quiet machine): the decoder 33 ms warm with the + uploads and the read-back (by FLOP count about a third of it kernels, the 288² convolution ~8 ms at ~12 TFLOP/s; + the rest transfers), first use 0.09–0.17 s. Per prompt in the app (`--app`, against `--cpu-masks`): a Describe on a + photo already analyzed 1.9–2.2 s → 1.04–1.06 s, the first on a photo 2.0–2.1 s → 1.11–1.12 s (2.5 s → 1.65 s with + the first load); under load (~15, parallel builds) 1.9 s → 1.1–1.2 s. With the CPU-side text cache and one-pass box + bias as well: a new prompt on an analyzed photo ~0.7 s, a prompt used before 0.45–0.46 s. What remains is in candle + on the CPU: the DETR decoder (~0.4 s) and, for a new prompt, the CLIP text encoder (~0.25 s). +- Accuracy (`tests/it/sam3_mask_decoder.rs`; both models share one GPU accelerator, so only the mask decoder differs): + against the decoder transcribed with candle's tensor ops in f64, the GPU's instance features are within max rel + 4.2e-6, mean abs 1.7e-7; candle's own f32 decoder is 1.1e-3–1.5e-3 / 2e-4 from it, all of that from its GroupNorm's + f32 sums over 2.6 M numbers per group (with those in f64 the f32 transcription is within 1.1e-6). So GPU vs candle, + all 200 queries' mask logits: max rel 1.0e-3–1.7e-3; the same instances, Describe mask IoU 1.0 ("person", "sky", + "the red car" on the photo of `tools/sam3_reference.py`). Kernel unit tests (`src/sam3/pixel/tests.rs`): the + up-sampling + level (odd sizes), GroupNorm + ReLU (cut-off chunks, a mean of 50, 1–8 groups), a two-stage small + decoder (up-sampling → convolution at every border → GroupNorm) against f64 loops, and the size checks. +- Not done: masks only for the queries above the threshold (`merge` keeps sigmoid(logit) · sigmoid(presence) > 0.5). + `Sam3::detect` returns all 200 and the reference test (`crates/segment/tests/reference.rs`) checks the + best-scoring query's mask, which need not pass the threshold; with `rows` it is a matter of passing fewer of them. + ## Open items - Keep the loupe texture on the GPU (render into an `egui-wgpu` texture on eframe's device instead of reading back); share the device with eframe. diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index a6c63b816a..5aca6898e7 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (pen pressure for brush masks; monitor profile from colord on Linux); previously major (created from the code, gpu-pipeline.md and the parity checklist) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-17 · **Change:** minor (SAM 3's mask decoder on the GPU through wgpu on Windows and Linux); previously major (created from the code, gpu-pipeline.md and the parity checklist) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 What Lightroom does with the machine's hardware, per platform, and what LightCraft does. Sources: [gpu-pipeline.md](gpu-pipeline.md), [display-profiles.md](display-profiles.md), [denoise.md](denoise.md), @@ -10,7 +10,7 @@ What Lightroom does with the machine's hardware, per platform, and what LightCra |---|---|---|---|---|---|---| | GPU for display and editing | Metal / DX12, "Use GPU for display / image processing / export" | wgpu Metal: geometry, resize, blur, WB, NR, guided filter, dehaze, masks, finish; CPU fallback per render | DX12 only (Vulkan opt-in, #136) | Vulkan (CPU ↔ GPU equivalence verified on an AMD Radeon 8060S, RADV) | CPU only (no WebGPU yet) | 🟡 defringe, spot removal, heuristic masks, long brushes and high-bit exports stay on CPU | | GPU export | ✅ | ✅ (6000 × 4000 in ~0.3 s vs ~1.2 s CPU) | ✅ | ✅ | — | ✅ (black-export fix on an Intel iGPU, #78) | -| AI on GPU / neural engine | Metal / DirectML / Core ML, model per feature | AI denoise on GPU or CPU (setting); SAM 3 on Metal via candle; faces on CPU | CPU / GPU denoise | CPU / GPU denoise | — | 🟡 no Core ML / Neural Engine / DirectML | +| AI on GPU / neural engine | Metal / DirectML / Core ML, model per feature | AI denoise on GPU or CPU (setting); SAM 3 on Metal via candle; faces on GPU when faster (CPU-only setting) | CPU / GPU denoise; SAM 3 image encoder, necks, DETR encoder and mask decoder on the GPU (wgpu, DX12), the rest of the heads on CPU (untested on DX12 so far); faces GPU / CPU | CPU / GPU denoise; SAM 3 image encoder, necks, DETR encoder and mask decoder on the GPU (wgpu, Vulkan), the rest of the heads on CPU (a photo's analysis ~0.6 s on an RTX 5070 vs ~33 s on a Ryzen 9 3900X, a description ~0.5–0.7 s vs ~4.5 s); faces GPU / CPU | — | 🟡 no Core ML / Neural Engine / DirectML; SAM 3's click decoder, text encoder and DETR decoder on CPU outside macOS | | HDR (EDR) display | ✅ (macOS EDR, Windows HDR) | ⬜ | ⬜ | ⬜ | ⬜ | ⬜ (LR-VIEW-HDR-DISPLAY) | | Monitor profile | automatic per display, follows the window | ✅ the screen's profile, followed across screens | 🟡 picked by hand (WCS needs FFI) | 🟡 colord's profile (one display, or all sharing one); no follow across monitors | — | 🟡 Windows OS profile not read; Linux per-monitor follow missing | | Second window / second monitor | ✅ (Classic) | ✅ (⌘F11) | ✅ | ✅ | — | ✅ (Classic secondary-window keys missing) | @@ -49,6 +49,9 @@ NVIDIA, Intel and Windows DX12 still rely on user reports. | Date | Change | Summary | |---|---|---| +| 2026-10-17 | minor | AI on GPU: SAM 3's text detector mask decoder also runs on the GPU through wgpu on Windows and Linux (a description ~0.5–0.7 s with the text cache and box bias of the same change) | +| 2026-10-17 | minor | AI on GPU: SAM 3's necks and DETR encoder also run on the GPU through wgpu on Windows and Linux | +| 2026-10-17 | minor | AI on GPU: SAM 3's image encoder runs on the GPU through wgpu on Windows and Linux (CPU fallback; follows the GPU switches); faces run on the GPU when faster | | 2026-10-12 | minor | Monitor profile: Linux reads the display profile from colord; macOS row reflects #787 | | 2026-10-12 | minor | CPU ↔ GPU equivalence suite run on an AMD Radeon 8060S (Vulkan, RADV, Linux): 16 tests / 135 cases pass, max 2 LSB, mean ≤ 0.0003; first GPU verified outside Apple | | 2026-10-12 | minor | Pen pressure: strokes record per-point pressure from egui touch force, scaling dab size and flow; per-platform status | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 21140ae26e..163ebc5e8b 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-21 · **Change:** minor (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-22 · **Change:** minor (LR-MASK-OBJECTS: SAM 3's image encoder, necks, DETR encoder and mask decoder on the GPU through wgpu outside macOS) · **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 @@ -293,7 +293,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-MASK-SUBJECT | Select subject | P2 | 🟡 | `cmd:mask.add` (`subject`), `crates/pipeline/src/masks.rs` | saliency heuristic, no segmentation model; a photo that carries person mattes (DNG semantic masks: iPhone ProRAW portrait / skin / hair / teeth / glasses mattes) uses them instead (synthetic files only: no corpus file carries person mattes) | | LR-MASK-SKY | Select sky | P2 | 🟡 | `cmd:mask.add` (`sky`), `crates/pipeline/src/masks.rs` (`Mattes`), `crates/raw/src/semantic.rs` | heuristic; a photo that carries a sky matte (DNG semantic mask, e.g. iPhone ProRAW) uses it instead, through orientation / crop / lens corrections, preview = export (checked on one CC0 iPhone 12 Pro ProRAW and synthetic files) | | LR-MASK-BACKGROUND | Select background | P2 | 🟡 | `cmd:mask.add` (`background`) | inverse of the subject mask (heuristic, or the photo's person mattes) | -| 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/mod.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 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). 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-OBJECTS | Object selection | P2 | 🟡 | `cmd:mask.add` (`object`, `prompt`), `cmd:mask.objectPoint`, `cmd:mask.refineDetail`, `cmd:segment.prepare`, `cmd:segment.model.status`, `cmd:segment.settings`, `cmd:segment.model.download`, `cmd:segment.model.cancel`, `cmd:app.openSamModelFolder`, `crates/segment`, `crates/engine/src/segment/mod.rs` | SAM 3 in pure Rust (candle; Metal on macOS; on Windows and Linux the image encoder, the two necks and the text detector's DETR encoder and mask decoder on the GPU through wgpu (`lightcraft-gpu` `sam3`) and the rest of the heads on the CPU; a description ~0.5–0.7 s with an RTX 5070, falling back to the CPU without a usable GPU or when the GPU is switched off; Settings ▸ Performance ▸ AI masks ▸ Run on: CPU puts all of it on the CPU on every platform (`segment.settings`); Settings ▸ Performance ▸ AI masks and `segment.model.status` → `backend` show where it runs and the last photo's time): 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 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). 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, ~0.6 s with an RTX 5070 under Linux, ~32 s on a 12-core 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); coverage builds up by passes, not hold time (holding the brush still adds nothing, live or committed, #518); 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 | @@ -818,6 +818,10 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-15 | minor | LR-IMP-FORMATS: a Hasselblad FFF develops with the camera's colour matrix from the original 3FR header it embeds (tag `0xC51B`) instead of the neutral matrix; status unchanged (🟡) | | 2026-10-12 | minor | LR-IMP-FORMATS: folder discovery includes SR2/SRF; MCP and CLI reuse the engine extension list. DSC-F828 remains preview-only; decoder support and row status unchanged | | 2026-10-15 | patch | KEYC-RATING: `\` shows / hides the Filter Bar in Photo Grid and Square Grid (Show Original in Detail); status unchanged (🟡) | +| 2026-10-17 | minor | LR-MASK-OBJECTS: SAM 3's text detector mask decoder runs on the GPU through wgpu too (with the cached prompt features and the one-pass box bias: a description ~2 s → ~0.5–0.7 s with an RTX 5070); status unchanged (🟡) | +| 2026-10-17 | minor | LR-MASK-OBJECTS: SAM 3's two necks and the text detector's DETR encoder also run on the GPU (wgpu) outside macOS: a photo's analysis ~0.6 s, a description ~2 s on an RTX 5070; status unchanged (🟡) | +| 2026-10-17 | minor | LR-MASK-OBJECTS: Run on: Automatic / CPU for AI masks (`segment.settings`), CPU on every platform incl. macOS; status unchanged (🟡) | +| 2026-10-17 | minor | LR-MASK-OBJECTS: SAM 3's image encoder runs on the GPU through wgpu on Windows and Linux (CPU fallback, the GPU switches), where it runs shows in Settings and `segment.model.status`; status unchanged (🟡) | | 2026-10-12 | minor | LR-EDIT-OPTICS-PROFILE: Sony ARW shading, CA and distortion tables decoded with settings and provenance (raw IFD, `SR2SubIFD` fallback); applied corrections unchanged (ILCE-7RM4A and ILCE-7RM6 distortion); status unchanged (🟡) | | 2026-10-14 | minor | LR-IMP-CAMERA-COVERAGE: Camera-coverage sweep (#1327): 30 models verified on 40 CC0 files (coverage.py 515 → 545 verified); sensor verification does not establish colour parity (#1277); status unchanged (🟡) | | 2026-10-13 | minor | LR-MERGE-PANO: a panorama's DNG takes its `AsShotNeutral` from the median of its frames' vendor white-balance multipliers (CR2, NEF, ARW…) instead of the first frame's tags, and frames now carry the multipliers (issue #1144); status unchanged (✅) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0a7091a05a..7febd8cd7d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity: LightCraft vs Adobe Lightroom -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** minor (Minolta MRW decoded, 6 bodies verified; RAW: 83% of Adobe's models decode, 38% verified after the camera-coverage sweep #1327; Platforms: the Windows x64 installer verified on Windows 11) · **Target:** Adobe Lightroom Classic 15.5 (August 2026) and Lightroom 9.6 (desktop) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (Object / Describe masks: SAM 3 on the GPU through wgpu outside macOS) · **Target:** Adobe Lightroom Classic 15.5 (August 2026) and Lightroom 9.6 (desktop) The authoritative assessment of how close LightCraft is to Lightroom. The row-by-row checklist is [parity-checklist.md](parity-checklist.md); the ranked work list is [gaps.md](gaps.md); deep areas @@ -94,7 +94,7 @@ search embeddings; generative remove runs in Adobe's cloud. | 2026-10-12 | minor | Epson ERF decoded (raw-parity.md): 240 models verified, 229 preview-only; shares and rounded numbers unchanged | | Subject / Sky / Background masks | classical heuristics; the file's own DNG semantic mattes | 🟡 | | People (faces, body, hair, skin…) and Landscape masks | — | ⬜ | -| Object / Describe masks | SAM 3 in pure Rust (Metal / CPU); opt-in 3.4 GB download, no mirror configured | 🟡 | +| Object / Describe masks | SAM 3 in pure Rust (Metal on macOS; elsewhere the image encoder, necks and text detector's DETR encoder and mask decoder on the GPU through wgpu, the rest of the heads on the CPU, CPU fallback); opt-in 3.4 GB download, no mirror configured | 🟡 | | Depth range mask, Lens Blur | — | ⬜ | | AI Denoise | Bayer only, pure-Rust CPU / GPU, user-installed weights | 🟡 | | Raw Details, Super Resolution | — | ⬜ | @@ -302,6 +302,8 @@ P2 items 12–25 h; look tuning, performance, packaging, hardening 25–45 h. |---|---|---| | 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-17 | minor | Object / Describe masks: SAM 3's necks and text detector's encoder also on the GPU outside macOS; status unchanged | +| 2026-10-17 | minor | Object / Describe masks: SAM 3's image encoder runs on the GPU through wgpu on Windows and Linux (CPU fallback); status and numbers unchanged | | 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 418d63105767705109af80690abd0e06ec85e35b Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 20 Oct 2026 15:49:40 -0400 Subject: [PATCH 17/98] PERF-SEARCH: search and Text rules read each photo's text from a kept lower-cased copy The library search lower-cased the word and each photo's file name, title, caption, camera, lens, location, format and every keyword, for every photo and every word, on every keystroke; a smart album's Text rule joined and lower-cased a photo's text the same way. At 312 000 photos that was most of the time of a keystroke. The catalog now keeps each photo's lower-cased searchable text, made the first time it is asked for (like the other indexes) and kept current by the ops that change a searched field (AddPhoto, RemovePhoto, SetMeta, SetFile, Relink), their inverses and the rollback of a failed batch. A smart album's Text rule has its own kept text, made on first use, so the sidebar counts and the grid use it too. The search words are lower-cased once per query. A photo that isn't the catalog's own (a copy tried with other values) is still read from its own fields. Which photos match is unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/index.rs | 166 ++++++++- crates/catalog/src/lib.rs | 21 +- crates/catalog/src/query.rs | 58 +++- crates/catalog/src/rules.rs | 55 +-- crates/catalog/src/tests_search_text.rs | 429 ++++++++++++++++++++++++ docs/whats-new.md | 11 + 6 files changed, 699 insertions(+), 41 deletions(-) create mode 100644 crates/catalog/src/tests_search_text.rs diff --git a/crates/catalog/src/index.rs b/crates/catalog/src/index.rs index 2c347473bc..14d441a167 100644 --- a/crates/catalog/src/index.rs +++ b/crates/catalog/src/index.rs @@ -11,7 +11,7 @@ use std::collections::{HashMap, HashSet}; use std::sync::OnceLock; -use crate::{AlbumId, Catalog, PhotoId, StackId}; +use crate::{AlbumId, Catalog, Photo, PhotoId, StackId}; #[derive(Default)] pub(crate) struct Indexes { @@ -20,6 +20,10 @@ pub(crate) struct Indexes { stacks: OnceLock>>, /// Album → its photos (regular albums; a smart album's list is empty). albums: OnceLock>>, + /// Photo → its lower-cased searchable text ([`PhotoText`]), for the free-text search. + search: OnceLock>, + /// Photo → the lower-cased text a smart album's Text rule looks through ([`crate::rules::rule_text`]). + rule_text: OnceLock>, } /// A copy builds its own when asked (copies are made to be saved, not queried). @@ -70,6 +74,145 @@ impl Indexes { } } } + + /// Photo `id` is `p` now (`None`: it is gone): the text kept for it is made again. + pub(crate) fn text_changed(&mut self, id: PhotoId, p: Option<&Photo>) { + if let Some(m) = self.search.get_mut() { + match p { + Some(p) => m.insert(id, PhotoText::of(p)), + None => m.remove(&id), + }; + } + if let Some(m) = self.rule_text.get_mut() { + match p { + Some(p) => m.insert(id, RuleText::of(p)), + None => m.remove(&id), + }; + } + } + + /// Photo `id` is about to be changed in place, at `p`: an edit of a photo that others hold + /// (`Arc::make_mut`) puts it at another address, which its text follows. + pub(crate) fn text_moved(&mut self, id: PhotoId, p: &Photo) { + let at = addr(p); + if let Some(t) = self.search.get_mut().and_then(|m| m.get_mut(&id)) { + t.at = at; + } + if let Some(t) = self.rule_text.get_mut().and_then(|m| m.get_mut(&id)) { + t.at = at; + } + } +} + +/// A map from photos, for a pass over the library that asks about each one in id order. +type ByPhoto = HashMap>; + +/// Hashes a photo id as itself in the table's low bits, which is where the table looks first, so +/// ids that follow each other sit next to each other and a pass in id order walks it in order +/// rather than jumping about (a pass over 300 000 photos spent most of its time on that). The top +/// bits, which tag an entry in the table, are mixed so entries still tell each other apart. +#[derive(Default)] +pub(crate) struct IdHasher(u64); + +impl std::hash::Hasher for IdHasher { + fn finish(&self) -> u64 { + self.0 ^ (self.0.wrapping_mul(0x9E37_79B9_7F4A_7C15) & 0xFE00_0000_0000_0000) + } + + fn write(&mut self, bytes: &[u8]) { + for b in bytes { + self.0 = self.0.rotate_left(8) ^ u64::from(*b); + } + } + + fn write_u64(&mut self, n: u64) { + self.0 = n; + } +} + +/// Where `p` is in memory. The contract of the kept texts: a text is used only for the photo at the +/// address it was made for. The catalog's own photos (`Arc` contents) stay where they are +/// until `Arc::make_mut` copies one that others hold, which `photo_mut` reports ([`Indexes::text_moved`]); +/// every op that changes a searched field makes the text again ([`Indexes::text_changed`]). A copy +/// of a photo (a candidate tried with other values) is at another address, so it is read from its +/// own fields, never from a text kept for the photo with its id. Only ids and addresses are +/// compared; the address is never turned back into a reference. A catalog read from a snapshot +/// (and then repaired) or cloned starts with no texts at all: they are made when asked. +fn addr(p: &Photo) -> usize { + std::ptr::from_ref(p).addr() +} + +/// What the free-text search looks through for one photo, lower-cased as `str::to_lowercase` does +/// for each field alone: file name, title, caption, camera, lens, location, format, then each +/// keyword, then the name of each person (a named face), separated by NUL. A search word may hold +/// white space (a quoted phrase) but never NUL, so it never runs over a field. +pub(crate) struct PhotoText { + /// The address of the photo this was made from ([`addr`]). + at: usize, + text: Box, +} + +impl PhotoText { + pub(crate) fn of(p: &Photo) -> PhotoText { + let fields = [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format]; + let people = p.people(); + // (exact for ASCII, which most text is: the box takes the buffer without copying it) + let len = fields + .iter() + .map(|f| f.len() + 1) + .chain(p.meta.keywords.iter().map(|k| k.len() + 1)) + .chain(people.iter().map(|n| n.len() + 1)) + .sum::() + .saturating_sub(1); + let mut text = String::with_capacity(len); + for (i, field) in fields.into_iter().enumerate() { + if i > 0 { + text.push('\0'); + } + push_lowercase(&mut text, field); + } + for k in p.meta.keywords.iter().map(String::as_str).chain(people) { + text.push('\0'); + push_lowercase(&mut text, k); + } + PhotoText { at: addr(p), text: text.into_boxed_str() } + } + + /// Whether the lower-cased word `t` is in the file name, title, caption, camera, lens, + /// location, format, a keyword or the name of a person. + pub(crate) fn contains(&self, t: &str) -> bool { + self.text.contains(t) + } + + #[cfg(test)] + pub(crate) fn text(&self) -> &str { + &self.text + } +} + +/// Push `s` lower-cased as `str::to_lowercase` gives it, without a temporary string for ASCII. +fn push_lowercase(out: &mut String, s: &str) { + if s.is_ascii() { + let from = out.len(); + out.push_str(s); + if let Some(added) = out.get_mut(from..) { + added.make_ascii_lowercase(); + } + } else { + out.push_str(&s.to_lowercase()); + } +} + +/// A photo's text for a smart album's Text rule: [`crate::rules::rule_text`]. +struct RuleText { + at: usize, + text: Box, +} + +impl RuleText { + fn of(p: &Photo) -> RuleText { + RuleText { at: addr(p), text: crate::rules::rule_text(p).into_boxed_str() } + } } impl Catalog { @@ -98,4 +241,25 @@ impl Catalog { let m = self.index.albums.get_or_init(|| self.albums.values().map(|a| (a.id, a.photos.iter().copied().collect())).collect()); m.get(&album).is_some_and(|s| s.contains(&photo)) } + + /// `p`'s lower-cased text for the free-text search, when `p` is this catalog's own photo and the + /// text was made. `build`: make it for every photo first when it wasn't (a pass over the whole + /// library does; testing one photo shouldn't build it for 300 000). + pub(crate) fn search_text(&self, p: &Photo, build: bool) -> Option<&PhotoText> { + let m = if build { + self.index.search.get_or_init(|| self.photos.values().map(|p| (p.id, PhotoText::of(p))).collect()) + } else { + self.index.search.get()? + }; + m.get(&p.id).filter(|t| t.at == addr(p)) + } + + /// [`Catalog::search_text`] for a smart album's Text rule: the lower-cased, trimmed text of + /// [`crate::rules::rule_text`], made for every photo on first use (a smart album's count or + /// view asks for it photo by photo). + pub(crate) fn rule_text_of(&self, p: &Photo) -> Option<&str> { + let m = self.index.rule_text.get_or_init(|| self.photos.values().map(|p| (p.id, RuleText::of(p))).collect()); + let t = m.get(&p.id)?; + (t.at == addr(p)).then_some(&*t.text) + } } diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 7e094200ca..4a07efdd77 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -568,7 +568,10 @@ impl Catalog { fn photo_mut(&mut self, id: PhotoId) -> Result<&mut Photo> { self.touch(id); - self.photos.get_mut(&id).map(Arc::make_mut).ok_or(CatalogError::NoPhoto(id)) + let p = self.photos.get_mut(&id).map(Arc::make_mut).ok_or(CatalogError::NoPhoto(id))?; + // (`Arc::make_mut` copies a photo others hold: the text kept for it goes with the copy) + self.index.text_moved(id, p); + Ok(p) } /// The op being applied changes photo `id` (or adds or removes it). @@ -706,10 +709,12 @@ impl Catalog { let id = photo.id; self.next_photo = self.next_photo.max(id.0.saturating_add(1)); self.photos.insert(id, Arc::new(*photo)); + self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); Op::RemovePhoto { id } } Op::RemovePhoto { id } => { let p = self.photos.remove(&id).ok_or(CatalogError::NoPhoto(id))?; + self.index.text_changed(id, None); // album membership is restored by the batch the engine builds (see `delete_permanently`) Op::AddPhoto { photo: Box::new((*p).clone()) } } @@ -737,7 +742,9 @@ impl Catalog { } Op::SetMeta { id, meta } => { let p = self.photo_mut(id)?; - Op::SetMeta { id, meta: Box::new(std::mem::replace(&mut p.meta, *meta)) } + let old = std::mem::replace(&mut p.meta, *meta); + self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); + Op::SetMeta { id, meta: Box::new(old) } } Op::SetDeleted { id, deleted } => { let p = self.photo_mut(id)?; @@ -912,7 +919,9 @@ impl Catalog { let p = self.photo_mut(id)?; let old_name = std::mem::replace(&mut p.file_name, file_name); let old_format = format.map(|f| std::mem::replace(&mut p.format, f)); - Op::Relink { id, file_name: old_name, source: std::mem::replace(&mut p.source, source), format: old_format } + let old = Op::Relink { id, file_name: old_name, source: std::mem::replace(&mut p.source, source), format: old_format }; + self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); + old } Op::SetContent { id, width, height, file_size, content_hash, preview_only, preview_checked } => { let p = self.photo_mut(id)?; @@ -943,7 +952,9 @@ impl Catalog { } let p = self.photo_mut(id)?; let old_name = std::mem::replace(&mut p.file_name, file_name); - Op::SetFile { id, file_name: old_name, source: std::mem::replace(&mut p.source, source) } + let old = Op::SetFile { id, file_name: old_name, source: std::mem::replace(&mut p.source, source) }; + self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); + old } Op::SetLabelName { label, name } => { let name = name.map(|n| n.trim().to_string()).filter(|n| !n.is_empty()); @@ -1225,6 +1236,8 @@ mod tests_repair; #[cfg(test)] mod tests_scale; #[cfg(test)] +mod tests_search_text; +#[cfg(test)] mod tests_tally; #[cfg(test)] mod tests_torn_append; diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index ff94268a8b..e102c5c0ba 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -143,6 +143,10 @@ fn shuffle_rank(seed: u64, id: PhotoId) -> u64 { pub(crate) struct Prepared { root: Option, only: Option>, + /// The search words ([`Filter::tokens`]). + tokens: Vec, + /// A pass over the library, which makes the text kept for each photo when it isn't ([`Catalog::search_text`]). + whole: bool, } /// The tokens of a search text: split at whitespace, except inside double quotes, so @@ -174,8 +178,8 @@ fn unquote(s: &str) -> &str { s.strip_prefix('"').map_or(s, |inner| inner.strip_suffix('"').unwrap_or(inner)) } -fn token_matches(p: &Photo, tok: &str) -> bool { - let t = tok.to_lowercase(); +/// Whether the word `t` (lower-cased) is in `p`, as a field of it or as plain text. +fn token_matches(p: &Photo, t: &str, hay: &Hay) -> bool { // a token that starts with a quote is a phrase, even with a colon in it if let Some((field, quoted)) = t.split_once(':').filter(|_| !t.starts_with('"')) { let val = unquote(quoted); @@ -217,20 +221,30 @@ fn token_matches(p: &Photo, tok: &str) -> bool { "name" | "file" => p.file_name.to_lowercase().contains(val), // Not a known field: the colon is part of a plain word ("10:30", "Re:"), its value unquoted // (`re:"a b"` is the text `re:a b`). - _ if val.len() != quoted.len() => text_matches(p, &format!("{field}:{val}")), - _ => text_matches(p, &t), + _ if val.len() != quoted.len() => hay.text().contains(&format!("{field}:{val}")), + _ => hay.text().contains(t), }; } - text_matches(p, unquote(&t)) + hay.text().contains(unquote(t)) } -/// Whether the lower-cased word `t` is in the file name, title, caption, camera, lens, location, -/// format, a keyword or the name of a person (a named face) of `p`. -fn text_matches(p: &Photo, t: &str) -> bool { - let hay = [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format]; - hay.iter().any(|h| h.to_lowercase().contains(t)) - || p.meta.keywords.iter().any(|k| k.to_lowercase().contains(t)) - || p.people().iter().any(|n| n.to_lowercase().contains(t)) +/// A photo's lower-cased text for the free-text search: the one the catalog keeps when `p` is its +/// own photo and a pass over the library made them ([`Prepared::whole`]), else made when first asked. +struct Hay<'a> { + p: &'a Photo, + cat: &'a Catalog, + whole: bool, + kept: std::cell::OnceCell>, + own: std::cell::OnceCell, +} + +impl Hay<'_> { + fn text(&self) -> &crate::index::PhotoText { + match self.kept.get_or_init(|| self.cat.search_text(self.p, self.whole)) { + Some(t) => t, + None => self.own.get_or_init(|| crate::index::PhotoText::of(self.p)), + } + } } /// Whether `p` has a named face region called `name` (case-insensitive). @@ -332,13 +346,23 @@ impl Filter { /// [`Filter::prepare`] for testing one photo (the `only` ids are looked through, not hashed). pub(crate) fn prepare_one(&self) -> Prepared { - Prepared { root: self.library_root(), only: None } + Prepared { root: self.library_root(), only: None, tokens: self.tokens(), whole: false } } /// What [`Filter::matches_in`] needs worked out once for a pass over many photos rather than /// once per photo: the library folder's identity and the `only` ids as a set. pub(crate) fn prepare(&self) -> Prepared { - Prepared { root: self.library_root(), only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()) } + Prepared { + root: self.library_root(), + only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()), + tokens: self.tokens(), + whole: true, + } + } + + /// The search words ([`search_tokens`]), lower-cased (as `str::to_lowercase` does, once per query, not once per photo). + fn tokens(&self) -> Vec { + search_tokens(&self.text).map(str::to_lowercase).collect() } /// [`Filter::library_folder`] as a folder identity ([`folder_key`]); `None` without a choice. @@ -462,7 +486,11 @@ impl Filter { { return false; } - search_tokens(&self.text).all(|tok| token_matches(p, tok)) + if prepared.tokens.is_empty() { + return true; + } + let hay = Hay { p, cat, whole: prepared.whole, kept: std::cell::OnceCell::new(), own: std::cell::OnceCell::new() }; + prepared.tokens.iter().all(|t| token_matches(p, t, &hay)) } } diff --git a/crates/catalog/src/rules.rs b/crates/catalog/src/rules.rs index 2976a2659b..9b2c3c90ab 100644 --- a/crates/catalog/src/rules.rs +++ b/crates/catalog/src/rules.rs @@ -702,8 +702,37 @@ fn lower(v: &Value) -> String { } } +/// What a Text rule looks through for `p`: its file name, title, caption, camera, lens, location, city, +/// state, country, alt text, format, keywords, people and copy name, trimmed and lower-cased. +pub(crate) fn rule_text(p: &Photo) -> String { + let m = &p.meta; + let all = [ + p.file_name.as_str(), + &m.title, + &m.caption, + &m.camera, + &m.lens, + &m.location, + &m.city, + &m.state, + &m.country, + &m.alt_text, + &p.format, + &m.keywords.join(" "), + &p.people().join(" "), + p.copy_name.as_deref().unwrap_or(""), + ] + .join(" "); + let all = all.trim(); + if all.is_ascii() { all.to_ascii_lowercase() } else { all.to_lowercase() } +} + fn text_op(op: &str, have: &str, want: &str) -> bool { - let have = have.trim().to_lowercase(); + text_op_lowered(op, &have.trim().to_lowercase(), want) +} + +/// [`text_op`] for a `have` that is trimmed and lower-cased already. +fn text_op_lowered(op: &str, have: &str, want: &str) -> bool { match op { "contains" => want.split_whitespace().all(|w| have.contains(w)), "notContains" => !want.split_whitespace().any(|w| have.contains(w)), @@ -981,26 +1010,10 @@ impl Rule { "keywordCount" => num_op(op, Some(p.keyword_count() as f64), value), "person" => names_op(op, &p.people(), &want), "personCount" => num_op(op, Some(p.people().len() as f64), value), - "text" => { - let all = [ - p.file_name.as_str(), - &m.title, - &m.caption, - &m.camera, - &m.lens, - &m.location, - &m.city, - &m.state, - &m.country, - &m.alt_text, - &p.format, - &m.keywords.join(" "), - &p.people().join(" "), - p.copy_name.as_deref().unwrap_or(""), - ] - .join(" "); - text(&all) - } + "text" => match cat.rule_text_of(p) { + Some(have) => text_op_lowered(op, have, &want), + None => text_op_lowered(op, &rule_text(p), &want), + }, "fileName" => text(&p.file_name), "extension" => text_op(op, p.extension(), want.trim_start_matches('.')), "duration" => num_op(op, p.duration.filter(|d| d.is_finite()), value), diff --git a/crates/catalog/src/tests_search_text.rs b/crates/catalog/src/tests_search_text.rs new file mode 100644 index 0000000000..123e6d5692 --- /dev/null +++ b/crates/catalog/src/tests_search_text.rs @@ -0,0 +1,429 @@ +//! The free-text search and smart albums' Text rules read a photo's lower-cased text from a cache +//! ([`crate::index`]) rather than lower-casing every field of every photo on every keystroke. The +//! cache must give the matches the fields give, and follow every edit of a field it holds. + +use lightcraft_meta::{Rect, Region, RegionKind}; +use serde_json::json; + +use super::*; +use crate::index::PhotoText; + +fn photo(id: u64, file: &str) -> Photo { + Photo::new(PhotoId(id), Source::Demo { scene: 1 }, file, "JPEG", 60, 40, "2026-01-01T00:00:00") +} + +fn face(name: &str) -> Region { + Region { rect: Rect { x0: 0.4, y0: 0.4, x1: 0.6, y1: 0.6 }, kind: RegionKind::Face, name: Some(name.into()), description: None } +} + +/// Photos whose text is hard on a lower-casing shortcut: Unicode that changes length or depends on +/// its neighbours, a word that is only there across two fields, a colon in a plain word. +fn library() -> Catalog { + let mut photos = Vec::new(); + let mut p = photo(1, "IMG_0001.JPG"); + p.rating = 3; + p.meta.camera = "Canon EOS R5".into(); + p.meta.lens = "RF24-70mm F2.8 L".into(); + p.meta.title = "Trip to Ōsaka".into(); + p.meta.caption = "Straße am Fluss".into(); + p.meta.location = "Kyōto".into(); + p.meta.keywords = vec!["Travel|Italy".into(), "Ὀδυσσεύς".into(), "Kyōto Japan".into()]; + photos.push(p); + let mut p = photo(2, "İstanbul.jpg"); + p.meta.title = "ΣΊΣΥΦΟΣ".into(); + p.meta.caption = "Re: 10:30 meeting".into(); + p.meta.city = "Zürich".into(); + p.meta.regions = vec![face("Ana Lima")]; + photos.push(p); + let mut p = photo(3, "plain.png"); + p.format = "PNG".into(); + photos.push(p); + let mut p = photo(4, "abc"); + p.meta.camera = "def".into(); + p.meta.title = "Dž dž".into(); + photos.push(p); + let mut p = photo(5, "name:colon.jpg"); + p.meta.lens = "title:trip".into(); + p.copy_name = Some("Black and White".into()); + photos.push(p); + let mut c = Catalog::new(); + for p in photos { + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + c +} + +/// How the search read a word before the cache: each field lower-cased alone, for every photo. +fn before_text_matches(p: &Photo, t: &str) -> bool { + let hay = [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format]; + hay.iter().any(|h| h.to_lowercase().contains(t)) + || p.meta.keywords.iter().any(|k| k.to_lowercase().contains(t)) + || p.people().iter().any(|n| n.to_lowercase().contains(t)) +} + +/// [`before_text_matches`] for the words the tests use: plain ones and the fields the cache serves. +fn before_matches(p: &Photo, text: &str) -> bool { + text.split_whitespace().all(|tok| { + let t = tok.to_lowercase(); + match t.split_once(':') { + Some(("camera", val)) => p.meta.camera.to_lowercase().contains(val), + Some(("lens", val)) => p.meta.lens.to_lowercase().contains(val), + Some(("name" | "file", val)) => p.file_name.to_lowercase().contains(val), + Some(("rating", val)) => p.rating.to_string() == val, + Some(("kw" | "keyword", val)) => p.meta.keywords.iter().any(|k| crate::keywords::is_under(k, val)), + _ => before_text_matches(p, &t), + } + }) +} + +const QUERIES: &[&str] = &[ + "img", + "IMG_0001", + "IMG_0001.JPG", + "canon r5", + "CANON eos", + "ōsaka", + "ŌSAKA", + "osaka", + "straße", + "STRASSE", + "i̇stanbul", + "İSTANBUL", + "istanbul", + "σίσυφος", + "ΣΊΣΥΦΟΣ", + "ς", + "σ", + "ὀδυσσεύς", + "travel", + "italy", + "travel|italy", + "kyōto japan", + "kyōto", + "10:30", + "re:", + "name:img", + "NAME:IMG_0001", + "file:plain", + "name:", + "camera:canon", + "camera:r5", + "lens:rf24", + "lens:", + "title:trip", + "abcdef", + "abc def", + "dž", + "rating:3 trip", + "kw:travel ōsaka", + "kw:travel osaka", + "png jpeg", + "", + " ", + "zzz", +]; + +fn shown(c: &Catalog, text: &str) -> Vec { + let f = Filter { text: text.into(), ..Default::default() }; + let mut ids: Vec = c.query(&f, &Sort::default()).into_iter().map(|id| id.0).collect(); + ids.sort_unstable(); + ids +} + +fn expected(c: &Catalog, text: &str) -> Vec { + c.photos().filter(|p| !p.deleted && before_matches(p, text)).map(|p| p.id.0).collect() +} + +/// A search finds what the fields hold, whether it asks for one photo at a time, as a pass over the +/// library that makes the cache, or one photo after that. +#[test] +fn search_matches_as_the_fields_do() { + let c = library(); + let mut one_by_one = Vec::new(); + for q in QUERIES.iter().copied() { + let f = Filter { text: q.into(), ..Default::default() }; + one_by_one.push(c.photos().filter(|p| f.matches(p, &c)).map(|p| p.id.0).collect::>()); + } + assert!(c.photos().all(|p| c.search_text(p, false).is_none()), "testing one photo makes no cache for the library"); + for (q, got) in QUERIES.iter().zip(&one_by_one) { + assert_eq!(*got, expected(&c, q), "{q:?}, one photo at a time"); + } + for q in QUERIES.iter().copied() { + assert_eq!(shown(&c, q), expected(&c, q), "{q:?}, a pass over the library"); + } + assert!(c.photos().all(|p| c.search_text(p, false).is_some()), "a pass made the cache"); + for q in QUERIES.iter().copied() { + let f = Filter { text: q.into(), ..Default::default() }; + let got: Vec = c.photos().filter(|p| f.matches(p, &c)).map(|p| p.id.0).collect(); + assert_eq!(got, expected(&c, q), "{q:?}, one photo at a time, with the cache"); + } +} + +/// A photo that isn't the catalog's own (an edit not made yet, a candidate being tried) is read +/// from its own fields, not from what the catalog kept for the photo with its id. +#[test] +fn a_copy_of_a_photo_is_read_as_it_is() { + let c = library(); + let f = Filter { text: "ōsaka".into(), ..Default::default() }; + assert_eq!(c.count(&f), 1); + let mut p = (**c.photo(PhotoId(1)).unwrap()).clone(); + p.meta.title = "Trip to Nara".into(); + p.meta.keywords.clear(); + p.meta.location.clear(); + assert!(!f.matches(&p, &c), "the catalog's own text says Ōsaka, this copy doesn't"); + let nara = Filter { text: "nara".into(), ..Default::default() }; + assert!(nara.matches(&p, &c)); + assert!(!nara.matches(c.photo(PhotoId(1)).unwrap(), &c)); + let rule = Filter { rule_set: Some(rules(json!({"rules": [{"field": "text", "op": "contains", "value": "nara"}]}))), ..Default::default() }; + assert_eq!(c.count(&rule), 0); + assert!(rule.matches(&p, &c)); +} + +fn rules(v: serde_json::Value) -> RuleSet { + serde_json::from_value(v).unwrap() +} + +fn text_rule(op: &str, value: &str) -> Filter { + Filter { rule_set: Some(rules(json!({"rules": [{"field": "text", "op": op, "value": value}]}))), ..Default::default() } +} + +/// What the cache holds is what a scan of the photos would give it, and every photo's is used. +fn assert_current(c: &Catalog) { + for p in c.photos() { + let kept = c.search_text(p, false).unwrap_or_else(|| panic!("photo {}: no text kept, or kept for another place", p.id.0)); + let now = PhotoText::of(p); + assert_eq!(kept.text(), now.text(), "photo {}", p.id.0); + assert_eq!(c.rule_text_of(p), Some(crate::rules::rule_text(p).as_str()), "photo {}: the Text rule's text", p.id.0); + } +} + +/// Make the caches, as the first search and the first smart album with a Text rule do. +fn warm(c: &Catalog) { + c.count(&Filter { text: "x".into(), ..Default::default() }); + c.count(&text_rule("contains", "x")); + assert_current(c); +} + +fn found(c: &Catalog, text: &str) -> usize { + c.count(&Filter { text: text.into(), ..Default::default() }) +} + +fn found_by_rule(c: &Catalog, text: &str) -> usize { + c.count(&text_rule("contains", text)) +} + +/// An edit of each field that is searched puts the new text in the cache and takes the old one out, +/// through the op, its inverse and a batch that fails and is taken back. +#[test] +fn the_cache_follows_every_field_that_is_searched() { + let mut c = library(); + warm(&c); + let id = PhotoId(3); + let edit = |c: &mut Catalog, set: &dyn Fn(&mut Meta)| { + let mut meta = c.photo(id).unwrap().meta.clone(); + set(&mut meta); + c.apply(Op::SetMeta { id, meta: Box::new(meta) }).unwrap() + }; + type Set = fn(&mut Meta, &str); + let fields: [(&str, Set); 6] = [ + ("title", |m, v| m.title = v.into()), + ("caption", |m, v| m.caption = v.into()), + ("camera", |m, v| m.camera = v.into()), + ("lens", |m, v| m.lens = v.into()), + ("location", |m, v| m.location = v.into()), + ("keywords", |m, v| m.keywords = vec![v.into()]), + ]; + for (n, (field, set)) in fields.into_iter().enumerate() { + let word = format!("Zq{n}x"); + let before = found(&c, &word); + let undo = edit(&mut c, &|m| set(m, &word)); + assert_eq!((before, found(&c, &word)), (0, 1), "{field}: found after the edit"); + assert_eq!(found_by_rule(&c, &word.to_lowercase()), 1, "{field}: the Text rule"); + assert_current(&c); + c.apply(undo).unwrap(); + assert_eq!(found(&c, &word), 0, "{field}: gone after the undo"); + assert_current(&c); + } + // the fields only Text rules read + let rule_fields: [(&str, Set); 3] = + [("city", |m, v| m.city = v.into()), ("state", |m, v| m.state = v.into()), ("country", |m, v| m.country = v.into())]; + for (n, (field, set)) in rule_fields.into_iter().enumerate() { + let word = format!("zr{n}y"); + let undo = edit(&mut c, &|m| set(m, &word)); + assert_eq!((found_by_rule(&c, &word), found(&c, &word)), (1, 0), "{field}"); + assert_current(&c); + c.apply(undo).unwrap(); + assert_eq!(found_by_rule(&c, &word), 0, "{field}: gone after the undo"); + } + let undo = edit(&mut c, &|m| m.alt_text = "zalt".into()); + assert_eq!(found_by_rule(&c, "zalt"), 1); + c.apply(undo).unwrap(); + assert_eq!(found_by_rule(&c, "zalt"), 0); + let undo = edit(&mut c, &|m| m.regions = vec![face("Zed Person")]); + assert_eq!(found_by_rule(&c, "zed person"), 1, "a person named on a face"); + c.apply(undo).unwrap(); + assert_eq!(found_by_rule(&c, "zed person"), 0); + assert_current(&c); +} + +#[test] +fn the_cache_follows_a_file_name_and_a_format() { + let mut c = library(); + warm(&c); + let id = PhotoId(3); + let source = Source::Demo { scene: 1 }; + let undo = c.apply(Op::SetFile { id, file_name: "Renamed_0042.PNG".into(), source: source.clone() }).unwrap(); + assert_eq!((found(&c, "renamed_0042"), found(&c, "plain"), found(&c, "name:renamed")), (1, 0, 1)); + assert_eq!((found_by_rule(&c, "renamed_0042"), found_by_rule(&c, "plain")), (1, 0)); + assert_current(&c); + c.apply(undo).unwrap(); + assert_eq!((found(&c, "renamed_0042"), found(&c, "plain")), (0, 1)); + assert_current(&c); + + let undo = c.apply(Op::Relink { id, file_name: "Moved.TIF".into(), source: source.clone(), format: Some("TIFF".into()) }).unwrap(); + assert_eq!((found(&c, "moved"), found(&c, "tiff"), found(&c, "png")), (1, 1, 0)); + assert_eq!((found_by_rule(&c, "moved"), found_by_rule(&c, "tiff"), found_by_rule(&c, "png")), (1, 1, 0)); + assert_current(&c); + c.apply(undo).unwrap(); + assert_eq!((found(&c, "moved"), found(&c, "tiff"), found(&c, "png")), (0, 0, 1)); + assert_current(&c); +} + +/// A photo that comes or goes (an import, a virtual copy, a permanent delete and its undo) does +/// too, and a virtual copy's name is read by a Text rule. +#[test] +fn the_cache_follows_photos_that_come_and_go() { + let mut c = library(); + warm(&c); + let mut copy = (**c.photo(PhotoId(1)).unwrap()).clone(); + copy.id = PhotoId(9); + copy.copy_of = Some(PhotoId(1)); + copy.meta = Default::default(); + copy.copy_name = Some("Zcopy Name".into()); + copy.file_name = "Zfresh.jpg".into(); + let undo = c.apply(Op::AddPhoto { photo: Box::new(copy) }).unwrap(); + assert_eq!((found(&c, "zfresh"), found_by_rule(&c, "zcopy"), found(&c, "zcopy")), (1, 1, 0)); + assert_current(&c); + let redo = c.apply(undo).unwrap(); + assert_eq!((found(&c, "zfresh"), found_by_rule(&c, "zcopy")), (0, 0)); + assert_current(&c); + c.apply(redo).unwrap(); + assert_eq!(found(&c, "zfresh"), 1); + assert_current(&c); + let removed = c.apply(Op::RemovePhoto { id: PhotoId(1) }).unwrap(); + assert_eq!(found(&c, "ōsaka"), 0); + assert_current(&c); + c.apply(removed).unwrap(); + assert_eq!(found(&c, "ōsaka"), 1); + assert_current(&c); +} + +/// A batch that fails half way is taken back, and the cache with it. +#[test] +fn the_cache_follows_a_batch_that_fails() { + let mut c = library(); + warm(&c); + let mut meta = c.photo(PhotoId(3)).unwrap().meta.clone(); + meta.title = "Zbatch title".into(); + let batch = Op::Batch { + ops: vec![ + Op::SetMeta { id: PhotoId(3), meta: Box::new(meta) }, + Op::SetFile { id: PhotoId(3), file_name: "Zbatch.png".into(), source: Source::Demo { scene: 1 } }, + Op::SetFile { id: PhotoId(404), file_name: "gone.png".into(), source: Source::Demo { scene: 1 } }, + ], + }; + assert!(c.apply(batch).is_err()); + assert_eq!((found(&c, "zbatch"), found_by_rule(&c, "zbatch")), (0, 0)); + assert_eq!(found(&c, "plain"), 1); + assert_current(&c); +} + +/// An edit of a photo that something else holds (a thumbnail list, an undo step) puts it at another +/// place in memory. The cache follows it, so a search isn't left reading every such photo from its fields. +#[test] +fn the_cache_follows_a_photo_that_others_hold() { + let mut c = library(); + warm(&c); + let held: Vec<_> = c.photos().cloned().collect(); + for p in &held { + c.apply(Op::SetRating { id: p.id, rating: 5 }).unwrap(); + } + assert!(held.iter().all(|old| !std::ptr::eq(&**old, &**c.photo(old.id).unwrap())), "the edits copied the photos"); + assert_current(&c); + assert_eq!(found(&c, "ōsaka"), 1); + c.apply(Op::SetFile { id: PhotoId(2), file_name: "after.jpg".into(), source: Source::Demo { scene: 1 } }).unwrap(); + assert_current(&c); + assert_eq!((found(&c, "after"), found(&c, "istanbul")), (1, 0)); +} + +/// A catalog read from a snapshot or cloned starts with no cache and builds its own. +#[test] +fn a_clone_builds_its_own() { + let mut c = library(); + warm(&c); + let mut copy = c.clone(); + assert!(copy.photos().all(|p| copy.search_text(p, false).is_none())); + assert_eq!(found(©, "ōsaka"), 1); + warm(©); + let mut meta = copy.photo(PhotoId(1)).unwrap().meta.clone(); + meta.title = "Elsewhere".into(); + copy.apply(Op::SetMeta { id: PhotoId(1), meta: Box::new(meta) }).unwrap(); + assert_eq!((found(©, "elsewhere"), found(&c, "elsewhere")), (1, 0)); + c.apply(Op::SetRating { id: PhotoId(1), rating: 1 }).unwrap(); + assert_current(&c); +} + +/// The words of Text rules (not the search) read the same with the cache as without. +#[test] +fn text_rules_match_as_the_fields_do() { + let c = library(); + let every_op = ["contains", "notContains", "is", "isNot", "startsWith", "endsWith", "isEmpty", "isNotEmpty"]; + let values = + ["", "ōsaka", "TRIP TO", "kyōto japan", "ana lima", "zürich", "img_0001.jpg", "black and white", "ς", "i̇stanbul", "png", "re: 10:30 meeting"]; + let before: Vec> = + every_op.iter().map(|op| values.iter().map(|v| c.photos().filter(|p| text_rule(op, v).matches(p, &c)).count()).collect()).collect(); + let after: Vec> = every_op.iter().map(|op| values.iter().map(|v| c.count(&text_rule(op, v))).collect()).collect(); + assert_eq!(before, after); + assert!(c.photos().all(|p| c.rule_text_of(p).is_some()), "the first rule asked made the text"); + let again: Vec> = + every_op.iter().map(|op| values.iter().map(|v| c.photos().filter(|p| text_rule(op, v).matches(p, &c)).count()).collect()).collect(); + assert_eq!(before, again); +} + +/// A smart album's count through the tally path (`album_contains`, one photo at a time) reads the +/// kept text: it is made there, and an edit shows in the next count. +#[test] +fn a_smart_album_count_reads_the_kept_text() { + let mut c = library(); + let mut album = Album::new(AlbumId(1), "Osaka"); + album.smart = Some(Box::new(text_rule("contains", "ōsaka"))); + c.apply(Op::AddAlbum { album }).unwrap(); + let one_by_one = |c: &Catalog| c.photos().filter(|p| c.album_contains(AlbumId(1), p)).count(); + assert_eq!(one_by_one(&c), 1); + assert!(c.photos().all(|p| c.rule_text_of(p).is_some()), "counting made the text"); + let mut meta = c.photo(PhotoId(3)).unwrap().meta.clone(); + meta.title = "Ōsaka again".into(); + c.apply(Op::SetMeta { id: PhotoId(3), meta: Box::new(meta) }).unwrap(); + assert_eq!(one_by_one(&c), 2); +} + +/// The kept text holds the names of the people on a photo's faces, and a quoted phrase is read as +/// one word that never runs from one field into the next. +#[test] +fn the_kept_text_holds_the_people_and_a_phrase_stays_in_one_field() { + let mut c = library(); + warm(&c); + assert_eq!(found(&c, "ana"), 1, "a person's name is searched"); + assert_eq!(found(&c, "\"ana lima\""), 1, "a quoted name is one phrase"); + assert_eq!(found(&c, "\"lima ana\""), 0); + assert_eq!(found(&c, "\"ōsaka straße\""), 0, "a phrase doesn't run from the title into the caption"); + assert_eq!(found(&c, "\"trip to ōsaka\""), 1, "…but fits inside one field"); + assert_eq!(found(&c, "\"Kyōto Japan\""), 1, "…or one keyword"); + // (the photo that has Ana Lima's face) + let mut meta = c.photo(PhotoId(2)).unwrap().meta.clone(); + meta.regions = vec![face("Zed Person")]; + c.apply(Op::SetMeta { id: PhotoId(2), meta: Box::new(meta) }).unwrap(); + assert_eq!(found(&c, "\"zed person\""), 1, "a renamed person is found at once"); + assert_eq!(found(&c, "ana"), 0, "and the old name is gone"); + assert_current(&c); +} diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c2592003..8e63b0eca5 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -157,6 +157,17 @@ the full count took about 14 s instead of about 23 s on a heavily loaded machine; the rest is the text rules of the albums themselves. The counts are the same as before, including for albums that loop through each other. +### Searching a big library keeps up with your typing +- Typing in the library search stalls less on a library of hundreds of thousands of photos. The search used to + lower-case a photo's file name, title, caption, camera, lens, location, format, every keyword and the names of the + people on its faces again for each photo and each letter you typed. It now keeps that text, makes it the first time + you search, and keeps it up to date as you edit titles, captions, keywords, people and file names. Smart albums with + a Text rule keep their own text the same + way, made the first time such an album is counted or shown. Which photos match is unchanged. On a test library of + 312 000 photos, finding the photos for a word took about 50 ms where it took 120 to 160 ms. The first search makes + the text, which takes a fraction of a second and about 32 MB of memory at that size; a Text rule's text is another + 33 MB. Searches with `camera:`, `lens:` or `name:` gain less (about 70 ms became about 60 ms). + ### Sharper resampling in HDR and panorama merges - Merged photos (HDR and panorama) are resampled with a sharper filter (Lanczos-3 instead of bilinear). Moving a photo by half a pixel used to lose a third of its finest detail; now it keeps most of it, without halos around From 06c28b14c82f662c1adf5ad42dfa116927092273 Mon Sep 17 00:00:00 2001 From: Clyde C Brown Date: Sat, 24 Oct 2026 12:25:30 -0600 Subject: [PATCH 18/98] #2837: Lightroom import: keep compressed history-step and snapshot settings in the archive Lightroom Classic 13 and later store history-step settings as compressed BLOBs, which the catalog reader dropped, so the import archive kept each step without its settings. Decode them (and snapshots stored the same way) with the XMP decoder, warn per image on a malformed one, and cap the total decoded per table at what one archive can hold. An archive too big with those settings is now stored without them instead of being skipped whole, and oversize is a typed error rather than a match on the message text. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lib.rs | 4 + crates/engine/src/lightroom_archive.rs | 232 +++++++++++++----- crates/engine/src/lightroom_catalog.rs | 144 ++++++++--- crates/engine/src/lightroom_fixture.rs | 245 +++++++++++++++++++ crates/engine/src/lightroom_job.rs | 131 +++++----- crates/engine/src/tests_lightroom_history.rs | 136 ++++++++++ docs/lightroom-catalog-import.md | 7 +- docs/parity-checklist.md | 5 +- docs/whats-new.md | 10 + 9 files changed, 761 insertions(+), 153 deletions(-) create mode 100644 crates/engine/src/lightroom_fixture.rs create mode 100644 crates/engine/src/tests_lightroom_history.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4ad5695dc9..f85a014bf0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1304,6 +1304,8 @@ pub fn json_delta(old: &Value, new: &Value) -> Option { } } +#[cfg(test)] +mod lightroom_fixture; #[cfg(test)] mod tests; #[cfg(test)] @@ -1359,6 +1361,8 @@ mod tests_library; #[cfg(test)] mod tests_lightroom_folder; #[cfg(test)] +mod tests_lightroom_history; +#[cfg(test)] mod tests_mask_effects; #[cfg(test)] mod tests_merge; diff --git a/crates/engine/src/lightroom_archive.rs b/crates/engine/src/lightroom_archive.rs index 9c9979d970..4467d39b44 100644 --- a/crates/engine/src/lightroom_archive.rs +++ b/crates/engine/src/lightroom_archive.rs @@ -2,10 +2,10 @@ //! //! Archives use a deterministic JSON representation wrapped in zlib. The JSON //! writer streams through a bounded compressor, so an import cannot first build -//! an unbounded archive buffer. Blob columns are omitted by the catalog reader; -//! decoded XMP, -//! settings, history, snapshots, identities, paths, collections & membership -//! remain available for recovery. +//! an unbounded archive buffer. The catalog reader decodes Lightroom's compressed +//! XMP and history-step and snapshot settings and omits other blob columns, so +//! decoded XMP, settings, history, snapshots, identities, paths, collections & +//! membership remain available for recovery. use std::collections::BTreeMap; use std::fs::{self, File}; @@ -29,6 +29,41 @@ pub const MAX_TOTAL_ARCHIVE_BYTES: u64 = 128 * 1024 * 1024; /// Maximum number of managed archives retained. pub const MAX_MANAGED_ARCHIVES: usize = 8; +/// Why [`store`] stored no archive. +#[derive(Debug)] +pub enum StoreError { + /// The archive would pass [`MAX_ARCHIVE_BYTES`], as JSON or on disk. + TooBig, + /// Anything else, such as a folder or file that can't be written. + Failed(String), +} + +impl From for StoreError { + fn from(why: String) -> Self { + Self::Failed(why) + } +} + +impl std::fmt::Display for StoreError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::TooBig => write!(f, "{TooBig}"), + Self::Failed(why) => f.write_str(why), + } + } +} + +/// What [`store_best_effort`] kept. +#[derive(Debug, PartialEq, Eq)] +pub enum Kept { + /// The whole archive. + All(PathBuf), + /// The archive without history-step and snapshot settings (`text`): with them it passed [`MAX_ARCHIVE_BYTES`]. + WithoutSettings(PathBuf), + /// No archive: it passed [`MAX_ARCHIVE_BYTES`] even without them. + Nothing, +} + const FORMAT_VERSION: u8 = 1; const HEADER: &[u8] = b"LC-LRARCH\0\x01Z"; const NAME_PREFIX: &str = "lightroom-import-"; @@ -44,13 +79,18 @@ const IO_BUFFER: usize = 16 * 1024; /// most [`MAX_MANAGED_ARCHIVES`] and [`MAX_TOTAL_ARCHIVE_BYTES`]. Legacy /// `lightroom-import-*.json` files are deliberately ignored and preserved for /// an explicit caller warning. -pub fn store(directory: &Path, data: &CatalogImport) -> Result { +pub fn store(directory: &Path, data: &CatalogImport) -> Result { + store_with(directory, data, true) +} + +/// [`store`], with the `text` of history steps and snapshots only when `settings`. +fn store_with(directory: &Path, data: &CatalogImport, settings: bool) -> Result { prepare_directory(directory)?; let mut managed = managed_files(directory)?; managed.sort_by_key(|entry| entry.index); let temporary = temporary_path(directory)?; - write_archive(&temporary, data).inspect_err(|_| { + write_archive(&temporary, data, settings).inspect_err(|_| { let _ = remove_managed_file(&temporary); })?; @@ -60,7 +100,7 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result Ok(same) => same, Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error.to_string()); + return Err(error.to_string().into()); } }; if same { @@ -75,20 +115,20 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result let index = managed.last().map_or(0, |entry| entry.index.saturating_add(1)); if managed.last().is_some_and(|entry| entry.index == u64::MAX) { let _ = remove_managed_file(&temporary); - return Err("managed Lightroom archive index is exhausted".into()); + return Err(StoreError::Failed("managed Lightroom archive index is exhausted".into())); } let destination = match next_destination(directory, index) { Ok(path) => path, Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error); + return Err(error.into()); } }; let size = match fs::metadata(&temporary) { Ok(meta) => meta.len(), Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error.to_string()); + return Err(error.to_string().into()); } }; let new_entry = Managed { index, path: destination.clone(), size }; @@ -99,40 +139,46 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result Ok(retirees) => retirees, Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error); + return Err(error.into()); } }; let quarantined = match quarantine(&retirees) { Ok(quarantined) => quarantined, Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error); + return Err(error.into()); } }; if let Err(error) = publish_new(&temporary, &destination) { rollback_quarantine(&quarantined); let _ = remove_managed_file(&temporary); - return Err(error.to_string()); + return Err(error.to_string().into()); } if let Err(error) = remove_managed_file(&temporary) { - return Err(format!("archive published but temporary cleanup failed: {error}")); + return Err(StoreError::Failed(format!("archive published but temporary cleanup failed: {error}"))); } for (old, held) in quarantined { if let Err(error) = remove_managed_file(&held) { - return Err(format!("archive published but could not retire {}: {error}", old.display())); + return Err(StoreError::Failed(format!("archive published but could not retire {}: {error}", old.display()))); } } Ok(destination) } -/// Store source data when possible. An archive that reaches its bounded size is -/// omitted with a warning so catalog import can still complete. -pub fn store_best_effort(directory: &Path, data: &CatalogImport) -> Result, String> { +/// Store source data when possible, so catalog import can still complete. An archive past +/// [`MAX_ARCHIVE_BYTES`] is stored again without the history-step and snapshot settings, which +/// can be most of a catalog's data; one still too big is not stored at all. +pub fn store_best_effort(directory: &Path, data: &CatalogImport) -> Result { match store(directory, data) { - Ok(path) => Ok(Some(path)), - Err(error) if error.contains("Lightroom archive exceeds 32 MiB") => Ok(None), - Err(error) => Err(error), + Ok(path) => return Ok(Kept::All(path)), + Err(StoreError::TooBig) => {} + Err(StoreError::Failed(why)) => return Err(why), + } + match store_with(directory, data, false) { + Ok(path) => Ok(Kept::WithoutSettings(path)), + Err(StoreError::TooBig) => Ok(Kept::Nothing), + Err(StoreError::Failed(why)) => Err(why), } } @@ -213,21 +259,25 @@ fn next_destination(directory: &Path, mut index: u64) -> Result Err("no safe managed archive name available".into()) } -fn write_archive(path: &Path, data: &CatalogImport) -> Result<(), String> { +fn write_archive(path: &Path, data: &CatalogImport, settings: bool) -> Result<(), StoreError> { lightcraft_catalog::safe_file::write_atomic_with(path, &mut |raw| { let mut bounded = BoundedWriter { inner: raw, total: 0 }; bounded.write_all(HEADER)?; let mut compressor = ZlibWriter::new(&mut bounded); - serde_json::to_writer(&mut compressor, &ArchiveRef(data)).map_err(json_io)?; + serde_json::to_writer(&mut compressor, &ArchiveRef(data, settings)).map_err(json_io)?; compressor.finish()?; Ok(()) }) .map(|_| ()) - .map_err(|error| format!("could not write Lightroom archive: {error}")) + .map_err(|error| match error.get_ref().is_some_and(|inner| inner.is::()) { + true => StoreError::TooBig, + false => StoreError::Failed(format!("could not write Lightroom archive: {error}")), + }) } +/// A write error from the archive writers keeps its own `io::Error`, so [`TooBig`] can still be told apart. fn json_io(error: serde_json::Error) -> io::Error { - io::Error::new(io::ErrorKind::InvalidData, error.to_string()) + io::Error::from(error) } struct BoundedWriter<'a> { @@ -251,8 +301,20 @@ impl Write for BoundedWriter<'_> { } } +/// The archive writers' error when the archive would pass [`MAX_ARCHIVE_BYTES`]. +#[derive(Debug)] +struct TooBig; + +impl std::fmt::Display for TooBig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Lightroom archive exceeds {} MiB", MAX_ARCHIVE_BYTES >> 20) + } +} + +impl std::error::Error for TooBig {} + fn limit_error() -> io::Error { - io::Error::new(io::ErrorKind::InvalidData, "Lightroom archive exceeds 32 MiB") + io::Error::new(io::ErrorKind::InvalidData, TooBig) } struct ZlibWriter<'a, 'b> { @@ -435,73 +497,86 @@ fn remove_managed_file(path: &Path) -> io::Result<()> { fs::remove_file(path) } -struct ArchiveRef<'a>(&'a CatalogImport); +/// The archive of a catalog import, with the `text` of history steps and snapshots only when `.1`. +struct ArchiveRef<'a>(&'a CatalogImport, bool); impl Serialize for ArchiveRef<'_> { fn serialize(&self, serializer: S) -> Result { let mut out = serializer.serialize_struct("CatalogImportArchive", 7)?; out.serialize_field("version", &FORMAT_VERSION)?; out.serialize_field("source", &self.0.source)?; - out.serialize_field("photos", &PhotoSeq(&self.0.photos))?; - out.serialize_field("collections", &RowSeq(&self.0.collections))?; - out.serialize_field("members", &RowSeq(&self.0.members))?; - out.serialize_field("collection_content", &RowSeq(&self.0.collection_content))?; + out.serialize_field("photos", &PhotoSeq(&self.0.photos, self.1))?; + out.serialize_field("collections", &RowSeq(&self.0.collections, None))?; + out.serialize_field("members", &RowSeq(&self.0.members, None))?; + out.serialize_field("collection_content", &RowSeq(&self.0.collection_content, None))?; out.serialize_field("warnings", &self.0.warnings)?; out.end() } } -struct PhotoSeq<'a>(&'a [CatalogPhoto]); +struct PhotoSeq<'a>(&'a [CatalogPhoto], bool); impl Serialize for PhotoSeq<'_> { fn serialize(&self, serializer: S) -> Result { let mut out = serializer.serialize_seq(Some(self.0.len()))?; for photo in self.0 { - out.serialize_element(&PhotoRef(photo))?; + out.serialize_element(&PhotoRef(photo, self.1))?; } out.end() } } -struct PhotoRef<'a>(&'a CatalogPhoto); +struct PhotoRef<'a>(&'a CatalogPhoto, bool); impl Serialize for PhotoRef<'_> { fn serialize(&self, serializer: S) -> Result { let p = self.0; + let skip = (!self.1).then_some("text"); let mut out = serializer.serialize_struct("CatalogPhotoArchive", 8)?; out.serialize_field("source_id", &p.source_id)?; out.serialize_field("uuid", &p.uuid)?; out.serialize_field("path", &p.path)?; - out.serialize_field("image", &RowRef(&p.image))?; + out.serialize_field("image", &RowRef(&p.image, None))?; out.serialize_field("settings", &p.settings)?; out.serialize_field("xmp", &p.xmp)?; out.serialize_field("keywords", &p.keywords)?; - out.serialize_field("history", &RowSeq(&p.history))?; - out.serialize_field("snapshots", &RowSeq(&p.snapshots))?; + out.serialize_field("history", &RowSeq(&p.history, skip))?; + out.serialize_field("snapshots", &RowSeq(&p.snapshots, skip))?; out.end() } } -struct RowSeq<'a>(&'a [BTreeMap]); +/// Rows, each without the column `.1` names. +struct RowSeq<'a>(&'a [BTreeMap], Option<&'a str>); impl Serialize for RowSeq<'_> { fn serialize(&self, serializer: S) -> Result { let mut out = serializer.serialize_seq(Some(self.0.len()))?; for row in self.0 { - out.serialize_element(&RowRef(row))?; + out.serialize_element(&RowRef(row, self.1))?; } out.end() } } -struct RowRef<'a>(&'a BTreeMap); +struct RowRef<'a>(&'a BTreeMap, Option<&'a str>); impl Serialize for RowRef<'_> { fn serialize(&self, serializer: S) -> Result { let mut out = serializer.serialize_map(None)?; - for (key, value) in self.0 { + for (key, value) in self.0.iter().filter(|(key, _)| Some(key.as_str()) != self.1) { out.serialize_entry(key, value)?; } out.end() } } +/// The JSON an archive at `path` holds, for tests that check what an import kept. The JSON itself is capped at +/// [`MAX_ARCHIVE_BYTES`] too, so that is the most it can inflate to. +#[cfg(test)] +pub(crate) fn read_back(path: &Path) -> Value { + let bytes = fs::read(path).unwrap(); + assert!(bytes.starts_with(HEADER), "{} is not an import archive", path.display()); + let json = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&bytes[HEADER.len()..], MAX_ARCHIVE_BYTES as usize).unwrap(); + serde_json::from_slice(&json).unwrap() +} + #[cfg(test)] mod tests { use super::*; @@ -604,34 +679,77 @@ mod tests { fn rejects_oversize_before_creating_archive() { let path = tempdir(); let input = data("x".repeat((MAX_ARCHIVE_BYTES as usize) + 1)); - assert!(store(&path, &input).is_err()); + assert!(matches!(store(&path, &input), Err(StoreError::TooBig)), "an oversize archive is told apart by its error"); assert_eq!(managed_count(&path), 0); fs::remove_dir_all(path).unwrap(); } - #[test] - fn large_catalog_history_is_best_effort_and_does_not_abort_import() { - let path = tempdir(); + /// 5,000 photos with 8 KiB of history settings each: about 40 MiB of JSON. + fn large_catalog(history: bool) -> CatalogImport { let mut input = data("catalog.lrcat".into()); input.photos = (0..5_000) - .map(|index| CatalogPhoto { - source_id: index, - uuid: format!("photo-{index}"), - path: format!("/photos/{index}.raw"), - image: BTreeMap::new(), - settings: String::new(), - xmp: String::new(), - keywords: Vec::new(), - history: vec![BTreeMap::from([("text".into(), serde_json::json!(format!("history-{index}-{}", "x".repeat(8 * 1024))))])], - snapshots: Vec::new(), - original: crate::lightroom_catalog::Original::Local, + .map(|index| { + let bulk = format!("history-{index}-{}", "x".repeat(8 * 1024)); + CatalogPhoto { + source_id: index, + uuid: format!("photo-{index}"), + path: format!("/photos/{index}.raw"), + image: BTreeMap::new(), + settings: if history { String::new() } else { bulk.clone() }, + xmp: String::new(), + keywords: Vec::new(), + history: vec![BTreeMap::from([ + ("name".into(), serde_json::json!("Exposure")), + ("text".into(), serde_json::json!(if history { bulk.as_str() } else { "s = {}" })), + ])], + snapshots: vec![BTreeMap::from([("name".into(), serde_json::json!("Before")), ("text".into(), serde_json::json!("s = {}"))])], + original: crate::lightroom_catalog::Original::Local, + } }) .collect(); - assert_eq!(store_best_effort(&path, &input).unwrap(), None); + input + } + + #[test] + fn an_archive_too_big_with_its_history_settings_is_kept_without_them() { + let path = tempdir(); + let kept = store_best_effort(&path, &large_catalog(true)).unwrap(); + let Kept::WithoutSettings(archive) = kept else { panic!("the archive should be kept without settings, not {kept:?}") }; + let decoded = read_back(&archive); + let photos = decoded["photos"].as_array().unwrap(); + assert_eq!(photos.len(), 5_000, "every photo is still archived"); + assert_eq!(photos[7]["uuid"], serde_json::json!("photo-7")); + assert_eq!(photos[7]["history"], serde_json::json!([{"name": "Exposure"}]), "history steps keep everything but their settings"); + assert_eq!(photos[7]["snapshots"], serde_json::json!([{"name": "Before"}]), "and so do snapshots"); + assert_eq!(fs::read_dir(&path).unwrap().count(), 1, "the first, too big try leaves nothing behind"); + fs::remove_dir_all(path).unwrap(); + } + + #[test] + fn large_catalog_is_best_effort_and_does_not_abort_import() { + let path = tempdir(); + assert_eq!(store_best_effort(&path, &large_catalog(false)).unwrap(), Kept::Nothing, "too big even without history settings"); assert_eq!(managed_count(&path), 0); fs::remove_dir_all(path).unwrap(); } + /// Only the size limit leads to a smaller archive or none: any other failure is reported as such. + #[test] + fn a_write_failure_is_not_taken_for_an_oversize_archive() { + let path = tempdir(); + let file = path.join("not-a-folder"); + fs::write(&file, b"x").unwrap(); + assert!(matches!(store(&file, &rich_data()), Err(StoreError::Failed(_))), "a folder that can't be made"); + let folder = path.join("Interop"); + { + let _full = lightcraft_catalog::safe_file::fail_writes_after(0); + assert!(matches!(store(&folder, &rich_data()), Err(StoreError::Failed(_))), "a full disk while writing"); + assert!(store_best_effort(&folder, &rich_data()).is_err(), "a failure is an error, not a skipped archive"); + } + assert_eq!(fs::read_dir(&folder).unwrap().count(), 0, "a failed write leaves nothing behind"); + fs::remove_dir_all(path).unwrap(); + } + #[test] fn archive_roundtrips_zlib_payload_and_preserves_numeric_arrays() { let path = tempdir(); diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 797a96708b..42810d747b 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -48,8 +48,30 @@ struct Reader { db: Database, tables: Vec, } +/// Most bytes of history-step or snapshot settings decoded from one table. They are only archived, and an archive +/// holds at most [`crate::lightroom_archive::MAX_ARCHIVE_BYTES`] of JSON, so this keeps all a catalog can archive while +/// a hostile one can't make the reader allocate without bound (each row alone may decode to 16 MiB). +const MAX_DECODED_SETTINGS: usize = crate::lightroom_archive::MAX_ARCHIVE_BYTES as usize; + +/// The column of table `name` that Lightroom Classic 13 and later store as compressed text (see [`decode_compressed`]), +/// and what a warning calls one and several of its rows. +fn compressed_settings(name: &str) -> Option<(&'static str, &'static str, &'static str)> { + match name { + "Adobe_libraryImageDevelopHistoryStep" => Some(("text", "history step", "history steps")), + "Adobe_libraryImageDevelopSnapshot" => Some(("text", "snapshot", "snapshots")), + _ => None, + } +} + impl Reader { - fn table(&self, name: &str, required: bool) -> Result, String> { + fn table(&self, name: &str, required: bool, warnings: &mut Vec) -> Result, String> { + self.table_within(name, required, MAX_DECODED_SETTINGS, warnings) + } + + /// The rows of table `name`. Its compressed settings column ([`compressed_settings`]) is decoded while the decoded + /// total stays within `budget` bytes; a value that can't be decoded is left out of its row with a warning naming + /// the image, and those past the budget with one warning for all. Other BLOB columns are always left out. + fn table_within(&self, name: &str, required: bool, budget: usize, warnings: &mut Vec) -> Result, String> { let Some(t) = self.tables.iter().find(|t| t.name == name) else { return if required { Err(format!("unsupported Lightroom catalog: missing {name}")) } else { Ok(Vec::new()) }; }; @@ -58,28 +80,55 @@ impl Reader { if rows.len() > 1_000_000 { return Err(format!("{name}: more than one million records")); } - Ok(rows - .into_iter() - .map(|r| { - columns - .iter() - .cloned() - .zip(r.values.into_iter().map(|v| match v { - SqlValue::Null => Some(Value::Null), - SqlValue::Integer(n) => Some(json!(n)), - SqlValue::Real(n) => Some(json!(n)), - SqlValue::Text(s) => Some(json!(s)), - // Opaque Lightroom payloads never become JSON byte arrays. - SqlValue::Blob(_) => None, - })) - .filter_map(|(column, value)| value.map(|value| (column, value))) - .collect() - }) - .collect()) + let compressed = compressed_settings(name); + let mut left = budget; + let mut over_budget = 0usize; + let mut out = Vec::with_capacity(rows.len()); + for r in rows { + let mut row = Row::new(); + let mut settings = None; + for (column, value) in columns.iter().zip(r.values) { + let value = match value { + SqlValue::Null => Value::Null, + SqlValue::Integer(n) => json!(n), + SqlValue::Real(n) => json!(n), + SqlValue::Text(s) => json!(s), + SqlValue::Blob(bytes) => { + if compressed.is_some_and(|(settings_column, _, _)| settings_column == column) { + settings = Some((column, bytes)); + } + // Other opaque Lightroom payloads never become JSON byte arrays. + continue; + } + }; + row.insert(column.clone(), value); + } + if let (Some((column, bytes)), Some((_, what, _))) = (settings, compressed) { + // past the budget, the rest aren't inflated at all + match if over_budget > 0 { Ok(None) } else { decode_compressed(&bytes, "settings").map(Some) } { + Ok(Some(text)) if text.len() <= left => { + left -= text.len(); + row.insert(column.clone(), Value::String(text)); + } + Ok(_) => over_budget += 1, + Err(why) => warnings.push(format!( + "image {}: {what} {}: {why}; archived without its settings", + number(&row, "image"), + number(&row, "id_local") + )), + } + } + out.push(row); + } + if let (Some((_, one, many)), 1..) = (compressed, over_budget) { + let what = if over_budget == 1 { one } else { many }; + warnings.push(format!("{over_budget} {what} archived without their settings: more than {} MiB of settings in {name}", budget >> 20)); + } + Ok(out) } fn optional_table(&self, name: &str, warnings: &mut Vec) -> Result, String> { - match self.table(name, false) { + match self.table(name, false, warnings) { Ok(rows) => Ok(rows), Err(error) => { warnings.push(format!("skipping optional Lightroom table {name}: {error}")); @@ -116,7 +165,7 @@ impl Reader { SqlValue::Integer(n) => Some(json!(n)), SqlValue::Real(n) => Some(json!(n)), SqlValue::Text(s) => Some(json!(s)), - SqlValue::Blob(bytes) if column == "xmp" => match decode_xmp_bytes(&bytes) { + SqlValue::Blob(bytes) if column == "xmp" => match decode_compressed(&bytes, "XMP") { Ok(packet) => Some(Value::String(packet)), Err(error) => { warnings.push(format!("image {image}: {error}")); @@ -323,17 +372,20 @@ fn xmp(v: Option<&Value>) -> Result { } } -fn decode_xmp_bytes(bytes: &[u8]) -> Result { - let size = bytes.get(..4).and_then(|s| <[u8; 4]>::try_from(s).ok()).map(u32::from_be_bytes).ok_or("truncated XMP header")?; +/// Lightroom's compressed text (`Adobe_AdditionalMetadata.xmp`, and history-step and snapshot settings since Lightroom +/// Classic 13): the decoded length as 4 big-endian bytes, then a zlib stream, at most 16 MiB decoded. Errors name it +/// `what`. +fn decode_compressed(bytes: &[u8], what: &str) -> Result { + let size = bytes.get(..4).and_then(|s| <[u8; 4]>::try_from(s).ok()).map(u32::from_be_bytes).ok_or_else(|| format!("truncated {what} header"))?; if size > 16 << 20 { - return Err("XMP packet exceeds 16 MiB".into()); + return Err(format!("{what} longer than 16 MiB")); } - let decoded = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(bytes.get(4..).ok_or("truncated XMP")?, 16 << 20) - .map_err(|_| "invalid compressed XMP")?; + let decoded = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(bytes.get(4..).ok_or_else(|| format!("truncated {what}"))?, 16 << 20) + .map_err(|_| format!("invalid compressed {what}"))?; if decoded.len() != size as usize { - return Err("XMP packet length mismatch".into()); + return Err(format!("{what} length mismatch")); } - String::from_utf8(decoded).map_err(|e| e.to_string()) + String::from_utf8(decoded).map_err(|e| format!("{what} not UTF-8: {e}")) } fn be_word(bytes: &[u8], at: usize) -> Result { @@ -463,9 +515,9 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, } let reader = Reader { tables: db.live_tables()?, db }; let mut warnings = Vec::new(); - let table = |name: &str, required: bool| -> Result, String> { + let table = |name: &str, required: bool, warnings: &mut Vec| -> Result, String> { ensure_read_active(cancel)?; - let rows = reader.table(name, required)?; + let rows = reader.table(name, required, warnings)?; done.fetch_add(1, Ordering::Relaxed); Ok(rows) }; @@ -475,9 +527,9 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, done.fetch_add(1, Ordering::Relaxed); Ok(rows) }; - let roots: HashMap<_, _> = table("AgLibraryRootFolder", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); - let folders: HashMap<_, _> = table("AgLibraryFolder", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); - let files: HashMap<_, _> = table("AgLibraryFile", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); + let roots: HashMap<_, _> = table("AgLibraryRootFolder", true, &mut warnings)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); + let folders: HashMap<_, _> = table("AgLibraryFolder", true, &mut warnings)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); + let files: HashMap<_, _> = table("AgLibraryFile", true, &mut warnings)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); let develops: HashMap<_, _> = optional_table("Adobe_imageDevelopSettings", &mut warnings)? .into_iter() .map(|r| (number(&r, "image"), text(&r, "text").to_string())) @@ -559,7 +611,7 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, // these behind and ignores them); they and their virtual copies are skipped and reported // instead of failing the import let mut orphans = HashSet::new(); - for image in table("Adobe_images", true)? { + for image in table("Adobe_images", true, &mut out.warnings)? { ensure_read_active(cancel)?; let id = number(&image, "id_local"); let record = files.get(&number(&image, "rootFile")).ok_or(SkipReason::MissingFile).and_then(|file| { @@ -824,7 +876,7 @@ fn apply(s: &mut crate::Session, data: CatalogImport, update_existing: bool) -> let archive_dir = s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Interop")); let index_path = archive_dir.as_ref().map(|p| p.join("lightroom-index.json")); let mut index = load_index(index_path.as_deref())?; - let archive_path = archive_dir.as_ref().map(|dir| crate::lightroom_archive::store(dir, &data).map_err(error)).transpose()?; + let archive_path = archive_dir.as_ref().map(|dir| crate::lightroom_archive::store(dir, &data).map_err(|e| error(e.to_string()))).transpose()?; let undo0 = s.undo.len(); let existing: HashMap<_, _> = s.catalog.photos().filter(|p| p.copy_of.is_none()).filter_map(|p| source_path(p).map(|path| (key(path), p.id))).collect(); @@ -1140,6 +1192,28 @@ mod tests { skipped: Vec::new(), } } + /// A catalog whose settings decode to more than the budget keeps every row, archives the settings that fit, and + /// says once how many it left out, instead of allocating whatever its BLOBs inflate to. + #[test] + fn settings_past_the_decode_budget_are_left_out_with_one_warning() { + use crate::lightroom_fixture::{self as fixture, Field, Table}; + let dir = fixture::dir("history-budget"); + let catalog = dir.join("test.lrcat"); + let big = "x".repeat(512 << 10); + let rows = (1..=4).map(|id| fixture::history_step(id, 1, id as f64, "Step", Field::Blob(fixture::compressed(&big)))).collect(); + fixture::write(&catalog, &[Table { name: "Adobe_libraryImageDevelopHistoryStep", columns: fixture::HISTORY_COLUMNS, rows }]); + let db = Database::open_file_with_wal(FileSource::open(&catalog).unwrap(), &[]).unwrap(); + let reader = Reader { tables: db.live_tables().unwrap(), db }; + let mut warnings = Vec::new(); + let rows = reader.table_within("Adobe_libraryImageDevelopHistoryStep", true, 1 << 20, &mut warnings).unwrap(); + assert_eq!(rows.len(), 4, "every step is still read"); + assert_eq!(rows.iter().filter(|r| r.contains_key("text")).count(), 2, "the two steps within 1 MiB keep their settings"); + assert_eq!( + warnings, + ["2 history steps archived without their settings: more than 1 MiB of settings in Adobe_libraryImageDevelopHistoryStep"] + ); + let _ = std::fs::remove_dir_all(dir); + } /// A crafted `.lrcat` that names a program as a photo's original gets no record for it, so /// Photo ▸ Edit In ▸ Open Original has nothing to hand the system opener (#2135). Its virtual /// copies go with it; the catalog's real photos still import. diff --git a/crates/engine/src/lightroom_fixture.rs b/crates/engine/src/lightroom_fixture.rs new file mode 100644 index 0000000000..349bc6dc64 --- /dev/null +++ b/crates/engine/src/lightroom_fixture.rs @@ -0,0 +1,245 @@ +//! Synthetic Lightroom catalogs for tests: a small SQLite file written page by page, so the catalog reader is tested +//! on the bytes it reads in the field (text and BLOB cells, Lightroom's compressed encoding) with no SQLite library. +//! Each table is one leaf page; rows must fit in it without overflow pages. + +use std::path::{Path, PathBuf}; + +const PAGE_SIZE: usize = 4096; +/// The largest record a 4096-byte table leaf holds without an overflow page (SQLite file format §1.6: U - 35). +const MAX_LOCAL: usize = PAGE_SIZE - 35; + +#[derive(Clone, Debug)] +pub(crate) enum Field { + Null, + Integer(i64), + Real(f64), + Text(String), + Blob(Vec), +} + +pub(crate) fn text(s: &str) -> Field { + Field::Text(s.into()) +} + +pub(crate) struct Table { + pub name: &'static str, + /// The column list of its `CREATE TABLE`, as Lightroom writes it. + pub columns: &'static str, + pub rows: Vec>, +} + +/// Lightroom Classic's compressed text (as in `Adobe_AdditionalMetadata.xmp`, and history steps and snapshots since +/// Lightroom Classic 13): the decoded length as 4 big-endian bytes, then the zlib stream. +pub(crate) fn compressed(text: &str) -> Vec { + compressed_bytes(text.as_bytes()) +} + +/// [`compressed`] for any bytes, including ones that aren't UTF-8. +pub(crate) fn compressed_bytes(bytes: &[u8]) -> Vec { + let mut out = u32::try_from(bytes.len()).unwrap().to_be_bytes().to_vec(); + out.extend(miniz_oxide::deflate::compress_to_vec_zlib(bytes, 6)); + out +} + +pub(crate) const HISTORY_COLUMNS: &str = "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, dateCreated, digest, \ + hasBigData INTEGER NOT NULL DEFAULT 0, hasDevelopAdjustments, image INTEGER, name, relValueString, text, valueString"; +pub(crate) const SNAPSHOT_COLUMNS: &str = "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, digest, \ + hasBigData INTEGER NOT NULL DEFAULT 0, hasDevelopAdjustments, image INTEGER, locked, name, snapshotID, text"; + +/// A history step row for image `image` (columns as in [`HISTORY_COLUMNS`]); `settings` is a text or BLOB field. +pub(crate) fn history_step(id: i64, image: i64, date: f64, name: &str, settings: Field) -> Vec { + vec![ + Field::Integer(id), + text(&format!("history-{id}")), + Field::Real(date), + Field::Null, + Field::Integer(0), + Field::Integer(1), + Field::Integer(image), + text(name), + Field::Null, + settings, + Field::Null, + ] +} + +/// A snapshot row for image `image` (columns as in [`SNAPSHOT_COLUMNS`]); `settings` is a text or BLOB field. +pub(crate) fn snapshot(id: i64, image: i64, name: &str, settings: Field) -> Vec { + vec![ + Field::Integer(id), + text(&format!("snapshot-{id}")), + Field::Null, + Field::Integer(0), + Field::Integer(1), + Field::Integer(image), + Field::Null, + text(name), + Field::Null, + settings, + ] +} + +/// The tables of a catalog with one photo, image 1 (`/Photos/test.ARW`, not created), with the develop +/// settings `settings`. Add history, snapshot or other tables and pass them all to [`write`]. +pub(crate) fn one_photo(originals: &Path, settings: &str) -> Vec { + let mut root = originals.to_string_lossy().into_owned(); + if !root.ends_with('/') { + root.push('/'); + } + vec![ + Table { + name: "AgLibraryRootFolder", + columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, absolutePath UNIQUE NOT NULL DEFAULT '', name NOT NULL DEFAULT '', relativePathFromCatalog", + rows: vec![vec![Field::Integer(1), text("root-1"), Field::Text(root), text("originals"), Field::Null]], + }, + Table { + name: "AgLibraryFolder", + columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, pathFromRoot NOT NULL DEFAULT '', rootFolder INTEGER NOT NULL DEFAULT 0", + rows: vec![vec![Field::Integer(1), text("folder-1"), text("Photos/"), Field::Integer(1)]], + }, + Table { + name: "AgLibraryFile", + columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, baseName NOT NULL DEFAULT '', extension NOT NULL DEFAULT '', folder INTEGER NOT NULL DEFAULT 0, idx_filename NOT NULL DEFAULT ''", + rows: vec![vec![Field::Integer(1), text("file-1"), text("test"), text("ARW"), Field::Integer(1), text("test.ARW")]], + }, + Table { + name: "Adobe_images", + columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, fileFormat NOT NULL DEFAULT 'unset', fileHeight, fileWidth, masterImage INTEGER, pick NOT NULL DEFAULT 0, rating, rootFile INTEGER NOT NULL DEFAULT 0", + rows: vec![vec![ + Field::Integer(1), + text("image-1"), + text("RAW"), + Field::Integer(10), + Field::Integer(20), + Field::Null, + Field::Integer(0), + Field::Null, + Field::Integer(1), + ]], + }, + Table { + name: "Adobe_imageDevelopSettings", + columns: "id_local INTEGER PRIMARY KEY, image INTEGER, text", + rows: vec![vec![Field::Integer(1), Field::Integer(1), text(settings)]], + }, + ] +} + +/// A new, empty folder for one test's catalog. +pub(crate) fn dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lightcraft-lrcat-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// Write `tables` as a SQLite database at `path`: page 1 holds the schema, table `i` page `i + 2`. +pub(crate) fn write(path: &Path, tables: &[Table]) { + let mut schema = Vec::new(); + let mut pages = Vec::new(); + for (i, table) in tables.iter().enumerate() { + let root = i64::try_from(i + 2).unwrap(); + schema.push(vec![ + text("table"), + text(table.name), + text(table.name), + Field::Integer(root), + Field::Text(format!("CREATE TABLE {}({})", table.name, table.columns)), + ]); + pages.push(leaf(0, &table.rows, table.name)); + } + let mut first = leaf(100, &schema, "sqlite_master"); + first[..16].copy_from_slice(b"SQLite format 3\0"); + first[16..18].copy_from_slice(&u16::try_from(PAGE_SIZE).unwrap().to_be_bytes()); + first[18] = 1; // legacy journal mode: no WAL file is read unless it exists + first[19] = 1; + first[21] = 64; + first[22] = 32; + first[23] = 32; + first[24..28].copy_from_slice(&1u32.to_be_bytes()); + first[28..32].copy_from_slice(&u32::try_from(pages.len() + 1).unwrap().to_be_bytes()); + first[40..44].copy_from_slice(&1u32.to_be_bytes()); + first[44..48].copy_from_slice(&4u32.to_be_bytes()); + first[56..60].copy_from_slice(&1u32.to_be_bytes()); // UTF-8 + first[92..96].copy_from_slice(&1u32.to_be_bytes()); + first[96..100].copy_from_slice(&3_045_000u32.to_be_bytes()); + let mut bytes = first; + for page in pages { + bytes.extend(page); + } + std::fs::write(path, bytes).unwrap(); +} + +fn leaf(base: usize, rows: &[Vec], table: &str) -> Vec { + let mut page = vec![0u8; PAGE_SIZE]; + page[base] = 0x0d; + page[base + 3..base + 5].copy_from_slice(&u16::try_from(rows.len()).unwrap().to_be_bytes()); + let mut end = PAGE_SIZE; + for (i, values) in rows.iter().enumerate() { + let payload = record(values); + assert!(payload.len() <= MAX_LOCAL, "{table} row {i}: {} bytes needs an overflow page, which the fixture doesn't write", payload.len()); + let rowid = match values.first() { + Some(Field::Integer(id)) => u64::try_from(*id).unwrap(), + _ => u64::try_from(i + 1).unwrap(), + }; + let mut cell = varint(u64::try_from(payload.len()).unwrap()); + cell.extend(varint(rowid)); + cell.extend(payload); + let pointers_end = base + 8 + (i + 1) * 2; + end = end.checked_sub(cell.len()).filter(|e| *e >= pointers_end).unwrap_or_else(|| panic!("{table}: rows don't fit in one page")); + page[end..end + cell.len()].copy_from_slice(&cell); + page[pointers_end - 2..pointers_end].copy_from_slice(&u16::try_from(end).unwrap().to_be_bytes()); + } + page[base + 5..base + 7].copy_from_slice(&u16::try_from(end).unwrap().to_be_bytes()); + page +} + +/// A record (SQLite file format §2.1). An `INTEGER PRIMARY KEY` column's value is the rowid, stored as NULL. +fn record(values: &[Field]) -> Vec { + let mut serials = Vec::new(); + let mut body = Vec::new(); + for (i, value) in values.iter().enumerate() { + let serial = match value { + Field::Integer(_) if i == 0 => 0, + Field::Null => 0, + Field::Integer(n) => { + body.extend(n.to_be_bytes()); + 6 + } + Field::Real(n) => { + body.extend(n.to_be_bytes()); + 7 + } + Field::Text(s) => { + body.extend(s.as_bytes()); + 13 + 2 * u64::try_from(s.len()).unwrap() + } + Field::Blob(b) => { + body.extend(b); + 12 + 2 * u64::try_from(b.len()).unwrap() + } + }; + serials.extend(varint(serial)); + } + // the header length counts its own varint + let mut header_len = serials.len() + 1; + if varint(u64::try_from(header_len).unwrap()).len() > 1 { + header_len += 1; + } + let mut out = varint(u64::try_from(header_len).unwrap()); + out.extend(serials); + out.extend(body); + out +} + +/// SQLite's big-endian varint (values below 2^56, which is all a fixture needs). +fn varint(mut value: u64) -> Vec { + let mut out = vec![(value & 0x7f) as u8]; + value >>= 7; + while value != 0 { + out.push((value & 0x7f) as u8 | 0x80); + value >>= 7; + } + out.reverse(); + out +} diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rs index 762c8588df..90c96ff493 100644 --- a/crates/engine/src/lightroom_job.rs +++ b/crates/engine/src/lightroom_job.rs @@ -31,11 +31,20 @@ fn cancelled() -> crate::EngineError { } fn stage_archive(archive_dir: Option<&Path>, data: &mut CatalogImport) -> crate::Result> { - let archive_path = archive_dir.map(|dir| crate::lightroom_archive::store_best_effort(dir, data).map_err(error)).transpose()?.flatten(); - if archive_dir.is_some() && archive_path.is_none() { - data.warnings.push("Lightroom source archive exceeded 32 MiB; archive skipped".into()); - } - Ok(archive_path) + use crate::lightroom_archive::{Kept, MAX_ARCHIVE_BYTES}; + let Some(dir) = archive_dir else { return Ok(None) }; + let limit = MAX_ARCHIVE_BYTES >> 20; + Ok(match crate::lightroom_archive::store_best_effort(dir, data).map_err(error)? { + Kept::All(path) => Some(path), + Kept::WithoutSettings(path) => { + data.warnings.push(format!("Lightroom source archive exceeded {limit} MiB; archived without history-step and snapshot settings")); + Some(path) + } + Kept::Nothing => { + data.warnings.push(format!("Lightroom source archive exceeded {limit} MiB; archive skipped")); + None + } + }) } /// Memory identity of the library which owns a prepared completion. @@ -509,59 +518,67 @@ mod tests { assert_eq!(session.undo.len(), 3); } + /// 5,000 photos with 8 KiB each of history settings (`in_history`) or develop settings: about 40 MiB of JSON. An + /// archive too big with its history settings is kept without them; one too big even then is skipped. Either + /// way the import goes on and says so. #[test] - fn oversized_history_archive_keeps_prepared_import_successful_with_warning() { - let archive_dir = std::env::temp_dir().join(format!("lightcraft-lr-prepared-scale-{}", std::process::id())); - let mut data = empty_data(); - data.photos = (0..5_000) - .map(|source_id| { - let image = std::collections::BTreeMap::from([ - ("id_local".into(), serde_json::json!(source_id)), - ("fileFormat".into(), serde_json::json!("JPG")), - ("fileWidth".into(), serde_json::json!(1)), - ("fileHeight".into(), serde_json::json!(1)), - ]); - lightroom_catalog::CatalogPhoto { - source_id, - uuid: format!("scale-{source_id}"), - path: format!("/missing/scale-{source_id}.jpg"), - image, - settings: String::new(), - xmp: String::new(), - keywords: Vec::new(), - history: vec![std::collections::BTreeMap::from([( - "text".into(), - serde_json::json!(format!("history-{source_id}-{}", "x".repeat(8 * 1024))), - )])], - snapshots: Vec::new(), - original: lightroom_catalog::Original::Local, - } - }) - .collect(); - let archive_path = stage_archive(Some(&archive_dir), &mut data).unwrap(); - assert!(archive_path.is_none()); - let mut session = crate::Session::new(); - let token = LightroomLibraryToken::capture(&session); - let prepared = PreparedLightroom { - data, - normal: Prepared::default(), - index: ImportIndex::default(), - archive_path, - token, - missing_sources: HashSet::new(), - update_existing: false, - now: "2026-01-01T00:00:00".into(), - cancelled: false, - }; - let completion = commit_prepared(&mut session, prepared).unwrap(); - assert_eq!(completion.report["photos"], 5_000); - assert!( - completion.report["warnings"] - .as_array() - .is_some_and(|warnings| warnings.iter().any(|warning| warning == "Lightroom source archive exceeded 32 MiB; archive skipped")) - ); - assert_eq!(session.catalog.len(), 5_000); - std::fs::remove_dir_all(archive_dir).unwrap(); + fn oversized_archive_keeps_prepared_import_successful_with_warning() { + for (in_history, warning, archived) in [ + (true, "Lightroom source archive exceeded 32 MiB; archived without history-step and snapshot settings", true), + (false, "Lightroom source archive exceeded 32 MiB; archive skipped", false), + ] { + let archive_dir = std::env::temp_dir().join(format!("lightcraft-lr-prepared-scale-{in_history}-{}", std::process::id())); + let mut data = empty_data(); + data.photos = (0..5_000) + .map(|source_id| { + let image = std::collections::BTreeMap::from([ + ("id_local".into(), serde_json::json!(source_id)), + ("fileFormat".into(), serde_json::json!("JPG")), + ("fileWidth".into(), serde_json::json!(1)), + ("fileHeight".into(), serde_json::json!(1)), + ]); + let bulk = format!("history-{source_id}-{}", "x".repeat(8 * 1024)); + lightroom_catalog::CatalogPhoto { + source_id, + uuid: format!("scale-{source_id}"), + path: format!("/missing/scale-{source_id}.jpg"), + image, + settings: if in_history { String::new() } else { bulk.clone() }, + xmp: String::new(), + keywords: Vec::new(), + history: vec![std::collections::BTreeMap::from([( + "text".into(), + serde_json::json!(if in_history { bulk } else { String::new() }), + )])], + snapshots: Vec::new(), + original: lightroom_catalog::Original::Local, + } + }) + .collect(); + let archive_path = stage_archive(Some(&archive_dir), &mut data).unwrap(); + assert_eq!(archive_path.is_some(), archived, "{warning}"); + let mut session = crate::Session::new(); + let token = LightroomLibraryToken::capture(&session); + let prepared = PreparedLightroom { + data, + normal: Prepared::default(), + index: ImportIndex::default(), + archive_path, + token, + missing_sources: HashSet::new(), + update_existing: false, + now: "2026-01-01T00:00:00".into(), + cancelled: false, + }; + let completion = commit_prepared(&mut session, prepared).unwrap(); + assert_eq!(completion.report["photos"], 5_000); + assert!( + completion.report["warnings"].as_array().is_some_and(|warnings| warnings.iter().any(|w| w == warning)), + "the report should say: {warning}" + ); + assert_eq!(session.catalog.len(), 5_000); + std::fs::remove_dir_all(archive_dir).unwrap(); + } } #[test] diff --git a/crates/engine/src/tests_lightroom_history.rs b/crates/engine/src/tests_lightroom_history.rs new file mode 100644 index 0000000000..fbc9e77cbb --- /dev/null +++ b/crates/engine/src/tests_lightroom_history.rs @@ -0,0 +1,136 @@ +//! Lightroom history steps and snapshots read from a catalog file into the import archive: stored as text +//! (Lightroom 6) or as compressed BLOBs (history steps since Lightroom Classic 13, which also converts an upgraded +//! catalog's steps). + +use crate::lightroom_fixture::{self as fixture, Field, Table}; +use serde_json::{Value, json}; + +const CURRENT: &str = "s = { Exposure2012 = 1.25, Contrast2012 = 17 }"; +const FIRST: &str = "s = { Exposure2012 = 1.25 }"; + +/// Write a one-photo catalog with `extra` tables, read it, archive it, and return the archive's JSON. +fn archive(tag: &str, extra: Vec
) -> Value { + let dir = fixture::dir(tag); + let mut tables = fixture::one_photo(&dir.join("originals"), CURRENT); + tables.extend(extra); + let catalog = dir.join("test.lrcat"); + fixture::write(&catalog, &tables); + let data = crate::lightroom_catalog::read(&catalog).unwrap(); + let stored = crate::lightroom_archive::store(&dir.join("Interop"), &data).unwrap(); + let archived = crate::lightroom_archive::read_back(&stored); + let _ = std::fs::remove_dir_all(dir); + archived +} + +fn steps(settings: impl Fn(&str) -> Field) -> Table { + Table { + name: "Adobe_libraryImageDevelopHistoryStep", + columns: fixture::HISTORY_COLUMNS, + rows: vec![fixture::history_step(3, 1, 20.0, "Contrast", settings(CURRENT)), fixture::history_step(2, 1, 10.0, "Exposure", settings(FIRST))], + } +} + +/// `(name, dateCreated, text)` of each archived row, in the order the archive holds them. +fn rows(archive: &Value, key: &str) -> Vec<(Value, Value, Value)> { + let rows = archive["photos"][0][key].as_array().unwrap_or_else(|| panic!("the archive should list {key}: {archive}")); + rows.iter().map(|r| (r["name"].clone(), r["dateCreated"].clone(), r["text"].clone())).collect() +} + +#[test] +fn compressed_history_steps_keep_their_settings_in_the_archive() { + let archived = archive("history-blob", vec![steps(|t| Field::Blob(fixture::compressed(t)))]); + let mut steps = rows(&archived, "history"); + steps.sort_by(|a, b| a.1.as_f64().partial_cmp(&b.1.as_f64()).unwrap()); + assert_eq!( + steps, + [(json!("Exposure"), json!(10.0), json!(FIRST)), (json!("Contrast"), json!(20.0), json!(CURRENT))], + "each compressed step should be archived with its decoded settings: {archived}" + ); + assert_eq!(archived["warnings"], json!([]), "no step should be reported unreadable"); +} + +#[test] +fn text_history_steps_are_archived_as_before() { + let archived = archive("history-text", vec![steps(fixture::text)]); + let mut steps = rows(&archived, "history"); + steps.sort_by(|a, b| a.1.as_f64().partial_cmp(&b.1.as_f64()).unwrap()); + assert_eq!(steps, [(json!("Exposure"), json!(10.0), json!(FIRST)), (json!("Contrast"), json!(20.0), json!(CURRENT))], "{archived}"); + assert_eq!(archived["warnings"], json!([])); +} + +#[test] +fn compressed_and_text_snapshots_keep_their_settings_in_the_archive() { + let snapshots = Table { + name: "Adobe_libraryImageDevelopSnapshot", + columns: fixture::SNAPSHOT_COLUMNS, + rows: vec![ + fixture::snapshot(5, 1, "Bright", Field::Blob(fixture::compressed("s = { Exposure2012 = 2 }"))), + fixture::snapshot(6, 1, "Plain", fixture::text("s = { Contrast2012 = 30 }")), + ], + }; + let archived = archive("snapshot-blob", vec![snapshots]); + let mut kept: Vec<_> = rows(&archived, "snapshots").into_iter().map(|(name, _, text)| (name, text)).collect(); + kept.sort_by_key(|(name, _)| name.to_string()); + assert_eq!( + kept, + [(json!("Bright"), json!("s = { Exposure2012 = 2 }")), (json!("Plain"), json!("s = { Contrast2012 = 30 }"))], + "compressed and text snapshots should both be archived with their settings: {archived}" + ); + assert_eq!(archived["warnings"], json!([])); +} + +/// A hostile or damaged catalog: each bad BLOB costs only its own row's settings, with a warning naming the image. +#[test] +fn a_malformed_settings_blob_is_archived_without_its_settings_and_warned_about() { + let mut mismatch = fixture::compressed(FIRST); + mismatch[3] = mismatch[3].wrapping_add(1); + let mut over_cap = fixture::compressed(FIRST); + over_cap[..4].copy_from_slice(&((16u32 << 20) + 1).to_be_bytes()); + let bad = [ + ("Short", vec![0, 0]), + ("Not zlib", vec![0, 0, 0, 5, 1, 2, 3, 4, 5]), + ("Wrong length", mismatch), + ("Too big", over_cap), + ("Not UTF-8", fixture::compressed_bytes(&[0xff, 0xfe])), + ]; + let mut history = steps(|t| Field::Blob(fixture::compressed(t))); + for (i, (name, bytes)) in bad.iter().enumerate() { + let id = 10 + i64::try_from(i).unwrap(); + history.rows.push(fixture::history_step(id, 1, 30.0 + id as f64, name, Field::Blob(bytes.clone()))); + } + let snapshots = Table { + name: "Adobe_libraryImageDevelopSnapshot", + columns: fixture::SNAPSHOT_COLUMNS, + rows: vec![fixture::snapshot(5, 1, "Broken", Field::Blob(vec![0, 0, 0, 9, 9]))], + }; + let archived = archive("history-bad", vec![history, snapshots]); + assert_eq!(archived["photos"].as_array().map(Vec::len), Some(1), "the photo is still read: {archived}"); + let steps = rows(&archived, "history"); + assert_eq!(steps.len(), 7, "every step is still archived: {archived}"); + for (name, _, text) in &steps { + let good = name == "Exposure" || name == "Contrast"; + assert_eq!(text.is_string(), good, "{name}: only the good steps keep settings: {archived}"); + } + assert_eq!(rows(&archived, "snapshots")[0].2, Value::Null, "the broken snapshot is archived without settings"); + let warnings: Vec<_> = archived["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(warnings.len(), bad.len() + 1, "one warning per bad step and snapshot: {warnings:?}"); + assert!(warnings.iter().all(|w| w.starts_with("image 1: ")), "each warning names the image: {warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("history step 10")), "a warning names the step: {warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("snapshot 5")), "a warning names the snapshot: {warnings:?}"); +} + +/// Only the settings column is decoded; any other BLOB (even one in Lightroom's compressed encoding) stays out of +/// the archive, as before. +#[test] +fn other_blob_columns_never_reach_the_archive() { + let mut history = steps(|t| Field::Blob(fixture::compressed(t))); + for row in &mut history.rows { + row[3] = Field::Blob(vec![1, 2, 3, 4]); // digest + row[10] = Field::Blob(fixture::compressed("s = { Exposure2012 = 3 }")); // valueString + } + let archived = archive("history-other-blobs", vec![history]); + for step in archived["photos"][0]["history"].as_array().unwrap() { + assert!(step.get("digest").is_none() && step.get("valueString").is_none(), "other BLOB columns leaked: {step}"); + assert!(step["text"].is_string(), "the settings are still decoded: {step}"); + } +} diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index 441becd15e..904729b8a0 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -43,8 +43,11 @@ Before changing records, the importer attempts to save source image records, dec verbatim develop settings, history, snapshots and collection content to compressed `Interop/lightroom-import-N.lca` recovery archives in the LightCraft library. Archiving is best-effort: a size limit or write failure produces a warning and does not prevent photo import. -Unchanged source data reuses its existing archive. Opaque SQL BLOBs are skipped. Each archive is -capped at 32 MiB (uncompressed and on disk), with at most eight archives and 128 MiB total +Unchanged source data reuses its existing archive. History-step and snapshot settings that Lightroom +Classic 13 and later store compressed are decoded into it; one that can't be decoded, or past 32 MiB of +them in one table, is archived without its settings, with a warning. Other opaque SQL BLOBs are skipped. Each archive is +capped at 32 MiB (uncompressed and on disk); one past that with its history-step and snapshot settings is +saved without them, with a warning, and skipped only when still too big. At most eight archives and 128 MiB total are retained. Oldest managed archives are retired; legacy `.json` archives remain untouched. `Interop/lightroom-index.json` records imported identities. Source catalogs and originals are never overwritten. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 9790523e1c..90859255f4 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-22 · **Change:** minor (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-24 · **Change:** minor (LRC-LIB-CATALOG-IMPORT: compressed Lightroom Classic 13+ history-step and snapshot settings kept in the recovery archive; 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 @@ -699,7 +699,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-SURVEY | Survey view | P2 | ✅ | `cmd:view.survey` | N | | LRC-LIB-REFVIEW | Reference view | P2 | ✅ | `cmd:view.reference`, `cmd:photo.setReference`, `crates/ui-egui/src/panels/compare.rs` (`show_reference`) | View ▸ Reference View (⇧R): the reference photo beside the active one (edited with the Edit panel); photo menu ▸ Set as Reference Photo; each pane says “Rendering…” (widget `compare:rendering:`) or “This photo can't be opened” (`compare:renderFailed:`) as the loupe does. Escape → Detail without losing edits; pins are catalog-local; missing/deleted photos refused and deleted references no longer drawn (Windows regression/native smoke verified) | | LRC-LIB-CATALOG-PANEL | Catalog sets | P1 | ✅ | `cmd:library.source` (`missing`) | all, recently added, picks, recently deleted, missing photos (when any) | -| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `docs/lightroom-catalog-import.md` | read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders, a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891) | +| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `docs/lightroom-catalog-import.md` | read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders, a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped, except the compressed history-step and snapshot settings of Lightroom Classic 13 and later, which are decoded into the archive (an archive too big with them is kept without them). Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891) | | LRC-LIB-CATALOG-LOCK | Catalog open in one program at a time | P1 | ✅ | `cmd:app.openLibrary`, `crates/catalog/src/lock.rs`, `crates/engine/src/library.rs` (`open_library`) | exclusive OS lock on `catalog.lock` for the session (app and `lightcraft-cli --library`); a second opener is refused with who has it (`catalog.lock.owner`: program, process, computer); released by the OS on a crash, so never stale; file systems without locks open unprotected with a warning (the app's notices, `library.info` → `settingsWarnings`, and the CLI's stderr; issue #171); no read-only mode; the browser build (OPFS) has no guard across tabs yet. A library that can't be opened at launch (locked, unreadable, newer format, drive missing) shows a window — Try Again, Choose Another Library…, Continue Without Saving (then a banner; nothing written), Quit — instead of a silent demo session (`crates/ui-egui/src/panels/library_problem.rs`); the lock is released explicitly when the library closes, not by letting its file handle close, so a program another thread is starting at that moment (which holds a copy of every file handle until it is launched) cannot keep the library "already open" for a moment (issue #680) | | LRC-LIB-CATALOG-SWITCH | New / Open Recent catalog, catalog name shown | P1 | ✅ | `cmd:app.newLibrary`, `cmd:app.openLibrary`, `cmd:app.recentLibraries`, `cmd:app.clearRecentLibraries`, `crates/ui-egui/src/panels/settings.rs`, `crates/ui-egui/src/panels/left.rs` | File ▸ New Library… (name, then location), File ▸ Open Recent Library (last 8; missing ones greyed out, dropped when opened; Clear), the open library's name under My Photos and in the window title (issue #902); Open/New refused during imports and their folder scans; a library that can't be opened leaves the current one and its reference pin intact; a successful switch clears the catalog-local reference pin; ⌘O (Ctrl+O on Windows and Linux) runs Open Library… and asks for a folder once (`crates/ui-egui/src/tests_keymap.rs`: `cmd_o_opens_the_library_picker_once`); a dialog or a text field with the focus keeps the key | | LRC-LIB-FOLDERS | Disk folder tree | P1 | ✅ | `cmd:library.browse`, `cmd:folder.rename`, `cmd:folder.move`, `crates/ui-egui/src/panels/left.rs` (`local_section`, `folder_tree`) | standard places + the browsed folder + Browse Folder…, each an expandable tree of subfolders, breadcrumb navigation; context menu: Rename Folder…, Move Folder To…, Show in Finder (on disk, photos relinked; one undo step each: undo / redo move the folder back and forth, refused when the destination is taken) | @@ -798,6 +798,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-24 | patch | LRC-LIB-CATALOG-IMPORT: the recovery archive keeps the compressed history-step and snapshot settings of Lightroom Classic 13 and later; an archive too big with them is kept without them; status and counts unchanged | | 2026-10-22 | patch | LR-META-XMP: namespace URI determines ownership; foreign namespaces using recognized prefixes survive saves and cannot supply native settings or ratings; status and counts unchanged | | 2026-10-22 | patch | LR-EXP-PSD, LR-META-EXIF-FULL: PSD/PSB imports and image resources 1058/1060 now supply EXIF and XMP to metadata readers and All Metadata; Original with Remove Location Info refuses detected PSD/PSB GPS; statuses and feature counts unchanged | | 2026-10-21 | patch | LR-IMP-ADD-DIALOG: reconcile #2362 with current main; deleted-album guard and hierarchical picker retained; counts unchanged | diff --git a/docs/whats-new.md b/docs/whats-new.md index c09dddc097..0498ef06db 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,15 @@ # What's new in LightCraft +## 2026-10-24 + +### Lightroom catalog import keeps the settings of each history step +- Importing a Lightroom Classic catalog saves its history steps and snapshots in a recovery archive in the library. + For catalogs from Lightroom Classic 13 and later, the archive kept each step's name and date but not its + settings, because those versions store them compressed. They are now decoded and kept. A step whose settings + can't be read is kept without them, with a warning, and the import goes on. +- When an archive with the history settings would be too big (over 32 MiB), it is now saved without them, with a + warning, instead of not at all. + ## 2026-10-23 ### Tab leaves the name field in New Album, New Smart Album and the name prompts From 6433ba5edfe06d0f392a98cca13b40f2d3d3e3cb Mon Sep 17 00:00:00 2001 From: Clyde C Brown Date: Sat, 24 Oct 2026 12:38:31 -0600 Subject: [PATCH 19/98] #2837: move the archive reader for tests into the Lightroom fixture So the history tests build against code that predates the fix, and can be seen failing there. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lightroom_archive.rs | 13 ++----------- crates/engine/src/lightroom_fixture.rs | 11 +++++++++++ crates/engine/src/tests_lightroom_history.rs | 2 +- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/lightroom_archive.rs b/crates/engine/src/lightroom_archive.rs index 4467d39b44..adb0ee6ae5 100644 --- a/crates/engine/src/lightroom_archive.rs +++ b/crates/engine/src/lightroom_archive.rs @@ -567,16 +567,6 @@ impl Serialize for RowRef<'_> { } } -/// The JSON an archive at `path` holds, for tests that check what an import kept. The JSON itself is capped at -/// [`MAX_ARCHIVE_BYTES`] too, so that is the most it can inflate to. -#[cfg(test)] -pub(crate) fn read_back(path: &Path) -> Value { - let bytes = fs::read(path).unwrap(); - assert!(bytes.starts_with(HEADER), "{} is not an import archive", path.display()); - let json = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&bytes[HEADER.len()..], MAX_ARCHIVE_BYTES as usize).unwrap(); - serde_json::from_slice(&json).unwrap() -} - #[cfg(test)] mod tests { use super::*; @@ -715,7 +705,7 @@ mod tests { let path = tempdir(); let kept = store_best_effort(&path, &large_catalog(true)).unwrap(); let Kept::WithoutSettings(archive) = kept else { panic!("the archive should be kept without settings, not {kept:?}") }; - let decoded = read_back(&archive); + let decoded = crate::lightroom_fixture::read_archive(&archive); let photos = decoded["photos"].as_array().unwrap(); assert_eq!(photos.len(), 5_000, "every photo is still archived"); assert_eq!(photos[7]["uuid"], serde_json::json!("photo-7")); @@ -756,6 +746,7 @@ mod tests { let archive = store(&path, &rich_data()).unwrap(); let bytes = fs::read(archive).unwrap(); assert!(bytes.starts_with(HEADER)); + assert_eq!(crate::lightroom_fixture::ARCHIVE_HEADER, HEADER, "the fixture reads archives with this module's header"); let json = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&bytes[HEADER.len()..], MAX_ARCHIVE_BYTES as usize).unwrap(); let decoded: Value = serde_json::from_slice(&json).unwrap(); assert_eq!(decoded["version"], serde_json::json!(FORMAT_VERSION)); diff --git a/crates/engine/src/lightroom_fixture.rs b/crates/engine/src/lightroom_fixture.rs index 349bc6dc64..b3fe9027de 100644 --- a/crates/engine/src/lightroom_fixture.rs +++ b/crates/engine/src/lightroom_fixture.rs @@ -125,6 +125,17 @@ pub(crate) fn one_photo(originals: &Path, settings: &str) -> Vec
{ ] } +/// The format header an import archive starts with (`lightroom_archive`'s), before its zlib-compressed JSON. +pub(crate) const ARCHIVE_HEADER: &[u8] = b"LC-LRARCH\0\x01Z"; + +/// The JSON the import archive at `path` holds, for tests that check what an import kept. The JSON itself is capped +/// at 32 MiB too, so that is the most it can inflate to. +pub(crate) fn read_archive(path: &Path) -> serde_json::Value { + let bytes = std::fs::read(path).unwrap(); + let json = bytes.strip_prefix(ARCHIVE_HEADER).unwrap_or_else(|| panic!("{} is not an import archive", path.display())); + serde_json::from_slice(&miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(json, 32 << 20).unwrap()).unwrap() +} + /// A new, empty folder for one test's catalog. pub(crate) fn dir(tag: &str) -> PathBuf { let d = std::env::temp_dir().join(format!("lightcraft-lrcat-{tag}-{}", std::process::id())); diff --git a/crates/engine/src/tests_lightroom_history.rs b/crates/engine/src/tests_lightroom_history.rs index fbc9e77cbb..d1fa044186 100644 --- a/crates/engine/src/tests_lightroom_history.rs +++ b/crates/engine/src/tests_lightroom_history.rs @@ -17,7 +17,7 @@ fn archive(tag: &str, extra: Vec
) -> Value { fixture::write(&catalog, &tables); let data = crate::lightroom_catalog::read(&catalog).unwrap(); let stored = crate::lightroom_archive::store(&dir.join("Interop"), &data).unwrap(); - let archived = crate::lightroom_archive::read_back(&stored); + let archived = fixture::read_archive(&stored); let _ = std::fs::remove_dir_all(dir); archived } From 8c45aa359d029823f4bdd00a8a86d82a32f8814b Mon Sep 17 00:00:00 2001 From: Clyde C Brown Date: Sat, 24 Oct 2026 12:41:48 -0600 Subject: [PATCH 20/98] #2837: the fixture's archive reader takes its limit from MAX_ARCHIVE_BYTES Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lightroom_fixture.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/lightroom_fixture.rs b/crates/engine/src/lightroom_fixture.rs index b3fe9027de..ce8325a91e 100644 --- a/crates/engine/src/lightroom_fixture.rs +++ b/crates/engine/src/lightroom_fixture.rs @@ -129,11 +129,14 @@ pub(crate) fn one_photo(originals: &Path, settings: &str) -> Vec
{ pub(crate) const ARCHIVE_HEADER: &[u8] = b"LC-LRARCH\0\x01Z"; /// The JSON the import archive at `path` holds, for tests that check what an import kept. The JSON itself is capped -/// at 32 MiB too, so that is the most it can inflate to. +/// at `MAX_ARCHIVE_BYTES` too, so that is the most it can inflate to. pub(crate) fn read_archive(path: &Path) -> serde_json::Value { let bytes = std::fs::read(path).unwrap(); let json = bytes.strip_prefix(ARCHIVE_HEADER).unwrap_or_else(|| panic!("{} is not an import archive", path.display())); - serde_json::from_slice(&miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(json, 32 << 20).unwrap()).unwrap() + serde_json::from_slice( + &miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(json, crate::lightroom_archive::MAX_ARCHIVE_BYTES as usize).unwrap(), + ) + .unwrap() } /// A new, empty folder for one test's catalog. From 32767dffbb5edd67b0e1aaa481b5173d4a01445c Mon Sep 17 00:00:00 2001 From: Clyde C Brown Date: Sat, 24 Oct 2026 13:42:33 -0600 Subject: [PATCH 21/98] #2837: charge settings their declared length before inflating them Review follow-up: a settings BLOB that failed to decode wasn't charged to the table's budget, so a catalog of bad rows could make the reader inflate without limit. Each value is now charged its declared length first, and inflating stops at that length; past the budget, rows aren't inflated. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lightroom_catalog.rs | 90 ++++++++++++++++++++------ 1 file changed, 71 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 42810d747b..40fc6c6b49 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -68,9 +68,10 @@ impl Reader { self.table_within(name, required, MAX_DECODED_SETTINGS, warnings) } - /// The rows of table `name`. Its compressed settings column ([`compressed_settings`]) is decoded while the decoded - /// total stays within `budget` bytes; a value that can't be decoded is left out of its row with a warning naming - /// the image, and those past the budget with one warning for all. Other BLOB columns are always left out. + /// The rows of table `name`. Its compressed settings column ([`compressed_settings`]) is decoded within `budget` + /// bytes for the whole table: each value is charged its declared length before it is inflated, even one that then + /// fails to decode. A value that can't be decoded is left out of its row with a warning naming the image, and + /// those past the budget with one warning for all. Other BLOB columns are always left out. fn table_within(&self, name: &str, required: bool, budget: usize, warnings: &mut Vec) -> Result, String> { let Some(t) = self.tables.iter().find(|t| t.name == name) else { return if required { Err(format!("unsupported Lightroom catalog: missing {name}")) } else { Ok(Vec::new()) }; @@ -104,18 +105,23 @@ impl Reader { row.insert(column.clone(), value); } if let (Some((column, bytes)), Some((_, what, _))) = (settings, compressed) { - // past the budget, the rest aren't inflated at all - match if over_budget > 0 { Ok(None) } else { decode_compressed(&bytes, "settings").map(Some) } { - Ok(Some(text)) if text.len() <= left => { - left -= text.len(); - row.insert(column.clone(), Value::String(text)); + // charged at its declared length before it is inflated (which never goes past that length), so + // a row that then fails to decode counts too; past the budget, the rest aren't inflated at all + let declared = compressed_len(&bytes); + if declared.is_some_and(|n| over_budget > 0 || n > left) { + over_budget += 1; + } else { + left -= declared.unwrap_or(0); + match decode_compressed(&bytes, "settings") { + Ok(text) => { + row.insert(column.clone(), Value::String(text)); + } + Err(why) => warnings.push(format!( + "image {}: {what} {}: {why}; archived without its settings", + number(&row, "image"), + number(&row, "id_local") + )), } - Ok(_) => over_budget += 1, - Err(why) => warnings.push(format!( - "image {}: {what} {}: {why}; archived without its settings", - number(&row, "image"), - number(&row, "id_local") - )), } } out.push(row); @@ -372,17 +378,24 @@ fn xmp(v: Option<&Value>) -> Result { } } +/// The decoded length [`decode_compressed`] reads from `bytes`' header, when it has one of at most 16 MiB. +fn compressed_len(bytes: &[u8]) -> Option { + let size = bytes.get(..4).and_then(|s| <[u8; 4]>::try_from(s).ok()).map(u32::from_be_bytes)?; + usize::try_from(size).ok().filter(|size| *size <= 16 << 20) +} + /// Lightroom's compressed text (`Adobe_AdditionalMetadata.xmp`, and history-step and snapshot settings since Lightroom /// Classic 13): the decoded length as 4 big-endian bytes, then a zlib stream, at most 16 MiB decoded. Errors name it /// `what`. fn decode_compressed(bytes: &[u8], what: &str) -> Result { - let size = bytes.get(..4).and_then(|s| <[u8; 4]>::try_from(s).ok()).map(u32::from_be_bytes).ok_or_else(|| format!("truncated {what} header"))?; - if size > 16 << 20 { - return Err(format!("{what} longer than 16 MiB")); + if bytes.len() < 4 { + return Err(format!("truncated {what} header")); } - let decoded = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(bytes.get(4..).ok_or_else(|| format!("truncated {what}"))?, 16 << 20) + let size = compressed_len(bytes).ok_or_else(|| format!("{what} longer than 16 MiB"))?; + // inflated no further than its declared length: a stream that goes on is invalid, at no more cost than a valid one + let decoded = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(bytes.get(4..).ok_or_else(|| format!("truncated {what}"))?, size) .map_err(|_| format!("invalid compressed {what}"))?; - if decoded.len() != size as usize { + if decoded.len() != size { return Err(format!("{what} length mismatch")); } String::from_utf8(decoded).map_err(|e| format!("{what} not UTF-8: {e}")) @@ -1214,6 +1227,45 @@ mod tests { ); let _ = std::fs::remove_dir_all(dir); } + /// A stream that inflates past the length its header declares is stopped there, not inflated up to 16 MiB first. + #[test] + fn a_stream_longer_than_its_declared_length_is_stopped_at_that_length() { + let mut bytes = 10u32.to_be_bytes().to_vec(); + bytes.extend(miniz_oxide::deflate::compress_to_vec_zlib(&[b'x'; 1024], 6)); + assert_eq!(decode_compressed(&bytes, "settings"), Err("invalid compressed settings".to_string())); + let mut exact = 1024u32.to_be_bytes().to_vec(); + exact.extend(miniz_oxide::deflate::compress_to_vec_zlib(&[b'x'; 1024], 6)); + assert_eq!(decode_compressed(&exact, "settings").map(|text| text.len()), Ok(1024), "exactly its length decodes"); + } + + /// Settings that fail to decode still cost their declared length, so a catalog of damaged rows can't make the + /// reader inflate without bound: past the budget, the rest are left out without being inflated. + #[test] + fn settings_that_fail_to_decode_still_count_against_the_budget() { + use crate::lightroom_fixture::{self as fixture, Field, Table}; + let dir = fixture::dir("history-budget-bad"); + let catalog = dir.join("test.lrcat"); + let mut damaged = (512u32 << 10).to_be_bytes().to_vec(); + damaged.extend([1, 2, 3]); + let rows = (1..=4).map(|id| fixture::history_step(id, 1, id as f64, "Step", Field::Blob(damaged.clone()))).collect(); + fixture::write(&catalog, &[Table { name: "Adobe_libraryImageDevelopHistoryStep", columns: fixture::HISTORY_COLUMNS, rows }]); + let db = Database::open_file_with_wal(FileSource::open(&catalog).unwrap(), &[]).unwrap(); + let reader = Reader { tables: db.live_tables().unwrap(), db }; + let mut warnings = Vec::new(); + let rows = reader.table_within("Adobe_libraryImageDevelopHistoryStep", true, 1 << 20, &mut warnings).unwrap(); + assert_eq!(rows.len(), 4, "every step is still read"); + assert_eq!( + warnings, + [ + "image 1: history step 1: invalid compressed settings; archived without its settings", + "image 1: history step 2: invalid compressed settings; archived without its settings", + "2 history steps archived without their settings: more than 1 MiB of settings in Adobe_libraryImageDevelopHistoryStep", + ], + "the two damaged steps within 1 MiB are tried; the other two aren't" + ); + let _ = std::fs::remove_dir_all(dir); + } + /// A crafted `.lrcat` that names a program as a photo's original gets no record for it, so /// Photo ▸ Edit In ▸ Open Original has nothing to hand the system opener (#2135). Its virtual /// copies go with it; the catalog's real photos still import. From 29b5b3811dd94b0f54b8698f6621da74def2cd3a Mon Sep 17 00:00:00 2001 From: OneSlips Date: Sat, 17 Oct 2026 00:31:01 +1000 Subject: [PATCH 22/98] UI-PANEL-RESTORE: closing a tool panel gives the panel back as it was Opening Masking, Crop, Remove or Red Eye from the Edit panel and closing it again left no panel at all: the photo jumped sideways and the sliders had to be found again. The panel shown before a tool panel is now remembered (UiState::note_right / leave_tool) and put back in the same frame when the tool closes, by its button, its shortcut or Done: the Edit panel comes back at the same width, the photo stays where it was, and each panel keeps its own scroll position. A panel that was hidden stays hidden. ui.set keeps what is remembered. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 3b3daebb4ee1832fe1f81fb8734e679f433cab7c) --- crates/ui-egui/src/control.rs | 3 + crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/src/menus.rs | 9 +- crates/ui-egui/src/panels/right.rs | 3 +- crates/ui-egui/src/state.rs | 43 ++++++++- crates/ui-egui/src/tests_panel_restore.rs | 106 ++++++++++++++++++++++ 6 files changed, 164 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/tests_panel_restore.rs diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 7e04f1356d..14b569c9e7 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -387,6 +387,9 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest } u.collapsed_sidebar.clear(); u.toast = app.ui.toast.clone(); + // the panel a tool panel took the place of, to put back when it closes, survives a ui.set + u.tool_return = app.ui.tool_return; + u.right_seen = app.ui.right_seen; u.dialog = app.ui.dialog.clone(); u.status = app.ui.status.clone(); crate::docking::cancel_replaced_gesture(app, u.docking.as_ref()); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4fc43172ce..0fb89a88e8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -158,6 +158,8 @@ mod tests_offline; #[cfg(test)] mod tests_open_lightroom; #[cfg(test)] +mod tests_panel_restore; +#[cfg(test)] mod tests_panels; #[cfg(test)] mod tests_preset_favorites; @@ -1581,6 +1583,8 @@ impl LightcraftApp { ctx.send_viewport_cmd(egui::ViewportCommand::Close); } self.library_changed(&ctx); + // (a tool panel opened some other way still remembers the panel it took the place of) + self.ui.note_right(); // panels set it again this frame while the pointer rests on a preset or profile self.hover_preview = None; self.ai_mask_detail(&ctx); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 8c249dd365..1aeb29b743 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -290,8 +290,11 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ]; fn panel(app: &mut LightcraftApp, ctx: &egui::Context, p: RightPanel, name: &str) { + app.ui.note_right(); if app.ui.right == p && crate::docking::exposed(app, crate::docking::Panel::Tools) { - app.ui.right = RightPanel::None; + // a tool closing puts back the panel shown before it (in the same frame: no flash, no + // jump), or leaves the panel hidden when it was + app.ui.right = if p.is_tool() { app.ui.leave_tool() } else { RightPanel::None }; app.toast(ctx, crate::i18n::tr_format!("{name} Off", name = crate::i18n::tr(name))); } else { app.ui.right = p; @@ -303,6 +306,7 @@ fn panel(app: &mut LightcraftApp, ctx: &egui::Context, p: RightPanel, name: &str if p != RightPanel::Masking && app.ui.tool != "wbPicker" { app.ui.tool.clear(); } + app.ui.note_right(); let _ = app.session.end_interaction(); } @@ -1307,7 +1311,8 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option bool { + matches!(self, RightPanel::Crop | RightPanel::Remove | RightPanel::Masking | RightPanel::RedEye) + } + pub fn is_edit_tool(self) -> bool { matches!(self, RightPanel::Edit | RightPanel::Profiles | RightPanel::Crop | RightPanel::Remove | RightPanel::Masking | RightPanel::RedEye) } @@ -801,6 +807,13 @@ pub struct UiState { /// The right panel F8 (`view.rightPanel`) hid, which the next F8 shows again. #[serde(skip)] pub right_hidden: RightPanel, + /// The panel on show before a tool panel ([`RightPanel::is_tool`]) took its place, put back + /// when the tool closes ([`RightPanel::None`]: the panel was hidden, and stays hidden). + #[serde(skip)] + pub tool_return: Option, + /// The panel [`UiState::note_right`] last saw. + #[serde(skip)] + pub right_seen: RightPanel, /// Widths of the left sidebar and of the right panel in points (dragging their inner edge /// resizes them; within [`LEFT_WIDTH`] / [`RIGHT_WIDTH`]). pub left_width: f32, @@ -1477,6 +1490,32 @@ impl SyncCounts { } } +impl UiState { + /// Notes the panel on show: a tool panel opened from another panel (or from none) remembers + /// that one, to put it back when the tool closes; any other panel forgets it. + pub fn note_right(&mut self) { + if self.right == self.right_seen { + return; + } + if self.right.is_tool() { + if !self.right_seen.is_tool() { + self.tool_return = Some(self.right_seen); + } + } else { + self.tool_return = None; + } + self.right_seen = self.right; + } + + /// The panel to show when the tool panel on show closes: the one shown before it, or none + /// when the panel was hidden (Edit when nothing is known). + pub fn leave_tool(&mut self) -> RightPanel { + self.note_right(); + let back = self.tool_return.take().unwrap_or(RightPanel::Edit); + if back.is_tool() { RightPanel::Edit } else { back } + } +} + impl Default for UiState { fn default() -> Self { UiState { @@ -1493,6 +1532,8 @@ impl Default for UiState { right_width: RIGHT_WIDTH.default, right: RightPanel::Edit, right_hidden: RightPanel::None, + tool_return: None, + right_seen: RightPanel::Edit, presets: false, preset_thumbs: false, filmstrip: true, diff --git a/crates/ui-egui/src/tests_panel_restore.rs b/crates/ui-egui/src/tests_panel_restore.rs new file mode 100644 index 0000000000..dd952145f4 --- /dev/null +++ b/crates/ui-egui/src/tests_panel_restore.rs @@ -0,0 +1,106 @@ +//! The panel a tool takes the place of comes back when the tool closes (item 12 of the evening +//! retest): open Edit → Masking (or Crop) → close it → Edit again, at the same width and scroll +//! position, with the photo where it was; a hidden panel stays hidden. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::state::RightPanel; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +fn detail() -> Headless { + let services = Services { png: None, ..Default::default() }; + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services); + let mut h = Headless::new(app, [1400.0, 900.0], 1.0); + let r = h.request("ui.set", json!({"view": "detail", "right": "edit"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + h +} + +fn exec(h: &mut Headless, command: &str) { + let r = h.request("engine.execute", json!({"command": command, "params": {}}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + h.step(); + h.step(); +} + +fn widget(h: &Headless, id: &str) -> Option { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r) +} + +/// The Edit panel's first slider on show (its id and where it is: it moves when the panel scrolls). +fn first_slider(h: &Headless) -> (String, egui::Rect) { + let panel = widget(h, "panel:right_panel").expect("the right panel"); + h.app + .widgets + .iter() + .filter(|(w, r)| w.starts_with("slider:") && panel.contains_rect(*r)) + .min_by(|a, b| a.1.top().total_cmp(&b.1.top())) + .map(|(w, r)| (w.clone(), *r)) + .expect("a slider in the Edit panel") +} + +#[test] +fn the_edit_panel_comes_back_after_masking_and_crop_where_it_was() { + let mut h = detail(); + // scroll the Edit panel down a little (the wheel scrolls what the pointer is over) + let panel = widget(&h, "panel:right_panel").expect("the right panel"); + h.request("ui.move", json!({"x": panel.center().x, "y": panel.center().y}), T); + let r = h.request("ui.scroll", json!({"dy": -300.0}), T); + assert_eq!(r["ok"], true, "{r}"); + for _ in 0..60 { + h.step(); + } + let (slider, at) = first_slider(&h); + let photo = widget(&h, "canvas:image").expect("the photo"); + for tool in ["panel.masking", "panel.crop", "panel.remove"] { + exec(&mut h, tool); + assert!(h.app.ui.right.is_tool(), "{tool}: {:?}", h.app.ui.right); + assert_eq!(widget(&h, "panel:right_panel"), Some(panel), "{tool}: the panel keeps its place and width"); + // the same button again closes the tool: Edit is back, as it was + exec(&mut h, tool); + assert_eq!(h.app.ui.right, RightPanel::Edit, "{tool}: the Edit panel comes back"); + assert_eq!(widget(&h, "panel:right_panel"), Some(panel), "{tool}: same place and width"); + assert_eq!(widget(&h, "canvas:image"), Some(photo), "{tool}: the photo didn't move"); + assert_eq!(widget(&h, &slider), Some(at), "{tool}: Edit kept its scroll position"); + } + // Masking, then Crop from it, then Crop closed: still Edit + exec(&mut h, "panel.masking"); + exec(&mut h, "panel.crop"); + exec(&mut h, "panel.crop"); + assert_eq!(h.app.ui.right, RightPanel::Edit); + // Return (Done) in a tool also goes back + exec(&mut h, "panel.masking"); + exec(&mut h, "tool.done"); + assert_eq!(h.app.ui.right, RightPanel::Edit); +} + +#[test] +fn a_hidden_panel_stays_hidden_after_a_tool() { + let mut h = detail(); + exec(&mut h, "panel.close"); + assert_eq!(h.app.ui.right, RightPanel::None); + let photo = widget(&h, "canvas:image").expect("the photo"); + for tool in ["panel.masking", "panel.crop"] { + exec(&mut h, tool); + assert!(h.app.ui.right.is_tool(), "{tool} shows"); + exec(&mut h, tool); + assert_eq!(h.app.ui.right, RightPanel::None, "{tool}: nothing shows again"); + h.settle(SETTLE); + assert_eq!(widget(&h, "canvas:image"), Some(photo), "{tool}: the photo is where it was"); + } + exec(&mut h, "panel.masking"); + exec(&mut h, "tool.done"); + assert_eq!(h.app.ui.right, RightPanel::None, "Done: hidden as before"); + // a panel picked meanwhile is what comes back: Info → Masking → closed = Info + exec(&mut h, "panel.info"); + exec(&mut h, "panel.masking"); + exec(&mut h, "panel.masking"); + assert_eq!(h.app.ui.right, RightPanel::Info); +} From 283d65852fb6a67bb8900f9b92f016cbdc3d404f Mon Sep 17 00:00:00 2001 From: OneSlips Date: Sun, 25 Oct 2026 06:46:02 +1000 Subject: [PATCH 23/98] KEY-INFO: I toggled off brings back exactly what was there before, closed included (test notes 2026-10-24 note 21) Every panel toggle (I, M, R, Q, the tool strip's buttons) remembers what the right column showed when it opened the panel and puts exactly that back when toggled off: Edit -> I -> I = Edit, Masks -> I -> I = Masks, closed -> I -> I = closed. A tool opened from another tool goes back to that tool (UiState::toggle_panel). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit d5ec632329a60d6526549b71ae2907c09a0d74d0) --- crates/ui-egui/src/menus.rs | 10 ++--- crates/ui-egui/src/state.rs | 46 +++++++++++++++++++++++ crates/ui-egui/src/tests_panel_restore.rs | 41 +++++++++++++++++++- 3 files changed, 90 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 1aeb29b743..b2e880aecb 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -290,14 +290,12 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ]; fn panel(app: &mut LightcraftApp, ctx: &egui::Context, p: RightPanel, name: &str) { - app.ui.note_right(); - if app.ui.right == p && crate::docking::exposed(app, crate::docking::Panel::Tools) { - // a tool closing puts back the panel shown before it (in the same frame: no flash, no - // jump), or leaves the panel hidden when it was - app.ui.right = if p.is_tool() { app.ui.leave_tool() } else { RightPanel::None }; + // toggled off: back to exactly what the right column showed before (in the same frame: no flash, no jump), + // closed when it was closed (note 21) + let exposed = crate::docking::exposed(app, crate::docking::Panel::Tools); + if !app.ui.toggle_panel(p, exposed) { app.toast(ctx, crate::i18n::tr_format!("{name} Off", name = crate::i18n::tr(name))); } else { - app.ui.right = p; app.toast(ctx, crate::i18n::tr_format!("{name} On", name = crate::i18n::tr(name))); if p.is_edit_tool() && !matches!(app.ui.view, ViewMode::Detail) { app.ui.view = ViewMode::Detail; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index ba531918ee..60a99b8891 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -811,6 +811,11 @@ pub struct UiState { /// when the tool closes ([`RightPanel::None`]: the panel was hidden, and stays hidden). #[serde(skip)] pub tool_return: Option, + /// The panel a toggle (a panel key or button: I, M, R, Q…) opened, with what the right column showed before it + /// and that one's [`UiState::tool_return`]: toggling it off puts back exactly that, closed included (test notes + /// 2026-10-24 note 21). Forgotten once another panel is shown. + #[serde(skip)] + pub toggle_return: Option<(RightPanel, RightPanel, Option)>, /// The panel [`UiState::note_right`] last saw. #[serde(skip)] pub right_seen: RightPanel, @@ -1497,6 +1502,9 @@ impl UiState { if self.right == self.right_seen { return; } + if self.toggle_return.is_some_and(|(opened, ..)| opened != self.right) { + self.toggle_return = None; + } if self.right.is_tool() { if !self.right_seen.is_tool() { self.tool_return = Some(self.right_seen); @@ -1511,9 +1519,46 @@ impl UiState { /// when the panel was hidden (Edit when nothing is known). pub fn leave_tool(&mut self) -> RightPanel { self.note_right(); + if let Some(back) = self.untoggle() { + return back; + } let back = self.tool_return.take().unwrap_or(RightPanel::Edit); if back.is_tool() { RightPanel::Edit } else { back } } + + /// A panel toggle (`panel.info`, `panel.masking`…) for `p`: when `p` is on show (`exposed`: not hidden behind + /// another dock tab) it goes and the right column shows exactly what it showed before the toggle opened it, or + /// stays closed when it was (note 21); otherwise `p` comes up and what was there is remembered. Returns whether + /// `p` is now on. + pub fn toggle_panel(&mut self, p: RightPanel, exposed: bool) -> bool { + self.note_right(); + if self.right == p && exposed { + self.right = match self.untoggle() { + Some(back) => back, + None if p.is_tool() => self.leave_tool(), + None => RightPanel::None, + }; + self.note_right(); + false + } else { + let saved = (p, if exposed || self.right != p { self.right } else { RightPanel::None }, self.tool_return); + self.right = p; + self.note_right(); + self.toggle_return = Some(saved); + true + } + } + + /// What the toggle that opened the panel on show replaced (see [`UiState::toggle_panel`]), with its own tool + /// memory put back, or `None` when that panel wasn't opened by a toggle. + fn untoggle(&mut self) -> Option { + let (_, before, tool_return) = self.toggle_return.filter(|(opened, ..)| *opened == self.right)?; + self.toggle_return = None; + self.tool_return = tool_return; + // seen already: `note_right` must not take the panel being left for the one this came back from + self.right_seen = before; + Some(before) + } } impl Default for UiState { @@ -1533,6 +1578,7 @@ impl Default for UiState { right: RightPanel::Edit, right_hidden: RightPanel::None, tool_return: None, + toggle_return: None, right_seen: RightPanel::Edit, presets: false, preset_thumbs: false, diff --git a/crates/ui-egui/src/tests_panel_restore.rs b/crates/ui-egui/src/tests_panel_restore.rs index dd952145f4..640428a6c9 100644 --- a/crates/ui-egui/src/tests_panel_restore.rs +++ b/crates/ui-egui/src/tests_panel_restore.rs @@ -70,10 +70,12 @@ fn the_edit_panel_comes_back_after_masking_and_crop_where_it_was() { assert_eq!(widget(&h, "canvas:image"), Some(photo), "{tool}: the photo didn't move"); assert_eq!(widget(&h, &slider), Some(at), "{tool}: Edit kept its scroll position"); } - // Masking, then Crop from it, then Crop closed: still Edit + // Masking, then Crop from it, then Crop closed: exactly what was there before, Masking (note 21); then Edit exec(&mut h, "panel.masking"); exec(&mut h, "panel.crop"); exec(&mut h, "panel.crop"); + assert_eq!(h.app.ui.right, RightPanel::Masking); + exec(&mut h, "panel.masking"); assert_eq!(h.app.ui.right, RightPanel::Edit); // Return (Done) in a tool also goes back exec(&mut h, "panel.masking"); @@ -104,3 +106,40 @@ fn a_hidden_panel_stays_hidden_after_a_tool() { exec(&mut h, "panel.masking"); assert_eq!(h.app.ui.right, RightPanel::Info); } + +/// "I" toggles the Info panel; pressing it again brings back exactly what the right column showed before, closed +/// included (test notes 2026-10-24 note 21: the Edit sliders stayed gone). +#[test] +fn info_toggled_off_brings_back_exactly_what_was_there() { + let mut h = detail(); + assert_eq!(h.app.ui.right, RightPanel::Edit); + // the key, as the user pressed it + let key = |h: &mut Headless| { + let r = h.request("ui.key", json!({"key": "I"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); + }; + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::Info); + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::Edit, "Edit → I → I = Edit"); + exec(&mut h, "panel.masking"); + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::Info); + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::Masking, "Masks → I → I = Masks"); + // and Masks still closes back to Edit + exec(&mut h, "panel.masking"); + assert_eq!(h.app.ui.right, RightPanel::Edit); + for panel in ["panel.keywords", "panel.versions", "panel.activity"] { + exec(&mut h, panel); + exec(&mut h, panel); + assert_eq!(h.app.ui.right, RightPanel::Edit, "{panel} toggled off: Edit again"); + } + exec(&mut h, "panel.close"); + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::Info); + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::None, "closed → I → I = closed"); +} From 3245ad02ea56c7c3b74f61e0e6f5d66354824b09 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Mon, 26 Oct 2026 01:01:23 +1000 Subject: [PATCH 24/98] KEY-INFO: checklist rows, revision line and What's New for panels that come back as they were Co-Authored-By: Claude Opus 5.5 --- docs/parity-checklist.md | 7 ++++--- docs/whats-new.md | 8 ++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 080680b9ff..f854de9e81 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-24 · **Change:** minor (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-26 · **Change:** minor (LR-BEHAV-PANEL-RESIZE, KEY-INFO: closing a tool panel or toggling a panel off puts back exactly what the right column showed before; 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 @@ -474,7 +474,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-SIDEBAR-HIDE | Show and hide left-sidebar sections | P2 | ✅ | `cmd:view.sidebarSection`, `cmd:view.sidebarReset`, `crates/ui-egui/src/sidebar.rs`, `crates/ui-egui/src/panels/left.rs` (`sections_menu`), `crates/ui-egui/src/menubar.rs`, `crates/ui-egui/src/tests_panels.rs` | View ▸ Sidebar Sections lists Albums, Local, By Date, Folders and Keywords in the sidebar's order, each checked while shown; unchecking one takes its header and rows off the sidebar, checking it puts it back where and how it was (still folded if it was). The same list opens with a right-click on any section header (with Hide This Section first; widgets `sidebarMenu:hide`, `sidebarMenu:section:`, `sidebarMenu:reset`) and on the My Photos title (`sidebarTitle`), which is always there, so hidden sections can always come back. Reset Sidebar Sections (enabled once something changed) shows and opens every section in the usual order. `view.sidebarSection` `{section, show?, collapsed?}` flips shown / hidden when neither flag is given and refuses an unknown section or a flag that is not true / false. Hiding the section of what the grid shows (an album, a keyword filter) leaves the grid as it is; an album made while Albums is hidden or folded brings Albums back, open. Kept with the UI state (`sidebar`). My Photos itself can't be hidden | | LR-BEHAV-SIDEBAR-REORDER | Reorder left-sidebar sections | P2 | ✅ | `cmd:view.sidebarMoveSection`, `crates/ui-egui/src/sidebar.rs` (`move_before`, `move_by`), `crates/ui-egui/src/panels/left.rs` (`section_drag`, `section_drop_before`, `section_drag_feedback`), `crates/ui-egui/src/tests_panels.rs` | drag a section by its header: its name follows the pointer, a line (`sidebarSectionDrop`) shows the gap it would go to (above the section whose upper half the pointer is over, or below the last), releasing over the sidebar moves it there, Esc or releasing elsewhere leaves it; the sidebar scrolls when the drag nears its top or bottom edge, also over a pinned header (a section picked up by the pinned header scrolls once the pointer has left it). A press on a header's button is never a section drag. A click on the header still folds the section, and an album dragged onto the Albums header is still an album drag. The header's menu has Move Up / Move Down (`sidebarMenu:moveUp` / `moveDown`), one shown section at a time, stepping over hidden ones, disabled at the ends. `view.sidebarMoveSection` `{section, direction: up\|down}` or `{section, before:
\|null}` (null: last) answers `{moved, order}`. The order is kept with the UI state (`sidebar`). Recently Deleted is listed with My Photos (below Picks / Missing Photos), not after the sections. Not here: dragging My Photos, or rows from one section into another | | LR-BEHAV-SIDEBAR-STICKY | Pinned section header and section look | P2 | ✅ | `crates/ui-egui/src/panels/left.rs` (`pinned_header`, `section_header`, `empty_hint`), `crates/ui-egui/src/tests_panels.rs` | while the rows of an open section are in view but its header has scrolled away, a copy of the header (`sidebarSectionPinned:`, with the section's buttons and menu) stays at the top of the sidebar; the next section's header pushes it out; folding from it brings the section's own header into view. Rows scrolled beneath the pinned header are covered by it: an album or photos dropped on the pinned Albums header go to the top level / nowhere, never to the row under it; folding from it keeps the sideways scroll. Sections are told apart by a hairline in the gap above each; the fold chevron sits in the gutter, in the column of the rows' triangles (`sidebarSectionChevron:`); a header highlights under the pointer; a folded section shows how many top-level rows it holds (`sidebarSectionCount:`, with View ▸ Photo Counts); a count of 0 is fainter. Not here: a height of its own per section (one scroll area serves the whole sidebar), a count for Recently Added, Local's Browse Folder… as a header button | -| LR-BEHAV-PANEL-RESIZE | Resizable side panels | P1 | ✅ | `crates/ui-egui/src/panels/mod.rs` (`resizable_side`), `crates/ui-egui/src/state.rs` (`LEFT_WIDTH`, `RIGHT_WIDTH`), `crates/ui-egui/src/tests_panels.rs` | drag the left sidebar's right edge (200–480 pt) or the right panel's left edge (250–520 pt); the photo area keeps ≥ 360 pt; widths are kept across panels, views and restarts (`leftWidth` / `rightWidth` in the UI state); the Presets column stays fixed | +| LR-BEHAV-PANEL-RESIZE | Resizable side panels | P1 | ✅ | `crates/ui-egui/src/panels/mod.rs` (`resizable_side`), `crates/ui-egui/src/state.rs` (`LEFT_WIDTH`, `RIGHT_WIDTH`), `crates/ui-egui/src/tests_panels.rs`, `crates/ui-egui/src/tests_panel_restore.rs` | closing a tool panel (Crop, Remove, Masking, Red Eye) puts back the panel shown before it in the same frame, at the same width and scroll position, or leaves it hidden if it was (`UiState::leave_tool`); drag the left sidebar's right edge (200–480 pt) or the right panel's left edge (250–520 pt); the photo area keeps ≥ 360 pt; widths are kept across panels, views and restarts (`leftWidth` / `rightWidth` in the UI state); the Presets column stays fixed | | LR-BEHAV-EMPTY-STATES | Empty states | P1 | ✅ | `crates/ui-egui/src/panels/mod.rs` (`empty_message`, `empty_state`), `crates/ui-egui/src/panels/empty_library.rs`, `cmd:file.addPhotos`, `cmd:file.importLightroom`, `crates/ui-egui/src/tests_empty_library.rs` | each view says why it is empty (no photo selected, filters, an empty folder). A library with no photos (none, or only deleted or browsed ones) opens on the Photo Grid (Square Grid stays) with the sidebar, and the grid and Detail view (not while a folder is browsed under Local) offer Import Photos… (primary) and Import Lightroom Catalog… (desktop) as buttons, with a line saying photos and folders can be dropped into the window and the key Import Photos… is bound to now; the right-hand panel says to import photos first. The top bar has an Import button beside Export in every library. Files dragged over the window dim it and a card says what dropping will do; a drop of photos or folders opens the same import review as File ▸ Import | | LR-BEHAV-TOOLTIPS | Tooltips with shortcuts | P0 | ✅ | `crates/ui-egui/src/panels/bottombar.rs` | | | LR-BEHAV-TEXTFIELD | Text fields behave alike | P1 | 🟡 | `crates/ui-egui/src/text_field.rs`, `crates/ui-egui/src/panels/topbar.rs`, `crates/ui-egui/src/widgets.rs`, `crates/ui-egui/src/panels/right.rs` (`meta_field`), `crates/ui-egui/src/panels/dialogs.rs`, `crates/ui-egui/src/panels/unnamed.rs` | one shared field: right-click Cut / Copy / Paste / Select All (no Paste in the browser), Esc gives back the text from before the edit, Return / leaving / Esc reported to the caller, optional select-on-focus; agents use `ui.clipboard` (MCP `clipboard`) and `ui.inspect` → `copied`. Used by Search Photos, slider values, the Info panel's metadata fields (multi-line captions), the one-field dialogs (New / Rename Album, New Smart Album, Rename / Merge Keywords, text prompts) and the unnamed faces' name field so far; the other text fields (most dialogs, import, settings, masking, keywords …) still use egui's own and have no menu | @@ -605,7 +605,7 @@ From `06-shortcuts.md` part 1. Evidence is our binding; conflicts are explained | KEY-FULLSCREEN | Full-screen preview — F | P1 | ✅ | `cmd:view.fullScreenPreview` | | | KEY-LIGHTSOUT | Lights Out — Shift+L (Classic's L is Linear Gradient here) | P2 | ✅ | `cmd:view.lightsOut` | On → Dim (80 %) → Off; Esc turns the lights on | | KEY-GRID | Grid — G | P0 | ✅ | `cmd:view.gridToggle`, `cmd:view.photoGrid` | G toggles Photo Grid ↔ Square Grid; both View menu rows show its live shortcut (including remapping/unbinding), with direct grid bindings taking priority; menu clicks still choose the named grid (#2500) | -| KEY-INFO | Info — I | P0 | ✅ | `cmd:panel.info` | | +| KEY-INFO | Info — I | P0 | ✅ | `cmd:panel.info`, `crates/ui-egui/src/tests_panel_restore.rs` | pressing I again brings back exactly what the right column showed before (Edit, Masks…; closed stays closed); every panel key and button does the same (`UiState::toggle_panel`) | | KEY-KEYWORDS | Keywords — K | P0 | ✅ | `cmd:panel.keywords` | | | KEY-CLIPBOARD | Copy / paste edit settings — ⌘C / ⌘V | P0 | ✅ | `cmd:develop.copy`, `cmd:develop.paste`, `crates/ui-egui/src/shortcuts.rs` (`matches`) | ⌘X has nothing to cut outside text fields; on Windows and Linux, where the windowing layer sends Ctrl+C / Ctrl+V as clipboard events rather than key presses, those run the shortcuts too (⇧Insert pastes plainly); there Ctrl+V only arrives while the system clipboard holds text (egui-winit drops it otherwise), so with an empty clipboard Paste Settings needs the menu | | KEY-UNDOREDO | Undo / redo — ⌘Z / ⇧⌘Z | P0 | ✅ | `cmd:edit.undo`, `cmd:edit.redo` | | @@ -799,6 +799,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | LR-BEHAV-PANEL-RESIZE, KEY-INFO: closing a tool panel (Crop, Remove, Masking, Red Eye) puts back the panel shown before it, hidden if it was hidden, at the same width and scroll position; a panel key or button (I, M, C, H…) pressed again puts back exactly what the right column showed before it (Edit → I → I = Edit, closed → I → I = closed); status 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 🟡) | | 2026-10-24 | patch | LR-LIB-RATING, LR-LIB-DELETE: a slider drag still open when a rating, flag or label takes the photo out of the view, or when the photo is deleted, ends as its own undo step before the selection moves on, as moving to the next photo does; LR-BEHAV-LOCALIZE lists all 18 languages; status unchanged | diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c2592003..b2d5a5ae1b 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,13 @@ # What's new in LightCraft +## 2026-10-26 + +### Panels come back as they were +- Close Masking, Crop, Remove or Red Eye and the panel you came from is there again, at the same width and scroll + position, and the photo doesn't move; if the panel was hidden, it stays hidden. Pressing a panel key a second time + (I for Info, M for Masking, C for Crop, H for Remove) or its tool-strip button puts back exactly what the right + column showed before: Edit → I → I is Edit again, Masks → I → I is Masks, and a closed panel stays closed. + ## 2026-10-24 ### Relative-date filters and smart albums follow the clock From 426fc030349a81c7c810fa7b99deb928fcf16ee3 Mon Sep 17 00:00:00 2001 From: Adrian D'souza Date: Mon, 26 Oct 2026 11:07:02 +1100 Subject: [PATCH 25/98] LR-MERGE-HDRPANO: a repeated identical HDR merge reuses the verified output Running Photo Merge > HDR again on the same sources with the same options created a duplicate output. The merge now reuses the earlier output when it still matches (same sources, options and an intact file), and refuses a stale or duplicate reuse, producing a fresh merge instead. Existing edits on the output are left alone. Fixes #430. Refs #1947. Sources: own design. (cherry picked from commit 3267132d3e39672a8dc8c0905d9fd17966232fe4) (cherry picked from commit 101efb1ae0e4debe6e3cf4c232d62e24a4cde3d3) (cherry picked from commit 6459531cfb967943359d415c60a6570000c304af) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/merge.rs | 73 +++++++++++++++++++++++++------- crates/engine/src/tests_merge.rs | 70 +++++++++++++++++++++++++++--- 2 files changed, 122 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/merge.rs b/crates/engine/src/merge.rs index 76bcfd7f29..8dd26533c8 100644 --- a/crates/engine/src/merge.rs +++ b/crates/engine/src/merge.rs @@ -430,29 +430,72 @@ impl Session { /// apply Auto Settings / the auto crop. Returns `{id, path, …info}`. pub fn finish_merge(&mut self, job: &MergeJob, out: MergeOutput) -> Result { let first = &job.sources.first().ok_or_else(|| EngineError::Other("nothing merged".into()))?.1; - // a new file under a free name (never replacing one), complete and synced before it appears - let path = lightcraft_catalog::safe_file::write_new_unique(&mut output_names(first, job.kind.suffix()), &out.dng) - .map_err(|e| EngineError::Other(format!("could not write the merged DNG next to {first}: {e}")))? - .to_string_lossy() - .to_string(); - let report = crate::import::import(self, std::slice::from_ref(&path), crate::import::ImportMode::Add)?; - let id = report - .imported - .first() - .copied() - .map(PhotoId) - .ok_or_else(|| EngineError::Other(format!("the merged file {path} could not be imported: {:?}", report.failed)))?; - if job.finish.stack { + let output_hash = lightcraft_preview::hash_bytes(&out.dng).to_string(); + // Import deduplicates by content. Reuse an existing merge only while its live source has + // matching bytes; stale, missing or deleted rows fail before another file is published. + let candidates: Vec<(PhotoId, String, bool)> = self + .catalog + .photos() + .filter_map(|p| { + if p.content_hash.as_deref() != Some(output_hash.as_str()) { + return None; + } + let Source::File { path } = &p.source else { return None }; + Some((p.id, path.clone(), p.deleted)) + }) + .collect(); + let valid_existing = candidates + .iter() + .find(|(_, path, deleted)| { + if *deleted { + return false; + } + let bytes = match &self.media.file_bytes { + Some(read) => read(path).ok(), + None => std::fs::read(path).ok(), + }; + bytes.is_some_and(|bytes| lightcraft_preview::hash_bytes(&bytes).to_string() == output_hash) + }) + .cloned(); + let (id, path, reused) = if let Some((id, path, _)) = valid_existing { + (id, path, true) + } else if let Some((id, path, deleted)) = candidates.first() { + let state = if *deleted { "deleted" } else { "missing or changed" }; + return Err(EngineError::Other(format!( + "existing merge result {id:?} has a {state} source at {path}; relink or remove it before repeating the merge" + ))); + } else { + // A new file under a free name (never replacing one), complete and synced before it appears. + let path = lightcraft_catalog::safe_file::write_new_unique(&mut output_names(first, job.kind.suffix()), &out.dng) + .map_err(|e| EngineError::Other(format!("could not write the merged DNG next to {first}: {e}")))? + .to_string_lossy() + .to_string(); + let report = match crate::import::import(self, std::slice::from_ref(&path), crate::import::ImportMode::Add) { + Ok(report) => report, + Err(e) => { + let _ = std::fs::remove_file(&path); + return Err(e); + } + }; + if let Some(id) = report.imported.first().copied().map(PhotoId) { + (id, path, false) + } else { + let _ = std::fs::remove_file(&path); + return Err(EngineError::Other(format!("the merged file {path} could not be imported: {:?}", report.failed))); + } + }; + if !reused && job.finish.stack { let sources: Vec = job.sources.iter().map(|(p, _)| *p).collect(); if let Some(op) = self.catalog.stack_with_ops(id, &sources) { self.commit("Stack with Sources", op)?; } } self.selection = crate::Selection::single(id); - if job.finish.auto_settings { + if !reused && job.finish.auto_settings { self.execute("develop.auto", &json!({}))?; } - if let Some(c) = out.crop + if !reused + && let Some(c) = out.crop && let Some(d) = self.develop_of(id) { let mut d = (*d).clone(); diff --git a/crates/engine/src/tests_merge.rs b/crates/engine/src/tests_merge.rs index ed524ae3d2..550a550f9d 100644 --- a/crates/engine/src/tests_merge.rs +++ b/crates/engine/src/tests_merge.rs @@ -55,15 +55,24 @@ fn hdr_merge_command_creates_and_imports_a_dng() { assert_eq!(st.photos[1..].iter().map(|p| p.0).collect::>(), ids); assert!(st.collapsed); assert_eq!(s.visible_cloned(), vec![id]); - // the second merge doesn't overwrite the first - let r2 = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": false})).unwrap(); - assert!(r2["path"].as_str().unwrap().ends_with("IMG_0-HDR-2.dng")); - let id2 = lightcraft_catalog::PhotoId(r2["id"].as_u64().unwrap()); - assert!(s.catalog.stack_of(id2).is_none(), "no stack without the option"); + // A repeated deterministic merge reuses the existing content instead of publishing an + // unimported uniquely named orphan. + s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.73})).unwrap(); + let edited = s.develop_of(id).unwrap().as_ref().clone(); + let stack_before = s.catalog.stack_of(id).unwrap().clone(); + let undo_before = s.undo.len(); + let r2 = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true, "stack": true})).unwrap(); + assert_eq!(r2["id"].as_u64(), Some(id.0)); + assert_eq!(r2["path"].as_str(), Some(path)); + assert!(!dir.join("IMG_0-HDR-2.dng").exists(), "duplicate merge left an orphan"); + assert_eq!(s.catalog.photos().count(), 4); + assert_eq!(s.undo.len(), undo_before, "reusing merge content added an undo step"); + assert_eq!(s.develop_of(id).unwrap().as_ref(), &edited, "reusing merge content changed edits"); + assert_eq!(s.catalog.stack_of(id), Some(&stack_before), "reusing merge content changed stack"); // the type filter finds merge results (and only them) s.execute("library.filter", &json!({"merged": "hdr"})).unwrap(); let found: std::collections::HashSet<_> = s.catalog.query(&s.filter, &Default::default()).into_iter().collect(); - assert_eq!(found, [id, id2].into_iter().collect()); + assert_eq!(found, [id].into_iter().collect()); let _ = std::fs::remove_dir_all(&dir); } @@ -143,6 +152,55 @@ fn a_merge_of_raws_without_colour_matrices_keeps_their_colour() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn hdr_merge_refuses_stale_result_before_writing() { + let dir = temp_dir("hdr-stale"); + let mut paths = Vec::new(); + for (i, b) in lightcraft_merge::synth::bracket_dngs(240, 160, &[-2.0, 0.0, 2.0]).unwrap().into_iter().enumerate() { + let p = dir.join(format!("IMG_{i}.dng")); + std::fs::write(&p, b).unwrap(); + paths.push(p.to_string_lossy().to_string()); + } + let mut s = Session::new().with_fs(); + let ids = import(&mut s, paths.clone()); + let first = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": false})).unwrap(); + let id = lightcraft_catalog::PhotoId(first["id"].as_u64().unwrap()); + let path = first["path"].as_str().unwrap().to_string(); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.73})).unwrap(); + let edited = s.develop_of(id).unwrap().as_ref().clone(); + let stack_before = s.catalog.stack_of(id).cloned(); + + std::fs::remove_file(&path).unwrap(); + let undo_before = s.undo.len(); + let missing = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true})); + assert!(missing.as_ref().unwrap_err().to_string().contains("missing or changed")); + assert!(!std::path::Path::new(&path).exists()); + assert!(!dir.join("IMG_0-HDR-2.dng").exists()); + assert_eq!(s.undo.len(), undo_before); + assert_eq!(s.develop_of(id).unwrap().as_ref(), &edited, "repair changed edits"); + assert_eq!(s.catalog.stack_of(id).cloned(), stack_before); + + std::fs::write(&path, std::fs::read(&paths[0]).unwrap()).unwrap(); + let changed_bytes = std::fs::read(&path).unwrap(); + let changed = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true})); + assert!(changed.as_ref().unwrap_err().to_string().contains("missing or changed")); + assert_eq!(std::fs::read(&path).unwrap(), changed_bytes); + assert!(!dir.join("IMG_0-HDR-2.dng").exists()); + assert_eq!(s.undo.len(), undo_before); + assert_eq!(s.develop_of(id).unwrap().as_ref(), &edited, "changed-source repair changed edits"); + assert_eq!(s.catalog.stack_of(id).cloned(), stack_before); + + s.execute("photo.delete", &json!({"ids": [id.0]})).unwrap(); + let deleted_bytes = std::fs::read(&path).unwrap(); + let undo_after_delete = s.undo.len(); + let failed = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": false})); + assert!(failed.as_ref().unwrap_err().to_string().contains("deleted")); + assert_eq!(std::fs::read(&path).unwrap(), deleted_bytes); + assert!(!dir.join("IMG_0-HDR-3.dng").exists(), "failed import left an orphan"); + assert_eq!(s.undo.len(), undo_after_delete); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn panorama_command_with_auto_crop() { let dir = temp_dir("pano"); From 824395025b31afdb6d689287e5ad1137f4a0355c Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Mon, 26 Oct 2026 11:17:48 +1100 Subject: [PATCH 26/98] security(codecs): refuse decodes with no pixels; checked JPEG sample counts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `decode_unguarded` returns `Malformed` for an image of zero width or height or a buffer shorter than its size, so nothing downstream receives an empty image. - The JPEG short-output checks compute w × h × channels with `checked_sample_buf_len` instead of a `usize` product that wraps on wasm32. Refs #2579 Co-Authored-By: Claude Opus 5.5 --- crates/codecs/src/jpeg.rs | 6 ++++-- crates/codecs/src/lib.rs | 9 ++++++++- crates/codecs/tests/it/fuzz.rs | 16 ++++++++++++++++ 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/crates/codecs/src/jpeg.rs b/crates/codecs/src/jpeg.rs index d8b0241a13..ae9a1a61ae 100644 --- a/crates/codecs/src/jpeg.rs +++ b/crates/codecs/src/jpeg.rs @@ -226,7 +226,7 @@ fn decode_zune(bytes: &[u8], m: &Markers, budget: &DecodeOptions) -> Result let info = d.info().ok_or_else(|| Error::Malformed(F, "no info".into()))?; let (w, h) = (info.width as usize, info.height as usize); let model = if gray { Model::Gray } else { Model::Rgb }; - if px.len() < w * h * model.channels() { + if crate::checked_sample_buf_len(w, h, model.channels()).is_none_or(|n| (px.len() as u64) < n) { return Err(Error::Malformed(F, "short output".into())); } Ok(Raw { width: w, height: h, model, alpha: false, premultiplied: false, buf: Buf::U8(px), bit_depth: 8 }) @@ -403,7 +403,9 @@ pub(crate) fn decode_codes8(bytes: &[u8]) -> Result<(usize, usize, usize, Vec= raw.width * raw.height * ch => Ok((raw.width, raw.height, ch, v)), + Buf::U8(v) if crate::checked_sample_buf_len(raw.width, raw.height, ch).is_some_and(|n| v.len() as u64 >= n) => { + Ok((raw.width, raw.height, ch, v)) + } _ => Err(Error::Malformed(F, "unexpected sample format".into())), } } diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index a20a47d14c..f4fd1a8567 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -230,7 +230,7 @@ pub fn decode_unguarded(bytes: &[u8], format: Format, opts: &DecodeOptions) -> R let opts = *opts; // The reason a format can't be decoded lives in one place, `Format::not_decodable`. let unsupported = || Err(Error::Unsupported(format, format.not_decodable().unwrap_or("not decodable in this build"))); - match format { + let d = match format { Format::Jpeg => jpeg::decode(bytes, &opts), Format::Png => png_codec::decode(bytes, &opts), Format::Tiff => tiff_codec::decode(bytes, &opts), @@ -243,7 +243,14 @@ pub fn decode_unguarded(bytes: &[u8], format: Format, opts: &DecodeOptions) -> R Format::Jxl => unsupported(), Format::Heif => heif::decode(bytes, &opts), Format::Avif | Format::RawTiffLike | Format::RawOther => unsupported(), + }?; + // an image with no pixels (a malformed header claiming zero width or height, or a buffer + // shorter than its size) is refused here, so nothing downstream sees an empty image + let (w, h) = (d.image.width, d.image.height); + if w == 0 || h == 0 || w.checked_mul(h).is_none_or(|n| d.image.data.len() < n) { + return Err(Error::Malformed(format, "image has no pixels".into())); } + Ok(d) } /// Convert a decode result to linear Rec.2020 D65 (Bradford-adapted), the develop working space. diff --git a/crates/codecs/tests/it/fuzz.rs b/crates/codecs/tests/it/fuzz.rs index bfee84dfe4..d79bd7bd36 100644 --- a/crates/codecs/tests/it/fuzz.rs +++ b/crates/codecs/tests/it/fuzz.rs @@ -85,6 +85,22 @@ fn thumbnail_respects_configured_source_pixel_limit() { assert_eq!(decode_thumbnail_with(&bytes, &opts).unwrap().image.width, 1); } +/// A header claiming zero width or height is an error, never a decoded image with no pixels +/// (downstream filters index into it). +#[test] +fn zero_size_headers_are_refused() { + let jpeg = seeds()[0].clone(); + let sof = jpeg.windows(2).position(|m| m == [0xFF, 0xC0]).unwrap(); + for at in [sof + 5, sof + 7] { + let mut j = jpeg.clone(); + j[at..at + 2].copy_from_slice(&[0, 0]); + assert!(decode_unguarded(&j, Format::Jpeg, &small_opts()).is_err()); + } + let mut png = seeds()[1].clone(); + png[16..20].copy_from_slice(&[0; 4]); + assert!(decode_unguarded(&png, Format::Png, &small_opts()).is_err()); +} + fn seeds() -> &'static Vec> { static S: OnceLock>> = OnceLock::new(); S.get_or_init(|| { From 9d09ba4941c6431c5b2ed09aebc2c6545b310f0f Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Mon, 26 Oct 2026 11:47:06 +1100 Subject: [PATCH 27/98] LR-MERGE-HDRPANO: the merge result reports whether it reused an earlier output CLI, MCP and control-channel callers can now tell a reused result (edits kept, autoSettings/stack/auto-crop skipped) from a fresh merge. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/merge.rs | 1 + crates/engine/src/tests_merge.rs | 2 ++ 2 files changed, 3 insertions(+) diff --git a/crates/engine/src/merge.rs b/crates/engine/src/merge.rs index 8dd26533c8..70ad1328fb 100644 --- a/crates/engine/src/merge.rs +++ b/crates/engine/src/merge.rs @@ -506,6 +506,7 @@ impl Session { info["id"] = json!(id.0); info["path"] = json!(path); info["bytes"] = json!(out.dng.len()); + info["reused"] = json!(reused); Ok(info) } diff --git a/crates/engine/src/tests_merge.rs b/crates/engine/src/tests_merge.rs index 550a550f9d..7c30379ed7 100644 --- a/crates/engine/src/tests_merge.rs +++ b/crates/engine/src/tests_merge.rs @@ -40,6 +40,7 @@ fn hdr_merge_command_creates_and_imports_a_dng() { let r = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true, "stack": true})).unwrap(); let path = r["path"].as_str().unwrap(); assert!(path.ends_with("IMG_0-HDR.dng"), "{path}"); + assert_eq!(r["reused"].as_bool(), Some(false)); let id = lightcraft_catalog::PhotoId(r["id"].as_u64().unwrap()); let p = s.catalog.photo(id).unwrap().clone(); assert_eq!((p.width, p.height), (480, 320)); @@ -63,6 +64,7 @@ fn hdr_merge_command_creates_and_imports_a_dng() { let undo_before = s.undo.len(); let r2 = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true, "stack": true})).unwrap(); assert_eq!(r2["id"].as_u64(), Some(id.0)); + assert_eq!(r2["reused"].as_bool(), Some(true)); assert_eq!(r2["path"].as_str(), Some(path)); assert!(!dir.join("IMG_0-HDR-2.dng").exists(), "duplicate merge left an orphan"); assert_eq!(s.catalog.photos().count(), 4); From 0f17c6f3eb5f63f7a3a1261fca33168ddb08a6d5 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Mon, 26 Oct 2026 15:11:41 +1000 Subject: [PATCH 28/98] KEY-INFO: main's docking test expects Crop toggled off to give back the panel it replaced Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/tests_docking_acceptance.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tests_docking_acceptance.rs b/crates/ui-egui/src/tests_docking_acceptance.rs index 207ad5fae8..e0c274e45e 100644 --- a/crates/ui-egui/src/tests_docking_acceptance.rs +++ b/crates/ui-egui/src/tests_docking_acceptance.rs @@ -185,6 +185,7 @@ fn dock_tab_keeps_activation_keys_and_global_command_remains_reachable() { let mut h = app(); h.app.run("app.setShortcut", json!({"id":"panel.crop","shortcut":"K"})).unwrap(); dock(&mut h, json!({"operation":"move","panel":"tools","target":"library","zone":"center"})); + let before = h.app.ui.right; h.app.run("panel.crop", json!({})).unwrap(); h.step(); // The test chooses the renderer's actual registered tab, rather than an arbitrary focus owner. @@ -194,7 +195,9 @@ fn dock_tab_keeps_activation_keys_and_global_command_remains_reachable() { key(&mut h, egui::Key::Enter); assert_eq!(h.app.ui.right, RightPanel::Crop, "Enter activates the tab without tool.done"); key(&mut h, egui::Key::K); - assert_eq!(h.app.ui.right, RightPanel::None, "the global crop toggle is reachable from tab focus"); + // toggled off, Crop gives back the panel it took the place of (KEY-INFO / UiState::toggle_panel) + assert_eq!(h.app.ui.right, before, "the global crop toggle is reachable from tab focus"); + assert_ne!(before, RightPanel::Crop); } #[test] From a016dca0b540237f92d751c373236c4f6510392d Mon Sep 17 00:00:00 2001 From: OneSlips Date: Mon, 26 Oct 2026 15:35:16 +1000 Subject: [PATCH 29/98] KEY-INFO: a ui.set between the two presses keeps the pending panel toggle (CodeRabbit, #3031) ui.set copied tool_return and right_seen into the new UiState but not toggle_return, so Edit -> I -> ui.set -> I closed the column. Also a test that a tool panel restored from saved state closes to Edit. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/control.rs | 2 ++ crates/ui-egui/src/tests_panel_restore.rs | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 5e43b1477a..030c4be1c8 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -403,6 +403,8 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest // the panel a tool panel took the place of, to put back when it closes, survives a ui.set u.tool_return = app.ui.tool_return; u.right_seen = app.ui.right_seen; + // (and what a panel toggle replaced, so pressing its key again still puts that back) + u.toggle_return = app.ui.toggle_return; u.dialog = app.ui.dialog.clone(); u.status = app.ui.status.clone(); crate::docking::cancel_replaced_gesture(app, u.docking.as_ref()); diff --git a/crates/ui-egui/src/tests_panel_restore.rs b/crates/ui-egui/src/tests_panel_restore.rs index 640428a6c9..a90663ea87 100644 --- a/crates/ui-egui/src/tests_panel_restore.rs +++ b/crates/ui-egui/src/tests_panel_restore.rs @@ -143,3 +143,26 @@ fn info_toggled_off_brings_back_exactly_what_was_there() { key(&mut h); assert_eq!(h.app.ui.right, RightPanel::None, "closed → I → I = closed"); } + +/// A `ui.set` that changes something else (here the panel width) keeps a pending toggle: I still puts Edit back +/// (CodeRabbit on #3031). +#[test] +fn a_ui_set_between_the_two_presses_keeps_the_toggle() { + let mut h = detail(); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Info); + let r = h.request("ui.set", json!({"rightWidth": 320.0}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Edit, "Edit → I → ui.set → I = Edit"); +} + +/// A tool panel restored from the saved UI state (the panel before it unknown) closes to Edit, not to a hidden column. +#[test] +fn a_tool_restored_from_saved_state_closes_to_edit() { + let mut ui: crate::state::UiState = serde_json::from_str(r#"{"right": "crop"}"#).unwrap(); + assert_eq!(ui.right, RightPanel::Crop); + ui.note_right(); + assert_eq!(ui.leave_tool(), RightPanel::Edit); +} From a9afb1868c069257741214c35776b77464074d67 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Tue, 27 Oct 2026 17:31:27 +1100 Subject: [PATCH 30/98] test(codecs): test the no-pixels guard and checked JPEG sample count directly Moves the final-output check into check_has_pixels and tests it with zero width, zero height, an overflowing w*h and a short RGB buffer (fails when the guard is removed). Adds the 65535x21846x3 case a 32-bit usize product wraps. The PNG zero-dimension fixture now repairs its IHDR CRC and covers height too. Co-Authored-By: Claude Opus 5.5 --- crates/codecs/src/lib.rs | 41 +++++++++++++++++++++++++++++----- crates/codecs/tests/it/fuzz.rs | 27 +++++++++++++++++++--- 2 files changed, 60 insertions(+), 8 deletions(-) diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index f4fd1a8567..07d895a985 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -244,13 +244,19 @@ pub fn decode_unguarded(bytes: &[u8], format: Format, opts: &DecodeOptions) -> R Format::Heif => heif::decode(bytes, &opts), Format::Avif | Format::RawTiffLike | Format::RawOther => unsupported(), }?; - // an image with no pixels (a malformed header claiming zero width or height, or a buffer - // shorter than its size) is refused here, so nothing downstream sees an empty image - let (w, h) = (d.image.width, d.image.height); - if w == 0 || h == 0 || w.checked_mul(h).is_none_or(|n| d.image.data.len() < n) { + check_has_pixels(format, &d.image)?; + Ok(d) +} + +/// An image with no pixels (a malformed header claiming zero width or height, a `w × h` that +/// overflows, or a buffer shorter than its size) is refused, so nothing downstream sees an empty +/// image. +fn check_has_pixels(format: Format, image: &Rgb32f) -> Result<()> { + let (w, h) = (image.width, image.height); + if w == 0 || h == 0 || w.checked_mul(h).is_none_or(|n| image.data.len() < n) { return Err(Error::Malformed(format, "image has no pixels".into())); } - Ok(d) + Ok(()) } /// Convert a decode result to linear Rec.2020 D65 (Bradford-adapted), the develop working space. @@ -370,4 +376,29 @@ mod checked_arithmetic_tests { // 300 Mpx RGBA is within the default pixel limit, so it must not be refused by sample count. assert_eq!(checked_sample_buf_len(20_000, 15_000, 4), Some(1_200_000_000)); } + + #[test] + fn checked_sample_buf_len_does_not_wrap_like_32_bit_usize() { + // 65535 × 21846 × 3 = 4_295_032_830, which a 32-bit `usize` product wraps to 65_534 + assert_eq!(checked_sample_buf_len(65_535, 21_846, 3), Some(4_295_032_830)); + assert!(checked_sample_buf_len(65_535, 21_846, 3).is_some_and(|n| n > 65_534)); + } + + fn image(width: usize, height: usize, len: usize) -> Rgb32f { + Rgb32f { width, height, data: vec![[0.0; 3]; len] } + } + + #[test] + fn decoded_image_without_pixels_is_refused() { + for (w, h, len) in [(0, 4, 0), (4, 0, 0), (usize::MAX, 2, 1), (4, 4, 15)] { + let r = check_has_pixels(Format::Png, &image(w, h, len)); + assert!(matches!(r, Err(Error::Malformed(Format::Png, _))), "{w}x{h} with {len} pixels"); + } + } + + #[test] + fn decoded_image_with_all_pixels_is_accepted() { + assert!(check_has_pixels(Format::Png, &image(4, 4, 16)).is_ok()); + assert!(check_has_pixels(Format::Png, &image(1, 1, 1)).is_ok()); + } } diff --git a/crates/codecs/tests/it/fuzz.rs b/crates/codecs/tests/it/fuzz.rs index d79bd7bd36..0fa56101eb 100644 --- a/crates/codecs/tests/it/fuzz.rs +++ b/crates/codecs/tests/it/fuzz.rs @@ -88,6 +88,9 @@ fn thumbnail_respects_configured_source_pixel_limit() { /// A header claiming zero width or height is an error, never a decoded image with no pixels /// (downstream filters index into it). #[test] +// End-to-end no-panic check: headers claiming a zero dimension are errors. The JPEG and PNG +// readers already refuse these; `decode_unguarded`'s own final-output guard is tested directly in +// the crate's unit tests. fn zero_size_headers_are_refused() { let jpeg = seeds()[0].clone(); let sof = jpeg.windows(2).position(|m| m == [0xFF, 0xC0]).unwrap(); @@ -96,9 +99,27 @@ fn zero_size_headers_are_refused() { j[at..at + 2].copy_from_slice(&[0, 0]); assert!(decode_unguarded(&j, Format::Jpeg, &small_opts()).is_err()); } - let mut png = seeds()[1].clone(); - png[16..20].copy_from_slice(&[0; 4]); - assert!(decode_unguarded(&png, Format::Png, &small_opts()).is_err()); + let png = seeds()[1].clone(); + for at in [16, 20] { + let mut p = png.clone(); + p[at..at + 4].copy_from_slice(&[0; 4]); + // repair the IHDR CRC so the dimension, not the checksum, is what gets refused + let crc = crc32(&p[12..29]); + p[29..33].copy_from_slice(&crc.to_be_bytes()); + assert!(decode_unguarded(&p, Format::Png, &small_opts()).is_err()); + } +} + +/// CRC-32 (IEEE), as PNG chunks use. +fn crc32(bytes: &[u8]) -> u32 { + let mut c = !0u32; + for &b in bytes { + c ^= u32::from(b); + for _ in 0..8 { + c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }; + } + } + !c } fn seeds() -> &'static Vec> { From 4371ac5860376405e450e38ed7f2888251ab4529 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Wed, 28 Oct 2026 07:17:18 +1000 Subject: [PATCH 31/98] KEY-INFO: the Keywords panel scrolls under one id with or without a selection; KEY-COMMIT row says where Return goes Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/menus/run.rs | 2 +- crates/ui-egui/src/panels/right.rs | 10 ++++++++-- crates/ui-egui/src/panels/right/tests.rs | 11 +++++++++++ docs/parity-checklist.md | 2 +- 4 files changed, 21 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index df3816449f..0b734be463 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1021,7 +1021,7 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option { - // Return commits a tool panel (crop, remove, red eye, masking): back to Edit + // Return commits a tool panel (crop, remove, red eye, masking): back to the panel before it use RightPanel::*; if app.ui.dialog.is_none() && matches!(app.ui.right, Crop | Remove | RedEye | Masking) { let _ = app.session.end_interaction(); diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index 4fee12e4f6..1b2f5266f1 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -28,6 +28,12 @@ use info::info; pub(crate) use info::mixed_meta; use keywords::keywords; +/// The right column's scroll area for `panel`: one per panel, the same with or without a selected photo (the +/// Keywords panel shows its list either way). +fn scroll_salt(panel: RightPanel) -> (&'static str, RightPanel) { + ("right-scroll", panel) +} + pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); let frame = egui::Frame::NONE.fill(t.chrome).stroke(egui::Stroke::new(1.0, t.divider)); @@ -39,7 +45,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if app.ui.right == RightPanel::Keywords { // (without a selection there is no Add keyword box for Add Keywords to put the cursor in) app.ui.focus_keywords = None; - egui::ScrollArea::vertical().id_salt("right-scroll").auto_shrink([false, false]).show(ui, |ui| { + egui::ScrollArea::vertical().id_salt(scroll_salt(RightPanel::Keywords)).auto_shrink([false, false]).show(ui, |ui| { ui.spacing_mut().item_spacing.y = 0.0; if fold_header(app, ui, "keywording", "Keywords") { padded(ui, |ui| { @@ -60,7 +66,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { return; }; // each panel keeps its own scroll position: Edit is where it was after Masking or Crop - let mut area = egui::ScrollArea::vertical().id_salt(("right-scroll", app.ui.right)).auto_shrink([false, false]); + let mut area = egui::ScrollArea::vertical().id_salt(scroll_salt(app.ui.right)).auto_shrink([false, false]); if let Some(offset) = held { area = area.vertical_scroll_offset(offset); } diff --git a/crates/ui-egui/src/panels/right/tests.rs b/crates/ui-egui/src/panels/right/tests.rs index 1f1d60d609..482cdfceb0 100644 --- a/crates/ui-egui/src/panels/right/tests.rs +++ b/crates/ui-egui/src/panels/right/tests.rs @@ -30,3 +30,14 @@ fn short_times() { assert_eq!(super::short_time("2026-09-30T12:00:05"), "Sep 30, 2026, 12:00 PM"); assert_eq!(super::short_time("2026-01-02"), "Jan 2, 2026"); } + +// Feature: the Keywords panel keeps its scroll position when a photo is selected (CodeRabbit on #3031: the +// no-selection list scrolled under another id) +#[test] +fn the_keywords_panel_scrolls_under_one_id_with_or_without_a_selection() { + use crate::state::RightPanel; + // (`show` names the no-selection list's scroll area by `scroll_salt(RightPanel::Keywords)`, as it names the + // panel's with a selection by `scroll_salt(app.ui.right)`) + assert_eq!(super::scroll_salt(RightPanel::Keywords), ("right-scroll", RightPanel::Keywords)); + assert_ne!(super::scroll_salt(RightPanel::Keywords), super::scroll_salt(RightPanel::Edit), "each panel keeps its own"); +} diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 288d9213f7..c0d196b3f1 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -681,7 +681,7 @@ From `06-shortcuts.md` part 1. Evidence is our binding; conflicts are explained | KEY-HELP | Help — F1 | P2 | ✅ | `cmd:app.help` | | | KEY-VIDEO-PLAY | Play/pause video — Space | P1 | ⬜ | | | | KEY-ESC | Leave tool / view — Esc | P0 | ✅ | `cmd:view.back`, `crates/ui-egui/src/icons.rs` (`navigation_arrowheads_have_both_halves`), `crates/ui-egui/src/tests/crop_tool.rs` | top-bar navigation arrowheads render both halves at 1× and 2× scale; in the crop tool Esc closes the tool first (the crop stays), the next Esc goes back to the grid; Esc that ends an edit in a text field does nothing else | -| KEY-COMMIT | Commit tool — Return | P1 | ✅ | `cmd:tool.done` | Return closes Crop / Remove / Red Eye / Masking back to Edit (edits apply live, as in Lightroom) | +| KEY-COMMIT | Commit tool — Return | P1 | ✅ | `cmd:tool.done` | Return closes Crop / Remove / Red Eye / Masking and goes back to the panel shown before the tool, the right column hidden again if it was (edits apply live, as in Lightroom) | | KEY-DELETE-PIN | Delete selected pin — ⌫ | P0 | ✅ | `cmd:mask.delete`, `cmd:spot.delete` | ⌫ deletes the active mask (Masking) or the selected spot (Remove), never the photo while retouching | | KEY-HIDEPINS | Hide pins — H | P2 | ✅ | `cmd:view.toolOverlay`, `crates/ui-egui/src/tests/tool_overlay.rs` | ⇧H cycles the Tool Overlay (Auto → Always → Selected → Never) for spot and mask pins, since H opens Remove; also View ▸ Tool Overlay and the Remove / Masking panels (#224) | From ef01264ca77a91ec3033407323949ab3a96e5cda Mon Sep 17 00:00:00 2001 From: OneSlips Date: Wed, 28 Oct 2026 08:39:14 +1000 Subject: [PATCH 32/98] KEY-INFO: the panel-restore test covers Red Eye too Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/tests/panel_restore.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tests/panel_restore.rs b/crates/ui-egui/src/tests/panel_restore.rs index a90663ea87..1793e09529 100644 --- a/crates/ui-egui/src/tests/panel_restore.rs +++ b/crates/ui-egui/src/tests/panel_restore.rs @@ -59,7 +59,7 @@ fn the_edit_panel_comes_back_after_masking_and_crop_where_it_was() { } let (slider, at) = first_slider(&h); let photo = widget(&h, "canvas:image").expect("the photo"); - for tool in ["panel.masking", "panel.crop", "panel.remove"] { + for tool in ["panel.masking", "panel.crop", "panel.remove", "panel.redeye"] { exec(&mut h, tool); assert!(h.app.ui.right.is_tool(), "{tool}: {:?}", h.app.ui.right); assert_eq!(widget(&h, "panel:right_panel"), Some(panel), "{tool}: the panel keeps its place and width"); From 0b9343904ee85319e961a609c9a40fc167105ae7 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Wed, 28 Oct 2026 10:36:15 +1000 Subject: [PATCH 33/98] KEY-INFO: a tool F8 hid and showed again still closes to the panel before it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Info → Crop → F8 → F8 → Done went to a hidden column: F8's hidden column cleared the tool's return panel and the restored tool recorded the hidden column instead. note_right keeps the return panel while F8 hides the tool on show and doesn't overwrite it when F8 shows it again (CodeRabbit on #3031). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/state.rs | 8 +++++-- crates/ui-egui/src/tests/panel_restore.rs | 28 +++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 67d70746bd..3db12c0cd5 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -377,10 +377,14 @@ impl UiState { self.toggle_return = None; } if self.right.is_tool() { - if !self.right_seen.is_tool() { + // F8 showing a tool it hid: the panel before that tool still holds (`None` is F8's hidden column, not + // what the tool came from) + let back_from_f8 = self.right_seen == RightPanel::None && self.tool_return.is_some(); + if !self.right_seen.is_tool() && !back_from_f8 { self.tool_return = Some(self.right_seen); } - } else { + } else if !(self.right == RightPanel::None && self.right_seen.is_tool() && self.right_hidden == self.right_seen) { + // any panel but F8 hiding the tool on show forgets it self.tool_return = None; } self.right_seen = self.right; diff --git a/crates/ui-egui/src/tests/panel_restore.rs b/crates/ui-egui/src/tests/panel_restore.rs index 1793e09529..9b6bd89c6d 100644 --- a/crates/ui-egui/src/tests/panel_restore.rs +++ b/crates/ui-egui/src/tests/panel_restore.rs @@ -166,3 +166,31 @@ fn a_tool_restored_from_saved_state_closes_to_edit() { ui.note_right(); assert_eq!(ui.leave_tool(), RightPanel::Edit); } + +/// F8 hiding a tool and F8 showing it again keeps what the tool closes to: Info → Crop → F8 → F8 → Done = Info, not a +/// hidden column (CodeRabbit on #3031). +#[test] +fn a_tool_hidden_and_shown_by_f8_still_closes_to_the_panel_before_it() { + let mut h = detail(); + for close in ["tool.done", "panel.crop"] { + exec(&mut h, "panel.close"); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Info); + exec(&mut h, "panel.crop"); + assert_eq!(h.app.ui.right, RightPanel::Crop); + exec(&mut h, "view.rightPanel"); + assert_eq!(h.app.ui.right, RightPanel::None, "F8 hides Crop"); + exec(&mut h, "view.rightPanel"); + assert_eq!(h.app.ui.right, RightPanel::Crop, "F8 shows Crop again"); + exec(&mut h, close); + assert_eq!(h.app.ui.right, RightPanel::Info, "{close}: Info → Crop → F8 → F8 → closed = Info"); + } + // a panel picked while the tool was hidden is not undone: Crop → F8 → Masking → closed = closed, as before + exec(&mut h, "panel.close"); + exec(&mut h, "panel.crop"); + exec(&mut h, "view.rightPanel"); + exec(&mut h, "panel.info"); + exec(&mut h, "panel.masking"); + exec(&mut h, "panel.masking"); + assert_eq!(h.app.ui.right, RightPanel::Info, "a panel picked after F8 is what comes back"); +} From 04f46cf1c951d7b8201d0af359315096ab7ca701 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Wed, 28 Oct 2026 12:37:24 +1000 Subject: [PATCH 34/98] KEY-INFO: F8 keeps a tool's way back; nested panel toggles unwind one at a time (CodeRabbit, #3031) - A tool opened on the column F8 hid (Info, Crop, F8, Brush, Done) closes to the hidden column: only a tool F8 itself shows again keeps the panel it came from (an explicit `right_shown_by_f8`, consumed by `note_right`). - F8 hiding and showing a panel a toggle opened keeps its toggle record: Masking, Crop, F8, F8, Done = Masking. - Toggle records are a stack (at most 16): Edit, I, K, K, I = Edit. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/control.rs | 3 +- crates/ui-egui/src/menus/run.rs | 2 + crates/ui-egui/src/state.rs | 44 ++++++++++++----- crates/ui-egui/src/tests/panel_restore.rs | 57 +++++++++++++++++++++++ 4 files changed, 93 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 030c4be1c8..481fad16a3 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -404,7 +404,8 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest u.tool_return = app.ui.tool_return; u.right_seen = app.ui.right_seen; // (and what a panel toggle replaced, so pressing its key again still puts that back) - u.toggle_return = app.ui.toggle_return; + u.toggle_return = app.ui.toggle_return.clone(); + u.right_shown_by_f8 = app.ui.right_shown_by_f8; u.dialog = app.ui.dialog.clone(); u.status = app.ui.status.clone(); crate::docking::cancel_replaced_gesture(app, u.docking.as_ref()); diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 0b734be463..8c24c70734 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -613,6 +613,8 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option p, }; app.ui.right = p; + // (a tool shown again this way still closes to the panel before it) + app.ui.right_shown_by_f8 = Some(p); if p.is_edit_tool() && !matches!(app.ui.view, ViewMode::Detail) { app.ui.view = ViewMode::Detail; } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 3db12c0cd5..81b46c3247 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -50,15 +50,21 @@ pub struct UiState { /// The right panel F8 (`view.rightPanel`) hid, which the next F8 shows again. #[serde(skip)] pub right_hidden: RightPanel, + /// The panel F8 just showed again, until [`UiState::note_right`] sees it: a tool coming back this way still closes + /// to the panel before it, while a tool opened any other way on a hidden column closes to the hidden column. + #[serde(skip)] + pub right_shown_by_f8: Option, /// The panel on show before a tool panel ([`RightPanel::is_tool`]) took its place, put back /// when the tool closes ([`RightPanel::None`]: the panel was hidden, and stays hidden). #[serde(skip)] pub tool_return: Option, - /// The panel a toggle (a panel key or button: I, M, R, Q…) opened, with what the right column showed before it - /// and that one's [`UiState::tool_return`]: toggling it off puts back exactly that, closed included (test notes - /// 2026-10-24 note 21). Forgotten once another panel is shown. + /// The panels toggles (a panel key or button: I, M, R, Q…) opened, each with what the right column showed before + /// it and that one's [`UiState::tool_return`], the latest last: toggling the panel on show off puts back exactly + /// that, closed included (test notes 2026-10-24 note 21), and the one below it is then on show with its own + /// record (Edit → I → K → K → I = Edit). Forgotten once another panel is shown (not when F8 hides the panel and + /// shows it again). At most [`TOGGLE_HISTORY`] deep. #[serde(skip)] - pub toggle_return: Option<(RightPanel, RightPanel, Option)>, + pub toggle_return: Vec<(RightPanel, RightPanel, Option)>, /// The panel [`UiState::note_right`] last saw. #[serde(skip)] pub right_seen: RightPanel, @@ -366,20 +372,26 @@ pub struct UiState { pub print: crate::print_view::PrintUi, } +/// How many panel toggles [`UiState::toggle_return`] remembers (pressing I and K in turn would grow it without end). +pub const TOGGLE_HISTORY: usize = 16; + impl UiState { /// Notes the panel on show: a tool panel opened from another panel (or from none) remembers /// that one, to put it back when the tool closes; any other panel forgets it. pub fn note_right(&mut self) { + let shown_by_f8 = self.right_shown_by_f8.take(); if self.right == self.right_seen { return; } - if self.toggle_return.is_some_and(|(opened, ..)| opened != self.right) { - self.toggle_return = None; + // F8 hiding the panel a toggle opened keeps its record, for F8 showing it again + let f8_hid = |opened: RightPanel| self.right == RightPanel::None && self.right_hidden == opened; + if self.toggle_return.last().is_some_and(|&(opened, ..)| opened != self.right && !f8_hid(opened)) { + self.toggle_return.clear(); } if self.right.is_tool() { // F8 showing a tool it hid: the panel before that tool still holds (`None` is F8's hidden column, not - // what the tool came from) - let back_from_f8 = self.right_seen == RightPanel::None && self.tool_return.is_some(); + // what the tool came from). A tool opened another way on the hidden column came from the hidden column. + let back_from_f8 = self.right_seen == RightPanel::None && shown_by_f8 == Some(self.right); if !self.right_seen.is_tool() && !back_from_f8 { self.tool_return = Some(self.right_seen); } @@ -417,9 +429,13 @@ impl UiState { false } else { let saved = (p, if exposed || self.right != p { self.right } else { RightPanel::None }, self.tool_return); + if self.toggle_return.len() >= TOGGLE_HISTORY { + self.toggle_return.remove(0); + } + // (on the history before `note_right` sees `p`: the panel it replaced keeps its own record below it) + self.toggle_return.push(saved); self.right = p; self.note_right(); - self.toggle_return = Some(saved); true } } @@ -427,8 +443,11 @@ impl UiState { /// What the toggle that opened the panel on show replaced (see [`UiState::toggle_panel`]), with its own tool /// memory put back, or `None` when that panel wasn't opened by a toggle. fn untoggle(&mut self) -> Option { - let (_, before, tool_return) = self.toggle_return.filter(|(opened, ..)| *opened == self.right)?; - self.toggle_return = None; + let &(opened, before, tool_return) = self.toggle_return.last()?; + if opened != self.right { + return None; + } + self.toggle_return.pop(); self.tool_return = tool_return; // seen already: `note_right` must not take the panel being left for the one this came back from self.right_seen = before; @@ -454,7 +473,8 @@ impl Default for UiState { right: RightPanel::Edit, right_hidden: RightPanel::None, tool_return: None, - toggle_return: None, + toggle_return: Vec::new(), + right_shown_by_f8: None, right_seen: RightPanel::Edit, presets: false, preset_thumbs: false, diff --git a/crates/ui-egui/src/tests/panel_restore.rs b/crates/ui-egui/src/tests/panel_restore.rs index 9b6bd89c6d..678853f4db 100644 --- a/crates/ui-egui/src/tests/panel_restore.rs +++ b/crates/ui-egui/src/tests/panel_restore.rs @@ -194,3 +194,60 @@ fn a_tool_hidden_and_shown_by_f8_still_closes_to_the_panel_before_it() { exec(&mut h, "panel.masking"); assert_eq!(h.app.ui.right, RightPanel::Info, "a panel picked after F8 is what comes back"); } + +/// A tool opened another way on the column F8 hid is not F8 showing a tool again: Info → Crop → F8 → Brush → Done +/// leaves the column hidden, as it was when the brush was picked (CodeRabbit on #3031). +#[test] +fn a_tool_opened_on_the_column_f8_hid_closes_to_the_hidden_column() { + let mut h = detail(); + exec(&mut h, "panel.close"); + exec(&mut h, "panel.info"); + exec(&mut h, "panel.crop"); + exec(&mut h, "view.rightPanel"); + assert_eq!(h.app.ui.right, RightPanel::None, "F8 hides Crop"); + exec(&mut h, "tool.brush"); + assert_eq!(h.app.ui.right, RightPanel::Masking); + exec(&mut h, "tool.done"); + assert_eq!(h.app.ui.right, RightPanel::None, "Info → Crop → F8 → Brush → Done = hidden"); +} + +/// A tool opened from another tool keeps where it closes to across F8: Masking → Crop → F8 → F8 → closed = Masking, +/// and Masking then closes to Edit (CodeRabbit on #3031). +#[test] +fn a_nested_tool_hidden_and_shown_by_f8_still_closes_to_the_tool_before_it() { + let mut h = detail(); + for close in ["tool.done", "panel.crop"] { + exec(&mut h, "panel.masking"); + exec(&mut h, "panel.crop"); + assert_eq!(h.app.ui.right, RightPanel::Crop); + exec(&mut h, "view.rightPanel"); + assert_eq!(h.app.ui.right, RightPanel::None, "F8 hides Crop"); + exec(&mut h, "view.rightPanel"); + assert_eq!(h.app.ui.right, RightPanel::Crop, "F8 shows Crop again"); + exec(&mut h, close); + assert_eq!(h.app.ui.right, RightPanel::Masking, "{close}: Masking → Crop → F8 → F8 → closed = Masking"); + exec(&mut h, "panel.masking"); + assert_eq!(h.app.ui.right, RightPanel::Edit, "{close}: then Masking closes to Edit"); + } +} + +/// Toggles nest: Edit → I → K → K → I = Edit, each press taking back exactly the one before it (CodeRabbit on #3031). +#[test] +fn nested_panel_toggles_come_back_one_at_a_time() { + let mut h = detail(); + exec(&mut h, "panel.info"); + exec(&mut h, "panel.keywords"); + assert_eq!(h.app.ui.right, RightPanel::Keywords); + exec(&mut h, "panel.keywords"); + assert_eq!(h.app.ui.right, RightPanel::Info, "Keywords toggled off: Info again"); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Edit, "Info toggled off: Edit again"); + // pressing two keys in turn many times keeps a bounded history and still unwinds to a panel + for _ in 0..crate::state::TOGGLE_HISTORY { + exec(&mut h, "panel.info"); + exec(&mut h, "panel.keywords"); + } + assert!(h.app.ui.toggle_return.len() <= crate::state::TOGGLE_HISTORY); + exec(&mut h, "panel.keywords"); + assert_eq!(h.app.ui.right, RightPanel::Info); +} From 40f10cc1c0295e9b727154532c74e6fd0a18c82e Mon Sep 17 00:00:00 2001 From: OneSlips Date: Wed, 28 Oct 2026 14:42:10 +1000 Subject: [PATCH 35/98] KEY-INFO: a tool opened from another closes back to it; F8 is noted before the next command (CodeRabbit, #3031) - A tool opened by a command rather than a toggle (B from Crop) is recorded like a toggle: Info, Crop, B, Done = Crop; Crop closed = Info; I = Edit. The records below it are kept. - F8 notes the panel change at once, so a command run in the same frame (a batch of control requests) opens a tool on the hidden column: Info, Crop, F8, Brush, Done = hidden. - The Keywords panel test scrolls the list with no photo selected and checks that the panel's scroll area keeps that offset when a photo is selected. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/menus/run.rs | 6 ++- crates/ui-egui/src/panels/right/tests.rs | 47 +++++++++++++++++++++++ crates/ui-egui/src/state.rs | 18 +++++++-- crates/ui-egui/src/tests/panel_restore.rs | 33 ++++++++++++++++ 4 files changed, 99 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 8c24c70734..eb6be04fee 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -603,6 +603,9 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option