From 2eef428d407a6954bd692466508dca9de622f498 Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Fri, 16 Oct 2026 08:31:57 +0200 Subject: [PATCH 01/19] 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 ffede6c9f78ae4697f6135b4634df9f74a04ec0e Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Mon, 19 Oct 2026 15:02:55 +0200 Subject: [PATCH 02/19] Import: preserve embedded ratings, flags and labels via existing XMP sidecar pipeline - Apply embedded XMP to JPEG/TIFF during import via parse_sidecar and merge_into - Keep kind == Raw guard in sidecar::read_packet so non-raw originals are not read whole - Handle EXIF Rating tag (0x4746) including rejected (-1) rating in metadata extraction and writing - Add tests for embedded XMP rating & label, EXIF rating, and rejected (-1) ratings --- crates/engine/src/files.rs | 39 +++++++++------------ crates/engine/src/import.rs | 11 ++---- crates/engine/src/media.rs | 4 --- crates/engine/src/sidecar.rs | 13 ++++--- crates/engine/src/tests_import.rs | 57 +++++++++++++++++++++++++++++-- crates/meta/src/exif.rs | 13 ++++++- 6 files changed, 95 insertions(+), 42 deletions(-) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index c7fc994eee..81d41d0a09 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -125,6 +125,19 @@ pub fn embedded_lens(raw: &lightcraft_raw::RawInfo) -> Option Option { + match lightcraft_meta::embedded(bytes).xmp { + Some(x) if !x.contains("Rating") && m.rating.is_some() => { + let fresh = lightcraft_meta::write_xmp(m, None); + lightcraft_meta::merge_xmp(&x, &fresh, lightcraft_meta::MergeRules { owned_if_present: &["xmp:Rating"], ..Default::default() }) + .ok() + .or(Some(x)) + } + Some(x) => Some(x), + None => m.rating.map(|_| lightcraft_meta::write_xmp(m, None)), + } +} + fn ext_upper(name: &str) -> String { std::path::Path::new(name).extension().map(|e| e.to_string_lossy().to_uppercase()).unwrap_or_default() } @@ -137,13 +150,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { let content_hash = Some(lightcraft_preview::hash_bytes(bytes).to_string()); let m = lightcraft_meta::extract(bytes); let (meta, captured) = meta_of(&m); - let (rating, flag) = match m.rating { - Some(r) if r < 0 => (0, lightcraft_catalog::Flag::Reject), - Some(r) => (r.clamp(0, 5) as u8, lightcraft_catalog::Flag::None), - None => (0, lightcraft_catalog::Flag::None), - }; - let label = m.label.as_deref().and_then(|l| lightcraft_catalog::ColorLabel::parse(l.trim())); - let label_text = m.label.clone(); + let xmp = embedded_or_exif_xmp(bytes, &m); if lightcraft_raw::probe(bytes).is_some() { let raw = match lightcraft_raw::probe_info(bytes).map_err(|e| preview_reason(bytes, e)) { Ok(r) => r, @@ -158,13 +165,9 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { file_size: bytes.len() as u64, captured, meta, - rating, - flag, - label, - label_text, as_shot_wb: None, content_hash, - xmp: lightcraft_meta::embedded(bytes).xmp, + xmp, preview_only: Some(why), ..Default::default() }); @@ -189,13 +192,9 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { captured, file_modified: None, meta, - rating, - flag, - label, - label_text, as_shot_wb, content_hash, - xmp: lightcraft_meta::embedded(bytes).xmp, + xmp, preview_only: None, }); } @@ -225,14 +224,10 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { captured, file_modified: None, meta, - rating, - flag, - label, - label_text, as_shot_wb: None, content_hash, embedded_lens: None, - xmp: None, + xmp, preview_only: None, }) } diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 8cecda6f56..2b5d7aeda0 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -1060,12 +1060,13 @@ impl ImportJob { plan.slots.push(Slot::Item(PreparedItem::Duplicate { path, existing: *existing, reason: "content", hash: Some(h.clone()) })); continue; } - // the XMP sidecar (or a raw's embedded XMP), read before copying: its capture time files + // the XMP sidecar (or a file's embedded XMP), read before copying: its capture time files // and names the copy when the file itself has none let raw = info.kind == MediaKind::Raw; + let has_embedded_xmp = raw || matches!(info.format.as_str(), "JPEG" | "JPG" | "TIFF" | "TIF"); let packet = crate::sidecar::find_sidecar(&path, self.naming) .and_then(|f| std::fs::read_to_string(f).ok()) - .or_else(|| info.xmp.clone().filter(|_| raw)); + .or_else(|| info.xmp.clone().filter(|_| has_embedded_xmp)); let target = crate::crs::Target::for_file(info.kind, &info.format, info.preview_only.is_some(), &info.meta.camera); let sidecar = packet.and_then(|x| match crate::sidecar::parse_sidecar(&x, target) { Ok(sc) => Some(sc), @@ -1091,9 +1092,6 @@ impl ImportJob { let mut q = Photo::new(PhotoId(0), Source::File { path: path.clone() }, &own, &info.format, 0, 0, &self.now); q.captured = info.captured.clone(); q.meta = info.meta.clone(); - q.rating = info.rating; - q.flag = info.flag; - q.label = info.label; if let Some(sc) = &sidecar { crate::sidecar::merge_into(&mut q, sc, &self.now); } @@ -1421,9 +1419,6 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare p.file_size = info.file_size; p.captured = info.captured; p.meta = info.meta; - p.rating = info.rating; - p.flag = info.flag; - p.label = info.label_text.as_deref().and_then(|t| s.catalog.label_from_name(t)).or(info.label); p.as_shot_wb = info.as_shot_wb; p.content_hash = info.content_hash; p.embedded_lens = info.embedded_lens; diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 681b0bd5ce..22d76528d6 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -1658,10 +1658,6 @@ pub struct ProbeInfo { /// metadata would otherwise all land under "Unknown Date"). pub file_modified: Option, pub meta: lightcraft_catalog::Meta, - pub rating: u8, - pub flag: lightcraft_catalog::Flag, - pub label: Option, - pub label_text: Option, pub as_shot_wb: Option<(f64, f64)>, /// Hash of the file's bytes (hex), for duplicate detection. When it is a 32-digit /// [`lightcraft_preview::hash_bytes`] of the whole file (as the native probe computes it), diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 5ffa6b5042..cdee1e8942 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -500,16 +500,19 @@ fn file_path(p: &Photo) -> Option<&str> { } } -/// The XMP packet that describes a photo on disk: its sidecar, else the file's embedded XMP. -pub fn read_packet(original: &str, _kind: MediaKind, naming: SidecarNaming) -> Option<(String, PathBuf)> { +/// The XMP packet that describes a photo on disk: its sidecar, else (raw/DNG) the embedded XMP. +pub fn read_packet(original: &str, kind: MediaKind, naming: SidecarNaming) -> Option<(String, PathBuf)> { if let Some(sc) = find_sidecar(original, naming) && let Ok(s) = std::fs::read_to_string(&sc) { return Some((s, sc)); } - let bytes = std::fs::read(original).ok()?; - let x = lightcraft_meta::embedded(&bytes).xmp?; - Some((x, PathBuf::from(original))) + if kind == MediaKind::Raw { + let bytes = std::fs::read(original).ok()?; + let x = lightcraft_meta::embedded(&bytes).xmp?; + return Some((x, PathBuf::from(original))); + } + None } /// Photo ids touched by an op (for auto-write). diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs index e9f3365f41..2ac89d4661 100644 --- a/crates/engine/src/tests_import.rs +++ b/crates/engine/src/tests_import.rs @@ -1794,9 +1794,9 @@ fn presets_apply_the_imported_profile_they_name() { } #[test] -fn import_preserves_embedded_rating_and_label() { +fn import_preserves_embedded_xmp_rating_and_label() { use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; - let src = temp_dir("embedded-rating-test"); + let src = temp_dir("embedded-xmp-rating-test"); let px = [128u8; 40 * 30 * 3]; let xmp = r#""#; let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() }; @@ -1808,7 +1808,60 @@ fn import_preserves_embedded_rating_and_label() { assert_eq!(ids(&r, "imported"), 1); let p = s.catalog.photos().next().unwrap(); assert_eq!(p.rating, 5); + assert_eq!(p.flag, lightcraft_catalog::Flag::None); assert_eq!(p.label, Some(lightcraft_catalog::ColorLabel::Blue)); let _ = std::fs::remove_dir_all(&src); } + +#[test] +fn import_preserves_embedded_exif_rating() { + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("embedded-exif-rating-test"); + let px = [128u8; 40 * 30 * 3]; + let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { rating: Some(3), ..Default::default() }); + let meta = EncodeMeta { exif: Some(&exif), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("exif_rating.jpg"), &bytes).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.join("exif_rating.jpg").to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 1); + let p = s.catalog.photos().next().unwrap(); + assert_eq!(p.rating, 3); + assert_eq!(p.flag, lightcraft_catalog::Flag::None); + + let _ = std::fs::remove_dir_all(&src); +} + +#[test] +fn import_preserves_embedded_rejected_rating() { + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("embedded-rejected-rating-test"); + let px = [128u8; 40 * 30 * 3]; + + // Case 1: EXIF rating -1 + let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { rating: Some(-1), ..Default::default() }); + let meta = EncodeMeta { exif: Some(&exif), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("exif_rejected.jpg"), &bytes).unwrap(); + + // Case 2: XMP rating -1 + let xmp = r#""#; + let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("xmp_rejected.jpg"), &bytes).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 2); + let exif_p = s.catalog.photos().find(|p| p.file_name == "exif_rejected.jpg").unwrap(); + assert_eq!(exif_p.rating, 0); + assert_eq!(exif_p.flag, lightcraft_catalog::Flag::Reject); + + let xmp_p = s.catalog.photos().find(|p| p.file_name == "xmp_rejected.jpg").unwrap(); + assert_eq!(xmp_p.rating, 0); + assert_eq!(xmp_p.flag, lightcraft_catalog::Flag::Reject); + + let _ = std::fs::remove_dir_all(&src); +} diff --git a/crates/meta/src/exif.rs b/crates/meta/src/exif.rs index 2b2ea1d131..f2c9ceef4a 100644 --- a/crates/meta/src/exif.rs +++ b/crates/meta/src/exif.rs @@ -67,7 +67,10 @@ pub fn from_tiff(tiff: &Tiff) -> Metadata { m.lens_spec = nikon_lens_spec(exif, m.make.as_deref(), tiff.order); } m.orientation = ifd0.and_then(|i| i.u16(t::ORIENTATION)).filter(|v| (1..=8).contains(v)).map(Orientation::from_exif); - m.rating = ifd0.and_then(|i| i.i64(t::RATING)).map(|r| r.clamp(-1, 5) as i8); + m.rating = ifd0.and_then(|i| i.i64(t::RATING)).map(|r| { + let r = if r == 65535 || r == -1 { -1 } else { r }; + r.clamp(-1, 5) as i8 + }); m.exposure_time = pos(either(t::EXPOSURE_TIME).and_then(|v| v.get_f64(0))) .or_else(|| exif.and_then(|e| e.f64(t::SHUTTER_SPEED_VALUE)).filter(|v| v.abs() < 64.0).map(|tv| 2f64.powf(-tv))); @@ -444,6 +447,9 @@ pub fn write_exif(meta: &Metadata) -> Vec { ifd0.set(tag, v); } } + if let Some(r) = meta.rating { + ifd0.set(t::RATING, if r < 0 { Value::Short(vec![0xffff]) } else { Value::Short(vec![r as u16]) }); + } let mut ex = IfdBuilder::new(); ex.set(t::EXIF_VERSION, Value::Undefined(b"0232".to_vec())); let r = |v: Option| v.filter(|v| v.is_finite() && *v > 0.0).map(|v| Value::Rational(vec![rational(v)])); @@ -503,6 +509,7 @@ mod write_tests { focal_length: Some(35.0), lens_model: Some("35mm F2".into()), gps: Some(Gps { latitude: 43.7904, longitude: -110.6818, altitude: Some(2000.0) }), + rating: Some(4), ..Default::default() }; let back = read_exif(&write_exif(&m)); @@ -515,7 +522,11 @@ mod write_tests { assert!((back.f_number.unwrap() - 2.8).abs() < 1e-6); assert!((back.exposure_time.unwrap() - 0.004).abs() < 1e-9); assert_eq!(back.lens_model, m.lens_model); + assert_eq!(back.rating, Some(4)); let g = back.gps.unwrap(); assert!((g.latitude - 43.7904).abs() < 1e-5 && (g.longitude + 110.6818).abs() < 1e-5, "{g:?}"); + + let rejected = read_exif(&write_exif(&Metadata { rating: Some(-1), ..Default::default() })); + assert_eq!(rejected.rating, Some(-1)); } } From 7aeb1561ed574db776c9aae10166282307082ba7 Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Mon, 19 Oct 2026 15:25:25 +0200 Subject: [PATCH 03/19] 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 a5e943364187b69a37a908ed7182a4e17a684ab1 Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Wed, 21 Oct 2026 07:31:07 +0200 Subject: [PATCH 04/19] Import: ignore embedded develop adjustments for rendered images - Clear parsed develop settings and warnings when XMP packet is embedded in a non-raw image (JPEG, TIFF, PNG, WebP) - Keep develop adjustments for raw/DNG files or external sidecars - Add test verifying that a JPEG with embedded rating and crs:Exposure2012 imports with rating and default develop state --- crates/engine/src/import.rs | 17 +++++++++++++---- crates/engine/src/tests_import.rs | 25 +++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 96e8db7788..5abf63cdad 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -1064,17 +1064,26 @@ impl ImportJob { // and names the copy when the file itself has none let raw = info.kind == MediaKind::Raw; let has_embedded_xmp = raw || matches!(info.format.to_ascii_uppercase().as_str(), "JPEG" | "JPG" | "TIFF" | "TIF" | "PNG" | "WEBP"); - let packet = crate::sidecar::find_sidecar(&path, self.naming) - .and_then(|f| std::fs::read_to_string(f).ok()) - .or_else(|| info.xmp.clone().filter(|_| has_embedded_xmp)); + let sidecar_file = crate::sidecar::find_sidecar(&path, self.naming).and_then(|f| std::fs::read_to_string(f).ok()); + let from_file = sidecar_file.is_none(); + let packet = sidecar_file.or_else(|| info.xmp.clone().filter(|_| has_embedded_xmp)); let target = crate::crs::Target::for_file(info.kind, &info.format, info.preview_only.is_some(), &info.meta.camera); - let sidecar = packet.and_then(|x| match crate::sidecar::parse_sidecar(&x, target) { + let mut sidecar = packet.and_then(|x| match crate::sidecar::parse_sidecar(&x, target) { Ok(sc) => Some(sc), Err(e) => { log::warn!("import {path}: XMP: {e}"); None } }); + // Embedded XMP on a rendered file (JPEG, TIFF, PNG, WebP) has develop adjustments + // already baked into the pixels; only raws/DNGs keep foreign develop settings from embedded XMP. + if from_file + && !raw + && let Some(sc) = &mut sidecar + { + sc.develop = None; + sc.warnings.clear(); + } if info.captured.is_none() { info.captured = sidecar.as_ref().and_then(|sc| sc.captured.clone()); } diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs index 1ab0b24b87..3993f81b15 100644 --- a/crates/engine/src/tests_import.rs +++ b/crates/engine/src/tests_import.rs @@ -1920,3 +1920,28 @@ fn import_preserves_exif_rating_when_xmp_has_unrelated_rating_text() { let _ = std::fs::remove_dir_all(&src); } + +#[test] +fn import_rendered_file_ignores_embedded_develop_settings() { + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("embedded-rendered-develop-test"); + let px = [128u8; 40 * 30 * 3]; + + // A JPEG with embedded XMP containing rating and crs:Exposure2012="+1.00" + let xmp = r#""#; + let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("rendered_with_crs.jpg"), &bytes).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.join("rendered_with_crs.jpg").to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 1); + let p = s.catalog.photos().next().unwrap(); + // Rating is imported from embedded XMP + assert_eq!(p.rating, 3); + // Develop settings from embedded XMP are ignored for rendered files (already baked into pixels) + assert_eq!(p.develop.light.exposure, 0.0); + assert_eq!(p.develop, std::sync::Arc::new(p.camera_defaults())); + + let _ = std::fs::remove_dir_all(&src); +} From d6575581ed03215164fc6cee0257986705a8a474 Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Thu, 22 Oct 2026 22:25:39 +0200 Subject: [PATCH 05/19] 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 824395025b31afdb6d689287e5ad1137f4a0355c Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Mon, 26 Oct 2026 11:17:48 +1100 Subject: [PATCH 06/19] security(codecs): refuse decodes with no pixels; checked JPEG sample counts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `decode_unguarded` returns `Malformed` for an image of zero width or height or a buffer shorter than its size, so nothing downstream receives an empty image. - The JPEG short-output checks compute w × h × channels with `checked_sample_buf_len` instead of a `usize` product that wraps on wasm32. Refs #2579 Co-Authored-By: Claude Opus 5.5 --- crates/codecs/src/jpeg.rs | 6 ++++-- crates/codecs/src/lib.rs | 9 ++++++++- crates/codecs/tests/it/fuzz.rs | 16 ++++++++++++++++ 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/crates/codecs/src/jpeg.rs b/crates/codecs/src/jpeg.rs index d8b0241a13..ae9a1a61ae 100644 --- a/crates/codecs/src/jpeg.rs +++ b/crates/codecs/src/jpeg.rs @@ -226,7 +226,7 @@ fn decode_zune(bytes: &[u8], m: &Markers, budget: &DecodeOptions) -> Result let info = d.info().ok_or_else(|| Error::Malformed(F, "no info".into()))?; let (w, h) = (info.width as usize, info.height as usize); let model = if gray { Model::Gray } else { Model::Rgb }; - if px.len() < w * h * model.channels() { + if crate::checked_sample_buf_len(w, h, model.channels()).is_none_or(|n| (px.len() as u64) < n) { return Err(Error::Malformed(F, "short output".into())); } Ok(Raw { width: w, height: h, model, alpha: false, premultiplied: false, buf: Buf::U8(px), bit_depth: 8 }) @@ -403,7 +403,9 @@ pub(crate) fn decode_codes8(bytes: &[u8]) -> Result<(usize, usize, usize, Vec= raw.width * raw.height * ch => Ok((raw.width, raw.height, ch, v)), + Buf::U8(v) if crate::checked_sample_buf_len(raw.width, raw.height, ch).is_some_and(|n| v.len() as u64 >= n) => { + Ok((raw.width, raw.height, ch, v)) + } _ => Err(Error::Malformed(F, "unexpected sample format".into())), } } diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index a20a47d14c..f4fd1a8567 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -230,7 +230,7 @@ pub fn decode_unguarded(bytes: &[u8], format: Format, opts: &DecodeOptions) -> R let opts = *opts; // The reason a format can't be decoded lives in one place, `Format::not_decodable`. let unsupported = || Err(Error::Unsupported(format, format.not_decodable().unwrap_or("not decodable in this build"))); - match format { + let d = match format { Format::Jpeg => jpeg::decode(bytes, &opts), Format::Png => png_codec::decode(bytes, &opts), Format::Tiff => tiff_codec::decode(bytes, &opts), @@ -243,7 +243,14 @@ pub fn decode_unguarded(bytes: &[u8], format: Format, opts: &DecodeOptions) -> R Format::Jxl => unsupported(), Format::Heif => heif::decode(bytes, &opts), Format::Avif | Format::RawTiffLike | Format::RawOther => unsupported(), + }?; + // an image with no pixels (a malformed header claiming zero width or height, or a buffer + // shorter than its size) is refused here, so nothing downstream sees an empty image + let (w, h) = (d.image.width, d.image.height); + if w == 0 || h == 0 || w.checked_mul(h).is_none_or(|n| d.image.data.len() < n) { + return Err(Error::Malformed(format, "image has no pixels".into())); } + Ok(d) } /// Convert a decode result to linear Rec.2020 D65 (Bradford-adapted), the develop working space. diff --git a/crates/codecs/tests/it/fuzz.rs b/crates/codecs/tests/it/fuzz.rs index bfee84dfe4..d79bd7bd36 100644 --- a/crates/codecs/tests/it/fuzz.rs +++ b/crates/codecs/tests/it/fuzz.rs @@ -85,6 +85,22 @@ fn thumbnail_respects_configured_source_pixel_limit() { assert_eq!(decode_thumbnail_with(&bytes, &opts).unwrap().image.width, 1); } +/// A header claiming zero width or height is an error, never a decoded image with no pixels +/// (downstream filters index into it). +#[test] +fn zero_size_headers_are_refused() { + let jpeg = seeds()[0].clone(); + let sof = jpeg.windows(2).position(|m| m == [0xFF, 0xC0]).unwrap(); + for at in [sof + 5, sof + 7] { + let mut j = jpeg.clone(); + j[at..at + 2].copy_from_slice(&[0, 0]); + assert!(decode_unguarded(&j, Format::Jpeg, &small_opts()).is_err()); + } + let mut png = seeds()[1].clone(); + png[16..20].copy_from_slice(&[0; 4]); + assert!(decode_unguarded(&png, Format::Png, &small_opts()).is_err()); +} + fn seeds() -> &'static Vec> { static S: OnceLock>> = OnceLock::new(); S.get_or_init(|| { From a9afb1868c069257741214c35776b77464074d67 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Tue, 27 Oct 2026 17:31:27 +1100 Subject: [PATCH 07/19] test(codecs): test the no-pixels guard and checked JPEG sample count directly Moves the final-output check into check_has_pixels and tests it with zero width, zero height, an overflowing w*h and a short RGB buffer (fails when the guard is removed). Adds the 65535x21846x3 case a 32-bit usize product wraps. The PNG zero-dimension fixture now repairs its IHDR CRC and covers height too. Co-Authored-By: Claude Opus 5.5 --- crates/codecs/src/lib.rs | 41 +++++++++++++++++++++++++++++----- crates/codecs/tests/it/fuzz.rs | 27 +++++++++++++++++++--- 2 files changed, 60 insertions(+), 8 deletions(-) diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index f4fd1a8567..07d895a985 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -244,13 +244,19 @@ pub fn decode_unguarded(bytes: &[u8], format: Format, opts: &DecodeOptions) -> R Format::Heif => heif::decode(bytes, &opts), Format::Avif | Format::RawTiffLike | Format::RawOther => unsupported(), }?; - // an image with no pixels (a malformed header claiming zero width or height, or a buffer - // shorter than its size) is refused here, so nothing downstream sees an empty image - let (w, h) = (d.image.width, d.image.height); - if w == 0 || h == 0 || w.checked_mul(h).is_none_or(|n| d.image.data.len() < n) { + check_has_pixels(format, &d.image)?; + Ok(d) +} + +/// An image with no pixels (a malformed header claiming zero width or height, a `w × h` that +/// overflows, or a buffer shorter than its size) is refused, so nothing downstream sees an empty +/// image. +fn check_has_pixels(format: Format, image: &Rgb32f) -> Result<()> { + let (w, h) = (image.width, image.height); + if w == 0 || h == 0 || w.checked_mul(h).is_none_or(|n| image.data.len() < n) { return Err(Error::Malformed(format, "image has no pixels".into())); } - Ok(d) + Ok(()) } /// Convert a decode result to linear Rec.2020 D65 (Bradford-adapted), the develop working space. @@ -370,4 +376,29 @@ mod checked_arithmetic_tests { // 300 Mpx RGBA is within the default pixel limit, so it must not be refused by sample count. assert_eq!(checked_sample_buf_len(20_000, 15_000, 4), Some(1_200_000_000)); } + + #[test] + fn checked_sample_buf_len_does_not_wrap_like_32_bit_usize() { + // 65535 × 21846 × 3 = 4_295_032_830, which a 32-bit `usize` product wraps to 65_534 + assert_eq!(checked_sample_buf_len(65_535, 21_846, 3), Some(4_295_032_830)); + assert!(checked_sample_buf_len(65_535, 21_846, 3).is_some_and(|n| n > 65_534)); + } + + fn image(width: usize, height: usize, len: usize) -> Rgb32f { + Rgb32f { width, height, data: vec![[0.0; 3]; len] } + } + + #[test] + fn decoded_image_without_pixels_is_refused() { + for (w, h, len) in [(0, 4, 0), (4, 0, 0), (usize::MAX, 2, 1), (4, 4, 15)] { + let r = check_has_pixels(Format::Png, &image(w, h, len)); + assert!(matches!(r, Err(Error::Malformed(Format::Png, _))), "{w}x{h} with {len} pixels"); + } + } + + #[test] + fn decoded_image_with_all_pixels_is_accepted() { + assert!(check_has_pixels(Format::Png, &image(4, 4, 16)).is_ok()); + assert!(check_has_pixels(Format::Png, &image(1, 1, 1)).is_ok()); + } } diff --git a/crates/codecs/tests/it/fuzz.rs b/crates/codecs/tests/it/fuzz.rs index d79bd7bd36..0fa56101eb 100644 --- a/crates/codecs/tests/it/fuzz.rs +++ b/crates/codecs/tests/it/fuzz.rs @@ -88,6 +88,9 @@ fn thumbnail_respects_configured_source_pixel_limit() { /// A header claiming zero width or height is an error, never a decoded image with no pixels /// (downstream filters index into it). #[test] +// End-to-end no-panic check: headers claiming a zero dimension are errors. The JPEG and PNG +// readers already refuse these; `decode_unguarded`'s own final-output guard is tested directly in +// the crate's unit tests. fn zero_size_headers_are_refused() { let jpeg = seeds()[0].clone(); let sof = jpeg.windows(2).position(|m| m == [0xFF, 0xC0]).unwrap(); @@ -96,9 +99,27 @@ fn zero_size_headers_are_refused() { j[at..at + 2].copy_from_slice(&[0, 0]); assert!(decode_unguarded(&j, Format::Jpeg, &small_opts()).is_err()); } - let mut png = seeds()[1].clone(); - png[16..20].copy_from_slice(&[0; 4]); - assert!(decode_unguarded(&png, Format::Png, &small_opts()).is_err()); + let png = seeds()[1].clone(); + for at in [16, 20] { + let mut p = png.clone(); + p[at..at + 4].copy_from_slice(&[0; 4]); + // repair the IHDR CRC so the dimension, not the checksum, is what gets refused + let crc = crc32(&p[12..29]); + p[29..33].copy_from_slice(&crc.to_be_bytes()); + assert!(decode_unguarded(&p, Format::Png, &small_opts()).is_err()); + } +} + +/// CRC-32 (IEEE), as PNG chunks use. +fn crc32(bytes: &[u8]) -> u32 { + let mut c = !0u32; + for &b in bytes { + c ^= u32::from(b); + for _ in 0..8 { + c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }; + } + } + !c } fn seeds() -> &'static Vec> { From cd493e6a91b38500d38cdd639be1a9081c041eaf Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Wed, 28 Oct 2026 21:43:41 +0100 Subject: [PATCH 08/19] Import: preserve embedded metadata with partial external sidecar override - Apply embedded metadata first, then override only fields supplied by external sidecar - Keep embedded develop settings suppressed for rendered images before applying external develop settings - Add regression tests for partial and complete sidecar overrides --- crates/engine/src/import/job.rs | 44 ++++++++++++------ crates/engine/src/sidecar.rs | 72 +++++++++++++++++++++++++++++ crates/engine/src/tests/import.rs | 77 +++++++++++++++++++++++++++++++ 3 files changed, 179 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index 5230ef403b..f4f26b4806 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -333,26 +333,39 @@ 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 sidecar_file = crate::sidecar::find_sidecar_for_import(&stems, self.naming, &path).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 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 - } - }); + let mut embedded_sidecar = + info.xmp.as_deref().filter(|_| has_embedded_xmp).and_then(|x| match crate::sidecar::parse_sidecar(x, target) { + Ok(sc) => Some(sc), + Err(e) => { + log::warn!("import {path}: embedded 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 - { + if !raw && let Some(sc) = &mut embedded_sidecar { sc.develop = None; sc.warnings.clear(); } + let external_sidecar = crate::sidecar::find_sidecar_for_import(&stems, self.naming, &path) + .and_then(|f| std::fs::read_to_string(f).ok()) + .and_then(|x| match crate::sidecar::parse_sidecar(&x, target) { + Ok(sc) => Some(sc), + Err(e) => { + log::warn!("import {path}: XMP: {e}"); + None + } + }); + let sidecar = match (embedded_sidecar, external_sidecar) { + (Some(mut embedded), Some(external)) => { + embedded.override_with(external); + Some(embedded) + } + (Some(embedded), None) => Some(embedded), + (None, Some(external)) => Some(external), + (None, None) => None, + }; if info.captured.is_none() { info.captured = sidecar.as_ref().and_then(|sc| sc.captured.clone()); } @@ -370,6 +383,9 @@ 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(); + 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; diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index d13b951257..f20ec7ca61 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -342,6 +342,78 @@ impl SidecarData { } self } + + /// Overlay fields supplied by `other` onto `self`: any field present in `other` + /// replaces the one in `self`. + pub fn override_with(&mut self, other: SidecarData) { + if other.rating.is_some() { + self.rating = other.rating; + if self.flag == Some(Flag::Reject) && other.flag.is_none() { + self.flag = Some(Flag::None); + } + } + if other.flag.is_some() { + self.flag = other.flag; + } + if other.label.is_some() { + self.label = other.label; + self.label_text = other.label_text; + } + if other.title.is_some() { + self.title = other.title; + } + if other.caption.is_some() { + self.caption = other.caption; + } + if other.copyright.is_some() { + self.copyright = other.copyright; + } + if other.copyright_marked.is_some() { + self.copyright_marked = other.copyright_marked; + } + if other.usage_terms.is_some() { + self.usage_terms = other.usage_terms; + } + if other.copyright_url.is_some() { + self.copyright_url = other.copyright_url; + } + if other.creator.is_some() { + self.creator = other.creator; + } + if other.location.is_some() { + self.location = other.location; + } + if other.city.is_some() { + self.city = other.city; + } + if other.state.is_some() { + self.state = other.state; + } + if other.country.is_some() { + self.country = other.country; + } + if other.alt_text.is_some() { + self.alt_text = other.alt_text; + } + if other.extended_description.is_some() { + self.extended_description = other.extended_description; + } + if other.keywords.is_some() { + self.keywords = other.keywords; + } + if other.regions.is_some() { + self.regions = other.regions; + } + if other.captured.is_some() { + self.captured = other.captured; + } + if other.develop.is_some() { + self.develop = other.develop; + self.warnings = other.warnings; + } else { + self.warnings.extend(other.warnings); + } + } } /// The sidecar packet for a photo; the colour label is written by its name in `cat` (custom diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 5b8dbab1ab..441a7797f6 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -2359,6 +2359,83 @@ fn import_rendered_file_ignores_embedded_develop_settings() { let _ = std::fs::remove_dir_all(&src); } +#[test] +fn import_embedded_metadata_and_field_specific_sidecar_precedence() { + use lightcraft_catalog::ColorLabel; + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("embedded-sidecar-precedence-test"); + let px = [128u8; 40 * 30 * 3]; + + // Case 1: JPEG with embedded Rating 4 and Label Blue, external sidecar with only Label Red + let xmp = r#""#; + let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() }; + let bytes1 = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("partial.jpg"), &bytes1).unwrap(); + let partial_sidecar = r#""#; + std::fs::write(src.join("partial.xmp"), partial_sidecar).unwrap(); + + // Case 2: JPEG with embedded Rating 4 and Label Blue, without sidecar + let px2 = [129u8; 40 * 30 * 3]; + let bytes2 = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px2)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("no_sidecar.jpg"), &bytes2).unwrap(); + + // Case 3: JPEG with embedded Rating 4 and Label Blue, complete sidecar override with Rating 1 and Label Red + let px3 = [130u8; 40 * 30 * 3]; + let bytes3 = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px3)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("complete.jpg"), &bytes3).unwrap(); + let complete_sidecar = r#""#; + std::fs::write(src.join("complete.xmp"), complete_sidecar).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"), 3); + + let partial_p = s.catalog.photos().find(|p| p.file_name == "partial.jpg").unwrap(); + assert_eq!(partial_p.rating, 4); + assert_eq!(partial_p.label, Some(ColorLabel::Red)); + + let no_sidecar_p = s.catalog.photos().find(|p| p.file_name == "no_sidecar.jpg").unwrap(); + assert_eq!(no_sidecar_p.rating, 4); + assert_eq!(no_sidecar_p.label, Some(ColorLabel::Blue)); + + let complete_p = s.catalog.photos().find(|p| p.file_name == "complete.jpg").unwrap(); + assert_eq!(complete_p.rating, 1); + assert_eq!(complete_p.label, Some(ColorLabel::Red)); + + let _ = std::fs::remove_dir_all(&src); +} + +#[test] +fn import_partial_sidecar_override_with_rendered_develop() { + use lightcraft_catalog::ColorLabel; + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("embedded-sidecar-rendered-develop-test"); + let px = [128u8; 40 * 30 * 3]; + + // JPEG with embedded Rating 4, Label Blue, and crs:Exposure2012="+2.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("photo.jpg"), &bytes).unwrap(); + + // Sidecar overriding Label to Red and explicitly setting Exposure to +1.00 (no rating tag) + let sidecar_xmp = r#""#; + std::fs::write(src.join("photo.xmp"), sidecar_xmp).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(); + // Rating 4 from embedded is kept + assert_eq!(p.rating, 4); + // Label Red from sidecar overrides Blue + assert_eq!(p.label, Some(ColorLabel::Red)); + // External sidecar's develop settings apply; embedded exposure +2 stays suppressed + assert_eq!(p.develop.light.exposure, 1.0); + + let _ = std::fs::remove_dir_all(&src); +} + /// A raw container LightCraft shows by its embedded JPEG: a TIFF whose IFD0 points at one. fn write_raw(path: &Path) { use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; From c3ec4f31d79e16cabac98c07622504a01d79b69c Mon Sep 17 00:00:00 2001 From: Sebastian Berschneider Date: Fri, 30 Oct 2026 13:01:43 +0100 Subject: [PATCH 09/19] test(engine): pin raw embedded develop preservation with partial sidecar --- crates/engine/src/tests/import.rs | 59 +++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index c451d3b907..070caded38 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -2470,6 +2470,65 @@ fn import_partial_sidecar_override_with_rendered_develop() { let _ = std::fs::remove_dir_all(&src); } +#[test] +fn import_raw_with_embedded_develop_and_partial_sidecar() { + use lightcraft_catalog::ColorLabel; + let src = temp_dir("raw-embedded-develop-sidecar-test"); + let xmp = r#""#; + + // Case 1: Raw with embedded develop + rating + label, external sidecar has only Label Red + write_raw_with_xmp(&src.join("raw1.NEF"), xmp, 1); + let sidecar1 = r#""#; + std::fs::write(src.join("raw1.xmp"), sidecar1).unwrap(); + + // Case 2: Raw with embedded develop, external sidecar overrides develop settings to Exposure +0.50 and Rating 5 + write_raw_with_xmp(&src.join("raw2.NEF"), xmp, 2); + let sidecar2 = r#""#; + std::fs::write(src.join("raw2.xmp"), sidecar2).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 p1 = s.catalog.photos().find(|p| p.file_name == "raw1.NEF").unwrap(); + assert_eq!(p1.rating, 2, "rating from embedded XMP is preserved"); + assert_eq!(p1.label, Some(ColorLabel::Red), "label is overridden by external sidecar"); + assert_eq!(p1.develop.light.exposure, 1.5, "raw keeps embedded develop when sidecar provides none"); + + let p2 = s.catalog.photos().find(|p| p.file_name == "raw2.NEF").unwrap(); + assert_eq!(p2.rating, 5, "rating is overridden by external sidecar"); + assert_eq!(p2.label, Some(ColorLabel::Blue), "label from embedded XMP is preserved"); + assert_eq!(p2.develop.light.exposure, 0.5, "external sidecar develop overrides embedded develop"); + + let _ = std::fs::remove_dir_all(&src); +} + +/// A raw container LightCraft shows by its embedded JPEG: a TIFF whose IFD0 points at one, +/// optionally with an embedded XMP packet in tag 700. +fn write_raw_with_xmp(path: &Path, xmp: &str, seed: u8) { + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let px: Vec = (0..48 * 32).flat_map(|i| [(i % 251) as u8, 91, seed]).collect(); + let j = encode_jpeg(&EncodeImage::new(48, 32, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &EncodeMeta::default()).unwrap(); + let xmp_bytes = xmp.as_bytes(); + let xmp_off = 8 + 2 + 36 + 4; + let jpeg_off = xmp_off + xmp_bytes.len(); + let mut f = b"II*\0\x08\0\0\0\x03\0".to_vec(); + for (tag, v) in [(513u16, jpeg_off as u32), (514, j.len() as u32)] { + f.extend_from_slice(&tag.to_le_bytes()); + f.extend_from_slice(&[4, 0, 1, 0, 0, 0]); + f.extend_from_slice(&v.to_le_bytes()); + } + f.extend_from_slice(&700u16.to_le_bytes()); + f.extend_from_slice(&[1, 0]); + f.extend_from_slice(&(xmp_bytes.len() as u32).to_le_bytes()); + f.extend_from_slice(&(xmp_off as u32).to_le_bytes()); + f.extend_from_slice(&[0, 0, 0, 0]); + f.extend_from_slice(xmp_bytes); + f.extend_from_slice(&j); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, f).unwrap(); +} + /// A raw container LightCraft shows by its embedded JPEG: a TIFF whose IFD0 points at one. fn write_raw(path: &Path) { use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; From 8246dd00d6e71c841f11f97268b11ea75ea3ae3e Mon Sep 17 00:00:00 2001 From: radialmonster Date: Sun, 25 Oct 2026 17:16:59 -0400 Subject: [PATCH 10/19] Export: downscale with Lanczos-3 and sharpen with a Gaussian luma USM (#2970) Exports shrank with the preview's Mitchell filter, which left small exports (800 px web sizes) visibly soft even with output sharpening on. Exports now downscale with Lanczos-3 (RenderRequest::downscale = Sharp, CPU and GPU); previews and thumbnails keep Mitchell. Output sharpening is an unsharp mask on luma at output scale: a Gaussian of 0.7 / 0.8 / 1.0 output px for screen / glossy / matte, amount x0.5 / x1 / x1.6 for low / standard / high, with overshoot clamped to 10 % of the local 3x3 range so edges get no halos or colour fringes. Full-size exports keep their size and, with sharpening off, are bit-identical to before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014ti8KemZbjE2ZgHgV1q1BM --- apps/lightcraft-web/src/wire.rs | 1 + crates/engine/src/export/encoding.rs | 88 ++++++++++++++++++---------- crates/engine/src/export/tests.rs | 30 ++++++++++ crates/engine/src/media/session.rs | 5 +- crates/gpu/src/render.rs | 2 +- crates/pipeline/src/geometry.rs | 10 +++- crates/pipeline/src/lib.rs | 26 +++++++- crates/pipeline/src/tests.rs | 21 +++++++ 8 files changed, 145 insertions(+), 38 deletions(-) diff --git a/apps/lightcraft-web/src/wire.rs b/apps/lightcraft-web/src/wire.rs index e7202bbc59..4900f89c14 100644 --- a/apps/lightcraft-web/src/wire.rs +++ b/apps/lightcraft-web/src/wire.rs @@ -132,6 +132,7 @@ impl WireJob { proof: None, window: self.window.map(|[x, y, w, h]| lightcraft_engine::pipeline::PixelWindow { x, y, w, h }), display: None, + downscale: lightcraft_engine::pipeline::Downscale::Smooth, } } diff --git a/crates/engine/src/export/encoding.rs b/crates/engine/src/export/encoding.rs index ecdc32aa31..6b182e4f12 100644 --- a/crates/engine/src/export/encoding.rs +++ b/crates/engine/src/export/encoding.rs @@ -6,7 +6,7 @@ use super::{ }; use std::borrow::Cow; -/// Unsharp mask on an 8-bit image (separable box-blur approximation of a small Gaussian). +/// Output sharpening of an 8-bit image: an unsharp mask on its luma ([`unsharp`]). pub fn output_sharpen(img: &mut Rgba8, target: SharpenFor, amount: SharpenAmount) { if !sharpens(img.width, img.height, target) { return; @@ -52,47 +52,71 @@ fn sharpens(w: usize, h: usize, target: SharpenFor) -> bool { target != SharpenFor::None && w >= 3 && h >= 3 } -/// The sharpened values of `src` (`w × h`), or `None` when nothing is to be done. +// How far a sharpened pixel may pass the darkest and lightest of its 3×3 neighbours, as a share +/// of their difference: enough for crisp edges, too little for the light and dark rims (halos) +/// a plain unsharp mask draws along strong edges. +const SHARPEN_OVERSHOOT: f32 = 0.1; + +/// The sharpened values of `src` (`w × h`), or `None` when nothing is to be done: an unsharp mask +/// at the output's own pixel scale (a Gaussian of radius `sigma` output pixels), on luma only (no +/// colour fringes), with its overshoot past the local range limited ([`SHARPEN_OVERSHOOT`]). Print +/// media blur more than a screen and get a wider, stronger mask. The values may be on any scale. fn unsharp(w: usize, h: usize, src: &[[f32; 3]], target: SharpenFor, amount: SharpenAmount) -> Option> { - let (radius, base) = match target { + let (sigma, base) = match target { SharpenFor::None => return None, - SharpenFor::Screen => (1usize, 0.35f32), - SharpenFor::Matte => (2, 0.6), - SharpenFor::Glossy => (1, 0.5), + SharpenFor::Screen => (0.7f32, 0.65f32), + SharpenFor::Glossy => (0.8, 0.85), + SharpenFor::Matte => (1.0, 1.05), }; let k = base * match amount { - SharpenAmount::Low => 0.6, + SharpenAmount::Low => 0.5, SharpenAmount::Standard => 1.0, - SharpenAmount::High => 1.5, + SharpenAmount::High => 1.6, }; if w < 3 || h < 3 { return None; } - let r = radius as isize; - let box_pass = |inp: &[[f32; 3]], horizontal: bool| -> Vec<[f32; 3]> { - let mut out = vec![[0.0; 3]; inp.len()]; - // rows in parallel: each output pixel is computed on its own, so the bits don't depend on the split - lightcraft_raster::par_rows(&mut out, w, |y, row| { - for (x, o) in row.iter_mut().enumerate() { - let mut acc = [0.0f32; 3]; - for d in -r..=r { - let (sx, sy) = if horizontal { - ((x as isize + d).clamp(0, w as isize - 1) as usize, y) - } else { - (x, (y as isize + d).clamp(0, h as isize - 1) as usize) - }; - let p = inp[sy * w + sx]; - acc = [acc[0] + p[0], acc[1] + p[1], acc[2] + p[2]]; - } - let n = (2 * r + 1) as f32; - *o = acc.map(|v| v / n); - } - }); - out - }; - let blur = box_pass(&box_pass(src, true), false); - Some(src.iter().zip(&blur).map(|(s, b)| std::array::from_fn(|c| s[c] + (s[c] - b[c]) * k)).collect()) + let luma: Vec = src.iter().map(|p| 0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]).collect(); + let r = (3.0 * sigma).ceil() as isize; + let taps: Vec = (-r..=r).map(|d| (-((d * d) as f32) / (2.0 * sigma * sigma)).exp()).collect(); + let norm: f32 = taps.iter().sum(); + let taps: Vec = taps.iter().map(|t| t / norm).collect(); + let gauss = |acc: f32, d: isize, v: f32| acc + v * taps[(d + r) as usize]; + let blur = separable(&separable(&luma, w, h, r, true, 0.0, gauss), w, h, r, false, 0.0, gauss); + let lo = |acc: f32, _: isize, v: f32| acc.min(v); + let hi = |acc: f32, _: isize, v: f32| acc.max(v); + let lo = separable(&separable(&luma, w, h, 1, true, f32::INFINITY, lo), w, h, 1, false, f32::INFINITY, lo); + let hi = separable(&separable(&luma, w, h, 1, true, f32::NEG_INFINITY, hi), w, h, 1, false, f32::NEG_INFINITY, hi); + Some( + src.iter() + .enumerate() + .map(|(i, p)| { + let (y, margin) = (luma[i], (hi[i] - lo[i]) * SHARPEN_OVERSHOOT); + let sharp = (y + (y - blur[i]) * k).clamp(lo[i] - margin, hi[i] + margin); + p.map(|v| v + sharp - y) + }) + .collect(), + ) +} + +/// One pass of a separable filter over a `w × h` plane: each value folds (`f(acc, offset, value)`, +/// from `init`) its neighbours up to `reach` away along a row (`horizontal`) or a column, edges repeated. +fn separable(inp: &[f32], w: usize, h: usize, reach: isize, horizontal: bool, init: f32, f: impl Fn(f32, isize, f32) -> f32 + Sync) -> Vec { + let mut out = vec![0.0; inp.len()]; + lightcraft_raster::par_rows(&mut out, w, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + *o = (-reach..=reach).fold(init, |acc, d| { + let i = if horizontal { + y * w + (x as isize + d).clamp(0, w as isize - 1) as usize + } else { + (y as isize + d).clamp(0, h as isize - 1) as usize * w + x + }; + f(acc, d, inp[i]) + }); + } + }); + out } /// Encode a rendered display-referred image according to `o` (its pixels must already be in diff --git a/crates/engine/src/export/tests.rs b/crates/engine/src/export/tests.rs index d1d387b26f..0aba0fff57 100644 --- a/crates/engine/src/export/tests.rs +++ b/crates/engine/src/export/tests.rs @@ -245,6 +245,36 @@ const SHARPENED: [u64; 9] = [ 0x139f_6d78_b1f2_a910, ]; +/// Output sharpening (#2970): each step crisper than the one before, Screen / Standard roughly a +/// typical web export's, and no wide light or dark rim along a strong edge (overshoot stays +/// within a tenth of the edge's contrast). Colour is left alone: a grey edge stays grey. +#[test] +fn sharpen_steps_are_crisper_without_halos() { + let edge = || { + let mut img = Rgba8::new(32, 8); + for (i, p) in img.data.iter_mut().enumerate() { + let v = if i % 32 < 16 { 40 } else { 220 }; + *p = [v, v, v, 255]; + } + img + }; + let mut last = 0u8; + for amount in [SharpenAmount::Low, SharpenAmount::Standard, SharpenAmount::High] { + let mut img = edge(); + output_sharpen(&mut img, SharpenFor::Screen, amount); + let (dark, light) = (img.data[15], img.data[16]); + let spread = (40 - dark[0]).max(light[0] - 220); + assert!(spread >= last && spread > 0, "{amount:?}: {dark:?} {light:?}"); + assert!(dark[0] >= 40 - 18 && light[0] <= 220 + 18, "{amount:?}: {dark:?} {light:?}"); + assert!(dark[0] == dark[1] && dark[1] == dark[2] && light[0] == light[2], "grey stays grey"); + assert_eq!(img.data[0][0], 40, "{amount:?}: flat areas untouched"); + last = spread; + } + let mut none = edge(); + output_sharpen(&mut none, SharpenFor::None, SharpenAmount::High); + assert_eq!(none.data, edge().data); +} + /// Exported files carry keywords as Lightroom Classic writes them: names flat in `dc:subject` /// (with the keywords containing them), full paths in `lr:hierarchicalSubject`, and nothing of /// a keyword left out of export. They used to carry the `a|b` paths in `dc:subject`. diff --git a/crates/engine/src/media/session.rs b/crates/engine/src/media/session.rs index a3d5069177..f273cad738 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -586,7 +586,10 @@ impl crate::Session { } job.request.space = space; job.request.depth = depth; - job.key ^= (space as u64 + 1).wrapping_mul(0xa076_1d64_78bd_642f) ^ (depth as u64 + 1).wrapping_mul(0xe703_7ed1_a0b4_28db); + // an export shrinks with a sharp filter: a preview's soft one leaves a small export blurred (#2970) + job.request.downscale = lightcraft_pipeline::Downscale::Sharp; + job.key ^= + (space as u64 + 1).wrapping_mul(0xa076_1d64_78bd_642f) ^ (depth as u64 + 1).wrapping_mul(0xe703_7ed1_a0b4_28db) ^ 0x9e37_79b9_7f4a_7c15; Ok(job) } diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 2b20866e64..657173db91 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -567,7 +567,7 @@ fn sample(cx: &mut Cx<'_>, src: &Arc, src_buf: Arc, plan: &Plan<'_> Arc::new(out) }; let (base, (bw, bh)) = match sp.prefilter { - Some(d) => (Arc::new(resize(cx, &oriented, (sp.ow, sp.oh), d, 3, Filter::Mitchell)), d), + Some(d) => (Arc::new(resize(cx, &oriented, (sp.ow, sp.oh), d, 3, fr.downscale)), d), None => (oriented, (sp.ow, sp.oh)), }; let mut affine = |xf: &lightcraft_geom::Affine| { diff --git a/crates/pipeline/src/geometry.rs b/crates/pipeline/src/geometry.rs index 5d8a07489a..f9e8601006 100644 --- a/crates/pipeline/src/geometry.rs +++ b/crates/pipeline/src/geometry.rs @@ -37,6 +37,9 @@ pub struct Frame { /// `lightcraft_develop::Mask::on_photo`); otherwise they are normalized coordinates of this /// frame's transformed image, like spots and the crop. pub masks_on_photo: bool, + /// Filter of the area downscale ahead of the bilinear resample ([`Frame::sample`]); see + /// [`crate::Downscale`]. + pub downscale: Filter, } /// Where a windowed [`Frame`]'s pixels sit in the full output: its offset and the full output's @@ -82,6 +85,7 @@ impl Frame { warp: (!warp.is_identity()).then_some(warp), view: None, masks_on_photo: false, + downscale: Filter::Mitchell, }; if apply_crop { f.constrain_to_image(s.geometry.constrain_crop); @@ -333,7 +337,7 @@ impl Frame { let o = oriented.as_ref().unwrap_or(src); let plan = self.sample_plan(src.width, src.height, w, h); let base = match plan.prefilter { - Some((nw, nh)) => std::borrow::Cow::Owned(resize(o, nw, nh, Filter::Mitchell)), + Some((nw, nh)) => std::borrow::Cow::Owned(resize(o, nw, nh, self.downscale)), None => std::borrow::Cow::Borrowed(o), }; self.sample_base(base, plan, w, h) @@ -355,7 +359,7 @@ impl Frame { let mut bases: Vec<((usize, usize), Rgb32f)> = Vec::new(); for dims in plans.iter().filter_map(|p| p.1.prefilter) { if !bases.iter().any(|b| b.0 == dims) { - bases.push((dims, resize(o, dims.0, dims.1, Filter::Mitchell))); + bases.push((dims, resize(o, dims.0, dims.1, self.downscale))); } } plans @@ -443,7 +447,7 @@ pub struct SamplePlan { /// Oriented source size. pub ow: usize, pub oh: usize, - /// Size of the Mitchell prefilter (area downscale before the bilinear resample), if any. + /// Size of the prefilter ([`Frame::downscale`]: area downscale before the bilinear resample), if any. pub prefilter: Option<(usize, usize)>, /// Oriented-source px → prefiltered px. pub sx: f64, diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index d8835f4ef1..38d7473936 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -128,6 +128,26 @@ impl Default for SourceInfo { } } +/// How a render shrinks its source to the output size. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum Downscale { + /// Mitchell–Netravali: soft, no visible ringing. Previews and thumbnails. + #[default] + Smooth, + /// Lanczos-3: keeps the detail a smaller output can hold, as a dedicated downscale does + /// (exports, #2970). Its slight overshoot at hard edges stays below the output sharpening's. + Sharp, +} + +impl Downscale { + pub fn filter(self) -> lightcraft_raster::resample::Filter { + match self { + Downscale::Smooth => lightcraft_raster::resample::Filter::Mitchell, + Downscale::Sharp => lightcraft_raster::resample::Filter::Lanczos3, + } + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] pub enum Quality { /// Interactive drags: skips the most expensive refinements. @@ -161,6 +181,8 @@ pub struct RenderRequest { /// Previews for a monitor with a display profile: render 8-bit into its primaries instead of /// `space` (see [`DisplaySpace`]; ignored by deep renders). pub display: Option, + /// Filter of the downscale to the output size. + pub downscale: Downscale, } /// A window of the (virtual) full output, in its pixels: what a zoomed view needs, rendered @@ -214,6 +236,7 @@ impl RenderRequest { proof: None, window: None, display: None, + downscale: Downscale::Smooth, } } @@ -467,7 +490,8 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R } } let s = &*settings; - let frame = frame_for(src, info, s, req.apply_crop); + let mut frame = frame_for(src, info, s, req.apply_crop); + frame.downscale = req.downscale.filter(); let (full_w, full_h) = req.size(&frame); // sizes and scale are those of the whole output; a window only narrows what is drawn let px_per_long = frame.px_per_long(full_w); diff --git a/crates/pipeline/src/tests.rs b/crates/pipeline/src/tests.rs index f1229bd569..1a035def8a 100644 --- a/crates/pipeline/src/tests.rs +++ b/crates/pipeline/src/tests.rs @@ -107,6 +107,27 @@ fn dehaze_does_not_crush_dark_regions_next_to_bright_ones() { } } +/// An export's sharp downscale (#2970) keeps more of the fine detail a smaller output can hold +/// than a preview's smooth one, and changes nothing when the output is the source's own size. +#[test] +fn sharp_downscale_keeps_detail() { + use crate::Downscale; + // fine stripes: a period of 5 source pixels, 3 output pixels at 600 → 360 + let src = Rgb32f::from_fn(600, 400, |x, _| [0.18 * (1.0 + 0.8 * (x as f32 * std::f32::consts::TAU / 5.0).sin()); 3]); + let swing = |down: Downscale, edge: usize| { + let r = + render(&src, &SourceInfo::default(), &DevelopSettings::default(), &RenderRequest { downscale: down, ..RenderRequest::fit(edge, edge) }); + let row: Vec = (40..r.image.width - 40).map(|x| r.image.data[(r.image.height / 2) * r.image.width + x][1] as f32).collect(); + let m = row.iter().sum::() / row.len() as f32; + (row.iter().map(|v| (v - m).abs()).sum::() / row.len() as f32, r.image) + }; + let ((smooth, _), (sharp, _)) = (swing(Downscale::Smooth, 360), swing(Downscale::Sharp, 360)); + assert!(sharp > smooth * 1.25, "sharp {sharp} vs smooth {smooth}"); + let ((_, a), (_, b)) = (swing(Downscale::Smooth, 600), swing(Downscale::Sharp, 600)); + assert_eq!((b.width, b.height), (600, 400)); + assert_eq!(a.data, b.data, "no resize, no difference"); +} + #[test] fn resolution_independence_of_local_contrast() { // Clarity at two preview sizes should give similar results after downscaling. From 6e9040406f0b2f8bc772e6f0a1fd0d360ed64695 Mon Sep 17 00:00:00 2001 From: radialmonster Date: Sun, 25 Oct 2026 18:02:19 -0400 Subject: [PATCH 11/19] Export sharpening: tolerate NaN and infinite float samples A non-finite F32 sample gave the luma unsharp mask inverted or NaN local bounds, and f32::clamp panics on those. Float samples that are not finite are now sharpened as black, and the overshoot limit uses max/min, which never panics. Regression test with a 3x3 image holding NaN and inf. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014ti8KemZbjE2ZgHgV1q1BM --- crates/engine/src/export/encoding.rs | 6 ++++-- crates/engine/src/export/tests.rs | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/export/encoding.rs b/crates/engine/src/export/encoding.rs index 6b182e4f12..9ce5aa7252 100644 --- a/crates/engine/src/export/encoding.rs +++ b/crates/engine/src/export/encoding.rs @@ -37,7 +37,8 @@ pub fn output_sharpen_deep(img: &mut DeepImage, target: SharpenFor, amount: Shar } } DeepSamples::F32(v) => { - let src: Vec<[f32; 3]> = v.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect(); + // A NaN or infinite sample would poison its neighbours' blur and local range; treat it as black. + let src: Vec<[f32; 3]> = v.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]].map(|x| if x.is_finite() { x } else { 0.0 })).collect(); if let Some(out) = unsharp(w, h, &src, target, amount) { for (d, s) in v.iter_mut().zip(out.as_flattened()) { *d = s.max(0.0); @@ -93,7 +94,8 @@ fn unsharp(w: usize, h: usize, src: &[[f32; 3]], target: SharpenFor, amount: Sha .enumerate() .map(|(i, p)| { let (y, margin) = (luma[i], (hi[i] - lo[i]) * SHARPEN_OVERSHOOT); - let sharp = (y + (y - blur[i]) * k).clamp(lo[i] - margin, hi[i] + margin); + // max/min rather than clamp: never panics, even on bounds a non-finite input left inverted or NaN. + let sharp = (y + (y - blur[i]) * k).max(lo[i] - margin).min(hi[i] + margin); p.map(|v| v + sharp - y) }) .collect(), diff --git a/crates/engine/src/export/tests.rs b/crates/engine/src/export/tests.rs index 0aba0fff57..c8df165499 100644 --- a/crates/engine/src/export/tests.rs +++ b/crates/engine/src/export/tests.rs @@ -275,6 +275,25 @@ fn sharpen_steps_are_crisper_without_halos() { assert_eq!(none.data, edge().data); } +/// Output sharpening of a float image with NaN and infinite samples does not panic (#2970 review): +/// they are sharpened as black and every result is finite. +#[test] +fn sharpen_deep_survives_non_finite_samples() { + let (nan, inf) = (f32::NAN, f32::INFINITY); + let mut samples = vec![0.5f32; 27]; + samples[..9].copy_from_slice(&[nan, nan, nan, inf, inf, inf, -inf, nan, inf]); + samples[12] = nan; + samples[20] = inf; + for target in [SharpenFor::Screen, SharpenFor::Glossy, SharpenFor::Matte] { + let mut img = DeepImage { width: 3, height: 3, space: OutputSpace::Srgb, samples: DeepSamples::F32(samples.clone()) }; + output_sharpen_deep(&mut img, target, SharpenAmount::High); + let DeepSamples::F32(out) = &img.samples else { unreachable!() }; + assert!(out.iter().all(|v| v.is_finite() && *v >= 0.0), "{target:?}: {out:?}"); + } + let mut all_nan = DeepImage { width: 3, height: 3, space: OutputSpace::Srgb, samples: DeepSamples::F32(vec![nan; 27]) }; + output_sharpen_deep(&mut all_nan, SharpenFor::Screen, SharpenAmount::Standard); +} + /// Exported files carry keywords as Lightroom Classic writes them: names flat in `dc:subject` /// (with the keywords containing them), full paths in `lr:hierarchicalSubject`, and nothing of /// a keyword left out of export. They used to carry the `a|b` paths in `dc:subject`. From aa98d48fa5703c0dafeb5434cfc98a52920e6a85 Mon Sep 17 00:00:00 2001 From: radialmonster Date: Wed, 28 Oct 2026 14:09:02 -0400 Subject: [PATCH 12/19] Export tests: pin the new output sharpening's pixels Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014ti8KemZbjE2ZgHgV1q1BM --- crates/engine/src/export/encoding.rs | 2 +- crates/engine/src/export/tests.rs | 20 ++++++++++---------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/export/encoding.rs b/crates/engine/src/export/encoding.rs index 9ce5aa7252..ccceb57286 100644 --- a/crates/engine/src/export/encoding.rs +++ b/crates/engine/src/export/encoding.rs @@ -53,7 +53,7 @@ fn sharpens(w: usize, h: usize, target: SharpenFor) -> bool { target != SharpenFor::None && w >= 3 && h >= 3 } -// How far a sharpened pixel may pass the darkest and lightest of its 3×3 neighbours, as a share +/// How far a sharpened pixel may pass the darkest and lightest of its 3×3 neighbours, as a share /// of their difference: enough for crisp edges, too little for the light and dark rims (halos) /// a plain unsharp mask draws along strong edges. const SHARPEN_OVERSHOOT: f32 = 0.1; diff --git a/crates/engine/src/export/tests.rs b/crates/engine/src/export/tests.rs index c8df165499..c480e554eb 100644 --- a/crates/engine/src/export/tests.rs +++ b/crates/engine/src/export/tests.rs @@ -209,7 +209,7 @@ fn sharpen_increases_edge_contrast() { assert!(img.data[3][0] < 80 && img.data[4][0] > 170); } -/// Output sharpening's pixels for every target and amount, pinned (its box blurs run row-parallel, which must not +/// Output sharpening's pixels for every target and amount, pinned (its separable passes run row-parallel, which must not /// change a bit), on 8- and 16-bit images; with no target the image is left as it is. #[test] fn sharpened_pixels_are_pinned() { @@ -234,15 +234,15 @@ fn sharpened_pixels_are_pinned() { assert_eq!(img, test_image()); } const SHARPENED: [u64; 9] = [ - 0x1494_273e_0bdc_a61c, - 0x3fbb_40c4_74f4_b0c3, - 0xa27f_8ff5_82a0_99f9, - 0x6550_6571_a38d_4d9f, - 0x5e28_f4f3_fc8a_9685, - 0xdc2b_6f65_9138_3b1d, - 0x8ce6_f0b8_d8ed_8026, - 0x92d8_12e7_4b2e_81fe, - 0x139f_6d78_b1f2_a910, + 0x1a04_82d5_edaa_37c8, + 0xcb78_18b7_938e_beda, + 0x0490_bb9e_2b64_3d00, + 0x1662_0293_b8a2_2538, + 0xa3f7_7957_1af3_1b39, + 0x30b0_919c_7c6a_705b, + 0x27ef_4e5b_42e6_d1ed, + 0x1dc3_3b96_b2f9_c1b6, + 0xdab7_1280_a47a_ffeb, ]; /// Output sharpening (#2970): each step crisper than the one before, Screen / Standard roughly a From f8e6222f45217fb0c999d9241a0c20ce348e0782 Mon Sep 17 00:00:00 2001 From: radialmonster Date: Sun, 1 Nov 2026 03:38:33 -0500 Subject: [PATCH 13/19] 2988: verify and cover sharp prefiltering for mild export downscales Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fnx9MvcZS4u9LfRDQ2ABZe --- crates/pipeline/src/geometry.rs | 22 ++++++++++- crates/pipeline/tests/sharp_downscale.rs | 23 ++++++++++++ docs/sharp-downscale-measurements.md | 48 ++++++++++++++++++++++++ 3 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 crates/pipeline/tests/sharp_downscale.rs create mode 100644 docs/sharp-downscale-measurements.md diff --git a/crates/pipeline/src/geometry.rs b/crates/pipeline/src/geometry.rs index f9e8601006..cc2b11ca72 100644 --- a/crates/pipeline/src/geometry.rs +++ b/crates/pipeline/src/geometry.rs @@ -317,7 +317,9 @@ impl Frame { let (ow, oh) = if self.orient.swaps_axes() { (src_h, src_w) } else { (src_w, src_h) }; let crop_px = self.crop.rect_px(self.ow, self.oh); let k = crop_px.width() / w as f64; - let prefilter = (k > 1.25).then(|| (((ow as f64 / k).round() as usize).max(1), ((oh as f64 / k).round() as usize).max(1))); + // Sharp exports use their selected filter for every downscale; keep smooth previews' threshold. + let threshold = if self.downscale == Filter::Lanczos3 { 1.0 } else { 1.25 }; + let prefilter = (k > threshold).then(|| (((ow as f64 / k).round() as usize).max(1), ((oh as f64 / k).round() as usize).max(1))); let (bw, bh) = prefilter.unwrap_or((ow, oh)); let (sx, sy) = (bw as f64 / ow as f64, bh as f64 / oh as f64); let mode = if self.warp.is_some() { @@ -533,6 +535,24 @@ mod tests { assert!((f.px_per_long(300) - 300.0).abs() < 1e-9); } + #[test] + fn sharp_downscale_filters_mild_reductions_and_native_size_stays_identical() { + let src = Rgb32f::from_fn(100, 100, |x, y| [((x + y) % 2) as f32; 3]); + for filter in [Filter::Mitchell, Filter::Lanczos3] { + let mut f = Frame::new(100, 100, &DevelopSettings::default(), true); + f.downscale = filter; + let edge = if filter == Filter::Lanczos3 { 90 } else { 70 }; + assert_eq!(f.sample_plan(100, 100, edge, edge).prefilter, Some((edge, edge))); + assert_eq!(f.sample(&src, edge, edge).data, resize(&src, edge, edge, filter).data); + if filter == Filter::Mitchell { + assert_eq!(f.sample_plan(100, 100, 90, 90).prefilter, None); + } + assert_eq!(f.sample_plan(100, 100, 100, 100).prefilter, None); + assert_eq!(f.sample(&src, 100, 100).data, src.data); + assert_eq!(f.sample_plan(100, 100, 110, 110).prefilter, None); + } + } + #[test] fn rotation_swaps_aspect() { let s = DevelopSettings { orientation: Orientation::Rotate90, ..Default::default() }; diff --git a/crates/pipeline/tests/sharp_downscale.rs b/crates/pipeline/tests/sharp_downscale.rs new file mode 100644 index 0000000000..8d81593c69 --- /dev/null +++ b/crates/pipeline/tests/sharp_downscale.rs @@ -0,0 +1,23 @@ +//! A pure above-Nyquist carrier must be suppressed rather than folded into a smaller export. +use lightcraft_develop::DevelopSettings; +use lightcraft_pipeline::geometry::Frame; +use lightcraft_raster::{Rgb32f, resample::Filter}; + +#[test] +fn mild_sharp_reductions_suppress_above_target_nyquist_aliases() { + // 0.49 cycles/source pixel is above the 90% and 80% outputs' Nyquist limits. + let source = Rgb32f::from_fn(1000, 100, |x, _| [0.5 + 0.25 * (std::f32::consts::TAU * 0.49 * x as f32).sin(); 3]); + let power = |image: &Rgb32f| { + let values: Vec = (12..image.width - 12).map(|x| f64::from(image.get(x, image.height / 2)[0])).collect(); + let mean = values.iter().sum::() / values.len() as f64; + values.iter().map(|v| (v - mean).powi(2)).sum::() / values.len() as f64 + }; + let mut frame = Frame::new(1000, 100, &DevelopSettings::default(), true); + frame.downscale = Filter::Lanczos3; + for (w, h) in [(900, 90), (800, 80)] { + let k = 1000.0 / w as f64; + let unfiltered = Rgb32f::from_fn(w, h, |x, y| source.sample_bilinear(((x as f64 + 0.5) * k) as f32, ((y as f64 + 0.5) * k) as f32)); + let (sharp, bilinear) = (power(&frame.sample(&source, w, h)), power(&unfiltered)); + assert!(sharp < bilinear * 0.95, "{w}: residual alias power {sharp} vs unfiltered {bilinear}"); + } +} diff --git a/docs/sharp-downscale-measurements.md b/docs/sharp-downscale-measurements.md new file mode 100644 index 0000000000..bbcb008f2a --- /dev/null +++ b/docs/sharp-downscale-measurements.md @@ -0,0 +1,48 @@ +# Sharp downscale threshold measurement + +Compare the Sharp export resizer with prefilter thresholds k > 1.0 and k > 1.25, where k is source width / output width. Smooth previews retain their existing threshold. These numbers measure the resize operation; they do not establish perceptual quality, halo visibility, or behavior under every geometric warp. + +Six existing CC0-1.0 RAW corpus records were verified against their manifest SHA-256 before decoding through the engine. The native sensor decode was required (not the embedded JPEG). Numeric linear Rec.2020 luminance uses weights 0.2627, 0.6780, 0.0593. + +## Method + +- Five fixed 500 x 500 source tiles per file, at 20%/80% corners and center of the available tile-origin range. No content-based tile selection. +- Export scales 0.9, 0.8, 0.7; actual Frame::sample with Lanczos3. The old path at k <= 1.25 is reproduced with its bilinear mapping; at 0.7 both thresholds use the same Lanczos path, providing an unchanged control. +- Alias proxy: mirror-pad each source tile by 250 pixels; FFT-isolate frequencies outside the target Nyquist square (either axis greater than scale/2 cycles/source pixel), inverse transform, crop to the original tile, then resize that signed high-band component through each path. Measure mean-square output energy, excluding 12 output pixels on each border. This measures folded energy from the removed source band rather than calling all output high frequencies aliases. +- Edge acutance proxy: mean of the strongest 5% Sobel gradient magnitudes in the resized ordinary tile, divided by its 95th-minus-5th-percentile luminance contrast; same border exclusion. Average five tiles per file. Percent changes compare threshold 1.0 against 1.25. + +## Results across six files + +- Scale 0.9: alias energy -25.48% (range -26.39% to -20.30%); edge acutance +4.62% (range +3.15% to +8.37%). +- Scale 0.8: alias energy -65.59% (range -66.07% to -62.74%); edge acutance +3.59% (range +2.39% to +6.03%). +- Scale 0.7: alias energy +0.00% (range +0.00% to +0.00%); edge acutance +0.00% (range +0.00% to +0.00%). + +## Per-file changes + +- Canon EOS 7D, 0.9: alias energy -25.70%; edge acutance +8.37%. +- Canon EOS 7D, 0.8: alias energy -64.35%; edge acutance +6.03%. +- Canon EOS 7D, 0.7: alias energy +0.00%; edge acutance +0.00%. +- Sony ILCE-7M3, 0.9: alias energy -24.27%; edge acutance +6.70%. +- Sony ILCE-7M3, 0.8: alias energy -62.74%; edge acutance +5.93%. +- Sony ILCE-7M3, 0.7: alias energy +0.00%; edge acutance +0.00%. +- Nikon D7000, 0.9: alias energy -26.02%; edge acutance +3.63%. +- Nikon D7000, 0.8: alias energy -65.91%; edge acutance +3.17%. +- Nikon D7000, 0.7: alias energy +0.00%; edge acutance +0.00%. +- Panasonic DMC-GF6, 0.9: alias energy -25.25%; edge acutance +4.42%. +- Panasonic DMC-GF6, 0.8: alias energy -65.70%; edge acutance +3.94%. +- Panasonic DMC-GF6, 0.7: alias energy +0.00%; edge acutance +0.00%. +- Pentax K-5, 0.9: alias energy -26.39%; edge acutance +3.15%. +- Pentax K-5, 0.8: alias energy -66.07%; edge acutance +2.39%. +- Pentax K-5, 0.7: alias energy +0.00%; edge acutance +0.00%. +- Fujifilm X-T3, 0.9: alias energy -20.30%; edge acutance +4.83%. +- Fujifilm X-T3, 0.8: alias energy -65.48%; edge acutance +3.23%. +- Fujifilm X-T3, 0.7: alias energy +0.00%; edge acutance +0.00%. + +## Source records + +- [Canon EOS 7D, record 131](https://raw.pixls.us/getfile.php/131/nice/Canon%20-%20EOS%207D%20-%20RAW%20%283:2%29.CR2), CC0-1.0; SHA-256 `b5e47c5fcf7332ac03e0134926f17a338a42e68c1fd7f83e16f45f4b767544e8`. +- [Sony ILCE-7M3, record 2414](https://raw.pixls.us/getfile.php/2414/nice/Sony%20-%20ILCE-7M3%20-%2014bit%2014bit%20compressed%20%283:2%29.ARW), CC0-1.0; SHA-256 `250784580ea527442c09004417bb0eead484f2bf3ee8f9121a776ac65bb50d0f`. +- [Nikon D7000, record 958](https://raw.pixls.us/getfile.php/958/nice/Nikon%20-%20D7000%20-%2014bit%2014bit%20compressed%20%28Lossless%29%20%283:2%29.NEF), CC0-1.0; SHA-256 `639945753240005d80488c0462c01e73a7ab82c96d3d1cdb6661f02e1b3c1319`. +- [Panasonic DMC-GF6, record 739](https://raw.pixls.us/getfile.php/739/nice/Panasonic%20-%20DMC-GF6%20-%204:3.RW2), CC0-1.0; SHA-256 `dace6b3818f00a5d4f7cc1cfc29744d15dcf7dd8684c882bea4a81c6ef670ad0`. +- [Pentax K-5, record 1479](https://raw.pixls.us/getfile.php/1479/nice/Pentax%20-%20K-5%20-%2014bit%20%283:2%29.DNG), CC0-1.0; SHA-256 `6f6419209340d07d597ccca66dc367d64cff3308ef2694c8f90c6259f3a5c431`. +- [Fujifilm X-T3, record 2783](https://raw.pixls.us/getfile.php/2783/nice/Fujifilm%20-%20X-T3%20-%2014bit%2014bit%20compressed%20%283:2%29.RAF), CC0-1.0; SHA-256 `95b33021160b239ceb1a09d46a1b29cb60cb7dd47581feb126b337c219091754`. From cd275006e5de305fbb89bbfea50d737e2a72347a Mon Sep 17 00:00:00 2001 From: radialmonster Date: Sat, 7 Nov 2026 03:03:14 -0500 Subject: [PATCH 14/19] 2988: prefilter scale from both axes Frame::sample_plan took the prefilter scale k from the width alone, so a reduction on the height only (a 100x1000 source to 100x900) had k = 1, skipped the prefilter and bilinear-minified the height, which aliases. k is now the larger of the two axes' reductions. The prefilter shrinks the source isotropically by k, and the bilinear pass after it then reduces each axis by k_axis / k. With the larger k that ratio is at most 1 on both axes, so the bilinear pass never minifies; the smaller k would leave the more-reduced axis minified by bilinear and aliasing. The cost of the larger k is a slight bilinear upsample on the less-reduced axis, which only differs from 1 when the crop and output aspects differ (by rounding, or a stretched size). Fits with matching aspects keep the same prefilter size as before. A test covers a height-only Lanczos-3 reduction: it now prefilters and suppresses a vertical carrier above the output's Nyquist limit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fnx9Mvap24RDADn7A3Wnwq --- crates/pipeline/src/geometry.rs | 4 +++- crates/pipeline/tests/sharp_downscale.rs | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/pipeline/src/geometry.rs b/crates/pipeline/src/geometry.rs index cc2b11ca72..32516eaae2 100644 --- a/crates/pipeline/src/geometry.rs +++ b/crates/pipeline/src/geometry.rs @@ -316,7 +316,9 @@ impl Frame { pub fn sample_plan(&self, src_w: usize, src_h: usize, w: usize, h: usize) -> SamplePlan { let (ow, oh) = if self.orient.swaps_axes() { (src_h, src_w) } else { (src_w, src_h) }; let crop_px = self.crop.rect_px(self.ow, self.oh); - let k = crop_px.width() / w as f64; + // the larger of the two axes' reductions: the prefilter then takes every axis at least as small + // as its output needs, so the bilinear pass after it never minifies (and aliases) either one + let k = (crop_px.width() / w as f64).max(crop_px.height() / h as f64); // Sharp exports use their selected filter for every downscale; keep smooth previews' threshold. let threshold = if self.downscale == Filter::Lanczos3 { 1.0 } else { 1.25 }; let prefilter = (k > threshold).then(|| (((ow as f64 / k).round() as usize).max(1), ((oh as f64 / k).round() as usize).max(1))); diff --git a/crates/pipeline/tests/sharp_downscale.rs b/crates/pipeline/tests/sharp_downscale.rs index 8d81593c69..da4fb57e09 100644 --- a/crates/pipeline/tests/sharp_downscale.rs +++ b/crates/pipeline/tests/sharp_downscale.rs @@ -21,3 +21,22 @@ fn mild_sharp_reductions_suppress_above_target_nyquist_aliases() { assert!(sharp < bilinear * 0.95, "{w}: residual alias power {sharp} vs unfiltered {bilinear}"); } } + +#[test] +fn a_height_only_reduction_is_prefiltered_too() { + // the width stays 1:1, the height shrinks 1000 → 900: the vertical carrier must not fold in + let source = Rgb32f::from_fn(100, 1000, |_, y| [0.5 + 0.25 * (std::f32::consts::TAU * 0.49 * y as f32).sin(); 3]); + let power = |image: &Rgb32f| { + let values: Vec = (12..image.height - 12).map(|y| f64::from(image.get(image.width / 2, y)[0])).collect(); + let mean = values.iter().sum::() / values.len() as f64; + values.iter().map(|v| (v - mean).powi(2)).sum::() / values.len() as f64 + }; + let mut frame = Frame::new(100, 1000, &DevelopSettings::default(), true); + frame.downscale = Filter::Lanczos3; + let (w, h) = (100, 900); + assert!(frame.sample_plan(100, 1000, w, h).prefilter.is_some(), "a reduction on either axis is prefiltered"); + let k = 1000.0 / h as f64; + let unfiltered = Rgb32f::from_fn(w, h, |x, y| source.sample_bilinear(x as f32 + 0.5, ((y as f64 + 0.5) * k) as f32)); + let (sharp, bilinear) = (power(&frame.sample(&source, w, h)), power(&unfiltered)); + assert!(sharp < bilinear * 0.95, "residual alias power {sharp} vs unfiltered {bilinear}"); +} From 36511c799a0d9b434b6255731af058b1fb608c23 Mon Sep 17 00:00:00 2001 From: radialmonster Date: Sat, 7 Nov 2026 05:39:16 -0500 Subject: [PATCH 15/19] 2988: panic, not unreachable, in the non-finite sharpen test The engine crate denies clippy::unreachable, and clippy.toml allows panics only in tests; the same file already writes `else { panic!("expected U16 samples") }`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fnx9Mvap24RDADn7A3Wnwq --- crates/engine/src/export/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/export/tests.rs b/crates/engine/src/export/tests.rs index c480e554eb..88d943cc9f 100644 --- a/crates/engine/src/export/tests.rs +++ b/crates/engine/src/export/tests.rs @@ -287,7 +287,7 @@ fn sharpen_deep_survives_non_finite_samples() { for target in [SharpenFor::Screen, SharpenFor::Glossy, SharpenFor::Matte] { let mut img = DeepImage { width: 3, height: 3, space: OutputSpace::Srgb, samples: DeepSamples::F32(samples.clone()) }; output_sharpen_deep(&mut img, target, SharpenAmount::High); - let DeepSamples::F32(out) = &img.samples else { unreachable!() }; + let DeepSamples::F32(out) = &img.samples else { panic!("expected F32 samples") }; assert!(out.iter().all(|v| v.is_finite() && *v >= 0.0), "{target:?}: {out:?}"); } let mut all_nan = DeepImage { width: 3, height: 3, space: OutputSpace::Srgb, samples: DeepSamples::F32(vec![nan; 27]) }; From b2929857804be4db3ba55cb5370ab31ff36af04f Mon Sep 17 00:00:00 2001 From: radialmonster Date: Sun, 15 Nov 2026 00:11:54 -0500 Subject: [PATCH 16/19] Presets: Amount blends curves and fades in a changed choice's strength (#2669) Ported onto main's #2207 composition (`compose_named`, `interpolate_object` / `interpolate_leaf`), whose step at half amount for switches, choices, integers and nulls stays. The continuous rules of this PR now live there: - point curves blend as curves (both evaluated monotone cubic at every control point of either), towards the original's curve; - when a preset changes a choice (a string such as the profile or LUT id, or an object's `enabled` switch), that object's `amount` fades in from 0 from half amount up, where the preset's choice applies; below half amount the original's choice keeps its own amount; - white balance on another scale (Kelvin against relative) is never blended: numbers and scale come together from the original below half amount and from the preset from half amount up; - HDR, left out of the JSON at its defaults, is written into the base so its numbers blend too. The base is the original (import) state, as `compose_named` has it, so the test numbers are measured from it. `apply_partial` uses the same rules on its own base, and `scale_patch` (its separate copy of the old rules) is gone. At 0 % a preset's masks are not added, and a NaN amount changes nothing. Replaces f36107636 and 6ef42980f of the PR (rebased onto 6b2b7e6d1). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fnx9MvXCjGmV3UZ1Xs54DG --- crates/develop/src/presets.rs | 417 ++++++++++++++++++++++++++++++---- docs/parity-checklist.md | 3 +- 2 files changed, 374 insertions(+), 46 deletions(-) diff --git a/crates/develop/src/presets.rs b/crates/develop/src/presets.rs index 0ea3d12f8c..42f92df005 100644 --- a/crates/develop/src/presets.rs +++ b/crates/develop/src/presets.rs @@ -5,8 +5,12 @@ //! computed from the photo's *original* state (its import settings, when known) and the preset's //! value, and replaces the photo's value; every other setting keeps the photo's value (issue //! #2159). `amount` (0..200 %) moves each named number between the original and the preset's -//! value. Copy/paste/sync use the same group selection ([`SettingsGroup`]) and merge into the -//! current settings as before. +//! value; a point curve (a tone curve) moves between the two curves as rendered. Switches and choices +//! (a profile or LUT id, a style, a flag) take the original's value below half amount and the +//! preset's from half amount up, and the strength of a choice the preset changes fades in from 0 +//! there; white balance on another scale is taken whole (see [`interpolate_object`]). +//! Copy/paste/sync use the same group selection ([`SettingsGroup`]) and merge into the current +//! settings as before. //! //! The rendering process ([`crate::ProcessVersion`]) is in no group: copy, paste, sync and presets //! made from a photo never carry it, so the photos they change keep their own. A partial that names @@ -159,42 +163,34 @@ pub fn deep_merge(base: &mut Value, patch: &Value) { } } -/// Interpolate numbers in `patch` towards/away from `base` by `t` (1 = patch as-is); non-numeric -/// values are taken from the patch when `t >= 0.5`. -fn scale_patch(base: &Value, patch: &Value, t: f64) -> Value { - match (base, patch) { - (Value::Object(b), Value::Object(p)) => { - let mut out = Map::new(); - for (k, pv) in p { - let bv = b.get(k).unwrap_or(&Value::Null); - out.insert(k.clone(), scale_patch(bv, pv, t)); - } - Value::Object(out) - } - // Integer fields (the grain seed, ids) are discrete like strings: an interpolated seed would - // not deserialize as an integer, and the whole preset would silently not apply. - (Value::Number(b), Value::Number(p)) if b.is_f64() || p.is_f64() => { - let (b, p) = (b.as_f64().unwrap_or(0.0), p.as_f64().unwrap_or(0.0)); - serde_json::Number::from_f64(b + (p - b) * t).map(Value::Number).unwrap_or(Value::Null) - } - (b, p) => { - if t >= 0.5 { - p.clone() - } else { - b.clone() - } - } - } -} - -/// Apply a partial settings object with an amount (1.0 = 100 %). Out-of-range values are clamped -/// through the control specs, as every merge does ([`DevelopSettings::merged`]). +/// Apply a partial settings object with an amount (1.0 = 100 %): each setting it names is blended +/// from `s`'s value by the same rules as a preset ([`interpolate_object`]). Out-of-range values are +/// clamped through the control specs, as every merge does ([`DevelopSettings::merged`]). At 0 % +/// (or less) nothing changes; at 100 % the partial is merged as it is. pub fn apply_partial(s: &DevelopSettings, partial: &Value, amount: f64) -> DevelopSettings { - let patch = if (amount - 1.0).abs() < 1e-9 { Cow::Borrowed(partial) } else { Cow::Owned(scale_patch(&s.to_json_for_merge(), partial, amount)) }; + if amount.is_nan() || amount <= 0.0 { + return s.clone(); + } + let patch = if (amount - 1.0).abs() < 1e-9 { + Cow::Borrowed(partial) + } else { + let base = blend_base(s); + Cow::Owned(Value::Object(partial.as_object().map(|p| interpolate_object(base.as_object(), p, amount)).unwrap_or_default())) + }; // (a white balance without a scale keeps its old meaning: `DevelopSettings::merged`) s.merged(&patch).unwrap_or_else(|_| s.clone()) } +/// `s` as the base an amount blends from: every group written out, also the ones serialization +/// leaves out while at their defaults (HDR), so their numbers blend from `s`'s values too. +fn blend_base(s: &DevelopSettings) -> Value { + let mut v = s.to_json_for_merge(); + if let (Some(o), Ok(hdr)) = (v.as_object_mut(), serde_json::to_value(s.hdr)) { + o.entry("hdr").or_insert(hdr); + } + v +} + /// Top-level settings keys that hold per-photo pixel repairs: a preset's named repairs compose on /// the photo's own values instead of the original's (masks are added by [`Preset::apply_on`]), and /// a preset without them leaves the photo's alone. @@ -212,7 +208,7 @@ fn compose_named(current: &DevelopSettings, original: &DevelopSettings, settings return current.merged(settings).unwrap_or_else(|_| current.clone()); } let cur = current.to_json(); - let mut base = original.to_json(); + let mut base = blend_base(original); if let (Some(b), Some(c)) = (base.as_object_mut(), cur.as_object()) { for k in REPAIR_KEYS { if let Some(v) = c.get(k) { @@ -229,12 +225,38 @@ fn compose_named(current: &DevelopSettings, original: &DevelopSettings, settings } /// The leaves of `patch` that apply at `t` (below 100 %), each computed from the same place in -/// `base`. A leaf the amount does not reach is left out, so the photo keeps its own value there. +/// `base` ([`interpolate_leaf`]). A leaf the amount does not reach is left out, so the photo keeps +/// its own value there. Two rules look at an object as a whole (issue #2669): +/// +/// - **The `amount` beside a choice.** When the preset changes a choice here (a string such as the +/// profile or LUT id or a style, or the object's `enabled` switch), its `amount` is the strength of +/// that choice, not of the base's: from half amount up, where the preset's choice applies, the +/// amount fades in from 0 (a new profile at 50 % has half the preset's strength, and a profile at +/// 0 % is no look at all); below half amount the base's choice keeps its own amount. +/// - **White balance on another scale.** `temp` / `tint` on a different [`crate::WbScale`] than the +/// base's (Kelvin against the older relative scale; a partial that names no scale is on the +/// relative one, as [`DevelopSettings::merged`] reads it) are in other units and are never +/// blended: below half amount the base's numbers and scale apply, from half amount up the +/// preset's, as for any other choice. fn interpolate_object(base: Option<&Map>, patch: &Map, t: f64) -> Map { + let get = |k: &str| base.and_then(|b| b.get(k)); + let choice_changed = patch.iter().any(|(k, pv)| (pv.is_string() || (k == "enabled" && pv.is_boolean())) && get(k) != Some(pv)); + let scale_of = |o: Option<&Map>| o.and_then(|o| o.get("scale")).and_then(Value::as_str).unwrap_or("legacy").to_string(); + let other_scale = (patch.contains_key("temp") || patch.contains_key("tint")) && scale_of(Some(patch)) != scale_of(base); let mut out = Map::new(); for (k, pv) in patch { - let bv = base.and_then(|b| b.get(k)); + if other_scale && matches!(k.as_str(), "temp" | "tint" | "scale") { + continue; + } + let bv = get(k); let v = match pv { + Value::Number(_) if choice_changed && k == "amount" => { + if t >= 0.5 { + interpolate_leaf(Some(&Value::from(0.0)), pv, t) + } else { + bv.cloned() + } + } Value::Object(p) => Some(Value::Object(interpolate_object(bv.and_then(Value::as_object), p, t))), _ => interpolate_leaf(bv, pv, t), }; @@ -242,18 +264,38 @@ fn interpolate_object(base: Option<&Map>, patch: &Map= 0.5 { Some(patch) } else { base }; + for k in ["temp", "tint"] { + if let Some(v) = patch.get(k).and(side.and_then(|o| o.get(k))) { + out.insert(k.to_string(), v.clone()); + } + } + out.insert("scale".to_string(), Value::from(scale_of(side))); + } out } -/// One leaf at `t`. Numbers move from `base` towards `patch`. Other values switch to the preset's -/// at half amount and up, and below it take the base's value. A null in the base is the baseline -/// value the import state recorded (a cleared option, such as a free crop aspect): below half -/// amount it applies and clears the photo's value, as the amount contract promises. A null the -/// preset writes is a value like any other, so it applies at half amount and up (a preset can -/// clear an option field such as a crop aspect). +/// One leaf at `t`. Numbers move from `base` towards `patch`. Point curves (lists of `{x, y}` +/// points, the tone curves; empty is the identity) move as curves: both are evaluated as the +/// renderer does (monotone cubic) at every control point of either, and the points blend like +/// numbers, `y` kept in `0..1`. Other values switch to the preset's at half amount and up, and +/// below it take the base's value. A null in the base is the baseline value the import state +/// recorded (a cleared option, such as a free crop aspect): below half amount it applies and +/// clears the photo's value, as the amount contract promises. A null the preset writes is a value +/// like any other, so it applies at half amount and up (a preset can clear an option field such as +/// a crop aspect). fn interpolate_leaf(base: Option<&Value>, patch: &Value, t: f64) -> Option { + if t > 0.0 + && let (Some(bc), Some(pc)) = (base.and_then(point_curve), point_curve(patch)) + && !(bc.is_empty() && pc.is_empty()) + { + return Some(blend_curves(&bc, &pc, t)); + } match (base, patch) { - // integer fields (the grain seed, ids) are discrete like strings: see `scale_patch` + // integer fields (the grain seed, ids) are discrete like strings: an interpolated seed would + // not deserialize as an integer, and the whole preset would silently not apply (Some(Value::Number(b)), Value::Number(p)) if b.is_f64() || p.is_f64() => { let (b, p) = (b.as_f64().unwrap_or(0.0), p.as_f64().unwrap_or(0.0)); serde_json::Number::from_f64(b + (p - b) * t).map(Value::Number) @@ -263,6 +305,34 @@ fn interpolate_leaf(base: Option<&Value>, patch: &Value, t: f64) -> Option Option> { + v.as_array()? + .iter() + .map(|q| { + let o = q.as_object().filter(|o| o.len() == 2)?; + Some((o.get("x")?.as_f64()?, o.get("y")?.as_f64()?)) + }) + .collect() +} + +/// Two point curves blended by `t` at the control points of both (see [`interpolate_leaf`]). +fn blend_curves(base: &[(f64, f64)], patch: &[(f64, f64)], t: f64) -> Value { + use lightcraft_color::spline::MonotoneCurve; + let (bc, pc) = (MonotoneCurve::new(base), MonotoneCurve::new(patch)); + let mut xs: Vec = bc.points().into_iter().chain(pc.points()).map(|(x, _)| x.clamp(0.0, 1.0)).collect(); + xs.sort_by(f64::total_cmp); + xs.dedup_by(|a, b| (*a - *b).abs() < 1e-6); + let points = xs + .into_iter() + .map(|x| { + let (yb, yp) = (bc.eval(x), pc.eval(x)); + serde_json::json!({"x": x, "y": (yb + (yp - yb) * t).clamp(0.0, 1.0)}) + }) + .collect(); + Value::Array(points) +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Preset { pub id: String, @@ -285,6 +355,11 @@ impl Preset { /// settings (see [`Preset::apply_on`]): right for the import default preset and for scratch /// bases. Masks in the preset are added to the photo's own (ones it already has are skipped), /// their effect scaled by the amount. + /// + /// This knows nothing about the photo's source. A preset that names only one white balance + /// number needs the photo prepared against its as-shot white first, and the result put back on + /// the scale the photo is edited on: callers on a real photo go through the engine's + /// `apply_preset_to_photo`, which does that. pub fn apply(&self, s: &DevelopSettings, amount: f64) -> DevelopSettings { self.apply_on(s, s, amount) } @@ -295,8 +370,15 @@ impl Preset { /// the photo's pixel repairs (masks, spots, red eye), which the preset patches; masks in the /// preset are added to the photo's own (ones it already has are skipped), their effect scaled /// by the amount. A second preset therefore restores what the first one changed in the - /// settings it names (issue #2159), and nothing it leaves out. + /// settings it names (issue #2159), and nothing it leaves out. At 0 % (or less) the settings it + /// names take `original`'s values, so with `current` as the original nothing changes, and its + /// masks are not added (a mask at no strength would only block applying the preset later); a + /// NaN `amount` changes nothing. pub fn apply_on(&self, current: &DevelopSettings, original: &DevelopSettings, amount: f64) -> DevelopSettings { + if amount.is_nan() { + return current.clone(); + } + let amount = amount.max(0.0); let Some(masks) = self.settings.get("masks").and_then(Value::as_array).filter(|m| !m.is_empty()) else { return compose_named(current, original, &self.settings, amount); }; @@ -305,7 +387,9 @@ impl Preset { o.remove("masks"); } let mut out = compose_named(current, original, &rest, amount); - add_masks(&mut out, masks, amount); + if amount > 0.0 { + add_masks(&mut out, masks, amount); + } out } } @@ -391,6 +475,249 @@ mod tests { } } + fn pts(v: &[(f64, f64)]) -> Vec { + v.iter().map(|&(x, y)| lightcraft_geom::Point::new(x, y)).collect() + } + + fn eval(c: &[lightcraft_geom::Point], x: f64) -> f64 { + lightcraft_color::spline::MonotoneCurve::new(&c.iter().map(|p| (p.x, p.y)).collect::>()).eval(x) + } + + fn preset(settings: Value) -> Preset { + Preset { id: "p".into(), name: "P".into(), group: "G".into(), settings, favorite: false, builtin: false } + } + + /// Issue #2669: a preset's tone curve did nothing below 50 % and all of it from 50 % up. + #[test] + fn amount_blends_point_curves() { + let curve = [(0.0, 0.0), (0.25, 0.15), (0.75, 0.85), (1.0, 1.0)]; + let partial = json!({"curve": {"master": pts(&curve)}}); + let base = DevelopSettings::default(); + let mut last = 0.25; + for i in 1..=10 { + let t = f64::from(i) / 10.0; + let out = apply_partial(&base, &partial, t); + let y = eval(&out.curve.master, 0.25); + assert!((y - (0.25 - 0.10 * t)).abs() < 1e-9, "{t}: y(0.25) = {y}"); + assert!(y < last + 1e-12, "{t}: the curve moves steadily towards the preset's"); + last = y; + } + assert!(apply_partial(&base, &partial, 0.0).curve.master.is_empty(), "0 % keeps the photo's curve"); + // 200 % goes twice as far, kept in 0..1 + let more = apply_partial(&base, &partial, 2.0); + assert!((eval(&more.curve.master, 0.25) - 0.05).abs() < 1e-9); + assert!(more.curve.master.iter().all(|p| (0.0..=1.0).contains(&p.y))); + + // a photo whose original has its own curves (other points): at every control point of either + // curve the result is the blend of the original's curve and the preset's as rendered, whatever + // the photo's current curve is + let mut original = DevelopSettings::default(); + original.curve.master = pts(&[(0.0, 0.05), (0.5, 0.6), (1.0, 0.95)]); + original.curve.red = pts(&[(0.0, 0.0), (0.4, 0.5), (1.0, 1.0)]); + let mut current = DevelopSettings::default(); + current.curve.master = pts(&[(0.0, 0.2), (1.0, 0.8)]); + let p = preset(json!({"curve": {"master": pts(&curve), "red": []}})); + let out = p.apply_on(¤t, &original, 0.4); + for x in [0.0, 0.25, 0.5, 0.75, 1.0] { + let want = eval(&original.curve.master, x) * 0.6 + eval(&pts(&curve), x) * 0.4; + assert!((eval(&out.curve.master, x) - want).abs() < 1e-9, "x {x}"); + } + // towards the identity (an empty curve) too + assert!((eval(&out.curve.red, 0.4) - (0.5 * 0.6 + 0.4 * 0.4)).abs() < 1e-9); + } + + /// The profile (and LUT) choice steps to the preset's at half amount, as every choice does + /// (#2207); from there its strength fades in from 0 %, so the look shows in proportion to the + /// amount. The same profile blends its amount from the original's, not the photo's current one. + #[test] + fn amount_fades_in_a_new_profile() { + let p = preset(json!({"profile": {"id": "lc.vivid", "amount": 150.0}})); + let base = DevelopSettings::default(); + for (t, id, amount) in [(0.3, "lc.color", 100.0), (0.5, "lc.vivid", 75.0), (0.8, "lc.vivid", 120.0), (1.0, "lc.vivid", 150.0)] { + let out = p.apply_on(&base, &base, t); + assert_eq!(out.profile.id, id, "{t}"); + assert!((out.profile.amount - amount).abs() < 1e-9, "{t}: amount {}", out.profile.amount); + } + assert_eq!(p.apply_on(&base, &base, 0.0), base, "0 % changes nothing"); + // the same profile: its amount blends from the original's (60 → 150 at 50 % is 105), not + // from the photo's current 20 + let mut original = DevelopSettings::default(); + original.profile.id = "lc.vivid".into(); + original.profile.amount = 60.0; + let mut current = original.clone(); + current.profile.amount = 20.0; + for t in [0.3, 0.5] { + let out = p.apply_on(¤t, &original, t); + assert_eq!(out.profile.id, "lc.vivid"); + assert!((out.profile.amount - (60.0 + 90.0 * t)).abs() < 1e-9, "{t}: {}", out.profile.amount); + } + } + + /// Switches and choices keep the original's value below half amount and take the preset's from + /// half amount up; an `enabled` switch or a style the preset changes brings its amount in from 0 + /// there, and below half amount leaves the original's amount as it is. + #[test] + fn amount_steps_switches_and_choices_at_half_and_fades_in_their_amount() { + let mut original = DevelopSettings::default(); + original.lens_blur.amount = 50.0; + original.optics.lens_profile = true; + let style = serde_json::to_value(crate::VignetteStyle::ColorPriority).unwrap(); + let p = preset(json!({ + "lens_blur": {"enabled": true, "amount": 80.0}, + "treatment": "bw", + "optics": {"lens_profile": false}, + "vignette": {"style": style, "amount": -40.0}, + })); + let mut current = original.clone(); + current.light.exposure = 1.0; + let low = p.apply_on(¤t, &original, 0.25); + assert!(!low.lens_blur.enabled); + assert_eq!(low.lens_blur.amount, 50.0, "below half the original's own amount"); + assert_eq!(low.treatment, original.treatment); + assert!(low.optics.lens_profile); + assert_eq!((low.vignette.style, low.vignette.amount), (original.vignette.style, original.vignette.amount)); + assert_eq!(low.light.exposure, 1.0, "a setting the preset doesn't name keeps the photo's value"); + let half = p.apply_on(¤t, &original, 0.5); + assert!(half.lens_blur.enabled); + assert!((half.lens_blur.amount - 40.0).abs() < 1e-9, "{}", half.lens_blur.amount); + assert_eq!(half.treatment, crate::Treatment::Bw); + assert!(!half.optics.lens_profile); + assert_eq!(half.vignette.style, crate::VignetteStyle::ColorPriority); + assert!((half.vignette.amount + 20.0).abs() < 1e-9, "{}", half.vignette.amount); + assert_eq!(p.apply_on(¤t, &original, 0.0), current, "0 % changes nothing"); + } + + /// HDR is left out of the JSON while at its defaults; its numbers still blend from the original's. + #[test] + fn amount_blends_groups_left_out_at_their_defaults() { + let p = preset(json!({"hdr": {"enabled": true, "sdr_contrast": 40.0}})); + let base = DevelopSettings::default(); + let out = p.apply_on(&base, &base, 0.5); + assert!(out.hdr.enabled); + assert!((out.hdr.sdr_contrast - 20.0).abs() < 1e-9, "{}", out.hdr.sdr_contrast); + let out = apply_partial(&base, &p.settings, 0.3); + assert!(!out.hdr.enabled); + assert!((out.hdr.sdr_contrast - 12.0).abs() < 1e-9, "{}", out.hdr.sdr_contrast); + } + + /// White balance on another scale (Kelvin against the older relative one) is in other units: + /// the original's below half amount and the preset's from half amount up, each whole with its + /// scale, never a blend of the two. + #[test] + fn amount_takes_white_balance_on_another_scale_whole() { + let kelvin = preset(json!({"wb": {"mode": "custom", "temp": 4200.0, "tint": 8.0, "scale": "kelvin"}})); + let photo = DevelopSettings::default(); // relative scale, 6500 / 0 = as shot + for t in [0.01, 0.3, 0.49] { + assert_eq!(kelvin.apply_on(&photo, &photo, t).wb, photo.wb, "{t}"); + } + for t in [0.5, 0.7, 1.5] { + let out = kelvin.apply_on(&photo, &photo, t); + assert_eq!((out.wb.scale, out.wb.temp, out.wb.tint), (crate::WbScale::Kelvin, 4200.0, 8.0), "{t}"); + } + let wb = crate::WhiteBalance { mode: crate::WbMode::Custom, temp: 5000.0, tint: 0.0, scale: crate::WbScale::Kelvin }; + let photo = DevelopSettings { wb, ..DevelopSettings::default() }; + // a partial without a scale is on the relative scale + let relative = preset(json!({"wb": {"temp": 7000.0, "tint": 10.0}})); + assert_eq!(relative.apply_on(&photo, &photo, 0.3).wb, photo.wb); + let out = relative.apply_on(&photo, &photo, 0.6); + assert_eq!((out.wb.scale, out.wb.temp, out.wb.tint), (crate::WbScale::Legacy, 7000.0, 10.0)); + // the same scale blends + let out = kelvin.apply_on(&photo, &photo, 0.5); + assert_eq!((out.wb.scale, out.wb.temp, out.wb.tint), (crate::WbScale::Kelvin, 4600.0, 4.0)); + } + + #[test] + fn zero_amount_mask_preset_leaves_settings_unchanged_and_can_be_applied_later() { + let photo = DevelopSettings { masks: vec![crate::Mask { id: 9, name: "Existing".into(), ..Default::default() }], ..Default::default() }; + let p = preset(json!({"light": {"exposure": 1.0}, "masks": [{"name": "New", "adjust": {"amount": 80.0}}]})); + for amount in [0.0, -0.5, f64::NAN] { + let unchanged = p.apply_on(&photo, &photo, amount); + assert_eq!(unchanged, photo); + let out = p.apply(&unchanged, 1.0); + assert_eq!(out.light.exposure, 1.0); + assert_eq!(out.masks.len(), 2); + assert_eq!(out.masks[0], photo.masks[0]); + assert_eq!(out.masks[1].name, "New"); + assert_eq!(out.masks[1].adjust.amount, 80.0); + } + // with an import state, 0 % is that state for the settings the preset names (#2207), and still + // adds no mask + let mut current = photo.clone(); + current.light.exposure = 2.0; + current.curve.master = pts(&[(0.0, 0.1), (1.0, 0.9)]); + let original = DevelopSettings { light: crate::Light { exposure: -0.5, ..Default::default() }, ..Default::default() }; + let q = + preset(json!({"light": {"exposure": 1.0}, "curve": {"master": pts(&[(0.0, 0.0), (0.5, 0.7), (1.0, 1.0)])}, "masks": [{"name": "New"}]})); + let out = q.apply_on(¤t, &original, 0.0); + assert_eq!(out.light.exposure, -0.5); + assert!(out.curve.master.is_empty(), "the original's curve, point for point"); + assert_eq!(out.masks, current.masks); + } + + /// Every leaf of `v` that is not a number (and every list's length), by path. + fn non_numbers(v: &Value, path: &str, out: &mut Vec<(String, Value)>) { + match v { + Value::Object(o) => o.iter().for_each(|(k, v)| non_numbers(v, &format!("{path}/{k}"), out)), + Value::Array(a) => { + out.push((format!("{path}#len"), Value::from(a.len()))); + a.iter().enumerate().for_each(|(i, v)| non_numbers(v, &format!("{path}/{i}"), out)); + } + Value::Number(_) => {} + v => out.push((path.to_string(), v.clone())), + } + } + + /// Across the whole Amount range a preset has one step, at half amount (#2207): below it the + /// switches, choices and lists stay as at 1 %, from it as at 50 %; the numbers and tone curves + /// move in proportion to the amount throughout, and the strength of a changed choice fades in + /// from 0 once the choice is the preset's. + #[test] + fn amount_has_one_step_at_half_and_blends_the_rest() { + let mut a = DevelopSettings::default(); + a.profile.id = "lc.vivid".into(); + a.profile.amount = 140.0; + a.treatment = crate::Treatment::Bw; + a.light.exposure = 0.8; + a.curve.master = pts(&[(0.0, 0.0), (0.3, 0.2), (0.7, 0.8), (1.0, 1.0)]); + a.curve.green = pts(&[(0.0, 0.05), (1.0, 0.9)]); + a.grain.amount = 30.0; + a.grain.seed = 777; + a.vignette.style = crate::VignetteStyle::ColorPriority; + a.vignette.amount = -25.0; + a.lens_blur = crate::LensBlur { enabled: true, amount: 60.0, focal_distance: 30.0, focal_range: 20.0 }; + a.optics.remove_ca = true; + let p = Preset::from_settings("p", "P", "User", &a, &SettingsGroup::default_copy()); + let mut original = DevelopSettings::default(); + original.curve.master = pts(&[(0.0, 0.1), (0.5, 0.45), (1.0, 1.0)]); + original.light.exposure = -0.4; + let mut current = original.clone(); + current.light.exposure = 2.0; + let leaves = |t: f64| { + let mut v = Vec::new(); + non_numbers(&p.apply_on(¤t, &original, t).to_json(), "", &mut v); + v + }; + let (below, above) = (leaves(0.01), leaves(0.5)); + assert_ne!(below, above, "the choices step at half amount"); + let y0 = eval(&original.curve.master, 0.3); + for i in 2..=200 { + let t = f64::from(i) / 100.0; + let out = p.apply_on(¤t, &original, t); + if i != 100 { + // (at exactly 100 % the preset is merged as it is: its own curve points) + assert_eq!(leaves(t), if t < 0.5 { below.clone() } else { above.clone() }, "{t}: a switch, choice or list moved off its side"); + } + let want = (-0.4 + 1.2 * t).min(5.0); + assert!((out.light.exposure - want).abs() < 1e-9, "{t}: exposure {}", out.light.exposure); + let (profile, blur) = if t < 0.5 { (original.profile.amount, original.lens_blur.amount) } else { ((140.0 * t).min(200.0), 60.0 * t) }; + assert!((out.profile.amount - profile).abs() < 1e-9, "{t}: profile amount {}", out.profile.amount); + assert!((out.lens_blur.amount - blur).abs() < 1e-9, "{t}: lens blur amount {}", out.lens_blur.amount); + let y = eval(&out.curve.master, 0.3); + let want = (y0 + (0.2 - y0) * t).clamp(0.0, 1.0); + assert!((y - want).abs() < 1e-9, "{t}: curve y(0.3) {y}, want {want}"); + } + } + /// A preset changes only the settings it names: a setting in a group it styles but does not /// name keeps the photo's value, and so does a whole group it leaves out. #[test] diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index eb8906f2ba..99bd5648e6 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -324,7 +324,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-PRE-PANEL | Presets panel | P0 | ✅ | `cmd:panel.presets`, `cmd:preset.apply`, `crates/ui-egui/src/panels/presets.rs` | grouped list with amount; the preset applied to a photo stays marked on returning to it until the photo is edited further (issue #2392); resting on a preset previews it in the loupe (no history entry); optional live thumbnails (⋯ → Show Thumbnails); a preset changes only the settings it names: each is computed on the photo's import state (or on its current settings when no default preset recorded one), and every setting it does not name keeps the photo's value, so a second preset restores what an earlier one changed in the settings it names (issue #2159) | | LR-PRE-CREATE | Create preset | P0 | ✅ | `cmd:dialog.createPreset`, `cmd:preset.create` (`groups`) | name, group and a checklist of settings groups (crop, masks, remove, red eye off by default; All / None) | | LR-PRE-MANAGE | Manage presets | P1 | ✅ | `cmd:preset.delete`, `cmd:preset.favorite`, `cmd:preset.import`, `cmd:preset.export`, `cmd:preset.rename`, `cmd:preset.update`, `cmd:preset.move` | rename, update with current settings, move to a group (existing or new); starred presets are listed in a Favorites section on top, as in the Profile browser (issue #1999, `crates/ui-egui/src/tests/preset_favorites.rs`); no hiding of groups | -| LR-PRE-AMOUNT | Preset amount | P1 | ✅ | `cmd:preset.apply` (`amount` 0–200) | each named setting moves from the photo's import look (or, when none is recorded, from its current value) towards the preset's value; 0 % gives the import look's value for the settings the preset names, and the current value when no look is recorded | +| LR-PRE-AMOUNT | Preset amount | P1 | ✅ | `cmd:preset.apply` (`amount` 0–200) | each named setting moves from the photo's import look (or, when none is recorded, from its current value) towards the preset's value; 0 % gives the import look's value for the settings the preset names, and the current value when no look is recorded; sliders and tone-curve points blend with the amount, switches and choices (profile/LUT, treatment, styles) take the preset's value from half amount, and the strength of a profile or `enabled` group the preset changes fades in from 0 there; white balance on another scale (Kelvin vs relative) is never blended (`interpolate_object`, `crates/develop/src/presets.rs`, issue #2669) | | LR-PRE-ADAPTIVE | Adaptive presets | P2 | ⬜ | | | | LR-PRE-PREMIUM | Built-in presets (own) | P2 | ✅ | `crates/engine/src/presets.rs` | 41 own-authored presets in 10 groups (Color, Film, B&W incl. toners, Portrait, Landscape, Urban, Food, Seasons, Vintage, Style) | | LR-PRE-RECOMMENDED | Community recommendations | OOS | 🚫 | | | @@ -802,6 +802,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-11-15 | patch | LR-PRE-AMOUNT: Amount blends tone curves, fades in the strength of a profile/LUT or switched-on group a preset changes, and takes white balance on another scale whole (#2669); the step at half amount for switches and choices stays (#2207); status unchanged (✅) | | 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | | 2026-11-05 | patch | LRC-LIB-CATALOG-LOCK: a library is written only to the folder it was opened from (on Unix, where the system gives a folder an identity, it is checked before every write of the catalog, settings, lock note and thumbnails; a share mounted over it, or a replaced folder, is refused and nothing is written; a folder that holds this session's lock note counts as the opened one, so a drive mounted again keeps saving; on Windows only that the path is still a folder is checked, so a replaced folder or a share mounted at the same path is not caught), a Move import removes its originals only once the catalog log is on disk, and dropping the lock removes only the owner note it wrote itself (#3240); status unchanged | | 2026-11-05 | minor | LR-EDIT-LENSBLUR: ⬜ → 🟡 (Lens Blur section: Apply, Blur Amount, Boost, focus on the subject or a mask; no depth map yet); LR-MASK-SLIDERS: a Lens Blur block in every mask (selection or outside, Amount, Boost, Transition); KEY-SECTIONS: ⌘6 opens Lens Blur | From 8ea984f8673ef2857291e11d4c47a49ec5a40589 Mon Sep 17 00:00:00 2001 From: radialmonster Date: Sun, 15 Nov 2026 00:11:55 -0500 Subject: [PATCH 17/19] Presets: one shared path for white balance preparation and zero Amount `apply_preset_to_photo` in the engine prepares a one-field white balance preset against the photo's as-shot white (as `develop.merge` does, #2910), applies it with `Preset::apply_on` on the photo's original, and puts the result back on the scale the photo is edited on. `Session::preset_applied` (the command and the panel's previews and thumbnails), importing with a preset and import defaults all go through it, so they show and store the same result. Without an import state, a zero Amount returns the photo's settings untouched, so a preview at nothing never turns As Shot into Custom; with one, 0 % is the import state's value for each named setting, as #2207 has it. The photo's source is read only for presets that need it, since the panel asks for every visible row each frame. Ports e2d6d5cf5 of the PR onto main's `apply_on` call sites. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fnx9MvXCjGmV3UZ1Xs54DG --- crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/develop.rs | 36 +++------ crates/engine/src/import/commit.rs | 2 +- crates/engine/src/import/defaults.rs | 2 +- crates/engine/src/presets.rs | 52 +++++++++--- crates/engine/src/tests/color.rs | 113 +++++++++++++++++++++++++++ 6 files changed, 171 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 72b2dce09a..f15576228c 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -14,6 +14,7 @@ pub mod curves; pub mod dcp_profiles; pub(crate) mod denoise; mod develop; +pub(crate) use develop::{prepare_photo_for_wb_partial, wb_partial_names_one_field}; mod edit; mod export; pub(crate) mod face_detect; diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index dc89e3a9c3..2403841de2 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -120,13 +120,11 @@ fn wb_mode_ignores_its_numbers(mode: WbMode, info: &lightcraft_pipeline::SourceI /// numbers, neither, or a mode of its own. [`merge_settings_for_photo`] and `preset.apply` both start here, and /// both finish with `normalize_wb` so the photo ends on the scale it is edited on. pub(crate) fn prepare_photo_for_wb_partial(d: &DevelopSettings, partial: &Value, info: &lightcraft_pipeline::SourceInfo) -> Option { - let mut d = (*d).clone(); - let wb = partial.get("wb").and_then(Value::as_object); - // the partial names one of the two numbers, and not both or neither - let one_field = wb.is_some_and(|wb| wb.contains_key("temp") != wb.contains_key("tint")); - if !one_field { + if !wb_partial_names_one_field(partial) { return None; } + let mut d = (*d).clone(); + let wb = partial.get("wb").and_then(Value::as_object); // a photo whose source is edited in Kelvin is the one with two scales to trip over let kelvin_source = info.raw && !info.relative_wb; // the scale the partial's numbers are written on: an unmentioned scale means the relative scale, as `merged` reads it @@ -154,6 +152,12 @@ pub(crate) fn prepare_photo_for_wb_partial(d: &DevelopSettings, partial: &Value, Some(d) } +/// Whether `partial`'s white balance names one of the two numbers, and not both or neither: the partials +/// [`prepare_photo_for_wb_partial`] prepares the photo for. +pub(crate) fn wb_partial_names_one_field(partial: &Value) -> bool { + partial.get("wb").and_then(Value::as_object).is_some_and(|wb| wb.contains_key("temp") != wb.contains_key("tint")) +} + /// Merge a partial settings JSON into a photo's settings (issue #2910). `DevelopSettings::merged` keeps a white /// balance that names no scale on the relative scale; on a photo edited in Kelvin the field the partial does not /// name (a partial with only `temp`, or only `tint`) would then be read on the other scale, giving a white neither @@ -1323,24 +1327,10 @@ pub fn specs() -> Vec { let ops = ids .iter() .filter_map(|id| s.develop_of(*id).map(|d| (*id, d))) - .filter_map(|(id, d)| { - // a hand-written preset may name one white balance number only, and then it means the same as - // a partial: bring the photo onto that scale first, with its own as-shot white, and put the - // result back on the scale the photo is edited on (issue #2910) — the merge `develop.merge` uses - let info = s.source_info(id); - let prepared = prepare_photo_for_wb_partial(&d, &preset.settings, &info); - let on_kelvin_scale = prepared.is_some() && info.raw && !info.relative_wb; - let base: &DevelopSettings = prepared.as_ref().unwrap_or(&d); - // Amount is measured from the import look only when the photo has one. - // Otherwise the current settings (on the partial's WB scale) are its baseline. - let imported = s.catalog.photo(id).filter(|p| p.import_look.is_some() && amount != 1.0).map(|p| p.import_defaults()); - let prepared_import = - imported.as_ref().map(|d| prepare_photo_for_wb_partial(d, &preset.settings, &info).unwrap_or_else(|| d.clone())); - let original = prepared_import.as_ref().unwrap_or(base); - let mut next = preset.apply_on(base, original, amount); - if on_kelvin_scale { - lightcraft_pipeline::local::normalize_wb(&mut next, &info); - } + .filter_map(|(id, _)| { + // the same composition, white balance preparation and final scale as previews and import + // (`Session::preset_applied`, issues #2159 and #2910) + let next = s.preset_applied(id, &preset, amount)?; s.develop_op(id, next, &format!("Preset: {}", preset.name)) }) .collect::>(); diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 016ce01393..35210faf78 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -285,7 +285,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare } } if let Some(preset) = &opts.preset { - let d = std::sync::Arc::new(preset.apply(&p.develop, 1.0)); + let d = std::sync::Arc::new(crate::presets::apply_preset_to_photo(preset, &p.develop, None, 1.0, &crate::media::source_info(&p))); let label = format!("Preset: {}", preset.name); p.develop = d.clone(); p.edited = Some(now.clone()); diff --git a/crates/engine/src/import/defaults.rs b/crates/engine/src/import/defaults.rs index 6fd3feb007..72e4019d22 100644 --- a/crates/engine/src/import/defaults.rs +++ b/crates/engine/src/import/defaults.rs @@ -87,7 +87,7 @@ pub fn apply_import_defaults(s: &Session, p: &mut Photo) { let preset = s.import_defaults.preset_for(raw, &p.meta.camera).and_then(|id| s.presets.iter().find(|x| x.id == id)); match preset { Some(pr) => { - let look = std::sync::Arc::new(pr.apply(&base, 1.0)); + let look = std::sync::Arc::new(crate::presets::apply_preset_to_photo(pr, &base, None, 1.0, &crate::media::source_info(p))); p.develop = look.clone(); p.import_look = (*look != base).then_some(look); } diff --git a/crates/engine/src/presets.rs b/crates/engine/src/presets.rs index a1aa603c83..d43dbd2f58 100644 --- a/crates/engine/src/presets.rs +++ b/crates/engine/src/presets.rs @@ -178,21 +178,18 @@ impl Session { /// from an XMP sidecar or a catalog import, which record none) composes them on its current /// settings instead, since the camera defaults are not its import state. Either way, the /// settings the preset does not name keep the photo's values (issue #2159). The `preset.apply` - /// command and the UI's hover previews share this, so hovering shows exactly what a click commits. + /// command and the UI's hover previews and thumbnails share this, so hovering shows exactly what + /// a click commits, white balance preparation included ([`apply_preset_to_photo`]). pub fn preset_applied(&self, id: PhotoId, preset: &Preset, amount: f64) -> Option { let current = self.develop_of(id)?; let photo = self.catalog.photo(id)?; // The original is read only below 100 %: the panel asks for every visible row at 100 % on // every frame, and then neither the import state nor a copy of the photo's settings is built. - let look; - let original: &DevelopSettings = match &photo.import_look { - Some(_) if (amount - 1.0).abs() >= 1e-9 => { - look = photo.import_defaults(); - &look - } - _ => ¤t, - }; - Some(preset.apply_on(¤t, original, amount)) + let original = photo.import_look.as_ref().filter(|_| (amount - 1.0).abs() >= 1e-9).map(|_| photo.import_defaults()); + // the photo's source is read only for a preset that needs it (one white balance number): + // the panel asks for every visible row on every frame + let info = if crate::cmd::wb_partial_names_one_field(&preset.settings) { self.source_info(id) } else { Default::default() }; + Some(apply_preset_to_photo(preset, ¤t, original.as_ref(), amount, &info)) } /// Add imported presets. Identical presets (same name, group and settings) already present are @@ -634,6 +631,41 @@ impl Session { } } +/// Apply `preset` to a photo's settings `current` at `amount` (1.0 = 100 %), composing on +/// `original` (the photo's import state; `None`: `current` itself, see [`Preset::apply_on`]): the +/// one path every caller that puts a preset on a photo takes (the `preset.apply` command, +/// thumbnails and hover previews through [`Session::preset_applied`], importing with a preset, +/// import defaults), so all of them show and store the same result. +/// +/// `info` is the photo's source: a hand-written preset may name one white balance number only, and +/// then it means what a one-field partial means (`prepare_photo_for_wb_partial`, shared with +/// `develop.merge`, issue #2910): the photo (and its original) are brought onto the preset's scale +/// with the photo's own as-shot white first, and the result is put back on the scale the photo is +/// edited on. Without an import state a zero (or negative) `amount` returns `current` exactly as it +/// was, before any preparation, so a preview at nothing never turns As Shot into Custom; with one, +/// 0 % is the import state's value for each setting the preset names ([`Preset::apply_on`]). A NaN +/// `amount` changes nothing. +pub fn apply_preset_to_photo( + preset: &Preset, + current: &DevelopSettings, + original: Option<&DevelopSettings>, + amount: f64, + info: &lightcraft_pipeline::SourceInfo, +) -> DevelopSettings { + if amount.is_nan() || (amount <= 0.0 && original.is_none()) { + return current.clone(); + } + let prepared = crate::cmd::prepare_photo_for_wb_partial(current, &preset.settings, info); + let on_kelvin_scale = prepared.is_some() && info.raw && !info.relative_wb; + let base = prepared.as_ref().unwrap_or(current); + let prepared_original = original.map(|o| crate::cmd::prepare_photo_for_wb_partial(o, &preset.settings, info).unwrap_or_else(|| o.clone())); + let mut next = preset.apply_on(base, prepared_original.as_ref().unwrap_or(base), amount); + if on_kelvin_scale { + lightcraft_pipeline::local::normalize_wb(&mut next, info); + } + next +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/tests/color.rs b/crates/engine/src/tests/color.rs index 4805c70ece..b9acb42a00 100644 --- a/crates/engine/src/tests/color.rs +++ b/crates/engine/src/tests/color.rs @@ -470,3 +470,116 @@ fn one_field_wb_preset_apply_keeps_the_other_field_on_its_scale() { let back = (*s.develop_of(kelvin).unwrap()).clone(); assert_eq!(back.wb, look.wb, "a preset made from the photo puts its whole white balance back: {:?} vs {:?}", back.wb, look.wb); } + +/// A preset applied to a photo goes through one function whether it is the `preset.apply` command, a thumbnail or +/// hover preview, or an import: a hand-written preset naming one white balance number (either one, on either +/// scale) gives the same settings in all three, on a photo edited in Kelvin and on one edited relative to its +/// as-shot white. Before, the previews (`Session::preset_applied`) and import called the source-free +/// `Preset::apply_on` / `Preset::apply` directly, which stored the number without the photo's as-shot white. +#[test] +fn one_field_wb_preset_gives_the_same_result_in_command_preview_and_import() { + use lightcraft_catalog::{MediaKind, Op, Photo, Source}; + use lightcraft_develop::{Preset, WbMode, WbScale}; + let as_shot = (4986.0, -2.0); + let photo = |camera: &str| { + let mut p = Photo::new( + lightcraft_catalog::PhotoId(1), + Source::File { path: "/photos/one-field.arw".into() }, + "one-field.arw", + "ARW", + 64, + 64, + "2026-01-01T00:00:00", + ); + p.kind = MediaKind::Raw; + p.meta.camera = camera.into(); + p.as_shot_wb = Some(as_shot); + p.develop = std::sync::Arc::new(p.camera_defaults()); + p + }; + let one_field = |name: &str, wb: serde_json::Value| Preset { + id: format!("user.{name}"), + name: name.into(), + group: "User".into(), + settings: json!({ "wb": wb }), + favorite: false, + builtin: false, + }; + let presets = [ + one_field("temp-only", json!({"temp": 5800.0})), + one_field("tint-only", json!({"tint": 9.0})), + // the reverse scale: numbers written in Kelvin on a photo edited relative to as shot, and the relative + // scale named outright on a photo edited in Kelvin + one_field("kelvin-temp", json!({"scale": "kelvin", "temp": 6500.0})), + one_field("kelvin-tint", json!({"scale": "kelvin", "tint": 6.0})), + one_field("relative-temp", json!({"scale": "legacy", "temp": 6800.0})), + ]; + for (camera, kelvin_photo) in [("SONY ILCE-7M3", true), ("Nobody X1", false)] { + assert_eq!(photo(camera).relative_wb(), !kelvin_photo, "{camera}"); + for preset in &presets { + let mut s = Session::new(); + let p = photo(camera); + let id = p.id; + s.catalog.apply(Op::AddPhoto { photo: Box::new(p.clone()) }).unwrap(); + s.presets.push(preset.clone()); + let why = format!("{camera}, {}", preset.name); + let before = (*s.develop_of(id).unwrap()).clone(); + assert_eq!(before.wb.mode, WbMode::AsShot, "{why}"); + + // preview / hover + let preview = s.preset_applied(id, preset, 1.0).unwrap(); + // command + s.execute("library.select", &json!({"ids": [id.0], "active": id.0})).unwrap(); + s.execute("preset.apply", &json!({"id": preset.id})).unwrap(); + let command = (*s.develop_of(id).unwrap()).clone(); + // import (the photo is not in a catalog yet) + let mut imported = p; + s.import_defaults.raw_preset = Some(preset.id.clone()); + crate::import::apply_import_defaults(&s, &mut imported); + + assert_eq!(preview, command, "{why}: preview and command"); + assert_eq!(*imported.develop, command, "{why}: import and command"); + assert_eq!(command.wb.mode, WbMode::Custom, "{why}: the preset's number replaces As Shot: {:?}", command.wb); + // a photo edited in Kelvin ends there; a relative one keeps the scale the preset names (as `develop.merge` does) + let want_scale = if kelvin_photo || preset.name.starts_with("kelvin") { WbScale::Kelvin } else { WbScale::Legacy }; + assert_eq!(command.wb.scale, want_scale, "{why}: the photo stays on the scale it is edited on: {:?}", command.wb); + assert_ne!(command.wb, before.wb, "{why}"); + } + } +} + +/// Zero Amount changes nothing, and not by being applied and undone: the photo keeps As Shot mode and every +/// setting, through the command and the preview, even for a preset whose preparation would write Custom values. +#[test] +fn zero_amount_preset_keeps_as_shot_mode_and_settings() { + use lightcraft_catalog::{MediaKind, Op, Photo, Source}; + use lightcraft_develop::{Preset, WbMode}; + let mut s = Session::new(); + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: "/photos/zero.arw".into() }, "zero.arw", "ARW", 64, 64, "2026-01-01T00:00:00"); + p.kind = MediaKind::Raw; + p.meta.camera = "SONY ILCE-7M3".into(); + p.as_shot_wb = Some((4986.0, -2.0)); + p.develop = std::sync::Arc::new(p.camera_defaults()); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let preset = Preset { + id: "user.zero".into(), + name: "Zero".into(), + group: "User".into(), + settings: json!({"wb": {"temp": 5800.0}, "light": {"exposure": 1.0}}), + favorite: false, + builtin: false, + }; + s.presets.push(preset.clone()); + s.execute("library.select", &json!({"ids": [id.0], "active": id.0})).unwrap(); + let before = (*s.develop_of(id).unwrap()).clone(); + assert_eq!(before.wb.mode, WbMode::AsShot); + for amount in [0.0, -1.0, f64::NAN] { + assert_eq!(crate::presets::apply_preset_to_photo(&preset, &before, None, amount, &s.source_info(id)), before, "preview at {amount}"); + assert_eq!(s.preset_applied(id, &preset, amount).unwrap(), before, "panel preview at {amount}"); + } + s.execute("preset.apply", &json!({"id": preset.id, "amount": 0})).unwrap(); + let after = (*s.develop_of(id).unwrap()).clone(); + assert_eq!(after, before); + assert_eq!(after.wb.mode, WbMode::AsShot); +} From 6f7859b600e135dbeaf5f8dcbcb7952663a480cc Mon Sep 17 00:00:00 2001 From: radialmonster Date: Sun, 15 Nov 2026 02:17:26 -0500 Subject: [PATCH 18/19] Presets: align amount sweep with current Lens Blur (#2669) Supply defaults for the Lens Blur fields added on main so the amount sweep compiles. Cap its expected Blur Amount at the existing control maximum of 100 when the preset amount extrapolates above that limit. No production behavior changes. --- crates/develop/src/presets.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/develop/src/presets.rs b/crates/develop/src/presets.rs index 42f92df005..8ce6fc5c0f 100644 --- a/crates/develop/src/presets.rs +++ b/crates/develop/src/presets.rs @@ -684,7 +684,7 @@ mod tests { a.grain.seed = 777; a.vignette.style = crate::VignetteStyle::ColorPriority; a.vignette.amount = -25.0; - a.lens_blur = crate::LensBlur { enabled: true, amount: 60.0, focal_distance: 30.0, focal_range: 20.0 }; + a.lens_blur = crate::LensBlur { enabled: true, amount: 60.0, focal_distance: 30.0, focal_range: 20.0, ..Default::default() }; a.optics.remove_ca = true; let p = Preset::from_settings("p", "P", "User", &a, &SettingsGroup::default_copy()); let mut original = DevelopSettings::default(); @@ -709,7 +709,8 @@ mod tests { } let want = (-0.4 + 1.2 * t).min(5.0); assert!((out.light.exposure - want).abs() < 1e-9, "{t}: exposure {}", out.light.exposure); - let (profile, blur) = if t < 0.5 { (original.profile.amount, original.lens_blur.amount) } else { ((140.0 * t).min(200.0), 60.0 * t) }; + let (profile, blur) = + if t < 0.5 { (original.profile.amount, original.lens_blur.amount) } else { ((140.0 * t).min(200.0), (60.0 * t).min(100.0)) }; assert!((out.profile.amount - profile).abs() < 1e-9, "{t}: profile amount {}", out.profile.amount); assert!((out.lens_blur.amount - blur).abs() < 1e-9, "{t}: lens blur amount {}", out.lens_blur.amount); let y = eval(&out.curve.master, 0.3); From 07223327e05955b96aa382949302924fd0207182 Mon Sep 17 00:00:00 2001 From: Lamsoda1123 <139034695+Lamsoda1123@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:58:49 +0800 Subject: [PATCH 19/19] SAM 3: reduce DX12 attention pipeline startup time --- crates/gpu/src/sam3.rs | 12 +++++++++--- crates/gpu/src/sam3/detr.rs | 4 ++-- crates/gpu/src/sam3/detr/tests.rs | 2 ++ crates/gpu/src/sam3/tests.rs | 9 +++++++++ 4 files changed, 22 insertions(+), 5 deletions(-) diff --git a/crates/gpu/src/sam3.rs b/crates/gpu/src/sam3.rs index 1c059268d7..f646935079 100644 --- a/crates/gpu/src/sam3.rs +++ b/crates/gpu/src/sam3.rs @@ -59,10 +59,16 @@ 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). +/// Conservative workgroup memory for 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. +/// The maximum keys per step; also used to bound the required workgroup memory. const ATTENTION_KEYS: u32 = 32; + +/// On DX12, creating the fully unrolled 32-key shader can be very slow on some drivers. Smaller +/// tiles shorten initialization; the existing 32-key limits remain conservative for every backend. +fn attention_keys(backend: wgpu::Backend) -> u32 { + if backend == wgpu::Backend::Dx12 { 8 } else { ATTENTION_KEYS } +} /// The matrix product's blocking. const TILE: Tile = Tile { rows: 4, cols: 4, bk: 16 }; @@ -255,7 +261,7 @@ fn make_device(backends: wgpu::Backends) -> Result { 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"), + attention: pipe("sam3 attention", &attention_source(attention_keys(info.backend)), "main"), layernorm: pipe("sam3 ops", ops, "layernorm"), rope: pipe("sam3 ops", ops, "rope"), im2col: pipe("sam3 ops", ops, "im2col"), diff --git a/crates/gpu/src/sam3/detr.rs b/crates/gpu/src/sam3/detr.rs index a3e28c25cb..1c2850c8ec 100644 --- a/crates/gpu/src/sam3/detr.rs +++ b/crates/gpu/src/sam3/detr.rs @@ -30,7 +30,7 @@ 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). +/// Required key-count alignment, kept at 32 even when the DX12 kernel uses smaller tiles. const KEYS: u32 = 32; /// `p.gelu` of the matrix product: ReLU. const RELU: u32 = 2; @@ -49,7 +49,7 @@ 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 source = attention_source(super::attention_keys(dev.info.backend)); 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()) { diff --git a/crates/gpu/src/sam3/detr/tests.rs b/crates/gpu/src/sam3/detr/tests.rs index 95884facab..b94f342d99 100644 --- a/crates/gpu/src/sam3/detr/tests.rs +++ b/crates/gpu/src/sam3/detr/tests.rs @@ -83,6 +83,8 @@ fn the_kernel_source_is_written_out() { 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 = ")); + let dx12 = attention_source(super::super::attention_keys(wgpu::Backend::Dx12)); + assert!(dx12.contains("let s7 = ") && !dx12.contains("let s8 = ")); } #[test] diff --git a/crates/gpu/src/sam3/tests.rs b/crates/gpu/src/sam3/tests.rs index d9f6050fe4..1b9041f263 100644 --- a/crates/gpu/src/sam3/tests.rs +++ b/crates/gpu/src/sam3/tests.rs @@ -456,3 +456,12 @@ fn an_adapter_short_of_the_limits_is_refused_with_what_it_lacks() { assert_eq!(short.len(), 1, "{short:?}"); assert!(short[0].starts_with("max_compute_workgroup_storage_size 8192 <"), "{short:?}"); } + +/// DX12 pipeline creation can take minutes for the fully unrolled attention shader; other backends keep the larger tile. +#[test] +fn attention_tiles_are_smaller_on_dx12() { + assert_eq!(attention_keys(wgpu::Backend::Dx12), 8); + assert_eq!(attention_keys(wgpu::Backend::Vulkan), ATTENTION_KEYS); + let src = attention_source(attention_keys(wgpu::Backend::Dx12)); + assert!(src.contains("let s7 = ") && !src.contains("let s8 = ")); +}