LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Merge origin/main into smart-preview-look-version
Brandon Thomasb7e791a136b2
diff --cc crates/engine/src/tests_import.rsindex 6c0cc6b50,784200310..59bc3f404--- a/crates/engine/src/tests_import.rs+++ b/crates/engine/src/tests_import.rs@@@ -1106,148 -1125,53 +1125,199 @@@ fn folder_import_picks_up_undecodable_rlet _ = std::fs::remove_dir_all(&src);}+/// Rewrite the JSON header line of the smart preview at `file`.+fn edit_smart_header(file: &Path, edit: impl FnOnce(&mut Value)) {+ let bytes = std::fs::read(file).unwrap();+ let start = b"LCSP1\n".len();+ let nl = start + bytes[start..].iter().position(|b| *b == b'\n').unwrap();+ let mut head: Value = serde_json::from_slice(&bytes[start..nl]).unwrap();+ edit(&mut head);+ let mut out = bytes[..start].to_vec();+ out.extend_from_slice(head.to_string().as_bytes());+ out.extend_from_slice(&bytes[nl..]);+ std::fs::write(file, out).unwrap();+}++fn smart_header(file: &Path) -> Value {+ let bytes = std::fs::read(file).unwrap();+ let start = b"LCSP1\n".len();+ let nl = start + bytes[start..].iter().position(|b| *b == b'\n').unwrap();+ serde_json::from_slice(&bytes[start..nl]).unwrap()+}++/// A camera tone curve with a recognisable shape (`k` changes it).+fn test_tone(k: f32) -> lightcraft_pipeline::tone::CameraTone {+ lightcraft_pipeline::tone::CameraTone::new(std::array::from_fn(|i| {+ let x = 0.004 * 1.17f32.powi(i as i32);+ [x, 0.95 * (1.0 - (-k * x).exp())]+ }))+ .unwrap()+}++/// `plain`, but reporting `tone` as the camera look the (current) fit gives the file; counts its calls.+fn look_loader(+ plain: crate::media::FileLoader,+ tone: lightcraft_pipeline::tone::CameraTone,+ calls: std::sync::Arc<std::sync::atomic::AtomicUsize>,+) -> crate::media::FileLoader {+ std::sync::Arc::new(move |path, max_edge| {+ calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ let (img, mut info) = plain(path, max_edge)?;+ info.camera_tone = Some(tone);+ Ok((img, info))+ })+}++/// The follow-up to the camera tone curve change (#499): a smart preview keeps the look the fit+/// gave it, so one written by an older fit is rebuilt when its original is online, kept while the+/// original is offline, and not rebuilt again once current.+#[test]+fn smart_previews_from_an_older_look_fit_are_refreshed() {+ use std::sync::atomic::{AtomicUsize, Ordering};+ let src = temp_dir("smartlook-src");+ let lib = temp_dir("smartlook-lib");+ write_png(&src.join("a.png"), 3);+ let mut s = Session::new().with_fs();+ s.open_library(&lib, false).unwrap();+ s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()]})).unwrap();+ let id = s.active().unwrap();+ let file = s.media.smart_dir.clone().unwrap().join(crate::smart::file_name(s.catalog.photo(id).unwrap()));+ let (old, new) = (test_tone(1.5), test_tone(3.5));+ let calls = std::sync::Arc::new(AtomicUsize::new(0));+ let plain = s.media.file_loader.clone().unwrap();+ s.media.file_loader = Some(look_loader(plain.clone(), old, calls.clone()));+ let r = s.execute("library.smartPreviews", &json!({})).unwrap();+ assert_eq!((r["built"].as_u64(), r["refreshed"].as_u64()), (Some(1), Some(0)), "{r}");+ assert_eq!(smart_header(&file)["look_version"], json!(crate::camera_preview::LOOK_VERSION), "the writer stamps the fit version");+ assert!(!crate::smart::is_stale(&file));++ // current header: kept as it is, the original is not even read+ let before = std::fs::read(&file).unwrap();+ calls.store(0, Ordering::SeqCst);+ s.media.file_loader = Some(look_loader(plain.clone(), new, calls.clone()));+ let r = s.execute("library.smartPreviews", &json!({})).unwrap();+ assert_eq!((r["built"].as_u64(), r["refreshed"].as_u64()), (Some(1), Some(0)), "{r}");+ assert!(std::fs::read(&file).unwrap() == before, "a current proxy is not rebuilt");+ assert_eq!(calls.load(Ordering::SeqCst), 0);++ // an old header (no field), original offline: kept unchanged, and still marked stale+ edit_smart_header(&file, |h| {+ h.as_object_mut().unwrap().remove("look_version");+ });+ assert!(crate::smart::is_stale(&file), "no field = version 0");+ let old_bytes = std::fs::read(&file).unwrap();+ std::fs::rename(&src, src.with_extension("offline")).unwrap();+ s.media.forget(id);+ let r = s.execute("library.smartPreviews", &json!({})).unwrap();+ assert_eq!((r["built"].as_u64(), r["refreshed"].as_u64(), r["staleKept"].as_u64()), (Some(1), Some(0), Some(1)), "{r}");+ assert!(r["failed"].as_array().unwrap().is_empty(), "{r}");+ assert!(std::fs::read(&file).unwrap() == old_bytes, "offline: the stored preview and curve are untouched");+ assert!(crate::smart::is_stale(&file), "and it stays marked for the next time");+ assert_eq!(crate::smart::decode(&old_bytes).unwrap().1, Some(old), "the old look is still there");+ // ... and the opening refresh keeps it too+ crate::cmd::previews::refresh_stale_smart_previews(&mut s).unwrap().join().unwrap();+ assert!(std::fs::read(&file).unwrap() == old_bytes);++ // the original comes back: the library's next opening rebuilds it with the current look+ std::fs::rename(src.with_extension("offline"), &src).unwrap();+ calls.store(0, Ordering::SeqCst);+ crate::cmd::previews::refresh_stale_smart_previews(&mut s).unwrap().join().unwrap();+ assert_eq!(calls.load(Ordering::SeqCst), 1);+ assert_eq!(smart_header(&file)["look_version"], json!(crate::camera_preview::LOOK_VERSION));+ assert_eq!(crate::smart::decode(&std::fs::read(&file).unwrap()).unwrap().1, Some(new), "rebuilt with the current look");+ assert!(!crate::smart::is_stale(&file));+ // once only+ let rebuilt = std::fs::read(&file).unwrap();+ crate::cmd::previews::refresh_stale_smart_previews(&mut s).unwrap().join().unwrap();+ let r = s.execute("library.smartPreviews", &json!({})).unwrap();+ assert_eq!((r["refreshed"].as_u64(), calls.load(Ordering::SeqCst)), (Some(0), 1), "{r}");+ assert!(std::fs::read(&file).unwrap() == rebuilt);++ // Build Smart Previews refreshes a stale one the same way+ edit_smart_header(&file, |h| h["look_version"] = json!(0));+ s.media.file_loader = Some(plain);+ let r = s.execute("library.smartPreviews", &json!({})).unwrap();+ assert_eq!(r["refreshed"], 1, "{r}");+ assert_eq!(crate::smart::decode(&std::fs::read(&file).unwrap()).unwrap().1, None, "this fit gives no curve: none is kept");+ let _ = std::fs::remove_dir_all(&src);+ let _ = std::fs::remove_dir_all(&lib);+}++/// A hostile or damaged `look_version` never panics: anything that is not a non-negative integer+/// counts as 0 (rebuilt when the original is online); a version from a newer build is left alone.+#[test]+fn malformed_smart_preview_look_versions_are_handled() {+ let dir = temp_dir("smartlook-bad");+ let img = lightcraft_scenes::demo_library()[0].render(32, 20);+ let file = dir.join("a.lcsp");+ std::fs::write(&file, crate::smart::encode(&img, None).unwrap()).unwrap();+ let cur = u64::from(crate::camera_preview::LOOK_VERSION);+ for bad in [json!("1"), json!(-1), json!(1.5), json!(null), json!([]), json!({}), json!(true), json!(1e30), json!(-0.0)] {+ let shown = bad.to_string();+ edit_smart_header(&file, |h| h["look_version"] = bad);+ assert!(crate::smart::is_valid(&file), "{shown}");+ assert!(crate::smart::is_stale(&file), "{shown} counts as version 0");+ assert!(crate::smart::decode(&std::fs::read(&file).unwrap()).is_ok(), "{shown}");+ }+ for fine in [json!(cur), json!(cur + 1), json!(u64::MAX)] {+ let shown = fine.to_string();+ edit_smart_header(&file, |h| h["look_version"] = fine);+ assert!(!crate::smart::is_stale(&file), "{shown}");+ }+ // not a header at all, or missing+ assert!(!crate::smart::is_stale(&dir.join("missing.lcsp")));+ std::fs::write(&file, b"LCSP1\n{not json\n\xFF\xD8").unwrap();+ assert!(!crate::smart::is_stale(&file));+ let _ = std::fs::remove_dir_all(&dir);+}+++ #[test]+ fn a_file_gone_since_the_import_review_is_not_imported() {+ let src = temp_dir("gone-since-review");+ write_png(&src.join("a.png"), 1);+ write_png(&src.join("b.png"), 2);+ let mut s = Session::new().with_fs();+ s.execute("library.importPreview", &json!({"paths": [src.to_string_lossy()]})).unwrap();+ std::fs::remove_file(src.join("b.png")).unwrap();+ let r = s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy(), src.join("b.png").to_string_lossy()]})).unwrap();+ assert_eq!((ids(&r, "imported"), ids(&r, "failed")), (1, 1), "{r}");+ assert_eq!(s.catalog.len(), 1, "no photo for a file that isn't there");+ let _ = std::fs::remove_dir_all(&src);+ }++ /// A HEIC laid out like an iPhone's (a grid of HEVC pictures, a Display P3 profile, a quarter turn+ /// in the container, a thumbnail) imports as a normal photo that develops and exports upright like+ /// a JPEG. In a build without the codecs' `heif` feature it is reported as failed, saying why.+ #[test]+ fn heic_imports_as_a_normal_photo_or_says_why_not() {+ use lightcraft_heif::testdata::{Prop, Spec, build};+ let src = temp_dir("heic");+ let photo = |x: u32, y: u32| [((x * 7 + y * 13) % 200 + 30) as u16, 110, 150];+ let p3 = lightcraft_codecs::icc::write_named(lightcraft_codecs::NamedSpace::DisplayP3);+ let bytes = build(&Spec { props: vec![Prop::Icc(p3), Prop::Irot(1)], thumbnail: Some(&photo), ..Spec::new(96, 64, &photo) });+ std::fs::write(src.join("IMG_0001.HEIC"), &bytes).unwrap();+ let mut s = Session::new().with_fs();+ let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap();+ if !lightcraft_codecs::Format::Heif.can_decode() {+ assert_eq!((ids(&r, "imported"), ids(&r, "failed")), (0, 1), "{r}");+ assert!(r["failed"].to_string().contains("isn't included in this build"), "{r}");+ let _ = std::fs::remove_dir_all(&src);+ return;+ }+ assert_eq!((ids(&r, "imported"), ids(&r, "failed")), (1, 0), "{r}");+ let p = s.catalog.photos().next().unwrap();+ let id = p.id;+ // Upright (the container's turn applied) and not preview-only.+ assert_eq!((p.kind, p.preview_only.clone(), p.width, p.height), (lightcraft_catalog::MediaKind::Image, None, 64, 96));+ s.execute("library.select", &json!({"ids": [id.0], "active": id.0})).unwrap();+ let plain = crate::export::export_photo(&mut s, id, &crate::export::ExportOptions::from_json(&json!({"format": "png"})), 1).unwrap();+ assert_eq!((plain.width, plain.height), (64, 96));+ s.execute("develop.set", &json!({"control": "light.exposure", "value": 1.0})).unwrap();+ let brighter = crate::export::export_photo(&mut s, id, &crate::export::ExportOptions::from_json(&json!({"format": "png"})), 1).unwrap();+ let mean = |png: &[u8]| {+ let d = lightcraft_codecs::decode(png, Default::default()).unwrap();+ d.image.data.iter().map(|p| p[1]).sum::<f32>() / d.image.data.len() as f32+ };+ assert!(mean(&brighter.bytes) > mean(&plain.bytes) * 1.3, "exposure +1 brightens the HEIC");+ let _ = std::fs::remove_dir_all(&src);+ }diff --cc docs/camera-preview-colour.mdindex d17cb792c,813b1e162..accbeac15--- a/docs/camera-preview-colour.md+++ b/docs/camera-preview-colour.md@@@ -74,21 -78,27 +78,39 @@@ This is a per-file camera-look estimateOne photo can show too little of a colour for its own fit to learn it: in a second shot of the lime shirt only a few dozen proxy pixels show it, next to a hillside of foliage at the same hue that the camera renders differently, and the shirt stayed yellow (hue 68° against the JPEG's 82°; a 192-pixel proxy only reached 74°). `lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS…` therefore pools the colour pairs of many ARWs, NEFs or RAFs per camera model — each against its own embedded JPEG, at a 192-pixel proxy, at most 4000 pairs per photo, files spread evenly over the folders — and fits one matrix (from white-balanced camera RGB, so no single photo's white point is baked in) and one hue/saturation/value table. Models need at least 5 usable photos.- Profiles are JSON files `<model>.json` in `$LIGHTCRAFT_CAMERA_PROFILES`, else `<config>/camera-profiles` (macOS `~/Library/Application Support/LightCraft/camera-profiles`); a local profile replaces a built-in one. Built-in profiles live in `assets/camera-profiles/` (listed in `assets/ATTRIBUTION.md`) and are compiled in, so the app, CLI and web build share them: ILCE-7M4, fitted to 597 photos (2.2 million colour pairs) shot in 2026, mostly with the Standard creative style and DRO Auto; X-H2S, 201 photos; X-T4, 545 photos. They hold aggregate colour statistics only. A photo of a profiled model takes its colour from the profile and fits only its own tone and chroma curves (DRO and picture styles vary per shot); the acceptance gates still apply. A rejected profile fit retries the photo's own colour and tone fit before falling back to neutral rendering. Files are read once per process and validated (version, bounded invertible matrix, table shape and finite data); a damaged file is ignored with a warning. The profiles folder's contents are part of the render cache keys, so thumbnails rendered before a profile existed are redone; smart previews built before keep their colour until rebuilt.+ Profiles are JSON files `<model>.json` in `$LIGHTCRAFT_CAMERA_PROFILES`, else `<config>/camera-profiles` (macOS `~/Library/Application Support/LightCraft/camera-profiles`); a local profile replaces a built-in one. Built-in profiles live in `assets/camera-profiles/` (listed in `assets/ATTRIBUTION.md`) and are compiled in, so the app, CLI and web build share them: ILCE-7M4, fitted to 597 photos (2.2 million colour pairs) shot in 2026, mostly with the Standard creative style and DRO Auto; ILCE-7CR, 125 photos (below); X-H2S, 201 photos; X-T4, 545 photos. They hold aggregate colour statistics only. A photo of a profiled model takes its colour from the profile and fits only its own tone and chroma curves (picture styles vary per shot; with Sony's DRO on, that tone curve is then lowered as described below); the acceptance gates still apply. A rejected profile fit retries the photo's own colour and tone fit before falling back to neutral rendering. Files are read once per process and validated (version, bounded invertible matrix, table shape and finite data); a damaged file is ignored with a warning. The profiles folder's contents are part of the render cache keys, so thumbnails rendered before a profile existed are redone; smart previews built before keep their colour until rebuilt.+++ ### Sony ILCE-7CR++ Fitted from 125 usable photos of 131 ILCE-7CR ARWs (one photographer, September 2025 to September 2026, Standard creative style with DRO off, Lv3 or Auto; 127 uncompressed, 2 compressed, 2 lossless compressed), 448,230 colour pairs. Measured as above: rendered at 1200 px with `lightcraft-cli render`, mean CIE76 ΔE against each file's embedded JPEG at 200 px.++ Without a profile, 123 of the 131 photos accept their own fit; the other 8 open with the neutral fallback at ΔE 6–26. For validation every fifth photo in sorted name order (26) was withheld and a profile fitted to the other 105 (100 usable). On the withheld photos mean ΔE went from 4.07 with per-file fitting to 3.29 with the profile. Both withheld photos whose own fit is rejected are accepted (ΔE 26.0 → 6.1 on a night scene, 6.2 → 5.5). Withheld photos whose own fit was accepted are about unchanged and move both ways: 12 of 24 improve, mean ΔE 3.06 → 3.08, largest regression 1.8. On that photo (gold tinsel bokeh) the profile turns a blue light blue again where the per-file fit had made it teal, but renders the gold slightly more saturated than the camera. With the final profile all 131 photos are accepted, and the 8 previously rejected ones land at ΔE 1.3–5.7; that comparison is in-sample.++ The nine public raw.pixls.us ILCE-7CR files are one scene in every coding the camera writes (uncompressed, lossless compressed L, M and S, compressed, full frame and APS-C crop). They were not used for fitting. All nine accept their own fit at ΔE 1.3–2.1 and stay accepted with the profile, at ΔE 1.5–2.9 (mean 1.59 → 1.99). On this colourful daylight scene the per-file fit is already close. The subsampled M and S codings, which decode with unity white-balance gains, move most (2.0 → 2.8). This is a camera-JPEG look estimate like the others, not measured calibration or Lightroom parity.+ ## Sony Dynamic Range Optimizer (DRO)++ Sony bodies apply DRO, a local tone operator that brightens darker regions, to their JPEG (and the preview embedded in the ARW) only; the raw data are unchanged, and the factory default is DRO Auto. The tone curve fitted to that JPEG carried the brightening into the raw's starting look, so DRO photos opened lighter than in Lightroom, darktable, Photomator or Affinity, which develop the raw without it (issue #244). On 24 ILCE-7CR photos (Standard creative style) with Lightroom 9.5.1 default exports, mean L* at 200 px: with DRO off, Lightroom matches the camera JPEG (+0.15 L*, all within ±1.4) and LightCraft matches Lightroom (−0.19 L*, median ΔE76 3.6); with DRO Lv3 or Auto (8 photos), Lightroom is 2.4–10.7 L* darker than the camera JPEG and LightCraft followed the JPEG, +6.4 L* from Lightroom (median ΔE76 7.5). The tone curves fitted to 131 ILCE-7CR photos show where: at scene luminance 0.01, 0.02, 0.05 and 0.1 the median DRO Lv3/Auto curve is 8, 10, 9 and 6 L* above the DRO-off one, and from 0.3 up they agree.++ The ARW decoder reads the setting from maker-note tag `0xb025` (ExifTool's Sony tag documentation: 0 Off; 1 Standard, 2 Advanced Auto, 3 Auto, 8–12 Advanced Lv1–5, 16–23 Lv1–8; other values are treated as unknown). It was present on all 264 Sony raws checked (98 bodies, DSLR-A100 to ILCE-7CR); the second tag of that name, `0xb04f`, only says off or on and is missing on the older bodies. With DRO on, the look keeps the colour fitted to the JPEG (matrix, hue/saturation table, chroma curve) and its tone curve is lowered, knot by knot, to Sony's curve without DRO wherever that is darker (`assets/camera-tone/sony-dro-off.json`, listed in `assets/ATTRIBUTION.md`). Past its last knot a curve continues as a shoulder whose rate comes from its last two knots, so the second-last knot is lowered only as far as keeps that shoulder at or below the fitted one; the result is never brighter than the fitted curve at any scene luminance. Sony's curve is quantile-matched, as one photo's tone is, over the pooled pairs of 12 CC0 raw.pixls.us ARWs shot with DRO off and the Standard creative style on 10 interchangeable-lens bodies (ILCE-3500, -5000, -6600, -7M3, -7S, -7CR, -9M2, ILCA-77M2, SLT-A57, NEX-F3; the file lists their URLs and SHA-256); pooled the same way from 55 private ILCE-7CR photos with DRO off, the curve differs by at most 1.2 L* between scene luminance 0.01 and 0.5. DRO only brightens, so the photo's own curve bounds the curve without it from above: the 1″ compacts map raw values darker (with DRO off, the DSC-RX100M2, -RX100M5 and -RX10M4 curves lie 8–16 L* below Sony's at scene luminance 0.18) and keep their own curve where it is the darker one. Photos with DRO off or unknown, and other makers, are unchanged.++ Measured before → after (mean L* and CIE76 ΔE at 200 px): on the 24 ILCE-7CR photos with Lightroom references, the 8 with DRO on go from +6.4 L* (+4.4 to +10.5) to +0.8 L* (−0.4 to +1.9) against Lightroom's default, median ΔE 7.5 → 3.3; by Lightroom lightness band (L* 0–25, 25–50, 50–75, 75–100) they now differ from it by +2.3, +1.4, −0.8 and −3.0 L* (before +7.8, +9.4, +3.8, −0.8), like the 16 with DRO off (+2.5, −0.1, −2.0, −3.2), which render byte-identically. Of all 131 ILCE-7CR photos, the 56 fitted with DRO on now render 6.1 L* darker than their camera JPEGs on average (0.3 lighter before), as Lightroom renders the measured ones 5.7 L* darker; the 71 with DRO off are byte-identical. Of 116 CC0 Sony files from 100 bodies, 79 were shot with DRO on (71 of them Auto); the 57 changed of the 69 fitted ones render 2.1 L* darker on average (at most 10.8), the 12 others (six compacts, four ILCE-7M4 shots in Vivid, an ILCE-1 and an ILCE-7RM4, whose own curves are already darker) and all 35 DRO-off files are unchanged. The issue's ILCE-7M3 file goes from +0.8 to −6.5 L* against its camera JPEG. Applied to photos shot with DRO off, whose JPEG shows the camera's own curve, the rule would move the 68 fitted ILCE-7CR photos by −0.4 L* (median; at most −4.1) and 25 of 28 fitted CC0 ones by at most −1.8 L*; the exceptions are an ILCE-3500 (−4.7) and the cine bodies FX3 and FX30 (−7.2 and −5.1), whose picture profiles are not the Standard style.++ Picture styles other than Standard are lowered to the Standard curve too where it is darker; Lightroom ignores them as well. Nikon Active D-Lighting, Canon Auto Lighting Optimizer and Fujifilm D-Range settings are likely to have the same effect and are not handled yet. Render cache version 23 redraws thumbnails; smart previews built before keep the brightened tone curve in their header until rebuilt.+## Smart previews and the look version++A smart preview keeps the result of the fit twice: the colour matrix is baked into its pixels and the tone and chroma curves are stored in its header. When the fit changes, a preview built earlier keeps the old look until it is rebuilt, and the render cache version does not reach it (renders are keyed on the library's files, proxies are files of their own).++The fit therefore has a version, `LOOK_VERSION` in `crates/engine/src/camera_preview.rs`, and every smart preview records the version that wrote it in its header line (`look_version`). **Bump the constant in any change that makes the fit give a different result for the same file**: the matrix, hue/saturation, tone or chroma fit, their gates and fallbacks, or how a camera profile feeds them. Changes that leave the fitted look alone don't need it. A header without the field (everything built before it existed) counts as version 0, and so does a value that is not a non-negative integer; a value from a newer build is left alone.++A proxy older than the constant is brought up to date by the existing Build Smart Previews path (`smart_run`), which also repairs damaged proxies:++- when the library is opened, a background thread looks at the existing proxies and rebuilds the stale ones from their originals (no proxy is created, nothing is shown, the UI never waits on a drive);+- Build Smart Previews does the same for the photos it is run on (`refreshed` in its result);+- when the original can't be read (offline drive), the proxy and its curve are kept exactly as they are. The old version in its header is the mark: the next opening, or the next Build Smart Previews, with the original online rebuilds it. A rebuilt proxy carries the current version, so nothing is rebuilt twice. A proxy is only ever rebuilt from the original, never from another proxy.+## Nikon crop and preview colour metadataNikon maker-note `CropArea` (0x0045) supplies the default `[left, top, width, height]` crop. The decoder validates the rectangle against the active sensor area and falls back to that area for missing or invalid values. The CFA origin is unchanged; cropping follows demosaicing.