diff --git a/apps/lightcraft-web/src/wire.rs b/apps/lightcraft-web/src/wire.rs index 9854798673..16802032bd 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/codecs/src/lib.rs b/crates/codecs/src/lib.rs index 7370bde763..c2846db258 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -247,7 +247,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), @@ -261,7 +261,20 @@ pub fn decode_unguarded(bytes: &[u8], format: Format, opts: &DecodeOptions) -> R Format::Heif => heif::decode(bytes, &opts), Format::Avif => avif_decode::decode(bytes, &opts), Format::RawTiffLike | Format::RawOther => unsupported(), + }?; + 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(()) } /// Convert a decode result to linear Rec.2020 D65 (Bradford-adapted), the develop working space. @@ -381,4 +394,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 ceb271d869..7d445329b1 100644 --- a/crates/codecs/tests/it/fuzz.rs +++ b/crates/codecs/tests/it/fuzz.rs @@ -291,6 +291,43 @@ 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] +// 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(); + 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 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> { static S: OnceLock>> = OnceLock::new(); S.get_or_init(|| { diff --git a/crates/develop/src/presets.rs b/crates/develop/src/presets.rs index 0ea3d12f8c..8ce6fc5c0f 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,250 @@ 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, ..Default::default() }; + 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).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); + 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/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 8c449caea5..9f4e8237aa 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/export/encoding.rs b/crates/engine/src/export/encoding.rs index 957b932104..7f88982852 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; @@ -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); @@ -52,47 +53,72 @@ 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); + // 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(), + ) +} + +/// 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 854c34279f..4af8bab03c 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,17 +234,66 @@ 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 +/// 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); +} + +/// 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 { 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]) }; + 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`. diff --git a/crates/engine/src/files/probe.rs b/crates/engine/src/files/probe.rs index a9d262074e..4bdf22afa9 100644 --- a/crates/engine/src/files/probe.rs +++ b/crates/engine/src/files/probe.rs @@ -121,6 +121,23 @@ pub fn embedded_lens(raw: &lightcraft_raw::RawInfo) -> Option bool { + 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 !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() + .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() } @@ -133,6 +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 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, @@ -149,7 +167,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { meta, as_shot_wb: None, content_hash, - xmp: lightcraft_meta::embedded(bytes).xmp, + xmp, orientation: m.orientation, preview_only: Some(why), ..Default::default() @@ -184,7 +202,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { meta, as_shot_wb, content_hash, - xmp: lightcraft_meta::embedded(bytes).xmp, + xmp, orientation: Some(raw.orientation), preview_only: None, }); @@ -230,7 +248,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { as_shot_wb: None, content_hash, embedded_lens: None, - xmp: None, + xmp, orientation: m.orientation, preview_only: None, }) diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 958526b926..74e8aff66e 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -315,7 +315,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/import/job.rs b/crates/engine/src/import/job.rs index 8c44c82b96..0426af5ba9 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -288,6 +288,57 @@ impl ImportJob { Some(library) } + /// The batch's files the library already knows of, by path: a duplicate, a browsed file promoted (or a replaced + /// one probed again, noted in `changed`), the others left in `todo` to be probed. + fn sort_by_library( + &mut self, + files: Vec, + verdicts: Vec>, + local: bool, + out: &mut Prepared, + changed: &mut HashMap, + todo: &mut Vec, + ) { + use std::sync::atomic::Ordering::Relaxed; + for (f, verdict) in files.into_iter().zip(verdicts) { + match self.by_path.get(f.as_str()).cloned() { + Some((id, true, hash)) if !local => match verdict { + // ✕ before its size was looked at: nothing is decided about it, so it isn't promoted + Some(BrowsedFile::Unchecked) => {} + Some(BrowsedFile::Changed) => { + changed.insert(f.clone(), id); + todo.push(f); + } + Some(BrowsedFile::Unchanged) | None => { + out.items.push(self.promote_browsed(f, id, hash)); + self.done.fetch_add(1, Relaxed); + } + }, + Some((id, _, _)) => { + out.items.push(PreparedItem::Duplicate { path: f, existing: Some(id), reason: "path", hash: None, file: None }); + self.done.fetch_add(1, Relaxed); + } + None => todo.push(f), + } + } + } + + /// A browsed file this import brings into the library (its size unchanged): a duplicate of a library photo with + /// the same content, or promoted (and from then on the library's). + fn promote_browsed(&mut self, f: String, id: PhotoId, hash: Option) -> PreparedItem { + // a library photo with the same content comes first, and a file promoted earlier + // (here or in a previous batch) counts as the library's from then on + if let Some(h) = &hash { + if let Some(existing) = self.by_hash.get(h) { + return PreparedItem::Duplicate { path: f, existing: *existing, reason: "content", hash, file: None }; + } + self.by_hash.insert(h.clone(), Some(id)); + } + // a file that was only browsed (Local) joins the library when it is imported for real + self.by_path.insert(f, (id, false, hash)); + PreparedItem::Promote(id, None) + } + /// [`ImportJob::prepare`] for files [`ImportJob::expand`] returned. pub fn prepare_files(&mut self, files: Vec, cancel: &std::sync::atomic::AtomicBool) -> Prepared { use std::sync::atomic::Ordering::Relaxed; @@ -307,41 +358,7 @@ impl ImportJob { files.iter().filter(|f| is_browsed(f)).map(|f| (f.as_str(), self.local_sizes.get(f.as_str()).copied().unwrap_or(0))).collect(); let mut looked_at = browsed_files_changed(&browsed, cancel).into_iter(); let verdicts: Vec> = files.iter().map(|f| is_browsed(f).then(|| looked_at.next()).flatten()).collect(); - for (f, verdict) in files.into_iter().zip(verdicts) { - match self.by_path.get(f.as_str()).cloned() { - Some((id, true, hash)) if !opts.local => { - match verdict { - // ✕ before its size was looked at: nothing is decided about it, so it isn't promoted - Some(BrowsedFile::Unchecked) => continue, - Some(BrowsedFile::Changed) => { - changed.insert(f.clone(), id); - todo.push(f); - continue; - } - Some(BrowsedFile::Unchanged) | None => {} - } - // a library photo with the same content comes first, and a file promoted earlier - // (here or in a previous batch) counts as the library's from then on - if let Some(h) = &hash { - if let Some(existing) = self.by_hash.get(h) { - out.items.push(PreparedItem::Duplicate { path: f, existing: *existing, reason: "content", hash, file: None }); - self.done.fetch_add(1, Relaxed); - continue; - } - self.by_hash.insert(h.clone(), Some(id)); - } - // a file that was only browsed (Local) joins the library when it is imported for real - self.by_path.insert(f, (id, false, hash)); - out.items.push(PreparedItem::Promote(id, None)); - self.done.fetch_add(1, Relaxed); - } - Some((id, _, _)) => { - out.items.push(PreparedItem::Duplicate { path: f, existing: Some(id), reason: "path", hash: None, file: None }); - self.done.fetch_add(1, Relaxed); - } - None => todo.push(f), - } - } + self.sort_by_library(files, verdicts, opts.local, &mut out, &mut changed, &mut todo); // files a preceding scan already probed are not read again (a network share is slow to read), // as long as they are still there, as they were: a file gone or changed since is probed again @@ -425,22 +442,49 @@ impl ImportJob { plan.slots.push(Slot::Item(PreparedItem::Promote(id, Some(Box::new(info))))); 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 (a skipped duplicate needs only that time) let raw = info.kind == MediaKind::Raw; - let packet = if duplicate_of.is_some() && info.captured.is_some() && !opts.read_duplicates { + let has_embedded_xmp = raw || matches!(info.format.to_ascii_uppercase().as_str(), "JPEG" | "JPG" | "TIFF" | "TIF" | "PNG" | "WEBP"); + let skip_sidecar = duplicate_of.is_some() && info.captured.is_some() && !opts.read_duplicates; + let target = crate::crs::Target::for_file(info.kind, &info.format, info.preview_only.is_some(), &info.meta.camera); + let mut embedded_sidecar = if skip_sidecar { None } else { - found_sidecar.and_then(|f| std::fs::read_to_string(f).ok()).or_else(|| info.xmp.clone().filter(|_| raw)) + 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 + } + }) }; - 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), - 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 !raw && let Some(sc) = &mut embedded_sidecar { + sc.develop = None; + sc.warnings.clear(); + } + let external_sidecar = if skip_sidecar { + None + } else { + found_sidecar.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()); } @@ -469,6 +513,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 = if let Some(template) = opts.rename.as_deref().filter(|t| !t.trim().is_empty()) { let Some(seq) = self.seq else { self.done.fetch_add(1, Relaxed); diff --git a/crates/engine/src/media/session.rs b/crates/engine/src/media/session.rs index 9b0b0509fd..8e0cd85f5a 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -601,7 +601,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/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/sidecar.rs b/crates/engine/src/sidecar.rs index 1e89b7d537..b46f1a0d04 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -379,6 +379,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); + } + } + /// Take the orientation of the photo file at `original` (LightCraft shows the photo turned by it, and the packet /// may not repeat it) when the regions need it: they were drawn on a stated size ([`SidecarData::regions_drawn_on`]). /// Only then is the file read ([`file_orientation`]). 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); +} diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 60ebe8625d..c15c99411d 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -3900,6 +3900,295 @@ fn presets_apply_the_imported_profile_they_name() { let _ = std::fs::remove_dir_all(&src); } +#[test] +fn import_preserves_embedded_xmp_rating_and_label() { + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + 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() }; + 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.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); +} + +#[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 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(); + + 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); +} + +#[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); +} + +#[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); +} + +#[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}; diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index c569d3b9b5..31489ba476 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -609,7 +609,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/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 = ")); +} diff --git a/crates/meta/src/exif.rs b/crates/meta/src/exif.rs index c35b96856d..4eefbb6afa 100644 --- a/crates/meta/src/exif.rs +++ b/crates/meta/src/exif.rs @@ -68,6 +68,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)); @@ -80,8 +81,12 @@ 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)); } #[test] diff --git a/crates/pipeline/src/geometry.rs b/crates/pipeline/src/geometry.rs index 5d8a07489a..32516eaae2 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); @@ -312,8 +316,12 @@ 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; - let prefilter = (k > 1.25).then(|| (((ow as f64 / k).round() as usize).max(1), ((oh as f64 / k).round() as usize).max(1))); + // 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))); 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() { @@ -333,7 +341,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 +363,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 +451,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, @@ -529,6 +537,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/src/lib.rs b/crates/pipeline/src/lib.rs index cc19f7b31f..5d4fcf25dd 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -129,6 +129,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. @@ -162,6 +182,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 @@ -236,6 +258,7 @@ impl RenderRequest { proof: None, window: None, display: None, + downscale: Downscale::Smooth, } } @@ -491,7 +514,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 b21897073b..ed85e83c19 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. diff --git a/crates/pipeline/tests/sharp_downscale.rs b/crates/pipeline/tests/sharp_downscale.rs new file mode 100644 index 0000000000..da4fb57e09 --- /dev/null +++ b/crates/pipeline/tests/sharp_downscale.rs @@ -0,0 +1,42 @@ +//! 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}"); + } +} + +#[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}"); +} diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 694ef9b6dd..42f3eee1e4 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -329,7 +329,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 | 🚫 | | | @@ -807,6 +807,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-23 | minor | LR-BEHAV-RENDER-FIDELITY, LR-EDIT-LIGHT-SHADOWS, LR-EDIT-EFFECTS-TEXTURE, LR-EDIT-COLOR-GRADING, LRC-DEV-PROCESS: process V13 eases global Shadows off at large amounts, negative Texture and the Global grading wheel act less, fitted to Lightroom exports of real edits (#523); statuses and counts unchanged | | 2026-11-24 | minor | LR-REM-HEAL, LR-REM-CLONE, LRC-DEV-PROCESS: process V14 pins Heal and Remove spots to the photo on the spot's edge (membrane fill of the log ratio), matches the source's grain to its surroundings and reads every spot's source at whole pixels; statuses and counts unchanged | 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`.