From ac12fad9c8f8367657f2fe21469e7bb274a0b3ab Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Thu, 15 Oct 2026 15:11:52 +0200 Subject: [PATCH 001/331] Plain labels are no longer drag-selectable, as in Lightroom (fixes #1885) --- crates/ui-egui/src/theme.rs | 43 +++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 57ee987d1d..a42912896f 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -445,6 +445,9 @@ pub fn apply_kind(ctx: &egui::Context, kind: ThemeKind) { s.text_styles.insert(egui::TextStyle::Small, FontId::proportional(11.0)); s.text_styles.insert(egui::TextStyle::Heading, FontId::new(16.0, FontFamily::Name(FONT_SEMIBOLD.into()))); s.animation_time = 0.08; + // Captions and headings are not text to select (#1885); text meant for copying opts in + // with `Label::selectable(true)`. + s.interaction.selectable_labels = false; }); } @@ -466,6 +469,46 @@ mod tests { } } + /// Drag the pointer across `label` from end to end, press Copy, and return what egui copied. + fn drag_and_copy(label: impl Fn() -> egui::Label) -> Option { + let ctx = egui::Context::default(); + apply_kind(&ctx, ThemeKind::default()); + let frame = |events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 200.0))), + events, + ..Default::default() + }; + let mut rect = egui::Rect::NOTHING; + let mut out = ctx.run_ui(input, |ui| rect = ui.add(label()).rect); + out.textures_delta.clear(); + (out.platform_output.commands, rect) + }; + let (_, rect) = frame(vec![]); + let (from, to) = (rect.left_center() + egui::vec2(1.0, 0.0), rect.right_center() - egui::vec2(1.0, 0.0)); + let button = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let mut commands = Vec::new(); + for events in [ + vec![egui::Event::PointerMoved(from)], + vec![button(from, true)], + vec![egui::Event::PointerMoved(to)], + vec![button(to, false)], + vec![egui::Event::Copy], + ] { + commands.extend(frame(events).0); + } + commands.into_iter().find_map(|c| if let egui::OutputCommand::CopyText(text) = c { Some(text) } else { None }) + } + + /// #1885: a panel caption is not text to select, as in Lightroom; text a dialog offers for + /// copying (a path) opts in and still copies. + #[test] + fn static_labels_cannot_be_drag_selected_but_opted_in_text_can() { + assert_eq!(drag_and_copy(|| egui::Label::new("Exposure")), None, "a plain label was selected and copied"); + assert_eq!(drag_and_copy(|| egui::Label::new("/Users/me/Pictures").selectable(true)).as_deref(), Some("/Users/me/Pictures")); + } + /// #736: the release input must carry Thai, not silently skip the check with an older pin. /// Exercise the Thai characters of the reported folder name through every egui family. #[test] From 2eef428d407a6954bd692466508dca9de622f498 Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Fri, 16 Oct 2026 08:31:57 +0200 Subject: [PATCH 002/331] 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 0ef612f518c91add53e32316c7cc83b637268c9f Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Fri, 16 Oct 2026 21:24:45 -0400 Subject: [PATCH 003/331] LR-PROF-CAMERACOLOR: raw decoding keeps negative channels Decoding clamped each linear Rec.2020 channel at zero after the colour matrix. Near black those values are sensor noise, and the clamp kept only the positive half of each channel's noise: through a saturating camera matrix red and blue have the widest noise, so pushed shadows and dark frames came out magenta (a black frame pushed 4 EV: sRGB (64, 28, 65) in its darkest 40%, (2, 4, 4) now). Negative channels now pass through to noise reduction and the output gamut mapping, which already moves colours toward their luminance until in range; only non-finite values are zeroed. Moving each negative colour toward its luminance at decode instead still left it pink ((34, 14, 22)). RENDER_CACHE_VERSION 66. --- crates/engine/src/files.rs | 49 ++++++++++++++++++++++++++++++++++++-- crates/engine/src/media.rs | 2 +- docs/parity-checklist.md | 3 ++- docs/whats-new.md | 8 +++++++ 4 files changed, 58 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 31bb930fbf..9c6f02852b 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -280,7 +280,7 @@ impl CameraColourModel<'_> { } let out = hue_sat.apply_lanes(rgb); for (l, p) in chunk.iter_mut().enumerate() { - *p = [out[0][l], out[1][l], out[2][l]].map(|v| v.max(0.0)); + *p = finite([out[0][l], out[1][l], out[2][l]]); } } }); @@ -302,10 +302,22 @@ impl CameraColourModel<'_> { Some(tables) => tables.apply(rgb, gain), None => rgb.map(|v| v * gain), }; - self.hue_sat.map_or(rgb, |h| h.apply(rgb)).map(|v| v.max(0.0)) + finite(self.hue_sat.map_or(rgb, |h| h.apply(rgb))) } } +/// `rgb` (linear Rec.2020) as decoding leaves it for the stages after: negative channels kept, non-finite ones zero. +/// Near black, negative channels are sensor noise through the colour matrix, and keeping them keeps the noise zero-mean +/// until noise reduction and the output's gamut mapping (which moves a colour toward its luminance until it is in +/// range) deal with it. Clamping each channel at zero here kept only the positive half of every channel's noise: +/// through a saturating camera matrix (red row 3.5, −2.4, −0.1 on a NIKON D780 profile) red and blue have the widest +/// noise, so pushed shadows and dark frames came out magenta (a black frame pushed 4 EV rendered at sRGB (64, 28, 65) +/// in its darkest 40%, (2, 4, 4) without the clamp). Moving each such colour toward its luminance instead still left +/// it pink, at (34, 14, 22): any per-pixel rule that treats pixels by the sign of their noise biases the mean. +fn finite(rgb: [f32; 3]) -> [f32; 3] { + rgb.map(|v| if v.is_finite() { v } else { 0.0 }) +} + /// The white-balanced camera RGB that `model` (white-balanced camera RGB → linear Rec.2020) renders /// neutral, as bright as it renders `[1, 1, 1]`: what fully clipped highlights are rebuilt to, so they come out /// neutral whatever the colour model does to the camera's own neutral (a look fitted to the camera's JPEG or a @@ -1839,6 +1851,39 @@ pub(crate) mod tests { /// A fitted camera look applied in lanes, on rows that aren't a whole number of them, gives the bits of the /// pixel-by-pixel path, awkward pixels (black, negative, huge, NaN, infinite) included. + #[test] + fn decoding_keeps_negative_channels_and_zeroes_non_finite_ones() { + assert_eq!(finite([0.6, 0.05, -0.04]), [0.6, 0.05, -0.04]); + assert_eq!(finite([f32::NAN, -0.1, f32::INFINITY]), [0.0, -0.1, 0.0]); + } + + /// Dark sensor noise through a saturating camera matrix (a NIKON D780 profile's) averages to a neutral colour: the + /// per-channel clamp at zero decoding had kept red's and blue's wider positive halves and turned it magenta. + #[test] + fn dark_noise_through_a_saturating_matrix_stays_neutral() { + let matrix = lightcraft_color::Mat3([[3.48, -2.41, -0.06], [-0.41, 1.57, -0.16], [0.32, -1.86, 2.58]]); + let colour = CameraColourModel { wb: [1.0; 3], matrix, gain: 1.0, tables: None, hue_sat: None }; + // a grey 0.002 above black with ±0.004 of noise per channel (a deterministic sequence) + let mut state = 12345u32; + let mut noise = || { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (state >> 8) as f32 / (1u32 << 24) as f32 * 0.008 - 0.004 + }; + let mut img = Rgb32f::new(200, 200); + for p in img.data.iter_mut() { + *p = [0.002 + noise(), 0.002 + noise(), 0.002 + noise()]; + } + colour.apply(&mut img); + let mut mean = [0.0f64; 3]; + for p in &img.data { + for (m, v) in mean.iter_mut().zip(p) { + *m += f64::from(*v); + } + } + let (hi, lo) = (mean[0].max(mean[1]).max(mean[2]), mean[0].min(mean[1]).min(mean[2])); + assert!(lo > 0.0 && hi / lo < 1.2, "mean {mean:?} is tinted"); + } + #[test] fn camera_look_in_lanes_matches_pixel_by_pixel() { let data = (0..72 * 5 * 5).map(|i| [((i * 37) % 61) as f32 - 30.0, 0.6 + ((i * 11) % 13) as f32 / 13.0, 1.0]).collect(); diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 22d76528d6..e6c438ad72 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 = 64; +pub const RENDER_CACHE_VERSION: u64 = 65; /// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache). pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512]; diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 4e05317933..18863969ad 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-15 · **Change:** minor (LRC-PRINT-PAGE: Print Page Options) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **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 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 @@ -801,6 +801,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 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 | 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-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/whats-new.md b/docs/whats-new.md index 2f02ffb91b..441b4889bc 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,13 @@ # What's new in LightCraft +## 2026-10-16 + +### Pushed shadows of raws no longer turn magenta +- Raw decoding no longer clips each colour channel at zero. Near black, sensor noise through the camera's colour + matrix has negative values, and clipping kept only the positive half of each channel's noise, so dark areas + 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. + ## 2026-10-14 ### Model downloads time out on a name that doesn't resolve 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 004/331] 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 005/331] 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 006/331] 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 007/331] 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 008/331] 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 009/331] 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 010/331] 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 c61d946ef32e5227ec48d061fa723038b84b5261 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:38:22 +0200 Subject: [PATCH 011/331] LR-LIB-CULL: bursts keep an order set by hand (catalog format 10) `Analysis.rank` is a photo's place in its burst once the person arranged the burst by hand (0 = the pick). `Catalog::burst_index` / `burst` / `bursts_among` give each burst pick first, and `next_burst_id` a number no photo uses. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/bursts.rs | 118 +++++++++++++++++++++ crates/catalog/src/journal.rs | 3 +- crates/catalog/src/lib.rs | 1 + crates/catalog/src/model.rs | 14 +++ crates/catalog/src/tests_format_version.rs | 31 +++++- 5 files changed, 164 insertions(+), 3 deletions(-) create mode 100644 crates/catalog/src/bursts.rs diff --git a/crates/catalog/src/bursts.rs b/crates/catalog/src/bursts.rs new file mode 100644 index 0000000000..a5b393780b --- /dev/null +++ b/crates/catalog/src/bursts.rs @@ -0,0 +1,118 @@ +//! Bursts: the look-alike shots Assisted Culling groups ([`crate::Analysis::group`]), in the +//! order they are shown and arranged — the pick first. +//! +//! A burst culling made is ordered by what culling found: its best photo, then the sharper +//! shots, then capture time. Once the person arranges a burst by hand every member carries its +//! place ([`crate::Analysis::rank`]), and that order is kept. + +use std::collections::{HashMap, HashSet}; + +use crate::{Catalog, Photo, PhotoId}; + +/// A photo's place in its burst: hand-placed ones by their place, then the best, the sharper, +/// the earlier, the lower id. +fn order_key(p: &Photo) -> (u32, bool, i64, &str, PhotoId) { + let a = p.analysis.unwrap_or_default(); + // sharpness is 0..100: a fixed-point key keeps the sort total + (a.rank.unwrap_or(u32::MAX), !a.best, -((a.sharpness * 1000.0) as i64), p.captured.as_deref().unwrap_or("~"), p.id) +} + +impl Catalog { + /// Every burst: its number → its photos (deleted ones left out), pick first. + pub fn burst_index(&self) -> HashMap> { + let mut by: HashMap> = HashMap::new(); + for p in self.photos.values().filter(|p| !p.deleted) { + if let Some(g) = p.analysis.and_then(|a| a.group) { + by.entry(g).or_default().push(&**p); + } + } + by.into_iter() + .map(|(g, mut photos)| { + photos.sort_by(|a, b| order_key(a).cmp(&order_key(b))); + (g, photos.into_iter().map(|p| p.id).collect()) + }) + .collect() + } + + /// The photos of burst `group`, pick first (empty when there is no such burst). + pub fn burst(&self, group: u32) -> Vec { + self.burst_index().remove(&group).unwrap_or_default() + } + + /// The bursts `ids` meet, in the order their first photo appears in `ids`, each pick first. + /// Only photos in `scope` count as members (the photos of a view and the hidden members of + /// its collapsed stacks, say); `None` takes every photo of the burst. + pub fn bursts_among(&self, ids: &[PhotoId], scope: Option<&HashSet>) -> Vec<(u32, Vec)> { + let mut index = self.burst_index(); + let mut out = Vec::new(); + for id in ids { + let Some(g) = self.photo(*id).and_then(|p| p.analysis).and_then(|a| a.group) else { continue }; + if let Some(mut photos) = index.remove(&g) { + if let Some(scope) = scope { + photos.retain(|p| scope.contains(p)); + } + if !photos.is_empty() { + out.push((g, photos)); + } + } + } + out + } + + /// A burst number no photo uses (deleted ones included, so Undo never brings back a clash). + pub fn next_burst_id(&self) -> u32 { + self.photos.values().filter_map(|p| p.analysis.and_then(|a| a.group)).max().unwrap_or(0) + 1 + } +} + +#[cfg(test)] +mod tests { + use crate::{Analysis, Catalog, Op, Photo, PhotoId, Source}; + + fn add(c: &mut Catalog, when: &str, a: Option) -> PhotoId { + let id = c.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: format!("/p/{}.jpg", id.0) }, "p.jpg", "JPEG", 4, 3, "2026-01-01"); + p.captured = Some(when.into()); + p.analysis = a; + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id + } + + fn shot(group: u32, sharpness: f32, best: bool, rank: Option) -> Option { + Some(Analysis { sharpness, group: Some(group), best, rank, ..Default::default() }) + } + + #[test] + fn a_culled_burst_shows_its_best_then_the_sharper_shots() { + let mut c = Catalog::new(); + let a = add(&mut c, "2026-05-01T10:00:00", shot(1, 20.0, false, None)); + let b = add(&mut c, "2026-05-01T10:00:01", shot(1, 80.0, true, None)); + let d = add(&mut c, "2026-05-01T10:00:02", shot(1, 50.0, false, None)); + let loose = add(&mut c, "2026-05-01T10:00:03", Some(Analysis::default())); + assert_eq!(c.burst(1), vec![b, d, a]); + assert!(c.burst(2).is_empty()); + assert_eq!(c.bursts_among(&[a, loose, d], None), vec![(1, vec![b, d, a])]); + assert_eq!(c.next_burst_id(), 2); + } + + #[test] + fn a_burst_arranged_by_hand_keeps_its_order() { + let mut c = Catalog::new(); + // the pick by hand is the softest shot + let a = add(&mut c, "2026-05-01T10:00:00", shot(3, 20.0, true, Some(0))); + let b = add(&mut c, "2026-05-01T10:00:01", shot(3, 80.0, false, Some(2))); + let d = add(&mut c, "2026-05-01T10:00:02", shot(3, 50.0, false, Some(1))); + let other = add(&mut c, "2026-05-01T11:00:00", shot(7, 50.0, true, None)); + let other2 = add(&mut c, "2026-05-01T11:00:01", shot(7, 40.0, false, None)); + assert_eq!(c.burst(3), vec![a, d, b]); + // in the order the view meets them; a scope keeps a burst's members within it + assert_eq!(c.bursts_among(&[other, b], None), vec![(7, vec![other, other2]), (3, vec![a, d, b])]); + let scope = [b, d, other].into_iter().collect(); + assert_eq!(c.bursts_among(&[b, other], Some(&scope)), vec![(3, vec![d, b]), (7, vec![other])]); + assert_eq!(c.next_burst_id(), 8); + // deleted photos are no member + c.apply(Op::SetDeleted { id: d, deleted: true }).unwrap(); + assert_eq!(c.burst(3), vec![a, b]); + assert_eq!(c.next_burst_id(), 8); + } +} diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index edcfae22ae..a3421661d4 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -52,6 +52,7 @@ //! | 7 | Kelvin white balance for raws whose camera has matrices (#730) | `Op::SetAsShotWb`, `WhiteBalance.scale` | //! | 8 | History cursor: Go to History Step adds no step | `Op::SetHistoryCursor`, `Photo.history_cursor` | //! | 9 | preview-only recheck | `Photo.preview_checked`, `Op::SetContent.preview_checked` | +//! | 10 | bursts arranged by hand in Assisted Culling | `Analysis.rank` | //! //! Rules: //! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a @@ -76,7 +77,7 @@ pub const LOG: &str = "catalog.log"; const FORMAT: &str = "lightcraft-catalog"; /// The catalog format this build writes (and the newest it reads). See the module docs → /// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added. -pub const VERSION: u32 = 9; +pub const VERSION: u32 = 10; /// When [`Journal::wants_snapshot`] says it's time to compact the log. #[derive(Clone, Copy, Debug)] diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 1776c895c1..b3791a6d95 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -13,6 +13,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod bursts; pub mod dates; pub mod folders; mod index; diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 6ac3544ee7..1a3e03ea82 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -321,6 +321,20 @@ pub struct Analysis { pub group: Option, /// The best photo of its group. pub best: bool, + /// Set when the person arranged this photo's burst by hand (Window ▸ Bursts, or + /// `photo.moveToBurst`): its place in [`Analysis::group`], 0 being the pick, or `Some(0)` for + /// a photo taken out of every burst. Culling run again keeps such a photo's burst, place and + /// pick (unless asked to regroup). `None` while the burst is as culling made it; left out of the + /// catalog JSON then, so older catalogs read unchanged. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rank: Option, +} + +impl Analysis { + /// Whether the person placed this photo by hand (see [`Analysis::rank`]). + pub fn by_hand(&self) -> bool { + self.rank.is_some() + } } /// Raw formats whose files carry vendor white-balance multipliers but no colour matrices: their starting diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index e31d7fe0c4..56ffc6e58d 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -192,6 +192,33 @@ fn bad_crc_is_still_a_torn_tail() { assert!(r.torn_bytes > 0 && r.damaged.is_none(), "{r:?}"); } +/// A v9 library (bursts as culling made them) reads every analysis as not arranged by hand and +/// is rewritten in the current format; a place set by hand survives the round trip, and none is +/// written for a photo left as culling placed it. +#[test] +fn v9_analysis_loads_unarranged_and_is_upgraded() { + let mut c = Catalog::new(); + let id = c.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: "/p/a.jpg".into() }, "a.jpg", "JPEG", 160, 120, "2026-01-01"); + p.analysis = Some(Analysis { sharpness: 61.0, clipped: 0.01, group: Some(2), best: true, ..Default::default() }); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let snap = c.to_snapshot(); + assert!(!snap.contains("rank"), "nothing new is written for a burst culling made: {snap}"); + let m = MemStore::new(); + m.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":9,\"seq\":1,\"catalog\":{snap}}}\n").into_bytes()); + let (_, loaded, r) = Journal::open(Box::new(m.clone())).unwrap(); + let a = loaded.photo(id).unwrap().analysis.unwrap(); + assert_eq!((a.group, a.best, a.rank, a.by_hand()), (Some(2), true, None, false)); + assert_eq!(r.upgraded_from, Some(9)); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); + // a place set by hand round-trips + let mut c = loaded; + let b = Analysis { rank: Some(1), best: false, ..a }; + c.apply(Op::SetAnalysis { id, analysis: Some(b) }).unwrap(); + let again: Catalog = serde_json::from_str(&c.to_snapshot()).unwrap(); + assert_eq!(again.photo(id).unwrap().analysis, Some(b)); +} + /// Guard for the version rule (see `journal` → *Format versions*): adding an [`Op`] variant breaks /// this match. When it does, bump `journal::VERSION`, add a row to the format table, and add the /// variant here under the new version. A version that only adds serialized fields raises @@ -238,8 +265,8 @@ fn op_variants_are_versioned() { Op::SetHistoryCursor { .. } => 8, } } - /// v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`. - const NEWEST_FIELDS: u32 = 9; + /// v10: `Analysis.rank`. + const NEWEST_FIELDS: u32 = 10; let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None }); assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version"); } From 96a18539b9637289bfe52f37b94cfa16a33063f9 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:58:03 +0200 Subject: [PATCH 012/331] LR-LIB-CULL: photo.moveToBurst arranges bursts by hand; culling again keeps them `photo.moveToBurst {ids, burst?: n | "new" | null, index?}` moves photos within their burst, into another, into a new one or out of every burst. The first place is the pick: `best` (Best of Similar Shots), the Pick flag culling gave the old pick and the top of a stacked burst follow it. A burst a move leaves with one photo is no burst. One undo step. `photo.analyze` keeps the burst, place and pick of photos arranged by hand and only scores them again (`resetBursts` regroups them), and numbers new bursts after every burst that stays, so two runs on different photos no longer share burst numbers. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cull.rs | 247 +++++++++++++++++++++++++---- crates/engine/src/lib.rs | 2 + crates/engine/src/tests_bursts.rs | 250 ++++++++++++++++++++++++++++++ 3 files changed, 473 insertions(+), 26 deletions(-) create mode 100644 crates/engine/src/tests_bursts.rs diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 4266790edd..76725a968c 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -29,10 +29,14 @@ fn analyze(s: &mut Session, p: &Value) -> Result { let reject_below = p.get("rejectBelow").and_then(Value::as_f64).map(|v| v as f32); let pick_best = p.get("pickBest").and_then(Value::as_bool).unwrap_or(false); let (gap, same) = burst_params(p)?; - let stack_groups = match p.get("stackGroups") { - None | Some(Value::Null) => false, - Some(v) => v.as_bool().ok_or_else(|| super::bad("photo.analyze", "`stackGroups` must be true or false"))?, + let flag_param = |key: &str| -> Result { + match p.get(key) { + None | Some(Value::Null) => Ok(false), + Some(v) => v.as_bool().ok_or_else(|| super::bad("photo.analyze", format!("`{key}` must be true or false"))), + } }; + let stack_groups = flag_param("stackGroups")?; + let reset = flag_param("resetBursts")?; // measure (thumbnail-level sources: fast, and enough for focus at 512 px) let mut rows: Vec<(PhotoId, Option, f32, f32, [f32; 64])> = Vec::new(); let mut failed = Vec::new(); @@ -48,17 +52,25 @@ fn analyze(s: &mut Session, p: &Value) -> Result { } // bursts: consecutive (by capture time) look-alike shots rows.sort_by_key(|r| (r.1.unwrap_or(i64::MAX), r.0)); + // A photo whose burst was arranged by hand keeps it (burst, place, pick): only its scores + // are measured again. The others are grouped among themselves, in bursts numbered after + // every burst that stays (earlier runs on other photos, the ones arranged by hand). + let by_hand = |id: PhotoId| -> Option { s.catalog.photo(id).and_then(|p| p.analysis).filter(|a| !reset && a.by_hand()) }; + let kept: Vec> = rows.iter().map(|r| by_hand(r.0)).collect(); + let auto: Vec = (0..rows.len()).filter(|i| kept[*i].is_none()).collect(); + let regrouped: std::collections::HashSet = auto.iter().map(|i| rows[*i].0).collect(); + let mut next = s.catalog.photos().filter(|p| !regrouped.contains(&p.id)).filter_map(|p| p.analysis.and_then(|a| a.group)).max().unwrap_or(0) + 1; let mut group_of: Vec> = vec![None; rows.len()]; - let mut next = 1u32; - for i in 1..rows.len() { - let (a, b) = (&rows[i - 1], &rows[i]); + for w in auto.windows(2) { + let (i, j) = (w[0], w[1]); + let (a, b) = (&rows[i], &rows[j]); let close = matches!((a.1, b.1), (Some(x), Some(y)) if (y.saturating_sub(x)).unsigned_abs() as f64 <= gap); if close && lightcraft_pipeline::cull::similarity(&a.4, &b.4) >= same { - let g = *group_of[i - 1].get_or_insert_with(|| { + let g = *group_of[i].get_or_insert_with(|| { next += 1; next - 1 }); - group_of[i] = Some(g); + group_of[j] = Some(g); } } let mut best: std::collections::HashMap = Default::default(); @@ -74,9 +86,16 @@ fn analyze(s: &mut Session, p: &Value) -> Result { let (mut rejected, mut picked) = (0, 0); let mut out = Vec::new(); for (i, (id, _, sharp, clip, _)) in rows.iter().enumerate() { - let g = group_of[i]; - let is_best = g.is_some_and(|g| best.get(&g).is_some_and(|b| b.0 == i)); - ops.push(Op::SetAnalysis { id: *id, analysis: Some(Analysis { sharpness: *sharp, clipped: *clip, group: g, best: is_best }) }); + let analysis = match kept[i] { + Some(k) => Analysis { sharpness: *sharp, clipped: *clip, ..k }, + None => { + let g = group_of[i]; + let is_best = g.is_some_and(|g| best.get(&g).is_some_and(|b| b.0 == i)); + Analysis { sharpness: *sharp, clipped: *clip, group: g, best: is_best, rank: None } + } + }; + let (g, is_best) = (analysis.group, analysis.best); + ops.push(Op::SetAnalysis { id: *id, analysis: Some(analysis) }); let flag = s.catalog.photo(*id).map(|p| p.flag).unwrap_or_default(); if reject_below.is_some_and(|t| *sharp < t) && flag != Flag::Reject { ops.push(Op::SetFlag { id: *id, flag: Flag::Reject }); @@ -85,7 +104,7 @@ fn analyze(s: &mut Session, p: &Value) -> Result { ops.push(Op::SetFlag { id: *id, flag: Flag::Pick }); picked += 1; } - out.push(json!({"id": id.0, "sharpness": (sharp * 10.0).round() / 10.0, "clipped": clip, "group": g, "best": is_best})); + out.push(json!({"id": id.0, "sharpness": (sharp * 10.0).round() / 10.0, "clipped": clip, "group": g, "best": is_best, "byHand": kept[i].is_some()})); } let mut stacks = 0; if stack_groups { @@ -118,22 +137,189 @@ fn analyze(s: &mut Session, p: &Value) -> Result { s.commit("Assisted Culling", Op::Batch { ops })?; } if stacks > 0 { - // a photo now hidden inside a collapsed stack must not stay the active one: its stack's - // top takes over, and the rest of the selection (what was culled) stays selected - let vis = s.visible_cloned(); - if let Some(a) = s.selection.active - && !vis.contains(&a) - && let Some(st) = s.catalog.stack_of(a) - { - let top = vis.iter().copied().find(|p| st.photos.contains(p)).unwrap_or(st.top()); - s.selection.ids.retain(|id| vis.contains(id)); - if !s.selection.ids.contains(&top) { - s.selection.ids.push(top); + keep_active_shown(s); + } + let kept = kept.iter().filter(|k| k.is_some()).count(); + Ok(json!({"photos": out, "groups": best.len(), "kept": kept, "stacks": stacks, "rejected": rejected, "picked": picked, "failed": failed})) +} + +/// A photo now hidden inside a collapsed stack must not stay the active one: its stack's top +/// takes over, and the rest of the selection stays selected. +fn keep_active_shown(s: &mut Session) { + let vis = s.visible_cloned(); + if let Some(a) = s.selection.active + && !vis.contains(&a) + && let Some(st) = s.catalog.stack_of(a) + { + let top = vis.iter().copied().find(|p| st.photos.contains(p)).unwrap_or(st.top()); + s.selection.ids.retain(|id| vis.contains(id)); + if !s.selection.ids.contains(&top) { + s.selection.ids.push(top); + } + s.selection.active = Some(top); + } +} + +/// Where `photo.moveToBurst` puts the photos. +#[derive(Clone, Copy, PartialEq)] +enum Dest { + Burst(u32), + New, + Nowhere, +} + +/// Arrange bursts by hand: `ids` go into a burst at `index` (0 = the pick), into a new burst, or +/// out of every burst. Every burst touched is then arranged by hand ([`Analysis::rank`]), so +/// culling run again keeps it. What marks a burst's pick follows its first photo: `best` (the +/// Best of Similar Shots rule), the Pick flag when culling's pick had it, and the top of the +/// burst's stack when the burst is stacked. One undo step. +fn move_to_burst(s: &mut Session, p: &Value) -> Result { + use std::collections::{BTreeMap, HashMap}; + const C: &str = "photo.moveToBurst"; + let mut ids = s.targets(p)?; + let mut seen = std::collections::HashSet::new(); + ids.retain(|id| seen.insert(*id)); + if ids.is_empty() { + return Err(super::bad(C, "no photos")); + } + for id in &ids { + match s.catalog.photo(*id) { + Some(ph) if ph.deleted => return Err(super::bad(C, format!("“{}” is deleted", ph.file_name))), + Some(ph) if ph.analysis.is_none() => { + return Err(super::bad(C, format!("“{}” has no culling scores yet: run Assisted Culling on it first", ph.file_name))); } - s.selection.active = Some(top); + Some(_) => {} + None => return Err(super::bad(C, format!("no photo {}", id.0))), } } - Ok(json!({"photos": out, "groups": best.len(), "stacks": stacks, "rejected": rejected, "picked": picked, "failed": failed})) + let group = |s: &Session, id: PhotoId| s.catalog.photo(id).and_then(|p| p.analysis).and_then(|a| a.group); + let index = s.catalog.burst_index(); + let into = match p.get("burst") { + None => Dest::Burst(group(s, ids[0]).ok_or_else(|| super::bad(C, "the photo isn't in a burst: say which `burst` it goes to"))?), + Some(Value::Null) => Dest::Nowhere, + Some(Value::String(n)) if n == "new" => Dest::New, + Some(v) => match v.as_u64().and_then(|n| u32::try_from(n).ok()) { + Some(n) if index.contains_key(&n) => Dest::Burst(n), + Some(n) => return Err(super::bad(C, format!("there is no burst {n}"))), + None => return Err(super::bad(C, "`burst` must be a burst number, \"new\" or null")), + }, + }; + let at = match p.get("index") { + None | Some(Value::Null) => usize::MAX, + Some(v) => v.as_u64().map(|n| n as usize).ok_or_else(|| super::bad(C, "`index` must be a place in the burst: 0 (the pick), 1, …"))?, + }; + // the bursts touched, before and after + let target = match into { + Dest::Burst(g) => Some(g), + Dest::New => Some(s.catalog.next_burst_id()), + Dest::Nowhere => None, + }; + let mut old: BTreeMap> = BTreeMap::new(); + for g in ids.iter().filter_map(|id| group(s, *id)).chain(target) { + old.entry(g).or_insert_with(|| index.get(&g).cloned().unwrap_or_default()); + } + let mut new = old.clone(); + for members in new.values_mut() { + members.retain(|m| !ids.contains(m)); + } + if let Some(g) = target { + let members = new.entry(g).or_default(); + let at = at.min(members.len()); + members.splice(at..at, ids.iter().copied()); + } + // each photo's burst, place and pick: a burst a move leaves with one photo is no burst (the + // burst moved into stays one, so a new burst may start with one photo for more to join) + let remains = |g: u32, members: &Vec| members.len() >= 2 || (target == Some(g) && !members.is_empty()); + let mut placed: HashMap, u32, bool)> = ids.iter().map(|id| (*id, (None, 0, false))).collect(); + for (g, members) in &new { + let stays = remains(*g, members); + for (i, m) in members.iter().enumerate() { + placed.insert(*m, if stays { (Some(*g), i as u32, i == 0) } else { (None, 0, false) }); + } + } + let mut ops = Vec::new(); + let mut by_id: Vec<_> = placed.iter().collect(); + by_id.sort_by_key(|(id, _)| **id); + for (id, (g, rank, best)) in by_id { + let Some(was) = s.catalog.photo(*id).and_then(|p| p.analysis) else { continue }; + let now = Analysis { group: *g, rank: Some(*rank), best: *best, ..was }; + if now != was { + ops.push(Op::SetAnalysis { id: *id, analysis: Some(now) }); + } + } + // what the target burst holds now + let members: Option> = target.and_then(|g| new.get(&g).filter(|m| remains(g, m))).map(|m| m.iter().map(|p| p.0).collect()); + let report = |changed: bool| json!({"burst": members.as_ref().and(target), "pick": members.as_ref().and_then(|m| m.first()), "photos": members, "changed": changed}); + if ops.is_empty() { + return Ok(report(false)); + } + // the Pick culling gave a burst's pick goes to its new pick + let is_pick = |id: PhotoId| placed.get(&id).is_some_and(|p| p.2); + let flag = |s: &Session, id: PhotoId| s.catalog.photo(id).map(|p| p.flag).unwrap_or_default(); + let mut flags: BTreeMap = BTreeMap::new(); + for (g, before) in &old { + let Some(old_pick) = before.iter().copied().find(|m| s.catalog.photo(*m).and_then(|p| p.analysis).is_some_and(|a| a.best)) else { continue }; + let new_pick = new.get(g).filter(|m| remains(*g, m)).and_then(|m| m.first()).copied(); + if flag(s, old_pick) != Flag::Pick || new_pick == Some(old_pick) { + continue; + } + if !is_pick(old_pick) { + flags.insert(old_pick, Flag::None); + } + if let Some(n) = new_pick + && flag(s, n) == Flag::None + { + flags.insert(n, Flag::Pick); + } + } + ops.extend(flags.into_iter().map(|(id, flag)| Op::SetFlag { id, flag })); + // a stacked burst (a stack of exactly its photos, as culling stacks them) follows it: its stack + // shrinks, grows or goes, in the burst's order. Shrinking first: a photo is in one stack at a time. + let (mut shrink, mut grow) = (Vec::new(), Vec::new()); + let mut grows_target = false; + let mut followed = std::collections::HashSet::new(); + for (g, before) in old.iter().filter(|(_, m)| m.len() >= 2) { + let Some(st) = s.catalog.stack_of(before[0]).filter(|st| st.photos.len() == before.len() && before.iter().all(|m| st.photos.contains(m))) + else { + continue; + }; + followed.insert(st.id); + let after = new.get(g).filter(|m| m.len() >= 2); + match after { + None => shrink.push(Op::RemoveStack { id: st.id }), + Some(after) if after == &st.photos => {} + Some(after) => { + let op = Op::SetStack { id: st.id, photos: after.clone(), collapsed: st.collapsed }; + if after.iter().all(|m| st.photos.contains(m)) { + shrink.push(op) + } else { + grows_target = true; + grow.push(op) + } + } + } + } + if grows_target { + // photos joining a stacked burst leave any other stack they are in + let strays: Vec = ids.iter().copied().filter(|id| s.catalog.stack_of(*id).is_some_and(|st| !followed.contains(&st.id))).collect(); + shrink.extend(s.catalog.remove_from_stacks_ops(&strays)); + } + let restacked = !shrink.is_empty() || !grow.is_empty(); + ops.extend(shrink); + ops.extend(grow); + let same = matches!(into, Dest::Burst(g) if ids.iter().all(|id| group(s, *id) == Some(g))); + let label = match into { + Dest::Burst(_) if same && at == 0 => "Choose Burst Pick", + Dest::Burst(_) if same => "Rearrange Burst", + Dest::Burst(_) => "Move to Burst", + Dest::New => "New Burst", + Dest::Nowhere => "Remove from Burst", + }; + s.commit(label, Op::Batch { ops })?; + if restacked { + keep_active_shown(s); + } + Ok(report(true)) } /// `burstGap` (seconds, 0..=a day) and `similarity` (0..=1) of `photo.analyze`, refused before @@ -202,9 +388,18 @@ pub fn specs() -> Vec { "Assisted Culling", [], None, - "{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool, stackGroups?: bool (false), burstGap?: seconds 0..86400 (10), similarity?: 0..1 (0.93)} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots (signature similarity at least `similarity`) taken at most `burstGap` seconds apart and mark the sharpest of each; optionally reject blurry photos, pick each group's best and, with `stackGroups`, stack each burst collapsed with its sharpest photo on top (photos already in a stack stay put: the rest of a burst is stacked when two or more remain); one undo step → {photos: [{id, sharpness, clipped, group, best}], groups, stacks, rejected, picked, failed}", + "{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool, stackGroups?: bool (false), burstGap?: seconds 0..86400 (10), similarity?: 0..1 (0.93), resetBursts?: bool (false)} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots (signature similarity at least `similarity`) taken at most `burstGap` seconds apart and mark the sharpest of each; optionally reject blurry photos, pick each group's best and, with `stackGroups`, stack each burst collapsed with its sharpest photo on top (photos already in a stack stay put: the rest of a burst is stacked when two or more remain). Photos whose burst was arranged by hand (`photo.moveToBurst`) keep their burst, place and pick and are only scored again, unless `resetBursts`; one undo step → {photos: [{id, sharpness, clipped, group, best, byHand}], groups, kept, stacks, rejected, picked, failed}", always, analyze ), + cmd!( + "photo.moveToBurst", + "Move to Burst", + [], + None, + "{ids?, burst?: number | \"new\" | null (default: the first photo's burst), index?: place (0 = the pick; default last)} — arrange Assisted Culling's bursts by hand (Window ▸ Bursts): the photos go into that burst at `index`, into a new burst, or (null) out of every burst; reordering within a burst is the same call. A burst left with one photo is no burst. The pick follows the first place: Best of Similar Shots, the Pick flag culling gave the old pick, and the top of the burst's stack. Every burst touched is kept as arranged when culling runs again (`photo.analyze` `resetBursts` forgets it). Photos must have been culled; one undo step → {burst, photos, pick, changed}", + always, + move_to_burst + ), ] } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 25e6ef52f8..7fc3195fd1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1247,6 +1247,8 @@ mod tests_album_remove; #[cfg(test)] mod tests_albums_local; #[cfg(test)] +mod tests_bursts; +#[cfg(test)] mod tests_color; #[cfg(test)] mod tests_crop_angle; diff --git a/crates/engine/src/tests_bursts.rs b/crates/engine/src/tests_bursts.rs new file mode 100644 index 0000000000..f402fbffe8 --- /dev/null +++ b/crates/engine/src/tests_bursts.rs @@ -0,0 +1,250 @@ +//! Bursts arranged by hand (`photo.moveToBurst`): a photo moved within its burst, into another, +//! into a new one or out of every burst; the pick follows the first place, and with it the +//! Best of Similar Shots rule, the Pick flag culling set and the burst's stack. Culling run again +//! keeps what was arranged by hand. + +use lightcraft_catalog::{Analysis, Flag, Op, Photo, PhotoId, Source, Stack}; +use serde_json::{Value, json}; + +use crate::Session; + +/// A photo culled into `group` (`None`: culled, in no burst; `best`: its pick), or never culled. +fn add(s: &mut Session, name: &str, when: &str, culled: Option<(Option, f32, bool)>) -> PhotoId { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: format!("/nowhere/{name}") }, name, "JPEG", 40, 30, "2026-05-01T12:00:00"); + p.captured = Some(when.into()); + p.analysis = culled.map(|(group, sharpness, best)| Analysis { sharpness, group, best, ..Default::default() }); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id +} + +fn an(s: &Session, id: PhotoId) -> Analysis { + s.catalog.photo(id).unwrap().analysis.unwrap() +} + +fn flag(s: &Session, id: PhotoId) -> Flag { + s.catalog.photo(id).unwrap().flag +} + +fn mv(s: &mut Session, p: Value) -> Value { + s.execute("photo.moveToBurst", &p).unwrap_or_else(|e| panic!("{p}: {e}")) +} + +/// Burst 1 (a best and picked, b, c), burst 2 (d best, e), x culled in no burst, y never culled. +fn library() -> (Session, [PhotoId; 7]) { + let mut s = Session::new(); + let a = add(&mut s, "a.jpg", "2026-05-01T10:00:00", Some((Some(1), 80.0, true))); + let b = add(&mut s, "b.jpg", "2026-05-01T10:00:01", Some((Some(1), 60.0, false))); + let c = add(&mut s, "c.jpg", "2026-05-01T10:00:02", Some((Some(1), 40.0, false))); + let d = add(&mut s, "d.jpg", "2026-05-01T11:00:00", Some((Some(2), 70.0, true))); + let e = add(&mut s, "e.jpg", "2026-05-01T11:00:01", Some((Some(2), 30.0, false))); + let x = add(&mut s, "x.jpg", "2026-05-01T12:00:00", Some((None, 50.0, false))); + let y = add(&mut s, "y.jpg", "2026-05-01T13:00:00", None); + s.catalog.apply(Op::SetFlag { id: a, flag: Flag::Pick }).unwrap(); + (s, [a, b, c, d, e, x, y]) +} + +#[test] +fn a_photo_dragged_to_the_front_of_its_burst_becomes_the_pick() { + let (mut s, [a, b, c, ..]) = library(); + assert_eq!(s.catalog.burst(1), vec![a, b, c]); + let commits = s.commits(); + // the softest shot is the one the person likes best + let r = mv(&mut s, json!({"ids": [c.0], "index": 0})); + assert_eq!((r["burst"].clone(), r["photos"].clone(), r["pick"].clone()), (json!(1), json!([c.0, a.0, b.0]), json!(c.0)), "{r}"); + assert_eq!(s.catalog.burst(1), vec![c, a, b]); + assert!(an(&s, c).best && !an(&s, a).best); + assert_eq!([an(&s, c).rank, an(&s, a).rank, an(&s, b).rank], [Some(0), Some(1), Some(2)], "the whole burst is now arranged by hand"); + // the Pick culling gave the old best goes with it + assert_eq!((flag(&s, c), flag(&s, a)), (Flag::Pick, Flag::None)); + // and so does Best of Similar Shots + s.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "bestOfGroup", "op": "is", "value": true}]}})).unwrap(); + let shown = s.visible_cloned(); + assert!(shown.contains(&c) && !shown.contains(&a), "{shown:?}"); + // one undo step + assert_eq!(s.commits(), commits + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.burst(1), vec![a, b, c]); + assert!(an(&s, a).best && an(&s, a).rank.is_none()); + assert_eq!((flag(&s, a), flag(&s, c)), (Flag::Pick, Flag::None)); + // reordering further back: the pick stays, the order is kept + mv(&mut s, json!({"ids": [b.0], "index": 2})); + assert_eq!(s.catalog.burst(1), vec![a, c, b]); + assert!(an(&s, a).best); + assert_eq!(flag(&s, a), Flag::Pick); + // placing a photo where it already is changes nothing and makes no undo step + let commits = s.commits(); + let r = mv(&mut s, json!({"ids": [a.0], "index": 0})); + assert_eq!(r["changed"], false, "{r}"); + assert_eq!(s.commits(), commits); +} + +#[test] +fn photos_move_between_bursts_into_new_ones_and_out() { + let (mut s, [a, b, c, d, e, x, y]) = library(); + // e joins burst 1 in second place; burst 2 keeps only d, which is then in no burst + let r = mv(&mut s, json!({"ids": [e.0], "burst": 1, "index": 1})); + assert_eq!(r["photos"], json!([a.0, e.0, b.0, c.0]), "{r}"); + assert_eq!(an(&s, e).group, Some(1)); + assert!(s.catalog.burst(2).is_empty()); + assert_eq!((an(&s, d).group, an(&s, d).best, an(&s, d).by_hand()), (None, false, true)); + // without an index it goes last; a culled loose photo can join too + mv(&mut s, json!({"ids": [x.0], "burst": 1})); + assert_eq!(s.catalog.burst(1), vec![a, e, b, c, x]); + // two photos make a new burst, in the order named + let r = mv(&mut s, json!({"ids": [c.0, b.0], "burst": "new"})); + let new = r["burst"].as_u64().unwrap() as u32; + assert_ne!(new, 1, "a number no photo uses: {r}"); + assert_eq!(s.catalog.burst(new), vec![c, b]); + assert!(an(&s, c).best); + assert_eq!(s.catalog.burst(1), vec![a, e, x]); + // out of every burst: the photo left alone in its burst is out too + let r = mv(&mut s, json!({"ids": [b.0], "burst": null})); + assert_eq!(r["burst"], Value::Null, "{r}"); + assert!(s.catalog.burst(new).is_empty()); + assert!([b, c].iter().all(|p| an(&s, *p).group.is_none() && !an(&s, *p).best && an(&s, *p).by_hand())); + // a whole burst dropped on another merges them, the target's pick first + mv(&mut s, json!({"ids": [b.0, c.0], "burst": "new"})); + let merged = s.catalog.burst(1); + let theirs = s.catalog.bursts_among(&[b], None)[0].clone(); + mv(&mut s, json!({"ids": theirs.1.iter().map(|p| p.0).collect::>(), "burst": 1})); + assert_eq!(s.catalog.burst(1), [merged, theirs.1].concat()); + assert!(s.catalog.burst(theirs.0).is_empty()); + // refused, with nothing changed: a photo never culled, a burst that isn't there, a bad index + let commits = s.commits(); + for (p, why) in [ + (json!({"ids": [y.0], "burst": 1}), "Assisted Culling"), + (json!({"ids": [a.0], "burst": 99}), "no burst 99"), + (json!({"ids": [a.0], "index": -1}), "index"), + (json!({"ids": [a.0], "burst": "first"}), "burst"), + (json!({"ids": [d.0]}), "isn't in a burst"), + (json!({"ids": []}), "no photos"), + ] { + let err = s.execute("photo.moveToBurst", &p).expect_err(&p.to_string()).to_string(); + assert!(err.contains(why), "{p}: {err}"); + } + assert_eq!(s.commits(), commits); + // a new burst may start with one photo, for more to join + let r = mv(&mut s, json!({"ids": [d.0], "burst": "new"})); + let solo = r["burst"].as_u64().unwrap() as u32; + assert_eq!(s.catalog.burst(solo), vec![d]); + assert!(an(&s, d).best); + mv(&mut s, json!({"ids": [x.0], "burst": solo, "index": 0})); + assert_eq!(s.catalog.burst(solo), vec![x, d]); +} + +#[test] +fn a_stacked_burst_follows_its_pick_and_its_members() { + let (mut s, [a, b, c, d, e, ..]) = library(); + // as Assisted Culling with "Stack each burst" leaves them: collapsed, the best on top + s.catalog.apply(Op::AddStack { stack: Stack { id: lightcraft_catalog::StackId(1), photos: vec![a, b, c], collapsed: true } }).unwrap(); + s.catalog.apply(Op::AddStack { stack: Stack { id: lightcraft_catalog::StackId(2), photos: vec![d, e], collapsed: true } }).unwrap(); + mv(&mut s, json!({"ids": [c.0], "index": 0})); + let st = s.catalog.stack_of(c).unwrap(); + assert_eq!((st.photos.clone(), st.collapsed), (vec![c, a, b], true), "the new pick tops the stack"); + // d moves into burst 1: its stack (now just e) goes, burst 1's stack takes it in + s.selection = crate::Selection::single(d); + mv(&mut s, json!({"ids": [d.0], "burst": 1, "index": 1})); + assert_eq!(s.catalog.stack_of(c).unwrap().photos, vec![c, d, a, b]); + assert!(s.catalog.stack_of(e).is_none()); + // d is hidden in the collapsed stack now: the stack's top is the active photo + assert_eq!(s.selection.active, Some(c)); + // one undo brings both stacks back as they were + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.stack_of(e).unwrap().photos, vec![d, e]); + assert_eq!(s.catalog.stack_of(c).unwrap().photos, vec![c, a, b]); + // a photo stacked with something else than its burst keeps that stack when it goes to an unstacked burst + let (mut s, [a, b, c, _, e, x, _]) = library(); + s.catalog.apply(Op::AddStack { stack: Stack { id: lightcraft_catalog::StackId(5), photos: vec![x, e], collapsed: false } }).unwrap(); + mv(&mut s, json!({"ids": [e.0], "burst": 1})); + assert_eq!(s.catalog.stack_of(e).unwrap().photos, vec![x, e]); + assert_eq!(s.catalog.burst(1), vec![a, b, c, e]); +} + +/// Look-alike PNGs (a scene and two softer copies) for the culling runs below. +fn burst_files(tag: &str, scene: usize) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("lc-bursts-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let img = lightcraft_scenes::demo_library()[scene].render(480, 320); + let soften = |img: &lightcraft_raster::Rgb32f, r: usize| { + let (w, h) = (img.width, img.height); + let mut out = img.clone(); + for y in 0..h { + for x in 0..w { + let (mut acc, mut n) = ([0f32; 3], 0.0); + for yy in y.saturating_sub(r)..(y + r + 1).min(h) { + for xx in x.saturating_sub(r)..(x + r + 1).min(w) { + let c = img.data[yy * w + xx]; + acc = [acc[0] + c[0], acc[1] + c[1], acc[2] + c[2]]; + n += 1.0; + } + } + out.data[y * w + x] = acc.map(|v| v / n); + } + } + out + }; + for (name, im) in [("1_sharp.png", img.clone()), ("2_soft.png", soften(&img, 3)), ("3_softer.png", soften(&img, 6))] { + let data: Vec<[u8; 4]> = im + .data + .iter() + .map(|c| { + let e = |v: f32| (lightcraft_color::transfer::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0).round() as u8; + [e(c[0]), e(c[1]), e(c[2]), 255] + }) + .collect(); + let png = lightcraft_codecs::encode_png( + &lightcraft_codecs::EncodeImage::rgba8(&lightcraft_raster::Rgba8 { width: im.width, height: im.height, data }), + &Default::default(), + ) + .unwrap(); + std::fs::write(dir.join(format!("s{scene}_{name}")), png).unwrap(); + } + dir +} + +#[test] +fn culling_again_keeps_bursts_arranged_by_hand() { + let (one, two) = (burst_files("keep-1", 0), burst_files("keep-2", 7)); + let mut s = Session::new().with_fs(); + let import = |s: &mut Session, dir: &std::path::Path, hour: u32| -> Vec { + let r = s.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap(); + let mut ids: Vec = r["imported"].as_array().unwrap().iter().filter_map(Value::as_u64).map(PhotoId).collect(); + ids.sort_by_key(|id| s.catalog.photo(*id).unwrap().file_name.clone()); + for (i, id) in ids.iter().enumerate() { + s.commit("t", Op::SetCaptured { id: *id, captured: Some(format!("2026-05-01T{hour:02}:00:0{i}")) }).unwrap(); + } + ids + }; + let first = import(&mut s, &one, 10); + let second = import(&mut s, &two, 14); + let ids = |v: &[PhotoId]| v.iter().map(|p| p.0).collect::>(); + // two runs on different photos number their bursts apart + s.execute("photo.analyze", &json!({"ids": ids(&first), "pickBest": true})).unwrap(); + s.execute("photo.analyze", &json!({"ids": ids(&second)})).unwrap(); + let (g1, g2) = (an(&s, first[0]).group.unwrap(), an(&s, second[0]).group.unwrap()); + assert_ne!(g1, g2, "each run's bursts get numbers of their own"); + assert_eq!(s.catalog.burst(g1), first, "sharpest first"); + // the softest is the person's pick + let softest = first[2]; + mv(&mut s, json!({"ids": [softest.0], "index": 0})); + assert_eq!(flag(&s, softest), Flag::Pick); + // culling the whole view again keeps that burst as arranged, with fresh scores + let r = s.execute("photo.analyze", &json!({"ids": ids(&[first.clone(), second.clone()].concat()), "pickBest": true})).unwrap(); + assert_eq!(r["kept"], 3, "{r}"); + assert_eq!(s.catalog.burst(g1), vec![first[2], first[0], first[1]]); + assert!(an(&s, softest).best && !an(&s, first[0]).best); + assert_eq!(flag(&s, first[0]), Flag::None, "pickBest picks the pick chosen by hand, not the sharpest"); + let g2_again = an(&s, second[0]).group.unwrap(); + assert_ne!(g2_again, g1, "an automatic burst never takes a hand-made burst's number"); + assert_eq!(s.catalog.burst(g2_again), second); + // asked to regroup, culling forgets the order set by hand + s.execute("photo.analyze", &json!({"ids": ids(&first), "resetBursts": true})).unwrap(); + let g = an(&s, first[0]).group.unwrap(); + assert_eq!(s.catalog.burst(g), first); + assert!(first.iter().all(|p| !an(&s, *p).by_hand())); + assert!(s.execute("photo.analyze", &json!({"ids": ids(&first), "resetBursts": "yes"})).is_err()); + let _ = std::fs::remove_dir_all(&one); + let _ = std::fs::remove_dir_all(&two); +} From 74ded5b14fbb6fb7697b81fce58c6c171c38a457 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:04:54 +0200 Subject: [PATCH 013/331] =?UTF-8?q?LR-LIB-CULL:=20Window=20=E2=96=B8=20Bur?= =?UTF-8?q?sts=20arranges=20bursts=20by=20drag=20and=20drop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A right-hand panel (`panel.bursts`) shows the bursts of the photos in view, with the hidden members of collapsed stacks, each a row of thumbnails with its pick first. Drag a photo to another place in its burst (first: it becomes the pick), into another burst, onto New burst or Not in a burst; drag a burst by its title onto another to merge them. Photos dragged from the grid drop here too. The drag is the grid's photo drag (its label says what a drop does); each drop is one `photo.moveToBurst`. Photos culling never scored are refused. The Assisted Culling dialog gets "Regroup bursts I arranged by hand" (`resetBursts`) and a hint pointing to Window ▸ Bursts. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/src/menubar.rs | 2 + crates/ui-egui/src/menus.rs | 14 +- crates/ui-egui/src/panels/bursts.rs | 271 +++++++++++++++++++++++++++ crates/ui-egui/src/panels/dialogs.rs | 9 +- crates/ui-egui/src/panels/left.rs | 2 +- crates/ui-egui/src/panels/mod.rs | 1 + crates/ui-egui/src/panels/right.rs | 9 +- crates/ui-egui/src/state.rs | 7 +- crates/ui-egui/src/tests_bursts.rs | 207 ++++++++++++++++++++ 10 files changed, 518 insertions(+), 8 deletions(-) create mode 100644 crates/ui-egui/src/panels/bursts.rs create mode 100644 crates/ui-egui/src/tests_bursts.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bb290bd86e..4c43ec8a69 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -60,6 +60,8 @@ mod tests_before_after; #[cfg(test)] mod tests_browse_active; #[cfg(test)] +mod tests_bursts; +#[cfg(test)] mod tests_button; #[cfg(test)] mod tests_canvas_keys; @@ -1625,6 +1627,8 @@ mod drop_tests { #[derive(Default)] pub struct Caches { keyword_tree: Option<(u64, std::sync::Arc>)>, + /// The Bursts panel's bursts, by the view's generation. + bursts: Option<(u64, panels::bursts::Shown)>, /// The Keywording box's read-only names (with containing keywords, or Will Export), by library /// revision, selection and view. keyword_names: Option<(u64, u64, std::sync::Arc>)>, diff --git a/crates/ui-egui/src/menubar.rs b/crates/ui-egui/src/menubar.rs index c5e4e45c77..4c2a7e4b6e 100644 --- a/crates/ui-egui/src/menubar.rs +++ b/crates/ui-egui/src/menubar.rs @@ -236,6 +236,7 @@ const LAYOUT: &[(&str, &[&str])] = &[ "panel.activity", "panel.info", "panel.keywords", + "panel.bursts", "---", "@Edit Sections", "@Tools", @@ -367,6 +368,7 @@ pub fn checked(app: &LightcraftApp, id: &str) -> Option { "panel.activity" => panel(RightPanel::Activity), "panel.info" => panel(RightPanel::Info), "panel.keywords" => panel(RightPanel::Keywords), + "panel.bursts" => panel(RightPanel::Bursts), "panel.presets" => Some(u.presets), "library.toggleAutoWriteXmp" => Some(app.session.xmp.auto_write), _ => None, diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 41df245a78..01fbd49216 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -145,6 +145,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("panel.keywords", "Keywords", Some("K"), "Window"), ("panel.versions", "Versions", Some("Shift+V"), "Window"), ("panel.activity", "History", None, "Window"), + ("panel.bursts", "Bursts", None, "Window"), ("panel.close", "Close Panel", None, ""), // {solo?}: true opens just that section (⌥-click on its header); otherwise opens or closes it ("section.light", "Light", Some("Cmd+1"), "Window>Edit Sections"), @@ -1157,6 +1158,10 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option { + panel(app, &ctx, RightPanel::Bursts, "Bursts"); + Ok(Value::Null) + } "panel.presets" => { app.ui.presets = !app.ui.presets || !crate::docking::exposed(app, crate::docking::Panel::Presets); if app.ui.presets && app.ui.view != ViewMode::Detail { @@ -1444,7 +1449,14 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option open_original_in(app, &ctx, p), "dialog.cull" => { let (burst_gap, similarity) = app.ui.cull_burst.unwrap_or((10.0, 0.93)); - app.ui.dialog = Some(Dialog::Cull { reject_below: 0.0, pick_best: true, stack_groups: app.ui.cull_stack, burst_gap, similarity }); + app.ui.dialog = Some(Dialog::Cull { + reject_below: 0.0, + pick_best: true, + stack_groups: app.ui.cull_stack, + burst_gap, + similarity, + reset_bursts: false, + }); Ok(Value::Null) } "app.whatsNew" => { diff --git a/crates/ui-egui/src/panels/bursts.rs b/crates/ui-egui/src/panels/bursts.rs new file mode 100644 index 0000000000..8a6d17fd9d --- /dev/null +++ b/crates/ui-egui/src/panels/bursts.rs @@ -0,0 +1,271 @@ +//! Window ▸ Bursts: Assisted Culling's bursts among the photos in view (with the hidden members of +//! their collapsed stacks), each a row of thumbnails with its pick first, to put right by hand. +//! +//! Drag a photo to another place in its burst (to the front, and it becomes the pick), into +//! another burst, onto *New burst* or onto *Not in a burst*; drag a burst by its title onto +//! another to merge them. Photos dragged from the grid drop here too. A drag is the grid's photo +//! drag ([`crate::state::UiState::dragging_photos`]: its label, Esc and release), and a drop is one +//! `photo.moveToBurst`, so one undo step. +//! +//! Widgets: `burst:{n}` (a burst's title, `n` its number), `burstPhoto:{id}`, `burstPick:{n}`, +//! `burst:new`, `burst:none`. + +use std::collections::HashSet; +use std::sync::Arc; + +use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use lightcraft_catalog::{Flag, PhotoId}; +use serde_json::{Value, json}; + +use crate::LightcraftApp; +use crate::theme::Tokens; +use crate::widgets::register; + +/// Thumbnail cells: side, gap, row inset. +const CELL: f32 = 68.0; +const GAP: f32 = 6.0; +const INSET: f32 = 20.0; +/// A burst's title row. +const TITLE_H: f32 = 30.0; + +/// The bursts shown, by the view's generation (which follows every catalog change). +pub type Shown = Arc)>>; + +/// The bursts among the photos in view and the hidden members of their stacks, in view order. +fn bursts(app: &mut LightcraftApp) -> Shown { + let (generation, ids) = app.session.visible_shared(); + if let Some((g, b)) = &app.caches.bursts + && *g == generation + { + return b.clone(); + } + let cat = &app.session.catalog; + let mut scope: HashSet = ids.iter().copied().collect(); + for id in ids.iter() { + if let Some(st) = cat.stack_of(*id) { + scope.extend(st.photos.iter().copied()); + } + } + let b: Shown = Arc::new(cat.bursts_among(&ids, Some(&scope))); + app.caches.bursts = Some((generation, b.clone())); + b +} + +/// Where a drop under the pointer would put the dragged photos. +#[derive(Clone, Copy, PartialEq, Debug)] +enum Target { + /// Burst `n` at `slot` (a place among its photos as shown, the dragged ones included). + Burst(u32, usize), + New, + Nowhere, +} + +pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + egui::ScrollArea::vertical().id_salt("bursts-scroll").auto_shrink([false, false]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + super::left::drag_auto_scroll(app, ui); + super::right::header(ui, "Bursts"); + let shown = bursts(app); + let dragged: Option> = app.ui.dragging_photos.as_ref().map(|v| v.iter().copied().map(PhotoId).collect()); + let pointer = ui.input(|i| i.pointer.latest_pos()).filter(|p| ui.clip_rect().contains(*p)); + let mut target: Option<(Target, Option)> = None; + let width = ui.available_width(); + let explain = if shown.is_empty() { + "Photo → Assisted Culling… groups look-alike shots into bursts. They show here to put right by hand." + } else { + "Drag a photo to its place: the first of a burst is its pick. Drag one into another burst, or a burst by its title onto another to merge them." + }; + egui::Frame::NONE.inner_margin(egui::Margin { left: INSET as i8, right: INSET as i8, top: 0, bottom: 10 }).show(ui, |ui| { + ui.set_width(width - 2.0 * INSET); + ui.label(egui::RichText::new(crate::i18n::tr(explain)).color(t.text_dim).size(12.0)); + }); + let cols = (((width - 2.0 * INSET + GAP) / (CELL + GAP)).floor() as usize).max(1); + for (k, (g, photos)) in shown.iter().enumerate() { + // the title: a drop there puts the photos last; dragged, it takes the burst along + let (title, resp) = ui.allocate_exact_size(vec2(width, TITLE_H), Sense::click_and_drag()); + register(ui.ctx(), format!("burst:{g}"), title); + let p = ui.painter(); + let name = format!("{} {}", crate::i18n::tr("Burst"), k + 1); + p.text(pos2(title.left() + INSET, title.center().y), Align2::LEFT_CENTER, name, t.semibold(12.5), t.text); + let n = photos.len(); + let count = crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n); + p.text(pos2(title.right() - INSET, title.center().y), Align2::RIGHT_CENTER, count, t.font(11.5), t.text_dim); + if resp.hovered() && dragged.is_none() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); + } + if resp.drag_started() { + app.ui.dragging_photos = Some(photos.iter().map(|p| p.0).collect()); + } + if pointer.is_some_and(|p| title.contains(p)) { + target = Some((Target::Burst(*g, n), None)); + } + // the photos, in rows + let rows = n.div_ceil(cols); + let (area, _) = ui.allocate_exact_size(vec2(width, rows as f32 * (CELL + GAP) + GAP), Sense::hover()); + let cell_at = |i: usize| { + let (r, c) = (i / cols, i % cols); + Rect::from_min_size(pos2(area.left() + INSET + c as f32 * (CELL + GAP), area.top() + r as f32 * (CELL + GAP)), vec2(CELL, CELL)) + }; + for (i, id) in photos.iter().enumerate() { + let r = cell_at(i); + if let Some(badge) = photo_cell(app, ui, *id, r) { + register(ui.ctx(), format!("burstPick:{g}"), badge); + } + // a drop on a photo's left half goes before it, on its right half after it + if let Some(p) = pointer + && r.expand(GAP / 2.0).contains(p) + { + let slot = if p.x < r.center().x { i } else { i + 1 }; + let edge = if slot == i { r.left() - GAP / 2.0 } else { r.right() + GAP / 2.0 }; + target = Some((Target::Burst(*g, slot), Some(Rect::from_min_max(pos2(edge - 1.5, r.top()), pos2(edge + 1.5, r.bottom()))))); + } + } + if target.is_none() + && let Some(p) = pointer + && area.contains(p) + { + // the room after the last photo: last + let last = cell_at(n.saturating_sub(1)); + target = Some((Target::Burst(*g, n), Some(Rect::from_min_max(pos2(last.right() + GAP / 2.0 - 1.5, last.top()), pos2(last.right() + GAP / 2.0 + 1.5, last.bottom()))))); + } + if dragged.is_some() && matches!(target, Some((Target::Burst(tg, _), _)) if tg == *g) { + ui.painter().rect_stroke(title.union(area).shrink2(vec2(8.0, 1.0)), 4.0, Stroke::new(1.0, t.accent.gamma_multiply(0.6)), StrokeKind::Inside); + } + } + // drop places for a new burst and for none: there while there are bursts, or a drag + if !shown.is_empty() || dragged.is_some() { + ui.add_space(8.0); + for (key, label, tgt) in [("burst:new", "New burst", Target::New), ("burst:none", "Not in a burst", Target::Nowhere)] { + let (row, _) = ui.allocate_exact_size(vec2(width, 40.0), Sense::hover()); + let zone = row.shrink2(vec2(INSET, 4.0)); + register(ui.ctx(), key, zone); + let over = dragged.is_some() && pointer.is_some_and(|p| zone.contains(p)); + let stroke = if over { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, t.divider) }; + ui.painter().rect_stroke(zone, 6.0, stroke, StrokeKind::Inside); + ui.painter().text(zone.center(), Align2::CENTER_CENTER, crate::i18n::tr(label), t.font(12.0), if over { t.text } else { t.text_dim }); + if over { + target = Some((tgt, None)); + } + } + } + if let Some(ids) = dragged + && let Some((tgt, mark)) = target + { + drop_on(app, ui, &shown, &ids, tgt, mark); + } + ui.add_space(12.0); + }); +} + +/// One photo of a burst: its thumbnail, the pick's badge (returned), the active photo's outline; +/// a click selects it, a drag takes it along. +fn photo_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect) -> Option { + let t = Tokens::get(ui.ctx()); + let photo = app.session.catalog.photo(id).cloned()?; + let pick = photo.analysis.is_some_and(|a| a.best); + let resp = ui.interact(r, egui::Id::new(("burst-photo", id.0)), Sense::click_and_drag()); + register(ui.ctx(), format!("burstPhoto:{}", id.0), r); + // Any thumbnail will do at this size: one is asked for only when there is none, so the grid's + // larger ones are never asked again at this size (and back) every frame. Above the grid's own + // priorities: a member hidden in a collapsed stack isn't in the grid, which evicts the rest. + if app.renderer.thumb(id).is_none() && !app.renderer.is_pending(crate::render::Slot::Thumb(id)) { + let px = (CELL * ui.ctx().pixels_per_point()).ceil() as usize; + super::grid::request_thumb(app, id, px, 12); + } + let p = ui.painter(); + p.rect_filled(r, 3.0, Color32::from_gray(30)); + let shown = match app.renderer.thumb(id) { + Some(tex) => { + let fit = super::detail::fit_texture_rect(r, tex.size); + p.image(tex.tex.id(), fit, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + fit + } + None => r, + }; + if photo.flag == Flag::Reject { + p.rect_filled(shown, 0.0, Color32::from_black_alpha(110)); + } + let state = app.session.selection.state_of(id); + if state == lightcraft_engine::SelectionState::Active { + p.rect_stroke(shown, 0.0, Stroke::new(2.0, Color32::WHITE), StrokeKind::Outside); + } else if state != lightcraft_engine::SelectionState::NotSelected { + p.rect_stroke(shown, 0.0, Stroke::new(2.0, Color32::from_gray(170)), StrokeKind::Outside); + } + let badge = pick.then(|| { + let g = p.layout_no_wrap(crate::i18n::tr("Pick").into(), t.semibold(9.5), Color32::WHITE); + let badge = Rect::from_min_size(r.min + vec2(3.0, 3.0), vec2(g.size().x + 10.0, 14.0)); + p.rect_filled(badge, 7.0, t.accent); + p.galley(pos2(badge.left() + 5.0, badge.center().y - g.size().y / 2.0), g, Color32::WHITE); + badge + }); + if photo.flag == Flag::Pick { + crate::icons::paint( + p, + Rect::from_min_size(pos2(r.right() - 16.0, r.bottom() - 16.0), vec2(13.0, 13.0)), + crate::icons::Icon::FlagPick, + t.pick, + ); + } + let focus = photo.analysis.map(|a| a.sharpness.round() as i32).unwrap_or_default(); + let resp = resp.on_hover_text(format!("{} · {} {focus}", photo.file_name, crate::i18n::tr("Focus"))); + if resp.clicked() { + let _ = app.run("library.select", json!({"ids": [id.0]})); + } + if resp.drag_started() { + app.ui.dragging_photos = Some(vec![id.0]); + } + badge +} + +/// Photos dragged over `tgt`: the mark where they would go, the label saying what a drop does, +/// and on release the move. +fn drop_on(app: &mut LightcraftApp, ui: &mut egui::Ui, shown: &Shown, ids: &[PhotoId], tgt: Target, mark: Option) { + let t = Tokens::get(ui.ctx()); + let released = ui.input(|i| i.pointer.any_released()); + // only photos culling scored can be in a burst + if ids.iter().any(|id| app.session.catalog.photo(*id).is_none_or(|p| p.analysis.is_none())) { + ui.ctx().set_cursor_icon(egui::CursorIcon::NotAllowed); + let why = if ids.len() == 1 { "Run Assisted Culling on it first" } else { "Run Assisted Culling on these photos first" }; + super::grid::drag_hint(ui.ctx(), crate::i18n::tr(why).into()); + if released { + app.toast( + ui.ctx(), + crate::i18n::tr("Only photos Assisted Culling scored can be in a burst: run Photo → Assisted Culling… on them first"), + ); + app.ui.dragging_photos = None; + } + return; + } + let (params, hint) = match tgt { + Target::Burst(g, slot) => { + let members = shown.iter().find(|(n, _)| *n == g).map(|(_, m)| m.as_slice()).unwrap_or(&[]); + // the place once the dragged photos have left theirs + let index = members.iter().take(slot).filter(|m| !ids.contains(m)).count(); + let whole = shown.iter().any(|(n, m)| *n != g && m.len() > 1 && m.len() == ids.len() && m.iter().all(|p| ids.contains(p))); + let hint = if whole { + "Merge into this burst" + } else if index == 0 && slot < members.len() { + if ids.len() == 1 { "Make it the pick" } else { "Put first: the first is the pick" } + } else if ids.iter().all(|id| members.contains(id)) { + "Move here" + } else { + "Move to this burst" + }; + let index = if slot >= members.len() { Value::Null } else { json!(index) }; + (json!({"ids": ids.iter().map(|p| p.0).collect::>(), "burst": g, "index": index}), hint) + } + Target::New => (json!({"ids": ids.iter().map(|p| p.0).collect::>(), "burst": "new"}), "New burst"), + Target::Nowhere => (json!({"ids": ids.iter().map(|p| p.0).collect::>(), "burst": null}), "Take out of its burst"), + }; + if let Some(mark) = mark { + ui.painter().rect_filled(mark, 1.5, t.accent); + } + super::grid::drag_hint(ui.ctx(), crate::i18n::tr(hint).into()); + if released { + if let Err(e) = app.run("photo.moveToBurst", params) { + app.toast(ui.ctx(), e); + } + app.ui.dragging_photos = None; + } +} diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs index 575ba09cd3..d55e38e4ce 100644 --- a/crates/ui-egui/src/panels/dialogs.rs +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -336,7 +336,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { egui::RichText::new(crate::i18n::tr_format!("Creates {} stacks from {} of {scope}", preview["stacks"], preview["photos"], scope = crate::i18n::tr(scope))).color(t.text_dim), ); } - Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity } => { + Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity, reset_bursts } => { let n = app.session.selection.ids.len(); let scope = if n > 1 { crate::i18n::tr_format!("the {n} selected photos", n = n) } else { crate::i18n::tr_format!("the {} photos in view", app.session.visible_cloned().len()) }; ui.label(egui::RichText::new(crate::i18n::tr_format!("Scores {scope} for focus and exposure and finds similar shots taken within seconds of each other (bursts).", scope = scope)).color(t.text_label)); @@ -360,6 +360,9 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { let r = ui.add(egui::Slider::new(similarity, 0.70..=0.99).text(crate::i18n::tr("Burst: how alike (loose … strict)")).step_by(0.01).fixed_decimals(2)); crate::widgets::register(ui.ctx(), "field:cullSimilar", r.rect); ui.label(egui::RichText::new(crate::i18n::tr("Lower it when a panning or moving burst splits into several groups.")).color(t.text_dim)); + let r = ui.checkbox(reset_bursts, crate::i18n::tr("Regroup bursts I arranged by hand")); + crate::widgets::register(ui.ctx(), "check:cullResetBursts", r.rect); + ui.label(egui::RichText::new(crate::i18n::tr("Put bursts right by dragging in Window → Bursts: the first photo of a burst is its pick, and culling again keeps what you arranged.")).color(t.text_dim)); ui.label(egui::RichText::new(crate::i18n::tr("Scores stay on the photos: filter or make smart albums with Focus and Best of Similar Shots.")).color(t.text_dim)); } Dialog::WhatsNew => { @@ -1920,10 +1923,10 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result crate::panels::denoise::install(app, info, *accepted), Dialog::FaceModel { path, info, accepted } => crate::panels::faces::install(app, path, info, *accepted), Dialog::AllMetadata { .. } | Dialog::SystemInfo { .. } | Dialog::WhatsNew => Ok(serde_json::Value::Null), - Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity } => { + Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity, reset_bursts } => { app.ui.cull_burst = Some((*burst_gap, *similarity)); app.ui.cull_stack = *stack_groups; - let mut p = json!({"pickBest": pick_best, "stackGroups": stack_groups, "burstGap": burst_gap, "similarity": similarity}); + let mut p = json!({"pickBest": pick_best, "stackGroups": stack_groups, "burstGap": burst_gap, "similarity": similarity, "resetBursts": reset_bursts}); if *reject_below > 0.0 { p["rejectBelow"] = json!(reject_below); } diff --git a/crates/ui-egui/src/panels/left.rs b/crates/ui-egui/src/panels/left.rs index 3bb8deba2e..1b83e709c4 100644 --- a/crates/ui-egui/src/panels/left.rs +++ b/crates/ui-egui/src/panels/left.rs @@ -1273,7 +1273,7 @@ pub fn auto_scroll_speed(y: f32, top: f32, bottom: f32) -> f32 { /// While an album, or photos from the grid, are dragged over the sidebar: scrolls it when the /// pointer is near its top or bottom edge, so rows beyond the visible part can be reached. Call /// inside the scroll area. -fn drag_auto_scroll(app: &LightcraftApp, ui: &egui::Ui) { +pub(crate) fn drag_auto_scroll(app: &LightcraftApp, ui: &egui::Ui) { if app.ui.dragging_album.is_none() && app.ui.dragging_photos.is_none() && app.ui.dragging_section.is_none() { return; } diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index 2fcb36663c..9b9eebc1c5 100644 --- a/crates/ui-egui/src/panels/mod.rs +++ b/crates/ui-egui/src/panels/mod.rs @@ -2,6 +2,7 @@ pub mod activity; pub mod bottombar; +pub mod bursts; pub mod chips; pub mod compare; pub mod crop_overlay; diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index 5373308102..b17d3dd8f1 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -1,5 +1,5 @@ //! The right-hand panel next to the tool strip: Edit, Crop, Remove, Masking, Red Eye, Info, -//! Keywords, Versions, Activity. +//! Keywords, Versions, Activity, Bursts. use egui::{Align2, Rect, Sense, pos2, vec2}; use lightcraft_catalog::PhotoId; @@ -15,6 +15,11 @@ 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)); frame.show(ui, |ui| { + // the bursts are the view's, not a photo's: they are there without a selection + if app.ui.right == RightPanel::Bursts { + super::bursts::show(app, ui); + return; + } // (taken on every pass the panel is drawn; one from earlier than the pass before is forgotten) let held = held_offset(ui.ctx()); let Some(id) = app.session.active() else { @@ -66,7 +71,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { RightPanel::Keywords => keywords(app, ui, id), RightPanel::Versions => versions(app, ui, id), RightPanel::Activity => activity(app, ui, id), - RightPanel::None => {} + RightPanel::Bursts | RightPanel::None => {} } }); ui.data_mut(|d| d.insert_temp(egui::Id::new(AREA), scrolled.id)); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f97a4b44dd..783ccd0b4f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -37,6 +37,8 @@ pub enum RightPanel { Info, /// The profile browser (part of Edit). Profiles, + /// Assisted Culling's bursts, to arrange by hand (Window ▸ Bursts). + Bursts, } impl RightPanel { @@ -1097,13 +1099,16 @@ pub enum Dialog { WhatsNew, /// Photo ▸ Assisted Culling: reject photos below this focus score (0 = none), pick the best /// of each burst (and stack each burst, best on top, with `stack_groups`); shots at most - /// `burst_gap` seconds apart and at least `similarity` alike are a burst. + /// `burst_gap` seconds apart and at least `similarity` alike are a burst. Bursts arranged by + /// hand (Window ▸ Bursts) are kept unless `reset_bursts`. Cull { reject_below: f32, pick_best: bool, stack_groups: bool, burst_gap: f32, similarity: f32, + #[serde(default)] + reset_bursts: bool, }, /// Help ▸ System Info: (label, value) rows. DenoiseModel { diff --git a/crates/ui-egui/src/tests_bursts.rs b/crates/ui-egui/src/tests_bursts.rs new file mode 100644 index 0000000000..e7ce2858ba --- /dev/null +++ b/crates/ui-egui/src/tests_bursts.rs @@ -0,0 +1,207 @@ +//! Window ▸ Bursts: Assisted Culling's bursts as rows of thumbnails, pick first. A photo dragged +//! to the front of its burst becomes the pick; dragged into another burst, onto New Burst or Not +//! in a Burst it moves there; a burst dragged by its title merges into another; photos dragged +//! from the grid drop here too. Each drop is one undo step. + +use egui::{Pos2, Rect, pos2}; +use lightcraft_catalog::{Analysis, Flag, Op, Photo, PhotoId, Source}; +use serde_json::json; + +use crate::headless::Headless; +use crate::state::RightPanel; +use crate::{LightcraftApp, Services}; + +/// Burst 1: a (picked by culling), b, c; burst 2: d, e; f never culled. The grid, with the +/// Bursts panel open. +fn app() -> (Headless, [PhotoId; 6]) { + let mut session = lightcraft_engine::Session::new(); + let mut add = |name: &str, when: &str, culled: Option<(u32, f32, bool)>| { + let id = session.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: format!("/nowhere/{name}") }, name, "JPEG", 300, 200, "2026-05-01T12:00:00"); + p.captured = Some(when.into()); + p.analysis = culled.map(|(g, sharpness, best)| Analysis { sharpness, group: Some(g), best, ..Default::default() }); + session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id + }; + let ids = [ + add("a.jpg", "2026-05-01T10:00:00", Some((1, 80.0, true))), + add("b.jpg", "2026-05-01T10:00:01", Some((1, 60.0, false))), + add("c.jpg", "2026-05-01T10:00:02", Some((1, 40.0, false))), + add("d.jpg", "2026-05-01T11:00:00", Some((2, 70.0, true))), + add("e.jpg", "2026-05-01T11:00:01", Some((2, 30.0, false))), + add("f.jpg", "2026-05-01T12:00:00", None), + ]; + session.catalog.apply(Op::SetFlag { id: ids[0], flag: Flag::Pick }).unwrap(); + let mut h = Headless::new(LightcraftApp::new(session, Services { png: None, ..Default::default() }), [1400.0, 900.0], 1.0); + let r = h.request("ui.set", json!({"view": "photoGrid"}), std::time::Duration::from_secs(10)); + assert_eq!(r["ok"], true, "{r}"); + h.app.run("panel.bursts", json!({})).unwrap(); + for _ in 0..4 { + h.step(); + } + assert_eq!(h.app.ui.right, RightPanel::Bursts); + (h, ids) +} + +fn widget(h: &Headless, id: &str) -> Rect { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| { + panic!("no {id} in {:?}", h.app.widgets.iter().filter(|(w, _)| w.starts_with("burst")).map(|(w, _)| w).collect::>()) + }) +} + +fn cell(h: &Headless, id: PhotoId) -> Rect { + widget(h, &format!("burstPhoto:{}", id.0)) +} + +fn press(h: &mut Headless, at: Pos2) { + h.app.synthetic.push(egui::Event::PointerMoved(at)); + h.app.synthetic.push(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }); + h.step(); +} + +fn glide(h: &mut Headless, from: Pos2, to: Pos2) { + for i in 1..=8 { + h.app.synthetic.push(egui::Event::PointerMoved(from + (to - from) * (i as f32 / 8.0))); + h.step(); + } + // (synthetic input arrives a frame or two behind) + for _ in 0..3 { + h.step(); + } +} + +fn release(h: &mut Headless, at: Pos2) { + h.app.synthetic.push(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }); + h.step(); + h.step(); +} + +fn drag(h: &mut Headless, from: Pos2, to: Pos2) { + press(h, from); + glide(h, from, to); +} + +fn hint(h: &Headless) -> Option { + h.view.ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::new("drag-photos-hint"))).map(|(_, text)| text) +} + +fn best(h: &Headless, id: PhotoId) -> bool { + h.app.session.catalog.photo(id).unwrap().analysis.unwrap().best +} + +#[test] +fn bursts_show_their_pick_first() { + let (h, [a, b, c, d, e, f]) = app(); + // a row per burst, its pick first + let (one, two) = (widget(&h, "burst:1"), widget(&h, "burst:2")); + assert!(one.bottom() <= cell(&h, a).top() && cell(&h, e).top() >= two.bottom(), "each title above its photos"); + assert!(cell(&h, a).left() < cell(&h, b).left() && cell(&h, b).left() < cell(&h, c).left()); + assert!(cell(&h, d).left() < cell(&h, e).left()); + widget(&h, "burstPick:1"); + assert!(widget(&h, "burstPick:1").intersects(cell(&h, a)), "the pick is marked"); + // a photo culling never saw has no row; the drop places for a new burst and for none are there + assert!(!h.app.widgets.iter().any(|(w, _)| w == &format!("burstPhoto:{}", f.0))); + widget(&h, "burst:new"); + widget(&h, "burst:none"); +} + +#[test] +fn a_photo_dragged_to_the_front_becomes_the_pick() { + let (mut h, [a, b, c, ..]) = app(); + let to = pos2(cell(&h, a).left() + 4.0, cell(&h, a).center().y); + let from = cell(&h, c).center(); + drag(&mut h, from, to); + assert_eq!(h.app.ui.dragging_photos, Some(vec![c.0])); + assert_eq!(hint(&h).as_deref(), Some("Make it the pick")); + release(&mut h, to); + assert!(h.app.ui.dragging_photos.is_none()); + assert_eq!(h.app.session.catalog.burst(1), vec![c, a, b]); + assert!(best(&h, c) && !best(&h, a)); + assert_eq!(h.app.session.catalog.photo(c).unwrap().flag, Flag::Pick, "culling's Pick follows the pick"); + // the panel shows the new order + h.step(); + assert!(cell(&h, c).left() < cell(&h, a).left()); + // one undo step + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.catalog.burst(1), vec![a, b, c]); + assert!(best(&h, a)); +} + +#[test] +fn photos_move_between_bursts_and_bursts_merge() { + let (mut h, [a, b, c, d, e, _]) = app(); + let group = |h: &Headless, id: PhotoId| h.app.session.catalog.photo(id).unwrap().analysis.unwrap().group; + // e onto burst 1 between a and b; burst 2 is left with d alone: no burst any more + let to = pos2(cell(&h, b).left() + 4.0, cell(&h, b).center().y); + let from = cell(&h, e).center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Move to this burst")); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(1), vec![a, e, b, c]); + assert!(h.app.session.catalog.burst(2).is_empty() && group(&h, d).is_none()); + h.step(); + // d dragged from the grid onto burst 1's title goes last + let title = widget(&h, "burst:1").center(); + let from = widget(&h, &format!("thumb:{}", d.0)).center(); + drag(&mut h, from, title); + assert_eq!(hint(&h).as_deref(), Some("Move to this burst")); + release(&mut h, title); + assert_eq!(h.app.session.catalog.burst(1), vec![a, e, b, c, d]); + h.step(); + // b onto New Burst: a burst of its own, which c then joins by its title + let new = widget(&h, "burst:new").center(); + let from = cell(&h, b).center(); + drag(&mut h, from, new); + assert_eq!(hint(&h).as_deref(), Some("New burst")); + release(&mut h, new); + let g = group(&h, b).expect("a new burst"); + assert_eq!(h.app.session.catalog.burst(g), vec![b]); + h.step(); + let to = widget(&h, &format!("burst:{g}")).center(); + let from = cell(&h, c).center(); + drag(&mut h, from, to); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(g), vec![b, c]); + h.step(); + // e onto Not in a Burst + let out = widget(&h, "burst:none").center(); + let from = cell(&h, e).center(); + drag(&mut h, from, out); + assert_eq!(hint(&h).as_deref(), Some("Take out of its burst")); + release(&mut h, out); + assert!(group(&h, e).is_none()); + assert_eq!(h.app.session.catalog.burst(1), vec![a, d]); + h.step(); + // a burst dragged by its title onto another merges into it + let to = widget(&h, "burst:1").center(); + let from = widget(&h, &format!("burst:{g}")).center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Merge into this burst")); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(1), vec![a, d, b, c]); + assert!(h.app.session.catalog.burst(g).is_empty()); +} + +#[test] +fn a_photo_never_culled_is_refused() { + let (mut h, [_, _, _, _, _, f]) = app(); + let to = widget(&h, "burst:1").center(); + let from = widget(&h, &format!("thumb:{}", f.0)).center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Run Assisted Culling on it first")); + let commits = h.app.session.commits(); + release(&mut h, to); + assert_eq!(h.app.session.commits(), commits); + let toast = h.app.ui.toast.as_ref().map(|(t, _, _)| t.clone()).unwrap_or_default(); + assert!(toast.contains("Assisted Culling"), "{toast}"); +} From 507d4d344075f1705121ea767874886bf0c88610 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:04:54 +0200 Subject: [PATCH 014/331] LR-LIB-CULL: German strings and checklist for bursts arranged by hand Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/de.json | 24 +++++++++++++++++++++++- docs/parity-checklist.md | 5 +++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 4d08cbd4a4..9a9f6eaed6 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -2345,5 +2345,27 @@ "Checking the GPU…": "GPU wird geprüft …", "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "Ein Gesichtsmodell nutzt die GPU nur, wenn eine Prüfung zeigt, dass sie dieselben Ergebnisse schneller liefert.", - "Checking the GPU for faces": "GPU für Gesichter wird geprüft" + "Checking the GPU for faces": "GPU für Gesichter wird geprüft", + "Bursts": "Serien", + "Burst": "Serie", + "Photo → Assisted Culling… groups look-alike shots into bursts. They show here to put right by hand.": "Foto → Unterstützte Fotoauswahl… fasst ähnliche Aufnahmen zu Serien zusammen. Hier lassen sie sich von Hand korrigieren.", + "Drag a photo to its place: the first of a burst is its pick. Drag one into another burst, or a burst by its title onto another to merge them.": "Ziehe ein Foto an seinen Platz: Das erste einer Serie ist ihre Auswahl. Ziehe ein Foto in eine andere Serie oder eine Serie an ihrem Titel auf eine andere, um sie zusammenzuführen.", + "New burst": "Neue Serie", + "Not in a burst": "In keiner Serie", + "Run Assisted Culling on it first": "Zuerst die unterstützte Fotoauswahl darauf anwenden", + "Run Assisted Culling on these photos first": "Zuerst die unterstützte Fotoauswahl auf diese Fotos anwenden", + "Only photos Assisted Culling scored can be in a burst: run Photo → Assisted Culling… on them first": "Nur Fotos, die die unterstützte Fotoauswahl bewertet hat, können in einer Serie sein: Wende zuerst Foto → Unterstützte Fotoauswahl… darauf an", + "Merge into this burst": "Mit dieser Serie zusammenführen", + "Make it the pick": "Zur Auswahl machen", + "Put first: the first is the pick": "An den Anfang: Das erste ist die Auswahl", + "Move here": "Hierher verschieben", + "Move to this burst": "In diese Serie verschieben", + "Take out of its burst": "Aus der Serie nehmen", + "Regroup bursts I arranged by hand": "Von Hand geordnete Serien neu gruppieren", + "Put bursts right by dragging in Window → Bursts: the first photo of a burst is its pick, and culling again keeps what you arranged.": "Serien lassen sich unter Fenster → Serien per Ziehen korrigieren: Das erste Foto einer Serie ist ihre Auswahl, und eine erneute Fotoauswahl behält, was du geordnet hast.", + "Choose Burst Pick": "Auswahl der Serie wählen", + "Rearrange Burst": "Serie umordnen", + "Move to Burst": "In Serie verschieben", + "New Burst": "Neue Serie", + "Remove from Burst": "Aus Serie nehmen" } diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 32488a4dda..5d8c4f26fb 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-19 · **Change:** patch (LR-LIB-CULL: bursts can be stacked, best on top) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** patch (LR-LIB-CULL: bursts arranged by hand) · **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 @@ -116,7 +116,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-CAPTURETIME | Edit capture time | P1 | ✅ | `cmd:photo.setCaptureTime`, `cmd:dialog.captureTime`, `crates/catalog/src/dates.rs` | set (the other selected photos shift by the same amount, or `each`), shift by days/hours/minutes, time-zone shift; one undo step, journaled; Info panel button; no “revert to original capture time”. Impossible calendar dates cannot anchor relative shifts; rejection preserves metadata, selection, Undo and Redo. | | LR-LIB-SHOWFINDER | Reveal original in file manager | P0 | ✅ | `cmd:app.showInFinder` | ⌘R (see MENU-FILE-SHOWFINDER) | | LR-LIB-COVER | Album cover | P2 | ✅ | `cmd:album.setCover` | | -| LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `crates/pipeline/src/cull.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked, optionally stacked collapsed with the best photo on top (`stackGroups`, #2277; photos already stacked are left alone); reject below a focus score, pick each burst's best; classical measures — no eyes-closed / expression detection | +| LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `cmd:photo.moveToBurst`, `cmd:panel.bursts`, `crates/pipeline/src/cull.rs`, `crates/ui-egui/src/panels/bursts.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked, optionally stacked collapsed with the best photo on top (`stackGroups`, #2277; photos already stacked are left alone); reject below a focus score, pick each burst's best; bursts put right by hand in Window ▸ Bursts (drag a photo within its burst — first place is the pick, and the Pick flag culling set, Best of Similar Shots and a stacked burst's top follow — into another burst, a new one or none; drag a burst onto another to merge; kept when culling runs again unless *Regroup bursts I arranged by hand*); classical measures — no eyes-closed / expression detection | | LR-LIB-ACTIVITY | Comments & likes | OOS | 🚫 | | | | LR-LIB-QUICKCOLL | Quick collection [Classic] | P2 | ✅ | `cmd:album.toggleTarget`, `cmd:album.clearQuick` | B in the grids | | LR-LIB-VIRTUALCOPY | Virtual copies [Classic] | P1 | ✅ | `cmd:photo.virtualCopy`, `cmd:photo.delete`, `crates/engine/src/cmd/organize.rs` | “Copy N” badge, stacked with the original, same albums, no XMP writes; deleting a copy dissolves or renumbers the stack (#1493); no “Set Copy as Master” | @@ -797,6 +797,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-19 | patch | LR-LIB-CULL: bursts can be arranged by hand by drag and drop in Window ▸ Bursts; the first photo of a burst is its pick, and culling again keeps the arrangement (`photo.moveToBurst`, `panel.bursts`, `photo.analyze` `resetBursts`). Statuses and feature counts unchanged. | | 2026-10-19 | patch | LR-LIB-CULL: Assisted Culling can stack each burst collapsed with its best photo on top (dialog checkbox, `photo.analyze` `stackGroups`; #2277). Statuses and feature counts unchanged. | | 2026-10-19 | patch | LR-LIB-CULL: Assisted Culling's burst gap and similarity are adjustable (dialog, `photo.analyze` `burstGap` / `similarity`; #2275). Statuses and feature counts unchanged. | | 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. | From ffede6c9f78ae4697f6135b4634df9f74a04ec0e Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Mon, 19 Oct 2026 15:02:55 +0200 Subject: [PATCH 015/331] 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 663497fc71106584ca0d1fe974bbe36a805ea670 Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Mon, 19 Oct 2026 09:20:21 -0400 Subject: [PATCH 016/331] LR-PROF-CAMERACOLOR: negative channels render finite on CPU and GPU Raw decoding keeps negative channels since the previous commit. A noisy near-black frame through a saturating camera matrix, pushed 4 EV, renders finite with every slider at its ends, at every output depth with HDR on and off, and gives finite auto settings; the GPU matches the CPU on it across the equivalence cases. The camera-look lanes test gets its doc comment back, which the new tests had split from it. The previous commit's message says RENDER_CACHE_VERSION 66; it is 65. --- crates/engine/src/files.rs | 5 +-- crates/gpu/tests/equivalence.rs | 28 +++++++++++++++ crates/pipeline/src/tests.rs | 62 +++++++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 9c6f02852b..612e1d7458 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -1849,8 +1849,7 @@ pub(crate) mod tests { lightcraft_color::Mat3([[0.42, 0.548, 0.04], [0.246, 0.728, 0.033], [-0.247, 0.679, 0.447]]) } - /// A fitted camera look applied in lanes, on rows that aren't a whole number of them, gives the bits of the - /// pixel-by-pixel path, awkward pixels (black, negative, huge, NaN, infinite) included. + /// Decoding passes finite values through, negative ones included, and zeroes NaN and infinities. #[test] fn decoding_keeps_negative_channels_and_zeroes_non_finite_ones() { assert_eq!(finite([0.6, 0.05, -0.04]), [0.6, 0.05, -0.04]); @@ -1884,6 +1883,8 @@ pub(crate) mod tests { assert!(lo > 0.0 && hi / lo < 1.2, "mean {mean:?} is tinted"); } + /// A fitted camera look applied in lanes, on rows that aren't a whole number of them, gives the bits of the + /// pixel-by-pixel path, awkward pixels (black, negative, huge, NaN, infinite) included. #[test] fn camera_look_in_lanes_matches_pixel_by_pixel() { let data = (0..72 * 5 * 5).map(|i| [((i * 37) % 61) as f32 - 30.0, 0.6 + ((i * 11) % 13) as f32 / 13.0, 1.0]).collect(); diff --git a/crates/gpu/tests/equivalence.rs b/crates/gpu/tests/equivalence.rs index c877e3d9d8..aa37153ccc 100644 --- a/crates/gpu/tests/equivalence.rs +++ b/crates/gpu/tests/equivalence.rs @@ -877,3 +877,31 @@ fn windows_of_a_big_photo_share_one_uploaded_source() { lightcraft_gpu::render(&src, &info, &s, &at(1000), Some(&after)).expect("gpu render"); assert_eq!(lightcraft_gpu::source_uploads() - start, 2); } + +/// Raw decoding keeps negative channels (near-black sensor noise through a saturating camera matrix, a NIKON D780 +/// profile's): pushed and edited, the GPU renders them as the CPU does. +#[test] +fn negative_channels_match_cpu() { + if !gpu() { + return; + } + let m = [[3.48f32, -2.41, -0.06], [-0.41, 1.57, -0.16], [0.32, -1.86, 2.58]]; + let noise = |x: usize, y: usize, c: usize| { + let h = ((x * 7919 + y * 104_729 + c * 1_299_709) as u32).wrapping_mul(2_654_435_761); + (h >> 8) as f32 / (1u32 << 24) as f32 * 0.008 - 0.004 + }; + let src = Arc::new(Rgb32f::from_fn(320, 240, |x, y| { + let g = 0.0005 * 1.02f32.powi(x as i32); + let cam: [f32; 3] = std::array::from_fn(|c| g + noise(x, y, c)); + std::array::from_fn(|i| m[i][0] * cam[0] + m[i][1] * cam[1] + m[i][2] * cam[2]) + })); + assert!(src.data.iter().flatten().any(|v| *v < 0.0)); + let info = SourceInfo { raw: true, ..Default::default() }; + let req = RenderRequest::fit(320, 240); + for (name, edit) in cases() { + let mut s = DevelopSettings::default(); + edit(&mut s); + s.light.exposure += 4.0; + check(&format!("negatives +4 EV, {name}"), &src, &info, &s, &req); + } +} diff --git a/crates/pipeline/src/tests.rs b/crates/pipeline/src/tests.rs index 910705497e..7b38f86e3e 100644 --- a/crates/pipeline/src/tests.rs +++ b/crates/pipeline/src/tests.rs @@ -790,3 +790,65 @@ fn sliver_crops_render_quickly_with_wide_stages_on() { assert!(r.image.width >= 1 && r.image.height >= 1, "{rect:?}"); } } + +/// A raw's linear Rec.2020 as decoding leaves it since it stopped clamping channels at zero: a dark ramp with +/// sensor noise through a saturating camera matrix (a NIKON D780 profile's), so near black many channels are +/// negative, and a few strongly out-of-gamut pixels. +fn negative_noise() -> Rgb32f { + let m = [[3.48f32, -2.41, -0.06], [-0.41, 1.57, -0.16], [0.32, -1.86, 2.58]]; + // ±0.004 of noise per channel, a hash of the position + let noise = |x: usize, y: usize, c: usize| { + let h = ((x * 7919 + y * 104_729 + c * 1_299_709) as u32).wrapping_mul(2_654_435_761); + (h >> 8) as f32 / (1u32 << 24) as f32 * 0.008 - 0.004 + }; + Rgb32f::from_fn(48, 32, |x, y| { + if (x + y) % 37 == 0 { + return [-0.05, 0.01, -0.02]; + } + let g = 0.0005 * 1.15f32.powi(x as i32); + let cam: [f32; 3] = std::array::from_fn(|c| g + noise(x, y, c)); + std::array::from_fn(|i| m[i][0] * cam[0] + m[i][1] * cam[1] + m[i][2] * cam[2]) + }) +} + +/// Negative channels from decoding reach every stage after it: every slider at its ends, at every output depth +/// (HDR on and off), and the auto settings give finite values only. +#[test] +fn negative_channels_render_finite_everywhere() { + use crate::{DeepSamples, OutputDepth, auto}; + let src = negative_noise(); + assert!(src.data.iter().flatten().filter(|v| **v < 0.0).count() > src.data.len() / 4, "the source has few negatives"); + let info = SourceInfo { raw: true, ..Default::default() }; + let finite = |s: &DevelopSettings, depth: OutputDepth, what: &str| { + let r = render(&src, &info, s, &RenderRequest { depth, ..RenderRequest::fit(48, 48) }); + assert!(r.histogram.total > 0, "{what}"); + if let Some(DeepSamples::F32(v)) = r.deep.map(|d| d.samples) { + assert!(v.iter().all(|v| v.is_finite()), "{what} {depth:?}: non-finite output"); + } + }; + let mut pushed = DevelopSettings::default(); + pushed.light.exposure = 4.0; + pushed.light.shadows = 100.0; + pushed.light.blacks = 100.0; + for hdr in [false, true] { + let mut s = pushed.clone(); + s.hdr.enabled = hdr; + for depth in [OutputDepth::U8, OutputDepth::U16, OutputDepth::F32Linear, OutputDepth::F32Hdr] { + finite(&s, depth, &format!("pushed, hdr {hdr}")); + } + } + for c in controls::CONTROLS { + for v in [c.min, c.max] { + let mut s = pushed.clone(); + controls::set(&mut s, c.id, v); + finite(&s, OutputDepth::F32Linear, &format!("{} = {v}", c.id)); + } + } + let tone = auto::auto_tone(&src, &info, &pushed); + let t = [tone.exposure, tone.contrast, tone.highlights, tone.shadows, tone.whites, tone.blacks, tone.vibrance, tone.saturation]; + assert!(t.iter().all(|v| v.is_finite()), "auto tone {t:?}"); + assert!(auto::auto_bw_mix(&src, &info, &pushed).iter().all(|v| v.is_finite())); + let (t, k) = auto::auto_wb(&src, &info); + assert!(t.is_finite() && k.is_finite(), "auto WB {t} {k}"); + assert!(auto::scene_log_mean(&src, &info, &pushed).is_none_or(f64::is_finite)); +} From 7aeb1561ed574db776c9aae10166282307082ba7 Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Mon, 19 Oct 2026 15:25:25 +0200 Subject: [PATCH 017/331] 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 31a243ca28f5903b74761c2de28139dea80bc286 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:13:51 +0200 Subject: [PATCH 018/331] LR-LIB-CULL: Stack each burst stacks hand-arranged bursts; the panel lists bursts hidden in stacks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - photo.analyze with stackGroups now stacks a burst arranged by hand too, in its order with its pick on top; before, only the bursts culling grouped were stacked. - Window ▸ Bursts lists a burst whose photos are all hidden in another burst's collapsed stack (anchored after that stack's top), so it can be arranged. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cull.rs | 38 ++++++++++++++++++++++------- crates/engine/src/tests_bursts.rs | 6 +++++ crates/ui-egui/src/panels/bursts.rs | 10 +++++--- crates/ui-egui/src/tests_bursts.rs | 18 ++++++++++++++ 4 files changed, 60 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 76725a968c..4f5b2c93b5 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -109,24 +109,44 @@ fn analyze(s: &mut Session, p: &Value) -> Result { let mut stacks = 0; if stack_groups { // Photos already in a stack stay where they are (like `stack.auto`): a burst is stacked - // from its other photos when two or more remain, with the sharpest of those on top. + // from its other photos when two or more remain. A burst culling grouped has the sharpest + // of those on top; a burst arranged by hand keeps its order, its pick (place 0) on top. let index = s.catalog.stack_index(); let mut members: std::collections::BTreeMap> = Default::default(); - for (i, g) in group_of.iter().enumerate() { - if let (Some(g), Some(r)) = (g, rows.get(i)) - && !index.contains_key(&r.0) - && s.catalog.photo(r.0).is_some_and(|ph| !ph.deleted) - { - members.entry(*g).or_default().push((r.0, r.2)); + let mut arranged: std::collections::BTreeMap> = Default::default(); + for (i, r) in rows.iter().enumerate() { + if index.contains_key(&r.0) || !s.catalog.photo(r.0).is_some_and(|ph| !ph.deleted) { + continue; + } + match kept[i] { + Some(k) => { + if let Some(g) = k.group { + arranged.entry(g).or_default().push((k.rank.unwrap_or(u32::MAX), r.0)); + } + } + None => { + if let Some(g) = group_of[i] { + members.entry(g).or_default().push((r.0, r.2)); + } + } } } + let mut orders: Vec> = Vec::new(); for group in members.values() { let Some(top) = group.iter().fold(None::<(PhotoId, f32)>, |b, m| if b.is_none_or(|b| m.1 > b.1) { Some(*m) } else { b }) else { continue; }; - let photos: Vec = group.iter().map(|m| m.0).collect(); + let mut photos = vec![top.0]; + photos.extend(group.iter().map(|m| m.0).filter(|p| *p != top.0)); + orders.push(photos); + } + for group in arranged.values_mut() { + group.sort(); + orders.push(group.iter().map(|m| m.1).collect()); + } + for photos in orders { if photos.len() >= 2 - && let Some(op) = s.catalog.group_ops(top.0, &photos, true) + && let Some(op) = s.catalog.group_ops(photos[0], &photos, true) { ops.push(op); stacks += 1; diff --git a/crates/engine/src/tests_bursts.rs b/crates/engine/src/tests_bursts.rs index f402fbffe8..ff7ba98c69 100644 --- a/crates/engine/src/tests_bursts.rs +++ b/crates/engine/src/tests_bursts.rs @@ -239,6 +239,12 @@ fn culling_again_keeps_bursts_arranged_by_hand() { let g2_again = an(&s, second[0]).group.unwrap(); assert_ne!(g2_again, g1, "an automatic burst never takes a hand-made burst's number"); assert_eq!(s.catalog.burst(g2_again), second); + // stacking each burst stacks the one arranged by hand too, in its order, the pick on top + let r = s.execute("photo.analyze", &json!({"ids": ids(&[first.clone(), second.clone()].concat()), "stackGroups": true})).unwrap(); + assert_eq!(r["stacks"], 2, "{r}"); + let st = s.catalog.stack_of(softest).expect("the hand-arranged burst is stacked"); + assert_eq!(st.photos, vec![first[2], first[0], first[1]], "in the order set by hand, its pick on top"); + assert_eq!(s.catalog.stack_of(second[0]).map(|st| st.top()), Some(second[0]), "an automatic burst: the sharpest on top"); // asked to regroup, culling forgets the order set by hand s.execute("photo.analyze", &json!({"ids": ids(&first), "resetBursts": true})).unwrap(); let g = an(&s, first[0]).group.unwrap(); diff --git a/crates/ui-egui/src/panels/bursts.rs b/crates/ui-egui/src/panels/bursts.rs index 8a6d17fd9d..f03240e104 100644 --- a/crates/ui-egui/src/panels/bursts.rs +++ b/crates/ui-egui/src/panels/bursts.rs @@ -40,13 +40,17 @@ fn bursts(app: &mut LightcraftApp) -> Shown { return b.clone(); } let cat = &app.session.catalog; - let mut scope: HashSet = ids.iter().copied().collect(); + // each photo in view, then the hidden members of its stack: a burst whose photos are all + // hidden in another burst's collapsed stack is listed too, after that stack's top + let mut anchors: Vec = Vec::with_capacity(ids.len()); for id in ids.iter() { + anchors.push(*id); if let Some(st) = cat.stack_of(*id) { - scope.extend(st.photos.iter().copied()); + anchors.extend(st.photos.iter().copied().filter(|p| p != id)); } } - let b: Shown = Arc::new(cat.bursts_among(&ids, Some(&scope))); + let scope: HashSet = anchors.iter().copied().collect(); + let b: Shown = Arc::new(cat.bursts_among(&anchors, Some(&scope))); app.caches.bursts = Some((generation, b.clone())); b } diff --git a/crates/ui-egui/src/tests_bursts.rs b/crates/ui-egui/src/tests_bursts.rs index e7ce2858ba..f9e0d0c64d 100644 --- a/crates/ui-egui/src/tests_bursts.rs +++ b/crates/ui-egui/src/tests_bursts.rs @@ -115,6 +115,24 @@ fn bursts_show_their_pick_first() { widget(&h, "burst:none"); } +/// A burst whose photos are all hidden in a collapsed stack of another burst's photo is still +/// listed, so it can be arranged. +#[test] +fn a_burst_hidden_in_another_bursts_stack_is_listed() { + let (mut h, [a, _, _, d, e, _]) = app(); + h.app.session.selection.ids = vec![a, d, e]; + h.app.session.selection.active = Some(a); + h.app.session.execute("stack.group", &json!({"collapsed": true})).unwrap(); + for _ in 0..4 { + h.step(); + } + let visible = h.app.session.visible_cloned(); + assert!(visible.contains(&a) && !visible.contains(&d) && !visible.contains(&e), "d and e are hidden under a: {visible:?}"); + let (one, two) = (widget(&h, "burst:1"), widget(&h, "burst:2")); + assert!(one.top() < two.top(), "listed after the burst of the stack's top"); + assert!(cell(&h, d).top() >= two.bottom() && cell(&h, e).top() >= two.bottom(), "with its photos"); +} + #[test] fn a_photo_dragged_to_the_front_becomes_the_pick() { let (mut h, [a, b, c, ..]) = app(); 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 019/331] 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 da275f9c6c0ea197025d278e9a76f80d5e70a250 Mon Sep 17 00:00:00 2001 From: tecari0 <121329615+tecari0@users.noreply.github.com> Date: Mon, 19 Oct 2026 19:40:35 -0700 Subject: [PATCH 020/331] #2284: date files and the session clock in the host's time zone The catalog stores local civil times, but `system_clock` and `file_modified` both formatted an instant as UTC. A JPEG that carries no capture date is dated by its modification time, so one modified at 20:15 in UTC-5 was catalogued as 01:15 the next day; the same offset went into every `imported`, album `created` and `edited` stamp, and into the "added in the last N days" rules. `import::local_civil` converts an instant with the offset in force *then*, so a file from July keeps summer time when it is read in January. The zone comes from `jiff`, a native-only dependency: it has no dependencies of its own on Unix, where it reads the system database, and embeds one on Windows, which has no canonical copy. The web build keeps its fixed clock. `import::local_instant` is the inverse, so a test can pin a file's modification time to the local date it means whatever zone the machine is in; the fixtures that pinned a fixed epoch for that now use it. Existing catalogs keep the stamps they already hold: the zone they were written in is not recorded, so they are left alone rather than migrated. Co-Authored-By: Claude Opus 5 --- Cargo.lock | 86 +++++++++++++++++++++ Cargo.toml | 6 ++ crates/engine/Cargo.toml | 1 + crates/engine/src/files.rs | 15 +++- crates/engine/src/import.rs | 101 ++++++++++++++++++++++++- crates/engine/src/tests_import.rs | 9 ++- crates/engine/src/tests_import_move.rs | 9 ++- crates/ui-egui/src/headless.rs | 25 +++--- 8 files changed, 231 insertions(+), 21 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5d7f5111ac..386f5840a8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1199,6 +1199,37 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "defmt" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "defmt-parser" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "der" version = "0.7.10" @@ -2698,6 +2729,60 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jiff" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +dependencies = [ + "defmt", + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "jixel" version = "0.3.4" @@ -3225,6 +3310,7 @@ dependencies = [ "ab_glyph", "craft-docpath", "harfrust", + "jiff", "jxl-oxide", "libc", "lightcraft-catalog", diff --git a/Cargo.toml b/Cargo.toml index cf21739d89..0e9dd8ecef 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,6 +57,12 @@ siphasher = "1" libc = "0.2" # dev-only: process CPU time in benches dhat = "0.3" # opt-in heap profiling (lightcraft-cli --features dhat-heap) and heap tests; never in product builds +# The host's time zone: the catalog stores local civil times, so a file's modification time and +# the session clock need the UTC offset in force at that instant (DST included). Native only; the +# web build keeps its fixed clock. Zero dependencies on Unix (it reads the system tzdb); on Windows +# it embeds one, since Windows has no canonical copy. +jiff = { version = "0.2", default-features = false, features = ["std", "tz-system", "tzdb-zoneinfo", "tzdb-bundle-platform"] } + # formats quick-xml = "0.38" miniz_oxide = "0.8" diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 091efe0661..8d3a445ed2 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -46,6 +46,7 @@ lightcraft-segment = { workspace = true, optional = true } # model downloads run natively only (the web build fetches no models) [target.'cfg(not(target_arch = "wasm32"))'.dependencies] lightcraft-fetch = { workspace = true } +jiff = { workspace = true } [features] # AI masks with SAM 3 (Object / Describe). Off for the web and CLI builds. diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 31bb930fbf..600c72b1a8 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -1083,11 +1083,12 @@ pub fn fs_hooks() -> (FileLoader, FileProbe) { } /// `path`'s modification time as ISO 8601 (see [`ProbeInfo::file_modified`]); `None` when the -/// filesystem doesn't say or the time is before 1970. +/// filesystem doesn't say or the time is before 1970. In the host's time zone, like every date the +/// catalog stores: this is the capture date of a file that carries none of its own. fn file_modified(path: &str) -> Option { let t = std::fs::metadata(path).ok()?.modified().ok()?; let secs = i64::try_from(t.duration_since(std::time::UNIX_EPOCH).ok()?.as_secs()).ok()?; - Some(crate::import::civil(secs)) + Some(crate::import::local_civil(secs)) } impl crate::Session { @@ -1498,8 +1499,16 @@ pub(crate) mod tests { let path = dir.join("export.jpg"); std::fs::write(&path, &jpeg).unwrap(); let path = path.to_string_lossy().to_string(); + // The case reported in issue #2284: a JPEG that went through a messenger keeps no capture + // date, only a modification time, here 2026-10-18 20:15:11 in UTC-5. Pinning it also dates + // the file in the other half of the year from "now", so a zone with summer time is read at + // the right instant and not at today's offset. + let shot = lightcraft_meta::DateTime::parse_iso("2026-10-19T01:15:11Z").unwrap().unix_seconds(); + let when = std::time::UNIX_EPOCH + std::time::Duration::from_secs(u64::try_from(shot).unwrap()); + std::fs::File::options().write(true).open(&path).unwrap().set_modified(when).unwrap(); let mtime = std::fs::metadata(&path).unwrap().modified().unwrap().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs(); - let want = crate::import::civil(mtime as i64); + assert_eq!(mtime as i64, shot, "the file date is the one the test set"); + let want = crate::import::local_civil(mtime as i64); let (_, probe) = fs_hooks(); let info = probe(&path).unwrap(); assert_eq!(info.captured, None, "the file itself has no date"); diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 9aa847b01f..7e26027cf6 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -1515,7 +1515,7 @@ pub fn system_clock() -> String { #[cfg(not(target_arch = "wasm32"))] { let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0); - civil(secs) + local_civil(secs) } #[cfg(target_arch = "wasm32")] { @@ -1528,6 +1528,50 @@ pub fn civil(secs: i64) -> String { lightcraft_catalog::dates::civil(secs) } +/// Unix seconds → `YYYY-MM-DDTHH:MM:SS` in the host's time zone: the local civil time every date +/// the catalog stores is in (`captured`, `imported`, an album's `created`, an edit's `edited`). +/// +/// The offset is the one in force *at that instant*, not today's, so a photo from July keeps +/// summer time when it is read in January. A host whose zone cannot be read falls back to UTC, as +/// the web build does (issue #2284: a file with no capture date was dated by its modification time +/// in UTC, which put an evening photo on the next day). +#[cfg(not(target_arch = "wasm32"))] +pub fn local_civil(secs: i64) -> String { + // The zone is read once: it holds the whole rule set, so each instant still gets the offset + // that was in force then, and an import does not re-read the system database per file. + static ZONE: std::sync::OnceLock = std::sync::OnceLock::new(); + civil_in(secs, ZONE.get_or_init(jiff::tz::TimeZone::system)) +} + +/// [`local_civil`] in a given zone. `jiff::TimeZone::system` falls back to a zone that behaves +/// like UTC when the host has none to read, and an instant outside the range it can represent +/// (far outside the range of a file date) keeps its UTC reading rather than failing an import. +#[cfg(not(target_arch = "wasm32"))] +fn civil_in(secs: i64, zone: &jiff::tz::TimeZone) -> String { + let offset = jiff::Timestamp::from_second(secs).map(|t| i64::from(zone.to_offset_info(t).offset().seconds())).unwrap_or(0); + civil(secs.saturating_add(offset)) +} + +#[cfg(target_arch = "wasm32")] +pub fn local_civil(secs: i64) -> String { + civil(secs) +} + +/// The instant at which the host's zone reads `civil` (`YYYY-MM-DDTHH:MM:SS`): the inverse of +/// [`local_civil`]. `None` when the text is not a civil date-time, or when the host's zone has no +/// such moment (the hour a spring-forward skips). Tests pin a file's modification time with it, so +/// that an undated file takes the local date they mean whatever zone the machine is in. +#[cfg(not(target_arch = "wasm32"))] +pub fn local_instant(civil: &str) -> Option { + let when: jiff::civil::DateTime = civil.trim().parse().ok()?; + when.to_zoned(jiff::tz::TimeZone::system()).ok().map(|z| z.timestamp().as_second()) +} + +#[cfg(target_arch = "wasm32")] +pub fn local_instant(civil: &str) -> Option { + lightcraft_catalog::dates::iso_seconds(civil) +} + impl Session { /// A thumbnail for an import candidate (not in the catalog): a raw's embedded preview, else a /// small render of the file. `slot` makes the job's photo id unique (`u64::MAX - slot`). @@ -1585,6 +1629,61 @@ impl Session { #[path = "import/tests_known.rs"] mod tests_known; +#[cfg(test)] +mod clock_tests { + use super::*; + + /// Issue #2284: an instant becomes the civil time the host's own zone shows for it, with the + /// offset in force *then*. The reported case is a JPEG with no capture date whose modification + /// time is 2026-10-18 20:15:11 in UTC-5: dated by `civil` it read 01:15 the next day. + #[test] + fn local_civil_reads_the_hosts_zone_at_that_instant() { + let zone = jiff::tz::TimeZone::system(); + // the report, then one in each half of the year (so a zone with DST uses both offsets), + // one on a year boundary, and one before the epoch + for iso in ["2026-10-19T01:15:11Z", "2026-07-04T12:00:00Z", "2026-01-15T23:30:00Z", "2027-01-01T00:00:00Z", "1969-12-31T23:59:59Z"] { + let secs = lightcraft_meta::DateTime::parse_iso(iso).expect("a test timestamp").unix_seconds(); + let zoned = jiff::Timestamp::from_second(secs).expect("in range").to_zoned(zone.clone()); + assert_eq!(local_civil(secs), zoned.strftime("%Y-%m-%dT%H:%M:%S").to_string(), "{iso}"); + } + } + + /// The reported numbers, against a fixed UTC-5 zone, so they are checked on any host: a CI + /// runner set to UTC would make the test above agree with itself and prove nothing. + #[test] + fn an_evening_in_utc_minus_5_stays_that_evening() { + let secs = lightcraft_meta::DateTime::parse_iso("2026-10-19T01:15:11Z").expect("a test timestamp").unix_seconds(); + assert_eq!(civil(secs), "2026-10-19T01:15:11", "the UTC reading the file used to be dated by"); + let zone = jiff::tz::TimeZone::fixed(jiff::tz::offset(-5)); + assert_eq!(civil_in(secs, &zone), "2026-10-18T20:15:11"); + // and the other way, so the sign cannot be read backwards + assert_eq!(civil_in(secs, &jiff::tz::TimeZone::fixed(jiff::tz::offset(2))), "2026-10-19T03:15:11"); + } + + /// `local_instant` undoes `local_civil`, so a fixture can pin a file to a local date. + #[test] + fn local_instant_is_the_inverse_of_local_civil() { + for iso in ["2026-01-14T05:58:48", "2026-07-04T12:00:00", "2026-10-18T20:15:11"] { + let secs = local_instant(iso).expect("a local instant"); + assert_eq!(local_civil(secs), iso); + } + assert_eq!(local_instant("not a date"), None); + } + + /// Whatever the host's zone, what it produces is a date the rest of the catalog can read back, + /// and it differs from UTC only by a whole number of minutes no larger than a real offset. + #[test] + fn local_civil_is_a_catalog_date_within_a_real_offset_of_utc() { + let secs = lightcraft_meta::DateTime::parse_iso("2026-10-19T01:15:11Z").expect("a test timestamp").unix_seconds(); + let local = local_civil(secs); + let read = lightcraft_catalog::dates::iso_seconds(&local).expect("a date the catalog can read"); + let shift = read - secs; + assert_eq!(shift % 60, 0, "{local}"); + assert!(shift.abs() <= 18 * 3600, "{local}"); + assert_eq!(lightcraft_catalog::dates::normalize_iso(&local).as_deref(), Some(local.as_str())); + } +} + #[cfg(test)] mod prepared_tests { use super::*; diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs index 13f02ce778..07b8634ad1 100644 --- a/crates/engine/src/tests_import.rs +++ b/crates/engine/src/tests_import.rs @@ -13,6 +13,9 @@ fn temp_dir(tag: &str) -> std::path::PathBuf { d } +/// The clock these tests run on; an undated file is pinned to it too (see `write_png`). +const CLOCK: &str = "2026-01-14T05:58:48"; + /// A small procedural PNG (distinct per seed). fn write_png(path: &Path, seed: u8) { let (w, h) = (48usize, 32usize); @@ -21,8 +24,10 @@ fn write_png(path: &Path, seed: u8) { let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(path, bytes).unwrap(); - // undated files take the file's date: the tests' clock time (2026-01-14T05:58:48) - let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_768_370_328); + // Undated files take the file's date, read in the host's zone (issue #2284), so the file is + // pinned to the instant this machine reads as the tests' clock time rather than to a fixed one. + let secs = crate::import::local_instant(CLOCK).and_then(|s| u64::try_from(s).ok()).unwrap_or(0); + let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs); std::fs::File::options().write(true).open(path).unwrap().set_modified(t).unwrap(); } diff --git a/crates/engine/src/tests_import_move.rs b/crates/engine/src/tests_import_move.rs index ce249df161..2b328c5bc6 100644 --- a/crates/engine/src/tests_import_move.rs +++ b/crates/engine/src/tests_import_move.rs @@ -15,6 +15,9 @@ fn temp_dir(tag: &str) -> PathBuf { d } +/// The clock these tests run on; an undated file is pinned to it too (see `write_png`). +const CLOCK: &str = "2026-01-14T05:58:48"; + fn write_png(path: &Path, seed: u8) { let (w, h) = (40usize, 24usize); let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 5) as u8, (i / w * 7) as u8, seed, 255]).collect(); @@ -22,8 +25,10 @@ fn write_png(path: &Path, seed: u8) { let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(path, bytes).unwrap(); - // undated files take the file's date: the tests' clock time (2026-01-14T05:58:48) - let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_768_370_328); + // Undated files take the file's date, read in the host's zone (issue #2284), so the file is + // pinned to the instant this machine reads as the tests' clock time rather than to a fixed one. + let secs = crate::import::local_instant(CLOCK).and_then(|s| u64::try_from(s).ok()).unwrap_or(0); + let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs); std::fs::File::options().write(true).open(path).unwrap().set_modified(t).unwrap(); } diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rs index 1d8b584010..173c4f2fb8 100644 --- a/crates/ui-egui/src/headless.rs +++ b/crates/ui-egui/src/headless.rs @@ -3862,6 +3862,12 @@ mod tests { let _ = std::fs::remove_dir_all(&base); } + /// The instant this machine reads as the tests' clock time: an undated file takes the file's + /// date in the host's zone, so a fixed epoch would file it on the day before west of UTC. + fn filed_at() -> u64 { + lightcraft_engine::import::local_instant("2026-01-14T05:58:48").and_then(|s| u64::try_from(s).ok()).unwrap_or(0) + } + /// Import review, Copy, Folders → Custom template…: the default `{date:%Y}/{date:%Y%m%d}` /// files copies under `2026/20260114/`, the example line shows the full destination, and a /// template that would climb out of the destination is refused. @@ -3874,13 +3880,10 @@ mod tests { let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[40, 3, 9, 255]; 64] }; let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); std::fs::write(src.join("IMG_01.png"), png).unwrap(); - // undated files are filed by the file's date (2026-01-14T05:58:48) - std::fs::File::options() - .write(true) - .open(src.join("IMG_01.png")) - .unwrap() - .set_modified(std::time::UNIX_EPOCH + Duration::from_secs(1_768_370_328)) - .unwrap(); + // Undated files are filed by the file's date, read in the host's zone (issue #2284), so + // the file is pinned to the instant this machine reads as 2026-01-14T05:58:48. + let when = std::time::UNIX_EPOCH + Duration::from_secs(filed_at()); + std::fs::File::options().write(true).open(src.join("IMG_01.png")).unwrap().set_modified(when).unwrap(); let dest_s = dest.to_string_lossy().to_string(); let services = crate::Services { png: None, pick_folder: Some(Box::new(move || Some(dest_s.clone()))), ..Default::default() }; let mut session = lightcraft_engine::Session::with_demo().with_fs(); @@ -3933,12 +3936,8 @@ mod tests { let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[40 + i, 3, 9, 255]; 64] }; let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); std::fs::write(src.join(format!("IMG_0{i}.png")), png).unwrap(); - std::fs::File::options() - .write(true) - .open(src.join(format!("IMG_0{i}.png"))) - .unwrap() - .set_modified(std::time::UNIX_EPOCH + Duration::from_secs(1_768_370_328)) - .unwrap(); + let when = std::time::UNIX_EPOCH + Duration::from_secs(filed_at()); + std::fs::File::options().write(true).open(src.join(format!("IMG_0{i}.png"))).unwrap().set_modified(when).unwrap(); } let dest_s = dest.to_string_lossy().to_string(); let services = crate::Services { png: None, pick_folder: Some(Box::new(move || Some(dest_s.clone()))), ..Default::default() }; From 8a3d51b78bd5dc979ffcb43ccacf13cac87a168c Mon Sep 17 00:00:00 2001 From: tecari0 <121329615+tecari0@users.noreply.github.com> Date: Mon, 19 Oct 2026 20:10:01 -0700 Subject: [PATCH 021/331] #2284: local_instant answers nothing for an hour a spring-forward removed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The doc comment claimed it, the code did not do it: jiff's ordinary civil → instant conversion resolves a gap by moving past it, so 02:30 on a spring-forward morning came back as the instant of 03:30 — a time that reads back as something else, which is no inverse at all. It now asks the zone first and answers `None` for a gap. An hour a fall-back repeats keeps the first of the two, which is what the conversion already did and is now written down. The zone lookup moves into `system_zone`, and `instant_in` takes the zone so the gap and the fold can be tested against America/New_York instead of whatever zone the machine is in. Reported by CodeRabbit on PR #2381. Co-Authored-By: Claude Opus 5 --- crates/engine/src/import.rs | 55 ++++++++++++++++++++++++++++++++----- 1 file changed, 48 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 7e26027cf6..8013756791 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -1537,10 +1537,15 @@ pub fn civil(secs: i64) -> String { /// in UTC, which put an evening photo on the next day). #[cfg(not(target_arch = "wasm32"))] pub fn local_civil(secs: i64) -> String { - // The zone is read once: it holds the whole rule set, so each instant still gets the offset - // that was in force then, and an import does not re-read the system database per file. + civil_in(secs, system_zone()) +} + +/// The host's zone, read once: it holds the whole rule set, so each instant still gets the offset +/// that was in force then, and an import does not re-read the system database per file. +#[cfg(not(target_arch = "wasm32"))] +fn system_zone() -> &'static jiff::tz::TimeZone { static ZONE: std::sync::OnceLock = std::sync::OnceLock::new(); - civil_in(secs, ZONE.get_or_init(jiff::tz::TimeZone::system)) + ZONE.get_or_init(jiff::tz::TimeZone::system) } /// [`local_civil`] in a given zone. `jiff::TimeZone::system` falls back to a zone that behaves @@ -1558,13 +1563,26 @@ pub fn local_civil(secs: i64) -> String { } /// The instant at which the host's zone reads `civil` (`YYYY-MM-DDTHH:MM:SS`): the inverse of -/// [`local_civil`]. `None` when the text is not a civil date-time, or when the host's zone has no -/// such moment (the hour a spring-forward skips). Tests pin a file's modification time with it, so -/// that an undated file takes the local date they mean whatever zone the machine is in. +/// [`local_civil`]. Tests pin a file's modification time with it, so that an undated file takes +/// the local date they mean whatever zone the machine is in. #[cfg(not(target_arch = "wasm32"))] pub fn local_instant(civil: &str) -> Option { + instant_in(civil, system_zone()) +} + +/// [`local_instant`] in a given zone. `None` when the text is not a civil date-time, or when the +/// zone has no such moment: an hour a spring-forward removes is not a time anything happened at, +/// and jiff's ordinary conversion would answer with the instant an hour later, which reads back as +/// a different time and so is not an inverse at all. An hour a fall-back repeats takes the first +/// of the two. +#[cfg(not(target_arch = "wasm32"))] +fn instant_in(civil: &str, zone: &jiff::tz::TimeZone) -> Option { let when: jiff::civil::DateTime = civil.trim().parse().ok()?; - when.to_zoned(jiff::tz::TimeZone::system()).ok().map(|z| z.timestamp().as_second()) + let ambiguous = zone.to_ambiguous_zoned(when); + match ambiguous.offset() { + jiff::tz::AmbiguousOffset::Gap { .. } => None, + _ => ambiguous.earlier().ok().map(|z| z.timestamp().as_second()), + } } #[cfg(target_arch = "wasm32")] @@ -1670,6 +1688,29 @@ mod clock_tests { assert_eq!(local_instant("not a date"), None); } + /// The hour a spring-forward removes is no instant at all, so there is nothing to answer with: + /// jiff's ordinary conversion returns the hour after the gap, which would pin a file to a time + /// it does not read back as. The hour a fall-back repeats takes the first of the two. + #[test] + fn a_local_time_a_spring_forward_removed_has_no_instant() { + let Ok(zone) = jiff::tz::TimeZone::get("America/New_York") else { + lightcraft_testkit::skip!(System, "no IANA time zone database to read America/New_York from"); + return; + }; + // 2026-03-08: 02:00 becomes 03:00, so nothing happened at 02:30 + assert_eq!(instant_in("2026-03-08T02:30:00", &zone), None); + // the hours either side of the gap are ordinary, and round-trip + for iso in ["2026-03-08T01:30:00", "2026-03-08T03:30:00"] { + let secs = instant_in(iso, &zone).expect("either side of the gap"); + assert_eq!(civil_in(secs, &zone), iso); + } + // 2026-11-01: 02:00 becomes 01:00, so 01:30 happens twice; the first is the one in summer + // time, 05:30 UTC, and it reads back as what was asked for + let fold = instant_in("2026-11-01T01:30:00", &zone).expect("the repeated hour"); + assert_eq!(fold, lightcraft_meta::DateTime::parse_iso("2026-11-01T05:30:00Z").expect("a test timestamp").unix_seconds()); + assert_eq!(civil_in(fold, &zone), "2026-11-01T01:30:00"); + } + /// Whatever the host's zone, what it produces is a date the rest of the catalog can read back, /// and it differs from UTC only by a whole number of minutes no larger than a real offset. #[test] From a5e943364187b69a37a908ed7182a4e17a684ab1 Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Wed, 21 Oct 2026 07:31:07 +0200 Subject: [PATCH 022/331] 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 b1cd4b923aed6f16283af0e3eab2c73afa941a74 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:33:37 +0200 Subject: [PATCH 023/331] LR-LIB-CULL: a photo dragged to the front takes the Pick even over a Reject; a burst dragged by its title takes all its photos MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - photo.moveToBurst: when the Pick moves to a new first photo, that photo takes it whatever its flag; it was chosen by hand, so a Reject (from Reject below, say) no longer leaves the burst without a pick flag. - Window ▸ Bursts: dragging a burst by its title drags every photo of the burst, not only those in view, so a merge leaves none behind; the "Merge into this burst" label compares with the whole burst too. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cull.rs | 5 ++--- crates/engine/src/tests_bursts.rs | 6 ++++++ crates/ui-egui/src/panels/bursts.rs | 8 ++++++-- crates/ui-egui/src/tests_bursts.rs | 20 ++++++++++++++++++++ 4 files changed, 34 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 4f5b2c93b5..13687ac935 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -286,9 +286,8 @@ fn move_to_burst(s: &mut Session, p: &Value) -> Result { if !is_pick(old_pick) { flags.insert(old_pick, Flag::None); } - if let Some(n) = new_pick - && flag(s, n) == Flag::None - { + // the new pick was chosen by hand: it takes the Pick even over a Reject + if let Some(n) = new_pick { flags.insert(n, Flag::Pick); } } diff --git a/crates/engine/src/tests_bursts.rs b/crates/engine/src/tests_bursts.rs index ff7ba98c69..04f2706624 100644 --- a/crates/engine/src/tests_bursts.rs +++ b/crates/engine/src/tests_bursts.rs @@ -72,6 +72,12 @@ fn a_photo_dragged_to_the_front_of_its_burst_becomes_the_pick() { assert_eq!(s.catalog.burst(1), vec![a, c, b]); assert!(an(&s, a).best); assert_eq!(flag(&s, a), Flag::Pick); + // a rejected shot dragged to the front was chosen by hand: it takes the Pick + s.catalog.apply(Op::SetFlag { id: b, flag: Flag::Reject }).unwrap(); + mv(&mut s, json!({"ids": [b.0], "index": 0})); + assert_eq!((flag(&s, b), flag(&s, a)), (Flag::Pick, Flag::None)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((flag(&s, b), flag(&s, a)), (Flag::Reject, Flag::Pick)); // placing a photo where it already is changes nothing and makes no undo step let commits = s.commits(); let r = mv(&mut s, json!({"ids": [a.0], "index": 0})); diff --git a/crates/ui-egui/src/panels/bursts.rs b/crates/ui-egui/src/panels/bursts.rs index f03240e104..060b8cda7f 100644 --- a/crates/ui-egui/src/panels/bursts.rs +++ b/crates/ui-egui/src/panels/bursts.rs @@ -98,8 +98,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if resp.hovered() && dragged.is_none() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); } + // the whole burst, also its photos out of view if resp.drag_started() { - app.ui.dragging_photos = Some(photos.iter().map(|p| p.0).collect()); + app.ui.dragging_photos = Some(app.session.catalog.burst(*g).iter().map(|p| p.0).collect()); } if pointer.is_some_and(|p| title.contains(p)) { target = Some((Target::Burst(*g, n), None)); @@ -246,7 +247,10 @@ fn drop_on(app: &mut LightcraftApp, ui: &mut egui::Ui, shown: &Shown, ids: &[Pho let members = shown.iter().find(|(n, _)| *n == g).map(|(_, m)| m.as_slice()).unwrap_or(&[]); // the place once the dragged photos have left theirs let index = members.iter().take(slot).filter(|m| !ids.contains(m)).count(); - let whole = shown.iter().any(|(n, m)| *n != g && m.len() > 1 && m.len() == ids.len() && m.iter().all(|p| ids.contains(p))); + let whole = shown.iter().any(|(n, _)| { + let all = app.session.catalog.burst(*n); + *n != g && all.len() > 1 && all.len() == ids.len() && all.iter().all(|p| ids.contains(p)) + }); let hint = if whole { "Merge into this burst" } else if index == 0 && slot < members.len() { diff --git a/crates/ui-egui/src/tests_bursts.rs b/crates/ui-egui/src/tests_bursts.rs index f9e0d0c64d..03f44f57a3 100644 --- a/crates/ui-egui/src/tests_bursts.rs +++ b/crates/ui-egui/src/tests_bursts.rs @@ -223,3 +223,23 @@ fn a_photo_never_culled_is_refused() { let toast = h.app.ui.toast.as_ref().map(|(t, _, _)| t.clone()).unwrap_or_default(); assert!(toast.contains("Assisted Culling"), "{toast}"); } + +/// A burst dragged by its title takes all its photos along, also those the view leaves out. +#[test] +fn a_burst_dragged_by_its_title_takes_its_photos_out_of_view() { + let (mut h, [a, b, c, d, e, _]) = app(); + // only the picks are in view: e (of burst 2) is left out + let r = h.app.session.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "bestOfGroup", "op": "is", "value": true}]}})).unwrap(); + assert!(r.is_object(), "{r}"); + for _ in 0..4 { + h.step(); + } + assert!(!h.app.session.visible_cloned().contains(&e), "e is out of view"); + let to = widget(&h, "burst:1").center(); + let from = widget(&h, "burst:2").center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Merge into this burst")); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(1), vec![a, b, c, d, e], "e came along"); + assert!(h.app.session.catalog.burst(2).is_empty()); +} From a2dd47d682ee55fbf6786b94b365d532114caab9 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:44:03 +0200 Subject: [PATCH 024/331] LR-LIB-CULL: Bursts panel drops land in the whole burst; one burst index per catalog change - A photo dropped after a shown photo of a burst goes right after it in the whole burst, before the members the view leaves out; a drop on the title or after the last photo still goes last. - The burst index a drag compares with (the title drag, the merge label) is built once per view generation and cached, not once per burst on every frame of the drag. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 3 ++ crates/ui-egui/src/panels/bursts.rs | 59 +++++++++++++++++++++++------ crates/ui-egui/src/tests_bursts.rs | 18 +++++++++ 3 files changed, 68 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8cfc5d8a95..4ee5ce4ae0 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1637,6 +1637,9 @@ pub struct Caches { keyword_tree: Option<(u64, std::sync::Arc>)>, /// The Bursts panel's bursts, by the view's generation. bursts: Option<(u64, panels::bursts::Shown)>, + /// Every burst of the library (pick first), by the view's generation: what a drag in the + /// Bursts panel compares with, so a frame of the drag builds no index of its own. + burst_index: Option<(u64, panels::bursts::All)>, /// The Keywording box's read-only names (with containing keywords, or Will Export), by library /// revision, selection and view. keyword_names: Option<(u64, u64, std::sync::Arc>)>, diff --git a/crates/ui-egui/src/panels/bursts.rs b/crates/ui-egui/src/panels/bursts.rs index 060b8cda7f..de5092fac5 100644 --- a/crates/ui-egui/src/panels/bursts.rs +++ b/crates/ui-egui/src/panels/bursts.rs @@ -10,7 +10,7 @@ //! Widgets: `burst:{n}` (a burst's title, `n` its number), `burstPhoto:{id}`, `burstPick:{n}`, //! `burst:new`, `burst:none`. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; @@ -55,10 +55,31 @@ fn bursts(app: &mut LightcraftApp) -> Shown { b } +/// Every burst of the library: its number → its photos, pick first. +pub type All = Arc>>; + +/// Every burst of the library, built once per view generation (it follows every catalog change). +fn all_bursts(app: &mut LightcraftApp) -> All { + let (generation, _) = app.session.visible_shared(); + if let Some((g, b)) = &app.caches.burst_index + && *g == generation + { + return b.clone(); + } + let b: All = Arc::new(app.session.catalog.burst_index()); + app.caches.burst_index = Some((generation, b.clone())); + b +} + +/// A [`Target::Burst`] slot after every photo of the burst: a drop on its title or after its +/// last photo. +const LAST: usize = usize::MAX; + /// Where a drop under the pointer would put the dragged photos. #[derive(Clone, Copy, PartialEq, Debug)] enum Target { - /// Burst `n` at `slot` (a place among its photos as shown, the dragged ones included). + /// Burst `n` at `slot` (a place among its photos as shown, the dragged ones included; + /// [`LAST`]: after every photo of the burst, those out of view too). Burst(u32, usize), New, Nowhere, @@ -100,10 +121,10 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } // the whole burst, also its photos out of view if resp.drag_started() { - app.ui.dragging_photos = Some(app.session.catalog.burst(*g).iter().map(|p| p.0).collect()); + app.ui.dragging_photos = Some(all_bursts(app).get(g).map(|m| m.iter().map(|p| p.0).collect()).unwrap_or_default()); } if pointer.is_some_and(|p| title.contains(p)) { - target = Some((Target::Burst(*g, n), None)); + target = Some((Target::Burst(*g, LAST), None)); } // the photos, in rows let rows = n.div_ceil(cols); @@ -132,7 +153,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { { // the room after the last photo: last let last = cell_at(n.saturating_sub(1)); - target = Some((Target::Burst(*g, n), Some(Rect::from_min_max(pos2(last.right() + GAP / 2.0 - 1.5, last.top()), pos2(last.right() + GAP / 2.0 + 1.5, last.bottom()))))); + target = Some((Target::Burst(*g, LAST), Some(Rect::from_min_max(pos2(last.right() + GAP / 2.0 - 1.5, last.top()), pos2(last.right() + GAP / 2.0 + 1.5, last.bottom()))))); } if dragged.is_some() && matches!(target, Some((Target::Burst(tg, _), _)) if tg == *g) { ui.painter().rect_stroke(title.union(area).shrink2(vec2(8.0, 1.0)), 4.0, Stroke::new(1.0, t.accent.gamma_multiply(0.6)), StrokeKind::Inside); @@ -244,13 +265,27 @@ fn drop_on(app: &mut LightcraftApp, ui: &mut egui::Ui, shown: &Shown, ids: &[Pho } let (params, hint) = match tgt { Target::Burst(g, slot) => { + let all = all_bursts(app); let members = shown.iter().find(|(n, _)| *n == g).map(|(_, m)| m.as_slice()).unwrap_or(&[]); - // the place once the dragged photos have left theirs - let index = members.iter().take(slot).filter(|m| !ids.contains(m)).count(); - let whole = shown.iter().any(|(n, _)| { - let all = app.session.catalog.burst(*n); - *n != g && all.len() > 1 && all.len() == ids.len() && all.iter().all(|p| ids.contains(p)) - }); + // the place in the whole burst (members the view leaves out included) once the dragged + // photos have left theirs: right after the last shown member before the slot + let rest: Vec = all.get(&g).map(|m| m.iter().copied().filter(|p| !ids.contains(p)).collect()).unwrap_or_default(); + let index = if slot == LAST { + rest.len() + } else { + members[..slot.min(members.len())] + .iter() + .rev() + .find(|m| !ids.contains(m)) + .and_then(|m| rest.iter().position(|p| p == m)) + .map_or(0, |i| i + 1) + }; + // the dragged photos are a whole other burst (one lookup: the first one's burst) + let from = ids.first().and_then(|id| app.session.catalog.photo(*id)).and_then(|p| p.analysis).and_then(|a| a.group); + let whole = from + .filter(|n| *n != g) + .and_then(|n| all.get(&n)) + .is_some_and(|m| m.len() > 1 && m.len() == ids.len() && m.iter().all(|p| ids.contains(p))); let hint = if whole { "Merge into this burst" } else if index == 0 && slot < members.len() { @@ -260,7 +295,7 @@ fn drop_on(app: &mut LightcraftApp, ui: &mut egui::Ui, shown: &Shown, ids: &[Pho } else { "Move to this burst" }; - let index = if slot >= members.len() { Value::Null } else { json!(index) }; + let index = if index >= rest.len() { Value::Null } else { json!(index) }; (json!({"ids": ids.iter().map(|p| p.0).collect::>(), "burst": g, "index": index}), hint) } Target::New => (json!({"ids": ids.iter().map(|p| p.0).collect::>(), "burst": "new"}), "New burst"), diff --git a/crates/ui-egui/src/tests_bursts.rs b/crates/ui-egui/src/tests_bursts.rs index 03f44f57a3..e6618152b5 100644 --- a/crates/ui-egui/src/tests_bursts.rs +++ b/crates/ui-egui/src/tests_bursts.rs @@ -243,3 +243,21 @@ fn a_burst_dragged_by_its_title_takes_its_photos_out_of_view() { assert_eq!(h.app.session.catalog.burst(1), vec![a, b, c, d, e], "e came along"); assert!(h.app.session.catalog.burst(2).is_empty()); } + +/// A photo dropped after a shown member lands right after it in the whole burst, before the +/// members the view leaves out, not after them. +#[test] +fn a_drop_after_a_shown_photo_goes_before_the_photos_out_of_view() { + let (mut h, [a, b, c, d, _, _]) = app(); + // only the picks are in view: burst 1 shows a, its b and c are left out + h.app.session.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "bestOfGroup", "op": "is", "value": true}]}})).unwrap(); + for _ in 0..4 { + h.step(); + } + let to = pos2(cell(&h, a).right() - 4.0, cell(&h, a).center().y); + let from = cell(&h, d).center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Move to this burst")); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(1), vec![a, d, b, c], "right after a, before b and c"); +} From e1ab84a94503bc4b1bf42b4d7151d861e4dc8599 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:57:23 +0200 Subject: [PATCH 025/331] LR-LIB-CULL: a drop in the Bursts panel keeps its side of the photo it is on With a member out of view between two shown photos, a drop on the left half of the second one now goes right before it, and a drop on the right half of the first right after that one; they used to land in the same place. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/bursts.rs | 22 ++++++++++++++-------- crates/ui-egui/src/tests_bursts.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/bursts.rs b/crates/ui-egui/src/panels/bursts.rs index de5092fac5..305271d492 100644 --- a/crates/ui-egui/src/panels/bursts.rs +++ b/crates/ui-egui/src/panels/bursts.rs @@ -79,8 +79,9 @@ const LAST: usize = usize::MAX; #[derive(Clone, Copy, PartialEq, Debug)] enum Target { /// Burst `n` at `slot` (a place among its photos as shown, the dragged ones included; - /// [`LAST`]: after every photo of the burst, those out of view too). - Burst(u32, usize), + /// [`LAST`]: after every photo of the burst, those out of view too), dropped on the left half + /// of the photo at `slot` (`true`: right before it) or the right half of the one before. + Burst(u32, usize, bool), New, Nowhere, } @@ -124,7 +125,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { app.ui.dragging_photos = Some(all_bursts(app).get(g).map(|m| m.iter().map(|p| p.0).collect()).unwrap_or_default()); } if pointer.is_some_and(|p| title.contains(p)) { - target = Some((Target::Burst(*g, LAST), None)); + target = Some((Target::Burst(*g, LAST, false), None)); } // the photos, in rows let rows = n.div_ceil(cols); @@ -144,7 +145,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { { let slot = if p.x < r.center().x { i } else { i + 1 }; let edge = if slot == i { r.left() - GAP / 2.0 } else { r.right() + GAP / 2.0 }; - target = Some((Target::Burst(*g, slot), Some(Rect::from_min_max(pos2(edge - 1.5, r.top()), pos2(edge + 1.5, r.bottom()))))); + target = Some((Target::Burst(*g, slot, slot == i), Some(Rect::from_min_max(pos2(edge - 1.5, r.top()), pos2(edge + 1.5, r.bottom()))))); } } if target.is_none() @@ -153,9 +154,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { { // the room after the last photo: last let last = cell_at(n.saturating_sub(1)); - target = Some((Target::Burst(*g, LAST), Some(Rect::from_min_max(pos2(last.right() + GAP / 2.0 - 1.5, last.top()), pos2(last.right() + GAP / 2.0 + 1.5, last.bottom()))))); + target = Some((Target::Burst(*g, LAST, false), Some(Rect::from_min_max(pos2(last.right() + GAP / 2.0 - 1.5, last.top()), pos2(last.right() + GAP / 2.0 + 1.5, last.bottom()))))); } - if dragged.is_some() && matches!(target, Some((Target::Burst(tg, _), _)) if tg == *g) { + if dragged.is_some() && matches!(target, Some((Target::Burst(tg, ..), _)) if tg == *g) { ui.painter().rect_stroke(title.union(area).shrink2(vec2(8.0, 1.0)), 4.0, Stroke::new(1.0, t.accent.gamma_multiply(0.6)), StrokeKind::Inside); } } @@ -264,14 +265,19 @@ fn drop_on(app: &mut LightcraftApp, ui: &mut egui::Ui, shown: &Shown, ids: &[Pho return; } let (params, hint) = match tgt { - Target::Burst(g, slot) => { + Target::Burst(g, slot, before) => { let all = all_bursts(app); let members = shown.iter().find(|(n, _)| *n == g).map(|(_, m)| m.as_slice()).unwrap_or(&[]); // the place in the whole burst (members the view leaves out included) once the dragged - // photos have left theirs: right after the last shown member before the slot + // photos have left theirs: right before the photo dropped on, or right after the one + // whose right half it was (members out of view between them stay on their side) let rest: Vec = all.get(&g).map(|m| m.iter().copied().filter(|p| !ids.contains(p)).collect()).unwrap_or_default(); + let at = |m: &PhotoId| rest.iter().position(|p| p == m); + let next = members.get(slot..).and_then(|after| after.iter().find(|m| !ids.contains(m))); let index = if slot == LAST { rest.len() + } else if let Some(i) = next.filter(|_| before).and_then(at) { + i } else { members[..slot.min(members.len())] .iter() diff --git a/crates/ui-egui/src/tests_bursts.rs b/crates/ui-egui/src/tests_bursts.rs index e6618152b5..429ce1eee7 100644 --- a/crates/ui-egui/src/tests_bursts.rs +++ b/crates/ui-egui/src/tests_bursts.rs @@ -261,3 +261,30 @@ fn a_drop_after_a_shown_photo_goes_before_the_photos_out_of_view() { release(&mut h, to); assert_eq!(h.app.session.catalog.burst(1), vec![a, d, b, c], "right after a, before b and c"); } + +/// Between two shown photos with one out of view between them, a drop on the left half of the +/// second goes right before it, a drop on the right half of the first right after that one. +#[test] +fn a_drop_keeps_its_side_of_a_photo_out_of_view() { + let (mut h, [a, b, c, d, _, _]) = app(); + // b is left out: burst 1 shows a, c + h.app.session.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "fileName", "op": "notContains", "value": "b.jpg"}]}})).unwrap(); + for _ in 0..4 { + h.step(); + } + assert!(!h.app.session.visible_cloned().contains(&b)); + let before_c = pos2(cell(&h, c).left() + 4.0, cell(&h, c).center().y); + let from = cell(&h, d).center(); + drag(&mut h, from, before_c); + release(&mut h, before_c); + assert_eq!(h.app.session.catalog.burst(1), vec![a, b, d, c], "right before c"); + h.app.run("edit.undo", json!({})).unwrap(); + for _ in 0..4 { + h.step(); + } + let after_a = pos2(cell(&h, a).right() - 4.0, cell(&h, a).center().y); + let from = cell(&h, d).center(); + drag(&mut h, from, after_a); + release(&mut h, after_a); + assert_eq!(h.app.session.catalog.burst(1), vec![a, d, b, c], "right after a"); +} From 7a50c7fb594764b626e0a1466b85b83533a841e7 Mon Sep 17 00:00:00 2001 From: Patrik Lermon Date: Thu, 22 Oct 2026 16:01:10 +0200 Subject: [PATCH 026/331] i18n(sv): translate 1074 new strings, use the agreed terms in 16 Brings the Swedish catalog up to date with upstream main (c66014e6). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/sv.json | 1108 +++++++++++++++++++++++++++++++- 1 file changed, 1091 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 76f08c2d38..fcea297678 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -132,7 +132,7 @@ "any": "någon", "Any camera": "Valfri kamera", "Any keyword": "Valfritt nyckelord", - "Any lens": "Valfri lins", + "Any lens": "Valfritt objektiv", "Any Searchable Text": "All sökbar text", "Aperture": "Bländare", "Appearance": "Utseende", @@ -663,7 +663,7 @@ "Effect": "Effekt", "Effects": "Effekter", "Empty Recently Deleted": "Töm Nyligen raderade", - "Enable Lens Corrections": "Aktivera linskorrigeringar", + "Enable Lens Corrections": "Aktivera objektivkorrigeringar", "Enable Profile Corrections": "Aktivera profilkorrigeringar", "End": "Slut", "End Interaction": "Avsluta interaktion", @@ -909,8 +909,8 @@ "HDR TIFF needs 32-bit float.": "HDR TIFF kräver 32-bitars flyttal.", "HDR with Last Settings": "HDR med senaste inställningar", "HDR…": "HDR…", - "Heal": "Läk", - "Heal the small, soft dark spots sensor dust leaves on smooth areas": "Läk de små, mjuka mörka fläckar som sensordamm lämnar på jämna ytor", + "Heal": "Retuschera", + "Heal the small, soft dark spots sensor dust leaves on smooth areas": "Retuschera de små, mjuka mörka fläckar som sensordamm lämnar på jämna ytor", "Height": "Höjd", "Height (px)": "Höjd (px)", "Help": "Hjälp", @@ -944,7 +944,7 @@ "Hue": "Nyans", "Hue Range": "Nyansintervall", "I have read these terms and accept them for my own use": "Jag har läst villkoren och godkänner dem för eget bruk", - "Identity plate": "Identitetsplåt", + "Identity plate": "Namnskylt", "If file exists": "Om filen finns", "If your library can't be opened at launch (open in another program, unreadable, on a drive that isn't connected,": "Om ditt bibliotek inte kan öppnas vid start (öppet i ett annat program, oläsbart, på en enhet som inte är ansluten,", "ignored before) chooses the graphics backend; `off` renders on the CPU. The GPU now starts after the window": "ignorerades tidigare) väljer grafikbakänden; `off` renderar på CPU:n. GPU:n startar nu efter att fönstret", @@ -1116,9 +1116,9 @@ "leaves no DNG and keeps the raw. Smart previews are written the same way; a damaged one (cut short by a crash or": "lämnar ingen DNG och behåller rawfilen. Smarta förhandsgranskningar skrivs på samma sätt; en skadad (avbruten av en krasch eller", "Left": "Vänster", "Left: the standard (SDR) range up to SDR white. Right: the HDR range, one band per stop above SDR white (the orange line: the HDR headroom). With Visualize HDR range on, the bands take its colours.": "Vänster: standardomfånget (SDR) upp till SDR-vitt. Höger: HDR-omfånget, ett band per steg över SDR-vitt (den orange linjen: HDR-marginalen). När Visualisera HDR-omfång är på får banden dess färger.", - "Lens": "Lins", + "Lens": "Objektiv", "Lens Blur": "Linsoskärpa", - "Lens Corrections": "Linskorrigeringar", + "Lens Corrections": "Objektivkorrigeringar", "Level": "Nivå", "Library": "Bibliotek", "Library Folders": "Biblioteksmappar", @@ -1218,8 +1218,8 @@ "Match": "Matcha", "Match Total Exposures": "Matcha total exponering", "Matrix/TRC": "Matris/TRC", - "Matte": "Matte", - "Matte Soft": "Matte mjuk", + "Matte": "Matt", + "Matte Soft": "Matt mjuk", "Med": "Medel", "Medium Contrast": "Medelkontrast", "Megapixels": "Megapixel", @@ -1393,12 +1393,12 @@ "No keywords match": "Inga nyckelord matchar", "No keywords yet": "Inga nyckelord än", "No Label": "Ingen etikett", - "No lens data embedded in this file (DNG lens opcodes only).": "Inga linsdata finns inbäddade i den här filen (endast DNG-linsopkoder).", - "No lens data embedded in this file.": "Inga linsdata finns inbäddade i den här filen.", + "No lens data embedded in this file (DNG lens opcodes only).": "Inga objektivdata finns inbäddade i den här filen (endast DNG-objektivopkoder).", + "No lens data embedded in this file.": "Inga objektivdata finns inbäddade i den här filen.", "No masks yet. Choose a mask type above.": "Inga masker än. Välj en masktyp ovan.", "No matching commands": "Inga matchande kommandon", "No matching photos": "Inga matchande foton", - "No Matte": "Ingen matte", + "No Matte": "Ingen matthet", "No metadata found": "Inga metadata hittades", "No model credits were built into this copy.": "Inga modellkrediteringar finns inbyggda i den här kopian.", "No named people in these photos": "Inga namngivna personer i de här fotona", @@ -1437,7 +1437,7 @@ "Nothing to compare": "Inget att jämföra", "Nothing to survey": "Inget att granska", "now develop from the raw data instead of the camera's embedded JPEG, so a B&W or other picture style set in the": "framkallas nu från rådata i stället för kamerans inbäddade JPEG, så en svartvit eller annan bildstil som ställts in i", - "Nudge Develop Value": "Knuffa framkallningsvärde", + "Nudge Develop Value": "Flytta framkallningsvärde stegvis", "Numbered JPEG files (name-001.jpg…) in a new folder named in the next step.": "Numrerade JPEG-filer (namn-001.jpg…) i en ny mapp som du namnger i nästa steg.", "Object": "Objekt", "Object and Describe masks use SAM 3, Meta's segmentation model. It isn't part of LightCraft, and everything else works without it.": "Masker av typen Objekt och Beskriv använder SAM 3, Metas segmenteringsmodell. Den ingår inte i LightCraft, och allt annat fungerar utan den.", @@ -1558,7 +1558,7 @@ "Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.": "Foton som hamnar i den här mappen (tethering, en skanner, en synkapp) läggs till så fort de är kompletta.", "photos waiting": "foton väntar", "Photos); importing (also by drag and drop), Find Missing Photos, Build / Discard Smart Previews, the Rename preview,": "Foton); import (även med dra och släpp), Hitta saknade foton, Skapa/släng smarta förhandsgranskningar, förhandsgranskningen för Byt namn,", - "Pick": "Plocka", + "Pick": "Välj", "pick": "vald", "Pick a colour on the photo with the eyedropper.": "Välj en färg i fotot med pipetten.", "Pick a date": "Välj ett datum", @@ -1704,7 +1704,7 @@ "Red Luminance": "Röd luminans", "Red Primary": "Röd primärfärg", "Red Saturation": "Röd mättnad", - "Red/Cyan Fringe": "Röd/cyan fransning", + "Red/Cyan Fringe": "Röd/cyan färgkant", "Redo": "Gör om", "Reference": "Referens", "Reference the files where they are": "Referera till filerna där de ligger", @@ -2181,7 +2181,7 @@ "the graphics card is not used": "grafikkortet används inte", "The graphics card is set up when the next photo is made.": "Grafikkortet konfigureras när nästa foto skapas.", "The import reads the catalog without changing it and adds its photos, edits, keywords and collections to the library open now.": "Importen läser katalogen utan att ändra den och lägger till dess foton, redigeringar, nyckelord och samlingar i biblioteket som är öppet nu.", - "The intro plays once before the first photo; the ending after the last photo when Repeat is off. The identity plate is the one set under Overlays. Titles fade like slides and random order never moves them.": "Introt spelas en gång före det första fotot; avslutningen efter det sista fotot när Upprepa är av. Identitetsplåten är den som angetts under Överlägg. Titlar tonas som bilderna och slumpmässig ordning flyttar dem aldrig.", + "The intro plays once before the first photo; the ending after the last photo when Repeat is off. The identity plate is the one set under Overlays. Titles fade like slides and random order never moves them.": "Introt spelas en gång före det första fotot; avslutningen efter det sista fotot när Upprepa är av. Namnskylten är den som angetts under Överlägg. Titlar tonas som bilderna och slumpmässig ordning flyttar dem aldrig.", "The intro screen, before the first photo.": "Introskärmen, före det första fotot.", "the JPEG uses `IMG_0001.JPG.xmp`.": "JPEG-filen använder `IMG_0001.JPG.xmp`.", "The layout image can't be shown": "Layoutbilden kan inte visas", @@ -2414,5 +2414,1079 @@ "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-dra för att räta upp, ⇧G guidad upprätning, ett rutnät under transformering.", "★ Favorites": "★ Favoriter", "日本語": "日本語", - "繁體中文(台灣)": "繁體中文(台灣)" + "繁體中文(台灣)": "繁體中文(台灣)", + "\"24.0-70.0 mm f/2.8\". Those cameras don't write a lens name, so the lens field was empty and you couldn't filter or": "\"24.0-70.0 mm f/2.8\". De kamerorna skriver inget objektivnamn, så objektivfältet var tomt och du kunde inte filtrera eller", + "\"Albums\" header takes it back to the top level; Esc cancels; holding a dragged album or photos near the top or bottom edge of the sidebar scrolls it). Drop on the top or bottom half of another album,": "Rubriken \"Album\" tar den tillbaka till översta nivån; Esc avbryter; håller du ett draget album eller foton nära sidofältets över- eller nederkant rullas det). Släpp på övre eller nedre halvan av ett annat album,", + "\"Canon CRX adaptive QP value 172\" or \"175\". They now decode from the sensor data. Photos imported before this": "\"Canon CRX adaptive QP value 172\" eller \"175\". Nu avkodas de från sensordata. Foton som importerats före denna", + "\"File exists\".": "\"File exists\".", + "\"HEIC/HEIF support isn't included in this build\" for each `.heic`/`.heif` at import.": "\"HEIC/HEIF-stöd ingår inte i det här bygget\" för varje `.heic`/`.heif` vid import.", + "\"If file exists\" works per folder as usual, and an original is never written over.": "\"Om filen finns\" fungerar per mapp som vanligt, och ett original skrivs aldrig över.", + "\"LightCraft stopped unexpectedly\" and why, instead of \"could not open its window\", and the next start renders": "\"LightCraft har stoppats oväntat\" och varför, i stället för \"kunde inte öppna sitt fönster\", och nästa start renderar", + "\"Rendering…\" on the photo": "\"Renderar…\" på fotot", + "#1236). The D7000, D5100, D800, D800E, Df, D4, D3, D3S, D700, D300, D300S, D600, D610, D810, D4S, D5600,": "#1236). D7000, D5100, D800, D800E, Df, D4, D3, D3S, D700, D300, D300S, D600, D610, D810, D4S, D5600,", + "#1440): a Sony α1 face reads 8 MB instead of 70 MB, an A7S III face about 1 MB instead of 24 MB, several times": "#1440): för ett ansikte i en Sony α1-bild läses 8 MB i stället för 70 MB, i en A7S III-bild ungefär 1 MB i stället för 24 MB, flera gånger", + "#1447), or keeps the photo you had when the folder holds it. Before, the photo from the previous view stayed active:": "#1447), eller behåller fotot du hade när mappen innehåller det. Tidigare förblev fotot från föregående vy aktivt:", + "(\"Failed to associate portal window with parent window\" in the portal's log): tiling compositors put it beside the": "(\"Failed to associate portal window with parent window\" i portalens logg): fönsterhanterare med tiling lade den bredvid", + "(`album.setRules` takes `name`).": "(`album.setRules` tar `name`).", + "(`id`, `parent?`, `before?`) and `album.sort`.": "(`id`, `parent?`, `before?`) och `album.sort`.", + "(`render in.raw -o out.jxl`). Quality as for JPEG, or Lossless; Effort (Fast / Normal) trades time for a": "(`render in.raw -o out.jxl`). Kvalitet som för JPEG, eller Förlustfri; Ansträngning (Snabb / Normal) väger tid mot en", + "(`slideshow.exportStatus` for the result).": "(`slideshow.exportStatus` för resultatet).", + "(checked on one CC0 iPhone 12 Pro ProRAW). Photos without mattes are unchanged.": "(kontrollerat på en CC0-bild i iPhone 12 Pro ProRAW). Foton utan segmenteringsmasker är oförändrade.", + "(Esc keeps the old angle; a decimal comma works too), or click the Straighten value; hovering any slider's value now says it can be typed.": "(Esc behåller den gamla vinkeln; decimalkomma fungerar också), eller klicka på värdet för Räta upp; när du hovrar över ett reglagevärde står det nu att det kan skrivas in.", + "(folders open on click) or finds them as you type part of a name or folder (↑ / ↓ and Enter to pick); albums that": "(mappar öppnas vid klick) eller hittar dem medan du skriver en del av ett namn eller en mapp (↑ / ↓ och Enter för att välja); album som", + "(issue #1455), up to 512 MP and 65,000 pixels on the long edge, as in Lightroom. When the full size needs more": "(ärende #1455), upp till 512 MP och 65 000 pixlar på långsidan, som i Lightroom. När full storlek kräver mer", + "(issue #256): the correction the camera records in the file is applied under Lens Corrections ▸ Enable Profile": "(ärende #256): korrigeringen som kameran registrerar i filen tillämpas under Objektivkorrigeringar → Aktivera profil", + "(issue #706; before, the import skipped it as \"already in the library\" while the grid showed it deleted). The": "(ärende #706; tidigare hoppade importen över den som \"redan i biblioteket\" medan rutnätet visade den som raderad). Den", + "(issue #735).": "(ärende #735).", + "(issue #782).": "(ärende #782).", + "(issues #187, #298). Importing files that are in Recently Deleted asks whether to leave them there, restore them": "(ärenden #187, #298). När du importerar filer som finns i Nyligen raderade får du frågan om du vill låta dem vara kvar där, återställa dem", + "(its width over its height was 0 / 0, which stopped debug builds); it shows as a single pixel's colour.": "(dess bredd genom höjd var 0 / 0, vilket stoppade debug-byggen); den visas som färgen på en enda pixel.", + "(macOS, Windows, Linux, FreeBSD, Nix) now really are built with HEIC support; a build without it reports": "(macOS, Windows, Linux, FreeBSD, Nix) byggs nu verkligen med HEIC-stöd; ett bygge utan det rapporterar", + "(now 0.05 s). The scan looks up only the files it finds and the contents it reads, on its own thread.": "(nu 0,05 s). Genomsökningen slår bara upp de filer den hittar och det innehåll den läser, i en egen tråd.", + "(Space, G, X, ⌫) and ⌘ shortcuts were not affected.": "(Blanksteg, G, X, ⌫) och ⌘-kortkommandon påverkades inte.", + "(with their edits) or import them as new; the trash view's Photo menu has Empty Recently Deleted.": "(med sina redigeringar) eller importera dem som nya; skräpvyns Foto-meny har Töm Nyligen raderade.", + "(~0.6 s per slider tick); now the list is saved only after it changes, and a slider tick takes ~2 ms.": "(~0,6 s per reglagesteg); nu sparas listan bara när den har ändrats, och ett reglagesteg tar ~2 ms.", + ")": ")", + "**Import Lightroom Catalog…** with that catalog, or Cancel. `lightcraft-cli --library` refuses those folders too.": "**Importera Lightroom-katalog…** med den katalogen, eller Avbryt. `lightcraft-cli --library` vägrar också öppna de mapparna.", + "**JPEG:** numbered files (`Holiday-001.jpg`, `Holiday-002.jpg`…) in a new folder.": "**JPEG:** numrerade filer (`Holiday-001.jpg`, `Holiday-002.jpg`…) i en ny mapp.", + "**PDF:** one page per slide at 1024, 1920 or 3840 pixels on the long side, at a JPEG quality you choose. Each page": "**PDF:** en sida per bild med 1024, 1920 eller 3840 pixlar på långsidan, med en JPEG-kvalitet du väljer. Varje sida", + "**Photos already in your library get theirs in the background**: LightCraft reads just the few kilobytes of each": "**Foton som redan finns i biblioteket får sina i bakgrunden**: LightCraft läser bara de få kilobyte i varje", + "**Video:** AV1 video in an MP4 (or WebM) file at 720p or 1080p, 24 or 30 frames per second: each slide stays up for": "**Video:** AV1-video i en MP4-fil (eller WebM) med 720p eller 1080p, 24 eller 30 bilder per sekund: varje bild visas i", + "**Z zooms to it**: Toggle Zoom centres on the focus point, so checking that the subject is sharp is one key": "**Z zoomar till den**: Växla zoom centrerar på fokuspunkten, så att kontrollera att motivet är skarpt kräver bara en tangent", + "0.3 MB of JPEG instead of 5.6 MB and is ready several times sooner; Nikon and Panasonic raws with a mid-sized": "0,3 MB JPEG i stället för 5,6 MB och är klar flera gånger snabbare; raw-filer från Nikon och Panasonic med en medelstor", + "1200D (Rebel T5) and 100D (Rebel SL1) now count as clipped (issue #1272). They used to stop at 81–98% of white, so": "1200D (Rebel T5) och 100D (Rebel SL1) räknas nu som klippta (ärende #1272). De stannade tidigare vid 81–98 % av vitt, så", + "12–32 mm kit zoom was off by about 5 % of the image width at the corners before. Files shot with the correction off": "12–32 mm-kitzoom avvek tidigare med ungefär 5 % av bildbredden i hörnen. Filer som fotograferats med korrigeringen avstängd", + "1440 px at the corners, where it was up to 17 px off before. The camera's lateral chromatic aberration table is read": "1440 px i hörnen, där det tidigare var upp till 17 px fel. Kamerans tabell för lateral kromatisk aberration läses", + "150 dpi · sRGB · current edits · fit without cropping": "150 dpi · sRGB · aktuella redigeringar · anpassa utan beskärning", + "16 GB, 355 MP with 32 GB) and the message says so. The merge also frees each photo's pixels once they are": "16 GB, 355 MP med 32 GB) och meddelandet säger det. Sammanfogningen frigör också varje fotos pixlar så snart de är", + "16-bit Rec. 2020 PQ. Not in the web version yet.": "16-bitars Rec. 2020 PQ. Inte i webbversionen än.", + "2026-10-02": "2026-10-02", + "2026-10-05": "2026-10-05", + "2026-10-07": "2026-10-07", + "2026-10-08": "2026-10-08", + "2026-10-09": "2026-10-09", + "2026-10-10": "2026-10-10", + "2026-10-11": "2026-10-11", + "2026-10-12": "2026-10-12", + "2026-10-13": "2026-10-13", + "2026-10-14": "2026-10-14", + "3396 K, one on the Shade preset 7493 K. As for #730, only the numbers change: edits made on the old relative": "3396 K, ett med förinställningen Skugga 7493 K. Liksom för #730 ändras bara siffrorna: redigeringar gjorda på den gamla relativa", + "67,000 photos that step went from 37 ms to under 1 ms. Still worked out whole: an edit to more than 256 photos, a": "67 000 foton gick det steget från 37 ms till under 1 ms. Räknas fortfarande ut i sin helhet: en redigering av fler än 256 foton, en", + "[camera preview colour](camera-preview-colour.md#spectral-camera-matrices-and-the-order-of-precedence).": "[kamerans förhandsgranskningsfärg](camera-preview-colour.md#spectral-camera-matrices-and-the-order-of-precedence).", + "`*.jpg` case-sensitively, so `.JPG` and `.NEF` files were hidden — issues #342 and #705).": "`*.jpg` skiftlägeskänsligt, så `.JPG`- och `.NEF`-filer doldes — ärenden #342 och #705).", + "`--import ` takes HEIC": "`--import ` tar med HEIC", + "`--memory` sessions keep their promise to save nothing (issues #164, #169): UI changes made in one no longer": "`--memory`-sessioner håller sitt löfte att inte spara något (ärenden #164, #169): gränssnittsändringar som görs i en sådan session inte längre", + "`.jpg`) have always been taken for the cache's, and are renamed with it.": "`.jpg`) har alltid räknats som cachens och byter namn tillsammans med den.", + "`.lrcat-data` folders, or the `.lrcat`) no longer makes an empty LightCraft library inside it (issue #891). The": "`.lrcat-data`-mappar, eller `.lrcat`) skapar inte längre ett tomt LightCraft-bibliotek inuti den (ärende #891).", + "`destinationMode: \"sameAsOriginal\"` (or `\"specificFolder\"`) to `app.export`; `dir` is then not needed.": "`destinationMode: \"sameAsOriginal\"` (eller `\"specificFolder\"`) till `app.export`; `dir` behövs då inte.", + "`develop.curve` are kept in order, and a sidecar curve with a \"NaN\" or \"inf\" point is ignored.": "`develop.curve` behålls i ordning, och en kurva i en sidecar-fil med en \"NaN\"- eller \"inf\"-punkt ignoreras.", + "`export.photosImports`. See [Add to Apple Photos](apple-photos.md).": "`export.photosImports`. Se [Lägg till i Apple Photos](apple-photos.md).", + "`lightcraft-cli --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`lightcraft-cli --library` som får ett biblioteks egen fil (`catalog.snap`) öppnar dess mapp i stället för att misslyckas med", + "`lightcraft-cli run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`lightcraft-cli run --import ` (och MCP-verktygen som tar mappar) tar nu med HEIC, HEIF och Nikon NRW", + "`lightcraft-cli` logs warnings on stderr too (issue #168); `LIGHTCRAFT_LOG` or `RUST_LOG` picks another level.": "`lightcraft-cli` loggar varningar även på stderr (ärende #168); `LIGHTCRAFT_LOG` eller `RUST_LOG` väljer en annan nivå.", + "`mask.brushStroke {connect: true}` does the same for agents.": "`mask.brushStroke {connect: true}` gör samma sak för agenter.", + "`publicDomain` (rules and agents keep using the ids; `album.ruleFields` adds `choiceLabels`).": "`publicDomain` (regler och agenter använder fortfarande id:na; `album.ruleFields` lägger till `choiceLabels`).", + "`Shift+6–9` labels and advances. `Shift+P` picks and advances in Photo Grid and Square Grid; it opens Presets in other views. With Auto Advance on, Shift still moves only once.": "`Shift+6–9` sätter etikett och går vidare. `Shift+P` flaggar som vald och går vidare i Fotorutnät och Kvadratiskt rutnät; i andra vyer öppnar det Förinställningar. Med Gå vidare automatiskt på flyttar Shift ändå bara en gång.", + "`slideshow.overlays`; `slideshow.preview` now also returns where each overlay landed.": "`slideshow.overlays`; `slideshow.preview` returnerar nu även var varje överlägg hamnade.", + "`slideshow.playback`; `view.slideshow` takes any of them for one run (`interval` still sets the slide duration).": "`slideshow.playback`; `view.slideshow` tar vilken som helst av dem för en körning (`interval` anger fortfarande visningstiden per bild).", + "`{file}`, `{date}`, `{exposure}` (\"1/250 s at f/8\"), `{iso}`, `{focal}`, `{camera}`, `{lens}`, `{rating}` and the": "`{file}`, `{date}`, `{exposure}` (\"1/250 s vid f/8\"), `{iso}`, `{focal}`, `{camera}`, `{lens}`, `{rating}` och", + "A `thumbs` folder that holds nothing but the cache says that it is one (`CACHEDIR.TAG`), so backup programs that": "En `thumbs`-mapp som inte innehåller något annat än cachen anger att den är en sådan (`CACHEDIR.TAG`), så att säkerhetskopieringsprogram som", + "a cast shadow (opacity, offset, radius, angle), and a backdrop colour with an optional colour wash (a gradient from a": "en slagskugga (opacitet, förskjutning, radie, vinkel) och en fondfärg med valfri färgslöja (en gradient från en", + "A crop a hair wide (or of no size), set by an agent or read from a sidecar, no longer crashes or hangs the": "En beskärning som är hårfint bred (eller utan storlek), satt av en agent eller läst från en sidecar-fil, kraschar eller låser inte längre", + "A crop of no size (from an agent or a sidecar) no longer gives the Detail view a photo of no size to lay out": "En beskärning utan storlek (från en agent eller en sidecar-fil) ger inte längre Detalj-vyn ett foto utan storlek att lägga ut", + "A crop of no size with healing spots or masks no longer crashes the render: samples outside the picture read its": "En beskärning utan storlek med retuscheringsfläckar eller masker kraschar inte längre renderingen: sampel utanför bilden läser dess", + "A damaged or crafted raw can no longer make LightCraft set aside gigabytes of memory before finding out the file is": "En skadad eller manipulerad raw-fil kan inte längre få LightCraft att reservera gigabyte av minne innan det upptäcker att filen är", + "A demo photo whose stored size was damaged (a width of 4294967295) is rendered at its own size instead of": "Ett demofoto vars lagrade storlek var skadad (en bredd på 4294967295) renderas i sin egen storlek i stället för", + "A dialog taller than the window no longer runs off it (issue #781): on a 1366×768 screen the Export dialog's title": "En dialogruta som är högre än fönstret går inte längre utanför det (ärende #781): på en 1366×768-skärm har exportdialogrutans rubrik", + "A dialog's confirm button says it's the next step": "En dialogrutas bekräftelseknapp visar att den är nästa steg", + "A double-click on the thumb is a single step in History and Undo. Its first click no longer nudges the value to": "Ett dubbelklick på reglagehandtaget är ett enda steg i Historik och Ångra. Dess första klick flyttar inte längre värdet till", + "A face model uses the GPU only when a check shows it gives the same results faster.": "En ansiktsmodell använder GPU:n bara när en kontroll visar att den ger samma resultat snabbare.", + "A file named `portable.txt` next to the LightCraft program makes it keep its settings, logs and downloaded": "En fil med namnet `portable.txt` bredvid LightCraft-programmet gör att det sparar sina inställningar, loggar och nedladdade", + "a flag taken off in Picks, a rating that falls under the filter bar's. With it off, as before, the photo leaves the": "en flagga som tagits bort i Valda, ett betyg som hamnar under filterfältets. När det är av försvinner fotot, som tidigare, ur", + "A Folders section in the sidebar lists the folders your photos were imported from; choose one to see its photos.": "Avsnittet Mappar i sidofältet listar mapparna som dina foton importerades från; välj en för att se dess foton.", + "A label follows its folder when it is renamed or moved in LightCraft, together with the labels of the folders": "En etikett följer med sin mapp när den byter namn eller flyttas i LightCraft, tillsammans med etiketterna för mapparna", + "A library holding thousands of presets (a Lightroom collection imported whole: 11 000 presets, a 42 MB": "Ett bibliotek med tusentals förinställningar (en Lightroom-samling importerad i sin helhet: 11 000 förinställningar, en 42 MB", + "A library whose catalog file was damaged (or edited by hand) in a way that still reads no longer crashes": "Ett bibliotek vars katalogfil har skadats (eller redigerats för hand) på ett sätt som fortfarande går att läsa kraschar inte längre", + "A library with no photos now opens on the Photo Grid with the sidebar (Square Grid stays as it is), instead of a": "Ett bibliotek utan foton öppnas nu i Fotorutnät med sidofältet (Kvadratiskt rutnät förblir som det är), i stället för en", + "A Lightroom Classic catalog whose changes are all still in its `.lrcat-wal` file (a new catalog Lightroom has": "En Lightroom Classic-katalog vars ändringar fortfarande alla ligger i dess `.lrcat-wal`-fil (en ny katalog som Lightroom har", + "a line, a tab per level, synonyms in braces, keywords left out of export in brackets). Capture One, darktable, Adobe": "en rad, en tabb per nivå, synonymer inom klammerparenteser, nyckelord som utesluts från export inom hakparenteser). Capture One, darktable, Adobe", + "a magazine cover's masthead and cover lines, so you can frame a shot for the page it is made for. It fits inside": "ett tidningsomslags namnvinjett och puffar, så att du kan komponera en bild för sidan den är gjord för. Den ryms inom", + "A name the library doesn't have is marked as a new keyword before you press Return, so a misspelling no longer": "Ett namn som inte finns i biblioteket markeras som ett nytt nyckelord innan du trycker på Retur, så att en felstavning inte längre", + "a photo stop matching the view keeps it in the view: a keyword given in a smart album of photos without keywords,": "får ett foto att sluta matcha vyn behåller det i vyn: ett nyckelord som ges i ett smart album med foton utan nyckelord,", + "A photo that has no folder on disk (a demo photo, or one in the web version's browser storage) or whose folder": "Ett foto som inte har någon mapp på disken (ett demofoto, eller ett i webbversionens webbläsarlagring) eller vars mapp", + "A photo that runs into a bug in LightCraft while it renders (in a raw decoder or the editing pipeline) now fails": "Ett foto som stöter på en bugg i LightCraft medan det renderas (i en raw-avkodare eller i redigeringskedjan) misslyckas nu", + "A photo the folder lists is there for the scan, also where its file could not be opened by its path (a folder": "Ett foto som mappen listar finns med i genomsökningen, även där dess fil inte kunde öppnas via sökvägen (en mapp", + "A photo whose Defringe amount was stored far past the sliders' 20 (in a damaged catalog or sidecar) no longer": "Ett foto vars värde för Ta bort kantfärg lagrats långt över reglagens 20 (i en skadad katalog eller sidecar-fil) inte längre", + "A photo whose file was replaced (Reload Changed Files after an outside edit) no longer keeps the faces recognition": "Ett foto vars fil har ersatts (Läs in ändrade filer igen efter en extern redigering) behåller inte längre ansiktsigenkänningen", + "A preset whose lens-profile switch is off no longer turns off the lens corrections built into a DNG (iPhone ProRAW": "En förinställning vars reglage för objektivprofil är av stänger inte längre av objektivkorrigeringarna som är inbyggda i en DNG (iPhone ProRAW", + "A raw file whose black level is stored as \"not a number\" (or infinity), or a floating-point DNG with such": "En raw-fil vars svartnivå lagrats som \"inte ett tal\" (eller oändlighet), eller en flyttals-DNG med sådana", + "A selection without keywords now says \"No keywords yet\" where its chips would be.": "En markering utan nyckelord visar nu \"Inga nyckelord än\" där dess nyckelordsbrickor skulle vara.", + "A slideshow can now open with an intro screen and close with an ending screen, like Lightroom Classic's Titles": "Ett bildspel kan nu börja med en introskärm och avslutas med en slutskärm, som Titlar i Lightroom Classic", + "A small edit (a keyword, a rating, a flag, a slider) no longer has the grid's list worked out again from every": "En liten ändring (ett nyckelord, ett betyg, en flagga, ett reglage) gör inte längre att rutnätets lista räknas ut igen från varje", + "A smart album can include or exclude another smart album: \"Keywords contain travel\" and \"Album isn't Excluded Photos\"": "Ett smart album kan inkludera eller utesluta ett annat smart album: \"Nyckelord innehåller travel\" och \"Album är inte Excluded Photos\"", + "A smart album whose rules no longer check (an album they test was deleted) is marked ⚠ in the sidebar; its tooltip": "Ett smart album vars regler inte längre går att kontrollera (ett album de testar har raderats) markeras med ⚠ i sidofältet; dess knappbeskrivning", + "A spot with Feather at 0 no longer draws black pixels exactly on its radius. This also fixes spots at 0% Opacity": "En fläck med Fjädring på 0 ritar inte längre svarta pixlar exakt på sin radie. Detta åtgärdar också fläckar med 0 % Opacitet", + "A star, the moon or a light that moves between the photos of a bracket (a night bracket on a tripod) no longer": "En stjärna, månen eller ett ljus som rör sig mellan fotona i en gaffling (en nattgaffling på stativ) inte längre", + "A Synchronize Folder scan no longer asks the disk about every photo of the library in the folder (is its file": "En genomsökning med Synkronisera mapp frågar inte längre disken om varje foto i biblioteket i mappen (finns dess fil", + "a Synchronize scan began (now under 1 s), 2.6 s before an import review (now 0.05 s) and 1.7 s before an import": "en genomsökning med Synkronisera började (nu under 1 s), 2,6 s före en importgranskning (nu 0,05 s) och 1,7 s före en import", + "A template file that can't be used (damaged, from a newer LightCraft, too large) is listed as skipped instead of": "En mallfil som inte kan användas (skadad, från en nyare LightCraft, för stor) listas som överhoppad i stället för", + "A thumbnail of the photo open in Detail is made from its already decoded preview instead of decoding the file": "En miniatyr av fotot som är öppet i Detalj skapas från dess redan avkodade förhandsgranskning i stället för att avkoda filen", + "A view can hold its photos until you refresh it": "En vy kan behålla sina foton tills du uppdaterar den", + "A zoomed view keeps the GPU copy of the original while it is on screen: pausing for a few seconds between pans no": "En zoomad vy behåller GPU-kopian av originalet medan den visas på skärmen: en paus på några sekunder mellan panoreringar inte längre", + "Activity stack": "Aktivitetsstack", + "Add a cell": "Lägg till en cell", + "Add a Face Recognition Model": "Lägg till en modell för ansiktsigenkänning", + "Add Print Cell": "Lägg till utskriftscell", + "Add to Apple Photos (macOS)": "Lägg till i Apple Photos (macOS)", + "adjust or switch them off, and DNG export keeps them. Lateral chromatic aberration data is not applied: our": "justera eller stänga av dem, och DNG-export behåller dem. Data för lateral kromatisk aberration används inte: vår", + "advance (the next two slides render while the current one is up, so a fade never waits or flashes).": "framåt (de två nästa bilderna renderas medan den aktuella visas, så en toning aldrig väntar eller blinkar).", + "after a rename, an `.XMP` sidecar. Adding photos or a folder, Browse Folder (Local), drag-and-drop, the CLI and the": "efter ett namnbyte, en `.XMP`-sidecarfil. Att lägga till foton eller en mapp, Bläddra i mapp (Lokalt), dra och släpp, CLI:t och", + "again.": "igen.", + "Agents list and stop tasks with `activity.list` and `activity.cancel`; `ui.inspect` reports them as `activity`.": "Agenter listar och stoppar uppgifter med `activity.list` och `activity.cancel`; `ui.inspect` rapporterar dem som `activity`.", + "Agents use `app.newLibrary {path, name}`, `app.recentLibraries` and `app.clearRecentLibraries`.": "Agenter använder `app.newLibrary {path, name}`, `app.recentLibraries` och `app.clearRecentLibraries`.", + "Agents: `app.export {addToPhotos, photosAlbum}`, `export.addToPhotos {paths}` for files already on disk, and": "Agenter: `app.export {addToPhotos, photosAlbum}`, `export.addToPhotos {paths}` för filer som redan finns på disk, och", + "Agents: `view.sidebarSection`, `view.sidebarMoveSection`, `view.sidebarReset`; `ui.set` takes `sidebar`.": "Agenter: `view.sidebarSection`, `view.sidebarMoveSection`, `view.sidebarReset`; `ui.set` tar `sidebar`.", + "AI Denoise and Find Missing Photos. Each row has the task's name, a progress bar, the count and what it is working": "AI-brusreducering och Sök efter saknade foton. Varje rad visar uppgiftens namn, en förloppsindikator, antalet och vad den arbetar", + "AI RAW denoise": "AI-brusreducering för raw", + "Album folders fold with the same disclosure triangle as Local, By Date, Folders and Keywords.": "Albummappar fälls ihop med samma triangel som Lokalt, Efter datum, Mappar och Nyckelord.", + "Album rule is \"is\" or \"isn't\" an album, picked with the album picker.": "Albumregeln är \"är\" eller \"är inte\" ett album, valt med albumväljaren.", + "album that is gone, or an empty group is reported with its rule (\"rule 2.1: no rating 0–5 is 9\")": "album som inte längre finns, eller en tom grupp rapporteras med sin regel (\"regel 2.1: inget betyg 0–5 är 9\")", + "album, Delete changes nothing: its rules decide what it shows.": "album ändrar Radera ingenting: dess regler avgör vad det visar.", + "Album, New Smart Album, Rename Keyword, Merge Keywords and similar dialogs, or the name field under unnamed faces for": "Album, Nytt smart album, Byt namn på nyckelord, Sammanfoga nyckelord och liknande dialogrutor, eller namnfältet under namnlösa ansikten för", + "Albums tree": "Albumträd", + "all again.": "alla igen.", + "alone, so the photo's preview and thumbnail sources and its neighbours' were decoded from the raw again on every": "ensamt, så fotots källor för förhandsgranskning och miniatyr och dess grannars avkodades från raw-filen igen vid varje", + "also holds files of yours (a library opened on a photo folder that had one) is not tagged, and your files in it": "även innehåller dina egna filer (ett bibliotek som öppnats på en fotomapp som hade en) märks inte, och dina filer i den", + "an edit to more than 256 photos, and each new minute for an album that asks about \"the last N days\" are still": "en redigering av fler än 256 foton, och varje ny minut för ett album som frågar om \"de senaste N dagarna\" är fortfarande", + "An empty library leads to Import": "Ett tomt bibliotek leder till Importera", + "An export enlarged far past the photo's size (20000 typed for 2000 with Don't Enlarge off) no longer ends": "En export som förstorats långt över fotots storlek (20000 inskrivet för 2000 med Förstora inte avstängt) slutar inte längre", + "An HDR merged from raws that LightCraft colours from the camera's JPEG (CR2, NEF, ARW…) now opens at the same": "En HDR sammanfogad från raw-filer som LightCraft färgsätter från kamerans JPEG (CR2, NEF, ARW…) öppnas nu med samma", + "An uncompressed Leaf Aptus 22 MOS no longer opens as a dark, colourless picture of its sensor mosaic: it imports": "En okomprimerad Leaf Aptus 22 MOS öppnas inte längre som en mörk, färglös bild av sensorns mosaik: den importeras", + "and a dark theme card, each previewing its theme (dark: Charcoal, the look so far, or Midnight;": "och ett kort för mörkt tema, som vart och ett förhandsgranskar sitt tema (mörkt: Kol, utseendet hittills, eller Midnatt;", + "and a section with nothing in it says so instead of disappearing.": "och ett avsnitt utan innehåll säger det i stället för att försvinna.", + "and a smaller export look like the full-size result scaled down; 1:1 views and full-size exports are unchanged.": "och en mindre export ser ut som resultatet i full storlek nedskalat; 1:1-vyer och exporter i full storlek är oförändrade.", + "and a view that asks about \"the last N days\".": "och en vy som frågar om \"de senaste N dagarna\".", + "and CR3, instead of opening flat and desaturated (issue #310). Photos already imported pick it up when re-rendered.": "och CR3, i stället för att öppnas platta och avmättade (ärende #310). Foton som redan importerats får det när de renderas om.", + "and exports don't change. Agents use `app.displayProfile`. See [display profiles](display-profiles.md).": "och exporter ändras inte. Agenter använder `app.displayProfile`. Se [bildskärmsprofiler](display-profiles.md).", + "and its Cancel / OK buttons were off screen, so it couldn't be confirmed. Now its options scroll and the title and": "och dess knappar Avbryt/OK hamnade utanför skärmen, så den gick inte att bekräfta. Nu rullar dess alternativ, och rubriken och", + "and new photos never reuse an id in use. What was repaired is written to the log.": "och nya foton återanvänder aldrig ett id som används. Det som reparerades skrivs till loggen.", + "and other files with embedded distortion / vignetting corrections), matching what the preset does elsewhere.": "och andra filer med inbäddade korrigeringar för distorsion/vinjettering), i linje med vad förinställningen gör på andra ställen.", + "and press Return; Esc keeps the old value.": "och tryck på Return; Esc behåller det gamla värdet.", + "and Survey, following rotation and crops; the Info panel says how it focused (`AF-C · Wide · Animal Eye Tracking`).": "och Översikt, med hänsyn till rotation och beskärningar; panelen Info visar hur den fokuserade (`AF-C · Wide · Animal Eye Tracking`).", + "and the control bar says Intro or End while one is up (the photo count only counts photos).": "och kontrollfältet visar Intro eller Slut medan en sådan visas (fotoantalet räknar bara foton).", + "and the fit to the photo's own JPEG still come first, so photos that had a fitted look keep it. See": "och anpassningen till fotots egen JPEG kommer fortfarande först, så foton som hade ett anpassat utseende behåller det. Se", + "and WB2000. The compressed ones (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini) still open from their": "och WB2000. De komprimerade (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini) öppnas fortfarande från sin", + "Animal Eye Tracking": "Ögonspårning för djur", + "Another library was opened since the photos were dropped: nothing was moved": "Ett annat bibliotek öppnades efter att fotona släpptes: ingenting flyttades", + "answered there too. In such a folder the scan saves less, and its checks now start after the listing where they": "besvaras där också. I en sådan mapp sparar genomsökningen mindre, och dess kontroller startar nu efter listningen där de", + "Any Searchable Text also finds the state / province, alt text, people and a virtual copy's name.": "All sökbar text hittar även delstat/provins, alternativtext, personer och en virtuell kopias namn.", + "app, and with LightCraft fullscreen it was hidden altogether, so Import Photos… looked like a hang until the": "appen, och med LightCraft i helskärm doldes den helt, så Importera foton… såg ut som om programmet hängt sig tills", + "Appearance lists the modes and themes. On Linux, Auto follows the desktop portal's colour scheme": "Utseende listar lägena och temana. På Linux följer Auto skrivbordsportalens färgschema", + "Apple ProRAW's gain table map (its local tone mapping, `ProfileGainTableMap`) is now read and kept when a photo is": "Apple ProRAW:s gain table map (dess lokala tonmappning, `ProfileGainTableMap`) läses nu och behålls när ett foto", + "Apply Mask Effect": "Använd maskeffekt", + "Apply Print Template": "Använd utskriftsmall", + "Apply Slideshow Template": "Använd bildspelsmall", + "apply their effect inside the circle, as Lightroom does, instead of outside it (issue #1815). A mask inverted in": "tillämpar sin effekt inuti cirkeln, som Lightroom gör, i stället för utanför den (ärende #1815). En mask inverterad i", + "Arabic names and other Arabic text in headings, chosen tabs and other bold places are now drawn bold, as Latin text": "Arabiska namn och annan arabisk text i rubriker, valda flikar och andra feta ställen ritas nu i fetstil, som latinsk text", + "are left as they are. Note that files there named exactly like the cache's own (`ab/ab…` with 32 hex digits and": "lämnas som de är. Observera att filer där med exakt samma namn som cachens egna (`ab/ab…` med 32 hexadecimala siffror och", + "are unchanged; photos imported before this change get it when imported again.": "är oförändrade; foton som importerats före denna ändring får det när de importeras igen.", + "are unchanged; the guidance does not guarantee a build will fit every 16 GB machine.": "är oförändrade; riktlinjerna garanterar inte att ett bygge får plats på varje maskin med 16 GB.", + "Arrange Print Cell": "Ordna utskriftscell", + "Arrange the left sidebar your way: drag Albums, Local, By Date, Folders or Keywords by its header to move it (a line": "Ordna det vänstra sidofältet som du vill: dra Album, Lokalt, Efter datum, Mappar eller Nyckelord i rubriken för att flytta avsnittet (en linje", + "ARW) gives the merged DNG the colour each photo has when opened alone (issue #965). An HDR merge of CR2s used to come": "ARW) ger den sammanfogade DNG-filen den färg varje foto har när det öppnas ensamt (ärende #965). En HDR-sammanfogning av CR2-filer brukade bli", + "as 1/250), File Extension, Video Duration, Copy Name, In a Stack, Alt Text, City, State / Province, Country, Long": "som 1/250), Filändelse, Videolängd, Kopiera namn, I en stapel, Alternativtext, Ort, Delstat/provins, Land, Lång", + "as a raw and shows its embedded preview (preview only, with the reason), as the compressed MOS files do.": "som raw och visar sin inbäddade förhandsgranskning (endast förhandsgranskning, med orsaken), som de komprimerade MOS-filerna gör.", + "as before.": "som tidigare.", + "as Exposure would; the edges between bright and dark regions stay as sharp as before. This is rendering process 2:": "som Exponering skulle; kanterna mellan ljusa och mörka områden förblir lika skarpa som tidigare. Detta är renderingsprocess 2:", + "as it changes, without polling.": "när den ändras, utan avfrågning.", + "As Shot temperature and tint as its photos, and changing the white balance no longer turns it green. Sony ARW": "Som tagen-temperatur och -tonvärde som sina foton, och att ändra vitbalansen gör den inte längre grön. Sony ARW", + "ASCII (an umlaut, a curly apostrophe, a dash), about every name the folder does not list. Names it does list are": "ASCII (ett omljudstecken, en typografisk apostrof, ett tankstreck), om varje namn som mappen inte listar. Namn som den listar är", + "Aspect Ratio (a 24 MP photo cropped to a square is 16 MP).": "Bildförhållande (ett foto på 24 MP beskuret till kvadrat är 16 MP).", + "at the camera JPEG's size (6016 × 4016 for the D600 and D610, 4288 × 2848 for the D5000, as the D90 already": "i kamera-JPEG:ens storlek (6016 × 4016 för D600 och D610, 4288 × 2848 för D5000, som D90 redan", + "at their import settings). See `docs/sony-ilce7rm6-lens-corrections.md`.": "med sina importinställningar). Se `docs/sony-ilce7rm6-lens-corrections.md`.", + "Auto Layout": "Auto layout", + "Auto use the same model. Custom white balances on these photos render slightly differently than before.": "Auto använder samma modell. Anpassade vitbalanser på dessa foton renderas något annorlunda än tidigare.", + "bad (issue #1512): a compressed PEF whose data is too short for the size it declares, an uncompressed TIFF-based": "felaktiga (ärende #1512): en komprimerad PEF vars data är för kort för storleken den anger, en okomprimerad TIFF-baserad", + "becomes a keyword unnoticed. The suggestions further down stay put while you type.": "blir ett nyckelord utan att det märks. Förslagen längre ned ligger kvar medan du skriver.", + "before it looks at the first file. In a library of 3.5 million photos that held the window for about 6 s before": "innan den tittar på den första filen. I ett bibliotek med 3,5 miljoner foton höll det upp fönstret i cirka 6 s innan", + "before, and becomes the Kelvin value with the same look the next time it is edited. A photo imported earlier shows": "tidigare, och blir det Kelvinvärde som ger samma utseende nästa gång det redigeras. Ett foto som importerats tidigare visar", + "before. Agents use `slideshow.layout`, and `slideshow.preview` returns one composed slide as a PNG.": "tidigare. Agenter använder `slideshow.layout`, och `slideshow.preview` returnerar en sammansatt bild som PNG.", + "behaviour, `fresh` imports a clean copy and deletes the old record).": "beteende, `fresh` importerar en ren kopia och raderar den gamla posten).", + "behind. A photo that can't be read is skipped and named in the message at the end. Agents use `slideshow.export`": "kvar. Ett foto som inte kan läsas hoppas över och nämns i meddelandet i slutet. Agenter använder `slideshow.export`", + "belonged to another command moves to the new one. Menus show the new keys; agents use `app.setShortcut`.": "tillhörde ett annat kommando flyttas till det nya. Menyerna visar de nya tangenterna; agenter använder `app.setShortcut`.", + "beside the After's, and a window asked for again while the first was still decoding (a pan, the layout settling)": "bredvid Efter-vyns, och ett fönster som begärdes igen medan det första fortfarande avkodades (en panorering, layouten som sätter sig)", + "beside them is; they used to stay at regular weight.": "bredvid dem; tidigare förblev de i normal stil.", + "between slides (a crossfade, or through black, white or any colour; 0 cuts), random order (every photo once per": "mellan bilder (en korstoning, eller via svart, vitt eller valfri färg; 0 ger raka snitt), slumpmässig ordning (varje foto en gång per", + "Blown highlights in CR2 files from the Canon EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i),": "Utbrända högdagrar i CR2-filer från Canon EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i),", + "Bold text in other scripts": "Fet text i andra skriftsystem", + "Bridge and Photo Supreme (its Formatted Vocabulary File) use the same files, so keyword lists move between them and": "Bridge och Photo Supreme (dess Formatted Vocabulary File) använder samma filer, så nyckelordslistor kan flyttas mellan dem och", + "brings in something (Import N Photos, Merge, Save, Create, Download…). Delete and Remove stay plain, so a destructive": "tar in något (Importera N foton, Sammanfoga, Spara, Skapa, Hämta…). Radera och Ta bort förblir neutrala, så en destruktiv", + "browsers, for example) show it in HDR; **viewers that don't read `cICP` show the PQ values as if they were sRGB**,": "webbläsare, till exempel) visar den i HDR; **visningsprogram som inte läser `cICP` visar PQ-värdena som om de vore sRGB**,", + "Building from source": "Bygga från källkod", + "built-in profile: straight lines near the edges stay straight and the framing matches the camera's JPEG. It works": "inbyggd profil: raka linjer nära kanterna förblir raka och inramningen matchar kamerans JPEG. Det fungerar", + "burst by file name, so the first file is the cover.": "bildserien efter filnamn, så att den första filen blir omslaget.", + "buttons stay visible. Long lists in dialogs (What's New, All Metadata, Keyboard Shortcuts) get shorter to fit.": "knapparna förblir synliga. Långa listor i dialogrutor (Nyheter, Alla metadata, Kortkommandon) blir kortare för att få plats.", + "by double-clicking it, delete one with − after a confirmation. Right-click for more: create inside, Put New Keywords": "genom att dubbelklicka på den, radera en med − efter en bekräftelse. Högerklicka för mer: skapa inuti, Lägg nya nyckelord", + "C-RAWs imported earlier, Photo ▸ Reload from Disk picks up the raw data.": "C-RAW-filer som importerats tidigare hämtar Foto → Läs in igen från disk rådata.", + "Cached thumbnails are redrawn.": "Cachade miniatyrer ritas om.", + "Camera & Lens": "Kamera och objektiv", + "camera JPEG can't be fitted no longer open with the neutral fallback: they start from colour matrices fitted to the": "kamera-JPEG inte kan anpassas öppnas inte längre med den neutrala reservprofilen: de utgår från färgmatriser anpassade till", + "camera JPEG. Photos already imported pick the change up on Reload.": "kamera-JPEG:en. Foton som redan importerats får ändringen vid Läs in igen.", + "camera's embedded JPEG while a raw decodes, the previous render while an edit renders, or the magnified frame": "kamerans inbäddade JPEG medan en raw-fil avkodas, den föregående renderingen medan en redigering renderas, eller den förstorade bilden", + "camera's measured spectral sensitivities, from the Academy Software Foundation's rawtoaces-data. A camera profile": "kamerans uppmätta spektrala känslighet, från Academy Software Foundations rawtoaces-data. En kameraprofil", + "camera's own colour matrices, as Lightroom does, instead of shifting the colours of the as-shot rendering: a grey": "kamerans egna färgmatriser, som Lightroom gör, i stället för att förskjuta färgerna i Som tagen-renderingen: en grå", + "camera's own zoom to fill the frame) and vignetting, as with Panasonic and Sony files. The Optics profile controls": "kamerans egen zoom för att fylla bilden) och vinjettering, som med Panasonic- och Sony-filer. Profilkontrollerna under Optik", + "Camera-look deep shadows": "Djupa skuggor som i kameran", + "can be attached to a report without hunting for the settings folder (issue #260).": "kan bifogas till en rapport utan att du behöver leta efter inställningsmappen (ärende #260).", + "Can't be moved here": "Kan inte flyttas hit", + "can't be picked, such as one that would make an album include itself, are greyed with the reason. Esc with a dropdown or calendar open in a dialog": "kan inte väljas, till exempel ett som skulle få ett album att inkludera sig självt, är nedtonade med orsaken. Esc med en rullgardinsmeny eller kalender öppen i en dialogruta", + "Canon CR2 and Pentax PEF raws get the same starting look fitted to the camera's own JPEG as ARW, NEF, RW2, RAF": "Raw-filer i Canon CR2 och Pentax PEF får samma utgångsutseende anpassat till kamerans egen JPEG som ARW, NEF, RW2, RAF", + "Canon CR2 highlights": "Högdagrar i Canon CR2", + "Canon CR2 raws no longer open too dark with blocked-up shadows: the black level was measured over border columns": "Raw-filer i Canon CR2 öppnas inte längre för mörka med igensatta skuggor: svartnivån mättes över kantkolumner", + "Canon CR3 raws now develop from their sensor data: lossless RAW and C-RAW, checked sample for sample on the EOS": "Raw-filer i Canon CR3 framkallas nu från sina sensordata: förlustfri RAW och C-RAW, kontrollerade sampel för sampel på EOS", + "Canon CRW, Minolta MRW, Sigma X3F, Kodak KDC, Leaf MOS and Epson ERF files that LightCraft can't decode yet": "Canon CRW-, Minolta MRW-, Sigma X3F-, Kodak KDC-, Leaf MOS- och Epson ERF-filer som LightCraft inte kan avkoda ännu", + "Canon EOS R5 Mark II": "Canon EOS R5 Mark II", + "Canon EOS R7 C-RAW files develop from their sensor data too, instead of opening from their embedded JPEG. For R7": "C-RAW-filer från Canon EOS R7 framkallas också från sina sensordata, i stället för att öppnas från sin inbäddade JPEG. För R7", + "Canon PowerShot G9 raws open with the camera's white balance (White Balance ▸ As Shot); it used to start from a": "Raw-filer från Canon PowerShot G9 öppnas med kamerans vitbalans (Vitbalans → Som tagen); förut utgick de från en", + "carries Huffman tables made for its own picture instead of the standard example tables. Every viewer opens them": "har Huffman-tabeller gjorda för sin egen bild i stället för standardens exempeltabeller. Alla visningsprogram öppnar dem", + "carries the slide duration and fade, so a PDF viewer's presentation mode plays it as a slideshow, and \"Automatically": "innehåller visningstid per bild och toning, så att en PDF-läsares presentationsläge spelar upp den som ett bildspel, och \"Automatiskt", + "cells": "celler", + "cells overlap": "celler överlappar", + "Center": "Center", + "centre show nothing. More cameras will follow. Details: [focus-points.md](focus-points.md).": "mitten visar ingenting. Fler kameror kommer. Detaljer: [focus-points.md](focus-points.md).", + "centre, and can be turned off under Lens Corrections. Vignetting correction from the file comes later.": "mitten, och kan stängas av under Objektivkorrigeringar. Vinjetteringskorrigering från filen kommer senare.", + "change to an album, a stack or the keyword list, an album shown in its own order, Recently Added, Missing Photos,": "byte till ett album, en stapel eller nyckelordslistan, ett album som visas i sin egen ordning, Nyligen tillagda, Saknade foton,", + "changed doesn't put its faces on the new one (issue #1524).": "ändrats lägger inte sina ansikten på den nya (ärende #1524).", + "changing pixels along their edge. The hard edge now leaves pixels on the radius unchanged.": "ändrade pixlar längs kanten. Den hårda kanten lämnar nu pixlar på radien oförändrade.", + "Checking the GPU for faces": "Kontrollerar GPU:n för ansiktsigenkänning", + "Checking the GPU…": "Kontrollerar GPU:n…", + "Chinese (Simplified and Traditional), Japanese and Brazilian Portuguese.": "kinesiska (förenklad och traditionell), japanska och brasiliansk portugisiska.", + "choice is never the eye-catching default.": "val är aldrig det iögonfallande standardvalet.", + "choice next to that (Restore them / Import as new / Leave them) now starts on Restore. Files dropped on the window": "valet bredvid (Återställ dem / Importera som ny / Låt dem vara) börjar nu på Återställ. Filer som dras till fönstret", + "Choice values read as words in every language: \"Public Domain\", \"Picked\", \"Black & White\" rather than ids like": "Värden för val läses som ord på alla språk: \"Allmän egendom\", \"Vald\", \"Svartvitt\" i stället för id:n som", + "Choose Monitor Profile": "Välj bildskärmsprofil", + "choose what to do: import the new photos and relink the moved ones (the defaults), move the missing ones to Recently": "välja vad som ska göras: importera de nya fotona och länka om de flyttade (standardvalen), flytta de saknade till Nyligen", + "Choosing a date under By Date or a keyword under Keywords shows those photos from All Photos, as their counts": "Om du väljer ett datum under Efter datum eller ett nyckelord under Nyckelord visas de fotona från Alla foton, eftersom deras antal", + "Choosing a Lightroom Classic catalog folder in File → Open Library… (or one of its `Previews.lrdata` /": "Om du väljer en Lightroom Classic-katalogmapp i Arkiv → Öppna bibliotek… (eller en av dess `Previews.lrdata` /", + "choosing a profile file.": "att välja en profilfil.", + "chose) and ends on a page saying it was installed, with a \"Launch LightCraft\" box. It used to finish without a word,": "valde) och avslutas med en sida som säger att den installerades, med en ruta för \"Starta LightCraft\". Tidigare slutfördes den utan att säga något,", + "Classic (issue #956). With the second, each photo is exported into the folder its original is in, plus the": "Classic (ärende #956). Med det andra exporteras varje foto till mappen där originalet ligger, plus", + "Cleaner HDR merges": "Renare HDR-sammanfogningar", + "Clear Print Layout": "Rensa utskriftslayout", + "Click a cell to move, resize or arrange it": "Klicka på en cell för att flytta, ändra storlek på eller ordna den", + "Click to hide clipping warnings for shadows and highlights.": "Klicka för att dölja klippningsvarningar för skuggor och högdagrar.", + "Click to show clipping warnings for shadows and highlights.": "Klicka för att visa klippningsvarningar för skuggor och högdagrar.", + "Click to type a value, drag to change it": "Klicka för att skriva ett värde, dra för att ändra det", + "clipped highlights.": "klippta högdagrar.", + "Closer camera colour for lens-corrected raws": "Närmare kamerafärg för objektivkorrigerade raw-filer", + "closes just that.": "stänger bara det.", + "Closing a library releases its lock explicitly (issue #680). On Linux and macOS the lock used to go with the file": "När ett bibliotek stängs släpps dess lås uttryckligen (ärende #680). På Linux och macOS följde låset tidigare med filen", + "codecs' `heif` feature — 8- and 10-bit, alpha, grid tiles, the container's rotation/mirror/crop, ICC, EXIF and XMP.": "codecs `heif`-funktion — 8 och 10 bitar, alfa, rutnätsrutor, behållarens rotation/spegling/beskärning, ICC, EXIF och XMP.", + "Color Overlay": "Färgöverlägg", + "Color Overlay on B&W": "Färgöverlägg på svartvitt", + "Colour labels tint thumbnail surrounds in Square Grid and the Detail filmstrip, and a translucent footer along the bottom of the photo in Photo Grid. Label confirmations use a matching pale colour.": "Färgetiketter färgar ytan runt miniatyrerna i Kvadratiskt rutnät och filmremsan i Detalj, och en genomskinlig sidfot längs fotots nederkant i Fotorutnät. Bekräftelser av etiketter använder en matchande blek färg.", + "colours are right on wide-gamut and calibrated displays instead of oversaturated. The Detail view renders straight": "färgerna blir rätt på skärmar med brett färgomfång och kalibrerade skärmar i stället för övermättade. Detaljvyn renderar direkt", + "comes back as large as you left it, but not as a zoomed window. That is so after a zoom from the Window menu": "kommer tillbaka lika stort som du lämnade det, men inte som ett zoomat fönster. Så är det efter en zoomning från menyn Fönster", + "Compare and Reference View panes say \"Rendering…\" (or that the photo can't be opened) the same way, so a": "Rutorna i Jämför och Referensvy säger \"Renderar…\" (eller att fotot inte kan öppnas) på samma sätt, så en", + "compiler built into Windows (FXC). `WGPU_DX12_COMPILER=dxc` uses a `dxcompiler.dll` instead.": "kompilatorn som är inbyggd i Windows (FXC). `WGPU_DX12_COMPILER=dxc` använder en `dxcompiler.dll` i stället.", + "computer has is refused with the size it would take, before it starts.": "datorn har avvisas med det utrymme det skulle kräva, innan det startar.", + "Confirm before moving photos to another folder on disk": "Bekräfta innan foton flyttas till en annan mapp på disken", + "Confirm matching faces together": "Bekräfta matchande ansikten tillsammans", + "Contact Sheet PDF": "Kontaktark-PDF", + "contains it: `Canon EOS R6` stays `Canon EOS R6`, rather than `Canon Canon EOS R6` (the camera": "innehåller den: `Canon EOS R6` förblir `Canon EOS R6` i stället för `Canon Canon EOS R6` (kamerans", + "controls work as they did. With the default layout (no margins, border, shadow or backdrop) it plays the photos as": "kontrollerna fungerar som förut. Med standardlayouten (inga marginaler, kant, skugga eller fond) spelar den upp fotona som", + "Coolpix A, D3000, D40X, D60, D80, D2Xs, D200, D3200, D3100, D5000, D40, D50, D70, D70s and Nikon 1 V1 now show": "Coolpix A, D3000, D40X, D60, D80, D2Xs, D200, D3200, D3100, D5000, D40, D50, D70, D70s och Nikon 1 V1 visar nu", + "correction on (24–70 mm, 100 mm macro, 200–600 mm) the render lines up with the camera's JPEG within 0.68 px at": "korrigering på (24–70 mm, 100 mm makro, 200–600 mm) stämmer renderingen överens med kamerans JPEG inom 0,68 px vid", + "correction, checked against Sony's exports; other Sony bodies record the same tables, but they stay uncorrected until": "korrigering, kontrollerad mot Sonys exporter; andra Sony-kameror registrerar samma tabeller, men de förblir okorrigerade tills", + "Corrections, on by default for newly imported photos, with the same framing as the camera's JPEG. At 12 mm the": "Korrigeringar, på som standard för nyimporterade foton, med samma inramning som kamerans JPEG. Vid 12 mm", + "counted from every photo.": "räknas från alla foton.", + "covers lossless, Compressed and Compressed HQ (ARW 6.0) ARWs alike. The A7R IVA (ILCE-7RM4A) has its own distortion": "gäller förlustfria, Compressed och Compressed HQ (ARW 6.0) ARW-filer likadant. A7R IVA (ILCE-7RM4A) har sin egen distorsions-", + "CPU": "CPU", + "crashes LightCraft each time it renders: the amount acts as 20.": "kraschar LightCraft varje gång det renderas: mängden behandlas som 20.", + "Create keywords with + (inside the one you picked, with synonyms, and given to the selection if you like), edit one": "Skapa nyckelord med + (inuti det du valde, med synonymer, och tilldelat markeringen om du vill), redigera ett", + "Crop (issue #295): a Lock toggle keeps the aspect ratio on every handle, Custom takes your own ratio (Apply), and": "Beskär (ärende #295): en Lås-knapp behåller bildförhållandet på alla handtag, Anpassad tar ditt eget förhållande (Använd), och", + "Crop rotation": "Beskärningsrotation", + "Culling.": "Gallring.", + "current edits": "aktuella ändringar", + "curves, as Lightroom does: a preset with just one channel curve (or no master curve) leaves the channels alone.": "kurvor, som Lightroom gör: en förinställning med bara en kanalkurva (eller ingen huvudkurva) låter kanalerna vara.", + "Custom AF Area": "Anpassat AF-område", + "Cut, Copy, Paste and Select All. Esc in them gives back the text from before you started typing (in the Info panel it": "Klipp ut, Kopiera, Klistra in och Markera allt. Esc i dem återställer texten från innan du började skriva (i panelen Info", + "Cycle Flag": "Växla flagga", + "Cycle Tool Overlay": "Växla verktygsöverlägg", + "D60, D80 and D2Xs now show the area the camera itself frames, a few pixels smaller than before.": "D60, D80 och D2Xs visar nu området som kameran själv ramar in, några pixlar mindre än tidigare.", + "D7000, D5100, D800, D800E, Df, D4, D3, D3S, D700, D300, D300S, D600, D610, D810, D4S, D5600, Coolpix A, D3000, D40X,": "D7000, D5100, D800, D800E, Df, D4, D3, D3S, D700, D300, D300S, D600, D610, D810, D4S, D5600, Coolpix A, D3000, D40X,", + "dark sky is now removed too.": "mörk himmel tas nu också bort.", + "darkens the photo outside it. The layout stays chosen across launches.": "mörkar fotot utanför den. Layouten förblir vald mellan starter.", + "Date rules have a calendar button: pick a day, a month or a whole year (Year / Month / Day), in your language; the": "Datumregler har en kalenderknapp: välj en dag, en månad eller ett helt år (År / Månad / Dag), på ditt språk;", + "Daylight, Cloudy, Shade, Tungsten, Fluorescent and Flash presets set real temperatures (issue #730). The matrices": "Förinställningarna Dagsljus, Molnigt, Skugga, Glödlampa, Lysrör och Blixt ställer in verkliga temperaturer (ärende #730). Matriserna", + "Decrease Flag Status": "Sänk flaggstatus", + "Decrease Grid Thumbnail Size": "Minska miniatyrstorlek i rutnätet", + "default cache share (768 MB), so it was evicted as soon as it was stored. The original of the photo shown in Detail": "standardandel av cachen (768 MB), så den rensades ut så fort den lagrats. Originalet för fotot som visas i Detalj", + "Dehaze while zoomed in": "Ta bort dis vid inzoomning", + "Delete Cell": "Radera cell", + "Delete in an album removes from the album only": "Radera i ett album tar bara bort från albumet", + "Delete Mask Effect": "Radera maskeffekt", + "Delete Print Cell": "Radera utskriftscell", + "Delete Print Template": "Radera utskriftsmall", + "Delete Slideshow Template": "Radera bildspelsmall", + "Deleted, read the metadata updates. A folder on a disk that isn't connected is reported as such. Synchronizing": "raderade, läsa in metadatauppdateringarna. En mapp på en disk som inte är ansluten rapporteras som sådan. Synkronisering", + "deletes a keyword from the whole library.": "raderar ett nyckelord från hela biblioteket.", + "demosaic already lines the colour planes up. Details and measurements: `docs/fuji-lens-corrections.md`.": "demosaicingen riktar redan in färgplanen. Detaljer och mätningar: `docs/fuji-lens-corrections.md`.", + "depending on the graphics card. On a Windows laptop with an AMD Radeon 780M, a full-size export of a 24 MP raw": "beroende på grafikkortet. På en bärbar Windows-dator med AMD Radeon 780M, en export i full storlek av en 24 MP raw-fil", + "Detail has a per-photo AI Denoise switch and Amount. Bayer RAW photos use a disposable cache, with matching previews and exports and pure-Rust CPU/GPU inference.": "Detalj har ett reglage för AI-brusreducering per foto och Mängd. Bayer-RAW-foton använder en tillfällig cache, med matchande förhandsgranskningar och exporter och CPU/GPU-inferens i ren Rust.", + "Detail view that pointed at an empty grid. The grid and Detail view offer Import Photos… and, in the desktop app,": "Detaljvy som pekade på ett tomt rutnät. Rutnätet och Detaljvyn erbjuder Importera foton… och, i skrivbordsappen,", + "Detection": "Detektering", + "dialog was found and closed.": "dialogrutan hittades och stängdes.", + "Dialogs": "Dialogrutor", + "Dialogs fit the window": "Dialogrutor anpassas till fönstret", + "Dialogs that fit look as before.": "Dialogrutor som får plats ser ut som förut.", + "Dialogs' buttons and About's Discord link are drawn by one button component: primary (filled with the accent),": "Dialogrutornas knappar och Discord-länken i Om ritas av en och samma knappkomponent: primär (fylld med accentfärgen),", + "did). On the D600 and D610 the white level is also measured inside the picture, so the filler can't pass for": "gjorde). På D600 och D610 mäts även vitnivån inuti bilden, så att utfyllnaden inte kan tas för", + "didn't line up with the raw near the edges. Photos you already imported pick this up when their previews are rebuilt.": "stämde inte med raw-filen nära kanterna. Foton du redan har importerat får detta när deras förhandsgranskningar byggs om.", + "differ by about 7–10 % on the ILCE-7M3; which one is off is still open.": "skiljer sig med cirka 7–10 % på ILCE-7M3; vilken som är fel är fortfarande oklart.", + "Dimensions": "Dimensioner", + "directives. See README → Quick start → Logs.": "direktiv. Se README → Quick start → Logs.", + "Display profile not used": "Skärmprofilen används inte", + "DNG camera identity": "DNG-kameraidentitet", + "DNG export and Convert to DNG no longer duplicate the camera make when the model already": "DNG-export och Konvertera till DNG duplicerar inte längre kameratillverkaren när modellen redan", + "Dock can be attached to a bug report. `LIGHTCRAFT_LOG` works as before; `RUST_LOG` takes env_logger-style": "Dock kan bifogas till en buggrapport. `LIGHTCRAFT_LOG` fungerar som förut; `RUST_LOG` tar env_logger-liknande", + "does the photos it was made from. HDRs merged before this don't have it; merge them again.": "gör de foton den skapades av. HDR-bilder som sammanfogats före detta har det inte; sammanfoga dem igen.", + "does: As Shot reads the file's white (an ILCE-7M3 sample: 4268 K / +7), the Temp slider runs 2000–50000 K and the": "gör: Som tagen läser filens vitbalans (ett ILCE-7M3-exempel: 4268 K / +7), reglaget Temp går 2000–50000 K och", + "Don't ask again": "Fråga inte igen", + "Drag a keyword onto another to nest it, or onto the list's title to bring it back to the top level; photos dragged": "Dra ett nyckelord till ett annat för att lägga det inuti, eller till listans rubrik för att flytta det tillbaka till översta nivån; foton som dras", + "Drag an album or folder onto a folder to move it there (a closed folder opens after 0.6 s under the pointer; a": "Dra ett album eller en mapp till en mapp för att flytta dit (en stängd mapp öppnas efter 0,6 s under pekaren; en", + "Drag anywhere inside the selected radial gradient's ellipse to move it, including rotated": "Dra var som helst inuti den markerade radiella gradientens ellips för att flytta den, även när den är roterad", + "dragging a handle into the image edge stops there instead of pushing the crop out of shape.": "om du drar ett handtag mot bildkanten stannar det där i stället för att förvränga beskärningen.", + "Dragging a slider no longer re-renders the edited photo's filmstrip thumbnail on every frame; it follows once you": "Att dra ett reglage renderar inte längre om det redigerade fotots miniatyr i filmremsan för varje bildruta; den följer efter när du", + "Dragging a Tone Curve point that sits very close to its neighbours (two clicks side by side, or a curve from a": "Att dra en punkt i Tonkurva som ligger mycket nära sina grannar (två klick bredvid varandra, eller en kurva från en", + "Duplicate Mask Effect": "Duplicera maskeffekt", + "E-1, E-400 and XZ-2 corpus files: all accepted), with white balance relative to the as-shot look as for the other": "E-1, E-400 och XZ-2 korpusfiler: alla godkända), med vitbalansen relativ till utseendet Som tagen, som för de andra", + "each image (issue #1522). When renders come in faster than the disk takes them, at most 128 MB of images wait;": "varje bild (ärende #1522). När renderingar kommer in snabbare än disken hinner ta emot dem väntar högst 128 MB bilder;", + "each of those questions is a round trip. Measured on a hard disk over SMB, for folders of 1,600 to 2,400 photos": "var och en av de frågorna är en tur och retur. Uppmätt på en hårddisk över SMB, för mappar med 1 600 till 2 400 foton", + "Each sits at one of nine anchors of the slide or of the photo, moved by an offset, and never leaves the slide.": "Var och en sitter vid ett av nio ankare på bilden eller på fotot, flyttad med en förskjutning, och lämnar aldrig bilden.", + "Each such bug used to take one of the render threads with it, so after a few of them no photo rendered until": "Varje sådan bugg tog tidigare med sig en av renderingstrådarna, så efter några av dem renderades inget foto förrän", + "each time you look (issue #1392): the next time you browse the folder, in a later session, they're left out. A photo you had rated, flagged or": "varje gång du tittar (ärende #1392): nästa gång du bläddrar i mappen, i en senare session, utelämnas de. Ett foto som du hade betygsatt, flaggat eller", + "Edge, Short Edge, Aspect Ratio (landscape / portrait / square), Cropped and Treatment (in color / black & white).": "sida, Kortsida, Bildförhållande (liggande / stående / kvadrat), Beskuren och Behandling (i färg / svartvitt).", + "edge.": "kant.", + "edit at 1:1, every zoom out and every step to the next photo.": "redigering vid 1:1, varje utzoomning och varje steg till nästa foto.", + "Edit In": "Redigera i", + "edited earlier may shift by a few pixels.": "redigerats tidigare kan förskjutas några pixlar.", + "edited stays, marked missing, so its changes aren't lost; photos in My Photos are unchanged.": "redigerat finns kvar, markerat som saknat, så att ändringarna inte går förlorade; foton i Mina foton är oförändrade.", + "Editing a smart album's name and rules is one step: both or neither, and one undo takes both back": "Att redigera ett smart albums namn och regler är ett steg: båda eller inget, och en ångring tar tillbaka båda", + "Edits keep up in a large library": "Redigeringar hänger med i ett stort bibliotek", + "ellipses and radial components in compound masks. Edge and rotation handles keep their existing": "ellipser och radiella komponenter i sammansatta masker. Kant- och rotationshandtag behåller sina befintliga", + "else (issue #1504): trimming or clearing the cache can't delete files outside it, and thumbnails are never read": "annat (ärende #1504): när cachen trimmas eller rensas kan inga filer utanför den raderas, och miniatyrer läses aldrig", + "embedded JPEG.": "inbäddad JPEG.", + "End Slideshow": "Avsluta bildspel", + "end), a folder the scan did not walk to its end, and, in a folder that holds any name with a character outside": "slut), en mapp som genomsökningen inte gick igenom till slutet och, i en mapp som innehåller något namn med ett tecken utanför", + "end. Space pauses, ← / → step (a cut), Esc ends. A slide's time starts once it is shown sharp.": "slut. Blanksteg pausar, ← / → går ett steg (med ett snitt), Esc avslutar. En bilds tid börjar först när den visas skarp.", + "ending. They are saved with the library. Agents use `slideshow.titles`, and `slideshow.preview {title: \"intro\"}`": "avslutning. De sparas med biblioteket. Agenter använder `slideshow.titles` och `slideshow.preview {title: \"intro\"}`", + "every selected photo; a chip's menu acts on the selection (add to all, remove, show photos, edit) and no longer": "varje markerat foto; menyn på en bricka verkar på markeringen (lägg till i alla, ta bort, visa foton, redigera) och inte längre", + "everything about how a slideshow looks and plays: the playback timing and fades, the layout, options and backdrop,": "allt om hur ett bildspel ser ut och spelas upp: uppspelningens tidsinställning och toningar, layouten, alternativen och fonden,", + "existing LightCraft edits are preserved by default. Source settings/history are archived, unsupported": "befintliga LightCraft-redigeringar behålls som standard. Källinställningar/historik arkiveras, fält som inte stöds", + "Existing smart previews are refreshed when their originals are online, and cached renders are redrawn.": "Befintliga smarta förhandsgranskningar uppdateras när deras original är online, och cachade renderingar ritas om.", + "Expanded Flexible Spot": "Utökad flexibel punkt", + "Export as JPEG XL (issue #247): Format ▸ JPEG XL in the Export dialog, `format: \"jxl\"` for agents and the CLI": "Exportera som JPEG XL (ärende #247): Format → JPEG XL i dialogrutan Exportera, `format: \"jxl\"` för agenter och CLI:t", + "Export can write PSD too (flat, 8- or 16-bit).": "Exporten kan även skriva PSD (sammanslagen, 8 eller 16 bitar).", + "Export Effect Presets": "Exportera effektförinställningar", + "Export Effect Presets…": "Exportera effektförinställningar…", + "Export Mask Effects": "Exportera maskeffekter", + "Export next to the originals": "Exportera bredvid originalen", + "export or delete it, and import templates others share with you. Your templates are `.json` files in the settings": "exportera eller radera den, och importera mallar som andra delar med dig. Dina mallar är `.json`-filer i inställnings-", + "exported files will carry for the selection.": "exporterade filer kommer att ha för markeringen.", + "exported or converted to DNG. It is not applied by default: Lightroom Classic renders ProRAW without it. To see a": "exporteras eller konverteras till DNG. Den används inte som standard: Lightroom Classic renderar ProRAW utan den. För att se en", + "exported with).": "exporterades med).", + "Exporting a photo more than 65,535 times as long as it is wide (a one-pixel strip), or opening the Export dialog's": "Export av ett foto som är mer än 65 535 gånger så långt som det är brett (en remsa på en pixel), eller öppning av dialogrutan Exportera", + "Exports with noise reduction, Texture, Clarity, Dehaze or Highlights and Shadows can be much faster on the GPU,": "Exporter med brusreducering, Textur, Klarhet, Ta bort dis eller Högdagrar och Skuggor kan gå mycket snabbare på GPU:n,", + "exposure, ISO, focal length, camera and lens under each photo on a dark backdrop).": "exponering, ISO, brännvidd, kamera och objektiv under varje foto på en mörk fond).", + "Face models (ONNX)": "Ansiktsmodeller (ONNX)", + "Face Models on the GPU": "Ansiktsmodeller på GPU:n", + "Face tracking": "Ansiktsspårning", + "Face Tracking": "Ansiktsspårning", + "Faces are kept in the thumbnail cache at a few fixed sizes, so moving the thumbnail slider no longer renders them": "Ansikten sparas i miniatyrcachen i några fasta storlekar, så när du drar i miniatyrreglaget renderas de inte längre", + "Faces load faster in the People view": "Ansikten läses in snabbare i vyn Människor", + "Faces on unedited raws are cut from the camera's preview inside the file instead of developing the raw (issue": "Ansikten på oredigerade raw-filer klipps ut ur kamerans förhandsgranskning i filen i stället för att raw-filen framkallas (ärende", + "Faster GPU exports": "Snabbare GPU-exporter", + "faster on an external hard disk. A face whose preview is too small, and any edited photo, is still developed from": "snabbare på en extern hårddisk. Ett ansikte vars förhandsgranskning är för liten, och alla redigerade foton, framkallas fortfarande från", + "Favorite Mask Effect": "Favoritmaskeffekt", + "favourites across restarts (issue #328).": "favoriter mellan omstarter (ärende #328).", + "few pixels.": "några pixlar.", + "fields are reported, and the original Lightroom database stays read-only. Rendering is approximate.": "fält rapporteras, och den ursprungliga Lightroom-databasen förblir skrivskyddad. Renderingen är ungefärlig.", + "File extensions match whatever their letter case: `IMG_0001.JPG` and `DSC_0002.NEF` as Nikon writes them, `.Jpg`": "Filändelser matchas oavsett skiftläge: `IMG_0001.JPG` och `DSC_0002.NEF` som Nikon skriver dem, `.Jpg`", + "file is gone, photos whose file was renamed or moved within the folder, and XMP sidecars changed by other apps; then": "filen saknas, foton vars fil har bytt namn eller flyttats inom mappen och XMP-sidofiler som ändrats av andra appar; sedan", + "file name, then id, instead of import order. Recently Added keeps a batch in file name order, and Auto-Stack orders a": "filnamn, sedan id, i stället för importordning. Nyligen tillagda håller en batch i filnamnsordning, och Autostapla ordnar en", + "file that hold the focus point (about 100 photos a second from a spinning disk), with a *Reading focus points* row": "fil som innehåller fokuspunkten (ungefär 100 foton per sekund från en snurrande disk), med en rad *Läser fokuspunkter*", + "File → Import Lightroom Catalog… opens `.lrcat` directly, with originals referenced in place.": "Arkiv → Importera Lightroom-katalog… öppnar `.lrcat` direkt, med originalen refererade där de ligger.", + "File ▸ Import Keywords… and Export Keywords… read and write keyword list files as Lightroom Classic does (a keyword": "Arkiv →Importera nyckelord… och Exportera nyckelord… läser och skriver nyckelordslistfiler som Lightroom Classic gör (ett nyckelord", + "File ▸ New Library… asks for a name, then where to put it, and opens the new library (issue #902).": "Arkiv →Nytt bibliotek… frågar efter ett namn och sedan var det ska ligga, och öppnar det nya biblioteket (ärende #902).", + "File ▸ Open Recent Library lists the last 8 libraries; ones that are gone (moved, drive disconnected) are greyed": "Arkiv →Öppna senaste bibliotek listar de 8 senaste biblioteken; de som har försvunnit (flyttats, enheten frånkopplad) är nedtonade", + "Filename captions": "Filnamn som bildtext", + "files also Adobe RGB and ProPhoto), metadata as for JPEG. With HDR output, photos edited in HDR are written as": "filer även Adobe RGB och ProPhoto), metadata som för JPEG. Med HDR-utdata skrivs foton som redigerats i HDR som", + "files in the test corpus still decode.": "filer i testkorpusen avkodas fortfarande.", + "files, the same files as `library.import` (issue #1080). They used to be skipped without a word.": "filer, samma filer som `library.import` (ärende #1080). Tidigare hoppades de över utan ett ord.", + "Five built-in templates of our own: Plain Black (the photo on black), Gallery Wall (a light wall, a white mat and a": "Fem egna inbyggda mallar: Enkel svart (fotot på svart), Gallerivägg (en ljus vägg, ett vitt passepartout och en", + "Flexible Spot": "Flexibel punkt", + "Focus": "Fokus", + "Focus point": "Fokuspunkt", + "Folder colour labels": "Färgetiketter för mappar", + "folder scans, exports (and the contact sheet PDF), Synchronize Folder, Build / Smart Previews, Lightroom catalog import, Photo Merge, model downloads, the face scan,": "mappgenomsökningar, exporter (och kontaktkartans PDF), Synkronisera mapp, Bygg / Smarta förhandsgranskningar, import av Lightroom-katalog, Fotosammanfogning, modellhämtningar, ansiktsgenomsökningen,", + "folder's `slideshow-templates` folder, shared by all your libraries.": "mappens `slideshow-templates`-mapp, som delas av alla dina bibliotek.", + "folder, fold that folder first (the bottom of an open folder means \"inside\"). Agents use `album.reorder`": "mapp, fäll ihop den mappen först (nederkanten av en öppen mapp betyder \"inuti\"). Agenter använder `album.reorder`", + "Folder…. The folder and the folders inside it are scanned in the background for photos added on disk, photos whose": "Mapp…. Mappen och mapparna i den genomsöks i bakgrunden efter foton som lagts till på disken, foton vars", + "follow.": "följa.", + "For scripts: a size set with `ui.resize` is remembered like any other, so a script that needs a size sets it.": "För skript: en storlek som ställs in med `ui.resize` sparas som alla andra, så ett skript som behöver en storlek ställer in den.", + "for\").": "för\").", + "Formats": "Format", + "formats. On an E-1 photo the starting render moved from ΔE00 11.3 to 8.3 against Lightroom's. Photos already": "format. På ett E-1-foto minskade startrenderingens avvikelse från Lightrooms från ΔE00 11,3 till 8,3. Foton som redan", + "forward); what was read is remembered for the session, so a full cache still lets go of what is not in use first.": "framåt); det som lästs sparas under sessionen, så en full cache släpper fortfarande först det som inte används.", + "from or written through such a link.": "från eller skrivs genom en sådan länk.", + "From the command line: `lightcraft-cli merge hdr-batch FOLDER`.": "Från kommandoraden: `lightcraft-cli merge hdr-batch FOLDER`.", + "from the grid onto a keyword get it.": "från rutnätet till ett nyckelord får det.", + "Fujifilm lens corrections": "Objektivkorrigeringar för Fujifilm", + "Fujifilm RAFs from 59 camera models now get the lens correction the camera stores in the file: distortion (with the": "Fujifilm RAF-filer från 59 kameramodeller får nu den objektivkorrigering som kameran lagrar i filen: distorsion (med", + "Full screen is not remembered (the app opens as a window), and neither is where on the desktop the window was:": "Helskärm sparas inte (appen öppnas som ett fönster), och inte heller var på skrivbordet fönstret låg:", + "full-range/matrix signalling is honoured (iPhone photos are full range), chroma is upsampled like libheif, grids": "signaleringen av fullt omfång/matris följs (iPhone-foton har fullt omfång), kroma uppsamplas som i libheif, rutnät", + "Full-resolution panoramas": "Panoramor i full upplösning", + "functions, and one Undo restores the entire drag.": "funktioner, och en enda Ångra återställer hela dragningen.", + "further ⇧-clicks carry on from the last point, as in Lightroom. Change the brush size, feather or flow before the": "ytterligare ⇧-klick fortsätter från den senaste punkten, som i Lightroom. Ändra penselstorlek, fjädring eller flöde före", + "give the offered keyword and keep the cursor in the box for the next one; Return alone still adds what you typed.": "ger det föreslagna nyckelordet och behåller textmarkören i rutan för nästa; bara Retur lägger fortfarande till det du skrev.", + "go by that can leave it out. It is safe to delete while LightCraft is closed, as before. A `thumbs` folder that": "går efter som kan utelämna den. Det går att radera den medan LightCraft är stängt, som tidigare. En `thumbs`-mapp som", + "Grid thumbnails and the first picture in the loupe of an unedited raw now come from the smallest JPEG the camera": "Miniatyrer i rutnätet och den första bilden i lupen för en oredigerad raw-fil kommer nu från den minsta JPEG som kameran", + "Grid: add the next photo to the selection": "Rutnät: lägg till nästa foto i markeringen", + "Grid: add the previous photo to the selection": "Rutnät: lägg till föregående foto i markeringen", + "Grid: first photo of the view": "Rutnät: vyns första foto", + "Grid: last photo of the view": "Rutnät: vyns sista foto", + "guides, at the screen's aspect or 16:9 / 4:3). Sizes are a share of the slide, so a slide looks the same on any": "stödlinjer, i skärmens bildförhållande eller 16:9 / 4:3). Storlekar är en andel av bilden, så en bild ser likadan ut på vilken", + "handle, and a program being started by another thread at that moment held a copy of the handle until it was fully": "handtag, och ett program som startades av en annan tråd i det ögonblicket höll en kopia av handtaget tills det var helt", + "Hard-edged Heal and Clone spots": "Retuscherings- och klonpunkter med hårda kanter", + "HDR and panorama merges of CR2 keep their colour": "HDR- och panoramasammanfogningar av CR2 behåller färgen", + "HDR merges keep the lens correction": "HDR-sammanfogningar behåller objektivkorrigeringen", + "HDR merges keep the white balance": "HDR-sammanfogningar behåller vitbalansen", + "HDR merges of moving lights, and many brackets at once": "HDR-sammanfogningar av rörliga ljus, och många exponeringsserier på en gång", + "HDR output": "HDR-utdata", + "HDR PNG export": "HDR-export till PNG", + "HEIC / HEIF photos (iPhone and Mac) open now: the optional `lightcraft-heif` crate (heic-rs, pure Rust) behind": "HEIC-/HEIF-foton (iPhone och Mac) kan nu öppnas: den valfria craten `lightcraft-heif` (heic-rs, ren Rust) bakom", + "HEIC colours now match libheif to within one code value (they were up to ~10 off): the HEVC stream's own": "HEIC-färger stämmer nu med libheif inom ett kodvärde (de avvek med upp till ~10): HEVC-strömmens egen", + "Help → Keyboard Shortcuts includes the number-key bindings. See [library shortcuts](library-shortcuts.md).": "Hjälp → Kortkommandon inkluderar bindningarna för siffertangenterna. Se [kortkommandon i biblioteket](library-shortcuts.md).", + "Help → Open Log Folder shows that log file in the file manager (Finder, Explorer, or the folder on Linux), so it": "Hjälp → Öppna loggmappen visar loggfilen i filhanteraren (Finder, Utforskaren eller mappen på Linux), så att den", + "Hide the sections you don't use: View ▸ Sidebar Sections, or right-click a header ▸ Hide This Section. Right-click": "Dölj de avsnitt du inte använder: Visa → Sidofältsavsnitt, eller högerklicka på en rubrik → Dölj det här avsnittet. Högerklicka", + "Hide this wheel's effect": "Dölj det här hjulets effekt", + "high-resolution cameras such as the Sony A7R VI (64 MP). Their decoded original (~800 MB) is bigger than the": "högupplösta kameror som Sony A7R VI (64 MP). Deras avkodade original (~800 MB) är större än", + "highlight recovery missed them and, darkened, they took a colour cast instead of going neutral grey.": "högdageråterställningen missade dem, och när de mörkades fick de ett färgstick i stället för att bli neutralt grå.", + "Highlights and Shadows (process 2)": "Högdagrar och skuggor (process 2)", + "Highlights and Shadows keep the fine detail of the tones they move (issue #632): pulling Highlights down on a bright": "Högdagrar och Skuggor behåller de fina detaljerna i de toner de flyttar (ärende #632): att dra ner Högdagrar på en ljus", + "hold (such as a name in brackets), which it leaves out so the file always reads back.": "rymma (som ett namn inom hakparenteser), vilket det utelämnar så att filen alltid kan läsas tillbaka.", + "Human Eye Tracking": "Ögonspårning för människor", + "ICC Profiles": "ICC-profiler", + "identity subissue in #840). The separate Make and Model tags keep their original values.": "delärendet om identitet i #840). De separata taggarna Make och Model behåller sina ursprungliga värden.", + "If LightCraft can't open a photo (its original is on a drive that isn't connected, or the file is damaged) but has": "Om LightCraft inte kan öppna ett foto (originalet ligger på en enhet som inte är ansluten, eller filen är skadad) men har", + "If the desktop app can't open its window (for example when no graphics device can be used), it now says so in a": "Om skrivbordsappen inte kan öppna sitt fönster (till exempel när ingen grafikenhet kan användas) säger den nu det i en", + "If you go back to an older version, it renders its thumbnails again as `.jpg`. This version then takes those": "Om du går tillbaka till en äldre version renderar den sina miniatyrer igen som `.jpg`. Den här versionen tar sedan de", + "image file such as a PNG logo with transparency, at a size and opacity, optionally drawn behind the photo), the": "bildfil, till exempel en PNG-logotyp med transparens, i en viss storlek och opacitet, eventuellt ritad bakom fotot), den", + "Image on Black": "Bild på svart", + "Image on White": "Bild på vitt", + "Import Lightroom Catalog… as buttons, and say that photos (and, in the desktop app, folders) can be dropped into": "Importera Lightroom-katalog… som knappar, och säger att foton (och, i skrivbordsappen, mappar) kan släppas i", + "Import Mask Effects": "Importera maskeffekter", + "import only the raws and leave the JPEGs beside them (issue #344).": "importera bara raw-filerna och lämna JPEG-filerna bredvid dem (ärende #344).", + "Import photos to get started": "Importera foton för att komma igång", + "import review checks such files, marks them \"Will be restored\" and counts them as \"in Recently Deleted\"; the": "importgranskningen kontrollerar sådana filer, markerar dem \"Kommer att återställas\" och räknar dem som \"i Nyligen raderade\"; den", + "Import Slideshow Template": "Importera bildspelsmall", + "Import when a card is connected": "Importera när ett kort ansluts", + "Imported `.cube` LUT profiles appear in the Profile menu and the profile browser, grouped by their folder, and stay": "Importerade `.cube`-LUT-profiler visas i profilmenyn och profilbläddraren, grupperade efter sin mapp, och förblir", + "imported from files (or read from sidecars) keep the hierarchy `lr:hierarchicalSubject` gives them.": "som importerats från filer (eller lästs från sidofiler) behåller den hierarki som `lr:hierarchicalSubject` ger dem.", + "imported pick it up when re-rendered.": "importerade får det när de renderas om.", + "Importing a deleted photo again": "Importera ett raderat foto igen", + "Importing a file whose photo is in Recently Deleted brings the photo back, with its edits, rating and albums": "Om du importerar en fil vars foto finns i Nyligen raderade kommer fotot tillbaka, med sina redigeringar, sitt betyg och sina album", + "Importing a large collection and opening its library no longer compare every preset with every other.": "När du importerar en stor samling och öppnar dess bibliotek jämförs inte längre varje förinställning med alla andra.", + "Importing a preset zip that unpacks to far more than any preset (a \"zip bomb\") is refused with a message naming": "Om du importerar en zip med förinställningar som packas upp till långt mer än någon förinställning (en \"zip-bomb\") vägras den med ett meddelande som anger", + "Importing XMP presets no longer lists bookkeeping fields (`Cluster`, `SortName`, `SupportsAmount2`, the as-shot": "När du importerar XMP-förinställningar listas inte längre interna fält (`Cluster`, `SortName`, `SupportsAmount2`, den som tagna", + "In a long section, the header stays at the top of the sidebar while you scroll through its rows, so you always see": "I ett långt avsnitt stannar rubriken överst i sidofältet medan du rullar genom dess rader, så att du alltid ser", + "In an album, the Delete key now takes the selected photos out of the album, as in Lightroom. It used to move them": "I ett album tar Delete-tangenten nu bort de markerade fotona ur albumet, som i Lightroom. Tidigare flyttade den dem", + "In dialogs, the confirm button is on the right with Cancel to its left, and filled with the accent when it makes or": "I dialogrutor sitter bekräftelseknappen till höger med Avbryt till vänster om den, och den fylls med accentfärgen när den skapar eller", + "in, instead of moving it back to Program Files (issue #399). If that folder has been deleted since, the upgrade": "i, i stället för att flytta tillbaka den till Program Files (ärende #399). Om den mappen har raderats sedan dess, ", + "Increase Flag Status": "Höj flaggstatus", + "Increase Grid Thumbnail Size": "Öka miniatyrstorlek i rutnätet", + "inference on a Mac through SSH. Saved masks still render and export offline.": "inferens på en Mac via SSH. Sparade masker renderas och exporteras fortfarande offline.", + "inside it; undo and redo carry them back and forth.": "inuti den; ångra och gör om flyttar dem fram och tillbaka.", + "inside Pictures, so every thumbnail (one for each photo, size and state of its edits) was listed as a photo.": "i Bilder, så varje miniatyr (en för varje foto, storlek och redigeringsläge) listades som ett foto.", + "inside the view. A plain mouse wheel over a zoomed photo pans it too.": "i vyn. Ett vanligt mushjul över ett inzoomat foto panorerar det också.", + "Inside This Keyword, Purge Unused Keywords.": "Inuti det här nyckelordet, Rensa oanvända nyckelord.", + "installs to Program Files.": "installeras i Program Files.", + "instead of opening as their embedded preview. Photos imported earlier switch over with Photo ▸ Reload from Disk.": "i stället för att öppnas som sin inbäddade förhandsgranskning. Foton som importerats tidigare byter över med Foto → Läs in igen från disk.", + "instead of quietly matching nothing or everything. New date rules start at the current year.": "i stället för att i tysthet matcha ingenting eller allt. Nya datumregler börjar vid aktuellt år.", + "into the display's own gamut; thumbnails and other previews are converted to it. Histograms, the preview caches": "till bildskärmens eget färgomfång; miniatyrer och andra förhandsgranskningar konverteras till det. Histogram, förhandsgranskningscacharna", + "iPhone ProRAW and other DNGs that carry their own segmentation mattes (DNG semantic masks) use them for the Select": "iPhone ProRAW och andra DNG-filer som har egna segmenteringsmasker (semantiska DNG-masker) använder dem för Markera", + "is a larger target that lights up on its own, and taking a keyword off several photos at once now says which": "är ett större mål som tänds av sig självt, och när du tar bort ett nyckelord från flera foton samtidigt står det nu vilka", + "is connected, the same review File → Import from Device opens. It's off by default. A card that's already in when": "ansluts, samma granskning som Arkiv → Importera från enhet öppnar. Den är av som standard. Ett kort som redan sitter i när", + "is missing (moved, drive unplugged) is not exported; it gets its own error naming it.": "saknas (flyttad, enheten urkopplad) exporteras inte; den får ett eget fel som anger den.", + "is touched. Agents use `folder.scanChanges` and `folder.synchronize`.": "rörs. Agenter använder `folder.scanChanges` och `folder.synchronize`.", + "It is not a denoise model LightCraft understands": "Det är inte en brusreduceringsmodell som LightCraft förstår", + "it slightly worse. The vignetting table is read but not applied: the camera's own JPEGs don't apply it either. This": "den något sämre. Vinjetteringstabellen läses men tillämpas inte: kamerans egna JPEG-filer tillämpar den inte heller. Detta", + "it. The list is there with no photo selected too, to set up keywords first.": "den. Listan finns också när inget foto är markerat, så att du kan ställa in nyckelord först.", + "its duration and the fades are rendered frame by frame (crossfades, or fades through the fade colour). The video has": "dess längd och toningarna renderas bildruta för bildruta (övertoningar, eller toningar via toningsfärgen). Videon har", + "its embedded JPEG or a thumbnail to show, the loupe now says so at the bottom of the photo (\"Original offline · no": "dess inbäddade JPEG eller en miniatyr att visa står det nu i lupen längst ned på fotot (\"Original offline · ingen", + "its real As Shot temperature once the file is opened (or Reload reads it).": "sin verkliga Som tagen-temperatur när filen öppnas (eller när Läs in igen läser den).", + "its text reads at 4.5:1 or more on its fill in every theme. Dialog buttons are 30 points tall, like the welcome's.": "dess text har en kontrast på 4,5:1 eller mer mot fyllningen i alla teman. Dialogknappar är 30 punkter höga, som välkomstfönstrets.", + "JPEG exports are 12–14 % smaller at the same quality, with exactly the same pixels (issue #1373): each file now": "JPEG-exporter är 12–14 % mindre med samma kvalitet, med exakt samma pixlar (ärende #1373): varje fil nu", + "JPEG get faster too.": "JPEG blir också snabbare.", + "JPEG XL compressed DNGs (DNG 1.7) now open: lossless tiles decode sample for sample (checked on synthetic files);": "JPEG XL-komprimerade DNG-filer (DNG 1.7) öppnas nu: förlustfria rutor avkodas sampel för sampel (kontrollerat på syntetiska filer);", + "JPEG XL export": "JPEG XL-export", + "Kelvin white balance for more Sony cameras": "Vitbalans i kelvin för fler Sony-kameror", + "Kelvin white balance for raws whose camera has colour matrices": "Vitbalans i kelvin för raw-filer vars kamera har färgmatriser", + "Keyword lists": "Nyckelordslistor", + "keyword only some of them have is marked with an asterisk (hover: how many). Only the × removes a keyword, from": "nyckelord som bara några av dem har markeras med en asterisk (hovra: hur många). Endast × tar bort ett nyckelord, från", + "Keyword Set ▸ Edit Set… edits a set's nine keywords in place, one field per ⌥ key, and renames it (or saves the edits as a new": "Nyckelordsuppsättning → Redigera uppsättning… redigerar en uppsättnings nio nyckelord på plats, ett fält per ⌥-tangent, och byter namn på den (eller sparar ändringarna som en ny", + "Keyword sets": "Nyckelordsuppsättningar", + "Keyword tag options decide what exported files carry: Include on Export, Export Containing Keywords, Export": "Alternativ för nyckelordstaggar avgör vad exporterade filer innehåller: Ta med vid export, Exportera överordnade nyckelord, Exportera", + "Keywording box": "Nyckelordsruta", + "Keywords has a + in its header, like Albums: Create Keyword Tag without opening the Keyword List.": "Nyckelord har ett + i rubriken, som Album: Skapa nyckelordstagg utan att öppna Nyckelordslista.", + "Keywords panel": "Panelen Nyckelord", + "keywords, dates, people and counts; a keyword leaves the folders, the dates and the counts as they are. With both": "nyckelord, datum, personer och antal; ett nyckelord lämnar mapparna, datumen och antalen som de är. Med båda", + "labels 6–9, P / U and the rest did nothing, because macOS only passes ⌘ / ⌃ combinations and function keys": "etiketter 6–9, P / U och resten gjorde ingenting, eftersom macOS bara skickar vidare ⌘- / ⌃-kombinationer och funktionstangenter", + "land in `ui.json` (where they replaced the saved settings), and the GPU crash sentinel no longer creates the": "hamnar i `ui.json` (där de ersatte de sparade inställningarna), och GPU-kraschvakten skapar inte längre", + "Languages": "Språk", + "Large libraries: Synchronize Folder, import and sidecars start sooner": "Stora bibliotek: Synkronisera mapp, import och sidecar-filer startar tidigare", + "Large preset collections": "Stora samlingar av förinställningar", + "launch. Reading a thumbnail writes nothing (but for one that went unused for a week, whose date is brought": "start. Att läsa en miniatyr skriver ingenting (utom för en som inte använts på en vecka, vars datum förs", + "launched, so reopening the library straight away could be refused with \"This library is already open in another": "startats, så att öppna biblioteket igen direkt kunde vägras med \"Det här biblioteket är redan öppet i ett annat", + "Layout Image Matte": "Matthet för layoutbild", + "Layout Image Opacity": "Opacitet för layoutbild", + "Layout image over the loupe": "Layoutbild över lupen", + "Leaf and Hasselblad raws": "Raw-filer från Leaf och Hasselblad", + "leaves a black hole where the middle photo had it clipped. With Deghost, the brightest photo's copy of it in a": "lämnar ett svart hål där mittenfotot hade det klippt. Med spökborttagning: det ljusaste fotots kopia av det i en", + "leaves out whatever Excluded Photos matches, as its rules change. The album picker shows your albums as in the sidebar": "utesluter det som Uteslutna foton matchar, i takt med att dess regler ändras. Albumväljaren visar dina album som i sidofältet", + "left out, so these photos come out a little smaller, closer to the camera's own JPEG. Crops and masks on photos": "utelämnas, så dessa foton blir lite mindre, närmare kamerans egen JPEG. Beskärningar och masker på foton", + "lens it doesn't have a name for. Newly imported photos show it.": "objektiv som den inte har något namn för. Nyimporterade foton visar det.", + "Lens names for Nikon DSLR raws": "Objektivnamn för raw-filer från Nikons DSLR-kameror", + "let go. On a 64 MP raw the first of those renders decoded the whole file again, which held up the loupe's": "släpps. På en 64 MP raw-fil avkodade den första av de renderingarna hela filen igen, vilket fördröjde lupens", + "Letter": "Letter", + "Library and views": "Bibliotek och vyer", + "Library keyboard culling": "Gallring med tangentbordet i biblioteket", + "library open now stays, and LightCraft says \"This is a Lightroom catalog, not a LightCraft library\" and offers": "biblioteket som är öppet förblir nu öppet, och LightCraft säger \"Det här är en Lightroom-katalog, inte ett LightCraft-bibliotek\" och erbjuder", + "Library sorting": "Sortering i biblioteket", + "light: Silver or Paper). New and existing installs stay dark; following the system is opt-in.": "ljust: Silver eller Papper). Nya och befintliga installationer förblir mörka; att följa systemet måste du välja själv.", + "LightCraft Effect Presets": "LightCraft-effektförinställningar", + "LightCraft program\" although nothing had it open. Nothing in the shipped app is known to hit the window today; it": "LightCraft-program\" fast inget hade det öppet. Inget i den levererade appen är känt för att träffa den tidsluckan i dag; den", + "LightCraft starts doesn't ask, and if a dialog is open or an import is running it waits until that's done.": "LightCraft startar frågar inte, och om en dialogruta är öppen eller en import pågår väntar den tills det är klart.", + "LightCraft the copy shows what you saved.": "LightCraft visar kopian det du sparade.", + "LightCraft was restarted. The bug is still written to the log (Help ▸ Open Log Folder) for a report.": "LightCraft startades om. Felet skrivs fortfarande till loggen (Hjälp → Öppna loggmappen) för en rapport.", + "LightCraft when it shows a stack, or hangs it when a folder is moved: on opening, records are put back under": "LightCraft när den visar en stapel, eller får den att hänga när en mapp flyttas: vid öppning läggs posterna tillbaka under", + "LightCraft's cached thumbnails no longer show up in Windows Photos / Gallery or other photo apps as pictures of": "LightCrafts cachade miniatyrer visas inte längre i Windows Foton / Galleri eller andra fotoappar som bilder av", + "LightCraft's window opens at the size it had when you last used it, and zoomed (macOS) / maximized if it was: it": "LightCrafts fönster öppnas i den storlek det hade när du senast använde det, och zoomat (macOS) / maximerat om det var det: det", + "LightCraft. Importing adds the keywords you don't have, in one undo step; a file it can't read says which line, or": "LightCraft. Importen lägger till de nyckelord du inte har, i ett enda ångra-steg; en fil den inte kan läsa anger vilken rad, eller", + "LightCraft: an enlargement stops at 512 megapixels, as in Lightroom, and one that needs more memory than the": "LightCraft: en förstoring stannar vid 512 megapixel, som i Lightroom, och en som behöver mer minne än", + "Lightroom Classic catalogs": "Lightroom Classic-kataloger", + "Lightroom Classic's Export PDF, Export JPEG and Export Video: the photos in view as their slides, with the layout,": "Lightroom Classics Exportera PDF, Exportera JPEG och Exportera video: fotona i vyn som bilder i bildspelet, med layouten,", + "Lightroom has no such view.": "Lightroom har ingen sådan vy.", + "Lightroom radial masks on the right side": "Lightrooms radiella masker på höger sida", + "Lightroom stays inverted, and older Radial Filters keep their Effect Outside / Invert Mask setting. Photos imported": "Lightroom förblir inverterad, och äldre radiella filter behåller sin inställning Effekt utanför / Invertera mask. Foton som importerats", + "Lightroom's `crs:Temperature` for these raws is read as the Kelvin it is (sidecars, Lightroom catalogs, presets);": "Lightrooms `crs:Temperature` för dessa raw-filer läses som de kelvin det är (sidecar-filer, Lightroom-kataloger, förinställningar);", + "like a photo that can't be opened, with the reason, instead of rendering forever; its thumbnail stops waiting too.": "som ett foto som inte kan öppnas, med orsaken, i stället för att renderas i all evighet; dess miniatyr slutar också vänta.", + "Like in Lightroom, judge noise reduction at 1:1: at small sizes the noise it removes is mostly averaged away.": "Precis som i Lightroom bör du bedöma brusreducering i 1:1: i små storlekar jämnas bruset den tar bort till största delen ut ändå.", + "like the HDR AVIF: the same brightness, with SDR white at 203 cd/m², and content light levels recorded.": "som HDR-AVIF-filen: samma ljusstyrka, med SDR-vitt på 203 cd/m², och innehållets ljusnivåer registrerade.", + "linked, or each on its own), Zoom to Fill Frame (crop the photo to fill its cell), a stroke border (colour, width),": "länkade, eller var för sig), Zooma för att fylla bildrutan (beskär fotot så att det fyller sin cell), en konturkant (färg, bredd),", + "listing itself took 4 to 5 s and is as it was.": "själva listningen tog 4 till 5 s och är som förut.", + "lit by the chosen white comes out grey and saturated colours move as the camera records them. The eyedropper and": "belyst av det valda vita blir grått och mättade färger flyttas så som kameran registrerar dem. Pipetten och", + "Local folders select a photo": "Lokala mappar markerar ett foto", + "Local photos aren't in the library yet: Add to My Photos first, then move them": "Lokala foton finns inte i biblioteket än: Lägg till i Mina foton först och flytta dem sedan", + "Lock On AF": "Lock On AF", + "Long-running tasks show in one place, top left under the top bar, as in Lightroom Classic (issue #345): imports and": "Långvariga uppgifter visas på ett ställe, uppe till vänster under det övre fältet, som i Lightroom Classic (ärende #345): importer och", + "longer frees it, which cost a re-upload of about a second on the next pan (800 MB for a 64 MP raw). It is freed": "frigör det längre, vilket kostade en ny uppladdning på ungefär en sekund vid nästa panorering (800 MB för en 64 MP raw-fil). Det frigörs", + "looks right everywhere, export a JPEG with HDR output on (an SDR image plus a gain map).": "ser rätt ut överallt, exportera en JPEG med HDR-utdata på (en SDR-bild plus en förstärkningskarta).", + "Lossy JPEG XL files in Display P3 or Rec. 2020 now open in their real colours; saturated colours used to come in": "Förlustbringande JPEG XL-filer i Display P3 eller Rec. 2020 öppnas nu i sina verkliga färger; mättade färger kom tidigare in", + "lossy tiles decode too, keeping the raw values above 1.0 instead of clipping them (checked on one real file). A tile that cannot be decoded makes the file open from its embedded": "förlustbringande rutor avkodas också, och raw-värdena över 1,0 behålls i stället för att klippas (kontrollerat på en verklig fil). En ruta som inte kan avkodas gör att filen öppnas från sin inbäddade", + "Loupe Info 1": "Lupinfo 1", + "Loupe Info 2": "Lupinfo 2", + "Loupe Overlay": "Lupöverlägg", + "Loupe View": "Lupvy", + "Luminance and colour noise reduction no longer look much stronger in grid thumbnails and the filmstrip than in": "Brusreducering av luminans och färg ser inte längre mycket starkare ut i rutnätsminiatyrer och filmremsan än i", + "M50, R100 and R8. CR3 files the decoder can't read yet still open from their embedded JPEG, as before.": "M50, R100 och R8. CR3-filer som avkodaren inte kan läsa än öppnas fortfarande från sin inbäddade JPEG, som tidigare.", + "M50, R100, R8 and RP (on the RP also in 1.6× crop mode). CR3 files the decoder can't read yet still open from their embedded JPEG, as before.": "M50, R100, R8 och RP (på RP även i beskärningsläget 1,6×). CR3-filer som avkodaren inte kan läsa än öppnas fortfarande från sin inbäddade JPEG, som tidigare.", + "macOS, Linux packages, AppImage, Flatpak), and says so if it isn't installed, before making a copy.": "macOS, Linux-paket, AppImage, Flatpak), och säger till om det inte är installerat, innan en kopia görs.", + "made a lock test flaky, and the fix closes the window for good.": "gjorde ett låstest instabilt, och korrigeringen stänger luckan för gott.", + "made from the old pixels: they are made again from the new file, and a scan still busy with the old file when it": "skapade från de gamla pixlarna: de skapas igen från den nya filen, och en skanning som fortfarande arbetar med den gamla filen när den", + "magnified preview isn't taken for the photo when checking focus at 1:1.": "förstorad förhandsgranskning tas inte för fotot när du kontrollerar skärpan i 1:1.", + "makes it inside that folder (`dialog.newAlbum`, `dialog.newFolder`, `dialog.smartAlbum`, `dialog.newSmartAlbum` take `parent`).": "skapar den i den mappen (`dialog.newAlbum`, `dialog.newFolder`, `dialog.smartAlbum`, `dialog.newSmartAlbum` tar `parent`).", + "Manage Effect Presets…": "Hantera effektförinställningar…", + "Managed by Printer (Adobe RGB)": "Hanteras av skrivaren (Adobe RGB)", + "Managed by Printer (sRGB)": "Hanteras av skrivaren (sRGB)", + "many Photos added, or why it added none. Export with Previous and export presets repeat it.": "många foton som lades till, eller varför inga lades till. Exportera med föregående och exportförinställningar upprepar det.", + "map); the option is per photo, so presets and Copy Settings carry it.": "karta); alternativet gäller per foto, så förinställningar och Kopiera inställningar för det med sig.", + "Mask Effect Presets": "Maskeffektförinställningar", + "means no (it used to count as yes), and a value that is neither yes nor no is refused.": "betyder nej (det räknades tidigare som ja), och ett värde som varken är ja eller nej vägras.", + "memory than the computer has, the panorama is made as large as fits (five 51 MP photos: up to 166 MP with": "minne än datorn har görs panoramat så stort som ryms (fem foton på 51 MP: upp till 166 MP med", + "menu, and Return in the painter's box starts painting.": "menyn, och Return i målningsrutan startar målningen.", + "merges used to open at about 7000 K / +115 where the photos show 4000–5300 K / +8. HDRs merged before this keep": "sammanfogningar öppnades tidigare vid ungefär 7000 K / +115 där fotona visar 4000–5300 K / +8. HDR-bilder som sammanfogats före detta behåller", + "Merging uses about a quarter less memory: three 67 MP raws need 3.8 GB instead of 4.8 GB.": "Sammanfogning använder ungefär en fjärdedel mindre minne: tre raw-filer på 67 MP kräver 3,8 GB i stället för 4,8 GB.", + "message box that names the log file, instead of quitting without a trace (issue #260).": "en meddelanderuta som anger loggfilen, i stället för att avsluta utan att lämna något spår (ärende #260).", + "missing ones.": "saknade.", + "missing. And a share that drops after the scan has listed a folder no longer turns that folder's photos into": "saknas. Och en nätverksresurs som försvinner efter att genomsökningen har listat en mapp gör inte längre den mappens foton till", + "Models are installed separately after accepting their terms; no weights are bundled. See [setup and limitations](denoise.md).": "Modellerna installeras separat efter att du har godkänt deras villkor; inga vikter medföljer. Se [installation och begränsningar](denoise.md).", + "models in a `LightCraftData` folder beside it instead of the per-user settings folder (issue #1200), as": "modeller i en `LightCraftData`-mapp bredvid den i stället för i inställningsmappen per användare (ärende #1200), som", + "Monitor profiles": "Bildskärmsprofiler", + "More Canon EOS R6 Mark II C-RAW files decode": "Fler C-RAW-filer från Canon EOS R6 Mark II avkodas", + "Move Mask Effect to Group": "Flytta maskeffekt till grupp", + "Move Photos": "Flytta foton", + "Move Print Cell": "Flytta utskriftscell", + "Move Print Cell to Page": "Flytta utskriftscell till sida", + "moved from ΔE00 7.6 to 5.2 against Lightroom's.": "flyttades från ΔE00 7,6 till 5,2 jämfört med Lightrooms.", + "Multi": "Flera", + "My Preset": "Min förinställning", + "name (`catalog.snap.tmp`, `model.onnx.part`): the link is removed and a new file made in its place, so the file it": "namn (`catalog.snap.tmp`, `model.onnx.part`): länken tas bort och en ny fil skapas i dess ställe, så filen den", + "name. Whole names, one chip per keyword, stays the default.": "namn. Hela namn, en bricka per nyckelord, är fortfarande standard.", + "names.": "namn.", + "neutral default.": "neutralt standardvärde.", + "never restore anything. Agents: `library.import` → `onDeleted` defaults to `restore` (`skip` keeps the old": "återställer aldrig något. Agenter: `library.import` → `onDeleted` har `restore` som standard (`skip` behåller det gamla", + "New fields: Keyword Count (\"2 or more\", \"exactly 2\"…), People and People Count (named faces), Shutter Speed (written": "Nya fält: Antal nyckelord (\"2 eller fler\", \"exakt 2\"…), Personer och Antal personer (namngivna ansikten), Slutartid (skrivs", + "new photos (and Reset) get it, photos you already edited keep their look until you choose Photo ▸ Update to Current": "nya foton (och Återställ) får den, foton du redan har redigerat behåller sitt utseende tills du väljer Foto → Uppdatera till aktuell", + "New Print Page": "Ny utskriftssida", + "Next History Step": "Nästa historiksteg", + "Next Slide": "Nästa bild", + "next to it while you rotate (issue #534). For an exact angle, type it in the new Angle field under Straighten and press Return": "bredvid den medan du roterar (ärende #534). För en exakt vinkel skriver du den i det nya fältet Vinkel under Räta upp och trycker på Return", + "Nikon D600, D610 and D5000": "Nikon D600, D610 och D5000", + "Nikon D850, Canon EOS 5D Mark III and others) now show white balance in Kelvin, as a DNG does and as Lightroom": "Nikon D850, Canon EOS 5D Mark III med flera) visar nu vitbalansen i kelvin, som en DNG gör och som Lightroom", + "Nikon lens corrections": "Objektivkorrigeringar för Nikon", + "Nikon raws without coloured edge bars": "Nikon-raw-filer utan färgade kantränder", + "Nikon Z 6II, Z 8 and D5300 colour profiles": "Färgprofiler för Nikon Z 6II, Z 8 och D5300", + "No clipping detected in this preview.": "Ingen klippning upptäcktes i den här förhandsgranskningen.", + "No faces by that name": "Inga ansikten med det namnet", + "no longer saves it). Return in those dialogs now confirms them, and their name opens selected. More fields will": "sparar den inte längre). Return i de dialogrutorna bekräftar dem nu, och deras namn öppnas markerat. Fler fält kommer", + "No named people yet. Name the faces below to start.": "Inga namngivna personer än. Namnge ansiktena nedan för att börja.", + "No people yet": "Inga personer än", + "No person by that name": "Ingen person med det namnet", + "no sound yet. It is AV1 rather than Lightroom's H.264, which has no open encoder we can ship; current browsers,": "inget ljud än. Det är AV1 i stället för Lightrooms H.264, som saknar en öppen kodare vi kan leverera; aktuella webbläsare,", + "No unnamed faces. Faces found in your photos appear here until you name them.": "Inga namnlösa ansikten. Ansikten som hittas i dina foton visas här tills du namnger dem.", + "Noise reduction looks the same at every size": "Brusreduceringen ser likadan ut i alla storlekar", + "Not loaded yet": "Inte inläst än", + "note saying what is missing. Agents use `slideshow.templates.*`, and `slideshow.preview {template}` renders a template": "anteckning som anger vad som saknas. Agenter använder `slideshow.templates.*`, och `slideshow.preview {template}` renderar en mall", + "Nothing already edited changes: a Custom white balance set on the old relative scale renders pixel for pixel as": "Inget som redan redigerats ändras: en anpassad vitbalans som ställts in på den gamla relativa skalan renderas pixel för pixel som", + "Nothing else changes: the same files are found new, already there, moved or missing, and sidecars get the same": "Inget annat ändras: samma filer hittas som nya, redan befintliga, flyttade eller saknade, och sidecar-filer får samma", + "noticeably duller.": "märkbart mattare.", + "now import as \"preview only\" with their embedded JPEG instead of failing. A raw whose data is damaged but whose": "importeras nu som \"endast förhandsgranskning\" med sin inbäddade JPEG i stället för att misslyckas. En raw-fil vars data är skadade men vars", + "now measured on the masked columns alone (8 corpus bodies, EOS 40D to 5DS R). On a 6D photo the starting render": "mäts nu enbart på de maskerade kolumnerna (8 kamerahus i korpusen, EOS 40D till 5DS R). På ett foto från 6D blir startrenderingen", + "now stays, like its preview, until another photo or view is shown.": "stannar nu kvar, liksom dess förhandsgranskning, tills ett annat foto eller en annan vy visas.", + "of a portrait photo): masked sensor columns were being developed as part of the picture (issues #976, #914). The": "av ett stående foto): maskerade sensorkolumner framkallades som en del av bilden (ärenden #976, #914). Den", + "of a portrait photo): masked sensor columns were being developed as part of the picture (issues #976, #914,": "av ett stående foto): maskerade sensorkolumner framkallades som en del av bilden (ärenden #976, #914,", + "of quietly rendering everything on the CPU, much more slowly. Help ▸ System Info says why. On NixOS this happens": "i stället för att i tysthet rendera allt på CPU:n, mycket långsammare. Hjälp → Systeminfo anger varför. På NixOS händer detta", + "Off by default (HEVC patents are the distributor's call, same as PhotoCraft); official builds pass `--features heif`.": "Av som standard (HEVC-patent är distributörens sak, precis som i PhotoCraft); officiella byggen skickar `--features heif`.", + "Older raw cameras": "Äldre raw-kameror", + "older versions refuse it, as with every format change.": "äldre versioner vägrar öppna det, som vid varje formatändring.", + "Olympus E-10 raws open with the camera's white balance (White Balance ▸ As Shot) and without the grey haze in": "Raw-filer från Olympus E-10 öppnas med kamerans vitbalans (Vitbalans → Som tagen) och utan det grå diset i", + "Olympus ORF raws get the starting look fitted to the camera's own JPEG too, instead of opening flat and grey (the": "Även ORF-raw-filer från Olympus får startutseendet anpassat efter kamerans egen JPEG, i stället för att öppnas platta och grå (de", + "On a person's page, the ↑ control on a suggested face confirms it and all shown suggestions with equal or higher": "På en persons sida bekräftar ↑-kontrollen på ett föreslaget ansikte det och alla visade förslag med lika hög eller högre", + "On Linux and FreeBSD, file dialogs (Import Photos…, Open Library, Export, presets, keyword lists…) are children of": "På Linux och FreeBSD är fildialogrutor (Importera foton…, Öppna bibliotek, Exportera, förinställningar, nyckelordslistor…) underordnade", + "On macOS the system does not tell LightCraft when a window is zoomed from the Window menu or resized after a": "På macOS meddelar systemet inte LightCraft när ett fönster zoomas från Fönster-menyn eller storleksändras efter en", + "On macOS, photos are shown through the profile of the screen the window is on while no monitor profile is chosen in": "På macOS visas foton genom profilen för skärmen som fönstret ligger på så länge ingen bildskärmsprofil har valts i", + "On macOS, ratings `0–5`, labels `6–9` and pick/unflag `P/U` now reach the app even when shown in the native menu (issue #283; adapted from PR #261).": "På macOS når betyg `0–5`, etiketter `6–9` och vald/ta bort flagga `P/U` nu appen även när de visas i den inbyggda menyn (ärende #283; anpassat från PR #261).", + "On macOS, single-key shortcuts that appear in the menu bar now work: E, C, H, M, ⇧P, I, K, D, ratings 0–5,": "På macOS fungerar nu kortkommandon med en tangent som visas i menyraden: E, C, H, M, ⇧P, I, K, D, betyg 0–5,", + "on the CPU and explains how to turn the GPU back on.": "på CPU:n och förklarar hur du slår på GPU:n igen.", + "on the CPU, are not waited for).": "på CPU:n, väntas inte in).", + "on the DLL search path without its `dxil.dll` (issue #471): DirectX 12 shaders now always compile with the": "i DLL-sökvägen utan sin `dxil.dll` (ärende #471): DirectX 12-shaders kompileras nu alltid med", + "on the top bar it comes back zoomed. The other way round, a window you drag out until it is as wide as the": "i det övre fältet kommer det tillbaka zoomat. Omvänt blir ett fönster som du drar ut tills det är lika brett som", + "On Windows and Linux, Ctrl+C outside a text field copies edit settings and Ctrl+V pastes them (⇧Ctrl+V: Paste": "På Windows och Linux kopierar Ctrl+C utanför ett textfält redigeringsinställningar och Ctrl+V klistrar in dem (⇧Ctrl+V: Klistra in", + "on; ✕ stops the tasks that can stop. Three rows show, then \"+N more\". The separate export panel and the progress": "pågår; × stoppar de uppgifter som kan stoppas. Tre rader visas, sedan \"+N till\". Den separata exportpanelen och förloppet", + "once you zoom out or move on.": "när du zoomar ut eller går vidare.", + "One kind of button": "En sorts knapp", + "One photo fills each page inside the margins.": "Ett foto fyller varje sida innanför marginalerna.", + "one that overflows.": "den som flödar över.", + "only convert between the camera's multipliers and Kelvin; the colour look is what it was.": "konverterar bara mellan kamerans multiplikatorer och kelvin; färgutseendet är detsamma som förut.", + "only the header and the preview are read, as for other raws.": "läses bara filhuvudet och förhandsgranskningen, som för andra raw-filer.", + "open and hasn't written back yet) imports instead of failing with \"unsupported SQLite schema format\".": "öppen och inte har skrivit tillbaka än) importeras i stället för att misslyckas med \"unsupported SQLite schema format\".", + "Open Library knows a Lightroom catalog": "Öppna bibliotek känner igen en Lightroom-katalog", + "Open Original in Other Editor (RAW, no copy)": "Öppna original i annat redigeringsprogram (RAW, ingen kopia)", + "opened a library, older versions refuse it, as with every format change.": "öppnat ett bibliotek vägrar äldre versioner öppna det, som vid varje formatändring.", + "Opening a library no longer rewrites the date of every thumbnail it shows, which made them all look new at each": "Att öppna ett bibliotek skriver inte längre om datumet för varje miniatyr det visar, vilket fick alla att se nya ut vid varje", + "Opening Synchronize Folder, an import review or an import no longer makes a table of every photo in the library": "Att öppna Synkronisera mapp, en importgranskning eller en import skapar inte längre en tabell över varje foto i biblioteket", + "Optics, Geometry and Calibration (issue #316).": "Optik, Geometri och Kalibrering (ärende #316).", + "Optional remote SAM 3: keep the native editor local and run Object, Describe, and detail": "Valfri fjärr-SAM 3: behåll den inbyggda redigeraren lokalt och kör Objekt, Beskriv och detalj", + "or drop photos and folders into this window": "eller släpp foton och mappar i det här fönstret", + "or drop photos into this window": "eller släpp foton i det här fönstret", + "or the edge of another folder, to place it before or after it: that folder is then ordered by hand. Right-click ▸": "eller kanten på en annan mapp för att placera den före eller efter den: den mappen ordnas då manuellt. Högerklicka →", + "or unchecks a range of photos (issue #338).": "eller bockar ur ett intervall av foton (ärende #338).", + "original again to find the haze colour. On a 64 MP raw (Sony A7R VI) that took ~0.2 s of CPU per pan and per": "originalet igen för att hitta disets färg. På en raw-fil på 64 MP (Sony A7R VI) tog det ~0,2 s CPU-tid per panorering och per", + "other file-naming tokens, with a size, colour, opacity and an optional soft shadow (opacity, offset, radius, angle).": "andra filnamnstoken, med storlek, färg, opacitet och en valfri mjuk slagskugga (opacitet, förskjutning, radie, vinkel).", + "out green and dark.": "ut gröna och mörka.", + "out, a folder that went read-only) used to be written only to the library, with a line in the log, so the sidecar": "ut, en mapp som blev skrivskyddad) skrevs tidigare bara till biblioteket, med en rad i loggen, så att sidecar-filen", + "out. Clear Recent Libraries empties the list.": "ut. Rensa senaste bibliotek tömmer listan.", + "Outside the crop box, where dragging rotates the photo, the pointer is a curved double arrow, and the angle is shown": "Utanför beskärningsramen, där dragning roterar fotot, är pekaren en krökt dubbelpil, och vinkeln visas", + "over one by one as they are used; the rest stay until the cache makes room.": "över en i taget när de används; resten ligger kvar tills cachen gör plats.", + "overlays and the intro and ending screens, in view order.": "överlägg och intro- och slutskärmarna, i visningsordning.", + "owns every shared sidecar name in the library: 2.4 s a write in that library, now under 1 s.": "äger varje delat sidecar-namn i biblioteket: 2,4 s per skrivning i det biblioteket, nu under 1 s.", + "Page": "Sida", + "Page Options": "Sidalternativ", + "Panasonic and Leica raws (RW2, RWL) are now corrected for lens distortion the way the camera corrects its own JPEG": "Raw-filer från Panasonic och Leica (RW2, RWL) korrigeras nu för objektivdistorsion på samma sätt som kameran korrigerar sin egen JPEG", + "panel. Each is switched on on its own and has a background colour and, centred on it, your identity plate (the one": "panelen. Var och en slås på för sig och har en bakgrundsfärg och, centrerad på den, din namnskylt (den", + "panels closed, from 71 ms).": "paneler stängda, från 71 ms).", + "Panning a photo zoomed to 1:1, or moving a slider while zoomed, no longer decodes the whole raw again each time on": "Att panorera ett foto zoomat till 1:1, eller att flytta ett skjutreglage medan det är zoomat, avkodar inte längre hela raw-filen igen varje gång på", + "Panorama and HDR Panorama merges keep the resolution of their photos instead of stopping at 40 megapixels": "Panorama- och HDR-panoramasammanfogningar behåller sina fotons upplösning i stället för att stanna vid 40 megapixel", + "pass, a new order each time round), repeat (off: the slideshow ends after the last photo) and preparing previews in": "genomgång, en ny ordning varje varv), upprepa (av: bildspelet slutar efter det sista fotot) och förberedelse av förhandsgranskningar i", + "past that a write is skipped (the image stays in memory and is written by a later render), so a slow disk can't": "efter det hoppas en skrivning över (bilden stannar i minnet och skrivs av en senare rendering), så att en långsam disk inte kan", + "Pause / Resume Slideshow": "Pausa/återuppta bildspel", + "Pentax raws without black borders": "Pentax-raw-filer utan svarta kanter", + "Photo Above": "Foto ovanför", + "Photo Below": "Foto nedanför", + "Photo Grid marked nothing, and Detail, the histogram and the photo info showed a photo that isn't in the folder.": "Fotorutnät markerade ingenting, och Detalj, histogrammet och fotoinformationen visade ett foto som inte finns i mappen.", + "photo has yet too. Filter it, tick a keyword to give it to the selected photos (a dash: only some have it), or click": "fotot har ännu också. Filtrera, bocka för ett nyckelord för att ge det till de markerade fotona (ett streck: bara vissa har det), eller klicka", + "Photo Merge of Canon CR2 (and other raws whose colour LightCraft fits from the camera's own JPEG, such as NEF and": "Fotosammanfogning av Canon CR2 (och andra raw-filer vars färg LightCraft anpassar efter kamerans egen JPEG, till exempel NEF och", + "photo's rating as stars, and any number of text overlays (up to 16) built from tokens: `{caption}`, `{title}`,": "fotots betyg som stjärnor, och valfritt antal textöverlägg (upp till 16) byggda av token: `{caption}`, `{title}`,", + "photo: only the photos the edit touched are asked about again and put at their place in the order. In a library of": "foto: bara de foton som redigeringen berörde tillfrågas igen och placeras på sin plats i ordningen. I ett bibliotek med", + "PhotoCraft does. If that folder can't be written, the usual folder is used and the log says why.": "PhotoCraft gör. Om den mappen inte går att skriva till används den vanliga mappen och loggen anger varför.", + "photos along the areas they clipped: right next to a clipped area, a photo's colour isn't used. It showed most when": "foton längs områdena de klippte: precis intill ett klippt område används inte ett fotos färg. Det syntes mest när", + "Photos deleted (or moved) by another app no longer stay in a Local folder, failing to load and logging an error": "Foton som raderats (eller flyttats) av en annan app ligger inte längre kvar i en lokal mapp, där de inte gick att läsa in och loggade ett fel", + "Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float": "Foton redigerade i HDR: JPEG med en HDR-förstärkningskarta (ser rätt ut överallt, ljusare högdagrar på HDR-skärmar), AVIF som 10-bitars, PNG och JPEG XL som 16-bitars Rec. 2020 PQ; TIFF kräver 32-bitars flyttal", + "Photos from Nikon DSLRs like the D700, D750, D80 or D5300 now show which lens they were taken with, for example": "Foton från Nikons systemkameror som D700, D750, D80 eller D5300 visar nu vilket objektiv de togs med, till exempel", + "Photos that start matching still appear at once, and deleting a photo or taking it out of the album or folder": "Foton som börjar matcha visas fortfarande direkt, och om du raderar ett foto eller tar ut det ur albumet eller mappen", + "Photos that tie on the sort key (equal ratings, one import batch, a burst shot within the same second) now sort by": "Foton som har samma sorteringsnyckel (lika betyg, samma importbatch, en bildserie inom samma sekund) sorteras nu efter", + "Photos with deep shadows no longer have to extend the first measured tone in a straight line to black.": "Foton med djupa skuggor behöver inte längre förlänga den första uppmätta tonen i en rak linje till svart.", + "Photos you import show up here. Nothing is copied or moved unless you choose to.": "Foton som du importerar visas här. Ingenting kopieras eller flyttas om du inte väljer det.", + "pile up threads and memory.": "samla på sig trådar och minne.", + "pointed to is never changed (issue #1502).": "som den pekar på ändras aldrig (ärende #1502).", + "Portable mode": "Portabelt läge", + "preset pickers in Import and Settings ▸ Import scroll the same way.": "förinställningsväljarna i Import och Inställningar → Import rullar på samma sätt.", + "presets.json) stays responsive. Every command used to re-serialize the whole list to see whether it had changed": "presets.json) fortsätter att svara snabbt. Varje kommando brukade serialisera om hela listan för att se om den hade ändrats", + "press the new keys (Esc cancels), × removes it, ↺ restores the original, Reset All undoes every change. A key that": "tryck på de nya tangenterna (Esc avbryter), × tar bort det, ↺ återställer originalet, Återställ alla ångrar alla ändringar. En tangent som", + "preview is intact does the same.": "förhandsgranskningen är intakt gör samma sak.", + "Preview or Photos. Moving the window to another screen is followed; **Use Screen Profile** goes back to it after": "Preview eller Photos. När fönstret flyttas till en annan skärm följer profilen med; **Använd skärmprofil** går tillbaka till den efter", + "preview, with the reason, instead of showing a black tile. A JPEG XL preview stored in the DNG is used like an": "förhandsgranskning, med orsaken, i stället för att visa en svart ruta. En JPEG XL-förhandsgranskning som lagras i DNG-filen används som en", + "previews for up to a second.": "förhandsgranskningar i upp till en sekund.", + "Previews match exports on Mac screens": "Förhandsgranskningar matchar exporter på Mac-skärmar", + "Previous History Step": "Föregående historiksteg", + "Previous Slide": "Föregående bild", + "Print Settings": "Utskriftsinställningar", + "Print Templates": "Utskriftsmallar", + "Print to PDF": "Skriv ut till PDF", + "Process. See [process versions](process-versions.md).": "Process. Se [processversioner](process-versions.md).", + "profile overrides for memory-constrained builders (issue #1196), including why packaging": "profilåsidosättningar för byggare med begränsat minne (ärende #1196), inklusive varför paketering", + "projected, so it needs less memory than before at any size (an 81 MP stitch: 4.4 GB instead of 6.2 GB).": "projiceras, så den behöver mindre minne än tidigare i alla storlekar (en sammanfogning på 81 MP: 4,4 GB i stället för 6,2 GB).", + "promise, instead of filtering whatever album or folder was open, which often showed nothing (issue #341).": "lovar, i stället för att filtrera det album eller den mapp som var öppen, vilket ofta inte visade något (ärende #341).", + "ProRAW the way the iPhone renders it, turn on Profile ▸ Camera local tone mapping (shown for photos that carry the": "ProRAW så som iPhone renderar det aktiverar du Profil → Kamerans lokala tonmappning (visas för foton som har", + "Quitting while a task that can be stopped is running asks first (\"Quit Anyway\" stops it).": "Om du avslutar medan en uppgift som kan stoppas körs får du en fråga först (\"Avsluta ändå\" stoppar den).", + "Radial masks brought over from Lightroom Classic (catalog import, XMP sidecars, edits inside DNGs and presets) now": "Radiella masker som förts över från Lightroom Classic (katalogimport, XMP-sidofiler, redigeringar i DNG-filer och förinställningar) nu", + "ran beside it.": "kördes bredvid den.", + "Ratings, flags, labels, keywords, collections/sets, virtual copies and supported edits migrate;": "Betyg, flaggor, etiketter, nyckelord, samlingar/uppsättningar, virtuella kopior och redigeringar som stöds migreras;", + "Raw files whose raw data sits in a private block of a TIFF (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and Kodak DCS": "Raw-filer vars rådata ligger i ett privat block i en TIFF (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds och Kodak DCS", + "raw whose tile claims far more samples than it holds, and an ARW6 with a broken tile are refused first. All 74": "raw-fil vars ruta påstår sig innehålla långt fler sampel än den har, och en ARW6 med en trasig ruta avvisas först. Alla 74", + "Raws from 52 camera models (22 Canon, 11 Nikon, 11 Sony, 3 Fujifilm and 5 others, plus their other names) whose": "Raw-filer från 52 kameramodeller (22 Canon, 11 Nikon, 11 Sony, 3 Fujifilm och 5 andra, plus deras andra namn) vars", + "Raws from cameras that correct their own JPEG for lens distortion (Panasonic and Fujifilm with that setting on, the": "Raw-filer från kameror som korrigerar sin egen JPEG för objektivdistorsion (Panasonic och Fujifilm med den inställningen på,", + "Raws from older Nikon bodies no longer show a thin coloured or dark bar along one edge (the right edge, or the top": "Raw-filer från äldre Nikon-hus visar inte längre en tunn färgad eller mörk rand längs en kant (högerkanten, eller överkanten", + "Raws from the 52 camera models whose colour matrices LightCraft has measured (Sony ILCE-7M3, ILCE-7M4, ILCE-7RM3,": "Raw-filer från de 52 kameramodeller vars färgmatriser LightCraft har mätt upp (Sony ILCE-7M3, ILCE-7M4, ILCE-7RM3,", + "Raws from the Nikon D600, D610 and D5000 no longer show a bright line down the right edge (issue #1627). Their": "Raw-filer från Nikon D600, D610 och D5000 visar inte längre en ljus linje längs högerkanten (ärende #1627). Deras", + "Raws from the Nikon Z 6II, Z 8 and D5300 now start from a colour profile built from a few hundred photos from each camera, the same way the": "Raw-filer från Nikon Z 6II, Z 8 och D5300 utgår nu från en färgprofil som byggts av några hundra foton från varje kamera, på samma sätt som", + "Raws from the Nikon Z 6II, Z 8 and Z f now open with the camera's own distortion correction, as Lightroom applies a": "Raw-filer från Nikon Z 6II, Z 8 och Z f öppnas nu med kamerans egen distorsionskorrigering, så som Lightroom tillämpar en", + "Raws from the Pentax KP, KF, K-3 Mark III (and Monochrome), K-70, K-1, K-1 Mark II, K-S1, K-S2 and 645Z no longer": "Raw-filer från Pentax KP, KF, K-3 Mark III (och Monochrome), K-70, K-1, K-1 Mark II, K-S1, K-S2 och 645Z visar inte längre", + "raws of other cameras keep the as-shot shift of issue #510. The two Kelvin scales come from different matrices and": "raw-filer från andra kameror behåller förskjutningen av Som tagen från ärende #510. De två Kelvinskalorna kommer från olika matriser och", + "Raws whose preview is in Adobe RGB (Sony α1 among others) no longer read the whole file for their grid thumbnail:": "Raw-filer vars förhandsgranskning är i Adobe RGB (bland annat Sony α1) läser inte längre hela filen för sin miniatyr i rutnätet:", + "Read Focus Points": "Läs fokuspunkter", + "Read Focus Points in the Background": "Läs fokuspunkter i bakgrunden", + "read from the white-balance presets the camera stores in every ARW: a photo shot at 3400 K on the camera reads": "läses från de vitbalansförinställningar som kameran lagrar i varje ARW: ett foto som tagits med 3400 K på kameran visar", + "Reading focus points": "Läser fokuspunkter", + "Recently Deleted is listed with All Photos, Recently Added and Picks under My Photos.": "Nyligen raderade visas tillsammans med Alla foton, Nyligen tillagda och Valda under Mina foton.", + "Recheck Preview-Only Raws": "Kontrollera raw-filer med bara förhandsgranskning igen", + "recipes can override inherited settings. Default release profiles and application behavior": "recept kan åsidosätta ärvda inställningar. Standardprofiler för releaser och programmets beteende", + "Recognition": "Igenkänning", + "relinked to the file it is imported from. Browsing a folder in Local, Auto Import and a Lightroom catalog import": "omlänkat till filen som det importeras från. När du bläddrar i en mapp i Lokalt, Automatisk import och en import av Lightroom-katalog", + "remembered.": "sparas.", + "Rename Mask Effect": "Byt namn på maskeffekt", + "Rename Mask Effect Group": "Byt namn på maskeffektgrupp", + "Rename Person": "Byt namn på person", + "Rename Slideshow Template": "Byt namn på bildspelsmall", + "render with Clarity, Dehaze, Texture or Highlights / Shadows on: their blurs are held to the picture's size.": "renderas med Klarhet, Ta bort dis, Textur eller Högdagrar / Skuggor på: deras oskärpa begränsas till bildens storlek.", + "renders a screen as a PNG.": "renderar en skärm som PNG.", + "replaced are listed as \"Previous settings\" until you quit: click that to go back.": "ersatts listas som \"Föregående inställningar\" tills du avslutar: klicka på det för att gå tillbaka.", + "reports each row's `label`.": "rapporterar varje rads `label`.", + "Reset Print Settings": "Återställ utskriftsinställningar", + "Resetting a slider": "Återställning av reglage", + "Reshuffle, another source, filter or sort, or new rules for the smart album shows what matches now.": "Blanda om, en annan källa, ett annat filter eller en annan sortering, eller nya regler för det smarta albumet visar vad som matchar nu.", + "Resize Print Cell": "Ändra storlek på utskriftscell", + "Resting the pointer on a slider's name or its thumb now says that a double-click resets it (\"Exposure — double-click": "Om du vilar pekaren på ett reglages namn eller dess handtag visas nu att ett dubbelklick återställer det (\"Exponering – dubbelklicka", + "Restore All": "Återställ alla", + "restore the photo too and say \"Restored 1 photo from Recently Deleted\". A deleted photo whose file was moved is": "återställer också fotot och säger \"Återställde 1 foto från Nyligen raderade\". Ett raderat foto vars fil har flyttats är", + "Return presses OK in Choose Edit Settings to Copy (⇧⌘C) and Paste Selected Settings (⇧⌘V), and Esc cancels them": "Return trycker på OK i Välj redigeringsinställningar att kopiera (⇧⌘C) och Klistra in markerade inställningar (⇧⌘V), och Esc avbryter dem", + "Right-click a folder (or a disk other than the startup disk) in the sidebar's Folders section ▸ Set Color Label ▸ a colour or None. The row": "Högerklicka på en mapp (eller en annan disk än startdisken) i sidofältets avsnitt Mappar → Ange färgetikett → en färg eller Ingen. Raden", + "Right-click a folder (or a disk other than the startup disk) in the sidebar's Folders section ▸ Synchronize": "Högerklicka på en mapp (eller en annan disk än startdisken) i sidofältets avsnitt Mappar → Synkronisera", + "Right-click a folder ▸ New ▸ Create Album… / Create Smart Album… / Create Smart Album from Filter… / Create Folder…": "Högerklicka på en mapp → Ny → Skapa album… / Skapa smart album… / Skapa smart album från filter… / Skapa mapp…", + "Right-click a photo ▸ Edit In ▸ Edit in PhotoCraft (or Photo ▸ Edit In, ⇧⌘E) renders a copy with your edits, stacks it": "Högerklicka på ett foto → Redigera i → Redigera i PhotoCraft (eller Foto → Redigera i, ⇧⌘E) renderar en kopia med dina redigeringar, staplar den", + "Right-click Search Photos, a slider's typed value, the Info panel's fields, the name field of New Album, Rename": "Högerklicka på Sök foton, ett reglages inskrivna värde, fälten i panelen Info, namnfältet i Nytt album, Byt namn", + "Right-click ▸ Put New Keywords Inside This Keyword: new keywords, made with + or typed in the box above, go inside": "Högerklicka → Lägg nya nyckelord inuti detta nyckelord: nya nyckelord, som skapas med + eller skrivs i rutan ovanför, hamnar inuti", + "Rule problems are shown in your language and name the field the way the menu does (\"Title: needs something to look": "Regelproblem visas på ditt språk och anger fältet på samma sätt som menyn (\"Titel: behöver något att söka", + "Rule values are checked: a rating of 9, a date like 2026-13 or \"banana\", a \"between\" whose dates are the wrong": "Regelvärden kontrolleras: betyget 9, ett datum som 2026-13 eller \"banana\", ett \"mellan\" vars datum står i fel", + "Run face models on the CPU only": "Kör ansiktsmodeller bara på CPU:n", + "runs in the background with a row in the activity stack (✕ stops it); everything it does is one undo step, and no file on disk": "körs i bakgrunden med en rad i aktivitetsstapeln (× stoppar den); allt den gör är ett enda ångra-steg, och ingen fil på disken", + "samples, no longer crashes LightCraft at 1:1 or on export: the bad values read as black.": "sampel, får inte längre LightCraft att krascha vid 1:1 eller vid export: de felaktiga värdena läses som svart.", + "Samsung SRW files without compression now open as raws: NX5, NX10, NX11, NX20, NX200, NX210, NX1000, NX1100, EX1": "Samsung SRW-filer utan komprimering öppnas nu som raw-filer: NX5, NX10, NX11, NX20, NX200, NX210, NX1000, NX1100, EX1", + "Save Current Settings as New Effect Preset…": "Spara aktuella inställningar som ny effektförinställning…", + "Save Mask Effect": "Spara maskeffekt", + "Save Print Template": "Spara utskriftsmall", + "Save Slideshow Template": "Spara bildspelsmall", + "Save the current settings as a template of your own; right-click it to update it with the current settings, rename,": "Spara de aktuella inställningarna som en egen mall; högerklicka på den för att uppdatera den med de aktuella inställningarna, byta namn,", + "saved in an earlier version now shifts the other way; set it again (or re-run Auto / the white-balance picker).": "som sparats i en tidigare version förskjuts nu åt andra hållet; ange den igen (eller kör Auto / vitbalansväljaren igen).", + "Saving the catalog and resuming a model download no longer write through a link left at the temporary file's": "När katalogen sparas och en modellhämtning återupptas skrivs det inte längre via en länk som lämnats kvar vid den tillfälliga filens", + "says what to fix, and `albums.list` reports `problems`.": "säger vad som ska åtgärdas, och `albums.list` rapporterar `problems`.", + "scale keep their look, and As Shot shows the real temperature once the file is opened.": "skala behåller sitt utseende, och Som tagen visar den verkliga temperaturen när filen har öppnats.", + "scale. Each stays up for its own duration (by default the slide duration) and fades in and out like a slide.": "skala. Var och en visas under sin egen längd (som standard visningstiden per bild) och tonas in och ut som en bild.", + "screen and nearly as tall counts as zoomed.": "skärmen och nästan lika hög räknas som inzoomad.", + "screen readers). Each darkens a little when hovered and more when pressed, shows a ring where the keyboard is, and": "skärmläsare). Var och en mörknar lite när pekaren är över den och mer när den trycks ned, visar en ring där tangentbordsfokus är, och", + "screen. They are saved with the library.": "skärm. De sparas med biblioteket.", + "search by lens. LightCraft now reads the lens range Nikon keeps in its own maker note, the way Lightroom shows a": "söka efter objektiv. LightCraft läser nu objektivets omfång som Nikon lagrar i sin egen tillverkarnotering (maker note), så som Lightroom visar en", + "second colour, at an angle and opacity) and a background image (a photo from the library, at an opacity).": "andra färg, med en vinkel och en opacitet) och en bakgrundsbild (ett foto från biblioteket, med en opacitet).", + "secondary, danger (filled red) and ghost, in three sizes, with an icon or without, and an icon alone (named for": "sekundär, fara (fylld röd) och ghost, i tre storlekar, med eller utan ikon, och enbart en ikon (namngiven för", + "Sections are easier to tell apart: a hairline between them, the fold chevron in the same column as the rows'": "Avsnitten är lättare att skilja åt: en hårfin linje mellan dem, fällchevronen i samma kolumn som radernas", + "See [remote Metal inference](ai-masks.md#remote-metal-inference).": "Se [fjärrinferens med Metal](ai-masks.md#remote-metal-inference).", + "Select All and multi-selection show every selected photo in the grid and filmstrip, not only the active one": "Markera allt och flermarkering visar alla markerade foton i rutnätet och filmremsan, inte bara det aktiva", + "Select Only Active Photo": "Markera bara aktivt foto", + "Selected Settings). Ctrl+V only reaches LightCraft while the system clipboard holds text; otherwise use Edit ▸ Paste Edit": "markerade inställningar). Ctrl+V når bara LightCraft medan systemets urklipp innehåller text; annars använder du Redigera → Klistra in redigering", + "sensor data runs a few columns of filler past the picture, which stayed in the image; these bodies now develop": "sensordata har några kolumner utfyllnad efter bilden, som blev kvar i bilden; dessa hus framkallas nu", + "Set Effect for New Masks": "Ange effekt för nya masker", + "Set Print Cell Photo": "Ange foto för utskriftscell", + "Set Print Settings": "Ange utskriftsinställningar", + "set under Overlays: its text or image) or a line of text of its own, in the plate's colour or one you pick, at a": "som anges under Överlägg: dess text eller bild) eller en egen textrad, i skyltens färg eller en som du väljer, med en", + "set). An empty field leaves its key empty instead of moving the keywords after it; editing Recent Keywords and naming": "uppsättning). Ett tomt fält lämnar sin tangent tom i stället för att flytta nyckelorden efter det; redigering av Senaste nyckelord och namngivning", + "Setting or clearing a colour label shows a brief bottom confirmation, like rating a photo; custom label names appear in the message too.": "När du anger eller rensar en färgetikett visas en kort bekräftelse längst ned, som när du ger ett foto betyg; anpassade etikettnamn visas också i meddelandet.", + "settings folder there. The same goes for the temporary session offered when the library can't be opened.": "inställningsmappen där. Detsamma gäller den tillfälliga session som erbjuds när biblioteket inte kan öppnas.", + "Settings stays put when you change tabs": "Inställningar stannar kvar när du byter flik", + "Settings → Confirm before moving photos to another folder on disk turns it back on": "Inställningar → Bekräfta innan foton flyttas till en annan mapp på disken aktiverar det igen", + "Settings → Import → Cameras and Cards has an option to open the import review as soon as a camera or memory card": "Inställningar → Import → Kameror och kort har ett alternativ för att öppna importgranskningen så snart en kamera eller ett minneskort", + "Settings ▸ Display (issue #787). On P3 screens previews used to look more saturated than the exported files in": "Inställningar → Visning (ärende #787). På P3-skärmar såg förhandsgranskningar tidigare mer mättade ut än de exporterade filerna i", + "Settings ▸ Display ▸ Choose Profile… shows photos through your monitor's ICC profile (matrix/TRC or LUT-based), so": "Inställningar → Visning → Välj profil… visar foton genom bildskärmens ICC-profil (matris/TRC eller LUT-baserad), så", + "Settings ▸ General ▸ External Editing: the format (PSD or TIFF), colour space and bit depth for PhotoCraft and for": "Inställningar → Allmänt → Extern redigering: format (PSD eller TIFF), färgrymd och bitdjup för PhotoCraft och för", + "Settings ▸ Interface ▸ Appearance Mode: Sync with System, Dark Mode or Light Mode, above a light": "Inställningar → Gränssnitt → Utseendeläge: Synka med systemet, Mörkt läge eller Ljust läge, ovanför ett ljust", + "settings, one after the other: each stack, and photos taken less than a second apart at different exposures.": "inställningar, en efter en: varje stapel, och foton som tagits med mindre än en sekunds mellanrum med olika exponeringar.", + "Settings.": "Inställningar.", + "share of the slide, so slides look the same on any screen. They are saved with the library. Agents use": "andel av bilden, så att bilderna ser likadana ut på alla skärmar. De sparas med biblioteket. Agenter använder", + "Shortcuts are editable: Help ▸ Keyboard Shortcuts (⌘/) lists every command with a search box; click a shortcut and": "Kortkommandon kan redigeras: Hjälp → Kortkommandon (⌘/) listar alla kommandon med en sökruta; klicka på ett kortkommando och", + "show a black (or, on the 645Z, white) band along one or more edges (issue #1271). The sensor's masked border is": "visar en svart (eller, på 645Z, vit) rand längs en eller flera kanter (ärende #1271). Sensorns maskerade kant är", + "show as a partial import.": "visas som en delvis import.", + "Show Focus Point": "Visa fokuspunkt", + "show full screen\" asks the viewer to open it that way.": "visa i helskärm\" ber visningsprogrammet att öppna den så.", + "Show in Folders": "Visa i mappar", + "Show Info Overlay": "Visa infoöverlägg", + "Show Layout Image": "Visa layoutbild", + "show no dialogs and take `INSTALLFOLDER=...`.": "visar inga dialogrutor och tar emot `INSTALLFOLDER=...`.", + "Show this wheel's effect": "Visa det här hjulets effekt", + "Showing a Local folder now makes its first photo the active one, as albums and the other sources do (issue": "När en lokal mapp visas blir nu dess första foto det aktiva, som för album och de andra källorna (ärende", + "shown still takes it out of the view.": "visas tar den ändå ur vyn.", + "shows and as in Lightroom, and Tint values in Lightroom XMP sidecars now render as they do there. A custom Tint": "visar och som i Lightroom, och tonvärden i XMP-sidofiler från Lightroom renderas nu som där. Ett anpassat tonvärde", + "shows only a little of come out closer to the camera's JPEG.": "visar bara lite av blir nu närmare kamerans JPEG.", + "shows the label's dot before its photo count. Agents use `folder.label` (`path`, `label`); `library.folders`": "visar etikettens punkt före antalet foton. Agenter använder `folder.label` (`path`, `label`); `library.folders`", + "shows where it will go), or right-click a header for Move Up / Move Down.": "visar var det hamnar), eller högerklicka på en rubrik för Flytta upp / Flytta ned.", + "side panels open, the frame after a keyword went from about 156 ms to about 54 ms in that library (2 ms with the": "sidopanelerna öppna gick bildrutan efter ett nyckelord från cirka 156 ms till cirka 54 ms i det biblioteket (2 ms med", + "side under it. A long list stops after eight lines with \"+N more\", and the suggestions say only the keyword's own": "sida under det. En lång lista slutar efter åtta rader med \"+N till\", och förslagen anger bara nyckelordets eget", + "Sidebar sections": "Sidofältsavsnitt", + "sidecar lookup always did; the Add Photos dialog on Linux did not until 0.5.0 (GTK and the desktop portal match": "sökningen efter sidofiler alltid har gjort; dialogrutan Lägg till foton på Linux gjorde det inte förrän 0.5.0 (GTK och skrivbordsportalen matchar", + "sidecar, a preset or an agent) no longer crashes LightCraft; the point stays between them. Curve points sent to": "sidofil, en förinställning eller en agent) får inte längre LightCraft att krascha; punkten stannar mellan dem. Kurvpunkter som skickas till", + "similarity as one undo step. Hover or focus that face and press A for the same action; hidden suggestions stay hidden.": "likhet som ett ångra-steg. Hovra över eller fokusera det ansiktet och tryck på A för samma åtgärd; dolda förslag förblir dolda.", + "Size rules measure the photo as shown: Megapixels now counts the cropped photo, like Long Edge, Short Edge and": "Storleksregler mäter fotot som det visas: Megapixel räknar nu det beskurna fotot, liksom Långsida, Kortsida och", + "sky no longer flattens the twigs, lines and texture in it, and lifting Shadows keeps the texture of dark areas, much": "himmel plattar inte längre till kvistarna, linjerna och texturen i den, och när du lyfter Skuggor behålls texturen i mörka partier, mycket", + "Sky, Subject and Background masks instead of our heuristics, so the sky is selected where the camera found it": "maskerna Himmel, Motiv och Bakgrund i stället för våra heuristiker, så himlen markeras där kameran hittade den", + "Slider drags follow the pointer more closely": "Reglagedragningar följer pekaren närmare", + "Slider drags on large raws": "Reglagedragningar på stora raw-filer", + "slider step; a slider step now takes ~5 ms on the GPU.": "reglagesteg; ett reglagesteg tar nu ~5 ms på GPU:n.", + "Slides can now be laid out like Lightroom Classic's Slideshow Layout, Options and Backdrop panels: margins (all four": "Bilder kan nu läggas ut som i Lightroom Classics bildspelspaneler Layout, Alternativ och Fond: marginaler (alla fyra", + "Slides can now carry Lightroom Classic's Slideshow overlays: an identity plate (a line of text in a colour, or an": "Bilder kan nu ha Lightroom Classics bildspelsöverlägg: en namnskylt (en textrad i en färg, eller en", + "Slideshow Export Status": "Exportstatus för bildspel", + "Slideshow export: PDF, JPEG and video": "Bildspelsexport: PDF, JPEG och video", + "Slideshow intro and ending screens": "Intro- och slutskärmar för bildspel", + "Slideshow Layout Settings": "Layoutinställningar för bildspel", + "Slideshow layout, options and backdrop": "Layout, alternativ och fond för bildspel", + "Slideshow Options…": "Bildspelsalternativ…", + "Slideshow Overlay Settings": "Överläggsinställningar för bildspel", + "Slideshow overlays": "Bildspelsöverlägg", + "Slideshow playback": "Uppspelning av bildspel", + "Slideshow Playback Settings": "Uppspelningsinställningar för bildspel", + "Slideshow Slide Preview": "Förhandsgranskning av bildspelsbild", + "Slideshow Title Settings": "Titelinställningar för bildspel", + "smaller file; Progressive files show a coarse version first. 8- or 16-bit, sRGB, Display P3 or Rec. 2020 (lossless": "mindre fil; progressiva filer visar en grov version först. 8 eller 16 bitar, sRGB, Display P3 eller Rec. 2020 (förlustfri", + "Smaller JPEG exports": "Mindre JPEG-exporter", + "Smart album rules": "Regler för smarta album", + "smart preview\" or \"This photo can't be opened\", the reason on hover) instead of showing that preview as if it were": "smart förhandsgranskning\" eller \"Det här fotot kan inte öppnas\", med orsaken när du hovrar) i stället för att visa den förhandsgranskningen som om den vore", + "so a successful install looked like nothing had happened (issues #18, #399). Silent installs (`/qn`, `/passive`)": "så en lyckad installation såg ut som om ingenting hade hänt (ärenden #18, #399). Tysta installationer (`/qn`, `/passive`)", + "so the picture looks flat and washed out there. That's how PQ PNG works, not a broken file: for a picture that": "så bilden ser platt och urblekt ut där. Så fungerar PQ PNG, det är inte en trasig fil: för en bild som", + "soft shadow, with the caption and rating under the photo), Edge to Edge (photos cropped to fill the screen), Cinema": "mjuk skugga, med bildtext och betyg under fotot), Kant till kant (foton beskurna för att fylla skärmen), Bio", + "Some EOS R6 Mark II C-RAW files (about 1 in 50 in one photographer's library) opened as their preview with": "Vissa C-RAW-filer från EOS R6 Mark II (ungefär 1 av 50 i en fotografs bibliotek) öppnades som sin förhandsgranskning med", + "Sony A7R II (and other) raws whose camera JPEG is lens-corrected no longer open grey and too dark (issue #232): the": "Raw-filer från Sony A7R II (och andra) vars kamera-JPEG är objektivkorrigerad öppnas inte längre grå och för mörka (ärende #232):", + "Sony A7R IVA) now start from colours closer to the camera's. The starting look was being fitted against a JPEG that": "Sony A7R IVA) utgår nu från färger närmare kamerans. Startutseendet anpassades mot en JPEG som", + "Sony A7R VI (ILCE-7RM6) raws are corrected for lens distortion from the table the camera records in each file,": "Raw-filer från Sony A7R VI (ILCE-7RM6) korrigeras för objektivdistorsion utifrån tabellen som kameran sparar i varje fil,", + "Sony and Fujifilm profiles were made, instead of fitting each photo's colour on its own. Colours that one photo": "Sony- och Fujifilm-profilerna togs fram, i stället för att anpassa varje fotos färg för sig. Färger som ett foto", + "Sony ILCA-99M2, ILCA-77M2, SLT-A33, DSC-RX10, ILCE-3500 and ILCE-7S raws now show white balance in Kelvin too,": "Raw-filer från Sony ILCA-99M2, ILCA-77M2, SLT-A33, DSC-RX10, ILCE-3500 och ILCE-7S visar nu också vitbalans i Kelvin,", + "Sony α1 (ILCE-1) and A7S III (ILCE-7SM3) raws for now; manual-focus shots and Wide shots that only report the frame": "raw-filer från Sony α1 (ILCE-1) och A7S III (ILCE-7SM3) tills vidare; bilder med manuell fokus och Wide-bilder som bara anger ramen", + "Sort Contents A–Z (or + ▸ Sort Albums A–Z at the top level) goes back to by name. To put a folder after an open": "Sortera innehåll A–Ö (eller + → Sortera album A–Ö på översta nivån) återgår till namnordning. För att lägga en mapp efter en öppen", + "started yet another decode.": "startade ännu en avkodning.", + "starting look is fitted to the camera JPEG away from edges when the misaligned edges spoil the fit on all pixels.": "startutseendet anpassas till kamerans JPEG en bit från kanterna när de feljusterade kanterna förstör anpassningen över alla pixlar.", + "stayed behind the edit. LightCraft now says once that the sidecars are waiting, tries again every few seconds once": "låg kvar efter redigeringen. LightCraft säger nu en gång att sidofilerna väntar, försöker igen med några sekunders mellanrum när", + "Still tallied from every photo on each edit: the filter bar's lists of cameras, lenses and keywords.": "Räknas fortfarande fram ur varje foto vid varje redigering: filterfältets listor över kameror, objektiv och nyckelord.", + "stopping the others, and a template whose identity plate image or background photo isn't there still applies, with a": "stoppa de andra, och en mall vars namnskyltsbild eller bakgrundsfoto saknas används ändå, med en", + "stored that is big enough, not always from the largest one. On a Sony A7R VI file a 512 px thumbnail decodes": "sparad som är tillräckligt stor, inte alltid från den största. På en fil från Sony A7R VI avkodas en miniatyr på 512 px", + "Straight brush strokes with ⇧-click": "Raka penseldrag med ⇧-klick", + "Subfolder if you give one (say `Exports`), so a batch from several folders lands next to each set of originals.": "Undermapp om du anger en (till exempel `Exports`), så att en batch från flera mappar hamnar bredvid varje uppsättning original.", + "submenus for Source, File, Date, Keywords & People, Description, Camera Info, Location, Size, Develop and Assisted": "undermenyer för Källa, Fil, Datum, Nyckelord och människor, Beskrivning, Kamerainfo, Plats, Storlek, Framkalla och Assisterad", + "Switch to & Containing to see the keywords with the keywords containing them, or to Will Export to see what": "Byt till & innehåller för att se nyckelorden tillsammans med de nyckelord som innehåller dem, eller till Kommer att exporteras för att se vad", + "Switching libraries": "Byte av bibliotek", + "Synchronize Folder asks a network share less": "Synkronisera mapp frågar en nätverksresurs mindre", + "Synonyms. Exports now write keyword names to `dc:subject` and their paths to `lr:hierarchicalSubject`, and keywords": "Synonymer. Exporter skriver nu nyckelordsnamn till `dc:subject` och deras sökvägar till `lr:hierarchicalSubject`, och nyckelord", + "System Info, All Metadata and What's New end with one Close button, like About, instead of Cancel and OK": "Systeminfo, Alla metadata och Nyheter avslutas med en Stäng-knapp, som Om, i stället för Avbryt och OK", + "T) now matches.": "T) matchar nu.", + "take their tiles' ICC profile, and `imir` mirrors the way libheif writes it. Importing a HEIC reads its size from": "tar sina rutors ICC-profil, och `imir` speglar på samma sätt som libheif skriver det. Vid import av en HEIC läses storleken från", + "Template name": "Mallnamn", + "Text fields": "Textfält", + "that had not changed: 4.6 to 7.1 s of questions after the listing (about 3 ms a photo), now under 0.05 s. The": "som inte hade ändrats: 4,6 till 7,1 s frågor efter listningen (cirka 3 ms per foto), nu under 0,05 s. ", + "that light already reaches (left of the image area Canon records), 4 % of the range too high on the EOS 6D. It is": "som ljus redan når (till vänster om bildområdet som Canon sparar), 4 % av omfånget för högt på EOS 6D. Det är", + "that may be listed but not searched, a path longer than the system takes): such photos used to be listed as": "som kan listas men inte genomsökas, en sökväg längre än systemet klarar): sådana foton listades tidigare som", + "the area the camera itself frames, a few pixels smaller than before.": "området som kameran själv ramar in, några pixlar mindre än förut.", + "the arrow to see its photos.": "pilen för att se dess foton.", + "The catalog format is now version 3 (`Album.order`, `Op::SetAlbumOrder`). Once this version has opened a library,": "Katalogformatet är nu version 3 (`Album.order`, `Op::SetAlbumOrder`). När den här versionen har öppnat ett bibliotek,", + "The catalog format is now version 4 (`Catalog.folder_records`, `Op::SetFolderRecord`). Once this version has": "Katalogformatet är nu version 4 (`Catalog.folder_records`, `Op::SetFolderRecord`). När den här versionen har", + "The chips at the top of the Keywords panel are the keywords of every selected photo, not only the active one's; a": "Brickorna överst i panelen Nyckelord är nyckelorden för alla markerade foton, inte bara det aktivas; en", + "The choice is saved in export presets and Export with Previous. Agents pass": "Valet sparas i exportförinställningar och i Exportera med föregående. Agenter skickar", + "The colour is described by the PNG `cICP` chunk, not an ICC profile. HDR-aware viewers (current Chromium-based": "Färgen beskrivs av PNG-blocket `cICP`, inte av en ICC-profil. HDR-medvetna visningsprogram (aktuella Chromium-baserade", + "the container instead of decoding it; small previews use the file's embedded thumbnail. The release packages": "behållaren i stället för att avkoda den; små förhandsgranskningar använder filens inbäddade miniatyr. Releasepaketen", + "The copy is a 16-bit PSD by default, which PhotoCraft saves straight back to with File ▸ Save; when you come back to": "Kopian är som standard en 16-bitars PSD, som PhotoCraft sparar direkt tillbaka till med Arkiv → Spara; när du kommer tillbaka till", + "The count beside each smart album in the left panel follows an edit the same way: the album asks only the photos": "Antalet bredvid varje smart album i den vänstra panelen följer en redigering på samma sätt: albumet frågar bara de foton", + "The desktop app keeps a log file: `logs/lightcraft.log` in its settings folder (Linux `~/.config/lightcraft/logs/`),": "Skrivbordsappen för en loggfil: `logs/lightcraft.log` i sin inställningsmapp (Linux `~/.config/lightcraft/logs/`),", + "The disk is still asked wherever a listing can't be sure what a file system would say: about a name that is": "Disken tillfrågas fortfarande där en listning inte kan vara säker på vad ett filsystem skulle svara: om ett namn som är", + "the edit touched, where it asked every photo of the library after each edit (about 25 ms an album in that library).": "som redigeringen berörde, där det tidigare frågade alla foton i biblioteket efter varje redigering (cirka 25 ms per album i det biblioteket).", + "The English and Simplified Chinese build guides now describe command-local job and release": "Bygghandledningarna på engelska och förenklad kinesiska beskriver nu kommandolokala jobb och release", + "The Export dialog has **Add to Apple Photos**, with an optional album. The files are exported to your folder as": "Exportdialogrutan har **Lägg till i Apple Photos**, med ett valfritt album. Filerna exporteras till din mapp som", + "The Export dialog has Export to: Specific folder (as before) or Same folder as original photo, like Lightroom": "Exportdialogrutan har Exportera till: Angiven mapp (som förut) eller Samma mapp som originalfotot, som i Lightroom", + "The export runs in the background with its row in the activity stack; ✕ stops it and leaves no half-written file": "Exporten körs i bakgrunden med en egen rad i aktivitetsstapeln; × stoppar den och lämnar ingen halvskriven fil", + "The export watermark can be drawn on every slide's photo too (\"Use export watermark\" takes the one you last": "Exportvattenstämpeln kan också ritas på varje bilds foto (\"Använd exportvattenstämpel\" tar den du senast", + "The eye on the Light, Color and Detail section headers now hides their adjustments, as it already did for Effects,": "Ögat på avsnittsrubrikerna Ljus, Färg och Detalj döljer nu deras justeringar, som det redan gjorde för Effekter,", + "the file, instead of asking for gigabytes of memory, which could end LightCraft.": "filen, i stället för att begära flera gigabyte minne, vilket kunde få LightCraft att avslutas.", + "the files are reachable, and says when they're written. `library.retrySidecars` does it on request.": "filerna går att nå, och meddelar när de har skrivits. `library.retrySidecars` gör det på begäran.", + "the first time a library opens after this update, \"Tidying the thumbnail cache\" shows in the activity stack": "första gången ett bibliotek öppnas efter den här uppdateringen visas \"Städar miniatyrcachen\" i aktivitetsstapeln", + "The first time, macOS asks whether LightCraft may control Photos. Photos may ask about duplicates; files it skips": "Första gången frågar macOS om LightCraft får styra Photos. Photos kan fråga om dubbletter; filer som det hoppar över", + "The Hasselblad Lunar's raws (a Sony NEX-7 inside) now develop from their sensor data with every editing tool,": "Raw-filerna från Hasselblad Lunar (en Sony NEX-7 inuti) framkallas nu från sina sensordata med alla redigeringsverktyg,", + "the highlights were darkened or saturated.": "högdagrarna mörkades eller mättades.", + "The Import Photos review opens bigger and can be resized; its photo grid fills it (issue #337). Shift-click checks": "Granskningen i Importera foton öppnas större och kan ändras i storlek; fotorutnätet fyller den (ärende #337). Shift-klick markerar", + "The interface is available in Spanish (issue #371), German and Russian (Edit ▸ Language), alongside English,": "Gränssnittet finns på spanska (ärende #371), tyska och ryska (Redigera → Språk), förutom engelska,", + "The intro plays once before the first photo; the ending after the last photo when Repeat is off (while repeating": "Introt spelas en gång före det första fotot; avslutningen efter det sista fotot när Upprepa är av (vid upprepning", + "The kept original no longer pushes everything else out of the cache: on a 64 MP raw it filled the cache share": "Det behållna originalet tränger inte längre ut allt annat ur cachen: på en raw-fil på 64 MP fyllde det cacheandelen", + "The keyword set's buttons and the suggestions follow the selection too; the typing boxes get the Cut / Copy / Paste": "Nyckelordsuppsättningens knappar och förslagen följer också markeringen; skrivrutorna får Klipp ut / Kopiera / Klistra in", + "the keyword they are inside: \"Places › Italy\" once, on a line of its own, with Rome, Venice and the others side by": "nyckelordet de ligger inuti: \"Platser › Italien\" en gång, på en egen rad, med Rom, Venedig och de andra sida vid", + "The Keywords panel ends with a Keyword List, as in Lightroom Classic: every keyword with its photo count, those no": "Panelen Nyckelord avslutas med en Nyckelordslista, som i Lightroom Classic: varje nyckelord med sitt antal foton, de som inte", + "the LightCraft window. The xdg-desktop-portal picker used to open as a separate top-level window on Wayland": "LightCraft-fönstret. Väljaren från xdg-desktop-portal öppnades tidigare som ett separat toppnivåfönster i Wayland", + "the list of every keyword is one click away however many keywords the selected photos have. What is folded is": "listan över alla nyckelord är ett klick bort hur många nyckelord de markerade fotona än har. Det som är hopfällt är", + "the loupe (issue #960). Their radii are now set in the original photo's pixels, so a thumbnail, the fitted loupe": "lupen (ärende #960). Deras radier anges nu i originalfotots pixlar, så att en miniatyr, den anpassade lupen", + "The loupe says \"Rendering…\" at the bottom of the photo when what it shows isn't the finished photo yet: the": "Lupen visar \"Renderar…\" längst ned på fotot när det den visar inte är det färdiga fotot ännu: ", + "the My Photos title to bring one back, or choose Reset Sidebar Sections. The arrangement is remembered.": "rubriken Mina foton för att få tillbaka ett, eller välj Återställ sidofältets avsnitt. Arrangemanget sparas.", + "The open library's name shows under My Photos at the top of the left panel and in the window title.": "Namnet på det öppna biblioteket visas under Mina foton överst i den vänstra panelen och i fönstertiteln.", + "the other editor (Edit in Other Editor, now ⌥⌘E), and where PhotoCraft is if you use a portable copy.": "det andra redigeringsprogrammet (Redigera i annat program, nu ⌥⌘E), och var PhotoCraft finns om du använder en portabel kopia.", + "the overlays and the intro and ending screens. Click one to apply it; point at one to see it on the selected photo in": "överläggen och intro- och slutskärmarna. Klicka på en för att använda den; peka på en för att se den på det markerade fotot i", + "the photo, follows zoom and pan, and ⌥⌘O shows or hides it. The same menu sets its opacity and a matte that": "fotot, följer zoomning och panorering, och ⌥⌘O visar eller döljer det. Samma meny ställer in dess opacitet och en matthet som", + "the photo.": "fotot.", + "The place names list towns of 15,000 people or more: in a smaller one, City gets the nearest larger town.": "Ortnamnen omfattar orter med 15 000 invånare eller fler: för en mindre ort anger Ort närmaste större ort.", + "The Presets panel builds only the rows in view (and their thumbnails) instead of every preset on every frame; the": "Panelen Förinställningar bygger bara de rader som syns (och deras miniatyrer) i stället för alla förinställningar i varje bildruta; ", + "the preview beside it without changing anything.": "förhandsgranskningen bredvid utan att ändra något.", + "the raw, so it keeps its look.": "raw-filen, så att den behåller sin look.", + "The rule editor marks each rule that needs fixing right under it and keeps OK disabled until they are fixed. An": "Regelredigeraren markerar varje regel som behöver rättas direkt under den och håller OK inaktiverad tills de är rättade. En", + "The rule editor's field menu is grouped: Rating, Pick Flag, Color Label and Any Searchable Text at the top, then": "Regelredigerarens fältmeny är grupperad: Betyg, Flagga som vald, Färgetikett och All sökbar text överst, sedan", + "The same photos give the same HDR whatever order they are selected in; before, a different order could change a": "Samma foton ger samma HDR oavsett i vilken ordning de markeras; tidigare kunde en annan ordning ändra en", + "The Settings window keeps its top edge and width when you switch tabs, so the tab row no longer jumps around": "Inställningsfönstret behåller sin överkant och bredd när du byter flik, så att flikraden inte längre hoppar runt", + "the shadows: the black level recorded in the file is now subtracted.": "skuggorna: den svartnivå som är registrerad i filen dras nu av.", + "the show runs until you stop it, so the ending doesn't come up). Random order never moves them, ←/→ step across them,": "bildspelet pågår tills du stoppar det, så avslutningen visas inte). Slumpmässig ordning flyttar dem aldrig, ←/→ stegar över dem,", + "The side panels keep a tally an edit cannot have changed: a rating or a slider changes none of the folders,": "Sidopanelerna håller en räkning som en redigering inte kan ha ändrat: ett betyg eller ett reglage ändrar ingen av mapparna,", + "The starting look fitted from a raw's camera JPEG now uses its darkest tones too (issue #1307).": "Startlooken som anpassas från en raw-fils kamera-JPEG använder nu även dess mörkaste toner (ärende #1307).", + "the system places it.": "systemet placerar den.", + "The thumbnail cache is no longer taken for your photos": "Miniatyrcachen tas inte längre för dina foton", + "The thumbnail cache no longer follows a shard folder (`thumbs/ab/`) that is a symlink or junction to somewhere": "Miniatyrcachen följer inte längre en delmapp (`thumbs/ab/`) som är en symbolisk länk eller knutpunkt (junction) till någon", + "The Tint slider works the right way round (issues #188, #321): left adds green, right adds magenta, as its track": "Reglaget Färgton fungerar åt rätt håll (ärenden #188, #321): vänster lägger till grönt, höger lägger till magenta, som dess skena", + "The titles **Keywords** and **Keyword List** in the Keywords panel fold their sections shut and open again, so": "Rubrikerna **Nyckelord** och **Nyckelordslista** i panelen Nyckelord fäller ihop sina avsnitt och öppnar dem igen, så", + "The top bar has an Import button, beside Export, in every library.": "Det övre fältet har en Importera-knapp, bredvid Exportera, i varje bibliotek.", + "The top bar's appearance button cycles Auto, Light, Dark (a monitor, sun or moon), and View ▸": "Det övre fältets utseendeknapp växlar mellan Auto, Ljus och Mörk (en skärm, sol eller måne), och Visa →", + "The window opens at the size you left it": "Fönstret öppnas i den storlek du lämnade det", + "the window. The shortcut they show is the one Import Photos… has now.": "fönstret. Kortkommandot de visar är det som Importera foton… har nu.", + "The Windows app no longer quits at launch with \"Parent device is lost\" when another program's `dxcompiler.dll` is": "Windows-appen avslutas inte längre vid start med \"Parent device is lost\" när ett annat programs `dxcompiler.dll` är", + "The Windows installer asks where to install LightCraft (Program Files by default; upgrades keep the folder you": "Windows-installationsprogrammet frågar var LightCraft ska installeras (Program Files som standard; uppgraderingar behåller mappen du", + "Their files and XMP sidecars move on disk. Edit → Undo moves them back.": "Deras filer och XMP-sidofiler flyttas på disken. Redigera → Ångra flyttar tillbaka dem.", + "their old white balance; merge them again.": "sin gamla vitbalans; sammanfoga dem igen.", + "their own ids, stacks keep only photos that exist (at least two), folders inside themselves move to the top,": "sina egna id:n, staplar behåller bara foton som finns (minst två), mappar inuti sig själva flyttas till toppen,", + "them saves a new set.": "dem sparar en ny uppsättning.", + "there in another case, a link, a name Windows reads another way (`aux.jpg`, a `~`, a `:`, a dot or a space at the": "där med andra versaler/gemener, en länk, ett namn som Windows läser på ett annat sätt (`aux.jpg`, ett `~`, ett `:`, en punkt eller ett blanksteg i", + "there, has it a sidecar): it has just listed the folder, and reads the answers off the listing. On a network share": "där, har den en sidofil): den har just listat mappen och läser svaren ur listningen. På en nätverksresurs", + "They are now kept under a name that is no picture's. The ones already there are taken over, not rendered again:": "De sparas nu under ett namn som inte tillhör någon bild. De som redan finns tas över i stället för att renderas igen:", + "This does not change colour matrices, camera calibration or RAW noise rendering.": "Detta ändrar inte färgmatriser, kamerakalibrering eller brusrendering för RAW.", + "This page setup is not valid": "Sidinställningarna är inte giltiga", + "This row covers more than one disk: drop on a folder inside it": "Den här raden omfattar mer än en disk: släpp på en mapp inuti den", + "Thumbnail cache stays in its folder": "Miniatyrcachen stannar i sin mapp", + "Thumbnails and previews are written to the cache on disk by one background writer instead of a new thread for": "Miniatyrer och förhandsgranskningar skrivs till cachen på disken av en enda bakgrundsskrivare i stället för en ny tråd för", + "Thumbnails of raw files appear sooner": "Miniatyrer av raw-filer visas snabbare", + "TIFFs) are no longer opened as a thumbnail-sized ordinary image. They are recognised as raws LightCraft can't decode": "TIFF-filer) öppnas inte längre som en vanlig bild i miniatyrstorlek. De känns igen som raw-filer som LightCraft inte kan avkoda", + "time is typed, and picking a day replaces one). Typing still works, and \"2026-10-01 10:00\" (a space for the": "tid skrivs, och att välja en dag ersätter en). Det går fortfarande att skriva, och \"2026-10-01 10:00\" (ett blanksteg för", + "to Recently Deleted, so they also left their folder's view (issue #1805). They stay in the library and in their": "till Nyligen raderade, så de försvann också från mappens vy (ärende #1805). De finns kvar i biblioteket och i sina", + "to reset it\"), in every language (issue #1436).": "för att återställa den\"), på alla språk (ärende #1436).", + "to save it as UTF-8. Exporting warns about keywords Capture One won't import, and names any keyword the format can't": "att spara den som UTF-8. Vid export varnas för nyckelord som Capture One inte importerar, och varje nyckelord som formatet inte kan", + "to the menu bar and the app ignored those keys, assuming the menu bar would handle them. Keys outside the menus": "till menyraden och appen ignorerade de tangenterna i tron att menyraden skulle hantera dem. Tangenter utanför menyerna", + "Told when there is no GPU": "Meddelar när det inte finns någon GPU", + "too, but not applied by default: our demosaic already hides most of that colour fringing, and the table on top made": "också, men används inte som standard: vår demosaicing döljer redan det mesta av de färgkanterna, och tabellen ovanpå gjorde", + "Tool Overlay: Always": "Verktygsöverlägg: Alltid", + "Tool Overlay: Auto": "Verktygsöverlägg: Auto", + "Tool Overlay: Never": "Verktygsöverlägg: Aldrig", + "Tool Overlay: Selected": "Verktygsöverlägg: Markerade", + "Tracking": "Spärrning", + "Trackpads: pinch to zoom around the pointer and scroll with two fingers to pan the photo; panning keeps the photo": "Styrplattor: nyp för att zooma runt pekaren och scrolla med två fingrar för att panorera fotot; panorering håller fotot", + "triangles, a highlight under the pointer. A folded section shows how many rows it holds, counts of 0 are fainter,": "trianglar, en markering under pekaren. Ett hopfällt avsnitt visar hur många rader det innehåller, antal 0 är svagare,", + "two dates of a \"between\" can't be picked out of order; Esc closes just the calendar. It picks dates, not times (a": "två datum i ett \"mellan\" kan inte väljas i fel ordning; Esc stänger bara kalendern. Den väljer datum, inte tider (en", + "Type an exact value into any slider (issue #322): click the number next to its name, type (`1.5`, `-20`, `5600`)": "Skriv ett exakt värde i valfritt reglage (ärende #322): klicka på talet bredvid dess namn, skriv (`1.5`, `-20`, `5600`)", + "Typing in **Add keyword** offers the library's matching keywords right under the box. ↓ and Return (or a click)": "När du skriver i **Lägg till nyckelord** föreslås bibliotekets matchande nyckelord direkt under rutan. ↓ och Retur (eller ett klick)", + "under the pointer. It used to be centred, so every tab of a different height moved it.": "under pekaren. Det var tidigare centrerat, så varje flik med en annan höjd flyttade det.", + "Unknown date": "Okänt datum", + "Update Mask Effect": "Uppdatera maskeffekt", + "Update Slideshow Template": "Uppdatera bildspelsmall", + "Upgrading from a Windows installer older than 0.6 (such as 0.5.0) keeps LightCraft in the folder it was installed": "Uppgradering från ett Windows-installationsprogram äldre än 0.6 (till exempel 0.5.0) behåller LightCraft i mappen det installerades", + "Use Defaults": "Använd standardvärden", + "used to open at 1600 × 1000 every time. Double-click the top bar to zoom the window, quit, and it is zoomed when": "öppnades tidigare i 1600 × 1000 varje gång. Dubbelklicka på det övre fältet för att zooma fönstret, avsluta, så är det zoomat när", + "usual and then added to Photos, into a top-level album of that name (made when it's missing). The toast says how": "som vanligt och läggs sedan till i Photos, i ett album på toppnivå med det namnet (skapas om det saknas). Notisen anger hur", + "View Options": "Visningsalternativ", + "View Options…": "Visningsalternativ…", + "View → View Options chooses the lines Info 1 and Info 2 show.": "Visa → Visningsalternativ väljer vilka rader Info 1 och Info 2 visar.", + "VLC and recent phones and TVs play it.": "VLC och nya telefoner och tv-apparater spelar upp den.", + "watermark preview for it, no longer crashes LightCraft; the export is capped at the encoders' 65,535 pixels.": "vattenstämpelförhandsgranskning för den, kraschar inte längre LightCraft; exporten begränsas till kodarnas 65 535 pixlar.", + "way round, \"in the last 0 days\", a colour label that doesn't exist, \"contains\" with nothing to look for, an": "fel håll, \"de senaste 0 dagarna\", en färgetikett som inte finns, \"innehåller\" utan något att söka efter, en", + "when a `cargo` build runs outside `nix develop` (no Vulkan loader); start it from there.": "när ett `cargo`-bygge körs utanför `nix develop` (ingen Vulkan-laddare); starta det därifrån.", + "When a folder holds several file types, the Import Photos review has a toggle per type (`ARW · 120`, `JPG · 120`):": "När en mapp innehåller flera filtyper har granskningen i Importera foton en växlingsknapp per typ (`ARW · 120`, `JPG · 120`):", + "When GPU rendering is on but no graphics processor can be found, LightCraft now says so once at start-up instead": "När GPU-rendering är på men ingen grafikprocessor hittas meddelar LightCraft nu det en gång vid start i stället", + "When the graphics driver resets the GPU while LightCraft is exporting or rendering (issue #1337, seen on Windows": "När grafikdrivrutinen återställer GPU:n medan LightCraft exporterar eller renderar (ärende #1337, sett på Windows", + "when the preview renders in a few milliseconds (it waits at most 40 % of a frame for it; slower renders, such as": "när förhandsgranskningen renderas på några millisekunder (den väntar högst 40 % av en bildruta på den; långsammare renderingar, som", + "Where the camera focused": "Där kameran fokuserade", + "where the pointer landed, and a single click on the thumb leaves the value alone.": "där pekaren hamnade, och ett enkelklick på reglageknappen lämnar värdet orört.", + "which section you are in and can fold it from there.": "vilket avsnitt du är i och kan fälla ihop det därifrån.", + "While it plays, moving the pointer shows a small control bar: previous, play / pause, next, the slide number and": "Medan det spelas visar en rörelse med pekaren ett litet kontrollfält: föregående, spela upp/pausa, nästa, bildnumret och", + "while the 1:1 detail is on its way. It appears once that has lasted half a second, so quick renders never show it.": "medan 1:1-detaljen är på väg. Den visas när det har pågått en halv sekund, så snabba renderingar visar den aldrig.", + "while they are renamed (it can be stopped, and goes on at the next open).": "medan de döps om (det kan stoppas och fortsätter vid nästa öppning).", + "White balance on DNGs (and other raws with a colour matrix) re-develops the photo for the new white through the": "Vitbalans på DNG-filer (och andra raw-filer med en färgmatris) framkallar om fotot för den nya vitpunkten genom", + "White on Black": "Vitt på svart", + "white, empty Point Color slots…) as settings that couldn't be carried over.": "vit, tomma Punktfärg-platser…) som inställningar som inte kunde föras över.", + "Wide": "Bred", + "Wide (16:9 with black bars, the title in the corner, fades through black and a closing card) and Shooting Data (the": "Bred (16:9 med svarta kanter, titeln i hörnet, toningar via svart och ett avslutande kort) och Fotograferingsdata (", + "Width & Height": "Bredd och höjd", + "windows and toasts are gone.": "fönster och notiser är borta.", + "With **HDR output** on, a photo edited in HDR can now be exported as a **16-bit PNG** with the PQ curve in Rec. 2020,": "Med **HDR-utdata** på kan ett foto redigerat i HDR nu exporteras som **16-bitars PNG** med PQ-kurvan i Rec. 2020,", + "With a GPU, a slider drag's preview is drawn in the same frame as the slider moves instead of one frame later,": "Med en GPU ritas förhandsgranskningen vid reglagedragning i samma bildruta som reglaget flyttas i stället för en bildruta senare,", + "With automatic XMP writing on, an edit to a photo whose folder can't be written (a network share that dropped": "Med automatisk XMP-skrivning på kan en redigering av ett foto vars mapp inte går att skriva till (en nätverksresurs som tappade", + "With Dehaze on, panning a photo zoomed to 1:1 or moving a slider while zoomed no longer samples the whole": "Med Ta bort dis på samplar panorering av ett foto zoomat till 1:1, eller flyttning av ett reglage under zoom, inte längre hela", + "With no filter set, the count of the source is taken from the list instead of from a second pass over the library.": "Utan något filter tas antalet för källan från listan i stället för från en andra genomgång av biblioteket.", + "with NVIDIA), LightCraft still stops, because its window can't keep drawing on the lost device, but it now says": "med NVIDIA), avslutas LightCraft fortfarande, eftersom fönstret inte kan fortsätta rita på den förlorade enheten, men nu anges", + "With several photos selected, the Keywords panel says how many photos its keywords belong to. The × on a keyword": "Med flera foton markerade anger panelen Nyckelord hur många foton dess nyckelord hör till. × på ett nyckelord", + "With that, the frame after a keyword is at about 29 ms there. New rules, a change to an album or the keyword list,": "Därmed ligger bildrutan efter ett nyckelord på omkring 29 ms där. Nya regler, en ändring i ett album eller nyckelordslistan,", + "With the brush, click once, then ⇧-click somewhere else: the brush paints a straight line between the two, and": "Med penseln: klicka en gång och ⇧-klicka sedan någon annanstans: penseln målar en rak linje mellan de två, och", + "with the Dock at a side of the screen, or of a window already as wide as the screen. Zoomed by a double-click": "med Dock vid en sida av skärmen, eller för ett fönster som redan är lika brett som skärmen. Zoomat med ett dubbelklick", + "with the logs of the two previous runs beside it, so warnings and crashes of a run started from a desktop menu or the": "med loggarna från de två föregående körningarna bredvid, så att varningar och krascher från en körning startad från en skrivbordsmeny eller", + "with the original and opens it in PhotoCraft. LightCraft finds PhotoCraft where its installer put it (Windows,": "med originalet och öppnar den i PhotoCraft. LightCraft hittar PhotoCraft där installationsprogrammet placerade det (Windows,", + "with those edits went from about 3.7 s to 1.9 s. Photos look the same as before.": "med de redigeringarna gick från cirka 3,7 s till 1,9 s. Fotona ser ut som förut.", + "with Z lenses and with F-mount lenses on the FTZ adapter, follows the in-body stabilisation's shift of the optical": "med Z-objektiv och med F-objektiv på FTZ-adaptern, följer den inbyggda stabiliseringens förskjutning av den optiska", + "without applying it.": "utan att använda den.", + "Write Waiting XMP Sidecars": "Skriv väntande XMP-sidofiler", + "Writing one photo's XMP sidecar (Save Metadata to File, or automatically after an edit) no longer works out who": "När ett fotos XMP-sidofil skrivs (Spara metadata till fil, eller automatiskt efter en redigering) räknas inte längre ut vem", + "XMP presets apply their red / green / blue curves only when they also have the master curve and all three channel": "XMP-förinställningar använder sina röda/gröna/blå kurvor bara när de också har huvudkurvan och alla tre kanal-", + "XMP sidecars catch up after a network share comes back": "XMP-sidofiler kommer ikapp när en nätverksresurs är tillbaka", + "Yes/no fields (Has Edits, Cropped, Has GPS…) read Yes / No instead of true / false. A rule sent as `\"false\"` now": "Ja/nej-fält (Har redigeringar, Beskuren, Har GPS…) visar Ja/Nej i stället för sant/falskt. En regel skickad som `\"false\"` nu", + "yet and import as \"preview only\", with the reason.": "ännu och importeras som \"endast förhandsgranskning\", med orsaken.", + "you come back; un-zoom it and it goes back to the size it had before.": "du kommer tillbaka; avzooma det så återgår det till storleken det hade innan.", + "Your library is empty": "Ditt bibliotek är tomt", + "yours (issues #610, #1066). They were ordinary `.jpg` files in the library's `thumbs` folder, which is usually": "dina (ärenden #610, #1066). De var vanliga `.jpg`-filer i bibliotekets mapp `thumbs`, som oftast är", + "Zone": "Zon", + "Zoom to Focus Point": "Zooma till fokuspunkt", + "zoom, so it goes by the window's size, and when in doubt takes the window for a window of the size it has: it": "zoom, så det utgår från fönstrets storlek, och i tveksamma fall tar det fönstret för ett fönster av den storlek det har: det", + "Zoomed 64 MP raws stay decoded": "Zoomade raw-filer på 64 MP förblir avkodade", + "Zooming in with Before/After side by side decodes the original once: the Before side used to decode its own copy": "Att zooma in med Före/Efter sida vid sida avkodar originalet en gång: Före-sidan avkodade tidigare sin egen kopia", + "⇧-click and the line tapers from the old values to the new ones. The whole line is one undo step.": "⇧-klicka så smalnar linjen av från de gamla värdena till de nya. Hela linjen är ett ångrasteg." } From d6575581ed03215164fc6cee0257986705a8a474 Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Thu, 22 Oct 2026 22:25:39 +0200 Subject: [PATCH 027/331] 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 028/331] 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 029/331] 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 c60e248471b912134217982c877589381cff08cc Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:19:44 -0400 Subject: [PATCH 030/331] LR-PROF-CAMERACOLOR: negative-channel test requires the deep samples each output depth asks for --- crates/pipeline/src/tests.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/pipeline/src/tests.rs b/crates/pipeline/src/tests.rs index c2388c36b7..0596eff719 100644 --- a/crates/pipeline/src/tests.rs +++ b/crates/pipeline/src/tests.rs @@ -840,8 +840,12 @@ fn negative_channels_render_finite_everywhere() { let finite = |s: &DevelopSettings, depth: OutputDepth, what: &str| { let r = render(&src, &info, s, &RenderRequest { depth, ..RenderRequest::fit(48, 48) }); assert!(r.histogram.total > 0, "{what}"); - if let Some(DeepSamples::F32(v)) = r.deep.map(|d| d.samples) { - assert!(v.iter().all(|v| v.is_finite()), "{what} {depth:?}: non-finite output"); + match (depth, r.deep.map(|d| d.samples)) { + (OutputDepth::U8, None) | (OutputDepth::U16, Some(DeepSamples::U16(_))) => {} + (OutputDepth::F32Linear | OutputDepth::F32Hdr, Some(DeepSamples::F32(v))) => { + assert!(v.iter().all(|v| v.is_finite()), "{what} {depth:?}: non-finite output"); + } + _ => panic!("{what} {depth:?}: missing or wrong deep samples"), } }; let mut pushed = DevelopSettings::default(); 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 031/331] 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 48a002e73af31fe837a21358ce3290e36e0fda37 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:52:38 +0200 Subject: [PATCH 032/331] M12: SAM 3 accelerator plumbing: backend choice, CPU fallback and the AI masks setting Part 1 of 5 of #2167. lightcraft-segment gets a BackboneAccel trait (backbone, plus optional necks, DETR encoder and mask decoder, asked only when runs_heads()), WeightReader and Sam3::load_accelerated. Whatever an accelerator returns is checked (length, finite values); an error, a wrong size or a NaN falls back to candle, logged once, with the reason kept for the status. The engine worker places the model (Metal on macOS, the CPU elsewhere, or the CPU when chosen or switched off), reloads it when a GPU switch or the setting changes, and reports where it ran in segment.model.status. Settings > Performance > AI masks gets Run on: Automatic / CPU. #2067's retry is kept: a job that fails on candle's GPU (Metal) runs once more on the CPU, which then serves the session (now a placement with the reason); LIGHTCRAFT_GPU=0 / LIGHTCRAFT_GPU_BACKEND=off keep the model on the CPU on macOS too. #1963's semantic mask comes from the mask decoder as before (on an accelerator: one more row of its mask product). This build has no GPU backbone (GPU_BACKBONE is None), so the GPU path is off: outside macOS candle runs everything on the CPU, as on main. Also on the CPU: the text features of the last 16 prompts are cached per model, and the detector's box relative-position bias is one pass, with the decoder MLPs' bias and ReLU fused (bit-identical outputs). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/engine/src/cmd/masks.rs | 20 +- crates/engine/src/config.rs | 7 +- crates/engine/src/segment/mod.rs | 99 ++- crates/engine/src/segment/worker.rs | 685 ++++++++++++++++---- crates/engine/src/tests_segment.rs | 45 ++ crates/gpu/src/lib.rs | 7 +- crates/segment/Cargo.toml | 2 + crates/segment/examples/sam3_bench.rs | 56 +- crates/segment/src/cpu.rs | 147 +++++ crates/segment/src/detector.rs | 293 ++++++++- crates/segment/src/lib.rs | 633 ++++++++++++++++-- crates/segment/src/nn.rs | 48 +- crates/segment/tests/it/accel.rs | 58 ++ crates/segment/tests/it/main.rs | 2 + crates/segment/tests/it/prompts.rs | 63 ++ crates/ui-egui/locales/cs-formats.json | 3 +- crates/ui-egui/locales/cs.json | 10 +- crates/ui-egui/locales/de-formats.json | 3 +- crates/ui-egui/locales/de.json | 10 +- crates/ui-egui/locales/es-formats.json | 3 +- crates/ui-egui/locales/es.json | 10 +- crates/ui-egui/locales/fi-formats.json | 3 +- crates/ui-egui/locales/fi.json | 10 +- crates/ui-egui/locales/fr-formats.json | 3 +- crates/ui-egui/locales/fr.json | 10 +- crates/ui-egui/locales/id-formats.json | 3 +- crates/ui-egui/locales/id.json | 10 +- crates/ui-egui/locales/it-formats.json | 3 +- crates/ui-egui/locales/it.json | 11 +- crates/ui-egui/locales/ja-formats.json | 3 +- crates/ui-egui/locales/ja.json | 10 +- crates/ui-egui/locales/ka-formats.json | 3 +- crates/ui-egui/locales/ka.json | 10 + crates/ui-egui/locales/pl-formats.json | 3 +- crates/ui-egui/locales/pl.json | 12 +- crates/ui-egui/locales/pt-br-formats.json | 3 +- crates/ui-egui/locales/pt-br.json | 10 +- crates/ui-egui/locales/ru-formats.json | 3 +- crates/ui-egui/locales/ru.json | 10 +- crates/ui-egui/locales/sv-formats.json | 3 +- crates/ui-egui/locales/sv.json | 10 +- crates/ui-egui/locales/uk-formats.json | 3 +- crates/ui-egui/locales/uk.json | 10 +- crates/ui-egui/locales/vi-formats.json | 3 +- crates/ui-egui/locales/vi.json | 10 +- crates/ui-egui/locales/zh-hans-formats.json | 3 +- crates/ui-egui/locales/zh-hans.json | 10 +- crates/ui-egui/locales/zh-hant-formats.json | 3 +- crates/ui-egui/locales/zh-hant.json | 10 +- crates/ui-egui/src/panels/settings.rs | 57 +- crates/ui-egui/src/tests_dialog_fit.rs | 37 ++ 52 files changed, 2219 insertions(+), 265 deletions(-) create mode 100644 crates/segment/src/cpu.rs create mode 100644 crates/segment/tests/it/accel.rs create mode 100644 crates/segment/tests/it/prompts.rs diff --git a/Cargo.lock b/Cargo.lock index 8b3985fc09..8c29f11536 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3485,6 +3485,7 @@ dependencies = [ "lightcraft-fetch", "lightcraft-testkit", "log", + "rayon", "serde", "serde_json", "thiserror 2.0.21", diff --git a/crates/engine/src/cmd/masks.rs b/crates/engine/src/cmd/masks.rs index dc403df9b1..9c7c8bca8f 100644 --- a/crates/engine/src/cmd/masks.rs +++ b/crates/engine/src/cmd/masks.rs @@ -533,7 +533,7 @@ pub fn specs() -> Vec { "AI Mask Model Status", [], None, - "{} — whether this build has AI masks, whether the SAM 3 model is installed (and where), loaded, busy, and the download's progress → {available, installed, dir, loaded, busy, analyzing, sizeBytes, license, licenseUrl, mirrors, download: {running, done, total, file, error, finished}}", + "{} — whether this build has AI masks, whether the SAM 3 model is installed (and where), loaded, busy, where it runs and how long the last photo took, and the download's progress → {available, installed, dir, loaded, busy, analyzing, runOn (auto | cpu: segment.settings), backend: {device (what runs the backbone: a GPU's name, Metal GPU or CPU; null until loaded), runtime (wgpu|candle), heads (CPU|Metal GPU, and which of the parts after the backbone the GPU accelerator runs, e.g. `CPU; the necks on the GPU`), fallback (why the backbone is not on the GPU), encodeMs (last backbone run), analyzeMs (last photo's analysis before the first click)}, sizeBytes, license, licenseUrl, mirrors, download: {running, done, total, file, error, finished}}", super::always, |s, _| { let g = &s.segmenter; @@ -545,6 +545,8 @@ pub fn specs() -> Vec { "loaded": g.loaded(), "busy": g.busy(), "analyzing": g.analyzing(), + "runOn": g.run_on().name(), + "backend": g.backend(), "sizeBytes": crate::segment::MODEL_BYTES, "license": crate::segment::LICENSE_NAME, "licenseUrl": crate::segment::LICENSE_URL, @@ -553,6 +555,22 @@ pub fn specs() -> Vec { })) } ), + cmd!( + query "segment.settings", + "AI Mask Settings", + [], + None, + "{runOn?: auto | cpu} → {runOn} — where SAM 3 runs (Settings ▸ Performance ▸ AI masks): `auto` (the default) the GPU when there is one (Metal on macOS; elsewhere candle on the CPU: this build has no wgpu kernels for SAM 3 yet), `cpu` all of it on the CPU on every platform (for a GPU that can't run it). Local inference only: a remote worker (`LIGHTCRAFT_SAM3_REMOTE`) runs on its Mac's Metal device either way. Kept with the app's settings; a loaded model moves at its next request", + super::always, + |s, p| { + let c = "segment.settings"; + if let Some(v) = p.get("runOn") { + let run_on = v.as_str().and_then(crate::segment::RunOn::parse).ok_or_else(|| bad(c, "`runOn` must be auto or cpu"))?; + s.segmenter.set_run_on(run_on).map_err(ai_err)?; + } + Ok(json!({"runOn": s.segmenter.run_on().name()})) + } + ), cmd!( query "segment.model.download", "Download AI Mask Model", diff --git a/crates/engine/src/config.rs b/crates/engine/src/config.rs index b3ded1fbd7..839836b274 100644 --- a/crates/engine/src/config.rs +++ b/crates/engine/src/config.rs @@ -132,11 +132,14 @@ fn sam3_dir(var: Option, config: Option) -> Option< } impl Session { - /// Look for the SAM 3 model in the shared default folder ([`default_sam3_dir`]), and for the user's - /// download mirrors in `/models/sam3-mirrors.txt`. + /// Look for the SAM 3 model in the shared default folder ([`default_sam3_dir`]), for the user's + /// download mirrors in `/models/sam3-mirrors.txt` and for where it runs in + /// `/models/sam3-settings.json`. pub fn with_default_sam3_model(mut self) -> Self { self.segmenter.dir = default_sam3_dir(); self.segmenter.mirrors_file = config_dir().map(|d| d.join("models").join("sam3-mirrors.txt")); + self.segmenter.settings_file = config_dir().map(|d| d.join("models").join("sam3-settings.json")); + self.segmenter.load_settings(); self } diff --git a/crates/engine/src/segment/mod.rs b/crates/engine/src/segment/mod.rs index b69a6dca27..b4302d77f7 100644 --- a/crates/engine/src/segment/mod.rs +++ b/crates/engine/src/segment/mod.rs @@ -117,12 +117,57 @@ pub struct DownloadStatus { pub finished: bool, } +/// Where SAM 3 runs (Settings ▸ Performance ▸ AI masks; `segment.settings {runOn}`, kept in +/// [`Segmenter::settings_file`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum RunOn { + /// The GPU when there is one: Metal on macOS, elsewhere the image encoder through wgpu unless + /// the GPU is switched off ("Use the GPU for rendering", `LIGHTCRAFT_GPU=0`, …). + #[default] + Auto, + /// The CPU for all of it, on every platform (on macOS candle's CPU device instead of Metal). + Cpu, +} + +impl RunOn { + pub fn parse(name: &str) -> Option { + match name { + "auto" => Some(RunOn::Auto), + "cpu" => Some(RunOn::Cpu), + _ => None, + } + } + + pub fn name(self) -> &'static str { + match self { + RunOn::Auto => "auto", + RunOn::Cpu => "cpu", + } + } +} + +/// Why the model runs on the CPU when [`RunOn::Cpu`] is chosen (`segment.model.status` → +/// `backend.fallback`). +pub const CPU_CHOSEN: &str = "the CPU is chosen in Settings (AI masks)"; + +/// The settings file's contents (`sam3-settings.json`). +#[derive(Default, serde::Serialize, serde::Deserialize)] +#[serde(default, rename_all = "camelCase")] +struct Settings { + /// `auto` or `cpu` (`None` or anything else: `auto`). + run_on: Option, +} + /// The model (on its worker thread), the download, and AI mask requests in flight. pub struct Segmenter { /// Where the `facebook/sam3` files live (set by the app; `None`: no AI masks). pub dir: Option, /// The user's list of download mirrors (one base URL per line), if any. pub mirrors_file: Option, + /// Where [`Segmenter::run_on`] is kept (`/models/sam3-settings.json` in the app; `None`: + /// only for this session). + pub settings_file: Option, + run_on: RunOn, /// Run requests in the background and apply them in [`Session::segment_poll`] (the /// desktop app); otherwise commands wait for their result (CLI, MCP, tests). pub background: bool, @@ -143,6 +188,8 @@ impl Default for Segmenter { Segmenter { dir: None, mirrors_file: None, + settings_file: None, + run_on: RunOn::Auto, background: false, pending: None, messages: Vec::new(), @@ -160,6 +207,33 @@ impl Segmenter { /// Whether this build can compute AI masks at all. pub const AVAILABLE: bool = cfg!(feature = "sam"); + /// Where SAM 3 runs: the user's choice. + pub fn run_on(&self) -> RunOn { + self.run_on + } + + /// Read the choice of where SAM 3 runs from [`Segmenter::settings_file`] (a missing or damaged + /// file is [`RunOn::Auto`]). + pub fn load_settings(&mut self) { + let read = self.settings_file.as_deref().and_then(|f| crate::denoise::read_capped(f, 4096)); + let st: Settings = read.and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + self.run_on = st.run_on.as_deref().and_then(RunOn::parse).unwrap_or_default(); + } + + /// Choose where SAM 3 runs, and keep the choice in [`Segmenter::settings_file`]. A loaded model + /// moves at its next request (it loads again). + pub fn set_run_on(&mut self, run_on: RunOn) -> Result<(), String> { + if let Some(f) = &self.settings_file { + if let Some(parent) = f.parent() { + std::fs::create_dir_all(parent).map_err(|e| format!("could not create {}: {e}", parent.display()))?; + } + let st = Settings { run_on: Some(run_on.name().to_string()) }; + crate::denoise::write_atomic(f, &serde_json::to_vec_pretty(&st).map_err(|e| e.to_string())?)?; + } + self.run_on = run_on; + Ok(()) + } + pub fn remote_endpoint(&self) -> Option { #[cfg(feature = "sam")] return lightcraft_segment::remote::configured(); @@ -192,6 +266,28 @@ impl Segmenter { false } + /// Where the model runs and how long the last photo took (`segment.model.status` → `backend`): + /// `{device, runtime, heads, fallback, encodeMs, analyzeMs}` (see `worker::Backend`; `device` + /// is `null` until the model first loads, and `fallback` then says whether the GPU is switched + /// off), or `null` in a build without AI masks. + pub fn backend(&self) -> serde_json::Value { + #[cfg(feature = "sam")] + { + let mut b = self.worker.backend(); + if b.device.is_none() { + b.fallback = match self.run_on { + RunOn::Cpu => Some(CPU_CHOSEN.into()), + // macOS: Metal, unless the environment switches the GPU off (the preference is wgpu's) + RunOn::Auto if cfg!(target_os = "macos") => lightcraft_gpu::env_off_reason().map(Into::into), + RunOn::Auto => lightcraft_gpu::switched_off(), + }; + } + serde_json::to_value(b).unwrap_or_default() + } + #[cfg(not(feature = "sam"))] + serde_json::Value::Null + } + /// Whether a zoomed-in detail pass is queued or running. pub fn detail_busy(&self) -> bool { #[cfg(feature = "sam")] @@ -431,7 +527,8 @@ impl Session { job } }; - Ok(worker::Job { dir, key: if region.is_some() { 0 } else { key }, render: Some(render), missing, kind, tag, reply }) + let cpu = self.segmenter.run_on == RunOn::Cpu; + Ok(worker::Job { dir, cpu, key: if region.is_some() { 0 } else { key }, render: Some(render), missing, kind, tag, reply }) } /// Send a request and wait for its result (CLI, MCP, tests; or when not in background mode). diff --git a/crates/engine/src/segment/worker.rs b/crates/engine/src/segment/worker.rs index efbb1c21c4..6bae968924 100644 --- a/crates/engine/src/segment/worker.rs +++ b/crates/engine/src/segment/worker.rs @@ -8,24 +8,33 @@ //! counters are decremented by drop guards, so they can't stay stuck. The model is unloaded //! after [`IDLE_UNLOAD`] without requests (it holds several GB). //! -//! Where the model can run on the GPU (Metal on macOS), a job that fails there (a panic or an -//! error from candle, e.g. a kernel the GPU's compiler can't build, issue #1974) frees the -//! model and runs once more on the CPU. When that works, the model stays on the CPU for the rest -//! of the session and the job's outcome says so; when it fails too, the GPU wasn't the cause and -//! the next job uses it again. `LIGHTCRAFT_GPU=0` or `LIGHTCRAFT_GPU_BACKEND=off` keep the model on -//! the CPU from the start. +//! Where the model runs ([`Placement`]): on macOS candle runs all of it on the GPU through Metal. +//! Elsewhere candle runs on the CPU, and the backbone (most of the work) can run on the GPU through an +//! accelerator ([`GPU_BACKBONE`]: none in this build yet, so it runs in candle as before), unless the GPU is switched off (`LIGHTCRAFT_GPU=0`, +//! `LIGHTCRAFT_GPU_BACKEND=off`, or Settings ▸ Performance ▸ Use the GPU for rendering, as for AI +//! Denoise and faces); a GPU that can't be used or fails on a photo leaves the backbone to the CPU. +//! Settings ▸ Performance ▸ AI masks ▸ CPU ([`Job::cpu`]) puts all of it on the CPU, on every +//! platform, and so do `LIGHTCRAFT_GPU=0` and `LIGHTCRAFT_GPU_BACKEND=off` (macOS included, as +//! for AI Denoise and the face models). +//! +//! Where candle runs the model on the GPU (Metal on macOS), a job that fails there (a panic or an +//! error from candle, e.g. a kernel the GPU's compiler can't build, issue #1974) frees the model +//! and runs once more on the CPU. When that works, the model stays on the CPU for the rest of the +//! session and the job's outcome says so; when it fails too, the GPU wasn't the cause and the next +//! job uses it again. (The wgpu backbone elsewhere falls back to candle by itself, part by part.) +//! [`Backend`] tells the session where it ran and how long the last photo took. use std::collections::VecDeque; use std::panic::AssertUnwindSafe; -use std::path::PathBuf; -use std::sync::Arc; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{self, RecvTimeoutError}; +use std::sync::{Arc, Mutex, PoisonError}; use std::time::Duration; use lightcraft_develop::SegMask; use lightcraft_segment::{ - Encoded, Sam3, + BackboneAccel, Device, Encoded, Sam3, WeightReader, remote::{self, Operation, Request, text_logits}, }; @@ -62,6 +71,8 @@ pub enum Kind { pub struct Job { /// The model folder. pub dir: PathBuf, + /// The user chose the CPU for SAM 3 (Settings ▸ Performance ▸ AI masks). + pub cpu: bool, /// Which photo and look the request is about (the encode cache's key). pub key: u64, /// Renders the model input when the cache doesn't hold `key` (always for a detail pass). @@ -87,29 +98,6 @@ pub struct Outcome { pub const GPU_FAILED: &str = "The GPU couldn't run the AI mask model, so it runs on the CPU until LightCraft restarts (slower). Details are in the log."; -/// Where the model is loaded. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Placement { - /// On the GPU when there is one (Metal on macOS); a job that fails there is retried on the CPU. - Gpu, - /// On the CPU: this build has no GPU path, the environment switches the GPU off, or the model - /// failed on it. - Cpu, -} - -impl Placement { - fn initial() -> Self { - if !lightcraft_segment::GPU_BUILD { - return Placement::Cpu; - } - if let Some(why) = lightcraft_gpu::env_off_reason() { - log::info!("SAM 3 runs on the CPU ({why})"); - return Placement::Cpu; - } - Placement::Gpu - } -} - /// Why a job failed. #[derive(Debug)] enum Failure { @@ -156,6 +144,154 @@ pub struct Shared { pub loaded: AtomicBool, /// Loading the model or encoding a photo right now (the slow parts). pub encoding: AtomicBool, + /// Where the model runs and how long the last photo took. + pub backend: Mutex, +} + +/// Where the model runs, and how long the last photo took (`segment.model.status` → `backend`, +/// Settings ▸ Performance ▸ AI masks). +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Backend { + /// What the backbone (the 32-layer ViT, most of the work) runs on: a GPU's name ("NVIDIA + /// GeForce RTX 5070 (Vulkan)"), "Metal GPU" or "CPU". `None` until the model first loads. + pub device: Option, + /// What runs the backbone: "wgpu" (LightCraft's GPU kernels) or "candle". + pub runtime: Option, + /// What runs the rest (the necks and the click and text heads): "CPU" or "Metal GPU", with the parts the GPU + /// accelerator runs ("CPU; the necks on the GPU"). + pub heads: Option, + /// Why the backbone runs on the CPU where it could use the GPU: the GPU is switched off, there + /// is no usable one, or it failed on a photo. + pub fallback: Option, + /// The last photo's backbone run, in milliseconds. + pub encode_ms: Option, + /// The last photo's whole analysis before the first click (backbone and click features), in + /// milliseconds. + pub analyze_ms: Option, +} + +/// Where the model runs on this machine. +#[derive(Clone, Debug, PartialEq)] +enum Placement { + /// All of it in candle on its best device (Metal on macOS). + Best, + /// The backbone on the GPU (wgpu), the rest in candle on the CPU. + GpuBackbone, + /// All of it in candle on the CPU: the CPU is chosen, or the GPU is switched off (why). + Cpu(String), +} + +/// Where the model runs, for candle's best device being the CPU (`best_is_cpu`), the GPU switched +/// off (`switched_off`: why) or not, and the CPU chosen in Settings (`cpu`) or not. The choice wins +/// on every platform; the GPU switches only govern the wgpu backbone (macOS keeps Metal). +fn placement(best_is_cpu: bool, switched_off: Option, cpu: bool) -> Placement { + match (cpu, best_is_cpu, switched_off) { + (true, _, _) => Placement::Cpu(super::CPU_CHOSEN.into()), + (false, false, _) => Placement::Best, + (false, true, None) => Placement::GpuBackbone, + (false, true, Some(why)) => Placement::Cpu(why), + } +} + +/// Where the model is to run now: [`placement`], unless candle's GPU failed on it this session (`failed`: why; +/// the CPU until LightCraft restarts) or the environment switches the GPU off (`LIGHTCRAFT_GPU=0`, +/// `LIGHTCRAFT_GPU_BACKEND=off`), which keeps it off Metal too. +fn wanted(best_is_cpu: bool, cpu: bool, failed: Option<&str>) -> Placement { + if cpu { + return placement(best_is_cpu, None, true); + } + if let Some(why) = failed { + return Placement::Cpu(why.into()); + } + if let Some(why) = lightcraft_gpu::env_off_reason() { + return Placement::Cpu(why.into()); + } + match placement(best_is_cpu, lightcraft_gpu::switched_off(), false) { + // without a GPU backbone in this build, candle's best device runs it all + Placement::GpuBackbone if GPU_BACKBONE.is_none() => Placement::Best, + p => p, + } +} + +/// Whether a model loaded for `loaded` runs somewhere else than `wanted` (it must load again), candle's best device +/// being the CPU or not (`best_is_cpu`). Two reasons for the CPU are the same place, and so is candle's best device +/// when that is the CPU. +fn moves(loaded: &Placement, wanted: &Placement, best_is_cpu: bool) -> bool { + #[derive(PartialEq)] + enum Runs { + Cpu, + Metal, + Wgpu, + } + let runs = |p: &Placement| match p { + Placement::Best if best_is_cpu => Runs::Cpu, + Placement::Best => Runs::Metal, + Placement::GpuBackbone => Runs::Wgpu, + Placement::Cpu(_) => Runs::Cpu, + }; + runs(loaded) != runs(wanted) +} + +/// Builds the GPU backbone from the checkpoint (tests use fakes). +type MakeAccel = fn(&WeightReader) -> Result, String>; + +/// The GPU backbone of this build: none yet (its wgpu kernels come separately), so where candle has no GPU the +/// model runs in candle on the CPU, as before. +const GPU_BACKBONE: Option = None; + +fn no_accelerator(_: &WeightReader) -> Result, String> { + Err("this build has no GPU backbone".into()) +} + +/// Load the model in `dir` as `placement` says, on `best` (candle's best device). +fn load(dir: &Path, best: Device, placement: &Placement, make: MakeAccel) -> lightcraft_segment::Result { + match placement { + Placement::Best => Sam3::load_on(dir, best), + Placement::Cpu(_) => Sam3::load_on(dir, Device::Cpu), + Placement::GpuBackbone => Sam3::load_accelerated(dir, Device::Cpu, make), + } +} + +/// Note where the model `m`, just loaded for `placement`, runs. +fn note_loaded(shared: &Shared, m: &Sam3, placement: &Placement) { + let mut b = shared.backend.lock().unwrap_or_else(PoisonError::into_inner); + *b = Backend { + device: Some(m.backbone_device()), + runtime: Some(if m.accelerated() { "wgpu" } else { "candle" }.into()), + heads: Some(m.heads_device()), + fallback: match placement { + Placement::Cpu(why) => Some(why.clone()), + _ => m.backbone_fallback(), + }, + encode_ms: None, + analyze_ms: None, + }; +} + +/// Note where the backbone ran a photo (it may have moved to the CPU on the way) and, when it +/// succeeded, how long it took (`encode`). +fn note_run(shared: &Shared, m: &Sam3, encode: Option) { + let mut b = shared.backend.lock().unwrap_or_else(PoisonError::into_inner); + b.device = Some(m.backbone_device()); + b.runtime = Some(if m.accelerated() { "wgpu" } else { "candle" }.into()); + b.heads = Some(m.heads_device()); + if let Some(why) = m.backbone_fallback() { + b.fallback = Some(why); + } + if let Some(d) = encode { + b.encode_ms = Some(millis(d)); + } +} + +/// Note where the backbone ran a detail pass (a zoomed-in region): not how long it took, since the last photo's +/// times are its whole analysis and the backbone run in it. +fn note_detail(shared: &Shared, m: &Sam3) { + note_run(shared, m, None); +} + +fn millis(d: Duration) -> u64 { + u64::try_from(d.as_millis()).unwrap_or(u64::MAX) } /// Decrements a counter when dropped (also when unwinding). @@ -218,6 +354,11 @@ impl Worker { !self.dead() && self.shared.loaded.load(Ordering::SeqCst) } + /// Where the model runs (ran, once unloaded) and how long the last photo took. + pub fn backend(&self) -> Backend { + self.shared.backend.lock().unwrap_or_else(PoisonError::into_inner).clone() + } + /// Queue `job`; returns at once. pub fn submit(&mut self, job: Job) -> Result<(), String> { if self.dead() { @@ -237,7 +378,7 @@ impl Worker { // (re)start the thread let (tx, rx) = mpsc::channel(); let shared = self.shared.clone(); - match std::thread::Builder::new().name("sam3".into()).spawn(move || run(&rx, &shared, IDLE_UNLOAD, Placement::initial())) { + match std::thread::Builder::new().name("sam3".into()).spawn(move || run(&rx, &shared, IDLE_UNLOAD, lightcraft_segment::GPU_BUILD)) { Ok(t) => { self.thread = Some(t); self.tx = Some(tx.clone()); @@ -255,6 +396,8 @@ impl Worker { #[derive(Default)] struct State { model: Option<(PathBuf, Sam3)>, + /// Where the model was loaded to run, and whether candle's best device was the CPU then. + placement: Option<(Placement, bool)>, cache: Option<(u64, Encoded)>, remote: Option, } @@ -269,8 +412,12 @@ fn supersedes(later: &Job, job: &Job) -> bool { } } -fn run(rx: &mpsc::Receiver, shared: &Shared, idle: Duration, mut placement: Placement) { +/// The worker's loop. `metal`: candle may run the model on a GPU here (macOS), so a job that fails is retried on +/// the CPU. +fn run(rx: &mpsc::Receiver, shared: &Shared, idle: Duration, metal: bool) { let mut state = State::default(); + // why the model runs on the CPU for the rest of the session: it failed on the GPU and works on the CPU + let mut gpu_failed: Option = None; let mut queue: VecDeque = VecDeque::new(); loop { if queue.is_empty() { @@ -300,24 +447,26 @@ fn run(rx: &mpsc::Receiver, shared: &Shared, idle: Duration, mut placement: let _ = job.reply.send(Outcome { tag: job.tag, result: Ok(None), superseded: true, notice: None }); continue; } - // what a retry on the CPU needs (running the job takes them) - let retry = (placement == Placement::Gpu && remote::configured().is_none()).then(|| (job.kind.clone(), job.render.clone())); - let mut result = attempt(&mut state, shared, &mut job, placement); + // on candle's GPU: what a retry on the CPU needs (running the job takes them) + let on_gpu = metal && gpu_failed.is_none() && !job.cpu && lightcraft_gpu::env_off_reason().is_none() && remote::configured().is_none(); + let retry = on_gpu.then(|| (job.kind.clone(), job.render.clone())); + let mut result = attempt(&mut state, shared, &mut job, gpu_failed.as_deref()); let mut notice = None; - let gpu_failed = match &result { + let failed_why = match &result { Err(Failure::Model(why)) => Some(why.clone()), _ => None, }; - if let (Some(why), Some((kind, render))) = (gpu_failed, retry) { + if let (Some(why), Some((kind, render))) = (failed_why, retry) { // the GPU may be the cause (e.g. a kernel its compiler can't build, issue #1974): free // the model there and try once on the CPU log::warn!("SAM 3 failed on the GPU ({why}); trying the CPU"); state = State::default(); (job.kind, job.render) = (kind, render); - match attempt(&mut state, shared, &mut job, Placement::Cpu) { + let reason = format!("the GPU couldn't run it ({why}); the CPU until LightCraft restarts"); + match attempt(&mut state, shared, &mut job, Some(&reason)) { Ok(r) => { log::warn!("SAM 3 runs on the CPU from now on: it failed on the GPU and works on the CPU"); - placement = Placement::Cpu; + gpu_failed = Some(reason); notice = Some(GPU_FAILED.to_string()); result = Ok(r); } @@ -338,10 +487,10 @@ fn run(rx: &mpsc::Receiver, shared: &Shared, idle: Duration, mut placement: } } -/// Run `job` with the model on `placement`. A panic is a [`Failure::Model`] and drops what the -/// model kept. -fn attempt(state: &mut State, shared: &Shared, job: &mut Job, placement: Placement) -> Result, Failure> { - match std::panic::catch_unwind(AssertUnwindSafe(|| run_job(state, shared, job, placement))) { +/// Run `job`, on the CPU when `failed` says the GPU failed this session. A panic is a [`Failure::Model`] and drops +/// what the model kept. +fn attempt(state: &mut State, shared: &Shared, job: &mut Job, failed: Option<&str>) -> Result, Failure> { + match std::panic::catch_unwind(AssertUnwindSafe(|| run_job(state, shared, job, failed))) { Ok(r) => r, Err(p) => { let why = p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::().cloned()).unwrap_or_default(); @@ -353,19 +502,38 @@ fn attempt(state: &mut State, shared: &Shared, job: &mut Job, placement: Placeme } } -/// The model for `dir`, loading it on `placement` when needed. -fn model<'a>(state: &'a mut State, shared: &Shared, dir: &std::path::Path, placement: Placement) -> Result<&'a mut Sam3, Failure> { - if state.model.as_ref().is_none_or(|(d, _)| d != dir) { +/// The model for `dir`, loading it when needed (and again when the GPU was switched on or off, or +/// the CPU chosen or not: `cpu`; `failed`: the GPU failed this session, see [`wanted`]). +fn model<'a>(state: &'a mut State, shared: &Shared, dir: &Path, cpu: bool, failed: Option<&str>) -> Result<&'a mut Sam3, Failure> { + let now = state.placement.as_ref().map(|(_, best_is_cpu)| wanted(*best_is_cpu, cpu, failed)); + let stale = state.placement.as_ref().zip(now.as_ref()).is_some_and(|((p, best_is_cpu), now)| moves(p, now, *best_is_cpu)); + if let (false, Some((p, _)), Some(now)) = (stale, state.placement.as_mut(), now) { + // the same device for another reason (the choice, a GPU switch): the model stays, the reason it shows changes + if *p != now { + shared.backend.lock().unwrap_or_else(PoisonError::into_inner).fallback = match &now { + Placement::Cpu(why) => Some(why.clone()), + _ => None, + }; + *p = now; + } + } + if stale || state.model.as_ref().is_none_or(|(d, _)| d != dir) { state.model = None; + state.placement = None; state.cache = None; let _busy = Flag::raise(&shared.encoding); let t = web_time::Instant::now(); - let m = match placement { - Placement::Gpu => Sam3::load(dir)?, - Placement::Cpu => Sam3::load_cpu(dir)?, - }; - log::info!("SAM 3 loaded in {:?} ({})", t.elapsed(), if m.device().is_cpu() { "CPU" } else { "GPU" }); + // with the CPU chosen (or forced) candle's best device isn't asked for (on macOS that sets up Metal): + // it counts as Metal on macOS and the CPU elsewhere when the choice changes back + let skip = cpu || failed.is_some() || lightcraft_gpu::env_off_reason().is_some(); + let best = if skip { Device::Cpu } else { lightcraft_segment::best_device() }; + let best_is_cpu = if skip { !cfg!(target_os = "macos") } else { best.is_cpu() }; + let placement = wanted(best_is_cpu, cpu, failed); + let m = load(dir, best, &placement, GPU_BACKBONE.unwrap_or(no_accelerator))?; + log::info!("SAM 3 loaded in {:?}: the backbone on the {}, the rest on the {}", t.elapsed(), m.backbone_device(), m.heads_device()); + note_loaded(shared, &m, &placement); state.model = Some((dir.to_path_buf(), m)); + state.placement = Some((placement, best_is_cpu)); shared.loaded.store(true, Ordering::SeqCst); } state.model.as_mut().map(|(_, m)| m).ok_or_else(|| "the model did not load".into()) @@ -390,17 +558,33 @@ fn render(job: &mut Job) -> Result { } /// The model and the encoded photo `job.key` (rendering and encoding it when needed). -fn encoded<'a>(state: &'a mut State, shared: &Shared, job: &mut Job, placement: Placement) -> Result<(&'a mut Sam3, &'a mut Encoded), Failure> { - model(state, shared, &job.dir, placement)?; +fn encoded<'a>(state: &'a mut State, shared: &Shared, job: &mut Job, failed: Option<&str>) -> Result<(&'a mut Sam3, &'a mut Encoded), Failure> { + model(state, shared, &job.dir, job.cpu, failed)?; if state.cache.as_ref().is_none_or(|(k, _)| *k != job.key) { state.cache = None; let input = render(job)?; let _busy = Flag::raise(&shared.encoding); let m = state.model.as_mut().map(|(_, m)| m).ok_or("the model did not load")?; let t = web_time::Instant::now(); - let mut enc = m.encode(&input.rgb, input.w, input.h)?; + let enc = m.encode(&input.rgb, input.w, input.h); + let encode = t.elapsed(); + note_run(shared, m, None); + let mut enc = enc?; m.prepare_clicks(&mut enc)?; - log::info!("SAM 3 encoded {}×{} in {:?}", input.w, input.h, t.elapsed()); + let analyze = t.elapsed(); + // both times together, once the whole analysis worked: never one photo's encoder with another's total + { + let mut b = shared.backend.lock().unwrap_or_else(PoisonError::into_inner); + (b.encode_ms, b.analyze_ms) = (Some(millis(encode)), Some(millis(analyze))); + } + log::info!( + "SAM 3 analyzed {}×{} in {analyze:?}: backbone {encode:?} on the {}, click features {:?} on the {}", + input.w, + input.h, + m.backbone_device(), + analyze.saturating_sub(encode), + m.heads_device() + ); state.cache = Some((job.key, enc)); } let State { model, cache, .. } = state; @@ -457,7 +641,7 @@ fn remote_job(state: &mut State, shared: &Shared, job: &mut Job, endpoint: &str) })) } -fn run_job(state: &mut State, shared: &Shared, job: &mut Job, placement: Placement) -> Result, Failure> { +fn run_job(state: &mut State, shared: &Shared, job: &mut Job, failed: Option<&str>) -> Result, Failure> { if let Some(endpoint) = remote::configured() { let result = remote_job(state, shared, job, &endpoint); if result.is_err() { @@ -468,33 +652,38 @@ fn run_job(state: &mut State, shared: &Shared, job: &mut Job, placement: Placeme let side = lightcraft_segment::MASK_SIDE; match std::mem::replace(&mut job.kind, Kind::Prepare) { Kind::Prepare => { - encoded(state, shared, job, placement)?; + encoded(state, shared, job, failed)?; Ok(None) } Kind::Clicks(clicks) => { - let (m, enc) = encoded(state, shared, job, placement)?; + let (m, enc) = encoded(state, shared, job, failed)?; let p = m.segment_clicks(enc, &clicks)?; Ok(Some(SegMask::from_logits(side, &p.logits))) } Kind::Text(text) => { - let (m, enc) = encoded(state, shared, job, placement)?; - Ok(text_logits(m, enc, &text)?.map(|l| SegMask::from_logits(side, &l))) + let (m, enc) = encoded(state, shared, job, failed)?; + let logits = text_logits(m, enc, &text)?; + // the text heads may have moved to the CPU on the way (a failure on the GPU) + shared.backend.lock().unwrap_or_else(PoisonError::into_inner).heads = Some(m.heads_device()); + Ok(logits.map(|l| SegMask::from_logits(side, &l))) } #[cfg(test)] #[allow(clippy::panic)] Kind::Panic => panic!("a test panic"), #[cfg(test)] #[allow(clippy::panic)] - Kind::FailOnGpu { panic } => match placement { - Placement::Gpu if panic => panic!("a test panic on the GPU"), - Placement::Gpu => Err(Failure::Model("a test error on the GPU".into())), - Placement::Cpu => Ok(None), + Kind::FailOnGpu { panic } => match failed.is_some() || job.cpu { + false if panic => panic!("a test panic on the GPU"), + false => Err(Failure::Model("a test error on the GPU".into())), + true => Ok(None), }, Kind::Detail { prompt, region } => { let input = render(job)?; - let m = model(state, shared, &job.dir, placement)?; + let m = model(state, shared, &job.dir, job.cpu, failed)?; let t = web_time::Instant::now(); - let mut enc = m.encode(&input.rgb, input.w, input.h)?; + let enc = m.encode(&input.rgb, input.w, input.h); + note_detail(shared, m); + let mut enc = enc?; let (rw, rh) = (region[2] - region[0], region[3] - region[1]); if !(rw > 0.0 && rh > 0.0) { return Ok(None); @@ -527,7 +716,7 @@ mod tests { fn job(tag: Tag, reply: &mpsc::Sender) -> Job { // an empty folder: loading fails with an error (no model files) let dir = std::env::temp_dir().join(format!("lc-sam3-worker-none-{}", std::process::id())); - Job { dir, key: 1, render: None, missing: None, kind: Kind::Prepare, tag, reply: reply.clone() } + Job { dir, cpu: false, key: 1, render: None, missing: None, kind: Kind::Prepare, tag, reply: reply.clone() } } #[test] @@ -560,7 +749,7 @@ mod tests { jtx.send(job(Tag::Wait, &tx)).unwrap(); shared.pending.store(2, Ordering::SeqCst); drop(jtx); - run(&jrx, &shared, Duration::from_secs(60), Placement::Cpu); + run(&jrx, &shared, Duration::from_secs(60), false); let first = rx.recv().unwrap(); assert!(first.result.unwrap_err().contains("failed unexpectedly")); let second = rx.recv().unwrap(); @@ -569,72 +758,6 @@ mod tests { assert!(!shared.encoding.load(Ordering::SeqCst)); } - /// Run `kinds` in turn on a worker that starts on `placement`; their outcomes. - fn run_kinds(placement: Placement, kinds: Vec) -> Vec { - let (tx, rx) = mpsc::channel(); - let (jtx, jrx) = mpsc::channel(); - let shared = Shared::default(); - shared.pending.store(kinds.len(), Ordering::SeqCst); - for kind in kinds { - let mut j = job(Tag::Wait, &tx); - j.kind = kind; - jtx.send(j).unwrap(); - } - drop(jtx); - run(&jrx, &shared, Duration::from_secs(60), placement); - assert_eq!(shared.pending.load(Ordering::SeqCst), 0, "counters reset"); - assert!(!shared.encoding.load(Ordering::SeqCst)); - rx.try_iter().collect() - } - - #[test] - fn a_job_that_panics_on_the_gpu_runs_on_the_cpu_and_so_do_the_next_ones() { - // issue #1974: candle panics compiling a Metal kernel the GPU's compiler can't build - let out = run_kinds(Placement::Gpu, vec![Kind::FailOnGpu { panic: true }, Kind::FailOnGpu { panic: true }]); - assert_eq!(out.len(), 2); - assert!(matches!(out[0].result, Ok(None)), "retried on the CPU: {:?}", out[0].result.as_ref().err()); - assert_eq!(out[0].notice.as_deref(), Some(GPU_FAILED)); - assert!(matches!(out[1].result, Ok(None)), "the next job starts on the CPU"); - assert_eq!(out[1].notice, None, "said once"); - } - - #[test] - fn a_model_error_on_the_gpu_is_retried_on_the_cpu_too() { - let out = run_kinds(Placement::Gpu, vec![Kind::FailOnGpu { panic: false }]); - assert!(matches!(out[0].result, Ok(None))); - assert_eq!(out[0].notice.as_deref(), Some(GPU_FAILED)); - } - - #[test] - fn a_job_that_fails_on_the_cpu_too_keeps_the_gpu() { - let out = run_kinds(Placement::Gpu, vec![Kind::Panic, Kind::FailOnGpu { panic: true }]); - assert!(out[0].result.as_ref().unwrap_err().contains("failed unexpectedly")); - assert_eq!(out[0].notice, None); - // not the GPU's fault: the next job tries the GPU first again - assert!(matches!(out[1].result, Ok(None))); - assert_eq!(out[1].notice.as_deref(), Some(GPU_FAILED)); - } - - #[test] - fn a_worker_on_the_cpu_never_tries_the_gpu() { - // no GPU in this build, or LIGHTCRAFT_GPU=0 / LIGHTCRAFT_GPU_BACKEND=off - let out = run_kinds(Placement::Cpu, vec![Kind::FailOnGpu { panic: true }]); - assert!(matches!(out[0].result, Ok(None))); - assert_eq!(out[0].notice, None); - if !lightcraft_segment::GPU_BUILD { - assert_eq!(Placement::initial(), Placement::Cpu); - } - } - - #[test] - fn missing_model_files_are_not_retried_on_the_cpu() { - let out = run_kinds(Placement::Gpu, vec![Kind::Prepare]); - assert!(out[0].result.as_ref().unwrap_err().contains("not found")); - assert_eq!(out[0].notice, None); - let missing = lightcraft_segment::Error::Missing(PathBuf::from("models")); - assert!(matches!(Failure::from(missing), Failure::Other(_))); - } - #[test] fn a_newer_request_for_the_same_selection_supersedes_a_queued_one() { let (tx, rx) = mpsc::channel(); @@ -652,10 +775,298 @@ mod tests { drop(jtx); let shared = Shared::default(); shared.pending.store(3, Ordering::SeqCst); - run(&jrx, &shared, Duration::from_secs(60), Placement::Cpu); + run(&jrx, &shared, Duration::from_secs(60), false); let out: Vec = rx.try_iter().collect(); assert_eq!(out.len(), 3); assert!(out[0].superseded && out[1].superseded && !out[2].superseded); assert_eq!(shared.pending.load(Ordering::SeqCst), 0); } + + /// A model folder whose checkpoint holds no tensors: it loads with an accelerator, never in candle. + #[allow(clippy::unwrap_used)] + fn empty_model(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-sam3-worker-{name}-{}", 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(lightcraft_segment::WEIGHTS_FILE), st).unwrap(); + std::fs::write(dir.join("vocab.json"), "{}").unwrap(); + std::fs::write(dir.join("merges.txt"), "").unwrap(); + dir + } + + /// A GPU backbone that answers with zeros, or fails on every photo. + struct FakeGpu(bool); + + impl BackboneAccel for FakeGpu { + fn forward(&self, _: &[f32]) -> Result, String> { + if self.0 { Err("device lost".into()) } else { Ok(vec![0.0; 1024 * 72 * 72]) } + } + fn device(&self) -> String { + "Fake GPU (Vulkan)".into() + } + } + + fn fake_gpu(_: &WeightReader) -> Result, String> { + Ok(Box::new(FakeGpu(false))) + } + + fn failing_gpu(_: &WeightReader) -> Result, String> { + Ok(Box::new(FakeGpu(true))) + } + + fn no_gpu(_: &WeightReader) -> Result, String> { + Err("no GPU adapter".into()) + } + + #[allow(clippy::panic)] + fn never(_: &WeightReader) -> Result, String> { + panic!("the GPU backbone was built") + } + + #[allow(clippy::unwrap_used)] + fn backend(shared: &Shared) -> Backend { + shared.backend.lock().unwrap().clone() + } + + #[test] + fn the_backbone_goes_to_the_gpu_only_where_candle_has_none_and_the_gpu_is_on() { + // macOS: candle runs everything on Metal, as before (the GPU switches are wgpu's) + assert_eq!(placement(false, None, false), Placement::Best); + assert_eq!(placement(false, Some("disabled by LIGHTCRAFT_GPU=0".into()), false), Placement::Best); + // elsewhere: the backbone on the GPU unless it is switched off + assert_eq!(placement(true, None, false), Placement::GpuBackbone); + let off = "disabled by the GPU rendering preference (app.gpu)"; + assert_eq!(placement(true, Some(off.into()), false), Placement::Cpu(off.into())); + } + + #[test] + fn the_cpu_chosen_in_settings_wins_on_every_platform() { + let chosen = Placement::Cpu(super::super::CPU_CHOSEN.into()); + // macOS (Metal) and elsewhere, the GPU on or off + for best_is_cpu in [false, true] { + for off in [None, Some("disabled by LIGHTCRAFT_GPU=0".to_string())] { + assert_eq!(placement(best_is_cpu, off.clone(), true), chosen, "{best_is_cpu} {off:?}"); + } + } + assert_eq!(super::super::CPU_CHOSEN, "the CPU is chosen in Settings (AI masks)"); + } + + #[test] + fn switching_the_gpu_or_the_choice_reloads_only_a_model_it_moves() { + let cpu = |why: &str| Placement::Cpu(why.into()); + let chosen = || placement(true, None, true); + // the GPU switch: Metal stays; the wgpu backbone goes to the CPU and back + assert!(!moves(&Placement::Best, &placement(false, Some("off".into()), false), false)); + assert!(moves(&Placement::GpuBackbone, &placement(true, Some("off".into()), false), true)); + assert!(moves(&cpu("off"), &placement(true, None, false), true)); + // without a GPU backbone candle's best device is the CPU: the GPU switch moves nothing + assert!(!moves(&Placement::Best, &cpu("off"), true)); + assert!(!moves(&cpu("off"), &Placement::Best, true)); + // the choice: Metal (macOS) or the GPU backbone to the CPU and back + assert!(moves(&Placement::Best, &placement(false, None, true), false)); + assert!(moves(&placement(false, None, true), &placement(false, None, false), false)); + assert!(moves(&Placement::GpuBackbone, &chosen(), true)); + // the CPU for one reason or the other: it stays loaded + assert!(!moves(&cpu("disabled by LIGHTCRAFT_GPU=0"), &chosen(), true)); + assert!(!moves(&chosen(), &cpu("disabled by LIGHTCRAFT_GPU=0"), false)); + assert!(!moves(&Placement::GpuBackbone, &placement(true, None, false), true)); + } + + #[test] + fn with_the_cpu_chosen_the_gpu_backbone_is_never_built() { + let dir = empty_model("chosen"); + // candle loads on the CPU (and fails: the checkpoint is empty), without touching the GPU + assert!(load(&dir, Device::Cpu, &placement(true, None, true), never).is_err()); + assert!(load(&dir, Device::Cpu, &placement(false, None, true), never).is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn the_gpu_backbone_loads_and_reports_where_it_runs() { + let dir = empty_model("gpu"); + let m = load(&dir, Device::Cpu, &Placement::GpuBackbone, fake_gpu).unwrap(); + let shared = Shared::default(); + note_loaded(&shared, &m, &Placement::GpuBackbone); + let b = backend(&shared); + assert_eq!( + (b.device.as_deref(), b.runtime.as_deref(), b.heads.as_deref(), b.fallback.as_deref()), + (Some("Fake GPU (Vulkan)"), Some("wgpu"), Some("CPU"), None) + ); + let enc = m.encode(&[0; 8 * 8 * 3], 8, 8); + note_run(&shared, &m, enc.is_ok().then_some(Duration::from_millis(812))); + assert_eq!(backend(&shared).encode_ms, Some(812)); + let json = serde_json::to_value(backend(&shared)).unwrap(); + assert_eq!(json["device"], "Fake GPU (Vulkan)"); + assert_eq!(json["encodeMs"], 812); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn with_the_gpu_switched_off_the_gpu_backbone_is_never_built() { + let dir = empty_model("off"); + let off = Placement::Cpu("disabled by LIGHTCRAFT_GPU_BACKEND=off".into()); + // candle loads (and fails: the checkpoint is empty), without touching the GPU + assert!(load(&dir, Device::Cpu, &off, never).is_err()); + assert!(load(&dir, Device::Cpu, &Placement::Best, never).is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_gpu_that_cannot_be_used_leaves_the_backbone_to_the_cpu() { + let dir = empty_model("nogpu"); + // without an adapter candle loads the backbone (failing here only for the empty checkpoint) + let e = load(&dir, Device::Cpu, &Placement::GpuBackbone, no_gpu).err().unwrap(); + assert!(!e.to_string().contains("no GPU adapter"), "{e}"); + // a GPU that fails on a photo: the CPU takes over, and the status says why + let m = load(&dir, Device::Cpu, &Placement::GpuBackbone, failing_gpu).unwrap(); + let shared = Shared::default(); + note_loaded(&shared, &m, &Placement::GpuBackbone); + assert_eq!(backend(&shared).runtime.as_deref(), Some("wgpu")); + let enc = m.encode(&[0; 8 * 8 * 3], 8, 8); + note_run(&shared, &m, enc.is_ok().then_some(Duration::from_millis(1))); + let b = backend(&shared); + assert_eq!((b.device.as_deref(), b.runtime.as_deref()), (Some("CPU"), Some("candle"))); + assert!(b.fallback.as_deref().is_some_and(|f| f.contains("device lost")), "{b:?}"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn the_environment_switches_and_a_failed_gpu_keep_the_model_on_the_cpu_also_on_macos() { + // candle's GPU failed this session: the CPU, with the reason, wherever candle has a GPU or not + for best_is_cpu in [false, true] { + assert_eq!(wanted(best_is_cpu, false, Some("the GPU couldn't run it")), Placement::Cpu("the GPU couldn't run it".into())); + } + // the CPU chosen in Settings still says so + assert_eq!(wanted(false, true, Some("x")), Placement::Cpu(super::super::CPU_CHOSEN.into())); + // otherwise as `placement`, with the environment switches deciding for Metal too + let want = match lightcraft_gpu::env_off_reason() { + Some(why) => Placement::Cpu(why.into()), + None => Placement::Best, + }; + assert_eq!(wanted(false, false, None), want); + } + + /// Run `kinds` in turn on a worker where candle has a GPU (`metal`) or not, the CPU chosen or not; their outcomes. + fn run_kinds(metal: bool, cpu: bool, kinds: Vec) -> Vec { + let (tx, rx) = mpsc::channel(); + let (jtx, jrx) = mpsc::channel(); + let shared = Shared::default(); + shared.pending.store(kinds.len(), Ordering::SeqCst); + for kind in kinds { + let mut j = job(Tag::Wait, &tx); + j.kind = kind; + j.cpu = cpu; + jtx.send(j).unwrap(); + } + drop(jtx); + run(&jrx, &shared, Duration::from_secs(60), metal); + assert_eq!(shared.pending.load(Ordering::SeqCst), 0, "counters reset"); + assert!(!shared.encoding.load(Ordering::SeqCst)); + rx.try_iter().collect() + } + + /// The tests of the CPU fallback assume the GPU isn't switched off in the environment (it never is tried then). + fn gpu_allowed() -> bool { + let ok = lightcraft_gpu::env_off_reason().is_none(); + if !ok { + lightcraft_testkit::skip!(Gpu, "the GPU is switched off in the environment"); + } + ok + } + + #[test] + fn a_job_that_panics_on_the_gpu_runs_on_the_cpu_and_so_do_the_next_ones() { + if !gpu_allowed() { + return; + } + // issue #1974: candle panics compiling a Metal kernel the GPU's compiler can't build + let out = run_kinds(true, false, vec![Kind::FailOnGpu { panic: true }, Kind::FailOnGpu { panic: true }]); + assert_eq!(out.len(), 2); + assert!(matches!(out[0].result, Ok(None)), "retried on the CPU: {:?}", out[0].result.as_ref().err()); + assert_eq!(out[0].notice.as_deref(), Some(GPU_FAILED)); + assert!(matches!(out[1].result, Ok(None)), "the next job starts on the CPU"); + assert_eq!(out[1].notice, None, "said once"); + } + + #[test] + fn a_model_error_on_the_gpu_is_retried_on_the_cpu_too() { + if !gpu_allowed() { + return; + } + let out = run_kinds(true, false, vec![Kind::FailOnGpu { panic: false }]); + assert!(matches!(out[0].result, Ok(None))); + assert_eq!(out[0].notice.as_deref(), Some(GPU_FAILED)); + } + + #[test] + fn a_job_that_fails_on_the_cpu_too_keeps_the_gpu() { + if !gpu_allowed() { + return; + } + let out = run_kinds(true, false, vec![Kind::Panic, Kind::FailOnGpu { panic: true }]); + assert!(out[0].result.as_ref().unwrap_err().contains("failed unexpectedly"), "reported as before"); + assert_eq!(out[0].notice, None); + // the next job still starts on the GPU, fails there and works on the CPU + assert!(matches!(out[1].result, Ok(None))); + assert_eq!(out[1].notice.as_deref(), Some(GPU_FAILED)); + } + + #[test] + fn missing_model_files_are_not_retried_on_the_cpu() { + let out = run_kinds(true, false, vec![Kind::Prepare]); + assert!(out[0].result.as_ref().unwrap_err().contains("not found")); + assert_eq!(out[0].notice, None); + } + + #[test] + fn a_worker_on_the_cpu_never_tries_the_gpu() { + // the CPU chosen in Settings, and a build where candle has no GPU + for (metal, cpu) in [(true, true), (false, true)] { + let out = run_kinds(metal, cpu, vec![Kind::FailOnGpu { panic: true }]); + assert!(matches!(out[0].result, Ok(None))); + assert_eq!(out[0].notice, None); + } + // no GPU path (not macOS): a failure is reported, not retried + let out = run_kinds(false, false, vec![Kind::FailOnGpu { panic: false }]); + assert!(out[0].result.is_err()); + assert_eq!(out[0].notice, None); + } + + #[test] + fn a_cpu_model_kept_for_another_reason_shows_that_reason() { + let dir = empty_model("reason"); + let shared = Shared::default(); + let mut state = State::default(); + let chosen = Placement::Cpu(super::super::CPU_CHOSEN.into()); + // loaded with the CPU chosen (put there by hand: the empty checkpoint doesn't load) + state.placement = Some((chosen.clone(), true)); + shared.backend.lock().unwrap().fallback = Some(super::super::CPU_CHOSEN.into()); + // the choice goes back to Automatic while the CPU stays for another reason: the new reason shows (the reload + // that follows here is only because no model was in memory) + let why = "the GPU couldn't run it"; + let _ = model(&mut state, &shared, &dir, false, Some(why)); + assert_eq!(backend(&shared).fallback.as_deref(), Some(why)); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_detail_pass_leaves_the_last_photos_times_alone() { + let dir = empty_model("detail"); + let m = load(&dir, Device::Cpu, &Placement::GpuBackbone, failing_gpu).unwrap(); + let shared = Shared::default(); + note_loaded(&shared, &m, &Placement::GpuBackbone); + { + let mut b = shared.backend.lock().unwrap(); + (b.encode_ms, b.analyze_ms) = (Some(812), Some(900)); + } + // the zoomed-in region: the GPU fails on it, and the status says where the backbone runs now + let _ = m.encode(&[0; 8 * 8 * 3], 8, 8); + note_detail(&shared, &m); + let b = backend(&shared); + assert_eq!((b.device.as_deref(), b.runtime.as_deref()), (Some("CPU"), Some("candle"))); + assert!(b.fallback.as_deref().is_some_and(|f| f.contains("device lost")), "{b:?}"); + assert_eq!((b.encode_ms, b.analyze_ms), (Some(812), Some(900)), "the last photo's times"); + std::fs::remove_dir_all(dir).unwrap(); + } } diff --git a/crates/engine/src/tests_segment.rs b/crates/engine/src/tests_segment.rs index f4b9f4f484..f317ef8fd4 100644 --- a/crates/engine/src/tests_segment.rs +++ b/crates/engine/src/tests_segment.rs @@ -50,6 +50,17 @@ fn status_and_model_commands_without_the_model() { assert_eq!(st["installed"], false); assert_eq!(st["download"]["running"], false); assert!(st["license"].as_str().unwrap().contains("SAM License")); + // where it runs: nowhere yet (no model loaded), and nothing timed + if Segmenter::AVAILABLE { + let b = &st["backend"]; + assert!(b["device"].is_null() && b["encodeMs"].is_null() && b["analyzeMs"].is_null(), "{b}"); + // the GPU switches show before the model loads (macOS: Metal, which only the environment switches govern) + let off = if cfg!(target_os = "macos") { lightcraft_gpu::env_off_reason().map(str::to_string) } else { lightcraft_gpu::switched_off() }; + assert_eq!(b["fallback"].as_str(), off.as_deref(), "{b}"); + } else { + assert!(st["backend"].is_null()); + } + assert_eq!(st["runOn"], "auto"); // downloading needs the user's consent, and names the size and the licence let e = s.execute("segment.model.download", &json!({})).unwrap_err().to_string(); assert!(e.contains("acknowledged") && e.contains("SAM License") && e.contains("GB"), "{e}"); @@ -305,3 +316,37 @@ fn a_missing_model_is_model_missing_by_kind() { } } } + +/// Where SAM 3 runs is the user's choice (`segment.settings`), shown by `segment.model.status`, kept in the settings +/// file and read back by the next session; a bad value is refused and changes nothing. +#[test] +fn the_choice_of_where_ai_masks_run_is_kept() { + let dir = tmp("runon"); + let file = dir.join("models").join("sam3-settings.json"); + let mut s = Session::with_demo(); + s.segmenter.settings_file = Some(file.clone()); + assert_eq!(s.execute("segment.settings", &json!({})).unwrap()["runOn"], "auto"); + assert_eq!(s.execute("segment.settings", &json!({"runOn": "cpu"})).unwrap()["runOn"], "cpu"); + let st = s.execute("segment.model.status", &json!({})).unwrap(); + assert_eq!(st["runOn"], "cpu"); + if Segmenter::AVAILABLE { + assert_eq!(st["backend"]["fallback"], crate::segment::CPU_CHOSEN, "{st}"); + } + let e = s.execute("segment.settings", &json!({"runOn": "gpu"})).unwrap_err().to_string(); + assert!(e.contains("auto or cpu"), "{e}"); + assert_eq!(s.segmenter.run_on(), crate::segment::RunOn::Cpu); + let saved: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + assert_eq!(saved["runOn"], "cpu"); + // the next session reads it; a damaged file is Automatic + let mut again = Session::with_demo(); + again.segmenter.settings_file = Some(file.clone()); + again.segmenter.load_settings(); + assert_eq!(again.segmenter.run_on(), crate::segment::RunOn::Cpu); + std::fs::write(&file, b"{not json").unwrap(); + again.segmenter.load_settings(); + assert_eq!(again.segmenter.run_on(), crate::segment::RunOn::Auto); + // without a settings file the choice holds for the session + let mut memory = Session::with_demo(); + assert_eq!(memory.execute("segment.settings", &json!({"runOn": "cpu"})).unwrap()["runOn"], "cpu"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 7efae6a576..ec644df6e7 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -237,10 +237,11 @@ pub fn wait_idle(timeout: std::time::Duration) -> bool { } } -/// Why GPU compute that has a device of its own (denoise, faces) is switched off by the user's settings, or `None`: the -/// environment switches and the rendering preference, but not a render-device failure (the devices are separate). +/// Why GPU compute that has a device of its own (denoise, faces, SAM 3) is switched off by the user's settings, or +/// `None`: the environment switches and the rendering preference, but not a render-device failure (the devices are +/// separate). #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn switched_off() -> Option { +pub fn switched_off() -> Option { if let Some(why) = env_off_reason() { return Some(why.into()); } diff --git a/crates/segment/Cargo.toml b/crates/segment/Cargo.toml index b4614a81d8..77f6353524 100644 --- a/crates/segment/Cargo.toml +++ b/crates/segment/Cargo.toml @@ -19,6 +19,8 @@ log = { workspace = true } candle-core = { workspace = true } candle-nn = { workspace = true } lightcraft-fetch = { workspace = true } +# the CPU kernels share candle's thread pool +rayon = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] candle-core = { workspace = true, features = ["metal"] } diff --git a/crates/segment/examples/sam3_bench.rs b/crates/segment/examples/sam3_bench.rs index 982f482e96..a00ae556dd 100644 --- a/crates/segment/examples/sam3_bench.rs +++ b/crates/segment/examples/sam3_bench.rs @@ -1,25 +1,57 @@ //! Times SAM 3 on this machine (a synthetic gradient image; the first run includes compiling -//! the GPU kernels): `cargo run -p lightcraft-segment --release --example sam3_bench -- `. +//! the GPU kernels and loading the heads): `cargo run -p lightcraft-segment --release --example +//! sam3_bench -- `. Each run times the backbone, the click features (tracker neck), +//! a first and a further click, and a first and a second description of the same image (the +//! first one computes the detector's features). + +use std::time::{Duration, Instant}; + +fn ms(d: Duration) -> String { + format!("{:.0} ms", d.as_secs_f64() * 1e3) +} fn main() -> Result<(), Box> { let mut args = std::env::args().skip(1); - let dir = std::path::PathBuf::from(args.next().ok_or("usage: sam3_bench ")?); - let t = std::time::Instant::now(); + let dir = std::path::PathBuf::from(args.next().ok_or("usage: sam3_bench [runs]")?); + let runs: usize = args.next().map(|s| s.parse()).transpose()?.unwrap_or(3); + let t = Instant::now(); let mut model = lightcraft_segment::Sam3::load(&dir)?; - eprintln!("load: {:?} on {:?}", t.elapsed(), model.device()); + eprintln!("load: {} on {}", ms(t.elapsed()), model.backbone_device()); let (w, h) = (1200, 800); let rgb: Vec = (0..w * h * 3).map(|i| ((i / 3 % w) * 255 / w) as u8).collect(); - for run in 0..3 { - let t = std::time::Instant::now(); + let click = |x, y| lightcraft_segment::Click { x, y, positive: true }; + for run in 0..runs { + let t = Instant::now(); let mut enc = model.encode(&rgb, w, h)?; lightcraft_segment::sync(&model)?; - let e = t.elapsed(); - let t = std::time::Instant::now(); - let p = model.segment_clicks(&mut enc, &[lightcraft_segment::Click { x: 0.5, y: 0.5, positive: true }])?; - let c = t.elapsed(); - let t = std::time::Instant::now(); + let encode = t.elapsed(); + let t = Instant::now(); + model.prepare_clicks(&mut enc)?; + lightcraft_segment::sync(&model)?; + let features = t.elapsed(); + let t = Instant::now(); + let p = model.segment_clicks(&mut enc, &[click(0.5, 0.5)])?; + let click1 = t.elapsed(); + let t = Instant::now(); + model.segment_clicks(&mut enc, &[click(0.5, 0.5), click(0.3, 0.6)])?; + let click2 = t.elapsed(); + let t = Instant::now(); let d = model.segment_text(&mut enc, "sky", 0.5)?; - eprintln!("run {run}: encode {e:?}, click {c:?} (score {:.2}), text {:?} ({})", p.score, t.elapsed(), d.is_some()); + let text1 = t.elapsed(); + let t = Instant::now(); + model.segment_text(&mut enc, "the red car", 0.5)?; + let text2 = t.elapsed(); + eprintln!( + "run {run}: encode {}, click features {}, click {} (score {:.2}), further click {}, first describe {} ({}), second describe {}", + ms(encode), + ms(features), + ms(click1), + p.score, + ms(click2), + ms(text1), + d.is_some(), + ms(text2) + ); } Ok(()) } diff --git a/crates/segment/src/cpu.rs b/crates/segment/src/cpu.rs new file mode 100644 index 0000000000..64827840ce --- /dev/null +++ b/crates/segment/src/cpu.rs @@ -0,0 +1,147 @@ +//! Fused CPU kernels for the model's elementwise work. +//! +//! On the CPU, candle runs bias adds, activations, broadcasts and layout copies one element at a +//! time on one thread. The kernels do the same arithmetic in the same order (bit-identical +//! results), fused into fewer passes over memory and spread over the rayon pool that candle's +//! matrix products use. + +use std::f32::consts::FRAC_1_SQRT_2; + +use candle_core::cpu::erf::erf_f32; +use candle_core::{CpuStorage, CustomOp2, D, Layout, Shape, Tensor, bail}; +use candle_nn::Linear; +use rayon::prelude::*; + +use crate::{Error, Result}; + +/// The contiguous `f32` values of a CPU tensor. +fn values<'a>(s: &'a CpuStorage, l: &Layout) -> candle_core::Result<&'a [f32]> { + match (s, l.contiguous_offsets()) { + (CpuStorage::F32(v), Some((start, end))) => match v.get(start..end) { + Some(v) => Ok(v), + None => bail!("layout outside its storage"), + }, + _ => bail!("fused kernels take contiguous f32 tensors"), + } +} + +/// `x · Wᵀ` over the rows of `x` (`[…, K]`) as `[rows, N]`: `Linear::forward` without the bias. +fn product(x: &Tensor, l: &Linear) -> Result { + let k = x.dim(D::Minus1)?; + Ok(x.reshape(((), k))?.matmul(&l.weight().t()?)?) +} + +fn bias(l: &Linear) -> Result<&Tensor> { + l.bias().ok_or_else(|| Error::Model("fused linear without a bias".into())) +} + +/// `gelu_erf(x · Wᵀ + b)` (`gelu`) or `relu(x · Wᵀ + b)`: `[rows, N]`. +pub fn linear_act(x: &Tensor, l: &Linear, gelu: bool) -> Result { + Ok(product(x, l)?.apply_op2_no_bwd(bias(l)?, &BiasAct { gelu })?) +} + +/// The detector's box relative-position bias `[1, heads, 1 + queries, side²]` from its row and +/// column terms `ey`, `ex` (`[queries, side, heads]`): `ey[q, y, h] + ex[q, x, h]` at `y·side + x`, +/// after a row of zeros (the presence token). +pub fn box_bias(ey: &Tensor, ex: &Tensor) -> Result { + Ok(ey.contiguous()?.apply_op2_no_bwd(&ex.contiguous()?, &BoxBias)?) +} + +/// Rows of `x` (`[rows, N]`) with a bias `[N]`. +fn rows(x: &[f32], b: &[f32]) -> candle_core::Result { + if b.is_empty() || !x.len().is_multiple_of(b.len()) { + bail!("bias of {} for {} values", b.len(), x.len()); + } + Ok(b.len()) +} + +struct BiasAct { + gelu: bool, +} + +impl CustomOp2 for BiasAct { + fn name(&self) -> &'static str { + if self.gelu { "bias-gelu-erf" } else { "bias-relu" } + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (x, b) = (values(s1, l1)?, values(s2, l2)?); + let n = rows(x, b)?; + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(n).zip(x.par_chunks(n)).for_each(|(o, x)| { + for ((o, x), b) in o.iter_mut().zip(x).zip(b) { + let v = x + b; + // candle's `gelu_erf` and `relu` + *o = if self.gelu { (erf_f32(v * FRAC_1_SQRT_2) + 1.) * 0.5 * v } else { v.max(0f32) }; + } + }); + Ok((CpuStorage::F32(out), l1.shape().clone())) + } +} + +struct BoxBias; + +impl CustomOp2 for BoxBias { + fn name(&self) -> &'static str { + "box-relative-position-bias" + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (ey, ex) = (values(s1, l1)?, values(s2, l2)?); + let (q, side, heads) = l1.shape().dims3()?; + if l2.shape() != l1.shape() { + bail!("box bias terms {:?} and {:?}", l1.shape(), l2.shape()); + } + let n = side * side; + let mut out = vec![0f32; heads * (q + 1) * n]; + // row 0 of each head (the presence token) stays zero + out.par_chunks_mut(n).enumerate().filter(|(i, _)| i % (q + 1) != 0).for_each(|(i, o)| { + let (h, q) = (i / (q + 1), i % (q + 1) - 1); + for (y, o) in o.chunks_exact_mut(side).enumerate() { + let ey = ey[(q * side + y) * heads + h]; + for (x, o) in o.iter_mut().enumerate() { + *o = ey + ex[(q * side + x) * heads + h]; + } + } + }); + Ok((CpuStorage::F32(out), Shape::from((1, heads, q + 1, n)))) + } +} + +#[cfg(test)] +mod tests { + use candle_core::Device; + use candle_nn::Module; + + use super::*; + + fn randn(shape: &[usize]) -> Tensor { + Tensor::randn(0f32, 1.0, shape, &Device::Cpu).unwrap() + } + + #[test] + fn linear_act_matches_the_tensor_ops() { + let x = randn(&[2, 7, 5]); + let l = Linear::new(randn(&[6, 5]), Some(randn(&[6]))); + for gelu in [false, true] { + let want = l.forward(&x).unwrap(); + let want = if gelu { want.gelu_erf() } else { want.relu() }.unwrap().reshape((14, 6)).unwrap(); + let got = linear_act(&x, &l, gelu).unwrap(); + assert_eq!(got.dims(), want.dims()); + assert_eq!(got.flatten_all().unwrap().to_vec1::().unwrap(), want.flatten_all().unwrap().to_vec1::().unwrap()); + } + assert!(linear_act(&x, &Linear::new(randn(&[6, 5]), None), false).is_err()); + } + + #[test] + fn box_bias_matches_the_tensor_ops() { + let (ey, ex) = (randn(&[4, 5, 3]), randn(&[4, 5, 3])); + let want = ey.unsqueeze(2).unwrap().broadcast_add(&ex.unsqueeze(1).unwrap()).unwrap(); + let want = want.reshape((4, 25, 3)).unwrap().permute((2, 0, 1)).unwrap().pad_with_zeros(1, 1, 0).unwrap().unsqueeze(0).unwrap(); + let got = box_bias(&ey, &ex).unwrap(); + assert_eq!(got.dims(), want.dims()); + // the same additions: bit-identical + assert_eq!(got.flatten_all().unwrap().to_vec1::().unwrap(), want.flatten_all().unwrap().to_vec1::().unwrap()); + assert!(box_bias(&ey, &randn(&[4, 6, 3])).is_err()); + } +} diff --git a/crates/segment/src/detector.rs b/crates/segment/src/detector.rs index c302aafe76..edb8557dff 100644 --- a/crates/segment/src/detector.rs +++ b/crates/segment/src/detector.rs @@ -6,18 +6,24 @@ //! the Python/PyTorch SAM 3 code of Hugging Face Transformers (`models/sam3/modeling_sam3.py`), Copyright The HuggingFace //! Team and Meta Platforms, Inc.; translated to Rust on candle and restructured. See NOTICE. +use std::collections::VecDeque; +use std::sync::{Mutex, OnceLock, PoisonError}; + use candle_core::{D, Device, IndexOp, Module, Tensor}; use candle_nn::{Conv2d, Conv2dConfig, GroupNorm, LayerNorm, Linear, VarBuilder}; use crate::clip::TextEncoder; use crate::neck::{FPN, Neck}; use crate::nn::{Attention, DecoderMlp, Mlp, TORCH_LN_EPS, cxcywh_to_xyxy, inverse_sigmoid, linear, ln, padding_bias, sine_grid, to_vec}; -use crate::{Error, Prediction, Result}; +use crate::{BackboneAccel, Error, Prediction, Result, cpu}; const HIDDEN: usize = FPN; const HEADS: usize = 8; const QUERIES: usize = 200; const LAYERS: usize = 6; +/// Prompts whose text features are kept: they don't depend on the image, and the same few come back (Subject's +/// "person" on every photo). 32 KB each. +const TEXT_CACHE: usize = 16; /// Detector image features, computed once per image. pub struct Features { @@ -44,6 +50,17 @@ pub struct Output { /// Semantic logits `[288, 288]` flattened: everything the prompt names, one mask without /// boundaries between instances. pub semantic: Vec, + /// The DETR encoder's memory `[1, 5184, 256]` (tests). + pub memory: Tensor, +} + +/// Where the DETR encoder and the mask decoder may run outside candle: the model's accelerator (if it still has one), +/// and why the encoder (`failed`) or the mask decoder (`masks_failed`) stopped running there (set on its first failure; +/// from then on candle runs it). +pub struct EncoderAccel<'a> { + pub accel: &'a Mutex>>, + pub failed: &'a OnceLock, + pub masks_failed: &'a OnceLock, } struct EncoderLayer { @@ -71,6 +88,8 @@ pub struct Detector { neck: Neck, text: TextEncoder, text_proj: Linear, + /// The latest prompts' token ids and valid marks with their features `[1, 32, 256]`, most recent last. + texts: Mutex, Vec, Tensor)>>, encoder: Vec, decoder: Vec, out_ln: LayerNorm, @@ -138,6 +157,7 @@ impl Detector { neck: Neck::new(vb.pp("vision_encoder.neck"))?, text: TextEncoder::new(vb.pp("text_encoder.text_model"))?, text_proj: linear(1024, HIDDEN, vb.pp("text_projection"))?, + texts: Mutex::new(VecDeque::with_capacity(TEXT_CACHE)), encoder, decoder, out_ln: ln(HIDDEN, TORCH_LN_EPS, d.pp("output_layer_norm"))?, @@ -164,9 +184,13 @@ impl Detector { }) } - /// The detector's feature pyramid for the backbone output `[1, 1024, 72, 72]`. - pub fn features(&self, backbone: &Tensor) -> Result { - let levels = self.neck.forward(backbone, 3)?; + /// The detector's feature pyramid for the backbone output `[1, 1024, 72, 72]`, or from its neck's three + /// levels when they were computed elsewhere (an accelerator). + pub fn features(&self, backbone: &Tensor, levels: Option>) -> Result { + let levels = match levels { + Some(levels) => levels, + None => self.neck.forward(backbone, 3)?, + }; let last = levels.last().ok_or_else(|| Error::Model("detector neck".into()))?; let (_, _, side, _) = last.dims4()?; let flat = last.flatten_from(2)?.transpose(1, 2)?.contiguous()?; @@ -174,6 +198,23 @@ impl Detector { Ok(Features { levels, flat, pos, side }) } + /// The prompt's features `[1, 32, 256]`: the CLIP text encoder and its projection, or the same tensor again + /// when the prompt was among the last [`TEXT_CACHE`]. + fn text_features(&self, ids: &[u32], valid: &[bool]) -> Result { + let mut texts = self.texts.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(seen) = texts.iter().position(|(i, v, _)| i == ids && v == valid).and_then(|at| texts.remove(at)) { + let text = seen.2.clone(); + texts.push_back(seen); + return Ok(text); + } + let text = self.text_proj.forward(&self.text.forward(ids, valid)?)?; + if texts.len() >= TEXT_CACHE { + texts.pop_front(); + } + texts.push_back((ids.to_vec(), valid.to_vec(), text.clone())); + Ok(text) + } + /// Box relative-position bias `[1, heads, 1 + 200, side²]` for reference boxes (cx, cy, w, h). fn rpb(&self, boxes: &Tensor, side: usize) -> Result { let xyxy = cxcywh_to_xyxy(boxes)?.squeeze(0)?; // [200, 4] @@ -188,6 +229,9 @@ impl Detector { let dx = log_scale(coords.broadcast_sub(&pick(0, 2)?)?)?; let ey = self.rpb_y.forward(&dy)?; // [200, side, heads] let ex = self.rpb_x.forward(&dx)?; + if self.device.is_cpu() { + return cpu::box_bias(&ey, &ex); + } let m = ey.unsqueeze(2)?.broadcast_add(&ex.unsqueeze(1)?)?; // [200, side, side, heads] let m = m.reshape((QUERIES, side * side, HEADS))?.permute((2, 0, 1))?; // [heads, 200, side²] let m = m.pad_with_zeros(1, 1, 0)?; // the presence token attends everywhere @@ -208,23 +252,143 @@ impl Detector { Ok(Tensor::cat(&[one(1)?, one(0)?, one(2)?, one(3)?], D::Minus1)?) } - /// Run the detector for one tokenized prompt. - pub fn predict(&self, f: &Features, ids: &[u32], valid: &[bool]) -> Result { - let text = self.text_proj.forward(&self.text.forward(ids, valid)?)?; // [1, 32, 256] - let text_bias = padding_bias(valid, &self.device)?; - - // DETR encoder: image tokens attend to themselves and to the prompt + /// The DETR encoder: image tokens attend to themselves and to the prompt. Returns the memory `[1, 5184, 256]`. + fn encode(&self, f: &Features, text: &Tensor, text_bias: &Tensor) -> Result { let mut x = f.flat.clone(); for l in &self.encoder { let h = l.ln1.forward(&x)?; let hp = (&h + &f.pos)?; x = (&x + l.self_attn.forward(&hp, &hp, &h, None)?)?; let h = l.ln2.forward(&x)?; - x = (&x + l.cross_attn.forward(&h, &text, &text, Some(&text_bias))?)?; + x = (&x + l.cross_attn.forward(&h, text, text, Some(text_bias))?)?; let h = l.ln3.forward(&x)?; x = (&x + l.mlp.forward(&h)?)?; } - let memory = x; + Ok(x) + } + + /// [`Detector::encode`] on the accelerator; `None` when there is none, or it doesn't run the encoder or fails (the + /// first failure is logged and noted in `accel.failed`, and the accelerator isn't asked again). `Err` when the app is + /// closing. + fn encode_accelerated(&self, f: &Features, text: &Tensor, valid: &[bool], accel: &EncoderAccel) -> Result> { + if accel.failed.get().is_some() { + return Ok(None); + } + let guard = accel.accel.lock().unwrap_or_else(PoisonError::into_inner); + // an accelerator for the backbone only: candle runs this, and that is no failure + let Some(a) = guard.as_ref().filter(|a| a.runs_detr_encoder()) else { return Ok(None) }; + let image = to_vec(&f.flat)?; + let want = image.len(); + // what the decoder can't use is a failure too: a wrong size, or NaN / ∞ from a broken kernel + let checked = a.detr_encoder(&image, &to_vec(&f.pos)?, &to_vec(text)?, valid).and_then(|out| { + if out.len() != want { + Err(format!("it returned {} values instead of {want}", out.len())) + } else if out.iter().any(|v| !v.is_finite()) { + Err("it returned values that are not numbers".into()) + } else { + Ok(out) + } + }); + match checked { + Ok(out) => Ok(Some(Tensor::from_vec(out, f.flat.dims(), &self.device)?)), + Err(e) if a.closing() => Err(Error::Model(e)), + Err(e) => { + log::warn!("SAM 3 DETR encoder not run on {} ({e}); using the {} for it from now on", a.device(), crate::device_name(&self.device)); + let _ = accel.failed.set(format!("{}: {e}", a.device())); + Ok(None) + } + } + } + + /// The mask decoder in candle: the per-query mask logits `[200, 288, 288]` for the encoder memory and the mask + /// embeddings `e` `[1, 200, 256]`. + fn masks(&self, f: &Features, memory: &Tensor, text: &Tensor, text_bias: &Tensor, e: &Tensor) -> Result<(Tensor, Vec)> { + // the encoder memory attends to the prompt, then a pixel decoder up to 288² + let mem = (memory + self.prompt_attn.forward(&self.prompt_ln.forward(memory)?, text, text, Some(text_bias))?)?; + let [l0, l1, _] = &f.levels[..] else { return Err(Error::Model("detector levels".into())) }; + let mut prev = mem.transpose(1, 2)?.reshape((1, HIDDEN, f.side, f.side))?; + for (i, skip) in [l1, l0].into_iter().enumerate() { + let (_, _, sh, sw) = skip.dims4()?; + prev = (prev.upsample_nearest2d(sh, sw)? + skip)?; + let (Some(conv), Some(norm)) = (self.pixel_convs.get(i), self.pixel_norms.get(i)) else { + return Err(Error::Model("pixel decoder".into())); + }; + prev = norm.forward(&conv.forward(&prev)?)?.relu()?; + } + let inst = self.instance_proj.forward(&prev)?; // [1, 256, 288, 288] + let semantic = to_vec(&self.semantic_proj.forward(&prev)?)?; + let (_, c, mh, mw) = inst.dims4()?; + Ok((e.matmul(&inst.reshape((1, c, mh * mw))?)?.reshape((QUERIES, mh, mw))?, semantic)) + } + + /// [`Detector::masks`] on the accelerator (the semantic mask as one more row of the same product); `None` when there + /// is none, or it doesn't run the mask decoder or fails + /// (the first failure is logged and noted in `accel.masks_failed`, and the accelerator isn't asked again). `Err` when + /// the app is closing. + fn masks_accelerated( + &self, + f: &Features, + memory: &Tensor, + (text, valid): (&Tensor, &[bool]), + e: &Tensor, + accel: &EncoderAccel, + ) -> Result)>> { + if accel.masks_failed.get().is_some() { + return Ok(None); + } + let guard = accel.accel.lock().unwrap_or_else(PoisonError::into_inner); + // an accelerator for the backbone only: candle runs this, and that is no failure + let Some(a) = guard.as_ref().filter(|a| a.runs_mask_decoder()) else { return Ok(None) }; + let [l0, l1, _] = &f.levels[..] else { return Err(Error::Model("detector levels".into())) }; + let (_, _, mh, mw) = l0.dims4()?; + // the instance projection folded into the embeddings: e · (W x + b) = (e W) x + e b, one product per pixel + let e = e.squeeze(0)?; // [200, 256] + let rows = e.matmul(&self.instance_proj.weight().reshape((HIDDEN, HIDDEN))?)?; + let mut bias = match self.instance_proj.bias() { + Some(b) => to_vec(&e.matmul(&b.unsqueeze(1)?)?)?, + None => vec![0.0; QUERIES], + }; + // the semantic projection (1 × 1, 256 → 1) is one more row: the last mask is the semantic one + let rows = Tensor::cat(&[rows, self.semantic_proj.weight().reshape((1, HIDDEN))?], 0)?; + bias.push(match self.semantic_proj.bias() { + Some(b) => to_vec(b)?.first().copied().unwrap_or(0.0), + None => 0.0, + }); + let want = (QUERIES + 1) * mh * mw; + // what the masks can't use is a failure too: a wrong size, or NaN / ∞ from a broken kernel + let checked = a.mask_decoder(&to_vec(memory)?, &to_vec(text)?, valid, [&to_vec(l1)?, &to_vec(l0)?], &to_vec(&rows)?, &bias).and_then(|out| { + if out.len() != want { + Err(format!("it returned {} values instead of {want}", out.len())) + } else if !out.iter().fold(true, |ok, v| ok & v.is_finite()) { + // without short-cutting, so that it vectorizes (17 M values) + Err("it returned values that are not numbers".into()) + } else { + Ok(out) + } + }); + match checked { + Ok(mut out) => { + let semantic = out.split_off(QUERIES * mh * mw); + Ok(Some((Tensor::from_vec(out, (QUERIES, mh, mw), &self.device)?, semantic))) + } + Err(e) if a.closing() => Err(Error::Model(e)), + Err(e) => { + log::warn!("SAM 3 mask decoder not run on {} ({e}); using the {} for it from now on", a.device(), crate::device_name(&self.device)); + let _ = accel.masks_failed.set(format!("{}: {e}", a.device())); + Ok(None) + } + } + } + + /// Run the detector for one tokenized prompt, the DETR encoder and the mask decoder on `accel` when it runs them. + pub fn predict(&self, f: &Features, ids: &[u32], valid: &[bool], accel: &EncoderAccel) -> Result { + let text = self.text_features(ids, valid)?; + let text_bias = padding_bias(valid, &self.device)?; + + let memory = match self.encode_accelerated(f, &text, valid, accel)? { + Some(memory) => memory, + None => self.encode(f, &text, &text_bias)?, + }; // DETR decoder: presence token + 200 queries with iterative box refinement let mut boxes = candle_nn::ops::sigmoid(&self.reference_points)?; @@ -260,21 +424,7 @@ impl Detector { let pq = self.score_query_proj.forward(&queries)?; // [1, 200, 256] let logits = (pq.matmul(&pt.unsqueeze(2)?)? / (HIDDEN as f64).sqrt())?.clamp(-12f32, 12f32)?; - // masks: the encoder memory attends to the prompt, then a pixel decoder up to 288² - let mem = (&memory + self.prompt_attn.forward(&self.prompt_ln.forward(&memory)?, &text, &text, Some(&text_bias))?)?; - let [l0, l1, _] = &f.levels[..] else { return Err(Error::Model("detector levels".into())) }; - let mut prev = mem.transpose(1, 2)?.reshape((1, HIDDEN, f.side, f.side))?; - for (i, skip) in [l1, l0].into_iter().enumerate() { - let (_, _, sh, sw) = skip.dims4()?; - prev = (prev.upsample_nearest2d(sh, sw)? + skip)?; - let (Some(conv), Some(norm)) = (self.pixel_convs.get(i), self.pixel_norms.get(i)) else { - return Err(Error::Model("pixel decoder".into())); - }; - prev = norm.forward(&conv.forward(&prev)?)?.relu()?; - } - let inst = self.instance_proj.forward(&prev)?; // [1, 256, 288, 288] - let semantic = to_vec(&self.semantic_proj.forward(&prev)?)?; - let (_, c, mh, mw) = inst.dims4()?; + // masks: each query's mask embedding against the mask decoder's per-pixel output let mut e = queries.clone(); for (i, l) in self.mask_embedder.iter().enumerate() { e = l.forward(&e)?; @@ -282,7 +432,10 @@ impl Detector { e = e.relu()?; } } - let masks = e.matmul(&inst.reshape((1, c, mh * mw))?)?.reshape((QUERIES, mh, mw))?; + let (masks, semantic) = match self.masks_accelerated(f, &memory, (&text, valid), &e, accel)? { + Some(masks) => masks, + None => self.masks(f, &memory, &text, &text_bias, &e)?, + }; let boxes = cxcywh_to_xyxy(&boxes)?; let bv = to_vec(&boxes)?; Ok(Output { @@ -292,6 +445,7 @@ impl Detector { boxes: bv.as_chunks::<4>().0.to_vec(), text, semantic, + memory, }) } } @@ -335,7 +489,89 @@ pub fn merge(out: &Output, threshold: f32) -> Option { #[cfg(test)] mod tests { + use std::path::PathBuf; + use super::*; + use crate::Sam3; + + /// The real checkpoint in `$LIGHTCRAFT_SAM3_DIR` (as the GPU tests), or `None` (the test skips) without it or when it + /// doesn't load. + fn model() -> Option { + let dir = std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()).map(PathBuf::from)?; + if !crate::is_model_dir(&dir) { + return None; + } + match Sam3::load_on(&dir, Device::Cpu) { + Ok(m) => Some(m), + Err(e) => { + eprintln!("the model in {} doesn't load: {e}", dir.display()); + None + } + } + } + + fn values(t: &Tensor) -> Vec { + t.flatten_all().unwrap().to_vec1().unwrap() + } + + #[test] + fn the_box_bias_matches_the_tensor_ops_on_random_boxes() { + let Some(mut m) = model() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let (det, _, _) = m.detector_parts().unwrap(); + let side = 72; + for _ in 0..3 { + let centres = Tensor::rand(0f32, 1.0, (1, QUERIES, 2), &Device::Cpu).unwrap(); + let sizes = Tensor::rand(0.01f32, 0.6, (1, QUERIES, 2), &Device::Cpu).unwrap(); + let boxes = Tensor::cat(&[centres, sizes], 2).unwrap(); + let got = det.rpb(&boxes, side).unwrap(); + // what the other devices run, from the same row and column terms + let xyxy = cxcywh_to_xyxy(&boxes).unwrap().squeeze(0).unwrap(); + let coords = Tensor::arange(0u32, side as u32, &Device::Cpu).unwrap().to_dtype(candle_core::DType::F32).unwrap(); + let coords = coords.affine(1.0 / side as f64, 0.0).unwrap().reshape((1, side, 1)).unwrap(); + let term = |mlp: &DecoderMlp, a: usize, b: usize| { + let pick = Tensor::cat(&[xyxy.narrow(1, a, 1).unwrap(), xyxy.narrow(1, b, 1).unwrap()], 1).unwrap().unsqueeze(1).unwrap(); + let d = (coords.broadcast_sub(&pick).unwrap() * 8.0).unwrap(); + let d = d.sign().unwrap().mul(&((d.abs().unwrap() + 1.0).unwrap().log().unwrap() / 8f64.ln()).unwrap()).unwrap(); + mlp.forward(&d).unwrap() + }; + let (ey, ex) = (term(&det.rpb_y, 1, 3), term(&det.rpb_x, 0, 2)); + let want = ey.unsqueeze(2).unwrap().broadcast_add(&ex.unsqueeze(1).unwrap()).unwrap(); + let want = want.reshape((QUERIES, side * side, HEADS)).unwrap().permute((2, 0, 1)).unwrap().pad_with_zeros(1, 1, 0).unwrap(); + assert_eq!(got.dims(), [1, HEADS, 1 + QUERIES, side * side]); + assert_eq!(values(&got), values(&want)); + } + } + + #[test] + fn prompt_features_are_kept_for_the_latest_prompts() { + let Some(mut m) = model() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let (det, tok, _) = m.detector_parts().unwrap(); + let prompts: Vec<(Vec, Vec)> = (0..=TEXT_CACHE).map(|i| tok.encode(&format!("{i} people"))).collect(); + let features = |i: usize| det.text_features(&prompts[i].0, &prompts[i].1).unwrap(); + let first = features(0); + let fresh = det.text_proj.forward(&det.text.forward(&prompts[0].0, &prompts[0].1).unwrap()).unwrap(); + assert_eq!(values(&first), values(&fresh)); + // the same tensor again, also after other prompts + assert_eq!(features(0).id(), first.id()); + let second = features(1); + for i in 2..TEXT_CACHE { + features(i); + } + assert_eq!(features(0).id(), first.id(), "prompt 0 is the latest one now"); + // one more prompt drops the least recently used, prompt 1, which is computed again + features(TEXT_CACHE); + assert_eq!(det.texts.lock().unwrap().len(), TEXT_CACHE); + assert_eq!(features(0).id(), first.id()); + let again = features(1); + assert_ne!(again.id(), second.id()); + assert_eq!(values(&again), values(&second)); + } /// Two people side by side on a row of cells, each only weakly sure of themself and both fading where /// they touch; the semantic mask is sure of both and runs across. Each takes the semantic logits where @@ -376,6 +612,7 @@ mod tests { boxes: vec![[0.0; 4]; 3], text: Tensor::zeros(1, candle_core::DType::F32, &Device::Cpu).unwrap(), semantic: semantic.to_vec(), + memory: Tensor::zeros(1, candle_core::DType::F32, &Device::Cpu).unwrap(), }; let semantic = [5.0, 6.0, 4.0, 6.0, 5.0]; let merged = merge(&output([4.0, 4.0, -6.0], &semantic), 0.5).unwrap(); diff --git a/crates/segment/src/lib.rs b/crates/segment/src/lib.rs index 6c24d0836f..959232edf4 100644 --- a/crates/segment/src/lib.rs +++ b/crates/segment/src/lib.rs @@ -8,9 +8,14 @@ //! The expensive part, the 32-layer ViT over the 1008 × 1008 input, runs once per image //! ([`Sam3::encode`]); each click or prompt then reuses the [`Encoded`] features. //! -//! On macOS the model runs on the GPU through Metal; elsewhere (for now) on the CPU. The -//! weights are not part of LightCraft: they are the `facebook/sam3` checkpoint (SAM License), -//! read from a directory the user downloads them to ([`Sam3::load`]). +//! On macOS the model runs on the GPU through Metal ([`Sam3::load`]). Elsewhere candle runs on +//! the CPU, and the backbone, most of the work, can run outside candle on an accelerator, with +//! the two necks after it ([`BackboneAccel`]: `lightcraft-gpu`'s wgpu kernels on Vulkan / DX12, loaded with +//! [`Sam3::load_accelerated`]); when that can't be built or fails on a photo, the candle backbone +//! takes over ([`Sam3::backbone_fallback`] says why; not while the app is closing: [`BackboneAccel::closing`]). +//! The accelerator can also run the text detector's DETR encoder (else, or once it fails, candle does: +//! [`Sam3::detr_fallback`]). The weights are not part of LightCraft: they are the `facebook/sam3` checkpoint +//! (SAM License), read from a directory the user downloads them to. //! //! Ported from the Hugging Face `transformers` implementation (Apache-2.0); see `NOTICE`. //! This crate is therefore licensed under the Apache License 2.0 only (not the MIT option of @@ -29,6 +34,8 @@ #[cfg(not(target_arch = "wasm32"))] mod clip; #[cfg(not(target_arch = "wasm32"))] +mod cpu; +#[cfg(not(target_arch = "wasm32"))] mod detector; #[cfg(not(target_arch = "wasm32"))] pub mod fetch; @@ -49,13 +56,15 @@ mod weights; use std::path::{Path, PathBuf}; #[cfg(not(target_arch = "wasm32"))] -use std::sync::Arc; +use std::sync::{Arc, Mutex, OnceLock, PoisonError}; #[cfg(not(target_arch = "wasm32"))] -use candle_core::{DType, Device, Tensor}; +use candle_core::{DType, Tensor}; #[cfg(not(target_arch = "wasm32"))] use candle_nn::VarBuilder; +#[cfg(not(target_arch = "wasm32"))] +pub use candle_core::Device; #[cfg(not(target_arch = "wasm32"))] pub use tracker::Click; @@ -103,12 +112,135 @@ pub fn best_device() -> Device { } #[cfg(not(target_arch = "wasm32"))] -/// A loaded model. The vision backbone loads with it; the point and text heads load on first use. +/// Where the backbone's weights are in the checkpoint. +pub const BACKBONE_PREFIX: &str = "detector_model.vision_encoder.backbone"; + +#[cfg(not(target_arch = "wasm32"))] +/// The vision backbone run outside candle (the wgpu compute kernels of `lightcraft-gpu` on +/// Vulkan / DX12 / Metal). It computes what the candle ViT computes, so everything after the +/// backbone (necks, heads) stays as it is. +pub trait BackboneAccel: Send + Sync { + /// `pixels`: `[3, 1008, 1008]` (CHW, normalized to −1..1). Returns the backbone output + /// `[1024, 72, 72]` (CHW), as the candle ViT's `[1, 1024, 72, 72]` without the batch. + fn forward(&self, pixels: &[f32]) -> std::result::Result, String>; + /// What it runs on, for logs and Settings (e.g. "NVIDIA GeForce RTX 5070 (Vulkan)"). + fn device(&self) -> String; + + /// Whether the app is closing, so that an `Err` from it is no failure of the accelerator: it stays in use, and the + /// work ends with that error instead of running in candle (no CPU inference while the app quits). + fn closing(&self) -> bool { + false + } + + /// Whether it runs the necks ([`BackboneAccel::neck`]); when not, they are never asked for and run in candle. + fn runs_necks(&self) -> bool { + false + } + + /// Whether it runs the text detector's DETR encoder ([`BackboneAccel::detr_encoder`]); when not, candle does. + fn runs_detr_encoder(&self) -> bool { + false + } + + /// Whether it runs the text detector's mask decoder ([`BackboneAccel::mask_decoder`]); when not, candle does. + fn runs_mask_decoder(&self) -> bool { + false + } + + /// The feature pyramid of the `which` neck for a backbone output `[1024, 72, 72]` (CHW): the + /// `n` finest levels, each `[256, s, s]` (CHW; s = 288, 144, 72, 36), as the candle `Neck::forward`. + /// `Err` when this accelerator doesn't run it (the candle neck runs instead). + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> std::result::Result>, String> { + let _ = (which, backbone, n); + Err("no neck on this accelerator".into()) + } + + /// The detector's DETR encoder (6 layers): the image tokens `[5184, 256]` with their sine + /// position encoding `pos` `[5184, 256]` attend to themselves and to the prompt `text` + /// `[32, 256]` (`valid` marks its real tokens). Returns the encoder memory `[5184, 256]`. + /// `Err` when this accelerator doesn't run it (the candle encoder runs instead). + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> std::result::Result, String> { + let _ = (image, pos, text, valid); + Err("no DETR encoder on this accelerator".into()) + } + + /// The detector's mask decoder: the encoder memory `[5184, 256]` attends to the prompt `text` `[32, 256]` (`valid` + /// marks its real tokens) and is added to it, the pixel decoder brings that up to 288² with the detector neck's + /// `levels` `[256, 144, 144]` and `[256, 288, 288]` (CHW), and each of the `rows` `[r, 256]` (1 ≤ r ≤ 256, with + /// `bias` `[r]`) is a 1 × 1 projection of its output. Returns `[r, 288, 288]` (the detector passes its mask + /// embeddings with the instance projection folded in: the per-query mask logits). `Err` when this accelerator + /// doesn't run it (the candle decoder runs instead). + fn mask_decoder( + &self, + memory: &[f32], + text: &[f32], + valid: &[bool], + levels: [&[f32]; 2], + rows: &[f32], + bias: &[f32], + ) -> std::result::Result, String> { + let _ = (memory, text, valid, levels, rows, bias); + Err("no mask decoder on this accelerator".into()) + } +} + +#[cfg(not(target_arch = "wasm32"))] +/// The two feature pyramids of the checkpoint. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NeckKind { + /// `tracker_neck`: the click decoder's (3 levels). + Tracker, + /// `detector_model.vision_encoder.neck`: the text detector's (3 levels). + Detector, +} + +#[cfg(not(target_arch = "wasm32"))] +/// Read access to a checkpoint's tensors (for accelerators that upload weights themselves; +/// cloning shares the open file, so an accelerator can keep one and load more layers later). +#[derive(Clone)] +pub struct WeightReader(Arc); + +#[cfg(not(target_arch = "wasm32"))] +impl WeightReader { + /// The checkpoint in a model directory (see [`is_model_dir`]). + pub fn open(dir: &Path) -> Result { + if !is_model_dir(dir) { + return Err(Error::Missing(dir.to_path_buf())); + } + Ok(Self(weights::Weights::open(&dir.join(WEIGHTS_FILE))?)) + } + + /// The stored shape of `name`, without reading its data. + pub fn shape(&self, name: &str) -> Option> { + self.0.shape(name).map(<[usize]>::to_vec) + } + + /// Tensor `name`: its shape and its values (f32, row-major). + pub fn read(&self, name: &str) -> Result<(Vec, Vec)> { + let t = self.0.read(name)?; + Ok((t.dims().to_vec(), t.flatten_all()?.to_vec1::()?)) + } +} + +#[cfg(not(target_arch = "wasm32"))] +/// A loaded model. The vision backbone loads with it (unless an accelerator runs it); the point +/// and text heads load on first use. pub struct Sam3 { dir: PathBuf, device: Device, weights: Arc, - backbone: vit::Vit, + /// The candle backbone: loaded with the model, or only when an accelerator fails. + backbone: OnceLock, + accel: Mutex>>, + /// Why the accelerator `load_accelerated` was given is not (or no longer) used. + fallback: Mutex>, + /// Why the DETR encoder runs in candle although there is an accelerator (it failed there once). + detr_fallback: OnceLock, + /// The same for the text detector's mask decoder. + mask_fallback: OnceLock, + /// The necks the accelerator failed on: candle runs them from then on. + necks_off: Mutex>, + /// The candle tracker neck: loaded on first use, unless the accelerator runs it. tracker_neck: Option, tracker: Option, detector: Option, @@ -149,8 +281,123 @@ impl Sam3 { return Err(Error::Missing(dir.to_path_buf())); } let weights = weights::Weights::open(&dir.join(WEIGHTS_FILE))?; - let backbone = vit::Vit::new(Self::vb(&weights, &device).pp("detector_model.vision_encoder.backbone"))?; - Ok(Self { dir: dir.to_path_buf(), device, weights, backbone, tracker_neck: None, tracker: None, detector: None, tokenizer: None }) + let model = Self::unloaded(dir, device, weights, None); + model.candle_backbone()?; + Ok(model) + } + + /// Load with the backbone on an accelerator `make` builds from the checkpoint, and the rest + /// on `device`. When `make` fails the candle backbone loads instead, and when the + /// accelerator fails later, [`Sam3::encode`] falls back to it (logged, not an error), unless the app is closing. + pub fn load_accelerated( + dir: &Path, + device: Device, + make: impl FnOnce(&WeightReader) -> std::result::Result, String>, + ) -> Result { + let reader = WeightReader::open(dir)?; + match make(&reader) { + Ok(accel) => { + log::info!("SAM 3 backbone on {}", accel.device()); + Ok(Self::unloaded(dir, device, reader.0, Some(accel))) + } + Err(e) => { + log::warn!("SAM 3 backbone accelerator unavailable ({e}); using the {}", device_name(&device)); + let model = Self::unloaded(dir, device, reader.0, None); + *model.fallback.lock().unwrap_or_else(PoisonError::into_inner) = Some(e); + model.candle_backbone()?; + Ok(model) + } + } + } + + fn unloaded(dir: &Path, device: Device, weights: Arc, accel: Option>) -> Self { + Self { + dir: dir.to_path_buf(), + device, + weights, + backbone: OnceLock::new(), + accel: Mutex::new(accel), + fallback: Mutex::new(None), + detr_fallback: OnceLock::new(), + mask_fallback: OnceLock::new(), + necks_off: Mutex::new(Vec::new()), + tracker_neck: None, + tracker: None, + detector: None, + tokenizer: None, + } + } + + /// The candle backbone, loading it on first use. + fn candle_backbone(&self) -> Result<&vit::Vit> { + if let Some(b) = self.backbone.get() { + return Ok(b); + } + let b = vit::Vit::new(Self::vb(&self.weights, &self.device).pp(BACKBONE_PREFIX))?; + Ok(self.backbone.get_or_init(|| b)) + } + + /// What the backbone runs on: the accelerator's device, else the candle device ("CPU", "Metal GPU"). + pub fn backbone_device(&self) -> String { + match &*self.accel.lock().unwrap_or_else(PoisonError::into_inner) { + Some(a) => a.device(), + None => device_name(&self.device), + } + } + + /// Whether the backbone runs on the accelerator (rather than in candle). + pub fn accelerated(&self) -> bool { + self.accel.lock().unwrap_or_else(PoisonError::into_inner).is_some() + } + + /// Why the backbone runs in candle although an accelerator was offered: it could not be built, or it failed on + /// a photo (from then on the model stays in candle). `None` when there is no such reason. + pub fn backbone_fallback(&self) -> Option { + self.fallback.lock().unwrap_or_else(PoisonError::into_inner).clone() + } + + /// Why the text detector's DETR encoder runs in candle although the backbone runs on an accelerator: the + /// accelerator doesn't run it or failed on it (then it isn't asked again). `None` when there is no such reason. + pub fn detr_fallback(&self) -> Option { + self.detr_fallback.get().cloned() + } + + /// Why the text detector's mask decoder runs in candle although the backbone runs on an accelerator: the + /// accelerator doesn't run it or failed on it (then it isn't asked again). `None` when there is no such reason. + pub fn mask_fallback(&self) -> Option { + self.mask_fallback.get().cloned() + } + + /// What runs everything after the backbone: the model's device, and which of those parts the accelerator runs + /// (e.g. "CPU; the necks, the DETR encoder and the mask decoder on the GPU"). + pub fn heads_device(&self) -> String { + let base = device_name(&self.device); + // what the accelerator runs (none: there is none any more), less what failed on it + let (necks, detr, masks) = match self.accel.lock().unwrap_or_else(PoisonError::into_inner).as_ref() { + Some(a) => (a.runs_necks(), a.runs_detr_encoder(), a.runs_mask_decoder()), + None => (false, false, false), + }; + let mut gpu = Vec::new(); + if necks { + let off = self.necks_off.lock().unwrap_or_else(PoisonError::into_inner); + match (off.contains(&NeckKind::Tracker), off.contains(&NeckKind::Detector)) { + (false, false) => gpu.push("the necks"), + (false, true) => gpu.push("the click neck"), + (true, false) => gpu.push("the text neck"), + (true, true) => {} + } + } + if detr && self.detr_fallback.get().is_none() { + gpu.push("the DETR encoder"); + } + if masks && self.mask_fallback.get().is_none() { + gpu.push("the mask decoder"); + } + match gpu.split_last() { + None => base, + Some((last, [])) => format!("{base}; {last} on the GPU"), + Some((last, rest)) => format!("{base}; {} and {last} on the GPU", rest.join(", ")), + } } fn vb<'a>(w: &Arc, device: &Device) -> VarBuilder<'a> { @@ -171,30 +418,133 @@ impl Sam3 { /// Run the backbone on preprocessed pixels `[1, 3, 1008, 1008]` (−1..1). pub fn encode_pixels(&self, pixels: &Tensor) -> Result { - Ok(Encoded { backbone: self.backbone.forward(&pixels.to_device(&self.device)?)?, tracker: None, detector: None }) + let side = vit::GRID; + { + let mut accel = self.accel.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(a) = accel.as_ref() { + let px = pixels.to_device(&Device::Cpu)?.flatten_all()?.to_vec1::()?; + // what the necks can't use is a failure too: a wrong size, or NaN / ∞ from a broken kernel + let want = vit::HIDDEN * side * side; + let checked = a.forward(&px).and_then(|out| { + if out.len() != want { + Err(format!("it returned {} values instead of {want}", out.len())) + } else if out.iter().any(|v| !v.is_finite()) { + Err("it returned values that are not numbers".into()) + } else { + Ok(out) + } + }); + match checked { + Ok(out) => { + let backbone = Tensor::from_vec(out, (1, vit::HIDDEN, side, side), &self.device)?; + return Ok(Encoded { backbone, tracker: None, detector: None }); + } + Err(e) if a.closing() => return Err(Error::Model(e)), + Err(e) => { + log::warn!("SAM 3 backbone failed on {} ({e}); using the {} from now on", a.device(), device_name(&self.device)); + *self.fallback.lock().unwrap_or_else(PoisonError::into_inner) = Some(format!("{} failed: {e}", a.device())); + *accel = None; + } + } + } + } + let backbone = self.candle_backbone()?.forward(&pixels.to_device(&self.device)?)?; + Ok(Encoded { backbone, tracker: None, detector: None }) } - fn tracker_parts(&mut self) -> Result<(&neck::Neck, &tracker::Tracker)> { - if self.tracker_neck.is_none() { - self.tracker_neck = Some(neck::Neck::new(Self::vb(&self.weights, &self.device).pp("tracker_neck"))?); + /// The `n` finest levels of the `which` neck for `backbone`, computed by the accelerator and put on the model's + /// device; `None` when there is no accelerator, it doesn't run this neck or failed on it (logged once; candle + /// runs that neck from then on). `Err` when the app is closing. + fn accel_neck(&self, which: NeckKind, backbone: &Tensor, n: usize) -> Result>> { + let accel = self.accel.lock().unwrap_or_else(PoisonError::into_inner); + // an accelerator for the backbone only: the necks run in candle, and that is no failure + let Some(a) = accel.as_ref().filter(|a| a.runs_necks()) else { return Ok(None) }; + let mut off = self.necks_off.lock().unwrap_or_else(PoisonError::into_inner); + if off.contains(&which) { + return Ok(None); } + let run = || -> std::result::Result, String> { + let x = backbone.to_device(&Device::Cpu).and_then(|t| t.flatten_all()).and_then(|t| t.to_vec1::()).map_err(|e| e.to_string())?; + let levels = a.neck(which, &x, n)?; + if levels.len() != n { + return Err(format!("it returned {} levels instead of {n}", levels.len())); + } + levels + .into_iter() + .enumerate() + .map(|(i, l)| { + // what the heads can't use is a failure too: a wrong size, or NaN / ∞ from a broken kernel + let side = tracker::LOW_RES >> i; + if l.len() != neck::FPN * side * side { + return Err(format!("it returned {} values for level {i} instead of {}", l.len(), neck::FPN * side * side)); + } + // without short-cutting, so that it vectorizes (28 M values) + if !l.iter().fold(true, |ok, v| ok & v.is_finite()) { + return Err("it returned values that are not numbers".into()); + } + Tensor::from_vec(l, (1, neck::FPN, side, side), &self.device).map_err(|e| e.to_string()) + }) + .collect() + }; + match run() { + Ok(levels) => Ok(Some(levels)), + Err(e) if a.closing() => Err(Error::Model(e)), + Err(e) => { + let name = match which { + NeckKind::Tracker => "tracker", + NeckKind::Detector => "detector", + }; + log::warn!("SAM 3 {name} neck failed on {} ({e}); using the {} for it from now on", a.device(), device_name(&self.device)); + off.push(which); + Ok(None) + } + } + } + + fn tracker(&mut self) -> Result<&tracker::Tracker> { if self.tracker.is_none() { self.tracker = Some(tracker::Tracker::new(Self::vb(&self.weights, &self.device).pp("tracker_model"))?); } - match (&self.tracker_neck, &self.tracker) { - (Some(n), Some(t)) => Ok((n, t)), - _ => Err(Error::Model("tracker failed to load".into())), + self.tracker.as_ref().ok_or_else(|| Error::Model("tracker failed to load".into())) + } + + /// The click decoder's features for `enc`, once: the tracker neck on the accelerator when it runs it, else in + /// candle. + fn tracker_features(&mut self, enc: &mut Encoded) -> Result<()> { + if enc.tracker.is_some() { + return Ok(()); } + let levels = match self.accel_neck(NeckKind::Tracker, &enc.backbone, 3)? { + Some(levels) => levels, + None => { + if self.tracker_neck.is_none() { + self.tracker_neck = Some(neck::Neck::new(Self::vb(&self.weights, &self.device).pp("tracker_neck"))?); + } + let neck = self.tracker_neck.as_ref().ok_or_else(|| Error::Model("tracker neck failed to load".into()))?; + neck.forward(&enc.backbone, 3)? + } + }; + enc.tracker = Some(self.tracker()?.features(&levels)?); + Ok(()) + } + + /// The `which` neck's three finest levels for `enc`, each `[1, 256, s, s]` (tests and tools): on the + /// accelerator when it runs it, else in candle. + pub fn neck_levels(&self, which: NeckKind, enc: &Encoded) -> Result> { + if let Some(levels) = self.accel_neck(which, &enc.backbone, 3)? { + return Ok(levels); + } + let prefix = match which { + NeckKind::Tracker => "tracker_neck", + NeckKind::Detector => "detector_model.vision_encoder.neck", + }; + neck::Neck::new(Self::vb(&self.weights, &self.device).pp(prefix))?.forward(&enc.backbone, 3) } /// Compute the click decoder's features for `enc` now (so the first click is fast). pub fn prepare_clicks(&mut self, enc: &mut Encoded) -> Result<()> { - let (neck, tracker) = self.tracker_parts()?; - if enc.tracker.is_none() { - let levels = neck.forward(&enc.backbone, 3)?; - enc.tracker = Some(tracker.features(&levels)?); - } - Ok(()) + self.tracker()?; + self.tracker_features(enc) } /// Segment one object from clicks (positions normalized to the image, 0..1). @@ -202,18 +552,15 @@ impl Sam3 { if clicks.is_empty() { return Err(Error::Model("no clicks".into())); } - let (neck, tracker) = self.tracker_parts()?; - if enc.tracker.is_none() { - let levels = neck.forward(&enc.backbone, 3)?; - enc.tracker = Some(tracker.features(&levels)?); - } + self.tracker_features(enc)?; + let tracker = self.tracker()?; let f = enc.tracker.as_ref().ok_or_else(|| Error::Model("tracker features".into()))?; // one click: SAM's three alternatives, best by predicted IoU; more: the single mask let p = tracker.predict(f, clicks, clicks.len() == 1)?; Ok(Prediction { logits: p.logits, score: p.iou * sigmoid(p.object_score) }) } - fn detector_parts(&mut self) -> Result<(&detector::Detector, &tokenizer::Tokenizer)> { + fn detector_parts(&mut self) -> Result<(&detector::Detector, &tokenizer::Tokenizer, detector::EncoderAccel<'_>)> { if self.detector.is_none() { self.detector = Some(detector::Detector::new(Self::vb(&self.weights, &self.device).pp("detector_model"))?); } @@ -221,34 +568,42 @@ impl Sam3 { self.tokenizer = Some(tokenizer::Tokenizer::load(&self.dir)?); } match (&self.detector, &self.tokenizer) { - (Some(d), Some(t)) => Ok((d, t)), + (Some(d), Some(t)) => { + Ok((d, t, detector::EncoderAccel { accel: &self.accel, failed: &self.detr_fallback, masks_failed: &self.mask_fallback })) + } _ => Err(Error::Model("detector failed to load".into())), } } + /// The detector's features for `enc`, once: its neck on the accelerator when it runs it, else in candle. + fn detector_features(&mut self, enc: &mut Encoded) -> Result<()> { + if enc.detector.is_none() { + let levels = self.accel_neck(NeckKind::Detector, &enc.backbone, 3)?; + let (det, _, _) = self.detector_parts()?; + enc.detector = Some(det.features(&enc.backbone, levels)?); + } + Ok(()) + } + /// Segment every instance of the concept `text` names. Instances scoring above /// `threshold` (0..1, 0.5 is the reference default) are merged into one mask; `None` when /// nothing matches. pub fn segment_text(&mut self, enc: &mut Encoded, text: &str, threshold: f32) -> Result> { - let (det, tok) = self.detector_parts()?; - if enc.detector.is_none() { - enc.detector = Some(det.features(&enc.backbone)?); - } + self.detector_features(enc)?; + let (det, tok, accel) = self.detector_parts()?; let f = enc.detector.as_ref().ok_or_else(|| Error::Model("detector features".into()))?; let (ids, valid) = tok.encode(text); - let out = det.predict(f, &ids, &valid)?; + let out = det.predict(f, &ids, &valid, &accel)?; Ok(detector::merge(&out, threshold)) } /// Raw detector outputs for `text` (tests and tools). pub fn detect(&mut self, enc: &mut Encoded, text: &str) -> Result { - let (det, tok) = self.detector_parts()?; - if enc.detector.is_none() { - enc.detector = Some(det.features(&enc.backbone)?); - } + self.detector_features(enc)?; + let (det, tok, accel) = self.detector_parts()?; let f = enc.detector.as_ref().ok_or_else(|| Error::Model("detector features".into()))?; let (ids, valid) = tok.encode(text); - det.predict(f, &ids, &valid) + det.predict(f, &ids, &valid, &accel) } } @@ -260,6 +615,16 @@ impl Encoded { } } +#[cfg(not(target_arch = "wasm32"))] +/// A candle device as people call it ("CPU", "Metal GPU"). +pub fn device_name(device: &Device) -> String { + match device { + Device::Cpu => "CPU".into(), + Device::Metal(_) => "Metal GPU".into(), + Device::Cuda(_) => "CUDA GPU".into(), + } +} + #[cfg(not(target_arch = "wasm32"))] fn sigmoid(x: f32) -> f32 { 1.0 / (1.0 + (-x).exp()) @@ -273,3 +638,193 @@ pub use detector::Output as DetectorOutput; pub fn sync(model: &Sam3) -> Result<()> { Ok(model.device.synchronize()?) } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + /// A model folder whose checkpoint holds no tensors: enough to load with an accelerator, never to run candle. + #[allow(clippy::unwrap_used)] + fn empty_model(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-sam3-{name}-{}", 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(WEIGHTS_FILE), st).unwrap(); + std::fs::write(dir.join("vocab.json"), "{}").unwrap(); + std::fs::write(dir.join("merges.txt"), "").unwrap(); + dir + } + + /// Answers with `values` backbone values, all `fill`, or fails. + struct Fake { + values: usize, + fill: f32, + fail: bool, + } + + impl BackboneAccel for Fake { + fn forward(&self, pixels: &[f32]) -> std::result::Result, String> { + assert_eq!(pixels.len(), 3 * INPUT * INPUT); + if self.fail { Err("device lost".into()) } else { Ok(vec![self.fill; self.values]) } + } + fn device(&self) -> String { + "Fake GPU (Vulkan)".into() + } + } + + const FULL: usize = vit::HIDDEN * vit::GRID * vit::GRID; + + fn with(fake: Fake) -> impl FnOnce(&WeightReader) -> std::result::Result, String> { + move |_| Ok(Box::new(fake)) + } + + #[test] + fn the_backbone_runs_on_the_accelerator_without_loading_candle() { + let dir = empty_model("accel"); + let m = Sam3::load_accelerated(&dir, Device::Cpu, with(Fake { values: FULL, fill: 0.25, fail: false })).unwrap(); + assert!(m.accelerated()); + assert_eq!(m.backbone_device(), "Fake GPU (Vulkan)"); + assert_eq!(m.backbone_fallback(), None); + // an accelerator for the backbone only: the rest is candle's + assert_eq!(m.heads_device(), "CPU"); + let enc = m.encode(&[128; 4 * 3 * 3], 4, 3).unwrap(); + assert_eq!(enc.backbone().dims(), [1, vit::HIDDEN, vit::GRID, vit::GRID]); + assert!(m.backbone.get().is_none(), "the candle backbone was never loaded"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn an_accelerator_that_cannot_be_built_leaves_the_backbone_to_candle() { + let dir = empty_model("nomake"); + // the empty checkpoint has no candle backbone: the load fails, but only after trying it + let r = Sam3::load_accelerated(&dir, Device::Cpu, |_| Err("no adapter".into())); + assert!(r.is_err_and(|e| !e.to_string().contains("no adapter"))); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// A backbone of `fill`, and neck levels of the right sizes (filled with their index) for the tracker; for the + /// detector the third level is cut short (`short`) or holds a NaN. + struct NeckFake { + calls: Arc, + short: bool, + } + + impl BackboneAccel for NeckFake { + fn forward(&self, _: &[f32]) -> std::result::Result, String> { + Ok(vec![0.5; FULL]) + } + fn device(&self) -> String { + "Fake GPU (Vulkan)".into() + } + fn runs_necks(&self) -> bool { + true + } + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> std::result::Result>, String> { + self.calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + assert_eq!((backbone.len(), backbone[0]), (FULL, 0.5)); + let mut levels: Vec> = (0..n).map(|i| vec![i as f32; neck::FPN * (tracker::LOW_RES >> i).pow(2)]).collect(); + if which == NeckKind::Detector { + if self.short { + levels[2].pop(); + } else { + levels[2][7] = f32::NAN; + } + } + Ok(levels) + } + } + + #[test] + fn neck_levels_come_from_the_accelerator_and_a_failing_neck_is_left_to_candle() { + for short in [true, false] { + let dir = empty_model(&format!("neck-{short}")); + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let fake = NeckFake { calls: calls.clone(), short }; + let m = Sam3::load_accelerated(&dir, Device::Cpu, move |_| Ok(Box::new(fake))).unwrap(); + let enc = m.encode(&[128; 4 * 3 * 3], 4, 3).unwrap(); + assert_eq!(m.heads_device(), "CPU; the necks on the GPU"); + let levels = m.accel_neck(NeckKind::Tracker, enc.backbone(), 3).unwrap().unwrap(); + for (i, (l, side)) in levels.iter().zip([288, 144, 72]).enumerate() { + assert_eq!(l.dims(), [1, neck::FPN, side, side]); + assert_eq!(l.flatten_all().unwrap().max(0).unwrap().to_scalar::().unwrap(), i as f32); + } + // a wrong level: candle's neck from then on, without asking again + assert!(m.accel_neck(NeckKind::Detector, enc.backbone(), 3).unwrap().is_none()); + assert!(m.accel_neck(NeckKind::Detector, enc.backbone(), 3).unwrap().is_none()); + assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 2); + assert_eq!(m.heads_device(), "CPU; the click neck on the GPU"); + // the other neck and the backbone stay on the accelerator + assert!(m.accel_neck(NeckKind::Tracker, enc.backbone(), 3).unwrap().is_some()); + assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 3); + assert!(m.accelerated()); + std::fs::remove_dir_all(dir).unwrap(); + } + } + + /// Fails as the GPU does once the app is closing (the backbone or, with a backbone of zeros, a neck). + struct Closing { + backbone: bool, + } + + impl BackboneAccel for Closing { + fn forward(&self, _: &[f32]) -> std::result::Result, String> { + if self.backbone { Err("LightCraft is closing".into()) } else { Ok(vec![0.0; FULL]) } + } + fn device(&self) -> String { + "Fake GPU (Vulkan)".into() + } + fn closing(&self) -> bool { + true + } + fn runs_necks(&self) -> bool { + true + } + fn neck(&self, _: NeckKind, _: &[f32], _: usize) -> std::result::Result>, String> { + Err("LightCraft is closing".into()) + } + } + + #[test] + fn closing_is_no_accelerator_failure_and_nothing_runs_in_candle() { + let dir = empty_model("closing"); + let m = Sam3::load_accelerated(&dir, Device::Cpu, with_closing(true)).unwrap(); + let e = m.encode(&[128; 4 * 3 * 3], 4, 3).err().unwrap(); + assert!(e.to_string().contains("LightCraft is closing"), "{e}"); + assert!(m.backbone.get().is_none(), "the candle backbone was never loaded"); + assert!(m.accelerated()); + assert_eq!((m.backbone_device().as_str(), m.backbone_fallback()), ("Fake GPU (Vulkan)", None)); + // a neck: the error, not candle's neck, and the accelerator keeps it + let m = Sam3::load_accelerated(&dir, Device::Cpu, with_closing(false)).unwrap(); + let enc = m.encode(&[128; 4 * 3 * 3], 4, 3).unwrap(); + for which in [NeckKind::Tracker, NeckKind::Detector] { + assert!(m.accel_neck(which, enc.backbone(), 3).is_err_and(|e| e.to_string().contains("closing")), "{which:?}"); + assert!(m.neck_levels(which, &enc).is_err_and(|e| e.to_string().contains("closing")), "{which:?}"); + } + assert_eq!(m.heads_device(), "CPU; the necks on the GPU"); + std::fs::remove_dir_all(dir).unwrap(); + } + + fn with_closing(backbone: bool) -> impl FnOnce(&WeightReader) -> std::result::Result, String> { + move |_| Ok(Box::new(Closing { backbone })) + } + + #[test] + fn a_failing_or_wrong_accelerator_is_dropped_for_candle() { + for (name, fake, why) in [ + ("fail", Fake { values: FULL, fill: 0.0, fail: true }, "device lost"), + ("short", Fake { values: 10, fill: 0.0, fail: false }, "returned 10 values"), + ("nan", Fake { values: FULL, fill: f32::NAN, fail: false }, "not numbers"), + ] { + let dir = empty_model(name); + let m = Sam3::load_accelerated(&dir, Device::Cpu, with(fake)).unwrap(); + // the candle backbone takes over (and fails here: the checkpoint is empty) + assert!(m.encode(&[128; 4 * 3 * 3], 4, 3).is_err(), "{name}"); + assert!(!m.accelerated(), "{name}"); + assert_eq!(m.backbone_device(), "CPU", "{name}"); + let fallback = m.backbone_fallback().unwrap(); + assert!(fallback.starts_with("Fake GPU (Vulkan) failed: ") && fallback.contains(why), "{name}: {fallback}"); + std::fs::remove_dir_all(dir).unwrap(); + } + } +} diff --git a/crates/segment/src/nn.rs b/crates/segment/src/nn.rs index 540196e5d8..3666d8c411 100644 --- a/crates/segment/src/nn.rs +++ b/crates/segment/src/nn.rs @@ -7,7 +7,7 @@ use candle_core::{D, DType, Device, Module, Tensor}; use candle_nn::{LayerNorm, Linear, VarBuilder}; -use crate::Result; +use crate::{Result, cpu}; /// `nn.LayerNorm(d)` (PyTorch's default eps). pub const TORCH_LN_EPS: f64 = 1e-5; @@ -149,15 +149,25 @@ impl DecoderMlp { Ok(Self { layers }) } + /// On the CPU the hidden layers' bias add and ReLU are fused ([`cpu::linear_act`]: the box bias's MLPs have + /// 200 · 72 rows of 256). pub fn forward(&self, x: &Tensor) -> Result { + let mut dims = x.dims().to_vec(); let mut x = x.clone(); for (i, l) in self.layers.iter().enumerate() { - x = l.forward(&x)?; - if i + 1 < self.layers.len() { - x = x.relu()?; - } + x = if i + 1 == self.layers.len() { + l.forward(&x)? + } else if x.device().is_cpu() { + cpu::linear_act(&x, l, false)? + } else { + l.forward(&x)?.relu()? + }; } - Ok(x) + // the fused layers return rows + if let Some(last) = dims.last_mut() { + *last = x.dim(D::Minus1)?; + } + Ok(x.reshape(dims)?) } } @@ -240,3 +250,29 @@ pub fn cxcywh_to_xyxy(b: &Tensor) -> Result { pub fn to_vec(t: &Tensor) -> Result> { Ok(t.to_dtype(DType::F32)?.flatten_all()?.to_vec1::()?) } + +#[cfg(test)] +mod tests { + use candle_core::{DType, Device}; + use candle_nn::VarMap; + + use super::*; + + #[test] + fn a_decoder_mlp_over_rows_matches_linear_per_batch() { + let vars = VarMap::new(); + let vb = VarBuilder::from_varmap(&vars, DType::F32, &Device::Cpu); + let mlp = DecoderMlp::new(2, 256, 8, 2, vb).unwrap(); + let x = Tensor::randn(0f32, 1.0, (200, 72, 2), &Device::Cpu).unwrap(); + let mut want = x.clone(); + for (i, l) in mlp.layers.iter().enumerate() { + want = l.forward(&want).unwrap(); + if i + 1 < mlp.layers.len() { + want = want.relu().unwrap(); + } + } + let got = mlp.forward(&x).unwrap(); + assert_eq!(got.dims(), [200, 72, 8]); + assert_eq!(got.flatten_all().unwrap().to_vec1::().unwrap(), want.flatten_all().unwrap().to_vec1::().unwrap()); + } +} diff --git a/crates/segment/tests/it/accel.rs b/crates/segment/tests/it/accel.rs new file mode 100644 index 0000000000..ad8dad3c11 --- /dev/null +++ b/crates/segment/tests/it/accel.rs @@ -0,0 +1,58 @@ +//! A backbone accelerator that fails leaves the work to candle, with the real checkpoint. +//! +//! Needs the model: `$LIGHTCRAFT_SAM3_DIR`, else the desktop app's folder (`~/.config/lightcraft/models/sam3` on +//! Linux). Skipped when it is missing. Runs the candle backbone once on the CPU (about half a minute in release). + +use std::path::PathBuf; + +use lightcraft_segment::{BackboneAccel, Device, Sam3, WeightReader}; + +fn model_dir() -> Option { + // only `$LIGHTCRAFT_SAM3_DIR`, as the GPU tests: never whatever is in the user's model folder + let dir = std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()).map(PathBuf::from)?; + lightcraft_segment::is_model_dir(&dir).then_some(dir) +} + +/// Fails on every photo, as a GPU that lost its device would. +struct Lost; + +impl BackboneAccel for Lost { + fn forward(&self, _: &[f32]) -> Result, String> { + Err("device lost".into()) + } + fn device(&self) -> String { + "Lost GPU (Vulkan)".into() + } +} + +#[test] +fn an_accelerator_failing_on_a_photo_falls_back_to_candle() { + let Some(dir) = model_dir() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let m = Sam3::load_accelerated(&dir, Device::Cpu, |_: &WeightReader| Ok(Box::new(Lost) as Box)).unwrap(); + assert!(m.accelerated()); + assert_eq!(m.backbone_device(), "Lost GPU (Vulkan)"); + let (w, h) = (64, 48); + let rgb: Vec = (0..w * h * 3).map(|i| (i % 251) as u8).collect(); + let enc = m.encode(&rgb, w, h).unwrap(); + assert_eq!(enc.backbone().dims(), [1, 1024, 72, 72]); + let v = enc.backbone().flatten_all().unwrap().to_vec1::().unwrap(); + assert!(v.iter().all(|x| x.is_finite()) && v.iter().any(|x| *x != 0.0), "candle computed the features"); + assert!(!m.accelerated()); + assert_eq!(m.backbone_device(), "CPU"); + assert_eq!(m.backbone_fallback().as_deref(), Some("Lost GPU (Vulkan) failed: device lost")); +} + +#[test] +fn an_accelerator_that_cannot_be_built_loads_candles_backbone() { + let Some(dir) = model_dir() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let m = Sam3::load_accelerated(&dir, Device::Cpu, |_| Err("no GPU adapter".into())).unwrap(); + assert!(!m.accelerated()); + assert_eq!(m.backbone_device(), "CPU"); + assert_eq!(m.backbone_fallback().as_deref(), Some("no GPU adapter")); +} diff --git a/crates/segment/tests/it/main.rs b/crates/segment/tests/it/main.rs index 4dcb685916..629ae5f085 100644 --- a/crates/segment/tests/it/main.rs +++ b/crates/segment/tests/it/main.rs @@ -1,4 +1,6 @@ //! The integration tests, one module per file, linked into one test binary. +mod accel; +mod prompts; mod reference; mod remote; diff --git a/crates/segment/tests/it/prompts.rs b/crates/segment/tests/it/prompts.rs new file mode 100644 index 0000000000..1ff14679e8 --- /dev/null +++ b/crates/segment/tests/it/prompts.rs @@ -0,0 +1,63 @@ +//! A text prompt seen before reuses its features, with the same detector output as the first time. +//! +//! Needs the model: `$LIGHTCRAFT_SAM3_DIR`, else the desktop app's folder (`~/.config/lightcraft/models/sam3` on +//! Linux). Skipped when it is missing. The backbone output is made up (no ViT run); the necks, the text encoder +//! and the detector are candle's on the CPU. + +use std::path::PathBuf; + +use candle_core::Tensor; +use lightcraft_segment::{BackboneAccel, DetectorOutput, Device, Sam3}; + +fn model_dir() -> Option { + // only `$LIGHTCRAFT_SAM3_DIR`, as the GPU tests: never whatever is in the user's model folder + let dir = std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()).map(PathBuf::from)?; + lightcraft_segment::is_model_dir(&dir).then_some(dir) +} + +/// A backbone output `[1024, 72, 72]` that varies over the channels and the grid. +struct Waves; + +impl BackboneAccel for Waves { + fn forward(&self, _: &[f32]) -> Result, String> { + Ok((0..1024 * 72 * 72).map(|i| (i as f32 * 0.37).sin() * 0.5).collect()) + } + fn device(&self) -> String { + "Waves (test)".into() + } +} + +fn values(t: &Tensor) -> Vec { + t.flatten_all().unwrap().to_vec1().unwrap() +} + +fn assert_same(a: &DetectorOutput, b: &DetectorOutput) { + assert_eq!(a.logits, b.logits); + assert_eq!(a.presence, b.presence); + assert_eq!(a.boxes, b.boxes); + assert_eq!(values(&a.text), values(&b.text)); + assert_eq!(values(&a.memory), values(&b.memory)); + assert_eq!(values(&a.masks), values(&b.masks)); +} + +#[test] +fn a_repeated_prompt_gives_the_same_output() { + let Some(dir) = model_dir() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let mut m = Sam3::load_accelerated(&dir, Device::Cpu, |_| Ok(Box::new(Waves) as Box)).unwrap(); + let (w, h) = (64, 48); + let rgb: Vec = (0..w * h * 3).map(|i| (i % 251) as u8).collect(); + let mut enc = m.encode(&rgb, w, h).unwrap(); + let fresh = m.detect(&mut enc, "person").unwrap(); + m.detect(&mut enc, "sky").unwrap(); + let cached = m.detect(&mut enc, "person").unwrap(); + assert_eq!(cached.text.id(), fresh.text.id(), "the prompt's features were reused"); + assert_same(&cached, &fresh); + // and on the next photo + let mut next = m.encode(&rgb, w, h).unwrap(); + let again = m.detect(&mut next, "person").unwrap(); + assert_eq!(again.text.id(), fresh.text.id()); + assert_same(&again, &fresh); +} diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 8a50d38f10..822688011d 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Přesunout do „{1}“ fotografie: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Přesunout do „{1}“ fotografie: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Procházení složek – složky: {folders}, soubory: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Do „{1}“ přesunuto fotografií: {n}{0:.0}. Úpravy → Zpět je vrátí." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Do „{1}“ přesunuto fotografií: {n}{0:.0}. Úpravy → Zpět je vrátí.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, kodér obrazu {encoder:.1} s" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index e3a98569fd..84a3efb7b2 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2394,5 +2394,13 @@ "End Slideshow": "Ukončit prezentaci", "Save Current Settings as New Effect Preset…": "Uložit aktuální nastavení jako nové přednastavení efektu…", "Manage Effect Presets…": "Spravovat přednastavení efektů…", - "Export Effect Presets…": "Exportovat přednastavení efektů…" + "Export Effect Presets…": "Exportovat přednastavení efektů…", + "AI masks": "AI masky", + "Device": "Zařízení", + "Last photo": "Poslední fotka", + "Remote worker": "Vzdálený proces", + "Run on": "Spouštět na", + "Automatic (GPU when available)": "Automaticky (GPU, je-li k dispozici)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Masky Objekt a Popsat analyzují každou fotku jednou, na grafické kartě, pokud není zvoleno CPU nebo vypnuto „Použít GPU pro vykreslování“. Na procesoru to trvá mnohem déle.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automaticky spouští model na grafické kartě Macu. Pokud tam AI masky selhávají, zvolte CPU; na procesoru trvají mnohem déle." } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index af29f7134e..109126c4de 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "{n} Foto{0} nach „{1}“ verschieben", "Move {n} photo{} to “{}”?": "{n} Foto{0} nach „{1}“ verschieben?", "Listing folders — folders: {folders}, files: {files}": "Ordner werden aufgelistet – Ordner: {folders}, Dateien: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} Foto{0} nach „{1}“ verschoben. Bearbeiten → Rückgängig holt sie zurück." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} Foto{0} nach „{1}“ verschoben. Bearbeiten → Rückgängig holt sie zurück.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, Bildencoder {encoder:.1} s" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 67a305ddf5..4184b529f5 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3422,5 +3422,13 @@ "favourites across restarts (issue #328).": "über Neustarts hinweg Favoriten (Issue #328).", "Optional remote SAM 3: keep the native editor local and run Object, Describe, and detail": "Optionales entferntes SAM 3: Der native Editor bleibt lokal, und Objekt-, Beschreibungs- und Detail-", "inference on a Mac through SSH. Saved masks still render and export offline.": "Inferenz laufen über SSH auf einem Mac. Gespeicherte Masken werden weiterhin offline gerendert und exportiert.", - "See [remote Metal inference](ai-masks.md#remote-metal-inference).": "Siehe [remote Metal inference](ai-masks.md#remote-metal-inference)." + "See [remote Metal inference](ai-masks.md#remote-metal-inference).": "Siehe [remote Metal inference](ai-masks.md#remote-metal-inference).", + "AI masks": "KI-Masken", + "Device": "Gerät", + "Last photo": "Letztes Foto", + "Remote worker": "Entfernter Worker", + "Run on": "Ausführen auf", + "Automatic (GPU when available)": "Automatisch (GPU, wenn vorhanden)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Objekt- und Beschreiben-Masken analysieren jedes Foto einmal, auf der Grafikkarte, außer CPU ist gewählt oder „GPU zum Rendern verwenden“ ist aus. Auf dem Prozessor dauert das deutlich länger.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatisch führt das Modell auf der Grafikkarte des Mac aus. Wählen Sie CPU, wenn KI-Masken dort scheitern; auf dem Prozessor dauern sie deutlich länger." } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index fd15401693..55ac68506e 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Mover {n} foto{0} a “{1}”", "Move {n} photo{} to “{}”?": "¿Mover {n} foto{0} a “{1}”?", "Listing folders — folders: {folders}, files: {files}": "Listando carpetas — carpetas: {folders}, archivos: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto{0} movida{0} a “{1}”. Editar → Deshacer las devuelve." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto{0} movida{0} a “{1}”. Editar → Deshacer las devuelve.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificador de imagen {encoder:.1} s" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 46965c7782..9a6ae2b299 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2342,5 +2342,13 @@ "Checking the GPU…": "Comprobando la GPU…", "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "Un modelo de caras usa la GPU solo cuando una comprobación muestra que da los mismos resultados más rápido.", - "Checking the GPU for faces": "Comprobando la GPU para las caras" + "Checking the GPU for faces": "Comprobando la GPU para las caras", + "AI masks": "Máscaras de IA", + "Device": "Dispositivo", + "Last photo": "Última foto", + "Remote worker": "Proceso remoto", + "Run on": "Ejecutar en", + "Automatic (GPU when available)": "Automático (GPU si la hay)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Las máscaras Objeto y Describir analizan cada foto una sola vez, en la tarjeta gráfica salvo que se elija CPU o «Usar la GPU para renderizar» esté desactivado. En el procesador tarda mucho más.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automático ejecuta el modelo en la tarjeta gráfica del Mac. Elige CPU si las máscaras de IA fallan allí; en el procesador tardan mucho más." } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 698080e10d..78025df6b5 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "”{to}” on jo henkilö. Yhdistäminen tekee kahdesta yhden henkilön; Kumoa erottaa ne uudelleen.", "• {assumption}": "• {assumption}", "… and {more} more": "… ja {more} lisää", - "…and {more} more": "…ja {more} lisää" + "…and {more} more": "…ja {more} lisää", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, kuvakooderi {encoder:.1} s" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index ff1707ac7a..aadff2f442 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2311,5 +2311,13 @@ "− harder border · + softer border": "− terävämpi reuna · + pehmeämpi reuna", "≤ at most": "≤ enintään", "≥ at least": "≥ vähintään", - "★ Favorites": "★ Suosikit" + "★ Favorites": "★ Suosikit", + "AI masks": "Tekoälymaskit", + "Device": "Laite", + "Last photo": "Viimeisin kuva", + "Remote worker": "Etätyöskentelijä", + "Run on": "Suorita", + "Automatic (GPU when available)": "Automaattinen (GPU, jos saatavilla)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Kohde- ja Kuvaile-maskit analysoivat jokaisen kuvan kerran, näytönohjaimella, ellei Suoritin ole valittuna tai ”Käytä GPU:ta renderöintiin” ole pois päältä. Suorittimella se kestää paljon kauemmin.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automaattinen suorittaa mallin Macin näytönohjaimella. Valitse Suoritin, jos tekoälymaskit epäonnistuvat siellä; suorittimella ne kestävät paljon kauemmin." } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index ae2b778725..566a24c37b 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Déplacer {n} photo{} vers « {} »", "Move {n} photo{} to “{}”?": "Déplacer {n} photo{} vers « {} » ?", "Listing folders — folders: {folders}, files: {files}": "Liste des dossiers — dossiers : {folders}, fichiers : {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} photo{} déplacée(s) vers « {} ». Modifier → Annuler les remet en place." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} photo{} déplacée(s) vers « {} ». Modifier → Annuler les remet en place.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, encodeur d’image {encoder:.1} s" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 2f22a70c1c..47f2f6025f 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -2340,5 +2340,13 @@ "Checking the GPU…": "Vérification du GPU…", "CPU": "Processeur", "A face model uses the GPU only when a check shows it gives the same results faster.": "Un modèle de visages n’utilise le GPU que si une vérification montre qu’il donne les mêmes résultats plus vite.", - "Checking the GPU for faces": "Vérification du GPU pour les visages" + "Checking the GPU for faces": "Vérification du GPU pour les visages", + "AI masks": "Masques IA", + "Device": "Appareil", + "Last photo": "Dernière photo", + "Remote worker": "Processus distant", + "Run on": "Exécuter sur", + "Automatic (GPU when available)": "Automatique (GPU si disponible)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Les masques Objet et Décrire analysent chaque photo une fois, sur la carte graphique sauf si Processeur est choisi ou si « Utiliser le GPU pour le rendu » est désactivé. Sur le processeur, c’est beaucoup plus long.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatique exécute le modèle sur la carte graphique du Mac. Choisissez Processeur si les masques IA y échouent ; sur le processeur, ils sont beaucoup plus longs." } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index b3887f9174..0072148c1f 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -297,5 +297,6 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "Hasil penggabungan {what} ditambahkan dengan resolusi {mp}: resolusi penuhnya ({full}) memerlukan memori melebihi kapasitas komputer ini", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Hasil penggabungan {what} ditambahkan dengan resolusi {mp}, resolusi maksimum untuk panorama (resolusi penuhnya {full})", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", - "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}" + "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} dtk, penyandi gambar {encoder:.1} dtk" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index aefe04417a..17d698afab 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2325,5 +2325,13 @@ "≤ at most": "≤ maksimal", "≥ at least": "≥ minimal", "日本語": "日本語", - "繁體中文(台灣)": "繁體中文(台灣)" + "繁體中文(台灣)": "繁體中文(台灣)", + "AI masks": "Masker AI", + "Device": "Perangkat", + "Last photo": "Foto terakhir", + "Remote worker": "Worker jarak jauh", + "Run on": "Jalankan di", + "Automatic (GPU when available)": "Otomatis (GPU jika tersedia)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Masker Objek dan Deskripsikan menganalisis setiap foto sekali, di kartu grafis kecuali CPU dipilih atau “Gunakan GPU untuk rendering” dimatikan. Di prosesor hal itu jauh lebih lama.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Otomatis menjalankan model di kartu grafis Mac. Pilih CPU jika masker AI gagal di sana; di prosesor prosesnya jauh lebih lama." } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index ccd01e6a71..778c4568c9 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Sposta foto in “{1}” ({n}){0:.0}", "Move {n} photo{} to “{}”?": "Spostare le foto in “{1}” ({n})?{0:.0}", "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Foto spostate in “{1}”: {n}{0:.0}. Modifica → Annulla le riporta indietro.", - "Listing folders — folders: {folders}, files: {files}": "Elenco delle cartelle — cartelle: {folders}, file: {files}" + "Listing folders — folders: {folders}, files: {files}": "Elenco delle cartelle — cartelle: {folders}, file: {files}", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificatore d’immagine {encoder:.1} s" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index a638c14820..00035165d4 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2344,7 +2344,14 @@ "Loupe Info 1": "Info lente 1", "Loupe Info 2": "Info lente 2", "Use Defaults": "Usa predefiniti", - "Dimensions": "Dimensioni", "Camera & Lens": "Fotocamera e obiettivo", - "View → View Options chooses the lines Info 1 and Info 2 show.": "Visualizza → Opzioni di visualizzazione sceglie le righe di Info 1 e Info 2." + "View → View Options chooses the lines Info 1 and Info 2 show.": "Visualizza → Opzioni di visualizzazione sceglie le righe di Info 1 e Info 2.", + "AI masks": "Maschere IA", + "Device": "Dispositivo", + "Last photo": "Ultima foto", + "Remote worker": "Processo remoto", + "Run on": "Esegui su", + "Automatic (GPU when available)": "Automatico (GPU se disponibile)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Le maschere Oggetto e Descrivi analizzano ogni foto una volta, sulla scheda grafica a meno che sia scelta la CPU o «Usa la GPU per il rendering» sia disattivato. Sul processore richiede molto più tempo.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatico esegue il modello sulla scheda grafica del Mac. Scegli CPU se lì le maschere IA non funzionano; sul processore richiedono molto più tempo." } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index ce56500b5e..5f2e86b59b 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "「{to}」はすでに別の人物です。まとめると1人になり、元に戻すと再び分かれます。", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what}合成を{mp}で追加しました:フルサイズ({full})にはこのコンピューターのメモリが足りません", "Listing folders — folders: {folders}, files: {files}": "フォルダーを一覧中 — フォルダー:{folders}、ファイル:{files}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}合成を{mp}で追加しました。パノラマの最大サイズです(フルサイズ:{full})" + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}合成を{mp}で追加しました。パノラマの最大サイズです(フルサイズ:{full})", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒(画像エンコーダー {encoder:.1} 秒)" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 4c55ee4947..794cc0539e 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2342,5 +2342,13 @@ "Checking the GPU…": "GPU を確認中…", "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "顔モデルが GPU を使うのは、同じ結果をより速く出せると確認できた場合だけです。", - "Checking the GPU for faces": "顔用の GPU を確認中" + "Checking the GPU for faces": "顔用の GPU を確認中", + "AI masks": "AIマスク", + "Device": "デバイス", + "Last photo": "直前の写真", + "Remote worker": "リモートワーカー", + "Run on": "実行先", + "Automatic (GPU when available)": "自動(GPUがあれば使用)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "オブジェクトと説明で選択のマスクは、写真ごとに一度だけ解析します。CPUを選んだ場合や「描画にGPUを使用」がオフの場合を除き、グラフィックカードで行います。処理装置ではかなり時間がかかります。", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "自動ではMacのグラフィックカードでモデルを実行します。そこでAIマスクが失敗する場合はCPUを選んでください。処理装置ではかなり時間がかかります。" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index c3b48ef626..5c6ea7c16a 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Move {n} photo{} to “{}”", "Move {n} photo{} to “{}”?": "Move {n} photo{} to “{}”?", "Listing folders — folders: {folders}, files: {files}": "საქაღალდეების ჩამოთვლა — საქაღალდეები: {folders}, ფაილები: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} წმ, გამოსახულების ენკოდერი {encoder:.1} წმ" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 066f2ecd25..190df90630 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -86,6 +86,7 @@ "AI Denoise needs a model. Install one in Settings.": "AI ხმაურის მოცილებას მოდელი სჭირდება. დააინსტალირეთ პარამეტრებში.", "AI Mask Model Status": "AI ნიღბების მოდელის მდგომარეობა", "AI RAW denoise": "RAW-ის AI ხმაურის მოცილება", + "AI masks": "AI ნიღბები", "AI masks with SAM 3 (Object and Describe in the Masking panel): click an object to select it (⌥-click leaves a": "AI ნიღბები SAM 3-ით (ობიექტი და აღწერა ნიღბვის პანელში): დაწკაპეთ ობიექტზე მის მოსანიშნად (⌥-დაწკაპუნება ტოვებს", "ARW) gives the merged DNG the colour each photo has when opened alone (issue #965). An HDR merge of CR2s used to come": "ARW) ფოტოების გაერთიანება გაერთიანებულ DNG-ს აძლევს იმ ფერს, რომელიც თითო ფოტოს ცალკე გახსნისას აქვს (ხარვეზი #965). CR2-ების HDR გაერთიანება ადრე", "About": "პროგრამის შესახებ", @@ -229,7 +230,9 @@ "Auto-Tag from Tracklog: GPS locations for your photos from a GPX track log, matched by capture time.": "მდებარეობის მინიჭება მარშრუტის ჟურნალიდან: GPS მდებარეობები თქვენი ფოტოებისთვის GPX მარშრუტის ჟურნალიდან, გადაღების დროის მიხედვით.", "Auto-Tag from Tracklog…": "მდებარეობის მინიჭება მარშრუტის ჟურნალიდან…", "Automatic": "ავტომატური", + "Automatic (GPU when available)": "ავტომატური (GPU, თუ არის)", "Automatic renders the Detail view at the size it is shown, up to the photo's own pixels. Choose a size to cap it: smaller is faster.": "ავტომატური რეჟიმი დეტალურ ხედს ასახავს იმ ზომით, რომლითაც ის ჩანს, ფოტოს საკუთარ პიქსელებამდე. ზღვრისთვის აირჩიეთ ზომა: პატარა უფრო სწრაფია.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "ავტომატური რეჟიმი მოდელს Mac-ის ვიდეობარათზე უშვებს. აირჩიეთ CPU, თუ AI ნიღბები იქ ვერ მუშაობს; პროცესორზე ისინი გაცილებით დიდხანს გრძელდება.", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "ავტომატური რეჟიმი იყენებს ვიდეობარათს, როცა ის პროცესორზე სწრაფია: ორივეს დრო ამ კომპიუტერზე იზომება, როცა ფოტო პირველად მზადდება.", "Automatically Write Changes into XMP": "ცვლილებების XMP-ში ავტომატურად ჩაწერა", "Automatically write changes into XMP sidecars": "ცვლილებების XMP თანმხლებ ფაილებში ავტომატურად ჩაწერა", @@ -296,6 +299,7 @@ "By day (YYYY/YYYY-MM-DD)": "დღის მიხედვით (YYYY/YYYY-MM-DD)", "By month (YYYY/YYYY-MM)": "თვის მიხედვით (YYYY/YYYY-MM)", "C-RAWs imported earlier, Photo ▸ Reload from Disk picks up the raw data.": "R7 C-RAW-ებისთვის ფოტო → დისკიდან ხელახლა ჩატვირთვა RAW მონაცემებს წაიკითხავს.", + "CPU": "CPU", "CPU threads": "CPU ნაკადები", "Cache": "ქეში", "Calibration": "კალიბრაცია", @@ -597,6 +601,7 @@ "Detect Faces": "სახეების ამოცნობა", "Detect Faces (Photo menu) needs it: a small one-time download.": "სახეების ამოცნობას (მენიუ „ფოტო“) ეს სჭირდება: მცირე, ერთჯერადი ჩამოტვირთვა.", "Develop": "დამუშავება", + "Device": "მოწყობილობა", "Diagonal": "დიაგონალური", "Dialogs": "დიალოგები", "Dialogs fit the window": "დიალოგები ფანჯარაში ეტევა", @@ -1085,6 +1090,7 @@ "Last GPU fallback": "GPU-დან ბოლო გადართვა", "Last commit": "ბოლო კომიტი", "Last loupe render": "ლუპის ბოლო რენდერი", + "Last photo": "ბოლო ფოტო", "Last view": "ბოლო ხედი", "Lateral Chromatic Aberration": "განივი ქრომატული აბერაცია", "Layer": "შრე", @@ -1368,6 +1374,7 @@ "None": "არცერთი", "None (the display is treated as sRGB)": "არცერთი (ეკრანი sRGB-ად ითვლება)", "Not Now": "ახლა არა", + "Not loaded yet": "ჯერ არ ჩატვირთულა", "Not saved": "არ არის შენახული", "Nothing already edited changes: a Custom white balance set on the old relative scale renders pixel for pixel as": "არაფერი უკვე დამუშავებული არ იცვლება: ძველ ფარდობით შკალაზე დაყენებული მორგებული თეთრის ბალანსი პიქსელ-პიქსელ ისევე რენდერდება, როგორც", "Nothing is fetched until you accept. The model is kept on this computer only; LightCraft never uploads or shares it.": "თქვენს თანხმობამდე არაფერი ჩამოიტვირთება. მოდელი მხოლოდ ამ კომპიუტერზე ინახება; LightCraft მას არასოდეს ატვირთავს და არავის უზიარებს.", @@ -1378,6 +1385,7 @@ "ONNX model": "ONNX მოდელი", "Object": "ობიექტი", "Object Mask": "ობიექტის ნიღაბი", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "ობიექტისა და აღწერის ნიღბები თითო ფოტოს ერთხელ აანალიზებს, ვიდეობარათზე, თუ CPU არ არის არჩეული და „რენდერირებისთვის GPU-ის გამოყენება“ გამორთული არ არის. პროცესორზე ეს გაცილებით დიდხანს გრძელდება.", "Object and Describe masks use SAM 3, Meta's segmentation model. It isn't part of LightCraft, and everything else works without it.": "ნიღბები „ობიექტი“ და „აღწერა“ იყენებს SAM 3-ს, Meta-ს სეგმენტაციის მოდელს. ის LightCraft-ის ნაწილი არ არის და ყველაფერი დანარჩენი მის გარეშეც მუშაობს.", "October 2026": "ოქტომბერი 2026", "Off": "გამორთული", @@ -1663,6 +1671,7 @@ "Relinked": "ხელახლა დაკავშირებულია", "Reload Changed Files": "შეცვლილი ფაილების ხელახლა ჩატვირთვა", "Reload from Disk": "დისკიდან ხელახლა ჩატვირთვა", + "Remote worker": "დისტანციური დამმუშავებელი", "Remove": "მოშორება", "Remove (H)": "მოშორება (H)", "Remove CA": "ქრომატული აბერაციის მოცილება", @@ -1766,6 +1775,7 @@ "Rule problems are shown in your language and name the field the way the menu does (\"Title: needs something to look": "წესების პრობლემები ნაჩვენებია თქვენს ენაზე და ველს ისე ასახელებს, როგორც მენიუ („დასახელება: საჭიროა საძიებო", "Rule values are checked: a rating of 9, a date like 2026-13 or \"banana\", a \"between\" whose dates are the wrong": "წესების მნიშვნელობები მოწმდება: შეფასება 9, თარიღი, როგორიცაა 2026-13 ან „banana“, „შორის“, რომლის თარიღებიც არასწორი", "Rules": "წესები", + "Run on": "გაშვება", "SAM 3 download stopped: it resumes where it left off next time.": "SAM 3-ის ჩამოტვირთვა შეწყდა: შემდეგ ჯერზე იქიდან გაგრძელდება, სადაც შეჩერდა.", "SDR": "SDR", "SDR Brightness": "SDR სიკაშკაშე", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index e3ce316a0d..7791c4f840 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Przenieś do „{1}” — zdjęcia: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Przenieść do „{1}” — zdjęcia: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Przeglądanie folderów — foldery: {folders}, pliki: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Przeniesiono do „{1}” — zdjęcia: {n}{0:.0}. Edytuj → Cofnij przywróci je." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Przeniesiono do „{1}” — zdjęcia: {n}{0:.0}. Edytuj → Cofnij przywróci je.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, koder obrazu {encoder:.1} s" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index aba88ef445..dad3624832 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2269,5 +2269,15 @@ "SDR Shadows": "Cienie SDR", "SDR Whites": "Biele SDR", "SDR Clarity": "Przejrzystość SDR", - "Face Models on the GPU": "Modele twarzy przetwarzane na GPU" + "Face Models on the GPU": "Modele twarzy przetwarzane na GPU", + "AI masks": "Maski AI", + "Device": "Urządzenie", + "Last photo": "Ostatnie zdjęcie", + "Remote worker": "Zdalny proces", + "Not loaded yet": "Jeszcze nie wczytano", + "Run on": "Uruchamiaj na", + "Automatic (GPU when available)": "Automatycznie (GPU, gdy jest)", + "CPU": "CPU", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Maski Obiekt i Opisz analizują każde zdjęcie raz, na karcie graficznej, chyba że wybrano CPU albo opcja „Użyj procesora graficznego do renderowania” jest wyłączona. Na procesorze trwa to znacznie dłużej.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatycznie uruchamia model na karcie graficznej Maca. Wybierz CPU, jeśli maski AI tam zawodzą; na procesorze trwa to znacznie dłużej." } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index bab81a3688..facb052cb1 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "“{to}” já é uma pessoa. Combiná-las deixa uma só; Desfazer as separa de novo.", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what} mesclagem adicionada em {mp}: o tamanho completo, {full}, precisa de mais memória do que este computador tem", "Listing folders — folders: {folders}, files: {files}": "Listando pastas — pastas: {folders}, arquivos: {files}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what} mesclagem adicionada em {mp}, o maior tamanho possível para um panorama (tamanho completo: {full})" + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what} mesclagem adicionada em {mp}, o maior tamanho possível para um panorama (tamanho completo: {full})", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificador de imagem {encoder:.1} s" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 5b4ae44096..e6e41243ac 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2188,5 +2188,13 @@ "Color Overlay on B&W": "Sobreposição de cor em P&B", "Image on Black": "Imagem sobre preto", "Image on White": "Imagem sobre branco", - "White on Black": "Branco sobre preto" + "White on Black": "Branco sobre preto", + "AI masks": "Máscaras de IA", + "Device": "Dispositivo", + "Last photo": "Última foto", + "Remote worker": "Processo remoto", + "Run on": "Executar em", + "Automatic (GPU when available)": "Automático (GPU quando houver)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "As máscaras Objeto e Descrever analisam cada foto uma vez, na placa de vídeo, a menos que CPU esteja escolhida ou “Usar a GPU para renderização” esteja desligado. No processador isso demora muito mais.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automático executa o modelo na placa de vídeo do Mac. Escolha CPU se as máscaras de IA falharem nela; no processador elas demoram muito mais." } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 1efc30268e..2299b498ad 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Переместить в «{1}» фото: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Переместить в «{1}» фото: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Просмотр папок — папок: {folders}, файлов: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "В «{1}» перемещено фото: {n}{0:.0}. Правка → Отменить вернёт их." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "В «{1}» перемещено фото: {n}{0:.0}. Правка → Отменить вернёт их.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} с, кодировщик изображения {encoder:.1} с" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index bf191bb515..744bc0ce55 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2335,5 +2335,13 @@ "Checking the GPU…": "Проверка ГП…", "CPU": "ЦП", "A face model uses the GPU only when a check shows it gives the same results faster.": "Модель лиц использует ГП, только если проверка показала, что он даёт те же результаты быстрее.", - "Checking the GPU for faces": "Проверка ГП для лиц" + "Checking the GPU for faces": "Проверка ГП для лиц", + "AI masks": "ИИ-маски", + "Device": "Устройство", + "Last photo": "Последнее фото", + "Remote worker": "Удалённый обработчик", + "Run on": "Выполнять на", + "Automatic (GPU when available)": "Автоматически (GPU, если есть)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Маски «Объект» и «Описать» анализируют каждое фото один раз — на видеокарте, если не выбран ЦП и не выключено «Использовать GPU для рендеринга». На процессоре это намного дольше.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "«Автоматически» запускает модель на видеокарте Mac. Если ИИ-маски там не работают, выберите ЦП; на процессоре они намного дольше." } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 50e3fa4be0..ca8350cc57 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -297,5 +297,6 @@ "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", "{n} selected photos · {pages} pages": "{n} selected photos · {pages} pages", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", - "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}" + "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, bildkodare {encoder:.1} s" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 76f08c2d38..00bcb9f599 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2414,5 +2414,13 @@ "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-dra för att räta upp, ⇧G guidad upprätning, ett rutnät under transformering.", "★ Favorites": "★ Favoriter", "日本語": "日本語", - "繁體中文(台灣)": "繁體中文(台灣)" + "繁體中文(台灣)": "繁體中文(台灣)", + "AI masks": "AI-masker", + "Device": "Enhet", + "Last photo": "Senaste foto", + "Remote worker": "Fjärrarbetare", + "Run on": "Kör på", + "Automatic (GPU when available)": "Automatisk (GPU när den finns)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Objekt- och Beskriv-masker analyserar varje foto en gång, på grafikkortet om inte CPU är vald eller ”Använd GPU:n för rendering” är av. På processorn tar det mycket längre tid.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatisk kör modellen på Macens grafikkort. Välj CPU om AI-masker misslyckas där; på processorn tar de mycket längre tid." } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 0ada44e080..f960122d27 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Перемістити до «{1}» фото: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Перемістити до «{1}» фото: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Перегляд тек — тек: {folders}, файлів: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "До «{1}» переміщено фото: {n}{0:.0}. Редагування → Скасувати поверне їх." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "До «{1}» переміщено фото: {n}{0:.0}. Редагування → Скасувати поверне їх.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} с, кодувальник зображення {encoder:.1} с" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 4dff39f784..0628803bcd 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2340,5 +2340,13 @@ "Checking the GPU…": "Перевірка ГП…", "CPU": "ЦП", "A face model uses the GPU only when a check shows it gives the same results faster.": "Модель облич використовує ГП, лише якщо перевірка показала, що він дає ті самі результати швидше.", - "Checking the GPU for faces": "Перевірка ГП для облич" + "Checking the GPU for faces": "Перевірка ГП для облич", + "AI masks": "ШІ-маски", + "Device": "Пристрій", + "Last photo": "Останнє фото", + "Remote worker": "Віддалений обробник", + "Run on": "Виконувати на", + "Automatic (GPU when available)": "Автоматично (ГП, якщо є)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Маски «Об’єкт» і «Описати» аналізують кожне фото один раз — на відеокарті, якщо не вибрано ЦП і не вимкнено «Використовувати ГП для рендерингу». На процесорі це значно довше.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "«Автоматично» запускає модель на відеокарті Mac. Якщо ШІ-маски там не працюють, виберіть ЦП; на процесорі вони значно довші." } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index 9ff8ed6b99..c627d80df2 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "“{to}” is already a person. Combining them makes one person; Undo separates them again.", "• {assumption}": "• {assumption}", "… and {more} more": "… và {more} nữa", - "…and {more} more": "…and {more} more" + "…and {more} more": "…và {more} nữa", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} giây, bộ mã hóa ảnh {encoder:.1} giây" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 6908be70e1..d752190a82 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2220,5 +2220,13 @@ "≥ at least": "≥ tối thiểu", "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-kéo để chỉnh thẳng, ⇧G Chỉnh thẳng có hướng dẫn, lưới khi biến đổi.", "日本語": "日本語", - "繁體中文(台灣)": "繁體中文(台灣)" + "繁體中文(台灣)": "繁體中文(台灣)", + "AI masks": "Mặt nạ AI", + "Device": "Thiết bị", + "Last photo": "Ảnh gần nhất", + "Remote worker": "Worker từ xa", + "Run on": "Chạy trên", + "Automatic (GPU when available)": "Tự động (GPU nếu có)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Mặt nạ Đối tượng và Mô tả phân tích mỗi ảnh một lần, trên card đồ họa trừ khi chọn CPU hoặc tắt “Dùng GPU để kết xuất”. Trên bộ xử lý việc này lâu hơn nhiều.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Tự động chạy mô hình trên card đồ họa của máy Mac. Hãy chọn CPU nếu mặt nạ AI bị lỗi ở đó; trên bộ xử lý chúng chạy lâu hơn nhiều." } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index a28b07d2c8..e6688a8fb7 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "“{to}”已经是另一个人。合并后成为一个人;撤销会再把他们分开。", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "已添加 {what} 合并({mp}):完整尺寸({full})所需的内存超出了这台电脑的内存", "Listing folders — folders: {folders}, files: {files}": "正在列出文件夹 — 文件夹:{folders},文件:{files}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "已添加 {what} 合并({mp}),这是全景图的最大尺寸(完整尺寸:{full})" + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "已添加 {what} 合并({mp}),这是全景图的最大尺寸(完整尺寸:{full})", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒,图像编码器 {encoder:.1} 秒" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 4a2ebaa7b1..633147d336 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2186,5 +2186,13 @@ "Suggests who is in a photo from the faces you have named. Everything stays on your computer.": "根据你已命名的人脸,推测照片中的人物。所有数据仅保存在本机。", "This build cannot run recognition models: they can be added and chosen, not used.": "此版本无法运行识别模型:可以添加和选择,但无法使用。", "Detect Faces (Photo menu) needs it: a small one-time download.": "“检测人脸”(照片菜单)依赖它:一次性小文件下载。", - "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "此版本无法存放人脸模型,因此模型列表不可用。(桌面版可以存放。)" + "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "此版本无法存放人脸模型,因此模型列表不可用。(桌面版可以存放。)", + "AI masks": "AI 蒙版", + "Device": "设备", + "Last photo": "上一张照片", + "Remote worker": "远程工作进程", + "Run on": "运行位置", + "Automatic (GPU when available)": "自动(有 GPU 时使用)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "“对象”和“描述”蒙版对每张照片只分析一次;除非选择了 CPU 或关闭了“使用 GPU 渲染”,否则在显卡上进行。在处理器上分析要慢得多。", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "“自动”会在 Mac 的显卡上运行模型。如果 AI 蒙版在那里失败,请选择 CPU;在处理器上会慢得多。" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 1192722251..7eca03bbd6 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "「{to}」已經是另一個人。合併後成為一個人;還原會再把他們分開。", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "已新增{what}合併照片({mp}):完整尺寸({full})所需的記憶體超過這台電腦的記憶體", "Listing folders — folders: {folders}, files: {files}": "正在列出資料夾 — 資料夾:{folders},檔案:{files}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "已新增{what}合併照片({mp}),這是全景圖的最大尺寸(完整尺寸:{full})" + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "已新增{what}合併照片({mp}),這是全景圖的最大尺寸(完整尺寸:{full})", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒,影像編碼器 {encoder:.1} 秒" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 78d8851285..961d83505e 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2143,5 +2143,13 @@ "Checking the GPU…": "正在檢查 GPU…", "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "只有在檢查顯示 GPU 能更快得出相同結果時,臉孔模型才會使用 GPU。", - "Checking the GPU for faces": "正在檢查用於臉孔的 GPU" + "Checking the GPU for faces": "正在檢查用於臉孔的 GPU", + "AI masks": "AI 遮色片", + "Device": "裝置", + "Last photo": "上一張照片", + "Remote worker": "遠端工作程序", + "Run on": "執行位置", + "Automatic (GPU when available)": "自動(有 GPU 時使用)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "「物件」和「描述」遮色片對每張照片只分析一次;除非選擇了 CPU 或關閉了「使用 GPU 算繪」,否則在顯示卡上進行。在處理器上分析要慢得多。", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "「自動」會在 Mac 的顯示卡上執行模型。如果 AI 遮色片在那裡失敗,請選擇 CPU;在處理器上會慢得多。" } diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs index 2f844f4ae9..66df3e719b 100644 --- a/crates/ui-egui/src/panels/settings.rs +++ b/crates/ui-egui/src/panels/settings.rs @@ -1,5 +1,5 @@ -//! The Settings dialog (⌘,): General, Import, Performance, Display, Interface, Slideshow, Faces, -//! AI Denoise. +//! The Settings dialog (⌘,): General, Import, Performance (incl. where AI masks run), Display, +//! Interface, Slideshow, Faces, AI Denoise. //! //! Changes apply immediately (no OK/Cancel). Where they are stored: //! - **app settings** ([`crate::state::AppSettings`]: startup view, delete confirmation, GPU, @@ -485,6 +485,59 @@ fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { ); #[cfg(not(target_arch = "wasm32"))] smart_previews(app, ui, t); + ai_masks(app, ui, t); +} + +/// Where AI masks (SAM 3) run: the choice (`segment.settings {runOn}`), what they run on, why not on +/// the GPU, and how long the last photo took (`segment.model.status` → `backend`), as Settings ▸ +/// Faces shows its models' processor. The same lines whatever the state, so nothing moves when the +/// model loads. +fn ai_masks(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + if !lightcraft_engine::segment::Segmenter::AVAILABLE { + return; + } + heading(ui, t, crate::i18n::tr("AI masks")); + let current = app.session.segmenter.run_on().name(); + let mut run_on = current; + if row(ui, t, "Run on", |ui| choices(ui, "settingsAiMasksRunOn", &[("auto", "Automatic (GPU when available)"), ("cpu", "CPU")], &mut run_on)) + && let Err(e) = app.run("segment.settings", json!({"runOn": run_on})) + { + app.toast(ui.ctx(), e); + } + let g = &app.session.segmenter; + let b = g.backend(); + let device = if g.remote_endpoint().is_some() { + crate::i18n::tr("Remote worker").to_string() + } else { + b["device"].as_str().map_or_else(|| crate::i18n::tr("Not loaded yet").to_string(), str::to_string) + }; + let text = match b["fallback"].as_str() { + Some(why) if g.remote_endpoint().is_none() => format!("{device} ({why})"), + _ => device, + }; + row(ui, t, "Device", |ui| { + let r = ui.add(egui::Label::new(RichText::new(text.clone()).color(t.text)).truncate()).on_hover_text(text); + register(ui.ctx(), "settings:aiMasksDevice", r.rect); + }); + let took = match (b["analyzeMs"].as_u64().or(b["encodeMs"].as_u64()), b["encodeMs"].as_u64()) { + (Some(all), Some(encoder)) => { + crate::i18n::tr_format!("{all:.1} s, image encoder {encoder:.1} s", all = all as f64 / 1000.0, encoder = encoder as f64 / 1000.0) + } + _ => "—".to_string(), + }; + row(ui, t, "Last photo", |ui| { + let r = ui.label(RichText::new(took).color(t.text)); + register(ui.ctx(), "settings:aiMasksTime", r.rect); + }); + hint( + ui, + t, + crate::i18n::tr(if cfg!(target_os = "macos") { + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer." + } else { + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer." + }), + ); } /// Where this library keeps its smart previews (the offline-editing proxies, which can be large): diff --git a/crates/ui-egui/src/tests_dialog_fit.rs b/crates/ui-egui/src/tests_dialog_fit.rs index 52d4128294..3d11c260fa 100644 --- a/crates/ui-egui/src/tests_dialog_fit.rs +++ b/crates/ui-egui/src/tests_dialog_fit.rs @@ -158,3 +158,40 @@ fn gpu_status_never_moves_the_performance_controls() { let first = seen[0].1; assert!(seen.iter().all(|(_, r, _)| *r == first), "the memory buttons moved: {seen:?}"); } + +/// Settings ▸ Performance says where AI masks run and how long the last photo took (issue #932): before the model +/// loads, its two lines are there all the same, at the end of the tab, so nothing above them moves when it loads. +#[test] +fn performance_tab_shows_where_ai_masks_run() { + let mut h = demo([1300.0, 820.0]); + let r = h.request("ui.key", json!({"key": ",", "cmd": true}), T); + assert_eq!(r["ok"], true, "{r}"); + let r = h.request("ui.clickWidget", json!({"id": "button:settingsTab-performance"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + let has = |h: &Headless, id: &str| h.app.widgets.iter().any(|(w, _)| w == id); + if !lightcraft_engine::segment::Segmenter::AVAILABLE { + assert!(!has(&h, "settings:aiMasksDevice"), "a build without AI masks says nothing about them"); + return; + } + let (device, time) = (rect(&h, "settings:aiMasksDevice"), rect(&h, "settings:aiMasksTime")); + assert!(device.bottom() <= time.top() + 1.0, "the device line comes first: {device:?} {time:?}"); + let choice = rect(&h, "button:settingsAiMasksRunOn-1"); + assert!(choice.bottom() <= device.top() + 1.0, "the choice of where they run comes first: {choice:?} {device:?}"); + assert!(rect(&h, "button:settingsMemory-2").bottom() < choice.top(), "after the other performance settings"); + let b = h.app.session.segmenter.backend(); + assert!(b["device"].is_null() && b["encodeMs"].is_null(), "nothing loaded or timed yet: {b}"); + // CPU, then Automatic again: the choice applies at once, and nothing moves + use lightcraft_engine::segment::{CPU_CHOSEN, RunOn}; + for (button, want) in [("button:settingsAiMasksRunOn-1", RunOn::Cpu), ("button:settingsAiMasksRunOn-0", RunOn::Auto)] { + let r = h.request("ui.clickWidget", json!({"id": button}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); + assert_eq!(h.app.session.segmenter.run_on(), want); + let fallback = h.app.session.segmenter.backend()["fallback"].clone(); + assert_eq!(fallback == CPU_CHOSEN, want == RunOn::Cpu, "{fallback}"); + // (its text says why it runs on the CPU now, so only its width changes) + assert_eq!(rect(&h, "settings:aiMasksDevice").min, device.min, "the device line stays put"); + } +} From d653132a250c9884d8209bbfec4d1615b9f45ae9 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:52:41 +0200 Subject: [PATCH 033/331] M12: SAM 3 image encoder on the GPU (wgpu): shared kernels and the 32-layer ViT Part 2 of 5 of #2167. lightcraft-gpu gets a `sam` feature with `sam3`: a device of its own (like denoise and faces, with the same switches, the crash sentinel and the shutdown gate), the shared kernels (tiled matrix products with bias / GELU / residual in the epilogue, flash-style attention, layer norm, RoPE, im2col, the final reorder) and the image encoder built from them. The engine now uses it as the GPU backbone where candle has no GPU (not macOS); the necks and the text detector's heads stay in candle. An adapter without the needed limits (98 MB storage buffers, 16 KB workgroup memory) or whose device can't be created gets no device; the backbone then runs in candle on the CPU and Settings shows why (sam3::tests::an_adapter_short_of_the_limits_is_refused_with_what_it_lacks). A pass that doesn't finish names its stage in the reason the device is given up with. The parity test prints the largest mask difference to the CPU next to the IoU. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 + crates/engine/Cargo.toml | 2 +- crates/engine/src/cmd/masks.rs | 2 +- crates/engine/src/segment/worker.rs | 22 +- crates/gpu/Cargo.toml | 12 + crates/gpu/examples/sam3_backbone_bench.rs | 125 +++ crates/gpu/src/lib.rs | 2 + crates/gpu/src/sam3.rs | 1102 ++++++++++++++++++++ crates/gpu/src/sam3/tests.rs | 458 ++++++++ crates/gpu/src/wgsl/sam3_attention.wgsl | 75 ++ crates/gpu/src/wgsl/sam3_matmul.wgsl | 138 +++ crates/gpu/src/wgsl/sam3_ops.wgsl | 143 +++ crates/gpu/tests/it/main.rs | 2 + crates/gpu/tests/it/sam3_backbone.rs | 143 +++ xtask/src/layers.rs | 2 + xtask/src/main.rs | 8 +- 16 files changed, 2217 insertions(+), 21 deletions(-) create mode 100644 crates/gpu/examples/sam3_backbone_bench.rs create mode 100644 crates/gpu/src/sam3.rs create mode 100644 crates/gpu/src/sam3/tests.rs create mode 100644 crates/gpu/src/wgsl/sam3_attention.wgsl create mode 100644 crates/gpu/src/wgsl/sam3_matmul.wgsl create mode 100644 crates/gpu/src/wgsl/sam3_ops.wgsl create mode 100644 crates/gpu/tests/it/sam3_backbone.rs diff --git a/Cargo.lock b/Cargo.lock index 8c29f11536..fd65dd2931 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3320,6 +3320,7 @@ name = "lightcraft-gpu" version = "0.13.0" dependencies = [ "bytemuck", + "candle-core", "lightcraft-color", "lightcraft-denoise", "lightcraft-develop", @@ -3329,6 +3330,7 @@ dependencies = [ "lightcraft-raster", "lightcraft-raw", "lightcraft-scenes", + "lightcraft-segment", "lightcraft-testkit", "log", "pollster 1.0.1", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 9caa8cdb0e..1eccf72577 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -51,7 +51,7 @@ chrono = { workspace = true } [features] # AI masks with SAM 3 (Object / Describe). Off for the web and CLI builds. -sam = ["dep:lightcraft-segment"] +sam = ["dep:lightcraft-segment", "lightcraft-gpu/sam"] denoise = ["dep:lightcraft-denoise", "lightcraft-denoise/runtime", "lightcraft-gpu/denoise"] rawnind-model = ["denoise", "lightcraft-denoise/rawnind-model", "lightcraft-denoise-core/rawnind-model"] diff --git a/crates/engine/src/cmd/masks.rs b/crates/engine/src/cmd/masks.rs index 9c7c8bca8f..d00c685a3d 100644 --- a/crates/engine/src/cmd/masks.rs +++ b/crates/engine/src/cmd/masks.rs @@ -560,7 +560,7 @@ pub fn specs() -> Vec { "AI Mask Settings", [], None, - "{runOn?: auto | cpu} → {runOn} — where SAM 3 runs (Settings ▸ Performance ▸ AI masks): `auto` (the default) the GPU when there is one (Metal on macOS; elsewhere candle on the CPU: this build has no wgpu kernels for SAM 3 yet), `cpu` all of it on the CPU on every platform (for a GPU that can't run it). Local inference only: a remote worker (`LIGHTCRAFT_SAM3_REMOTE`) runs on its Mac's Metal device either way. Kept with the app's settings; a loaded model moves at its next request", + "{runOn?: auto | cpu} → {runOn} — where SAM 3 runs (Settings ▸ Performance ▸ AI masks): `auto` (the default) the GPU when there is one (Metal on macOS; elsewhere the parts LightCraft's wgpu kernels run, while GPU rendering is allowed, and the rest on the CPU: `segment.model.status` → `backend` says which), `cpu` all of it on the CPU on every platform (for a GPU that can't run it). Local inference only: a remote worker (`LIGHTCRAFT_SAM3_REMOTE`) runs on its Mac's Metal device either way. Kept with the app's settings; a loaded model moves at its next request", super::always, |s, p| { let c = "segment.settings"; diff --git a/crates/engine/src/segment/worker.rs b/crates/engine/src/segment/worker.rs index 6bae968924..d9f437a2d6 100644 --- a/crates/engine/src/segment/worker.rs +++ b/crates/engine/src/segment/worker.rs @@ -9,8 +9,8 @@ //! after [`IDLE_UNLOAD`] without requests (it holds several GB). //! //! Where the model runs ([`Placement`]): on macOS candle runs all of it on the GPU through Metal. -//! Elsewhere candle runs on the CPU, and the backbone (most of the work) can run on the GPU through an -//! accelerator ([`GPU_BACKBONE`]: none in this build yet, so it runs in candle as before), unless the GPU is switched off (`LIGHTCRAFT_GPU=0`, +//! Elsewhere candle runs on the CPU, and the backbone (most of the work) on the GPU with +//! `lightcraft-gpu`'s wgpu kernels, unless the GPU is switched off (`LIGHTCRAFT_GPU=0`, //! `LIGHTCRAFT_GPU_BACKEND=off`, or Settings ▸ Performance ▸ Use the GPU for rendering, as for AI //! Denoise and faces); a GPU that can't be used or fails on a photo leaves the backbone to the CPU. //! Settings ▸ Performance ▸ AI masks ▸ CPU ([`Job::cpu`]) puts all of it on the CPU, on every @@ -207,11 +207,7 @@ fn wanted(best_is_cpu: bool, cpu: bool, failed: Option<&str>) -> Placement { if let Some(why) = lightcraft_gpu::env_off_reason() { return Placement::Cpu(why.into()); } - match placement(best_is_cpu, lightcraft_gpu::switched_off(), false) { - // without a GPU backbone in this build, candle's best device runs it all - Placement::GpuBackbone if GPU_BACKBONE.is_none() => Placement::Best, - p => p, - } + placement(best_is_cpu, lightcraft_gpu::switched_off(), false) } /// Whether a model loaded for `loaded` runs somewhere else than `wanted` (it must load again), candle's best device @@ -233,17 +229,9 @@ fn moves(loaded: &Placement, wanted: &Placement, best_is_cpu: bool) -> bool { runs(loaded) != runs(wanted) } -/// Builds the GPU backbone from the checkpoint (tests use fakes). +/// Builds the GPU backbone from the checkpoint (`lightcraft_gpu::sam3::backbone`; tests use fakes). type MakeAccel = fn(&WeightReader) -> Result, String>; -/// The GPU backbone of this build: none yet (its wgpu kernels come separately), so where candle has no GPU the -/// model runs in candle on the CPU, as before. -const GPU_BACKBONE: Option = None; - -fn no_accelerator(_: &WeightReader) -> Result, String> { - Err("this build has no GPU backbone".into()) -} - /// Load the model in `dir` as `placement` says, on `best` (candle's best device). fn load(dir: &Path, best: Device, placement: &Placement, make: MakeAccel) -> lightcraft_segment::Result { match placement { @@ -529,7 +517,7 @@ fn model<'a>(state: &'a mut State, shared: &Shared, dir: &Path, cpu: bool, faile let best = if skip { Device::Cpu } else { lightcraft_segment::best_device() }; let best_is_cpu = if skip { !cfg!(target_os = "macos") } else { best.is_cpu() }; let placement = wanted(best_is_cpu, cpu, failed); - let m = load(dir, best, &placement, GPU_BACKBONE.unwrap_or(no_accelerator))?; + let m = load(dir, best, &placement, lightcraft_gpu::sam3::backbone)?; log::info!("SAM 3 loaded in {:?}: the backbone on the {}, the rest on the {}", t.elapsed(), m.backbone_device(), m.heads_device()); note_loaded(shared, &m, &placement); state.model = Some((dir.to_path_buf(), m)); diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml index 02edcefd1b..689d0e64ed 100644 --- a/crates/gpu/Cargo.toml +++ b/crates/gpu/Cargo.toml @@ -24,13 +24,25 @@ log = { workspace = true } wgpu = { workspace = true } pollster = { workspace = true } bytemuck = { workspace = true } +# the SAM 3 backbone kernels (`sam` feature) implement `lightcraft_segment::BackboneAccel` +lightcraft-segment = { workspace = true, optional = true } [features] default = [] denoise = ["dep:lightcraft-denoise", "lightcraft-denoise/runtime"] +# SAM 3's vision backbone on the GPU (`sam3`); the engine's `sam` feature turns it on +sam = ["dep:lightcraft-segment"] [dev-dependencies] # tests record why they skip (`cargo xtask ci` lists the skips) lightcraft-testkit = { workspace = true } lightcraft-scenes = { workspace = true } lightcraft-raw = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +# the SAM 3 backbone test and benchmark compare against the candle backbone +candle-core = { workspace = true } + +[[example]] +name = "sam3_backbone_bench" +required-features = ["sam"] diff --git a/crates/gpu/examples/sam3_backbone_bench.rs b/crates/gpu/examples/sam3_backbone_bench.rs new file mode 100644 index 0000000000..05a001308e --- /dev/null +++ b/crates/gpu/examples/sam3_backbone_bench.rs @@ -0,0 +1,125 @@ +//! Times the SAM 3 backbone on the GPU (wgpu) against the candle backbone on the CPU, on a procedural photo. +//! +//! `cargo run --release -p lightcraft-gpu --features sam --example sam3_backbone_bench -- [--f16] [--runs N] [--no-cpu]` +//! +//! 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, 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, the rest in candle on the CPU): encode, click features, first click, first and second Describe. + +use std::path::PathBuf; +use std::time::Instant; + +use lightcraft_gpu::sam3::{self, Precision}; +use lightcraft_segment::{BackboneAccel, INPUT, Sam3}; + +fn model_dir() -> Option { + let dir = match std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()) { + Some(d) => PathBuf::from(d), + None => PathBuf::from(std::env::var_os("HOME")?).join(".config/lightcraft/models/sam3"), + }; + lightcraft_segment::is_model_dir(&dir).then_some(dir) +} + +fn main() -> Result<(), String> { + let args: Vec = std::env::args().skip(1).collect(); + let precision = if args.iter().any(|a| a == "--f16") { Precision::F16 } else { Precision::F32 }; + let runs: usize = match args.iter().position(|a| a == "--runs").map(|i| args.get(i + 1).and_then(|v| v.parse().ok())) { + None => 5, + Some(Some(n)) if n > 0 => n, + Some(_) => return Err("--runs needs a positive number".into()), + }; + let cpu = !args.iter().any(|a| a == "--no-cpu"); + let app = args.iter().any(|a| a == "--app"); + let dir = model_dir().ok_or("no SAM 3 model: set LIGHTCRAFT_SAM3_DIR")?; + + let scene = &lightcraft_scenes::demo_library()[0]; + let img = scene.render_fit(1600).to_srgb8(); + let rgb: Vec = img.data.iter().flat_map(|p| [p[0], p[1], p[2]]).collect(); + let pixels = lightcraft_segment::mask::preprocess(&rgb, img.width, img.height, INPUT).map_err(|e| e.to_string())?; + + let t = Instant::now(); + let adapter = sam3::adapter()?; + println!("device + kernels: {:7.1} ms ({adapter})", t.elapsed().as_secs_f64() * 1e3); + let reader = lightcraft_segment::WeightReader::open(&dir).map_err(|e| e.to_string())?; + let t = Instant::now(); + let gpu = sam3::load(&reader, precision)?; + println!( + "weight upload: {:7.1} ms ({:.0} MB weights, {:.0} MB work buffers, {precision:?})", + t.elapsed().as_secs_f64() * 1e3, + gpu.weight_bytes() as f64 / 1e6, + gpu.work_bytes() as f64 / 1e6 + ); + let t = Instant::now(); + let out = gpu.forward(&pixels)?; + println!("first forward: {:7.1} ms", t.elapsed().as_secs_f64() * 1e3); + let mut best = f64::MAX; + let mut sum = 0.0; + for _ in 0..runs { + let t = Instant::now(); + gpu.forward(&pixels)?; + let ms = t.elapsed().as_secs_f64() * 1e3; + best = best.min(ms); + sum += ms; + } + println!("warm forward: {:7.1} ms (mean of {runs}: {:.1} ms)", best, sum / runs.max(1) as f64); + 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())?; + let t = Instant::now(); + let enc = model.encode_pixels(&px).map_err(|e| e.to_string())?; + println!("CPU (candle): {:7.1} ms", t.elapsed().as_secs_f64() * 1e3); + let want = enc.backbone().flatten_all().and_then(|t| t.to_vec1::()).map_err(|e| e.to_string())?; + let scale = want.iter().fold(0f32, |m, v| m.max(v.abs())); + let (mut max, mut sum) = (0f32, 0f64); + for (a, b) in out.iter().zip(&want) { + max = max.max((a - b).abs()); + sum += f64::from((a - b).abs()); + } + println!( + "GPU vs CPU: max abs {max:.3e}, max rel {:.3e} (scale {scale:.2}), mean abs {:.3e}", + max / scale.max(1e-6), + sum / want.len().max(1) as f64 + ); + } + drop(gpu); + if app { + as_the_app(&dir, &rgb, (img.width, img.height), runs)?; + } + // no GPU work in flight when the process ends (issue #620) + lightcraft_gpu::begin_shutdown(); + lightcraft_gpu::wait_idle(std::time::Duration::from_secs(5)); + Ok(()) +} + +fn ms(t: Instant) -> String { + format!("{:.0} ms", t.elapsed().as_secs_f64() * 1e3) +} + +/// 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) -> Result<(), String> { + let t = Instant::now(); + let mut model = Sam3::load_accelerated(dir, candle_core::Device::Cpu, sam3::backbone).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 }; + for run in 0..runs.max(1) { + let t = Instant::now(); + let mut enc = model.encode(rgb, w, h).map_err(|e| e.to_string())?; + let encode = ms(t); + let t = Instant::now(); + model.prepare_clicks(&mut enc).map_err(|e| e.to_string())?; + let features = ms(t); + let t = Instant::now(); + model.segment_clicks(&mut enc, &[click(0.5, 0.5)]).map_err(|e| e.to_string())?; + let click1 = ms(t); + let t = Instant::now(); + model.segment_text(&mut enc, "sky", 0.5).map_err(|e| e.to_string())?; + let text1 = ms(t); + let t = Instant::now(); + model.segment_text(&mut enc, "the red car", 0.5).map_err(|e| e.to_string())?; + let text2 = ms(t); + println!("app run {run}: encode {encode}, click features {features}, click {click1}, first describe {text1}, second describe {text2}"); + } + println!("app: the rest on {}", model.heads_device()); + Ok(()) +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index ec644df6e7..125eddd2de 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -43,6 +43,8 @@ pub mod nn; mod params; #[cfg(not(target_arch = "wasm32"))] mod render; +#[cfg(all(feature = "sam", not(target_arch = "wasm32")))] +pub mod sam3; #[cfg(not(target_arch = "wasm32"))] pub use render::GpuStages; diff --git a/crates/gpu/src/sam3.rs b/crates/gpu/src/sam3.rs new file mode 100644 index 0000000000..bf37f72454 --- /dev/null +++ b/crates/gpu/src/sam3.rs @@ -0,0 +1,1102 @@ +//! The SAM 3 vision backbone on the GPU: a [`lightcraft_segment::BackboneAccel`] that runs the 32-layer ViT of +//! `lightcraft-segment` (`vit.rs`, the reference) with WGSL compute kernels, so AI masks (Object, Subject, Describe) +//! need not wait ~40 s per photo for the CPU on machines without Metal. +//! +//! What runs (`docs/gpu-pipeline.md` → SAM 3 backbone): the patch embedding as im2col and a matrix product, the +//! 24 × 24 position table, `ln_pre`, then per layer layer norm → one q|k|v product → 2-D RoPE → attention (24 × 24 +//! windows, or all 5184 tokens in layers 7, 15, 23 and 31) → output projection and residual → layer norm → MLP +//! (GELU, erf form) and residual. The tokens stay in *window order* the whole way (window-major, row-major inside a +//! window): a window's tokens are then a contiguous range for attention, the position table repeats per window, and +//! the global layers don't care about order (their RoPE table is stored in the same order). Only the last step puts +//! them back on the 72 × 72 grid, channels-first. +//! +//! Kernels: `wgsl/sam3_matmul.wgsl` (tiled, register-blocked; bias, GELU and residual in its epilogue), +//! `wgsl/sam3_attention.wgsl` (flash style: online softmax, the 16 × 5184² scores of a global layer never exist), +//! `wgsl/sam3_ops.wgsl` (layer norm, RoPE, im2col, the final reorder). All of the dispatches, with their parameters +//! and bind groups, are built once with the weights; a forward pass uploads the pixels, submits one command buffer +//! per layer and reads the result back once. No subgroups or shader-f16 needed. The necks and the text detector's +//! heads stay in candle on the CPU. +//! +//! 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 +//! around device creation and the shutdown gate. A device error or loss stops its use for the process; every +//! failure is an `Err` (the caller then runs the candle backbone), never a panic. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, PoisonError}; +use std::time::Duration; + +use bytemuck::Pod; +use lightcraft_segment::{BACKBONE_PREFIX, BackboneAccel, WeightReader}; +use wgpu::util::DeviceExt; + +#[cfg(test)] +mod tests; + +/// Input side (pixels), patch size, patches per side. +const IMAGE: usize = 1008; +const PATCH: usize = 14; +const GRID: usize = IMAGE / PATCH; +const TOKENS: usize = GRID * GRID; +const HIDDEN: usize = 1024; +const HEADS: usize = 16; +const HEAD_DIM: usize = HIDDEN / HEADS; +const MLP: usize = 4736; +const LAYERS: usize = 32; +const WINDOW: usize = 24; +const GLOBAL: [usize; 4] = [7, 15, 23, 31]; +/// The pretraining grid of the position table (336 / 14), tiled over the 72 × 72 grid. +const POS_SIDE: usize = 24; +const EPS: f32 = 1e-6; +/// Numbers per patch (3 × 14 × 14): the patch embedding's K. +const PATCH_K: usize = 3 * PATCH * PATCH; + +/// Longest wait for one forward pass before the device is given up on. +const TIMEOUT: Duration = Duration::from_secs(120); +/// Workgroup memory the attention kernel needs: its key and value tiles (2 × [`ATTENTION_KEYS`] × 64 floats). +const ATTENTION_BYTES: u32 = 2 * ATTENTION_KEYS * HEAD_DIM as u32 * 4; +/// Keys per step of the attention kernel. +const ATTENTION_KEYS: u32 = 32; +/// The matrix product's blocking. +const TILE: Tile = Tile { rows: 4, cols: 4, bk: 16 }; + +/// How the matrix-product kernel blocks its work: each of its 16 × 16 threads makes `rows × cols` outputs (so a +/// workgroup makes 16 · rows × 16 · cols), walking k in steps of `bk` (a multiple of 8). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Tile { + rows: u32, + cols: u32, + bk: u32, +} + +impl Tile { + fn bm(self) -> usize { + 16 * self.rows as usize + } + + fn bn(self) -> usize { + 16 * self.cols as usize + } + + /// Workgroup memory: both tiles, k-contiguous, each row padded by one vector. + fn workgroup_bytes(self) -> u32 { + (self.bm() + self.bn()) as u32 * (self.bk / 4 + 1) * 16 + } +} + +/// A matrix-product pipeline and its blocking. +struct Matmul { + pipeline: wgpu::ComputePipeline, + tile: Tile, +} + +// --------------------------------------------------------------------------------------------------------------------- +// the device + +struct Dev { + device: wgpu::Device, + queue: wgpu::Queue, + info: wgpu::AdapterInfo, + limits: wgpu::Limits, + layout: wgpu::BindGroupLayout, + pipeline_layout: wgpu::PipelineLayout, + k: Kernels, + /// Bound where a kernel has fewer operands than bindings. + dummy: wgpu::Buffer, +} + +struct Kernels { + matmul: Matmul, + /// The same with f16 weights, compiled when first needed. + matmul16: OnceLock, + attention: wgpu::ComputePipeline, + layernorm: wgpu::ComputePipeline, + rope: wgpu::ComputePipeline, + im2col: wgpu::ComputePipeline, + to_chw: wgpu::ComputePipeline, +} + +static DEV: OnceLock> = OnceLock::new(); +static BROKEN: AtomicBool = AtomicBool::new(false); +static BROKEN_WHY: Mutex> = Mutex::new(None); + +fn mark_broken(why: &str) { + let mut w = BROKEN_WHY.lock().unwrap_or_else(PoisonError::into_inner); + if w.is_none() { + *w = Some(why.to_string()); + } + BROKEN.store(true, Ordering::Relaxed); +} + +/// Why the GPU stopped being used for SAM 3 (a device error), if it did. +pub fn broken_reason() -> Option { + BROKEN.load(Ordering::Relaxed).then(|| BROKEN_WHY.lock().unwrap_or_else(PoisonError::into_inner).clone().unwrap_or_else(|| "device error".into())) +} + +fn dev() -> Result<&'static Dev, String> { + if let Some(why) = broken_reason() { + return Err(format!("stopped after a GPU failure: {why}")); + } + if let Some(why) = crate::switched_off() { + return Err(why); + } + // creating the device is GPU work too: not once the process is ending (issue #620) + let _work = match DEV.get() { + Some(_) => None, + None => Some(crate::exit::enter().ok_or("LightCraft is closing")?), + }; + DEV.get_or_init(create_device).as_ref().map_err(|e| e.clone()) +} + +fn create_device() -> Result { + let Some(backends) = crate::backend::compute_backends() else { return Err("disabled by LIGHTCRAFT_GPU_BACKEND=off".into()) }; + crate::backend::with_init_marker(backends, || { + std::panic::catch_unwind(|| make_device(backends)).unwrap_or_else(|_| Err("device creation panicked".into())) + }) +} + +fn entry(binding: u32, ty: wgpu::BufferBindingType) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None }, + count: None, + } +} + +/// The largest buffer the backbone binds: the MLP's hidden activations (5184 × 4736 floats, 98 MB). +const LARGEST_BUFFER: u64 = (TOKENS * MLP * 4) as u64; + +/// The limits the kernels need: the WebGPU downlevel defaults, with room for the largest buffer and the tiles. +fn needed_limits() -> wgpu::Limits { + wgpu::Limits { + max_storage_buffer_binding_size: LARGEST_BUFFER, + max_buffer_size: LARGEST_BUFFER, + max_compute_workgroup_storage_size: ATTENTION_BYTES.max(TILE.workgroup_bytes()), + max_compute_invocations_per_workgroup: 256, + max_compute_workgroup_size_x: 256, + ..wgpu::Limits::downlevel_defaults() + } +} + +/// The limits an adapter with `have` falls short of ([`needed_limits`]), as "name have < want"; empty when it has them all. +/// Such an adapter gets no device: SAM 3 then runs in candle on the CPU, and Settings says why. +fn short_limits(have: &wgpu::Limits) -> Vec { + let mut short = Vec::new(); + needed_limits().check_limits_with_fail_fn(have, false, |name, want, have| short.push(format!("{name} {have} < {want}"))); + short +} + +fn make_device(backends: wgpu::Backends) -> Result { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = backends; + desc.backend_options = crate::backend::backend_options(); + desc.flags = crate::backend::instance_flags_from_env(desc.flags); + let instance = wgpu::Instance::new(desc); + let wanted = std::env::var("LIGHTCRAFT_GPU_ADAPTER").ok().map(|s| s.trim().to_lowercase()).filter(|s| !s.is_empty()); + let adapter = match &wanted { + Some(w) => pollster::block_on(instance.enumerate_adapters(backends)) + .into_iter() + .find(|a| { + let i = a.get_info(); + i.device_type != wgpu::DeviceType::Cpu && i.name.to_lowercase().contains(w.as_str()) + }) + .ok_or_else(|| format!("no GPU adapter named like `{w}`"))?, + None => pollster::block_on( + instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }), + ) + .map_err(|e| format!("no GPU adapter among {backends:?} ({e})"))?, + }; + let info = adapter.get_info(); + if info.device_type == wgpu::DeviceType::Cpu { + return Err(format!("software adapter ({}) skipped: the CPU is faster", info.name)); + } + let need = needed_limits(); + let short = short_limits(&adapter.limits()); + if !short.is_empty() { + return Err(format!("{} is too limited for the SAM 3 kernels ({})", info.name, short.join(", "))); + } + let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + label: Some("lightcraft-sam3"), + required_limits: need, + ..Default::default() + })) + .map_err(|e| format!("{}: device creation failed ({e})", info.name))?; + device.on_uncaptured_error(Arc::new(|e| { + log::error!("gpu (sam3): {e}"); + mark_broken(&format!("device error: {e}")); + })); + device.set_device_lost_callback(|reason, msg| { + log::error!("gpu (sam3): device lost ({reason:?}): {msg}"); + mark_broken(&format!("device lost ({reason:?}): {msg}")); + }); + // a kernel the driver or naga rejects fails the device here, not the first forward pass + let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); + use wgpu::BufferBindingType::{Storage, Uniform}; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("sam3"), + entries: &[ + entry(0, Uniform), + entry(1, Storage { read_only: true }), + entry(2, Storage { read_only: true }), + entry(3, Storage { read_only: true }), + entry(4, Storage { read_only: false }), + ], + }); + let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layout)], immediate_size: 0 }); + let pipe = |label: &str, source: &str, entry: &str| pipeline(&device, &pl, label, source, entry); + let ops = include_str!("wgsl/sam3_ops.wgsl"); + let k = Kernels { + matmul: Matmul { pipeline: pipe("sam3 matmul", &matmul_source(TILE, false), "main"), tile: TILE }, + matmul16: OnceLock::new(), + attention: pipe("sam3 attention", &attention_source(ATTENTION_KEYS), "main"), + layernorm: pipe("sam3 ops", ops, "layernorm"), + rope: pipe("sam3 ops", ops, "rope"), + im2col: pipe("sam3 ops", ops, "im2col"), + to_chw: pipe("sam3 ops", ops, "to_chw"), + }; + let dummy = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("sam3 unused"), + size: 16, + usage: wgpu::BufferUsages::STORAGE, + mapped_at_creation: false, + }); + if let Some(e) = pollster::block_on(validation.pop()) { + return Err(format!("{}: the SAM 3 kernels did not compile ({e})", info.name)); + } + let limits = device.limits(); + log::info!("gpu (sam3): {} ({:?})", info.name, info.backend); + Ok(Dev { device, queue, info, limits, layout, pipeline_layout: pl, k, dummy }) +} + +impl Dev { + fn matmul16(&self) -> &Matmul { + self.k.matmul16.get_or_init(|| Matmul { + pipeline: pipeline(&self.device, &self.pipeline_layout, "sam3 matmul f16", &matmul_source(TILE, true), "main"), + tile: TILE, + }) + } +} + +fn pipeline(device: &wgpu::Device, layout: &wgpu::PipelineLayout, label: &str, source: &str, entry: &str) -> wgpu::ComputePipeline { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(source.into()) }); + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some(entry), + layout: Some(layout), + module: &module, + entry_point: Some(entry), + // every kernel writes its workgroup memory before reading it + compilation_options: wgpu::PipelineCompilationOptions { zero_initialize_workgroup_memory: false, ..Default::default() }, + cache: None, + }) +} + +/// The matrix-product kernel for `tile` (`bk` 16 with `f16` weights), written out from `wgsl/sam3_matmul.wgsl`: one +/// variable per accumulator and per prefetched vector. +fn matmul_source(tile: Tile, f16: bool) -> String { + matmul_source_with(tile, f16, None) +} + +/// [`matmul_source`] with `load_a` (the A-tile loader) from `a_loader` instead of the dense one (the neck's 3 × 3 +/// convolution, `sam3/neck.rs`). +fn matmul_source_with(tile: Tile, f16: bool, a_loader: Option<&str>) -> String { + let Tile { rows, cols, bk } = tile; + use std::fmt::Write; + let mut src = String::new(); + // keep the B-tile loader of this weight type, and the A-tile loader asked for + let mut keep = true; + for line in include_str!("wgsl/sam3_matmul.wgsl").lines() { + match line.trim() { + "// #if f32" => keep = !f16, + "// #if f16" => keep = f16, + "// #if dense" => keep = a_loader.is_none(), + "// #endif" => keep = true, + _ if keep => { + src.push_str(line); + src.push('\n'); + } + _ => {} + } + } + src.push_str(a_loader.unwrap_or_default()); + let (bm, bn) = (16 * rows, 16 * cols); + let a_vecs = bm * bk / 4; + let b_vecs = if f16 { bn * bk / 8 } else { bn * bk / 4 }; + let (mut decl, mut load, mut next, mut store_tile, mut compute, mut store) = + (String::new(), String::new(), String::new(), String::new(), String::new(), String::new()); + let w = |s: &mut String, line: String| { + s.push_str(&line); + s.push('\n'); + }; + for i in 0..rows { + let row: Vec = (0..cols).map(|j| format!("var c{i}_{j} = 0.0;")).collect(); + w(&mut decl, format!(" {}", row.join(" "))); + } + let b_type = if f16 { "array, 2>" } else { "vec4" }; + let b_load = if f16 { "load_b16" } else { "load_b" }; + for (l, start) in (0..a_vecs).step_by(256).enumerate() { + w(&mut decl, format!(" var pa{l}: vec4;")); + let guard = if start + 256 > a_vecs { format!("if (tid + {start}u < {a_vecs}u) ") } else { String::new() }; + w(&mut load, format!(" {guard}{{ pa{l} = load_a(m0, 0u, tid + {start}u); }}")); + w(&mut next, format!(" {guard}{{ pa{l} = load_a(m0, k0 + BK, tid + {start}u); }}")); + w(&mut store_tile, format!(" {guard}{{ let e = tid + {start}u; As[e / KV * KS + e % KV] = pa{l}; }}")); + } + for (l, start) in (0..b_vecs).step_by(256).enumerate() { + w(&mut decl, format!(" var pb{l}: {b_type};")); + let guard = if start + 256 > b_vecs { format!("if (tid + {start}u < {b_vecs}u) ") } else { String::new() }; + w(&mut load, format!(" {guard}{{ pb{l} = {b_load}(n0, 0u, tid + {start}u); }}")); + w(&mut next, format!(" {guard}{{ pb{l} = {b_load}(n0, k0 + BK, tid + {start}u); }}")); + let put = if f16 { + format!("let r = e / (BK / 8u) * KS + 2u * (e % (BK / 8u)); Bs[r] = pb{l}[0]; Bs[r + 1u] = pb{l}[1];") + } else { + format!("Bs[e / KV * KS + e % KV] = pb{l};") + }; + w(&mut store_tile, format!(" {guard}{{ let e = tid + {start}u; {put} }}")); + } + for i in 0..rows { + w(&mut compute, format!(" let a{i} = As[(ty + {}u) * KS + kv];", 16 * i)); + } + for j in 0..cols { + w(&mut compute, format!(" let b{j} = Bs[(tx + {}u) * KS + kv];", 16 * j)); + } + for c in ["x", "y", "z", "w"] { + for i in 0..rows { + let mut line = String::from(" "); + for j in 0..cols { + // writing into a String cannot fail + let _ = write!(line, " c{i}_{j} = fma(a{i}.{c}, b{j}.{c}, c{i}_{j});"); + } + w(&mut compute, line); + } + } + for i in 0..rows { + w(&mut store, format!(" {{\n let m = m0 + ty + {}u;\n if (m < p.m) {{", 16 * i)); + for j in 0..cols { + w(&mut store, format!(" put(m, n0 + tx + {}u, c{i}_{j});", 16 * j)); + } + w(&mut store, " }\n }".into()); + } + src.replace("{{WEIGHT}}", if f16 { "vec4" } else { "vec4" }) + .replace("{{BM}}", &bm.to_string()) + .replace("{{BN}}", &bn.to_string()) + .replace("{{BK}}", &bk.to_string()) + .replace("{{DECL}}", &decl) + .replace("{{LOAD}}", &load) + .replace("{{LOAD_NEXT}}", &next) + .replace("{{STORE_TILE}}", &store_tile) + .replace("{{COMPUTE}}", &compute) + .replace("{{STORE}}", &store) +} + +/// The attention kernel for `keys` keys per step, written out from `wgsl/sam3_attention.wgsl`: one variable per q +/// and output vector and per score. +fn attention_source(keys: u32) -> String { + use std::fmt::Write; + let d4 = (HEAD_DIM / 4) as u32; + let (mut decl, mut scores, mut rescale, mut acc, mut store) = (String::new(), String::new(), String::new(), String::new(), String::new()); + // writing into a String cannot fail + for c in 0..d4 { + let _ = writeln!(decl, " let q{c} = qkv[qa + {c}u];\n var o{c} = vec4(0.0);"); + let _ = writeln!(rescale, " o{c} *= fix;"); + let _ = writeln!(store, " out[oa + {c}u] = o{c} * r;"); + } + for j in 0..keys { + let terms: Vec = (0..d4).map(|c| format!("q{c} * Ks[{}u]", j * d4 + c)).collect(); + let _ = writeln!( + scores, + " let d{j} = {};\n let s{j} = d{j}.x + d{j}.y + d{j}.z + d{j}.w;\n top = max(top, s{j});", + terms.join(" + ") + ); + let _ = writeln!(acc, " {{\n let w = exp(s{j} - top);\n l += w;"); + for c in 0..d4 { + let _ = writeln!(acc, " o{c} = fma(vec4(w), Vs[{}u], o{c});", j * d4 + c); + } + let _ = writeln!(acc, " }}"); + } + include_str!("wgsl/sam3_attention.wgsl") + .replace("{{KB}}", &keys.to_string()) + .replace("{{DECL}}", &decl) + .replace("{{SCORES}}", &scores) + .replace("{{RESCALE}}", &rescale) + .replace("{{ACCUMULATE}}", &acc) + .replace("{{STORE}}", &store) +} + +/// The adapter the SAM 3 backbone would use ("NVIDIA GeForce RTX 5070 (Vulkan)"), or why it cannot use one. Creates +/// the device on first use. +pub fn adapter() -> Result { + dev().map(|d| format!("{} ({:?})", d.info.name, d.info.backend)) +} + +// --------------------------------------------------------------------------------------------------------------------- +// steps: one dispatch each, recorded once + +/// One dispatch: a kernel, its parameters, its buffers (bindings 1–3 read, 4 written) and its workgroup counts. +struct Pending { + pipeline: &'static wgpu::ComputePipeline, + params: [u32; 8], + buffers: [wgpu::Buffer; 4], + groups: [u32; 3], +} + +/// A recorded dispatch, ready to replay. +struct Step { + pipeline: &'static wgpu::ComputePipeline, + bind: wgpu::BindGroup, + groups: [u32; 3], +} + +fn u32_of(v: usize) -> Result { + u32::try_from(v).ok().filter(|v| *v < (1 << 31)).ok_or_else(|| "a tensor too large for the SAM 3 kernels".to_string()) +} + +/// How the linear layers' weights are stored on the device. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Precision { + /// As in the checkpoint. + F32, + /// Halves, two per u32 (along k): half the memory and weight traffic; the products still run in f32. + F16, +} + +/// Builds a list of dispatches. +struct Graph { + dev: &'static Dev, + steps: Vec, + /// Where command buffers end (indices into `steps`): one submission each. + cuts: Vec, +} + +impl Graph { + fn new(dev: &'static Dev) -> Graph { + Graph { dev, steps: Vec::new(), cuts: Vec::new() } + } + + /// Workgroups for `count` items of 256 (or `count` workgroups), and the row length the kernel reads back. + fn flat(&self, count: usize) -> Result<([u32; 3], u32), String> { + let limit = (self.dev.limits.max_compute_workgroups_per_dimension as usize).min(65_535); + let blocks = count.max(1); + let row = blocks.min(limit); + let rows = blocks.div_ceil(row); + if rows > limit { + return Err("a step too large for the SAM 3 kernels".into()); + } + Ok(([u32_of(row)?, u32_of(rows)?, 1], u32_of(row)?)) + } + + fn push(&mut self, pipeline: &'static wgpu::ComputePipeline, params: [u32; 8], buffers: [&wgpu::Buffer; 4], groups: [u32; 3]) { + let buffers = buffers.map(Clone::clone); + self.steps.push(Pending { pipeline, params, buffers, groups }); + } + + /// End a command buffer here. + fn cut(&mut self) { + if self.cuts.last() != Some(&self.steps.len()) { + self.cuts.push(self.steps.len()); + } + } + + /// `y = act(x · wᵀ + bias[row % bias_rows])` (or `y +=` with `residual`): x `[m, k]`, w `[n, k]` (f32, or f16 + /// pairs), bias `[bias_rows, n]`, y `[m, n]`. + #[allow(clippy::too_many_arguments)] + fn matmul( + &mut self, + [x, w, bias, y]: [&wgpu::Buffer; 4], + (m, n, k): (usize, usize, usize), + bias_rows: usize, + gelu: bool, + residual: bool, + precision: Precision, + ) -> Result<(), String> { + let kernel = match precision { + Precision::F32 => &self.dev.k.matmul, + Precision::F16 => self.dev.matmul16(), + }; + self.matmul_with(kernel, precision, [x, w, bias, y], (m, n, k), bias_rows, gelu, residual) + } + + /// [`Graph::matmul`] with the pipeline `kernel` (benchmarks of other tiles). + #[allow(clippy::too_many_arguments)] + fn matmul_with( + &mut self, + kernel: &'static Matmul, + precision: Precision, + [x, w, bias, y]: [&wgpu::Buffer; 4], + (m, n, k): (usize, usize, usize), + bias_rows: usize, + gelu: bool, + residual: bool, + ) -> Result<(), String> { + let step = match precision { + Precision::F32 => 4, + Precision::F16 => kernel.tile.bk as usize, + }; + if !k.is_multiple_of(step) || bias_rows == 0 { + return Err(format!("a {m}×{k}·{k}×{n} product the SAM 3 kernel cannot do")); + } + let params = [u32_of(m)?, u32_of(n)?, u32_of(k)?, u32_of(bias_rows)?, u32::from(gelu), u32::from(residual), 0, 0]; + let groups = [u32_of(n.div_ceil(kernel.tile.bn()))?, u32_of(m.div_ceil(kernel.tile.bm()))?, 1]; + self.push(&kernel.pipeline, params, [x, w, bias, y], groups); + Ok(()) + } + + /// Layer norm of `rows` rows of `c` numbers: `y = (x − mean) / sqrt(var + eps) · gamma + beta`. + fn layernorm(&mut self, [x, gamma, beta, y]: [&wgpu::Buffer; 4], rows: usize, c: usize) -> Result<(), String> { + let (g, row) = self.flat(rows)?; + self.push(&self.dev.k.layernorm, [u32_of(rows)?, u32_of(c)?, 0, 0, EPS.to_bits(), 0, u32_of(rows)?, row], [x, gamma, beta, y], g); + Ok(()) + } + + /// RoPE on the q and k of `qkv` (`[tokens, stride]`, q | k | v each `hidden` wide) in place, from a table of + /// `table_rows` positions (token t uses row t % table_rows), and q scaled by `scale`. + fn rope( + &mut self, + qkv: &wgpu::Buffer, + table: &wgpu::Buffer, + (tokens, stride, hidden): (usize, usize, usize), + table_rows: usize, + scale: f32, + ) -> Result<(), String> { + if hidden % HEAD_DIM != 0 || table_rows == 0 { + return Err("a RoPE the SAM 3 kernel cannot do".into()); + } + let count = tokens.checked_mul(hidden).ok_or("too many tokens")?; + let (g, row) = self.flat(count.div_ceil(256))?; + let dummy = &self.dev.dummy; + let params = [u32_of(tokens)?, u32_of(stride)?, u32_of(hidden)?, u32_of(table_rows)?, 0, scale.to_bits(), u32_of(count)?, row]; + self.push(&self.dev.k.rope, params, [dummy, table, dummy, qkv], g); + Ok(()) + } + + /// Attention of every head over `qkv` (`[tokens, stride]`, q | k | v each `hidden` wide) into `out` + /// (`[tokens, hidden]`), each query over the `span` tokens of its window. + fn attention( + &mut self, + qkv: &wgpu::Buffer, + out: &wgpu::Buffer, + (tokens, stride, hidden): (usize, usize, usize), + span: usize, + ) -> Result<(), String> { + if span == 0 + || !span.is_multiple_of(64) + || !span.is_multiple_of(ATTENTION_KEYS as usize) + || !tokens.is_multiple_of(span) + || !hidden.is_multiple_of(HEAD_DIM) + || !stride.is_multiple_of(4) + { + return Err("an attention the SAM 3 kernel cannot do".into()); + } + let dummy = &self.dev.dummy; + let params = [u32_of(tokens)?, u32_of(span)?, u32_of(stride)?, u32_of(hidden)?, 0, 0, 0, 0]; + let groups = [u32_of(tokens / 64)?, u32_of(hidden / HEAD_DIM)?, 1]; + if groups[0] > self.dev.limits.max_compute_workgroups_per_dimension { + return Err("too many tokens for the SAM 3 attention kernel".into()); + } + self.push(&self.dev.k.attention, params, [qkv, dummy, dummy, out], groups); + Ok(()) + } + + /// The patches of `pixels` (`[channels, side, side]`) as rows of `[tokens, channels · patch²]`, in window order. + fn im2col( + &mut self, + pixels: &wgpu::Buffer, + cols: &wgpu::Buffer, + (side, patch, channels): (usize, usize, usize), + window: usize, + ) -> Result<(), String> { + let grid = side / patch.max(1); + if patch == 0 || window == 0 || grid % window != 0 { + return Err("a patch embedding the SAM 3 kernel cannot do".into()); + } + let count = grid * grid * channels * patch * patch; + let (g, row) = self.flat(count.div_ceil(256))?; + let dummy = &self.dev.dummy; + let params = [u32_of(side)?, u32_of(patch)?, u32_of(grid)?, u32_of(window)?, u32_of(channels)?, 0, u32_of(count)?, row]; + self.push(&self.dev.k.im2col, params, [pixels, dummy, dummy, cols], g); + Ok(()) + } + + /// Tokens `[grid², channels]` in window order to `[channels, grid, grid]`. + fn channels_first(&mut self, x: &wgpu::Buffer, out: &wgpu::Buffer, channels: usize, grid: usize, window: usize) -> Result<(), String> { + if window == 0 || !grid.is_multiple_of(window) { + return Err("a reorder the SAM 3 kernel cannot do".into()); + } + let count = channels * grid * grid; + let (g, row) = self.flat(count.div_ceil(256))?; + let dummy = &self.dev.dummy; + self.push(&self.dev.k.to_chw, [u32_of(channels)?, u32_of(grid)?, u32_of(window)?, 0, 0, 0, u32_of(count)?, row], [x, dummy, dummy, out], g); + Ok(()) + } + + /// The bind groups, with every step's parameters in one uniform buffer. + fn record(self) -> Recorded { + let d = self.dev; + let align = (d.limits.min_uniform_buffer_offset_alignment as usize).max(32); + let mut blob = vec![0u8; self.steps.len().max(1) * align]; + for (chunk, s) in blob.chunks_mut(align).zip(&self.steps) { + if let Some(to) = chunk.get_mut(..32) { + to.copy_from_slice(bytemuck::cast_slice(&s.params)); + } + } + let uniform = d.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("sam3 params"), + contents: &blob, + usage: wgpu::BufferUsages::UNIFORM, + }); + let steps = self + .steps + .iter() + .enumerate() + .map(|(i, s)| { + let [a, b, c, out] = &s.buffers; + let bind = d.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &d.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &uniform, + offset: (i * align) as u64, + size: wgpu::BufferSize::new(32), + }), + }, + wgpu::BindGroupEntry { binding: 1, resource: a.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 2, resource: b.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: c.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 4, resource: out.as_entire_binding() }, + ], + }); + Step { pipeline: s.pipeline, bind, groups: s.groups } + }) + .collect(); + let mut cuts = self.cuts; + if cuts.last() != Some(&self.steps.len()) { + cuts.push(self.steps.len()); + } + Recorded { steps, cuts } + } +} + +/// Dispatches ready to replay, with where each command buffer ends. +struct Recorded { + steps: Vec, + cuts: Vec, +} + +impl Recorded { + /// Submit every step (one command buffer per cut), copy `len` floats of `src` into `staging` after the last, + /// wait and read them back. + /// Run the recorded dispatches of `stage` (its name for the reason a hung device is given up on) and read `len` + /// floats of `src` back. + fn run(&self, stage: &str, dev: &Dev, src: &wgpu::Buffer, staging: &wgpu::Buffer, len: usize) -> Result, String> { + let bytes = len as u64 * 4; + let oom = dev.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let mut from = 0; + let mut last = None; + for (n, &to) in self.cuts.iter().enumerate() { + let mut enc = dev.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("sam3") }); + { + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("sam3"), timestamp_writes: None }); + for s in self.steps.get(from..to).unwrap_or_default() { + pass.set_pipeline(s.pipeline); + pass.set_bind_group(0, &s.bind, &[]); + let [x, y, z] = s.groups; + pass.dispatch_workgroups(x, y, z); + } + } + if n + 1 == self.cuts.len() { + enc.copy_buffer_to_buffer(src, 0, staging, 0, bytes); + } + last = Some(dev.queue.submit([enc.finish()])); + from = to; + } + let slice = staging.slice(..bytes); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |r| { + let _ = tx.send(r); + }); + let waited = dev.device.poll(wgpu::PollType::Wait { submission_index: last, timeout: Some(TIMEOUT) }); + let (validation, oom) = (pollster::block_on(validation.pop()), pollster::block_on(oom.pop())); + // the read-back buffer must not stay mapped, whatever failed: the next pass copies into it + let mapped = if waited.is_ok() { rx.recv_timeout(Duration::from_secs(10)).map_err(|e| e.to_string()) } else { Err("not finished".into()) }; + let out = (|| { + if let Some(e) = oom { + return Err(format!("the GPU ran out of memory: {e}")); + } + if let Some(e) = validation { + mark_broken(&format!("device error: {e}")); + return Err(format!("the GPU reported an error: {e}")); + } + if let Err(e) = &waited { + mark_broken(&format!("the GPU did not finish {stage}: {e}")); + return Err(format!("the GPU did not finish: {e}")); + } + match &mapped { + Ok(Ok(())) => {} + Ok(Err(e)) => return Err(format!("reading the result back failed: {e}")), + Err(e) => return Err(format!("reading the result back failed: {e}")), + } + let data = slice.get_mapped_range().map_err(|e| format!("reading the result back failed: {e:?}"))?; + Ok(data.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect::>()) + })(); + if matches!(mapped, Ok(Ok(()))) { + staging.unmap(); + } + let out = out?; + if out.len() != len { + return Err("the GPU returned a short result".into()); + } + Ok(out) + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// the backbone + +/// Device buffers, each `len` floats (`STORAGE | COPY_DST | COPY_SRC`), or uploaded from `data`. +fn buffer(dev: &Dev, label: &str, len: usize) -> wgpu::Buffer { + dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: (len.max(4) * 4) as u64, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC, + mapped_at_creation: false, + }) +} + +/// A buffer holding `data`. Written through the queue rather than mapped at creation: a buffer the device has no +/// memory for then raises an out-of-memory error (and the caller tries something smaller), not a failed mapping. +fn upload(dev: &Dev, label: &str, data: &[T]) -> wgpu::Buffer { + let bytes: &[u8] = bytemuck::cast_slice(data); + let b = dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: (bytes.len() as u64).next_multiple_of(4).max(16), + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + // write_buffer wants whole 4-byte words + if bytes.len().is_multiple_of(4) && !bytes.is_empty() { + dev.queue.write_buffer(&b, 0, bytes); + } + b +} + +/// The nearest f16 to `v` (ties to even), as its bits. +fn f16_bits(v: f32) -> u16 { + let b = v.to_bits(); + let sign = ((b >> 16) & 0x8000) as u16; + let exp = ((b >> 23) & 0xff) as i32; + let man = b & 0x7f_ffff; + if exp == 0xff { + return sign | 0x7c00 | if man != 0 { 0x200 } else { 0 }; + } + let e = exp - 127 + 15; + if e >= 0x1f { + return sign | 0x7c00; + } + let round = |value: u32, shift: u32| -> u32 { + let rest = value & ((1 << shift) - 1); + let half = 1 << (shift - 1); + let r = value >> shift; + if rest > half || (rest == half && r & 1 == 1) { r + 1 } else { r } + }; + if e <= 0 { + // a subnormal half, or zero + if e < -10 { + return sign; + } + return sign | round(man | 0x80_0000, (14 - e) as u32) as u16; + } + // a carry out of the mantissa correctly bumps the exponent (up to infinity) + sign | round(((e as u32) << 23) | man, 13) as u16 +} + +/// Weights `[n, k]` as f16 pairs (k even): u32 i holds k 2i (low half) and 2i + 1. +fn pack_f16(w: &[f32]) -> Vec { + w.chunks(2) + .map(|p| u32::from(f16_bits(p.first().copied().unwrap_or(0.0))) | (u32::from(f16_bits(p.get(1).copied().unwrap_or(0.0))) << 16)) + .collect() +} + +/// The RoPE table of `Sam3ViTRotaryEmbedding` as `vit::rope_tables` makes it, for the tokens of a `side × side` grid +/// listed in window order (`window` per side; `side` itself: plain row-major), coordinates scaled by `scale`: +/// `[tokens, 32]` pairs (cos, sin), pair i of a head rotating by x · f_i (i < 16) or y · f_(i − 16). +fn rope_table(side: usize, window: usize, scale: f64) -> Vec { + let spatial = HEAD_DIM / 2; + let inv: Vec = (0..spatial).step_by(2).map(|i| 1.0 / 10000f64.powf(i as f64 / spatial as f64)).collect(); + let mut out = Vec::with_capacity(side * side * HEAD_DIM); + for t in 0..side * side { + let (row, col) = window_cell(t, side, window); + let (x, y) = (col as f64 * scale, row as f64 * scale); + for pos in [x, y] { + for f in &inv { + let a = (pos * f) as f32 as f64; + out.extend([a.cos() as f32, a.sin() as f32]); + } + } + } + out +} + +/// The grid cell (row, col) of window-order token `t` on a `side × side` grid of `window × window` windows. +fn window_cell(t: usize, side: usize, window: usize) -> (usize, usize) { + let per_side = (side / window.max(1)).max(1); + let (w, l) = (t / (window * window).max(1), t % (window * window).max(1)); + (w / per_side * window + l / window.max(1), w % per_side * window + l % window.max(1)) +} + +/// One layer's weights on the device. +struct LayerWeights { + ln1: [wgpu::Buffer; 2], + qkv: [wgpu::Buffer; 2], + o: [wgpu::Buffer; 2], + ln2: [wgpu::Buffer; 2], + fc1: [wgpu::Buffer; 2], + fc2: [wgpu::Buffer; 2], +} + +/// Reads the backbone's tensors, checking their shapes. +struct Loader<'a> { + weights: &'a WeightReader, + dev: &'static Dev, + precision: Precision, + bytes: u64, +} + +impl Loader<'_> { + fn read(&self, name: &str, shape: &[usize]) -> Result, String> { + let full = format!("{BACKBONE_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:?}")); + } + Ok(data) + } + + /// A small tensor (a bias, a norm's scale…), always f32. + fn small(&mut self, name: &str, shape: &[usize]) -> Result { + let data = self.read(name, shape)?; + self.bytes += data.len() as u64 * 4; + Ok(upload(self.dev, name, &data)) + } + + /// A linear layer's weight `[n, k]` (concatenated along n when there are several) in the backbone's precision. + fn weight(&mut self, names: &[&str], n: usize, k: usize) -> Result { + let mut all = Vec::with_capacity(names.len() * n * k); + for name in names { + all.extend(self.read(name, &[n, k])?); + } + self.store(names.first().copied().unwrap_or("weight"), &all) + } + + fn store(&mut self, label: &str, data: &[f32]) -> Result { + Ok(match self.precision { + Precision::F32 => { + self.bytes += data.len() as u64 * 4; + upload(self.dev, label, data) + } + Precision::F16 => { + let packed = pack_f16(data); + self.bytes += packed.len() as u64 * 4; + upload(self.dev, label, &packed) + } + }) + } + + fn norm(&mut self, name: &str) -> Result<[wgpu::Buffer; 2], String> { + Ok([self.small(&format!("{name}.weight"), &[HIDDEN])?, self.small(&format!("{name}.bias"), &[HIDDEN])?]) + } + + fn layer(&mut self, i: usize) -> Result { + let l = format!("layers.{i}"); + let a = format!("{l}.attention"); + let qkv_names = [format!("{a}.q_proj.weight"), format!("{a}.k_proj.weight"), format!("{a}.v_proj.weight")]; + let qkv_names: Vec<&str> = qkv_names.iter().map(String::as_str).collect(); + let mut qkv_bias = Vec::with_capacity(3 * HIDDEN); + for p in ["q_proj", "k_proj", "v_proj"] { + qkv_bias.extend(self.read(&format!("{a}.{p}.bias"), &[HIDDEN])?); + } + self.bytes += qkv_bias.len() as u64 * 4; + Ok(LayerWeights { + ln1: self.norm(&format!("{l}.layer_norm1"))?, + qkv: [self.weight(&qkv_names, HIDDEN, HIDDEN)?, upload(self.dev, "qkv bias", &qkv_bias)], + o: [self.weight(&[&format!("{a}.o_proj.weight")], HIDDEN, HIDDEN)?, self.small(&format!("{a}.o_proj.bias"), &[HIDDEN])?], + ln2: self.norm(&format!("{l}.layer_norm2"))?, + fc1: [self.weight(&[&format!("{l}.mlp.fc1.weight")], MLP, HIDDEN)?, self.small(&format!("{l}.mlp.fc1.bias"), &[MLP])?], + fc2: [self.weight(&[&format!("{l}.mlp.fc2.weight")], HIDDEN, MLP)?, self.small(&format!("{l}.mlp.fc2.bias"), &[HIDDEN])?], + }) + } +} + +/// The buffers of a forward pass. +struct Work { + pixels: wgpu::Buffer, + out: wgpu::Buffer, + staging: wgpu::Buffer, +} + +/// The SAM 3 backbone on the GPU: weights, work buffers and every dispatch of a forward pass, made once. +pub struct Sam3Gpu { + dev: &'static Dev, + recorded: Recorded, + /// One forward pass at a time (they share the work buffers). + work: Mutex, + /// Bytes of weights on the device. + weight_bytes: u64, + /// Bytes of work buffers on the device. + work_bytes: u64, + precision: Precision, +} + +/// The SAM 3 backbone on the GPU with the checkpoint's weights uploaded, or why it can't run there (GPU off, missing, +/// broken, a software adapter, too small, or out of memory). The weights take 1.8 GB of device memory, or 0.9 GB as f16 +/// when the f32 ones do not fit. +pub fn backbone(weights: &WeightReader) -> Result, String> { + match load(weights, Precision::F32) { + Ok(b) => Ok(Box::new(b)), + // half the memory (0.9 GB of weights), a little less accurate (see `docs/gpu-pipeline.md`) + Err(e) if e.starts_with(NO_MEMORY) => { + log::info!("gpu (sam3): {e}; trying f16 weights"); + Ok(Box::new(load(weights, Precision::F16)?)) + } + Err(e) => Err(e), + } +} + +/// How a build that ran out of device memory fails. +const NO_MEMORY: &str = "not enough GPU memory for the SAM 3 backbone"; + +/// [`backbone`] with the linear layers' weights stored in `precision`. +pub fn load(weights: &WeightReader, precision: Precision) -> Result { + let dev = dev()?; + let Some(_work) = crate::exit::enter() else { return Err("LightCraft is closing".into()) }; + guarded("the SAM 3 backbone", || build(dev, weights, precision)) +} + +fn build(dev: &'static Dev, weights: &WeightReader, precision: Precision) -> Result { + let oom = dev.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let made = build_inner(dev, weights, precision); + // let the uploads land before the scopes close + let _ = dev.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(TIMEOUT) }); + let (validation, oom) = (pollster::block_on(validation.pop()), pollster::block_on(oom.pop())); + if let Some(e) = oom { + return Err(format!("{NO_MEMORY}: {e}")); + } + if let Some(e) = validation { + return Err(format!("the GPU rejected the SAM 3 backbone: {e}")); + } + made +} + +fn build_inner(dev: &'static Dev, weights: &WeightReader, precision: Precision) -> Result { + let mut ld = Loader { weights, dev, precision: Precision::F32, bytes: 0 }; + // the patch embedding (K = 588, not a multiple of the f16 tile) and its position table stay f32 + let patch = ld.read("embeddings.patch_embeddings.projection.weight", &[HIDDEN, 3, PATCH, PATCH])?; + let patch = ld.store("patch embedding", &patch)?; + let pos = ld.small("embeddings.position_embeddings", &[1, POS_SIDE * POS_SIDE, HIDDEN])?; + let ln_pre = ld.norm("layer_norm")?; + ld.precision = precision; + let mut layers = Vec::with_capacity(LAYERS); + for i in 0..LAYERS { + layers.push(ld.layer(i)?); + // hand the queued uploads (~55 MB a layer) to the device, so their staging memory is freed as they land + dev.queue.submit([]); + } + let rope_window = upload(dev, "rope window", &rope_table(WINDOW, WINDOW, 1.0)); + let rope_global = upload(dev, "rope global", &rope_table(GRID, WINDOW, WINDOW as f64 / GRID as f64)); + + let pixels = buffer(dev, "sam3 pixels", 3 * IMAGE * IMAGE); + let x = buffer(dev, "sam3 hidden", TOKENS * HIDDEN); + let y = buffer(dev, "sam3 normed", TOKENS * HIDDEN); + // im2col, then q|k|v, then the MLP's hidden activations + let big = buffer(dev, "sam3 wide", TOKENS * MLP.max(3 * HIDDEN).max(PATCH_K)); + let staging = dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("sam3 read-back"), + size: (TOKENS * HIDDEN * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let work_bytes = ((3 * IMAGE * IMAGE + 3 * TOKENS * HIDDEN + TOKENS * MLP) * 4) as u64; + + let mut g = Graph::new(dev); + g.im2col(&pixels, &big, (IMAGE, PATCH, 3), WINDOW)?; + g.matmul([&big, &patch, &pos, &y], (TOKENS, HIDDEN, PATCH_K), POS_SIDE * POS_SIDE, false, false, Precision::F32)?; + g.layernorm([&y, &ln_pre[0], &ln_pre[1], &x], TOKENS, HIDDEN)?; + g.cut(); + for (i, l) in layers.iter().enumerate() { + let global = GLOBAL.contains(&i); + g.layernorm([&x, &l.ln1[0], &l.ln1[1], &y], TOKENS, HIDDEN)?; + g.matmul([&y, &l.qkv[0], &l.qkv[1], &big], (TOKENS, 3 * HIDDEN, HIDDEN), 1, false, false, precision)?; + let (table, rows, span) = if global { (&rope_global, TOKENS, TOKENS) } else { (&rope_window, WINDOW * WINDOW, WINDOW * WINDOW) }; + g.rope(&big, table, (TOKENS, 3 * HIDDEN, HIDDEN), rows, 1.0 / (HEAD_DIM as f32).sqrt())?; + g.attention(&big, &y, (TOKENS, 3 * HIDDEN, HIDDEN), span)?; + g.matmul([&y, &l.o[0], &l.o[1], &x], (TOKENS, HIDDEN, HIDDEN), 1, false, true, precision)?; + g.layernorm([&x, &l.ln2[0], &l.ln2[1], &y], TOKENS, HIDDEN)?; + g.matmul([&y, &l.fc1[0], &l.fc1[1], &big], (TOKENS, MLP, HIDDEN), 1, true, false, precision)?; + g.matmul([&big, &l.fc2[0], &l.fc2[1], &x], (TOKENS, HIDDEN, MLP), 1, false, true, precision)?; + g.cut(); + } + g.channels_first(&x, &y, HIDDEN, GRID, WINDOW)?; + let recorded = g.record(); + Ok(Sam3Gpu { dev, recorded, work: Mutex::new(Work { pixels, out: y, staging }), weight_bytes: ld.bytes, work_bytes, precision }) +} + +/// Run `f`, the work of `stage`, turning a panic into a broken device (with the stage's name). +fn guarded(stage: &str, f: impl FnOnce() -> Result) -> Result { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| { + mark_broken(&format!("{stage} on the GPU panicked")); + Err("the GPU runner gave up".into()) + }) +} + +impl Sam3Gpu { + /// Bytes of device memory the weights take. + pub fn weight_bytes(&self) -> u64 { + self.weight_bytes + } + + /// Bytes of device memory the work buffers take (activations, input, read-back). + pub fn work_bytes(&self) -> u64 { + self.work_bytes + (TOKENS * HIDDEN * 4) as u64 + } + + fn run(&self, pixels: &[f32]) -> Result, String> { + if pixels.len() != 3 * IMAGE * IMAGE { + return Err(format!("{} pixel values, expected 3 × {IMAGE} × {IMAGE}", pixels.len())); + } + let Some(_work) = crate::exit::enter() else { return Err("LightCraft is closing".into()) }; + let work = self.work.lock().unwrap_or_else(PoisonError::into_inner); + self.dev.queue.write_buffer(&work.pixels, 0, bytemuck::cast_slice(pixels)); + let out = self.recorded.run("the SAM 3 backbone", self.dev, &work.out, &work.staging, TOKENS * HIDDEN)?; + if out.iter().any(|v| !v.is_finite()) { + return Err("the GPU backbone produced non-finite values".into()); + } + Ok(out) + } +} + +impl BackboneAccel for Sam3Gpu { + fn forward(&self, pixels: &[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); + } + guarded("the SAM 3 backbone", || self.run(pixels)) + } + + fn closing(&self) -> bool { + crate::shutting_down() + } + + fn device(&self) -> String { + let weights = match self.precision { + Precision::F32 => "", + Precision::F16 => ", f16 weights", + }; + format!("{} ({:?}{weights})", self.dev.info.name, self.dev.info.backend) + } +} diff --git a/crates/gpu/src/sam3/tests.rs b/crates/gpu/src/sam3/tests.rs new file mode 100644 index 0000000000..d9f6050fe4 --- /dev/null +++ b/crates/gpu/src/sam3/tests.rs @@ -0,0 +1,458 @@ +//! The SAM 3 kernels against plain loops on small shapes (tiles cut off at the edges, several windows). The whole +//! backbone against candle: `tests/it/sam3_backbone.rs`. + +use super::*; + +pub(super) fn gpu() -> Option<&'static Dev> { + match dev() { + Ok(d) => Some(d), + // 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})"); + None + } + } +} + +/// Deterministic values in −scale..scale. +pub(super) fn values(n: usize, seed: u64, scale: f32) -> Vec { + let mut s = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (0..n) + .map(|_| { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((s >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0) * scale + }) + .collect() +} + +pub(super) fn read(d: &'static Dev, g: Graph, out: &wgpu::Buffer, len: usize) -> Vec { + let staging = d.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: (len * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + g.record().run("a test", d, out, &staging, len).unwrap() +} + +pub(super) fn worst(got: &[f32], want: &[f32]) -> f32 { + assert_eq!(got.len(), want.len()); + got.iter().zip(want).fold(0f32, |m, (a, b)| m.max((a - b).abs())) +} + +/// GELU, erf form (candle's `gelu_erf`), with a high-precision erf: the kernel's approximation is what is checked. +pub(super) fn gelu(v: f64) -> f64 { + 0.5 * v * (1.0 + erf(v / std::f64::consts::SQRT_2)) +} + +/// erf to ~1e-15 (Taylor series near 0, continued fraction of erfc further out). +fn erf(x: f64) -> f64 { + let a = x.abs(); + let r = if a < 2.5 { + let (mut term, mut sum, mut n) = (a, a, 0.0); + while term.abs() > 1e-17 * sum.abs() { + n += 1.0; + term *= -a * a / n; + sum += term / (2.0 * n + 1.0); + } + sum * 2.0 / std::f64::consts::PI.sqrt() + } else { + // erfc(a) = exp(−a²)/√π · 1/(a + 1/2/(a + 1/(a + 3/2/(a + 2/(a + …))))) + let mut f = a; + for k in (1..60).rev() { + f = a + (k as f64 / 2.0) / f; + } + 1.0 - (-a * a).exp() / std::f64::consts::PI.sqrt() / f + }; + if x < 0.0 { -r } else { r } +} + +#[test] +fn erf_reference_is_right() { + for (x, want) in [(0.5, 0.520_499_877_813_046_5), (1.0, 0.842_700_792_949_714_9), (2.0, 0.995_322_265_018_952_7), (3.0, 0.999_977_909_503_001_4)] + { + assert!((erf(x) - want).abs() < 1e-13, "erf({x}) = {}", erf(x)); + assert!((erf(-x) + want).abs() < 1e-13); + } +} + +/// `y = act(x · wᵀ + bias[row % rows])` (+ y0) in f64. +#[allow(clippy::too_many_arguments)] +fn matmul_ref(x: &[f32], w: &[f32], bias: &[f32], y0: Option<&[f32]>, (m, n, k): (usize, usize, usize), rows: usize, act: bool) -> Vec { + let mut out = vec![0f32; m * n]; + for i in 0..m { + for j in 0..n { + let mut v = bias[(i % rows) * n + j] as f64; + for t in 0..k { + v += x[i * k + t] as f64 * w[j * k + t] as f64; + } + if act { + v = gelu(v); + } + if let Some(y0) = y0 { + v += y0[i * n + j] as f64; + } + out[i * n + j] = v as f32; + } + } + out +} + +#[test] +fn the_matrix_product_gives_what_the_definition_gives() { + let Some(d) = gpu() else { return }; + // whole tiles, cut-off tiles in every direction, K not a multiple of the tile's 16, a position-style bias table + for (case, (m, n, k, rows, act, residual)) in [ + (256, 128, 64, 1, false, false), + (200, 136, 52, 1, false, false), + (130, 300, 588, 7, false, false), + (77, 260, 96, 1, true, false), + (150, 129, 132, 1, false, true), + (5, 3, 4, 1, true, true), + ] + .into_iter() + .enumerate() + { + let x = values(m * k, case as u64, 1.0); + let w = values(n * k, 100 + case as u64, 0.2); + let bias = values(rows * n, 200 + case as u64, 0.5); + let y0 = values(m * n, 300 + case as u64, 1.0); + let (bx, bw, bb) = (upload(d, "x", &x), upload(d, "w", &w), upload(d, "b", &bias)); + let by = buffer(d, "y", m * n); + d.queue.write_buffer(&by, 0, bytemuck::cast_slice(&y0)); + let mut g = Graph::new(d); + g.matmul([&bx, &bw, &bb, &by], (m, n, k), rows, act, residual, Precision::F32).unwrap(); + let got = read(d, g, &by, m * n); + let want = matmul_ref(&x, &w, &bias, residual.then_some(&y0[..]), (m, n, k), rows, act); + let err = worst(&got, &want); + assert!(err < 2e-5 * (k as f32).sqrt().max(1.0), "case {case} ({m}×{n}×{k}): off by {err}"); + } +} + +#[test] +fn the_f16_matrix_product_uses_the_rounded_weights() { + let Some(d) = gpu() else { return }; + let (m, n, k) = (140, 200, 96); + let x = values(m * k, 1, 1.0); + let w = values(n * k, 2, 0.2); + let bias = values(n, 3, 0.5); + let rounded: Vec = w.iter().map(|v| f16_value(f16_bits(*v))).collect(); + let (bx, bw, bb) = (upload(d, "x", &x), upload(d, "w", &pack_f16(&w)), upload(d, "b", &bias)); + let by = buffer(d, "y", m * n); + let mut g = Graph::new(d); + g.matmul([&bx, &bw, &bb, &by], (m, n, k), 1, true, false, Precision::F16).unwrap(); + let got = read(d, g, &by, m * n); + let want = matmul_ref(&x, &rounded, &bias, None, (m, n, k), 1, true); + let err = worst(&got, &want); + assert!(err < 1e-4, "off by {err}"); + // K must be a multiple of the f16 tile + assert!(Graph::new(d).matmul([&bx, &bw, &bb, &by], (m, n, 40), 1, false, false, Precision::F16).is_err()); +} + +/// The value of half `h` (test reference). +fn f16_value(h: u16) -> f32 { + let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; + let (e, m) = (((h >> 10) & 0x1f) as i32, (h & 0x3ff) as f32); + sign * match e { + 0 => m * 2f32.powi(-24), + 0x1f => { + if m == 0.0 { + f32::INFINITY + } else { + f32::NAN + } + } + _ => (1.0 + m / 1024.0) * 2f32.powi(e - 15), + } +} + +#[test] +fn halves_round_to_nearest_even() { + for (v, h) in [ + (0.0f32, 0x0000u16), + (-0.0, 0x8000), + (1.0, 0x3c00), + (-2.0, 0xc000), + (65504.0, 0x7bff), + (65520.0, 0x7c00), + (1e10, 0x7c00), + (f32::INFINITY, 0x7c00), + (6.103_515_6e-5, 0x0400), + (5.960_464_5e-8, 0x0001), + (2.0e-8, 0x0000), + (0.333_333_34, 0x3555), + // exactly between 1 and the next half up (1 + 2⁻¹¹): ties to even (down), just above: up + (1.000_488_3, 0x3c00), + (1.000_488_4, 0x3c01), + ] { + assert_eq!(f16_bits(v), h, "{v}"); + } + assert!(f16_value(f16_bits(f32::NAN)).is_nan()); + // every half survives the round trip + for h in (0u16..0x7c00).step_by(7) { + assert_eq!(f16_bits(f16_value(h)), h); + } +} + +#[test] +fn layer_norm_gives_what_the_definition_gives() { + let Some(d) = gpu() else { return }; + for (rows, c) in [(7, 1024), (3, 300), (2, 4)] { + let x: Vec = values(rows * c, c as u64, 3.0).iter().enumerate().map(|(i, v)| v + (i / c) as f32).collect(); + let (gamma, beta) = (values(c, 5, 1.0), values(c, 6, 0.5)); + let (bx, bg, bb, by) = (upload(d, "x", &x), upload(d, "g", &gamma), upload(d, "b", &beta), buffer(d, "y", rows * c)); + let mut g = Graph::new(d); + g.layernorm([&bx, &bg, &bb, &by], rows, c).unwrap(); + let got = read(d, g, &by, rows * c); + let mut want = vec![0f32; rows * c]; + for r in 0..rows { + let row = &x[r * c..(r + 1) * c]; + let mean = row.iter().map(|v| *v as f64).sum::() / c as f64; + let var = row.iter().map(|v| (*v as f64 - mean).powi(2)).sum::() / c as f64; + for i in 0..c { + want[r * c + i] = ((row[i] as f64 - mean) / (var + EPS as f64).sqrt() * gamma[i] as f64 + beta[i] as f64) as f32; + } + } + let err = worst(&got, &want); + assert!(err < 2e-5, "{rows}×{c}: off by {err}"); + } +} + +/// `vit::apply_rope` (x·cos + rotate_pairwise(x)·sin) with the tables of `vit::rope_tables` for token `t`. +fn rope_ref(x: &[f32], table: &[f32], t: usize) -> Vec { + // the candle tables: [head_dim] cos and sin, each pair's value duplicated + let (mut cos, mut sin) = (Vec::new(), Vec::new()); + for i in 0..32 { + let (c, s) = (table[(t * 32 + i) * 2], table[(t * 32 + i) * 2 + 1]); + cos.extend([c, c]); + sin.extend([s, s]); + } + let mut out = vec![0f32; x.len()]; + for (h, head) in x.chunks(HEAD_DIM).enumerate() { + for i in 0..HEAD_DIM { + let rot = if i % 2 == 0 { -head[i + 1] } else { head[i - 1] }; + out[h * HEAD_DIM + i] = head[i] * cos[i] + rot * sin[i]; + } + } + out +} + +#[test] +fn rope_tables_follow_the_candle_port() { + // window table: plain row-major 24 × 24 positions; the global one lists the 72 × 72 grid in window order + let win = rope_table(WINDOW, WINDOW, 1.0); + let global = rope_table(GRID, WINDOW, WINDOW as f64 / GRID as f64); + assert_eq!(win.len(), WINDOW * WINDOW * 64); + assert_eq!(global.len(), TOKENS * 64); + // token 25 of a window is at (1, 1): x frequency 0 rotates by 1, y frequency 0 by 1 + assert!((win[(25 * 32) * 2] - 1f32.cos()).abs() < 1e-7); + assert!((win[(25 * 32 + 16) * 2 + 1] - 1f32.sin()).abs() < 1e-7); + // window-order token 576 (the second window's first) is cell (0, 24): x = 24 · (24 / 72) = 8 + assert_eq!(window_cell(576, GRID, WINDOW), (0, 24)); + assert!((global[(576 * 32) * 2] - 8f32.cos()).abs() < 1e-6); + assert!((global[(576 * 32 + 16) * 2] - 1.0).abs() < 1e-7, "y = 0"); + // every cell exactly once + let mut seen = vec![false; TOKENS]; + for t in 0..TOKENS { + let (r, c) = window_cell(t, GRID, WINDOW); + assert!(!seen[r * GRID + c]); + seen[r * GRID + c] = true; + } +} + +#[test] +fn rope_rotates_q_and_k_and_scales_q() { + let Some(d) = gpu() else { return }; + let (tokens, hidden, rows) = (40, 128, 16); + let stride = 3 * hidden; + let qkv = values(tokens * stride, 9, 1.0); + let table = rope_table(4, 4, 1.0); + let (bq, bt) = (buffer(d, "qkv", tokens * stride), upload(d, "table", &table)); + d.queue.write_buffer(&bq, 0, bytemuck::cast_slice(&qkv)); + let mut g = Graph::new(d); + g.rope(&bq, &bt, (tokens, stride, hidden), rows, 0.125).unwrap(); + let got = read(d, g, &bq, tokens * stride); + let mut want = qkv.clone(); + for t in 0..tokens { + let row = &qkv[t * stride..(t + 1) * stride]; + let q: Vec = rope_ref(&row[..hidden], &table, t % rows).iter().map(|v| v * 0.125).collect(); + let k = rope_ref(&row[hidden..2 * hidden], &table, t % rows); + want[t * stride..t * stride + hidden].copy_from_slice(&q); + want[t * stride + hidden..t * stride + 2 * hidden].copy_from_slice(&k); + } + let err = worst(&got, &want); + assert!(err < 1e-6, "off by {err}"); +} + +/// Softmax attention of each query over its window's `span` keys (q already scaled), f64. +fn attention_ref(qkv: &[f32], (tokens, stride, hidden): (usize, usize, usize), span: usize) -> Vec { + let mut out = vec![0f32; tokens * hidden]; + for h in 0..hidden / HEAD_DIM { + for t in 0..tokens { + let first = t / span * span; + let q = &qkv[t * stride + h * HEAD_DIM..][..HEAD_DIM]; + let s: Vec = (first..first + span) + .map(|j| q.iter().zip(&qkv[j * stride + hidden + h * HEAD_DIM..][..HEAD_DIM]).map(|(a, b)| *a as f64 * *b as f64).sum()) + .collect(); + let top = s.iter().fold(f64::MIN, |m, v| m.max(*v)); + let e: Vec = s.iter().map(|v| (v - top).exp()).collect(); + let sum: f64 = e.iter().sum(); + for c in 0..HEAD_DIM { + let v: f64 = (first..first + span).zip(&e).map(|(j, w)| w * qkv[j * stride + 2 * hidden + h * HEAD_DIM + c] as f64).sum(); + out[t * hidden + h * HEAD_DIM + c] = (v / sum) as f32; + } + } + } + out +} + +#[test] +fn windowed_and_global_attention_give_the_softmax_of_the_definition() { + let Some(d) = gpu() else { return }; + let (tokens, hidden) = (384, 128); + let stride = 3 * hidden; + // large scores: the online maximum must keep exp() in range + let qkv = values(tokens * stride, 11, 2.5); + let bq = upload(d, "qkv", &qkv); + for span in [64, 128, 384] { + let out = buffer(d, "out", tokens * hidden); + let mut g = Graph::new(d); + g.attention(&bq, &out, (tokens, stride, hidden), span).unwrap(); + let got = read(d, g, &out, tokens * hidden); + let want = attention_ref(&qkv, (tokens, stride, hidden), span); + let err = worst(&got, &want); + // relative to the outputs' size: Metal's exp() is a little less exact than Vulkan's + // (span 128 is off by 2.04e-5 on an M4 Pro, 8e-6 of the largest output) + let scale = want.iter().fold(1f32, |m, v| m.max(v.abs())); + assert!(err < 2e-5 * scale, "span {span}: off by {err} (scale {scale})"); + } + // windows must hold whole workgroups of queries + assert!(Graph::new(d).attention(&bq, &bq, (tokens, stride, hidden), 96).is_err()); +} + +#[test] +fn patches_go_in_and_out_of_window_order() { + let Some(d) = gpu() else { return }; + // 3 × 56 × 56 pixels, 14-pixel patches: a 4 × 4 grid of 2 × 2 windows + let (side, patch, window) = (56, 14, 2); + let grid = side / patch; + let k = 3 * patch * patch; + let pixels = values(3 * side * side, 12, 1.0); + let bp = upload(d, "pixels", &pixels); + let cols = buffer(d, "cols", grid * grid * k); + let mut g = Graph::new(d); + g.im2col(&bp, &cols, (side, patch, 3), window).unwrap(); + let got = read(d, g, &cols, grid * grid * k); + for t in 0..grid * grid { + let (row, col) = window_cell(t, grid, window); + for ch in 0..3 { + for ky in 0..patch { + for kx in 0..patch { + let want = pixels[(ch * side + row * patch + ky) * side + col * patch + kx]; + assert_eq!(got[t * k + (ch * patch + ky) * patch + kx], want, "token {t}"); + } + } + } + } + // and back: channels-first on the grid + let channels = 8; + let tokens = values(grid * grid * channels, 13, 1.0); + let bt = upload(d, "tokens", &tokens); + let out = buffer(d, "chw", grid * grid * channels); + let mut g = Graph::new(d); + g.channels_first(&bt, &out, channels, grid, window).unwrap(); + let got = read(d, g, &out, grid * grid * channels); + for t in 0..grid * grid { + let (row, col) = window_cell(t, grid, window); + for ch in 0..channels { + assert_eq!(got[(ch * grid + row) * grid + col], tokens[t * channels + ch]); + } + } +} + +#[test] +fn the_kernel_source_is_written_out_for_both_weight_types() { + for f16 in [false, true] { + let src = matmul_source(TILE, f16); + assert!(!src.contains("{{"), "a mark left"); + assert_eq!(src.contains("fn load_b16"), f16); + assert_eq!(src.contains("fn load_b("), !f16); + assert_eq!(src.matches("= fma(").count() as u32, 4 * TILE.rows * TILE.cols); + } +} + +/// Kernel timings at the backbone's shapes: +/// `cargo test --release -p lightcraft-gpu --features sam --lib sam3::tests::timings -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: needs a GPU"] +fn timings() { + let Some(d) = gpu() else { return }; + let reps = 20; + let time = |name: &str, flops: f64, build: &dyn Fn(&mut Graph)| { + let out = buffer(d, "out", 4); + let staging = d.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 16, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut g = Graph::new(d); + for _ in 0..reps { + build(&mut g); + } + let rec = g.record(); + rec.run("a test", d, &out, &staging, 4).unwrap(); + let t = std::time::Instant::now(); + rec.run("a test", d, &out, &staging, 4).unwrap(); + let ms = t.elapsed().as_secs_f64() * 1e3 / reps as f64; + eprintln!("{name:>34}: {ms:7.3} ms {:6.2} TFLOP/s", flops / ms / 1e9); + }; + let x = buffer(d, "x", TOKENS * MLP); + let y = buffer(d, "y", TOKENS * MLP); + let w = buffer(d, "w", MLP * HIDDEN); + let b = buffer(d, "b", MLP); + let w16 = buffer(d, "w16", MLP * HIDDEN / 2); + for (n, k) in [(3 * HIDDEN, HIDDEN), (HIDDEN, HIDDEN), (MLP, HIDDEN), (HIDDEN, MLP)] { + let flops = 2.0 * (TOKENS * n * k) as f64; + time(&format!("matmul {TOKENS}x{n}x{k}"), flops, &|g| g.matmul([&x, &w, &b, &y], (TOKENS, n, k), 1, false, false, Precision::F32).unwrap()); + time(&format!("matmul f16 {TOKENS}x{n}x{k}"), flops, &|g| { + g.matmul([&x, &w16, &b, &y], (TOKENS, n, k), 1, false, false, Precision::F16).unwrap() + }); + } + // other blockings (`LC_SAM3_TILES=rows,cols,bk;…`) + for t in std::env::var("LC_SAM3_TILES").unwrap_or_default().split(';').filter(|t| !t.is_empty()) { + let v: Vec = t.split(',').map(|v| v.trim().parse().unwrap()).collect(); + let tile = Tile { rows: v[0], cols: v[1], bk: v[2] }; + let kernel: &'static Matmul = + Box::leak(Box::new(Matmul { pipeline: pipeline(&d.device, &d.pipeline_layout, "variant", &matmul_source(tile, false), "main"), tile })); + for (n, k) in [(3 * HIDDEN, HIDDEN), (MLP, HIDDEN), (HIDDEN, MLP)] { + let flops = 2.0 * (TOKENS * n * k) as f64; + time(&format!("{tile:?} {n}x{k}"), flops, &|g| { + g.matmul_with(kernel, Precision::F32, [&x, &w, &b, &y], (TOKENS, n, k), 1, false, false).unwrap() + }); + } + } + time("matmul 5184x4736x1024 gelu", 2.0 * (TOKENS * MLP * HIDDEN) as f64, &|g| { + g.matmul([&x, &w, &b, &y], (TOKENS, MLP, HIDDEN), 1, true, false, Precision::F32).unwrap() + }); + for span in [WINDOW * WINDOW, TOKENS] { + let flops = 4.0 * (TOKENS * span * HIDDEN) as f64; + time(&format!("attention span {span}"), flops, &|g| g.attention(&x, &y, (TOKENS, 3 * HIDDEN, HIDDEN), span).unwrap()); + } + time("layernorm", 0.0, &|g| g.layernorm([&x, &b, &b, &y], TOKENS, HIDDEN).unwrap()); + time("rope", 0.0, &|g| g.rope(&x, &w, (TOKENS, 3 * HIDDEN, HIDDEN), TOKENS, 0.125).unwrap()); +} + +/// An adapter without the storage-buffer size or the workgroup memory the kernels need gets no device (the model then +/// runs in candle on the CPU); the error names what it lacks. No GPU needed. +#[test] +fn an_adapter_short_of_the_limits_is_refused_with_what_it_lacks() { + assert!(short_limits(&needed_limits()).is_empty()); + let short = short_limits(&wgpu::Limits { max_storage_buffer_binding_size: 64 << 20, ..needed_limits() }); + assert_eq!(short.len(), 1, "{short:?}"); + assert!(short[0].starts_with("max_storage_buffer_binding_size 67108864 <"), "{short:?}"); + let short = short_limits(&wgpu::Limits { max_compute_workgroup_storage_size: 8 << 10, ..needed_limits() }); + assert_eq!(short.len(), 1, "{short:?}"); + assert!(short[0].starts_with("max_compute_workgroup_storage_size 8192 <"), "{short:?}"); +} diff --git a/crates/gpu/src/wgsl/sam3_attention.wgsl b/crates/gpu/src/wgsl/sam3_attention.wgsl new file mode 100644 index 0000000000..e9dca40da3 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_attention.wgsl @@ -0,0 +1,75 @@ +// Self-attention of the SAM 3 backbone (`sam3.rs`), flash style: the scores are never stored. Each query keeps a +// running maximum, softmax denominator and weighted sum of values while the keys stream past (online softmax), so a +// global layer (5184 tokens, 16 heads) needs no 16 x 5184² score matrix. +// +// qkv [tokens, stride]: per token q | k | v, each `hidden` wide (heads x 64), q and k already rotated (RoPE) +// and q already scaled by 1 / sqrt(64) +// out [tokens, hidden] +// +// Tokens are in window order, so a query's keys are the `span` tokens of its window: a contiguous range (span = all +// tokens for the global layers). A workgroup is 64 queries of one head (span is a multiple of 64, so they share +// their window), one query per thread with its q and its partial output in registers; keys and values pass through +// workgroup memory KB at a time, read by all 64 threads at once (a broadcast). The host writes out the per-thread +// work with one variable per vector and score (the DECL, SCORES, RESCALE, ACCUMULATE and STORE marks): arrays indexed +// in loops can end up in slow local memory. + +struct P { + tokens: u32, + span: u32, + stride: u32, + hidden: u32, +} + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var qkv: array>; +@group(0) @binding(4) var out: array>; + +// head_dim / 4, keys per step +const D4: u32 = 16u; +const KB: u32 = {{KB}}u; + +var Ks: array, KB * D4>; +var Vs: array, KB * D4>; + +@compute @workgroup_size(64) +fn main(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let head = wg.y; + let qw = wg.x * 64u; + let tq = qw + lid; + let s4 = p.stride / 4u; + let h4 = p.hidden / 4u; + let first = qw / p.span * p.span; + // a whole workgroup returns together (tokens is a multiple of 64): the barriers below stay uniform + if (qw >= p.tokens) { + return; + } + let qa = tq * s4 + head * D4; + +{{DECL}} + var m = -3.0e38; + var l = 0.0; + + for (var k0 = 0u; k0 < p.span; k0 += KB) { + for (var e = lid; e < KB * D4; e += 64u) { + let t = first + k0 + e / D4; + let c = head * D4 + e % D4; + Ks[e] = qkv[t * s4 + h4 + c]; + Vs[e] = qkv[t * s4 + 2u * h4 + c]; + } + workgroupBarrier(); + + var top = m; +{{SCORES}} + // rescale what was summed under the old maximum + let fix = exp(m - top); + l *= fix; +{{RESCALE}} +{{ACCUMULATE}} + m = top; + workgroupBarrier(); + } + + let r = 1.0 / l; + let oa = tq * h4 + head * D4; +{{STORE}} +} diff --git a/crates/gpu/src/wgsl/sam3_matmul.wgsl b/crates/gpu/src/wgsl/sam3_matmul.wgsl new file mode 100644 index 0000000000..7ccc17f7f1 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_matmul.wgsl @@ -0,0 +1,138 @@ +// The linear layers of the SAM 3 backbone (`sam3.rs`): Y = act(X · Wᵀ + bias), or Y += X · Wᵀ + bias (a residual); +// act is none, GELU (gelu = 1) or ReLU (gelu = 2, the DETR encoder's MLP, `sam3/detr.rs`). +// +// X [M, K] row-major activations +// W [N, K] row-major: the checkpoint's own layout (f32; or, with the f16 variant, pairs of halves packed into +// u32s, k first) +// bias [bias_rows, N]: row m adds bias row m % bias_rows (1: an ordinary bias; 576: the patch embedding's +// 24 x 24 position table, which repeats over the windows) +// Y [M, N] +// +// K is a multiple of 4 (of BK for the f16 variant); M and N are anything. A workgroup of 256 threads (16 x 16) makes a +// BM x BN block of Y, TM x TN values per thread: rows ty + 16 i and columns tx + 16 j, so neighbouring threads write +// neighbouring numbers. K is walked in steps of BK through workgroup memory, where both tiles are kept k-contiguous +// as they are loaded (four k per vector), each row padded by one vector so that the eight threads of a 128-bit load +// phase read eight different bank groups. The next step's tiles are fetched into registers while the current one is +// multiplied. The host writes out the per-thread work with one variable per accumulator (the DECL, LOAD, STORE_TILE, +// COMPUTE and STORE marks): arrays indexed in loops can end up in slow local memory. + +struct P { + m: u32, + n: u32, + k: u32, + bias_rows: u32, + gelu: u32, + residual: u32, + // the image side of the 3 x 3 convolution's loader (`sam3_conv.wgsl`); unused here + side: u32, + pad: u32, +} + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var x: array>; +@group(0) @binding(2) var w: array<{{WEIGHT}}>; +@group(0) @binding(3) var bias: array; +@group(0) @binding(4) var y: array; + +const BM: u32 = {{BM}}u; +const BN: u32 = {{BN}}u; +const BK: u32 = {{BK}}u; +// vectors per tile row, and the padded row stride +const KV: u32 = BK / 4u; +const KS: u32 = KV + 1u; + +var As: array, BM * KS>; +var Bs: array, BN * KS>; + +// #if dense +// Vector e of the A tile at k0 (row e / KV); zero outside X. +fn load_a(m0: u32, k0: u32, e: u32) -> vec4 { + let m = m0 + e / KV; + let kq = k0 / 4u + e % KV; + let k4 = p.k / 4u; + if (m < p.m && kq < k4) { + return x[m * k4 + kq]; + } + return vec4(0.0); +} +// #endif + +// #if f32 +// Vector e of the B tile at k0 (row e / KV of W); zero outside W. +fn load_b(n0: u32, k0: u32, e: u32) -> vec4 { + let n = n0 + e / KV; + let kq = k0 / 4u + e % KV; + let k4 = p.k / 4u; + if (n < p.n && kq < k4) { + return w[n * k4 + kq]; + } + return vec4(0.0); +} +// #endif + +// #if f16 +// The f16 variant: packed vector e of the B tile at k0 (eight k of row e / (BK / 8)), as two f32 vectors. +fn load_b16(n0: u32, k0: u32, e: u32) -> array, 2> { + let n = n0 + e / (BK / 8u); + let kq = k0 / 8u + e % (BK / 8u); + let k8 = p.k / 8u; + var v = vec4(0u); + if (n < p.n && kq < k8) { + v = w[n * k8 + kq]; + } + return array, 2>(vec4(unpack2x16float(v.x), unpack2x16float(v.y)), vec4(unpack2x16float(v.z), unpack2x16float(v.w))); +} +// #endif + +fn erf(v: f32) -> f32 { + // Abramowitz & Stegun 7.1.26 (|error| < 1.5e-7) + let a = abs(v); + let t = 1.0 / (1.0 + 0.3275911 * a); + let poly = t * (0.254829592 + t * (-0.284496736 + t * (1.421413741 + t * (-1.453152027 + t * 1.061405429)))); + let r = 1.0 - poly * exp(-a * a); + return select(-r, r, v >= 0.0); +} + +fn put(m: u32, n: u32, acc: f32) { + if (n >= p.n) { + return; + } + var v = acc + bias[(m % p.bias_rows) * p.n + n]; + if (p.gelu == 1u) { + // GELU, exact (erf) form + v = 0.5 * v * (1.0 + erf(v * 0.7071067811865476)); + } else if (p.gelu == 2u) { + // ReLU (the DETR encoder's MLP) + v = max(v, 0.0); + } + let o = m * p.n + n; + if (p.residual != 0u) { + v += y[o]; + } + y[o] = v; +} + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) tid: u32) { + let n0 = wg.x * BN; + let m0 = wg.y * BM; + let tx = tid % 16u; + let ty = tid / 16u; + +{{DECL}} + +{{LOAD}} + for (var k0 = 0u; k0 < p.k; k0 += BK) { +{{STORE_TILE}} + workgroupBarrier(); + if (k0 + BK < p.k) { +{{LOAD_NEXT}} + } + for (var kv = 0u; kv < KV; kv++) { +{{COMPUTE}} + } + workgroupBarrier(); + } + +{{STORE}} +} diff --git a/crates/gpu/src/wgsl/sam3_ops.wgsl b/crates/gpu/src/wgsl/sam3_ops.wgsl new file mode 100644 index 0000000000..a46d3ccad1 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_ops.wgsl @@ -0,0 +1,143 @@ +// The small steps of the SAM 3 backbone (`sam3.rs`) around its matrix products and attention: layer norm, rotary +// position encoding, the patch embedding's im2col and the final reordering to channels-first. +// +// Tokens are kept in window order: token t = window · win² + (row % win) · win + col % win, windows row-major over +// the grid (win = 24 on the 72 x 72 grid). The per-token steps don't care; `im2col` puts the patches in this order +// and `to_chw` takes them out of it. +// +// One uniform block of up to eight numbers per step (`P`); 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; +} + +// The position in window order of grid cell (row, col). +fn window_token(row: u32, col: u32, grid: u32, win: u32) -> u32 { + let w = row / win * (grid / win) + col / win; + return w * win * win + row % win * win + col % win; +} + +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; +} + +// LayerNorm over rows of `c` numbers (a: rows, b: c, e: eps bits): dst = (src − mean) / sqrt(var + eps) · aux + aux2. +// One workgroup per row. +@compute @workgroup_size(256) +fn layernorm(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let row = wg.y * p.row + wg.x; + if (row >= p.a) { + return; + } + let c = p.b; + let base = row * c; + var s = 0.0; + for (var i = lid; i < c; i += 256u) { + s += src[base + i]; + } + let mean = reduce(lid, s) / f32(c); + var q = 0.0; + for (var i = lid; i < c; i += 256u) { + let d = src[base + i] - mean; + q += d * d; + } + let rstd = inverseSqrt(reduce(lid, q) / f32(c) + bitcast(p.e)); + for (var i = lid; i < c; i += 256u) { + dst[base + i] = (src[base + i] - mean) * rstd * aux[i] + aux2[i]; + } +} + +// Rotary position encoding of q and k in place, and q scaled (a: tokens, b: row stride, c: hidden = heads · 64, +// d: rows of the table, f: q scale bits). One thread per pair (x, y) of neighbouring numbers of a head: +// (x cos − y sin, y cos + x sin), cos and sin from row t % d of `aux` ([rows, 32] pairs of cos, sin). +@compute @workgroup_size(256) +fn rope(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let half = p.c / 2u; + let t = g / p.c; + let r = g % p.c; + let which = r / half; + let pair = r % half; + let i = t * p.b + which * p.c + 2u * pair; + let at = ((t % p.d) * 32u + pair % 32u) * 2u; + let cs = aux[at]; + let sn = aux[at + 1u]; + let x = dst[i]; + let y = dst[i + 1u]; + let scale = select(1.0, bitcast(p.f), which == 0u); + dst[i] = (x * cs - y * sn) * scale; + dst[i + 1u] = (y * cs + x * sn) * scale; +} + +// The patches as rows, in window order (a: image side, b: patch, c: grid side, d: window, e: channels): +// dst[t, (ch · patch + ky) · patch + kx] = src[ch, row · patch + ky, col · patch + kx] for the cell (row, col) of t. +@compute @workgroup_size(256) +fn im2col(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let side = p.a; + let size = p.b; + let grid = p.c; + let k = p.e * size * size; + let t = g / k; + let r = g % k; + let ch = r / (size * size); + let ky = r / size % size; + let kx = r % size; + // the cell of window-order token t + let win = p.d; + let w = t / (win * win); + let l = t % (win * win); + let row = w / (grid / win) * win + l / win; + let col = w % (grid / win) * win + l % win; + dst[g] = src[(ch * side + row * size + ky) * side + col * size + kx]; +} + +// Tokens in window order to channels-first (a: channels, b: grid side, c: window): dst[ch, row, col] = src[t, ch]. +@compute @workgroup_size(256) +fn to_chw(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let n = p.b * p.b; + let ch = g / n; + let cell = g % n; + let t = window_token(cell / p.b, cell % p.b, p.b, p.c); + dst[g] = src[t * p.a + ch]; +} diff --git a/crates/gpu/tests/it/main.rs b/crates/gpu/tests/it/main.rs index d26d1efc94..184916cfb0 100644 --- a/crates/gpu/tests/it/main.rs +++ b/crates/gpu/tests/it/main.rs @@ -7,3 +7,5 @@ mod equivalence; mod fallback; #[cfg(not(target_arch = "wasm32"))] mod gpu_probe; +#[cfg(feature = "sam")] +mod sam3_backbone; diff --git a/crates/gpu/tests/it/sam3_backbone.rs b/crates/gpu/tests/it/sam3_backbone.rs new file mode 100644 index 0000000000..66741d6a3a --- /dev/null +++ b/crates/gpu/tests/it/sam3_backbone.rs @@ -0,0 +1,143 @@ +//! The SAM 3 backbone on the GPU against the candle backbone on the CPU (the reference), on one photo, and what the +//! difference does to the masks downstream (a click mask and a Describe mask). +//! +//! Needs the checkpoint: `LIGHTCRAFT_SAM3_DIR= cargo test --release -p lightcraft-gpu --features sam +//! --test it sam3_backbone:: -- --nocapture`. The photo is a procedural one, or the input of a reference file made by +//! `tools/sam3_reference.py` (`LIGHTCRAFT_SAM3_REF=`; then the backbone is also checked against +//! Hugging Face's). `LIGHTCRAFT_SAM3_PROMPT` names the Describe prompt (default "sky"); `LIGHTCRAFT_SAM3_GPU_F16=1` +//! stores the GPU weights as f16 (bounds as for f32 do not apply then: the errors are printed). Skipped without a +//! model or a GPU. + +use std::path::PathBuf; + +use candle_core::{Device, Tensor}; +use lightcraft_gpu::sam3::{self, Precision}; +use lightcraft_segment::{BackboneAccel, Click, INPUT, 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 } +} + +/// The largest |Δ| between two masks' logits, and between the masks themselves (their sigmoid, 0..1). +fn mask_diff(a: &[f32], b: &[f32]) -> (f32, f32) { + let sigmoid = |v: f32| 1.0 / (1.0 + (-v).exp()); + a.iter().zip(b).fold((0f32, 0f32), |(l, m), (x, y)| (l.max((x - y).abs()), m.max((sigmoid(*x) - sigmoid(*y)).abs()))) +} + +/// The photo as preprocessed pixels `[1, 3, 1008, 1008]`, and the reference backbone (72 × 72 tokens of 1024) if there +/// is a reference file. +fn photo() -> (Tensor, Option) { + 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(), r.remove("backbone")); + } + 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(), None) +} + +#[test] +fn the_gpu_backbone_matches_the_cpu_backbone() { + 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 (pixels, reference) = photo(); + let mut cpu = Sam3::load_on(&dir, Device::Cpu).unwrap(); + let want_f16 = std::env::var("LIGHTCRAFT_SAM3_GPU_F16").is_ok_and(|v| v == "1"); + let mut gpu = if want_f16 { + let make = |w: &WeightReader| -> Result, String> { Ok(Box::new(sam3::load(w, Precision::F16)?)) }; + Sam3::load_accelerated(&dir, Device::Cpu, make).unwrap() + } else { + Sam3::load_accelerated(&dir, Device::Cpu, sam3::backbone).unwrap() + }; + assert!(gpu.backbone_device().starts_with(&adapter[..adapter.len() - 1]), "the accelerator is in use"); + // f16 weights asked for, or the fallback `sam3::backbone` takes when the f32 ones don't fit: the f16 bounds apply + let f16 = want_f16 || gpu.backbone_device().contains("f16 weights"); + if f16 { + eprintln!("f16 weights: {}", gpu.backbone_device()); + } + + let t = std::time::Instant::now(); + let mut want = cpu.encode_pixels(&pixels).unwrap(); + eprintln!("CPU backbone: {:?}", t.elapsed()); + let t = std::time::Instant::now(); + let mut got = gpu.encode_pixels(&pixels).unwrap(); + eprintln!("GPU backbone (first run): {:?} on {adapter}", t.elapsed()); + // a GPU that failed on the photo leaves it to candle, which would compare the CPU with itself + assert!(gpu.accelerated(), "the GPU backbone ran (it fell back: {:?})", gpu.backbone_fallback()); + // the bounds of `docs/gpu-pipeline.md`: f16 weights are ~20 × further off (max rel 3.8e-3, mean abs 5.4e-4 measured) + let (rel_max, mean_max) = if f16 { (1e-2, 1e-3) } else { (2e-3, 1e-4) }; + let (a, b) = (values(got.backbone()), values(want.backbone())); + let (_, rel, mean) = errors("GPU vs CPU backbone", &a, &b); + assert!(rel < rel_max && mean < mean_max, "the GPU backbone is off"); + if let Some(r) = reference { + let hf = values(&r.reshape((1, 72, 72, 1024)).unwrap().permute((0, 3, 1, 2)).unwrap()); + let (_, cpu_rel, _) = errors("CPU vs Hugging Face", &b, &hf); + let (_, gpu_rel, _) = errors("GPU vs Hugging Face", &a, &hf); + assert!(gpu_rel < rel_max && cpu_rel < 2e-3); + } + + // a click mask (the tracker head) and a Describe mask (the detector head) from both + for click in [Click { x: 0.5, y: 0.6, positive: true }, Click { x: 0.3, y: 0.3, positive: true }] { + let (m_cpu, m_gpu) = (cpu.segment_clicks(&mut want, &[click]).unwrap(), gpu.segment_clicks(&mut got, &[click]).unwrap()); + let i = iou(&m_gpu.logits, &m_cpu.logits); + let (dl, dm) = mask_diff(&m_gpu.logits, &m_cpu.logits); + eprintln!( + "click ({}, {}): mask IoU {i:.5}, max |Δ| logits {dl:.2e}, mask {dm:.2e}, score {:.4} vs {:.4}", + click.x, click.y, m_gpu.score, m_cpu.score + ); + assert!(i > 0.99, "click mask IoU {i}"); + } + let prompt = std::env::var("LIGHTCRAFT_SAM3_PROMPT").unwrap_or_else(|_| "sky".into()); + let (d_cpu, d_gpu) = (cpu.segment_text(&mut want, &prompt, 0.5).unwrap(), gpu.segment_text(&mut got, &prompt, 0.5).unwrap()); + match (d_cpu, d_gpu) { + (Some(c), Some(g)) => { + let i = iou(&g.logits, &c.logits); + let (dl, dm) = mask_diff(&g.logits, &c.logits); + let cover = c.logits.iter().filter(|v| **v > 0.0).count() as f32 / c.logits.len() as f32; + eprintln!( + "describe {prompt:?}: mask IoU {i:.5} (covers {:.1} %), max |Δ| logits {dl:.2e}, mask {dm:.2e}, score {:.4} vs {:.4}", + cover * 100.0, + g.score, + c.score + ); + assert!(i > 0.98, "describe mask IoU {i}"); + } + (None, None) => eprintln!("describe {prompt:?}: nothing found by either"), + (c, g) => panic!("describe {prompt:?}: CPU found {}, GPU {}", c.is_some(), g.is_some()), + } +} diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index d5be5523f3..342f25fbb9 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -73,6 +73,7 @@ pub const TABLE: &[(&str, Class)] = &[ /// Explicit orderings *within* a layer (earlier may be used by later). /// L0: `raster` builds on `color` and `geom`; `color` uses `geom` for matrices. /// L1: `raw` and `codecs` read metadata through `meta`; `develop` uses `meta` for XMP. +/// L3: `gpu` runs the SAM 3 backbone of `segment` (its `sam` feature). pub const INTRA_LAYER_ORDER: &[&[&str]] = &[ &["geom", "color", "raster"], &["tiff", "raster"], @@ -82,6 +83,7 @@ pub const INTRA_LAYER_ORDER: &[&[&str]] = &[ &["meta", "develop"], &["develop", "scenes"], &["codecs", "raw"], + &["segment", "gpu"], ]; fn intra_layer_allowed(from: &str, to: &str) -> bool { diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 7ce3cb4234..339fa1669a 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -358,7 +358,11 @@ fn cmd_ci(args: &[&str]) -> Result<(), String> { Box::new(|| { let mut c = cargo(); c.args(["clippy", "--workspace", "--all-targets", "--keep-going", "--", "-D", "warnings"]); - run(c, "cargo clippy --workspace --all-targets --keep-going -- -D warnings") + run(c, "cargo clippy --workspace --all-targets --keep-going -- -D warnings")?; + // the GPU crate's optional parts (the SAM 3 kernels may be off in the workspace build) + let mut c = cargo(); + c.args(["clippy", "-p", "lightcraft-gpu", "--features", "denoise,sam", "--all-targets", "--keep-going", "--", "-D", "warnings"]); + run(c, "cargo clippy -p lightcraft-gpu --features denoise,sam --all-targets --keep-going -- -D warnings") }), ), ( @@ -397,7 +401,7 @@ fn cmd_ci(args: &[&str]) -> Result<(), String> { let mut failed = Vec::new(); for (backend, adapter) in backends { let step = format!("gpu-{backend}"); - let (mut c, what) = tests(&with_test_targets(&["-p", "lightcraft-gpu", "--features", "denoise"])); + let (mut c, what) = tests(&with_test_targets(&["-p", "lightcraft-gpu", "--features", "denoise,sam"])); c.env("LIGHTCRAFT_GPU_BACKEND", &backend).env(ci_report::SKIP_LOG_ENV, ci_report::skip_log(&root, &step)); let t = std::time::Instant::now(); let ok = run(c, &format!("LIGHTCRAFT_GPU_BACKEND={backend} {what}")).is_ok(); From 0d217dad6dd12441a4ff7a03ed65f97898c95758 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:52:44 +0200 Subject: [PATCH 034/331] M12: SAM 3 necks on the GPU (wgpu): the tracker and detector feature pyramids Part 3 of 5 of #2167. Both necks (3 levels each) run on the GPU device of the image encoder: the 2 x 2 stride-2 transposed convolutions as per-pixel products (weights re-laid on upload), the 3 x 3 convolutions as an implicit GEMM (the matrix kernel with an A-tile loader that reads the neighbourhood straight from the image, so the 764 MB im2col at 288^2 never exists). Built on first use, ~250 MB. A failing neck is left to candle on its own; the backbone stays on the GPU. The bench reports a failing neck and goes on. Co-Authored-By: Claude Opus 5.5 --- crates/gpu/examples/sam3_backbone_bench.rs | 88 ++++- crates/gpu/src/sam3.rs | 27 +- crates/gpu/src/sam3/neck.rs | 425 +++++++++++++++++++++ crates/gpu/src/sam3/neck/tests.rs | 215 +++++++++++ crates/gpu/src/wgsl/sam3_conv.wgsl | 29 ++ crates/gpu/src/wgsl/sam3_neck.wgsl | 60 +++ crates/gpu/tests/it/main.rs | 2 + crates/gpu/tests/it/sam3_necks.rs | 165 ++++++++ 8 files changed, 998 insertions(+), 13 deletions(-) create mode 100644 crates/gpu/src/sam3/neck.rs create mode 100644 crates/gpu/src/sam3/neck/tests.rs create mode 100644 crates/gpu/src/wgsl/sam3_conv.wgsl create mode 100644 crates/gpu/src/wgsl/sam3_neck.wgsl create mode 100644 crates/gpu/tests/it/sam3_necks.rs diff --git a/crates/gpu/examples/sam3_backbone_bench.rs b/crates/gpu/examples/sam3_backbone_bench.rs index 05a001308e..9f6c8ebe11 100644 --- a/crates/gpu/examples/sam3_backbone_bench.rs +++ b/crates/gpu/examples/sam3_backbone_bench.rs @@ -1,17 +1,20 @@ -//! Times the SAM 3 backbone on the GPU (wgpu) against the candle backbone on the CPU, on a procedural photo. +//! Times the SAM 3 backbone and both necks on the GPU (wgpu) against the candle backbone on the CPU, on a procedural +//! photo. //! //! `cargo run --release -p lightcraft-gpu --features sam --example sam3_backbone_bench -- [--f16] [--runs N] [--no-cpu]` //! //! 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, 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, the rest in candle on the CPU): encode, click features, first click, first and second Describe. +//! 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 and necks, 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). use std::path::PathBuf; use std::time::Instant; use lightcraft_gpu::sam3::{self, Precision}; -use lightcraft_segment::{BackboneAccel, INPUT, Sam3}; +use lightcraft_segment::{BackboneAccel, INPUT, NeckKind, Sam3, WeightReader}; fn model_dir() -> Option { let dir = match std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()) { @@ -31,6 +34,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 dir = model_dir().ok_or("no SAM 3 model: set LIGHTCRAFT_SAM3_DIR")?; let scene = &lightcraft_scenes::demo_library()[0]; @@ -41,7 +45,7 @@ fn main() -> Result<(), String> { let t = Instant::now(); let adapter = sam3::adapter()?; println!("device + kernels: {:7.1} ms ({adapter})", t.elapsed().as_secs_f64() * 1e3); - let reader = lightcraft_segment::WeightReader::open(&dir).map_err(|e| e.to_string())?; + let reader = WeightReader::open(&dir).map_err(|e| e.to_string())?; let t = Instant::now(); let gpu = sam3::load(&reader, precision)?; println!( @@ -63,6 +67,14 @@ fn main() -> Result<(), String> { sum += ms; } println!("warm forward: {:7.1} ms (mean of {runs}: {:.1} ms)", best, sum / runs.max(1) as f64); + // a head that fails here is reported, and the `--app` run below still measures its fallback to candle + for which in [NeckKind::Tracker, NeckKind::Detector] { + match timed(runs, || gpu.neck(which, &out, 3).map(drop)) { + Ok((first, best, mean)) => println!("{which:?} neck: first {first:7.1} ms, warm {best:.1} ms (mean of {runs}: {mean:.1} ms)"), + Err(e) => println!("{which:?} neck failed on the GPU: {e}"), + } + } + println!("neck device memory: {:.0} MB", gpu.neck_bytes() as f64 / 1e6); 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())?; @@ -84,7 +96,7 @@ fn main() -> Result<(), String> { } drop(gpu); if app { - as_the_app(&dir, &rgb, (img.width, img.height), runs)?; + as_the_app(&dir, &rgb, (img.width, img.height), runs, cpu_necks)?; } // no GPU work in flight when the process ends (issue #620) lightcraft_gpu::begin_shutdown(); @@ -92,14 +104,72 @@ fn main() -> Result<(), String> { Ok(()) } +/// `f` once (its first run, in ms), then `runs` times: (first, best, mean) in milliseconds; the first error ends it. +fn timed(runs: usize, mut f: impl FnMut() -> Result<(), String>) -> Result<(f64, f64, f64), String> { + let t = Instant::now(); + f()?; + let first = t.elapsed().as_secs_f64() * 1e3; + let (mut best, mut sum) = (f64::MAX, 0.0); + for _ in 0..runs { + let t = Instant::now(); + f()?; + let ms = t.elapsed().as_secs_f64() * 1e3; + best = best.min(ms); + sum += ms; + } + Ok((first, best, sum / runs.max(1) as f64)) +} + 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`). +struct Heads { + gpu: Box, + necks: bool, +} + +impl BackboneAccel for Heads { + fn forward(&self, pixels: &[f32]) -> Result, String> { + self.gpu.forward(pixels) + } + fn device(&self) -> String { + self.gpu.device() + } + fn runs_necks(&self) -> bool { + self.necks && self.gpu.runs_necks() + } + fn runs_detr_encoder(&self) -> bool { + self.gpu.runs_detr_encoder() + } + fn runs_mask_decoder(&self) -> bool { + self.gpu.runs_mask_decoder() + } + 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.gpu.mask_decoder(memory, text, valid, levels, rows, bias) + } +} + /// 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) -> Result<(), String> { +fn as_the_app(dir: &std::path::Path, rgb: &[u8], (w, h): (usize, usize), runs: usize, cpu_necks: bool) -> Result<(), String> { let t = Instant::now(); - let mut model = Sam3::load_accelerated(dir, candle_core::Device::Cpu, sam3::backbone).map_err(|e| e.to_string())?; + let make = |r: &WeightReader| -> Result, String> { Ok(Box::new(Heads { gpu: sam3::backbone(r)?, necks: !cpu_necks })) }; + 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 }; for run in 0..runs.max(1) { diff --git a/crates/gpu/src/sam3.rs b/crates/gpu/src/sam3.rs index bf37f72454..263599d373 100644 --- a/crates/gpu/src/sam3.rs +++ b/crates/gpu/src/sam3.rs @@ -14,8 +14,9 @@ //! `wgsl/sam3_attention.wgsl` (flash style: online softmax, the 16 × 5184² scores of a global layer never exist), //! `wgsl/sam3_ops.wgsl` (layer norm, RoPE, im2col, the final reorder). All of the dispatches, with their parameters //! and bind groups, are built once with the weights; a forward pass uploads the pixels, submits one command buffer -//! per layer and reads the result back once. No subgroups or shader-f16 needed. The necks and the text detector's -//! heads stay in candle on the CPU. +//! 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 text detector's heads stay in +//! candle on the CPU. //! //! 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 @@ -27,9 +28,10 @@ use std::sync::{Arc, Mutex, OnceLock, PoisonError}; use std::time::Duration; use bytemuck::Pod; -use lightcraft_segment::{BACKBONE_PREFIX, BackboneAccel, WeightReader}; +use lightcraft_segment::{BACKBONE_PREFIX, BackboneAccel, NeckKind, WeightReader}; use wgpu::util::DeviceExt; +mod neck; #[cfg(test)] mod tests; @@ -947,6 +949,8 @@ pub struct Sam3Gpu { /// Bytes of work buffers on the device. work_bytes: u64, precision: Precision, + /// The feature pyramids, built on first use. + necks: neck::Necks, } /// The SAM 3 backbone on the GPU with the checkpoint's weights uploaded, or why it can't run there (GPU off, missing, @@ -1040,7 +1044,8 @@ fn build_inner(dev: &'static Dev, weights: &WeightReader, precision: Precision) } g.channels_first(&x, &y, HIDDEN, GRID, WINDOW)?; let recorded = g.record(); - Ok(Sam3Gpu { dev, recorded, work: Mutex::new(Work { pixels, out: y, staging }), weight_bytes: ld.bytes, work_bytes, precision }) + 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, necks }) } /// Run `f`, the work of `stage`, turning a panic into a broken device (with the stage's name). @@ -1088,10 +1093,24 @@ impl BackboneAccel for Sam3Gpu { guarded("the SAM 3 backbone", || self.run(pixels)) } + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> 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); + } + guarded("a SAM 3 neck", || self.necks.run(self.dev, which, backbone, n)) + } + fn closing(&self) -> bool { crate::shutting_down() } + fn runs_necks(&self) -> bool { + true + } + fn device(&self) -> String { let weights = match self.precision { Precision::F32 => "", diff --git a/crates/gpu/src/sam3/neck.rs b/crates/gpu/src/sam3/neck.rs new file mode 100644 index 0000000000..1d42fd341f --- /dev/null +++ b/crates/gpu/src/sam3/neck.rs @@ -0,0 +1,425 @@ +//! SAM 3's feature pyramids on the GPU: the necks of `lightcraft-segment` (`neck.rs`, the reference) for the click +//! decoder (`tracker_neck`) and the text detector (`detector_model.vision_encoder.neck`), the three finest levels of +//! each (288, 144 and 72 per side, 256 channels), from the backbone's `[1024, 72, 72]`. +//! +//! Images are kept as pixel rows (`[pixels, channels]`), so every step is a product of the backbone's matrix kernel: +//! - a 2 × 2 stride-2 transposed convolution is one product per input pixel, `[pixels, cin] · [cin, 4 · cout]` +//! (the checkpoint's `[cin, cout, 2, 2]` laid out as `[(ky, kx, cout), cin]` on upload), whose row holds the +//! pixel's four outputs one after the other; GELU (erf) between the two of level 0 runs in its epilogue; +//! - `proj1` (1 × 1) is a plain product, and does not care in which order the pixels come; +//! - `unshuffle` (`wgsl/sam3_neck.wgsl`) then puts the pixels of the transposed convolutions in row-major order; +//! - `proj2` (3 × 3, padding 1) is the same kernel with an A-tile loader that reads the 9 · cin numbers of a pixel's +//! neighbourhood straight from the image (`wgsl/sam3_conv.wgsl`): an implicit GEMM, the im2col matrix (764 MB at +//! 288²) never exists; +//! - `to_chw` (`wgsl/sam3_ops.wgsl`) writes the channels-first result. +//! +//! Nothing is uploaded with the backbone: the kernels compile, the work buffers (~190 MB, shared by both necks) are +//! made and a neck's weights (~27 MB) are uploaded when that neck is first asked for. A level is one submission +//! and one read-back, so no buffer exceeds the backbone's limits. Level 3 (36², a max pool) is not needed by either +//! head and is not run here. + +use std::sync::{Mutex, OnceLock, PoisonError}; + +use lightcraft_segment::{NeckKind, WeightReader}; + +use super::{Dev, GRID, Graph, HIDDEN, Matmul, Precision, Recorded, TILE, TIMEOUT, buffer, matmul_source_with, pipeline, u32_of, upload}; + +#[cfg(test)] +pub(super) mod tests; + +/// Channels of every level. +const FPN: usize = 256; +/// Levels run here: 288², 144² and 72². +const LEVELS: usize = 3; + +/// The sizes of a neck: the backbone's side and channels, and the channels of the levels (SAM 3's, or small ones +/// in tests). +#[derive(Clone, Copy, Debug)] +struct Sizes { + grid: usize, + hidden: usize, + fpn: usize, +} + +const SAM3: Sizes = Sizes { grid: GRID, hidden: HIDDEN, fpn: FPN }; + +impl Sizes { + /// Floats of the largest step of level 0: the second transposed convolution's output (4 · grid² · hidden), or a + /// 256-channel image of (4 · grid)² (both 85 MB for SAM 3). + fn largest(self) -> usize { + self.grid * self.grid * (4 * self.hidden).max(16 * self.fpn) + } +} + +/// Where a neck's tensors are in the checkpoint. +fn prefix(which: NeckKind) -> &'static str { + match which { + NeckKind::Tracker => "tracker_neck", + NeckKind::Detector => "detector_model.vision_encoder.neck", + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// kernels + +pub(super) struct Kernels { + /// The 3 × 3 convolution: the matrix product with the implicit-im2col A loader. + conv: Matmul, + to_rows: wgpu::ComputePipeline, + unshuffle: wgpu::ComputePipeline, +} + +static KERNELS: OnceLock> = OnceLock::new(); + +/// The neck's own kernels, compiled on first use (the backbone's are compiled with the device; the mask decoder uses +/// the 3 × 3 convolution too). +pub(super) fn kernels(dev: &'static Dev) -> Result<&'static Kernels, String> { + KERNELS + .get_or_init(|| { + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let pipe = |label: &str, source: &str, entry: &str| pipeline(&dev.device, &dev.pipeline_layout, label, source, entry); + let conv = matmul_source_with(TILE, false, Some(include_str!("../wgsl/sam3_conv.wgsl"))); + let ops = include_str!("../wgsl/sam3_neck.wgsl"); + let k = Kernels { + conv: Matmul { pipeline: pipe("sam3 conv3x3", &conv, "main"), tile: TILE }, + to_rows: pipe("sam3 neck", ops, "to_rows"), + unshuffle: pipe("sam3 neck", ops, "unshuffle"), + }; + if let Some(e) = pollster::block_on(validation.pop()) { + return Err(format!("{}: the SAM 3 neck kernels did not compile ({e})", dev.info.name)); + } + Ok(k) + }) + .as_ref() + .map_err(Clone::clone) +} + +impl Graph { + /// The 3 × 3 convolution (padding 1) of the image `x` (`[side², cin]`, cin a multiple of 4) with `w` + /// (`[cout, 3, 3, cin]`) and `bias` (`[cout]`) into `y` (`[side², cout]`). + pub(super) fn conv3( + &mut self, + k: &'static Kernels, + [x, w, bias, y]: [&wgpu::Buffer; 4], + side: usize, + (cin, cout): (usize, usize), + ) -> Result<(), String> { + if side == 0 || !cin.is_multiple_of(4) || cin == 0 || cout == 0 { + return Err(format!("a {side}² {cin} → {cout} convolution the SAM 3 kernel cannot do")); + } + let (m, depth) = (side * side, 9 * cin); + let params = [u32_of(m)?, u32_of(cout)?, u32_of(depth)?, 1, 0, 0, u32_of(side)?, 0]; + let groups = [u32_of(cout.div_ceil(k.conv.tile.bn()))?, u32_of(m.div_ceil(k.conv.tile.bm()))?, 1]; + if groups[1] > self.dev.limits.max_compute_workgroups_per_dimension { + return Err("an image too large for the SAM 3 convolution kernel".into()); + } + self.push(&k.conv.pipeline, params, [x, w, bias, y], groups); + Ok(()) + } + + /// `[channels, pixels]` (channels-first) to `[pixels, channels]`. + fn channels_last(&mut self, k: &'static Kernels, src: &wgpu::Buffer, dst: &wgpu::Buffer, channels: usize, pixels: usize) -> Result<(), String> { + let count = channels.checked_mul(pixels).ok_or("an image too large")?; + let (g, row) = self.flat(count.div_ceil(256))?; + let dummy = &self.dev.dummy; + self.push(&k.to_rows, [u32_of(channels)?, u32_of(pixels)?, 0, 0, 0, 0, u32_of(count)?, row], [src, dummy, dummy, dst], g); + Ok(()) + } + + /// The rows of a `side × side` image after `ups` 2 × 2 stride-2 transposed convolutions (in their order, see + /// `wgsl/sam3_neck.wgsl`) in row-major order. + fn unshuffle( + &mut self, + k: &'static Kernels, + src: &wgpu::Buffer, + dst: &wgpu::Buffer, + channels: usize, + side: usize, + ups: usize, + ) -> Result<(), String> { + if ups >= 16 || !side.is_multiple_of(1 << ups) { + return Err("a reorder the SAM 3 kernel cannot do".into()); + } + let count = channels.checked_mul(side * side).ok_or("an image too large")?; + let (g, row) = self.flat(count.div_ceil(256))?; + let dummy = &self.dev.dummy; + self.push(&k.unshuffle, [u32_of(channels)?, u32_of(side)?, u32_of(ups)?, 0, 0, 0, u32_of(count)?, row], [src, dummy, dummy, dst], g); + Ok(()) + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// weights + +/// A transposed convolution's weights `[cin, cout, 2, 2]` as the rows of a product: `[(ky · 2 + kx) · cout + co, ci]`. +fn transposed_rows(w: &[f32], cin: usize, cout: usize) -> Vec { + let mut out = vec![0f32; w.len()]; + for ci in 0..cin { + for co in 0..cout { + for q in 0..4 { + if let (Some(o), Some(v)) = (out.get_mut((q * cout + co) * cin + ci), w.get((ci * cout + co) * 4 + q)) { + *o = *v; + } + } + } + } + out +} + +/// A convolution's weights `[cout, cin, k, k]` in the order of the convolution's A columns: `[cout, k, k, cin]`. +fn conv_rows(w: &[f32], cout: usize, cin: usize, k: usize) -> Vec { + let taps = k * k; + let mut out = vec![0f32; w.len()]; + for co in 0..cout { + for ci in 0..cin { + for t in 0..taps { + if let (Some(o), Some(v)) = (out.get_mut((co * taps + t) * cin + ci), w.get((co * cin + ci) * taps + t)) { + *o = *v; + } + } + } + } + out +} + +/// A transposed convolution's weight `[cin, cout, 2, 2]` and bias on the device: rows `[4 · cout, cin]`, and the +/// bias repeated for the four outputs. +fn transposed_weights(dev: &Dev, label: &str, w: &[f32], b: &[f32], cin: usize, cout: usize) -> [wgpu::Buffer; 2] { + [upload(dev, label, &transposed_rows(w, cin, cout)), upload(dev, label, &b.repeat(4))] +} + +/// A `k × k` convolution's weight `[cout, cin, k, k]` and bias on the device: rows `[cout, k, k, cin]`. +pub(super) fn conv_weights(dev: &Dev, label: &str, w: &[f32], b: &[f32], (cin, cout, k): (usize, usize, usize)) -> [wgpu::Buffer; 2] { + [upload(dev, label, &conv_rows(w, cout, cin, k)), upload(dev, label, b)] +} + +/// One level's weights on the device: the transposed convolutions (none, one or two), `proj1`, `proj2`. +struct LevelWeights { + up: Vec<[wgpu::Buffer; 2]>, + proj1: [wgpu::Buffer; 2], + proj2: [wgpu::Buffer; 2], +} + +/// Reads a neck's tensors, checking their shapes. +struct Loader<'a> { + weights: &'a WeightReader, + dev: &'static Dev, + prefix: &'static str, + bytes: u64, +} + +impl Loader<'_> { + fn read(&self, name: &str, shape: &[usize]) -> Result, String> { + let full = format!("{}.{name}", self.prefix); + let (got, data) = self.weights.read(&full).map_err(|e| format!("{full}: {e}"))?; + if got != shape { + return Err(format!("{full}: shape {got:?}, expected {shape:?}")); + } + Ok(data) + } + + /// A 2 × 2 stride-2 transposed convolution. + fn transposed(&mut self, name: &str, cin: usize, cout: usize) -> Result<[wgpu::Buffer; 2], String> { + let w = self.read(&format!("{name}.weight"), &[cin, cout, 2, 2])?; + let b = self.read(&format!("{name}.bias"), &[cout])?; + self.bytes += (w.len() + 4 * b.len()) as u64 * 4; + Ok(transposed_weights(self.dev, name, &w, &b, cin, cout)) + } + + /// A `k × k` convolution. + fn conv(&mut self, name: &str, cin: usize, cout: usize, k: usize) -> Result<[wgpu::Buffer; 2], String> { + let w = self.read(&format!("{name}.weight"), &[cout, cin, k, k])?; + let b = self.read(&format!("{name}.bias"), &[cout])?; + self.bytes += (w.len() + b.len()) as u64 * 4; + Ok(conv_weights(self.dev, name, &w, &b, (cin, cout, k))) + } + + /// Level `i` (0: 4× up, 1: 2× up, 2: as is). + fn level(&mut self, i: usize) -> Result { + let l = format!("fpn_layers.{i}"); + let s = format!("{l}.scale_layers"); + let (up, inter) = match i { + 0 => ( + vec![self.transposed(&format!("{s}.0"), HIDDEN, HIDDEN / 2)?, self.transposed(&format!("{s}.2"), HIDDEN / 2, HIDDEN / 4)?], + HIDDEN / 4, + ), + 1 => (vec![self.transposed(&format!("{s}.0"), HIDDEN, HIDDEN / 2)?], HIDDEN / 2), + 2 => (Vec::new(), HIDDEN), + _ => return Err(format!("level {i} of the SAM 3 neck does not run on the GPU")), + }; + Ok(LevelWeights { up, proj1: self.conv(&format!("{l}.proj1"), inter, FPN, 1)?, proj2: self.conv(&format!("{l}.proj2"), FPN, FPN, 3)? }) + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// the necks + +/// The work buffers, shared by both necks (one runs at a time): the backbone as pixel rows, two buffers the steps +/// alternate between (the backbone's upload lands in the first), and the read-back. +struct Work { + x: wgpu::Buffer, + a: wgpu::Buffer, + b: wgpu::Buffer, + staging: wgpu::Buffer, +} + +impl Work { + fn new(dev: &Dev, sizes: Sizes) -> Work { + let largest = sizes.largest(); + Work { + x: buffer(dev, "sam3 neck input", sizes.hidden * sizes.grid * sizes.grid), + a: buffer(dev, "sam3 neck ping", largest), + b: buffer(dev, "sam3 neck pong", largest), + staging: dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("sam3 neck read-back"), + size: (largest.max(4) * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }), + } + } + + /// Bytes on the device: the read-back buffer is host memory on discrete GPUs and not counted. + fn bytes(sizes: Sizes) -> u64 { + ((sizes.hidden * sizes.grid * sizes.grid + 2 * sizes.largest()) * 4) as u64 + } +} + +/// One level, recorded: its dispatches, and the buffer its `[256, side, side]` result ends in (`len` floats). +struct Level { + recorded: Recorded, + out: wgpu::Buffer, + len: usize, +} + +/// A neck with its weights uploaded and its levels recorded. +struct Built { + levels: Vec, + weight_bytes: u64, +} + +/// The dispatches of level `i` from the pixel rows in `work.x` (level 0 first fills them from the channels-first +/// upload in `work.a`). +fn record_level(dev: &'static Dev, k: &'static Kernels, work: &Work, w: &LevelWeights, i: usize, sizes: Sizes) -> Result { + let Sizes { grid, hidden, fpn } = sizes; + let mut g = Graph::new(dev); + if i == 0 { + g.channels_last(k, &work.a, &work.x, hidden, grid * grid)?; + } + let mut spare = [&work.a, &work.b].into_iter().cycle(); + let mut next = || spare.next().ok_or_else(|| "no work buffer".to_string()); + let (mut cur, mut pixels, mut channels, mut side) = (&work.x, grid * grid, hidden, grid); + for (j, [weight, bias]) in w.up.iter().enumerate() { + let cout = channels / 2; + let dst = next()?; + // GELU between the two of level 0 + g.matmul([cur, weight, bias, dst], (pixels, 4 * cout, channels), 1, j + 1 < w.up.len(), false, Precision::F32)?; + (cur, pixels, channels, side) = (dst, pixels * 4, cout, side * 2); + } + let dst = next()?; + g.matmul([cur, &w.proj1[0], &w.proj1[1], dst], (pixels, fpn, channels), 1, false, false, Precision::F32)?; + cur = dst; + if !w.up.is_empty() { + let dst = next()?; + g.unshuffle(k, cur, dst, fpn, side, w.up.len())?; + cur = dst; + } + let dst = next()?; + g.conv3(k, [cur, &w.proj2[0], &w.proj2[1], dst], side, (fpn, fpn))?; + cur = dst; + let dst = next()?; + g.channels_first(cur, dst, fpn, side, side)?; + Ok(Level { recorded: g.record(), out: dst.clone(), len: fpn * side * side }) +} + +fn build(dev: &'static Dev, k: &'static Kernels, weights: &WeightReader, which: NeckKind, work: &Work) -> Result { + let mut ld = Loader { weights, dev, prefix: prefix(which), bytes: 0 }; + let mut levels = Vec::with_capacity(LEVELS); + for i in 0..LEVELS { + let w = ld.level(i)?; + levels.push(record_level(dev, k, work, &w, i, SAM3)?); + } + Ok(Built { levels, weight_bytes: ld.bytes }) +} + +/// Run `f` (buffer creation and uploads for `stage`), turning the device's out-of-memory and validation errors into an +/// `Err` that names the stage. +pub(super) fn scoped(dev: &Dev, stage: &str, f: impl FnOnce() -> Result) -> Result { + let oom = dev.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let made = f(); + // let the uploads land before the scopes close + let _ = dev.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(TIMEOUT) }); + let (validation, oom) = (pollster::block_on(validation.pop()), pollster::block_on(oom.pop())); + if let Some(e) = oom { + return Err(format!("not enough GPU memory for {stage}: {e}")); + } + if let Some(e) = validation { + return Err(format!("the GPU rejected {stage}: {e}")); + } + made +} + +#[derive(Default)] +struct State { + work: Option, + tracker: Option, + detector: Option, +} + +/// Both necks of a backbone on the GPU, each built when first run. +pub(super) struct Necks { + weights: WeightReader, + state: Mutex, +} + +impl Necks { + pub(super) fn new(weights: WeightReader) -> Necks { + Necks { weights, state: Mutex::new(State::default()) } + } + + /// The `n` finest levels of the `which` neck for `backbone` (`[1024, 72, 72]`), each `[256, s, s]`. + pub(super) fn run(&self, dev: &'static Dev, which: NeckKind, backbone: &[f32], n: usize) -> Result>, String> { + if n > LEVELS { + return Err(format!("{n} levels asked for; the GPU neck makes the {LEVELS} finest")); + } + if backbone.len() != HIDDEN * GRID * GRID { + return Err(format!("{} backbone values, expected {HIDDEN} × {GRID} × {GRID}", backbone.len())); + } + let Some(_work) = crate::exit::enter() else { return Err("LightCraft is closing".into()) }; + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + let State { work, tracker, detector } = &mut *state; + let work = match work { + Some(w) => w, + None => work.insert(scoped(dev, "the SAM 3 necks", || Ok(Work::new(dev, SAM3)))?), + }; + let built = match which { + NeckKind::Tracker => tracker, + NeckKind::Detector => detector, + }; + let built = match built { + Some(b) => b, + None => { + let k = kernels(dev)?; + built.insert(scoped(dev, "a SAM 3 neck", || build(dev, k, &self.weights, which, work))?) + } + }; + dev.queue.write_buffer(&work.a, 0, bytemuck::cast_slice(backbone)); + built.levels.iter().take(n).map(|l| l.recorded.run("a SAM 3 neck", dev, &l.out, &work.staging, l.len)).collect() + } + + /// Device memory the necks built so far take (weights and work buffers). + fn bytes(&self) -> u64 { + let state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + let weights: u64 = [&state.tracker, &state.detector].into_iter().flatten().map(|b| b.weight_bytes).sum(); + weights + if state.work.is_some() { Work::bytes(SAM3) } else { 0 } + } +} + +impl super::Sam3Gpu { + /// Bytes of device memory the necks run so far take (0 before the first): their weights and the work buffers + /// they share. + pub fn neck_bytes(&self) -> u64 { + self.necks.bytes() + } +} diff --git a/crates/gpu/src/sam3/neck/tests.rs b/crates/gpu/src/sam3/neck/tests.rs new file mode 100644 index 0000000000..d7b1ec668e --- /dev/null +++ b/crates/gpu/src/sam3/neck/tests.rs @@ -0,0 +1,215 @@ +//! The neck kernels against plain loops in f64 (odd sizes, every border of the 3 × 3 convolution, tiles cut off), and +//! a whole small neck against a direct transcription of `Neck::forward`. The real necks against candle: +//! `tests/it/sam3_backbone.rs`. + +use super::super::tests::{gelu, gpu, read, values, worst}; +use super::*; + +/// The neck's kernels on the test device; a kernel that doesn't compile is a failure. +fn neck_kernels(d: &'static Dev) -> &'static Kernels { + kernels(d).unwrap() +} + +/// PyTorch's `ConvTranspose2d(cin, cout, 2, stride 2)` on pixel rows `x` (`[side², cin]`), weight `[cin, cout, 2, 2]`: +/// `[(2 · side)², cout]`, row-major. +fn conv_transpose_ref(x: &[f64], side: usize, (cin, cout): (usize, usize), w: &[f32], b: &[f32]) -> Vec { + let out_side = 2 * side; + let mut y = vec![0f64; out_side * out_side * cout]; + for i in 0..side { + for j in 0..side { + for ky in 0..2 { + for kx in 0..2 { + for co in 0..cout { + let mut v = b[co] as f64; + for ci in 0..cin { + v += x[(i * side + j) * cin + ci] * w[((ci * cout + co) * 2 + ky) * 2 + kx] as f64; + } + y[((2 * i + ky) * out_side + 2 * j + kx) * cout + co] = v; + } + } + } + } + } + y +} + +/// PyTorch's `Conv2d(cin, cout, k, padding k / 2)` on pixel rows `x` (`[side², cin]`), weight `[cout, cin, k, k]`: +/// `[side², cout]`. +pub(in crate::sam3) fn conv_ref(x: &[f64], side: usize, (cin, cout, k): (usize, usize, usize), w: &[f32], b: &[f32]) -> Vec { + let pad = (k / 2) as isize; + let mut y = vec![0f64; side * side * cout]; + for r in 0..side { + for c in 0..side { + for co in 0..cout { + let mut v = b[co] as f64; + for ky in 0..k { + for kx in 0..k { + let (rr, cc) = (r as isize + ky as isize - pad, c as isize + kx as isize - pad); + if rr < 0 || cc < 0 || rr >= side as isize || cc >= side as isize { + continue; + } + let at = (rr as usize * side + cc as usize) * cin; + for ci in 0..cin { + v += x[at + ci] * w[((co * cin + ci) * k + ky) * k + kx] as f64; + } + } + } + y[(r * side + c) * cout + co] = v; + } + } + } + y +} + +pub(in crate::sam3) fn f32s(v: &[f64]) -> Vec { + v.iter().map(|x| *x as f32).collect() +} + +pub(in crate::sam3) fn f64s(v: &[f32]) -> Vec { + v.iter().map(|x| *x as f64).collect() +} + +#[test] +fn weights_are_laid_out_as_the_products_read_them() { + // ConvTranspose2d [cin 2, cout 3, 2, 2]: value = 1000 ci + 100 co + 10 ky + kx; rows [(ky, kx, co), ci] + let w: Vec = + (0..2).flat_map(|ci| (0..3).flat_map(move |co| (0..4).map(move |q| (1000 * ci + 100 * co + 10 * (q / 2) + q % 2) as f32))).collect(); + let rows = transposed_rows(&w, 2, 3); + assert_eq!(rows[(3 * 3 + 2) * 2 + 1], 1211.0); + assert_eq!(rows[3 * 2], 1.0); + // Conv2d [cout 2, cin 3, 3, 3]: value = 1000 co + 100 ci + 10 ky + kx; rows [cout, ky, kx, cin] + let w: Vec = + (0..2).flat_map(|co| (0..3).flat_map(move |ci| (0..9).map(move |t| (1000 * co + 100 * ci + 10 * (t / 3) + t % 3) as f32))).collect(); + let rows = conv_rows(&w, 2, 3, 3); + assert_eq!(rows[(9 + 2 * 3 + 1) * 3 + 2], 1221.0); + assert_eq!(rows[4 * 3], 11.0); +} + +#[test] +fn transposed_convolutions_and_the_reorder_give_the_definition() { + let Some(d) = gpu() else { return }; + let k = neck_kernels(d); + // one up-sampling (odd side, cut-off tiles), and two with GELU between as in level 0 + for (case, (side, chans)) in [(5usize, vec![8usize, 6]), (3, vec![12, 8, 4]), (9, vec![4, 68])].into_iter().enumerate() { + let x = values(side * side * chans[0], 10 + case as u64, 1.0); + let mut want = f64s(&x); + let mut s = side; + let mut g = Graph::new(d); + let mut cur = upload(d, "x", &x); + for (j, pair) in chans.windows(2).enumerate() { + let (cin, cout) = (pair[0], pair[1]); + let w = values(cin * cout * 4, 20 + j as u64, 0.3); + let b = values(cout, 30 + j as u64, 0.5); + let gelu_after = j + 2 < chans.len(); + want = conv_transpose_ref(&want, s, (cin, cout), &w, &b); + if gelu_after { + want.iter_mut().for_each(|v| *v = gelu(*v)); + } + let [bw, bb] = transposed_weights(d, "w", &w, &b, cin, cout); + let y = buffer(d, "y", s * s * 4 * cout); + g.matmul([&cur, &bw, &bb, &y], (s * s, 4 * cout, cin), 1, gelu_after, false, Precision::F32).unwrap(); + cur = y; + s *= 2; + } + let cout = *chans.last().unwrap(); + let out = buffer(d, "out", s * s * cout); + g.unshuffle(k, &cur, &out, cout, s, chans.len() - 1).unwrap(); + let got = read(d, g, &out, s * s * cout); + let err = worst(&got, &f32s(&want)); + assert!(err < 1e-4, "case {case}: off by {err}"); + } +} + +#[test] +fn the_3x3_convolution_gives_the_definition_at_every_border() { + let Some(d) = gpu() else { return }; + let k = neck_kernels(d); + // odd sides, a single pixel (all border), N not a multiple of the tile, more pixels than one tile + for (case, (side, cin, cout)) in [(7usize, 12usize, 5usize), (1, 8, 3), (9, 4, 70), (17, 16, 64), (2, 256, 9)].into_iter().enumerate() { + let x = values(side * side * cin, 40 + case as u64, 1.0); + let w = values(cout * cin * 9, 50 + case as u64, 0.2); + let b = values(cout, 60 + case as u64, 0.5); + let [bw, bb] = conv_weights(d, "w", &w, &b, (cin, cout, 3)); + let (bx, by) = (upload(d, "x", &x), buffer(d, "y", side * side * cout)); + let mut g = Graph::new(d); + g.conv3(k, [&bx, &bw, &bb, &by], side, (cin, cout)).unwrap(); + let got = read(d, g, &by, side * side * cout); + let want = f32s(&conv_ref(&f64s(&x), side, (cin, cout, 3), &w, &b)); + let err = worst(&got, &want); + assert!(err < 2e-5 * ((9 * cin) as f32).sqrt(), "case {case} ({side}² {cin} → {cout}): off by {err}"); + } +} + +#[test] +fn the_neck_kernels_refuse_what_they_cannot_do() { + let Some(d) = gpu() else { return }; + let k = neck_kernels(d); + let b = buffer(d, "b", 16); + let mut g = Graph::new(d); + assert!(g.conv3(k, [&b, &b, &b, &b], 4, (6, 8)).is_err(), "channels not a multiple of 4"); + assert!(g.conv3(k, [&b, &b, &b, &b], 0, (8, 8)).is_err(), "an empty image"); + assert!(g.unshuffle(k, &b, &b, 4, 6, 2).is_err(), "a side that is not a multiple of 2^ups"); +} + +/// A neck level's weights in the checkpoint's layouts: the transposed convolutions (weight, bias, cin, cout), +/// `proj1` (weight, bias, cin) and `proj2`. +struct RefLevel { + up: Vec<(Vec, Vec, usize, usize)>, + proj1: (Vec, Vec, usize), + proj2: (Vec, Vec), +} + +/// `Neck::forward` for one level on the channels-first backbone `x`, in f64: `[fpn, side, side]`. +fn level_ref(x: &[f32], sizes: Sizes, l: &RefLevel) -> Vec { + let Sizes { grid, hidden, fpn } = sizes; + let mut rows: Vec = (0..grid * grid).flat_map(|p| (0..hidden).map(move |c| x[c * grid * grid + p] as f64)).collect(); + let mut side = grid; + for (j, (w, b, cin, cout)) in l.up.iter().enumerate() { + rows = conv_transpose_ref(&rows, side, (*cin, *cout), w, b); + if j + 1 < l.up.len() { + rows.iter_mut().for_each(|v| *v = gelu(*v)); + } + side *= 2; + } + let (w1, b1, inter) = &l.proj1; + let rows = conv_ref(&rows, side, (*inter, fpn, 1), w1, b1); + let rows = conv_ref(&rows, side, (fpn, fpn, 3), &l.proj2.0, &l.proj2.1); + (0..fpn).flat_map(|c| (0..side * side).map(move |p| (c, p))).map(|(c, p)| rows[p * fpn + c] as f32).collect() +} + +#[test] +fn a_small_neck_gives_what_the_reference_neck_gives() { + let Some(d) = gpu() else { return }; + let k = neck_kernels(d); + let sizes = Sizes { grid: 6, hidden: 32, fpn: 8 }; + let Sizes { grid, hidden, fpn } = sizes; + let x = values(hidden * grid * grid, 70, 1.0); + let work = Work::new(d, sizes); + d.queue.write_buffer(&work.a, 0, bytemuck::cast_slice(&x)); + let mut seed = 80; + let mut next = |n: usize, scale: f32| { + seed += 1; + values(n, seed, scale) + }; + // in order: level 0 turns the upload into the pixel rows the others read + for i in 0..LEVELS { + let chans: Vec = match i { + 0 => vec![hidden, hidden / 2, hidden / 4], + 1 => vec![hidden, hidden / 2], + _ => vec![hidden], + }; + let up: Vec<_> = chans.windows(2).map(|p| (next(p[0] * p[1] * 4, 0.3), next(p[1], 0.3), p[0], p[1])).collect(); + let inter = *chans.last().unwrap(); + let r = RefLevel { up, proj1: (next(fpn * inter, 0.3), next(fpn, 0.3), inter), proj2: (next(fpn * fpn * 9, 0.2), next(fpn, 0.3)) }; + let w = LevelWeights { + up: r.up.iter().map(|(w, b, cin, cout)| transposed_weights(d, "up", w, b, *cin, *cout)).collect(), + proj1: conv_weights(d, "proj1", &r.proj1.0, &r.proj1.1, (inter, fpn, 1)), + proj2: conv_weights(d, "proj2", &r.proj2.0, &r.proj2.1, (fpn, fpn, 3)), + }; + let level = record_level(d, k, &work, &w, i, sizes).unwrap(); + let got = level.recorded.run("a test", d, &level.out, &work.staging, level.len).unwrap(); + let want = level_ref(&x, sizes, &r); + let err = worst(&got, &want); + assert!(err < 1e-4, "level {i}: off by {err}"); + } +} diff --git a/crates/gpu/src/wgsl/sam3_conv.wgsl b/crates/gpu/src/wgsl/sam3_conv.wgsl new file mode 100644 index 0000000000..67cc55ef73 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_conv.wgsl @@ -0,0 +1,29 @@ +// The A-tile loader of the necks' 3 x 3 convolution (`sam3/neck.rs`, padding 1, stride 1): spliced into +// `sam3_matmul.wgsl` in place of its dense `load_a`, so the convolution is that kernel's product over an im2col +// matrix that is never stored (an implicit GEMM; at 288 x 288 x 256 the stored one would be 764 MB). +// +// X [side², cin] the image, pixels row-major, channels last (cin a multiple of 4) +// A [side², 9 · cin] row m: output pixel (m / side, m % side); column k = tap · cin + c: input channel c of the +// pixel at tap (ky, kx) = (tap / 3, tap % 3), i.e. (row + ky − 1, col + kx − 1), zero outside the image +// W [cout, 9 · cin] the weights in the same (ky, kx, c) order +// +// A vector of four k is four channels of one pixel, so it is one aligned load from X. + +// Vector e of the A tile at k0 (row e / KV); zero outside the image (the padding) and outside A. +fn load_a(m0: u32, k0: u32, e: u32) -> vec4 { + let m = m0 + e / KV; + let kq = k0 / 4u + e % KV; + let k4 = p.k / 4u; + if (m >= p.m || kq >= k4) { + return vec4(0.0); + } + let side = p.side; + let c4 = k4 / 9u; + let tap = kq / c4; + let row = i32(m / side) + i32(tap / 3u) - 1; + let col = i32(m % side) + i32(tap % 3u) - 1; + if (row < 0 || col < 0 || row >= i32(side) || col >= i32(side)) { + return vec4(0.0); + } + return x[(u32(row) * side + u32(col)) * c4 + kq % c4]; +} diff --git a/crates/gpu/src/wgsl/sam3_neck.wgsl b/crates/gpu/src/wgsl/sam3_neck.wgsl new file mode 100644 index 0000000000..db2853a1b4 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_neck.wgsl @@ -0,0 +1,60 @@ +// The reorderings of the SAM 3 necks (`sam3/neck.rs`) around their products: the backbone's channels-first output +// to pixel rows, and the rows of the transposed convolutions back to row-major. (Back to channels-first: `to_chw` +// of `sam3_ops.wgsl`, with one window over the whole image.) +// +// 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; +} + +// Channels-first to pixel rows (a: channels, b: pixels): dst[pixel, ch] = src[ch, pixel]. +@compute @workgroup_size(256) +fn to_rows(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + dst[g] = src[g % p.a * p.b + g / p.a]; +} + +// Pixel rows after `c` 2 x 2 stride-2 transposed convolutions to row-major (a: channels, b: side). Such a convolution +// is one product per input pixel whose row holds its four output pixels (ky, kx) one after the other, so after c of +// them the pixels of the side x side image come ordered by (row >> c, col >> c), then the (ky, kx) of the first, …, +// of the last: dst[row · side + col, ch] = src[that position, ch]. +@compute @workgroup_size(256) +fn unshuffle(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let side = p.b; + let ups = p.c; + let ch = g % p.a; + let pixel = g / p.a; + let row = pixel / side; + let col = pixel % side; + var at = (row >> ups) * (side >> ups) + (col >> ups); + for (var s = ups; s > 0u; s--) { + at = at * 4u + ((row >> (s - 1u)) & 1u) * 2u + ((col >> (s - 1u)) & 1u); + } + dst[g] = src[at * p.a + ch]; +} diff --git a/crates/gpu/tests/it/main.rs b/crates/gpu/tests/it/main.rs index 184916cfb0..0d1aa1303f 100644 --- a/crates/gpu/tests/it/main.rs +++ b/crates/gpu/tests/it/main.rs @@ -9,3 +9,5 @@ mod fallback; mod gpu_probe; #[cfg(feature = "sam")] mod sam3_backbone; +#[cfg(feature = "sam")] +mod sam3_necks; diff --git a/crates/gpu/tests/it/sam3_necks.rs b/crates/gpu/tests/it/sam3_necks.rs new file mode 100644 index 0000000000..8529162de7 --- /dev/null +++ b/crates/gpu/tests/it/sam3_necks.rs @@ -0,0 +1,165 @@ +//! SAM 3's two necks on the GPU against the candle necks on the CPU (the reference), on one photo: every level, and +//! what the difference does to the masks downstream (click masks and a Describe mask). Both models get the same +//! GPU backbone output, so only the necks differ. +//! +//! Needs the checkpoint: `LIGHTCRAFT_SAM3_DIR= cargo test --release -p lightcraft-gpu --features sam +//! --test it sam3_necks:: -- --nocapture`. `LIGHTCRAFT_SAM3_PROMPT` names the Describe prompt (default "sky"). 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, Click, INPUT, NeckKind, Sam3}; + +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 } +} + +/// The largest |Δ| between two masks' logits, and between the masks themselves (their sigmoid, 0..1). +fn mask_diff(a: &[f32], b: &[f32]) -> (f32, f32) { + let sigmoid = |v: f32| 1.0 / (1.0 + (-v).exp()); + a.iter().zip(b).fold((0f32, 0f32), |(l, m), (x, y)| (l.max((x - y).abs()), m.max((sigmoid(*x) - sigmoid(*y)).abs()))) +} + +/// One GPU backbone for both models: with its necks (counting the levels it hands out), or without (candle's run). +struct Shared { + gpu: Arc, + necks: bool, + runs: 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 neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> Result>, String> { + if !self.necks { + return Err("necks off".into()); + } + let levels = self.gpu.neck(which, backbone, n)?; + self.runs.fetch_add(1, Ordering::Relaxed); + Ok(levels) + } +} + +#[test] +fn the_gpu_necks_match_the_cpu_necks() { + 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 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(); + let pixels = Tensor::from_vec(px, (1, 3, INPUT, INPUT), &Device::Cpu).unwrap(); + + let reader = lightcraft_segment::WeightReader::open(&dir).unwrap(); + let gpu = Arc::new(sam3::load(&reader, Precision::F32).unwrap()); + let runs = Arc::new(AtomicUsize::new(0)); + let accel = |necks: bool| { + let shared = Shared { gpu: gpu.clone(), necks, runs: runs.clone() }; + move |_: &lightcraft_segment::WeightReader| -> Result, String> { Ok(Box::new(shared)) } + }; + let mut cpu = Sam3::load_accelerated(&dir, Device::Cpu, accel(false)).unwrap(); + let mut on_gpu = Sam3::load_accelerated(&dir, Device::Cpu, accel(true)).unwrap(); + let mut want = cpu.encode_pixels(&pixels).unwrap(); + let mut got = on_gpu.encode_pixels(&pixels).unwrap(); + assert_eq!(values(want.backbone()), values(got.backbone()), "the same backbone output for both"); + + for which in [NeckKind::Tracker, NeckKind::Detector] { + let t = Instant::now(); + let reference = cpu.neck_levels(which, &want).unwrap(); + eprintln!("{which:?} neck, CPU: {:?}", t.elapsed()); + let before = runs.load(Ordering::Relaxed); + let t = Instant::now(); + let levels = on_gpu.neck_levels(which, &got).unwrap(); + eprintln!("{which:?} neck, GPU (first, builds it): {:?} on {adapter}", t.elapsed()); + let t = Instant::now(); + on_gpu.neck_levels(which, &got).unwrap(); + eprintln!("{which:?} neck, GPU (again): {:?}", t.elapsed()); + assert_eq!(runs.load(Ordering::Relaxed), before + 2, "{which:?}: the GPU neck ran"); + for (i, (g, c)) in levels.iter().zip(&reference).enumerate() { + assert_eq!(g.dims(), c.dims(), "{which:?} level {i}"); + let (_, rel, mean) = errors(&format!("{which:?} level {i}"), &values(g), &values(c)); + assert!(rel < 1e-4 && mean < 1e-5, "{which:?} level {i} is off"); + } + } + + // a click mask (the tracker head) and a Describe mask (the detector head) from both + for click in [Click { x: 0.5, y: 0.6, positive: true }, Click { x: 0.3, y: 0.3, positive: true }] { + let (m_cpu, m_gpu) = (cpu.segment_clicks(&mut want, &[click]).unwrap(), on_gpu.segment_clicks(&mut got, &[click]).unwrap()); + let i = iou(&m_gpu.logits, &m_cpu.logits); + let (dl, dm) = mask_diff(&m_gpu.logits, &m_cpu.logits); + eprintln!( + "click ({}, {}): mask IoU {i:.5}, max |Δ| logits {dl:.2e}, mask {dm:.2e}, score {:.4} vs {:.4}", + click.x, click.y, m_gpu.score, m_cpu.score + ); + assert!(i > 0.995, "click mask IoU {i}"); + } + let prompt = std::env::var("LIGHTCRAFT_SAM3_PROMPT").unwrap_or_else(|_| "sky".into()); + let (d_cpu, d_gpu) = (cpu.segment_text(&mut want, &prompt, 0.5).unwrap(), on_gpu.segment_text(&mut got, &prompt, 0.5).unwrap()); + match (d_cpu, d_gpu) { + (Some(c), Some(g)) => { + let i = iou(&g.logits, &c.logits); + let (dl, dm) = mask_diff(&g.logits, &c.logits); + let cover = c.logits.iter().filter(|v| **v > 0.0).count() as f32 / c.logits.len() as f32; + eprintln!( + "describe {prompt:?}: mask IoU {i:.5} (covers {:.1} %), max |Δ| logits {dl:.2e}, mask {dm:.2e}, score {:.4} vs {:.4}", + cover * 100.0, + g.score, + c.score + ); + assert!(i > 0.99, "describe mask IoU {i}"); + } + (None, None) => eprintln!("describe {prompt:?}: nothing found by either"), + (c, g) => panic!("describe {prompt:?}: CPU found {}, GPU {}", c.is_some(), g.is_some()), + } + assert_eq!(runs.load(Ordering::Relaxed), 4 + 2, "the clicks and the prompt used the GPU necks"); + eprintln!("neck device memory: {:.0} MB", gpu.neck_bytes() as f64 / 1e6); + drop((cpu, on_gpu, gpu)); + // no GPU work in flight when the process ends (issue #620) + lightcraft_gpu::begin_shutdown(); + lightcraft_gpu::wait_idle(std::time::Duration::from_secs(5)); +} From 502a61997af5a2193b67fe6dde61ba0f79d25618 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:52:46 +0200 Subject: [PATCH 035/331] M12: SAM 3 DETR encoder on the GPU (wgpu): the text detector's 6 layers over 5184 tokens Part 4 of 5 of #2167. The text detector's DETR encoder runs on the GPU device of the image encoder: the same matrix products (ReLU as a third epilogue), attention for 8 heads of 32 with separate q / k / v buffers and the prompt's key-padding bias. Its weights (~120 MB) load on the first text prompt. A failure leaves the encoder to candle for the rest of the session; the backbone and the necks stay on the GPU. The mask decoder is still in candle. The parity test prints the largest difference of every query's mask. Co-Authored-By: Claude Opus 5.5 --- crates/gpu/examples/sam3_backbone_bench.rs | 2 +- crates/gpu/src/sam3.rs | 32 +- crates/gpu/src/sam3/detr.rs | 356 +++++++++++++++++++++ crates/gpu/src/sam3/detr/tests.rs | 267 ++++++++++++++++ crates/gpu/src/wgsl/sam3_detr.wgsl | 105 ++++++ crates/gpu/tests/it/main.rs | 2 + crates/gpu/tests/it/sam3_detr.rs | 182 +++++++++++ 7 files changed, 942 insertions(+), 4 deletions(-) create mode 100644 crates/gpu/src/sam3/detr.rs create mode 100644 crates/gpu/src/sam3/detr/tests.rs create mode 100644 crates/gpu/src/wgsl/sam3_detr.wgsl create mode 100644 crates/gpu/tests/it/sam3_detr.rs diff --git a/crates/gpu/examples/sam3_backbone_bench.rs b/crates/gpu/examples/sam3_backbone_bench.rs index 9f6c8ebe11..700c53c0a2 100644 --- a/crates/gpu/examples/sam3_backbone_bench.rs +++ b/crates/gpu/examples/sam3_backbone_bench.rs @@ -6,7 +6,7 @@ //! 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 and necks, the rest in candle on the CPU): encode, +//! 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). diff --git a/crates/gpu/src/sam3.rs b/crates/gpu/src/sam3.rs index 263599d373..2265533336 100644 --- a/crates/gpu/src/sam3.rs +++ b/crates/gpu/src/sam3.rs @@ -15,8 +15,10 @@ //! `wgsl/sam3_ops.wgsl` (layer norm, RoPE, im2col, the final reorder). All of the dispatches, with their parameters //! and bind groups, are built once with the weights; a forward pass uploads the pixels, submits one command buffer //! 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 text detector's heads stay in -//! candle on the CPU. +//! 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 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 @@ -31,6 +33,7 @@ use bytemuck::Pod; use lightcraft_segment::{BACKBONE_PREFIX, BackboneAccel, NeckKind, WeightReader}; use wgpu::util::DeviceExt; +mod detr; mod neck; #[cfg(test)] mod tests; @@ -949,6 +952,8 @@ pub struct Sam3Gpu { /// Bytes of work buffers on the device. work_bytes: u64, precision: Precision, + /// The detector's DETR encoder, loaded on the first text prompt. + detr: detr::Encoder, /// The feature pyramids, built on first use. necks: neck::Necks, } @@ -1044,8 +1049,9 @@ fn build_inner(dev: &'static Dev, weights: &WeightReader, precision: Precision) } g.channels_first(&x, &y, HIDDEN, GRID, WINDOW)?; 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, necks }) + Ok(Sam3Gpu { dev, recorded, work: Mutex::new(Work { pixels, out: y, staging }), weight_bytes: ld.bytes, work_bytes, precision, detr, necks }) } /// Run `f`, the work of `stage`, turning a panic into a broken device (with the stage's name). @@ -1067,6 +1073,11 @@ impl Sam3Gpu { self.work_bytes + (TOKENS * HIDDEN * 4) as u64 } + /// Bytes of device memory the DETR encoder's weights and work buffers take, once a text prompt loaded them. + pub fn detr_bytes(&self) -> Option<(u64, u64)> { + self.detr.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())); @@ -1103,6 +1114,17 @@ impl BackboneAccel for Sam3Gpu { guarded("a SAM 3 neck", || self.necks.run(self.dev, which, backbone, n)) } + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> 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 DETR encoder", || self.detr.run(self.dev, image, pos, text, valid)) + } + fn closing(&self) -> bool { crate::shutting_down() } @@ -1111,6 +1133,10 @@ impl BackboneAccel for Sam3Gpu { true } + fn runs_detr_encoder(&self) -> bool { + true + } + fn device(&self) -> String { let weights = match self.precision { Precision::F32 => "", diff --git a/crates/gpu/src/sam3/detr.rs b/crates/gpu/src/sam3/detr.rs new file mode 100644 index 0000000000..a3e28c25cb --- /dev/null +++ b/crates/gpu/src/sam3/detr.rs @@ -0,0 +1,356 @@ +//! The DETR encoder of SAM 3's text detector on the GPU (`lightcraft-segment`'s `detector.rs` is the reference): six +//! layers over the 72 × 72 image tokens of 256, each self-attention (q and k from the normed tokens plus their sine +//! position encoding, v from the normed tokens) → cross-attention to the prompt's 32 tokens (with the key-padding bias) +//! → MLP 256 → 2048 → 256 with ReLU, each after a layer norm (eps 1e-5) and added to the tokens. ~4 s per prompt on +//! the CPU through candle. +//! +//! Kernels: the backbone's matrix product (ReLU in its epilogue) and layer norm, and `wgsl/sam3_detr.wgsl`: attention +//! with heads of 32 whose q, k and v come from separate buffers (the cross-attention's k and v from the prompt), with +//! an optional per-key bias, and a sum. The weights (38 MB) and the kernels load on the first prompt, not with the +//! backbone; then every dispatch is recorded once, and 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. + +use std::sync::{Mutex, OnceLock, PoisonError}; + +use lightcraft_segment::WeightReader; + +use super::{Dev, Graph, Precision, Recorded, TIMEOUT, buffer, pipeline, u32_of, upload}; + +#[cfg(test)] +mod tests; + +/// Where the encoder's weights are in the checkpoint. +const PREFIX: &str = "detector_model.detr_encoder"; +/// Image tokens (72 × 72), their width, the prompt's tokens. +const TOKENS: usize = 72 * 72; +const WIDTH: usize = 256; +const TEXT: usize = 32; +const HEAD_DIM: usize = 32; +const MLP: usize = 2048; +const LAYERS: usize = 6; +/// PyTorch's `nn.LayerNorm` default (`TORCH_LN_EPS`). +const EPS: f32 = 1e-5; +/// Keys per step of the attention kernel (the prompt's 32 tokens are one step). +const KEYS: u32 = 32; +/// `p.gelu` of the matrix product: ReLU. +const RELU: u32 = 2; +/// No bias in the attention kernel. +const NONE: u32 = u32::MAX; + +pub(super) struct Kernels { + attention: wgpu::ComputePipeline, + add: wgpu::ComputePipeline, +} + +static KERNELS: OnceLock> = OnceLock::new(); + +/// The encoder's kernels, compiled on first use (the mask decoder's prompt attention uses them too). +pub(super) 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 = attention_source(KEYS); + let pipe = |entry: &str| pipeline(&dev.device, &dev.pipeline_layout, "sam3 detr", &source, entry); + let k = Kernels { attention: pipe("attention"), add: pipe("add") }; + match pollster::block_on(validation.pop()) { + Some(e) => Err(format!("{}: the SAM 3 DETR kernels did not compile ({e})", dev.info.name)), + None => Ok(k), + } + }) + .as_ref() + .map_err(Clone::clone) +} + +/// The attention kernel for `keys` keys per step, written out from `wgsl/sam3_detr.wgsl` (as the backbone's). +fn attention_source(keys: u32) -> String { + use std::fmt::Write; + let d4 = (HEAD_DIM / 4) as u32; + let (mut decl, mut scores, mut rescale, mut acc, mut store) = (String::new(), String::new(), String::new(), String::new(), String::new()); + // writing into a String cannot fail + for c in 0..d4 { + let _ = writeln!(decl, " let q{c} = qs[qa + {c}u];\n var o{c} = vec4(0.0);"); + let _ = writeln!(rescale, " o{c} *= fix;"); + let _ = writeln!(store, " out[oa + {c}u] = o{c} * r;"); + } + for j in 0..keys { + let terms: Vec = (0..d4).map(|c| format!("q{c} * Ks[{}u]", j * d4 + c)).collect(); + let _ = writeln!( + scores, + " let d{j} = {};\n let s{j} = (d{j}.x + d{j}.y + d{j}.z + d{j}.w) * SCALE + Bs[{j}u];\n top = max(top, s{j});", + terms.join(" + ") + ); + let _ = writeln!(acc, " {{\n let w = exp(s{j} - top);\n l += w;"); + for c in 0..d4 { + let _ = writeln!(acc, " o{c} = fma(vec4(w), Vs[{}u], o{c});", j * d4 + c); + } + let _ = writeln!(acc, " }}"); + } + include_str!("../wgsl/sam3_detr.wgsl") + .replace("{{KB}}", &keys.to_string()) + .replace("{{DECL}}", &decl) + .replace("{{SCORES}}", &scores) + .replace("{{RESCALE}}", &rescale) + .replace("{{ACCUMULATE}}", &acc) + .replace("{{STORE}}", &store) +} + +/// Where an attention's q, k and v are: a buffer, its row stride and the column of head 0 (in floats). +pub(super) struct Operand<'a> { + pub(super) buffer: &'a wgpu::Buffer, + pub(super) stride: usize, + pub(super) offset: usize, +} + +impl Graph { + /// Layer norm with PyTorch's eps (the backbone's is 1e-6). + pub(super) fn layernorm_torch(&mut self, [x, gamma, beta, y]: [&wgpu::Buffer; 4], rows: usize, c: usize) -> Result<(), String> { + let (g, row) = self.flat(rows)?; + self.push(&self.dev.k.layernorm, [u32_of(rows)?, u32_of(c)?, 0, 0, EPS.to_bits(), 0, u32_of(rows)?, row], [x, gamma, beta, y], g); + Ok(()) + } + + /// `y = relu(x · wᵀ + bias)`. + fn matmul_relu(&mut self, buffers: [&wgpu::Buffer; 4], dims: (usize, usize, usize)) -> Result<(), String> { + self.matmul(buffers, dims, 1, false, false, Precision::F32)?; + if let Some(step) = self.steps.last_mut() { + step.params[4] = RELU; + } + Ok(()) + } + + /// `out = a + b`, `len` floats (a multiple of 4). + fn add(&mut self, k: &'static Kernels, [a, b, out]: [&wgpu::Buffer; 3], len: usize) -> Result<(), String> { + if !len.is_multiple_of(4) { + return Err("a sum the SAM 3 kernel cannot do".into()); + } + let (g, row) = self.flat((len / 4).div_ceil(256))?; + self.push(&k.add, [u32_of(len / 4)?, row, 0, 0, 0, 0, 0, 0], [a, b, &self.dev.dummy, out], g); + Ok(()) + } + + /// Attention of `queries` queries over `keys` keys, `heads` heads of 32, into `out` (`[queries, heads · 32]`); + /// with `bias`, key j's scores get `k.buffer[bias + j]` added. + #[allow(clippy::too_many_arguments)] + pub(super) fn attention_detr( + &mut self, + kernels: &'static Kernels, + [q, k, v]: [Operand; 3], + bias: Option, + out: &wgpu::Buffer, + (queries, keys, heads): (usize, usize, usize), + ) -> Result<(), String> { + let aligned = [q.stride, q.offset, k.stride, k.offset, v.stride, v.offset].iter().all(|n| n.is_multiple_of(4)); + if keys == 0 || !keys.is_multiple_of(KEYS as usize) || !aligned || q.offset != 0 { + return Err("an attention the SAM 3 DETR kernel cannot do".into()); + } + let bias = match bias { + Some(b) => u32_of(b)?, + None => NONE, + }; + let params = + [u32_of(queries)?, u32_of(keys)?, u32_of(q.stride)?, u32_of(k.stride)?, u32_of(v.stride)?, u32_of(k.offset)?, u32_of(v.offset)?, bias]; + let groups = [u32_of(queries.div_ceil(64))?, u32_of(heads)?, 1]; + if groups[0] > self.dev.limits.max_compute_workgroups_per_dimension { + return Err("too many queries for the SAM 3 DETR attention kernel".into()); + } + self.push(&kernels.attention, params, [q.buffer, k.buffer, v.buffer, out], groups); + Ok(()) + } +} + +/// One layer's weights on the device: (weight, bias) pairs, the q | k and k | v ones concatenated. +struct Layer { + ln1: [wgpu::Buffer; 2], + self_qk: [wgpu::Buffer; 2], + self_v: [wgpu::Buffer; 2], + self_o: [wgpu::Buffer; 2], + ln2: [wgpu::Buffer; 2], + cross_q: [wgpu::Buffer; 2], + cross_kv: [wgpu::Buffer; 2], + cross_o: [wgpu::Buffer; 2], + ln3: [wgpu::Buffer; 2], + fc1: [wgpu::Buffer; 2], + fc2: [wgpu::Buffer; 2], +} + +/// Reads the encoder's tensors, checking their shapes. +struct Loader<'a> { + weights: &'a WeightReader, + dev: &'static Dev, + bytes: u64, +} + +impl Loader<'_> { + /// The tensors `names` (each of `shape`) concatenated along the first axis. + fn upload(&mut self, names: &[String], shape: &[usize]) -> Result { + 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(upload(self.dev, names.first().map_or("weight", String::as_str), &all)) + } + + /// A linear layer (or several along n): `[n, k]` weights and their bias. + fn linear(&mut self, 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(); + Ok([self.upload(&w, &[n, k])?, self.upload(&b, &[n])?]) + } + + fn norm(&mut self, name: &str) -> Result<[wgpu::Buffer; 2], String> { + Ok([self.upload(&[format!("{name}.weight")], &[WIDTH])?, self.upload(&[format!("{name}.bias")], &[WIDTH])?]) + } + + fn layer(&mut self, i: usize) -> Result { + let l = format!("layers.{i}"); + let (s, c) = (format!("{l}.self_attn"), format!("{l}.cross_attn")); + let proj = |a: &str, ps: &[&str]| -> Vec { ps.iter().map(|p| format!("{a}.{p}_proj")).collect() }; + Ok(Layer { + ln1: self.norm(&format!("{l}.layer_norm1"))?, + self_qk: self.linear(&proj(&s, &["q", "k"]), WIDTH, WIDTH)?, + self_v: self.linear(&proj(&s, &["v"]), WIDTH, WIDTH)?, + self_o: self.linear(&proj(&s, &["o"]), WIDTH, WIDTH)?, + ln2: self.norm(&format!("{l}.layer_norm2"))?, + cross_q: self.linear(&proj(&c, &["q"]), WIDTH, WIDTH)?, + cross_kv: self.linear(&proj(&c, &["k", "v"]), WIDTH, WIDTH)?, + cross_o: self.linear(&proj(&c, &["o"]), WIDTH, WIDTH)?, + ln3: self.norm(&format!("{l}.layer_norm3"))?, + fc1: self.linear(&[format!("{l}.mlp.fc1")], MLP, WIDTH)?, + fc2: self.linear(&[format!("{l}.mlp.fc2")], WIDTH, MLP)?, + }) + } +} + +/// The buffers a prompt writes and reads. +struct Work { + /// The image tokens in, the memory out (the layers add to it in place). + x: wgpu::Buffer, + pos: wgpu::Buffer, + text: wgpu::Buffer, + /// The cross-attention's k | v of the prompt (`[32, 512]`), then its padding bias (32 floats). + text_kv: wgpu::Buffer, + staging: wgpu::Buffer, +} + +/// The encoder with its weights on the device and its dispatches recorded. +struct Built { + recorded: Recorded, + /// One prompt at a time (they share the work buffers). + work: Mutex, + /// Bytes of device memory: weights, work buffers. + weight_bytes: u64, + work_bytes: u64, +} + +/// The DETR encoder, built on first use from the checkpoint the backbone came from. +pub(super) struct Encoder { + weights: WeightReader, + built: OnceLock>, +} + +impl Encoder { + 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, b.work_bytes)) + } + + /// The memory `[5184, 256]` for the image tokens and their position encoding (`[5184, 256]` each) and the prompt's + /// tokens `[32, 256]` (`valid`: its real ones). + pub(super) fn run(&self, dev: &'static Dev, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> Result, String> { + if image.len() != TOKENS * WIDTH || pos.len() != TOKENS * WIDTH || text.len() != TEXT * WIDTH || valid.len() != TEXT { + return Err(format!( + "{} image, {} position, {} prompt values and {} prompt tokens, expected {TOKENS} × {WIDTH}, {TOKENS} × {WIDTH}, {TEXT} × {WIDTH} and {TEXT}", + image.len(), + pos.len(), + text.len(), + valid.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 work = b.work.lock().unwrap_or_else(PoisonError::into_inner); + dev.queue.write_buffer(&work.x, 0, bytemuck::cast_slice(image)); + dev.queue.write_buffer(&work.pos, 0, bytemuck::cast_slice(pos)); + dev.queue.write_buffer(&work.text, 0, bytemuck::cast_slice(text)); + dev.queue.write_buffer(&work.text_kv, (TEXT * 2 * WIDTH * 4) as u64, bytemuck::cast_slice(&bias)); + let out = b.recorded.run("the SAM 3 DETR encoder", dev, &work.x, &work.staging, TOKENS * WIDTH)?; + if out.iter().any(|v| !v.is_finite()) { + return Err("the GPU DETR encoder produced non-finite values".into()); + } + Ok(out) + } +} + +fn build(dev: &'static Dev, weights: &WeightReader) -> Result { + let k = kernels(dev)?; + let oom = dev.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let made = build_inner(dev, k, weights); + // let the uploads land before the scopes close + let _ = dev.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(TIMEOUT) }); + let (validation, oom) = (pollster::block_on(validation.pop()), pollster::block_on(oom.pop())); + if let Some(e) = oom { + return Err(format!("not enough GPU memory for the SAM 3 DETR encoder: {e}")); + } + if let Some(e) = validation { + return Err(format!("the GPU rejected the SAM 3 DETR encoder: {e}")); + } + made +} + +fn build_inner(dev: &'static Dev, k: &'static Kernels, weights: &WeightReader) -> Result { + let mut ld = Loader { weights, dev, bytes: 0 }; + let layers = (0..LAYERS).map(|i| ld.layer(i)).collect::, _>>()?; + + let tokens = |label: &str| buffer(dev, label, TOKENS * WIDTH); + let (x, y, hp, v, att, pos) = + (tokens("detr hidden"), tokens("detr normed"), tokens("detr normed + pos"), tokens("detr v"), tokens("detr attention"), tokens("detr pos")); + // the self-attention's q | k, then the MLP's hidden activations + let wide = buffer(dev, "detr wide", TOKENS * MLP.max(2 * WIDTH)); + let text = buffer(dev, "detr prompt", TEXT * WIDTH); + let text_kv = buffer(dev, "detr prompt k|v", TEXT * 2 * WIDTH + TEXT); + let staging = dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("detr read-back"), + size: (TOKENS * WIDTH * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let work_bytes = ((7 * TOKENS * WIDTH + TOKENS * MLP + TEXT * (3 * WIDTH + 1)) * 4) as u64; + + let mut g = Graph::new(dev); + let heads = WIDTH / HEAD_DIM; + for l in &layers { + // self-attention: q and k from the normed tokens plus their position, v from the normed tokens + g.layernorm_torch([&x, &l.ln1[0], &l.ln1[1], &y], TOKENS, WIDTH)?; + g.add(k, [&y, &pos, &hp], TOKENS * WIDTH)?; + g.matmul([&hp, &l.self_qk[0], &l.self_qk[1], &wide], (TOKENS, 2 * WIDTH, WIDTH), 1, false, false, Precision::F32)?; + g.matmul([&y, &l.self_v[0], &l.self_v[1], &v], (TOKENS, WIDTH, WIDTH), 1, false, false, Precision::F32)?; + let (q, kk) = (Operand { buffer: &wide, stride: 2 * WIDTH, offset: 0 }, Operand { buffer: &wide, stride: 2 * WIDTH, offset: WIDTH }); + g.attention_detr(k, [q, kk, Operand { buffer: &v, stride: WIDTH, offset: 0 }], None, &att, (TOKENS, TOKENS, heads))?; + g.matmul([&att, &l.self_o[0], &l.self_o[1], &x], (TOKENS, WIDTH, WIDTH), 1, false, true, Precision::F32)?; + // cross-attention to the prompt, its padding masked + g.layernorm_torch([&x, &l.ln2[0], &l.ln2[1], &y], TOKENS, WIDTH)?; + g.matmul([&y, &l.cross_q[0], &l.cross_q[1], &v], (TOKENS, WIDTH, WIDTH), 1, false, false, Precision::F32)?; + g.matmul([&text, &l.cross_kv[0], &l.cross_kv[1], &text_kv], (TEXT, 2 * WIDTH, WIDTH), 1, false, false, Precision::F32)?; + let (tk, tv) = (Operand { buffer: &text_kv, stride: 2 * WIDTH, offset: 0 }, Operand { buffer: &text_kv, stride: 2 * WIDTH, offset: WIDTH }); + g.attention_detr(k, [Operand { buffer: &v, stride: WIDTH, offset: 0 }, tk, tv], Some(TEXT * 2 * WIDTH), &att, (TOKENS, TEXT, heads))?; + g.matmul([&att, &l.cross_o[0], &l.cross_o[1], &x], (TOKENS, WIDTH, WIDTH), 1, false, true, Precision::F32)?; + // MLP + g.layernorm_torch([&x, &l.ln3[0], &l.ln3[1], &y], TOKENS, WIDTH)?; + g.matmul_relu([&y, &l.fc1[0], &l.fc1[1], &wide], (TOKENS, MLP, WIDTH))?; + g.matmul([&wide, &l.fc2[0], &l.fc2[1], &x], (TOKENS, WIDTH, MLP), 1, false, true, Precision::F32)?; + g.cut(); + } + let recorded = g.record(); + Ok(Built { recorded, work: Mutex::new(Work { x, pos, text, text_kv, staging }), weight_bytes: ld.bytes, work_bytes }) +} diff --git a/crates/gpu/src/sam3/detr/tests.rs b/crates/gpu/src/sam3/detr/tests.rs new file mode 100644 index 0000000000..95884facab --- /dev/null +++ b/crates/gpu/src/sam3/detr/tests.rs @@ -0,0 +1,267 @@ +//! The DETR encoder's kernels against plain loops: attention with heads of 32 (self- and cross-attention, the padding +//! bias, queries not filling the last workgroup), the sum, ReLU and the layer norm's eps. The whole encoder against +//! candle: `tests/it/sam3_detr.rs`. + +use super::super::dev; +use super::*; + +fn gpu() -> Option<(&'static Dev, &'static Kernels)> { + let d = match dev() { + Ok(d) => d, + // 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 None; + } + }; + Some((d, kernels(d).unwrap())) +} + +/// Deterministic values in −scale..scale. +fn values(n: usize, seed: u64, scale: f32) -> Vec { + let mut s = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (0..n) + .map(|_| { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((s >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0) * scale + }) + .collect() +} + +fn read(d: &'static Dev, g: Graph, out: &wgpu::Buffer, len: usize) -> Vec { + let staging = d.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: (len * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + g.record().run("a test", d, out, &staging, len).unwrap() +} + +fn worst(got: &[f32], want: &[f32]) -> f32 { + assert_eq!(got.len(), want.len()); + got.iter().zip(want).fold(0f32, |m, (a, b)| m.max((a - b).abs())) +} + +/// Where a test attention's operand is in its buffer. +struct At<'a> { + data: &'a [f32], + stride: usize, + offset: usize, +} + +/// Softmax attention of every query over all keys, `heads` heads of 32, as candle computes it: the scores +/// `q · k / sqrt(32) + bias` in f32 (so f32::MIN swallows a padded key's score), the rest in f64. +fn attention_ref(q: At, k: At, v: At, bias: Option<&[f32]>, (queries, keys, heads): (usize, usize, usize)) -> Vec { + let scale = (HEAD_DIM as f32).powf(-0.5); + let mut out = vec![0f32; queries * heads * HEAD_DIM]; + for t in 0..queries { + for h in 0..heads { + let at = |o: &At, row: usize, c: usize| o.data[row * o.stride + o.offset + h * HEAD_DIM + c]; + let scores: Vec = (0..keys) + .map(|j| { + let dot = (0..HEAD_DIM).map(|c| f64::from(at(&q, t, c)) * f64::from(at(&k, j, c))).sum::() as f32; + dot * scale + bias.map_or(0.0, |b| b[j]) + }) + .collect(); + let top = scores.iter().fold(f32::MIN, |m, s| m.max(*s)); + let w: Vec = scores.iter().map(|s| f64::from(s - top).exp()).collect(); + let sum: f64 = w.iter().sum(); + for c in 0..HEAD_DIM { + let o = (0..keys).map(|j| w[j] * f64::from(at(&v, j, c))).sum::() / sum; + out[(t * heads + h) * HEAD_DIM + c] = o as f32; + } + } + } + out +} + +#[test] +fn the_kernel_source_is_written_out() { + let src = attention_source(KEYS); + assert!(!src.contains("{{"), "a mark is left"); + assert!(src.contains("let s31 = ") && !src.contains("let s32 = ")); + assert!(src.contains("let q7 = ") && !src.contains("let q8 = ")); +} + +#[test] +fn self_attention_over_8_heads_of_32_gives_the_softmax_of_the_definition() { + let Some((d, k)) = gpu() else { return }; + let heads = 8; + let w = heads * HEAD_DIM; + // q | k in one buffer (k at column 256), v in another; 200 queries leave the last workgroup part empty + for (queries, keys) in [(200, 96), (64, 32), (130, 320)] { + let rows = queries.max(keys); + let qk = values(rows * 2 * w, queries as u64, 2.0); + let v = values(keys * w, 7 + keys as u64, 1.0); + let (bqk, bv) = (upload(d, "qk", &qk), upload(d, "v", &v)); + let out = buffer(d, "out", queries * w); + let mut g = Graph::new(d); + let ops = [ + Operand { buffer: &bqk, stride: 2 * w, offset: 0 }, + Operand { buffer: &bqk, stride: 2 * w, offset: w }, + Operand { buffer: &bv, stride: w, offset: 0 }, + ]; + g.attention_detr(k, ops, None, &out, (queries, keys, heads)).unwrap(); + let got = read(d, g, &out, queries * w); + let want = attention_ref( + At { data: &qk, stride: 2 * w, offset: 0 }, + At { data: &qk, stride: 2 * w, offset: w }, + At { data: &v, stride: w, offset: 0 }, + None, + (queries, keys, heads), + ); + let err = worst(&got, &want); + assert!(err < 2e-5, "{queries} queries × {keys} keys: off by {err}"); + } +} + +#[test] +fn cross_attention_to_32_prompt_tokens_leaves_out_the_padding() { + let Some((d, k)) = gpu() else { return }; + let (heads, queries) = (8, 130); + let w = heads * HEAD_DIM; + let q = values(queries * w, 1, 2.0); + // the prompt's k | v ([32, 512]), then its bias: 0 for the real tokens, f32::MIN for padding + for real in [5, 32, 1, 0] { + let mut kv = values(TEXT * 2 * w, 2 + real as u64, 2.0); + let bias: Vec = (0..TEXT).map(|j| if j < real { 0.0 } else { f32::MIN }).collect(); + kv.extend(&bias); + let (bq, bkv) = (upload(d, "q", &q), upload(d, "kv", &kv)); + let out = buffer(d, "out", queries * w); + let mut g = Graph::new(d); + let ops = [ + Operand { buffer: &bq, stride: w, offset: 0 }, + Operand { buffer: &bkv, stride: 2 * w, offset: 0 }, + Operand { buffer: &bkv, stride: 2 * w, offset: w }, + ]; + g.attention_detr(k, ops, Some(TEXT * 2 * w), &out, (queries, TEXT, heads)).unwrap(); + let got = read(d, g, &out, queries * w); + let want = attention_ref( + At { data: &q, stride: w, offset: 0 }, + At { data: &kv, stride: 2 * w, offset: 0 }, + At { data: &kv, stride: 2 * w, offset: w }, + Some(&bias), + (queries, TEXT, heads), + ); + let err = worst(&got, &want); + assert!(err < 2e-5, "{real} real tokens: off by {err}"); + if real == 1 { + // one real token: every query gets its v + let first = &kv[w..2 * w]; + assert!(worst(&got[..w], first) < 1e-6); + } + } +} + +#[test] +fn attention_the_kernel_cannot_do_is_an_error() { + let Some((d, k)) = gpu() else { return }; + let b = buffer(d, "b", 64 * 256); + let op = |stride, offset| Operand { buffer: &b, stride, offset }; + // keys not a multiple of 32, a stride not a multiple of 4, q not at column 0 + assert!(Graph::new(d).attention_detr(k, [op(256, 0), op(256, 0), op(256, 0)], None, &b, (64, 40, 8)).is_err()); + assert!(Graph::new(d).attention_detr(k, [op(256, 0), op(258, 0), op(256, 0)], None, &b, (64, 32, 8)).is_err()); + assert!(Graph::new(d).attention_detr(k, [op(256, 4), op(256, 0), op(256, 0)], None, &b, (64, 32, 8)).is_err()); + assert!(Graph::new(d).add(k, [&b, &b, &b], 6).is_err()); +} + +#[test] +fn sum_relu_and_torch_layer_norm_give_what_the_definitions_give() { + let Some((d, k)) = gpu() else { return }; + // the sum, over more than one row of workgroups' worth + let n = 4 * 256 * 70 + 12; + let (a, b) = (values(n, 1, 1.0), values(n, 2, 1.0)); + let (ba, bb, out) = (upload(d, "a", &a), upload(d, "b", &b), buffer(d, "out", n)); + let mut g = Graph::new(d); + g.add(k, [&ba, &bb, &out], n).unwrap(); + let want: Vec = a.iter().zip(&b).map(|(x, y)| x + y).collect(); + assert_eq!(read(d, g, &out, n), want); + + // ReLU in the product's epilogue + let (m, nn, kk) = (70, 90, 64); + let (x, w, bias) = (values(m * kk, 3, 1.0), values(nn * kk, 4, 0.3), values(nn, 5, 0.5)); + let (bx, bw, bbias, by) = (upload(d, "x", &x), upload(d, "w", &w), upload(d, "bias", &bias), buffer(d, "y", m * nn)); + let mut g = Graph::new(d); + g.matmul_relu([&bx, &bw, &bbias, &by], (m, nn, kk)).unwrap(); + let got = read(d, g, &by, m * nn); + let want: Vec = (0..m * nn) + .map(|o| { + let (i, j) = (o / nn, o % nn); + let v = f64::from(bias[j]) + (0..kk).map(|t| f64::from(x[i * kk + t]) * f64::from(w[j * kk + t])).sum::(); + v.max(0.0) as f32 + }) + .collect(); + assert!(worst(&got, &want) < 1e-5); + assert!(got.contains(&0.0) && got.iter().any(|v| *v > 0.0)); + + // rows of small spread, where eps 1e-5 and 1e-6 differ + let (rows, c) = (5, WIDTH); + let x = values(rows * c, 6, 3e-3); + let (gamma, beta) = (values(c, 7, 1.0), values(c, 8, 0.1)); + let (bx, bg, bb, by) = (upload(d, "x", &x), upload(d, "g", &gamma), upload(d, "b", &beta), buffer(d, "y", rows * c)); + let mut g = Graph::new(d); + g.layernorm_torch([&bx, &bg, &bb, &by], rows, c).unwrap(); + let got = read(d, g, &by, rows * c); + let mut want = vec![0f32; rows * c]; + for r in 0..rows { + let row = &x[r * c..(r + 1) * c]; + let mean = row.iter().map(|v| f64::from(*v)).sum::() / c as f64; + let var = row.iter().map(|v| (f64::from(*v) - mean).powi(2)).sum::() / c as f64; + for i in 0..c { + want[r * c + i] = ((f64::from(row[i]) - mean) / (var + f64::from(EPS)).sqrt() * f64::from(gamma[i]) + f64::from(beta[i])) as f32; + } + } + let err = worst(&got, &want); + assert!(err < 1e-4, "layer norm off by {err}"); +} + +/// The encoder's steps at its shapes: +/// `cargo test --release -p lightcraft-gpu --features sam --lib sam3::detr::tests::timings -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: needs a GPU"] +fn timings() { + let Some((d, k)) = gpu() else { return }; + let reps = 20; + let time = |name: &str, flops: f64, build: &dyn Fn(&mut Graph)| { + let out = buffer(d, "out", 4); + let staging = d.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 16, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut g = Graph::new(d); + for _ in 0..reps { + build(&mut g); + } + let rec = g.record(); + rec.run("a test", d, &out, &staging, 4).unwrap(); + let t = std::time::Instant::now(); + rec.run("a test", d, &out, &staging, 4).unwrap(); + let ms = t.elapsed().as_secs_f64() * 1e3 / reps as f64; + eprintln!("{name:>34}: {ms:7.3} ms {:6.2} TFLOP/s", flops / ms / 1e9); + }; + let x = buffer(d, "x", TOKENS * MLP); + let y = buffer(d, "y", TOKENS * MLP); + let w = buffer(d, "w", MLP * WIDTH); + let b = buffer(d, "b", MLP); + for (n, kk) in [(2 * WIDTH, WIDTH), (WIDTH, WIDTH), (MLP, WIDTH), (WIDTH, MLP)] { + let flops = 2.0 * (TOKENS * n * kk) as f64; + time(&format!("matmul {TOKENS}x{n}x{kk}"), flops, &|g| g.matmul([&x, &w, &b, &y], (TOKENS, n, kk), 1, false, false, Precision::F32).unwrap()); + } + for keys in [TOKENS, TEXT] { + let flops = 4.0 * (TOKENS * keys * WIDTH) as f64; + time(&format!("attention {keys} keys"), flops, &|g| { + let ops = [ + Operand { buffer: &x, stride: 2 * WIDTH, offset: 0 }, + Operand { buffer: &x, stride: 2 * WIDTH, offset: WIDTH }, + Operand { buffer: &x, stride: WIDTH, offset: 0 }, + ]; + g.attention_detr(k, ops, None, &y, (TOKENS, keys, WIDTH / HEAD_DIM)).unwrap() + }); + } + time("layernorm", 0.0, &|g| g.layernorm_torch([&x, &b, &b, &y], TOKENS, WIDTH).unwrap()); + time("add", 0.0, &|g| g.add(k, [&x, &x, &y], TOKENS * WIDTH).unwrap()); +} diff --git a/crates/gpu/src/wgsl/sam3_detr.wgsl b/crates/gpu/src/wgsl/sam3_detr.wgsl new file mode 100644 index 0000000000..2ed63db145 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_detr.wgsl @@ -0,0 +1,105 @@ +// The DETR encoder of SAM 3's text detector (`sam3/detr.rs`): attention with heads of 32 (8 of them over 256 numbers), +// for the image tokens over themselves (self-attention) and over the prompt's tokens (cross-attention, with a +// key-padding bias), and the sum of two arrays (the position encoding added to the normed tokens). +// +// q [queries, q_stride]: head h's q at h · 32 (binding 1) +// k [keys, k_stride] from k_off (binding 2), v [keys, v_stride] from v_off (binding 3); 2 and 3 may be one buffer +// bias `keys` floats in binding 2 from `bias` (NONE: no bias), added to every score of its key: 0 for a real +// token, f32::MIN for padding, as candle's `padding_bias` +// out [queries, heads · 32] +// +// Strides and offsets count floats (multiples of 4); keys is a multiple of KB. Flash style like +// `sam3_attention.wgsl`: one query per thread with its q and partial output in registers, keys and values KB at a +// time through workgroup memory, online softmax. The running maximum starts at f32::MIN rather than below it: a padded +// key's score is then exactly f32::MIN (as in candle, where s + f32::MIN rounds to f32::MIN) and weighs nothing next +// to a real one, and a query whose keys are all padding averages them, as candle's softmax over equal scores does. +// The host writes out the per-thread work with one variable per vector and score (the DECL, SCORES, RESCALE, +// ACCUMULATE and STORE marks). + +struct P { + queries: u32, + keys: u32, + q_stride: u32, + k_stride: u32, + v_stride: u32, + k_off: u32, + v_off: u32, + bias: u32, +} + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var qs: array>; +@group(0) @binding(2) var ks: array>; +@group(0) @binding(3) var vs: array>; +@group(0) @binding(4) var out: array>; + +// head_dim / 4, keys per step, 1 / sqrt(head_dim) +const D4: u32 = 8u; +const KB: u32 = {{KB}}u; +const SCALE: f32 = 0.17677669529663687; +const NONE: u32 = 0xffffffffu; +const LOWEST: f32 = -3.4028234663852886e38; + +var Ks: array, KB * D4>; +var Vs: array, KB * D4>; +var Bs: array; + +@compute @workgroup_size(64) +fn attention(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) groups: vec3, @builtin(local_invocation_index) lid: u32) { + let head = wg.y; + let tq = wg.x * 64u + lid; + // threads past the last query compute on query 0 (the barriers below stay uniform) and store nothing + let live = tq < p.queries; + let qa = select(0u, tq, live) * (p.q_stride / 4u) + head * D4; + let k4 = p.k_stride / 4u; + let v4 = p.v_stride / 4u; + let ka = p.k_off / 4u + head * D4; + let va = p.v_off / 4u + head * D4; + +{{DECL}} + var m = LOWEST; + var l = 0.0; + + for (var k0 = 0u; k0 < p.keys; k0 += KB) { + for (var e = lid; e < KB * D4; e += 64u) { + let t = k0 + e / D4; + Ks[e] = ks[t * k4 + ka + e % D4]; + Vs[e] = vs[t * v4 + va + e % D4]; + } + if (lid < KB) { + var b = 0.0; + if (p.bias != NONE) { + let i = p.bias + k0 + lid; + b = ks[i / 4u][i % 4u]; + } + Bs[lid] = b; + } + workgroupBarrier(); + + var top = m; +{{SCORES}} + // rescale what was summed under the old maximum + let fix = exp(m - top); + l *= fix; +{{RESCALE}} +{{ACCUMULATE}} + m = top; + workgroupBarrier(); + } + + if (live) { + let r = 1.0 / l; + let oa = tq * groups.y * D4 + head * D4; +{{STORE}} + } +} + +// out = qs + ks, `queries` vectors (keys: workgroups per row of the dispatch). +@compute @workgroup_size(256) +fn add(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let i = (wg.y * p.keys + wg.x) * 256u + lid; + if (i >= p.queries) { + return; + } + out[i] = qs[i] + ks[i]; +} diff --git a/crates/gpu/tests/it/main.rs b/crates/gpu/tests/it/main.rs index 0d1aa1303f..89aa46310a 100644 --- a/crates/gpu/tests/it/main.rs +++ b/crates/gpu/tests/it/main.rs @@ -10,4 +10,6 @@ mod gpu_probe; #[cfg(feature = "sam")] mod sam3_backbone; #[cfg(feature = "sam")] +mod sam3_detr; +#[cfg(feature = "sam")] mod sam3_necks; diff --git a/crates/gpu/tests/it/sam3_detr.rs b/crates/gpu/tests/it/sam3_detr.rs new file mode 100644 index 0000000000..69e2355626 --- /dev/null +++ b/crates/gpu/tests/it/sam3_detr.rs @@ -0,0 +1,182 @@ +//! The text detector's DETR encoder on the GPU against the candle encoder (the reference), on one photo: the encoder +//! memory, and what the difference does to the detector's outputs (per-query logits, presence, boxes and the merged +//! Describe mask) for a few prompts. Both models get the same backbone output (one GPU backbone, shared), so only the +//! encoder differs. +//! +//! Needs the checkpoint: `LIGHTCRAFT_SAM3_DIR= cargo test --release -p lightcraft-gpu --features sam +//! --test it sam3_detr:: -- --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, 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), and how many instances that is. +fn merged(out: &DetectorOutput) -> (Vec, usize) { + let masks = values(&out.masks); + 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); + } + } + (merged, keep.len()) +} + +/// 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() +} + +/// One GPU backbone for both models; the DETR encoder only for one of them (`asked` counts the calls). +struct Shared { + gpu: Arc, + detr: 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_detr_encoder(&self) -> bool { + true + } + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> Result, String> { + self.asked.fetch_add(1, Ordering::Relaxed); + if self.detr { self.gpu.detr_encoder(image, pos, text, valid) } else { Err("left to candle for the comparison".into()) } + } +} + +#[test] +fn the_gpu_detr_encoder_matches_the_candle_encoder() { + 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 = |detr: bool, asked: &Arc| { + let (gpu, asked) = (gpu.clone(), asked.clone()); + move |_: &WeightReader| -> Result, String> { Ok(Box::new(Shared { gpu, detr, 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(); + assert_eq!(values(enc_cpu.backbone()), values(enc_acc.backbone()), "the same backbone output for both"); + + 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 encoder {cpu_time:?}, with the GPU encoder {gpu_time:?}{first}"); + assert_eq!(acc.detr_fallback(), None, "the GPU encoder ran"); + assert!(cpu.detr_fallback().is_some_and(|w| w.contains("left to candle"))); + + let (_, rel, mean) = errors("memory", &values(&got.memory), &values(&want.memory)); + assert!(rel < 1e-3 && mean < 1e-4, "the GPU encoder memory is off"); + let (logits, _, _) = errors("query logits", &got.logits, &want.logits); + let presence = (got.presence - want.presence).abs(); + let boxes = got.boxes.iter().flatten().zip(want.boxes.iter().flatten()).fold(0f32, |m, (a, b)| m.max((a - b).abs())); + let ((mask_g, kept_g), (mask_c, kept_c)) = (merged(&got), merged(&want)); + let i = iou(&mask_g, &mask_c); + eprintln!( + " presence {:.4} vs {:.4} (logit diff {presence:.2e}), boxes max diff {boxes:.2e}, instances {kept_g} vs {kept_c}, mask IoU {i:.5}", + sigmoid(got.presence), + sigmoid(want.presence) + ); + // every query's mask, not only the merged ones: the largest |Δ| of the logits and of the masks (sigmoid, 0..1) + let (dl, dm) = values(&got.masks) + .iter() + .zip(&values(&want.masks)) + .fold((0f32, 0f32), |(l, m), (a, b)| (l.max((a - b).abs()), m.max((sigmoid(*a) - sigmoid(*b)).abs()))); + eprintln!(" masks of all {} queries: max |Δ| logits {dl:.2e}, mask {dm:.2e}", got.logits.len()); + assert!(logits < 0.05 && presence < 0.05 && boxes < 1e-2, "the detector outputs moved"); + assert_eq!(kept_g, kept_c, "the same instances"); + assert!(i > 0.99, "describe mask IoU {i}"); + } + // an accelerator that failed on the encoder once isn't asked again + assert_eq!(asked_cpu.load(Ordering::Relaxed), 1); + assert_eq!(asked_gpu.load(Ordering::Relaxed), prompts.len()); + + // the encoder alone (with the uploads and the read-back) + let (image, pos, text) = (vec![0.1f32; 5184 * 256], vec![0.2f32; 5184 * 256], vec![0.3f32; 32 * 256]); + let valid: Vec = (0..32).map(|i| i < 4).collect(); + let mut best = f64::MAX; + for _ in 0..5 { + let t = Instant::now(); + gpu.detr_encoder(&image, &pos, &text, &valid).unwrap(); + best = best.min(t.elapsed().as_secs_f64()); + } + let (w, b) = gpu.detr_bytes().unwrap(); + eprintln!("GPU DETR encoder alone: {:.1} ms on {adapter}; {:.0} MB weights, {:.0} MB work buffers", best * 1e3, w as f64 / 1e6, b as f64 / 1e6); +} From dbb754fe187d04effec94ffb36788e5f48d497a6 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:08:51 +0200 Subject: [PATCH 036/331] i18n(de): the GPU hint for AI masks uses du, like the rest of the German UI Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/de.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 529cebe691..5599c06131 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3445,5 +3445,5 @@ "Run on": "Ausführen auf", "Automatic (GPU when available)": "Automatisch (GPU, wenn vorhanden)", "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Objekt- und Beschreiben-Masken analysieren jedes Foto einmal, auf der Grafikkarte, außer CPU ist gewählt oder „GPU zum Rendern verwenden“ ist aus. Auf dem Prozessor dauert das deutlich länger.", - "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatisch führt das Modell auf der Grafikkarte des Mac aus. Wählen Sie CPU, wenn KI-Masken dort scheitern; auf dem Prozessor dauern sie deutlich länger." + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatisch führt das Modell auf der Grafikkarte des Mac aus. Wähle CPU, wenn KI-Masken dort scheitern; auf dem Prozessor dauern sie deutlich länger." } From 418d63105767705109af80690abd0e06ec85e35b Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 20 Oct 2026 15:49:40 -0400 Subject: [PATCH 037/331] 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 038/331] #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 039/331] #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 040/331] #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 041/331] #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 55673bd1d639d3f091a053cdfa1de018bfa89e1e Mon Sep 17 00:00:00 2001 From: OneSlips Date: Fri, 16 Oct 2026 17:03:00 +1000 Subject: [PATCH 042/331] FIX-KEYWORDS: a keyword list written as one metadata entry is a keyword a line; names drawn on one line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The left panel's ghost text: the user's camera writes its whole keyword list as one dc:subject item, a keyword a line ("Beautiful Bride Bride and Groom…"). It was read as one keyword many lines tall, and its sidebar row painted the lines over the rows around it. keywords::from_file now splits an entry at line breaks (one keyword a line, blanks dropped); a library whose photos already carry such a keyword is repaired when it opens (Session::split_multiline_keywords, journaled, not an undo step); and the sidebar and Keyword List rows draw any name on one line (keywords::one_line). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 10541d62c3a2960bd787668ee26c5a0cfc6f2886) # Conflicts: # crates/catalog/src/keywords.rs # crates/engine/src/tests_culling.rs --- crates/catalog/src/keywords.rs | 38 +++++++++++++++++++-- crates/engine/src/library.rs | 34 ++++++++++++++++++ crates/engine/src/tests_keyword_list.rs | 14 ++++++++ crates/ui-egui/src/panels/keyword_list.rs | 3 +- crates/ui-egui/src/panels/left.rs | 4 +++ crates/ui-egui/src/tests_keyword_sidebar.rs | 21 ++++++++++++ docs/parity-checklist.md | 3 +- docs/whats-new.md | 7 ++++ 8 files changed, 120 insertions(+), 4 deletions(-) diff --git a/crates/catalog/src/keywords.rs b/crates/catalog/src/keywords.rs index 6b0c97f5a3..492363405f 100644 --- a/crates/catalog/src/keywords.rs +++ b/crates/catalog/src/keywords.rs @@ -46,17 +46,39 @@ pub fn reparent(k: &str, from: &str, to: &str) -> String { /// A file's keywords as a photo carries them: the paths of `lr:hierarchicalSubject`, then the /// names of `dc:subject` that aren't levels of those paths (Lightroom Classic writes each keyword's /// name, its parents' and synonyms flat besides its path). Each once, cleaned. +/// +/// An entry holding several lines is several keywords: some cameras' metadata presets write the +/// whole list as one `dc:subject` item, a keyword a line ("Beautiful Bride Bride and +/// Groom…"). Read as one, it would be a single keyword many lines tall. pub fn from_file(flat: &[String], hierarchical: &[String]) -> Vec { - let mut out: Vec = hierarchical.iter().map(|k| clean(k)).collect(); + let lines = |v: &[String]| -> Vec { v.iter().flat_map(|k| split_lines(k)).collect() }; + let (flat, hierarchical) = (lines(flat), lines(hierarchical)); + let mut out: Vec = hierarchical.iter().map(|k| clean(k)).filter(|k| !k.is_empty()).collect(); // One lowered set of every hierarchical level, not a search of `hierarchical` for each flat // keyword: disjoint lists from sidecars made the old approach quadratic in both (CWE-407), and // `same` allocates two lower-cased strings per comparison. let levels: std::collections::HashSet = hierarchical.iter().flat_map(|h| h.split(SEP).map(|l| l.trim().to_lowercase())).collect(); - out.extend(flat.iter().map(|k| clean(k)).filter(|k| !levels.contains(&k.to_lowercase()))); + out.extend(flat.iter().map(|k| clean(k)).filter(|k| !k.is_empty()).filter(|k| !levels.contains(&k.to_lowercase()))); dedupe(&mut out); out } +/// The keywords of one metadata entry: one a line (any of `\r`, `\n`, the Unicode line and +/// paragraph separators), blank lines dropped. +pub fn split_lines(k: &str) -> Vec { + k.split(['\r', '\n', '\u{2028}', '\u{2029}']).map(str::trim).filter(|l| !l.is_empty()).map(str::to_string).collect() +} + +/// `text` on one line: line breaks become spaces (a name drawn in a row must never spill over +/// the rows around it). +pub fn one_line(text: &str) -> std::borrow::Cow<'_, str> { + if text.contains(['\r', '\n', '\u{2028}', '\u{2029}']) { + std::borrow::Cow::Owned(split_lines(text).join(" ")) + } else { + std::borrow::Cow::Borrowed(text) + } +} + /// The deepest a keyword list file may nest keywords: a file is input, so its nesting is bounded. pub const MAX_LEVELS: usize = 64; @@ -824,6 +846,18 @@ impl Catalog { #[cfg(test)] mod tests { use super::*; + + /// A camera preset's keyword list written as one `dc:subject` item, a keyword a line, is one + /// keyword a line; names stay one line wherever they are drawn. + #[test] + fn a_list_in_one_entry_is_a_keyword_a_line() { + let flat = vec!["Beautiful Bride\r\n Bride and Groom\r\n\r\n Happy Couple".to_string(), "Solo".to_string()]; + assert_eq!(from_file(&flat, &[]), vec!["Beautiful Bride", "Bride and Groom", "Happy Couple", "Solo"]); + assert_eq!(from_file(&["a\nb".to_string()], &["x|a".to_string()]), vec!["x|a", "b"], "a level of a path isn't listed twice"); + assert_eq!(one_line("a\r\n b"), "a b"); + assert!(matches!(one_line("plain"), std::borrow::Cow::Borrowed(_))); + assert!(split_lines("\r\n").is_empty()); + } use crate::{Filter, Photo, PhotoId, Source}; fn lib(kws: &[&[&str]]) -> (Catalog, Vec) { diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index a5071b4b35..c515e516a1 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -605,6 +605,12 @@ impl Session { lib.forgot_local = Some(plan); } } + // keywords read whole from a list a line long (before they were split) become one each + if self.split_multiline_keywords() > 0 + && let Err(e) = self.persist() + { + log::error!("library: {e}"); + } // smart previews written by an older camera-look fit are brought up to date in the background #[cfg(not(target_arch = "wasm32"))] if on_disk { @@ -614,6 +620,34 @@ impl Session { Ok(()) } + /// Photos whose keywords hold line breaks (a camera preset's whole keyword list read as one + /// keyword by an earlier version) get one keyword a line, journaled, not an undo step. Returns + /// how many photos changed. + pub fn split_multiline_keywords(&mut self) -> usize { + let fix: Vec<(lightcraft_catalog::PhotoId, lightcraft_catalog::Meta)> = self + .catalog + .photos() + .filter(|p| p.meta.keywords.iter().any(|k| k.contains(['\r', '\n', '\u{2028}', '\u{2029}']))) + .map(|p| { + let mut meta = p.meta.clone(); + meta.keywords = lightcraft_catalog::keywords::from_file(&meta.keywords, &[]); + (p.id, meta) + }) + .collect(); + let n = fix.len(); + for (id, meta) in fix { + let op = lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }; + match self.catalog.apply(op.clone()) { + Ok(_) => self.pending_log.push(op), + Err(e) => log::warn!("split keywords: {e}"), + } + } + if n > 0 { + log::info!("split the line-separated keywords of {n} photo(s) into one keyword a line"); + } + n + } + /// Write pending ops to the log (fsynced), compact when due, and save changed presets. /// Called after every top-level command; cheap when nothing changed. Fails (with /// [`EngineError::NotSaved`]) only when the queued ops couldn't be written; they stay queued. diff --git a/crates/engine/src/tests_keyword_list.rs b/crates/engine/src/tests_keyword_list.rs index b98b45de8d..d7ff5fdfa9 100644 --- a/crates/engine/src/tests_keyword_list.rs +++ b/crates/engine/src/tests_keyword_list.rs @@ -339,3 +339,17 @@ fn importing_keywords_reads_a_list() { assert!(s.execute("keyword.import", &json!({})).is_err(), "a path or text"); let _ = std::fs::remove_dir_all(&dir); } + +/// A library whose photos got a whole keyword list as one keyword (line breaks inside) is +/// repaired when it opens: one keyword a line, journaled. +#[test] +fn line_separated_keywords_are_split_when_the_library_opens() { + let mut s = Session::with_demo(); + let id = s.visible_cloned()[0]; + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.keywords = vec!["Bride\r\n Groom\r\n Happy Couple".into()]; + s.catalog.apply(lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + assert_eq!(s.split_multiline_keywords(), 1); + assert_eq!(s.catalog.photo(id).unwrap().meta.keywords, vec!["Bride", "Groom", "Happy Couple"]); + assert_eq!(s.split_multiline_keywords(), 0, "nothing left to split"); +} diff --git a/crates/ui-egui/src/panels/keyword_list.rs b/crates/ui-egui/src/panels/keyword_list.rs index 43190002ab..3fc7a25dd3 100644 --- a/crates/ui-egui/src/panels/keyword_list.rs +++ b/crates/ui-egui/src/panels/keyword_list.rs @@ -271,7 +271,8 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId let room = (arrow.left() - 4.0 - (x + 34.0)).max(0.0); let font = t.font(13.0); let measure = |s: &str| ui.painter().layout_no_wrap(s.to_string(), font.clone(), t.text_label).size().x; - let name = if measure(&r.name) <= room { r.name.clone() } else { crate::widgets::elide_head(&r.name, room, measure) }; + let flat = lightcraft_catalog::keywords::one_line(&r.name); + let name = if measure(&flat) <= room { flat.to_string() } else { crate::widgets::elide_head(&flat, room, measure) }; let label = ui.painter().text(pos2(x + 34.0, cy), Align2::LEFT_CENTER, name, font.clone(), if picked { t.text } else { t.text_label }); // where new keywords go (Put New Keywords Inside This Keyword): a dot after the name if app.session.catalog.default_keyword_parent().as_deref().is_some_and(|k| same(k, &r.path)) { diff --git a/crates/ui-egui/src/panels/left.rs b/crates/ui-egui/src/panels/left.rs index 2c7d2642c9..446edf6117 100644 --- a/crates/ui-egui/src/panels/left.rs +++ b/crates/ui-egui/src/panels/left.rs @@ -132,6 +132,10 @@ fn row_sensed( mark: Option, ) -> egui::Response { let label = if matches!(id, "all" | "recentlyAdded" | "picks" | "missing" | "recentlyDeleted") { crate::i18n::tr(label) } else { label }; + // a name is drawn on one line: one holding line breaks (a whole keyword list read as one + // keyword) would spill over the rows around it + let one_line = lightcraft_catalog::keywords::one_line(label); + let label: &str = &one_line; let t = Tokens::get(ui.ctx()); let indent = drawn_indent(ui, indent); let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), sense); diff --git a/crates/ui-egui/src/tests_keyword_sidebar.rs b/crates/ui-egui/src/tests_keyword_sidebar.rs index 95c81ff0d9..bcce5dd681 100644 --- a/crates/ui-egui/src/tests_keyword_sidebar.rs +++ b/crates/ui-egui/src/tests_keyword_sidebar.rs @@ -85,3 +85,24 @@ fn probe_keyword_sidebar_cost() { } eprintln!("frame after a rating: {:?}", t.elapsed() / 10); } + +/// A keyword holding line breaks (a camera preset's whole keyword list read as one keyword by +/// 0.8.x: "Beautiful Bride\r\n Bride and Groom\r\n …") was drawn many lines tall over the rows +/// around it: the ghost text in the Keywords section. A row's name is drawn on one line. +#[test] +fn a_keyword_with_line_breaks_is_drawn_on_one_line() { + let mut s = Session::new(); + let list: Vec = (0..20).map(|i| format!("Wedding Keyword {i:02}")).collect(); + let mut p = + Photo::new(PhotoId(1), Source::File { path: "/lightcraft-kw-test/IMG_1.jpg".into() }, "IMG_1.jpg", "JPEG", 60, 40, "2026-01-01T00:00:00"); + p.meta.keywords = vec![list.join("\r\n "), "Solo".into()]; + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let app = LightcraftApp::new(s, Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1400.0, 900.0], 1.0); + let r = h.request("ui.set", json!({"view": "photoGrid", "leftPanel": true}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + let solo = h.app.widgets.iter().find(|(w, _)| w == "label:keyword:Solo").map(|(_, r)| *r).expect("the Solo row"); + let long = h.app.widgets.iter().find(|(w, _)| w.starts_with("label:keyword:Wedding Keyword 00")).map(|(_, r)| *r).expect("the long row"); + assert!(long.height() <= solo.height() + 0.5, "one line, as tall as any name: {long:?} vs {solo:?}"); +} diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index d059494cef..4f48e1d3f6 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 (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-25 · **Change:** minor (LRC-LIB-KEYWORDS: a keyword list written as one metadata entry, a keyword a line, is read as one keyword a line; 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 @@ -799,6 +799,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-25 | patch | LRC-LIB-KEYWORDS: a file whose keyword list is one `dc:subject` (or `lr:hierarchicalSubject`) entry with a keyword a line is read as one keyword a line; a library holding such a keyword is repaired when it opens (journaled, not an undo step); sidebar and Keyword List rows draw a name on one line; status unchanged | | 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 | | 2026-10-24 | patch | Integration batch 43: Integrated main 98702b5c, preserving the new fail-closed GPS metadata check for Original export. Watermark geometry/orientation and HDR JPEG size-limit fixes remain in their shared helpers; no feature-count changes. | | 2026-10-23 | patch | Export integration: Integrated main 5ca49b3e, retaining Width & Height resizing, export format/bit-depth validation and batch panic cancellation alongside the existing watermark and HDR JPEG size-limit fixes. No feature-count changes. | diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c2592003..1a378aeea5 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,12 @@ # What's new in LightCraft +## 2026-10-25 + +### Keywords +- **No more ghost text in the Keywords list.** Some cameras write their whole keyword list as one metadata entry, + a keyword a line; LightCraft now reads it as one keyword a line, and repairs libraries that already hold such a + keyword when they open. A name with a line break in it is drawn on one line in the sidebar and the Keyword List. + ## 2026-10-24 ### Relative-date filters and smart albums follow the clock From debc68ac6d36ecb547c7f0d422e045b3811f2d46 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Sun, 25 Oct 2026 15:36:34 +1000 Subject: [PATCH 043/331] LR-MASK-OVERLAY: one overlay rule; a mask with settings never shows by itself Every trigger goes through one check: the overlay shows with O / the eye (on to stay), or while the pointer is on a mask's row or pin and nothing is adjusted, or by itself for a mask without settings yet. A mask with settings is judged by its effect: creating, picking, duplicating or adding to one no longer shows the overlay (replaces #1800's re-show; its test is changed to the rule). A slider at work, a handle or pin drag and a brush stroke hide the overlay and the mask's lines and pins until let go, instead of switching the overlay off. No stand-in overlay while an Object click or a description is computed. From 42dbad7d, 5d074db8, 0c58de7a, 4436ab71 (minimum needed on main: no mask tree, overlay pop-up, dial input or on-photo AI progress). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 18 ++--- crates/ui-egui/src/menus.rs | 15 +++- crates/ui-egui/src/panels/detail.rs | 90 +++++++++++++++++++++-- crates/ui-egui/src/panels/masking.rs | 11 ++- crates/ui-egui/src/state.rs | 21 +++++- crates/ui-egui/src/tests_masking.rs | 69 +++++++++++------ crates/ui-egui/src/tests_preview_limit.rs | 4 + docs/parity-checklist.md | 5 +- docs/whats-new.md | 11 +++ 9 files changed, 192 insertions(+), 52 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4fc43172ce..e55617a601 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -695,16 +695,8 @@ impl LightcraftApp { // menu), it must not keep a search that no longer applies (issue #1648) self.ui.search.clear(); } - if r.is_ok() && id == "mask.adjust" { - // Judge local adjustments on the photo, without the selection overlay obscuring them. - // Keep it hidden after release; O / the overlay eye can show it again. - self.ui.mask_overlay = false; - } - if r.is_ok() && matches!(id, "mask.add" | "mask.addComponent" | "mask.duplicate" | "mask.select") { - // A new or newly picked mask shows its overlay again, as in Lightroom: hidden by a slider - // drag above, it stayed hidden while the Overlay menu still named a mode (issue #1800). - self.ui.mask_overlay = true; - } + // (a mask's sliders don't switch the overlay off, and creating or picking a mask doesn't + // switch it on: one rule decides when it shows, see `panels::detail::overlay_mask`) if r.is_ok() { // These commands finish synchronously, so their completion would otherwise // be invisible once the activity stack is gone. Never show success on error. @@ -907,8 +899,8 @@ impl LightcraftApp { ctx.request_repaint(); } if let Some(mask) = polled.refine { - // a new selection from a click or a description: show it, as `run` does for new masks - self.ui.mask_overlay = true; + // (a new selection from a click or a description shows by the overlay rule while its + // mask has no settings: `panels::detail::overlay_mask`) self.ui.detail_due = Some((now + 0.3, mask)); } if let Some(e) = polled.messages.into_iter().last() { @@ -1583,6 +1575,8 @@ impl LightcraftApp { self.library_changed(&ctx); // panels set it again this frame while the pointer rests on a preset or profile self.hover_preview = None; + // (and the mask row or pin under the pointer: the overlay shows that mask) + self.ui.mask_hover_prev = self.ui.mask_hover.take(); self.ai_mask_detail(&ctx); self.place_names_outcome(&ctx); if self.ui.fullscreen { diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index f6691a861d..5232f6c9fe 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1082,8 +1082,18 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option { - app.ui.mask_overlay = p.get("show").and_then(Value::as_bool).unwrap_or(!app.ui.mask_overlay); - Ok(json!({"maskOverlay": app.ui.mask_overlay})) + // O shows or hides what is on screen now: an overlay that showed by itself (a mask + // without settings yet) is hidden for that mask + let selected = app.session.active().and_then(|id| app.session.develop_of(id)).and_then(|d| { + app.session + .active_mask + .and_then(|mid| d.masks.iter().find(|m| m.id == mid).map(|m| (mid, crate::panels::detail::overlay_shown(app, m)))) + }); + let shown = selected.is_some_and(|s| s.1) || (selected.is_none() && app.ui.mask_overlay); + let show = p.get("show").and_then(Value::as_bool).unwrap_or(!shown); + app.ui.mask_overlay = show; + app.ui.mask_overlay_hidden = if show { None } else { selected.map(|s| s.0) }; + Ok(json!({"maskOverlay": show})) } "view.maskOverlayAll" => { app.ui.mask_overlay_all = !app.ui.mask_overlay_all; @@ -1363,7 +1373,6 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option bool { + app.ui.dragging_control.as_deref().is_some_and(|c| !shapes_graphics(c)) +} + +/// Slider ids that change what the mask graphics show rather than the photo's look. +fn shapes_graphics(id: &str) -> bool { + matches!(id, "refine" | "smoothness" | "edge" | "feather") +} + +/// The mask the overlay shows, if any. One rule: +/// overlay = O / Always, OR (the pointer on the mask's pin or row AND not adjusting), OR (Auto AND +/// the mask has no settings). "Adjusting" is a slider at work ([`adjusting`], which hides every +/// overlay in [`view_overlay`]) or a mask gesture (a handle or the gradient dragged, a brush +/// stroke): hovering never shows the overlay while one runs, even with the pointer over the pin +/// being dragged. A mask with settings (its own, or a preset's) never shows by itself, so its effect +/// can be judged while it is placed or picked; a mask without settings shows what it selects, also +/// while it is drawn (there is no effect to see yet). This replaces showing the overlay again on +/// every new, picked or duplicated mask (#1800): that covered the photo exactly when the user +/// judges a mask's effect; hovering its row or pin, or O, shows it on request. +pub(crate) fn overlay_mask<'a>(app: &LightcraftApp, d: &'a DevelopSettings) -> Option<&'a lightcraft_develop::Mask> { + if !mask_gesture(app) + && let Some(m) = app.ui.mask_hover.or(app.ui.mask_hover_prev).and_then(|id| d.masks.iter().find(|m| m.id == id)) + { + return Some(m); + } + let m = app.session.active_mask.and_then(|id| d.masks.iter().find(|m| m.id == id))?; + overlay_shown(app, m).then_some(m) +} + +/// Whether the selected mask `m`'s overlay shows (without hovering): O / Always, or Auto and `m` +/// has no settings ([`overlay_mask`] has the whole rule). +pub(crate) fn overlay_shown(app: &LightcraftApp, m: &lightcraft_develop::Mask) -> bool { + if app.ui.mask_overlay { + return true; + } + if app.ui.mask_overlay_hidden == Some(m.id) { + return false; + } + !mask_has_settings(m) +} + +/// Whether mask `m` changes the photo by itself: any adjustment off its default. (Its shape, Refine +/// Edges included, is not a setting: it is what the overlay is for.) +pub(crate) fn mask_has_settings(m: &lightcraft_develop::Mask) -> bool { + m.adjust != lightcraft_develop::LocalAdjustments::default() +} + +/// Whether a mask is being shaped on the photo right now: a handle or the gradient dragged, a brush +/// stroke. +pub(crate) fn mask_gesture(app: &LightcraftApp) -> bool { + matches!(app.gesture, Some(Gesture::MaskHandle { .. } | Gesture::Brush { .. })) +} + +/// Whether the selected mask `m` has an AI selection (an Object click or a description) still +/// being computed. Meanwhile no overlay shows for it: a stand-in would look like the result. +pub(crate) fn ai_computing(app: &LightcraftApp, m: &lightcraft_develop::Mask) -> bool { + app.session.segmenter.busy() + && m.components.iter().any(|c| matches!(&c.shape, MaskShape::Prompt { seg: None, .. } | MaskShape::Object { seg: None, .. })) +} + /// The diagnostic overlay the loupe shows (the selected mask, Point Color's visualized range, /// Visualize Spots). pub(crate) fn view_overlay(app: &LightcraftApp, d: &DevelopSettings) -> lightcraft_pipeline::Overlay { @@ -1570,19 +1634,22 @@ pub(crate) fn view_overlay(app: &LightcraftApp, d: &DevelopSettings) -> lightcra if app.ui.fullscreen { return Overlay::None; } + // a slider at work: the effect shows, not the overlay (it returns afterwards) + let shown = !adjusting(app); // Show every visible mask's region at once (Ctrl+Shift+O / Cmd+Shift+O), ahead of the selected-mask overlay - // so the shortcut is not shadowed by the always-on single-mask overlay. - if app.ui.right == RightPanel::Masking && app.ui.mask_overlay_all && d.masks.iter().any(|m| m.visible && !m.components.is_empty()) { + // so the shortcut is not shadowed by the single-mask overlay. + if shown && app.ui.right == RightPanel::Masking && app.ui.mask_overlay_all && d.masks.iter().any(|m| m.visible && !m.components.is_empty()) { return Overlay::AllMasks { view: MaskView::parse(&app.ui.mask_overlay_mode).unwrap_or_default(), color: app.ui.mask_overlay_color, opacity: app.ui.mask_overlay_opacity.clamp(0.0, 100.0).round() as u8, }; } - if app.ui.right == RightPanel::Masking - && app.ui.mask_overlay - && let Some(m) = app.session.active_mask.and_then(|id| d.masks.iter().find(|m| m.id == id)) + if shown + && app.ui.right == RightPanel::Masking + && let Some(m) = overlay_mask(app, d) && !m.components.is_empty() + && !ai_computing(app, m) { return Overlay::Mask { id: m.id.min(u16::MAX as u32) as u16, @@ -2337,7 +2404,12 @@ fn mask_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respons let long = (map.rect.width().max(map.rect.height())) as f64; let active = app.session.active_mask; let clip = app.canvas_rect.unwrap_or(map.rect); - let p = &ui.painter_at(clip); + let mut painter = ui.painter_at(clip); + // a slider at work: no lines, handles or pins over the effect + if adjusting(app) { + painter.set_invisible(); + } + let p = &painter; // (mask, component, handle, screen position) of everything that can be grabbed let mut grips: Vec<(u32, usize, u8, Pos2)> = Vec::new(); // pins follow Show Pins and the Tool Overlay mode (Shift+H); Auto hides them while brushing @@ -2419,6 +2491,12 @@ fn mask_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respons } } } + // the pointer on a pin shows that mask's overlay (as Lightroom Classic) + if let Some(h) = resp.hover_pos() + && let Some((mid, ..)) = grips.iter().find(|(_, _, handle, q)| *handle == 0 && q.distance(h) < 9.0) + { + app.ui.mask_hover = Some(*mid); + } mask_keys(app, ui, map, d, &grips); // Object selections (SAM 3) of the selected mask: each click, green to include, red to exclude // (clicks still on their way to the model included) diff --git a/crates/ui-egui/src/panels/masking.rs b/crates/ui-egui/src/panels/masking.rs index 675e5da6fb..7e1a91505c 100644 --- a/crates/ui-egui/src/panels/masking.rs +++ b/crates/ui-egui/src/panels/masking.rs @@ -195,9 +195,12 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { ui.horizontal(|ui| { ui.label(egui::RichText::new(crate::i18n::tr("Masks")).font(t.semibold(13.0)).color(t.text_label)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + // lit while the overlay is on to stay; a click does what O does let on = app.ui.mask_overlay; - if icon_button(ui, "maskOverlay", Icon::Eye, vec2(24.0, 24.0), on, true, "Show overlay (O)").clicked() { - app.ui.mask_overlay = !on; + if icon_button(ui, "maskOverlay", Icon::Eye, vec2(24.0, 24.0), on, true, "Show overlay (O)").clicked() + && let Err(e) = app.run("view.maskOverlay", json!({})) + { + app.toast(ui.ctx(), e); } let all = app.ui.mask_overlay_all; let all_mac = ui.ctx().os() == egui::os::OperatingSystem::Mac; @@ -260,6 +263,10 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { register(ui.ctx(), format!("maskName:{}", m.id), Rect::from_min_size(at, g.size())); ui.painter().galley(at, g, color); let resp = if elided { resp.on_hover_text(&m.name) } else { resp }; + // the pointer on a mask's row shows that mask's overlay (as Lightroom Classic) + if ui.rect_contains_pointer(r) { + app.ui.mask_hover = Some(m.id); + } // show / hide on hover (and always while hidden) // (the pointer test, not `hovered`: over the eye, the row itself no longer counts as hovered) if ui.rect_contains_pointer(r) || !m.visible { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index decdf63641..15e2b0a720 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -835,9 +835,21 @@ pub struct UiState { #[serde(skip)] pub proof_intent: lightcraft_engine::proof::ProofIntent, pub proof_paper_ink: bool, - /// Masking: show the selected mask as a rendered overlay (O), how (`MaskView` name, ⇧O cycles), - /// in which colour and opacity (0..100, colour views), and whether pins are drawn. + /// Masking: the selected mask's overlay switched on to stay (O, the panel's eye: "Always"), + /// how it is drawn (`MaskView` name, ⇧O cycles), in which colour and opacity (0..100, colour + /// views), and whether pins are drawn. Without it the overlay shows only by the one rule of + /// [`crate::panels::detail::overlay_mask`]: a mask without settings yet, or the mask whose row + /// or pin the pointer is on. Not kept between sessions: the photo opens without it. + #[serde(skip)] pub mask_overlay: bool, + /// The mask whose row or pin the pointer is on, this frame and the last (the overlay shows it). + #[serde(skip)] + pub mask_hover: Option, + #[serde(skip)] + pub mask_hover_prev: Option, + /// O hid the automatic overlay of this mask (until O shows it again). + #[serde(skip)] + pub mask_overlay_hidden: Option, pub mask_overlay_mode: String, pub mask_overlay_color: [u8; 3], pub mask_overlay_opacity: f32, @@ -1506,7 +1518,10 @@ impl Default for UiState { proof_profile: None, proof_intent: lightcraft_engine::proof::ProofIntent::Perceptual, proof_paper_ink: false, - mask_overlay: true, + mask_overlay: false, + mask_hover: None, + mask_hover_prev: None, + mask_overlay_hidden: None, mask_overlay_mode: "color".into(), mask_overlay_color: [230, 30, 40], mask_overlay_opacity: 50.0, diff --git a/crates/ui-egui/src/tests_masking.rs b/crates/ui-egui/src/tests_masking.rs index c8d6d6c2ea..4d95304b6a 100644 --- a/crates/ui-egui/src/tests_masking.rs +++ b/crates/ui-egui/src/tests_masking.rs @@ -119,7 +119,9 @@ fn new_brush_starts_a_separate_mask_in_paint_mode() { click(&mut h, "maskNew:brush"); assert_eq!(h.app.session.active_mask, Some(2)); assert!(!h.app.ui.brush_erase); - assert!(h.app.ui.mask_overlay); + // a new mask has no settings: its overlay shows by itself (O stays as it was) + assert!(!h.app.ui.mask_overlay); + assert_eq!(crate::panels::detail::overlay_mask(&h.app, &develop(&h)).map(|m| m.id), Some(2)); let r = h.request("ui.set", json!({"brushSize": 0.15, "brushFeather": 0.0, "brushFlow": 100.0}), T); assert_eq!(r["ok"], true, "{r}"); brush_at(&mut h, 0.5, 0.5); @@ -138,11 +140,14 @@ fn mask_adjustments_hide_overlay_without_disabling_the_mask() { use lightcraft_pipeline::Overlay; let mut h = detail("panel.masking"); exec(&mut h, "mask.add", json!({"kind": "linear", "start": [0.5, 0.2], "end": [0.5, 0.7]})); - assert!(h.app.ui.mask_overlay); + let shown = |h: &Headless| matches!(crate::panels::detail::view_overlay(&h.app, &develop(h)), Overlay::Mask { .. }); + // a mask without settings shows what it selects, by itself (O is off) + assert!(!h.app.ui.mask_overlay); + assert!(shown(&h), "a new mask shows its overlay"); // Changing the shape needs the overlay; changing the image needs an unobscured preview. exec(&mut h, "mask.refine", json!({"value": 10.0})); - assert!(h.app.ui.mask_overlay); + assert!(shown(&h), "Refine Edges is the mask's shape, not a setting"); // The dock header pushes this adjustment below the initial viewport. Exercise the // actual visible slider rather than sending a synthetic click outside its clipped body. let panel = h.app.widgets.iter().find(|(id, _)| id == "panel:right_panel").unwrap().1; @@ -155,21 +160,28 @@ fn mask_adjustments_hide_overlay_without_disabling_the_mask() { assert!(panel.contains_rect(slider), "exposure is visible before clicking: {slider:?} in {panel:?}"); let r = h.request("ui.clickWidget", json!({"id": "slider:exposure", "fx": 0.7}), T); assert_eq!(r["ok"], true, "{r}"); - assert!(!h.app.ui.mask_overlay, "the exposure slider hides the overlay after release"); let d = develop(&h); assert!(d.masks[0].adjust.exposure > 0.0); assert!(d.masks[0].visible, "hiding the overlay must not disable the mask"); - assert_eq!(crate::panels::detail::view_overlay(&h.app, &d), Overlay::None); + // the pointer is off the row and the pin: a mask with settings shows its effect, not the overlay + h.app.ui.mask_hover = None; + h.app.ui.mask_hover_prev = None; + assert_eq!(crate::panels::detail::view_overlay(&h.app, &d), Overlay::None, "a mask with settings never shows by itself"); let mask = d.masks[0].clone(); let r = h.request("ui.key", json!({"key": "o"}), T); assert_eq!(r["ok"], true, "{r}"); - assert!(h.app.ui.mask_overlay, "O can restore the overlay"); + assert!(h.app.ui.mask_overlay, "O shows the overlay on request"); assert_eq!(develop(&h).masks[0], mask, "toggling the overlay leaves the mask and its effect unchanged"); - assert!(matches!(crate::panels::detail::view_overlay(&h.app, &develop(&h)), Overlay::Mask { .. })); + assert!(shown(&h)); + // a slider at work hides even an overlay switched on with O; it comes back when let go + h.app.ui.dragging_control = Some("exposure".into()); + assert_eq!(crate::panels::detail::view_overlay(&h.app, &develop(&h)), Overlay::None, "nothing shows while a slider is at work"); + h.app.ui.dragging_control = None; + assert!(shown(&h)); // Ctrl+Shift+O / Cmd+Shift+O shows every visible mask's region at once (the new command), ahead of the selected - // mask overlay so it is not shadowed by the always-on single-mask overlay. + // mask overlay so it is not shadowed by the single-mask overlay. exec(&mut h, "view.maskOverlayAll", json!({})); assert!(h.app.ui.mask_overlay_all, "the all-masks overlay command turns it on"); assert!(matches!(crate::panels::detail::view_overlay(&h.app, &develop(&h)), Overlay::AllMasks { .. })); @@ -177,49 +189,58 @@ fn mask_adjustments_hide_overlay_without_disabling_the_mask() { assert!(!h.app.ui.mask_overlay_all, "the all-masks overlay command toggles it off"); assert!(!matches!(crate::panels::detail::view_overlay(&h.app, &develop(&h)), Overlay::AllMasks { .. })); - // Failed edits and global adjustments must not hide the mask overlay. + // O stays on through edits: failed ones, global adjustments and the mask's own values assert!(h.app.run("mask.adjust", json!({"id": 999, "values": {"exposure": 1.0}})).is_err()); assert!(h.app.ui.mask_overlay); exec(&mut h, "develop.set", json!({"control": "light.exposure", "value": 0.5})); assert!(h.app.ui.mask_overlay); - - // Numeric edits/resets and Amount use the same command path as the sliders. for values in [json!({"exposure": 0.0}), json!({"saturation": 20.0}), json!({"amount": 50.0})] { - exec(&mut h, "view.maskOverlay", json!({"show": true})); exec(&mut h, "mask.adjust", json!({"values": values})); - assert!(!h.app.ui.mask_overlay); + assert!(h.app.ui.mask_overlay && shown(&h), "{values}"); } h.settle(SETTLE); } -/// A slider hides the overlay (above); a new mask, an added part, a duplicate or picking a mask in -/// the list shows it again, so the Overlay menu's mode is what the photo shows (issue #1800). +/// One overlay rule replaces showing the overlay again on every new, picked, duplicated or extended +/// mask (issue #1800): a mask without settings shows what it selects by itself; picking a mask that +/// has settings, adding a part to it or duplicating it shows its effect, so it can be judged; the +/// pointer on its row (or pin), or O, shows its overlay on request. #[test] -fn a_new_or_picked_mask_shows_the_overlay_hidden_by_a_slider() { +fn a_mask_shows_its_overlay_by_itself_only_without_settings() { use lightcraft_pipeline::Overlay; let mut h = detail("panel.masking"); exec(&mut h, "mask.add", json!({"kind": "linear", "start": [0.5, 0.2], "end": [0.5, 0.7]})); let first = h.app.session.active_mask.unwrap(); - let hide = |h: &mut Headless| { - exec(h, "mask.adjust", json!({"values": {"exposure": 0.5}})); - assert!(!h.app.ui.mask_overlay); + let off_rows = |h: &mut Headless| { + h.app.ui.mask_hover = None; + h.app.ui.mask_hover_prev = None; }; let shown = |h: &Headless| matches!(crate::panels::detail::view_overlay(&h.app, &develop(h)), Overlay::Mask { .. }); - hide(&mut h); + assert!(shown(&h), "a new mask without settings shows its overlay"); + exec(&mut h, "mask.adjust", json!({"values": {"exposure": 0.5}})); + off_rows(&mut h); + assert!(!shown(&h), "with settings it shows its effect"); exec(&mut h, "mask.add", json!({"kind": "radial", "center": [0.4, 0.5], "rx": 0.2, "ry": 0.2})); + off_rows(&mut h); assert!(shown(&h), "a new mask shows its overlay"); - hide(&mut h); let r = h.request("ui.clickWidget", json!({"id": format!("mask:{first}")}), T); assert_eq!(r["ok"], true, "{r}"); assert_eq!(h.app.session.active_mask, Some(first)); - assert!(shown(&h), "picking a mask in the list shows its overlay"); + off_rows(&mut h); + assert!(!shown(&h), "picking a mask with settings shows its effect, not the overlay"); for (cmd, params) in [("mask.addComponent", json!({"kind": "radial", "op": "add", "center": [0.6, 0.5], "rx": 0.1, "ry": 0.1})), ("mask.duplicate", json!({}))] { - hide(&mut h); exec(&mut h, cmd, params); - assert!(shown(&h), "{cmd} shows the overlay"); + off_rows(&mut h); + assert!(!shown(&h), "{cmd} on a mask with settings shows its effect"); } + // on request: the pointer on the mask's row, or O + h.app.ui.mask_hover = h.app.session.active_mask; + assert!(shown(&h), "the pointer on its row shows the overlay"); + off_rows(&mut h); + h.request("ui.key", json!({"key": "o"}), T); + assert!(shown(&h), "O shows it"); h.settle(SETTLE); } diff --git a/crates/ui-egui/src/tests_preview_limit.rs b/crates/ui-egui/src/tests_preview_limit.rs index e87e523551..b5e17fe329 100644 --- a/crates/ui-egui/src/tests_preview_limit.rs +++ b/crates/ui-egui/src/tests_preview_limit.rs @@ -202,13 +202,16 @@ mod in_the_loupe { } h.request("engine.execute", json!({"command": "view.zoom100"}), T); h.app.ui.pan = (0.3, 0.4); + // (a mask without settings shows its overlay by itself: O hides it for that mask) h.app.ui.mask_overlay = false; + h.app.ui.mask_overlay_hidden = h.app.session.active_mask; h.settle(SETTLE); let (zoom, pan) = (h.app.ui.zoom, h.app.ui.pan); assert_eq!(zoom, crate::state::Zoom::Percent(100.0)); let plain = h.app.region_view.expect("a window render without the overlay"); h.app.ui.mask_overlay = true; + h.app.ui.mask_overlay_hidden = None; h.settle(SETTLE); let id = h.app.session.active().expect("a photo"); let d = h.app.session.develop_of(id).expect("settings"); @@ -222,6 +225,7 @@ mod in_the_loupe { assert_ne!(shown.settings, plain.settings, "the overlay is part of the window's look"); h.app.ui.mask_overlay = false; + h.app.ui.mask_overlay_hidden = h.app.session.active_mask; h.settle(SETTLE); assert_eq!((h.app.ui.zoom, h.app.ui.pan), (zoom, pan), "hiding it keeps them too"); assert_eq!(h.app.region_view.map(|r| r.settings), Some(plain.settings), "back to the plain window"); diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index dcdaec565d..429456a22b 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-25 · **Change:** minor (LR-MASK-OVERLAY: one overlay rule — O, the pointer on a row or pin, or a mask without settings; nothing while adjusting; 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 @@ -308,7 +308,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-MASK-FEATHER-EDGE | Refine mask edges | P2 | ✅ | `cmd:mask.refine`, `crates/pipeline/src/masks.rs` (`evaluate_one`) | Refine Edges slider per mask: guided filter on the photo's luminance snaps soft mask edges to the photo's edges (rendered on the CPU) | | LR-MASK-SLIDERS | Local adjustment sliders | P0 | ✅ | `cmd:mask.adjust`, `crates/pipeline/src/finish.rs` | every slider renders (CPU + GPU), incl. Noise, Moiré, Defringe (negative Defringe has no effect); no local curve | | LR-MASK-EFFECTS | Local adjustment (effect / brush) presets | P1 | ✅ | `cmd:mask.effects`, `cmd:mask.applyEffect`, `cmd:mask.saveEffect`, `cmd:mask.updateEffect`, `cmd:mask.renameEffect`, `cmd:mask.duplicateEffect`, `cmd:mask.deleteEffect`, `cmd:mask.favoriteEffect`, `cmd:mask.setEffectGroup`, `cmd:mask.renameEffectGroup`, `cmd:mask.toolEffect`, `cmd:mask.importEffects`, `cmd:mask.exportEffects`, `cmd:dialog.saveMaskEffect`, `cmd:dialog.manageMaskEffects`, `cmd:file.exportMaskEffects`, `crates/engine/src/cmd/mask_effects.rs`, `crates/engine/src/cmd/mask_effect_files.rs`, `crates/ui-egui/src/panels/mask_effects.rs` | Effect menu above the mask sliders: grouped (folders, ★ Favorites first), searchable, scrolls, ↑ ↓ Return, ✓ on the matching effect (else Custom), resting on an effect previews it on the photo; right-click: apply to all masks / to the same-named mask on the selected photos (one undo step), update, rename, duplicate, star, move to group, delete (asks first); Reset Sliders; New Effect Preset dialog: which sliders (All / None / Changed Only), Amount, brush size/feather/flow; any mask type; Manage Effect Presets window (search, inline rename, update, duplicate, stars, groups, export, delete with confirmation); a new mask starts with the effect last applied to a mask of its kind (per tool, kept with the library); imports Lightroom Classic local `.lrtemplate` presets, Camera Raw local-correction `.xmp` presets, `.lceffect` and `.zip` bundles, through File ▸ Import Profiles & Presets… and drag & drop too; folders and LrC divider presets (`10 ----- DETAIL ----- 10`) become groups; settings with no local slider here (`grain`, Point Color `pointColors`, `toningLuminance`) are reported and kept with the effect for export, not applied (🟡 for those); brush size/feather/flow aren't in LrC presets (it keeps them per brush), so only `.lceffect` carries them; no built-in effects | -| LR-MASK-OVERLAY | Mask overlay | P0 | ✅ | `cmd:view.maskOverlay`, `cmd:view.maskOverlayMode`, `cmd:view.maskOverlayColor`, `crates/pipeline/src/visualize.rs` | rendered alpha of the selected mask (CPU + GPU): colour, colour on B&W, image on black/white, white on black; ⇧O cycles while masking; successful local adjustments (including Amount) hide the overlay until O / the eye shows it again or a mask is created, picked, duplicated or added to (issue #1800); shape/edge edits retain it; zoomed in, the overlay is rendered on the same sharp window as the plain view (zoom and pan unchanged; `crates/ui-egui/src/tests_preview_limit.rs`, `crates/pipeline/src/tests_window.rs`); no auto-show on hover | +| LR-MASK-OVERLAY | Mask overlay | P0 | ✅ | `cmd:view.maskOverlay`, `cmd:view.maskOverlayMode`, `cmd:view.maskOverlayColor`, `crates/pipeline/src/visualize.rs`, `crates/ui-egui/src/panels/detail.rs` (`overlay_mask`, `adjusting`) | one rule decides when the overlay shows: O / the eye by the Masks title (on to stay), or the pointer on a mask's row or pin while nothing is being adjusted, or by itself for a mask without settings yet; a mask with settings never shows by itself (picking, creating, duplicating or adding to it shows its effect, replacing #1800's re-show); nothing shows while a slider or a mask drag or brush stroke is at work, and it comes back when let go; no stand-in overlay while an Object click or a description is still being computed; rendered alpha of the selected mask (CPU + GPU): colour, colour on B&W, image on black/white, white on black; ⇧O cycles while masking; zoomed in, the overlay is rendered on the same sharp window as the plain view (zoom and pan unchanged; `crates/ui-egui/src/tests_preview_limit.rs`, `crates/pipeline/src/tests_window.rs`) | | LR-MASK-OVERLAYALL | Show all mask overlays | P1 | ✅ | `cmd:view.maskOverlayAll`, `crates/ui-egui/src/panels/masking.rs`, `crates/pipeline/src/visualize.rs` | one diagnostic tint over every visible mask at once (CPU + GPU): the masks still stack their adjustments as before — this only paints each mask's region together, so you can see all masked areas at a glance (⌘⇧O / Ctrl+Shift+O) | | LR-MASK-PINS | Pins | P1 | ✅ | `cmd:view.maskPins`, `cmd:view.toolOverlay`, `crates/ui-egui/src/panels/detail.rs`, `crates/ui-egui/src/tests_tool_overlay.rs` | a pin per radial/linear/brush component: click selects its mask, drag moves it; Show Pins on follows the Tool Overlay mode (Auto: while the pointer is over the photo, hidden while brushing; Always; Selected: the selected mask's; Never; ⇧H cycles, #224); no pins for range/AI components | | LR-MASK-UPDATE | Recompute AI masks | P2 | ⬜ | | | @@ -799,6 +799,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-25 | minor | LR-MASK-OVERLAY: one overlay rule (O / the eye, or the pointer on the mask's row or pin while nothing is adjusted, or a mask without settings yet); a mask with settings never shows by itself, so picking, creating, duplicating or adding to one no longer shows the overlay (#1800's re-show replaced, its test changed to the rule); sliders, mask drags and brush strokes hide it and the mask's lines and pins while at work; no stand-in overlay while an AI selection is computed; 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..d276c2cc48 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,16 @@ # What's new in LightCraft +## 2026-10-25 + +### The mask overlay shows when it helps +- One rule now decides when a mask's overlay covers the photo: when you switch it on with **O** (or the eye by the + Masks title), while the pointer is on the mask's row or pin, or by itself for a mask that has no settings yet, so + you see what it selects. A mask with settings (its own or a preset's) never shows the overlay by itself, so you can + judge its effect: picking, creating, duplicating or adding to such a mask no longer covers the photo. While a + slider, a mask drag or a brush stroke is at work nothing covers the photo, not even an overlay switched on with O; + it comes back when you let go. While an Object click or a description is still being computed, no stand-in + overlay shows. + ## 2026-10-24 ### Relative-date filters and smart albums follow the clock From bda60a67803e2501cc4a1c22e626dfa5af7945aa Mon Sep 17 00:00:00 2001 From: Patrik Lermon Date: Sun, 25 Oct 2026 08:00:56 +0100 Subject: [PATCH 044/331] i18n(sv): translate 46 new strings Brings the Swedish catalog up to date with upstream main (31ec62cd). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/sv.json | 48 +++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 159c22025b..3f31d946ff 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -3503,5 +3503,51 @@ "Drop to open the face model": "Släpp för att öppna ansiktsmodellen", "Dropped Files": "Släppta filer", "Finish Lightroom catalog import before adding photos": "Slutför importen av Lightroom-katalogen innan du lägger till foton", - "Import dropped files without review": "Importera släppta filer utan granskning" + "Import dropped files without review": "Importera släppta filer utan granskning", + "A manual slideshow shows each slide until → or ← changes it. Exports still use the slide duration.": "I ett manuellt bildspel visas varje bild tills du byter med → eller ←. Exporter använder ändå visningstiden per bild.", + "Always merge into the open library": "Sammanfoga alltid med det öppna biblioteket", + "Another library was opened since this window appeared: nothing was imported": "Ett annat bibliotek öppnades efter att det här fönstret visades: ingenting importerades", + "Ask me": "Fråga mig", + "Ask me lists your recent libraries at launch. Holding Alt (Option on a Mac) as the window appears asks once.": "Med Fråga mig visas dina senaste bibliotek vid start. Håll ned Alt (Option på en Mac) när fönstret visas för att få frågan en gång.", + "Ask where to import it": "Fråga var det ska importeras", + "At launch": "Vid start", + "Burst: how alike (loose … strict)": "Bildserie: hur lika (löst … strikt)", + "Burst: shots at most this far apart": "Bildserie: högst så här lång tid mellan bilderna", + "Checking recent libraries": "Kontrollerar senaste bibliotek", + "Choose the library to open.": "Välj det bibliotek som ska öppnas.", + "Close a dialog by clicking outside it": "Stäng en dialogruta genom att klicka utanför den", + "Create a new library": "Skapa ett nytt bibliotek", + "Create Library and Import": "Skapa bibliotek och importera", + "Don't ask again (always merge into the open library)": "Fråga inte igen (sammanfoga alltid med det öppna biblioteket)", + "Last opened": "Senast öppnat", + "LightCraft opens the new library, then imports the catalog into it. Its folder must be new or empty.": "LightCraft öppnar det nya biblioteket och importerar sedan katalogen till det. Dess mapp måste vara ny eller tom.", + "Lower it when a panning or moving burst splits into several groups.": "Sänk värdet när en panorerad eller rörlig bildserie delas upp i flera grupper.", + "No horizon or vertical lines to level by": "Ingen horisont eller lodräta linjer att räta upp efter", + "No recent libraries. Open one from a folder, or make a new one.": "Inga senaste bibliotek. Öppna ett från en mapp eller skapa ett nytt.", + "Not answering yet: the drive may be asleep or offline": "Svarar inte än: enheten kan vara i viloläge eller offline", + "Not found: moved, renamed or on a disconnected drive": "Hittades inte: flyttat, omdöpt eller på en frånkopplad enhet", + "Open": "Öppna", + "Open a library first, then drop the presets again": "Öppna ett bibliotek först och släpp sedan förinställningarna igen", + "Open Another…": "Öppna ett annat…", + "Open now": "Öppna nu", + "Open the last library": "Öppna det senaste biblioteket", + "Photos whose capture time can't be read were left as they were": "Foton vars tagningstid inte kan läsas lämnades som de var", + "Remove from List": "Ta bort från listan", + "Show briefly when photo changes": "Visa kort när fotot byts", + "Show message when loading or rendering photos": "Visa meddelande när foton läses in eller renderas", + "Show Metadata For": "Visa metadata för", + "The active photo's capture time can't be read": "Det aktiva fotots tagningstid kan inte läsas", + "The catalog's photos, collections and edits join the ones already in this library.": "Katalogens foton, samlingar och redigeringar läggs till dem som redan finns i det här biblioteket.", + "The import reads the catalog without changing it. Next, choose whether its photos, edits, keywords and collections join the library open now or go into a new library.": "Importen läser katalogen utan att ändra den. Välj sedan om dess foton, redigeringar, nyckelord och samlingar ska läggas till i det bibliotek som är öppet nu eller i ett nytt bibliotek.", + "The library is empty: the catalog's photos, collections and edits become its first.": "Biblioteket är tomt: katalogens foton, samlingar och redigeringar blir de första i det.", + "The library itself stays where it is.": "Själva biblioteket ligger kvar där det är.", + "The library's catalog can't be read:": "Bibliotekets katalog kan inte läsas:", + "The photos are imported once a library is open": "Fotona importeras när ett bibliotek är öppet", + "There is no LightCraft library in this folder any more": "Det finns inte längre något LightCraft-bibliotek i den här mappen", + "This folder can't be read:": "Den här mappen kan inte läsas:", + "This is a file, not a library folder": "Det här är en fil, inte en biblioteksmapp", + "This library couldn't be checked": "Det gick inte att kontrollera det här biblioteket", + "This library couldn't be checked:": "Det gick inte att kontrollera det här biblioteket:", + "To be asked again: Settings → General → When importing a Lightroom catalog.": "Om du vill få frågan igen: Inställningar → Allmänt → När en Lightroom-katalog importeras.", + "When importing a Lightroom catalog": "När en Lightroom-katalog importeras" } From 197383884c8a947a659e4c1a67d2833d1fa1a53d Mon Sep 17 00:00:00 2001 From: OneSlips Date: Sun, 25 Oct 2026 21:11:10 +1000 Subject: [PATCH 045/331] LR-MASK-OVERLAY: the hovered and the O-hidden mask belong to their photo A mask's hover (row or pin) and O hiding a mask's automatic overlay now keep the photo they were on: on another photo a mask with the same id is another mask, so a hover left over from the photo the filmstrip just left, or a mask hidden there, says nothing about the photo now shown (CodeRabbit). Test `tests_masking::a_mask_hovered_or_hidden_on_one_photo_says_nothing_about_another`. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/menus.rs | 3 ++- crates/ui-egui/src/panels/detail.rs | 8 +++--- crates/ui-egui/src/panels/masking.rs | 2 +- crates/ui-egui/src/state.rs | 11 ++++---- crates/ui-egui/src/tests_masking.rs | 32 ++++++++++++++++++++++- crates/ui-egui/src/tests_preview_limit.rs | 4 +-- 6 files changed, 47 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 5232f6c9fe..396f2aad9d 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1092,7 +1092,8 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option { diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 33d84fcb7a..0829134d7c 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -1588,7 +1588,9 @@ fn shapes_graphics(id: &str) -> bool { /// judges a mask's effect; hovering its row or pin, or O, shows it on request. pub(crate) fn overlay_mask<'a>(app: &LightcraftApp, d: &'a DevelopSettings) -> Option<&'a lightcraft_develop::Mask> { if !mask_gesture(app) - && let Some(m) = app.ui.mask_hover.or(app.ui.mask_hover_prev).and_then(|id| d.masks.iter().find(|m| m.id == id)) + && let Some(photo) = app.session.active() + && let Some(m) = + app.ui.mask_hover.or(app.ui.mask_hover_prev).filter(|(p, _)| *p == photo).and_then(|(_, id)| d.masks.iter().find(|m| m.id == id)) { return Some(m); } @@ -1602,7 +1604,7 @@ pub(crate) fn overlay_shown(app: &LightcraftApp, m: &lightcraft_develop::Mask) - if app.ui.mask_overlay { return true; } - if app.ui.mask_overlay_hidden == Some(m.id) { + if app.session.active().is_some_and(|photo| app.ui.mask_overlay_hidden == Some((photo, m.id))) { return false; } !mask_has_settings(m) @@ -2495,7 +2497,7 @@ fn mask_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respons if let Some(h) = resp.hover_pos() && let Some((mid, ..)) = grips.iter().find(|(_, _, handle, q)| *handle == 0 && q.distance(h) < 9.0) { - app.ui.mask_hover = Some(*mid); + app.ui.mask_hover = app.session.active().map(|photo| (photo, *mid)); } mask_keys(app, ui, map, d, &grips); // Object selections (SAM 3) of the selected mask: each click, green to include, red to exclude diff --git a/crates/ui-egui/src/panels/masking.rs b/crates/ui-egui/src/panels/masking.rs index 7e1a91505c..31526ccedf 100644 --- a/crates/ui-egui/src/panels/masking.rs +++ b/crates/ui-egui/src/panels/masking.rs @@ -265,7 +265,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let resp = if elided { resp.on_hover_text(&m.name) } else { resp }; // the pointer on a mask's row shows that mask's overlay (as Lightroom Classic) if ui.rect_contains_pointer(r) { - app.ui.mask_hover = Some(m.id); + app.ui.mask_hover = app.session.active().map(|photo| (photo, m.id)); } // show / hide on hover (and always while hidden) // (the pointer test, not `hovered`: over the eye, the row itself no longer counts as hovered) diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 15e2b0a720..24f9799bb2 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -842,14 +842,15 @@ pub struct UiState { /// or pin the pointer is on. Not kept between sessions: the photo opens without it. #[serde(skip)] pub mask_overlay: bool, - /// The mask whose row or pin the pointer is on, this frame and the last (the overlay shows it). + /// The mask whose row or pin the pointer is on, this frame and the last (the overlay shows it), + /// with the photo it is on: a mask of the same id on another photo is another mask. #[serde(skip)] - pub mask_hover: Option, + pub mask_hover: Option<(lightcraft_engine::catalog::PhotoId, u32)>, #[serde(skip)] - pub mask_hover_prev: Option, - /// O hid the automatic overlay of this mask (until O shows it again). + pub mask_hover_prev: Option<(lightcraft_engine::catalog::PhotoId, u32)>, + /// O hid the automatic overlay of this mask of this photo (until O shows it again). #[serde(skip)] - pub mask_overlay_hidden: Option, + pub mask_overlay_hidden: Option<(lightcraft_engine::catalog::PhotoId, u32)>, pub mask_overlay_mode: String, pub mask_overlay_color: [u8; 3], pub mask_overlay_opacity: f32, diff --git a/crates/ui-egui/src/tests_masking.rs b/crates/ui-egui/src/tests_masking.rs index 4d95304b6a..034b530f48 100644 --- a/crates/ui-egui/src/tests_masking.rs +++ b/crates/ui-egui/src/tests_masking.rs @@ -236,7 +236,7 @@ fn a_mask_shows_its_overlay_by_itself_only_without_settings() { assert!(!shown(&h), "{cmd} on a mask with settings shows its effect"); } // on request: the pointer on the mask's row, or O - h.app.ui.mask_hover = h.app.session.active_mask; + h.app.ui.mask_hover = h.app.session.active().zip(h.app.session.active_mask); assert!(shown(&h), "the pointer on its row shows the overlay"); off_rows(&mut h); h.request("ui.key", json!({"key": "o"}), T); @@ -244,6 +244,36 @@ fn a_mask_shows_its_overlay_by_itself_only_without_settings() { h.settle(SETTLE); } +/// The pointer on a mask's row, and O hiding a mask's automatic overlay, belong to that photo: on +/// another photo a mask with the same id is another mask. +#[test] +fn a_mask_hovered_or_hidden_on_one_photo_says_nothing_about_another() { + use lightcraft_pipeline::Overlay; + let mut h = detail("panel.masking"); + let first = h.app.session.active().unwrap(); + exec(&mut h, "mask.add", json!({"kind": "linear", "start": [0.5, 0.2], "end": [0.5, 0.7]})); + let mask = h.app.session.active_mask.unwrap(); + let shown = |h: &Headless| matches!(crate::panels::detail::view_overlay(&h.app, &develop(h)), Overlay::Mask { .. }); + // O hides the fresh mask's overlay on this photo + h.request("ui.key", json!({"key": "o"}), T); + assert!(!shown(&h)); + assert_eq!(h.app.ui.mask_overlay_hidden, Some((first, mask))); + // another photo with a fresh mask of the same id still shows it + let other = h.app.session.visible_cloned().into_iter().find(|p| *p != first).unwrap(); + exec(&mut h, "library.select", json!({"ids": [other.0]})); + exec(&mut h, "mask.add", json!({"kind": "linear", "start": [0.5, 0.2], "end": [0.5, 0.7]})); + assert_eq!(h.app.session.active(), Some(other)); + assert_eq!(h.app.session.active_mask, Some(mask), "the same id on the other photo"); + h.app.ui.mask_hover = None; + h.app.ui.mask_hover_prev = None; + assert!(shown(&h), "hidden on the first photo only"); + // a hover left over from the first photo doesn't count here + exec(&mut h, "mask.adjust", json!({"values": {"exposure": 0.5}})); + h.app.ui.mask_hover_prev = Some((first, mask)); + assert!(!shown(&h), "the first photo's hover is not this photo's"); + h.settle(SETTLE); +} + #[test] fn radial_body_drag_moves_rotated_components_and_undoes_once() { let mut h = detail("panel.masking"); diff --git a/crates/ui-egui/src/tests_preview_limit.rs b/crates/ui-egui/src/tests_preview_limit.rs index b5e17fe329..26397af151 100644 --- a/crates/ui-egui/src/tests_preview_limit.rs +++ b/crates/ui-egui/src/tests_preview_limit.rs @@ -204,7 +204,7 @@ mod in_the_loupe { h.app.ui.pan = (0.3, 0.4); // (a mask without settings shows its overlay by itself: O hides it for that mask) h.app.ui.mask_overlay = false; - h.app.ui.mask_overlay_hidden = h.app.session.active_mask; + h.app.ui.mask_overlay_hidden = h.app.session.active().zip(h.app.session.active_mask); h.settle(SETTLE); let (zoom, pan) = (h.app.ui.zoom, h.app.ui.pan); assert_eq!(zoom, crate::state::Zoom::Percent(100.0)); @@ -225,7 +225,7 @@ mod in_the_loupe { assert_ne!(shown.settings, plain.settings, "the overlay is part of the window's look"); h.app.ui.mask_overlay = false; - h.app.ui.mask_overlay_hidden = h.app.session.active_mask; + h.app.ui.mask_overlay_hidden = h.app.session.active().zip(h.app.session.active_mask); h.settle(SETTLE); assert_eq!((h.app.ui.zoom, h.app.ui.pan), (zoom, pan), "hiding it keeps them too"); assert_eq!(h.app.region_view.map(|r| r.settings), Some(plain.settings), "back to the plain window"); From 5a8f54a1ba8c6a6905a3bd5da88a8a9adee75f46 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Sun, 25 Oct 2026 23:44:29 +1000 Subject: [PATCH 046/331] LR-MASK-OVERLAY: each mask hidden with O stays hidden until O shows it again mask_overlay_hidden holds every (photo, mask) O hid, not just the last one: hiding mask B no longer brings mask A's automatic overlay back (CodeRabbit). Test `tests_masking::each_mask_hidden_with_o_stays_hidden`. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/menus.rs | 8 ++++++- crates/ui-egui/src/panels/detail.rs | 2 +- crates/ui-egui/src/state.rs | 6 ++--- crates/ui-egui/src/tests_masking.rs | 28 ++++++++++++++++++++++- crates/ui-egui/src/tests_preview_limit.rs | 6 ++--- 5 files changed, 41 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 396f2aad9d..7f22ab7401 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1093,7 +1093,13 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option