diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a9d4d065a3..b6ad6bfb69 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,15 +12,21 @@ on: type: string default: "" -permissions: - contents: write - packages: write +# Nothing by default; each job names what it needs. Only `release` writes (the draft GitHub Release +# and its packages). +permissions: {} concurrency: group: release-${{ github.ref }} cancel-in-progress: false jobs: + # Regenerates contributors/contributors.json for the release commit; every build bundles it. + credits: + permissions: + contents: read + pull-requests: read + uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main git-sources: name: Git dependencies come from storytold runs-on: ubuntu-latest @@ -61,7 +67,10 @@ jobs: PY release: - needs: git-sources + needs: [git-sources, credits] + permissions: + contents: write + packages: write # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: @@ -70,6 +79,7 @@ jobs: craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 web-craft-fonts: true version: ${{ inputs.version }} + contributors-artifact: ${{ needs.credits.outputs.artifact-name }} secrets: APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} diff --git a/Cargo.lock b/Cargo.lock index acd433bc27..1d824dde9d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1246,7 +1246,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a231e517c3b371e1bf0ee8af71ed807424a9a05d#a231e517c3b371e1bf0ee8af71ed807424a9a05d" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "chrono", "dunce", @@ -3744,6 +3744,7 @@ dependencies = [ "ab_glyph", "chrono", "craft-docpath", + "crc32fast", "fs4", "harfrust 0.13.3", "jxl-oxide", diff --git a/Cargo.toml b/Cargo.toml index 8549d6167e..2215751be9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,7 @@ craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-l # Canon CRW decoder shared with the other Craft apps craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "f3b62ec61f45534392376492fc5ad33047375205" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a231e517c3b371e1bf0ee8af71ed807424a9a05d", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } # internal lightcraft-denoise-core = { path = "crates/denoise-core" } diff --git a/README.md b/README.md index 21ff4306ec..a3e4981360 100644 --- a/README.md +++ b/README.md @@ -350,7 +350,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det Fujifilm / Nikon / older-Canon raws on one machine; see [docs/raw-parity.md](docs/raw-parity.md) for your camera. - **The biggest gaps:** - **camera colour calibration:** Sony, Nikon, Panasonic, Fujifilm and Canon CR3 and CRW raws have guarded estimates from their camera JPEGs, with built-in Canon EOS D60, ILCA-99M2, ILCE-7CR, ILCE-7M4, ILCE-7RM5, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300 profiles; measured calibration covers one model so far (chart-measured matrices for the Canon EOS D60), and other raws or rejected fits retain a neutral matrix; - - **unsupported CR3 variants and Nikon High Efficiency NEFs:** these use embedded JPEG previews when present. Olympus compressed ORF now decodes sensor data on 58 more bodies (2 verified) ([docs/orf-compression.md](docs/orf-compression.md)); Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md); + - **unsupported CR3 variants and Nikon High Efficiency NEFs:** these use embedded JPEG previews when present. Olympus compressed ORF is unsupported for sensor decoding and uses embedded JPEG previews when available ([docs/orf-compression.md](docs/orf-compression.md)); Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md); - **AI quality and model setup:** Subject and Sky selection are classical heuristics; Object/Describe use an optional SAM 3 model. AI Denoise supports Bayer RAW with separately installed weights, while X-Trans and linear-RGB denoise and Super Resolution remain missing; see [AI masks](docs/ai-masks.md) and [AI Denoise](docs/denoise.md); @@ -370,7 +370,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det | Profiles (Color, Neutral, Vivid, Landscape, Portrait, Monochrome: our own looks), presets, versions, history, copy/paste/sync settings | ✅ | | Camera colour: DNG matrices, guarded camera-JPEG look fits and built-in profiles for selected cameras | 🚧 measured calibration and per-model coverage remain incomplete ([raw parity](docs/raw-parity.md)) | | Native macOS menu bar (generated from the command registry), control channel + every widget addressable, headless UI snapshots | ✅ | -| RAW: DNG, CR2, CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW), ARW, NEF (uncompressed + lossless/lossy compressed, incl. lossy after split), Fujifilm RAF (uncompressed + lossless/lossy compressed, Bayer + X-Trans), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format, DMC-LX1 to DC-S1RM2), Pentax PEF, Olympus ORF (uncompressed, 12.8 bpp, compressed), Samsung SRW (uncompressed); embedded previews for every format incl. CR3 | 🚧 · other CR3 variants, compressed SRW and Nikon HE NEF decode ⬜ ([raw parity](docs/raw-parity.md)) | +| RAW: DNG, CR2, CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW), ARW, NEF (uncompressed + lossless/lossy compressed, incl. lossy after split), Fujifilm RAF (uncompressed + lossless/lossy compressed, Bayer + X-Trans), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format, DMC-LX1 to DC-S1RM2), Pentax PEF, Olympus ORF (uncompressed, 12.8 bpp), Samsung SRW (uncompressed); embedded previews for every format incl. CR3 | 🚧 · other CR3 variants, compressed ORF / SRW and Nikon HE NEF decode ⬜ ([raw parity](docs/raw-parity.md)) | | Detail: sharpening, luminance + colour noise reduction | ✅ · AI Denoise 🚧 (Bayer, user-installed weights; [setup](docs/denoise.md)), Super Resolution ⬜ | | Remove / Heal / Clone spots (auto source), non-generative Fill, editable spot pins, Visualize Spots, Red Eye and Pet Eye | ✅ · Fill uses PatchMatch; no generative fill | | Export: JPEG / PNG / TIFF / flat PSD / WebP / AVIF / JPEG XL / raw or rendered DNG / original, sizing, file-size limit, output sharpening, naming templates, batch, metadata policy, text or image watermark | ✅ | diff --git a/ROADMAP.md b/ROADMAP.md index 8804f42701..ee50aed31b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -30,7 +30,7 @@ Each audience with its own hours (Opus 5.5 agent wall-clock hours to ~95%): The gap between breadth and readiness is quality and coverage, not missing buttons: camera colour is estimated rather than measured, CR3 decodes on 26 verified Canon bodies (rarer CRX variants still open as previews), HE NEF opens -as preview (compressed ORF now decodes on 58 more bodies (2 verified)), rendering is tuned by eye, AI masks are heuristics, there is no lens database, and +as preview, as does compressed ORF when an embedded preview is available; rendering is tuned by eye, AI masks are heuristics, there is no lens database, and tests run in CI on Linux x64 (every pull request and push to `main`) and FreeBSD (nightly), not on macOS or Windows. **Why alpha:** core workflows run end to end, but readiness is below the ~75% beta bar (it is above the ~40% alpha bar) and Lightroom's main inputs, raw files, still have gaps (Nikon HE NEF opens as preview; Canon, ~30% of raw users, decodes CR3 on 26 verified bodies). It passes the alpha gate: all six core workflows @@ -107,14 +107,16 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/ 3. Render-fidelity suite against Lightroom, then tuning (30–60 h) 4. ~~Full-resolution zoom~~ (done 2026-10-12) 5. AI masks: Subject / Sky / People (40–70 h + model decision) -6. ~~Compressed ORF~~ (done 2026-11-04) and HE NEF (20–40 h) +6. Compressed ORF (support withdrawn; estimate pending provenance review) and HE NEF (20–40 h) 7. Lens profile database of our own (40–80 h, #329) 8. Tests in CI on macOS and Windows, and the GPU tests in CI (6–12 h) 9. Per-model raw verification (20–35 h) ## Progress log -- 2026-11-04: Olympus / OM System compressed ORF decodes from sensor data: clean-room pure-Rust bitstream decoder (`crates/raw/src/vendor/orfc.rs`) derived strictly from Olympus patents US7333035B2/US7715639B2, maker notes and CC0 samples without third-party decoder code (see `docs/orf-compression.md`), verified on OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) CC0 samples; 58 bodies newly unlocked (78 total across Olympus and OM; OM/Olympus 6% → 81% fully working, overall weighted camera coverage 94% → 97%). +- 2026-11-07: Compressed ORF support withdrawn pending provenance review; uncompressed support remains. Regenerated camera coverage: 557 verified, 665 unverified, 187 preview-only and 37 unsupported; 94% use-weighted coverage. See [ORF status](docs/orf-compression.md). + +- 2026-11-04: Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. - 2026-10-22: Print page setup and PDF output gain the Japanese photo and postcard papers — L判 (89 × 127 mm), 2L判 (127 × 178), KG判 (102 × 152), はがき (100 × 148), 往復はがき (148 × 200), 六切 (203 × 254), 四切 (254 × 305) and 名刺 (55 × 91) — at their exact metric sizes. The Print dialog diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 3a7bda6696..97479ad68a 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -201,6 +201,10 @@ impl eframe::App for App { // app after this and the session's last writes (face data) still go out under the lock. #[cfg(target_os = "macos")] self.0.session.release_library_lock(); + // macOS only: the process ends below without dropping the app, so a ready update's helper + // starts here. Elsewhere dropping the app starts it. + #[cfg(target_os = "macos")] + self.0.start_pending_update(); // macOS (#1331): end the process here, before eframe tears the window down, as Quit from // the menu bar already does (PR #444). AccessKit's macOS adapter subclasses the window's // content view and restores its class on teardown; AppKit's Touch Bar support observes diff --git a/apps/lightcraft/src/session.rs b/apps/lightcraft/src/session.rs index c02ce47a1e..52a5a5ba03 100644 --- a/apps/lightcraft/src/session.rs +++ b/apps/lightcraft/src/session.rs @@ -49,7 +49,7 @@ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std:: pick_lightroom_catalog: Some(Box::new(|| { file_dialog() .set_title(lightcraft_ui_egui::i18n::tr("Import Lightroom Catalog")) - .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Lightroom Classic Catalog"), &["lrcat"]) + .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Lightroom Classic Catalog"), &["lrcat", "zip"]) .pick_file() .map(|p| p.to_string_lossy().to_string()) })), diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index 75ec07e59f..fc93ea9f13 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -64,6 +64,7 @@ //! | 10 | masks stay on the photo under lens corrections, Upright and Transform | `Mask.on_photo` (develop settings) | //! | 11 | lens database profiles named in the Optics panel | `EmbeddedLens.source` | //! | 12 | history steps and versions share segmentation grids (#2154) | `Catalog.grids`, `SegMask.grid` | +//! | 13 | Lens Blur | `DevelopSettings.lens_blur`, `Mask.adjust.lens_blur` | //! //! Rules: //! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a @@ -88,7 +89,7 @@ pub const LOG: &str = "catalog.log"; const FORMAT: &str = "lightcraft-catalog"; /// The catalog format this build writes (and the newest it reads). See the module docs → /// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added. -pub const VERSION: u32 = 12; +pub const VERSION: u32 = 13; /// When [`Journal::wants_snapshot`] says it's time to compact the log. #[derive(Clone, Copy, Debug)] diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 5a82d2a67d..f106e753f7 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -221,8 +221,8 @@ pub enum Op { /// `None` = its raw data decodes (or it isn't a raw). #[serde(default, skip_serializing_if = "Option::is_none")] preview_only: Option, - /// The app version that decided `preview_only` (see [`Photo::preview_checked`]); empty - /// when it is `None`. + /// The app version that decided `preview_only` (see [`Photo::preview_checked`]); also + /// retained for supported ORF files so their withdrawal recheck runs only once. #[serde(default, skip_serializing_if = "String::is_empty")] preview_checked: String, }, diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index ebf2d1ef08..37749e5f1f 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -316,10 +316,10 @@ pub struct Photo { /// picture style baked in — so it is treated as a rendered (non-raw) source. #[serde(default, skip_serializing_if = "Option::is_none")] pub preview_only: Option, - /// The app version (`CARGO_PKG_VERSION`) whose decoder set [`Photo::preview_only`]; empty when - /// it isn't set, and in catalogs from before format v9. A preview-only photo whose stamp - /// differs from the running version is rechecked when its library opens (issue #662): newer - /// builds may decode the file, older ones may decode less. + /// The app version (`CARGO_PKG_VERSION`) whose decoder checked [`Photo::preview_only`]. + /// Also set for supported ORF files: compressed ORF support was withdrawn after #3775, so + /// old sensor-decodable records need rechecking too. Empty for other supported formats and + /// legacy records. A stale stamp is rechecked when the library opens (issue #662). #[serde(default, skip_serializing_if = "String::is_empty")] pub preview_checked: String, /// A Local record: the fingerprint of its state when the browse catalogued it, to tell @@ -429,13 +429,18 @@ impl Photo { } /// Sets [`Photo::preview_only`] as this build decided it, with its stamp. pub fn set_preview_only(&mut self, preview_only: Option) { - self.preview_checked = preview_stamp(&preview_only); + self.preview_checked = self.preview_stamp(&preview_only); self.preview_only = preview_only; } - /// A preview-only photo whose flag was set by another app version (or before stamps existed), - /// so this build should probe its file again (issue #662). + /// The stamp for a fresh probe. Supported ORFs keep it too, so the support-withdrawal + /// recheck runs once, without repeatedly probing uncompressed ORFs on every library open. + pub fn preview_stamp(&self, preview_only: &Option) -> String { + if self.format.eq_ignore_ascii_case("orf") { APP_VERSION.to_string() } else { preview_stamp(preview_only) } + } + /// A preview-only photo or ORF whose support was checked by another app version (or before + /// stamps existed), so this build should probe its file again (issues #662 and #3775). pub fn preview_only_stale(&self) -> bool { - self.preview_only.is_some() && self.preview_checked != APP_VERSION + (self.preview_only.is_some() || self.format.eq_ignore_ascii_case("orf")) && self.preview_checked != APP_VERSION } /// A raw file developed from its sensor data: not a rendered image, and not a raw shown from /// its embedded preview ([`Photo::preview_only`]). diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rs index 19817d78da..8688d87a30 100644 --- a/crates/catalog/src/tests.rs +++ b/crates/catalog/src/tests.rs @@ -12,6 +12,26 @@ fn photo(c: &mut Catalog, name: &str, date: &str) -> PhotoId { id } +/// ORF probes record both supported and preview-only outcomes, without changing other formats. +#[test] +fn orf_support_checks_keep_a_stamp_even_when_sensor_data_decodes() { + let mut p = Photo::new(PhotoId(1), Source::File { path: "a.orf".into() }, "a.orf", "ORF", 4, 3, "2026-01-01"); + p.kind = MediaKind::Raw; + assert!(p.preview_only_stale(), "legacy supported ORF needs the withdrawal recheck"); + p.set_preview_only(None); + assert_eq!(p.preview_checked, APP_VERSION); + assert!(!p.preview_only_stale()); + assert!(p.develops_raw(), "supported uncompressed ORF remains sensor-decodable"); + p.set_preview_only(Some("Olympus compressed ORF".into())); + assert_eq!(p.preview_checked, APP_VERSION); + assert!(!p.preview_only_stale()); + assert!(!p.develops_raw()); + p.format = "DNG".into(); + p.set_preview_only(None); + assert!(p.preview_checked.is_empty(), "other supported formats keep their existing semantics"); + assert!(!p.preview_only_stale()); +} + #[test] fn date_token_matches_time_part_case_insensitively() { let mut c = Catalog::new(); diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index 612ee4586b..248933a4a2 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -238,9 +238,9 @@ fn op_variants_are_versioned() { Op::SetHistoryCursor { .. } => 8, } } - /// v12: `Catalog.grids` and `SegMask.grid`, shared by a snapshot's masks (#2154) (v11: `EmbeddedLens.source`; v10: `Mask.on_photo`; v9: - /// `Photo.preview_checked` and `Op::SetContent.preview_checked`). - const NEWEST_FIELDS: u32 = 12; + /// v13: Lens Blur in develop settings and mask adjustments (v12: `Catalog.grids` and `SegMask.grid`; v11: `EmbeddedLens.source`; + /// v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`). + const NEWEST_FIELDS: u32 = 13; let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None }); assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version"); } diff --git a/crates/codecs/src/encode.rs b/crates/codecs/src/encode.rs index 8aff31c5cb..82f654adf2 100644 --- a/crates/codecs/src/encode.rs +++ b/crates/codecs/src/encode.rs @@ -39,12 +39,16 @@ impl<'a> EncodeImage<'a> { if self.width == 0 || self.height == 0 { return Err(Error::Encode("zero dimension".into())); } - let need = self.width as u64 * self.height as u64 * self.channels as u64; + // u128: 2^32 x 2^32 x 4 does not fit u64, and every later `width * height * channels` is bounded by this + let need = self.width as u128 * self.height as u128 * self.channels as u128; + if need > usize::MAX as u128 { + return Err(Error::Encode("image too large".into())); + } let have = match self.samples { Samples::U8(s) => s.len(), Samples::U16(s) => s.len(), Samples::F32(s) => s.len(), - } as u64; + } as u128; if have < need { return Err(Error::Encode(format!("sample buffer too short: {have} < {need}"))); } @@ -671,6 +675,13 @@ fn avif_10bit(enc: &ravif::Encoder, img: &EncodeImage, s: &[u16]) -> Result u16::MAX as usize || gain.height > u16::MAX as usize { + return Err(Error::Encode("JPEG dimensions are limited to 65535".into())); + } if !m.is_valid() || m.multichannel != (gain.channels == 3) { return Err(Error::Encode("gain map metadata doesn't match the map".into())); } @@ -786,6 +790,21 @@ mod tests { } } + #[test] + fn a_gain_map_wider_than_a_jpeg_allows_is_refused() { + let base = [0u8; 3]; + let gain = GainImage { width: 65_536, height: 1, channels: 1, data: vec![0; 65_536] }; + let r = encode_jpeg( + &EncodeImage::new(1, 1, 3, Samples::U8(&base)), + &gain, + &GainMapMeta::default(), + 90, + ChromaSubsampling::S444, + &EncodeMeta::default(), + ); + assert!(matches!(r, Err(Error::Encode(m)) if m.contains("65535"))); + } + #[test] fn jpeg_round_trip_and_container_structure() { let (w, h) = (96, 64); diff --git a/crates/codecs/src/jpeg_par.rs b/crates/codecs/src/jpeg_par.rs index 763b73afa1..cc2d41629a 100644 --- a/crates/codecs/src/jpeg_par.rs +++ b/crates/codecs/src/jpeg_par.rs @@ -401,6 +401,12 @@ fn encode_with( app_segments: &[(u8, Vec)], optimize: bool, ) -> Vec { + // The public entry takes caller-sized dimensions: refuse (an empty output) what would size an allocation from + // them or index past `data`, rather than panic or allocate for them. + let fits = width.checked_mul(height).and_then(|n| n.checked_mul(channels)).is_some_and(|n| n <= data.len()); + if !fits || width == 0 || height == 0 || width > 65_535 || height > 65_535 || !matches!(channels, 1 | 3 | 4) { + return Vec::new(); + } let gray = channels == 1; let (hs, vs) = match (gray, sub) { (true, _) | (false, ChromaSubsampling::S444) => (1usize, 1usize), @@ -586,6 +592,13 @@ fn encode_with( mod tests { use super::*; + #[test] + fn hostile_dimensions_give_no_output_instead_of_a_panic_or_allocation() { + for (w, h, c) in [(1usize << 40, 1usize << 40, 3usize), (0, 8, 3), (70_000, 2, 3), (8, 8, 7), (8, 8, 3)] { + assert!(encode(&[0u8; 16], w, h, c, 90, ChromaSubsampling::S444, &[]).is_empty(), "{w} x {h} x {c}"); + } + } + fn test_rgb(w: usize, h: usize) -> Vec { let mut v = Vec::with_capacity(w * h * 3); for y in 0..h { diff --git a/crates/develop/src/controls.rs b/crates/develop/src/controls.rs index 9d384f57c4..589bcc6f19 100644 --- a/crates/develop/src/controls.rs +++ b/crates/develop/src/controls.rs @@ -28,6 +28,7 @@ pub enum Section { Calibration, PointColor, RedEye, + LensBlur, } impl Section { @@ -49,6 +50,7 @@ impl Section { Section::Calibration => "Calibration", Section::PointColor => "Point Color", Section::RedEye => "Red Eye", + Section::LensBlur => "Lens Blur", } } } @@ -286,6 +288,9 @@ controls! { "geometry.scale" => geometry.scale, "Scale", Geometry, 50, 150, 100, 1, 0, Plain; "geometry.offsetX" => geometry.offset_x, "Offset X", Geometry, -100, 100, 0, 0.1, 1, Centered; "geometry.offsetY" => geometry.offset_y, "Offset Y", Geometry, -100, 100, 0, 0.1, 1, Centered; + "lensBlur.amount" => lens_blur.amount, "Blur Amount", LensBlur, 0, 100, 0, 1, 0, Plain; + "lensBlur.boost" => lens_blur.boost, "Boost", LensBlur, 0, 100, 0, 1, 0, Plain; + "lensBlur.transition" => lens_blur.transition, "Transition", LensBlur, 0, 100, 50, 1, 0, Plain; "calibration.shadowsTint" => calibration.shadows_tint, "Shadows Tint", Calibration, -100, 100, 0, 1, 0, Tint; "calibration.redHue" => calibration.red_hue, "Red Hue", Calibration, -100, 100, 0, 1, 0, Gradient { from: "#e0306a", to: "#e08a30" }; "calibration.redSat" => calibration.red_sat, "Red Saturation", Calibration, -100, 100, 0, 1, 0, Gradient { from: "#7a7a7a", to: "#e03a3a" }; diff --git a/crates/develop/src/lib.rs b/crates/develop/src/lib.rs index cb5acab6f5..0e90df716a 100644 --- a/crates/develop/src/lib.rs +++ b/crates/develop/src/lib.rs @@ -200,6 +200,14 @@ impl DevelopSettings { } } + /// The middle of the crop, in normalized photo coordinates (the photo's middle when the crop + /// isn't a usable rectangle). + pub fn crop_center(&self) -> lightcraft_geom::Point { + let r = self.crop.geometry.rect; + let (x, y) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); + if x.is_finite() && y.is_finite() { lightcraft_geom::Point::new(x, y) } else { lightcraft_geom::Point::new(0.5, 0.5) } + } + /// Next free mask id: one past the highest, or, when that is `u32::MAX` (ids come from files, /// pastes and agents), the lowest one no mask uses. pub fn next_mask_id(&self) -> u32 { diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index c4197c2911..a4e6eab147 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -96,12 +96,18 @@ pub enum Process { /// V5, with colour noise reduction on the linear colour differences R−Y and B−Y, leaving Y alone, with /// edge-aware weights from a denoised guide and a brake for isolated colour specks (issue #815). V6, + /// V6, with film grain from a stack of crystal layers (after Aurélien Pierre's model): resolution + /// independent, fading out at black and white; V1 to V6 keep their value noise. + V7, + /// V7, with the Highlights/Shadows base taken of log luminance without its fine detail (clamped + /// between a fine and a 3× wider median), so gaps in dark lettering aren't lifted into bright blocks. + V8, } impl Process { /// Every process, oldest first. - pub const ALL: [Process; 6] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6]; - pub const LATEST: Process = Process::V6; + pub const ALL: [Process; 8] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6, Process::V7, Process::V8]; + pub const LATEST: Process = Process::V8; pub const fn version(self) -> ProcessVersion { match self { @@ -111,6 +117,8 @@ impl Process { Process::V4 => ProcessVersion(4), Process::V5 => ProcessVersion(5), Process::V6 => ProcessVersion(6), + Process::V7 => ProcessVersion(7), + Process::V8 => ProcessVersion(8), } } } @@ -890,6 +898,25 @@ pub struct LocalAdjustments { pub noise: f64, pub moire: f64, pub defringe: f64, + /// Lens Blur inside the mask, 0..100 (`lightcraft_pipeline::lens_blur`): disc (bokeh) blur + /// whose radius follows the mask's strength. Omitted while 0, so masks without it keep their + /// JSON (and hash). + #[serde(skip_serializing_if = "is_zero")] + pub lens_blur: f64, + /// The mask's Lens Blur block switched off (its values kept). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub lens_blur_off: bool, + /// Blur what the mask leaves out instead of what it selects (the mask's other adjustments + /// still go where it selects). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub lens_blur_outside: bool, + /// Brighter bokeh highlights in the mask's blur, 0..100. + #[serde(skip_serializing_if = "is_zero")] + pub lens_blur_boost: f64, + /// How gradually the mask's blur grows away from what stays sharp, 0..100 (0: it follows the + /// mask's own edge). + #[serde(skip_serializing_if = "is_zero")] + pub lens_blur_transition: f64, /// Colour overlay (hue degrees, saturation 0..100); sat 0 = none. pub color_hue: f64, pub color_sat: f64, @@ -917,6 +944,11 @@ impl Default for LocalAdjustments { noise: 0.0, moire: 0.0, defringe: 0.0, + lens_blur: 0.0, + lens_blur_off: false, + lens_blur_outside: false, + lens_blur_boost: 0.0, + lens_blur_transition: 0.0, color_hue: 0.0, color_sat: 0.0, amount: 100.0, @@ -1258,13 +1290,157 @@ impl Default for RedEye { } } -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +/// Lens Blur: a shallow depth of field added after the fact (`lightcraft_pipeline::lens_blur`). +/// What stays sharp is the photo's subject, or the selection of the mask [`LensBlur::focus_mask`] +/// names; everything else gets disc-shaped (bokeh) blur up to [`LensBlur::amount`]. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct LensBlur { pub enabled: bool, + /// Blur of what is out of focus, 0..100 (100: a disc of 3.5 % of the long edge). pub amount: f64, + /// Reserved for a depth map (not rendered yet). pub focal_distance: f64, + /// Reserved for a depth map (not rendered yet). pub focal_range: f64, + /// How much brighter the out-of-focus highlights turn into bokeh discs, 0..100. Omitted while + /// 0, so settings without it keep their JSON (and hash). + #[serde(skip_serializing_if = "is_zero")] + pub boost: f64, + /// The id of the mask whose selection stays in focus (any mask, shown or hidden); `None`, or a + /// mask that no longer exists: the photo's subject. + #[serde(skip_serializing_if = "Option::is_none")] + pub focus_mask: Option, + /// Brush Refinement, Focus brush: strokes painted in focus (their strength: how far; erase + /// strokes take it back). Omitted while empty. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub focus_strokes: Vec, + /// Brush Refinement, Blur brush: strokes painted out of focus, over the focus and the Focus + /// brush. Omitted while empty. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub blur_strokes: Vec, + /// How gradually the blur grows away from what is in focus, 0..100: 0 a sharp cut at the + /// focus's edge, higher a longer ramp (a stand-in for depth until there is a depth map). + /// Omitted at its default, so settings without it keep their JSON (and hash). + #[serde(skip_serializing_if = "LensBlur::is_default_transition")] + pub transition: f64, + /// What stays in focus without a focus mask: the subject estimate, or a fixed shape in the + /// middle of the framing. Omitted while automatic. + #[serde(skip_serializing_if = "FocusShape::is_auto")] + pub shape: FocusShape, + /// Where a fixed shape sits and how large it is, once moved or resized on the photo; `None`: + /// the shape's preset, in the middle of the crop. + #[serde(skip_serializing_if = "Option::is_none")] + pub area: Option, +} + +/// A fixed focus shape on the photo: an upright ellipse. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct FocusArea { + /// Normalized (uncropped, oriented) photo coordinates, as mask shapes. + pub center: Point, + /// Half-width and half-height, in units of the photo's long edge. + pub rx: f64, + pub ry: f64, +} + +impl FocusArea { + /// Smallest and largest radius (long-edge units). + pub const MIN_RADIUS: f64 = 0.02; + pub const MAX_RADIUS: f64 = 1.0; + + /// Usable values: finite, the radii within range, the centre no farther than a photo's width + /// outside it. A hostile value falls back to the middle and the default size. + pub fn sanitized(self) -> FocusArea { + let r = |v: f64, d: f64| if v.is_finite() { v.clamp(Self::MIN_RADIUS, Self::MAX_RADIUS) } else { d }; + let c = |v: f64| if v.is_finite() { v.clamp(-1.0, 2.0) } else { 0.5 }; + FocusArea { center: Point::new(c(self.center.x), c(self.center.y)), rx: r(self.rx, 0.22), ry: r(self.ry, 0.22) } + } +} + +impl LensBlur { + /// The fixed focus shape in effect, if any: the moved / resized [`LensBlur::area`], else the + /// shape's preset centred on `crop_center`. `None` for [`FocusShape::Auto`]. + pub fn focus_area(&self, crop_center: Point) -> Option { + let (rx, ry) = self.shape.radii()?; + Some(self.area.unwrap_or(FocusArea { center: crop_center, rx, ry }).sanitized()) + } +} + +/// The focus area [`LensBlur`] uses when no mask says what is in focus. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum FocusShape { + /// A circle. + Round, + /// An oval lying down (landscape). + Wide, + /// An oval standing up (portrait). + Tall, + /// The photo's subject, estimated (person mattes, else a saliency heuristic). Also what a + /// shape this build doesn't know reads as (so it is last: serde's `other`). + #[default] + #[serde(other)] + Auto, +} + +impl FocusShape { + pub const ALL: [FocusShape; 4] = [FocusShape::Auto, FocusShape::Round, FocusShape::Wide, FocusShape::Tall]; + + /// Whether this is the default (Auto: no fixed shape), for skipping it in the JSON. + fn is_auto(&self) -> bool { + *self == FocusShape::Auto + } + + /// The fixed shape's half-width and half-height, in units of the photo's long edge; `None` + /// for [`FocusShape::Auto`]. + pub fn radii(self) -> Option<(f64, f64)> { + match self { + FocusShape::Auto => None, + FocusShape::Round => Some((0.22, 0.22)), + FocusShape::Wide => Some((0.32, 0.17)), + FocusShape::Tall => Some((0.17, 0.32)), + } + } + + /// The name shown on the shape's button (translated by the UI). + pub fn label(self) -> &'static str { + match self { + FocusShape::Auto => "Auto", + FocusShape::Round => "Round", + FocusShape::Wide => "Horizontal", + FocusShape::Tall => "Vertical", + } + } +} + +impl LensBlur { + /// [`LensBlur::transition`]'s default. + pub const DEFAULT_TRANSITION: f64 = 50.0; + + /// Whether `v` is [`Self::DEFAULT_TRANSITION`], for skipping it in the JSON. + fn is_default_transition(v: &f64) -> bool { + *v == Self::DEFAULT_TRANSITION + } +} + +impl Default for LensBlur { + /// Off, with the default Transition and everything else empty. + fn default() -> Self { + Self { + enabled: false, + amount: 0.0, + focal_distance: 0.0, + focal_range: 0.0, + boost: 0.0, + focus_mask: None, + focus_strokes: Vec::new(), + blur_strokes: Vec::new(), + transition: Self::DEFAULT_TRANSITION, + shape: FocusShape::Auto, + area: None, + } + } } #[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] diff --git a/crates/develop/src/tests_process.rs b/crates/develop/src/tests_process.rs index f89ebfa115..1694a3ea07 100644 --- a/crates/develop/src/tests_process.rs +++ b/crates/develop/src/tests_process.rs @@ -89,13 +89,13 @@ fn v1_is_left_out_when_saving_and_other_processes_are_kept() { #[test] fn unknown_process_numbers_load_and_render_with_the_newest_known() { // written by a newer LightCraft: kept as it is, rendered with the latest process this build has - let s = DevelopSettings::from_json(&json!({"process": 7, "light": {"exposure": 0.5}})).unwrap(); - assert_eq!(s.process, ProcessVersion(7)); + let s = DevelopSettings::from_json(&json!({"process": LATEST_PLUS_ONE, "light": {"exposure": 0.5}})).unwrap(); + assert_eq!(s.process, ProcessVersion(LATEST_PLUS_ONE)); assert_eq!(s.process.process(), Process::LATEST); assert!(!s.process.is_known()); assert!(!s.process.is_outdated(), "never downgraded by Update to Current Process"); - assert_eq!(s.to_json()["process"], json!(7)); - assert_eq!(s.merged(&json!({"light": {"exposure": 1.0}})).unwrap().process, ProcessVersion(7)); + assert_eq!(s.to_json()["process"], json!(LATEST_PLUS_ONE)); + assert_eq!(s.merged(&json!({"light": {"exposure": 1.0}})).unwrap().process, ProcessVersion(LATEST_PLUS_ONE)); // below V1 (no LightCraft writes it): rendered as V1, and updatable let zero = DevelopSettings::from_json(&json!({"process": 0})).unwrap().process; assert_eq!((zero.process(), zero.is_known(), zero.is_outdated()), (Process::V1, false, true)); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index a01f28510b..895ef52126 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -29,6 +29,8 @@ lightcraft-meta = { workspace = true } lightcraft-lensdb = { workspace = true } lightcraft-faces = { workspace = true } miniz_oxide = { workspace = true } +# CRC-32 of a catalog unpacked from a Lightroom backup zip (lightroom_backup.rs). +crc32fast = { workspace = true } lightcraft-merge = { workspace = true } lightcraft-geocode = { workspace = true } lightcraft-slideshow = { workspace = true } diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index 261a4dd018..f6bcd8fe8d 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -206,7 +206,7 @@ fn edit_copy(s: &mut Session, p: &Value, id: lightcraft_catalog::PhotoId, opts: /// preview-only photo this version hasn't checked yet: its stamp is refreshed so it isn't probed /// again (see [`lightcraft_catalog::Photo::preview_checked`]). pub(crate) fn content_op(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::Photo, info: crate::media::ProbeInfo) -> Option { - let preview_checked = lightcraft_catalog::preview_stamp(&info.preview_only); + let preview_checked = ph.preview_stamp(&info.preview_only); let same = info.content_hash == ph.content_hash && info.file_size == ph.file_size && (info.width, info.height) == (ph.width, ph.height) diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index 5403ad6eb2..5223710ed6 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -8,6 +8,9 @@ use serde_json::{Value, json}; use super::{CommandSpec, always, bad, bool_or, cmd, f64_or, f64_req, has_active, has_clipboard, has_selection, index_req, ok, str_param}; use crate::{Result, Session, media::SourceLevel}; +/// Strokes one Lens Blur refinement brush keeps (a document can't grow without bound). +const MAX_LENS_BLUR_STROKES: usize = 2000; + fn active(s: &Session, c: &str) -> Result { s.active().ok_or_else(|| bad(c, "no active photo")) } @@ -482,6 +485,150 @@ pub fn specs() -> Vec { Ok(()) }) }), + cmd!( + "lensBlur.brushStroke", + "Lens Blur Brush Stroke", + [], + None, + "{mode: \"focus\"|\"blur\", points: [[x,y],…] normalized, size?: fraction of long edge (0.03), feather?: 0..100, flow?: 1..100, amount?: 1..100 (how far the stroke refines), erase?: bool, autoMask?: bool, pressure?: [p,…] 0..1 per point} — Lens Blur Brush Refinement: Focus strokes stay sharp, Blur strokes are blurred", + has_active, + |s, p| { + const C: &str = "lensBlur.brushStroke"; + let focus = match str_param(p, "mode") { + Some("focus") => true, + Some("blur") => false, + _ => return Err(bad(C, "`mode` must be \"focus\" or \"blur\"")), + }; + let points: Vec = p + .get("points") + .and_then(Value::as_array) + .ok_or_else(|| bad(C, "missing points"))? + .iter() + .filter_map(|q| Some(Point::new(q.get(0)?.as_f64()?, q.get(1)?.as_f64()?))) + .filter(|q| q.x.is_finite() && q.y.is_finite()) + .collect(); + if points.is_empty() { + return Err(bad(C, "a stroke needs at least one point")); + } + let d = lightcraft_develop::BrushStroke::default(); + let num = |key: &str, def: f64, lo: f64, hi: f64| { + let v = f64_or(p, key, def); + if v.is_finite() { v.clamp(lo, hi) } else { def } + }; + let stroke = lightcraft_develop::BrushStroke { + pressure: super::masks::pressure_list(p.get("pressure"), points.len())?, + points, + size: num("size", d.size, 0.001, 0.5), + feather: num("feather", d.feather, 0.0, 100.0), + flow: num("flow", d.flow, 1.0, 100.0), + density: num("amount", d.density, 1.0, 100.0), + erase: bool_or(p, "erase", false), + auto_mask: bool_or(p, "autoMask", false), + }; + edit(s, C, if focus { "Lens Blur Focus Brush" } else { "Lens Blur Blur Brush" }, |d| { + let strokes = if focus { &mut d.lens_blur.focus_strokes } else { &mut d.lens_blur.blur_strokes }; + if strokes.len() >= MAX_LENS_BLUR_STROKES { + return Err(bad(C, format!("at most {MAX_LENS_BLUR_STROKES} strokes per brush: Reset the brush first"))); + } + strokes.push(stroke); + Ok(()) + }) + } + ), + cmd!( + "lensBlur.findSubject", + "Find Subject", + [], + None, + "{} — selects the photo's subject with an Object mask (SAM 3) clicked where the camera focused, when the file records it, else at the likeliest subject; Lens Blur is switched on and keeps that mask in focus → {mask, point: [x,y], from: \"camera\"|\"photo\", pending?}", + has_active, + |s, _| { + const C: &str = "lensBlur.findSubject"; + let id = active(s, C)?; + let d = s.develop_of(id).unwrap_or_default(); + let camera = s.catalog.photo(id).and_then(|p| p.meta.focus.clone()); + let (point, from) = match camera { + // stored on the upright photo: the user's Rotate / Flip on top, as masks are + Some(f) => { + let r = d.orientation.map_norm_rect(f.rect); + (Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0), "camera") + } + None => { + let src = s.source_now(id, SourceLevel::Thumb).map_err(|e| bad(C, e))?; + let info = s.source_info(id); + let p = lightcraft_pipeline::lens_blur::subject_point(&src, &d, info.mattes.as_deref()) + .ok_or_else(|| bad(C, "the photo has no picture to look for a subject in"))?; + (p, "photo") + } + }; + if !(point.x.is_finite() && point.y.is_finite()) { + return Err(bad(C, "the camera's focus point is not usable")); + } + let point = Point::new(point.x.clamp(0.0, 1.0), point.y.clamp(0.0, 1.0)); + // an Object waiting for the subject (the photo is analyzed meanwhile); the + // segmenter fills it with the people / animals the focus falls on, or the object + // at the point + let mut out = s.execute("mask.add", &json!({"kind": "object", "name": "Lens Blur Subject"}))?; + let mask = out + .get("activeMask") + .and_then(Value::as_u64) + .and_then(|v| u32::try_from(v).ok()) + .ok_or_else(|| bad(C, "the subject mask was not created"))?; + let focus = (from == "camera").then_some(point); + if let Err(e) = s.segment_subject_later(id, mask, 0, point, focus) { + // nothing half-made: the empty mask goes again + let _ = s.execute("edit.undo", &json!({})); + return Err(crate::EngineError::Other(e)); + } + out["pending"] = json!(s.segmenter.background); + edit(s, C, "Lens Blur Subject", |d| { + // a mask that only says what is in focus: no adjustments of its own + if let Some(m) = d.masks.iter_mut().find(|m| m.id == mask) { + m.adjust = lightcraft_develop::LocalAdjustments::default(); + } + let b = &mut d.lens_blur; + b.enabled = true; + if b.amount <= 0.0 || !b.amount.is_finite() { + b.amount = 50.0; + } + b.focus_mask = Some(mask); + d.set_section_enabled("lensBlur", true); + Ok(()) + })?; + if let Some(o) = out.as_object_mut() { + o.insert("mask".into(), json!(mask)); + o.insert("point".into(), json!([point.x, point.y])); + o.insert("from".into(), json!(from)); + } + Ok(out) + } + ), + cmd!( + "lensBlur.brushReset", + "Reset Lens Blur Brush", + [], + None, + "{mode?: \"focus\"|\"blur\"} — removes that brush's strokes (both brushes without `mode`)", + has_active, + |s, p| { + const C: &str = "lensBlur.brushReset"; + let (focus, blur) = match str_param(p, "mode") { + None => (true, true), + Some("focus") => (true, false), + Some("blur") => (false, true), + Some(_) => return Err(bad(C, "`mode` must be \"focus\" or \"blur\"")), + }; + edit(s, C, "Reset Lens Blur Brush", |d| { + if focus { + d.lens_blur.focus_strokes.clear(); + } + if blur { + d.lens_blur.blur_strokes.clear(); + } + Ok(()) + }) + } + ), cmd!("develop.sectionEnabled", "Toggle Section", [], None, "{section: string, enabled: bool}", has_active, |s, p| { let sec = str_param(p, "section").ok_or_else(|| bad("develop.sectionEnabled", "missing section"))?.to_string(); let on = bool_or(p, "enabled", true); diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index c725ac216b..bbd618f9f1 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -1302,10 +1302,13 @@ pub fn specs() -> Vec { }), // ---- import cmd!(query "library.inspectLightroom", "Inspect Lightroom Catalog", [], None, - "{path: .lrcat} → {photos, collections, missing, warnings}; read-only, no Lightroom required", - always, |_, p| { + "{path: .lrcat, or a Lightroom catalog backup .zip} → {photos, collections, missing, warnings}; read-only, no Lightroom required", + always, |s, p| { let path = str_param(p,"path").ok_or_else(|| bad("library.inspectLightroom","missing path"))?; - let data = crate::lightroom_catalog::read(std::path::Path::new(path)).map_err(|e| bad("library.inspectLightroom",e))?; + let (cancel, total, done) = Default::default(); + let temp = crate::lightroom_catalog::backup_temp_root(s); + let data = crate::lightroom_catalog::read_source(std::path::Path::new(path), temp.as_deref(), &cancel, &total, &done) + .map_err(|e| bad("library.inspectLightroom",e))?; Ok(json!({"photos":data.photos.len(),"collections":data.collections.iter().filter(|r|r.get("systemOnly").and_then(Value::as_f64).unwrap_or(0.0)==0.0).count(),"missing":data.photos.iter().filter(|p| !p.original_is_file()).map(|p|&p.path).collect::>(),"warnings":data.warnings,"skipped":data.skipped})) }), cmd!( @@ -1313,7 +1316,7 @@ pub fn specs() -> Vec { "Import Lightroom Catalog", [], None, - "{path: .lrcat, updateExisting?: false}; direct import of paths, ratings, flags, metadata, keywords, collections, virtual copies & mapped edits. Archives source settings/history first. Existing edited photos are preserved unless updateExisting=true; source catalog is read-only.", + "{path: .lrcat, or a Lightroom catalog backup .zip (unpacked to a temporary folder in the library, removed after reading; the zip is not changed), updateExisting?: false}; direct import of paths, ratings, flags, metadata, keywords, collections, virtual copies & mapped edits. Archives source settings/history first. Existing edited photos are preserved unless updateExisting=true; source catalog is read-only.", always, |s, p| { let path = str_param(p, "path").ok_or_else(|| bad("library.importLightroom", "missing path"))?; diff --git a/crates/engine/src/cmd/mask_effects.rs b/crates/engine/src/cmd/mask_effects.rs index d791b42606..529566f3bb 100644 --- a/crates/engine/src/cmd/mask_effects.rs +++ b/crates/engine/src/cmd/mask_effects.rs @@ -33,6 +33,7 @@ pub const FIELDS: &[&str] = &[ "noise", "moire", "defringe", + "lens_blur", "color_hue", "color_sat", ]; @@ -118,10 +119,11 @@ pub fn get(a: &LocalAdjustments, k: &str) -> f64 { serde_json::to_value(a).ok().and_then(|v| v.get(k).and_then(Value::as_f64)).unwrap_or(0.0) } -/// `a` with field `k` set to `v` (unchanged for an unknown name). +/// `a` with field `k` set to `v` (unchanged for an unknown name). A [`FIELDS`] slider counts as +/// known also while its JSON leaves it out at 0 (`lens_blur`). pub fn set(a: &LocalAdjustments, k: &str, v: f64) -> LocalAdjustments { let Ok(Value::Object(mut o)) = serde_json::to_value(a) else { return *a }; - if !o.contains_key(k) || !v.is_finite() { + if !(o.contains_key(k) || FIELDS.contains(&k)) || !v.is_finite() { return *a; } o.insert(k.into(), json!(v)); @@ -707,6 +709,22 @@ mod tests { assert!(!e.matches(&LocalAdjustments { amount: 100.0, ..out }), "Amount counts when carried"); } + /// A partial effect sets Lens Blur on a mask without any yet (its JSON leaves `lens_blur` out + /// at 0); a name no slider has still changes nothing. + #[test] + fn partial_effects_set_lens_blur_from_zero() { + let e = MaskEffect { + name: "Bokeh".into(), + adjust: LocalAdjustments { lens_blur: 60.0, ..Default::default() }, + fields: vec!["lens_blur".into()], + ..Default::default() + }; + let out = e.apply(&LocalAdjustments::default()); + assert_eq!(out.lens_blur, 60.0); + assert!(e.matches(&out)); + assert_eq!(set(&LocalAdjustments::default(), "bogus", 5.0), LocalAdjustments::default()); + } + #[test] fn hue_without_saturation_still_matches() { let e = MaskEffect { diff --git a/crates/engine/src/cmd/masks.rs b/crates/engine/src/cmd/masks.rs index 171435e22b..e4017f4003 100644 --- a/crates/engine/src/cmd/masks.rs +++ b/crates/engine/src/cmd/masks.rs @@ -98,6 +98,10 @@ fn resolve_ai(s: &mut Session, shape: &mut MaskShape, c: &str) -> Result match shape { MaskShape::Object { seg: Some(_), .. } | MaskShape::Prompt { seg: Some(_), .. } => {} MaskShape::Object { hint, exclude, .. } if !hint.is_empty() && background => { + // refused here, not when the worker later fails at the model's limit after "pending" + if hint.len() + exclude.len() > crate::segment::MAX_CLICKS { + return Err(ai_err(format!("an Object selection takes at most {} clicks", crate::segment::MAX_CLICKS))); + } s.segmenter.require_model()?; return Ok(Later::Clicks(std::mem::take(hint), std::mem::take(exclude))); } @@ -158,7 +162,11 @@ fn masks_edit(s: &mut Session, c: &str, label: &str, f: impl FnOnce(&mut Vec Vec { "Set Mask Adjustments", [], None, - "{id?, values: {exposure, contrast, highlights, shadows, whites, blacks, temp, tint, texture, clarity, dehaze, hue, saturation, sharpness, noise, moire, defringe, color_hue, color_sat, amount}}", + "{id?, values: {exposure, contrast, highlights, shadows, whites, blacks, temp, tint, texture, clarity, dehaze, hue, saturation, sharpness, noise, moire, defringe, lens_blur, lens_blur_off, lens_blur_outside, lens_blur_boost, lens_blur_transition, color_hue, color_sat, amount}}", has_active, |s, p| { let vals = p.get("values").cloned().ok_or_else(|| bad("mask.adjust", "missing values"))?; @@ -1147,6 +1155,9 @@ pub(crate) fn clamp_local(mut a: LocalAdjustments) -> LocalAdjustments { ] { c(v, -100.0, 100.0); } + c(&mut a.lens_blur, 0.0, 100.0); + c(&mut a.lens_blur_boost, 0.0, 100.0); + c(&mut a.lens_blur_transition, 0.0, 100.0); c(&mut a.color_hue, 0.0, 360.0); c(&mut a.color_sat, 0.0, 100.0); c(&mut a.amount, 0.0, 200.0); @@ -1155,7 +1166,7 @@ pub(crate) fn clamp_local(mut a: LocalAdjustments) -> LocalAdjustments { /// `mask.brushStroke`'s `pressure`: one number 0..1 per point (clamped), at most one per point; absent or `null` /// is no pressure data. -fn pressure_list(v: Option<&Value>, points: usize) -> Result> { +pub(super) fn pressure_list(v: Option<&Value>, points: usize) -> Result> { let Some(v) = v.filter(|v| !v.is_null()) else { return Ok(Vec::new()) }; let list = v.as_array().ok_or_else(|| bad("mask.brushStroke", "pressure must be a list of numbers 0..1"))?; if list.len() > points { diff --git a/crates/engine/src/cmd/recheck.rs b/crates/engine/src/cmd/recheck.rs index 494426b90c..a7d40a8370 100644 --- a/crates/engine/src/cmd/recheck.rs +++ b/crates/engine/src/cmd/recheck.rs @@ -4,6 +4,8 @@ //! library opens in another version, its stale preview-only photos are probed again and get //! exactly what Reload from Disk would give them: a file that decodes now loses the flag, one that //! still doesn't gets the new reason and a fresh stamp, so it isn't probed again. +//! ORF records are rechecked even when previously sensor-decodable: compressed sensor support +//! was withdrawn after #3775. Supported uncompressed ORFs also keep a stamp to avoid repeat work. //! //! The work is split so the app can probe on a worker thread: [`stale`] lists what to probe (no //! file-system calls), [`probe`] reads the files without the session, and [`apply`] applies the @@ -17,7 +19,7 @@ use super::{CommandSpec, always, bad, cmd}; use crate::media::{FileProbe, ProbeInfo}; use crate::{Result, Session}; -/// A preview-only photo to probe, and what the library knew about it when it was listed (so a +/// A photo to probe, and what the library knew about it when it was listed (so a /// result for a photo that changed meanwhile is dropped). #[derive(Clone, Debug, PartialEq, Eq)] pub struct Stale { @@ -40,12 +42,12 @@ impl Stale { } } -/// The library's preview-only photos whose flag another app version set (or every preview-only -/// photo, with `all`): library photos with a file, not virtual copies (they follow the photo they -/// were copied from). No file-system calls. +/// The library's preview-only photos and ORFs whose support another app version checked (or +/// every such photo, with `all`): library photos with a file, not virtual copies (they follow +/// the photo they were copied from). No file-system calls. pub fn stale(cat: &Catalog, all: bool) -> Vec { cat.photos() - .filter(|p| p.copy_of.is_none() && p.preview_only.is_some() && (all || p.preview_only_stale())) + .filter(|p| p.copy_of.is_none() && (p.preview_only_stale() || (all && (p.preview_only.is_some() || p.format.eq_ignore_ascii_case("orf"))))) .filter_map(|p| crate::cmd::missing::checked_path(p).map(|path| Stale::of(p, path))) .collect() } @@ -92,7 +94,7 @@ pub fn apply(s: &mut Session, results: Vec<(Stale, std::result::Result Vec { "Recheck Preview-Only Raws", [], None, - "{all?: bool} — probe again the raws shown from their embedded preview whose flag another LightCraft version set (the app does this in the background when a library opens; `all` rechecks every preview-only raw, e.g. when testing a decoder build of the same version), and bring each up to date as Reload from Disk would; not an undo step, develop settings and history are kept; files that can't be read are left for next time → {checked, updated: [ids], cleared: [ids] (develop from their raw data now)}", + "{all?: bool} — probe again preview-only raws and ORFs whose support another LightCraft version checked (the app does this in the background when a library opens; `all` rechecks every preview-only raw and ORF, e.g. when testing a decoder build of the same version), and bring each up to date as Reload from Disk would; not an undo step, develop settings and history are kept; files that can't be read are left for next time → {checked, updated: [ids], cleared: [ids] (develop from their raw data now)}", always, recheck )] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 53077f95c6..a733d90e08 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -51,6 +51,7 @@ pub mod lens_profiles; pub mod lensfun_download; pub mod library; mod lightroom_archive; +pub mod lightroom_backup; pub mod lightroom_catalog; pub mod lightroom_folder; pub mod lightroom_job; diff --git a/crates/engine/src/lightroom_archive.rs b/crates/engine/src/lightroom_archive.rs index 9c9979d970..511f81f308 100644 --- a/crates/engine/src/lightroom_archive.rs +++ b/crates/engine/src/lightroom_archive.rs @@ -519,6 +519,8 @@ mod tests { fn data(source: String) -> CatalogImport { CatalogImport { source, + catalog_id: None, + catalog_path: None, photos: Vec::new(), collections: Vec::new(), members: Vec::new(), @@ -543,6 +545,8 @@ mod tests { }; CatalogImport { source: "source.lrcat".into(), + catalog_id: None, + catalog_path: None, photos: vec![photo], collections: vec![BTreeMap::from([("name".into(), serde_json::json!("Keepers"))])], members: vec![BTreeMap::from([("image".into(), serde_json::json!(7))])], diff --git a/crates/engine/src/lightroom_backup.rs b/crates/engine/src/lightroom_backup.rs new file mode 100644 index 0000000000..ab51ffd3de --- /dev/null +++ b/crates/engine/src/lightroom_backup.rs @@ -0,0 +1,558 @@ +//! Lightroom Classic catalog backups (issue #2592): `Backups/YYYY-MM-DD HHMM/.zip`, which +//! holds the catalog `.lrcat` (and, since Classic 12, a small `.lrcat-data/` folder that +//! the import does not need). Someone who has left Lightroom may have nothing else: the import takes +//! the zip as it is. +//! +//! The catalog entry is inflated by streaming into a private folder ([`Extracted`]), read from +//! there like any `.lrcat`, and the folder is removed when the [`Extracted`] guard is dropped (after +//! the read, on an error and on cancel alike). The zip itself is only read. The folder is made under +//! the open library's `Interop/` when there is one (the library's disk, not a RAM-backed `/tmp`), +//! else under [`std::env::temp_dir`]; a folder left by a crash (`lc-lrbackup-*`, older than a day) +//! is removed by the next extraction there. +//! +//! Written from the ZIP application note (PKWARE APPNOTE.TXT 6.3: end of central directory, +//! ZIP64 end record and locator, central directory headers, local headers, the ZIP64 extra field +//! 0x0001) and RFC 1951 (deflate, inflated by `miniz_oxide`); no third-party zip code was used. +//! Every size and offset comes from the file and is checked before use. + +use std::fs::File; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; + +/// The largest catalog a backup may unpack to: the SQLite reader's cap on a database file. +pub const MAX_CATALOG_BYTES: u64 = 16 << 30; +/// The most central directory entries looked at (a Lightroom backup has one to four). +const MAX_ENTRIES: u64 = 4096; +/// The largest central directory read (names of `MAX_ENTRIES` entries fit easily). +const MAX_DIRECTORY_BYTES: u64 = 4 << 20; +/// Prefix of the private extraction folders, so leftovers can be found. +const PREFIX: &str = "lc-lrbackup-"; +/// Leftover folders older than this are removed (one still being read is never this old). +const STALE_SECS: u64 = 24 * 60 * 60; +/// Bytes read from the zip and written to the catalog per step. +const CHUNK: usize = 1 << 20; + +/// Whether `path` names a Lightroom catalog backup: a `.zip` file (any case). +pub fn is_backup(path: &Path) -> bool { + path.extension().is_some_and(|e| e.eq_ignore_ascii_case("zip")) +} + +/// Where the catalog in a backup lived, for resolving the paths it records relative to itself, and +/// whether that is known: `/Backups//.zip` (Lightroom's default +/// layout) → `/.lrcat`, known; a zip anywhere else (a backup folder of the +/// person's choosing, a zip moved away) → the `.lrcat` next to it, a guess that is only used to +/// resolve paths, never to recognise the catalog. +pub fn original_catalog(zip: &Path, entry: &str) -> (PathBuf, bool) { + let name = Path::new(entry).file_name().map_or_else(|| PathBuf::from("catalog.lrcat"), PathBuf::from); + let dated = zip.parent(); + let backups = dated.and_then(Path::parent); + match backups { + Some(b) if b.file_name().is_some_and(|n| n.eq_ignore_ascii_case("backups")) => (b.parent().unwrap_or(b).join(name), true), + _ => (dated.map_or_else(|| name.clone(), |d| d.join(&name)), false), + } +} + +/// A catalog unpacked from a backup; its private folder is removed when this is dropped. +#[derive(Debug)] +pub struct Extracted { + dir: PathBuf, + /// The unpacked `.lrcat`. + pub catalog: PathBuf, + /// The catalog's name inside the zip. + pub entry: String, +} + +impl Drop for Extracted { + /// Removes the private folder and the catalog in it; a failure is logged, not raised (drop can't fail). + fn drop(&mut self) { + if let Err(e) = std::fs::remove_dir_all(&self.dir) + && e.kind() != std::io::ErrorKind::NotFound + { + log::warn!("Lightroom backup: could not remove {}: {e}", self.dir.display()); + } + } +} + +/// One file in the zip's central directory. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Entry { + name: String, + method: u16, + crc: u32, + compressed: u64, + size: u64, + local: u64, +} + +/// The little-endian `u16` at `at` in `b`, or `None` past its end. +fn u16_at(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(2)?)?; + Some(u16::from_le_bytes([s[0], s[1]])) +} + +/// The little-endian `u32` at `at` in `b`, or `None` past its end. +fn u32_at(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(4)?)?; + Some(u32::from_le_bytes([s[0], s[1], s[2], s[3]])) +} + +/// The little-endian `u64` at `at` in `b`, or `None` past its end. +fn u64_at(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(8)?)?; + let mut a = [0u8; 8]; + a.copy_from_slice(s); + Some(u64::from_le_bytes(a)) +} + +/// `len` bytes of `f` from offset `at`; a length that doesn't fit memory or a short read is an error. +fn read_at(f: &mut File, at: u64, len: u64) -> Result, String> { + let len = usize::try_from(len).map_err(|_| "zip record too large".to_string())?; + f.seek(SeekFrom::Start(at)).map_err(|e| e.to_string())?; + let mut buf = vec![0u8; len]; + f.read_exact(&mut buf).map_err(|e| format!("truncated zip: {e}"))?; + Ok(buf) +} + +/// The central directory's entries (offset and count from the end record, or its ZIP64 record). +fn entries(f: &mut File) -> Result, String> { + let len = f.metadata().map_err(|e| e.to_string())?.len(); + // end of central directory: 22 bytes plus a comment of up to 64 KiB + let tail_len = len.min(22 + 65_535); + let tail_at = len - tail_len; + let tail = read_at(f, tail_at, tail_len)?; + let eocd = (0..tail.len().saturating_sub(21)).rev().find(|&i| tail.get(i..).is_some_and(|b| b.starts_with(b"PK\x05\x06"))); + let Some(eocd) = eocd else { return Err("not a zip file (no end of central directory)".into()) }; + let bad = || "damaged zip (end of central directory)".to_string(); + let mut count = u64::from(u16_at(&tail, eocd + 10).ok_or_else(bad)?); + let mut dir_len = u64::from(u32_at(&tail, eocd + 12).ok_or_else(bad)?); + let mut dir_at = u64::from(u32_at(&tail, eocd + 16).ok_or_else(bad)?); + // ZIP64: a locator just before the end record points at the ZIP64 end record + if (count == 0xFFFF || dir_len == 0xFFFF_FFFF || dir_at == 0xFFFF_FFFF) + && let Some(loc) = eocd.checked_sub(20) + && tail.get(loc..).is_some_and(|b| b.starts_with(b"PK\x06\x07")) + { + let rec_at = u64_at(&tail, loc + 8).ok_or_else(bad)?; + let rec = read_at(f, rec_at, 56)?; + if !rec.starts_with(b"PK\x06\x06") { + return Err("damaged zip (ZIP64 end record)".into()); + } + count = u64_at(&rec, 32).ok_or_else(bad)?; + dir_len = u64_at(&rec, 40).ok_or_else(bad)?; + dir_at = u64_at(&rec, 48).ok_or_else(bad)?; + } + if count > MAX_ENTRIES || dir_len > MAX_DIRECTORY_BYTES || dir_at.checked_add(dir_len).is_none_or(|end| end > len) { + return Err("damaged zip (central directory out of range)".into()); + } + let dir = read_at(f, dir_at, dir_len)?; + let mut out = Vec::new(); + let mut at = 0usize; + let bad = || "damaged zip (central directory)".to_string(); + for _ in 0..count { + if !dir.get(at..).is_some_and(|b| b.starts_with(b"PK\x01\x02")) { + return Err(bad()); + } + let method = u16_at(&dir, at + 10).ok_or_else(bad)?; + let crc = u32_at(&dir, at + 16).ok_or_else(bad)?; + let mut compressed = u64::from(u32_at(&dir, at + 20).ok_or_else(bad)?); + let mut size = u64::from(u32_at(&dir, at + 24).ok_or_else(bad)?); + let name_len = usize::from(u16_at(&dir, at + 28).ok_or_else(bad)?); + let extra_len = usize::from(u16_at(&dir, at + 30).ok_or_else(bad)?); + let comment_len = usize::from(u16_at(&dir, at + 32).ok_or_else(bad)?); + let mut local = u64::from(u32_at(&dir, at + 42).ok_or_else(bad)?); + let name_at = at + 46; + let name_end = name_at.checked_add(name_len).ok_or_else(bad)?; + let name = String::from_utf8_lossy(dir.get(name_at..name_end).ok_or_else(bad)?).replace('\\', "/"); + let extra = dir.get(name_end..name_end.checked_add(extra_len).ok_or_else(bad)?).ok_or_else(bad)?; + // ZIP64 extra field: the 64-bit values, in this order, of those set to 0xFFFFFFFF + let mut e = 0usize; + while e + 4 <= extra.len() { + let (id, len) = (u16_at(extra, e).ok_or_else(bad)?, usize::from(u16_at(extra, e + 2).ok_or_else(bad)?)); + let body = extra.get(e + 4..e + 4 + len).ok_or_else(bad)?; + if id == 0x0001 { + let mut v = 0usize; + for field in [&mut size, &mut compressed, &mut local] { + if *field == 0xFFFF_FFFF { + *field = u64_at(body, v).ok_or_else(bad)?; + v += 8; + } + } + } + e += 4 + len; + } + at = name_end.checked_add(extra_len).and_then(|x| x.checked_add(comment_len)).ok_or_else(bad)?; + out.push(Entry { name, method, crc, compressed, size, local }); + } + Ok(out) +} + +/// The backup's catalog entry: the one `*.lrcat` file in the zip, outside macOS resource forks. +fn catalog_entry(entries: &[Entry]) -> Result<&Entry, String> { + let mut found = entries.iter().filter(|e| { + let lower = e.name.to_lowercase(); + lower.ends_with(".lrcat") && !lower.split('/').any(|p| p == "__macosx" || p.starts_with("._")) + }); + match (found.next(), found.next()) { + (Some(e), None) => Ok(e), + (None, _) => Err("this zip holds no Lightroom catalog (.lrcat)".into()), + (Some(_), Some(_)) => Err("this zip holds more than one Lightroom catalog (.lrcat); unzip it and import one".into()), + } +} + +/// Whether the zip at `path` holds exactly one Lightroom catalog, by its central directory only +/// (nothing is unpacked). Any read error means no. +pub fn holds_catalog(path: &Path) -> bool { + File::open(path).ok().and_then(|mut f| entries(&mut f).ok()).is_some_and(|all| catalog_entry(&all).is_ok()) +} + +/// Remove `lc-lrbackup-*` folders in `root` left by an earlier run that ended without cleaning up. +fn sweep(root: &Path) { + let Ok(dir) = std::fs::read_dir(root) else { return }; + for entry in dir.take(10_000).flatten() { + if !entry.file_name().to_str().is_some_and(|n| n.starts_with(PREFIX)) { + continue; + } + // only a real folder of ours: `DirEntry::metadata` doesn't follow a link (Unix), and a link named + // like one is skipped explicitly rather than relying on `remove_dir_all` removing just the link + let Ok(meta) = entry.metadata() else { continue }; + let stale = meta.modified().ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age.as_secs() > STALE_SECS); + if meta.is_dir() + && !meta.file_type().is_symlink() + && stale + && let Err(e) = std::fs::remove_dir_all(entry.path()) + { + log::warn!("Lightroom backup: could not remove the leftover {}: {e}", entry.path().display()); + } + } +} + +/// Refuse a known shortage; an unavailable space reading is left to normal write-error handling. +fn check_space(root: &Path, needed: u64, available: Option) -> Result<(), String> { + if let Some(available) = available + && needed > available + { + return Err(format!("not enough free space in {} to unpack this catalog ({} bytes needed, {} available)", root.display(), needed, available)); + } + Ok(()) +} + +/// Unpack the catalog of the backup `zip` into a new private folder under `root`, checking its +/// size and CRC-32. Stops with an error when `cancel` is set; the folder is removed then too. +pub fn extract(zip: &Path, root: &Path, cancel: &AtomicBool) -> Result { + let mut f = File::open(zip).map_err(|e| format!("{}: {e}", zip.display()))?; + let all = entries(&mut f)?; + let entry = catalog_entry(&all)?.clone(); + if entry.size > MAX_CATALOG_BYTES { + return Err(format!("the catalog in this backup unpacks to {} GB, more than LightCraft reads", entry.size >> 30)); + } + std::fs::create_dir_all(root).map_err(|e| format!("{}: {e}", root.display()))?; + check_space(root, entry.size, crate::disk_space::read(root).map(|space| space.available))?; + sweep(root); + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + let dir = root.join(format!("{PREFIX}{}-{stamp}", std::process::id())); + // owner-only from the start on Unix (a catalog holds the person's paths and metadata) + #[cfg(unix)] + let builder = { + let mut builder = std::fs::DirBuilder::new(); + std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); + builder + }; + #[cfg(not(unix))] + let builder = std::fs::DirBuilder::new(); + builder.create(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + // a fixed name, not the zip's: an entry named `NUL.lrcat` or `a:b.lrcat` would be a device or an + // alternate data stream on Windows. The guard exists before the first byte is written: every + // early return below cleans up. + let out = Extracted { catalog: dir.join("catalog.lrcat"), dir, entry: entry.name.clone() }; + let local = read_at(&mut f, entry.local, 30)?; + if !local.starts_with(b"PK\x03\x04") { + return Err("damaged zip (local header)".into()); + } + let bad = || "damaged zip (local header)".to_string(); + let skip = u64::from(u16_at(&local, 26).ok_or_else(bad)?) + u64::from(u16_at(&local, 28).ok_or_else(bad)?); + let data_at = entry.local.checked_add(30 + skip).ok_or_else(bad)?; + f.seek(SeekFrom::Start(data_at)).map_err(|e| e.to_string())?; + let mut input = f.take(entry.compressed); + // created new: a file or a link already in its place is an error, never written through + let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&out.catalog).map_err(|e| format!("{}: {e}", out.catalog.display()))?; + let mut writer = std::io::BufWriter::with_capacity(CHUNK, file); + let mut crc = crc32fast::Hasher::new(); + let mut written = 0u64; + let mut write = |bytes: &[u8], written: &mut u64| -> Result<(), String> { + *written = written.saturating_add(bytes.len() as u64); + if *written > entry.size { + return Err("damaged zip (the catalog is longer than the zip says)".into()); + } + crc.update(bytes); + writer.write_all(bytes).map_err(|e| format!("writing {}: {e}", out.catalog.display())) + }; + let mut buf = vec![0u8; CHUNK]; + match entry.method { + 0 => loop { + if cancel.load(Ordering::Relaxed) { + return Err("cancelled".into()); + } + let n = input.read(&mut buf).map_err(|e| e.to_string())?; + if n == 0 { + break; + } + write(buf.get(..n).unwrap_or_default(), &mut written)?; + }, + 8 => { + use miniz_oxide::inflate::stream::{InflateState, inflate}; + use miniz_oxide::{DataFormat, MZFlush, MZStatus}; + let mut state = InflateState::new_boxed(DataFormat::Raw); + let mut out_buf = vec![0u8; CHUNK]; + let (mut start, mut end) = (0usize, 0usize); + loop { + if cancel.load(Ordering::Relaxed) { + return Err("cancelled".into()); + } + if start == end { + end = input.read(&mut buf).map_err(|e| e.to_string())?; + start = 0; + } + let flush = if end == 0 { MZFlush::Finish } else { MZFlush::None }; + let r = inflate(&mut state, buf.get(start..end).unwrap_or_default(), &mut out_buf, flush); + start = start.saturating_add(r.bytes_consumed).min(end); + write(out_buf.get(..r.bytes_written).unwrap_or_default(), &mut written)?; + match r.status { + Ok(MZStatus::StreamEnd) => break, + Ok(_) => {} + // no progress with all input given: the stream is cut short + Err(miniz_oxide::MZError::Buf) if end == 0 && r.bytes_written == 0 => return Err("damaged zip (the catalog is cut short)".into()), + Err(miniz_oxide::MZError::Buf) => {} + Err(e) => return Err(format!("damaged zip (deflate: {e:?})")), + } + if r.bytes_consumed == 0 && r.bytes_written == 0 && start < end { + return Err("damaged zip (the catalog's data does not inflate)".into()); + } + } + } + m => return Err(format!("this zip uses compression method {m}, which LightCraft does not read; unzip it and import the .lrcat")), + } + writer.flush().map_err(|e| format!("writing {}: {e}", out.catalog.display()))?; + drop(writer); + if written != entry.size { + return Err("damaged zip (the catalog is shorter than the zip says)".into()); + } + if crc.finalize() != entry.crc { + return Err("damaged zip (the catalog's checksum does not match)".into()); + } + Ok(out) +} + +#[cfg(test)] +pub(crate) mod tests { + #[test] + fn free_space_check_refuses_known_shortage() { + let root = std::path::Path::new("library"); + assert!(super::check_space(root, 11, Some(10)).unwrap_err().contains("not enough free space")); + assert!(super::check_space(root, 10, Some(10)).is_ok()); + assert!(super::check_space(root, 11, None).is_ok()); + } + use super::*; + + /// A zip of `files` (name, bytes), each stored or deflated; `zip64` writes ZIP64 records and + /// extra fields (with the 32-bit fields set to 0xFFFFFFFF) as large archives do. + pub(crate) fn zip(files: &[(&str, &[u8])], deflate: bool, zip64: bool) -> Vec { + let mut out = Vec::new(); + let mut central = Vec::new(); + for (name, data) in files { + let body = if deflate { miniz_oxide::deflate::compress_to_vec(data, 6) } else { data.to_vec() }; + let crc = crc32fast::hash(data); + let local = out.len() as u64; + let method: u16 = if deflate { 8 } else { 0 }; + let big = |v: u64| if zip64 { 0xFFFF_FFFFu32 } else { v as u32 }; + let mut extra = Vec::new(); + if zip64 { + extra.extend_from_slice(&1u16.to_le_bytes()); + extra.extend_from_slice(&24u16.to_le_bytes()); + extra.extend_from_slice(&(data.len() as u64).to_le_bytes()); + extra.extend_from_slice(&(body.len() as u64).to_le_bytes()); + extra.extend_from_slice(&local.to_le_bytes()); + } + out.extend_from_slice(b"PK\x03\x04"); + out.extend_from_slice(&[20, 0, 0, 0]); + out.extend_from_slice(&method.to_le_bytes()); + out.extend_from_slice(&[0; 4]); + out.extend_from_slice(&crc.to_le_bytes()); + out.extend_from_slice(&big(body.len() as u64).to_le_bytes()); + out.extend_from_slice(&big(data.len() as u64).to_le_bytes()); + out.extend_from_slice(&(name.len() as u16).to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(name.as_bytes()); + out.extend_from_slice(&body); + central.extend_from_slice(b"PK\x01\x02"); + central.extend_from_slice(&[45, 0, 45, 0, 0, 0]); + central.extend_from_slice(&method.to_le_bytes()); + central.extend_from_slice(&[0; 4]); + central.extend_from_slice(&crc.to_le_bytes()); + central.extend_from_slice(&big(body.len() as u64).to_le_bytes()); + central.extend_from_slice(&big(data.len() as u64).to_le_bytes()); + central.extend_from_slice(&(name.len() as u16).to_le_bytes()); + central.extend_from_slice(&(extra.len() as u16).to_le_bytes()); + // comment length, disk number, internal attributes, external attributes + central.extend_from_slice(&[0; 6]); + central.extend_from_slice(&0u32.to_le_bytes()); + central.extend_from_slice(&big(local).to_le_bytes()); + central.extend_from_slice(name.as_bytes()); + central.extend_from_slice(&extra); + } + let dir_at = out.len() as u64; + out.extend_from_slice(¢ral); + let count = files.len() as u64; + if zip64 { + let rec_at = out.len() as u64; + out.extend_from_slice(b"PK\x06\x06"); + out.extend_from_slice(&44u64.to_le_bytes()); + out.extend_from_slice(&[45, 0, 45, 0]); + out.extend_from_slice(&[0; 8]); + out.extend_from_slice(&count.to_le_bytes()); + out.extend_from_slice(&count.to_le_bytes()); + out.extend_from_slice(&(central.len() as u64).to_le_bytes()); + out.extend_from_slice(&dir_at.to_le_bytes()); + out.extend_from_slice(b"PK\x06\x07"); + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(&rec_at.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); + } + out.extend_from_slice(b"PK\x05\x06"); + out.extend_from_slice(&[0; 4]); + let c16 = if zip64 { 0xFFFF } else { count as u16 }; + out.extend_from_slice(&c16.to_le_bytes()); + out.extend_from_slice(&c16.to_le_bytes()); + out.extend_from_slice(&(if zip64 { 0xFFFF_FFFF } else { central.len() as u32 }).to_le_bytes()); + out.extend_from_slice(&(if zip64 { 0xFFFF_FFFF } else { dir_at as u32 }).to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out + } + + /// A fresh, empty folder for one test. + fn temp(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-lrbackup-test-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + /// The private extraction folders still in `root`. + fn leftovers(root: &Path) -> Vec { + let Ok(dir) = std::fs::read_dir(root) else { return Vec::new() }; + dir.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).filter(|n| n.starts_with(PREFIX)).collect() + } + + /// Stored, deflated and ZIP64 backups give back the catalog byte for byte, under the fixed name, and leave nothing. + #[test] + fn stored_deflated_and_zip64_backups_unpack_their_catalog_and_clean_up() { + let catalog: Vec = (0..300_000u32).flat_map(|i| (i % 251).to_le_bytes()).collect(); + for (deflate, zip64) in [(false, false), (true, false), (true, true), (false, true)] { + let dir = temp(&format!("ok-{deflate}-{zip64}")); + let path = dir.join("Cat.zip"); + let files: [(&str, &[u8]); 3] = [("Cat.lrcat", &catalog), ("Cat.lrcat-data/CURRENT", b"MANIFEST-1\n"), ("__MACOSX/._Cat.lrcat", b"x")]; + std::fs::write(&path, zip(&files, deflate, zip64)).unwrap(); + let root = dir.join("tmp"); + let got = extract(&path, &root, &AtomicBool::new(false)).unwrap(); + assert_eq!(std::fs::read(&got.catalog).unwrap(), catalog, "deflate {deflate} zip64 {zip64}"); + assert_eq!(got.entry, "Cat.lrcat"); + assert_eq!(got.catalog.file_name().unwrap(), "catalog.lrcat", "a fixed name, never the zip's"); + drop(got); + assert!(leftovers(&root).is_empty(), "the private folder is removed"); + std::fs::remove_dir_all(&dir).unwrap(); + } + } + + /// Not a zip, empty, no or two catalogs, cut short, bad CRC, or cancelled: an error, and no folder left. + #[test] + fn damaged_or_wrong_zips_are_errors_and_leave_nothing_behind() { + let dir = temp("bad"); + let root = dir.join("tmp"); + let catalog = vec![7u8; 100_000]; + let good = zip(&[("Cat.lrcat", &catalog)], true, false); + let cases: Vec<(&str, Vec)> = vec![ + ("not a zip", b"SQLite format 3\0".to_vec()), + ("empty", Vec::new()), + ("no catalog", zip(&[("notes.txt", b"hi")], false, false)), + ("two catalogs", zip(&[("A.lrcat", b"a"), ("B.lrcat", b"b")], false, false)), + ("cut short", good.get(..good.len() / 2).unwrap().to_vec()), + ("bad crc", { + let mut z = good.clone(); + // flip one byte of the deflated data (after the 30-byte local header and the name) + z[30 + 9 + 10] ^= 0xFF; + z + }), + ]; + for (what, bytes) in cases { + let path = dir.join("x.zip"); + std::fs::write(&path, &bytes).unwrap(); + assert!(extract(&path, &root, &AtomicBool::new(false)).is_err(), "{what} must fail"); + if root.exists() { + assert!(leftovers(&root).is_empty(), "{what} left a folder"); + } + } + std::fs::write(dir.join("x.zip"), &good).unwrap(); + assert!(extract(&dir.join("x.zip"), &root, &AtomicBool::new(true)).is_err(), "cancel stops"); + assert!(leftovers(&root).is_empty(), "cancel cleans up"); + std::fs::remove_dir_all(&dir).unwrap(); + } + + /// A ZIP64 size of 1 TB is refused before anything is written. + #[test] + fn a_zip_that_lies_about_the_catalog_size_is_refused() { + let dir = temp("size"); + let mut z = zip(&[("Cat.lrcat", &[1u8; 1000])], true, true); + // the ZIP64 extra field's uncompressed size: 1 TB + let at = z.windows(4).rposition(|w| w == [1, 0, 24, 0]).unwrap() + 4; + z[at..at + 8].copy_from_slice(&(1u64 << 40).to_le_bytes()); + std::fs::write(dir.join("x.zip"), &z).unwrap(); + let err = extract(&dir.join("x.zip"), &dir.join("tmp"), &AtomicBool::new(false)).unwrap_err(); + assert!(err.contains("more than LightCraft reads"), "{err}"); + std::fs::remove_dir_all(&dir).unwrap(); + } + + /// A day-old leftover folder is removed; a recent one (another import still reading) is kept. + #[cfg(unix)] + #[test] + fn stale_leftovers_are_swept_and_recent_ones_kept() { + let root = temp("sweep"); + let old = root.join(format!("{PREFIX}1-1")); + let recent = root.join(format!("{PREFIX}2-2")); + std::fs::create_dir_all(&old).unwrap(); + std::fs::create_dir_all(&recent).unwrap(); + let past = std::time::SystemTime::now() - std::time::Duration::from_secs(STALE_SECS + 60); + File::open(&old).unwrap().set_modified(past).unwrap(); + sweep(&root); + assert!(!old.exists() && recent.exists()); + std::fs::remove_dir_all(&root).unwrap(); + } + + /// Paths relative to the catalog resolve from where Lightroom kept it, not from the zip. + #[test] + fn the_original_catalog_is_two_folders_above_a_dated_backup() { + let zip = Path::new("/p/Lightroom/Backups/2023-11-07 0900/Cat-v13.zip"); + assert_eq!(original_catalog(zip, "Cat-v13.lrcat"), (PathBuf::from("/p/Lightroom/Cat-v13.lrcat"), true)); + // a backup folder of the person's choosing: a guess for paths, not an identity + assert_eq!(original_catalog(Path::new("/elsewhere/Cat.zip"), "sub/Cat.lrcat"), (PathBuf::from("/elsewhere/Cat.lrcat"), false)); + let chosen = Path::new("/Volumes/Ext/LR Backups/2026-10-22 1200/Cat.zip"); + assert!(!original_catalog(chosen, "Cat.lrcat").1); + assert!(is_backup(Path::new("a/B.ZIP")) && !is_backup(Path::new("a/B.lrcat"))); + } + + /// Folder detection counts a zip only when its directory lists exactly one catalog. + #[test] + fn only_a_zip_with_one_catalog_holds_one() { + let dir = temp("holds"); + let cases: [(&str, Vec, bool); 4] = [ + ("one.zip", zip(&[("Cat.lrcat", b"x"), ("Cat.lrcat-data/CURRENT", b"y")], true, false), true), + ("none.zip", zip(&[("photo.jpg", b"x")], false, false), false), + ("two.zip", zip(&[("A.lrcat", b"a"), ("B.lrcat", b"b")], false, false), false), + ("junk.zip", b"PK".to_vec(), false), + ]; + for (name, bytes, want) in cases { + std::fs::write(dir.join(name), bytes).unwrap(); + assert_eq!(holds_catalog(&dir.join(name)), want, "{name}"); + } + assert!(!holds_catalog(&dir.join("absent.zip"))); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 8647be9b39..9a84b37ddb 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -78,6 +78,15 @@ impl Reader { .collect()) } + /// The catalog's `Adobe_storeProviderID` (a UUID), kept by Lightroom in its backups; `None` + /// when the table or the value is missing or doesn't look like an id. + fn catalog_id(&self) -> Option { + let rows = self.table("Adobe_variablesTable", false).ok()?; + let row = rows.iter().find(|r| text(r, "name") == "Adobe_storeProviderID")?; + let id = text(row, "value").trim(); + (!id.is_empty() && id.len() <= 128 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')).then(|| id.to_string()) + } + fn optional_table(&self, name: &str, warnings: &mut Vec) -> Result, String> { match self.table(name, false) { Ok(rows) => Ok(rows), @@ -176,6 +185,16 @@ impl CatalogPhoto { #[derive(Clone, Debug, Serialize, Deserialize)] pub struct CatalogImport { pub source: String, + /// The catalog's own id (`Adobe_storeProviderID` in `Adobe_variablesTable`), the same in the + /// catalog and in every backup of it, so a backup's collections match those of an earlier import + /// of the catalog (issue #2592). `None` when the catalog has none. + #[serde(default)] + pub catalog_id: Option, + /// Where the catalog was when it isn't `source`: for a backup zip, the `.lrcat` it was backed up + /// from. Collections imported by earlier releases are keyed on that path, so a backup still finds + /// them. `None` when the catalog was read where it is. + #[serde(default)] + pub catalog_path: Option, pub photos: Vec, pub collections: Vec, pub members: Vec, @@ -215,6 +234,11 @@ pub enum SkipReason { pub(crate) struct ImportIndex { pub(crate) photos: BTreeMap, pub(crate) collections: BTreeMap, + /// The catalog id (`Adobe_storeProviderID`) each collection key was recorded for, when the + /// import had one: a path key of one catalog never matches another catalog that later sits at + /// the same path. Keys without an owner (earlier releases, catalogs without an id) match any. + #[serde(default)] + pub(crate) collection_owners: BTreeMap, } pub(crate) fn load_index(path: Option<&Path>) -> crate::Result { @@ -246,7 +270,12 @@ pub(crate) struct AppliedImport { } fn identity(data: &CatalogImport, photo: &CatalogPhoto) -> String { - if photo.uuid.is_empty() { format!("{}:{}", key(&data.source), photo.source_id) } else { photo.uuid.clone() } + // (a backup's photos are recognised by the catalog it was made from, as the catalog's own are) + if photo.uuid.is_empty() { + format!("{}:{}", key(data.catalog_path.as_deref().unwrap_or(&data.source)), photo.source_id) + } else { + photo.uuid.clone() + } } fn validate(data: &CatalogImport) -> Result<(), String> { @@ -440,10 +469,47 @@ pub fn read(path: &Path) -> Result { /// stopping when `cancel` is set. Images whose catalog records are incomplete are left out and /// listed in [`CatalogImport::skipped`] instead of failing the read. pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, done: &AtomicUsize) -> Result { + read_source(path, None, cancel, total, done) +} + +/// Where a Lightroom backup's catalog is unpacked while it is read: the open library's `Interop/` +/// folder (on the library's disk), or `None` for the system's temporary folder. +pub fn backup_temp_root(s: &crate::Session) -> Option { + s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Interop")) +} + +/// [`read_with_progress`] of a catalog or of a Lightroom catalog backup (`.zip`, issue #2592): a +/// backup's catalog is unpacked into a private folder under `temp_root` (else the system's temporary +/// folder), read, and removed again ([`crate::lightroom_backup`]). Paths the catalog records +/// relative to itself are taken from where the catalog was before it was backed up. +pub fn read_source( + path: &Path, + temp_root: Option<&Path>, + cancel: &AtomicBool, + total: &AtomicUsize, + done: &AtomicUsize, +) -> Result { // 13 catalog tables plus one validation stage; ImportJob adds one unit per original path. total.store(14, Ordering::Relaxed); done.store(0, Ordering::Relaxed); ensure_read_active(cancel)?; + if crate::lightroom_backup::is_backup(path) { + let root = temp_root.map_or_else(std::env::temp_dir, Path::to_path_buf); + let extracted = crate::lightroom_backup::extract(path, &root, cancel)?; + let (document, known) = crate::lightroom_backup::original_catalog(path, &extracted.entry); + let mut data = read_file(&extracted.catalog, &document, path, cancel, done)?; + if !known { + // only a guess: it resolves relative paths, but never names the catalog + data.catalog_path = None; + } + return Ok(data); + } + read_file(path, path, path, cancel, done) +} + +/// Read the catalog file `path`, resolving the paths it records with `document` as the catalog's +/// place and reporting `source` as where it came from. +fn read_file(path: &Path, document: &Path, source: &Path, cancel: &AtomicBool, done: &AtomicUsize) -> Result { let before = std::fs::metadata(path).map_err(|e| e.to_string())?; let wal_path = PathBuf::from(format!("{}-wal", path.display())); let wal_before = std::fs::metadata(&wal_path).ok().map(|m| (m.len(), m.modified().ok())); @@ -529,7 +595,7 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, root_ids.sort_unstable(); for (id, root) in root_ids.iter().filter_map(|id| Some((*id, roots.get(id)?))) { let absolute = text(root, "absolutePath"); - let resolved = match relocated_root(absolute, text(root, "relativePathFromCatalog"), path) { + let resolved = match relocated_root(absolute, text(root, "relativePathFromCatalog"), document) { Some(found) => { let found = found.to_string_lossy().to_string(); warnings.push(format!("root folder {}: {absolute} not found; using {found} (relative to the catalog)", text(root, "name"))); @@ -537,7 +603,7 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, } None => absolute.to_string(), }; - if let Err(crate::doc_path::NotFollowed::Refused(why)) = crate::doc_path::resolve(&resolved, Some(path)) { + if let Err(crate::doc_path::NotFollowed::Refused(why)) = crate::doc_path::resolve(&resolved, Some(document)) { warnings .push(format!("root folder {}: {resolved} is not opened: {why}; its photos are listed as missing and not added", text(root, "name"))); refused_roots.insert(id); @@ -547,7 +613,9 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, let mut history = group(optional_table("Adobe_libraryImageDevelopHistoryStep", &mut warnings)?); let mut snapshots = group(optional_table("Adobe_libraryImageDevelopSnapshot", &mut warnings)?); let mut out = CatalogImport { - source: path.to_string_lossy().into(), + source: source.to_string_lossy().into(), + catalog_id: reader.catalog_id(), + catalog_path: (document != source).then(|| document.to_string_lossy().into()), photos: Vec::new(), collections: optional_table("AgLibraryCollection", &mut warnings)?, members: optional_table("AgLibraryCollectionImage", &mut warnings)?, @@ -584,7 +652,7 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, orphans.insert(id); continue; } - let (photo_path, original) = original_path(root_path, folder_path, name, path); + let (photo_path, original) = original_path(root_path, folder_path, name, document); if let Original::Refused(why) = &original && !refused_roots.contains(&root_id) { @@ -705,7 +773,12 @@ fn mapped_settings( ) -> Result<(Value, Vec), String> { let mut root = crate::preset_import::parse_lua(text)?; let deferred = strip_lua_sentinels(&mut root); - let (mut props, values) = crate::preset_import::lua_settings_props(&root)?; + let (mut props, mut values) = crate::preset_import::lua_settings_props(&root)?; + // Catalog Lua names the component inversion `Inverted` while XMP's is `MaskInverted`; + // rename it so an inverted mask keeps its inversion instead of importing as normal. + for v in values.values_mut() { + alias_catalog_inverted(v); + } // A catalog's develop settings carry the crop edges and angle but no `HasCrop` (XMP has it): // any crop field means the photo is cropped. const CROP: [&str; 5] = ["crs:CropLeft", "crs:CropTop", "crs:CropRight", "crs:CropBottom", "crs:CropAngle"]; @@ -787,6 +860,24 @@ fn in_photo_frame(catalog: Orientation, user: Orientation) -> Orientation { (0..turns).fold(o, |o, _| o.rotated(true)) } +/// Rename a catalog Lua component's `Inverted` to XMP's `MaskInverted` (see [`mapped_settings`]); +/// a `crs:MaskInverted` already present wins, and this does not touch `Flipped`. +fn alias_catalog_inverted(v: &mut lightcraft_meta::XmpValue) { + use lightcraft_meta::XmpValue; + match v { + XmpValue::Array(items) => items.iter_mut().for_each(alias_catalog_inverted), + XmpValue::Struct(map) => { + if let Some(inverted) = map.remove("crs:Inverted") + && !map.contains_key("crs:MaskInverted") + { + map.insert("crs:MaskInverted".into(), inverted); + } + map.values_mut().for_each(alias_catalog_inverted); + } + XmpValue::Text(_) => {} + } +} + /// Lightroom's masks in LightCraft's frame. Like the crop's corners, their positions are on the /// stored image (before orientation), normalized to its size; LightCraft's are on the oriented /// image. So the points go through the orientation, a radial's radii (in long-edge units, from the @@ -983,14 +1074,34 @@ fn stage_collections( if number(collection, "systemOnly") != 0 { continue; } - let collection_key = format!("{}:{}", key(&data.source), number(collection, "id_local")); - let indexed = index - .collections - .get(&collection_key) - .copied() + // keyed on the catalog's own id (the same in its backups); imports made before that was + // read are keyed on the catalog's path, and are still found by it, also from a backup (the + // path of the catalog it was backed up from) + let path_key = format!("{}:{}", key(&data.source), number(collection, "id_local")); + let original_key = data.catalog_path.as_ref().map(|p| format!("{}:{}", key(p), number(collection, "id_local"))); + let collection_key = data.catalog_id.as_ref().map_or_else(|| path_key.clone(), |c| format!("lrcat:{c}:{}", number(collection, "id_local"))); + // A path can be reused by a different catalog. Without an ID we cannot prove that an + // owned path key belongs to this input, so refuse instead of silently mixing albums. + if data.catalog_id.is_none() + && [Some(&path_key), original_key.as_ref()].into_iter().flatten().any(|k| index.collection_owners.contains_key(k)) + { + return Err(error( + "the Lightroom catalog has no stable identity and its path was previously associated with a catalog; cannot safely match collections", + )); + } + // a key recorded for another catalog (by its id) is not this one, whatever its path + let mine = |k: &String| match (data.catalog_id.as_ref(), index.collection_owners.get(k)) { + (Some(c), Some(owner)) => owner == c, + _ => true, + }; + let id = [Some(&collection_key), Some(&path_key), original_key.as_ref()] + .into_iter() + .flatten() + .filter(|k| mine(k)) + .filter_map(|k| index.collections.get(k).copied()) .map(lightcraft_catalog::AlbumId) - .filter(|id| s.catalog.album(*id).is_some() && !assigned.contains(id)); - let id = match indexed { + .find(|id| s.catalog.album(*id).is_some() && !assigned.contains(id)); + let id = match id { Some(id) => id, None => { let id = s.catalog.alloc_album_id(); @@ -1004,7 +1115,16 @@ fn stage_collections( } }; assigned.insert(id); - index.collections.insert(collection_key, id.0); + // recorded under its id and the live catalog's path (a backup's: the catalog it was made + // from), so a later import of the same catalog finds it in either order; a zip's own path + // is not kept when the catalog's is known (every dated backup has a new one) + let path_kept = if data.catalog_path.is_some() { None } else { Some(path_key) }; + for k in [Some(collection_key), path_kept, original_key].into_iter().flatten() { + if let Some(c) = &data.catalog_id { + index.collection_owners.insert(k.clone(), c.clone()); + } + index.collections.insert(k, id.0); + } albums.insert(number(collection, "id_local"), id); } let parents: HashMap<_, _> = rows.iter().map(|r| (number(r, "id_local"), number(r, "parent"))).collect(); diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index e2952fd000..837db27c90 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -24,6 +24,8 @@ fn sample() -> CatalogImport { photo.image.insert("captureTime".into(), json!("2024-01-16T12:34:56")); CatalogImport { source: "test.lrcat".into(), + catalog_id: None, + catalog_path: None, photos: vec![copy, photo], collections: vec![ row(json!({"id_local":9,"name":"Travel","creationId":"collection.group"})), @@ -850,6 +852,22 @@ fn catalog_masks_follow_the_photo_orientation() { assert!(close(&radial["rx"], 0.1) && close(&radial["ry"], 0.1), "{radial}"); } +#[test] +fn inverted_radial_mask_keeps_its_inversion_on_import() { + // #2475: an inverted radial (LocalExposure2012 applies outside the ellipse) keeps its + // inversion when the catalog import also turns the mask for the photo's orientation + let s = r#"s = { MaskGroupBasedCorrections = { { What = "Correction", CorrectionAmount = 1, LocalExposure2012 = 0.1, CorrectionMasks = { + { What = "Mask/CircularGradient", Left = 0, Right = 0.2, Top = 0.1, Bottom = 0.3, Angle = 10, Feather = 50, Version = 2, Flipped = true, Inverted = true } } } } }"#; + let (partial, _) = mapped_settings(s, crate::crs::Target::RawAbsolute, 1.5, Orientation::Rotate90, 1.5, Orientation::Normal).unwrap(); + let c = &partial["masks"][0]["components"][0]; + let close = |v: &Value, want: f64| (v.as_f64().unwrap() - want).abs() < 1e-9; + // the orientation is applied: (x, y) → (1 − y, x), a quarter turn clockwise; the radii swap + let shape = &c["shape"]; + assert!(close(&shape["center"]["x"], 0.8) && close(&shape["center"]["y"], 0.1), "{shape}"); + // but the effect stays outside the ellipse + assert!(c["invert"].as_bool().unwrap_or(false) || shape["invert"].as_bool().unwrap_or(false), "{c}"); +} + /// The `crs` corners and angle Lightroom would store for LightCraft crop `g` on a stored image /// of aspect `w` (height 1) shown with orientation `o`. fn lightroom_crop(g: CropGeometry, o: Orientation, w: f64) -> String { @@ -1072,6 +1090,178 @@ fn wal_checksums_cover_commits_without_materializing_historical_databases() { } } +/// Issue #2592: a catalog in Lightroom's backup layout (`Backups//.zip`), with one +/// collection and the catalog's own id. +fn backup_fixture(root: &Path, catalog_id: &str) -> (PathBuf, PathBuf) { + use SqlValue::{Integer as I, Null as N, Text as T}; + let mut tables: Vec<(&str, &str, Vec>)> = one_row(photo_tables(("/catalog/", ""))); + tables.push(( + "AgLibraryCollection", + "id_local INTEGER PRIMARY KEY, creationId, name, parent, systemOnly", + vec![vec![N, T("com.adobe.ag.library.collection".into()), T("Keepers".into()), N, I(0)]], + )); + tables.push(("AgLibraryCollectionImage", "id_local INTEGER PRIMARY KEY, collection, image", vec![vec![N, I(1), I(1)]])); + tables.push(( + "Adobe_variablesTable", + "id_local INTEGER PRIMARY KEY, id_global, name, type, value", + vec![vec![N, T("v1".into()), T("Adobe_storeProviderID".into()), N, T(catalog_id.into())]], + )); + let bytes = native_catalog_rows(&tables, None); + let folder = root.join("Lightroom"); + let dated = folder.join("Backups").join("2023-11-07 0900"); + std::fs::create_dir_all(&dated).unwrap(); + let live = folder.join("Cat.lrcat"); + std::fs::write(&live, &bytes).unwrap(); + let zip = dated.join("Cat.zip"); + let files: [(&str, &[u8]); 2] = [("Cat.lrcat", &bytes), ("Cat.lrcat-data/CURRENT", b"MANIFEST-000005\n")]; + std::fs::write(&zip, crate::lightroom_backup::tests::zip(&files, true, false)).unwrap(); + (live, zip) +} + +/// How many albums the library has. +fn albums(s: &crate::Session) -> usize { + s.catalog.albums().count() +} + +/// The zip imports the same photos and collections as its catalog, with the zip as source, no temp files and the zip unchanged. +#[test] +fn a_backup_zip_imports_like_its_catalog_and_leaves_no_temporary_files() { + let root = std::env::temp_dir().join(format!("lightcraft-lrbackup-zip-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let (live, zip) = backup_fixture(&root, "968AF29B-EEE2-481E-8AF9-55DD82965F49"); + let zip_before = std::fs::read(&zip).unwrap(); + let from_zip = read(&zip).unwrap(); + let from_live = read(&live).unwrap(); + assert_eq!(from_zip.source, zip.to_string_lossy(), "the zip is the import's source"); + assert_eq!(from_zip.catalog_id.as_deref(), Some("968AF29B-EEE2-481E-8AF9-55DD82965F49")); + assert_eq!((from_zip.photos.len(), from_zip.collections.len()), (from_live.photos.len(), from_live.collections.len())); + assert_eq!(from_zip.photos[0].path, from_live.photos[0].path); + // the live catalog is gone (Lightroom uninstalled): the backup alone imports into a library + std::fs::remove_file(&live).unwrap(); + let lib = root.join("Library"); + let mut s = crate::Session::new(); + s.open_library(&lib, false).unwrap(); + let report = import(&mut s, &zip, false).unwrap(); + assert_eq!((report["photos"].as_u64(), report["collections"].as_u64()), (Some(1), Some(1))); + assert_eq!(report["source"], json!(zip.to_string_lossy())); + assert_eq!(albums(&s), 1); + let interop: Vec<_> = std::fs::read_dir(lib.join("Interop")).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + assert!(!interop.iter().any(|n| n.starts_with("lc-lrbackup-")), "the unpacked catalog is removed: {interop:?}"); + assert_eq!(std::fs::read(&zip).unwrap(), zip_before, "the backup is only read"); + let _ = std::fs::remove_dir_all(&root); +} + +/// Issue #2606: the backup of an imported catalog matches its collections by the catalog id. +#[test] +fn importing_a_backup_after_its_catalog_adds_no_album_twice() { + let root = std::env::temp_dir().join(format!("lightcraft-lrbackup-twice-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let (live, zip) = backup_fixture(&root, "968AF29B-EEE2-481E-8AF9-55DD82965F49"); + let mut s = crate::Session::new(); + s.open_library(root.join("Library"), false).unwrap(); + import(&mut s, &live, false).unwrap(); + assert_eq!(albums(&s), 1); + let again = import(&mut s, &zip, false).unwrap(); + assert_eq!(again["imported"], 0, "the photos are matched by their Lightroom id"); + assert_eq!(albums(&s), 1, "the collections are matched by the catalog's id, not its path"); + let _ = std::fs::remove_dir_all(&root); +} + +/// A backup of a catalog that an earlier release imported (collections keyed on the live +/// `.lrcat` path, no catalog id) finds those albums through the path it was backed up from. +#[test] +fn a_backup_finds_collections_an_earlier_release_keyed_on_the_live_catalog_path() { + let root = std::env::temp_dir().join(format!("lightcraft-lrbackup-legacy-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let (live, zip) = backup_fixture(&root, "968AF29B-EEE2-481E-8AF9-55DD82965F49"); + let mut s = crate::Session::new(); + s.open_library(root.join("Library"), false).unwrap(); + // an earlier release: the live catalog imported without its id (path keys only) + let mut old = read(&live).unwrap(); + old.catalog_id = None; + apply(&mut s, old, false).unwrap(); + assert_eq!(albums(&s), 1); + let backup = read(&zip).unwrap(); + assert_eq!(backup.catalog_path.as_deref(), Some(live.to_string_lossy().as_ref()), "where the zip's catalog was"); + apply(&mut s, backup, false).unwrap(); + assert_eq!(albums(&s), 1, "the backup finds the albums keyed on the live catalog's path"); + let _ = std::fs::remove_dir_all(&root); +} + +/// Issue #2606, the other order: a backup without a catalog id imported first, then the live +/// catalog (no id either) finds the same albums through the live path the backup recorded. +#[test] +fn the_live_catalog_after_a_backup_without_an_id_adds_no_album_twice() { + let root = std::env::temp_dir().join(format!("lightcraft-lrbackup-noid-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let (live, zip) = backup_fixture(&root, "968AF29B-EEE2-481E-8AF9-55DD82965F49"); + let mut s = crate::Session::new(); + s.open_library(root.join("Library"), false).unwrap(); + let mut backup = read(&zip).unwrap(); + backup.catalog_id = None; + apply(&mut s, backup, false).unwrap(); + assert_eq!(albums(&s), 1); + let mut current = read(&live).unwrap(); + current.catalog_id = None; + apply(&mut s, current, false).unwrap(); + assert_eq!(albums(&s), 1, "the live catalog finds the albums the backup imported"); + let _ = std::fs::remove_dir_all(&root); +} + +/// Issue #2606, the reviewer's second order: a backup with an id, then the live catalog read +/// without one, is rejected rather than risk matching a different catalog at the same path. +#[test] +fn the_live_catalog_without_an_id_after_a_backup_with_one_adds_no_album_twice() { + let root = std::env::temp_dir().join(format!("lightcraft-lrbackup-idthennone-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let (live, zip) = backup_fixture(&root, "968AF29B-EEE2-481E-8AF9-55DD82965F49"); + let mut s = crate::Session::new(); + s.open_library(root.join("Library"), false).unwrap(); + apply(&mut s, read(&zip).unwrap(), false).unwrap(); + let mut current = read(&live).unwrap(); + current.catalog_id = None; + let err = apply(&mut s, current, false).unwrap_err(); + assert!(err.to_string().contains("no stable identity")); + assert_eq!(albums(&s), 1, "an ambiguous path must not change albums"); + let _ = std::fs::remove_dir_all(&root); +} + +/// Two different catalogs (different ids) that sat at the same path, one after the other (a +/// new computer's default location, a catalog recreated), keep their own albums even with the +/// same collection `id_local`. +#[test] +fn two_catalogs_at_the_same_path_keep_their_own_albums() { + let root = std::env::temp_dir().join(format!("lightcraft-lrcat-samepath-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let (live, _) = backup_fixture(&root, "AAAAAAAA-0000-0000-0000-000000000001"); + let mut s = crate::Session::new(); + s.open_library(root.join("Library"), false).unwrap(); + apply(&mut s, read(&live).unwrap(), false).unwrap(); + // another catalog, now at the same path + let (live2, _) = backup_fixture(&root, "BBBBBBBB-0000-0000-0000-000000000002"); + assert_eq!(live, live2); + apply(&mut s, read(&live2).unwrap(), false).unwrap(); + assert_eq!(albums(&s), 2, "the second catalog's collection is its own album"); + let _ = std::fs::remove_dir_all(&root); +} + +/// Libraries imported by earlier releases (path keys) still find their albums. +#[test] +fn collections_imported_before_the_catalog_id_was_read_are_still_matched_by_path() { + let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-pathkey-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = crate::Session::new(); + s.open_library(&dir, false).unwrap(); + // an import made by an earlier release: no catalog id, keys on the path + apply(&mut s, sample(), false).unwrap(); + let before = albums(&s); + let mut data = sample(); + data.catalog_id = Some("A-B".into()); + apply(&mut s, data, false).unwrap(); + assert_eq!(albums(&s), before, "the old path keys still find the albums"); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn persistent_reimport_keeps_copy_and_collection_ids_and_capture_time() { let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-reimport-{}", std::process::id())); @@ -1159,7 +1349,9 @@ fn native_catalog_with_last_table_page(tables: &[(&str, &str, Vec)], l /// table's root page. fn native_catalog_rows(tables: &[(&str, &str, Vec>)], last_page: Option) -> Vec { use SqlValue::{Integer as I, Text as T}; - let mut bytes = vec![0u8; 5 * 2048]; + // the schema page, then one page per table (at least four: the photo tables) + let pages = (tables.len() + 1).max(5); + let mut bytes = vec![0u8; pages * 2048]; bytes[..16].copy_from_slice(b"SQLite format 3\0"); bytes[16..18].copy_from_slice(&2048u16.to_be_bytes()); bytes[18] = 1; @@ -1167,7 +1359,7 @@ fn native_catalog_rows(tables: &[(&str, &str, Vec>)], last_page: O bytes[21] = 64; bytes[22] = 32; bytes[23] = 32; - bytes[28..32].copy_from_slice(&5u32.to_be_bytes()); + bytes[28..32].copy_from_slice(&(pages as u32).to_be_bytes()); bytes[44..48].copy_from_slice(&4u32.to_be_bytes()); bytes[56..60].copy_from_slice(&1u32.to_be_bytes()); let mut schema = Vec::new(); diff --git a/crates/engine/src/lightroom_folder.rs b/crates/engine/src/lightroom_folder.rs index 0b5a85659a..5bd2c52d3a 100644 --- a/crates/engine/src/lightroom_folder.rs +++ b/crates/engine/src/lightroom_folder.rs @@ -6,14 +6,20 @@ //! an empty LightCraft library inside Lightroom's folder; [`Session::open_library`] refuses with //! [`EngineError::LightroomCatalog`] instead, and the app offers File ▸ Import Lightroom Catalog…. //! -//! What counts (only names are looked at; no catalog is opened or read): +//! What counts (only names are looked at, and a backup zip's list of files; no catalog is opened +//! or read): //! - a LightCraft library (`catalog.snap` or `catalog.log` in the folder) is never a Lightroom //! catalog, whatever else the folder holds: it opens as before; //! - a path named `*.lrcat` or one of its companions (`*.lrcat-wal`, `*.lrcat-shm`, //! `*.lrcat-journal`, `*.lrcat.lock`); //! - a folder named `*.lrdata` or `*.lrcat-data` (Lightroom's previews and data); //! - a folder holding a `*.lrcat` at its top level (the catalog folder itself), or `Backups/` -//! next to one. +//! next to one; +//! - Lightroom's backups (issue #2592), even with the catalog itself gone: a `Backups/` folder or +//! one of its dated folders, `Backups/YYYY-MM-DD HHMM/`, holding a `*.zip` with one `.lrcat` in +//! it ([`crate::lightroom_backup::holds_catalog`]). A dated folder names +//! its zip; `Backups/` names one only when it holds a single backup, since the person has to choose +//! among several (the import then asks for the file). //! //! The folder scan is bounded ([`SCAN_LIMIT`] entries, top level only) and every I/O error just //! means "not found": this never fails and never panics. @@ -133,6 +139,41 @@ pub fn lightroom_catalog_at(path: &Path) -> Option { { return Some(LightroomPlace { catalog: Some(catalog) }); } + // `Backups/` alone (the catalog deleted): its backup when there is only one; with several, + // which one to import is the person's choice + if lower == "backups" + && let Some(backups) = backup_zips(path) + { + let catalog = if backups.len() == 1 { backups.into_iter().next() } else { None }; + return Some(LightroomPlace { catalog }); + } + // a dated backup folder, `Backups/2023-11-07 0900/` + if parent.and_then(lower_name).as_deref() == Some("backups") + && let Some(zip) = find_backup_zip(path) + { + return Some(LightroomPlace { catalog: Some(zip) }); + } } None } + +/// The first `*.zip` file (by name) at the top level of `dir` that holds a Lightroom catalog, +/// looking at no more than [`SCAN_LIMIT`] entries. +fn find_backup_zip(dir: &Path) -> Option { + let entries = std::fs::read_dir(dir).ok()?; + entries + .take(SCAN_LIMIT) + .flatten() + .map(|e| e.path()) + .filter(|p| crate::lightroom_backup::is_backup(p) && p.is_file()) + .filter(|p| crate::lightroom_backup::holds_catalog(p)) + .min() +} + +/// The backup zips in the dated folders of `backups`, one per folder; `None` when there are none. +fn backup_zips(backups: &Path) -> Option> { + let entries = std::fs::read_dir(backups).ok()?; + let zips: Vec = + entries.take(SCAN_LIMIT).flatten().map(|e| e.path()).filter(|p| p.is_dir()).filter_map(|d| find_backup_zip(&d)).collect(); + (!zips.is_empty()).then_some(zips) +} diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rs index 762c8588df..defdb850f0 100644 --- a/crates/engine/src/lightroom_job.rs +++ b/crates/engine/src/lightroom_job.rs @@ -241,8 +241,14 @@ impl LightroomJob { return Err(cancelled()); } // (reading stops with a message when `cancel` is set: the flag says it was cancelled) - let mut data = lightroom_catalog::read_with_progress(&self.path, cancel, &self.progress.catalog_total, &self.progress.catalog_done) - .map_err(|e| if cancel.load(Ordering::Relaxed) { cancelled() } else { error(e) })?; + let mut data = lightroom_catalog::read_source( + &self.path, + self.archive_dir.as_deref(), + cancel, + &self.progress.catalog_total, + &self.progress.catalog_done, + ) + .map_err(|e| if cancel.load(Ordering::Relaxed) { cancelled() } else { error(e) })?; lightroom_catalog::validate_for_job(&data).map_err(error)?; if cancel.load(Ordering::Relaxed) { return Err(cancelled()); @@ -350,6 +356,8 @@ mod tests { fn empty_data() -> CatalogImport { CatalogImport { source: "fixture.lrcat".into(), + catalog_id: None, + catalog_path: None, photos: Vec::new(), collections: Vec::new(), members: Vec::new(), @@ -384,6 +392,8 @@ mod tests { PreparedLightroom { data: CatalogImport { source: "fixture.lrcat".into(), + catalog_id: None, + catalog_path: None, photos: vec![lightroom_catalog::CatalogPhoto { source_id: 1, uuid: "fixture-photo".into(), diff --git a/crates/engine/src/media/quick.rs b/crates/engine/src/media/quick.rs index 25c93e9f81..f7163b0693 100644 --- a/crates/engine/src/media/quick.rs +++ b/crates/engine/src/media/quick.rs @@ -131,14 +131,31 @@ pub(super) fn embedded_thumb_key(k: Hash128) -> Hash128 { Hasher128::new().str("embedded-thumb").u64((k.0 >> 64) as u64).u64(k.0 as u64).finish() } -/// What identifies a photo's pixels for caching: its content hash, else its source. -/// Which decode of a photo a loaded source is: its file's content and, when it has one, its database lens profile +/// ORF decoding changed when compressed sensor support was withdrawn. Keep its old renders +/// out even before catalog rechecking finishes, and distinguish sensor from preview-only +/// pixels after Reload. Other formats keep their existing keys. This is deliberately not +/// part of `content_key`: smart previews and denoise products identify the original file. +pub(super) fn decoder_key(p: &Photo) -> u64 { + if !p.format.eq_ignore_ascii_case("ORF") { + return 0; + } + // Spread the status bit: this salt is XORed with frontend dimensions, so adjacent + // integers could cancel a small resize occurring at the same time as a recheck. + let h = Hasher128::new().str("orf-withdrawal-v1").u64(u64::from(p.preview_only.is_some())).finish(); + ((h.0 as u64) ^ ((h.0 >> 64) as u64)) | 1 +} + +/// Which decode of a photo a loaded source is: its file's content, decoder identity and database lens profile /// ([`lens_key`]; the decode fits the starting colour through it). A job's source is kept only when this still /// matches when the job finishes ([`super::Session::accept`]), so a decode started before a profile change never /// returns to the cache after `cmd::lens_refresh` has dropped the photo's sources. pub fn source_identity(p: &Photo) -> Hash128 { let mut k = Hasher128::new(); k.str(&content_key(p)); + let decoder = decoder_key(p); + if decoder != 0 { + k.str("decoder").u64(decoder); + } let lens = lens_key(p); if lens != 0 { k.u64(lens); diff --git a/crates/engine/src/media/session.rs b/crates/engine/src/media/session.rs index a3d5069177..4bf40bbf57 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -57,6 +57,7 @@ impl crate::Session { let content_key = content_key(&p); let content = Hasher128::new().str(&content_key).finish().0 as u64; let source_key = super::quick::source_identity(&p); + let decoder = super::quick::decoder_key(&p); // Temporary "before" settings must not replace the photo's cached develop hash. let settings_hash = if before { settings.hash64() ^ crate::files::hot_pixel_key(&settings) } else { self.media.settings_hashes.get(id, &settings) }; @@ -72,7 +73,8 @@ impl crate::Session { ^ content.rotate_left(17) ^ salt ^ profile_salt.rotate_left(29) - ^ lens.rotate_left(37); + ^ lens.rotate_left(37) + ^ decoder.rotate_left(43); let cache = thumb_bucket.map(|b| { let mut k = Hasher128::new(); k.str(&content_key).u64(settings_hash).u64(b as u64).u64(RENDER_CACHE_VERSION); @@ -89,6 +91,9 @@ impl crate::Session { if lens != 0 { k.u64(lens); } + if decoder != 0 { + k.str("decoder").u64(decoder); + } (self.media.rendered.clone(), k.finish()) }); Some(RenderJob { @@ -131,6 +136,7 @@ impl crate::Session { let profile_salt = self.media.camera_profile_salt(&settings.profile.id); // (the photo's database lens profile stays part of it: a profile looked up again renders afresh) let lens = self.catalog.photo(id).map_or(0, |p| super::quick::lens_key(p)); + let decoder = super::quick::decoder_key(&p); job.key = settings.hash64() ^ crate::files::hot_pixel_key(settings) ^ ((max_w as u64) << 40) @@ -138,7 +144,8 @@ impl crate::Session { ^ (apply_crop as u64) ^ (job.level as u64) << 60 ^ profile_salt.rotate_left(29) - ^ lens.rotate_left(37); + ^ lens.rotate_left(37) + ^ decoder.rotate_left(43); Some(job) } @@ -159,6 +166,10 @@ impl crate::Session { if lens != 0 { k.u64(lens); } + let decoder = super::quick::decoder_key(p); + if decoder != 0 { + k.str("decoder").u64(decoder); + } k.finish() } @@ -294,6 +305,10 @@ impl crate::Session { if lens != 0 { k.u64(lens); } + let decoder = super::quick::decoder_key(p); + if decoder != 0 { + k.str("decoder").u64(decoder); + } k.finish() } @@ -422,7 +437,7 @@ impl crate::Session { .u64(id.0) .u64(profile_salt) .finish(); - let key = h.0 as u64; + let key = h.0 as u64 ^ super::quick::decoder_key(&p).rotate_left(43); let embedded = self.embedded_of(&p).map(|(path, l)| (path, l, max_edge.clamp(1, SourceLevel::Preview.max_edge()))); let embedded_cache = embedded.as_ref().map(|(_, _, edge)| { let cache = self.media.rendered.clone(); diff --git a/crates/engine/src/preset_import.rs b/crates/engine/src/preset_import.rs index d1dbc946c6..f224c39972 100644 --- a/crates/engine/src/preset_import.rs +++ b/crates/engine/src/preset_import.rs @@ -42,7 +42,13 @@ pub fn read_zip(bytes: &[u8]) -> Result)>, String> { read_zip_limited(bytes, MAX_ZIP_ENTRY, MAX_ZIP_TOTAL) } -fn read_zip_limited(bytes: &[u8], max_entry: usize, max_total: usize) -> Result)>, String> { +pub(crate) fn read_zip_limited(bytes: &[u8], max_entry: usize, max_total: usize) -> Result)>, String> { + read_zip_spending(bytes, max_entry, max_total, &mut 0) +} + +/// [`read_zip_limited`] that adds to `spent` the bytes of each entry as it is unpacked, so they +/// are counted when a later entry fails; an entry that fails for size spends its whole limit. +pub(crate) fn read_zip_spending(bytes: &[u8], max_entry: usize, max_total: usize, spent: &mut usize) -> Result)>, String> { let u16_at = |o: usize| bytes.get(o..o.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]]) as usize); let u32_at = |o: usize| bytes.get(o..o.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize); // offsets from the file, added up without overflowing (a 32-bit build reads them too) @@ -53,7 +59,7 @@ fn read_zip_limited(bytes: &[u8], max_entry: usize, max_total: usize) -> Result< let count = u16_at(eocd + 10).ok_or("bad zip")?; let mut at = u32_at(eocd + 16).ok_or("bad zip")?; let mut out = Vec::new(); - let mut total = 0usize; + let total = spent; for _ in 0..count { if !bytes.get(at..).is_some_and(|b| b.starts_with(b"PK\x01\x02")) { return Err("bad zip central directory".into()); @@ -76,18 +82,40 @@ fn read_zip_limited(bytes: &[u8], max_entry: usize, max_total: usize) -> Result< } let data_at = add(add(add(local, 30)?, u16_at(add(local, 26)?).ok_or("bad zip")?)?, u16_at(add(local, 28)?).ok_or("bad zip")?)?; let data = bytes.get(data_at..add(data_at, csize)?).ok_or_else(|| format!("{name}: truncated"))?; - let left = max_total.saturating_sub(total); + let left = max_total.saturating_sub(*total); let limit = max_entry.min(left); let too_big = || format!("{name}: unpacks to more than {} MB, too much for a preset", limit >> 20); let content = match method { - 0 if data.len() > limit => return Err(too_big()), + 0 if data.len() > limit => { + *total = total.saturating_add(limit); + return Err(too_big()); + } 0 => data.to_vec(), - 8 => miniz_oxide::inflate::decompress_to_vec_with_limit(data, usize_.max(1).saturating_mul(2).saturating_add(1024).min(limit)).map_err( - |e| if matches!(e.status, miniz_oxide::inflate::TINFLStatus::HasMoreOutput) { too_big() } else { format!("{name}: {e:?}") }, - )?, + 8 => { + // the entry's own stated size, with slack, caps the inflate below `limit` + let cap = usize_.max(1).saturating_mul(2).saturating_add(1024); + match miniz_oxide::inflate::decompress_to_vec_with_limit(data, cap.min(limit)) { + Ok(v) => v, + Err(e) if matches!(e.status, miniz_oxide::inflate::TINFLStatus::HasMoreOutput) && cap < limit => { + // not over the budget: only what was unpacked is spent + *total = total.saturating_add(e.output.len()); + return Err(format!("{name}: unpacks to more than its stated size")); + } + Err(e) if matches!(e.status, miniz_oxide::inflate::TINFLStatus::HasMoreOutput) => { + // past the budget (or the entry limit): its whole limit is spent + *total = total.saturating_add(limit); + return Err(too_big()); + } + Err(e) => { + // what a corrupt stream unpacked before failing was still unpacked: charge it + *total = total.saturating_add(e.output.len()); + return Err(format!("{name}: {:?}", e.status)); + } + } + } m => return Err(format!("{name}: unsupported compression method {m}")), }; - total = total.saturating_add(content.len()); + *total = total.saturating_add(content.len()); out.push((name, content)); } Ok(out) @@ -139,7 +167,11 @@ impl LuaParser<'_> { if self.s[self.i..].starts_with(b"--") { self.i += 2; if let Some(level) = self.long_bracket_level() { - let _ = self.long_string(level); + // an unterminated long comment runs to the end (as in Lua): going on past its + // opening would search the rest of the file again for every such opening + if self.long_string(level).is_err() { + self.i = self.s.len(); + } } else { while self.i < self.s.len() && self.s[self.i] != b'\n' { self.i += 1; @@ -546,14 +578,23 @@ pub fn read_presets(name: &str, bytes: &[u8], group: Option) -> Result { let mut out = Vec::new(); let mut errors = Vec::new(); - for (inner, data) in read_zip(bytes)? { + let entries = read_zip(bytes)?; + // what the archive's entries left of the unpack budget: the Luminar packs inside it + // (archives themselves) unpack within it, not each with a budget of its own + let mut budget = MAX_ZIP_TOTAL.saturating_sub(entries.iter().map(|(_, d)| d.len()).sum()); + for (inner, data) in entries { let iext = Path::new(&inner).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); if !(PRESET_EXTS.contains(&iext.as_str()) || iext == crate::presets::LCPRESET_EXT) || iext == "zip" { continue; } let dir_group = inner.rsplit_once('/').and_then(|(d, _)| group_from_dir(d)).or_else(|| group_from_dir(&stem)).or_else(|| group.clone()); - match read_presets(&inner, &data, dir_group) { + let read = if iext == "mplumpack" { + crate::preset_luminar::read_mplumpack_within(&inner, &data, &mut budget) + } else { + read_presets(&inner, &data, dir_group) + }; + match read { Ok(v) => out.extend(v), Err(e) => errors.push(format!("{inner}: {e}")), } @@ -771,6 +812,68 @@ text]], z = ZSTR "loc" }"#, assert!(photo(r#"crs:WhiteBalance="As Shot""#).unmapped.is_empty()); } + #[test] + fn packs_inside_a_zip_share_its_unpack_budget() { + // two packs unpacking to 2 MB each on a 3 MB budget: the first spends it, the second is refused + let pad = vec![b' '; 2 << 20]; + let pack = zip(&[("a.lmp", b""), ("pad.txt", &pad)], true); + let mut budget = 3 << 20; + let first = crate::preset_luminar::read_mplumpack_within("one.mplumpack", &pack, &mut budget).unwrap_err(); + assert!(!first.contains("too much"), "{first}"); + assert_eq!(budget, (1 << 20) - 8); + let second = crate::preset_luminar::read_mplumpack_within("two.mplumpack", &pack, &mut budget).unwrap_err(); + assert!(second.contains("too much"), "{second}"); + } + + #[test] + fn a_pack_that_fails_part_way_still_spends_what_it_unpacked() { + // 2 MB unpacks, then an entry that does not fit the 3 MB budget: the next pack gets nothing + let pad = vec![b' '; 2 << 20]; + let pack = zip(&[("a.txt", &pad), ("b.txt", &pad)], true); + let mut budget = 3 << 20; + let first = crate::preset_luminar::read_mplumpack_within("one.mplumpack", &pack, &mut budget).unwrap_err(); + assert!(first.contains("too much"), "{first}"); + assert_eq!(budget, 0); + } + + #[test] + fn a_corrupt_deflate_entry_spends_what_it_unpacked() { + // 2 MB declared, the stream cut in half: it unpacks a part, then fails; the budget keeps the part + let pad = vec![b' '; 2 << 20]; + let deflated = miniz_oxide::deflate::compress_to_vec(&pad, 6); + let mut pack = zip(&[("a.txt", &deflated[..deflated.len() / 2])], false); + let central = 30 + "a.txt".len() + deflated.len() / 2; + pack[8] = 8; // local header: method deflate + pack[central + 10] = 8; // central header: method deflate + pack[central + 24..central + 28].copy_from_slice(&(pad.len() as u32).to_le_bytes()); + let mut budget = 3 << 20; + let err = crate::preset_luminar::read_mplumpack_within("one.mplumpack", &pack, &mut budget).unwrap_err(); + assert!(!err.contains("too much"), "{err}"); + assert!(budget < 3 << 20, "{budget}"); + } + + #[test] + fn an_unterminated_long_comment_ends_the_template() { + // 20 000 openings of a long comment that never closes: each used to search the rest of + // the file for its close (seconds to minutes); now the first ends the file + let text = format!("s = {{ a = 1 }} {}", "--[==[ ".repeat(20_000)); + let t = std::time::Instant::now(); + let _ = parse_lua(&text); + assert!(t.elapsed().as_secs() < 5, "took {:?}", t.elapsed()); + } + + #[test] + fn an_entry_past_its_stated_size_spends_only_what_it_unpacked() { + // the stated size (1 byte) caps the inflate at 1026 bytes, far below the 1 MB limit + let mut lying = zip(&[("a.xmp", &vec![b' '; 10_000])], true); + let cd = lying.windows(4).position(|w| w == b"PK\x01\x02").unwrap(); + lying[cd + 24..cd + 28].copy_from_slice(&1u32.to_le_bytes()); + let mut spent = 0; + let e = read_zip_spending(&lying, 1 << 20, 1 << 20, &mut spent).unwrap_err(); + assert!(e.contains("stated size"), "{e}"); + assert!(spent > 0 && spent <= 2048, "{spent}"); + } + #[test] fn zip_bombs_are_refused() { // an entry unpacking past the limit (3 MB of zeros pack into a few kB): refused, named diff --git a/crates/engine/src/preset_luminar.rs b/crates/engine/src/preset_luminar.rs index 73b008d9ff..5a4fb21582 100644 --- a/crates/engine/src/preset_luminar.rs +++ b/crates/engine/src/preset_luminar.rs @@ -19,7 +19,7 @@ use std::collections::BTreeMap; use std::path::Path; use crate::crs::Props; -use crate::preset_import::{Imported, build, group_from_dir, read_zip}; +use crate::preset_import::{Imported, MAX_ZIP_ENTRY, MAX_ZIP_TOTAL, build, group_from_dir, read_zip_spending}; // ----------------------------------------------------------------------------- property lists @@ -72,13 +72,26 @@ struct Parser<'a> { /// Deepest `` / `` nesting read (real looks nest a handful of levels). const MAX_DEPTH: usize = 64; +/// Index of the `;` that ends a reference starting at `rest` (its `&`). The scan stops at the first +/// byte that cannot appear in a name or a numeric reference, so zero-padded references such as +/// `a` are found and each run of name bytes is read once, not once per `&`. +fn entity_end(rest: &str) -> Option { + let n = rest.bytes().skip(1).take_while(|b| b.is_ascii_alphanumeric() || *b == b'#').count(); + (rest.as_bytes().get(n + 1) == Some(&b';')).then_some(n + 1) +} + fn unescape(t: &str) -> String { let mut out = String::with_capacity(t.len()); let mut rest = t; while let Some(p) = rest.find('&') { out.push_str(&rest[..p]); rest = &rest[p..]; - let Some(end) = rest.find(';') else { break }; + // no `;` within a reference's reach: the `&` is kept and the search goes on after it + let Some(end) = entity_end(rest) else { + out.push('&'); + rest = &rest[1..]; + continue; + }; let ent = &rest[1..end]; let c = match ent { "amp" => Some('&'), @@ -335,11 +348,13 @@ struct Acc { sums: BTreeMap, curves: BTreeMap>, unmapped: Vec, + /// What `unmapped` holds, for the look-up (a look names each unsupported setting once). + seen: std::collections::HashSet, } impl Acc { fn skip(&mut self, what: String) { - if !self.unmapped.contains(&what) { + if self.seen.insert(what.clone()) { self.unmapped.push(what); } } @@ -455,7 +470,18 @@ pub fn read_lmp(path: &str, bytes: &[u8], group: Option) -> Result Result, String> { - let entries = read_zip(bytes)?; + let mut budget = MAX_ZIP_TOTAL; + read_mplumpack_within(path, bytes, &mut budget) +} + +/// [`read_mplumpack`] unpacking at most `budget` bytes, which it spends: packs inside one zip +/// share the zip's budget. +pub(crate) fn read_mplumpack_within(path: &str, bytes: &[u8], budget: &mut usize) -> Result, String> { + // spent as each entry unpacks: a pack that fails part way still used its budget + let mut spent = 0; + let entries = read_zip_spending(bytes, MAX_ZIP_ENTRY, *budget, &mut spent); + *budget = budget.saturating_sub(spent); + let entries = entries?; let info = entries .iter() .find(|(n, _)| n.rsplit('/').next().is_some_and(|b| b.eq_ignore_ascii_case("PresetsInfo.plist"))) @@ -486,6 +512,19 @@ mod tests { use crate::preset_import::read_presets; use serde_json::json; + #[test] + fn many_ampersands_before_one_semicolon_are_read_once() { + let hostile = format!("{};&", "&".repeat(200_000)); + assert_eq!(unescape(&hostile), format!("{};&", "&".repeat(200_000))); + assert_eq!(unescape("<a> 􏿿 &unknownreference;"), " \u{10FFFF} &unknownreference;"); + } + + #[test] + fn zero_padded_numeric_references_decode() { + assert_eq!(unescape("Canon A A"), "Canon A A"); + assert_eq!(unescape("&abc&#xyz;&;"), "&abc&#xyz;&;"); + } + #[test] fn unescape_rejects_signed_numeric_references() { assert_eq!(unescape("&#+65;&#x+41;"), "&#+65;&#x+41;"); diff --git a/crates/engine/src/segment.rs b/crates/engine/src/segment.rs index 3f95c310bd..9c479cb176 100644 --- a/crates/engine/src/segment.rs +++ b/crates/engine/src/segment.rs @@ -64,6 +64,9 @@ pub(crate) enum Tag { NewPrompt { photo: PhotoId, mask: Option, op: String, name: Option, text: String }, /// A zoomed-in pass for a component, computed from `shape` (without its detail). Detail { photo: PhotoId, mask: u32, comp: usize, shape: MaskShape }, + /// Find Subject for component `comp` of mask `mask` (an Object waiting for it): the people / + /// animals found become a "person" Describe selection; none, the object at `point`. + Subject { photo: PhotoId, mask: u32, comp: usize, point: Point }, } /// The model input: 8-bit RGB. @@ -498,6 +501,9 @@ impl Session { if !clicks.iter().any(|c| c.include) { return Err("click the object to include it first".into()); } + if clicks.len() > MAX_CLICKS { + return Err(format!("an Object selection takes at most {MAX_CLICKS} clicks")); + } #[cfg(feature = "sam")] { self.segment_wait(id, worker::Kind::Clicks(Self::model_clicks(clicks)), None)?.ok_or_else(|| "nothing was selected".to_string()) @@ -570,6 +576,35 @@ impl Session { } } + /// Find Subject for component `comp` of mask `mask` on photo `id` (an Object without clicks): + /// the photo's main people / animals ([`worker::Kind::Subject`]), those the camera's `focus` + /// falls on when the file records it; when the subject is neither, the object at `point`. In + /// background mode [`Session::segment_poll`] applies the result; otherwise it is applied + /// before this returns. + pub(crate) fn segment_subject_later(&mut self, id: PhotoId, mask: u32, comp: usize, point: Point, focus: Option) -> Result<(), String> { + self.segmenter.model_dir()?; + #[cfg(feature = "sam")] + { + let kind = worker::Kind::Subject { focus: focus.map(|p| (p.x as f32, p.y as f32)) }; + let tag = Tag::Subject { photo: id, mask, comp, point }; + if self.segmenter.background { + return self.segment_queue(id, kind, tag, None); + } + let seg = self.segment_wait(id, kind, None)?; + let mut polled = Polled::default(); + self.apply_outcome(worker::Outcome { tag, result: Ok(seg), superseded: false, notice: None }, &mut polled); + match polled.messages.into_iter().next() { + Some(e) => Err(e), + None => Ok(()), + } + } + #[cfg(not(feature = "sam"))] + { + let _ = (id, mask, comp, point, focus); + Err("AI masks are not available in this build".into()) + } + } + /// Start a zoomed-in pass for component `comp` of mask `mask` on photo `id` (an Object or /// Describe selection): the photo around the selection is rendered at a higher resolution /// and segmented again. In background mode [`Session::segment_poll`] applies the result; @@ -706,6 +741,51 @@ impl Session { Err(e) => polled.messages.push(e.to_string()), } } + Tag::Subject { photo, mask, comp, point } => { + let found = match o.result { + Ok(found) => found, + Err(e) => return polled.messages.push(e), + }; + let Some(d) = self.develop_of(photo) else { return }; + let mut d = (*d).clone(); + let Some(c) = d.masks.iter_mut().find(|m| m.id == mask).and_then(|m| m.components.get_mut(comp)) else { return }; + // still the Object waiting for it (not clicked or replaced meanwhile) + let MaskShape::Object { hint, seg: None, edge, .. } = &c.shape else { return }; + if !hint.is_empty() { + return; + } + let edge = *edge; + let seg = match found { + Some(seg) => seg, + // neither a person nor an animal: the object at the point + None if self.segmenter.background => { + if let Err(e) = self.segment_clicks_later(photo, mask, comp, vec![point], Vec::new()) { + polled.messages.push(e); + } + return; + } + None => { + match self.segment_clicks(photo, &clicks_of(&[point], &[])) { + Ok(seg) => { + c.shape = MaskShape::Object { hint: vec![point], exclude: Vec::new(), seg: Some(seg), detail: Vec::new(), edge } + } + Err(e) => return polled.messages.push(e), + } + if let Err(e) = self.set_develop(photo, d, "Find Subject") { + polled.messages.push(e.to_string()); + } else { + polled.changed = true; + } + return; + } + }; + let text = lightcraft_segment::SUBJECT_CONCEPTS.join(", "); + c.shape = MaskShape::Prompt { text, seg: Some(seg), detail: Vec::new(), edge }; + match self.set_develop(photo, d, "Find Subject") { + Ok(()) => polled.changed = true, + Err(e) => polled.messages.push(e.to_string()), + } + } Tag::Detail { photo, mask, comp, shape } => { let patch = match o.result { Ok(Some(p)) => p, @@ -747,6 +827,47 @@ mod tests { assert!(s.segment_poll().messages.is_empty(), "once"); } + /// Find Subject's result: people / animals found become a Describe selection of the waiting + /// Object (one undo step), not after it was clicked meanwhile; nothing found queues the object + /// at the point (here: no model, so a message, and the mask still waits). + #[cfg(feature = "sam")] + #[test] + fn find_subject_results_fill_the_waiting_mask() { + use lightcraft_develop::{Mask, MaskComponent, MaskOp}; + let mut s = Session::with_demo(); + s.segmenter.dir = Some(std::env::temp_dir().join(format!("lc-no-sam3-subject-{}", std::process::id()))); + let id = s.active().unwrap(); + let waiting = || MaskShape::Object { hint: vec![], exclude: vec![], seg: None, detail: vec![], edge: 0.0 }; + let mut d = (*s.develop_of(id).unwrap()).clone(); + d.masks.push(Mask { + id: 3, + components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: waiting() }], + ..Default::default() + }); + s.set_develop(id, d, "test").unwrap(); + let point = Point::new(0.4, 0.5); + let send = |s: &mut Session, result| { + let tag = Tag::Subject { photo: id, mask: 3, comp: 0, point }; + s.segmenter.results.0.send(worker::Outcome { tag, result, superseded: false, notice: None }).unwrap(); + s.segment_poll() + }; + let shape = |s: &Session| s.develop_of(id).unwrap().masks[0].components[0].shape.clone(); + // nothing found, no model to click with: said so, and the mask still waits + let polled = send(&mut s, Ok(None)); + assert!(!polled.messages.is_empty() && shape(&s) == waiting(), "{:?}", polled.messages); + // people found: a Describe selection of them + let polled = send(&mut s, Ok(Some(seg_box(20, 5, 5, 15, 15)))); + assert!(polled.changed && polled.messages.is_empty()); + let MaskShape::Prompt { text, seg: Some(_), .. } = shape(&s) else { panic!("{:?}", shape(&s)) }; + assert_eq!(text, "person, animal"); + // a result for a mask that changed meanwhile is dropped + let before = shape(&s); + assert!(!send(&mut s, Ok(Some(seg_box(20, 0, 0, 4, 4)))).changed); + assert_eq!(shape(&s), before); + // an error reaches the user + assert_eq!(send(&mut s, Err("boom".into())).messages, vec!["boom".to_string()]); + } + fn seg_box(side: usize, x0: usize, y0: usize, x1: usize, y1: usize) -> SegMask { let l: Vec = (0..side * side).map(|i| if (x0..x1).contains(&(i % side)) && (y0..y1).contains(&(i / side)) { 8.0 } else { -8.0 }).collect(); diff --git a/crates/engine/src/segment/worker.rs b/crates/engine/src/segment/worker.rs index efbb1c21c4..1e4bf6e8d9 100644 --- a/crates/engine/src/segment/worker.rs +++ b/crates/engine/src/segment/worker.rs @@ -42,6 +42,12 @@ pub enum Kind { Prepare, Clicks(Vec), Text(String), + /// The photo's subject among its people and animals (`Sam3::segment_subject`); `focus`: where + /// the camera focused (normalized), when the file records it. No result: the subject is + /// something else. + Subject { + focus: Option<(f32, f32)>, + }, /// A zoomed-in pass over `region` (normalized) of the photo, rendered by the job's `render`. Detail { prompt: Prompt, @@ -420,6 +426,7 @@ fn remote_job(state: &mut State, shared: &Shared, job: &mut Job, endpoint: &str) let operation = match std::mem::replace(&mut job.kind, Kind::Prepare) { Kind::Prepare => Operation::Prepare, Kind::Text(text) => Operation::Text(text), + Kind::Subject { focus } => Operation::Subject(focus.map(|(x, y)| [x, y])), Kind::Clicks(clicks) => Operation::Clicks(clicks.iter().map(|c| [c.x, c.y, if c.positive { 1.0 } else { 0.0 }]).collect()), Kind::Detail { prompt, region: r } => { region = Some(r); @@ -480,6 +487,11 @@ fn run_job(state: &mut State, shared: &Shared, job: &mut Job, placement: Placeme let (m, enc) = encoded(state, shared, job, placement)?; Ok(text_logits(m, enc, &text)?.map(|l| SegMask::from_logits(side, &l))) } + Kind::Subject { focus } => { + let (m, enc) = encoded(state, shared, job, placement)?; + // (the reference score threshold, as Describe uses) + Ok(m.segment_subject(enc, focus, 0.5)?.map(|p| SegMask::from_logits(side, &p.logits))) + } #[cfg(test)] #[allow(clippy::panic)] Kind::Panic => panic!("a test panic"), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 632814334d..64641f9edf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -385,6 +385,84 @@ fn permanently_deleting_explicit_targets_keeps_the_surviving_selection() { assert_eq!(s.catalog.to_snapshot(), snapshot); } +/// `lensBlur.brushStroke` adds a stroke to the Focus or the Blur brush (clamped, undoable); hostile +/// input is an error; `lensBlur.brushReset` clears one brush or both. +#[test] +fn lens_blur_brush_strokes_and_reset() { + let mut s = demo(); + let id = s.active().unwrap(); + s.execute( + "lensBlur.brushStroke", + &json!({"mode": "focus", "points": [[0.2, 0.3], [0.25, 0.3]], "size": 9.0, "amount": 40, "feather": f64::NAN, "autoMask": true}), + ) + .unwrap(); + s.execute("lensBlur.brushStroke", &json!({"mode": "blur", "points": [[0.7, 0.6]]})).unwrap(); + let d = s.develop_of(id).unwrap(); + let (f, b) = (&d.lens_blur.focus_strokes, &d.lens_blur.blur_strokes); + assert_eq!((f.len(), b.len()), (1, 1)); + assert_eq!(f[0].points.len(), 2); + assert!(f[0].size == 0.5 && f[0].density == 40.0 && f[0].feather == lightcraft_develop::BrushStroke::default().feather && f[0].auto_mask); + for bad in [ + json!({"mode": "sideways", "points": [[0.5, 0.5]]}), + json!({"mode": "focus", "points": []}), + json!({"mode": "focus"}), + json!({"mode": "blur", "points": [[0.5, 0.5]], "pressure": [0.5, 0.5]}), + ] { + assert!(s.execute("lensBlur.brushStroke", &bad).is_err(), "{bad}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.develop_of(id).unwrap().lens_blur.blur_strokes.is_empty(), "a stroke is one undo step"); + s.execute("lensBlur.brushStroke", &json!({"mode": "blur", "points": [[0.7, 0.6]]})).unwrap(); + s.execute("lensBlur.brushReset", &json!({"mode": "blur"})).unwrap(); + let d = s.develop_of(id).unwrap(); + assert!(d.lens_blur.blur_strokes.is_empty() && d.lens_blur.focus_strokes.len() == 1); + assert!(s.execute("lensBlur.brushReset", &json!({"mode": "nope"})).is_err()); + s.execute("lensBlur.brushReset", &json!({})).unwrap(); + assert!(s.develop_of(id).unwrap().lens_blur.focus_strokes.is_empty()); +} + +/// `lensBlur.findSubject` without the SAM 3 model (or in a build without AI masks) is an error that +/// leaves the photo as it was: no empty mask, the blur not switched on. +#[test] +fn find_subject_without_the_model_changes_nothing() { + let mut s = demo(); + let id = s.active().unwrap(); + // (never the machine's own model: a folder that has none) + s.segmenter.dir = Some(std::env::temp_dir().join(format!("lc-no-sam3-{}", std::process::id()))); + let before = s.develop_of(id).unwrap(); + let e = s.execute("lensBlur.findSubject", &json!({})).unwrap_err(); + assert!(e.to_string().contains("SAM 3") || e.to_string().contains("AI masks"), "{e}"); + let after = s.develop_of(id).unwrap(); + assert!(after.masks.is_empty() && !after.lens_blur.enabled); + assert_eq!(*before, *after); +} + +/// Deleting the mask that is the Lens Blur focus clears the focus, so a new mask that gets the same +/// id doesn't become the focus; undo brings both back. +#[test] +fn deleting_the_focus_mask_clears_the_lens_blur_focus() { + let mut s = demo(); + let id = s.active().unwrap(); + let radial = json!({"kind": "radial", "center": [0.5, 0.5], "rx": 0.2, "ry": 0.2}); + s.execute("mask.add", &radial).unwrap(); + let mid = s.develop_of(id).unwrap().masks[0].id; + s.execute("develop.merge", &json!({"settings": {"lens_blur": {"enabled": true, "amount": 50, "focus_mask": mid}}})).unwrap(); + s.execute("mask.delete", &json!({"id": mid})).unwrap(); + assert_eq!(s.develop_of(id).unwrap().lens_blur.focus_mask, None); + // a new mask takes the freed id, and stays an ordinary mask + s.execute("mask.add", &radial).unwrap(); + let d = s.develop_of(id).unwrap(); + assert_eq!(d.masks[0].id, mid); + assert_eq!(d.lens_blur.focus_mask, None); + // undoing the add and the delete brings the focus back with its mask + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.develop_of(id).unwrap().lens_blur.focus_mask, Some(mid)); + // other mask edits keep it + s.execute("mask.adjust", &json!({"values": {"exposure": 0.5}})).unwrap(); + assert_eq!(s.develop_of(id).unwrap().lens_blur.focus_mask, Some(mid)); +} + /// `mask.brushStroke {connect: true}` (a ⇧-click) starts from the last point of the mask's last stroke: one straight /// stroke when the brush is unchanged, pieces whose size, feather and flow step from the last stroke's to the new /// values when it changed, and a plain dab when there is nothing to connect to. diff --git a/crates/engine/src/tests/lightroom_folder.rs b/crates/engine/src/tests/lightroom_folder.rs index eccff23ac9..a6ed212335 100644 --- a/crates/engine/src/tests/lightroom_folder.rs +++ b/crates/engine/src/tests/lightroom_folder.rs @@ -98,6 +98,37 @@ fn an_lrdata_folder_whose_catalog_was_renamed_finds_the_one_next_to_it() { let _ = std::fs::remove_dir_all(&root); } +/// Issue #2592: someone who deleted Lightroom and its catalog keeps only `Backups/`; that folder and +/// each dated folder in it are refused. A dated folder names its zip; `Backups/` names one only when +/// it is the only backup (with several, the import asks which). +#[test] +fn lightroom_backups_without_their_catalog_are_refused_and_name_the_zip() { + let root = temp_dir("backups"); + let backups = root.join("Lightroom").join("Backups"); + let backup = crate::lightroom_backup::tests::zip(&[("Cat.lrcat", b"SQLite format 3\0")], true, false); + for (dated, zip) in [("2019-03-26 0751", "Cat-2.lrcat.zip"), ("2023-11-07 0900", "Cat-v13.zip")] { + std::fs::create_dir_all(backups.join(dated)).unwrap(); + std::fs::write(backups.join(dated).join(zip), &backup).unwrap(); + } + // a zip without a catalog in a dated folder is not a backup + std::fs::create_dir_all(backups.join("2024-01-01 1200")).unwrap(); + std::fs::write(backups.join("2024-01-01 1200").join("photos.zip"), crate::lightroom_backup::tests::zip(&[("a.jpg", b"x")], false, false)) + .unwrap(); + assert_eq!(lightroom_catalog_at(&backups.join("2024-01-01 1200")), None, "no catalog in the zip"); + let newest = backups.join("2023-11-07 0900").join("Cat-v13.zip"); + assert_eq!(lightroom_catalog_at(&backups), Some(LightroomPlace { catalog: None }), "two backups: no arbitrary pick"); + refused(&root, &backups.join("2023-11-07 0900"), &newest); + refused(&root, &backups.join("2019-03-26 0751"), &backups.join("2019-03-26 0751").join("Cat-2.lrcat.zip")); + std::fs::remove_dir_all(backups.join("2019-03-26 0751")).unwrap(); + refused(&root, &backups, &newest); + // a folder of zips that isn't in a `Backups/` folder is not Lightroom's + let other = root.join("Downloads"); + std::fs::create_dir_all(&other).unwrap(); + std::fs::write(other.join("photos.zip"), &backup).unwrap(); + assert_eq!(lightroom_catalog_at(&other), None); + let _ = std::fs::remove_dir_all(&root); +} + #[test] fn an_empty_folder_still_becomes_a_library() { let root = temp_dir("empty"); diff --git a/crates/engine/src/tests/segment.rs b/crates/engine/src/tests/segment.rs index b649dbdd7e..51d6e26e8f 100644 --- a/crates/engine/src/tests/segment.rs +++ b/crates/engine/src/tests/segment.rs @@ -240,6 +240,25 @@ fn object_clicks_are_capped() { let _ = std::fs::remove_dir_all(&dir); } +/// In background mode a new Object mask with too many clicks is refused up front, not queued. +#[test] +fn background_object_clicks_over_the_cap_are_refused_before_queueing() { + if !Segmenter::AVAILABLE { + return; + } + let mut s = Session::with_demo(); + s.segmenter.background = true; + let dir = damaged_model("later-clicks"); + s.segmenter.dir = Some(dir.clone()); + let id = s.active().unwrap(); + let points: Vec<_> = (0..=crate::segment::MAX_CLICKS).map(|_| json!([0.5, 0.5])).collect(); + let e = s.execute("mask.add", &json!({"kind": "object", "points": points})).unwrap_err().to_string(); + assert!(e.contains("at most"), "{e}"); + assert!(s.develop_of(id).unwrap().masks.is_empty()); + assert!(!s.segmenter.busy()); + let _ = std::fs::remove_dir_all(&dir); +} + #[cfg(feature = "sam")] #[test] fn a_running_model_download_shows_in_activity_and_cancels() { diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 2c52d87e9d..c92411938f 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -4,4 +4,5 @@ mod denoise_cpu; #[cfg(feature = "denoise")] mod denoise_real; +mod orf_withdrawal; mod preview_read; diff --git a/crates/engine/tests/it/orf_withdrawal.rs b/crates/engine/tests/it/orf_withdrawal.rs new file mode 100644 index 0000000000..a29c8d06fc --- /dev/null +++ b/crates/engine/tests/it/orf_withdrawal.rs @@ -0,0 +1,207 @@ +//! Compressed ORF withdrawal: public import/recheck and render identities stay consistent. + +use std::path::PathBuf; +use std::sync::Arc; + +use lightcraft_catalog::{APP_VERSION, MediaKind, Op, Photo, PhotoId, Source}; +use lightcraft_engine::{Session, cmd::recheck, media::content_key}; +use lightcraft_pipeline::SourceInfo; +use lightcraft_preview::Hash128; +use lightcraft_raster::Rgb32f; +use serde_json::json; + +struct OrfLibrary { + s: Session, + dir: PathBuf, + lib: PathBuf, + id: PhotoId, +} + +impl Drop for OrfLibrary { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +/// A fixed original and settings isolate decoder status from every other render-key input. +fn decoder_session(format: &str) -> Session { + let mut s = Session::new(); + let mut p = Photo::new(PhotoId(1), Source::File { path: "same-original.orf".into() }, "same-original.orf", format, 6000, 4000, "2026-01-01"); + p.kind = MediaKind::Raw; + p.content_hash = Some("unchanged-file-bytes".into()); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + s +} + +/// Include the frontend's ordinary, hover and quick-view identities as well as all persistent +/// render families. The original-file identity must not change along with any of these. +fn decoder_keys(s: &mut Session) -> (Vec, Vec, String) { + let p = s.catalog.photo(PhotoId(1)).unwrap().clone(); + let thumb = s.thumb_job(p.id, 256).unwrap(); + let render = s.render_job(p.id, 640, 480, false, true).unwrap(); + let hover = s.preview_job(p.id, 640, 480, true, &p.develop).unwrap(); + let quick = s.quick_view_job(p.id, 640, true).unwrap(); + ( + vec![thumb.key, render.key, hover.key, quick.key], + vec![ + thumb.cache.unwrap().1, + s.loupe_job(p.id, 640, 480, true).unwrap().view_cache.unwrap().1, + Session::variant_key(&p, &p.develop, 256, 0), + render.source_key.unwrap(), + ], + content_key(&p), + ) +} + +/// Old ORF renders cannot stand in after withdrawal; other formats and original-file identities stay stable. +#[test] +fn withdrawn_orf_decoder_has_distinct_render_keys_without_changing_file_identity() { + // Before the withdrawal, format was not part of any of these keys: an otherwise identical + // non-ORF photo gives the old keys, preserved for every other camera and ordinary image. + let legacy = decoder_keys(&mut decoder_session("DNG")); + assert_eq!(legacy, decoder_keys(&mut decoder_session("JPEG"))); + let orf = decoder_keys(&mut decoder_session("ORF")); + for (old, new) in legacy.0.iter().zip(&orf.0) { + assert_ne!(old, new, "old ORF frontend render must not be reused"); + } + for (old, new) in legacy.1.iter().zip(&orf.1) { + assert_ne!(old, new, "old ORF persistent render or decoded source must not be reused"); + } + assert_eq!(legacy.2, orf.2, "smart previews and denoise products still identify the original file"); + assert_eq!(orf, decoder_keys(&mut decoder_session("orf"))); +} + +/// Apply the same-byte capability transition that Reload or the background recheck records. +fn mark_orf_preview_only(s: &mut Session) { + let p = s.catalog.photo(PhotoId(1)).unwrap().clone(); + s.catalog + .apply(Op::SetContent { + id: p.id, + width: p.width, + height: p.height, + file_size: p.file_size, + content_hash: p.content_hash.clone(), + preview_only: Some("Olympus compressed ORF".into()), + preview_checked: lightcraft_catalog::APP_VERSION.into(), + }) + .unwrap(); + s.media.forget(p.id); +} + +/// A support-status change invalidates every render family, even when a resize happens at the same time. +#[test] +fn orf_preview_transition_changes_render_keys_with_identical_bytes_and_settings() { + let mut s = decoder_session("ORF"); + let before = decoder_keys(&mut s); + mark_orf_preview_only(&mut s); + let after = decoder_keys(&mut s); + for (old, new) in before.0.iter().zip(&after.0) { + assert_ne!(old, new, "Reload changes frontend render identity"); + } + for (old, new) in before.1.iter().zip(&after.1) { + assert_ne!(old, new, "Reload changes persistent render and decoded source identity"); + } + assert_eq!(before.2, after.2, "Reload does not change the original file's identity"); + let p = s.catalog.photo(PhotoId(1)).unwrap().clone(); + assert_ne!(before.0[1], s.render_job(p.id, 648, 480, false, true).unwrap().key, "a resize must not cancel the status salt"); + assert_ne!(before.0[2], s.preview_job(p.id, 648, 480, true, &p.develop).unwrap().key, "a hover resize must not cancel the status salt"); +} + +/// An in-flight sensor decode must not refill a source cache cleared by the preview-only transition. +#[test] +fn source_from_before_orf_preview_transition_is_not_accepted() { + let mut s = decoder_session("ORF"); + s.media.file_loader = Some(Arc::new(|_, _, _| Ok((Rgb32f::new(8, 8), SourceInfo::default())))); + let old = s.thumb_job(PhotoId(1), 256).unwrap().run(); + assert!(old.loaded.is_some()); + mark_orf_preview_only(&mut s); + s.accept(&old); + assert_eq!(s.media.source_usage().0, 0, "a sensor decode finishing after Reload cannot repopulate its source cache"); +} + +/// A legacy ORF record and a controlled probe let the upgrade tests exercise catalog migration +/// without downloading camera files. The raw crate separately tests the actual ORF probe. +fn legacy_orf(name: &str, preview_only: Option) -> OrfLibrary { + let dir = std::env::temp_dir().join(format!("lc-orf-recheck-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let lib = dir.join("lib"); + let file = dir.join("legacy.orf"); + let mut s = Session::new(); + s.open_library(&lib, false).unwrap(); + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: file.to_string_lossy().into() }, "legacy.orf", "ORF", 96, 64, "2026-01-01"); + p.kind = MediaKind::Raw; + p.file_size = 1024; + p.content_hash = Some("same-file".into()); + let info = lightcraft_engine::media::ProbeInfo { + width: p.width, + height: p.height, + file_size: p.file_size, + content_hash: p.content_hash.clone(), + format: p.format.clone(), + kind: p.kind, + preview_only, + ..Default::default() + }; + s.commit("Legacy ORF", Op::AddPhoto { photo: Box::new(p) }).unwrap(); + s.selection = lightcraft_engine::Selection::single(id); + s.media.file_probe = Some(Arc::new(move |_| Ok(info.clone()))); + OrfLibrary { s, dir, lib, id } +} + +/// Previously supported compressed ORFs and their copies migrate without losing edits, history or persistence. +#[test] +fn legacy_compressed_orf_and_copies_become_preview_only_without_losing_edits() { + let mut x = legacy_orf("compressed", Some("Olympus compressed ORF".into())); + x.s.execute("develop.set", &json!({"ids": [x.id.0], "control": "light.exposure", "value": 0.5})).unwrap(); + let r = x.s.execute("photo.virtualCopy", &json!({"ids": [x.id.0]})).unwrap(); + let copy = PhotoId(r["ids"][0].as_u64().unwrap()); + let before = x.s.catalog.photo(x.id).unwrap().clone(); + let undo = x.s.undo.len(); + let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap(); + assert_eq!(r, json!({"checked": 1, "updated": [x.id.0, copy.0], "cleared": []})); + for id in [x.id, copy] { + let p = x.s.catalog.photo(id).unwrap(); + assert_eq!(p.preview_only.as_deref(), Some("Olympus compressed ORF")); + assert_eq!(p.preview_checked, APP_VERSION); + assert!(!p.develops_raw()); + assert_eq!(*p.develop, *before.develop); + } + assert_eq!(x.s.catalog.photo(x.id).unwrap().history, before.history); + assert_eq!(x.s.undo.len(), undo, "bookkeeping is not an undo step"); + x.s.persist().unwrap(); + x.s = Session::new(); + x.s.open_library(&x.lib, false).unwrap(); + assert!(x.s.catalog.photo(x.id).unwrap().preview_only.is_some()); + assert!(recheck::stale(&x.s.catalog, false).is_empty()); +} + +/// Supported uncompressed ORF is checked once and never reported as newly recovered sensor support. +#[test] +fn legacy_uncompressed_orf_is_stamped_once_without_a_false_recovery_notice() { + let mut x = legacy_orf("supported", None); + let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap(); + assert_eq!(r, json!({"checked": 1, "updated": [x.id.0], "cleared": []})); + let p = x.s.catalog.photo(x.id).unwrap(); + assert!(p.develops_raw()); + assert_eq!(p.preview_checked, APP_VERSION); + assert!(recheck::stale(&x.s.catalog, false).is_empty()); + assert_eq!(recheck::stale(&x.s.catalog, true).len(), 1); + x.s.persist().unwrap(); + x.s = Session::new(); + x.s.open_library(&x.lib, false).unwrap(); + assert!(recheck::stale(&x.s.catalog, false).is_empty()); + assert!(x.s.catalog.photo(x.id).unwrap().develops_raw()); +} + +/// An offline original keeps its catalog state and remains eligible for a later recheck. +#[test] +fn unavailable_legacy_orf_is_unchanged_and_retried() { + let mut x = legacy_orf("offline", None); + x.s.media.file_probe = Some(std::sync::Arc::new(|_| Err("offline".into()))); + let before = x.s.catalog.photo(x.id).unwrap().clone(); + let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap(); + assert_eq!(r, json!({"checked": 1, "updated": [], "cleared": []})); + assert_eq!(x.s.catalog.photo(x.id).unwrap(), &before); + assert_eq!(recheck::stale(&x.s.catalog, false).len(), 1); +} diff --git a/crates/gpu/examples/grain_drag_bench.rs b/crates/gpu/examples/grain_drag_bench.rs new file mode 100644 index 0000000000..5a47cb6740 --- /dev/null +++ b/crates/gpu/examples/grain_drag_bench.rs @@ -0,0 +1,56 @@ +//! Grain slider drags on the GPU: the time per frame of the draft renders the loupe makes while +//! Amount or Size is dragged, on a ~2.5 MP preview (1936 × 1290, the procedural demo photo). +//! `cargo run --release -p lightcraft-gpu --example grain_drag_bench` (`FRAMES=n`, default 40). +//! +//! The same source, settings and request on every build, so it can be copied unchanged into +//! another branch to compare grain models (see `docs/grain.md` → Performance). Each drag first +//! renders four frames that aren't counted (stage cache, GPU pipelines), then moves the slider one +//! step a frame; prints the median, fastest and slowest frame. +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::sync::Arc; +use std::time::Instant; + +use lightcraft_develop::DevelopSettings; +use lightcraft_pipeline::{Quality, RenderRequest, SourceInfo, StageCache}; + +fn main() { + let frames: usize = std::env::var("FRAMES").ok().and_then(|v| v.parse().ok()).unwrap_or(40).max(1); + let (w, h) = (1936, 1290); + let src = Arc::new(lightcraft_scenes::demo_library()[3].render(w, h)); + let info = SourceInfo { raw: true, ..Default::default() }; + let draft = RenderRequest { quality: Quality::Draft, ..RenderRequest::fit(w, h) }; + let Some(adapter) = lightcraft_gpu::adapter_name() else { + eprintln!("no GPU adapter: nothing to measure"); + return; + }; + println!("gpu: {adapter}; {w}×{h} draft renders, {frames} frames per drag"); + let mut s = DevelopSettings::default(); + s.light.exposure = 0.3; + let mut drag = |label: &str, step: &dyn Fn(&mut DevelopSettings, usize)| { + let cache = StageCache::default(); + let mut ms = Vec::with_capacity(frames); + for i in 0..frames + 4 { + step(&mut s, i); + let t = Instant::now(); + assert!(lightcraft_gpu::render(&src, &info, &s, &draft, Some(&cache)).is_some(), "GPU render failed"); + if i >= 4 { + ms.push(t.elapsed().as_secs_f64() * 1e3); + } + } + ms.sort_by(f64::total_cmp); + println!("{label:<30} median {:5.1} ms min {:5.1} max {:5.1}", ms[ms.len() / 2], ms[0], ms[ms.len() - 1]); + }; + drag("exposure drag, no grain", &|s, i| { + s.grain.amount = 0.0; + s.light.exposure = 0.3 + i as f64 * 0.01; + }); + drag("Amount drag (20 → 100)", &|s, i| { + s.grain.size = 25.0; + s.grain.amount = 20.0 + (i * 2 % 80) as f64; + }); + drag("Size drag (amount 50, 0 → 100)", &|s, i| { + s.grain.amount = 50.0; + s.grain.size = (i * 2 % 100) as f64; + }); +} diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index 6b683783f5..6be62a9bcf 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -51,6 +51,7 @@ const MODULES: &[Module] = &[ "guided_pre", "guided_ab", "guided_apply", + "clamp_between_k", "wb_k", "nr_lum", "chroma_k", @@ -197,7 +198,11 @@ fn build_jobs( layout: Some(&p.pipeline_layout), module: &p.module, entry_point: Some(entry), - compilation_options: Default::default(), + // Only the median kernels (`blur.wgsl`, `med_tile`) use workgroup memory, and they + // load every element they read before the barrier, so wgpu's default zeroing is not + // needed. On DX12 it is written out as one assignment per element, which made FXC take + // about 87 s over these kernels at every start of a release build. + compilation_options: wgpu::PipelineCompilationOptions { zero_initialize_workgroup_memory: false, ..Default::default() }, cache: None, }); let kernel = Kernel { pipeline, layout: p.layout.clone(), nbuf: p.nbuf }; @@ -382,6 +387,11 @@ pub struct Gpu { free: std::sync::Mutex>, /// Largest storage buffer the device accepts (bytes). pub max_buffer: u64, + /// The crystal grain tables of the last grain pattern, resident: a render (each Amount step + /// of a drag) copies them on the GPU instead of uploading their 12 MB again ([`Gpu::grain_tables`]). + /// Shared with each render that recorded a copy from them until it submits: replacing them + /// while another thread's copy is unsubmitted must not hand the buffer back to the pool. + grain: std::sync::Mutex, std::sync::Arc)>>, /// The device is the window's (eframe's): renders can hand it textures to draw directly. pub window: bool, } @@ -430,6 +440,11 @@ fn constants() -> String { for (i, h) in GRAIN_HASH.iter().enumerate() { s += &format!("const GRAIN_H{i}: u32 = {h}u;\n"); } + use lightcraft_pipeline::crystal::{TILE_PER_LONG, TORI}; + s += &format!( + "const CRYSTAL_T0: u32 = {}u;\nconst CRYSTAL_T1: u32 = {}u;\nconst CRYSTAL_TPL: f32 = {:?};\n", + TORI[0], TORI[1], TILE_PER_LONG as f32 + ); s += &format!("const DEEP_WRITTEN: u32 = {}u;\n", crate::params::DEEP_WRITTEN); for (name, idx) in crate::params::finish_fields() { s += &format!("const F_{name}: u32 = {idx}u;\n"); @@ -543,7 +558,7 @@ impl Gpu { max_buffer >> 20, if window { ", the window's device" } else { "" } ); - Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer, window }) + Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer, window, grain: Default::default() }) } /// A buffer of `len` 32-bit values with undefined contents (a recycled one when possible). @@ -718,6 +733,44 @@ impl Gpu { ); } + /// Record into `enc` a copy of `tile`'s summed-area tables (both tori, back to back) into + /// `dst` at value offset `at`, uploading them first unless they are the resident ones. + /// Returns the buffer copied from, which the caller keeps until it has submitted `enc` (another + /// render may replace the resident tables meanwhile). None when `dst` can't hold them (an + /// over-limit placeholder: the render has failed already). + pub fn grain_tables( + &self, + enc: &mut wgpu::CommandEncoder, + tile: &std::sync::Arc, + dst: &Buf, + at: usize, + ) -> Option> { + let len: usize = tile.sats.iter().map(Vec::len).sum(); + let (start, bytes) = ((at as u64) * 4, (len as u64) * 4); + if len == 0 || dst.raw().size() < start.saturating_add(bytes) { + return None; + } + let mut resident = self.grain.lock().unwrap_or_else(|e| e.into_inner()); + if !resident.as_ref().is_some_and(|(t, b)| std::sync::Arc::ptr_eq(t, tile) && b.raw().size() >= bytes) { + // the old tables go back to the pool first (once no unsubmitted copy holds them): one + // pattern's tables are resident at a time + *resident = None; + let buf = self.buffer(len); + if buf.raw().size() < bytes { + return None; + } + let mut off = 0u64; + for sat in &tile.sats { + self.queue.write_buffer(buf.raw(), off, bytemuck::cast_slice(sat)); + off += (sat.len() as u64) * 4; + } + *resident = Some((tile.clone(), std::sync::Arc::new(buf))); + } + let (_, src) = resident.as_ref()?; + enc.copy_buffer_to_buffer(src.raw(), 0, dst.raw(), start, bytes); + Some(src.clone()) + } + /// Stands in for a buffer that could not be created (the render has failed already). fn placeholder(&self) -> wgpu::Buffer { self.device.create_buffer(&wgpu::BufferDescriptor { @@ -1321,6 +1374,35 @@ mod tests { } } + /// Resident grain tables replaced by another pattern stay out of the pool while a render + /// that recorded a copy from them hasn't submitted it: reusing them then would hand that + /// render another tile's tables. + #[test] + fn replaced_grain_tables_stay_alive_until_their_copy_is_submitted() { + use lightcraft_pipeline::crystal::{CrystalLook, CrystalTile}; + let Some(g) = crate::device() else { + lightcraft_testkit::skip!(Gpu, "no GPU device"); + return; + }; + let look = CrystalLook::new(25.0, 50.0); + let (Some(a), Some(b)) = (CrystalTile::new(look, 0x7ab1_0001), CrystalTile::new(look, 0x7ab1_0002)) else { panic!("tiles") }; + let (a, b) = (std::sync::Arc::new(a), std::sync::Arc::new(b)); + let len: usize = a.sats.iter().map(Vec::len).sum(); + let (dst_a, dst_b) = (g.buffer(len), g.buffer(len)); + let mut first = g.encoder(); + let held = g.grain_tables(&mut first, &a, &dst_a, 0).expect("tables copied"); + // another render replaces the resident tables before `first` is submitted + let mut second = g.encoder(); + assert!(g.grain_tables(&mut second, &b, &dst_b, 0).is_some()); + let next = g.buffer(len); + assert!(next.raw() != held.raw(), "the replaced tables went back to the pool before their copy was submitted"); + g.submit([first.finish()]); + // each render read its own tile's tables + let tables = |t: &lightcraft_pipeline::crystal::CrystalTile| t.sats.concat(); + assert!(g.finish_and_read::(second, &dst_a, len) == tables(&a), "the first render copied other tables"); + assert!(g.finish_and_read::(g.encoder(), &dst_b, len) == tables(&b), "the second render copied other tables"); + } + /// A GPU retired by another failure (a validation error) keeps a live device: its buffers are /// still released, which takes a poll. #[test] diff --git a/crates/gpu/src/params.rs b/crates/gpu/src/params.rs index 5776c48caa..9140fe81d5 100644 --- a/crates/gpu/src/params.rs +++ b/crates/gpu/src/params.rs @@ -3,7 +3,7 @@ use lightcraft_develop::VignetteStyle; use lightcraft_pipeline::colorops::POINT_WORDS; -use lightcraft_pipeline::finish::{FinishParams, MASK_TERMS, srgb_lut}; +use lightcraft_pipeline::finish::{FinishParams, GrainModel, MASK_TERMS, srgb_lut}; use crate::ctx::{FailKind, fail}; @@ -71,6 +71,12 @@ const FIELDS: &[(&str, usize)] = &[ // the window's offset in the whole output and the whole output's size (pixels) ("VIG_VIEW", 4), ("GRAIN", 1), + // 0 = value noise (processes V1 to V6: GRAIN_AMT, GRAIN_SC, GRAIN_ROUGH), 1 = crystal layers (V7) + ("GRAIN_MODEL", 1), + // crystal grain: amplitude, footprint (tile px per output px), the tori's tables in `aux` + ("GRAIN_K", 1), + ("GRAIN_FOOT", 1), + ("GRAIN_SAT", 2), ("GRAIN_AMT", 1), ("GRAIN_SC", 1), ("GRAIN_ROUGH", 1), @@ -178,7 +184,8 @@ pub struct Present { } /// The `finish` kernel's parameter block and auxiliary table (tone LUT | chroma curve | sRGB LUT | curve LUTs | -/// mask terms | light operator tables) for `fp` with `masks` (their local adjustments' terms). +/// mask terms | light operator tables) for `fp` with `masks` (their local adjustments' terms). The crystal +/// grain's tables go after `aux` in the kernel's buffer ([`crate::render`] copies them there). /// /// `deep`: the kernel writes float samples, as the pipeline's `finish_deep` does. /// @@ -220,6 +227,16 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr if let Some((l, _)) = &fp.lut { aux.extend(l.data.iter().flatten()); } + // the crystal grain's tables follow `aux` on the GPU without being part of it: they stay + // resident between renders ([`crate::Gpu::grain_tables`]) and the render copies them in + let mut sat_off = [0u32; 2]; + if let Some(GrainModel::Crystal(g)) = &fp.grain { + let mut off = aux.len(); + for (slot, sat) in sat_off.iter_mut().zip(&g.tile.sats) { + *slot = off as u32; + off += sat.len(); + } + } let mut p = Block::new(); p.u("LIGHT_OPS", light.len() as u32); @@ -330,12 +347,27 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr p.b("PROOF_DEST_WARN", pp.dest_warning); p.b("PROOF_DISP_WARN", pp.display_warning); } - if let Some((amt, cell, rough, seed)) = fp.grain { + if let Some(model) = &fp.grain { p.b("GRAIN", true); - p.f("GRAIN_AMT", amt); - p.f("GRAIN_SC", fp.px_per_long as f32 / cell); - p.f("GRAIN_ROUGH", rough); - p.u("GRAIN_SEED", seed); + match model { + GrainModel::Value(g) => { + p.u("GRAIN_MODEL", 0); + p.f("GRAIN_AMT", g.amt); + p.f("GRAIN_SC", fp.px_per_long as f32 / g.cell); + p.f("GRAIN_ROUGH", g.rough); + p.u("GRAIN_SEED", g.seed); + } + GrainModel::Crystal(g) => { + p.u("GRAIN_MODEL", 1); + p.f("GRAIN_K", g.k); + p.f("GRAIN_FOOT", g.foot); + if let Some(i) = index("GRAIN_SAT") { + for (slot, off) in p.0.iter_mut().skip(i).zip(sat_off) { + *slot = off; + } + } + } + } let long = fp.ow.max(fp.oh); let [a, b, c, d, e, f] = fp.out_to_norm.0; let (kx, ky) = (fp.ow / long, fp.oh / long); diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 2b20866e64..a392ee6ee1 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -136,6 +136,10 @@ pub(crate) struct Cx<'a> { enc: Option, /// Kernel invocations recorded since the last submit. pending: u64, + /// Buffers shared with other renders that recorded commands read from (the resident grain + /// tables): kept until those commands are submitted. Declared after `enc`, so an unsubmitted + /// encoder is dropped before them. + held: Vec>, } /// Kernel invocations recorded before a render submits them (under one full-size pass over a @@ -147,7 +151,7 @@ const BAND_PIXELS: usize = 4 << 20; impl<'a> Cx<'a> { pub fn new(gpu: &'a Gpu) -> Cx<'a> { - Cx { gpu, enc: Some(gpu.encoder()), pending: 0 } + Cx { gpu, enc: Some(gpu.encoder()), pending: 0, held: Vec::new() } } /// Record kernel `name` (see [`Gpu::run`]). @@ -161,11 +165,27 @@ impl<'a> Cx<'a> { } } + /// The finish kernel's `aux` buffer: `aux`, then the crystal grain's tables when it has them + /// (copied on the GPU from the resident ones, see [`Gpu::grain_tables`]). + pub fn finish_aux(&mut self, aux: &[f32], grain: Option<&lightcraft_pipeline::finish::GrainModel>) -> Buf { + let Some(lightcraft_pipeline::finish::GrainModel::Crystal(g)) = grain else { return self.gpu.upload(aux) }; + let tables: usize = g.tile.sats.iter().map(Vec::len).sum(); + let out = self.gpu.buffer(aux.len().saturating_add(tables)); + if !aux.is_empty() && out.raw().size() >= (aux.len() as u64) * 4 { + self.gpu.queue.write_buffer(out.raw(), 0, bytemuck::cast_slice(aux)); + } + let enc = self.enc.get_or_insert_with(|| self.gpu.encoder()); + self.held.extend(self.gpu.grain_tables(enc, &g.tile, &out, aux.len())); + out + } + /// Submit what is recorded and read back `len` values of `b`. pub fn read(&mut self, b: &Buf, len: usize) -> Vec { self.pending = 0; let enc = self.enc.take().unwrap_or_else(|| self.gpu.encoder()); - self.gpu.finish_and_read(enc, b, len) + let out = self.gpu.finish_and_read(enc, b, len); + self.held.clear(); + out } /// Submit what is recorded so far without waiting. Renders submit stage by stage and every @@ -177,6 +197,7 @@ impl<'a> Cx<'a> { if let Some(enc) = self.enc.take() { self.gpu.submit([enc.finish()]); } + self.held.clear(); } /// Submit what is recorded and wait for it (profiling only: stage timings). @@ -185,6 +206,7 @@ impl<'a> Cx<'a> { if let Some(enc) = self.enc.take() { self.gpu.submit([enc.finish()]); } + self.held.clear(); let _ = self.gpu.poll(wgpu::PollType::wait_indefinitely()); } @@ -349,6 +371,9 @@ fn guided_coeffs(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, sigma: f32, eps: gaussian(cx, &ab, w, h, 2, sigma) } +/// Pixels per thread along the pass of `median_h` / `median_v` (`MED_K` in `blur.wgsl`). +const MEDIAN_K: usize = 4; + /// Separable median of a plane (`local::median_hv`). fn median_hv(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, r: usize) -> Buf { if r == 0 || w * h == 0 { @@ -356,21 +381,38 @@ fn median_hv(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, r: usize) -> Buf { } let pr = [w as u32, h as u32, 1, r.min(local::BASE_DETAIL_MAX) as u32]; let tmp = cx.gpu.buffer(w * h); - cx.run("median_h", &pr, &[Some(p), Some(&tmp)], groups2(w, h, [16, 16])); + cx.run("median_h", &pr, &[Some(p), Some(&tmp)], groups2(w.div_ceil(MEDIAN_K), h, [16, 16])); let out = cx.gpu.buffer(w * h); - cx.run("median_v", &pr, &[Some(&tmp), Some(&out)], groups2(w, h, [16, 16])); + cx.run("median_v", &pr, &[Some(&tmp), Some(&out)], groups2(w, h.div_ceil(MEDIAN_K), [16, 16])); out } -/// The highlights/shadows base (`local::tone_base`; `detail` 0: V1, no median). -fn tone_base(cx: &mut Cx<'_>, l: &Buf, w: usize, h: usize, sigma: f32, detail: usize) -> Buf { +/// The highlights/shadows base (`local::tone_base`; `detail` 0: V1, no detail removal). +fn tone_base(cx: &mut Cx<'_>, l: &Buf, w: usize, h: usize, sigma: f32, detail: usize, keeps_gaps: bool) -> Buf { if detail == 0 { return guided_fast(cx, l, w, h, sigma, local::BASE_EPS); } - let m = median_hv(cx, l, w, h, detail); + let m = if keeps_gaps { detail_free(cx, l, w, h, detail) } else { median_hv(cx, l, w, h, detail) }; guided_fast(cx, &m, w, h, sigma, local::BASE_EPS) } +/// Log luminance without detail finer than `r` px (`local::detail_free`): clamped between its +/// median at `r` and the median of a `local::BASE_COARSE_STEP`× downscaled copy, enlarged. +fn detail_free(cx: &mut Cx<'_>, l: &Buf, w: usize, h: usize, r: usize) -> Buf { + if r == 0 || w * h == 0 { + return cx.copy(l); + } + let fine = median_hv(cx, l, w, h, r); + let s = local::BASE_COARSE_STEP; + let (lw, lh) = (w.div_ceil(s).max(1), h.div_ceil(s).max(1)); + let lo = resize(cx, l, (w, h), (lw, lh), 1, Filter::Box); + let lo_median = median_hv(cx, &lo, lw, lh, r); + let coarse = resize(cx, &lo_median, (lw, lh), (w, h), 1, Filter::Bilinear); + let out = cx.gpu.buffer(w * h); + map(cx, "clamp_between_k", w * h, &[], [Some(l), Some(&fine), Some(&coarse)], &out); + out +} + /// Fast guided filter (`local::guided_fast`): coefficients on a subsampled grid. fn guided_fast(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, sigma: f32, eps: f32) -> Buf { let s = local::guided_fast_step(sigma); @@ -749,6 +791,7 @@ pub fn render( px_per_long: plan.px_per_long, air_pre: prep.air, space: req.space, + draft: req.quality == lightcraft_pipeline::Quality::Draft, }); // soft proofing as the CPU's `finish` sets it up (an output-device table never gets here: see `render`) fp.proof = req.proof.map(|pr| pr.params(req.space)); @@ -780,7 +823,7 @@ pub fn render( if crate::ctx::failed() { return None; // a malformed parameter block failed the render: the CPU fallback redoes it } - let aux = gpu.upload(&aux); + let aux = cx.finish_aux(&aux, fp.grain.as_ref()); // cleared, so that work which never ran cannot pass for an image (see the check below) let out = cx.zeroed(if deep { 3 * n } else { n }); if fault == Some(crate::Fault::Validation) { @@ -1011,7 +1054,14 @@ fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, ho eyed } }; - denoise(cx, img, plan, colour_noise) + let img = denoise(cx, img, plan, colour_noise); + if !lightcraft_pipeline::lens_blur::renders(s) { + return img; + } + // Lens Blur (global or a mask's): on the CPU, like the CPU renderer's (`lens_blur::apply`) + let mut host_img = cx.read_rgb(&img, w, h); + lightcraft_pipeline::lens_blur::apply_with(&mut host_img, s, &plan.frame, plan.px_per_long, plan.mattes.as_deref(), plan.lens_subject.as_deref()); + cx.gpu.upload(rgb_words(&host_img)) } /// Defringe (`optics::defringe`) of the white-balanced image. @@ -1395,7 +1445,7 @@ fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, pla let base = match sig.base { Some(sg) => { let key = local::base_key(&plan.settings, sg, sig.base_detail); - plane_at(&mut planes.base, key, || tone_base(cx, &log_l, w, h, sg, sig.base_detail)) + plane_at(&mut planes.base, key, || tone_base(cx, &log_l, w, h, sg, sig.base_detail, local::base_keeps_gaps(&plan.settings))) } None => log_l.clone(), }; @@ -1818,6 +1868,76 @@ mod tests { time("guided sigma=1.75", &mut |cx| drop(guided(cx, &src, w, h, 1.75, 0.01))); } + /// The tiled median kernels select exactly what the CPU's sorted window does: edge tiles, + /// planes smaller than a tile or a window, every radius and many ties. + #[test] + fn median_matches_cpu_bit_for_bit() { + // (creating the device writes the crash sentinel another test swaps out) + let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(gpu) = crate::device() else { return lightcraft_testkit::skip!(Gpu, "no GPU adapter") }; + let _scope = crate::ctx::RenderScope::new(gpu); + let mut seed = 0x9e37_79b9_u32; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed + }; + for (w, h) in [(1, 1), (2, 3), (5, 70), (70, 5), (63, 65), (130, 67), (200, 129)] { + // a coarse level set gives ties; a smooth ramp and fine noise give distinct values + let mut p = Plane::new(w, h); + for (i, o) in p.data.iter_mut().enumerate() { + let (x, y) = (i % w, i / w); + *o = match (next() % 3, next()) { + (0, v) => (v % 7) as f32 * 0.5 - 2.0, + (1, v) => (x + 2 * y) as f32 * 0.01 + (v % 100) as f32 * 1e-4, + (_, v) => (v % 10_000) as f32 * 1e-3 - 5.0, + }; + } + let src = gpu.upload(&p.data); + for r in 1..=local::BASE_DETAIL_MAX { + let mut cx = Cx::new(gpu); + let out = median_hv(&mut cx, &src, w, h, r); + let got: Vec = cx.read(&out, w * h); + let want = local::median_hv(&p, r); + let bad = got.iter().zip(&want.data).position(|(g, c)| g.to_bits() != c.to_bits()); + assert!(bad.is_none(), "{w}×{h} r={r}: pixel {bad:?}"); + } + } + } + + /// Highlights/shadows base timings on the #3460 frame size: + /// `cargo test --release -p lightcraft-gpu bench_tone_base -- --ignored --nocapture`. + #[test] + #[ignore] + fn bench_tone_base() { + let Some(gpu) = crate::device() else { return eprintln!("no gpu: {:?}", crate::unavailable_reason()) }; + let _scope = crate::ctx::RenderScope::new(gpu); + let (w, h) = (6960, 4640); + let r = local::base_detail_radius(w as f64); + eprintln!("{} ({:?}) r={r}", gpu.info.name, gpu.info.backend); + let l: Vec = (0..w * h).map(|i: usize| ((i.wrapping_mul(2_654_435_761)) % 1000) as f32 / 250.0 - 6.0).collect(); + let src = gpu.upload(&l); + let time = |name: &str, f: &mut dyn FnMut(&mut Cx<'_>)| { + let mut ts = Vec::new(); + for _ in 0..9 { + let mut cx = Cx::new(gpu); + cx.sync(); + let t = std::time::Instant::now(); + f(&mut cx); + cx.sync(); + ts.push(t.elapsed().as_secs_f64() * 1e3); + } + ts.sort_by(f64::total_cmp); + eprintln!("{name:<40} min {:.1} ms median {:.1} ms", ts[0], ts[4]); + }; + let sigma = 0.015 * w as f32; + time("median_hv", &mut |cx| drop(median_hv(cx, &src, w, h, r))); + time("detail_free", &mut |cx| drop(detail_free(cx, &src, w, h, r))); + time("guided_fast", &mut |cx| drop(guided_fast(cx, &src, w, h, sigma, local::BASE_EPS))); + time("tone_base", &mut |cx| drop(tone_base(cx, &src, w, h, sigma, r, true))); + } + /// The device scores Remove's candidate sources like the CPU and picks the same one. #[test] fn auto_source_picks_the_cpu_candidate() { diff --git a/crates/gpu/src/wgsl/blur.wgsl b/crates/gpu/src/wgsl/blur.wgsl index 756457ade4..e6a624dffb 100644 --- a/crates/gpu/src/wgsl/blur.wgsl +++ b/crates/gpu/src/wgsl/blur.wgsl @@ -113,56 +113,114 @@ fn minmax(@builtin(global_invocation_id) g: vec3) { } // Separable median of a single-channel plane (`lightcraft_pipeline::local::median_hv`): 2r+1 -// taps (r ≤ 24, clamped edges) along a row (median_h) or a column (median_v), one thread per -// pixel. The median is a selection, so the result matches the CPU's bit for bit. +// taps (1 ≤ r ≤ 24, clamped edges) along a row (median_h) or a column (median_v). The median is a +// selection, so the result matches the CPU's bit for bit. // P: w, h, nc (unused), r. -fn median_of(n: u32, r: u32, v: ptr>) -> f32 { - // partial selection sort up to the middle - for (var i = 0u; i <= r; i++) { - var m = i; - for (var j = i + 1u; j < n; j++) { - if ((*v)[j] < (*v)[m]) { - m = j; - } +// +// Each thread finds the medians of 4 neighbouring pixels along the pass by rank: a tap is the +// median of a window when fewer than r+1 of its taps are smaller and at least r+1 are smaller or +// equal. The 4 windows share all but their first and last 3 taps, so one count over the shared +// taps serves all four. A 16×16 workgroup (64 pixels along the pass, 16 lines across) first loads +// its taps into `med_tile`. On a 6960×4640 plane at r = 10 this takes 47 ms on an M2 Max, against +// 191 ms for a partial selection sort per pixel over a private array of taps, which drivers keep in +// scratch memory because it is indexed dynamically. +const MED_K: u32 = 4u; +const MED_LINE: u32 = 113u; // 16·MED_K + 2·24, odd +// Not zero-initialised (`build_jobs` in ctx.rs turns that off): write every element read. +var med_tile: array; // 16 lines + +// The medians of the 2r+1-tap windows starting at `med_tile[base + k]`, k < 4 (r ≥ 1). Taps 3 to +// n-1 are in all four windows; the three at each end are in some. +fn median4(base: u32, r: u32) -> vec4 { + let n = 2u * r + 1u; + let e0 = vec3(med_tile[base], med_tile[base + 1u], med_tile[base + 2u]); + let e1 = vec3(med_tile[base + n], med_tile[base + n + 1u], med_tile[base + n + 2u]); + var out = vec4(0.0); + var found = vec4(false); + for (var i = 0u; i < n + 3u; i++) { + let c = med_tile[base + i]; + var less = 0u; + var le = 0u; + for (var j = 3u; j < n; j++) { + let v = med_tile[base + j]; + less += select(0u, 1u, v < c); + le += select(0u, 1u, v <= c); + } + let l0 = select(vec3(0u), vec3(1u), e0 < vec3(c)); + let l1 = select(vec3(0u), vec3(1u), e1 < vec3(c)); + let q0 = select(vec3(0u), vec3(1u), e0 <= vec3(c)); + let q1 = select(vec3(0u), vec3(1u), e1 <= vec3(c)); + // window k: taps k..k+n-1 = taps k..2 of the start, the middle, taps n..n+k-1 of the end + let lw = vec4(l0.x + l0.y + l0.z, l0.y + l0.z + l1.x, l0.z + l1.x + l1.y, l1.x + l1.y + l1.z) + vec4(less); + let qw = vec4(q0.x + q0.y + q0.z, q0.y + q0.z + q1.x, q0.z + q1.x + q1.y, q1.x + q1.y + q1.z) + vec4(le); + let has = vec4((i < n), (i >= 1u) && (i < n + 1u), (i >= 2u) && (i < n + 2u), (i >= 3u)); + let hit = has & !found & (lw <= vec4(r)) & (qw > vec4(r)); + out = select(out, vec4(c), hit); + found = found | hit; + if (all(found)) { + break; } - let t = (*v)[i]; - (*v)[i] = (*v)[m]; - (*v)[m] = t; } - return (*v)[r]; + return out; } +// Thread (l.x, l.y) of a workgroup takes line l.x and pixels 4·l.y to 4·l.y + 3 along it, so the +// threads of a SIMD group read 16 different lines at once; with an odd line length those fall in +// different banks of workgroup memory. @compute @workgroup_size(16, 16) -fn median_h(@builtin(global_invocation_id) g: vec3) { +fn median_h(@builtin(local_invocation_id) l: vec3, @builtin(workgroup_id) wg: vec3) { let w = pu(0u); let h = pu(1u); let r = min(pu(3u), 24u); - if (g.x >= w || g.y >= h) { + let span = 16u * MED_K + 2u * r; + let x0 = i32(wg.x * 16u * MED_K) - i32(r); + // load: consecutive threads read consecutive pixels of a row + for (var e = l.y * 16u + l.x; e < 16u * span; e += 256u) { + let line = e / span; + let k = e % span; + let y = min(wg.y * 16u + line, h - 1u); + let x = clamp(x0 + i32(k), 0, i32(w) - 1); + med_tile[line * MED_LINE + k] = src[y * w + u32(x)]; + } + workgroupBarrier(); + let y = wg.y * 16u + l.x; + let x = (wg.x * 16u + l.y) * MED_K; + if (x >= w || y >= h) { return; } - let n = 2u * r + 1u; - var v: array; - let row = g.y * w; - for (var k = 0u; k < n; k++) { - let x = clamp(i32(g.x + k) - i32(r), 0, i32(w) - 1); - v[k] = src[row + u32(x)]; + let m = median4(l.x * MED_LINE + l.y * MED_K, r); + for (var k = 0u; k < MED_K; k++) { + if (x + k < w) { + dst[y * w + x + k] = m[k]; + } } - dst[row + g.x] = median_of(n, r, &v); } @compute @workgroup_size(16, 16) -fn median_v(@builtin(global_invocation_id) g: vec3) { +fn median_v(@builtin(local_invocation_id) l: vec3, @builtin(workgroup_id) wg: vec3) { let w = pu(0u); let h = pu(1u); let r = min(pu(3u), 24u); - if (g.x >= w || g.y >= h) { + let span = 16u * MED_K + 2u * r; + let y0 = i32(wg.y * 16u * MED_K) - i32(r); + // load: consecutive threads read consecutive pixels of a row (16 columns) + for (var e = l.y * 16u + l.x; e < 16u * span; e += 256u) { + let line = e % 16u; + let k = e / 16u; + let x = min(wg.x * 16u + line, w - 1u); + let y = clamp(y0 + i32(k), 0, i32(h) - 1); + med_tile[line * MED_LINE + k] = src[u32(y) * w + x]; + } + workgroupBarrier(); + let x = wg.x * 16u + l.x; + let y = (wg.y * 16u + l.y) * MED_K; + if (x >= w || y >= h) { return; } - let n = 2u * r + 1u; - var v: array; - for (var k = 0u; k < n; k++) { - let y = clamp(i32(g.y + k) - i32(r), 0, i32(h) - 1); - v[k] = src[u32(y) * w + g.x]; + let m = median4(l.x * MED_LINE + l.y * MED_K, r); + for (var k = 0u; k < MED_K; k++) { + if (y + k < h) { + dst[(y + k) * w + x] = m[k]; + } } - dst[g.y * w + g.x] = median_of(n, r, &v); } diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl index 266599644a..8a2f72f89f 100644 --- a/crates/gpu/src/wgsl/finish.wgsl +++ b/crates/gpu/src/wgsl/finish.wgsl @@ -291,6 +291,65 @@ fn ghash(i: i32, j: i32, seed: u32) -> f32 { return f32(v & 0xffffu) / 32768.0 - 1.0; } +// Crystal grain (process V4): `lightcraft_pipeline::crystal` (keep in step with it). The tori's +// summed-area tables follow the other tables in `aux` (offsets F_GRAIN_SAT). +fn cg_bilinear(o: u32, t: u32, x: f32, y: f32) -> f32 { + let s = t + 1u; + let i = min(u32(max(x, 0.0)), t - 1u); + let j = min(u32(max(y, 0.0)), t - 1u); + let fx = x - f32(i); + let fy = y - f32(j); + let b = o + j * s + i; + let a = aux[b] + (aux[b + 1u] - aux[b]) * fx; + let c = aux[b + s] + (aux[b + s + 1u] - aux[b + s]) * fx; + return a + (c - a) * fy; +} + +fn cg_integral(o: u32, t: u32, x: f32, y: f32) -> f32 { + let tf = f32(t); + let wx = x >= tf; + let wy = y >= tf; + let rx = select(x, x - tf, wx); + let ry = select(y, y - tf, wy); + var v = cg_bilinear(o, t, rx, ry); + if (wx) { + v += cg_bilinear(o, t, tf, ry); + } + if (wy) { + v += cg_bilinear(o, t, rx, tf); + } + if (wx && wy) { + v += cg_bilinear(o, t, tf, tf); + } + return v; +} + +fn cg_box(o: u32, t: u32, x0_: f32, y0_: f32, w: f32) -> f32 { + let tf = f32(t); + let x0 = x0_ - floor(x0_ / tf) * tf; + let y0 = y0_ - floor(y0_ / tf) * tf; + return cg_integral(o, t, x0 + w, y0 + w) - cg_integral(o, t, x0, y0 + w) - cg_integral(o, t, x0 + w, y0) + cg_integral(o, t, x0, y0); +} + +fn cg_lift(v: f32) -> f32 { + let c = clamp(v, 0.0, 1.0); + return select((c + 0.055) / 2.4, c, c <= 0.04045); +} + +fn cg_srgb_to_linear(v: f32) -> f32 { + return select(pow((v + 0.055) / 1.055, 2.4), v / 12.92, v <= 0.04045); +} + +fn crystal_grain(e: vec3, gx: f32, gy: f32) -> vec3 { + let w = pf(F_GRAIN_FOOT); + let x0 = gx * CRYSTAL_TPL - 0.5 * w; + let y0 = gy * CRYSTAL_TPL - 0.5 * w; + let g = (cg_box(pu(F_GRAIN_SAT), CRYSTAL_T0, x0, y0, w) + cg_box(pu(F_GRAIN_SAT + 1u), CRYSTAL_T1, x0, y0, w)) / (w * w); + let lum = clamp(0.2126 * e.x + 0.7152 * e.y + 0.0722 * e.z, 0.0, 1.0); + let k = pf(F_GRAIN_K) * g * (1.0 - cg_srgb_to_linear(lum)); + return e + k * vec3(cg_lift(e.x), cg_lift(e.y), cg_lift(e.z)); +} + fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { let x0 = floor(x); let y0 = floor(y); @@ -694,17 +753,21 @@ fn main(@builtin(global_invocation_id) gid: vec3) { let py = f32(y) + 0.5; let gx = pf(F_GRAIN_AFF) * px + pf(F_GRAIN_AFF + 2u) * py + pf(F_GRAIN_AFF + 4u); let gy = pf(F_GRAIN_AFF + 1u) * px + pf(F_GRAIN_AFF + 3u) * py + pf(F_GRAIN_AFF + 5u); - let sc = pf(F_GRAIN_SC); - let rough = pf(F_GRAIN_ROUGH); - let seed = pu(F_GRAIN_SEED); - var g = grain_noise(gx * sc, gy * sc, seed); - g = g * (1.0 - rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, seed ^ 0x55u) * rough * 0.7; - var lum = 0.2126 * e.x + 0.7152 * e.y + 0.0722 * e.z; - if (hdr) { - lum = clamp(lum, 0.0, 1.0); + if (pu(F_GRAIN_MODEL) == 1u) { + e = crystal_grain(e, gx, gy); + } else { + let sc = pf(F_GRAIN_SC); + let rough = pf(F_GRAIN_ROUGH); + let seed = pu(F_GRAIN_SEED); + var g = grain_noise(gx * sc, gy * sc, seed); + g = g * (1.0 - rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, seed ^ 0x55u) * rough * 0.7; + var lum = 0.2126 * e.x + 0.7152 * e.y + 0.0722 * e.z; + if (hdr) { + lum = clamp(lum, 0.0, 1.0); + } + let k = pf(F_GRAIN_AMT) * g * (0.35 + 2.6 * lum * (1.0 - lum)); + e = e + k; } - let k = pf(F_GRAIN_AMT) * g * (0.35 + 2.6 * lum * (1.0 - lum)); - e = e + k; } if (pu(F_LUT) != 0u) { let lc = clamp(e, vec3(0.0), vec3(1.0)); diff --git a/crates/gpu/src/wgsl/map.wgsl b/crates/gpu/src/wgsl/map.wgsl index 9b84b8d89d..2b5f658931 100644 --- a/crates/gpu/src/wgsl/map.wgsl +++ b/crates/gpu/src/wgsl/map.wgsl @@ -70,6 +70,25 @@ fn guided_apply(@builtin(global_invocation_id) g: vec3, @builtin(num_workgr dst[i] = b[2u * i] * a[i] + b[2u * i + 1u]; } +// `clamp_between` (`local::detail_free`): a clamped between b and c, in either order. +@compute @workgroup_size(256) +fn clamp_between_k(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + let lo = min(b[i], c[i]); + let hi = max(b[i], c[i]); + let v = a[i]; + if (v < lo) { + dst[i] = lo; + } else if (v > hi) { + dst[i] = hi; + } else { + dst[i] = v; + } +} + // Cross guided filter (`masks::guided_cross`), a: guide, b: input. P[1] = 0: (guide, input); // 1: (guide·input, guide²). @compute @workgroup_size(256) diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 8c87dd7e26..a8fa80f812 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -210,6 +210,33 @@ fn banded_full_size_render_matches() { check("banded 3000×2000", &src, &SourceInfo { raw: true, ..Default::default() }, &s, &RenderRequest::fit(w, h)); } +/// The crystal grain's tables stay on the GPU between renders: an Amount change reuses them, +/// another pattern (Size, Roughness, seed) replaces them, and going back draws the first again. +#[test] +fn grain_patterns_in_turn_match() { + if !gpu() { + return; + } + let src = scene(1, 480, 320); + let info = SourceInfo { raw: true, ..Default::default() }; + let steps: [(&str, f64, f64, f64, u32); 6] = [ + ("grain 50/25/50", 50.0, 25.0, 50.0, 1), + ("grain 90/25/50 (same pattern)", 90.0, 25.0, 50.0, 1), + ("grain 50/70/50 (new size)", 50.0, 70.0, 50.0, 1), + ("grain 50/70/0 (new roughness)", 50.0, 70.0, 0.0, 1), + ("grain 50/70/0 seed 7", 50.0, 70.0, 0.0, 7), + ("grain 50/25/50 again", 50.0, 25.0, 50.0, 1), + ]; + for (name, amount, size, roughness, seed) in steps { + let mut s = DevelopSettings::default(); + s.grain.amount = amount; + s.grain.size = size; + s.grain.roughness = roughness; + s.grain.seed = seed; + check(name, &src, &info, &s, &RenderRequest::fit(480, 320)); + } +} + fn cases() -> Vec<(&'static str, Edit)> { vec![ ("default", |_| {}), @@ -287,6 +314,25 @@ fn cases() -> Vec<(&'static str, Edit)> { s.grain.size = 40.0; s.grain.roughness = 60.0; }), + // the frozen value-noise grain of the earlier processes (the default is V7's crystals) + ("grain, process V6", |s| { + s.process = Process::V6.version(); + s.grain.amount = 50.0; + s.grain.size = 40.0; + s.grain.roughness = 60.0; + }), + ("grain, process V1", |s| { + s.process = Process::V1.version(); + s.grain.amount = 50.0; + s.grain.size = 40.0; + s.grain.roughness = 60.0; + }), + ("grain, process V2", |s| { + s.process = Process::V2.version(); + s.grain.amount = 50.0; + s.grain.size = 40.0; + s.grain.roughness = 60.0; + }), ("dehaze -", |s| s.effects.dehaze = -50.0), ("dehaze +", |s| s.effects.dehaze = 60.0), ("clarity/texture -", |s| { @@ -761,7 +807,7 @@ fn light_v3_operators_match() { } /// Issue #632: the Highlights / Shadows base of each process (V1: the edge-aware filter of log -/// luminance; V2: of its fine median, a radius that grows with the render) matches the CPU's, and +/// luminance; V2 to V7: of its fine median, V8 on: of its detail-free plane, a radius that grows with the render) matches the CPU's, and /// a warm cache never hands one process the other's base. #[test] fn highlights_shadows_base_matches_on_every_process() { @@ -792,7 +838,7 @@ fn highlights_shadows_base_matches_on_every_process() { }]; check(&format!("{p:?} local highlights {w}"), &src, &raw, &s, &req); } - for p in [Process::V1, Process::V2, Process::V4, Process::V1, Process::V2, Process::V4] { + for p in [Process::V1, Process::V2, Process::V4, Process::V8, Process::V1, Process::V2, Process::V4, Process::V8] { let mut s = DevelopSettings { process: p.version(), ..DevelopSettings::default() }; s.light.highlights = -100.0; let warm = lightcraft_gpu::render(&src, &raw, &s, &req, Some(&cache)).expect("gpu"); diff --git a/crates/heif/src/lib.rs b/crates/heif/src/lib.rs index 5b20e31d75..a0733f6334 100644 --- a/crates/heif/src/lib.rs +++ b/crates/heif/src/lib.rs @@ -162,13 +162,22 @@ fn probe_unguarded(bytes: &[u8]) -> Result { // items (`iloc` construction method 2) is rebuilt once per extent, so a chain of such items // multiplies at every level while each result stays small. Count those visits from the // `iloc` table before reconstructing anything: the primary item first (`heic_rs::probe` and - // `Context::grid` both rebuild its descriptor), then its alpha plane, then every tile - // reference, repeats included. + // `Context::grid` both rebuild its descriptor), then its alpha plane and, when that is a grid, + // its tiles, then every tile reference, repeats included. let mut visits = 0_usize; item_visits(&ctx, id, 0, &mut visits)?; + // `heic_rs::probe` reads an item without `ispe` from its parameter sets + check_item_parameter_sets(&ctx.props(id).map_err(err)?)?; let info = heic_rs::probe(bytes).map_err(open_error)?; - if let Some(alpha) = ctx.alpha_item(id).map_err(err)? { + let alpha = ctx.alpha_item(id).map_err(err)?; + if let Some(alpha) = alpha { item_visits(&ctx, alpha, 0, &mut visits)?; + // an alpha plane may be a grid too: its tiles are rebuilt when it is decoded + if let Some((_, tiles)) = ctx.grid(alpha).map_err(err)? { + for &tile in tiles.iter().filter(|&&tile| tile != alpha) { + item_visits(&ctx, tile, 0, &mut visits)?; + } + } } let mut coded = match ctx.grid(id).map_err(err)? { Some((_, tiles)) => tiles, @@ -257,6 +266,25 @@ pub fn decode_thumbnail(bytes: &[u8], min_edge: u32, options: &Options) -> Resul continue; } let Ok(p) = ctx.props(r.from) else { continue }; + if check_item_parameter_sets(&p).is_err() { + continue; + } + // A grid whose tile would fail the same check must not win and then fail in + // `decode_item`, with no fallback to a larger valid thumbnail. + let grid = match ctx.grid(r.from) { + Ok(grid) => grid, + // an unreadable grid fails in `decode_item` too: not a candidate + Err(_) => continue, + }; + if let Some((_, tiles)) = grid { + let mut seen = std::collections::HashSet::new(); + let tiles_ok = tiles.iter().filter(|t| seen.insert(**t)).all(|&t| { + item_visits(&ctx, t, 0, &mut candidate_visits).is_ok() && ctx.props(t).is_ok_and(|tp| check_item_parameter_sets(&tp).is_ok()) + }); + if !tiles_ok { + continue; + } + } let Ok((w, h)) = ctx.coded_size(r.from, &p) else { continue }; let edge = w.max(h); if edge >= min_edge && best.is_none_or(|(_, e)| edge < e) { @@ -316,7 +344,9 @@ fn decode_item(ctx: &Context<'_>, id: u32, options: &Options, with_alpha: bool) return Err(Error::Limit(format!("the image carries {} transform properties, over the {MAX_TRANSFORMS}-property cap", p.transforms.len()))); } let limit = options.max_pixels; - // The declared sizes are refused before anything is decoded or allocated. + // The declared sizes are refused before anything is decoded or allocated (an item without + // `ispe` takes its size from its parameter sets, checked first). + check_item_parameter_sets(&p)?; let (cw, ch) = ctx.coded_size(id, &p).map_err(err)?; heic_rs::image::check_pixels(cw, ch, limit).map_err(err)?; let (tw, th) = heic_rs::transform::transformed_size(cw, ch, &p.transforms).map_err(err)?; @@ -376,6 +406,44 @@ const GRID_BUDGET: u64 = 2; /// most one of each, so anything approaching this is a reordered or hostile association list. const MAX_TRANSFORMS: usize = 12; +/// The most parameter sets one `hvcC` may carry: one per id H.265 allows (16 VPS, 16 SPS, 64 PPS). +/// heic-rs 0.1.4 replaces a repeated id by scanning every set kept so far, so more sets (repeats, +/// or ids past the standard's range) only make that collection quadratic. +const MAX_PARAMETER_SETS: usize = 16 + 16 + 64; +/// Highest `pps_pic_parameter_set_id` H.265 allows (7.4.3.3.1). +const MAX_PPS_ID: u32 = 63; +/// Most tile columns and rows a picture may have: H.265's level limits (Table A.8, levels 6 to +/// 6.2). heic-rs 0.1.4 builds its tile tables by walking the tile boundaries for every coding tree +/// block, so its work grows with blocks × tiles; these keep that a small multiple of the blocks. +const MAX_TILE_COLS: u32 = 20; +const MAX_TILE_ROWS: u32 = 22; + +/// Refuses parameter sets that would make heic-rs's set collection or tile tables cost far more +/// than the picture: too many sets, a PPS id out of range, or more tiles than any level allows. +fn check_parameter_sets(sets: &[&[u8]]) -> Result<(), Error> { + if sets.len() > MAX_PARAMETER_SETS { + return Err(Error::Limit(format!("the hvcC record carries {} parameter sets, over the {MAX_PARAMETER_SETS}-set cap", sets.len()))); + } + let layouts = vui::pps_layouts(sets).ok_or_else(|| Error::Malformed("unreadable picture parameter set".into()))?; + for p in layouts { + if p.id > MAX_PPS_ID { + return Err(Error::Malformed(format!("picture parameter set id {} is out of range", p.id))); + } + if p.tile_cols > MAX_TILE_COLS || p.tile_rows > MAX_TILE_ROWS { + return Err(Error::Limit(format!( + "a picture of {} × {} tiles, over the {MAX_TILE_COLS} × {MAX_TILE_ROWS} H.265 allows", + p.tile_cols, p.tile_rows + ))); + } + } + Ok(()) +} + +/// [`check_parameter_sets`] of a coded item's `hvcC`, if it has one. +fn check_item_parameter_sets(p: &ItemProps<'_>) -> Result<(), Error> { + p.hvcc.as_ref().map_or(Ok(()), |h| check_parameter_sets(&h.parameter_sets())) +} + /// The decoded pictures of an item: one, or a grid's tiles in `dimg` order. struct Coded<'a> { frames: Vec, @@ -400,15 +468,24 @@ impl<'a> Coded<'a> { // conformance window (or a slice picking another SPS) can make far larger than the // declared one, and a grid holds all its tiles at once. Both are refused before decoding. let mut total = 0u64; + // A grid may list one tile thousands of times: each distinct tile is read and checked + // once, so the work follows the file's items, not the grid's cell count. + let mut largest_of: std::collections::HashMap = std::collections::HashMap::new(); for t in &ids { + if let Some(largest) = largest_of.get(t) { + total = total.saturating_add(*largest); + continue; + } let tp = ctx.props(*t).map_err(err)?; let hvcc = tp.hvcc.as_ref().ok_or(heic_rs::Error::MissingBox("hvcC")).map_err(err)?; + check_parameter_sets(&hvcc.parameter_sets())?; let sizes = vui::coded_sizes(&hvcc.parameter_sets()).ok_or_else(|| Error::Malformed("unreadable sequence parameter set".into()))?; let mut largest = 0u64; for (w, h) in sizes { heic_rs::image::check_pixels(w, h, limit).map_err(err)?; largest = largest.max(u64::from(w) * u64::from(h)); } + largest_of.insert(*t, largest); total = total.saturating_add(largest); } if total > limit.saturating_mul(GRID_BUDGET) { diff --git a/crates/heif/src/testdata.rs b/crates/heif/src/testdata.rs index 595cfa33c5..bd8945cabd 100644 --- a/crates/heif/src/testdata.rs +++ b/crates/heif/src/testdata.rs @@ -47,11 +47,25 @@ pub struct Spec<'a> { pub thumbnail: Option>, /// Auxiliary images of these types the decoder must ignore (HDR gain map, depth…). pub ignored_aux: Vec<&'static str>, + /// When nonzero, the alpha image is instead a grid of `n` × `n` references to one alpha tile + /// (a hostile file: the same stored picture rebuilt for every reference). + pub alpha_tile_repeats: u8, } impl<'a> Spec<'a> { pub fn new(width: u32, height: u32, sample: Sampler<'a>) -> Spec<'a> { - Spec { width, height, bit_depth: 8, sample, props: Vec::new(), exif: None, alpha: None, thumbnail: None, ignored_aux: Vec::new() } + Spec { + width, + height, + bit_depth: 8, + sample, + props: Vec::new(), + exif: None, + alpha: None, + thumbnail: None, + ignored_aux: Vec::new(), + alpha_tile_repeats: 0, + } } } @@ -524,7 +538,20 @@ pub fn build(spec: &Spec<'_>) -> Vec { } f.refs.push((b"auxl", id, vec![primary])); }; - if let Some(alpha) = spec.alpha { + if let (Some(alpha), n @ 1..) = (spec.alpha, spec.alpha_tile_repeats) { + let tile = f.image(TILE, TILE, bd, true, &|x, y| [alpha(x, y), 0, 0]); + if let Some(it) = f.items.iter_mut().find(|i| i.id == tile) { + it.hidden = true; + } + let side = u32::from(n) * TILE; + let mut g = vec![0u8, 0, n - 1, n - 1]; + g.extend_from_slice(&(side as u16).to_be_bytes()); + g.extend_from_slice(&(side as u16).to_be_bytes()); + let auxc = f.prop(full_box(b"auxC", 0, b"urn:mpeg:hevc:2015:auxid:1\0")); + let id = f.add(b"grid", g, vec![(auxc, true)]); + f.refs.push((b"dimg", id, vec![tile; usize::from(n) * usize::from(n)])); + f.refs.push((b"auxl", id, vec![primary])); + } else if let Some(alpha) = spec.alpha { aux(&mut f, "urn:mpeg:hevc:2015:auxid:1", &|x, y| [alpha(x, y), 0, 0]); } for urn in &spec.ignored_aux { diff --git a/crates/heif/src/tests_synthetic.rs b/crates/heif/src/tests_synthetic.rs index 1286ff82a9..d08b6d1fb4 100644 --- a/crates/heif/src/tests_synthetic.rs +++ b/crates/heif/src/tests_synthetic.rs @@ -139,6 +139,20 @@ fn alpha_comes_from_its_auxiliary_image() { assert_eq!(d.data[..3], [luma(0, 0) * 257; 3]); } +#[test] +fn an_alpha_grid_decodes_and_its_tile_references_share_the_visit_budget() { + let alpha = |x: u32, _: u32| (x * 4) as u16; + // a 2 × 2 alpha grid naming one tile four times: a valid file + let d = decoded(&Spec { alpha: Some(&alpha), alpha_tile_repeats: 2, ..Spec::new(64, 64, &grey) }); + assert!(d.has_alpha); + assert_eq!((d.data[10 * 4 + 3], d.data[42 * 4 + 3]), (40 * 257, 40 * 257)); + // 70 × 70 references to that tile: each would be rebuilt and decoded, so it is refused first + let bytes = build(&Spec { alpha: Some(&alpha), alpha_tile_repeats: 70, ..Spec::new(32, 32, &grey) }); + for r in [probe(&bytes).map(|_| ()), decode(&bytes, &Options::default()).map(|_| ())] { + assert!(matches!(&r, Err(Error::Limit(m)) if m.contains("extent reads")), "{r:?}"); + } +} + #[test] fn limits_are_checked_before_decoding() { let bytes = build(&Spec::new(96, 64, &grey)); diff --git a/crates/heif/src/vui.rs b/crates/heif/src/vui.rs index 6bc629fa57..bfe10fa097 100644 --- a/crates/heif/src/vui.rs +++ b/crates/heif/src/vui.rs @@ -49,6 +49,55 @@ pub fn coded_sizes(parameter_sets: &[&[u8]]) -> Option> { .collect() } +/// NAL unit type of a picture parameter set. +const PPS_NUT: u8 = 34; + +/// What [`pps_layouts`] reads of a picture parameter set. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PpsLayout { + /// `pps_pic_parameter_set_id`. + pub id: u32, + /// `num_tile_columns_minus1 + 1` (1 without tiles). + pub tile_cols: u32, + /// `num_tile_rows_minus1 + 1` (1 without tiles). + pub tile_rows: u32, +} + +/// The id and tile layout of every PPS among `parameter_sets`, read up to the tile counts +/// (H.265 7.3.2.3.1). `None`: a PPS this reader can't follow. +pub fn pps_layouts(parameter_sets: &[&[u8]]) -> Option> { + parameter_sets + .iter() + .filter(|n| n.first().is_some_and(|b| (b >> 1) & 0x3f == PPS_NUT)) + .map(|pps| { + let rbsp = unescape(pps.get(2..)?); + pps_layout(&mut Bits { data: &rbsp, pos: 0 }) + }) + .collect() +} + +fn pps_layout(r: &mut Bits) -> Option { + let id = r.ue()?; // pps_pic_parameter_set_id + r.ue()?; // pps_seq_parameter_set_id + // dependent slices, output flag, 3 extra slice header bits, sign hiding, cabac_init_present + r.skip(7)?; + r.ue()?; // num_ref_idx_l0_default_active_minus1 + r.ue()?; // num_ref_idx_l1_default_active_minus1 + r.se()?; // init_qp_minus26 + r.skip(2)?; // constrained_intra_pred_flag, transform_skip_enabled_flag + if r.flag()? { + r.ue()?; // diff_cu_qp_delta_depth + } + r.se()?; // pps_cb_qp_offset + r.se()?; // pps_cr_qp_offset + // slice chroma qp offsets present, weighted pred, weighted bipred, transquant bypass + r.skip(4)?; + let tiles = r.flag()?; // tiles_enabled_flag + r.skip(1)?; // entropy_coding_sync_enabled_flag + let (tile_cols, tile_rows) = if tiles { (r.ue()?.checked_add(1)?, r.ue()?.checked_add(1)?) } else { (1, 1) }; + Some(PpsLayout { id, tile_cols, tile_rows }) +} + /// Reads an SPS up to and including the picture size, leaving `r` after it: width, height and /// `sps_max_sub_layers_minus1`. fn sps_size(r: &mut Bits) -> Option<(u32, u32, u32)> { @@ -456,4 +505,63 @@ mod tests { } assert_eq!(signal(&[&[SPS_NUT << 1, 1, 0xff, 0xff, 0xff]]), None); } + + /// A PPS NAL as encoders write it, with `tiles` (columns, rows) when tiles are enabled. + fn pps(id: u32, cu_qp_delta: bool, tiles: Option<(u32, u32)>) -> Vec { + let mut w = Writer::default(); + w.ue(id); + w.ue(0); // sps id + w.u(0, 7); + w.ue(0); + w.ue(0); + w.ue(3); // init_qp_minus26 = -2 + w.u(0, 2); + w.u(u32::from(cu_qp_delta), 1); + if cu_qp_delta { + w.ue(1); + } + w.ue(1); // cb offset +1 + w.ue(2); // cr offset -1 + w.u(0, 4); + w.u(u32::from(tiles.is_some()), 1); + w.u(0, 1); + if let Some((c, r)) = tiles { + w.ue(c - 1); + w.ue(r - 1); + w.u(1, 1); // uniform spacing + w.u(1, 1); + } + w.u(0, 3); + [vec![PPS_NUT << 1, 1], w.bytes()].concat() + } + + #[test] + fn reads_pps_ids_and_tile_counts() { + let plain = pps(5, true, None); + let tiled = pps(63, false, Some((4, 3))); + let sps_nal = sps(|w| w.u(0, 1), |w| w.ue(0)); + assert_eq!( + pps_layouts(&[&sps_nal, &plain, &tiled]), + Some(vec![PpsLayout { id: 5, tile_cols: 1, tile_rows: 1 }, PpsLayout { id: 63, tile_cols: 4, tile_rows: 3 }]) + ); + assert_eq!(pps_layouts(&[&[PPS_NUT << 1, 1]]), None); + assert!(crate::check_parameter_sets(&[&sps_nal, &plain, &tiled]).is_ok()); + assert!(crate::check_parameter_sets(&[&pps(0, false, Some((20, 22)))]).is_ok()); + } + + #[test] + fn refuses_parameter_sets_that_multiply_decoder_work() { + // a PPS id past 63: heic-rs would keep every distinct one and rescan them all for each + let r = crate::check_parameter_sets(&[&pps(64, false, None)]); + assert!(matches!(r, Err(crate::Error::Malformed(_))), "{r:?}"); + // thousands of PPS records (even with valid, repeated ids): quadratic collection + let one = pps(1, false, None); + let many: Vec<&[u8]> = vec![&one; 5000]; + assert!(matches!(crate::check_parameter_sets(&many), Err(crate::Error::Limit(_)))); + // more tiles than any H.265 level allows: tile tables cost blocks × tiles + for (c, r) in [(21, 1), (1, 23), (1024, 1024)] { + let r = crate::check_parameter_sets(&[&pps(0, false, Some((c, r)))]); + assert!(matches!(r, Err(crate::Error::Limit(_))), "{r:?}"); + } + } } diff --git a/crates/inpaint/src/membrane.rs b/crates/inpaint/src/membrane.rs index 1f259b02fe..9fe3bf16fd 100644 --- a/crates/inpaint/src/membrane.rs +++ b/crates/inpaint/src/membrane.rs @@ -169,6 +169,10 @@ pub fn membrane_fill(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool]) if Some(hole.len()) != w.checked_mul(h) || Some(img.len()) != hole.len().checked_mul(ch) { return img.to_vec(); } + // no pixels: nothing to fill (and `ch` would otherwise size one plane per channel, whatever it claims) + if hole.is_empty() { + return img.to_vec(); + } per_channel(w, h, ch, |c| { let mut v: Vec = (0..w * h).map(|i| if hole[i] { 0.0 } else { img[i * ch + c] }).collect(); solve_membrane(w, h, hole, &mut v); @@ -183,6 +187,12 @@ mod tests { (0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect() } + #[test] + fn a_zero_area_image_comes_back_unchanged_whatever_its_channel_count() { + assert!(membrane_fill(0, 5, usize::MAX, &[], &[]).is_empty()); + assert!(membrane_fill(3, 0, 1 << 40, &[], &[]).is_empty()); + } + #[test] fn membrane_reproduces_linear_boundary() { // A linear function is harmonic: the solve must reproduce it exactly inside the hole. diff --git a/crates/lensdb/src/xml.rs b/crates/lensdb/src/xml.rs index 5eed2dd288..b3a1b520bc 100644 --- a/crates/lensdb/src/xml.rs +++ b/crates/lensdb/src/xml.rs @@ -53,13 +53,21 @@ fn entity(name: &str) -> Option { }) } +/// Index of the `;` that ends a reference starting at `rest` (its `&`). The scan stops at the first +/// byte that cannot appear in a name or a numeric reference, so zero-padded references such as +/// `a` are found and each run of name bytes is read once, not once per `&`. +fn entity_end(rest: &str) -> Option { + let n = rest.bytes().skip(1).take_while(|b| b.is_ascii_alphanumeric() || *b == b'#').count(); + (rest.as_bytes().get(n + 1) == Some(&b';')).then_some(n + 1) +} + fn unescape(s: &str) -> String { let mut out = String::with_capacity(s.len()); let mut rest = s; while let Some(i) = rest.find('&') { out.push_str(rest.get(..i).unwrap_or_default()); let tail = rest.get(i..).unwrap_or_default(); - match tail.find(';').and_then(|j| entity(tail.get(1..j)?).map(|c| (c, j))) { + match entity_end(tail).and_then(|j| entity(tail.get(1..j)?).map(|c| (c, j))) { Some((c, j)) => { out.push(c); rest = tail.get(j + 1..).unwrap_or_default(); @@ -140,6 +148,20 @@ fn close(stack: &mut Vec) { mod tests { use super::*; + #[test] + fn many_ampersands_before_one_semicolon_are_read_once() { + // 200 000 `&` then a `;`: each `&` once searched the whole rest for the `;` + let hostile = format!("{};&", "&".repeat(200_000)); + assert_eq!(unescape(&hostile), format!("{};&", "&".repeat(200_000))); + assert_eq!(unescape("<a> 􏿿 &unknownreference;"), " \u{10FFFF} &unknownreference;"); + } + + #[test] + fn zero_padded_numeric_references_decode() { + assert_eq!(unescape("Canon A A"), "Canon A A"); + assert_eq!(unescape("&abc&#xyz;&;"), "&abc&#xyz;&;"); + } + #[test] fn entity_rejects_signed_numeric_references() { assert_eq!(entity("#+65"), None); diff --git a/crates/merge/src/hdr.rs b/crates/merge/src/hdr.rs index dd1a9ee537..05aac1b082 100644 --- a/crates/merge/src/hdr.rs +++ b/crates/merge/src/hdr.rs @@ -119,6 +119,10 @@ pub fn merge_hdr(mut frames: Vec, opts: &HdrOptions, progress: &Progress) if frames.iter().any(|f| f.width() != w || f.height() != h) { return Err(MergeError::Mismatch("HDR merge needs photos of the same size".into())); } + // every buffer must hold exactly its frame's pixels before anything is sized from the dimensions + if frames.iter().any(|f| w.checked_mul(h) != Some(f.image.data.len())) { + return Err(MergeError::Mismatch("an HDR frame's pixels do not match its size".into())); + } if frames.iter().any(|f| f.orientation != frames[0].orientation) { for f in frames.iter_mut() { f.orient(); diff --git a/crates/meta/src/iptc.rs b/crates/meta/src/iptc.rs index 391774287f..a398c6fc49 100644 --- a/crates/meta/src/iptc.rs +++ b/crates/meta/src/iptc.rs @@ -20,6 +20,7 @@ pub fn parse_iptc(b: &[u8]) -> Metadata { let mut utf8 = false; let mut date: Option = None; let mut time: Option = None; + let mut seen_keywords = std::collections::HashSet::new(); let mut i = 0usize; while i + 5 <= b.len() { if b[i] != 0x1c { @@ -43,7 +44,7 @@ pub fn parse_iptc(b: &[u8]) -> Metadata { (2, 5) => m.title = Some(decode(data, utf8)).filter(|s| !s.is_empty()), (2, 25) => { let k = decode(data, utf8); - if !k.is_empty() && !m.keywords.contains(&k) { + if !k.is_empty() && seen_keywords.insert(k.clone()) { m.keywords.push(k); } } @@ -79,6 +80,18 @@ pub(crate) mod tests { out.extend_from_slice(data); } + #[test] + fn distinct_keywords_are_kept_once_each_without_rescanning() { + let mut b = Vec::new(); + for i in 0..50_000u32 { + ds(&mut b, 2, 25, format!("k{i}").as_bytes()); + ds(&mut b, 2, 25, b"same"); + } + let m = parse_iptc(&b); + assert_eq!(m.keywords.len(), 50_001); + assert_eq!(m.keywords.iter().filter(|k| *k == "same").count(), 1); + } + pub(crate) fn sample_iim() -> Vec { let mut v = Vec::new(); ds(&mut v, 1, 90, b"\x1b%G"); diff --git a/crates/meta/src/xmp.rs b/crates/meta/src/xmp.rs index 958abed653..b7ee773763 100644 --- a/crates/meta/src/xmp.rs +++ b/crates/meta/src/xmp.rs @@ -240,14 +240,21 @@ fn xml_safe(s: &str) -> String { s.chars().filter(|&c| is_xml_char(c)).collect() } -/// Unescape attribute values (predefined + numeric references; unknown references kept verbatim). +/// Index of the `;` that ends a reference starting at `rest` (its `&`). The scan stops at the first +/// byte that cannot appear in a name or a numeric reference, so zero-padded references such as +/// `a` are found and each run of name bytes is read once, not once per `&`. +fn entity_end(rest: &str) -> Option { + let n = rest.bytes().skip(1).take_while(|b| b.is_ascii_alphanumeric() || *b == b'#').count(); + (rest.as_bytes().get(n + 1) == Some(&b';')).then_some(n + 1) +} + pub(crate) fn unescape_attr(s: &str) -> String { let mut out = String::with_capacity(s.len()); let mut rest = s; while let Some(i) = rest.find('&') { out.push_str(&rest[..i]); rest = &rest[i..]; - match rest.find(';').and_then(|j| entity(&rest[1..j]).map(|c| (c, j))) { + match entity_end(rest).and_then(|j| entity(&rest[1..j]).map(|c| (c, j))) { Some((c, j)) => { out.push(c); rest = &rest[j + 1..]; @@ -353,8 +360,13 @@ fn is_rdf_meta_attr(k: &str) -> bool { fn collect_description(d: &Node, prefix: &str, props: &mut BTreeMap>, budget: &mut usize) { for (k, v) in &d.attrs { - if !is_rdf_meta_attr(k) && take_key_bytes(&format!("{prefix}{k}"), budget) { - props.entry(format!("{prefix}{k}")).or_default().push(v.clone()); + // the budget is checked before the path is built, not after + if is_rdf_meta_attr(k) || *budget < prefix.len().saturating_add(k.len()) { + continue; + } + let key = format!("{prefix}{k}"); + if take_key_bytes(&key, budget) { + props.entry(key).or_default().push(v.clone()); } } for c in &d.children { @@ -374,6 +386,11 @@ fn take_key_bytes(key: &str, budget: &mut usize) -> bool { } fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap>, budget: &mut usize) { + // a path that can't fit the budget isn't built (a long ancestor path shared by many children + // would otherwise be copied for each of them after the budget is spent) + if *budget < prefix.len().saturating_add(p.name.len()) { + return; + } let key = format!("{prefix}{}", p.name); if let Some(arr) = p.children.iter().find(|c| matches!(c.name.as_str(), "rdf:Seq" | "rdf:Bag" | "rdf:Alt")) { let mut items: Vec<(bool, String)> = arr @@ -393,6 +410,12 @@ fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap \u{10FFFF} &unknownreference;"); +} + +/// Children that add no key (empty structs) still had their whole ancestor path copied, each, +/// after the budget was spent: a 250 KB path under 100 000 such children was 25 GB of copying. +#[test] +fn paths_are_not_built_past_the_key_budget() { + let level = "n".repeat(60_000); + let mut doc = String::from( + "", + ); + for _ in 0..4 { + doc.push_str(&format!("")); + } + for _ in 0..100_000 { + doc.push_str(""); + } + for _ in 0..4 { + doc.push_str(&format!("")); + } + doc.push_str(""); + let t = std::time::Instant::now(); + let _ = parse_xmp(&doc); + assert!(t.elapsed().as_secs() < 10, "took {:?}", t.elapsed()); +} diff --git a/crates/pipeline/src/crystal.rs b/crates/pipeline/src/crystal.rs new file mode 100644 index 0000000000..325329d3ff --- /dev/null +++ b/crates/pipeline/src/crystal.rs @@ -0,0 +1,1082 @@ +//! Crystal-layer film grain, the grain of process V7 and later ([`crate::finish::GrainModel`]). +//! +//! After the model of Aurélien Pierre, *Stochastic photographic grain synthesis from +//! crystallographic structure simulation* (2023), implemented from the article's description of +//! the method; no code was taken from it or from any implementation. `docs/grain.md` has the +//! method, the calibration and the measurements. +//! +//! - **Emulsion.** A stack of layers. Each layer has one crystal shape (a regular polygon of 3–8 +//! vertices, a random rotation, a log-normal width) and is a Boolean model: Poisson seeds grown +//! into crystals, at the density that leaves half the layer covered ([`FILLING`]). +//! - **Capture.** A point's grain is the number of layers covering it, less its mean: many +//! independent layers of different crystal sizes give dense, soft, cloudy grain. +//! - **Print.** The light a point captures is proportional to the light falling on it, and the +//! print shows less grain towards paper white: the grain is `Y·(1 − Y)` in linear light, so +//! it fades out at black and at white. It is added in the display-encoded domain (first order), +//! where it is symmetric: it neither darkens shadows nor greys blown highlights. +//! +//! **Resolution independence.** The emulsion is drawn once per setting on two periodic tiles +//! (tori) in frame coordinates, at twice the resolution of a 6000 px export ([`PITCH`]). Each +//! output pixel takes the exact mean of the emulsion under its footprint from the tiles' summed +//! area tables (a rotated frame's pixel: of an axis-aligned square of its size), so a preview +//! shows exactly the export's grain box-downscaled to its size, and an +//! export larger than 6000 px still has crystals rather than enlarged pixels. The layers are +//! split between two tori of different sizes ([`TORI`]); their pattern only repeats as a whole +//! after tens of thousands of pixels. +//! +//! **Cost.** Drawing the tiles takes a few milliseconds and is cached per setting +//! ([`CrystalGrain::new`]); a pixel then costs two box sums (16 table reads), on the CPU and in the +//! GPU kernel (`finish.wgsl`, which reads the same tables). + +use std::f64::consts::TAU; +use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError}; + +use lightcraft_color::transfer::srgb_to_linear; +use lightcraft_develop::Grain; +use lightcraft_raster::par_rows; + +/// Long edge (output pixels) at which grain sizes and strengths are specified: a 24 MP export. +pub const REF_LONG: f64 = 6000.0; +/// Size of a tile pixel in reference pixels: tiles are drawn at twice the reference resolution. +pub const PITCH: f64 = 0.5; +/// Tile pixels per long edge of the frame. +pub const TILE_PER_LONG: f64 = REF_LONG / PITCH; +/// Sides of the two tori (tile pixels: 640 and 567 reference pixels). Layers alternate between +/// them; the sizes share no small factor, so the sum repeats only after 362,880 reference pixels. +pub const TORI: [usize; 2] = [1280, 1134]; +/// Fraction of each layer covered by its crystals. +pub const FILLING: f64 = 0.5; +/// Rows per band when drawing a tile (each band is drawn in parallel). +const BAND: usize = 64; +/// Encoded luminance at which the strength is specified (mid grey, 128 of 255). +const MID_GREY: f32 = 128.0 / 255.0; +/// A footprint this large (tile pixels: a render 24 px long or less) gets no grain. +const MAX_FOOTPRINT: f32 = 500.0; +/// Settings whose tiles are kept (a preview and an export, a few thumbnails). +const CACHE: usize = 4; + +/// The look of a grain setting: what the tiles are drawn from. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CrystalLook { + /// Median crystal width (circumscribed diameter, reference pixels). + pub width: f64, + /// Log standard deviation of the layers' crystal widths. + pub spread: f64, + /// Number of layers. + pub layers: usize, +} + +/// Piecewise-linear interpolation through `(x, y)` knots sorted by `x`, constant outside them. +fn interp(knots: &[(f64, f64)], x: f64) -> f64 { + let (Some(first), Some(last)) = (knots.first(), knots.last()) else { return 0.0 }; + if x <= first.0 { + return first.1; + } + for w in knots.windows(2) { + if let [(x0, y0), (x1, y1)] = *w + && x <= x1 + { + return y0 + (y1 - y0) * (x - x0) / (x1 - x0).max(1e-9); + } + } + last.1 +} + +/// Median crystal width at Roughness 50 by Size (reference pixels), fitted so the grain's width +/// matches Lightroom Classic's (`fit_widths`, `docs/grain.md`). Size 0 is as fine as the model +/// gets: crystals narrower than a pixel, uncorrelated pixels. +const WIDTH_BY_SIZE: [(f64, f64); 6] = [(0.0, 0.55), (10.0, 1.39), (25.0, 2.95), (50.0, 5.17), (75.0, 8.78), (100.0, 12.38)]; +/// Width factor by Roughness. +const WIDTH_BY_ROUGHNESS: [(f64, f64); 3] = [(0.0, 0.734), (50.0, 1.0), (100.0, 1.422)]; +/// Layers by Size: coarser grain averages more layers, so it stays a soft clump texture. +const LAYERS_BY_SIZE: [(f64, f64); 4] = [(0.0, 16.0), (25.0, 31.0), (50.0, 54.0), (100.0, 70.0)]; + +/// Log-width spread every look has on top of Roughness's. The look the tables were chosen from (a +/// prototype on whole-pixel crystals, `docs/grain.md`) rounded crystal widths to whole pixels, +/// which spreads their sizes by about this much; with it, the anti-aliased crystals here have the +/// prototype's texture at every scale, not just its width. +const SPREAD_FLOOR: f64 = 0.45; + +/// A slider value as a number in `0..=100`; `fallback` for NaN. +fn slider(v: f64, fallback: f64) -> f64 { + if v.is_nan() { fallback } else { v.clamp(0.0, 100.0) } +} + +impl CrystalLook { + pub fn new(size: f64, roughness: f64) -> CrystalLook { + let (s, r) = (slider(size, 25.0), slider(roughness, 50.0)); + CrystalLook { + width: interp(&WIDTH_BY_SIZE, s) * interp(&WIDTH_BY_ROUGHNESS, r), + spread: (0.1 + 0.6 * r / 100.0).hypot(SPREAD_FLOOR), + layers: interp(&LAYERS_BY_SIZE, s).round().clamp(2.0, 120.0) as usize, + } + } +} + +/// Grain strength (8-bit levels at mid grey on a 6000 px export) for Amount, Size and Roughness, +/// measured on Lightroom Classic exports (the fit of open PR #1060's `docs/grain.md`). +pub fn strength_levels(amount: f64, size: f64, roughness: f64) -> f64 { + let (s, d) = (slider(size, 25.0), slider(roughness, 50.0) / 100.0 - 0.5); + slider(amount, 0.0) / 100.0 * (2.447 + 1.386 * (-s / 19.88).exp()).exp() * (1.0 - 0.084 * d + 1.6384 * d * d) +} + +// ---- hashing + +#[inline] +fn mix(mut x: u32) -> u32 { + x ^= x >> 16; + x = x.wrapping_mul(0x7feb_352d); + x ^= x >> 15; + x = x.wrapping_mul(0x846c_a68b); + x ^ (x >> 16) +} + +#[inline] +fn hash(a: u32, b: u32, c: u32, d: u32) -> u32 { + mix(mix(mix(mix(a ^ 0x9e37_79b9) ^ b) ^ c.wrapping_mul(0x85eb_ca6b)) ^ d.wrapping_mul(0xc2b2_ae35)) +} + +/// A hash as a number in (0, 1]. +#[inline] +fn unit(h: u32) -> f64 { + (h as f64 + 0.5) / 4_294_967_296.0 +} + +/// The standard normal quantile of `p` in (0, 1) (Acklam's rational approximation, ~1e-9). +fn normal_quantile(p: f64) -> f64 { + const A: [f64; 6] = + [-39.696_830_286_653_76, 220.946_098_424_520_5, -275.928_510_446_968_7, 138.357_751_867_269, -30.664_798_066_147_16, 2.506_628_277_459_239]; + const B: [f64; 5] = [-54.476_098_798_224_06, 161.585_836_858_040_9, -155.698_979_859_886_6, 66.801_311_887_719_72, -13.280_681_552_885_72]; + const C: [f64; 6] = [ + -0.007_784_894_002_430_293, + -0.322_396_458_041_136_5, + -2.400_758_277_161_838, + -2.549_732_539_343_734, + 4.374_664_141_464_968, + 2.938_163_982_698_783, + ]; + const D: [f64; 4] = [0.007_784_695_709_041_462, 0.322_467_129_070_039_8, 2.445_134_137_142_996, 3.754_408_661_907_416]; + let p = p.clamp(1e-12, 1.0 - 1e-12); + let tail = + |q: f64| (((((C[0] * q + C[1]) * q + C[2]) * q + C[3]) * q + C[4]) * q + C[5]) / ((((D[0] * q + D[1]) * q + D[2]) * q + D[3]) * q + 1.0); + if p < 0.024_25 { + tail((-2.0 * p.ln()).sqrt()) + } else if p > 1.0 - 0.024_25 { + -tail((-2.0 * (1.0 - p).ln()).sqrt()) + } else { + let q = p - 0.5; + let r = q * q; + (((((A[0] * r + A[1]) * r + A[2]) * r + A[3]) * r + A[4]) * r + A[5]) * q + / (((((B[0] * r + B[1]) * r + B[2]) * r + B[3]) * r + B[4]) * r + 1.0) + } +} + +/// The emulsion's layers. Their crystal widths are the `layers` quantiles of the log-normal +/// width distribution, dealt to the layers in an order the seed shuffles: every seed has the same +/// mix of sizes (so the same grain width and strength), in a different arrangement. +fn emulsion(seed: u32, look: &CrystalLook) -> Vec { + let n = look.layers.max(1); + let mut order: Vec<(u32, usize)> = (0..n).map(|l| (hash(seed, l as u32, 0x5047, 0), l)).collect(); + order.sort_unstable(); + let mut rank = vec![0usize; n]; + for (r, &(_, l)) in order.iter().enumerate() { + if let Some(slot) = rank.get_mut(l) { + *slot = r; + } + } + (0..n).map(|l| Layer::new(seed, l as u32, look, normal_quantile((rank.get(l).copied().unwrap_or(0) as f64 + 0.5) / n as f64))).collect() +} + +fn normal(h1: u32, h2: u32) -> f64 { + (-2.0 * unit(h1).ln()).sqrt() * (TAU * unit(h2)).cos() +} + +/// The cumulative distribution of a Poisson count of mean `mu`, up to where it reaches 1 (at +/// most 512 entries; `mu` stays below ~150 here). +fn poisson_cdf(mu: f64) -> Vec { + let mut cdf = Vec::new(); + let mut p = (-mu).exp(); + let mut cum = p; + for k in 1..512u32 { + cdf.push(cum); + if cum >= 1.0 - 1e-12 { + break; + } + p *= mu / k as f64; + cum += p; + } + cdf +} + +/// A Poisson count drawn from its `cdf` by hash `h`. +#[inline] +fn poisson(cdf: &[f64], h: u32) -> usize { + let u = unit(h); + cdf.partition_point(|&c| c < u) +} + +// ---- one layer + +/// A stream of hashes: a Weyl sequence through [`mix`]. +struct Stream(u32); + +impl Stream { + #[inline] + fn next(&mut self) -> u32 { + self.0 = self.0.wrapping_add(0x9e37_79b9); + mix(self.0) + } +} + +/// Sub-pixel positions a crystal centre is rounded to, per axis, when drawn from its [`Stamp`]. +const PHASES: usize = 16; +/// Crystals up to this circumradius (tile pixels) are drawn from a stamp. +const STAMP_R: f64 = 16.0; + +/// A layer's crystal rasterised at every sub-pixel phase of its centre: for a centre at +/// `(X + qx/PHASES, Y + qy/PHASES)` (`X`, `Y` integers) it covers rows `Y + rows[qy].0 ..= Y + +/// rows[qy].1`, and in row `Y + rows[qy].0 + k` the pixels `X + o.0 ..= X + o.1`, with +/// `o = spans[(qy·PHASES + qx)·height + k]`. +/// +/// The same rows as bit masks, for drawing a crystal without a branch per row: phase +/// `p = qy·PHASES + qx` spans pixels `X + extent[p].0 ..= X + extent[p].1`, and its row `k` is +/// `masks[p·height + k]` shifted to `X + extent[p].0` (rows past the phase's own are empty). +/// `masks` is empty when a phase is wider than 64 pixels. +#[derive(Clone, Debug)] +struct Stamp { + rows: [(i32, i32); PHASES], + height: usize, + spans: Vec<(i32, i32)>, + extent: Vec<(i32, i32)>, + masks: Vec, +} + +/// Where [`Layer::draw`] draws: rows `y0..y0 + rows` of a torus of side `t`, `w` words per row, +/// after `margin` scratch rows. +#[derive(Clone, Copy)] +struct Band { + t: usize, + y0: usize, + rows: usize, + w: usize, + margin: usize, +} + +/// One emulsion layer: its crystal (a regular polygon) and seed density, in tile pixels. +#[derive(Clone, Debug)] +struct Layer { + /// The crystal as half-planes, relative to its centre: `x ≥ a + s·y` for each `(a, s)` of + /// `left` (`nl` used), `x ≤ a + s·y` for `right` (`nr` used), `y0 ≤ y ≤ y1`. + left: [(f64, f64); 8], + right: [(f64, f64); 8], + nl: usize, + nr: usize, + y0: f64, + y1: f64, + /// Circumradius. + r: f64, + /// Seeds per tile pixel. + lambda: f64, + seed: u32, + index: u32, + stamp: Option, +} + +/// Crystals narrower than this (tile pixels) cover at most two neighbouring pixel centres: their +/// layer is drawn as independent pixels. +const FINE: f64 = 1.5; + +impl Layer { + /// Layer `index` of the emulsion of `seed`, its crystal width `z` log standard deviations + /// from the median. + fn new(seed: u32, index: u32, look: &CrystalLook, z: f64) -> Layer { + let h = |k: u32| hash(seed, index, k, 0x51ed); + let n = (4.5 + normal(h(1), h(2))).round().clamp(3.0, 8.0) as usize; + let rot = TAU * unit(h(3)); + let width = look.width.max(0.05) * (look.spread * z.clamp(-2.5, 2.5)).exp(); + let r = width / 2.0 / PITCH; + let vert = |k: usize| { + let a = rot + TAU * k as f64 / n as f64; + (r * a.cos(), r * a.sin()) + }; + let mut layer = Layer { + left: [(0.0, 0.0); 8], + right: [(0.0, 0.0); 8], + nl: 0, + nr: 0, + y0: f64::INFINITY, + y1: f64::NEG_INFINITY, + r, + lambda: -(1.0 - FILLING).ln() / (0.5 * n as f64 * r * r * (TAU / n as f64).sin()).max(1e-9), + seed, + index, + stamp: None, + }; + for k in 0..n { + let ((x0, y0), (x1, y1)) = (vert(k), vert(k + 1)); + layer.y0 = layer.y0.min(y0); + layer.y1 = layer.y1.max(y0); + let dy = y1 - y0; + if dy.abs() < 1e-12 { + continue; + } + // counter-clockwise: the inside is left of each edge + let sl = (x1 - x0) / dy; + let line = (x0 - sl * y0, sl); + if dy > 0.0 { + if let Some(slot) = layer.right.get_mut(layer.nr) { + *slot = line; + layer.nr += 1; + } + } else if let Some(slot) = layer.left.get_mut(layer.nl) { + *slot = line; + layer.nl += 1; + } + } + if r <= STAMP_R && 2.0 * r >= FINE { + layer.stamp = Some(layer.stamp()); + } + layer + } + + fn stamp(&self) -> Stamp { + let q = PHASES as f64; + let mut rows = [(0, -1); PHASES]; + for (qy, r) in rows.iter_mut().enumerate() { + let g = qy as f64 / q; + *r = ((g + self.y0 - 0.5).ceil() as i32, (g + self.y1 - 0.5).floor() as i32); + } + let height = rows.iter().map(|(a, b)| (b - a + 1).max(0) as usize).max().unwrap_or(0); + let mut spans = vec![(0, -1); PHASES * PHASES * height]; + for (qy, &(a, b)) in rows.iter().enumerate() { + for k in 0..(b - a + 1).max(0) { + let (xl, xr) = self.span((a + k) as f64 + 0.5 - qy as f64 / q); + for qx in 0..PHASES { + let f = qx as f64 / q; + if let Some(o) = spans.get_mut((qy * PHASES + qx) * height + k as usize) { + *o = ((f + xl - 0.5).ceil() as i32, (f + xr - 0.5).floor() as i32); + } + } + } + } + let mut extent = vec![(0, -1); PHASES * PHASES]; + let mut masks = vec![0u64; PHASES * PHASES * height]; + let mut fits = true; + for (p, e) in extent.iter_mut().enumerate() { + let Some(rows) = spans.get(p * height..(p + 1) * height) else { continue }; + let used = || rows.iter().filter(|(o0, o1)| o0 <= o1); + let (Some(lo), Some(hi)) = (used().map(|o| o.0).min(), used().map(|o| o.1).max()) else { continue }; + *e = (lo, hi); + fits &= hi - lo < 64; + for (m, &(o0, o1)) in masks.iter_mut().skip(p * height).zip(rows) { + if o0 <= o1 && o1 - lo < 64 { + *m = (!0u64 >> (63 - (o1 - o0))) << (o0 - lo); + } + } + } + if !fits { + masks.clear(); + } + Stamp { rows, height, spans, extent, masks } + } + + /// The crystal's horizontal extent at height `y` above its centre (convex: one interval). + #[inline] + fn span(&self, y: f64) -> (f64, f64) { + let lo = self.left.iter().take(self.nl).fold(f64::NEG_INFINITY, |m, &(a, s)| m.max(a + s * y)); + let hi = self.right.iter().take(self.nr).fold(f64::INFINITY, |m, &(a, s)| m.min(a + s * y)); + (lo, hi) + } + + /// Sets the bits of the pixels the layer covers in rows `y0..` of a torus of side `t`: + /// `cover` holds whole rows of `w` words (bit `i % 64` of word `i / 64` is pixel `i`), the + /// band's rows between `margin` rows above and below it (scratch: what lands there is not part + /// of the band; `margin` is at least the stamp's height). + fn draw(&self, t: usize, y0: usize, w: usize, margin: usize, cover: &mut [u64]) { + let rows = (cover.len() / w.max(1)).saturating_sub(2 * margin); + if 2.0 * self.r < FINE { + // each pixel covered with probability FILLING (one half: one random bit) + for (j, row) in cover.chunks_mut(w.max(1)).skip(margin).take(rows).enumerate() { + let mut bits = Stream(hash(self.seed, self.index, (y0 + j) as u32, 0xb175)); + for v in row.iter_mut() { + *v = bits.next() as u64 | (bits.next() as u64) << 32; + } + if let (Some(last), r @ 1..=63) = (row.last_mut(), t % 64) { + *last &= (1u64 << r) - 1; + } + } + return; + } + let tf = t as f64; + let m = (tf / (4.0 * self.r).max(16.0)).floor().clamp(1.0, tf) as i64; + let c = tf / m as f64; + let cdf = poisson_cdf(self.lambda * c * c); + let (lo, hi) = (y0 as f64 - self.r - 1.0, (y0 + rows) as f64 + self.r + 1.0); + for cy in (lo / c).floor() as i64..=(hi / c).floor() as i64 { + let wy = cy.rem_euclid(m) as u32; + for cx in 0..m { + let mut h = Stream(hash(self.seed ^ (self.index << 20), cx as u32, wy, 0xce11)); + for _ in 0..poisson(&cdf, h.next()) { + let (u, v) = (unit(h.next()), unit(h.next())); + self.splat((cx as f64 + u) * c, (cy as f64 + v) * c, Band { t, y0, rows, w, margin }, cover); + } + } + } + } + + /// Marks the pixels whose centres the crystal at (`px`, `py`) covers (see [`Self::draw`]). + #[inline] + fn splat(&self, px: f64, py: f64, band: Band, cover: &mut [u64]) { + let Band { t, y0, rows, w, margin } = band; + if let Some(st) = &self.stamp { + let (bx, by) = (px.floor(), py.floor()); + let (qx, qy) = ((((px - bx) * PHASES as f64) as usize).min(PHASES - 1), (((py - by) * PHASES as f64) as usize).min(PHASES - 1)); + let (bx, by) = (bx as i64, by as i64); + let Some(&(a, b)) = st.rows.get(qy) else { return }; + let (lo, hi) = ((by + a as i64).max(y0 as i64), (by + b as i64).min((y0 + rows) as i64 - 1)); + if hi < lo { + return; + } + // within the torus across: the whole stamp, a fixed number of rows of masks (those + // above or below the band land in the margins) + let p = qy * PHASES + qx; + if let (Some(&(e0, e1)), Some(masks)) = (st.extent.get(p), st.masks.get(p * st.height..(p + 1) * st.height)) { + let (xs, top) = (bx + e0 as i64, by + a as i64 - y0 as i64 + margin as i64); + if xs >= 0 && bx + (e1 as i64) < t as i64 && top >= 0 { + let (word, shift) = ((xs >> 6) as usize, (xs & 63) as u32); + // a bit past the row's last word would be a pixel ≥ t: the high word is then 0 + let start = top as usize * w + word; + for (k, &m) in masks.iter().enumerate() { + let v = (m as u128) << shift; + let i = start + k * w; + if let Some(c) = cover.get_mut(i) { + *c |= v as u64; + } + if let Some(c) = cover.get_mut(i + 1) { + *c |= (v >> 64) as u64; + } + } + return; + } + } + // rows `lo..=hi` of the band, spans `k0..` of the stamp's rows (`hi ≤ by + b`: within its height) + let (k0, n) = ((lo - by - a as i64) as usize, (hi - lo + 1) as usize); + let base = (qy * PHASES + qx) * st.height + k0; + let (r0, r1) = (lo as usize - y0 + margin, hi as usize + 1 - y0 + margin); + let (Some(spans), Some(band)) = (st.spans.get(base..base + n), cover.get_mut(r0 * w..r1 * w)) else { return }; + for (row, &(o0, o1)) in band.chunks_exact_mut(w.max(1)).zip(spans) { + if o0 <= o1 { + set_wrapped(row, t, bx + o0 as i64, bx + o1 as i64); + } + } + return; + } + let first = (py + self.y0 - 0.5).ceil().max(y0 as f64); + let last = (py + self.y1 - 0.5).floor().min((y0 + rows) as f64 - 1.0); + if last < first { + return; + } + for j in first as usize..=last as usize { + let (xl, xr) = self.span(j as f64 + 0.5 - py); + let (i0, i1) = ((px + xl - 0.5).ceil() as i64, (px + xr - 0.5).floor() as i64); + if i1 < i0 { + continue; + } + let Some(row) = cover.get_mut((j - y0 + margin) * w..(j - y0 + margin + 1) * w) else { continue }; + set_wrapped(row, t, i0, i1); + } + } +} + +/// Sets bits `a..=b` (`a ≤ b`) of a row of words. +#[inline] +fn set_bits(row: &mut [u64], a: usize, b: usize) { + let (wa, wb) = (a >> 6, b >> 6); + let (lo, hi) = (!0u64 << (a & 63), !0u64 >> (63 - (b & 63))); + if wa == wb { + if let Some(v) = row.get_mut(wa) { + *v |= lo & hi; + } + return; + } + if let Some(v) = row.get_mut(wa) { + *v |= lo; + } + for v in row.iter_mut().take(wb).skip(wa + 1) { + *v = !0; + } + if let Some(v) = row.get_mut(wb) { + *v |= hi; + } +} + +/// Sets pixels `i0..=i1` of a periodic row of `t` pixels (`i0 ≤ i1`, within one period of +/// `0..t`: the crystal centres are in `0..t`). +#[inline] +fn set_wrapped(row: &mut [u64], t: usize, i0: i64, i1: i64) { + let ti = t as i64; + if i0 >= 0 && i1 < ti { + set_bits(row, i0 as usize, i1 as usize); + return; + } + if t == 0 { + return; + } + if i1 - i0 + 1 >= ti { + set_bits(row, 0, t - 1); + return; + } + let (a, b) = if i0 < 0 { + (i0 + ti, i1 + ti) + } else if i0 >= ti { + (i0 - ti, i1 - ti) + } else { + (i0, i1) + }; + let (a, b) = (a.clamp(0, ti - 1) as usize, b.max(0) as usize); + if b < t { + set_bits(row, a, b); + } else { + set_bits(row, a, t - 1); + set_bits(row, 0, (b - t).min(t - 1)); + } +} + +/// Bit planes of the layer counts (enough for 127 layers per torus). +const PLANES: usize = 7; + +/// Adds one layer's `cover` bits to the bit-sliced counters `planes` (`PLANES × cover.len()`). +#[inline] +fn add_layer(planes: &mut [u64], cover: &[u64]) { + let n = cover.len(); + for (i, &c) in cover.iter().enumerate() { + let mut carry = c; + for p in 0..PLANES { + if carry == 0 { + break; + } + let Some(slot) = planes.get_mut(p * n + i) else { break }; + let s = *slot; + *slot = s ^ carry; + carry &= s; + } + } +} + +// ---- tiles + +/// The emulsion drawn on the two tori: each as a summed-area table of its grain (layer count less +/// its mean), scaled so that the sum of both, averaged over a reference pixel, has unit variance. +pub struct CrystalTile { + pub look: CrystalLook, + /// `(side + 1)²` entries each: `sat[t][y·(side + 1) + x]` = sum over `[0, x) × [0, y)`. + pub sats: [Vec; 2], +} + +impl std::fmt::Debug for CrystalTile { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CrystalTile").field("look", &self.look).finish_non_exhaustive() + } +} + +/// Layer counts of torus `which` (side `t`): `t × t`, row-major. +fn draw_torus(which: usize, t: usize, seed: u32, look: &CrystalLook) -> Vec { + let layers: Vec = emulsion(seed, look).into_iter().filter(|l| l.index as usize % 2 == which).collect(); + let w = t.div_ceil(64); + // scratch rows above and below a band, for the stamps' rows outside it (`Layer::splat`) + let margin = layers.iter().filter_map(|l| l.stamp.as_ref().map(|s| s.height)).max().unwrap_or(0); + let mut count = vec![0u8; t * t]; + par_rows(&mut count, t * BAND, |band, out| { + let rows = out.len() / t.max(1); + let n = rows * w; + let (mut cover, mut planes) = (vec![0u64; n + 2 * margin * w], vec![0u64; PLANES * n]); + for layer in &layers { + cover.fill(0); + layer.draw(t, band * BAND, w, margin, &mut cover); + add_layer(&mut planes, cover.get(margin * w..margin * w + n).unwrap_or_default()); + } + for (j, row) in out.chunks_mut(t.max(1)).enumerate() { + for (i, o) in row.iter_mut().enumerate() { + let (word, bit) = (j * w + i / 64, i % 64); + *o = (0..PLANES).fold(0u8, |c, p| c | ((planes.get(p * n + word).map_or(0, |v| (v >> bit) & 1) as u8) << p)); + } + } + }); + count +} + +/// Integer summed-area table of `count` (`t × t`): `(t + 1)²` entries. +fn summed_area(count: &[u8], t: usize) -> Vec { + let s = t + 1; + let mut sat = vec![0u32; s * s]; + // row prefix sums in parallel, then each row adds the one above + par_rows(&mut sat, s, |y, row| { + let Some(src) = y.checked_sub(1).and_then(|y| count.get(y * t..(y + 1) * t)) else { return }; + let mut acc = 0u32; + for (o, &c) in row.iter_mut().skip(1).zip(src) { + acc += c as u32; + *o = acc; + } + }); + for y in 1..s { + let (above, below) = sat.split_at_mut(y * s); + let (Some(prev), Some(row)) = (above.get((y - 1) * s..), below.get_mut(..s)) else { continue }; + for (o, &p) in row.iter_mut().zip(prev) { + *o = o.wrapping_add(p); + } + } + sat +} + +/// Sum over the reference pixels (2 × 2 tile pixels) of torus `count` (`t × t`, `t` even) of +/// their squared deviation from `mean` (per tile pixel), and the number of reference pixels. +fn reference_square_sum(count: &[u8], t: usize, mean: f64) -> (f64, usize) { + let h = t / 2; + let mut rows = vec![0.0f64; h]; + par_rows(&mut rows, 1, |y, out| { + let (Some(a), Some(b)) = (count.get(2 * y * t..(2 * y + 1) * t), count.get((2 * y + 1) * t..(2 * y + 2) * t)) else { return }; + let mut s = 0.0; + for (&[a0, a1], &[b0, b1]) in a.as_chunks::<2>().0.iter().zip(b.as_chunks::<2>().0) { + let q = (a0 as u32 + a1 as u32 + b0 as u32 + b1 as u32) as f64 / 4.0 - mean; + s += q * q; + } + if let Some(o) = out.first_mut() { + *o = s; + } + }); + (rows.iter().sum(), h * h) +} + +impl CrystalTile { + /// Draws the emulsion of `look` with `seed`, or `None` if it has no grain (no variance). + pub fn new(look: CrystalLook, seed: u32) -> Option { + let [t0, t1] = TORI; + let (c0, c1) = lightcraft_raster::par_join(|| draw_torus(0, t0, seed, &look), || draw_torus(1, t1, seed, &look)); + let mut var = 0.0; + let mut tori = Vec::with_capacity(2); + for (count, t) in [(c0, t0), (c1, t1)] { + let mean = count.iter().map(|&c| c as u64).sum::() as f64 / (t * t).max(1) as f64; + let (sq, n) = reference_square_sum(&count, t, mean); + var += sq / n.max(1) as f64; + tori.push((summed_area(&count, t), t, mean)); + } + if !(var > 1e-12 && var.is_finite()) { + return None; + } + let k = 1.0 / var.sqrt(); + let mut sats = tori.into_iter().map(|(sat, t, mean)| { + let s = t + 1; + let mut out = vec![0.0f32; s * s]; + par_rows(&mut out, s, |y, row| { + for (x, (o, &v)) in row.iter_mut().zip(sat.get(y * s..).unwrap_or_default()).enumerate() { + *o = ((v as f64 - mean * (x * y) as f64) * k) as f32; + } + }); + out + }); + Some(CrystalTile { look, sats: [sats.next()?, sats.next()?] }) + } + + /// Sum of torus `which`'s grain over the box `[x0, x0 + w] × [y0, y0 + w]` (tile pixels, + /// `0 ≤ w < side`), the table bilinearly interpolated: the exact integral of the pixels. + #[inline] + fn box_sum(&self, which: usize, x0: f32, y0: f32, w: f32) -> f32 { + let (Some(sat), Some(&t)) = (self.sats.get(which), TORI.get(which)) else { return 0.0 }; + let tf = t as f32; + let (x0, y0) = (x0 - (x0 / tf).floor() * tf, y0 - (y0 / tf).floor() * tf); + let at = |x: f32, y: f32| integral(sat, t, x, y); + at(x0 + w, y0 + w) - at(x0, y0 + w) - at(x0 + w, y0) + at(x0, y0) + } + + /// Mean grain over the square of side `w` centred on (`x`, `y`) (tile pixels): unit variance + /// at `w` = 2 (a 6000 px render). + #[inline] + pub fn field(&self, x: f32, y: f32, w: f32) -> f32 { + let (x0, y0) = (x - 0.5 * w, y - 0.5 * w); + (self.box_sum(0, x0, y0, w) + self.box_sum(1, x0, y0, w)) / (w * w) + } +} + +/// The table `sat` (side `t + 1`) bilinearly interpolated at (`x`, `y`) in `0..=t`. +#[inline] +fn bilinear(sat: &[f32], t: usize, x: f32, y: f32) -> f32 { + let s = t + 1; + let (i, j) = ((x.max(0.0) as usize).min(t - 1), (y.max(0.0) as usize).min(t - 1)); + let (fx, fy) = (x - i as f32, y - j as f32); + let g = |i: usize, j: usize| sat.get(j * s + i).copied().unwrap_or(0.0); + let a = g(i, j) + (g(i + 1, j) - g(i, j)) * fx; + let b = g(i, j + 1) + (g(i + 1, j + 1) - g(i, j + 1)) * fx; + a + (b - a) * fy +} + +/// The periodic grain's integral over `[0, x) × [0, y)` for `x`, `y` in `0..2t`. +#[inline] +fn integral(sat: &[f32], t: usize, x: f32, y: f32) -> f32 { + let tf = t as f32; + let (wx, wy) = (x >= tf, y >= tf); + let (rx, ry) = (if wx { x - tf } else { x }, if wy { y - tf } else { y }); + let mut v = bilinear(sat, t, rx, ry); + if wx { + v += bilinear(sat, t, tf, ry); + } + if wy { + v += bilinear(sat, t, rx, tf); + } + if wx && wy { + v += bilinear(sat, t, tf, tf); + } + v +} + +/// The integral of torus `sat` (side `t`) over `[0, i) × [0, across)` (`along_x`) or +/// `[0, across) × [0, i)`, for `i` in `0..=t`: the table cut along a line, with the periodic part +/// of `across` folded in (`across` in `0..2t`). +fn line(sat: &[f32], t: usize, along_x: bool, across: f32, out: &mut Vec) { + let (tf, n) = (t as f32, t + 1); + let wrap = across >= tf; + let a = (if wrap { across - tf } else { across }).clamp(0.0, tf); + let j = (a as usize).min(t.saturating_sub(1)); + let f = (a - j as f32) as f64; + out.clear(); + out.resize(n, 0.0); + // entry `i` of table line `k` (a row when cutting along x, a column when along y) + let at = |k: usize, i: usize| if along_x { sat.get(k * n + i) } else { sat.get(i * n + k) }.copied().unwrap_or(0.0) as f64; + for (i, o) in out.iter_mut().enumerate() { + let (p, q) = (at(j, i), at(j + 1, i)); + *o = p + (q - p) * f + if wrap { at(t, i) } else { 0.0 }; + } +} + +/// [`line`] interpolated at `x ≥ 0` (any number of periods along). +#[inline] +fn along(line: &[f64], t: usize, inv_t: f64, x: f64) -> f64 { + let tf = t as f64; + let q = (x * inv_t).floor().max(0.0); + let r = (x - q * tf).clamp(0.0, tf); + let i = (r as usize).min(t.saturating_sub(1)); + let f = r - i as f64; + let (Some(&a), Some(&b), Some(&end)) = (line.get(i), line.get(i + 1), line.get(t)) else { return 0.0 }; + a + (b - a) * f + q * end +} + +impl CrystalTile { + /// The grain of a line of `out.len()` output pixels side by side, each a square of side `w` + /// (tile pixels), the first centred on (`x`, `y`), the next `step` (`±w`) along x (`along_x`) + /// or y. The table is cut once along the line's two box edges; each pixel then costs one + /// interpolation per torus instead of [`Self::field`]'s eight table lookups. + pub fn row_field(&self, x: f32, y: f32, w: f32, step: f32, along_x: bool, out: &mut [f32]) { + out.fill(0.0); + let n = out.len(); + let (pos, across) = if along_x { (x, y) } else { (y, x) }; + let sign = if step < 0.0 { -1.0 } else { 1.0 }; + let first = pos as f64 - 0.5 * step as f64; + let lowest = first.min(first + n as f64 * step as f64); + let (mut near, mut far) = (Vec::new(), Vec::new()); + for (which, &t) in TORI.iter().enumerate() { + let Some(sat) = self.sats.get(which) else { continue }; + let tf = t as f32; + let lo = across - 0.5 * w; + let lo = lo - (lo / tf).floor() * tf; + line(sat, t, along_x, lo, &mut near); + line(sat, t, along_x, lo + w, &mut far); + let shift = (lowest / t as f64).floor() * t as f64; + let inv_t = 1.0 / t as f64; + let edge = |k: usize| { + let e = first + k as f64 * step as f64 - shift; + along(&far, t, inv_t, e) - along(&near, t, inv_t, e) + }; + let mut prev = edge(0); + for (k, o) in out.iter_mut().enumerate() { + let next = edge(k + 1); + *o += (sign * (next - prev)) as f32; + prev = next; + } + } + let area = w * w; + out.iter_mut().for_each(|v| *v /= area); + } +} + +// ---- the render's grain + +/// The crystal grain of one render. +#[derive(Clone, Debug)] +pub struct CrystalGrain { + pub tile: Arc, + /// Encoded-luminance amplitude at unit field and unit tone weight. + pub k: f32, + /// An output pixel's side in tile pixels. + pub foot: f32, +} + +type Key = (u64, u64, u32); + +/// The cache key of the tile of `look` and `seed`. +fn key_of(look: CrystalLook, seed: u32) -> Key { + (look.width.to_bits(), look.spread.to_bits() ^ (look.layers as u64).rotate_left(40), seed) +} +/// Recently drawn tiles (the most recent last). +type Cache = Mutex)>>; +static TILES: Cache = Mutex::new(Vec::new()); + +/// The tile being drawn in the background for a drag ([`tile`]): one at a time. +static DRAWING: Mutex> = Mutex::new(None); + +/// The tile a drawing hands to the renders waiting for it, set when it is drawn. +type Slot = Arc>>; + +/// The tiles being drawn, by cache and key, and the condition their drawers signal when done: a +/// render that misses a tile another is drawing waits for it rather than drawing it again. The +/// drawer hands the tile over in its slot, so the waiters get it even if the cache has evicted it +/// by the time they wake. +static IN_FLIGHT: Mutex> = Mutex::new(Vec::new()); +static DRAWN: Condvar = Condvar::new(); + +/// Marks a tile drawn (or failed) when dropped and wakes the renders waiting for it. +struct Drawing { + id: (usize, Key), + done: Slot, +} + +impl Drawing { + /// Registers the draw of `id` in `busy` (the locked [`IN_FLIGHT`]). + fn register(busy: &mut Vec<((usize, Key), Slot)>, id: (usize, Key)) -> Drawing { + let done = Slot::default(); + busy.push((id, done.clone())); + Drawing { id, done } + } + + /// Hands `t` to the renders waiting for it (they wake when this is dropped). + fn finish(&self, t: &Arc) { + // (already set: only the first tile counts, and every drawing draws the same one) + let _ = self.done.set(t.clone()); + } +} + +impl Drop for Drawing { + fn drop(&mut self) { + IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner).retain(|(d, _)| *d != self.id); + DRAWN.notify_all(); + } +} + +/// Registers the tile of `id` as being drawn, or `None` if another thread is drawing it. +fn start_drawing(id: (usize, Key)) -> Option { + let mut busy = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner); + if busy.iter().any(|(d, _)| *d == id) { + return None; + } + Some(Drawing::register(&mut busy, id)) +} + +/// The tile of `key` in `cache`. +fn cached(cache: &Cache, key: Key) -> Option> { + let tiles = cache.lock().unwrap_or_else(PoisonError::into_inner); + tiles.iter().find(|(k, _)| *k == key).map(|(_, t)| t.clone()) +} + +/// The tile of `look` and `seed`, drawn or from the cache. Unless `wait`, a tile not drawn yet +/// is drawn in the background and the last one drawn for `seed` stands in for it meanwhile: a +/// Size or Roughness drag doesn't wait for every step's tile (tens of milliseconds on a slow +/// CPU), and the full-quality render when it ends waits for the exact one. With no tile cached +/// for `seed` nothing can stand in, so even without `wait` this waits for a draw already running +/// or draws the tile. +fn tile(look: CrystalLook, seed: u32, wait: bool) -> Option> { + tile_in(&TILES, look, seed, wait) +} + +/// [`tile`] with the tiles cached in `cache` (a test's own, which other tests can't evict from). +fn tile_in(cache: &'static Cache, look: CrystalLook, seed: u32, wait: bool) -> Option> { + let key = key_of(look, seed); + { + let tiles = cache.lock().unwrap_or_else(PoisonError::into_inner); + if let Some((_, t)) = tiles.iter().find(|(k, _)| *k == key) { + return Some(t.clone()); + } + // (wasm has no threads to draw on) + if !wait + && !cfg!(target_arch = "wasm32") + && let Some((_, stand_in)) = tiles.iter().rev().find(|(k, _)| k.2 == seed) + { + let stand_in = stand_in.clone(); + drop(tiles); + draw_in_background(cache, key, look, seed); + return Some(stand_in); + } + } + let id = (std::ptr::from_ref(cache) as usize, key); + // a pool worker draws the tile itself: blocked, it could hold up the drawing it waits for + // (its stack may carry a part of that drawing's parallel work); wasm has no other threads + let drawing = if !cfg!(target_arch = "wasm32") && rayon::current_thread_index().is_none() { + // checked, waited for and registered under one lock: two renders that miss the tile + // together can't both find it neither cached nor being drawn (`cached` takes the cache's + // lock under this one; nothing takes them the other way round) + let mut busy = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner); + let mut waited_for: Option = None; + loop { + if let Some(t) = waited_for.as_ref().and_then(|done| done.get().cloned()).or_else(|| cached(cache, key)) { + return Some(t); + } + let Some((_, done)) = busy.iter().find(|(d, _)| *d == id) else { break }; + waited_for = Some(done.clone()); + busy = DRAWN.wait(busy).unwrap_or_else(PoisonError::into_inner); + } + Some(Drawing::register(&mut busy, id)) + } else { + start_drawing(id) + }; + #[cfg(test)] + if let Some(d) = &drawing { + tests::hold_for_waiters(d); + } + let t = Arc::new(CrystalTile::new(look, seed)?); + if let Some(d) = &drawing { + d.finish(&t); + } + keep(cache, key, t.clone()); + #[cfg(test)] + if let Some(d) = &drawing { + tests::evict_before_waking(cache, d); + } + Some(t) +} + +/// Adds `t` to `cache` (the most recent last). +fn keep(cache: &Cache, key: Key, t: Arc) { + let mut tiles = cache.lock().unwrap_or_else(PoisonError::into_inner); + tiles.retain(|(k, _)| *k != key); + if tiles.len() >= CACHE { + tiles.remove(0); + } + tiles.push((key, t)); +} + +/// Draws the tile of `key` on the thread pool unless another is being drawn (the next render +/// asks again for what it needs then). +fn draw_in_background(cache: &'static Cache, key: Key, look: CrystalLook, seed: u32) { + let marker = { + let mut drawing = DRAWING.lock().unwrap_or_else(PoisonError::into_inner); + if drawing.is_some() { + return; + } + // (`None`: a render is drawing it already) + let Some(marker) = start_drawing((std::ptr::from_ref(cache) as usize, key)) else { return }; + *drawing = Some(key); + marker + }; + spawn_in_background(move || { + if let Some(t) = CrystalTile::new(look, seed) { + let t = Arc::new(t); + marker.finish(&t); + keep(cache, key, t); + } + drop(marker); + *DRAWING.lock().unwrap_or_else(PoisonError::into_inner) = None; + }); +} + +/// Runs `draw` on the background pool. +fn spawn_in_background(draw: impl FnOnce() + Send + 'static) { + // on a pool of its own: the renders of the drag don't queue behind its parallel bands + match background_pool() { + Some(pool) => pool.spawn(draw), + None => rayon::spawn(draw), + } +} + +/// Half the cores, for tiles drawn in the background (`None`: the pool couldn't be made). +fn background_pool() -> Option<&'static rayon::ThreadPool> { + static POOL: OnceLock> = OnceLock::new(); + POOL.get_or_init(|| { + let n = std::thread::available_parallelism().map_or(2, |n| n.get()).div_ceil(2); + rayon::ThreadPoolBuilder::new().num_threads(n).thread_name(|i| format!("grain-tile-{i}")).build().ok() + }) + .as_ref() +} + +/// The tone weight of an encoded channel value `v` (0..1): `Y·dV/dY` of the sRGB curve, i.e. how +/// much `v` moves when the channel's linear light is scaled. +#[inline] +pub fn lift(v: f32) -> f32 { + let v = v.clamp(0.0, 1.0); + if v <= 0.040_45 { v } else { (v + 0.055) / 2.4 } +} + +/// The tone weight at mid grey (what [`CrystalGrain::k`] is calibrated at). +fn mid_weight() -> f32 { + lift(MID_GREY) * (1.0 - srgb_to_linear(MID_GREY)) +} + +impl CrystalGrain { + /// The grain of `g` at `px_per_long` output pixels per long edge (`None`: no grain). + pub fn new(g: &Grain, px_per_long: f64) -> Option { + Self::with(g, px_per_long, true) + } + + /// [`Self::new`] for a draft render (a drag): while its tile is drawn, the last tile drawn for + /// the same seed stands in for it (see [`tile`]). + pub fn draft(g: &Grain, px_per_long: f64) -> Option { + Self::with(g, px_per_long, false) + } + + fn with(g: &Grain, px_per_long: f64, wait: bool) -> Option { + let levels = strength_levels(g.amount, g.size, g.roughness); + if !(levels > 0.0 && px_per_long.is_finite() && px_per_long > 0.0) { + return None; + } + let foot = (TILE_PER_LONG / px_per_long) as f32; + if !(foot.is_finite() && foot > 0.0 && foot < MAX_FOOTPRINT) { + return None; + } + let tile = tile(CrystalLook::new(g.size, g.roughness), g.seed, wait)?; + Some(CrystalGrain { tile, k: (levels / 255.0) as f32 / mid_weight(), foot }) + } + + /// Display-encoded colour `e` with grain, at frame position (`gx`, `gy`) (fractions of the + /// frame's long edge): the mean over an axis-aligned square footprint centred there, which + /// for a rotated frame's pixel stands in for its rotated footprint (`docs/grain.md`). + #[inline] + pub fn apply(&self, e: [f32; 3], gx: f32, gy: f32) -> [f32; 3] { + if !(gx.is_finite() && gy.is_finite()) { + return e; + } + let tpl = TILE_PER_LONG as f32; + self.apply_field(e, self.tile.field(gx * tpl, gy * tpl, self.foot)) + } + + /// The grain field of a row of `out.len()` pixels whose first centre is at (`gx`, `gy`) and + /// which step (`dx`, `dy`) (fractions of the long edge), when the step is along x or y (an + /// unrotated frame in any orientation) and the pixels are squares of the render's size + /// (`false` otherwise: use [`Self::apply`] per pixel). + pub fn row(&self, gx: f64, gy: f64, dx: f64, dy: f64, out: &mut [f32]) -> bool { + let tpl = TILE_PER_LONG; + let ((sx, sy), w) = ((dx * tpl, dy * tpl), self.foot as f64); + let (step, along_x) = if sy.abs() <= 1e-6 { + (sx, true) + } else if sx.abs() <= 1e-6 { + (sy, false) + } else { + return false; + }; + if !(gx.is_finite() && gy.is_finite() && step.is_finite()) || (step.abs() - w).abs() > 1e-4 * w { + return false; + } + self.tile.row_field((gx * tpl) as f32, (gy * tpl) as f32, self.foot, step as f32, along_x, out); + true + } + + /// Display-encoded colour `e` with grain field value `g` (see [`CrystalTile::field`]). + #[inline] + pub fn apply_field(&self, e: [f32; 3], g: f32) -> [f32; 3] { + let lum = (0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]).clamp(0.0, 1.0); + let k = self.k * g * (1.0 - srgb_to_linear(lum)); + if !k.is_finite() { + return e; + } + e.map(|v| v + k * lift(v)) + } +} + +#[cfg(test)] +#[path = "tests_crystal.rs"] +mod tests; diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index 4cb3388127..a4ec7ddec3 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -110,6 +110,50 @@ fn vignette(s: &DevelopSettings) -> Option { /// Hash constants of [`grain_noise`] (shared with the GPU kernel). pub const GRAIN_HASH: [u32; 4] = [0x8da6_b343, 0xd816_3841, 0xcb1a_b31f, 0x5bd1_e995]; +/// The grain of processes V1 to V3: two octaves of value noise. Frozen: photos on those +/// processes keep rendering with it (`docs/process-versions.md`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ValueGrain { + /// Amplitude (display-encoded). + pub amt: f32, + /// Noise cell size (output pixels). + pub cell: f32, + /// Roughness 0..1: weight of the finer octave. + pub rough: f32, + pub seed: u32, +} + +/// A render's film grain. The model follows the photo's process: changing it would change how +/// existing photos look, so the crystal grain came with process V4. +#[derive(Clone, Debug)] +pub enum GrainModel { + /// V1 to V3: value noise. + Value(ValueGrain), + /// V4 and later: crystal layers ([`crate::crystal`]). + Crystal(crate::crystal::CrystalGrain), +} + +impl GrainModel { + /// The grain `s` renders with at `px_per_long` output pixels per long edge (`None`: none); + /// `draft`: for a drag ([`crate::crystal::CrystalGrain::draft`]). + pub fn new(s: &DevelopSettings, px_per_long: f64, draft: bool) -> Option { + let g = &s.grain; + match s.process.process() { + Process::V1 | Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 => (g.amount > 0.0).then(|| { + let cell = (0.0006 + (g.size / 100.0) as f32 * 0.0024) * px_per_long as f32; + GrainModel::Value(ValueGrain { + amt: (g.amount / 100.0) as f32 * 0.13, + cell: cell.max(0.6), + rough: (g.roughness / 100.0) as f32, + seed: g.seed, + }) + }), + Process::V7 | Process::V8 if draft => crate::crystal::CrystalGrain::draft(g, px_per_long).map(GrainModel::Crystal), + Process::V7 | Process::V8 => crate::crystal::CrystalGrain::new(g, px_per_long).map(GrainModel::Crystal), + } + } +} + #[inline] fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { // A degenerate frame (zero-width crop) maps pixels to NaN/inf coordinates: no grain there. @@ -132,6 +176,21 @@ fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { a + (b - a) * v } +/// The crystal grain of output row `y` (`w` pixels) when its pixels are axis-aligned; empty +/// otherwise (and without crystal grain): the pixels then take it one by one. +fn crystal_row(fp: &FinishParams, y: usize, w: usize) -> Vec { + let Some(GrainModel::Crystal(g)) = &fp.grain else { return Vec::new() }; + let long = fp.ow.max(fp.oh); + let (a, b) = (fp.out_to_norm.apply(Point::new(0.5, y as f64 + 0.5)), fp.out_to_norm.apply(Point::new(1.5, y as f64 + 0.5))); + let (gx, gy) = (a.x * fp.ow / long, a.y * fp.oh / long); + let (dx, dy) = ((b.x - a.x) * fp.ow / long, (b.y - a.y) * fp.oh / long); + let mut out = vec![0.0; w]; + if !g.row(gx, gy, dx, dy, &mut out) { + out.clear(); + } + out +} + /// Number of per-mask terms in [`mask_terms`]. pub const MASK_TERMS: usize = 21; @@ -217,8 +276,8 @@ pub struct FinishParams { pub air_pre: f32, pub gain: f32, pub ev: f32, - /// Grain: amount, cell size (px), roughness, seed. - pub grain: Option<(f32, f32, f32, u32)>, + /// Film grain: the model of the photo's process ([`GrainModel`]). + pub grain: Option, /// Output px → normalized oriented coordinates. pub out_to_norm: lightcraft_geom::Affine, pub ow: f64, @@ -241,12 +300,14 @@ pub struct FinishParamsInput<'a> { pub px_per_long: f64, pub air_pre: f32, pub space: OutputSpace, + /// A draft render (a drag, [`crate::Quality::Draft`]): see [`GrainModel::new`]. + pub draft: bool, } impl FinishParams { /// Parameters for a `w × h` render into `space`; `ev`/`air_pre` as in [`crate::Prepared`]. pub fn new(input: FinishParamsInput<'_>) -> FinishParams { - let FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long, air_pre, space } = input; + let FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long, air_pre, space, draft } = input; let effects = s.section_enabled("effects"); let (clar, tex, dehaze) = if effects { ((s.effects.clarity / 100.0) as f32, (s.effects.texture / 100.0) as f32, (s.effects.dehaze / 100.0) as f32) @@ -263,10 +324,7 @@ impl FinishParams { && frame.oh.is_finite() && frame.ow.max(frame.oh) > 0.0 && out_to_norm.0.iter().all(|v| v.is_finite()); - let grain = (s.grain.amount > 0.0 && effects && finite_frame).then(|| { - let cell = (0.0006 + (s.grain.size / 100.0) as f32 * 0.0024) * px_per_long as f32; - ((s.grain.amount / 100.0) as f32 * 0.13, cell.max(0.6), (s.grain.roughness / 100.0) as f32, s.grain.seed) - }); + let grain = if effects && finite_frame { GrainModel::new(s, px_per_long, draft) } else { None }; let calibration = s.section_enabled("calibration"); let peak = s.hdr.peak(); FinishParams { @@ -349,7 +407,7 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap { }, // V4, with a raw's tone curve rolling off into white in stops: a camera curve past its last // knot, the generic curve from half a stop below its white point instead of clipping (issue #1632) - Process::V5 | Process::V6 => match info.camera_tone.as_ref().filter(|_| info.raw) { + Process::V5 | Process::V6 | Process::V7 | Process::V8 => match info.camera_tone.as_ref().filter(|_| info.raw) { Some(curve) => ToneMap::camera_rolloff_hdr(curve, 0.0, l.whites, 0.0, peak), None if info.raw => ToneMap::rolloff_hdr(l.contrast, l.whites, l.blacks, peak), None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak), @@ -358,18 +416,20 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap { } /// Finish the prepared pipeline stages into an 8-bit RGBA image in `space` (or `display`). -pub(crate) fn finish( - p: &Prepared, - s: &DevelopSettings, - frame: &Frame, - info: &SourceInfo, - space: OutputSpace, - display: Option<&crate::DisplaySpace>, - proof: Option, -) -> Rgba8 { +pub(crate) fn finish(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInfo, req: &crate::RenderRequest) -> Rgba8 { + let (space, display, proof) = (req.space, req.display.as_ref(), req.proof); let (w, h) = (p.img.width, p.img.height); - let mut fp = - FinishParams::new(FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long: p.px_per_long, air_pre: p.air, space }); + let draft = req.quality == crate::Quality::Draft; + let mut fp = FinishParams::new(FinishParamsInput { + settings: s, + frame, + info, + image_size: (w, h), + px_per_long: p.px_per_long, + air_pre: p.air, + space, + draft, + }); fp.proof = proof.map(|pr| pr.params(space)); if let Some(d) = display { fp.for_display(d, proof); @@ -389,19 +449,21 @@ pub(crate) fn finish( } /// [`finish`] into 16-bit display-encoded or 32-bit float linear samples (output primaries). -pub(crate) fn finish_deep( - p: &Prepared, - s: &DevelopSettings, - frame: &Frame, - info: &SourceInfo, - space: OutputSpace, - depth: OutputDepth, - proof: Option, -) -> DeepImage { +pub(crate) fn finish_deep(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInfo, req: &crate::RenderRequest) -> DeepImage { use lightcraft_color::transfer::srgb_to_linear; + let (space, depth, proof) = (req.space, req.depth, req.proof); let (w, h) = (p.img.width, p.img.height); - let mut fp = - FinishParams::new(FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long: p.px_per_long, air_pre: p.air, space }); + let draft = req.quality == crate::Quality::Draft; + let mut fp = FinishParams::new(FinishParamsInput { + settings: s, + frame, + info, + image_size: (w, h), + px_per_long: p.px_per_long, + air_pre: p.air, + space, + draft, + }); fp.proof = proof.map(|pr| pr.params(space)); let trc = fp.out_trc; let samples = match depth { @@ -453,6 +515,8 @@ pub(crate) fn finish_with( let hdr = peak > 1.0; let mut out = vec![T::default(); w * h]; for_rows(&mut out, w, |y, row| { + // the crystal grain of the whole row at once when its pixels are axis-aligned + let crystal_row = crystal_row(fp, y, row.len()); for (x, px) in row.iter_mut().enumerate() { let i = y * w + x; let raw = p.img.data[i]; @@ -587,20 +651,31 @@ pub(crate) fn finish_with( e = refine_saturation(e0, e, fp.refine_sat); } } - if let Some((amt, cell, rough, seed)) = *grain { - let n = out_to_norm.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5)); - let (gx, gy) = ((n.x * fp.ow) as f32 / long as f32, (n.y * fp.oh) as f32 / long as f32); - let sc = fp.px_per_long as f32 / cell; - let mut g = grain_noise(gx * sc, gy * sc, seed); - g = g * (1.0 - rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, seed ^ 0x55) * rough * 0.7; - let mut lum = 0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]; - if hdr { - lum = lum.clamp(0.0, 1.0); - } - let k = amt * g * (0.35 + 2.6 * lum * (1.0 - lum)); - if k.is_finite() { - e = e.map(|v| v + k); + match grain { + Some(GrainModel::Value(g)) => { + // V1/V2 (frozen): exactly the arithmetic those processes always had + let n = out_to_norm.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5)); + let (gx, gy) = ((n.x * fp.ow) as f32 / long as f32, (n.y * fp.oh) as f32 / long as f32); + let sc = fp.px_per_long as f32 / g.cell; + let mut v = grain_noise(gx * sc, gy * sc, g.seed); + v = v * (1.0 - g.rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, g.seed ^ 0x55) * g.rough * 0.7; + let mut lum = 0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]; + if hdr { + lum = lum.clamp(0.0, 1.0); + } + let k = g.amt * v * (0.35 + 2.6 * lum * (1.0 - lum)); + if k.is_finite() { + e = e.map(|v| v + k); + } } + Some(GrainModel::Crystal(g)) => match crystal_row.get(x) { + Some(&f) => e = g.apply_field(e, f), + None => { + let n = out_to_norm.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5)); + e = g.apply(e, (n.x * fp.ow / long) as f32, (n.y * fp.oh / long) as f32); + } + }, + None => {} } let e = match &p_lut { Some((l, k)) if hdr => { diff --git a/crates/pipeline/src/lens_blur.rs b/crates/pipeline/src/lens_blur.rs new file mode 100644 index 0000000000..f518eb5de7 --- /dev/null +++ b/crates/pipeline/src/lens_blur.rs @@ -0,0 +1,1109 @@ +//! Lens Blur: a shallow depth of field added after the fact. +//! +//! Without a depth map, the scene has two depths: what is in focus (the photo's subject, or the +//! selection of the mask [`LensBlur::focus_mask`](lightcraft_develop::LensBlur) names) and +//! everything else. A pixel's circle of confusion is `R · (1 − focus)`, `R` set by Blur Amount +//! relative to the long edge, so previews and exports match. +//! +//! The blur is gathered from [`LEVELS`] disc blurs of growing radius, blended per pixel by its +//! circle of confusion. Each disc blur runs on a grid coarse enough that the disc spans about +//! [`DISC_CELLS`] cells (its cost doesn't grow with the radius) and is a normalized convolution +//! weighted by how far out of focus each pixel is, so the sharp subject doesn't bleed into the +//! blurred background around it (no halo). Boost brightens highlights before they are spread, so +//! they turn into bright discs (bokeh), as a lens does with scene-linear light. +//! +//! Brush Refinement paints the focus by hand: Focus brush strokes stay sharp, Blur brush strokes +//! are blurred whatever the focus says. +//! +//! A mask can blur too (Lens Blur among its local adjustments): there the mask's strength is the +//! circle of confusion, so what it fully selects gets the whole blur, its feathered edge less, and +//! what it leaves out stays sharp and doesn't bleed into the blur. +//! +//! Amount is capped at 3.5% of the output's long edge. The disc convolution runs on a grid whose +//! disc radius is at most [`DISC_CELLS`] cells and whose size is capped by [`MAX_CELLS`] per level, +//! so increasing the output resolution or blur radius does not make the convolution kernel grow. +//! The full-resolution passes remain linear in the output pixel count. +//! +//! It runs on the scene-linear image (white-balanced and denoised, before exposure: a blur is +//! linear, so exposure commutes with it), on the CPU, for both renderers. + +use lightcraft_develop::{BrushStroke, DevelopSettings, Mask, MaskShape}; +use lightcraft_raster::{Plane, Rgb32f}; + +use crate::geometry::Frame; +use crate::masks::{self, Mattes}; + +/// The largest circle of confusion (Blur Amount 100), as a fraction of the long edge. +pub const MAX_RADIUS: f64 = 0.035; +/// How far from the focus the blur reaches its full size at Transition 100, as a fraction of the +/// long edge (a stand-in for depth: what is near the subject in the picture is usually near it in +/// the scene too, as a lens renders a floor or a wall running away from it). +pub const MAX_TRANSITION: f64 = 0.15; +/// The blur right at the focus's edge, as a share of the full blur (with a transition): the +/// background around a subject is a little soft at once, not cut out sharp. +const EDGE_BLUR: f32 = 0.1; +/// The feather (0..100) of a fixed focus shape's edge ([`lightcraft_develop::FocusShape`]). +const SHAPE_FEATHER: f64 = 40.0; +/// Most cells along the long edge of the grid the distance to the focus is measured on. +const DISTANCE_CELLS: usize = 384; +/// Disc blurs the per-pixel circle of confusion is interpolated between. +const LEVELS: usize = 4; +/// Radius, in grid cells, a level's disc blur works at. +const DISC_CELLS: f32 = 8.0; +/// Most cells a level's grid holds (bounds the memory of a full-size export). +const MAX_CELLS: usize = 3_000_000; +/// Weight of in-focus pixels in the blurred levels: enough to keep a level defined where only +/// in-focus pixels are near, too little to bleed them into the background. +const FOCUS_WEIGHT: f32 = 1e-4; +/// The brightest highlights grow this much brighter at Boost 100 before they are spread. +const BOOST_GAIN: f32 = 4.0; + +/// Whether `s` renders a lens blur (switched on, with some amount, and its section's eye open). +pub fn active(s: &DevelopSettings) -> bool { + let b = &s.lens_blur; + b.enabled && b.amount.is_finite() && b.amount > 0.0 && s.section_enabled("lensBlur") +} + +/// Whether [`apply`] changes anything: the global lens blur, or a mask's. +pub fn renders(s: &DevelopSettings) -> bool { + active(s) || blurring_masks(s).next().is_some() +} + +/// The largest circle of confusion (radius in output pixels) at `px_per_long` output pixels per +/// long edge; 0 when [`active`] is false. +pub fn radius_px(s: &DevelopSettings, px_per_long: f64) -> f32 { + if !active(s) { + return 0.0; + } + let r = s.lens_blur.amount.clamp(0.0, 100.0) / 100.0 * MAX_RADIUS * px_per_long; + if r.is_finite() { r.max(0.0) as f32 } else { 0.0 } +} + +/// The masks that blur what they select, or what they leave out (the Lens Blur block among a +/// mask's local adjustments): shown, with components, the block on and some blur. +fn blurring_masks(s: &DevelopSettings) -> impl Iterator { + s.masks + .iter() + .filter(|m| m.visible && !m.components.is_empty() && !m.adjust.lens_blur_off && m.adjust.lens_blur.is_finite() && m.adjust.lens_blur > 0.0) +} + +/// The circle of confusion (radius in output pixels) where mask `m` fully selects. +fn mask_radius_px(m: &Mask, px_per_long: f64) -> f32 { + let r = m.adjust.lens_blur.clamp(0.0, 100.0) / 100.0 * MAX_RADIUS * px_per_long; + if r.is_finite() { r.max(0.0) as f32 } else { 0.0 } +} + +/// The distance from the focus (output pixels) at which the blur is full; 0: a sharp cut. +pub fn transition_px(s: &DevelopSettings, px_per_long: f64) -> f32 { + if !active(s) { + return 0.0; + } + transition_of(s.lens_blur.transition, px_per_long) +} + +/// [`transition_px`] for a Transition slider value `t` (0..100). +fn transition_of(t: f64, px_per_long: f64) -> f32 { + if !t.is_finite() || t <= 0.0 { + return 0.0; + } + let d = t.min(100.0) / 100.0 * MAX_TRANSITION * px_per_long; + if d.is_finite() { d.max(0.0) as f32 } else { 0.0 } +} + +/// A Boost slider value (0..100) as 0..1. +fn boost_of(b: f64) -> f32 { + if b.is_finite() { (b.clamp(0.0, 100.0) / 100.0) as f32 } else { 0.0 } +} + +/// The farthest any lens blur of `s` reads (output pixels): the global one's (its blur, and how far +/// it looks for the focus) or a mask's. +pub fn reach_px(s: &DevelopSettings, px_per_long: f64) -> f32 { + let global = radius_px(s, px_per_long) + transition_px(s, px_per_long); + blurring_masks(s).map(|m| mask_radius_px(m, px_per_long) + transition_of(m.adjust.lens_blur_transition, px_per_long)).fold(global, f32::max) +} + +/// `win` (a window of the `full_w × full_h` output) grown by the blur's reach, so a zoomed view +/// blurs its edges with the pixels around them, as the whole render does (the render is cut back +/// to `win`, see [`crate::Plan::keep`]). +pub fn window_for_reads(s: &DevelopSettings, full_w: usize, full_h: usize, px_per_long: f64, win: crate::PixelWindow) -> crate::PixelWindow { + let r = reach_px(s, px_per_long); + if r <= 0.0 { + return win; + } + let m = (r * 1.25).ceil() as usize + 2; + let (x0, y0) = (win.x.saturating_sub(m), win.y.saturating_sub(m)); + let x1 = win.x.saturating_add(win.w).saturating_add(m).min(full_w.max(1)); + let y1 = win.y.saturating_add(win.h).saturating_add(m).min(full_h.max(1)); + crate::PixelWindow { x: x0, y: y0, w: x1.saturating_sub(x0).max(1), h: y1.saturating_sub(y0).max(1) } +} + +/// What [`apply`] reads from `s`, for render cache keys (empty when no lens blur renders). +pub fn key(s: &DevelopSettings) -> String { + let mut k = String::new(); + if active(s) { + k = match focus_mask(s) { + Some(m) => format!("{:?}|{m:?}", s.lens_blur), + None => format!("{:?}", s.lens_blur), + }; + } + for m in blurring_masks(s) { + k.push_str(&format!("|{m:?}")); + } + // a mask's luminance / colour ranges select on the exposed image + if !k.is_empty() { + k.push_str(&format!("|{}", s.light.exposure.to_bits())); + } + k +} + +/// The mask that says what is in focus, if the settings name one that exists and selects something. +/// An AI mask whose selection is still being computed (Find Subject on a slow machine) doesn't +/// count yet: until it is, the subject estimate stays in focus rather than nothing. +fn focus_mask(s: &DevelopSettings) -> Option<&Mask> { + let id = s.lens_blur.focus_mask?; + s.masks.iter().find(|m| m.id == id && !m.components.is_empty() && !awaiting_ai(m)) +} + +/// Whether every component of `m` is an AI selection (Object / Describe) not computed yet. +pub fn awaiting_ai(m: &Mask) -> bool { + m.components.iter().all(|c| match &c.shape { + MaskShape::Object { seg, detail, .. } | MaskShape::Prompt { seg, detail, .. } => seg.is_none() && detail.is_empty(), + _ => false, + }) +} + +/// Smoothstep: 0 below `e0`, 1 above `e1`, a smooth S-curve between. +#[inline] +fn smooth(e0: f32, e1: f32, x: f32) -> f32 { + let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// What is in focus, 0..1 per pixel of `img` (scene-linear, before exposure, output resolution). +pub fn focus(img: &Rgb32f, s: &DevelopSettings, frame: &Frame, mattes: Option<&Mattes>) -> Plane { + focus_with(img, s, frame, mattes, None) +} + +/// [`focus`], taking the automatic subject estimate from `subject` (made from the whole photo, +/// see [`subject_estimate`]) when there is one, so a window of the output gets the same focus as +/// the whole render. +fn focus_with(img: &Rgb32f, s: &DevelopSettings, frame: &Frame, mattes: Option<&Mattes>, subject: Option<&SubjectEstimate>) -> Plane { + let (w, h) = (img.width, img.height); + let log_l = img.map(crate::local::log_lum); + let mut a = match (focus_mask(s), s.lens_blur.focus_area(s.crop_center())) { + (Some(m), _) => masks::evaluate_one(m, frame, w, h, img, &log_l, s.light.exposure as f32, mattes), + // a fixed shape: where it was moved to, else the middle of the crop (in photo + // coordinates, so it stays put in a zoomed view) + (None, Some(area)) => { + let shape = MaskShape::Radial { center: area.center, rx: area.rx, ry: area.ry, angle: 0.0, feather: SHAPE_FEATHER, invert: false }; + masks::shape_alpha(&shape, frame, w, h, img, &log_l, 0.0, mattes) + } + (None, None) if let Some(est) = subject => est.sample(frame, w, h), + (None, None) => { + let mut a = masks::shape_alpha(&MaskShape::Subject, frame, w, h, img, &log_l, 0.0, mattes); + // the saliency heuristic gives a flat centre about 0.5: in focus too (person mattes + // are 0 or 1 and stay so) + a.data.iter_mut().for_each(|v| *v = smooth(0.25, 0.55, *v)); + a + } + }; + // Brush Refinement: the Focus brush adds focus, the Blur brush takes it away (last word) + let b = &s.lens_blur; + let brush = |strokes: &[BrushStroke]| { + (!strokes.is_empty()).then(|| masks::shape_alpha(&MaskShape::Brush { strokes: strokes.to_vec() }, frame, w, h, img, &log_l, 0.0, mattes)) + }; + if let Some(f) = brush(&b.focus_strokes) { + a.data.iter_mut().zip(&f.data).for_each(|(v, f)| *v = v.max(*f)); + } + if let Some(bl) = brush(&b.blur_strokes) { + a.data.iter_mut().zip(&bl.data).for_each(|(v, b)| *v *= 1.0 - b.clamp(0.0, 1.0)); + } + a.data.iter_mut().for_each(|v| *v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }); + a +} + +/// Long edge of the small render [`subject_point`] looks at. +const SUBJECT_EDGE: usize = 256; + +/// Long edge of the small render [`subject_estimate`] makes of the whole photo. +const ESTIMATE_EDGE: usize = 384; + +/// The automatic subject estimate (the saliency heuristic, for a photo without a person matte) +/// made once from the whole, uncropped photo at [`ESTIMATE_EDGE`]: every render of the photo, +/// whole or a window of it, samples the same estimate, so a zoomed view keeps the focus the +/// whole render has (the heuristic reads its neighbourhood, which a window cuts off). +#[derive(Debug)] +pub struct SubjectEstimate { + plane: Plane, + frame: Frame, +} + +impl SubjectEstimate { + /// The estimate at each pixel of a `w × h` output of `frame` (bilinear). + fn sample(&self, frame: &Frame, w: usize, h: usize) -> Plane { + let (pw, ph) = (self.plane.width, self.plane.height); + let mut out = Plane::new(w, h); + if pw == 0 || ph == 0 || self.plane.data.len() != pw * ph { + return out; + } + let to_norm = frame.out_to_norm(w, h); + let to_proxy = self.frame.norm_to_out(pw, ph); + let at = |x: usize, y: usize| self.plane.data.get(y.min(ph - 1) * pw + x.min(pw - 1)).copied().unwrap_or(0.0); + for (i, v) in out.data.iter_mut().enumerate() { + let n = to_norm.apply(lightcraft_geom::Point::new((i % w) as f64 + 0.5, (i / w) as f64 + 0.5)); + let p = to_proxy.apply(n); + let (fx, fy) = ((p.x - 0.5).clamp(0.0, (pw - 1) as f64), (p.y - 0.5).clamp(0.0, (ph - 1) as f64)); + if !(fx.is_finite() && fy.is_finite()) { + continue; + } + let (x0, y0) = (fx as usize, fy as usize); + let (tx, ty) = ((fx - x0 as f64) as f32, (fy - y0 as f64) as f32); + let top = at(x0, y0) + (at(x0 + 1, y0) - at(x0, y0)) * tx; + let bot = at(x0, y0 + 1) + (at(x0 + 1, y0 + 1) - at(x0, y0 + 1)) * tx; + *v = top + (bot - top) * ty; + } + out + } +} + +/// The [`SubjectEstimate`] the lens blur of `s` focuses on, when it focuses on the automatic +/// subject estimate (switched on, no focus mask, no fixed shape) of a photo without a person +/// matte; `None` otherwise (the focus then needs no whole-photo data). +pub fn subject_estimate(src: &Rgb32f, s: &DevelopSettings, mattes: Option<&Mattes>) -> Option { + if !active(s) || focus_mask(s).is_some() || s.lens_blur.focus_area(s.crop_center()).is_some() || mattes.is_some_and(Mattes::selects_subject) { + return None; + } + if src.width == 0 || src.height == 0 || src.data.len() != src.width.saturating_mul(src.height) { + return None; + } + let frame = Frame::new(src.width, src.height, s, false); + let (w, h) = frame.fit(ESTIMATE_EDGE, ESTIMATE_EDGE); + if w == 0 || h == 0 { + return None; + } + let img = frame.sample(src, w, h); + let log_l = img.map(crate::local::log_lum); + let mut plane = masks::shape_alpha(&MaskShape::Subject, &frame, w, h, &img, &log_l, 0.0, None); + // the saliency heuristic gives a flat centre about 0.5: in focus too + plane.data.iter_mut().for_each(|v| *v = smooth(0.25, 0.55, *v)); + Some(SubjectEstimate { plane, frame }) +} + +/// Where the photo's subject most likely is, for a photo whose camera recorded no focus point: the +/// peak of the subject estimate (person mattes, else the saliency heuristic) over the whole, +/// uncropped photo, in normalized mask coordinates. `None` for an empty source. +pub fn subject_point(src: &Rgb32f, s: &DevelopSettings, mattes: Option<&Mattes>) -> Option { + if src.width == 0 || src.height == 0 || src.data.len() != src.width.saturating_mul(src.height) { + return None; + } + let frame = Frame::new(src.width, src.height, s, false); + let (w, h) = frame.fit(SUBJECT_EDGE, SUBJECT_EDGE); + if w == 0 || h == 0 { + return None; + } + let img = frame.sample(src, w, h); + let log_l = img.map(crate::local::log_lum); + let a = masks::shape_alpha(&MaskShape::Subject, &frame, w, h, &img, &log_l, 0.0, mattes); + let (i, _) = a.data.iter().enumerate().filter(|(_, v)| v.is_finite()).max_by(|x, y| x.1.total_cmp(y.1))?; + let n = frame.out_to_norm(w, h).apply(lightcraft_geom::Point::new((i % w) as f64 + 0.5, (i / w) as f64 + 0.5)); + (n.x.is_finite() && n.y.is_finite()).then(|| lightcraft_geom::Point::new(n.x.clamp(0.0, 1.0), n.y.clamp(0.0, 1.0))) +} + +/// Blur what is out of focus in `img` (scene-linear, before exposure, at output resolution; +/// `frame` and `px_per_long` describe that output), then what each mask with a Lens Blur +/// adjustment selects (in mask order). Does nothing when no lens blur renders. +pub fn apply(img: &mut Rgb32f, s: &DevelopSettings, frame: &Frame, px_per_long: f64, mattes: Option<&Mattes>) { + apply_with(img, s, frame, px_per_long, mattes, None); +} + +/// [`apply`] with the photo's [`SubjectEstimate`] (renders pass [`crate::Plan::lens_subject`]). +pub fn apply_with( + img: &mut Rgb32f, + s: &DevelopSettings, + frame: &Frame, + px_per_long: f64, + mattes: Option<&Mattes>, + subject: Option<&SubjectEstimate>, +) { + let (w, h) = (img.width, img.height); + if w == 0 || h == 0 || img.data.len() != w.saturating_mul(h) { + return; + } + // a zoomed view's place in the whole output: its coarse grids line up with the whole render's + let at = |v: f64| if v.is_finite() && v > 0.0 { v.round() as usize } else { 0 }; + let origin = frame.view.map_or((0, 0), |v| (at(v.x), at(v.y))); + let r = radius_px(s, px_per_long); + if r >= 0.5 { + let focus = crate::timed("lens blur focus", || focus_with(img, s, frame, mattes, subject)); + if focus.data.len() == img.data.len() { + // the blur grows with the distance from what is in focus, as with depth + let ramp = crate::timed("lens blur transition", || transition_ramp(&focus, transition_px(s, px_per_long), px_per_long, origin)); + let coc: Vec = focus.data.iter().enumerate().map(|(i, f)| (1.0 - f) * ramp.as_ref().map_or(1.0, |r| r.at(i))).collect(); + blur(img, &coc, r, boost_of(s.lens_blur.boost), origin); + } + } + let ev = s.light.exposure as f32; + for m in blurring_masks(s) { + let r = mask_radius_px(m, px_per_long); + if r < 0.5 { + continue; + } + // the mask's strength (its Amount included) is how far out of focus a pixel is; blurring + // the outside, it is how far the mask stays below its Amount + let log_l = img.map(crate::local::log_lum); + let alpha = crate::timed("lens blur mask", || masks::evaluate_one(m, frame, w, h, img, &log_l, ev, mattes)); + if alpha.data.len() != img.data.len() { + continue; + } + let a = &m.adjust; + let top = if a.amount.is_finite() { (a.amount / 100.0).clamp(0.0, 1.0) as f32 } else { 0.0 }; + let mut coc: Vec = alpha + .data + .iter() + .map(|v| { + let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + if a.lens_blur_outside { (top - v).max(0.0) } else { v } + }) + .collect(); + // the blur grows away from what stays sharp, as the global one's does + let sharp = Plane { width: w, height: h, data: coc.iter().map(|c| 1.0 - c).collect() }; + if let Some(ramp) = transition_ramp(&sharp, transition_of(a.lens_blur_transition, px_per_long), px_per_long, origin) { + coc.iter_mut().enumerate().for_each(|(i, c)| *c *= ramp.at(i)); + } + blur(img, &coc, r, boost_of(a.lens_blur_boost), origin); + } +} + +/// How much of the full blur each pixel gets for its distance from the focus: [`EDGE_BLUR`] at +/// the focus's edge, growing smoothly to all of it `d` pixels away. +struct Ramp { + /// Distance from the focus, in grid cells. + dist: Plane, + /// Pixels per cell. + g: usize, + w: usize, + d: f32, + /// Where pixel (0, 0) sits in the grid (the grid follows the whole output's cells). + shift: (usize, usize), +} + +impl Ramp { + /// The share of the full blur pixel `i` (row-major in the window) gets. + fn at(&self, i: usize) -> f32 { + let (x, y) = (i % self.w.max(1) + self.shift.0, i / self.w.max(1) + self.shift.1); + let g = self.g as f32; + // bilinear in the grid, cell centres at +0.5 + let (fx, fy) = (((x as f32 + 0.5) / g - 0.5).max(0.0), ((y as f32 + 0.5) / g - 0.5).max(0.0)); + let (gw, gh) = (self.dist.width, self.dist.height); + let (x0, y0) = ((fx as usize).min(gw - 1), (fy as usize).min(gh - 1)); + let (x1, y1) = ((x0 + 1).min(gw - 1), (y0 + 1).min(gh - 1)); + let (tx, ty) = (fx - x0 as f32, fy - y0 as f32); + let v = |x: usize, y: usize| self.dist.data.get(y * gw + x).copied().unwrap_or(f32::MAX); + let top = v(x0, y0) + (v(x1, y0) - v(x0, y0)) * tx; + let bot = v(x0, y1) + (v(x1, y1) - v(x0, y1)) * tx; + let px = (top + (bot - top) * ty) * g; + EDGE_BLUR + (1.0 - EDGE_BLUR) * smooth(0.0, self.d, px) + } +} + +/// The [`Ramp`] for `focus` over `d` pixels; `None` for a sharp cut (`d` 0) or nothing in focus. +/// Distances are chamfer distances (steps of 1 and √2 cells) on a grid of about +/// [`DISTANCE_CELLS`] along the photo's long edge (`px_per_long`: the cell size follows the +/// photo's scale, not the rendered window's, and its cells are the whole output's: `origin` is +/// where a window's pixel (0, 0) sits in it, so a zoomed view measures as the whole render does): +/// what is in focus are the cells mostly in focus. +fn transition_ramp(focus: &Plane, d: f32, px_per_long: f64, origin: (usize, usize)) -> Option { + let (w, h) = (focus.width, focus.height); + // (a NaN distance is no transition) + if d.is_nan() || d <= 0.5 || w == 0 || h == 0 || focus.data.len() != w * h { + return None; + } + let per_cell = px_per_long / DISTANCE_CELLS as f64; + let g = if per_cell.is_finite() { (per_cell.ceil() as usize).clamp(1, w.max(h)) } else { 1 }; + let shift = (origin.0 % g, origin.1 % g); + // the grid covers the window shifted into the whole output's cells + let (gw, gh) = ((w + shift.0).div_ceil(g), (h + shift.1).div_ceil(g)); + let mut dist = Plane::new(gw, gh); + let mut any = false; + for cy in 0..gh { + for cx in 0..gw { + let (mut sum, mut n) = (0.0f32, 0usize); + for vy in cy * g..((cy + 1) * g).min(h + shift.1) { + for vx in cx * g..((cx + 1) * g).min(w + shift.0) { + let (Some(x), Some(y)) = (vx.checked_sub(shift.0), vy.checked_sub(shift.1)) else { continue }; + sum += focus.data.get(y * w + x).copied().unwrap_or(0.0); + n += 1; + } + } + let inside = n > 0 && sum / n as f32 > 0.5; + any |= inside; + if let Some(c) = dist.data.get_mut(cy * gw + cx) { + *c = if inside { 0.0 } else { f32::MAX }; + } + } + } + if !any { + return None; + } + let diag = std::f32::consts::SQRT_2; + let at = |d: &Plane, x: isize, y: isize| { + if x < 0 || y < 0 || x >= gw as isize || y >= gh as isize { + f32::MAX + } else { + d.data.get(y as usize * gw + x as usize).copied().unwrap_or(f32::MAX) + } + }; + // forward then backward chamfer passes + for y in 0..gh as isize { + for x in 0..gw as isize { + let c = at(&dist, x, y) + .min(at(&dist, x - 1, y) + 1.0) + .min(at(&dist, x, y - 1) + 1.0) + .min(at(&dist, x - 1, y - 1) + diag) + .min(at(&dist, x + 1, y - 1) + diag); + if let Some(v) = dist.data.get_mut(y as usize * gw + x as usize) { + *v = c; + } + } + } + for y in (0..gh as isize).rev() { + for x in (0..gw as isize).rev() { + let c = at(&dist, x, y) + .min(at(&dist, x + 1, y) + 1.0) + .min(at(&dist, x, y + 1) + 1.0) + .min(at(&dist, x + 1, y + 1) + diag) + .min(at(&dist, x - 1, y + 1) + diag); + if let Some(v) = dist.data.get_mut(y as usize * gw + x as usize) { + *v = c; + } + } + } + Some(Ramp { dist, g, w, d, shift }) +} + +/// Blur `img` by a circle of confusion `coc · r` pixels per pixel (`coc` 0..1, one per pixel), +/// highlights brightened by `boost` (0..1) before they are spread. +/// `origin`: where `img`'s pixel (0, 0) sits in the whole output (a zoomed view's window), so the +/// coarse grids line up with the whole render's. +fn blur(img: &mut Rgb32f, coc: &[f32], r: f32, boost: f32, origin: (usize, usize)) { + let w = img.width; + // highlights brightened before they are spread (the bokeh), the rest as it is + let gain = |c: [f32; 3]| 1.0 + BOOST_GAIN * boost * smooth(0.5, 1.0, lightcraft_color::luminance_2020(c)); + let levels: Vec = (1..=LEVELS).map(|k| crate::timed("lens blur level", || level(img, coc, k, r, &gain, origin))).collect(); + // each pixel between the two levels around its circle of confusion (level 0: the image) + let src = img.clone(); + crate::for_rows(&mut img.data, w, |y, row| { + for (x, px) in row.iter_mut().enumerate() { + let i = y * w + x; + let t = coc.get(i).copied().unwrap_or(0.0) * LEVELS as f32; + let k = (t.floor().max(0.0) as usize).min(LEVELS - 1); + let fr = (t - k as f32).clamp(0.0, 1.0); + let at = |k: usize| match k { + 0 => src.data.get(i).copied().unwrap_or(*px), + k => levels.get(k - 1).map_or(*px, |l| l.sample(x, y)), + }; + let (a, b) = (at(k), at(k + 1)); + *px = std::array::from_fn(|c| a[c] + (b[c] - a[c]) * fr); + } + }); +} + +/// One disc blur, on a grid `f` times coarser than the image. +struct Level { + img: Rgb32f, + f: usize, + /// Where image pixel (0, 0) sits on the grid's pixels (the whole output's cells). + shift: (usize, usize), +} + +impl Level { + /// The blurred value at image pixel `(x, y)`. + fn sample(&self, x: usize, y: usize) -> [f32; 3] { + let f = self.f as f32; + self.img.sample_bilinear(((x + self.shift.0) as f32 + 0.5) / f, ((y + self.shift.1) as f32 + 0.5) / f) + } +} + +/// Level `k` of [`LEVELS`] (radius `k / LEVELS · r` pixels): the disc blur of the pixels at least +/// that far out of focus. +fn level(img: &Rgb32f, coc: &[f32], k: usize, r: f32, gain: &(impl Fn([f32; 3]) -> f32 + Sync), origin: (usize, usize)) -> Level { + let (w, h) = (img.width, img.height); + let radius = r * k as f32 / LEVELS as f32; + let (f, shift, lw, lh) = level_grid(w, h, radius, origin); + let (grid_w, grid_h) = (w.saturating_add(shift.0), h.saturating_add(shift.1)); + // a pixel counts in this level when its own circle of confusion reaches it + let (lo, hi) = ((k - 1) as f32 / LEVELS as f32, k as f32 / LEVELS as f32); + let mut cells = vec![[0f32; 4]; lw * lh]; + crate::for_rows(&mut cells, lw, |cy, row| { + for (cx, cell) in row.iter_mut().enumerate() { + let mut acc = [0f32; 4]; + for vy in cy * f..((cy + 1) * f).min(grid_h) { + for vx in cx * f..((cx + 1) * f).min(grid_w) { + let (Some(x), Some(y)) = (vx.checked_sub(shift.0), vy.checked_sub(shift.1)) else { continue }; + let i = y * w + x; + let (Some(c), Some(d)) = (img.data.get(i), coc.get(i)) else { continue }; + // (a non-finite pixel would spread over the whole disc: left out) + if !c.iter().all(|v| v.is_finite()) { + continue; + } + let wt = FOCUS_WEIGHT + smooth(lo, hi, *d); + let g = gain(*c) * wt; + acc = [acc[0] + c[0] * g, acc[1] + c[1] * g, acc[2] + c[2] * g, acc[3] + wt]; + } + } + *cell = acc; + } + }); + Level { img: disc(&cells, lw, lh, radius / f as f32), f, shift } +} + +/// Grid scale and dimensions for one disc level, bounded even when a window's grid is offset. +fn level_grid(w: usize, h: usize, radius: f32, origin: (usize, usize)) -> (usize, (usize, usize), usize, usize) { + let at_least = ((w as f64 * h as f64) / MAX_CELLS as f64).sqrt().ceil() as usize; + let max_edge = w.max(h).max(1); + let mut f = ((radius / DISC_CELLS).ceil() as usize).max(at_least).clamp(1, max_edge); + loop { + let shift = (origin.0 % f, origin.1 % f); + let (lw, lh) = (w.saturating_add(shift.0).div_ceil(f), h.saturating_add(shift.1).div_ceil(f)); + if lw.saturating_mul(lh) <= MAX_CELLS || f == max_edge { + return (f, shift, lw, lh); + } + f = f.saturating_add(1); + } +} + +/// The normalized disc blur of radius `rho` cells of weighted sums `cells` (`[r·w, g·w, b·w, w]`, +/// `lw × lh`): per row of the disc, a span read from that row's prefix sums, its two end cells +/// weighted by the fraction of them inside. +fn disc(cells: &[[f32; 4]], lw: usize, lh: usize, rho: f32) -> Rgb32f { + let stride = lw + 1; + let mut pre = vec![[0f64; 4]; stride * lh]; + crate::for_rows(&mut pre, stride, |y, p| { + let Some(row) = cells.get(y * lw..(y + 1) * lw) else { return }; + let mut acc = [0f64; 4]; + for (x, c) in row.iter().enumerate() { + for ch in 0..4 { + acc[ch] += c[ch] as f64; + } + if let Some(slot) = p.get_mut(x + 1) { + *slot = acc; + } + } + }); + // (a disc past the grid reads nothing more) + let rho = if rho.is_finite() { rho.clamp(0.0, lw.max(lh) as f32 + 1.0) } else { 0.0 }; + let n = rho.ceil() as isize; + let spans: Vec<(isize, isize, f64)> = (-n..=n) + .filter_map(|dy| { + let q = rho * rho - (dy * dy) as f32; + (q >= 0.0).then(|| { + let hw = q.sqrt(); + (dy, hw.floor() as isize, (hw - hw.floor()) as f64) + }) + }) + .collect(); + let mut out = Rgb32f::new(lw, lh); + let (lwi, lhi) = (lw as isize, lh as isize); + crate::for_rows(&mut out.data, lw, |y, row| { + for (x, px) in row.iter_mut().enumerate() { + let x = x as isize; + let mut acc = [0f64; 4]; + for &(dy, hw, fr) in &spans { + let yy = y as isize + dy; + if yy < 0 || yy >= lhi { + continue; + } + let base = yy as usize * stride; + let (a, b) = ((x - hw).max(0), (x + hw + 1).min(lwi)); + if a < b + && let (Some(pa), Some(pb)) = (pre.get(base + a as usize), pre.get(base + b as usize)) + { + for ch in 0..4 { + acc[ch] += pb[ch] - pa[ch]; + } + } + if fr > 0.0 { + for xx in [x - hw - 1, x + hw + 1] { + if xx >= 0 + && xx < lwi + && let Some(c) = cells.get(yy as usize * lw + xx as usize) + { + for ch in 0..4 { + acc[ch] += fr * c[ch] as f64; + } + } + } + } + } + *px = if acc[3] > 0.0 { std::array::from_fn(|c| (acc[c] / acc[3]) as f32) } else { [0.0; 3] }; + } + }); + out +} + +#[cfg(test)] +mod tests { + use super::*; + use lightcraft_develop::{MaskComponent, MaskOp}; + use lightcraft_geom::Point; + + /// Settings with the lens blur switched on at `amount`. + fn on(amount: f64) -> DevelopSettings { + let mut s = DevelopSettings::default(); + s.lens_blur.enabled = true; + s.lens_blur.amount = amount; + s + } + + /// A frame for a `w × h` source rendered at its own size. + fn frame(s: &DevelopSettings, w: usize, h: usize) -> Frame { + Frame::new(w, h, s, true) + } + + /// A radial mask around the centre (radius `r`, long-edge units). + fn centre_mask(id: u32, r: f64) -> Mask { + let mut m = Mask { id, ..Mask::default() }; + m.components.push(MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Radial { center: Point::new(0.5, 0.5), rx: r, ry: r, angle: 0.0, feather: 0.0, invert: false }, + }); + m + } + + /// A black image with one bright point at `(px, py)` and white stripes in the left third. + fn scene(w: usize, h: usize, px: usize, py: usize) -> Rgb32f { + let mut img = Rgb32f::from_fn(w, h, |x, _| if x < w / 3 && x % 4 < 2 { [0.6; 3] } else { [0.02; 3] }); + img.set(px, py, [4.0; 3]); + img + } + + /// On a 60 MP export, the strongest global and per-mask settings keep a fixed-size disc kernel + /// and every level's coarse grid within its cell budget, including an offset render window. + #[test] + fn large_image_blur_work_is_bounded() { + let (w, h) = (9500, 6316); + let long_edge = w.max(h) as f64; + let s = on(100.0); + let r = radius_px(&s, long_edge); + assert!((r - (MAX_RADIUS * long_edge) as f32).abs() < 1e-3); + + let mut mask = Mask::default(); + mask.adjust.lens_blur = 100.0; + assert!((mask_radius_px(&mask, long_edge) - r).abs() < 1e-3); + + let mut total_cells = 0usize; + for k in 1..=LEVELS { + let radius = r * k as f32 / LEVELS as f32; + let (f, _, lw, lh) = level_grid(w, h, radius, (17, 29)); + let cells = lw.saturating_mul(lh); + assert!(cells <= MAX_CELLS, "level {k}: {lw} × {lh} = {cells}"); + total_cells = total_cells.saturating_add(cells); + assert!(radius / f as f32 <= DISC_CELLS); + } + assert!(total_cells <= LEVELS * MAX_CELLS); + + let (_, _, lw, lh) = level_grid(w, h, r, (w - 1, h - 1)); + assert!(lw.saturating_mul(lh) <= MAX_CELLS, "offset window: {lw} × {lh}"); + } + + /// Switched off, at Amount 0 or with the section's eye closed, the photo is untouched. + #[test] + fn off_amount_zero_or_section_hidden_changes_nothing() { + let img = scene(64, 48, 50, 10); + for s in [DevelopSettings::default(), on(0.0), { + let mut s = on(80.0); + s.set_section_enabled("lensBlur", false); + s + }] { + let mut out = img.clone(); + apply(&mut out, &s, &frame(&s, 64, 48), 64.0, None); + assert_eq!(out, img); + assert_eq!(key(&s), ""); + } + } + + /// An out-of-focus point of light spreads into a disc of the expected radius and keeps its energy. + #[test] + fn out_of_focus_point_becomes_a_disc_and_keeps_its_energy() { + let (w, h) = (200, 200); + let mut s = on(100.0); + // in focus: a small disc in the middle; the point sits far outside it + s.masks.push(centre_mask(7, 0.05)); + s.lens_blur.focus_mask = Some(7); + let mut img = Rgb32f::filled(w, h, [0.0; 3]); + img.set(40, 40, [100.0; 3]); + let before: f32 = img.data.iter().map(|c| c[1]).sum(); + apply(&mut img, &s, &frame(&s, w, h), w as f64, None); + let r = radius_px(&s, w as f64); + assert!((r - 7.0).abs() < 1e-3, "{r}"); + // spread over a disc: inside it lit, well outside it dark, the centre no longer a spike + let at = |x: usize, y: usize| img.get(x, y)[1]; + assert!(at(40, 40) < 10.0, "{}", at(40, 40)); + for (x, y) in [(44, 40), (40, 36), (37, 43)] { + assert!(at(x, y) > 0.2, "({x}, {y}) {}", at(x, y)); + } + for (x, y) in [(52, 40), (40, 28), (50, 50)] { + assert!(at(x, y) < 0.05, "({x}, {y}) {}", at(x, y)); + } + let after: f32 = img.data.iter().map(|c| c[1]).sum(); + assert!((after - before).abs() / before < 0.15, "{before} → {after}"); + } + + /// What is in focus stays sharp, and its brightness doesn't bleed into the blurred background as a halo. + #[test] + fn the_focus_stays_sharp_and_does_not_bleed_into_the_background() { + let (w, h) = (160, 160); + let mut s = on(100.0); + s.masks.push(centre_mask(3, 0.2)); + s.lens_blur.focus_mask = Some(3); + // a bright subject filling the focus (a disc of 30 px; the focus is 32 px), grey stripes + // around it + let mut img = Rgb32f::from_fn(w, h, |x, y| { + let d = ((x as f32 + 0.5 - 80.0).powi(2) + (y as f32 + 0.5 - 80.0).powi(2)).sqrt(); + if d < 30.0 { + [2.0; 3] + } else if x % 4 < 2 { + [0.3; 3] + } else { + [0.1; 3] + } + }); + let src = img.clone(); + apply(&mut img, &s, &frame(&s, w, h), w as f64, None); + // the subject is untouched + assert_eq!(img.get(80, 80), src.get(80, 80)); + assert_eq!(img.get(60, 70), src.get(60, 70)); + // the background's stripes are smoothed out… + let row: Vec = (4..40).map(|x| img.get(x, 10)[1]).collect(); + let (lo, hi) = row.iter().fold((f32::MAX, f32::MIN), |(a, b), v| (a.min(*v), b.max(*v))); + assert!(hi - lo < 0.04, "{lo}..{hi}"); + // …to their mean, also 5 px from the bright subject (within the blur's reach): no halo + let near = img.get(45, 80)[1]; + assert!((near - 0.2).abs() < 0.04, "{near}"); + } + + /// Boost brightens the blurred highlights only: a mid-grey background stays as it is. + #[test] + fn boost_brightens_bokeh_only() { + let (w, h) = (120, 120); + let mut s = on(60.0); + s.masks.push(centre_mask(1, 0.05)); + s.lens_blur.focus_mask = Some(1); + let mut img = Rgb32f::filled(w, h, [0.1; 3]); + img.set(20, 20, [8.0; 3]); + let (mut plain, mut boosted) = (img.clone(), img.clone()); + apply(&mut plain, &s, &frame(&s, w, h), w as f64, None); + s.lens_blur.boost = 100.0; + apply(&mut boosted, &s, &frame(&s, w, h), w as f64, None); + assert!(boosted.get(22, 20)[0] > plain.get(22, 20)[0] * 2.0, "{} vs {}", boosted.get(22, 20)[0], plain.get(22, 20)[0]); + // a mid-grey background stays as it is + assert!((boosted.get(100, 100)[0] - plain.get(100, 100)[0]).abs() < 1e-4); + } + + /// A small preview and a full-size export blur alike (the radius is relative to the long edge). + #[test] + fn previews_and_exports_blur_alike() { + // the same photo at two sizes: the blur scales with the long edge + let s = on(100.0); + let big = scene(240, 180, 200, 30); + let small = Rgb32f::from_fn(120, 90, |x, y| { + let p = |dx, dy| big.get(2 * x + dx, 2 * y + dy); + let q = [p(0, 0), p(1, 0), p(0, 1), p(1, 1)]; + std::array::from_fn(|c| q.iter().map(|v| v[c]).sum::() / 4.0) + }); + let (mut a, mut b) = (big.clone(), small.clone()); + apply(&mut a, &s, &frame(&s, 240, 180), 240.0, None); + apply(&mut b, &s, &frame(&s, 120, 90), 120.0, None); + let mut diff = 0.0; + for y in 0..90 { + for x in 0..120 { + let d = a.get(2 * x, 2 * y)[1] - b.get(x, y)[1]; + diff += d.abs(); + } + } + let mean = diff / (120.0 * 90.0); + assert!(mean < 0.02, "{mean}"); + } + + /// Brush Refinement: a Focus stroke keeps what it covers sharp, a Blur stroke blurs what it + /// covers even inside the focus. + #[test] + fn focus_and_blur_brushes_refine_the_focus() { + let (w, h) = (160, 120); + let img = Rgb32f::from_fn(w, h, |x, _| if x % 4 < 2 { [0.3; 3] } else { [0.1; 3] }); + let mut s = on(100.0); + // in focus: the middle + s.masks.push(centre_mask(5, 0.15)); + s.lens_blur.focus_mask = Some(5); + let dab = |x: f64, y: f64| BrushStroke { points: vec![Point::new(x, y)], size: 0.08, feather: 0.0, ..BrushStroke::default() }; + // Focus brush on the top-left corner (out of focus otherwise), Blur brush on the centre + s.lens_blur.focus_strokes.push(dab(0.1, 0.12)); + s.lens_blur.blur_strokes.push(dab(0.5, 0.5)); + let mut out = img.clone(); + apply(&mut out, &s, &frame(&s, w, h), w as f64, None); + let stripes = |o: &Rgb32f, cx: usize, cy: usize| { + let v: Vec = (cx - 4..cx + 4).map(|x| o.get(x, cy)[1]).collect(); + v.iter().fold(f32::MIN, |a, b| a.max(*b)) - v.iter().fold(f32::MAX, |a, b| a.min(*b)) + }; + // the corner the Focus brush painted keeps its stripes; one it didn't is smooth + assert!(stripes(&out, 16, 14) > 0.15, "{}", stripes(&out, 16, 14)); + assert!(stripes(&out, 140, 100) < 0.05, "{}", stripes(&out, 140, 100)); + // the centre is in focus, but the Blur brush wins + assert!(stripes(&out, 80, 60) < 0.05, "{}", stripes(&out, 80, 60)); + // without the strokes, the centre stays sharp + let mut plain = s.clone(); + plain.lens_blur.focus_strokes.clear(); + plain.lens_blur.blur_strokes.clear(); + let mut out = img.clone(); + apply(&mut out, &plain, &frame(&plain, w, h), w as f64, None); + assert!(stripes(&out, 80, 60) > 0.15); + assert_ne!(key(&plain), key(&s)); + } + + /// Without a focus mask, a fixed shape keeps a circle, a wide or a tall oval sharp in the + /// middle: a wide one reaches farther sideways than up, a tall one the other way round. + #[test] + fn fixed_focus_shapes() { + use lightcraft_develop::FocusShape; + let (w, h) = (300, 300); + let s0 = on(100.0); + let fr = frame(&s0, w, h); + let img = Rgb32f::filled(w, h, [0.2; 3]); + let alpha = |shape: FocusShape| { + let mut s = s0.clone(); + s.lens_blur.shape = shape; + focus(&img, &s, &fr, None) + }; + // sideways and upwards from the centre, 0.2 of the long edge away + let side = |a: &Plane| a.get(150 + 60, 150); + let up = |a: &Plane| a.get(150, 150 - 60); + let (round, wide, tall) = (alpha(FocusShape::Round), alpha(FocusShape::Wide), alpha(FocusShape::Tall)); + for a in [&round, &wide, &tall] { + assert!(a.get(150, 150) > 0.99, "the middle is in focus"); + assert!(a.get(5, 5) < 0.01, "a corner isn't"); + } + assert!((side(&round) - up(&round)).abs() < 0.05); + assert!(side(&wide) > 0.9 && up(&wide) < 0.1, "{} {}", side(&wide), up(&wide)); + assert!(up(&tall) > 0.9 && side(&tall) < 0.1, "{} {}", side(&tall), up(&tall)); + // moved and resized: the area follows; hostile values are tamed + let mut s = s0.clone(); + s.lens_blur.shape = FocusShape::Round; + s.lens_blur.area = Some(lightcraft_develop::FocusArea { center: Point::new(0.2, 0.2), rx: 0.1, ry: 0.1 }); + let a = focus(&img, &s, &fr, None); + assert!(a.get(60, 60) > 0.99 && a.get(150, 150) < 0.01, "moved to the top left"); + s.lens_blur.area = Some(lightcraft_develop::FocusArea { center: Point::new(f64::NAN, 9e9), rx: f64::INFINITY, ry: -3.0 }); + let a = focus(&img, &s, &fr, None); + assert!(a.data.iter().all(|v| v.is_finite())); + // an unknown shape in the JSON reads as Auto (never an error) + let b: lightcraft_develop::LensBlur = serde_json::from_value(serde_json::json!({"shape": "hexagon"})).unwrap(); + assert_eq!(b.shape, FocusShape::Auto); + } + + /// With a Transition the blur grows with the distance from the focus, as a lens renders what + /// is near the subject: soft right beside it, full far away. At 0 it is a sharp cut. + #[test] + fn the_blur_grows_away_from_the_focus() { + let (w, h) = (400, 200); + // wide stripes: how much of them a blur leaves says how large it is + let img = Rgb32f::from_fn(w, h, |x, _| if (x / 12) % 2 == 0 { [0.3; 3] } else { [0.1; 3] }); + let mut s = on(100.0); + // in focus: a disc left of centre + let mut m = centre_mask(2, 0.08); + if let MaskShape::Radial { center, .. } = &mut m.components[0].shape { + *center = Point::new(0.2, 0.5); + } + s.masks.push(m); + s.lens_blur.focus_mask = Some(2); + // how much detail is left (stripe contrast) around x, on the middle row + let detail = |o: &Rgb32f, x: usize| { + let v: Vec = (x - 12..x + 12).map(|x| o.get(x, 100)[1]).collect(); + v.iter().fold(f32::MIN, |a, b| a.max(*b)) - v.iter().fold(f32::MAX, |a, b| a.min(*b)) + }; + let render = |t: f64| { + let mut s = s.clone(); + s.lens_blur.transition = t; + let mut o = img.clone(); + apply(&mut o, &s, &frame(&s, w, h), w as f64, None); + o + }; + let (soft, cut) = (render(100.0), render(0.0)); + // the focus disc ends at x ≈ 112 (the ramp is 60 px long): just past it, then farther + let (near, mid, far) = (detail(&soft, 130), detail(&soft, 150), detail(&soft, 330)); + assert!(near > mid + 0.02 && mid > far + 0.02, "{near} > {mid} > {far}"); + // a sharp cut blurs right beside the focus as much as far away + let cut_near = detail(&cut, 130); + assert!((cut_near - detail(&cut, 330)).abs() < 0.02 && near > cut_near + 0.05, "{cut_near} vs {near}"); + // the focus itself stays sharp either way + assert!(detail(&soft, 70) > 0.19 && detail(&cut, 70) > 0.19); + } + + /// A focus mask whose AI selection isn't computed yet (Find Subject still running) leaves the + /// subject estimate in focus: the photo is never blurred all over meanwhile. + #[test] + fn a_pending_ai_focus_mask_falls_back_to_the_subject_estimate() { + let (w, h) = (160, 120); + let img = Rgb32f::from_fn(w, h, |x, _| if x % 4 < 2 { [0.3; 3] } else { [0.1; 3] }); + let mut s = on(100.0); + let mut m = Mask { id: 9, ..Mask::default() }; + let pending = MaskShape::Object { hint: vec![], exclude: vec![], seg: None, detail: vec![], edge: 0.0 }; + m.components.push(MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: pending }); + assert!(awaiting_ai(&m)); + s.masks.push(m); + s.lens_blur.focus_mask = Some(9); + let mut subject = s.clone(); + subject.lens_blur.focus_mask = None; + let (mut a, mut b) = (img.clone(), img.clone()); + apply(&mut a, &s, &frame(&s, w, h), w as f64, None); + apply(&mut b, &subject, &frame(&subject, w, h), w as f64, None); + assert_eq!(a, b, "the same as no focus mask"); + // the middle (the estimate's subject) keeps its stripes + let v: Vec = (76..84).map(|x| a.get(x, 60)[1]).collect(); + assert!(v.iter().fold(f32::MIN, |p, q| p.max(*q)) - v.iter().fold(f32::MAX, |p, q| p.min(*q)) > 0.1, "{v:?}"); + } + + /// A mask with Lens Blur blurs what it selects and nothing else; hidden, it blurs nothing. + #[test] + fn a_mask_blurs_only_what_it_selects() { + let (w, h) = (160, 120); + // vertical stripes everywhere + let img = Rgb32f::from_fn(w, h, |x, _| if x % 4 < 2 { [0.3; 3] } else { [0.1; 3] }); + let mut s = DevelopSettings::default(); + // the left half (a linear gradient with a short ramp in the middle) + let mut m = Mask { id: 2, ..Mask::default() }; + m.components.push(MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Linear { start: Point::new(0.45, 0.5), end: Point::new(0.55, 0.5) }, + }); + m.adjust.lens_blur = 100.0; + s.masks.push(m); + assert!(renders(&s) && !active(&s) && !key(&s).is_empty()); + let mut out = img.clone(); + apply(&mut out, &s, &frame(&s, w, h), w as f64, None); + // left: the stripes are smoothed to their mean + let left: Vec = (8..50).map(|x| out.get(x, 60)[1]).collect(); + let (lo, hi) = left.iter().fold((f32::MAX, f32::MIN), |(a, b), v| (a.min(*v), b.max(*v))); + assert!(hi - lo < 0.05 && (lo + hi) / 2.0 > 0.15 && (lo + hi) / 2.0 < 0.25, "{lo}..{hi}"); + // right: untouched + for x in 100..150 { + assert_eq!(out.get(x, 60), img.get(x, 60), "x {x}"); + } + // the window grows by the mask's blur + let win = crate::PixelWindow { x: 60, y: 40, w: 20, h: 20 }; + assert!(window_for_reads(&s, w, h, w as f64, win).w > 20); + // hidden or at 0: nothing + for change in [|m: &mut Mask| m.visible = false, |m: &mut Mask| m.adjust.lens_blur = 0.0, |m: &mut Mask| m.adjust.lens_blur_off = true] { + let mut t = s.clone(); + change(&mut t.masks[0]); + let mut out = img.clone(); + apply(&mut out, &t, &frame(&t, w, h), w as f64, None); + assert_eq!(out, img); + assert!(!renders(&t) && key(&t).is_empty()); + } + } + + /// A mask's Lens Blur block can blur what the mask leaves out, and its Transition makes that + /// blur grow away from what stays sharp. + #[test] + fn a_mask_blurs_its_outside_gradually() { + let (w, h) = (320, 120); + let img = Rgb32f::from_fn(w, h, |x, _| if x % 4 < 2 { [0.3; 3] } else { [0.1; 3] }); + let mut s = DevelopSettings::default(); + // the left third selected + let mut m = Mask { id: 2, ..Mask::default() }; + m.components.push(MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Linear { start: Point::new(0.30, 0.5), end: Point::new(0.34, 0.5) }, + }); + m.adjust.lens_blur = 100.0; + m.adjust.lens_blur_outside = true; + s.masks.push(m); + // how much of the stripes is left around column x + let spread = |out: &Rgb32f, x: usize| { + let v: Vec = (x..x + 8).map(|x| out.get(x, 60)[1]).collect(); + v.iter().fold(f32::MIN, |a, b| a.max(*b)) - v.iter().fold(f32::MAX, |a, b| a.min(*b)) + }; + let mut sharp_cut = img.clone(); + apply(&mut sharp_cut, &s, &frame(&s, w, h), w as f64, None); + // the selection stays sharp, the rest is blurred + for x in 8..80 { + assert_eq!(sharp_cut.get(x, 60), img.get(x, 60), "x {x}"); + } + assert!(spread(&sharp_cut, 150) < 0.05 && spread(&sharp_cut, 290) < 0.05); + // with a Transition, near the selection keeps more of the stripes than far from it + s.masks[0].adjust.lens_blur_transition = 100.0; + s.masks[0].adjust.lens_blur_boost = 50.0; + let mut gradual = img.clone(); + apply(&mut gradual, &s, &frame(&s, w, h), w as f64, None); + assert!(spread(&gradual, 112) > spread(&sharp_cut, 112) + 0.02, "{} vs {}", spread(&gradual, 112), spread(&sharp_cut, 112)); + assert!(spread(&gradual, 112) > spread(&gradual, 290), "{} vs {}", spread(&gradual, 112), spread(&gradual, 290)); + // the window reads farther with the transition + let win = crate::PixelWindow { x: 200, y: 40, w: 20, h: 20 }; + let mut no_t = s.clone(); + no_t.masks[0].adjust.lens_blur_transition = 0.0; + assert!(window_for_reads(&s, w, h, w as f64, win).w > window_for_reads(&no_t, w, h, w as f64, win).w); + // at Amount 0 the outside isn't blurred either + s.masks[0].adjust.amount = 0.0; + let mut out = img.clone(); + apply(&mut out, &s, &frame(&s, w, h), w as f64, None); + assert_eq!(out, img); + // hostile values + s.masks[0].adjust.amount = f64::NAN; + s.masks[0].adjust.lens_blur_transition = f64::INFINITY; + s.masks[0].adjust.lens_blur_boost = f64::NAN; + let mut out = img.clone(); + apply(&mut out, &s, &frame(&s, w, h), w as f64, None); + assert!(out.data.iter().all(|p| p.iter().all(|v| v.is_finite()))); + } + + /// The subject point lands on a person matte when the photo carries one, and is always inside + /// the photo; an empty source has none. + #[test] + fn subject_point_finds_the_person_matte() { + use crate::masks::{MatteKind, Mattes}; + let s = DevelopSettings::default(); + let src = Rgb32f::filled(300, 200, [0.2; 3]); + // a person in the top-right corner, far from the centre the heuristic favours + let mut person = lightcraft_raster::Image::::new(300, 200); + for y in 10..60 { + for x in 220..290 { + person.set(x, y, 255); + } + } + let mut mattes = Mattes::default(); + mattes.push(MatteKind::Person, person); + let p = subject_point(&src, &s, Some(&mattes)).unwrap(); + assert!(p.x > 0.72 && p.x < 0.97 && p.y > 0.04 && p.y < 0.3, "{p:?}"); + // without mattes: somewhere in the photo (the heuristic's centre-weighted peak) + let p = subject_point(&src, &s, None).unwrap(); + assert!((0.0..=1.0).contains(&p.x) && (0.0..=1.0).contains(&p.y), "{p:?}"); + assert!(subject_point(&Rgb32f::new(0, 0), &s, None).is_none()); + } + + /// Hostile settings and images: no panic, no NaN. + #[test] + fn hostile_input_never_panics() { + for amount in [f64::NAN, f64::INFINITY, -5.0, 1e9] { + let mut s = on(amount); + s.lens_blur.boost = f64::NAN; + s.lens_blur.focus_mask = Some(99); + for (w, h) in [(1, 1), (1, 7), (9, 1), (33, 5)] { + let mut img = Rgb32f::filled(w, h, [0.5, f32::NAN, f32::INFINITY]); + apply(&mut img, &s, &frame(&s, w, h), 1e6, None); + let mut img = Rgb32f::filled(w, h, [0.5; 3]); + apply(&mut img, &s, &frame(&s, w, h), w.max(h) as f64, None); + assert!(img.data.iter().flatten().all(|v| v.is_finite()), "{amount} {w}×{h}"); + } + } + // a mismatched buffer is left alone + let s = on(50.0); + let mut img = Rgb32f { width: 10, height: 10, data: vec![[0.5; 3]; 7] }; + apply(&mut img, &s, &frame(&s, 10, 10), 10.0, None); + assert_eq!(img.data.len(), 7); + } +} diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index d8835f4ef1..ef2d2359ca 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -26,11 +26,13 @@ pub mod auto; pub mod blemish; pub mod colorops; +pub mod crystal; pub mod cull; pub mod curve; pub mod dust; pub mod finish; pub mod geometry; +pub mod lens_blur; pub mod light_v3; // generated (`light_v3_params.rs`), kept in its own compact layout #[rustfmt::skip] @@ -443,6 +445,8 @@ pub struct Plan<'a> { pub keep: Option, /// The source's segmentation mattes ([`SourceInfo::mattes`]). pub mattes: Option>, + /// The whole photo's subject estimate a lens blur focuses on ([`lens_blur::subject_estimate`]). + pub lens_subject: Option>, /// The whole frame and its output size (a windowed render's [`Self::frame`] is part of it). pub full: (geometry::Frame, usize, usize), } @@ -486,8 +490,10 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R let (pw, ph) = (((full_w as f64 * k).round() as usize).max(1), ((full_h as f64 * k).round() as usize).max(1)); fixed_air = Some(local::frame_airlight(src, info, s, &frame, pw, ph)); } - // (spots grow the rendered window of 8-bit renders; a grown window is cut back to the request) - let mut work = if req.depth == OutputDepth::U8 { spots::window_for_reads(s, &frame, full_w, full_h, px_per_long, win) } else { win }; + // (spots grow the rendered window of 8-bit renders, the lens blur that of every + // render; a grown window is cut back to the request) + let work = if req.depth == OutputDepth::U8 { spots::window_for_reads(s, &frame, full_w, full_h, px_per_long, win) } else { win }; + let mut work = lens_blur::window_for_reads(s, full_w, full_h, px_per_long, work); if local::joint_colour_nr(s) && let Some(params) = local::nrc_params(s, detail_scale) { @@ -521,6 +527,8 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R // and the local tone mapping local_tone::enabled(info, s), src_long, + // and the lens blur (after noise reduction, but a draft must not reuse planes without it) + lens_blur::key(s), )); let lin_key = hash_of(( pre_nr_key, @@ -529,6 +537,7 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R // the process picks the colour filter (Update to Current Process, undo) local::joint_colour_nr(s), )); + let lens_subject = lens_blur::subject_estimate(src, s, info.mattes.as_deref()).map(Arc::new); let noise_key = hash_of((pre_nr_key, [d.nr_luminance, d.nr_detail].map(f64::to_bits), detail_scale.to_bits())); Plan { settings, @@ -547,6 +556,7 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R fixed_air, keep, mattes: info.mattes.clone(), + lens_subject, full, } } @@ -584,6 +594,7 @@ pub fn colour_noise(src: &Rgb32f, info: &SourceInfo, p: &Plan<'_>) -> Option, info: &SourceInfo, s: &DevelopSettings, req: &Rende colour_noise = self::colour_noise(src_img, info, &plan).map(|n| (plan.noise_key, n)); } local::denoise(&mut img, s, detail_scale, colour_noise.as_ref().map(|c| &c.1)); + lens_blur::apply_with(&mut img, s, frame, px_per_long, plan.mattes.as_deref(), plan.lens_subject.as_deref()); Arc::new(img) } }; @@ -743,7 +755,7 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende c.put(CacheEntry { src: a.clone(), geo, sampled, lin: Some((lin_key, lin)), colour_noise, planes }); } if req.depth != OutputDepth::U8 { - let deep = finish::finish_deep(&prep, s, frame, info, req.space, req.depth, req.proof); + let deep = finish::finish_deep(&prep, s, frame, info, req); let deep = match plan.keep { Some(k) => deep.crop(k.x, k.y, k.w, k.h), None => deep, @@ -753,7 +765,7 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende lap("finish (deep)", &mut t); return Rendered { image, histogram, deep: Some(deep) }; } - let image = finish::finish(&prep, s, frame, info, req.space, req.display.as_ref(), req.proof); + let image = finish::finish(&prep, s, frame, info, req); lap("finish", &mut t); let cut = |i: &Rgba8| match plan.keep { Some(k) => i.crop(k.x, k.y, k.w, k.h), @@ -905,6 +917,8 @@ mod tests; #[cfg(test)] mod tests_geometry; #[cfg(test)] +mod tests_grain; +#[cfg(test)] mod tests_hdr; #[cfg(test)] mod tests_legacy; diff --git a/crates/pipeline/src/light_v3.rs b/crates/pipeline/src/light_v3.rs index 394c7c0829..5f3e0f9bf2 100644 --- a/crates/pipeline/src/light_v3.rs +++ b/crates/pipeline/src/light_v3.rs @@ -284,7 +284,7 @@ pub fn applies(s: &DevelopSettings, info: &SourceInfo) -> bool { let camera_look = info.raw && info.camera_tone.is_some(); match s.process.process() { Process::V1 | Process::V2 | Process::V3 => false, - Process::V4 | Process::V5 | Process::V6 => camera_look, + Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 => camera_look, } } diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index debb5e8db6..749e10139d 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -357,7 +357,7 @@ fn transpose(p: &Plane) -> Plane { } /// Detail scale of the highlights/shadows base from process V2, as a fraction of the long edge: -/// the base is the edge-aware filter of the [`median_hv`] of log luminance at this radius, so +/// the base is the edge-aware filter of log luminance without its detail at this radius, so /// twigs, lines and fine texture brighter or darker than their surroundings take their /// surroundings' shift (and keep their contrast, as with Exposure) while region boundaries stay /// sharp (no halos). V1's base is the edge-aware filter of log luminance itself (issue #632). @@ -375,17 +375,76 @@ pub fn base_detail_radius(px_per_long: f64) -> usize { pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize { match s.process.process() { Process::V1 => 0, - Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 => base_detail_radius(px_per_long), + Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 => base_detail_radius(px_per_long), } } /// The highlights/shadows base layer of log luminance `l`: the fast guided filter ([`BASE_EPS`]) -/// of its [`median_hv`] at `detail` px ([`tone_base_detail`]); at 0, of `l` itself (V1). -pub fn tone_base(l: &Plane, sigma: f32, detail: usize) -> Plane { +/// at `detail` px ([`tone_base_detail`]) of its [`detail_free`] plane when `keeps_gaps` +/// ([`base_keeps_gaps`], V8 on), else of its [`median_hv`] (V2 to V7); at 0, of `l` itself (V1). +pub fn tone_base(l: &Plane, sigma: f32, detail: usize, keeps_gaps: bool) -> Plane { if detail == 0 { return guided_fast(l, sigma, BASE_EPS); } - guided_fast(&median_hv(l, detail), sigma, BASE_EPS) + let m = if keeps_gaps { detail_free(l, detail) } else { median_hv(l, detail) }; + guided_fast(&m, sigma, BASE_EPS) +} + +/// Downscale factor of the coarse median in [`detail_free`]: its radius at full size is this many +/// times the fine one's. +pub const BASE_COARSE_STEP: usize = 3; + +/// Log luminance `l` without detail finer than `r` px (the highlights/shadows base of process V8 +/// on takes its edge-aware filter): each value moves toward its [`median_hv`] at `r` only as far as the +/// median of a [`BASE_COARSE_STEP`]× wider neighbourhood agrees (`l` clamped between the two). +/// A twig, line or speck in an even surround has both medians on the surround's side and takes +/// its tone, as #632 wants. The gap between two letter strokes, which a median at `r` fills with the +/// strokes' tone, sits in a wider neighbourhood mostly of the panel's tone: the two medians +/// disagree and the gap keeps its own. The coarse median is taken at `r` of a box-downscaled copy and +/// enlarged bilinearly, like [`guided_fast`]'s coefficients. +pub fn detail_free(l: &Plane, r: usize) -> Plane { + use lightcraft_raster::resample::{Filter, resize}; + if r == 0 || l.data.is_empty() { + return l.clone(); + } + let (w, h) = (l.width, l.height); + let (lw, lh) = (w.div_ceil(BASE_COARSE_STEP).max(1), h.div_ceil(BASE_COARSE_STEP).max(1)); + if (lw, lh) == (w, h) { + // nothing to downscale: both medians are the same + return median_hv(l, r); + } + let lo = median_hv(&resize(l, lw, lh, Filter::Box), r); + // The bilinear enlargement of `lo` (`resize`'s horizontal pass, then its vertical pass taken + // row by row with the same sums) is clamped into `out` as it is made, not stored. + let wide = resize(&lo, w, lh, Filter::Bilinear); + let wy = lightcraft_raster::resample::weights(lh, h, Filter::Bilinear); + let mut out = median_hv(l, r); + for_rows(&mut out.data, w, |y, row| { + let Some((y0, ws)) = wy.get(y) else { return }; + let mut coarse = vec![0.0f32; w]; + for (k, &wt) in ws.iter().enumerate() { + let Some(t) = wide.data.get((y0 + k) * w..(y0 + k + 1) * w) else { continue }; + for (c, &v) in coarse.iter_mut().zip(t) { + *c += v * wt; + } + } + for ((o, &v), &c) in row.iter_mut().zip(l.row(y)).zip(&coarse) { + *o = clamp_between(v, *o, c); + } + }); + out +} + +/// `v` clamped between `a` and `b` (in either order); a NaN bound is ignored, not a panic. +fn clamp_between(v: f32, a: f32, b: f32) -> f32 { + let (lo, hi) = (a.min(b), a.max(b)); + if v < lo { + lo + } else if v > hi { + hi + } else { + v + } } /// Subsampling step of [`guided_fast`] for `sigma` (1 = no subsampling: the plain guided filter). @@ -638,6 +697,12 @@ pub fn sharpen_key(s: &DevelopSettings, sigma: f32) -> SharpenKey { (sigma.to_bits(), s.process.process()) } +/// Whether `s`'s highlights/shadows base takes [`detail_free`] (process V8 on) instead of V2's plain +/// [`median_hv`] (V2 to V7, which shipped with it and stay frozen). +pub fn base_keeps_gaps(s: &DevelopSettings) -> bool { + s.process.process() >= Process::V8 +} + pub fn pixel_sharpen(s: &DevelopSettings) -> bool { s.process.process() >= Process::V3 } @@ -677,7 +742,7 @@ pub const CHROMA_SIGMA: f32 = 0.004; #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct PlaneSigmas { /// Edge-aware base for highlights/shadows ([`tone_base`]: fast guided filter, [`BASE_EPS`]; from - /// process V2 of the [`BASE_DETAIL`] median). + /// process V2 of a median at [`BASE_DETAIL`], from V8 of a detail-free plane). pub base: Option, /// Median radius (px) of that base ([`tone_base_detail`]: 0 under V1). pub base_detail: usize, @@ -806,7 +871,7 @@ pub(crate) fn prepare( }); let l = &log_l; let (base, (clarity_blur, ((texture_blur, sharpen_blur), dark))) = par_join( - || base_sigma.map(|sg| plane_at(sb, base_key(s, sg, base_detail), || timed("base", || tone_base(l, sg, base_detail)))), + || base_sigma.map(|sg| plane_at(sb, base_key(s, sg, base_detail), || timed("base", || tone_base(l, sg, base_detail, base_keeps_gaps(s))))), || { par_join( || clarity_sigma.map(|sg| plane_at(sc, sg.to_bits(), || timed("clarity", || guided_fast(l, sg, CLARITY_EPS)))), @@ -1309,6 +1374,50 @@ mod tests { mod fast_tests { use super::*; + /// [`detail_free`] enlarges the coarse median as it clamps; the result is the plain + /// composition of `resize` and [`median_hv`], bit for bit. + #[test] + fn detail_free_matches_its_reference() { + use lightcraft_raster::resample::{Filter, resize}; + for (w, h) in [(1, 1), (2, 1), (3, 3), (4, 7), (61, 47), (200, 31)] { + let p = Plane::from_fn(w, h, |x, y| ((x * 37 + y * 101) % 23) as f32 * 0.4 - 4.0 + if (x / 5 + y / 7) % 2 == 0 { 2.0 } else { 0.0 }); + for r in [1, 2, 5, 10] { + let fine = median_hv(&p, r); + let (lw, lh) = (w.div_ceil(BASE_COARSE_STEP), h.div_ceil(BASE_COARSE_STEP)); + let coarse = resize(&median_hv(&resize(&p, lw, lh, Filter::Box), r), w, h, Filter::Bilinear); + let want: Vec = (0..w * h).map(|i| clamp_between(p.data[i], fine.data[i], coarse.data[i]).to_bits()).collect(); + let got: Vec = detail_free(&p, r).data.iter().map(|v| v.to_bits()).collect(); + assert_eq!(got, want, "{w}×{h} r={r}"); + } + } + } + + /// CPU highlights/shadows base timings on the #3460 frame size: + /// `cargo test --release -p lightcraft-pipeline bench_tone_base_cpu -- --ignored --nocapture`. + #[test] + #[ignore] + fn bench_tone_base_cpu() { + let (w, h) = (6960, 4640); + let r = base_detail_radius(w as f64); + let p = Plane::from_fn(w, h, |x, y| ((x * 7 + y * 13) % 1000) as f32 / 250.0 - 6.0 + if (x / 40 + y / 40) % 2 == 0 { 1.0 } else { 0.0 }); + let sigma = 0.015 * w as f32; + let time = |name: &str, f: &dyn Fn() -> Plane| { + let mut ts: Vec = (0..5) + .map(|_| { + let t = std::time::Instant::now(); + std::hint::black_box(f()); + t.elapsed().as_secs_f64() * 1e3 + }) + .collect(); + ts.sort_by(f64::total_cmp); + eprintln!("{name:<20} min {:.1} ms median {:.1} ms", ts[0], ts[2]); + }; + time("median_hv", &|| median_hv(&p, r)); + time("detail_free", &|| detail_free(&p, r)); + time("guided_fast", &|| guided_fast(&p, sigma, BASE_EPS)); + time("tone_base", &|| tone_base(&p, sigma, r, true)); + } + /// The previous fast path, including its two materialized coefficient resizes. fn resized_reference(p: &Plane, sigma: f32, eps: f32) -> Plane { use lightcraft_raster::resample::{Filter, resize}; @@ -1353,12 +1462,12 @@ mod fast_tests { } #[test] - fn sampled_tone_base_keeps_the_median_before_the_guided_filter() { + fn sampled_tone_base_keeps_the_detail_free_plane_before_the_guided_filter() { let p = Plane::from_fn(73, 51, |x, y| if x % 9 == 0 { 3.0 } else { -4.0 + ((x + y) % 7) as f32 * 0.03 }); for sigma in [6.0, 24.0, 120.0] { for detail in [0, 1, 3, BASE_DETAIL_MAX] { - let median = median_hv(&p, detail); - assert_eq!(tone_base(&p, sigma, detail).data, resized_reference(&median, sigma, BASE_EPS).data, "{sigma}, {detail}"); + let free = detail_free(&p, detail); + assert_eq!(tone_base(&p, sigma, detail, true).data, resized_reference(&free, sigma, BASE_EPS).data, "{sigma}, {detail}"); } } } diff --git a/crates/pipeline/src/masks.rs b/crates/pipeline/src/masks.rs index b40e3dcd97..dfbf00326a 100644 --- a/crates/pipeline/src/masks.rs +++ b/crates/pipeline/src/masks.rs @@ -93,6 +93,12 @@ impl Mattes { self.mattes.iter().filter(|(k, _)| kinds.contains(k)).map(|(_, m)| m).collect() } + /// Whether a mask of the photo's Subject comes from these mattes (a person, or a person's + /// parts) rather than from the saliency heuristic. + pub fn selects_subject(&self) -> bool { + !self.for_shape(&MaskShape::Subject).is_empty() + } + /// The mattes a shape uses instead of its heuristic (empty: none fits). fn for_shape(&self, shape: &MaskShape) -> Vec<&Image> { use MatteKind::*; diff --git a/crates/pipeline/src/output.rs b/crates/pipeline/src/output.rs index b514c25503..c3fa176eb6 100644 --- a/crates/pipeline/src/output.rs +++ b/crates/pipeline/src/output.rs @@ -346,6 +346,30 @@ pub struct DeepImage { } impl DeepImage { + /// The `w × h` part of the image at (`x`, `y`), clamped to the image (at least 1 × 1 when the + /// image has pixels). Samples are RGB, three per pixel, row-major. + pub fn crop(&self, x: usize, y: usize, w: usize, h: usize) -> DeepImage { + let x = x.min(self.width.saturating_sub(1)); + let y = y.min(self.height.saturating_sub(1)); + let w = w.min(self.width.saturating_sub(x)).max(usize::from(self.width > 0)); + let h = h.min(self.height.saturating_sub(y)).max(usize::from(self.height > 0)); + fn cut(v: &[T], width: usize, x: usize, y: usize, w: usize, h: usize) -> Vec { + let mut out = Vec::with_capacity(w.saturating_mul(h).saturating_mul(3)); + for row in y..y + h { + let start = row.saturating_mul(width).saturating_add(x).saturating_mul(3); + if let Some(r) = v.get(start..start.saturating_add(w * 3)) { + out.extend_from_slice(r); + } + } + out + } + let samples = match &self.samples { + DeepSamples::U16(v) => DeepSamples::U16(cut(v, self.width, x, y, w, h)), + DeepSamples::F32(v) => DeepSamples::F32(cut(v, self.width, x, y, w, h)), + }; + DeepImage { width: w, height: h, space: self.space, samples } + } + /// The same image reduced to 8 bits, display-encoded with the space's curve. pub fn to_rgba8(&self) -> lightcraft_raster::Rgba8 { let mut out = lightcraft_raster::Rgba8::new(self.width, self.height); @@ -364,27 +388,6 @@ impl DeepImage { } out } - - /// Crop to `[x0, x0+w) × [y0, y0+h)` (clamped to the image). - pub fn crop(&self, x0: usize, y0: usize, w: usize, h: usize) -> Self { - let x0 = x0.min(self.width); - let y0 = y0.min(self.height); - let w = w.min(self.width - x0); - let h = h.min(self.height - y0); - fn rows(v: &[T], width: usize, x0: usize, y0: usize, w: usize, h: usize) -> Vec { - let mut out = Vec::with_capacity(3 * w * h); - for y in y0..y0 + h { - let at = 3 * (y * width + x0); - out.extend_from_slice(v.get(at..at + 3 * w).unwrap_or_default()); - } - out - } - let samples = match &self.samples { - DeepSamples::U16(v) => DeepSamples::U16(rows(v, self.width, x0, y0, w, h)), - DeepSamples::F32(v) => DeepSamples::F32(rows(v, self.width, x0, y0, w, h)), - }; - Self { width: w, height: h, space: self.space, samples } - } } trait IntoRgba { @@ -401,6 +404,23 @@ impl IntoRgba for [u8; 3] { mod tests { use super::*; + /// A crop keeps the right pixels and never reads past the image, whatever the request. + #[test] + fn deep_crop_keeps_the_window_and_clamps() { + // 4 × 3, pixel (x, y) holds x + 10 y in every channel + let v: Vec = (0..3).flat_map(|y| (0..4).flat_map(move |x| [x + 10 * y; 3])).collect(); + let d = DeepImage { width: 4, height: 3, space: OutputSpace::Srgb, samples: DeepSamples::U16(v) }; + let c = d.crop(1, 1, 2, 2); + assert_eq!((c.width, c.height), (2, 2)); + assert_eq!(c.samples, DeepSamples::U16(vec![11, 11, 11, 12, 12, 12, 21, 21, 21, 22, 22, 22])); + for (x, y, w, h) in [(9, 9, 5, 5), (0, 0, usize::MAX, usize::MAX), (3, 2, 0, 0)] { + let c = d.crop(x, y, w, h); + let DeepSamples::U16(s) = &c.samples else { panic!("a U16 image crops to U16") }; + assert!(c.width >= 1 && c.height >= 1 && c.width <= 4 && c.height <= 3); + assert_eq!(s.len(), c.width * c.height * 3, "{x} {y} {w} {h}"); + } + } + #[test] fn trcs_invert() { for o in OutputSpace::ALL { diff --git a/crates/pipeline/src/tests_crystal.rs b/crates/pipeline/src/tests_crystal.rs new file mode 100644 index 0000000000..b784f219a8 --- /dev/null +++ b/crates/pipeline/src/tests_crystal.rs @@ -0,0 +1,661 @@ +use super::*; + +/// The draws [`hold_for_waiters`] holds, by cache: how many renders wait for each, and how many +/// draws are left to hold. +static HOLDS: Mutex> = Mutex::new(Vec::new()); + +/// Holds the draw of `d` until the renders [`HOLDS`] names for its cache are waiting for it (each +/// holds a clone of its slot, as do the drawing and its in-flight entry), so a test can make +/// renders miss a tile together. +pub(super) fn hold_for_waiters(d: &Drawing) { + let waiters = { + let mut holds = HOLDS.lock().unwrap_or_else(PoisonError::into_inner); + let Some(h) = holds.iter_mut().find(|h| h.0 == d.id.0 && h.2 > 0) else { return }; + h.2 -= 1; + h.1 + }; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while Arc::strong_count(&d.done) < 2 + waiters { + assert!(std::time::Instant::now() < deadline, "the renders never waited"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + +/// The caches [`evict_before_waking`] empties. +static EVICTS: Mutex> = Mutex::new(Vec::new()); + +/// Empties `cache` if [`EVICTS`] names it, after its drawer `d` has cached its tile and before it +/// wakes the renders waiting for it, as other renders' tiles can push it out in that gap. +pub(super) fn evict_before_waking(cache: &Cache, d: &Drawing) { + if EVICTS.lock().unwrap_or_else(PoisonError::into_inner).contains(&d.id.0) { + cache.lock().unwrap_or_else(PoisonError::into_inner).clear(); + } +} + +/// Waits until `n` renders wait for the draw of `d`. +fn until_waiting(d: &Drawing, n: usize) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while Arc::strong_count(&d.done) < 2 + n { + assert!(std::time::Instant::now() < deadline, "the renders never waited"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + +/// The field rendered at `long` px per long edge on an `n × n` patch starting at pixel `origin`. +fn patch(tile: &CrystalTile, long: f64, n: usize, origin: usize) -> Vec { + let w = (TILE_PER_LONG / long) as f32; + (0..n * n).map(|k| tile.field(((origin + k % n) as f32 + 0.5) * w, ((origin + k / n) as f32 + 0.5) * w, w)).collect() +} + +fn std(v: &[f32]) -> f64 { + let m = v.iter().map(|&x| x as f64).sum::() / v.len() as f64; + (v.iter().map(|&x| (x as f64 - m).powi(2)).sum::() / v.len() as f64).sqrt() +} + +/// Lag (px) at which the autocorrelation (mean of horizontal and vertical) falls to ½. +fn half_width(v: &[f32], n: usize) -> f64 { + let m = v.iter().map(|&x| x as f64).sum::() / v.len() as f64; + let d: Vec = v.iter().map(|&x| x as f64 - m).collect(); + let var = d.iter().map(|x| x * x).sum::() / d.len() as f64; + let corr = |k: usize, horizontal: bool| { + let mut s = 0.0; + let mut c = 0usize; + for y in 0..n - if horizontal { 0 } else { k } { + for x in 0..n - if horizontal { k } else { 0 } { + let b = if horizontal { y * n + x + k } else { (y + k) * n + x }; + s += d[y * n + x] * d[b]; + c += 1; + } + } + s / c as f64 / var + }; + let mut out = 0.0; + for horizontal in [true, false] { + let mut prev = 1.0; + let mut w = 16.0; + for k in 1..16 { + let c = corr(k, horizontal); + if c <= 0.5 { + w = k as f64 - 1.0 + (prev - 0.5) / (prev - c).max(1e-9); + break; + } + prev = c; + } + out += w / 2.0; + } + out +} + +fn tile_of(size: f64, roughness: f64) -> Arc { + tile(CrystalLook::new(size, roughness), 7, true).expect("a tile") +} + +#[test] +fn reference_render_has_unit_variance_and_no_mean() { + let t = tile_of(25.0, 50.0); + let v = patch(&t, REF_LONG, 600, 37); + let m = v.iter().map(|&x| x as f64).sum::() / v.len() as f64; + assert!((std(&v) - 1.0).abs() < 0.05, "std {}", std(&v)); + assert!(m.abs() < 0.03, "mean {m}"); +} + +#[test] +fn small_render_is_the_downscaled_reference() { + for (size, rough) in [(0.0, 50.0), (25.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0)] { + let t = tile_of(size, rough); + for k in [2usize, 4, 8] { + let full = patch(&t, REF_LONG, 120 * k, 0); + let n = 120; + let down: Vec = (0..n * n) + .map(|q| { + let (x, y) = (q % n, q / n); + let mut s = 0.0; + for dy in 0..k { + for dx in 0..k { + s += full[(y * k + dy) * n * k + x * k + dx]; + } + } + s / (k * k) as f32 + }) + .collect(); + let small = patch(&t, REF_LONG / k as f64, n, 0); + let worst = down.iter().zip(&small).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + assert!(worst < 2e-3, "size {size} roughness {rough} 1/{k}: differs by {worst}"); + } + } +} + +#[test] +fn strength_matches_the_target_at_mid_grey() { + for (a, s, r) in [(50.0, 25.0, 50.0), (25.0, 25.0, 50.0), (50.0, 0.0, 50.0), (50.0, 100.0, 50.0), (50.0, 25.0, 0.0)] { + let g = CrystalGrain::new(&Grain { amount: a, size: s, roughness: r, seed: 3 }, REF_LONG).expect("grain"); + let n = 500; + let lum: Vec = (0..n * n) + .map(|k| { + let (x, y) = ((k % n) as f32 + 0.5, (k / n) as f32 + 0.5); + let e = g.apply([MID_GREY; 3], x / REF_LONG as f32, y / REF_LONG as f32); + (0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]) * 255.0 + }) + .collect(); + let want = strength_levels(a, s, r); + assert!((std(&lum) / want - 1.0).abs() < 0.06, "{a}/{s}/{r}: {} levels, want {want}", std(&lum)); + } +} + +#[test] +fn tones_keep_their_mean() { + // the strongest settings in the shadows; near white, strong grain clips at 255 like any grain + let cases = [ + (100.0, 0.0, &[5.0f32, 20.0, 40.0, 60.0, 128.0, 255.0][..]), + (50.0, 0.0, &[200.0, 245.0][..]), + (50.0, 25.0, &[20.0, 128.0, 245.0, 255.0][..]), + ]; + for (amount, size, levels) in cases { + let g = CrystalGrain::new(&Grain { amount, size, roughness: 50.0, seed: 3 }, REF_LONG).expect("grain"); + for &level in levels { + let n = 400; + let mut sum = 0.0f64; + for k in 0..n * n { + let (x, y) = ((k % n) as f32 + 0.5, (k / n) as f32 + 0.5); + let e = g.apply([level / 255.0; 3], x / REF_LONG as f32, y / REF_LONG as f32); + sum += (e[1].clamp(0.0, 1.0) * 255.0) as f64; + } + let shift = sum / (n * n) as f64 - level as f64; + assert!(shift.abs() < 0.5, "{amount}/{size}: level {level} moved {shift:+.2}"); + } + } +} + +#[test] +fn hostile_settings_render_finite_or_no_grain() { + let bad = [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1e9, 1e9, 0.0]; + for &a in &bad { + for &s in &bad { + for &ppl in &[f64::NAN, 0.0, -5.0, 1.0, 24.0, 1e12, 6000.0] { + let g = Grain { amount: if a == 0.0 { 50.0 } else { a }, size: s, roughness: s, seed: u32::MAX }; + if let Some(c) = CrystalGrain::new(&g, ppl) { + for (x, y) in [(0.0, 0.0), (-3.5, 1e7), (f32::NAN, 0.2), (0.5, f32::INFINITY), (1.0, 0.6667)] { + let e = c.apply([0.5, 0.2, 0.9], x, y); + assert!(e.iter().all(|v| v.is_finite()), "{g:?} at {ppl}: {e:?}"); + } + } + } + } + } +} + +#[test] +fn seed_picks_the_pattern() { + let look = CrystalLook::new(25.0, 50.0); + let (Some(a), Some(c)) = (tile(look, 1, true), tile(look, 2, true)) else { panic!("tiles") }; + assert_ne!(patch(&a, REF_LONG, 64, 0), patch(&c, REF_LONG, 64, 0)); +} + +/// A tile drawn again (its cache entry evicted, another process, an export after a preview) is the +/// same to the bit, however many threads draw it. These draw directly: through [`tile`], the second +/// would be the first one out of the cache. +#[test] +fn a_tile_draws_the_same_every_time() { + let look = CrystalLook::new(25.0, 50.0); + let one_thread = rayon::ThreadPoolBuilder::new().num_threads(1).build().expect("a pool"); + let (Some(a), Some(b)) = (CrystalTile::new(look, 1), one_thread.install(|| CrystalTile::new(look, 1))) else { panic!("tiles") }; + assert!(a.sats == b.sats, "the same seed drew different tiles"); +} + +/// Every seed has the same mix of crystal sizes, dealt to the layers in its own order. +#[test] +fn seeds_share_the_mix_of_crystal_sizes() { + let look = CrystalLook::new(50.0, 80.0); + let radii = |seed| emulsion(seed, &look).iter().map(|l| l.r).collect::>(); + let sorted = |mut v: Vec| { + v.sort_by(f64::total_cmp); + v + }; + let (a, b) = (radii(1), radii(2)); + assert_eq!(a.len(), look.layers); + assert_eq!(a, radii(1), "the same seed deals the same order"); + assert_ne!(a, b, "another seed deals another order"); + assert_eq!(sorted(a), sorted(b)); + assert_eq!(emulsion(1, &CrystalLook { layers: 0, ..look }).len(), 1, "an emulsion has a layer"); +} + +#[test] +fn sliders_clamp_and_fall_back() { + let look = CrystalLook::new; + assert_eq!(look(f64::NAN, f64::NAN), look(25.0, 50.0), "NaN is the default"); + assert_eq!(look(-1e9, f64::NEG_INFINITY), look(0.0, 0.0)); + assert_eq!(look(1e9, f64::INFINITY), look(100.0, 100.0)); + // the ends of the tables + assert_eq!((look(0.0, 50.0).width, look(0.0, 50.0).layers), (0.55, 16)); + assert_eq!((look(100.0, 50.0).width, look(100.0, 50.0).layers), (12.38, 70)); + assert_eq!(look(100.0, 0.0).width, 12.38 * 0.734); + assert_eq!(look(100.0, 100.0).width, 12.38 * 1.422); + assert!(look(25.0, 100.0).spread > look(25.0, 0.0).spread); + + let default = strength_levels(50.0, 25.0, 50.0); + assert_eq!(strength_levels(f64::NAN, 25.0, 50.0), 0.0, "a NaN Amount is no grain"); + assert_eq!(strength_levels(-5.0, 25.0, 50.0), 0.0); + assert_eq!(strength_levels(50.0, f64::NAN, f64::NAN), default); + assert_eq!(strength_levels(1e9, 25.0, 50.0), 2.0 * default); + assert_eq!(strength_levels(50.0, -1e9, 50.0), strength_levels(50.0, 0.0, 50.0)); + assert_eq!(strength_levels(50.0, 25.0, f64::INFINITY), strength_levels(50.0, 25.0, 100.0)); + // Lightroom Classic's at the ends of each slider (`docs/grain.md`) + for (want, (a, s, r)) in [(23.08, (50.0, 0.0, 50.0)), (5.83, (50.0, 100.0, 50.0)), (12.42, (50.0, 25.0, 0.0)), (11.68, (50.0, 25.0, 100.0))] { + let got = strength_levels(a, s, r); + assert!((got / want - 1.0).abs() < 0.01, "{a}/{s}/{r}: {got}, want {want}"); + } +} + +#[test] +fn interp_is_linear_between_knots_and_constant_outside() { + let knots = [(0.0, 1.0), (10.0, 3.0), (20.0, 2.0)]; + for (x, want) in [(-5.0, 1.0), (0.0, 1.0), (5.0, 2.0), (10.0, 3.0), (15.0, 2.5), (20.0, 2.0), (99.0, 2.0)] { + assert_eq!(interp(&knots, x), want, "at {x}"); + } + assert_eq!(interp(&[], 5.0), 0.0); + assert_eq!(interp(&[(3.0, 7.0)], 5.0), 7.0); +} + +#[test] +fn normal_quantile_matches_the_table() { + for (p, z) in [(0.5, 0.0), (0.975, 1.959_963_985), (0.841_344_746, 1.0), (0.001, -3.090_232_306), (1e-6, -4.753_424_309)] { + assert!((normal_quantile(p) - z).abs() < 1e-7, "at {p}: {}, want {z}", normal_quantile(p)); + assert!((normal_quantile(1.0 - p) + z).abs() < 1e-7, "at 1 - {p}"); + } + // increasing across the approximation's joins (0.02425 and its mirror), finite at the ends + let sweep: Vec = (0..=1000).map(|k| normal_quantile(k as f64 / 1000.0)).collect(); + assert!(sweep.iter().all(|z| z.is_finite())); + assert!(sweep.windows(2).all(|w| w[0] < w[1])); +} + +#[test] +fn poisson_counts_have_the_mean_and_variance_of_mu() { + let n = 40_000u32; + for mu in [0.5, 4.0, 40.0, 150.0] { + let cdf = poisson_cdf(mu); + assert!(cdf.windows(2).all(|w| w[0] <= w[1]), "mu {mu}: the distribution must not fall"); + assert!(cdf.last().is_some_and(|&c| c >= 1.0 - 1e-12), "mu {mu}: the distribution must reach 1"); + let draws: Vec = (0..n).map(|i| poisson(&cdf, mix(i)) as f64).collect(); + let mean = draws.iter().sum::() / n as f64; + let var = draws.iter().map(|d| (d - mean).powi(2)).sum::() / n as f64; + assert!((mean - mu).abs() < 4.0 * (mu / n as f64).sqrt(), "mu {mu}: mean {mean}"); + assert!((var / mu - 1.0).abs() < 0.05, "mu {mu}: variance {var}"); + } +} + +#[test] +fn poisson_stays_in_range_at_the_ends() { + for h in [0, u32::MAX] { + assert_eq!(poisson(&poisson_cdf(0.0), h), 0, "mean 0 is never a crystal"); + // past what the model uses, e^-mu underflows: a capped count, not a panic + assert!(poisson(&poisson_cdf(1e6), h) <= 512); + assert_eq!(poisson(&[], h), 0); + } +} + +#[test] +fn summed_area_matches_brute_force() { + let t = 7; + let count: Vec = (0..t * t).map(|i| (mix(i as u32) % 71) as u8).collect(); + let sat = summed_area(&count, t); + assert_eq!(sat.len(), (t + 1) * (t + 1)); + for y in 0..=t { + for x in 0..=t { + let want: u32 = (0..y).flat_map(|j| (0..x).map(move |i| (i, j))).map(|(i, j)| count[j * t + i] as u32).sum(); + assert_eq!(sat[y * (t + 1) + x], want, "[0, {x}) × [0, {y})"); + } + } +} + +/// Boxes against the emulsion's own pixels (each table's counts, less their mean, scaled to unit +/// variance as [`CrystalTile::new`] does), integrated by hand. Whole and fractional boxes, across +/// the torus's seams, at negative coordinates and periods away. +#[test] +fn box_sum_is_the_integral_of_the_emulsion() { + let (look, seed) = (CrystalLook::new(25.0, 50.0), 7); + let tile = CrystalTile::new(look, seed).expect("a tile"); + let counts = [0, 1].map(|which| draw_torus(which, TORI[which], seed, &look)); + let means: [f64; 2] = [0, 1].map(|w| counts[w].iter().map(|&c| c as f64).sum::() / (TORI[w] * TORI[w]) as f64); + let var: f64 = [0, 1] + .map(|w| { + let (sq, n) = reference_square_sum(&counts[w], TORI[w], means[w]); + sq / n as f64 + }) + .iter() + .sum(); + let k = 1.0 / var.sqrt(); + // The overlap of the cell at `i` with `[a, a + w]`. + let overlap = |i: i64, a: f64, w: f64| ((i + 1) as f64).min(a + w) - (i as f64).max(a); + let integral_by_hand = |which: usize, x0: f32, y0: f32, w: f32| { + let (x0, y0, w, t) = (x0 as f64, y0 as f64, w as f64, TORI[which] as i64); + let mut sum = 0.0; + for j in y0.floor() as i64..(y0 + w).ceil() as i64 { + for i in x0.floor() as i64..(x0 + w).ceil() as i64 { + let c = counts[which][(j.rem_euclid(t) * t + i.rem_euclid(t)) as usize] as f64; + sum += (c - means[which]) * k * overlap(i, x0, w) * overlap(j, y0, w); + } + } + sum + }; + for which in [0, 1] { + let t = TORI[which] as f32; + for (x0, y0, w) in [ + (0.0, 0.0, 2.0), + (100.0, 200.0, 37.0), + (3.25, 7.5, 2.0), + (10.6, 11.3, 0.7), + (50.5, 60.25, 400.0), + (t - 1.5, 20.0, 4.0), + (20.0, t - 1.5, 4.0), + (t - 0.5, t - 0.25, 31.0), + (-1.5, -2.25, 8.0), + (3.0 * t + 12.5, -2.0 * t + 40.5, 8.0), + ] { + let (got, want) = (tile.box_sum(which, x0, y0, w) as f64, integral_by_hand(which, x0, y0, w)); + let area = (w * w) as f64; + assert!((got - want).abs() / area < 2e-3, "torus {which}, ({x0}, {y0}) side {w}: {got} vs {want}"); + } + } + // the field is the two tori's mean, centred on its position + let (x, y, w) = (640.25, 1133.5, 3.0); + let want = (integral_by_hand(0, x - 0.5 * w, y - 0.5 * w, w) + integral_by_hand(1, x - 0.5 * w, y - 0.5 * w, w)) / (w * w) as f64; + assert!((tile.field(x, y, w) as f64 - want).abs() < 2e-3, "field {} vs {want}", tile.field(x, y, w)); +} + +/// A render under the footprint limit gets grain, one at or past it none, whatever else it asks. +#[test] +fn only_a_render_past_the_footprint_limit_loses_its_grain() { + let g = Grain { amount: 50.0, size: 25.0, roughness: 50.0, seed: 3 }; + let limit = TILE_PER_LONG / MAX_FOOTPRINT as f64; + assert_eq!(limit, 24.0); + for none in [limit, limit - 1.0, 1.0, 0.0, -5.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(CrystalGrain::new(&g, none).is_none(), "{none} px per long edge"); + } + assert_eq!(CrystalGrain::new(&g, limit + 1.0).expect("grain").foot, 480.0); + assert_eq!(CrystalGrain::new(&g, REF_LONG).expect("grain").foot, 2.0); + assert!(CrystalGrain::new(&Grain { amount: 0.0, ..g }, REF_LONG).is_none(), "no grain at Amount 0"); +} + +/// A draft (a Size or Roughness drag) doesn't wait for a new tile: the last tile of the seed stands +/// in while the new one is drawn in the background, and then the drag gets it. A render that +/// waits always gets the exact tile, as does a draft for a seed with no tile yet. +#[test] +fn a_drag_takes_the_last_tile_while_the_next_is_drawn() { + // a cache of its own: other tests' tiles (through any V7 render) would evict from the shared one + static OWN: Cache = Mutex::new(Vec::new()); + let tile = |look, seed, wait| tile_in(&OWN, look, seed, wait); + let (seed, fresh) = (0x0d4a_0001, 0x0d4a_0002); + let (a, b) = (CrystalLook::new(30.0, 50.0), CrystalLook::new(31.0, 50.0)); + let exact = |look: CrystalLook, seed: u32| patch(&CrystalTile::new(look, seed).expect("tile"), REF_LONG, 32, 0); + let first = tile(a, seed, true).expect("tile"); + assert_eq!(first.look, a); + let stand_in = tile(b, seed, false).expect("tile"); + assert_eq!(stand_in.look, a, "the draft waited for its tile"); + // the drag's next renders get the new tile once it is drawn + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + let drawn = loop { + let t = tile(b, seed, false).expect("tile"); + if t.look == b { + break t; + } + assert!(std::time::Instant::now() < deadline, "the background tile never arrived"); + std::thread::sleep(std::time::Duration::from_millis(5)); + }; + assert_eq!(patch(&drawn, REF_LONG, 32, 0), exact(b, seed)); + assert_eq!(patch(&tile(b, seed, true).expect("tile"), REF_LONG, 32, 0), exact(b, seed)); + // nothing drawn for this seed: nothing to stand in, the draft draws it + assert_eq!(patch(&tile(a, fresh, false).expect("tile"), REF_LONG, 32, 0), exact(a, fresh)); +} + +/// A render that misses a tile another thread is drawing waits for that tile rather than drawing +/// it a second time. +#[test] +fn a_render_waits_for_a_tile_being_drawn() { + static OWN: Cache = Mutex::new(Vec::new()); + let (look, seed) = (CrystalLook::new(40.0, 50.0), 0x0d4a_0003); + let key = key_of(look, seed); + let marker = start_drawing((std::ptr::from_ref(&OWN) as usize, key)).expect("not drawn yet"); + let render = std::thread::spawn(move || tile_in(&OWN, look, seed, true)); + until_waiting(&marker, 1); + let drawn = Arc::new(CrystalTile::new(look, seed).expect("tile")); + keep(&OWN, key, drawn.clone()); + drop(marker); + let got = render.join().expect("render thread").expect("tile"); + assert!(Arc::ptr_eq(&got, &drawn), "the render drew the tile again"); +} + +/// A render waiting for a tile gets it from its drawer even when the cache evicted it before the +/// render woke. +#[test] +fn a_waiting_render_gets_the_tile_the_cache_evicted() { + static OWN: Cache = Mutex::new(Vec::new()); + let (look, seed) = (CrystalLook::new(40.0, 50.0), 0x0d4a_0004); + let key = key_of(look, seed); + let marker = start_drawing((std::ptr::from_ref(&OWN) as usize, key)).expect("not drawn yet"); + let render = std::thread::spawn(move || tile_in(&OWN, look, seed, true)); + until_waiting(&marker, 1); + let drawn = Arc::new(CrystalTile::new(look, seed).expect("tile")); + marker.finish(&drawn); + keep(&OWN, key, drawn.clone()); + // other renders' tiles push it out of the cache before the waiter wakes + // (each its own tile: a waiter that took another key's would fail the check below) + for other in 1..=CACHE as u32 { + keep(&OWN, key_of(look, seed + other), Arc::new(CrystalTile::new(look, seed + other).expect("tile"))); + } + assert!(cached(&OWN, key).is_none(), "the tile is still cached"); + drop(marker); + let got = render.join().expect("render thread").expect("tile"); + assert!(Arc::ptr_eq(&got, &drawn), "the render drew the tile again"); +} + +/// A render waiting for a tile another render is drawing gets the drawer's tile even when the +/// cache drops it before the waiter wakes. +#[test] +fn a_render_drawing_a_tile_hands_it_to_its_waiter() { + static OWN: Cache = Mutex::new(Vec::new()); + let id = std::ptr::from_ref(&OWN) as usize; + // the first render's draw (only: a second would be the waiter drawing it again) waits for the + // second render to wait for it, and the cache empties before the second wakes + HOLDS.lock().unwrap_or_else(PoisonError::into_inner).push((id, 1, 1)); + EVICTS.lock().unwrap_or_else(PoisonError::into_inner).push(id); + let (look, seed) = (CrystalLook::new(0.0, 50.0), 0x0d4a_0005); + let renders: Vec<_> = (0..2).map(|_| std::thread::spawn(move || tile_in(&OWN, look, seed, true))).collect(); + let got: Vec<_> = renders.into_iter().map(|r| r.join().expect("render thread").expect("tile")).collect(); + assert!(cached(&OWN, key_of(look, seed)).is_none(), "the cache kept the tile"); + assert!(Arc::ptr_eq(&got[0], &got[1]), "the waiter drew the tile again"); +} + +/// Renders that miss the same tile together draw it once: the first registers the draw and the +/// others wait for it, as no gap lets a second render find it neither cached nor being drawn. +/// The first draw is held until the other renders all wait for it, so the misses overlap. +#[test] +fn renders_that_miss_a_tile_together_draw_it_once() { + static OWN: Cache = Mutex::new(Vec::new()); + const N: usize = 8; + // the first render's draw waits for the other seven to miss the tile too + const SEEDS: u32 = 40; + HOLDS.lock().unwrap_or_else(PoisonError::into_inner).push((std::ptr::from_ref(&OWN) as usize, N - 1, SEEDS as usize)); + let look = CrystalLook::new(0.0, 50.0); + for seed in 0x0d4a_1000..0x0d4a_1000 + SEEDS { + let start = Arc::new(std::sync::Barrier::new(N)); + let renders: Vec<_> = (0..N) + .map(|_| { + let start = start.clone(); + std::thread::spawn(move || { + start.wait(); + tile_in(&OWN, look, seed, true) + }) + }) + .collect(); + let got: Vec<_> = renders.into_iter().map(|r| r.join().expect("render thread").expect("tile")).collect(); + assert!(got.iter().all(|t| Arc::ptr_eq(t, &got[0])), "seed {seed:#x}: a render drew the tile again"); + } +} + +/// Grain width (autocorrelation half-width at mid grey, 6000 px) at Lightroom Classic's +/// measured settings (open PR #1060's table); Size 0 is as fine as uncorrelated pixels get (0.5). +#[test] +fn width_matches_lightroom_classic() { + let lrc = [(0.0, 50.0, 0.5), (25.0, 50.0, 1.13), (100.0, 50.0, 3.38), (25.0, 0.0, 0.86), (25.0, 100.0, 1.54)]; + for (s, r, want) in lrc { + let got = half_width(&patch(&tile_of(s, r), REF_LONG, 360, 0), 360); + assert!((got / want - 1.0).abs() < 0.1, "size {s} roughness {r}: width {got:.3}, want {want}"); + } +} + +/// Prints how long drawing a tile takes per setting (`--ignored --nocapture`, alone). +#[test] +#[ignore] +fn tile_timing_report() { + for (s, r) in [(0.0, 50.0), (10.0, 50.0), (25.0, 50.0), (50.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0), (100.0, 100.0)] { + let look = CrystalLook::new(s, r); + let mut best = f64::INFINITY; + for seed in 0..5 { + let start = std::time::Instant::now(); + let t = CrystalTile::new(look, 100 + seed); + best = best.min(start.elapsed().as_secs_f64() * 1e3); + assert!(t.is_some()); + } + eprintln!("size {s:>5} roughness {r:>5}: {best:.1} ms ({:?})", look); + } +} + +/// Fits the median crystal width per Size (Roughness 50) and the Roughness factors at Size 25 to +/// Lightroom Classic's grain widths (`--ignored --nocapture`; paste into the look tables). +#[test] +#[ignore] +fn fit_widths() { + let width_of = |look: CrystalLook| { + let mut w = 0.0; + for seed in [11, 12] { + let t = CrystalTile::new(look, seed).expect("tile"); + w += half_width(&patch(&t, REF_LONG, 360, 0), 360) / 2.0; + } + w + }; + let fit = |s: f64, r: f64, want: f64| { + let base = CrystalLook::new(s, r); + let (mut lo, mut hi) = (0.05f64, 40.0f64); + for _ in 0..18 { + let mid = (lo * hi).sqrt(); + if width_of(CrystalLook { width: mid, ..base }) < want { lo = mid } else { hi = mid } + } + let d = (lo * hi).sqrt(); + (d, width_of(CrystalLook { width: d, ..base })) + }; + for (s, want) in [(0.0, 0.43), (10.0, 0.71), (25.0, 1.13), (50.0, 1.70), (75.0, 2.54), (100.0, 3.38)] { + let (d, got) = fit(s, 50.0, want); + eprintln!("size {s}: width {d:.3} gives {got:.3} (want {want})"); + } + let (d50, _) = fit(25.0, 50.0, 1.13); + for (r, want) in [(0.0, 0.86), (100.0, 1.54)] { + let (d, got) = fit(25.0, r, want); + eprintln!("roughness {r}: factor {:.3} gives {got:.3} (want {want})", d / d50); + } +} + +/// Autocorrelation at lags 1–4 and the strength kept by box downscales of 2–16 (relative), of +/// candidate looks (`--ignored --nocapture`): compares a look's texture with a reference's. +#[test] +#[ignore] +fn texture_report() { + let profile = |look: CrystalLook| { + let n = 512; + let (mut acf, mut down) = ([0.0; 4], [0.0; 4]); + for seed in [21, 22] { + let t = CrystalTile::new(look, seed).expect("tile"); + let v = patch(&t, REF_LONG, n, 0); + let s0 = std(&v); + for (k, a) in acf.iter_mut().enumerate() { + let lag = k + 1; + let mut s = 0.0f64; + for y in 0..n { + for x in 0..n - lag { + s += (v[y * n + x] * v[y * n + x + lag] + v[x * n + y] * v[(x + lag) * n + y]) as f64; + } + } + *a += s / (2 * n * (n - lag)) as f64 / (s0 * s0) / 2.0; + } + for (k, d) in down.iter_mut().enumerate() { + let f = 2usize << k; + let m = n / f; + let b: Vec = (0..m * m) + .map(|q| { + let (x, y) = (q % m * f, q / m * f); + (0..f * f).map(|i| v[(y + i / f) * n + x + i % f]).sum::() / (f * f) as f32 + }) + .collect(); + *d += std(&b) / s0 / 2.0; + } + } + (acf, down) + }; + for (s, r) in [(25.0, 50.0), (50.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0)] { + let (a, d) = profile(CrystalLook::new(s, r)); + eprintln!( + "size {s} roughness {r}: acf {:.2} {:.2} {:.2} {:.2} down {:.2} {:.2} {:.2} {:.3}", + a[0], a[1], a[2], a[3], d[0], d[1], d[2], d[3] + ); + } +} + +/// A row computed with shared box edges equals the per-pixel boxes: any size, mirrored rows, rows +/// across the tori's seams and far from the origin. +#[test] +fn row_field_matches_per_pixel_field() { + let t = tile_of(25.0, 50.0); + for (w, sign, x, y) in [ + (2.0f32, 1.0f32, 3.3f32, 7.9f32), + (2.0, -1.0, 9000.2, 1275.0), + (8.0, 1.0, 11990.0, 2260.5), + (0.7, 1.0, 1279.6, 0.1), + (31.0, -1.0, 400.0, 1133.9), + ] { + for along_x in [true, false] { + let mut row = vec![0.0f32; 700]; + t.row_field(x, y, w, sign * w, along_x, &mut row); + for (k, &v) in row.iter().enumerate() { + let d = sign * w * k as f32; + let want = if along_x { t.field(x + d, y, w) } else { t.field(x, y + d, w) }; + assert!((v - want).abs() < 2e-3, "w {w} sign {sign} x {along_x} from ({x}, {y}), pixel {k}: {v} vs {want}"); + } + } + } +} + +/// Per-pixel cost of the grain on one thread (`--ignored --nocapture`). +#[test] +#[ignore] +fn pixel_cost_report() { + let g = CrystalGrain::new(&Grain { amount: 50.0, size: 25.0, roughness: 50.0, seed: 1 }, REF_LONG).expect("grain"); + let (w, h) = (4000usize, 600usize); + let mut sink = 0.0f32; + let t0 = std::time::Instant::now(); + for y in 0..h { + for x in 0..w { + sink += g.tile.field((x as f32 + 0.5) * 2.0, (y as f32 + 0.5) * 2.0, 2.0); + } + } + let per_pixel = t0.elapsed().as_secs_f64() / (w * h) as f64 * 1e9; + let mut row = vec![0.0; w]; + let t1 = std::time::Instant::now(); + for y in 0..h { + g.tile.row_field(1.0, (y as f32 + 0.5) * 2.0, 2.0, 2.0, true, &mut row); + sink += row[7]; + } + let per_row = t1.elapsed().as_secs_f64() / (w * h) as f64 * 1e9; + let t3 = std::time::Instant::now(); + for y in 0..h { + g.tile.row_field((y as f32 + 0.5) * 2.0, 1.0, 2.0, 2.0, false, &mut row); + sink += row[7]; + } + eprintln!("column {:.1} ns/px", t3.elapsed().as_secs_f64() / (w * h) as f64 * 1e9); + let t2 = std::time::Instant::now(); + for y in 0..h { + for x in 0..w { + sink += g.apply_field([0.4, 0.5, 0.6], (x + y) as f32 * 1e-4)[1]; + } + } + let tone = t2.elapsed().as_secs_f64() / (w * h) as f64 * 1e9; + eprintln!("field {per_pixel:.1} ns/px, row {per_row:.1} ns/px, tone {tone:.1} ns/px ({sink})"); +} diff --git a/crates/pipeline/src/tests_grain.rs b/crates/pipeline/src/tests_grain.rs new file mode 100644 index 0000000000..9dc4892453 --- /dev/null +++ b/crates/pipeline/src/tests_grain.rs @@ -0,0 +1,99 @@ +//! Film grain through the whole pipeline: which model each process renders with, and the crystal +//! grain's resolution independence (`crate::crystal`). + +use lightcraft_develop::{DevelopSettings, Process}; +use lightcraft_raster::Rgb32f; + +use crate::finish::GrainModel; +use crate::{OutputDepth, RenderRequest, SourceInfo, render}; + +fn on(process: Process, amount: f64) -> DevelopSettings { + let mut s = DevelopSettings { process: process.version(), ..Default::default() }; + s.grain.amount = amount; + s +} + +/// Display-encoded luminance (0..255, 16-bit precision) of a render of `src` at `w × h`. +fn luma(src: &Rgb32f, s: &DevelopSettings, w: usize, h: usize) -> Vec { + let mut req = RenderRequest::fit(w, h); + req.depth = OutputDepth::U16; + let r = render(src, &SourceInfo::default(), s, &req); + let Some(crate::DeepSamples::U16(v)) = r.deep.map(|d| d.samples) else { panic!("no 16-bit render") }; + v.chunks(3).map(|p| (0.2126 * p[0] as f64 + 0.7152 * p[1] as f64 + 0.0722 * p[2] as f64) / 257.0).collect() +} + +fn std(v: &[f64]) -> f64 { + let m = v.iter().sum::() / v.len() as f64; + (v.iter().map(|x| (x - m).powi(2)).sum::() / v.len() as f64).sqrt() +} + +#[test] +fn processes_before_v7_keep_the_value_noise() { + for p in Process::ALL { + let model = GrainModel::new(&on(p, 40.0), 2000.0, false); + match p { + Process::V1 | Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 => { + assert!(matches!(model, Some(GrainModel::Value(_))), "{p:?}") + } + Process::V7 | Process::V8 => assert!(matches!(model, Some(GrainModel::Crystal(_))), "{p:?}"), + } + assert!(GrainModel::new(&on(p, 0.0), 2000.0, false).is_none(), "{p:?}: no grain at Amount 0"); + } + let src = Rgb32f::filled(160, 120, [0.18; 3]); + let (v6, v7) = (luma(&src, &on(Process::V6, 50.0), 160, 120), luma(&src, &on(Process::V7, 50.0), 160, 120)); + assert_ne!(v6, v7, "V7 renders the crystal grain"); +} + +/// Grain is all that V7 changes: without it, a photo renders as under V6. +#[test] +fn without_grain_v7_renders_as_v6() { + let src = Rgb32f::filled(160, 120, [0.18, 0.4, 0.7]); + assert_eq!(luma(&src, &on(Process::V6, 0.0), 160, 120), luma(&src, &on(Process::V7, 0.0), 160, 120)); +} + +/// A preview shows what the export shows, box-downscaled to its size (whole pipeline). +#[test] +fn small_render_matches_the_downscaled_large_render() { + let src = Rgb32f::filled(300, 200, [0.18; 3]); + let (w, h, k) = (1200, 800, 4); + for size in [0.0, 25.0, 100.0] { + let mut s = on(Process::V7, 60.0); + s.grain.size = size; + let base = luma(&src, &on(Process::V7, 0.0), w, h); + let big: Vec = luma(&src, &s, w, h).iter().zip(&base).map(|(a, b)| a - b).collect(); + let down: Vec = (0..(w / k) * (h / k)) + .map(|q| { + let (x, y) = (q % (w / k) * k, q / (w / k) * k); + (0..k * k).map(|i| big[(y + i / k) * w + x + i % k]).sum::() / (k * k) as f64 + }) + .collect(); + let small = luma(&src, &s, w / k, h / k); + let ratio = std(&small) / std(&down); + assert!((0.95..1.05).contains(&ratio), "size {size}: preview / export grain {ratio:.3}"); + // and the same grain pixel by pixel, not just as strong: the preview's grain (less its + // no-grain render) against the downscaled export's + let small_base = luma(&src, &on(Process::V7, 0.0), w / k, h / k); + let delta: Vec = small.iter().zip(&small_base).map(|(a, b)| a - b).collect(); + // (measured: at most 0.003 of 255 levels apart, the 16-bit output's rounding; the grain's + // standard deviation is 1.4–2.9 levels, so a shifted or reseeded pattern is far outside) + let worst = delta.iter().zip(&down).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max); + assert!(worst < 0.01, "size {size}: preview grain {worst:.4} levels from the downscaled export's"); + } +} + +/// Degenerate and hostile grain settings render finite pixels under V7. +#[test] +fn hostile_grain_settings_render() { + let src = Rgb32f::filled(40, 30, [0.5, 0.2, 0.05]); + for (amount, size, rough) in + [(f64::NAN, 25.0, 50.0), (1e9, -1e9, f64::INFINITY), (50.0, f64::NAN, f64::NAN), (100.0, 100.0, 100.0), (-5.0, 0.0, 0.0)] + { + let mut s = on(Process::V7, amount); + s.grain.size = size; + s.grain.roughness = rough; + s.grain.seed = u32::MAX; + for (w, h) in [(40, 30), (1, 1), (3, 400)] { + assert!(luma(&src, &s, w, h).iter().all(|v| v.is_finite()), "{amount}/{size}/{rough} at {w}×{h}"); + } + } +} diff --git a/crates/pipeline/src/tests_tone.rs b/crates/pipeline/src/tests_tone.rs index f76f44775f..f8926e780c 100644 --- a/crates/pipeline/src/tests_tone.rs +++ b/crates/pipeline/src/tests_tone.rs @@ -208,6 +208,98 @@ fn median_orders_special_values_and_ties_like_total_cmp() { } } +/// A row of "8"s (two rings each, strokes 1.3 detail radii `r` wide, neighbours 0.8 radii apart): +/// dark lettering on a bright panel at the size of a bus number, as log luminance. +fn lettering(r: usize) -> (Plane, impl Fn(usize, usize) -> bool) { + let rf = r as f32; + let ring = move |x: f32, y: f32, cx: f32, cy: f32, outer: f32| { + let d = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt(); + d <= outer && d >= outer - 1.3 * rf + }; + let stroke = move |x: usize, y: usize| { + let (x, y) = (x as f32, y as f32); + (0..5).any(|i| { + let cx = 150.0 + i as f32 * 7.4 * rf; + ring(x, y, cx, 200.0 - 2.8 * rf, 2.9 * rf) || ring(x, y, cx, 200.0 + 3.2 * rf, 3.3 * rf) + }) + }; + (Plane::from_fn(900, 400, |x, y| if stroke(x, y) { -4.6 } else { -1.3 }), stroke) +} + +#[test] +fn gaps_between_letters_keep_their_own_tone_in_the_base() { + // At the size of a bus number in a 7000 px photo, a median at the detail radius filled the + // gaps between the digits and around their waists with the letters' tone: 360 panel pixels + // sat over 1 EV (up to 2.3 EV) above their base, so Shadows lifted them by up to 1.3 EV into + // bright blocks. The wider median sees the panel there, so the gaps keep their own tone. + let ppl = 6960.0; + let r = local::base_detail_radius(ppl); + assert_eq!(r, 10); + let (l, stroke) = lettering(r); + let (w, h) = (l.width, l.height); + let base = local::tone_base(&l, 0.015 * ppl as f32, r, true); + // panel pixels at least 3 px from a stroke (the guided filter's own edge softness aside) + let panel = |x: usize, y: usize| !(x.saturating_sub(2)..(x + 3).min(w)).any(|a| (y.saturating_sub(2)..(y + 3).min(h)).any(|b| stroke(a, b))); + let (mut worst, mut under) = (0.0f32, 0usize); + for y in 0..h { + for x in (0..w).filter(|&x| panel(x, y)) { + let d = l.get(x, y) - base.get(x, y); + worst = worst.max(d); + under += usize::from(d > 1.0); + } + } + assert!(under == 0 && worst < 1.0, "{under} panel px over 1 EV above their base; worst {worst} EV"); +} + +#[test] +fn isolated_lines_up_to_the_detail_radius_stay_out_of_the_base() { + // Light lines 1 to 9 px wide on a dark ground (twigs against a dark wall, r = 10): the base + // keeps the ground's tone under each, as under the median (#632), so Shadows lifts them with + // the ground and they keep their contrast. Clamping to the window's quartiles instead let lines + // of 6 px and more a third to two thirds of the way into the base. + let ppl = 6960.0; + let r = local::base_detail_radius(ppl); + let widths = [1usize, 2, 3, 4, 5, 6, 7, 8, 9]; + let l = Plane::from_fn(1300, 200, |x, _| { + let (i, off) = (x / 130, x % 130); + if i < widths.len() && (60..60 + widths[i]).contains(&off) { -2.0 } else { -6.0 } + }); + let base = local::tone_base(&l, 0.015 * ppl as f32, r, true); + for (i, wd) in widths.iter().enumerate() { + let leak = (base.get(i * 130 + 60 + wd / 2, 100) + 6.0) / 4.0; + assert!(leak.abs() < 0.05, "a {wd} px line is {leak} of the way into the base"); + } +} + +#[test] +fn only_process_v8_on_takes_the_detail_free_base() { + // V2 to V7 keep the plain median (V1 has none): they are released and frozen (`tests_legacy`) + for p in Process::ALL { + let s = DevelopSettings { process: p.version(), ..Default::default() }; + assert_eq!(local::base_keeps_gaps(&s), p >= Process::V8, "{p:?}"); + } + let (l, _) = lettering(10); + let plain = local::guided_fast(&local::median_hv(&l, 10), 100.0, local::BASE_EPS); + assert_eq!(local::tone_base(&l, 100.0, 10, false).data, plain.data); + assert_ne!(local::tone_base(&l, 100.0, 10, true).data, plain.data); +} + +#[test] +fn detail_free_keeps_steps_and_regions() { + // a step between two flat regions, and a flat field, come out as they went in + let step = Plane::from_fn(90, 60, |x, _| if x < 45 { -4.0 } else { 0.5 }); + assert_eq!(local::detail_free(&step, 6).data, step.data); + let flat = Plane::from_fn(31, 17, |_, _| -1.25); + assert_eq!(local::detail_free(&flat, 3).data, flat.data); + assert_eq!(local::detail_free(&step, 0).data, step.data); + // tiny and empty planes, and NaNs, are not a panic + for (w, h) in [(1, 1), (2, 3), (5, 1)] { + let p = Plane::from_fn(w, h, |x, y| if (x + y) % 2 == 0 { f32::NAN } else { 1.0 }); + assert_eq!(local::detail_free(&p, 4).data.len(), w * h); + } + assert!(local::detail_free(&Plane::new(0, 0), 4).data.is_empty()); +} + #[test] fn v1_keeps_the_base_it_always_had() { // V1's base is the edge-aware filter of log luminance itself, as before process V2: no median @@ -225,7 +317,7 @@ fn v1_keeps_the_base_it_always_had() { let l = Plane::from_fn(301, 157, |x, y| (((x * 31 + y * 17) * 2_654_435_761usize) % 1000) as f32 / 250.0 - 2.0 + if x % 5 == 0 { 0.5 } else { 0.0 }); for sg in [1.0f32, 4.5, 18.0] { - assert_eq!(local::tone_base(&l, sg, 0).data, local::guided_fast(&l, sg, local::BASE_EPS).data, "sigma {sg}"); + assert_eq!(local::tone_base(&l, sg, 0, true).data, local::guided_fast(&l, sg, local::BASE_EPS).data, "sigma {sg}"); } // V2 takes the median wherever the image is big enough for one let v2 = with("light.highlights", -100.0); diff --git a/crates/pipeline/src/tests_window.rs b/crates/pipeline/src/tests_window.rs index e5fb6ea801..7fa71a5f25 100644 --- a/crates/pipeline/src/tests_window.rs +++ b/crates/pipeline/src/tests_window.rs @@ -6,7 +6,7 @@ use lightcraft_develop::{DevelopSettings, controls}; use lightcraft_geom::{Orientation, Rect}; use lightcraft_raster::{Rgb32f, Rgba8}; -use crate::{PixelWindow, RenderRequest, SourceInfo, render}; +use crate::{OutputDepth, PixelWindow, RenderRequest, SourceInfo, render}; const W: usize = 960; const H: usize = 640; @@ -422,6 +422,73 @@ fn auto_mask_strokes_match_the_whole_render() { check_noisy("auto mask", &s, PixelWindow { x: 400, y: 300, w: 300, h: 250 }, 2, 0.1); } +// Given a lens blur, a window (zoomed view) blurs right up to its edges as the whole render does: +// it is rendered with the blur's reach around it +#[test] +fn lens_blur_matches_the_whole_render_up_to_the_window_edges() { + lens_blur_window_matches(OutputDepth::U8); + lens_blur_window_matches(OutputDepth::U16); +} + +/// A high-bit-depth window grows for the lens blur too, and is cut back to the request. +fn lens_blur_window_matches(depth: OutputDepth) { + use lightcraft_develop::{Mask, MaskComponent, MaskOp, MaskShape}; + use lightcraft_geom::Point; + let radial = MaskShape::Radial { center: Point::new(0.5, 0.5), rx: 0.15, ry: 0.2, angle: 0.0, feather: 30.0, invert: false }; + let mut s = DevelopSettings { + masks: vec![Mask { + id: 4, + components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: radial }], + ..Default::default() + }], + ..Default::default() + }; + s.lens_blur.enabled = true; + s.lens_blur.amount = 80.0; + s.lens_blur.boost = 40.0; + s.lens_blur.focus_mask = Some(4); + let deep = |win: Option| { + let r = render(&scene(), &SourceInfo::default(), &s, &RenderRequest { window: win, depth, ..RenderRequest::fit(W, H) }); + if let Some(d) = &r.deep { + assert_eq!((d.width, d.height), (r.image.width, r.image.height)); + } + r.image + }; + let (f, w) = (deep(None), deep(Some(MID))); + assert_eq!((w.width, w.height), (MID.w, MID.h)); + let (max, mean) = compare_inset(&f, &w, MID, 0); + assert!(max <= 6 && mean <= 0.4, "max {max}, mean {mean:.3}"); + // and the blur shows: the whole render differs from the one without it + let mut off = s.clone(); + off.lens_blur.enabled = false; + let (_, mean) = compare_inset(&full(&off), &f, PixelWindow { x: 0, y: 0, w: f.width, h: f.height }, 0); + assert!(mean > 1.0, "{mean:.3}"); +} + +/// With the automatic subject focus (no focus mask, no fixed shape, no person matte) a window +/// focuses where the whole render does: the estimate comes from the whole photo, not from the +/// pixels the window holds. +#[test] +fn lens_blur_on_the_estimated_subject_matches_the_whole_render() { + let mut s = DevelopSettings::default(); + s.lens_blur.enabled = true; + s.lens_blur.amount = 80.0; + // a sharp cut: the window then grows only by the blur's radius, less than the estimate reads + s.lens_blur.transition = 0.0; + for depth in [OutputDepth::U8, OutputDepth::U16] { + let r = |win: Option| { + render(&scene(), &SourceInfo::default(), &s, &RenderRequest { window: win, depth, ..RenderRequest::fit(W, H) }).image + }; + // a window at the middle and one at an edge, where the estimate's neighbourhood is cut off + for win in [MID, PixelWindow { x: 0, y: 0, w: 300, h: 220 }] { + let (f, w) = (r(None), r(Some(win))); + assert_eq!((w.width, w.height), (win.w, win.h)); + let (max, mean) = compare_inset(&f, &w, win, 0); + assert!(max <= 6 && mean <= 0.4, "{depth:?} {win:?}: max {max}, mean {mean:.3}"); + } + } +} + // Given the joint colour NR, a window is filtered with the whole frame's noise model: a quiet part of // the frame does not make a window of its noisy part (or the other way round) smooth differently #[test] diff --git a/crates/raw/src/kelvin_presets.rs b/crates/raw/src/kelvin_presets.rs index 58ed396257..e5a908d5c7 100644 --- a/crates/raw/src/kelvin_presets.rs +++ b/crates/raw/src/kelvin_presets.rs @@ -82,7 +82,9 @@ pub fn covers(make: Option<&str>, model: &str) -> bool { .map_or(model, |(_, rest)| rest.trim_start()) }; let listed = MODELS.iter().any(|(b, m)| brand.is_none_or(|x| x.eq_ignore_ascii_case(b)) && bare_of(b).eq_ignore_ascii_case(m)); - let fuji = brand.is_none_or(|b| b.eq_ignore_ascii_case("FUJIFILM")) && FUJI_MODELS.iter().any(|m| bare_of("FUJIFILM").eq_ignore_ascii_case(m)); + // A DxO demosaiced DNG keeps the Fujifilm model but carries DxO as its make. + let fuji = brand.is_none_or(|b| b.eq_ignore_ascii_case("FUJIFILM") || b.eq_ignore_ascii_case("DxO")) + && FUJI_MODELS.iter().any(|m| bare_of("FUJIFILM").eq_ignore_ascii_case(m)); listed || fuji } @@ -408,6 +410,14 @@ mod tests { } } + #[test] + fn dxo_dng_fujifilm_model_is_covered_for_kelvin() { + // A DxO demosaiced DNG carries DxO as its make, not FUJIFILM, but it is still a Fujifilm model. + assert!(covers(Some("DxO"), "X-T2")); + assert!(covers(Some("DxO"), "FUJIFILM X-T2")); + assert!(covers_camera("DxO X-T2")); + } + #[test] fn covered_models() { assert!(covers_camera("NIKON CORPORATION NIKON Z5_2") && covers_camera("NIKON Z5_2") && !covers_camera("NIKON CORPORATION NIKON Z6")); diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index c7538c6b11..ff9ee048b7 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -18,8 +18,9 @@ //! Canon CR2 / CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW) / CRW (the CIFF bodies of 2000–2004; clean-room-derived //! compression, `vendor::crw`; the PowerShot G5's anomalous coding is refused), Nikon NEF/NRW (uncompressed, Huffman lossless / lossy compressed), Sony ARW (uncompressed, ARW2, lossless), Fujifilm RAF (uncompressed Bayer //! and X-Trans, lossless and lossy compressed), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format: compressed 4 and 6, the prefix-coded strips of 8, -//! packed 2/5/7, the 16-bit words of the oldest bodies), Pentax PEF (uncompressed, Huffman), Olympus ORF (uncompressed: 16-bit words, 12-bit XZ-2 words, 12-bit 16-byte blocks of the E-300/E-330/E-500; compressed: 12-bit entropy-coded sensor differences across interchangeable-lens and modern compact bodies). -//! [`embedded_preview`] covers these containers' JPEG previews. Variants we can't decode yet (CR3 unverified marker families / C-RAW configurations) return [`RawError::Unsupported`]; each vendor module documents its sources +//! packed 2/5/7, the 16-bit words of the oldest bodies), Pentax PEF (uncompressed, Huffman), Olympus ORF (uncompressed: 16-bit words, 12-bit XZ-2 words, +//! two-field 12-bit samples and 12-bit 16-byte blocks of the E-300/E-330/E-500). +//! [`embedded_preview`] covers these containers' JPEG previews. Variants we can't decode yet (compressed Olympus ORF, CR3 unverified marker families / C-RAW configurations) return [`RawError::Unsupported`]; each vendor module documents its sources //! (public specifications, tag-name documentation, black-box analysis of CC0 samples) and gaps. Non-DNG files carry no //! colour matrix: [`spectral`] has matrices fitted to measured spectral sensitivities for 52 models, and //! otherwise [`color`] falls back to a documented neutral model. The decoders never panic on malformed input. diff --git a/crates/raw/src/vendor.rs b/crates/raw/src/vendor.rs index 6b27843d56..a44262a2c4 100644 --- a/crates/raw/src/vendor.rs +++ b/crates/raw/src/vendor.rs @@ -21,7 +21,6 @@ pub mod nef; mod nef_lens; pub mod nefc; pub mod orf; -pub(crate) mod orfc; pub mod pef; pub mod raf; mod raf_lens; diff --git a/crates/raw/src/vendor/arw.rs b/crates/raw/src/vendor/arw.rs index ba1c556d7a..e260415648 100644 --- a/crates/raw/src/vendor/arw.rs +++ b/crates/raw/src/vendor/arw.rs @@ -358,7 +358,9 @@ fn read_quad_tiles(bytes: &[u8], info: &ImageInfo) -> Result> { .map(|c| { let src = chunk_bytes(bytes, c).ok_or_else(|| RawError::Corrupt("tile offset past end of file".into()))?; let f = ljpeg::decode(src, (c.width as usize * c.height as usize).max(1 << 16))?; - if f.components != 4 || f.data.len() < f.width * f.height * 4 { + // a tile's frame is half its nominal width and height: a larger one (which the sample cap above would + // still let through when the tile is small) is no Sony tile + if f.components != 4 || f.data.len() < f.width * f.height * 4 || f.width * 2 > c.width as usize || f.height * 2 > c.height as usize { return Err(RawError::Corrupt(format!( "lossless ARW tile: {} samples in a {}×{}×{} frame", f.data.len(), diff --git a/crates/raw/src/vendor/cr3.rs b/crates/raw/src/vendor/cr3.rs index 6136573245..ba526b6e56 100644 --- a/crates/raw/src/vendor/cr3.rs +++ b/crates/raw/src/vendor/cr3.rs @@ -215,10 +215,22 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { let maker = static_maker.as_ref().and_then(|m| m.ifds.first()); // Retain only the first useful timed maker note: repeated CTMD records must not accumulate // independent copies of every bounded TIFF value in memory. + // Records aliasing the same bytes are parsed once, and all parses share a budget of twice the file (at least 1 MiB); + // a record past what is left is skipped, a later smaller one still parsed. + let mut seen = std::collections::HashSet::new(); + let mut left = bytes.len().saturating_mul(2).max(1 << 20); let timed_maker = container .timed_exif(bytes) .into_iter() .filter(|b| b.tag == 0x927c) + .filter(|b| seen.insert((b.data.as_ptr() as usize, b.data.len()))) + .filter(|b| match left.checked_sub(b.data.len()) { + Some(rest) => { + left = rest; + true + } + None => false, + }) .filter_map(|b| Tiff::parse(b.data).ok()) .find(|t| t.ifds.first().is_some_and(|m| m.contains(COLOR_DATA))); let color_maker = timed_maker.as_ref().and_then(|t| t.ifds.first()).or(maker); diff --git a/crates/raw/src/vendor/orf.rs b/crates/raw/src/vendor/orf.rs index 97a640ddff..8c2bd28398 100644 --- a/crates/raw/src/vendor/orf.rs +++ b/crates/raw/src/vendor/orf.rs @@ -1,4 +1,4 @@ -//! Olympus ORF — uncompressed and compressed variants. +//! Olympus ORF — uncompressed variants; compressed sensor data is unsupported. //! //! Sources: TIFF 6.0 (the `IIRO`/`MMOR` container is a TIFF with a different magic number), Exif 2.3 (`CFAPattern`, //! tag `0xa302`), the ExifTool Olympus tag-name documentation (maker-note sub-directories `0x2020` CameraSettings — @@ -28,9 +28,8 @@ //! (last), the bit order and the pixel order were fixed by measurement on the CC0 files 2878 (E-300), 3540 (E-500) //! and 3624 (E-330), as was the sensor-origin RGGB anchoring (the maker-note crop offsets are odd). The E-M5 Mark II //! and PEN-F files were only checked for smoothness, not for CFA anchoring or black level. -//! - Olympus's compressed ORF (interchangeable-lens bodies and compacts using the 12/14-bit entropy coding stream): -//! decoded clean-room in `orfc.rs` from Olympus patents US7333035B2 and US7715639B2 (Takashi Ishikawa) and black-box -//! CC0 samples (OM-D E-M1, E-M10 Mark III). No GPL/LibRaw code was consulted. See `docs/orf-compression.md`. +//! - Compressed ORF sensor data is unsupported. The previous decoder was removed pending provenance +//! resolution; embedded previews remain available. See `docs/orf-compression.md`. //! - The colour-filter layout is the file's Exif `CFAPattern`: GRBG on the E-1 and E-400, RGGB on the XZ-2, where //! the colours of the decoded mosaic follow the embedded JPEG best with exactly that layout //! (`corpus_orf_cfa_patterns`). The samples' active areas start at even offsets, so they can't tell whether the @@ -200,7 +199,7 @@ fn field_rows(strips: &[(u64, u64)], w: usize, h: usize, file_len: usize) -> Opt Some(rows) } -/// Decode an Olympus ORF container into a mosaic raw image, supporting uncompressed 16-bit, packed 12-bit, and compressed formats. +/// Decode the supported uncompressed Olympus ORF layouts into a mosaic raw image. pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { let tiff = Tiff::parse(bytes)?; let ifd0 = &tiff.ifds[0]; @@ -232,20 +231,10 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { Vec::new() }; (RawData::U16(d), 12, false) - } else if let Some((params, stream)) = (|| { - let params = super::orfc::CompressionParameters::from_ifd(ip.as_ref()?, mn.as_ref())?; - let chunk = chunks.first()?; - let src = chunk_bytes(bytes, chunk)?; - if !super::orfc::validate_stream_header(src, params.header_prefix_len) { - return None; - } - let stream = src.get(params.header_prefix_len.saturating_add(2)..)?; - Some((params, stream)) - })() { - let d = if mode == Mode::Full || stated.is_none() { super::orfc::decompress_stream(stream, w, h, ¶ms)? } else { Vec::new() }; - (RawData::U16(d), params.valid_bits, false) - } else if total * 8 >= (n as u64) * 12 && total * 8 < (n as u64) * 13 && chunks.len() == 1 { + } else if info.bits() == 12 && total * 8 >= (n as u64) * 12 && total * 8 < (n as u64) * 13 && chunks.len() == 1 { let src = chunk_bytes(bytes, &chunks[0]).ok_or_else(|| RawError::Corrupt("ORF strip outside file".into()))?; + // Only the declared 12-bit layout is supported here. A compressed stream in a 16-bit + // ORF container must not fall through to packed decoding just because its length fits. // the strip as it is in the file (clipped at its end), not as its tag states it: one too short // for the samples is a truncated file, refused before they are allocated if (src.len() as u64).saturating_mul(8) < (n as u64).saturating_mul(12) { @@ -413,6 +402,17 @@ mod tests { b } + /// A 16-bit container with a short sensor stream is not the supported 12-bit packed layout. + /// Both entry points must report unsupported rather than returning fabricated sensor pixels. + #[test] + fn compressed_sensor_data_is_unsupported_in_probe_and_decode() { + for strip_len in [8, 24, 25] { + let bytes = orf_with(4, 4, 16, vec![0; strip_len], Some(&[2, 0, 2, 0, 0, 1, 1, 2])); + assert!(matches!(crate::decode(&bytes), Err(RawError::Unsupported(why)) if why == "Olympus compressed ORF")); + assert!(matches!(crate::probe_info(&bytes), Err(RawError::Unsupported(why)) if why == "Olympus compressed ORF")); + } + } + /// Strip byte counts that add up past `u64::MAX` (LONG8 `[u64::MAX, 1]`) are an error or a picture, not an overflow. #[test] fn strip_byte_counts_past_u64_max_do_not_overflow() { diff --git a/crates/raw/src/vendor/orfc.rs b/crates/raw/src/vendor/orfc.rs deleted file mode 100644 index a8df663bc4..0000000000 --- a/crates/raw/src/vendor/orfc.rs +++ /dev/null @@ -1,489 +0,0 @@ -//! Olympus compressed ORF entropy and predictive decoding. -//! -//! Clean-room implementation derived strictly from patent specifications and black-box CC0 samples: -//! - Olympus Patent US7333035B2 (Takashi Ishikawa): directional edge-directed prediction across Bayer channels -//! and run-length adaptive Golomb-Rice entropy coding with quotient escape codes. -//! - Olympus Patent US7715639B2 (Takashi Ishikawa): direct low-order bitfield splitting and residual difference -//! correction filters. -//! - ImageProcessing maker-note directory (`0x2040`) parameters (`0x0640`–`0x0653`) and valid sensor bit depth (`0x102c`). -//! - Verification against CC0 sample files from raw.pixls.us (OM-D E-M1, OM-D E-M10 Mark III). -//! -//! No LibRaw, dcraw, darktable, RawTherapee, or other GPL/LGPL/AGPL code was consulted or used. -//! See `docs/orf-compression.md` for format specification and verification records. - -use crate::{RawError, Result}; -use lightcraft_tiff::Ifd; -use lightcraft_tiff::makernote::MakerNote; - -/// Valid bits tag in Olympus MakerNote. -const MN_VALID_BITS: u16 = 0x102c; - -/// Bitstream reader for big-endian, MSB-first compressed ORF bitstreams. -struct BitStream<'a> { - data: &'a [u8], - cursor: usize, - buffer: u32, - bits_available: u32, - bits_loaded: u64, -} - -impl<'a> BitStream<'a> { - /// Create a new bitstream reader over the supplied byte slice. - fn new(data: &'a [u8]) -> Self { - Self { data, cursor: 0, buffer: 0, bits_available: 0, bits_loaded: 0 } - } - - /// Refill the bit buffer with a 32-bit big-endian word. - fn refill_word(&mut self) { - self.bits_loaded = self.bits_loaded.saturating_add(32); - if let Some(chunk) = self.data.get(self.cursor..self.cursor.saturating_add(4)) { - self.buffer = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); - self.cursor = self.cursor.saturating_add(4); - self.bits_available = 32; - } else { - let mut chunk = [0u8; 4]; - let remaining = self.data.len().saturating_sub(self.cursor); - if remaining > 0 { - if let Some(src) = self.data.get(self.cursor..self.cursor.saturating_add(remaining)) { - chunk[..remaining].copy_from_slice(src); - } - self.cursor = self.data.len(); - } - self.buffer = u32::from_be_bytes(chunk); - self.bits_available = 32; - } - } - - /// Append up to 16 bits to the lower part of the active bit buffer. - fn refill_halfword(&mut self) { - self.bits_loaded = self.bits_loaded.saturating_add(16); - let next = if let Some(chunk) = self.data.get(self.cursor..self.cursor.saturating_add(2)) { - self.cursor = self.cursor.saturating_add(2); - u16::from_be_bytes([chunk[0], chunk[1]]) - } else if let Some(&single) = self.data.get(self.cursor) { - self.cursor = self.cursor.saturating_add(1); - (single as u16) << 8 - } else { - 0 - }; - self.buffer = (self.buffer << 16) | u32::from(next); - self.bits_available = self.bits_available.saturating_add(16); - } - - /// Read up to 16 bits from the bitstream. - fn read_bits(&mut self, width: u32) -> u32 { - if width == 0 { - return 0; - } - while self.bits_available < width { - self.refill_halfword(); - } - let shift = self.bits_available & 0x1f; - let value = (self.buffer.wrapping_shl((32 - shift) & 0x1f)) >> (32 - width); - self.bits_available = self.bits_available.saturating_sub(width); - value - } - - /// Advance by one bit, refilling the 32-bit buffer if necessary. - fn advance_single_bit(&mut self, state: &mut u32) { - if *state == 0 { - self.refill_word(); - self.bits_available = self.bits_available.saturating_sub(1); - *state = self.bits_available; - } else { - *state = state.saturating_sub(1); - self.bits_available = *state; - } - } -} - -/// Parameters extracted from ImageProcessing SubIFD (`0x2040`) controlling compressed ORF decoding. -pub(crate) struct CompressionParameters { - /// Low-order direct bits extracted without prediction (tag `0x0640`). - pub(crate) direct_bits_low0: u32, - /// Gradient difference exponent threshold for edge classification (tag `0x0641`). - pub(crate) gradient_thresh_exp_641: u32, - /// Default spatial predictor boundary value (tag `0x0642`). - pub(crate) boundary_predictor_642: i32, - /// Direct residual sub-bits width (tag `0x0643`). - pub(crate) direct_bits_sub3: u32, - /// Vertical feedback shift exponent (tag `0x0644`). - pub(crate) feedback_shift_644: u32, - /// Flatness threshold exponent (tag `0x0645`). - pub(crate) flatness_thresh_exp_645: u32, - /// Flatness run threshold (tag `0x0646`). - pub(crate) run_thresh_646: i32, - /// Adaptive Rice parameter table offset A (tag `0x0647`). - pub(crate) table_647: i32, - /// Adaptive Rice parameter table limit A (tag `0x0648`). - pub(crate) table_648: i32, - /// Adaptive Rice parameter table offset B (tag `0x0649`). - pub(crate) table_649: i32, - /// Adaptive Rice parameter table limit B (tag `0x0650`). - pub(crate) table_650: i32, - /// Maximum Rice parameter allowed (tag `0x0651`). - pub(crate) max_rice_k: i32, - /// Maximum unary quotient run length before escape coding (tag `0x0652`). - pub(crate) max_unary_run: u32, - /// Prefix length of the compressed stream header in bytes (tag `0x0653`). - pub(crate) header_prefix_len: usize, - /// Valid sensor bit depth from MakerNote `0x102c`. - pub(crate) valid_bits: u32, -} - -impl CompressionParameters { - /// Parse and validate compression parameters from the ImageProcessing IFD and MakerNote. - pub(crate) fn from_ifd(ip: &Ifd, mn: Option<&MakerNote>) -> Option { - let header_prefix_len = usize::try_from(ip.u64(0x0653)?).ok()?; - if header_prefix_len == 0 || header_prefix_len > 8 { - return None; - } - if ip.u64(0x0640).is_some_and(|v| v > 16) || ip.u64(0x0643).is_some_and(|v| v > 16) { - return None; - } - if ip.u64(0x0644).is_some_and(|v| v == 0 || v > 15) { - return None; - } - let direct_bits_low0 = ip.u64(0x0640).and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - let gradient_thresh_exp_641 = ip.u64(0x0641).and_then(|v| u32::try_from(v).ok()).unwrap_or(5); - let boundary_predictor_642 = ip.i64(0x0642).and_then(|v| i32::try_from(v).ok()).filter(|&v| (-65536..=65536).contains(&v)).unwrap_or(0); - let direct_bits_sub3 = ip.u64(0x0643).and_then(|v| u32::try_from(v).ok()).unwrap_or(2); - let feedback_shift_644 = ip.u64(0x0644).and_then(|v| u32::try_from(v).ok()).unwrap_or(5); - let flatness_thresh_exp_645 = ip.u64(0x0645).and_then(|v| u32::try_from(v).ok()).unwrap_or(4); - let run_thresh_646 = ip.u64(0x0646).and_then(|v| i32::try_from(v).ok()).unwrap_or(3); - let table_647 = ip.u64(0x0647).and_then(|v| i32::try_from(v).ok()).unwrap_or(2); - let table_648 = ip.u64(0x0648).and_then(|v| i32::try_from(v).ok()).unwrap_or(3); - let table_649 = ip.u64(0x0649).and_then(|v| i32::try_from(v).ok()).unwrap_or(4); - let table_650 = ip.u64(0x0650).and_then(|v| i32::try_from(v).ok()).unwrap_or(7); - let max_rice_k = ip.u64(0x0651).and_then(|v| i32::try_from(v).ok()).unwrap_or(15); - let max_unary_run = ip.u64(0x0652).and_then(|v| u32::try_from(v).ok()).unwrap_or(12).clamp(1, 32); - let valid_bits = mn.and_then(|m| m.ifd.u64(MN_VALID_BITS)).and_then(|v| u32::try_from(v).ok()).filter(|b| (8..=16).contains(b)).unwrap_or(12); - - Some(Self { - direct_bits_low0, - gradient_thresh_exp_641, - boundary_predictor_642, - direct_bits_sub3, - feedback_shift_644, - flatness_thresh_exp_645, - run_thresh_646, - table_647, - table_648, - table_649, - table_650, - max_rice_k, - max_unary_run, - header_prefix_len, - valid_bits, - }) - } -} - -/// Check the stream header prefix: $N$ big-endian bytes equal to 1, followed by two zero bytes. -pub(crate) fn validate_stream_header(src: &[u8], prefix_bytes: usize) -> bool { - if prefix_bytes == 0 || prefix_bytes > 8 || src.len() < prefix_bytes.saturating_add(2) { - return false; - } - let mut prefix_int = 0u64; - for &b in src.get(..prefix_bytes).unwrap_or(&[]) { - prefix_int = (prefix_int << 8) | u64::from(b); - } - if prefix_int != 1 { - return false; - } - let Some(delimiter) = src.get(prefix_bytes..prefix_bytes.saturating_add(2)) else { - return false; - }; - delimiter == [0x00, 0x00] -} - -/// Decoded entropy-coded symbol components for one photosite. -struct DecodedSymbol { - signed_residual: i32, - raw_magnitude: u32, - direct_bits_low0: u32, - direct_bits_sub3: u32, -} - -/// Decode the next Golomb-Rice entropy residual symbol according to the patent specification. -fn decode_entropy_symbol(reader: &mut BitStream<'_>, rice_k: u32, params: &CompressionParameters) -> DecodedSymbol { - if reader.bits_available == 0 { - reader.refill_word(); - } - reader.bits_available = reader.bits_available.saturating_sub(1); - let sign_bit = (reader.buffer >> (reader.bits_available & 0x1f)) & 1; - - let direct_bits_sub3 = if params.direct_bits_sub3 > 0 { reader.read_bits(params.direct_bits_sub3) } else { 0 }; - let direct_bits_low0 = if params.direct_bits_low0 > 0 { reader.read_bits(params.direct_bits_low0) } else { 0 }; - - let mut state = reader.bits_available; - let mut quotient = 0u32; - - loop { - reader.advance_single_bit(&mut state); - if ((reader.buffer >> (state & 0x1f)) & 1) != 0 { - break; - } - quotient = quotient.saturating_add(1); - if quotient == params.max_unary_run { - quotient = 0; - if rice_k != 15 { - let bits_needed = 15u32.saturating_sub(rice_k); - while state < bits_needed { - reader.refill_halfword(); - state = reader.bits_available; - } - let shift = state & 0x1f; - quotient = (reader.buffer.wrapping_shl((32 - shift) & 0x1f)) >> (rice_k + 17); - state = state.saturating_sub(bits_needed); - reader.bits_available = state; - } - reader.advance_single_bit(&mut state); - break; - } - } - - let remainder = if rice_k == 0 { - 0 - } else { - while state < rice_k { - reader.refill_halfword(); - state = reader.bits_available; - } - let shift = state & 0x1f; - let rem = (reader.buffer.wrapping_shl((32 - shift) & 0x1f)) >> (32 - (rice_k & 0x1f)); - reader.bits_available = state.saturating_sub(rice_k); - rem - }; - - let raw_magnitude = remainder | (quotient << rice_k); - let sign_mask = if sign_bit != 0 { 0xffff_ffff } else { 0 }; - let signed_residual = (raw_magnitude ^ sign_mask) as i32; - - DecodedSymbol { signed_residual, raw_magnitude, direct_bits_low0, direct_bits_sub3 } -} - -/// Decompress an entire Olympus compressed entropy bitstream into mosaic sensor samples. -pub(crate) fn decompress_stream(stream: &[u8], width: usize, height: usize, params: &CompressionParameters) -> Result> { - let total_pixels = width.checked_mul(height).ok_or(RawError::Limit("ORF image dimensions overflow"))?; - if total_pixels > 0 && stream.is_empty() { - return Err(RawError::Corrupt("ORF compressed stream is empty".into())); - } - // Reject streams too short to encode even 1 bit per pixel (prevents large allocation - // from a truncated file before we start decoding). - if total_pixels > 0 && (stream.len() as u64).saturating_mul(8) < total_pixels as u64 { - return Err(RawError::Corrupt("ORF compressed stream too short for frame".into())); - } - let mut pixels = vec![0u16; total_pixels]; - let mut reader = BitStream::new(stream); - - let gradient_threshold = 1u32.checked_shl(params.gradient_thresh_exp_641.min(30)).unwrap_or(1 << 5); - let flatness_threshold = 1i32.checked_shl(params.flatness_thresh_exp_645.min(30)).unwrap_or(1 << 4); - - let mut context = [0i32; 4]; - let mut last_predicted_sum = 0i32; - let mut pred1 = 0i32; - let mut raw_magnitude = 0u32; - let mut prev_magnitude_signed = 0i32; - - for row in 0..height { - let row_offset = row.checked_mul(width).ok_or(RawError::Limit("ORF row overflow"))?; - for col in 0..width { - let p = prev_magnitude_signed; - prev_magnitude_signed = raw_magnitude as i32; - - let psel = if col > 1 && flatness_threshold >= p { context[3].saturating_add(1) } else { 0 }; - context[3] = context[2]; - context[2] = psel; - - let mut rice_k = if col > 1 { - let p16 = (p as u32 & 0xffff) as u16; - let high_bit_count = if p16 == 0 { 0i32 } else { (16 - p16.leading_zeros()) as i32 }; - let t1 = if psel >= params.run_thresh_646 { params.table_648 } else { params.table_650 }; - let t2 = if psel >= params.run_thresh_646 { params.table_647 } else { params.table_649 }; - let tt = (high_bit_count - t1).max(-1); - t2.saturating_add(tt).saturating_add(1) - } else { - params.table_649 - }; - - if rice_k > params.max_rice_k { - rice_k = params.max_rice_k; - } - if rice_k >= 16 { - return Err(RawError::Corrupt("ORF compressed Rice parameter out of range".into())); - } - - let symbol = decode_entropy_symbol(&mut reader, rice_k.max(0) as u32, params); - let residual = symbol.signed_residual; - raw_magnitude = symbol.raw_magnitude; - let direct_bits_low0 = symbol.direct_bits_low0; - let direct_bits_sub3 = symbol.direct_bits_sub3; - - let (adjusted_residual, feedback_bits) = if params.direct_bits_sub3 > 0 { - let v = if col < 2 { 0 } else { pred1 }; - let v_plus_g = v.checked_add(residual).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; - if params.direct_bits_sub3 == 1 { - let g_mult = v_plus_g.checked_mul(2).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; - let g = (direct_bits_sub3 as i32).checked_add(g_mult).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; - let v_res = v.checked_add(g >> 1).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; - (g, v_res) - } else { - let g_mult = v_plus_g.checked_mul(4).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; - let g = (direct_bits_sub3 as i32).checked_add(g_mult).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; - let half_g = ((g >> 1) as u32 & 0xffff_fffe) as i32; - let v_res = half_g - .checked_add(v) - .and_then(|x| x.checked_add(g >> 2)) - .ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; - (g, v_res) - } - } else { - (residual, 0) - }; - - pred1 = context[0]; - context[0] = feedback_bits >> params.feedback_shift_644.min(30); - - let west = if col < 2 { params.boundary_predictor_642 } else { context[1] }; - let mut north = if row < 2 { - params.boundary_predictor_642 - } else { - pixels.get((row - 2) * width + col).map_or(params.boundary_predictor_642, |&v| (v as i32) >> params.direct_bits_low0.min(15)) - }; - let north_west = if row < 2 || col < 2 { - params.boundary_predictor_642 - } else { - pixels.get((row - 2) * width + col - 2).map_or(params.boundary_predictor_642, |&v| (v as i32) >> params.direct_bits_low0.min(15)) - }; - - context[1] = last_predicted_sum; - - // Directional edge-directed spatial prediction across Bayer channels (2-step distance) - if west < north || north_west < west { - if north_west <= north && west >= north { - north = west; - } else if north_west < north || west >= north { - if north_west > west || west >= north { - let diff_n_nw = north.abs_diff(north_west); - let diff_w_nw = west.abs_diff(north_west); - if diff_n_nw > gradient_threshold { - north = north.saturating_add(west.saturating_sub(north_west)); - } else if diff_w_nw <= gradient_threshold { - north = (north.saturating_add(west)) >> 1; - } else { - north = north.saturating_add(west.saturating_sub(north_west)); - } - } - } else { - north = west; - } - } - - let sum = adjusted_residual.checked_add(north).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; - last_predicted_sum = sum; - let final_sample = i64::from(direct_bits_low0).saturating_add(i64::from(sum) << params.direct_bits_low0.min(15)); - if let Some(px) = pixels.get_mut(row_offset + col) { - *px = final_sample.clamp(0, i64::from(u16::MAX)) as u16; - } - } - } - - let consumed_bits = reader.bits_loaded.saturating_sub(u64::from(reader.bits_available)); - if consumed_bits > (stream.len() as u64).saturating_mul(8) { - return Err(RawError::Corrupt("ORF compressed bitstream terminates prematurely".into())); - } - - Ok(pixels) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn stream_header_validation() { - assert!(validate_stream_header(&[0, 0, 0, 1, 0, 0], 4)); - assert!(validate_stream_header(&[0, 0, 0, 0, 0, 0, 0, 1, 0, 0], 8)); - assert!(!validate_stream_header(&[0, 0, 0, 2, 0, 0], 4)); // prefix != 1 - assert!(!validate_stream_header(&[0, 0, 0, 1, 0, 1], 4)); // trailer != [0, 0] - assert!(!validate_stream_header(&[0, 0, 0, 0], 5)); // truncated - assert!(!validate_stream_header(&[], 0)); // zero length - assert!(!validate_stream_header(&[0; 20], 9)); // > 8 bytes - } - - #[test] - fn bitstream_reader_operations() { - let data = [0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc]; - let mut stream = BitStream::new(&data); - assert_eq!(stream.read_bits(4), 1); - assert_eq!(stream.read_bits(4), 2); - assert_eq!(stream.read_bits(8), 0x34); - assert_eq!(stream.read_bits(16), 0x5678); - assert_eq!(stream.read_bits(8), 0x9a); - assert_eq!(stream.read_bits(8), 0xbc); - // past EOF reads padded zeros without panicking - assert_eq!(stream.read_bits(8), 0); - } - - #[test] - fn decompress_bounds_and_safety() { - let params = CompressionParameters { - direct_bits_low0: 0, - gradient_thresh_exp_641: 5, - boundary_predictor_642: 0, - direct_bits_sub3: 2, - feedback_shift_644: 5, - flatness_thresh_exp_645: 4, - run_thresh_646: 3, - table_647: 2, - table_648: 3, - table_649: 4, - table_650: 7, - max_rice_k: 15, - max_unary_run: 12, - header_prefix_len: 5, - valid_bits: 12, - }; - // empty stream returns error for nonempty image, succeeds for 0x0 - assert!(decompress_stream(&[], 10, 10, ¶ms).is_err()); - assert_eq!(decompress_stream(&[], 0, 0, ¶ms).unwrap(), Vec::::new()); - // truncated stream (too short for requested dimensions) returns error - assert!(decompress_stream(&[0xff; 2], 10, 10, ¶ms).is_err()); - assert!(decompress_stream(&[0x00; 2], 10, 10, ¶ms).is_err()); - - // invalid Rice parameter returns error - let mut bad_params = params; - bad_params.table_649 = 20; - bad_params.max_rice_k = 20; - assert!(decompress_stream(&[0xff; 32], 4, 4, &bad_params).is_err()); - } - - #[test] - fn predictor_extreme_difference_never_panics() { - assert_eq!(i32::MIN.abs_diff(0), 2_147_483_648u32); - assert_eq!(i32::MIN.abs_diff(i32::MAX), 4_294_967_295u32); - - let params = CompressionParameters { - direct_bits_low0: 0, - gradient_thresh_exp_641: 5, - boundary_predictor_642: 0, - direct_bits_sub3: 0, - feedback_shift_644: 5, - flatness_thresh_exp_645: 4, - run_thresh_646: 3, - table_647: 2, - table_648: 3, - table_649: 4, - table_650: 7, - max_rice_k: 15, - max_unary_run: 12, - header_prefix_len: 5, - valid_bits: 12, - }; - for fill in [0x00, 0x55, 0xaa, 0xff] { - let stream = vec![fill; 64]; - let _ = decompress_stream(&stream, 4, 4, ¶ms); - } - } -} diff --git a/crates/raw/tests/it/corpus.rs b/crates/raw/tests/it/corpus.rs index 2fd0c04796..0be98991de 100644 --- a/crates/raw/tests/it/corpus.rs +++ b/crates/raw/tests/it/corpus.rs @@ -17,6 +17,8 @@ fn corpus_root() -> PathBuf { /// Variants known not to decode yet (see the crate docs): matched against the lower-case file name. const KNOWN_UNSUPPORTED: &[&str] = &[ + "orf-olympus-em1.orf", // Compressed Olympus sensor decoding withdrawn pending provenance resolution. + "orf-olympus-em10iii.orf", "cr3-", // Unverified CRX coding variants; exact supported cases live in cr3_corpus.rs. "-he.nef", // Nikon High Efficiency (HE / HE★) NEF, issue #193 "sraw", // Canon sRAW / mRAW diff --git a/crates/raw/tests/it/olympus_samsung_corpus.rs b/crates/raw/tests/it/olympus_samsung_corpus.rs index f5579ba0a1..9218b4b93d 100644 --- a/crates/raw/tests/it/olympus_samsung_corpus.rs +++ b/crates/raw/tests/it/olympus_samsung_corpus.rs @@ -8,7 +8,7 @@ //! pinned only (its small JPEG gives r 0.59); its render was inspected by eye. //! Missing files are reported as skipped. -use lightcraft_raw::{RawData, decode, embedded_preview, probe_info}; +use lightcraft_raw::{RawData, RawError, RawFormat, decode, embedded_preview, probe, probe_info}; use std::path::{Path, PathBuf}; fn corpus() -> PathBuf { @@ -67,8 +67,6 @@ fn olympus_and_samsung_bodies_decode_like_the_camera_jpeg() { ("orf-olympus-e-330.orf", (3280, 2450), 0xc938_38fa_9822_c81a, true), ("orf-olympus-e-500.orf", (3360, 2504), 0x5e22_2ac8_17ed_89d9, true), ("orf-olympus-e-m5-mark-ii.orf", (9280, 6932), 0xa222_be38_c767_7782, true), - ("orf-olympus-em1.orf", (4640, 3472), 0xc61b_0bb3_5170_4735, true), - ("orf-olympus-em10iii.orf", (4640, 3472), 0xedc1_ec6d_15a8_a303, true), ("orf-olympus-pen-f.orf", (10400, 7796), 0x415e_bf27_092e_9897, true), ("orf-olympus-sh-2.orf", (4624, 3470), 0xb25b_8d24_4ade_1f3d, true), ("orf-olympus-sp510uz.orf", (3088, 2309), 0xa885_b7ca_83ba_02f1, true), @@ -114,3 +112,21 @@ fn olympus_and_samsung_bodies_decode_like_the_camera_jpeg() { } eprintln!("Olympus / Samsung bodies checked on {seen} files"); } + +/// The withdrawn compressed decoder must stay out of both sensor-decode and import-probe paths. +/// Camera JPEG extraction is independent of sensor decoding and remains available for preview-only imports. +#[test] +fn compressed_olympus_bodies_are_unsupported_with_embedded_previews() { + for name in ["orf-olympus-em1.orf", "orf-olympus-em10iii.orf"] { + let path = corpus().join("raw").join(name); + let Ok(bytes) = std::fs::read(&path) else { + lightcraft_testkit::skip!(Corpus, "{} absent", path.display()); + continue; + }; + assert_eq!(probe(&bytes), Some(RawFormat::Orf), "{name}"); + assert!(matches!(decode(&bytes), Err(RawError::Unsupported(why)) if why == "Olympus compressed ORF"), "{name}"); + assert!(matches!(probe_info(&bytes), Err(RawError::Unsupported(why)) if why == "Olympus compressed ORF"), "{name}"); + let jpeg = embedded_preview(&bytes).unwrap_or_else(|| panic!("{name}: no camera JPEG")); + assert!(jpeg.starts_with(&[0xff, 0xd8]) && jpeg.ends_with(&[0xff, 0xd9]), "{name}: invalid camera JPEG"); + } +} diff --git a/crates/segment/src/detector.rs b/crates/segment/src/detector.rs index c302aafe76..3099af44af 100644 --- a/crates/segment/src/detector.rs +++ b/crates/segment/src/detector.rs @@ -333,10 +333,117 @@ pub fn merge(out: &Output, threshold: f32) -> Option { merged.map(|logits| Prediction { logits, score: best }) } +/// Share of the largest candidate's area another needs to count among the photo's main subjects +/// (people in front, not the crowd behind them). +pub const PROMINENT: f32 = 0.25; + +/// Which candidates are the photo's subject, given each one's area (cells it selects) and, when the +/// camera recorded where it focused, whether it covers that point. The focus decides: the +/// candidates it falls on, with the others about as large either way (a group at the same +/// distance); a focus on none of them means the subject is something else (empty: the caller +/// selects what is at the point). +/// Without a focus: the largest, and the others about as large. +pub fn pick_prominent(areas: &[usize], on_focus: Option<&[bool]>) -> Vec { + let largest = |ks: &mut dyn Iterator| ks.filter_map(|k| areas.get(k).copied()).max().unwrap_or(0); + let near = |a: usize, of: usize| of > 0 && a as f32 >= PROMINENT * of as f32; + match on_focus { + Some(hit) => { + let focused: Vec = (0..areas.len()).filter(|k| hit.get(*k).copied().unwrap_or(false) && areas[*k] > 0).collect(); + if focused.is_empty() { + return Vec::new(); + } + // about as large as what is in focus, either way: much larger is nearer the camera + // than the focus, so out of focus too + let of = largest(&mut focused.iter().copied()); + let alike = |a: usize| near(a, of) && (a as f32) * PROMINENT <= of as f32; + (0..areas.len()).filter(|k| focused.contains(k) || alike(areas[*k])).collect() + } + None => { + let of = largest(&mut (0..areas.len())); + (0..areas.len()).filter(|k| near(areas[*k], of)).collect() + } + } +} + +/// The instances of several detector outputs (one per concept: "person", "animal") above +/// `threshold` that [`pick_prominent`] keeps, each with its share of its concept's semantic mask, +/// merged into one mask. `focus`: where the camera focused (normalized). `None` when nothing is kept. +pub fn subject(outs: &[Output], threshold: f32, focus: Option<(f32, f32)>) -> Option { + let s = |x: f32| 1.0 / (1.0 + (-x).exp()); + // (mask, score, concept) + let mut cands: Vec<(Vec, f32, usize)> = Vec::new(); + for (c, out) in outs.iter().enumerate() { + let presence = s(out.presence); + for (i, l) in out.logits.iter().enumerate() { + let p = s(*l) * presence; + if p > threshold + && let Some(m) = out.masks.i(i).ok().and_then(|t| to_vec(&t).ok()) + { + cands.push((m, p, c)); + } + } + } + let n = cands.first()?.0.len(); + let side = (n as f64).sqrt() as usize; + if side == 0 || side * side != n || cands.iter().any(|c| c.0.len() != n) { + return None; + } + let areas: Vec = cands.iter().map(|c| c.0.iter().filter(|l| **l > 0.0).count()).collect(); + let cell = focus.filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| { + let at = |v: f32| ((v.clamp(0.0, 1.0) * side as f32) as usize).min(side - 1); + at(y) * side + at(x) + }); + let hits: Option> = cell.map(|i| cands.iter().map(|c| c.0.get(i).is_some_and(|l| *l > 0.0)).collect()); + let keep = pick_prominent(&areas, hits.as_deref()); + if keep.is_empty() { + return None; + } + let best = keep.iter().filter_map(|k| cands.get(*k)).map(|c| c.1).fold(0f32, f32::max); + let mut merged: Option> = None; + for (c, out) in outs.iter().enumerate() { + let mut masks: Vec> = keep.iter().filter_map(|k| cands.get(*k)).filter(|x| x.2 == c).map(|x| x.0.clone()).collect(); + if masks.is_empty() { + continue; + } + share(&mut masks, &out.semantic); + for m in masks { + merged = Some(match merged { + Some(acc) => acc.iter().zip(&m).map(|(a, b)| a.max(*b)).collect(), + None => m, + }); + } + } + merged.map(|logits| Prediction { logits, score: best }) +} + #[cfg(test)] mod tests { use super::*; + /// A group in front is kept, the crowd behind isn't; the camera's focus decides: on a person, + /// that person and the others as large; on nobody, nothing (the object there is the subject). + #[test] + fn prominent_subjects() { + // four people in front, two small ones far behind + let areas = [900, 1000, 800, 950, 60, 40]; + assert_eq!(pick_prominent(&areas, None), vec![0, 1, 2, 3]); + // focused on the first: the group + let hit = [true, false, false, false, false, false]; + assert_eq!(pick_prominent(&areas, Some(&hit)), vec![0, 1, 2, 3]); + // focused on someone small behind: that one and whoever is about as large, not the + // (much larger, so nearer and out of focus) group in front + let hit = [false, false, false, false, true, false]; + assert_eq!(pick_prominent(&areas, Some(&hit)), vec![4, 5]); + // a product in front of people: the focus is on none of them + assert!(pick_prominent(&areas, Some(&[false; 6])).is_empty()); + // nobody at all, or empty masks + assert!(pick_prominent(&[], None).is_empty()); + assert!(pick_prominent(&[0, 0], None).is_empty()); + assert!(pick_prominent(&[0, 5], Some(&[true, false])).is_empty()); + // a mismatched focus list is read as "not on it" + assert_eq!(pick_prominent(&[10, 9], Some(&[true])), vec![0, 1]); + } + /// Two people side by side on a row of cells, each only weakly sure of themself and both fading where /// they touch; the semantic mask is sure of both and runs across. Each takes the semantic logits where /// it is the strongest instance, a third region nobody is near keeps its own. diff --git a/crates/segment/src/lib.rs b/crates/segment/src/lib.rs index 6fd077ff96..98a47d9888 100644 --- a/crates/segment/src/lib.rs +++ b/crates/segment/src/lib.rs @@ -76,9 +76,15 @@ pub type Result = std::result::Result; pub const INPUT: usize = 1008; /// Side of the low-resolution masks the model predicts. pub const MASK_SIDE: usize = 288; +/// Most clicks one Object selection may carry (the engine's `MAX_CLICKS`). +pub const MAX_CLICKS: usize = 64; #[cfg(not(target_arch = "wasm32"))] const _: () = assert!(MASK_SIDE == tracker::LOW_RES && INPUT == vit::IMAGE); +/// What a photo's subject usually is, as concept prompts ([`Sam3::segment_subject`]); anything else +/// (an object, a landscape's feature) is selected at the focus point instead. +pub const SUBJECT_CONCEPTS: &[&str] = &["person", "animal"]; + /// The files of a model directory. pub const WEIGHTS_FILE: &str = "model.safetensors"; @@ -203,6 +209,10 @@ impl Sam3 { if clicks.is_empty() { return Err(Error::Model("no clicks".into())); } + // the prompt grows with every click: the editor takes at most this many (the engine's `MAX_CLICKS`) + if clicks.len() > MAX_CLICKS { + return Err(Error::Model(format!("at most {MAX_CLICKS} clicks, not {}", clicks.len()))); + } let (neck, tracker) = self.tracker_parts()?; if enc.tracker.is_none() { let levels = neck.forward(&enc.backbone, 3)?; @@ -241,6 +251,15 @@ impl Sam3 { Ok(detector::merge(&out, threshold)) } + /// The photo's subject among its people and animals ([`detector::subject`]): the ones the + /// camera's focus (`focus`, normalized; `None` when the file doesn't record it) falls on, or + /// without it the most prominent, with whoever is about as large. `None` when the subject is + /// neither (a focus on something else, or nobody in the photo): select what is at the point. + pub fn segment_subject(&mut self, enc: &mut Encoded, focus: Option<(f32, f32)>, threshold: f32) -> Result> { + let outs = SUBJECT_CONCEPTS.iter().map(|c| self.detect(enc, c)).collect::>>()?; + Ok(detector::subject(&outs, threshold, focus)) + } + /// Raw detector outputs for `text` (tests and tools). pub fn detect(&mut self, enc: &mut Encoded, text: &str) -> Result { let (det, tok) = self.detector_parts()?; diff --git a/crates/segment/src/remote.rs b/crates/segment/src/remote.rs index 10f7b2931a..4f23d10bc7 100644 --- a/crates/segment/src/remote.rs +++ b/crates/segment/src/remote.rs @@ -17,6 +17,9 @@ pub enum Operation { Prepare, Clicks(Vec<[f32; 3]>), Text(String), + /// The photo's subject among its people and animals ([`Sam3::segment_subject`]), from where + /// the camera focused (normalized `[x, y]`) when the file records it. + Subject(Option<[f32; 2]>), } #[derive(Serialize, Deserialize)] @@ -36,7 +39,8 @@ impl Request { return Err("detail pass requires an image".into()); } match &self.operation { - Operation::Prepare => {} + Operation::Prepare | Operation::Subject(None) => {} + Operation::Subject(Some(f)) if f.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)) => {} Operation::Text(text) if text.len() <= 4096 && text.split([',', ';']).any(|p| !p.trim().is_empty()) => {} Operation::Clicks(clicks) if !clicks.is_empty() @@ -131,6 +135,11 @@ fn predict(model: &mut Sam3, enc: &mut Encoded, operation: Operation) -> Result< Ok(None) } Operation::Text(text) => text_logits(model, enc, &text).map_err(|e| e.to_string()), + // (the reference score threshold, as a local Find Subject uses) + Operation::Subject(focus) => { + let p = model.segment_subject(enc, focus.map(|f| (f[0], f[1])), 0.5).map_err(|e| e.to_string())?; + Ok(p.map(|p| p.logits)) + } Operation::Clicks(points) => { let clicks: Vec<_> = points.into_iter().map(|p| Click { x: p[0], y: p[1], positive: p[2] == 1.0 }).collect(); Ok(Some(model.segment_clicks(enc, &clicks).map_err(|e| e.to_string())?.logits)) diff --git a/crates/segment/tests/it/remote.rs b/crates/segment/tests/it/remote.rs index ee20ea2066..7b612425d3 100644 --- a/crates/segment/tests/it/remote.rs +++ b/crates/segment/tests/it/remote.rs @@ -18,4 +18,10 @@ fn validates_images_and_prompt_boundaries() { assert!(request(4, 3, Operation::Clicks(vec![[0.5, f32::NAN, 1.0]])).validate().is_err()); assert!(request(4, 3, Operation::Clicks(vec![[0.5, 0.5, 0.0]])).validate().is_err()); assert!(request(4, 3, Operation::Text(" ".into())).validate().is_err()); + // Find Subject: with or without the camera's focus point, which must lie in the photo + assert!(request(4, 3, Operation::Subject(None)).validate().is_ok()); + assert!(request(4, 3, Operation::Subject(Some([0.3, 0.7]))).validate().is_ok()); + for bad in [[1.5, 0.5], [0.5, -0.1], [f32::NAN, 0.5], [0.5, f32::INFINITY]] { + assert!(request(4, 3, Operation::Subject(Some(bad))).validate().is_err(), "{bad:?}"); + } } diff --git a/crates/slideshow/src/compose.rs b/crates/slideshow/src/compose.rs index 61ce91f3ff..87e4f1880e 100644 --- a/crates/slideshow/src/compose.rs +++ b/crates/slideshow/src/compose.rs @@ -220,7 +220,7 @@ pub fn compose_with( ) -> (Rgba8, Layout) { let s = s.clone().sanitized(); let (w, h) = slide_size(out_w, out_h); - let has_photo = photo.width > 0 && photo.height > 0 && photo.data.len() == photo.width * photo.height; + let has_photo = photo.width > 0 && photo.height > 0 && Some(photo.data.len()) == photo.width.checked_mul(photo.height); let aspect = if has_photo { photo.width as f64 / photo.height as f64 } else { f64::NAN }; let l = layout(&s, aspect, w, h); let c = s.backdrop_color; diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index ea10219217..5ba9c5098f 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2400,6 +2400,34 @@ "Save Current Settings as New Effect Preset…": "Uložit aktuální nastavení jako nové přednastavení efektu…", "Manage Effect Presets…": "Spravovat přednastavení efektů…", "Export Effect Presets…": "Exportovat přednastavení efektů…", + "Blur Amount": "Míra rozostření", + "Boost": "Zesílení", + "In Focus": "Zaostřeno", + "Blur what is out of focus, as a wide aperture would": "Rozostří, co je mimo zaostření, jako by to udělala široce otevřená clona", + "What stays sharp: the photo's subject, or the selection of one of its masks": "Co zůstane ostré: subjekt fotky nebo výběr jedné z jejích masek", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Tip: subjekt přesně vyberte maskou Objekt (Maskování, M) a pak tu masku zvolte zde.", + "Brush Refinement": "Doladění štětcem", + "Blur": "Rozostření", + "Paint what should stay sharp": "Namalujte, co má zůstat ostré", + "Paint what should be blurred": "Namalujte, co se má rozostřit", + "Remove the strokes of both brushes": "Odstranit tahy obou štětců", + "Find Subject": "Najít subjekt", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Vybrat subjekt pomocí AI (SAM 3), od místa, kam zaostřil fotoaparát, pokud ho soubor uvádí, a ponechat ho zaostřený", + "Selecting the subject at the camera's focus point…": "Vybírá se subjekt v bodě zaostření fotoaparátu…", + "Selecting the subject…": "Vybírá se subjekt…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Dolaďte ho v Maskování (M): + → Objekt přidá, co chybí, − → Objekt část vynechá.", + "Finding the subject… The first time on a photo takes a while.": "Hledá se subjekt… Poprvé to u fotky chvíli trvá.", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Subjekt nebyl vybrán. Zkuste znovu Najít subjekt, nebo na něj klikněte v Maskování (M).", + "Transition": "Přechod", + "Selection": "Výběr", + "Outside": "Mimo výběr", + "Shape": "Tvar", + "Round": "Kruh", + "Auto: the photo's subject, estimated": "Automaticky: odhadnutý subjekt fotky", + "Horizontal oval": "Vodorovný ovál", + "Vertical oval": "Svislý ovál", + "Move & Resize": "Přesunout a změnit velikost", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Tažením tvaru na fotce ho přesunete; tažením boční nebo spodní úchytky ho roztáhnete. Tlačítko tvaru ho vrátí doprostřed.", "Before/After Side by Side": "Před/Po vedle sebe", "Clipping": "Ořezání tónů", "Mask Overlay": "Překrytí masky", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index bc67606eb6..70fa252dc8 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3433,6 +3433,34 @@ "Optional remote SAM 3: keep the native editor local and run Object, Describe, and detail": "Optionales entferntes SAM 3: Der native Editor bleibt lokal, und Objekt-, Beschreibungs- und Detail-", "inference on a Mac through SSH. Saved masks still render and export offline.": "Inferenz laufen über SSH auf einem Mac. Gespeicherte Masken werden weiterhin offline gerendert und exportiert.", "See [remote Metal inference](ai-masks.md#remote-metal-inference).": "Siehe [remote Metal inference](ai-masks.md#remote-metal-inference).", + "Blur Amount": "Unschärfestärke", + "Boost": "Verstärkung", + "In Focus": "Im Fokus", + "Blur what is out of focus, as a wide aperture would": "Zeichnet unscharf, was außerhalb des Fokus liegt, wie eine weit geöffnete Blende", + "What stays sharp: the photo's subject, or the selection of one of its masks": "Was scharf bleibt: das Motiv des Fotos oder die Auswahl einer seiner Masken", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Tipp: Wählen Sie das Motiv mit einer Objekt-Maske (Maskieren, M) genau aus und wählen Sie diese Maske dann hier.", + "Brush Refinement": "Pinselkorrektur", + "Blur": "Unschärfe", + "Paint what should stay sharp": "Malen, was scharf bleiben soll", + "Paint what should be blurred": "Malen, was unscharf werden soll", + "Remove the strokes of both brushes": "Die Striche beider Pinsel entfernen", + "Find Subject": "Motiv finden", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Das Motiv per KI (SAM 3) auswählen, ausgehend vom Fokuspunkt der Kamera, wenn die Datei ihn enthält, und scharf halten", + "Selecting the subject at the camera's focus point…": "Motiv am Fokuspunkt der Kamera wird ausgewählt…", + "Selecting the subject…": "Motiv wird ausgewählt…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "In Maskieren (M) verfeinern: + → Objekt fügt Fehlendes hinzu, − → Objekt lässt einen Teil weg.", + "Finding the subject… The first time on a photo takes a while.": "Motiv wird gesucht… Beim ersten Mal dauert das bei einem Foto eine Weile.", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Das Motiv wurde nicht ausgewählt. Versuchen Sie erneut „Motiv finden“ oder klicken Sie es in Maskieren (M) an.", + "Transition": "Übergang", + "Selection": "Auswahl", + "Outside": "Außerhalb", + "Shape": "Form", + "Round": "Rund", + "Auto: the photo's subject, estimated": "Automatisch: das geschätzte Motiv des Fotos", + "Horizontal oval": "Liegendes Oval", + "Vertical oval": "Stehendes Oval", + "Move & Resize": "Verschieben & Größe", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Ziehen Sie die Form auf dem Foto, um sie zu verschieben; ziehen Sie den seitlichen oder unteren Griff, um sie zu dehnen. Eine Form-Schaltfläche setzt sie wieder in die Mitte.", "Before/After Side by Side": "Vorher/Nachher nebeneinander", "Clipping": "Beschneidung", "Mask Overlay": "Maskenüberlagerung", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 77d40f0ec0..eb5edf4866 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -172,7 +172,7 @@ "{n} photo{} now · updates automatically as photos change": "{n} foto{} ahora · se actualiza automáticamente cuando cambian las fotos", "{n} selected photo{} · {pages} page{}": "{n} foto{0} seleccionada{0} · {pages} página{1}", "{pid} (missing)": "{pid} (falta)", - "{sel_n} selected · {counted}": "{sel_n} seleccionadas · {counted}", + "{sel_n} selected · {counted}": "Seleccionadas: {sel_n} · {counted}", "{stage}… {:.0}%": "{stage}… {:.0}%", "{verb} {n} Photo{}": "{verb} {n} foto{}", "{weekday}, {day}": "{weekday}, {day}", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index c34057bdfe..7b07c40a1f 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2358,6 +2358,34 @@ "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "Un modelo de caras usa la GPU solo cuando una comprobación muestra que da los mismos resultados más rápido.", "Checking the GPU for faces": "Comprobando la GPU para las caras", + "Blur Amount": "Cantidad de desenfoque", + "Boost": "Realce", + "In Focus": "Enfocado", + "Blur what is out of focus, as a wide aperture would": "Desenfoca lo que está fuera de foco, como lo haría una apertura amplia", + "What stays sharp: the photo's subject, or the selection of one of its masks": "Lo que queda nítido: el sujeto de la foto o la selección de una de sus máscaras", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Consejo: selecciona el sujeto con precisión con una máscara Objeto (Máscaras, M) y luego elige esa máscara aquí.", + "Brush Refinement": "Refinamiento con pincel", + "Blur": "Desenfoque", + "Paint what should stay sharp": "Pinta lo que debe quedar nítido", + "Paint what should be blurred": "Pinta lo que debe desenfocarse", + "Remove the strokes of both brushes": "Quitar los trazos de ambos pinceles", + "Find Subject": "Buscar sujeto", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Selecciona el sujeto con IA (SAM 3), empezando donde enfocó la cámara si el archivo lo registra, y lo mantiene enfocado", + "Selecting the subject at the camera's focus point…": "Seleccionando el sujeto en el punto de enfoque de la cámara…", + "Selecting the subject…": "Seleccionando el sujeto…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Ajústalo en Máscaras (M): + → Objeto añade lo que faltó, − → Objeto excluye una parte.", + "Finding the subject… The first time on a photo takes a while.": "Buscando el sujeto… La primera vez en una foto tarda un poco.", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "No se seleccionó el sujeto. Vuelve a probar Buscar sujeto o haz clic en él en Máscaras (M).", + "Transition": "Transición", + "Selection": "Selección", + "Outside": "Fuera", + "Shape": "Forma", + "Round": "Redonda", + "Auto: the photo's subject, estimated": "Automático: el sujeto estimado de la foto", + "Horizontal oval": "Óvalo horizontal", + "Vertical oval": "Óvalo vertical", + "Move & Resize": "Mover y redimensionar", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Arrastra la forma en la foto para moverla; arrastra su tirador lateral o inferior para estirarla. Un botón de forma la devuelve al centro.", "Layout Image": "Imagen de diseño", "Detail View": "Vista de detalle", "Edit Panel": "Panel Editar", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 59cc611cd6..f06ce0d4d2 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2340,6 +2340,34 @@ "≤ at most": "≤ enintään", "≥ at least": "≥ vähintään", "★ Favorites": "★ Suosikit", + "Blur Amount": "Epätarkkuuden määrä", + "Boost": "Korostus", + "In Focus": "Tarkka alue", + "Blur what is out of focus, as a wide aperture would": "Sumentaa tarkennuksen ulkopuolisen alueen, kuten suuri aukko tekisi", + "What stays sharp: the photo's subject, or the selection of one of its masks": "Mikä pysyy tarkkana: kuvan kohde tai jonkin sen maskin valinta", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Vinkki: valitse kohde tarkasti Kohde-maskilla (Maskaus, M) ja valitse sitten se maski tästä.", + "Brush Refinement": "Siveltimellä tarkennus", + "Blur": "Sumennus", + "Paint what should stay sharp": "Maalaa, minkä pitää pysyä tarkkana", + "Paint what should be blurred": "Maalaa, minkä pitää sumentua", + "Remove the strokes of both brushes": "Poista molempien siveltimien vedot", + "Find Subject": "Etsi kohde", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Valitse kohde tekoälyllä (SAM 3) aloittaen kameran tarkennuskohdasta, jos tiedosto kertoo sen, ja pidä se tarkkana", + "Selecting the subject at the camera's focus point…": "Valitaan kohdetta kameran tarkennuspisteestä…", + "Selecting the subject…": "Valitaan kohdetta…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Hienosäädä Maskauksessa (M): + → Kohde lisää puuttuvan, − → Kohde jättää osan pois.", + "Finding the subject… The first time on a photo takes a while.": "Etsitään kohdetta… Ensimmäisellä kerralla kuvassa tämä kestää hetken.", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Kohdetta ei valittu. Kokeile Etsi kohde uudelleen tai napsauta sitä Maskauksessa (M).", + "Transition": "Siirtymä", + "Selection": "Valinta", + "Outside": "Ulkopuoli", + "Shape": "Muoto", + "Round": "Pyöreä", + "Auto: the photo's subject, estimated": "Automaattinen: kuvan arvioitu kohde", + "Horizontal oval": "Vaakasuora soikio", + "Vertical oval": "Pystysuora soikio", + "Move & Resize": "Siirrä ja muuta kokoa", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Siirrä muotoa vetämällä sitä kuvassa; venytä sitä vetämällä sivu- tai alakahvasta. Muotopainike palauttaa sen keskelle.", "All Mask Overlays": "Kaikki maskien peittokuvat", "Before/After Side by Side": "Ennen/jälkeen vierekkäin", "Clipping": "Leikkautuminen", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 31e6814b6d..e946c67346 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -2353,6 +2353,34 @@ "CPU": "Processeur", "A face model uses the GPU only when a check shows it gives the same results faster.": "Un modèle de visages n’utilise le GPU que si une vérification montre qu’il donne les mêmes résultats plus vite.", "Checking the GPU for faces": "Vérification du GPU pour les visages", + "Blur Amount": "Quantité de flou", + "Boost": "Accentuation", + "In Focus": "Zone nette", + "Blur what is out of focus, as a wide aperture would": "Floute ce qui est hors de la mise au point, comme le ferait une grande ouverture", + "What stays sharp: the photo's subject, or the selection of one of its masks": "Ce qui reste net : le sujet de la photo ou la sélection de l'un de ses masques", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Astuce : sélectionnez précisément le sujet avec un masque Objet (Masquage, M), puis choisissez ce masque ici.", + "Brush Refinement": "Affinage au pinceau", + "Blur": "Flou", + "Paint what should stay sharp": "Peignez ce qui doit rester net", + "Paint what should be blurred": "Peignez ce qui doit être flou", + "Remove the strokes of both brushes": "Supprimer les traits des deux pinceaux", + "Find Subject": "Trouver le sujet", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Sélectionne le sujet par IA (SAM 3), à partir de l'endroit où l'appareil a fait la mise au point si le fichier l'indique, et le garde net", + "Selecting the subject at the camera's focus point…": "Sélection du sujet au point de mise au point de l'appareil…", + "Selecting the subject…": "Sélection du sujet…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Affinez-le dans Masquage (M) : + → Objet ajoute ce qui manque, − → Objet exclut une partie.", + "Finding the subject… The first time on a photo takes a while.": "Recherche du sujet… La première fois sur une photo, cela prend un moment.", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Le sujet n'a pas été sélectionné. Réessayez Trouver le sujet, ou cliquez dessus dans Masquage (M).", + "Transition": "Transition", + "Selection": "Sélection", + "Outside": "Extérieur", + "Shape": "Forme", + "Round": "Ronde", + "Auto: the photo's subject, estimated": "Auto : le sujet estimé de la photo", + "Horizontal oval": "Ovale horizontal", + "Vertical oval": "Ovale vertical", + "Move & Resize": "Déplacer et redimensionner", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Faites glisser la forme sur la photo pour la déplacer ; faites glisser sa poignée latérale ou inférieure pour l'étirer. Un bouton de forme la remet au centre.", "Layout Image": "Image de mise en page", "Detail View": "Vue de détail", "Edit Panel": "Panneau Modifier", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 52705328cc..aac5874ad6 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2353,6 +2353,34 @@ "≥ at least": "≥ minimal", "日本語": "日本語", "繁體中文(台灣)": "繁體中文(台灣)", + "Blur Amount": "Jumlah buram", + "Boost": "Penguatan", + "In Focus": "Dalam fokus", + "Blur what is out of focus, as a wide aperture would": "Memburamkan bagian di luar fokus, seperti bukaan lebar", + "What stays sharp: the photo's subject, or the selection of one of its masks": "Yang tetap tajam: subjek foto, atau seleksi salah satu maskernya", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Tips: pilih subjek dengan tepat memakai masker Objek (Masker, M), lalu pilih masker itu di sini.", + "Brush Refinement": "Penyempurnaan kuas", + "Blur": "Buram", + "Paint what should stay sharp": "Lukis bagian yang harus tetap tajam", + "Paint what should be blurred": "Lukis bagian yang harus diburamkan", + "Remove the strokes of both brushes": "Hapus goresan kedua kuas", + "Find Subject": "Cari subjek", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Pilih subjek dengan AI (SAM 3), mulai dari titik fokus kamera bila file mencatatnya, lalu jaga tetap fokus", + "Selecting the subject at the camera's focus point…": "Memilih subjek di titik fokus kamera…", + "Selecting the subject…": "Memilih subjek…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Sempurnakan di Masker (M): + → Objek menambah yang terlewat, − → Objek mengecualikan bagian.", + "Finding the subject… The first time on a photo takes a while.": "Mencari subjek… Pertama kali pada sebuah foto butuh waktu.", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Subjek tidak terpilih. Coba Cari subjek lagi, atau klik subjeknya di Masker (M).", + "Transition": "Transisi", + "Selection": "Seleksi", + "Outside": "Luar", + "Shape": "Bentuk", + "Round": "Bulat", + "Auto: the photo's subject, estimated": "Otomatis: perkiraan subjek foto", + "Horizontal oval": "Oval horizontal", + "Vertical oval": "Oval vertikal", + "Move & Resize": "Pindah & ubah ukuran", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Seret bentuk di foto untuk memindahkannya; seret pegangan samping atau bawahnya untuk merenggangkannya. Tombol bentuk mengembalikannya ke tengah.", "All Mask Overlays": "Semua overlay masker", "Before/After Side by Side": "Sebelum/Sesudah berdampingan", "Clipping": "Clipping", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 5b0ccc0cee..743b94e890 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2394,6 +2394,34 @@ "Show briefly when photo changes": "Mostra brevemente al cambio di foto", "Camera & Lens": "Fotocamera e obiettivo", "View → View Options chooses the lines Info 1 and Info 2 show.": "Visualizza → Opzioni di visualizzazione sceglie le righe di Info 1 e Info 2.", + "Blur Amount": "Quantità di sfocatura", + "Boost": "Enfasi", + "In Focus": "A fuoco", + "Blur what is out of focus, as a wide aperture would": "Sfoca ciò che è fuori fuoco, come farebbe un diaframma molto aperto", + "What stays sharp: the photo's subject, or the selection of one of its masks": "Cosa resta nitido: il soggetto della foto o la selezione di una delle sue maschere", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Suggerimento: seleziona con precisione il soggetto con una maschera Oggetto (Mascheratura, M), poi scegli qui quella maschera.", + "Brush Refinement": "Rifinitura a pennello", + "Blur": "Sfocatura", + "Paint what should stay sharp": "Dipingi ciò che deve restare nitido", + "Paint what should be blurred": "Dipingi ciò che deve essere sfocato", + "Remove the strokes of both brushes": "Rimuovi le pennellate di entrambi i pennelli", + "Find Subject": "Trova soggetto", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Seleziona il soggetto con l'IA (SAM 3), partendo dal punto di messa a fuoco della fotocamera se il file lo registra, e lo mantiene a fuoco", + "Selecting the subject at the camera's focus point…": "Selezione del soggetto nel punto di messa a fuoco della fotocamera…", + "Selecting the subject…": "Selezione del soggetto…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Rifiniscilo in Mascheratura (M): + → Oggetto aggiunge ciò che manca, − → Oggetto esclude una parte.", + "Finding the subject… The first time on a photo takes a while.": "Ricerca del soggetto… La prima volta su una foto richiede un po' di tempo.", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Il soggetto non è stato selezionato. Riprova Trova soggetto, oppure fai clic su di esso in Mascheratura (M).", + "Transition": "Transizione", + "Selection": "Selezione", + "Outside": "Esterno", + "Shape": "Forma", + "Round": "Rotonda", + "Auto: the photo's subject, estimated": "Automatico: il soggetto stimato della foto", + "Horizontal oval": "Ovale orizzontale", + "Vertical oval": "Ovale verticale", + "Move & Resize": "Sposta e ridimensiona", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Trascina la forma sulla foto per spostarla; trascina la maniglia laterale o inferiore per allungarla. Un pulsante di forma la riporta al centro.", "Before/After Side by Side": "Prima/Dopo affiancati", "Clipping": "Tagli tonali", "Mask Overlay": "Sovrapposizione maschera", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 97c15dd019..6c83e8aaa3 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2356,6 +2356,34 @@ "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "顔モデルが GPU を使うのは、同じ結果をより速く出せると確認できた場合だけです。", "Checking the GPU for faces": "顔用の GPU を確認中", + "Blur Amount": "ぼかしの量", + "Boost": "ブースト", + "In Focus": "ピントを合わせる対象", + "Blur what is out of focus, as a wide aperture would": "絞りを大きく開いたように、ピントの外側をぼかします", + "What stays sharp: the photo's subject, or the selection of one of its masks": "シャープに残す部分:写真の被写体、またはいずれかのマスクの選択範囲", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "ヒント:オブジェクトマスク(マスク、M)で被写体を正確に選択してから、ここでそのマスクを選びます。", + "Brush Refinement": "ブラシで調整", + "Blur": "ぼかし", + "Paint what should stay sharp": "シャープに残す部分をペイント", + "Paint what should be blurred": "ぼかす部分をペイント", + "Remove the strokes of both brushes": "両方のブラシのストロークを削除", + "Find Subject": "被写体を検出", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "AI(SAM 3)で被写体を選択します。ファイルにカメラのフォーカス位置があればそこから始め、被写体にピントを保ちます", + "Selecting the subject at the camera's focus point…": "カメラのフォーカス位置で被写体を選択しています…", + "Selecting the subject…": "被写体を選択しています…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "マスク(M)で調整:+ → オブジェクトで不足分を追加、− → オブジェクトで一部を除外します。", + "Finding the subject… The first time on a photo takes a while.": "被写体を探しています… 写真ごとに初回は時間がかかります。", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "被写体を選択できませんでした。もう一度「被写体を検出」を試すか、マスク(M)で被写体をクリックしてください。", + "Transition": "トランジション", + "Selection": "選択範囲", + "Outside": "外側", + "Shape": "形", + "Round": "円形", + "Auto: the photo's subject, estimated": "自動:推定した写真の被写体", + "Horizontal oval": "横長の楕円", + "Vertical oval": "縦長の楕円", + "Move & Resize": "移動とサイズ変更", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "写真上の形をドラッグして移動します。横または下のハンドルをドラッグして伸ばします。形のボタンで中央に戻ります。", "Layout Image": "レイアウト画像", "Detail View": "詳細表示", "Edit Panel": "編集パネル", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 30769b60fa..423ea1cc47 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -2751,6 +2751,34 @@ "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-გადათრევა გასასწორებლად, ⇧G მართვადი Upright, ბადე გარდაქმნისას.", "日本語": "日本語", "繁體中文(台灣)": "繁體中文(台灣)", + "Blur Amount": "ბუნდოვნების რაოდენობა", + "Boost": "გაძლიერება", + "In Focus": "ფოკუსში", + "Blur what is out of focus, as a wide aperture would": "აბუნდოვნებს იმას, რაც ფოკუსის გარეთაა, როგორც ფართოდ გახსნილი დიაფრაგმა", + "What stays sharp: the photo's subject, or the selection of one of its masks": "რა რჩება მკვეთრი: ფოტოს საგანი ან მისი ერთ-ერთი ნიღბის მონიშვნა", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "რჩევა: საგანი ზუსტად მონიშნეთ ობიექტის ნიღბით (ნიღბვა, M), შემდეგ კი აქ აირჩიეთ ეს ნიღაბი.", + "Brush Refinement": "ფუნჯით დახვეწა", + "Blur": "ბუნდოვნება", + "Paint what should stay sharp": "მოხატეთ ის, რაც მკვეთრი უნდა დარჩეს", + "Paint what should be blurred": "მოხატეთ ის, რაც უნდა გაბუნდოვნდეს", + "Remove the strokes of both brushes": "ორივე ფუნჯის შტრიხების წაშლა", + "Find Subject": "საგნის პოვნა", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "საგნის მონიშვნა AI-ით (SAM 3) იქიდან, სადაც კამერამ ფოკუსირება მოახდინა, თუ ფაილი ამას ინახავს, და მისი ფოკუსში დატოვება", + "Selecting the subject at the camera's focus point…": "საგანი ინიშნება კამერის ფოკუსის წერტილში…", + "Selecting the subject…": "საგანი ინიშნება…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "დახვეწეთ ნიღბვაში (M): + → ობიექტი ამატებს გამორჩენილს, − → ობიექტი ნაწილს გამორიცხავს.", + "Finding the subject… The first time on a photo takes a while.": "საგანი იძებნება… ფოტოზე პირველად ამას გარკვეული დრო სჭირდება.", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "საგანი ვერ მოინიშნა. სცადეთ „საგნის პოვნა“ ხელახლა, ან დააწკაპეთ მასზე ნიღბვაში (M).", + "Transition": "გადასვლა", + "Selection": "მონიშნული", + "Outside": "გარეთ", + "Shape": "ფორმა", + "Round": "მრგვალი", + "Auto: the photo's subject, estimated": "ავტომატური: ფოტოს სავარაუდო საგანი", + "Horizontal oval": "ჰორიზონტალური ოვალი", + "Vertical oval": "ვერტიკალური ოვალი", + "Move & Resize": "გადატანა და ზომის შეცვლა", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "გადაიტანეთ ფორმა ფოტოზე მის გადასაადგილებლად; გაწიეთ გვერდითი ან ქვედა სახელური მის გასაჭიმად. ფორმის ღილაკი მას შუაში დააბრუნებს.", "Focus Point": "ფოკუსის წერტილი", "Layout Image": "განლაგების სურათი", "Detail View": "დეტალური ხედი", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index dbc29a1941..c4954eb3a8 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2275,6 +2275,35 @@ "SDR Whites": "Biele SDR", "SDR Clarity": "Przejrzystość SDR", "Face Models on the GPU": "Modele twarzy przetwarzane na GPU", + "Blur Amount": "Siła rozmycia", + "Boost": "Wzmocnienie", + "In Focus": "Ostrość na", + "Blur what is out of focus, as a wide aperture would": "Rozmywa to, co jest poza ostrością, jak szeroko otwarta przysłona", + "What stays sharp: the photo's subject, or the selection of one of its masks": "Co pozostaje ostre: główny obiekt zdjęcia lub zaznaczenie jednej z jego masek", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Wskazówka: precyzyjnie zaznacz obiekt maską Obiekt (Maskowanie, M), a potem wybierz tę maskę tutaj.", + "Brush Refinement": "Korekta pędzlem", + "Focus": "Ostrość", + "Blur": "Rozmycie", + "Paint what should stay sharp": "Zamaluj to, co ma pozostać ostre", + "Paint what should be blurred": "Zamaluj to, co ma zostać rozmyte", + "Remove the strokes of both brushes": "Usuń pociągnięcia obu pędzli", + "Find Subject": "Znajdź obiekt", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Zaznacz główny obiekt za pomocą AI (SAM 3), zaczynając od punktu ostrości aparatu, jeśli plik go zapisuje, i zachowaj go ostrym", + "Selecting the subject at the camera's focus point…": "Zaznaczanie obiektu w punkcie ostrości aparatu…", + "Selecting the subject…": "Zaznaczanie obiektu…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Popraw w Maskowaniu (M): + → Obiekt dodaje to, czego brakuje, − → Obiekt pomija część.", + "Finding the subject… The first time on a photo takes a while.": "Wyszukiwanie obiektu… Za pierwszym razem na zdjęciu trwa to chwilę.", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Nie zaznaczono obiektu. Spróbuj ponownie Znajdź obiekt lub kliknij go w Maskowaniu (M).", + "Transition": "Przejście", + "Selection": "Zaznaczenie", + "Outside": "Na zewnątrz", + "Shape": "Kształt", + "Round": "Okrągły", + "Auto: the photo's subject, estimated": "Automatycznie: szacowany główny obiekt zdjęcia", + "Horizontal oval": "Owal poziomy", + "Vertical oval": "Owal pionowy", + "Move & Resize": "Przesuń i zmień rozmiar", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Przeciągnij kształt na zdjęciu, aby go przesunąć; przeciągnij uchwyt boczny lub dolny, aby go rozciągnąć. Przycisk kształtu przywraca go na środek.", "Before/After Side by Side": "Przed/Po obok siebie", "Clipping": "Prześwietlenia i niedoświetlenia", "Mask Overlay": "Nakładka maski", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index 4227fe328a..762eed671a 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -130,7 +130,7 @@ "{n} photo{} match · updates automatically as photos change": "{n} foto{0} correspondente{0} · atualiza automaticamente conforme as fotos mudam", "{n} photo{} now · updates automatically as photos change": "{n} foto{} agora · atualiza automaticamente conforme as fotos mudam", "{n} selected photo{} · {pages} page{}": "{n} foto{0} selecionada{0} · {pages} página{1}", - "{sel_n} selected · {counted}": "{sel_n} selecionadas · {counted}", + "{sel_n} selected · {counted}": "Selecionadas: {sel_n} · {counted}", "{stage}… {:.0}%": "{stage}… {:.0}%", "{verb} {n} Photo{}": "{verb} {n} foto{}", "{weekday}, {day}": "{weekday}, {day}", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 3aedd82906..c1e59c59a4 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2202,6 +2202,34 @@ "Image on Black": "Imagem sobre preto", "Image on White": "Imagem sobre branco", "White on Black": "Branco sobre preto", + "Blur Amount": "Intensidade do desfoque", + "Boost": "Realce", + "In Focus": "Em foco", + "Blur what is out of focus, as a wide aperture would": "Desfoca o que está fora de foco, como faria uma abertura ampla", + "What stays sharp: the photo's subject, or the selection of one of its masks": "O que fica nítido: o assunto da foto ou a seleção de uma de suas máscaras", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Dica: selecione o assunto com precisão usando uma máscara Objeto (Máscara, M) e escolha essa máscara aqui.", + "Brush Refinement": "Refinamento com pincel", + "Blur": "Desfoque", + "Paint what should stay sharp": "Pinte o que deve ficar nítido", + "Paint what should be blurred": "Pinte o que deve ser desfocado", + "Remove the strokes of both brushes": "Remover os traços dos dois pincéis", + "Find Subject": "Encontrar assunto", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Seleciona o assunto com IA (SAM 3), começando onde a câmera focou quando o arquivo registra isso, e o mantém em foco", + "Selecting the subject at the camera's focus point…": "Selecionando o assunto no ponto de foco da câmera…", + "Selecting the subject…": "Selecionando o assunto…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Refine em Máscara (M): + → Objeto acrescenta o que faltou, − → Objeto deixa uma parte de fora.", + "Finding the subject… The first time on a photo takes a while.": "Encontrando o assunto… Na primeira vez em uma foto, isso demora um pouco.", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "O assunto não foi selecionado. Tente Encontrar assunto de novo ou clique nele em Máscara (M).", + "Transition": "Transição", + "Selection": "Seleção", + "Outside": "Fora", + "Shape": "Formato", + "Round": "Redondo", + "Auto: the photo's subject, estimated": "Automático: o assunto estimado da foto", + "Horizontal oval": "Oval horizontal", + "Vertical oval": "Oval vertical", + "Move & Resize": "Mover e redimensionar", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Arraste o formato na foto para movê-lo; arraste a alça lateral ou inferior para esticá-lo. Um botão de formato o devolve ao centro.", "Layout Image": "Imagem de layout", "Detail View": "Exibição de detalhe", "Edit Panel": "Painel Editar", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index b3df02470e..258dae60bf 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2564,6 +2564,34 @@ "CPU": "ЦП", "A face model uses the GPU only when a check shows it gives the same results faster.": "Модель лиц использует ГП, только если проверка показала, что он даёт те же результаты быстрее.", "Checking the GPU for faces": "Проверка ГП для лиц", + "Blur Amount": "Сила размытия", + "Boost": "Усиление", + "In Focus": "В фокусе", + "Blur what is out of focus, as a wide aperture would": "Размывает то, что вне фокуса, как широко открытая диафрагма", + "What stays sharp: the photo's subject, or the selection of one of its masks": "Что остаётся резким: главный объект фото или выделение одной из его масок", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Совет: точно выделите объект маской «Объект» (Маски, M), затем выберите эту маску здесь.", + "Brush Refinement": "Уточнение кистью", + "Blur": "Размытие", + "Paint what should stay sharp": "Закрасьте то, что должно остаться резким", + "Paint what should be blurred": "Закрасьте то, что нужно размыть", + "Remove the strokes of both brushes": "Удалить мазки обеих кистей", + "Find Subject": "Найти главный объект", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Выделить главный объект с помощью ИИ (SAM 3), начиная с точки фокусировки камеры, если файл её хранит, и оставить его в фокусе", + "Selecting the subject at the camera's focus point…": "Выделяется объект в точке фокусировки камеры…", + "Selecting the subject…": "Выделяется объект…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Уточните в Масках (M): + → Объект добавляет пропущенное, − → Объект исключает часть.", + "Finding the subject… The first time on a photo takes a while.": "Поиск главного объекта… В первый раз на снимке это занимает время.", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Объект не выделен. Попробуйте «Найти главный объект» ещё раз или щёлкните по нему в Масках (M).", + "Transition": "Переход", + "Selection": "Выделение", + "Outside": "Снаружи", + "Shape": "Форма", + "Round": "Круг", + "Auto: the photo's subject, estimated": "Авто: предполагаемый главный объект снимка", + "Horizontal oval": "Горизонтальный овал", + "Vertical oval": "Вертикальный овал", + "Move & Resize": "Переместить и изменить размер", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Перетащите форму на снимке, чтобы переместить её; потяните за боковой или нижний маркер, чтобы растянуть. Кнопка формы вернёт её в центр.", "Layout Image": "Изображение макета", "Detail View": "Режим детализации", "Edit Panel": "Панель «Правка»", diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 124fcb3a18..e205ea56a9 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -253,7 +253,7 @@ "{pct} %": "{pct} %", "{photos} catalog records processed; {collections} collections.": "{photos} katalogposter bearbetade; {collections} samlingar.", "{pid} (missing)": "{pid} (saknas)", - "{sel_n} selected · {counted}": "{sel_n} markerade · {counted}", + "{sel_n} selected · {counted}": "Markerade: {sel_n} · {counted}", "{size} GB": "{size} GB", "{stage}… {:.0}%": "{stage}… {:.0} %", "{s} s of AV1 video": "{s} s AV1-video", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 94b9e30333..8b454e0b2d 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2437,6 +2437,35 @@ "★ Favorites": "★ Favoriter", "日本語": "日本語", "繁體中文(台灣)": "繁體中文(台灣)", + "Blur Amount": "Oskärpemängd", + "Boost": "Förstärkning", + "In Focus": "I fokus", + "Blur what is out of focus, as a wide aperture would": "Gör det som är utanför fokus oskarpt, som en stor bländaröppning", + "What stays sharp: the photo's subject, or the selection of one of its masks": "Det som förblir skarpt: fotots motiv eller markeringen i en av dess masker", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Tips: markera motivet exakt med en Objekt-mask (Maskering, M) och välj sedan den masken här.", + "Brush Refinement": "Penselförfining", + "Focus": "Fokus", + "Blur": "Oskärpa", + "Paint what should stay sharp": "Måla det som ska förbli skarpt", + "Paint what should be blurred": "Måla det som ska bli oskarpt", + "Remove the strokes of both brushes": "Ta bort penseldragen från båda penslarna", + "Find Subject": "Hitta motiv", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Markera motivet med AI (SAM 3) med start där kameran fokuserade, om filen anger det, och håll det i fokus", + "Selecting the subject at the camera's focus point…": "Markerar motivet vid kamerans fokuspunkt…", + "Selecting the subject…": "Markerar motivet…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Förfina i Maskering (M): + → Objekt lägger till det som saknas, − → Objekt utesluter en del.", + "Finding the subject… The first time on a photo takes a while.": "Söker motivet… Första gången i ett foto tar det en stund.", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Motivet markerades inte. Försök med Hitta motiv igen, eller klicka på det i Maskering (M).", + "Transition": "Övergång", + "Selection": "Markering", + "Outside": "Utanför", + "Shape": "Form", + "Round": "Rund", + "Auto: the photo's subject, estimated": "Auto: fotots uppskattade motiv", + "Horizontal oval": "Vågrät oval", + "Vertical oval": "Lodrät oval", + "Move & Resize": "Flytta och ändra storlek", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Dra formen i fotot för att flytta den; dra i dess sido- eller nederhandtag för att sträcka den. En formknapp sätter tillbaka den i mitten.", "All Mask Overlays": "Alla masköverlägg", "Before/After Side by Side": "Före/efter sida vid sida", "Clipping": "Klippning", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 09b78fab1e..b4d3e50020 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2354,6 +2354,34 @@ "CPU": "ЦП", "A face model uses the GPU only when a check shows it gives the same results faster.": "Модель облич використовує ГП, лише якщо перевірка показала, що він дає ті самі результати швидше.", "Checking the GPU for faces": "Перевірка ГП для облич", + "Blur Amount": "Сила розмиття", + "Boost": "Підсилення", + "In Focus": "У фокусі", + "Blur what is out of focus, as a wide aperture would": "Розмиває те, що поза фокусом, як широко відкрита діафрагма", + "What stays sharp: the photo's subject, or the selection of one of its masks": "Що лишається різким: головний об’єкт фото або виділення однієї з його масок", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Порада: точно виділіть об’єкт маскою «Об’єкт» (Маскування, M), а потім виберіть цю маску тут.", + "Brush Refinement": "Уточнення пензлем", + "Blur": "Розмиття", + "Paint what should stay sharp": "Зафарбуйте те, що має лишитися різким", + "Paint what should be blurred": "Зафарбуйте те, що треба розмити", + "Remove the strokes of both brushes": "Видалити мазки обох пензлів", + "Find Subject": "Знайти об’єкт", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Виділити головний об’єкт за допомогою ШІ (SAM 3), починаючи з точки фокусування камери, якщо файл її зберігає, і залишити його у фокусі", + "Selecting the subject at the camera's focus point…": "Виділяється об’єкт у точці фокусування камери…", + "Selecting the subject…": "Виділяється об’єкт…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Уточніть у Маскуванні (M): + → Об’єкт додає пропущене, − → Об’єкт виключає частину.", + "Finding the subject… The first time on a photo takes a while.": "Пошук об’єкта… Уперше на знімку це триває певний час.", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Об’єкт не виділено. Спробуйте «Знайти об’єкт» ще раз або клацніть на ньому в Маскуванні (M).", + "Transition": "Перехід", + "Selection": "Виділення", + "Outside": "Зовні", + "Shape": "Форма", + "Round": "Коло", + "Auto: the photo's subject, estimated": "Авто: імовірний головний об’єкт фото", + "Horizontal oval": "Горизонтальний овал", + "Vertical oval": "Вертикальний овал", + "Move & Resize": "Перемістити й змінити розмір", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Перетягніть форму на фото, щоб перемістити її; потягніть боковий або нижній маркер, щоб розтягнути. Кнопка форми поверне її в центр.", "Layout Image": "Зображення макета", "Detail View": "Детальне подання", "Edit Panel": "Панель «Редагування»", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index af27e9aa0a..5840e84b5f 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2246,6 +2246,34 @@ "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-kéo để chỉnh thẳng, ⇧G Chỉnh thẳng có hướng dẫn, lưới khi biến đổi.", "日本語": "日本語", "繁體中文(台灣)": "繁體中文(台灣)", + "Blur Amount": "Mức làm mờ", + "Boost": "Tăng cường", + "In Focus": "Vùng nét", + "Blur what is out of focus, as a wide aperture would": "Làm mờ phần nằm ngoài vùng lấy nét, như khi mở khẩu độ lớn", + "What stays sharp: the photo's subject, or the selection of one of its masks": "Phần giữ nét: chủ thể của ảnh hoặc vùng chọn của một trong các mặt nạ", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Mẹo: chọn chính xác chủ thể bằng mặt nạ Đối tượng (Mặt nạ, M), rồi chọn mặt nạ đó tại đây.", + "Brush Refinement": "Tinh chỉnh bằng cọ", + "Blur": "Làm mờ", + "Paint what should stay sharp": "Tô vùng cần giữ nét", + "Paint what should be blurred": "Tô vùng cần làm mờ", + "Remove the strokes of both brushes": "Xóa nét vẽ của cả hai cọ", + "Find Subject": "Tìm chủ thể", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Chọn chủ thể bằng AI (SAM 3), bắt đầu từ điểm lấy nét của máy ảnh nếu tệp có ghi, và giữ chủ thể nét", + "Selecting the subject at the camera's focus point…": "Đang chọn chủ thể tại điểm lấy nét của máy ảnh…", + "Selecting the subject…": "Đang chọn chủ thể…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Tinh chỉnh trong Mặt nạ (M): + → Đối tượng thêm phần còn thiếu, − → Đối tượng bỏ một phần.", + "Finding the subject… The first time on a photo takes a while.": "Đang tìm chủ thể… Lần đầu trên một ảnh sẽ mất một lúc.", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Chưa chọn được chủ thể. Thử Tìm chủ thể lần nữa, hoặc nhấp vào chủ thể trong Mặt nạ (M).", + "Transition": "Chuyển tiếp", + "Selection": "Vùng chọn", + "Outside": "Bên ngoài", + "Shape": "Hình dạng", + "Round": "Tròn", + "Auto: the photo's subject, estimated": "Tự động: chủ thể ước tính của ảnh", + "Horizontal oval": "Hình bầu dục ngang", + "Vertical oval": "Hình bầu dục dọc", + "Move & Resize": "Di chuyển & đổi kích thước", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Kéo hình trên ảnh để di chuyển; kéo tay nắm bên hoặc dưới để kéo giãn. Nút hình dạng đưa nó về giữa.", "All Mask Overlays": "Mọi lớp phủ mặt nạ", "Before/After Side by Side": "Trước/Sau cạnh nhau", "Clipping": "Vùng cắt tông", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index ca13d782a5..ec20786825 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2194,6 +2194,34 @@ "This build cannot run recognition models: they can be added and chosen, not used.": "此版本无法运行识别模型:可以添加和选择,但无法使用。", "Detect Faces (Photo menu) needs it: a small one-time download.": "“检测人脸”(照片菜单)依赖它:一次性小文件下载。", "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "此版本无法存放人脸模型,因此模型列表不可用。(桌面版可以存放。)", + "Blur Amount": "模糊量", + "Boost": "增强", + "In Focus": "对焦范围", + "Blur what is out of focus, as a wide aperture would": "像大光圈一样模糊焦外区域", + "What stays sharp: the photo's subject, or the selection of one of its masks": "保持清晰的部分:照片的主体,或其某个蒙版的选区", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "提示:先用“对象”蒙版(蒙版,M)精确选择主体,再在此处选择该蒙版。", + "Brush Refinement": "画笔调整", + "Blur": "模糊", + "Paint what should stay sharp": "涂抹需要保持清晰的部分", + "Paint what should be blurred": "涂抹需要模糊的部分", + "Remove the strokes of both brushes": "移除两种画笔的笔触", + "Find Subject": "查找主体", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "使用 AI(SAM 3)选择主体:若文件记录了相机的对焦点,则从该处开始,并保持主体清晰", + "Selecting the subject at the camera's focus point…": "正在相机对焦点处选择主体…", + "Selecting the subject…": "正在选择主体…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "在蒙版(M)中细化:+ → 对象 添加遗漏部分,− → 对象 排除某部分。", + "Finding the subject… The first time on a photo takes a while.": "正在查找主体… 每张照片第一次需要一些时间。", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "未能选中主体。请再次尝试“查找主体”,或在蒙版(M)中单击主体。", + "Transition": "过渡", + "Selection": "选区", + "Outside": "外部", + "Shape": "形状", + "Round": "圆形", + "Auto: the photo's subject, estimated": "自动:估计的照片主体", + "Horizontal oval": "水平椭圆", + "Vertical oval": "垂直椭圆", + "Move & Resize": "移动和调整大小", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "在照片上拖动形状以移动它;拖动其侧边或底部手柄以拉伸。形状按钮会让它回到中间。", "Before/After Side by Side": "修改前/修改后左右排列", "Clipping": "溢出警告", "Mask Overlay": "蒙版叠加", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index f3dfc422ec..f84f851102 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2158,6 +2158,34 @@ "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "只有在檢查顯示 GPU 能更快得出相同結果時,臉孔模型才會使用 GPU。", "Checking the GPU for faces": "正在檢查用於臉孔的 GPU", + "Blur Amount": "模糊量", + "Boost": "增強", + "In Focus": "對焦範圍", + "Blur what is out of focus, as a wide aperture would": "像大光圈一樣模糊焦外區域", + "What stays sharp: the photo's subject, or the selection of one of its masks": "保持清晰的部分:相片的主體,或其某個遮色片的選取範圍", + "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "提示:先用「物件」遮色片(遮色片,M)精確選取主體,再於此處選擇該遮色片。", + "Brush Refinement": "筆刷調整", + "Blur": "模糊", + "Paint what should stay sharp": "塗抹需要保持清晰的部分", + "Paint what should be blurred": "塗抹需要模糊的部分", + "Remove the strokes of both brushes": "移除兩種筆刷的筆觸", + "Find Subject": "尋找主體", + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "使用 AI(SAM 3)選取主體:若檔案記錄了相機的對焦點,則從該處開始,並保持主體清晰", + "Selecting the subject at the camera's focus point…": "正在相機對焦點選取主體…", + "Selecting the subject…": "正在選取主體…", + "Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "在遮色片(M)中調整:+ → 物件 加入遺漏部分,− → 物件 排除某部分。", + "Finding the subject… The first time on a photo takes a while.": "正在尋找主體… 每張相片第一次需要一些時間。", + "The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "未能選取主體。請再次嘗試「尋找主體」,或在遮色片(M)中按一下主體。", + "Transition": "過渡", + "Selection": "選取範圍", + "Outside": "外部", + "Shape": "形狀", + "Round": "圓形", + "Auto: the photo's subject, estimated": "自動:估計的相片主體", + "Horizontal oval": "水平橢圓", + "Vertical oval": "垂直橢圓", + "Move & Resize": "移動和調整大小", + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "在相片上拖曳形狀以移動它;拖曳其側邊或底部控點以拉伸。形狀按鈕會讓它回到中間。", "Layout Image": "版面圖像", "Detail View": "詳細檢視", "Edit Panel": "編輯面板", diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 74425972d8..6d9faaafc9 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -108,6 +108,7 @@ impl LightcraftApp { compare_windows: [None; 2], compare_tiles: Default::default(), compare_hold_until: f64::NEG_INFINITY, + survey_motion: Default::default(), merge: merge::MergeState::default(), import: None, scan: None, diff --git a/crates/ui-egui/src/dialogs/lightroom_destination.rs b/crates/ui-egui/src/dialogs/lightroom_destination.rs index 5fd781cfdd..fb681c250e 100644 --- a/crates/ui-egui/src/dialogs/lightroom_destination.rs +++ b/crates/ui-egui/src/dialogs/lightroom_destination.rs @@ -99,7 +99,7 @@ pub fn default_location(app: &LightcraftApp) -> Option { } /// The new library's default name: the catalog's file name without `.lrcat` (`Travel.lrcat` → -/// `Travel`), or `Travel 2`, `Travel 3`… when `location` has something by that name already. +/// `Travel`; a backup's `Travel.zip` gives `Travel` too), or `Travel 2`, `Travel 3`… when `location` has something by that name already. pub fn default_name(catalog: &Path, location: Option<&Path>) -> String { let stem = catalog.file_stem().map(|s| s.to_string_lossy().trim().to_string()).filter(|s| !s.is_empty()); let stem = stem.unwrap_or_else(|| "Lightroom Catalog".to_string()); @@ -353,6 +353,7 @@ mod tests { fn the_new_library_is_named_after_the_catalog() { assert_eq!(default_name(Path::new("/x/Travel.lrcat"), None), "Travel"); assert_eq!(default_name(Path::new("/x/Lightroom Catalog-v13-3.lrcat"), None), "Lightroom Catalog-v13-3"); + assert_eq!(default_name(Path::new("/x/Backups/2026-10-22 1200/Travel.zip"), None), "Travel"); // nothing to name it after assert_eq!(default_name(Path::new(""), None), "Lightroom Catalog"); // a name taken in the location: the next free one diff --git a/crates/ui-egui/src/dialogs/settings/libraries.rs b/crates/ui-egui/src/dialogs/settings/libraries.rs index 5e615bfbcb..4e8d2a10d1 100644 --- a/crates/ui-egui/src/dialogs/settings/libraries.rs +++ b/crates/ui-egui/src/dialogs/settings/libraries.rs @@ -85,6 +85,9 @@ fn switch_library(app: &mut LightcraftApp, path: &str) -> Result app.ui.dialog = None; } app.renderer.forget_all(); + // photo ids are local to a catalog: a survey tile of the next library must not glide from a + // cell of this one, nor keep its render slot + app.survey_motion = Default::default(); if let Err(err) = opened { let Some(prev) = previous_dir else { return Err(err) }; return match app.session.open_library(&prev, false) { diff --git a/crates/ui-egui/src/dialogs/updates_ui.rs b/crates/ui-egui/src/dialogs/updates_ui.rs index 27f7d0c13b..ee42c37681 100644 --- a/crates/ui-egui/src/dialogs/updates_ui.rs +++ b/crates/ui-egui/src/dialogs/updates_ui.rs @@ -21,6 +21,7 @@ pub(crate) struct Runtime { #[cfg(not(target_arch = "wasm32"))] repaint: Option, /// A requested check's result dialog is showing. + #[cfg(target_arch = "wasm32")] pub(crate) manual_window_open: bool, #[cfg(target_arch = "wasm32")] pub(crate) status_message: Option, @@ -37,6 +38,7 @@ impl Default for Runtime { check_requested: false, #[cfg(not(target_arch = "wasm32"))] repaint: None, + #[cfg(target_arch = "wasm32")] manual_window_open: false, #[cfg(target_arch = "wasm32")] status_message: None, @@ -50,6 +52,13 @@ impl LightcraftApp { pub fn set_startup_update_check(&mut self, on: bool) { self.updates_rt.startup_check = on; } + + /// Starts the helper of a ready update, which installs it once the process has exited. Call it + /// in `on_exit` when the process ends there without dropping the app. + #[cfg(not(target_arch = "wasm32"))] + pub fn start_pending_update(&mut self) { + self.updates_rt.updater.start_pending_update(); + } } /// The update prompt owns the keyboard while it is open: shortcuts must not reach the library behind it. @@ -89,7 +98,6 @@ pub(crate) fn tick(app: &mut LightcraftApp, ctx: &egui::Context) { rt.repaint = Some(ctx.clone()); if std::mem::take(&mut rt.check_requested) { rt.updater.check_now(ctx); - rt.manual_window_open = true; } else if rt.startup_check { rt.updater.check_at_start(ctx); } @@ -99,10 +107,18 @@ pub(crate) fn tick(app: &mut LightcraftApp, ctx: &egui::Context) { let _ = (app, ctx); } +/// Whether the result dialog shows: for every status but idle (a requested check, and the first +/// start after an update, which reports that it installed or why it failed), and never over the +/// startup prompt. +#[cfg(not(target_arch = "wasm32"))] +fn result_window_shows(status: &Status, prompt_open: bool) -> bool { + !prompt_open && !matches!(status, Status::Idle) +} + pub(crate) fn show(app: &mut LightcraftApp, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] { - // The restart helper is scheduled before the app closes, so no update starts over unsaved work. + // The close for a ready update waits until nothing is unsaved. let clean = app.session.unsaved().is_none(); match app.updates_rt.updater.show_if(ctx, clean) { Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)), @@ -111,20 +127,16 @@ pub(crate) fn show(app: &mut LightcraftApp, ctx: &egui::Context) { } // A found update opens the startup prompt and leaves the status idle, which ends the result dialog. let rt = &mut app.updates_rt; - if rt.manual_window_open { + if result_window_shows(rt.updater.status(), rt.updater.prompt_open()) { let dialog = CheckResultDialog::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")); match dialog.show(ctx, rt.updater.status()) { CheckResultResponse::None => {} - CheckResultResponse::Close => rt.manual_window_open = false, + // Closing the dialog dismisses the outcome it showed. + CheckResultResponse::Close => rt.updater.dismiss_status(), CheckResultResponse::CheckAgain => rt.check_requested = true, + // The next `show_if` asks the window to close once nothing is unsaved. + CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(), } - if matches!(rt.updater.status(), Status::Idle) { - rt.manual_window_open = false; - } - } - // Closing the dialog dismisses the outcome it showed. - if !rt.manual_window_open { - rt.updater.dismiss_status(); } } @@ -163,6 +175,7 @@ mod tests { #[test] fn default_runtime_is_idle() { let rt = Runtime::default(); + #[cfg(target_arch = "wasm32")] assert!(!rt.manual_window_open); #[cfg(not(target_arch = "wasm32"))] { @@ -192,4 +205,24 @@ mod tests { output.textures_delta.clear(); assert!(app.updates_rt.updater.prompt_open()); } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn result_window_shows_every_status_but_idle() { + let shown = [ + Status::Checking, + Status::UpToDate, + Status::Failed("no network".into()), + Status::Installing, + Status::Ready, + Status::Managed, + Status::Updated("0.2.0".into()), + Status::InstallFailed("disk full".into()), + ]; + for status in &shown { + assert!(result_window_shows(status, false), "{status:?}"); + assert!(!result_window_shows(status, true), "{status:?} over the prompt"); + } + assert!(!result_window_shows(&Status::Idle, false)); + } } diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rs index d9a90d5464..48a1161bfd 100644 --- a/crates/ui-egui/src/headless.rs +++ b/crates/ui-egui/src/headless.rs @@ -400,6 +400,7 @@ impl Headless { || self.app.import.is_some() || self.app.export.is_some() || self.app.session.denoise_busy() + || self.app.survey_motion.moving(self.time) || !self.app.tasks.is_empty() || !self.app.synthetic.is_empty() || !self.app.pending_gestures.is_empty() diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e1b3410556..c40d16b8e9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -320,6 +320,8 @@ pub struct LightcraftApp { pub(crate) compare_tiles: std::collections::HashMap<(u8, u64), region::RegionView>, /// Until when (s) a pinch or scroll in Compare / Reference holds the windows there are. pub(crate) compare_hold_until: f64, + /// Survey tiles gliding to new cells, and the render slot each surveyed photo keeps. + pub(crate) survey_motion: panels::compare::survey::SurveyMotion, /// Photo Merge dialog previews and background merges. pub merge: merge::MergeState, /// An import in progress (the import review dialog's batches). diff --git a/crates/ui-egui/src/lightroom_import.rs b/crates/ui-egui/src/lightroom_import.rs index 74db981078..895becd9b5 100644 --- a/crates/ui-egui/src/lightroom_import.rs +++ b/crates/ui-egui/src/lightroom_import.rs @@ -175,6 +175,7 @@ fn busy(app: &LightcraftApp) -> Result<(), String> { #[cfg(not(target_arch = "wasm32"))] fn spawn_inspect( path: PathBuf, + temp: Option, cancel: Arc, progress: LightroomProgress, tx: mpsc::Sender, @@ -184,7 +185,7 @@ fn spawn_inspect( .name("lc-lightroom-inspect".into()) .spawn(move || { let result = lightcraft_engine::guard::catch("Lightroom inspect", || { - lightcraft_engine::lightroom_catalog::read_with_progress(&path, &cancel, &progress.catalog_total, &progress.catalog_done) + lightcraft_engine::lightroom_catalog::read_source(&path, temp.as_deref(), &cancel, &progress.catalog_total, &progress.catalog_done) }) .and_then(|r| r.map(inspect_report)); let _ = tx.send(Message::Inspected(result)); @@ -385,7 +386,8 @@ fn start_inspect(app: &mut LightcraftApp, path: PathBuf, ctx: &egui::Context) -> let cancel = Arc::new(AtomicBool::new(false)); let progress = LightroomProgress::default(); let (tx, rx) = mpsc::channel(); - spawn_inspect(path.clone(), cancel.clone(), progress.clone(), tx, ctx.clone())?; + let temp = lightcraft_engine::lightroom_catalog::backup_temp_root(&app.session); + spawn_inspect(path.clone(), temp, cancel.clone(), progress.clone(), tx, ctx.clone())?; app.lightroom_last = None; app.lightroom = Some(LightroomTask::new(&app.session, Kind::Inspect, path.clone(), cancel, progress, rx)); Ok(json!({"running": true, "kind": "inspect", "path": path})) @@ -788,6 +790,8 @@ mod tests { fn inspect_report_keeps_empty_catalog_shape() { let report = inspect_report(CatalogImport { source: "synthetic.lrcat".into(), + catalog_id: None, + catalog_path: None, photos: Vec::new(), collections: Vec::new(), members: Vec::new(), diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 9791f0cac3..23863c4a0b 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1353,8 +1353,11 @@ fn ui_commands_10(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Va let path = match p.get("path").and_then(Value::as_str).map(str::to_string) { Some(path) => Some(path), None => { - let req = - PickRequest::file(crate::i18n::tr("Import Lightroom Catalog"), crate::i18n::tr("Lightroom Classic Catalog"), &["lrcat"]); + let req = PickRequest::file( + crate::i18n::tr("Import Lightroom Catalog"), + crate::i18n::tr("Lightroom Classic Catalog"), + &["lrcat", "zip"], + ); match crate::pick::ask(app, id, p, "path", req, |s| s.pick_lightroom_catalog.as_mut().and_then(|f| f()).map(|x| vec![x])) { Picked::Now(v) => v.into_iter().next(), Picked::Later | Picked::Unavailable => None, diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f4398d2842..e9deed4601 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -162,6 +162,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("section.effects", "Effects", Some("Cmd+3"), "Window>Edit Sections"), ("section.detail", "Detail", Some("Cmd+4"), "Window>Edit Sections"), ("section.optics", "Optics", Some("Cmd+5"), "Window>Edit Sections"), + ("section.lensBlur", "Lens Blur", Some("Cmd+6"), "Window>Edit Sections"), ("section.calibration", "Calibration", None, ""), // {on?}; no params toggles. Opening one Edit section closes the others. ("view.soloSections", "Solo Mode", None, "Window>Edit Sections"), diff --git a/crates/ui-egui/src/panels/compare.rs b/crates/ui-egui/src/panels/compare.rs index c6475a7017..4fc9e49554 100644 --- a/crates/ui-egui/src/panels/compare.rs +++ b/crates/ui-egui/src/panels/compare.rs @@ -13,6 +13,8 @@ use crate::state::{ViewMode, Zoom}; use crate::theme::Tokens; use crate::widgets::register; +pub mod survey; + /// Most photos a survey shows. pub const SURVEY_MAX: usize = 48; @@ -203,11 +205,27 @@ fn request_tile_renders(app: &mut LightcraftApp, id: PhotoId, slot: Slot, want: if let Some(job) = app.session.render_job(id, rw.max(8), rh.max(8), false, true) { app.renderer.request(slot, job, 60); } + request_thumb(app, id); +} + +/// Ask for the thumbnail a tile shows until its render is there. +fn request_thumb(app: &mut LightcraftApp, id: PhotoId) { if let Some(job) = app.session.thumb_job(id, 256) { app.renderer.request(Slot::Thumb(id), job, 30); } } +/// The photo's frame as shown: cropped, rotated and lens-corrected. +fn frame_of(photo: &lightcraft_catalog::Photo) -> lightcraft_pipeline::geometry::Frame { + lightcraft_pipeline::geometry::Frame::with_lens( + photo.width.max(1) as usize, + photo.height.max(1) as usize, + &photo.develop, + true, + photo.embedded_lens.as_ref(), + ) +} + /// Draw one photo fitted into `area` (rendered at its display size into `slot`), with its caption /// strip below. Returns the image rect and the click/drag response. fn photo_tile( @@ -226,13 +244,7 @@ fn photo_tile( let Some(photo) = app.session.catalog.photo(id).cloned() else { return (area, area, resp) }; let caption_h = 26.0; let img_area = Rect::from_min_max(area.min, pos2(area.right(), area.bottom() - caption_h)); - let frame = lightcraft_pipeline::geometry::Frame::with_lens( - photo.width.max(1) as usize, - photo.height.max(1) as usize, - &photo.develop, - true, - photo.embedded_lens.as_ref(), - ); + let frame = frame_of(&photo); let aspect = frame.aspect() as f32; let native = super::detail::output_px(&frame); let mut img = super::detail::fit_rect(img_area, aspect, zoom, native, ppp, app.ui.pan); @@ -249,7 +261,13 @@ fn photo_tile( let texture_side = super::detail::texture_side(ui.ctx()); let want = (img.width().max(img.height()).min(img_area.width().max(img_area.height()) * 4.0) * ppp).min(2560.0_f32.min(texture_side as f32)) as usize; - request_tile_renders(app, id, slot, want, aspect); + // a gliding survey tile asks for its render once it has landed, not one per size it passes on + // the way, and for its thumbnail (one size) meanwhile; tiles that stay put render as usual + if app.ui.view == ViewMode::Survey && app.survey_motion.gliding(id, ui.input(|i| i.time)) { + request_thumb(app, id); + } else { + request_tile_renders(app, id, slot, want, aspect); + } // zoomed past what that render holds (1:1 to check focus): the part on screen as a window, as // in the loupe. Compare and Reference only; Survey tiles are fit views. let pane = match slot { @@ -546,21 +564,6 @@ pub fn show_compare(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.painter().line_segment([pos2(mid, area.top()), pos2(mid, area.bottom())], Stroke::new(1.0, Tokens::get(ui.ctx()).divider)); } -/// Columns for `n` tiles of aspect ~3:2 in `area`, maximizing the tile size. -pub fn survey_columns(n: usize, area: Rect) -> usize { - let mut best = (1, 0.0f32); - for cols in 1..=n.max(1) { - let rows = n.div_ceil(cols); - let w = area.width() / cols as f32; - let h = area.height() / rows as f32; - let s = w.min(h * 1.5); - if s > best.1 { - best = (cols, s); - } - } - best.0 -} - pub fn show_survey(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); let canvas = area_and_filmstrip(app, ui); @@ -570,14 +573,20 @@ pub fn show_survey(app: &mut LightcraftApp, ui: &mut egui::Ui) { return; } let area = canvas.shrink(14.0); - let cols = survey_columns(photos.len(), area); - let rows = photos.len().div_ceil(cols); - let (cw, ch) = (area.width() / cols as f32, area.height() / rows as f32); - for (i, id) in photos.iter().enumerate() { - let (c, r) = (i % cols, i / cols); - let cell = Rect::from_min_size(pos2(area.left() + c as f32 * cw, area.top() + r as f32 * ch), vec2(cw, ch)).shrink(6.0); + let aspects: Vec = photos.iter().map(|id| app.session.catalog.photo(*id).map_or(1.5, |p| frame_of(p).aspect() as f32)).collect(); + let cells = survey::cells(&aspects, area); + let now = ui.input(|i| i.time); + let placed = app.survey_motion.place(&photos, &cells, area, ui.ctx().cumulative_frame_nr(), now); + let (slots, freed) = app.survey_motion.assign_slots(&photos); + for s in freed { + app.renderer.release(Slot::Compare(s)); + } + if app.survey_motion.moving(now) { + ui.ctx().request_repaint(); + } + for ((id, cell), slot) in photos.iter().zip(placed).zip(slots) { // (Survey tiles are fit views with no windows: what counts is the photo as painted) - let (_, img, resp) = photo_tile(app, ui, *id, Slot::Compare(i as u8), cell, "", Zoom::Fit); + let (_, img, resp) = photo_tile(app, ui, *id, Slot::Compare(slot), cell.shrink(survey::GAP), "", Zoom::Fit); if app.session.selection.active == Some(*id) { app.image_rect = Some(img); } diff --git a/crates/ui-egui/src/panels/compare/survey.rs b/crates/ui-egui/src/panels/compare/survey.rs new file mode 100644 index 0000000000..c4cb3eb9cf --- /dev/null +++ b/crates/ui-egui/src/panels/compare/survey.rs @@ -0,0 +1,261 @@ +//! Survey layout: the cells the photos are tiled in, fitted to their shapes, and the glide that +//! moves the tiles left to their new cells when a photo leaves or joins the survey, so it is +//! plain which photo went where. + +use std::collections::HashMap; + +use egui::{Rect, pos2, vec2}; +use lightcraft_catalog::PhotoId; + +/// Space a tile keeps below its photo for the caption (as `photo_tile` draws it). +pub const CAPTION_H: f32 = 26.0; +/// Margin around each tile inside its cell. +pub const GAP: f32 = 6.0; +/// Seconds a tile takes to glide to its new cell. +pub const GLIDE_SECS: f64 = 0.2; + +/// A width / height ratio that layout arithmetic can use: the photo's own, as it is drawn (a +/// 100:1 panorama counts as one), or a square for a size that is none. +fn usable_aspect(a: f32) -> f32 { + if a.is_finite() && a > 0.0 { a } else { 1.0 } +} + +/// Image area photos with `aspects` show in a grid of `cols` equal cells in `area`. +fn shown_area(aspects: &[f32], cols: usize, area: Rect) -> f32 { + let rows = aspects.len().div_ceil(cols.max(1)); + let iw = area.width() / cols.max(1) as f32 - 2.0 * GAP; + let ih = area.height() / rows.max(1) as f32 - 2.0 * GAP - CAPTION_H; + if iw <= 0.0 || ih <= 0.0 { + return 0.0; + } + aspects + .iter() + .map(|&a| { + let a = usable_aspect(a); + let w = iw.min(ih * a); + w * w / a + }) + .sum() +} + +/// The cell of each photo (width / height `aspects`, in survey order) in `area`: equal cells in +/// rows, with the column count that shows the most of the photos, so the survey fits their shapes +/// to the screen as Lightroom Classic's does (four portrait photos side by side on a wide screen, +/// not two by two). An incomplete last row is centred. +pub fn cells(aspects: &[f32], area: Rect) -> Vec { + let n = aspects.len(); + if n == 0 { + return Vec::new(); + } + let mut best = (1, f32::NEG_INFINITY); + for cols in 1..=n { + let shown = shown_area(aspects, cols, area); + if shown > best.1 { + best = (cols, shown); + } + } + let cols = best.0; + let rows = n.div_ceil(cols); + let (cw, ch) = (area.width() / cols as f32, area.height() / rows as f32); + let last_row = n - (rows - 1) * cols; + (0..n) + .map(|i| { + let (c, r) = (i % cols, i / cols); + let indent = if r == rows - 1 { (cols - last_row) as f32 * cw / 2.0 } else { 0.0 }; + Rect::from_min_size(pos2(area.left() + indent + c as f32 * cw, area.top() + r as f32 * ch), vec2(cw, ch)) + }) + .collect() +} + +/// One tile's way from where it was drawn to its cell. +#[derive(Clone, Copy, Debug)] +struct Glide { + from: Rect, + to: Rect, + start: f64, +} + +impl Glide { + fn at(&self, now: f64) -> Rect { + let t = ((now - self.start) / GLIDE_SECS).clamp(0.0, 1.0) as f32; + // ease out: quick to leave, gentle to land + let e = 1.0 - (1.0 - t).powi(3); + self.from.lerp_towards(&self.to, e) + } + + fn on_its_way(&self, now: f64) -> bool { + !self.done(now) && self.from != self.to + } + + fn done(&self, now: f64) -> bool { + // (a hair early: the clock's rounding must not keep a landed tile moving) + now - self.start >= GLIDE_SECS - 1e-9 + } +} + +/// Where the survey's tiles are drawn while they glide, and which render slot each photo keeps +/// (a photo keeps its slot while it is shown, so the tiles that move keep their renders). +#[derive(Default)] +pub struct SurveyMotion { + /// The survey area of the last frame drawn, and its frame number. + last: Option<(Rect, u64)>, + tiles: HashMap, + slots: HashMap, +} + +impl SurveyMotion { + /// Where to draw `photos` (in survey order) at `now`, given their `cells` in `area` this frame + /// (`frame`, egui's cumulative frame number). A tile whose cell changed since the last frame glides + /// there from where it was drawn; a photo that joined appears in its cell. A survey just opened + /// or a canvas that changed size is laid out at once. + pub fn place(&mut self, photos: &[PhotoId], cells: &[Rect], area: Rect, frame: u64, now: f64) -> Vec { + let continued = self.last.is_some_and(|(a, p)| a == area && frame <= p.saturating_add(1)); + self.last = Some((area, frame)); + let mut next = HashMap::with_capacity(photos.len()); + let placed = photos + .iter() + .zip(cells) + .map(|(id, &to)| { + let glide = match self.tiles.get(id) { + Some(g) if continued && g.to == to => *g, + Some(g) if continued => Glide { from: g.at(now), to, start: now }, + _ => Glide { from: to, to, start: now }, + }; + next.insert(*id, glide); + glide.at(now) + }) + .collect(); + self.tiles = next; + placed + } + + /// Whether a tile is still on its way. + pub fn moving(&self, now: f64) -> bool { + self.tiles.values().any(|g| g.on_its_way(now)) + } + + /// Whether the tile of `id` is still on its way (a tile that stays put, or a photo that just + /// joined, is not, while others glide). + pub fn gliding(&self, id: PhotoId, now: f64) -> bool { + self.tiles.get(&id).is_some_and(|g| g.on_its_way(now)) + } + + /// The render slot of each of `photos`: the one it had, else the lowest free one. Returns the + /// slots that photos no longer shown gave up, whose renders can be freed. + pub fn assign_slots(&mut self, photos: &[PhotoId]) -> (Vec, Vec) { + let freed: Vec = self.slots.iter().filter(|(id, _)| !photos.contains(id)).map(|(_, s)| *s).collect(); + self.slots.retain(|id, _| photos.contains(id)); + let used: Vec = self.slots.values().copied().collect(); + let mut free = (0..=u8::MAX).filter(move |s| !used.contains(s)); + let slots = photos.iter().map(|id| *self.slots.entry(*id).or_insert_with(|| free.next().unwrap_or(u8::MAX))).collect(); + (slots, freed) + } + + /// The render slot `id` keeps, if it has one. + #[cfg(test)] + pub fn slot(&self, id: PhotoId) -> Option { + self.slots.get(&id).copied() + } + + /// Whether `id` has a tile here (its place or its render slot). + #[cfg(test)] + pub fn tracks(&self, id: PhotoId) -> bool { + self.tiles.contains_key(&id) || self.slots.contains_key(&id) + } +} + +#[cfg(test)] +mod tests { + use super::{CAPTION_H, GAP, GLIDE_SECS, SurveyMotion, cells}; + use egui::{Rect, pos2, vec2}; + use lightcraft_catalog::PhotoId; + + const WIDE: Rect = Rect { min: pos2(0.0, 0.0), max: pos2(1600.0, 800.0) }; + + fn cols(cells: &[Rect]) -> usize { + cells.iter().filter(|c| c.top() == cells[0].top()).count() + } + + #[test] + fn four_portraits_stand_side_by_side_on_a_wide_screen() { + let c = cells(&[2.0 / 3.0; 4], WIDE); + assert_eq!(cols(&c), 4, "{c:?}"); + } + + #[test] + fn four_landscapes_on_a_wide_screen_take_two_rows() { + let c = cells(&[1.5; 4], WIDE); + assert_eq!(cols(&c), 2, "{c:?}"); + } + + /// Column choice follows the ratio drawn, also past 20:1: four 100:1 panoramas and four + /// portraits show most side by side in four columns, not one tall column. + #[test] + fn panoramas_count_at_their_own_ratio() { + let area = Rect::from_min_size(pos2(0.0, 0.0), vec2(2560.0, 1440.0)); + let aspects = [100.0, 100.0, 100.0, 100.0, 2.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0]; + assert_eq!(cols(&cells(&aspects, area)), 4); + } + + #[test] + fn the_last_row_is_centred() { + let c = cells(&[1.5; 5], WIDE); + assert_eq!(cols(&c), 3, "{c:?}"); + let (row, last) = (&c[..3], &c[3..]); + assert_eq!(last.len(), 2); + let mid = |r: &[Rect]| (r[0].left() + r[r.len() - 1].right()) / 2.0; + assert!((mid(row) - mid(last)).abs() < 0.01, "{c:?}"); + } + + #[test] + fn cells_stay_inside_the_area_and_survive_hostile_sizes() { + for aspects in [vec![f32::NAN, 0.0, -1.0, f32::INFINITY, 1e9, f32::MAX, f32::MIN_POSITIVE], vec![1.5; 48]] { + let c = cells(&aspects, WIDE); + assert_eq!(c.len(), aspects.len()); + assert!(c.iter().all(|r| WIDE.expand(0.01).contains_rect(*r)), "{c:?}"); + } + assert!(cells(&[], WIDE).is_empty()); + // a canvas too small for any tile still lays them out, one column + let tiny = Rect::from_min_size(pos2(0.0, 0.0), vec2(2.0 * GAP, CAPTION_H)); + assert_eq!(cells(&[1.0; 3], tiny).len(), 3); + } + + #[test] + fn a_tile_glides_to_its_new_cell_and_lands_there() { + let (a, b) = (PhotoId(1), PhotoId(2)); + let mut m = SurveyMotion::default(); + let first = cells(&[1.5; 2], WIDE); + assert_eq!(m.place(&[a, b], &first, WIDE, 1, 0.0), first, "a new survey is laid out at once"); + assert!(!m.moving(0.0)); + // a leaves: b moves to the single cell + let one = cells(&[1.5], WIDE); + let mid = m.place(&[b], &one, WIDE, 2, 1.0); + assert_eq!(mid[0], first[1], "it starts where it was drawn"); + assert!(m.moving(1.0)); + let half = m.place(&[b], &one, WIDE, 3, 1.0 + GLIDE_SECS / 2.0)[0]; + assert!(half != first[1] && half != one[0], "on its way: {half:?}"); + assert_eq!(m.place(&[b], &one, WIDE, 4, 1.0 + GLIDE_SECS)[0], one[0], "it lands in its cell"); + assert!(!m.moving(1.0 + GLIDE_SECS)); + } + + #[test] + fn a_reopened_survey_or_a_resized_canvas_does_not_glide() { + let (a, b) = (PhotoId(1), PhotoId(2)); + let mut m = SurveyMotion::default(); + m.place(&[a, b], &cells(&[1.5; 2], WIDE), WIDE, 1, 0.0); + let one = cells(&[1.5], WIDE); + assert_eq!(m.place(&[b], &one, WIDE, 9, 1.0), one, "frames skipped: the survey was not shown"); + let narrow = Rect::from_min_size(pos2(0.0, 0.0), vec2(900.0, 800.0)); + let c = cells(&[1.5], narrow); + assert_eq!(m.place(&[b], &c, narrow, 10, 2.0), c, "a new canvas size"); + } + + #[test] + fn photos_keep_their_slots_and_new_ones_take_freed_slots() { + let (a, b, c, d) = (PhotoId(1), PhotoId(2), PhotoId(3), PhotoId(4)); + let mut m = SurveyMotion::default(); + assert_eq!(m.assign_slots(&[a, b, c]), (vec![0, 1, 2], vec![])); + assert_eq!(m.assign_slots(&[a, c]), (vec![0, 2], vec![1]), "c keeps its render"); + assert_eq!(m.assign_slots(&[a, c, d]), (vec![0, 2, 1], vec![]), "d takes the freed slot"); + } +} diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 71b0ef8b60..2a6a83fd8e 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -18,6 +18,7 @@ mod crop; mod filmstrip; mod geometry; mod info; +mod lens_blur; mod look_ahead; mod masks; mod retouch; @@ -48,6 +49,7 @@ use info::{ preview_only_pill, quick_name, }; pub(crate) use info::{draw_focus_point, failed_pill, loupe_pill, rendering_overdue}; +use lens_blur::{lens_blur_brush_overlay, lens_blur_shape_overlay}; use look_ahead::BEHIND; pub use look_ahead::LookAhead; pub(crate) use look_ahead::{Prepare, look_ahead}; @@ -59,6 +61,12 @@ use window::{WindowCtx, WindowView, draw_window, request_window}; /// An in-progress on-canvas gesture. #[derive(Clone, Debug)] pub enum Gesture { + /// Lens Blur's fixed focus shape: moving it (`handle` 0) or stretching it sideways (1) or + /// up and down (2), from `original` (where it was when the drag began). + LensBlurArea { + handle: u8, + original: lightcraft_develop::FocusArea, + }, Brush { points: Vec, /// Pen pressure (0..1) at each point; empty when no pen pressure was reported (a mouse) or the @@ -758,6 +766,8 @@ fn tool_interaction(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Res RightPanel::Masking => mask_overlay(app, ui, resp, map, d), RightPanel::Remove => remove_overlay(app, ui, resp, map, d), RightPanel::RedEye => eye_overlay(app, ui, resp, map, d), + RightPanel::Edit if app.ui.tool == "lensBlurShape" => lens_blur_shape_overlay(app, ui, resp, map, d), + RightPanel::Edit if app.ui.tool.starts_with("lensBlur") => lens_blur_brush_overlay(app, ui, resp, map), _ => { // side by side / stacked: Before shows the same frame, so a click in its view (white // balance, colour samples, targeted adjustment) means the same point of the photo. diff --git a/crates/ui-egui/src/panels/detail/lens_blur.rs b/crates/ui-egui/src/panels/detail/lens_blur.rs new file mode 100644 index 0000000000..f3c5404ece --- /dev/null +++ b/crates/ui-egui/src/panels/detail/lens_blur.rs @@ -0,0 +1,148 @@ +//! Lens Blur's tools on the photo: moving and resizing its fixed focus shape, and painting its +//! Focus / Blur refinement brushes. + +use super::geometry::CanvasMap; +use super::masks::{frame_long_norm, pen_force, pin, record_pressure}; +use super::{Color32, DevelopSettings, Gesture, LightcraftApp, Point, Pos2, Rect, Stroke, json, register, vec2}; + +/// Lens Blur's fixed focus shape on the photo (Edit Shape): its outline, a centre pin that moves +/// it (or drag anywhere inside), and handles on its right and bottom edges that stretch it +/// sideways or up and down. One drag is one undo step. +pub(super) fn lens_blur_shape_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, map: &CanvasMap, d: &DevelopSettings) { + let Some(area) = d.lens_blur.focus_area(d.crop_center()) else { return }; + let clip = app.canvas_rect.unwrap_or(map.rect); + let p = &ui.painter_at(clip); + let l = frame_long_norm(map); + let at = |dx: f64, dy: f64| map.screen(Point::new(area.center.x + dx * l.0, area.center.y + dy * l.1)); + let outline: Vec = (0..72) + .map(|i| { + let a = i as f64 / 72.0 * std::f64::consts::TAU; + at(area.rx * a.cos(), area.ry * a.sin()) + }) + .collect(); + // a dark keyline under a light line: visible over bright and dark photos alike + p.add(egui::Shape::closed_line(outline.clone(), Stroke::new(3.0, Color32::from_black_alpha(140)))); + p.add(egui::Shape::closed_line(outline, Stroke::new(1.5, Color32::from_white_alpha(235)))); + let (c, hx, hy) = (at(0.0, 0.0), at(area.rx, 0.0), at(0.0, area.ry)); + pin(p, c, true); + for h in [hx, hy] { + p.circle_filled(h, 5.5, Color32::WHITE); + p.circle_stroke(h, 5.5, Stroke::new(1.5, Color32::from_black_alpha(160))); + } + for (name, q) in [("center", c), ("width", hx), ("height", hy)] { + register(ui, format!("lensBlurArea:{name}"), Rect::from_center_size(q, vec2(14.0, 14.0))); + } + // which part a point grabs: a handle, else the inside + let hit = |q: Pos2| -> Option { + if q.distance(hx) < 10.0 { + return Some(1); + } + if q.distance(hy) < 10.0 { + return Some(2); + } + let n = map.norm(q); + let (ex, ey) = ((n.x - area.center.x) / (area.rx * l.0).max(1e-9), (n.y - area.center.y) / (area.ry * l.1).max(1e-9)); + (q.distance(c) < 10.0 || ex * ex + ey * ey <= 1.0).then_some(0) + }; + if let Some(q) = resp.hover_pos() { + let icon = match hit(q) { + Some(1) => Some(egui::CursorIcon::ResizeHorizontal), + Some(2) => Some(egui::CursorIcon::ResizeVertical), + Some(_) => Some(egui::CursorIcon::Move), + None => None, + }; + if let Some(icon) = icon { + ui.ctx().set_cursor_icon(icon); + } + } + if resp.drag_started() + && let Some(q) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos()) + && let Some(handle) = hit(q) + { + let _ = app.run("develop.beginInteraction", json!({"label": "Lens Blur Shape"})); + app.gesture = Some(Gesture::LensBlurArea { handle, original: area }); + } + if resp.dragged() + && let (Some(Gesture::LensBlurArea { handle, original }), Some(q)) = (app.gesture.clone(), resp.interact_pointer_pos()) + { + let n = map.norm(q); + let n0 = map.norm(ui.input(|i| i.pointer.press_origin()).unwrap_or(q)); + let moved = match handle { + 0 => lightcraft_develop::FocusArea { center: Point::new(original.center.x + n.x - n0.x, original.center.y + n.y - n0.y), ..original }, + 1 => lightcraft_develop::FocusArea { rx: (n.x - original.center.x).abs() / l.0.max(1e-9), ..original }, + _ => lightcraft_develop::FocusArea { ry: (n.y - original.center.y).abs() / l.1.max(1e-9), ..original }, + } + .sanitized(); + let _ = app.run("develop.merge", json!({"settings": {"lens_blur": {"area": moved}}, "label": "Lens Blur Shape"})); + } + if resp.drag_stopped() && matches!(app.gesture, Some(Gesture::LensBlurArea { .. })) { + app.gesture = None; + let _ = app.run("develop.endInteraction", json!({})); + } +} + +/// Lens Blur Brush Refinement on the photo: the brush circle (size and feather), the stroke being +/// painted (green: Focus, red: Blur), committed as `lensBlur.brushStroke` when the drag ends. +/// ⌥ (Alt) erases what the brush painted. +pub(super) fn lens_blur_brush_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, map: &CanvasMap) { + let long = (map.rect.width().max(map.rect.height())) as f64; + let clip = app.canvas_rect.unwrap_or(map.rect); + let p = &ui.painter_at(clip); + let focus = app.ui.tool == "lensBlurFocus"; + let r = (app.ui.brush_size as f64 * long) as f32; + if let Some(h) = resp.hover_pos() { + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + p.circle_stroke(h, r, Stroke::new(1.0, Color32::WHITE)); + p.circle_stroke(h, r * (1.0 - app.ui.brush_feather / 100.0).max(0.05), Stroke::new(1.0, Color32::from_white_alpha(120))); + } + if let Some(q) = resp.interact_pointer_pos() + && (resp.drag_started() || resp.dragged() || resp.clicked()) + { + let n = map.norm(q); + let force = if app.ui.brush_pressure { ui.input(pen_force) } else { None }; + match &mut app.gesture { + Some(Gesture::Brush { points, .. }) if points.last() == Some(&n) => {} + Some(Gesture::Brush { points, pressure }) => { + record_pressure(pressure, points.len(), force); + points.push(n); + } + _ => { + let mut pressure = Vec::new(); + record_pressure(&mut pressure, 0, force); + app.gesture = Some(Gesture::Brush { points: vec![n], pressure }); + } + } + } + if let Some(Gesture::Brush { points, pressure }) = &app.gesture { + let screen: Vec = points.iter().map(|q| map.screen(*q)).collect(); + let params = crate::brush_live::LiveParams { + clip, + scale: ui.ctx().pixels_per_point(), + r, + hard: r * (1.0 - (app.ui.brush_feather / 100.0).clamp(0.0, 1.0)), + flow: (app.ui.brush_flow / 100.0).clamp(0.0, 1.0), + density: (app.ui.lens_blur_brush_amount / 100.0).clamp(0.0, 1.0), + color: if focus { [70, 200, 120] } else { [230, 70, 70] }, + opacity: 0.45, + }; + crate::brush_live::paint(&mut app.brush_live, ui.ctx(), p, params, &screen, pressure); + } else { + app.brush_live = None; + } + if (resp.drag_stopped() || resp.clicked()) + && let Some(Gesture::Brush { points, pressure }) = app.gesture.take() + { + app.brush_live = None; + let pts: Vec<[f64; 2]> = points.iter().map(|q| [q.x, q.y]).collect(); + let erase = resp.ctx.input(|i| i.modifiers.alt); + let r = app.run( + "lensBlur.brushStroke", + json!({"mode": if focus { "focus" } else { "blur" }, "points": pts, "size": app.ui.brush_size, "feather": app.ui.brush_feather, + "flow": app.ui.brush_flow, "amount": app.ui.lens_blur_brush_amount, "erase": erase, "autoMask": app.ui.brush_auto_mask, + "pressure": pressure}), + ); + if let Err(e) = r { + app.toast(ui.ctx(), e); + } + } +} diff --git a/crates/ui-egui/src/panels/detail/masks.rs b/crates/ui-egui/src/panels/detail/masks.rs index ebcb35e611..1148d9527b 100644 --- a/crates/ui-egui/src/panels/detail/masks.rs +++ b/crates/ui-egui/src/panels/detail/masks.rs @@ -879,7 +879,7 @@ fn current_on_photo(app: &LightcraftApp, mask: u32) -> Option { } /// Long-edge units → normalized units for x and y. -fn frame_long_norm(map: &CanvasMap) -> (f64, f64) { +pub(super) fn frame_long_norm(map: &CanvasMap) -> (f64, f64) { // derive from the mapping: 1 normalized unit in x and y in screen points (of the frame's // proportions, which a lens or perspective warp doesn't change) let map = map.for_mask(false); diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index 195bcb6488..15f2f277f3 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -21,6 +21,7 @@ mod curve; mod grading; mod hdr_flow; mod histogram; +mod lens_blur; mod mixer; mod sliders; @@ -31,6 +32,7 @@ pub(crate) use grading::wheel_pointer_frame_end; pub(crate) use grading::{WheelGrab, WheelLock, WheelMods, wheel_pick}; pub(crate) use histogram::histogram; use histogram::soft_proofing; +use lens_blur::lens_blur; use mixer::{mixer, point_color}; use sliders::{REL_TEMP, REL_TINT, hdr_row, header_buttons, k_to_rel, profile_menu, quick_develop, rel_to_k, reset_tip, section}; pub use sliders::{apply_slider_out, sub_title}; @@ -374,6 +376,10 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { } ui.add_space(8.0); }); + section(app, ui, &d, "lensBlur", "Lens Blur", |app, ui, d| { + lens_blur(app, ui, d); + ui.add_space(8.0); + }); // Lightroom Classic's Calibration panel (the cloud app hides it): last, like there. section(app, ui, &d, "calibration", "Calibration", |app, ui, d| { sub_title(ui, crate::i18n::tr("Shadows")); diff --git a/crates/ui-egui/src/panels/edit/lens_blur.rs b/crates/ui-egui/src/panels/edit/lens_blur.rs new file mode 100644 index 0000000000..b7aa696736 --- /dev/null +++ b/crates/ui-egui/src/panels/edit/lens_blur.rs @@ -0,0 +1,257 @@ +//! The Lens Blur section: Apply, the sliders, what stays in focus (the subject, a mask or a fixed +//! shape that can be moved on the photo), Find Subject and Brush Refinement. + +use super::{ + Color32, ControlSpec, Icon, LightcraftApp, Pos2, Rect, RichText, Section, Sense, Stroke, Tokens, Track, control, paint, pos2, register, slider, + sub_title, text_button, vec2, +}; +use lightcraft_develop::DevelopSettings; +use serde_json::json; + +/// The Lens Blur section: Apply, Blur Amount, Boost, and what stays in focus (the photo's subject, +/// or one of its masks, e.g. an Object mask that selected it). +pub(super) fn lens_blur(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) { + let t = Tokens::get(ui.ctx()); + let b = &d.lens_blur; + egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 4, bottom: 4 }).show(ui, |ui| { + let mut on = b.enabled; + let r = ui.checkbox(&mut on, crate::i18n::tr("Apply")); + register(ui, "check:lensBlur.enabled", r.rect); + if r.on_hover_text(crate::i18n::tr("Blur what is out of focus, as a wide aperture would")).changed() { + let mut patch = json!({"enabled": on}); + // switched on the first time: a visible starting amount, as in Lightroom + if on && b.amount == 0.0 { + patch["amount"] = json!(50.0); + } + let _ = app.run("develop.merge", json!({"settings": {"lens_blur": patch}, "label": "Lens Blur"})); + } + }); + control(app, ui, d, "lensBlur.amount", b.enabled); + control(app, ui, d, "lensBlur.boost", b.enabled); + control(app, ui, d, "lensBlur.transition", b.enabled); + // the focus controls do nothing while the blur is off: shown, but not usable + let has_mask = b.focus_mask.and_then(|id| d.masks.iter().find(|m| m.id == id)).is_some(); + if app.ui.tool == "lensBlurShape" && (!b.enabled || has_mask || b.shape == lightcraft_develop::FocusShape::Auto) { + app.ui.tool.clear(); + } + egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 6, bottom: 4 }).show(ui, |ui| ui.add_enabled_ui(b.enabled, |ui| { + ui.horizontal(|ui| { + ui.label(RichText::new(crate::i18n::tr("In Focus")).font(t.font(13.0)).color(t.text_dim)); + let chosen = b.focus_mask.and_then(|id| d.masks.iter().find(|m| m.id == id)); + // without a mask: the subject estimate, or the fixed shape chosen below + let auto = b.shape == lightcraft_develop::FocusShape::Auto; + let none = if auto { crate::i18n::tr("Subject") } else { crate::i18n::tr(b.shape.label()) }; + let shown = chosen.map_or_else(|| none.to_string(), |m| m.name.clone()); + let r = crate::widgets::dropdown(ui, "lensBlurFocus", &shown, t.font(14.0), t.text_label); + let r = r.on_hover_text(crate::i18n::tr("What stays sharp: the photo's subject, or the selection of one of its masks")); + let mut pick: Option> = None; + egui::Popup::menu(&r).show(|ui| { + let item = ui.selectable_label(chosen.is_none() && auto, crate::i18n::tr("Subject")); + register(ui, "lensBlurFocus:subject", item.rect); + if item.clicked() { + pick = Some(None); + } + for m in &d.masks { + let item = ui.selectable_label(chosen.is_some_and(|c| c.id == m.id), m.name.as_str()); + register(ui, format!("lensBlurFocus:mask:{}", m.id), item.rect); + if item.clicked() { + pick = Some(Some(m.id)); + } + } + }); + if let Some(focus) = pick { + // "Subject": the estimate again, not a fixed shape + let mut patch = json!({"focus_mask": focus}); + if focus.is_none() { + patch["shape"] = json!("auto"); + } + let _ = app.run("develop.merge", json!({"settings": {"lens_blur": patch}, "label": "Lens Blur Focus"})); + } + }); + // without a focus mask: the focus area's shape (the estimate, or a fixed one), which can + // be moved and resized on the photo + if !has_mask { + ui.add_space(4.0); + focus_shape_row(app, ui, b); + if b.shape != lightcraft_develop::FocusShape::Auto { + let active = app.ui.tool == "lensBlurShape"; + let r = text_button(ui, "lensBlurEditShape", "Move & Resize", active).on_hover_text(crate::i18n::tr( + "Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.", + )); + if r.clicked() { + if active { app.ui.tool.clear() } else { app.ui.tool = "lensBlurShape".into() } + } + } + } + // the AI subject search runs only when asked: it takes a while on the CPU, and the + // automatic estimate stays until then + ui.add_space(4.0); + let r = text_button(ui, "lensBlurFindSubject", "Find Subject", false).on_hover_text(crate::i18n::tr( + "Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus", + )); + if r.clicked() { + match app.run_typed("lensBlur.findSubject", json!({})) { + Ok(v) => { + let msg = if v["from"] == "camera" { "Selecting the subject at the camera's focus point…" } else { "Selecting the subject…" }; + app.toast(ui.ctx(), crate::i18n::tr(msg)); + } + Err(e) => app.ai_error(ui.ctx(), e, None), + } + } + // a Find Subject still running: say so (meanwhile the automatic estimate stays in focus) + let waiting = b.focus_mask.and_then(|id| d.masks.iter().find(|m| m.id == id)).is_some_and(lightcraft_pipeline::lens_blur::awaiting_ai); + if waiting && app.session.segmenter.busy() { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(RichText::new(crate::i18n::tr("Finding the subject… The first time on a photo takes a while.")).size(11.0).color(t.text)); + }); + ui.ctx().request_repaint_after(std::time::Duration::from_millis(250)); + } else if waiting { + ui.label( + RichText::new(crate::i18n::tr("The subject wasn't selected. Try Find Subject again, or click it in Masking (M).")) + .size(11.0) + .color(t.text), + ); + } + ui.label( + RichText::new(crate::i18n::tr("Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.")) + .size(11.0) + .color(t.text_dim), + ); + })); + lens_blur_brush(app, ui, b); +} + +/// The Lens Blur focus area's shape when no mask sets it: one button per shape, each showing it +/// (drawn in the theme's colours, so it reads on the light themes too). +fn focus_shape_row(app: &mut LightcraftApp, ui: &mut egui::Ui, b: &lightcraft_develop::LensBlur) { + use lightcraft_develop::FocusShape; + let t = Tokens::get(ui.ctx()); + let enabled = ui.is_enabled(); + ui.horizontal(|ui| { + ui.label(RichText::new(crate::i18n::tr("Shape")).font(t.font(13.0)).color(t.text_dim)); + ui.add_space(4.0); + for shape in FocusShape::ALL { + let selected = b.shape == shape; + let (r, resp) = ui.allocate_exact_size(vec2(36.0, 28.0), Sense::click()); + let name = serde_json::to_value(shape).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(); + register(ui, format!("lensBlurShape:{name}"), r); + crate::widgets::announce(&resp, crate::i18n::tr(shape.label())); + let resp = resp.on_hover_text(crate::i18n::tr(match shape { + FocusShape::Auto => "Auto: the photo's subject, estimated", + FocusShape::Round => "Round", + FocusShape::Wide => "Horizontal oval", + FocusShape::Tall => "Vertical oval", + })); + let p = ui.painter(); + let fill = if selected { + t.pressed + } else if resp.hovered() && enabled { + t.hover + } else { + t.button + }; + p.rect_filled(r, 4.0, fill); + if selected { + p.rect_stroke(r, 4.0, Stroke::new(1.0, if enabled { t.accent } else { t.text_dim }), egui::StrokeKind::Inside); + } + // (dimmed while the blur is off, in the theme's colours) + let colour = match (enabled, selected) { + (false, _) => t.icon.gamma_multiply(0.4), + (true, true) => t.accent, + (true, false) => t.icon, + }; + paint_focus_shape(p, r.shrink(5.0), shape, colour); + // a preset puts the shape back in the middle at its size (also the one in use, once moved) + if resp.clicked() && (!selected || b.area.is_some()) { + let _ = app.run("develop.merge", json!({"settings": {"lens_blur": {"shape": name, "area": null}}, "label": "Lens Blur Shape"})); + } + } + }); +} + +/// A focus shape's picture in `r`: the oval in its proportions (the largest fills the height), or +/// the subject icon for Auto. +fn paint_focus_shape(p: &egui::Painter, r: Rect, shape: lightcraft_develop::FocusShape, colour: Color32) { + let Some((rx, ry)) = shape.radii() else { + paint(p, r, Icon::Subject, colour); + return; + }; + // the shapes' largest radius spans the box's height (all shapes on one scale) + let k = r.height() / 2.0 / 0.32; + let (ax, ay) = (rx as f32 * k, ry as f32 * k); + let c = r.center(); + let pts: Vec = (0..48) + .map(|i| { + let a = i as f32 / 48.0 * std::f32::consts::TAU; + pos2(c.x + ax * a.cos(), c.y + ay * a.sin()) + }) + .collect(); + p.add(egui::Shape::convex_polygon(pts.clone(), colour.gamma_multiply(0.3), Stroke::NONE)); + p.add(egui::Shape::closed_line(pts, Stroke::new(1.5, colour))); +} + +/// Lens Blur Brush Refinement: the Focus and Blur brushes (painted on the photo, see +/// `detail::lens_blur_brush_overlay`), their Amount, the shared brush's Size, Feather, Flow and +/// Auto Mask, and Reset. +fn lens_blur_brush(app: &mut LightcraftApp, ui: &mut egui::Ui, b: &lightcraft_develop::LensBlur) { + let on = b.enabled; + sub_title(ui, crate::i18n::tr("Brush Refinement")); + egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 0, bottom: 4 }).show(ui, |ui| { + ui.add_enabled_ui(on, |ui| { + ui.horizontal(|ui| { + for (tool, label, tip) in + [("lensBlurFocus", "Focus", "Paint what should stay sharp"), ("lensBlurBlur", "Blur", "Paint what should be blurred")] + { + let active = app.ui.tool == tool; + let r = text_button(ui, tool, label, active).on_hover_text(crate::i18n::tr(tip)); + if r.clicked() { + if active { app.ui.tool.clear() } else { app.ui.tool = tool.to_string() } + } + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let painted = !b.focus_strokes.is_empty() || !b.blur_strokes.is_empty(); + if text_button(ui, "lensBlurBrushReset", "Reset", false) + .on_hover_text(crate::i18n::tr("Remove the strokes of both brushes")) + .clicked() + && painted + { + let _ = app.run("lensBlur.brushReset", json!({})); + } + }); + }); + let mut auto = app.ui.brush_auto_mask; + if ui + .checkbox(&mut auto, crate::i18n::tr("Auto Mask")) + .on_hover_text(crate::i18n::tr("Paint only areas like the one under the brush")) + .changed() + { + app.ui.brush_auto_mask = auto; + } + }); + }); + // the brush is the Masking brush's (its size also follows [ and ]), with its own Amount + // (a reset puts the brush's Amount back to full strength, the others to their minimum) + for (id, label, min, max, get) in [ + ("ui.lensBlurBrushAmount", "Amount", 1.0, 100.0, app.ui.lens_blur_brush_amount as f64), + ("ui.brushSize", "Size", 1.0, 100.0, (app.ui.brush_size * 400.0) as f64), + ("ui.brushFeather", "Feather", 0.0, 100.0, app.ui.brush_feather as f64), + ("ui.brushFlow", "Flow", 1.0, 100.0, app.ui.brush_flow as f64), + ] { + let default = if id == "ui.lensBlurBrushAmount" { 100.0 } else { min }; + let s = ControlSpec { id, label, section: Section::LensBlur, min, max, default, step: 1.0, decimals: 0, track: Track::Plain }; + let out = slider(ui, &s, get, on, None); + if let Some(v) = out.value { + match id { + "ui.lensBlurBrushAmount" => app.ui.lens_blur_brush_amount = v as f32, + "ui.brushSize" => app.ui.brush_size = (v / 400.0) as f32, + "ui.brushFeather" => app.ui.brush_feather = v as f32, + _ => app.ui.brush_flow = v as f32, + } + } + } + // the brushes paint only while the blur is on + if !on && app.ui.tool.starts_with("lensBlur") { + app.ui.tool.clear(); + } +} diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index db4dfa1b83..556f809d27 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -291,35 +291,20 @@ pub fn rows_between(rows: &[GridRow], top: f32, bottom: f32) -> &[GridRow] { } fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); let (generation, ids) = app.session.visible_shared(); // header: source title + count let sel_n = app.session.selection.ids.len(); let chips = lightcraft_engine::filter_chips(&app.session.filter, &app.session.catalog); let total = app.session.source_total(); let counted = super::chips::count_text(ids.len(), total, !chips.is_empty()); - let cnt = if sel_n > 1 { crate::i18n::tr_format!("{sel_n} selected · {counted}", counted = counted, sel_n = sel_n) } else { counted }; + let cnt = if sel_n > 0 { crate::i18n::tr_format!("{sel_n} selected · {counted}", counted = counted, sel_n = sel_n) } else { counted }; match app.session.browse.clone().filter(|_| app.session.source == lightcraft_engine::LibrarySource::Folder) { Some(b) => { let local = app.caches.grid.local(&app.session.catalog, &ids, generation); folder_header(app, ui, &b, &ids, local, &cnt); } None => { - let (hr, _) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0), Sense::hover()); - ui.painter().rect_filled(hr, 0.0, t.canvas); - let full = crate::i18n::source_title(&app.session); - let count_w = ui.painter().layout_no_wrap(cnt.clone(), t.font(12.5), t.text_dim).size().x; - // the title gives way to the count: a long album or folder name is trimmed, in full on hover - let room = (hr.width() - 20.0 - count_w - 36.0).max(0.0); - let font = t.semibold(17.0); - let title = crate::widgets::elide_head(&full, room, |s| ui.painter().layout_no_wrap(s.to_string(), font.clone(), t.text).size().x); - let title_rect = ui.painter().text(pos2(hr.left() + 20.0, hr.center().y), Align2::LEFT_CENTER, &title, font, t.text); - let count_rect = ui.painter().text(pos2(hr.right() - 20.0, hr.center().y), Align2::RIGHT_CENTER, cnt, t.font(12.5), t.text_dim); - crate::widgets::register(ui, "grid:title", title_rect); - crate::widgets::register(ui, "grid:count", count_rect); - if title != full { - ui.interact(title_rect, ui.scope_id().with("grid-title"), Sense::hover()).on_hover_text(full); - } + library_header(app, ui, &cnt); } } super::chips::show(app, ui, &chips); @@ -1016,6 +1001,35 @@ struct BadgeFlags { hovered: bool, } +/// The header of a library view (All Photos, an album, a library folder…): the source's title and +/// the photo count. +fn library_header(app: &LightcraftApp, ui: &mut egui::Ui, cnt: &str) -> Rect { + let t = Tokens::get(ui.ctx()); + let (hr, _) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0), Sense::hover()); + ui.painter().rect_filled(hr, 0.0, t.canvas); + let full = crate::i18n::source_title(&app.session); + // the title gives way to the count: a long album or folder name is trimmed, in full on hover; + // a count wider than all but the title's ellipsis (a narrow centre pane) is cut, as a Local + // folder's is, and reads in full on hover + let count_w = ui.painter().layout_no_wrap(cnt.to_owned(), t.font(12.5), t.text_dim).size().x.ceil().min((hr.width() - 96.0).max(0.0).floor()); + let room = (hr.width() - 20.0 - count_w - 36.0).max(0.0); + let font = t.semibold(17.0); + let title = crate::widgets::elide_head(&full, room, |s| ui.painter().layout_no_wrap(s.to_string(), font.clone(), t.text).size().x); + let title_rect = ui.painter().text(pos2(hr.left() + 20.0, hr.center().y), Align2::LEFT_CENTER, &title, font, t.text); + let count_box = Rect::from_min_max(pos2(hr.right() - 20.0 - count_w, hr.top()), pos2(hr.right() - 20.0, hr.bottom())); + let label = egui::Label::new(egui::RichText::new(cnt).font(t.font(12.5)).color(t.text_dim)).truncate().show_tooltip_when_elided(false); + let count = ui + .scope_builder(egui::UiBuilder::new().max_rect(count_box).layout(egui::Layout::right_to_left(egui::Align::Center)), |ui| ui.add(label)) + .inner; + crate::widgets::register(ui, "grid:title", title_rect); + crate::widgets::register(ui, "grid:count", count.rect); + count.on_hover_text(cnt); + if title != full { + ui.interact(title_rect, ui.scope_id().with("grid-title"), Sense::hover()).on_hover_text(full); + } + hr +} + /// The header of a Local folder view: the path as a breadcrumb (each part opens that folder), /// Include subfolders, Add to My Photos. fn folder_header(app: &mut LightcraftApp, ui: &mut egui::Ui, b: &lightcraft_engine::Browse, ids: &[PhotoId], local_n: usize, cnt: &str) -> Rect { diff --git a/crates/ui-egui/src/panels/grid/header_tests.rs b/crates/ui-egui/src/panels/grid/header_tests.rs index 463991625e..db5cd37ffe 100644 --- a/crates/ui-egui/src/panels/grid/header_tests.rs +++ b/crates/ui-egui/src/panels/grid/header_tests.rs @@ -17,6 +17,122 @@ fn breadcrumbs_open_their_folder_as_spelled() { assert!(to("").is_empty() && to("/").is_empty() && to(r"\\").is_empty()); } +/// Issue #3776: one selected photo is counted in the header as two or more are ("1 selected · 3 +/// photos"); with nothing selected the header shows the photo count alone. +#[test] +fn the_header_counts_a_single_selected_photo() { + use lightcraft_catalog::{Op, Photo, Source}; + for (selected, folder) in [(0, false), (1, false), (2, false), (0, true), (1, true)] { + let mut session = lightcraft_engine::Session::new(); + for i in 0..3 { + let id = session.catalog.alloc_photo_id(); + let p = Photo::new(id, Source::File { path: format!("/pics/{i}.jpg") }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00"); + session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + session.selection.ids = session.catalog.photos().take(selected).map(|p| p.id).collect(); + if folder { + // a Local folder view: the same count, in the breadcrumb header + session.source = lightcraft_engine::LibrarySource::Folder; + session.browse = Some(lightcraft_engine::Browse { path: "/pics".into(), subfolders: false }); + } + let mut app = LightcraftApp::new(session, Services { png: None, ..Default::default() }); + app.ui.view = crate::state::ViewMode::PhotoGrid; + let mut h = crate::headless::Headless::new(app, [1400.0, 900.0], 1.0); + h.step(); + h.step(); + assert_eq!(h.app.session.selection.ids.len(), selected, "the selection is kept"); + let has = |id: &str| h.app.widgets.iter().any(|(w, _)| w == id); + assert!(has("grid:count") && has("grid:folderHeader") == folder, "folder {folder}: {:?}", h.app.widgets); + let painted = h.painted_text(); + let photos = crate::panels::chips::count_text(h.app.session.visible_cloned().len(), h.app.session.source_total(), false); + assert!(folder || photos == "3 photos", "{photos}"); + let expected = if selected == 0 { photos } else { format!("{selected} selected · {photos}") }; + assert!(painted.contains(&expected), "folder {folder}, {selected} selected: the header shows {expected:?}: {painted:?}"); + if selected == 0 { + assert!(!painted.iter().any(|s| s.contains("selected ·")), "nothing selected, no count: {painted:?}"); + } + } + // a language whose word for "selected" agrees with the number reads "noun: number", right for one as for many + for (locale, expected) in [(Locale::Es, "Seleccionadas: 1 · x"), (Locale::PtBr, "Selecionadas: 1 · x"), (Locale::Sv, "Markerade: 1 · x")] { + crate::i18n::set_language(locale); + let one = crate::i18n::tr_format!("{sel_n} selected · {counted}", sel_n = 1, counted = "x"); + crate::i18n::set_language(Locale::En); + assert_eq!(one, expected, "{locale:?}"); + } +} + +/// Every text the frame painted as it reads on screen (a cut one with its "…"), with where it was painted. +fn texts_painted(shape: &egui::Shape, out: &mut Vec<(String, Rect)>) { + match shape { + egui::Shape::Text(text) => { + let shown = text.galley.rows.iter().flat_map(|row| row.glyphs.iter().map(|g| g.chr)).collect(); + out.push((shown, text.visual_bounding_rect())); + } + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| texts_painted(s, out)), + _ => {} + } +} + +/// A library view's count too long for a narrow centre pane (German, at the narrowest the photo +/// area gets) is cut to stay inside the header, beside the title, and reads in full on hover. +#[test] +fn a_long_library_count_stays_inside_a_narrow_header() { + for width in [crate::state::MIN_PHOTO_WIDTH, 590.0] { + for scale in [1.0, 2.0] { + let app = LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()); + let ctx = egui::Context::default(); + crate::i18n::set_language(Locale::De); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx); + let counted = crate::i18n::tr_format!("{matching} of {t} photos", matching = 123_456_789, t = 987_654_321); + let cnt = crate::i18n::tr_format!("{sel_n} selected · {counted}", sel_n = 123_456_789, counted = counted); + let frame = |time: f64, events: Vec| { + let mut header = Rect::NOTHING; + let raw = HeadlessView::raw_input(vec2(width, 300.0), scale, time, events); + let mut out = ctx.run_ui(raw, |ui| { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| { + header = super::library_header(&app, ui, &cnt); + }); + }); + out.textures_delta.clear(); + let mut texts = Vec::new(); + for shape in &out.shapes { + texts_painted(&shape.shape, &mut texts); + } + (texts, crate::widgets::take_registry(&ctx), header) + }; + let (mut texts, mut widgets, mut header) = (Vec::new(), Vec::new(), Rect::NOTHING); + for f in 0..3 { + (texts, widgets, header) = frame(f as f64 / 60.0, vec![]); + } + let widget = |id: &str| widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r); + let (Some(count), Some(title)) = (widget("grid:count"), widget("grid:title")) else { panic!("no count or title: {widgets:?}") }; + let at = format!("{width} {scale}"); + assert!(header.left() >= 0.0 && header.right() <= width, "{at}: header must not expand past the centre pane: {header:?}"); + assert!(header.contains_rect(count), "{at}: the count stays inside the header: {count:?} in {header:?}"); + assert!(title.right() <= count.left(), "{at}: the title stays left of the count: {title:?} {count:?}"); + for (i, (text, a)) in texts.iter().enumerate() { + assert!(header.expand(1.0).contains_rect(*a), "{at}: {text:?} painted outside the header: {a:?}"); + for (other, b) in texts.iter().skip(i + 1) { + assert!(!a.intersects(*b), "{at}: {text:?} overlaps {other:?}"); + } + } + // cut where it doesn't fit, and in full on hover + let fits = width > 500.0; + assert_eq!(texts.iter().any(|(t, _)| *t == cnt), fits, "{at}: {texts:?}"); + let cut = cnt.split(" von ").next().unwrap_or_default(); + assert!(fits || texts.iter().any(|(t, _)| t.ends_with('…') && t.starts_with(cut)), "{at}: the count is cut at its end: {texts:?}"); + let mut shown = Vec::new(); + for f in 3..120 { + let events = if f == 3 { vec![egui::Event::PointerMoved(count.center())] } else { vec![] }; + (shown, _, _) = frame(f as f64 / 60.0, events); + } + assert!(shown.iter().any(|(t, _)| *t == cnt), "{at}: the full count shows on hover: {shown:?}"); + crate::i18n::set_language(Locale::En); + } + } +} + fn text_bounds(shape: &egui::Shape, out: &mut Vec) { match shape { egui::Shape::Text(text) => out.push(text.visual_bounding_rect()), diff --git a/crates/ui-egui/src/panels/masking.rs b/crates/ui-egui/src/panels/masking.rs index ce28482c46..d833fbeb11 100644 --- a/crates/ui-egui/src/panels/masking.rs +++ b/crates/ui-egui/src/panels/masking.rs @@ -35,6 +35,7 @@ pub const LOCAL: &[ControlSpec] = &[ spec("noise", "Noise", -100.0, 100.0, 1.0, 0, Track::Centered), spec("moire", "Moiré", -100.0, 100.0, 1.0, 0, Track::Centered), spec("defringe", "Defringe", -100.0, 100.0, 1.0, 0, Track::Centered), + spec("lens_blur", "Lens Blur", 0.0, 100.0, 1.0, 0, Track::Plain), ]; pub fn local_get(a: &LocalAdjustments, key: &str) -> f64 { @@ -383,7 +384,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { } divider(ui); super::mask_effects::effect_row(app, ui, &m); - for s in LOCAL { + // (Lens Blur has its own block below) + for s in LOCAL.iter().filter(|s| s.id != "lens_blur") { let v = local_get(&m.adjust, s.id); let out = slider(ui, s, v, true, None); apply_slider_out(app, s, out, |app, v| app.run("mask.adjust", json!({"values": {s.id: v}}))); @@ -414,10 +416,63 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { }; let out = slider(ui, &refine, m.refine, true, None); apply_slider_out(app, &refine, out, |app, v| app.run("mask.refine", json!({"value": v}))); + divider(ui); + lens_blur_block(app, ui, &m); ui.add_space(30.0); let _ = Stroke::NONE; } +/// The mask's Lens Blur block (`section:maskLensBlur`): a header that folds it and whose eye +/// switches it off (the values kept), which side of the mask it blurs (`button:maskLensBlurSide-*`), +/// then its Amount, Boost and Transition (`lens_blur*` local adjustments, `mask.adjust`). +fn lens_blur_block(app: &mut LightcraftApp, ui: &mut egui::Ui, m: &lightcraft_develop::Mask) { + let a = &m.adjust; + let open = !app.ui.section_folded("maskLensBlur"); + let (resp, toggled) = crate::widgets::section_header(ui, "maskLensBlur", "Lens Blur", open, Some(!a.lens_blur_off)); + if let Some(on) = toggled { + // switched on with nothing to blur: a visible amount, as the Edit section's Apply does + let mut v = json!({"lens_blur_off": !on}); + if on && a.lens_blur <= 0.0 { + v["lens_blur"] = json!(50.0); + } + let _ = app.run("mask.adjust", json!({"values": v})); + } else if resp.clicked() { + app.ui.toggle_folded("maskLensBlur"); + } + if !open { + return; + } + ui.add_enabled_ui(!a.lens_blur_off, |ui| { + egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 0, bottom: 6 }).show(ui, |ui| { + let t = Tokens::get(ui.ctx()); + ui.label(egui::RichText::new(crate::i18n::tr("Blur")).color(t.text_dim).size(11.5)); + let items = [("Selection", "inside"), ("Outside", "outside")]; + let side = if a.lens_blur_outside { 1 } else { 0 }; + if let Some(i) = crate::widgets::segmented(ui, "maskLensBlurSide", &items, Some(side), 2) + && i != side + { + let mut v = json!({"lens_blur_outside": i == 1}); + if a.lens_blur <= 0.0 { + v["lens_blur"] = json!(50.0); + } + let _ = app.run("mask.adjust", json!({"values": v})); + } + }); + for s in LENS_BLUR { + let v = local_get(a, s.id); + let out = slider(ui, s, v, true, None); + apply_slider_out(app, s, out, |app, v| app.run("mask.adjust", json!({"values": {s.id: v}}))); + } + }); +} + +/// The sliders of a mask's Lens Blur block (key = `LocalAdjustments` field name). +const LENS_BLUR: &[ControlSpec] = &[ + spec("lens_blur", "Amount", 0.0, 100.0, 1.0, 0, Track::Plain), + spec("lens_blur_boost", "Boost", 0.0, 100.0, 1.0, 0, Track::Plain), + spec("lens_blur_transition", "Transition", 0.0, 100.0, 1.0, 0, Track::Plain), +]; + /// Translate fixed action labels, but never mutate or translate user-entered mask names. fn menu_label(source: &str) -> &str { crate::i18n::tr(source) diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 37a8c2d4bb..203ede571e 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -246,7 +246,8 @@ pub struct UiState { /// the photo that applies to: not an edit, and forgotten on moving to another photo or quitting. #[serde(skip)] pub grading_hidden: Option<(lightcraft_catalog::PhotoId, [bool; 3])>, - /// Active on-canvas tool: "", "brush", "linear", "radial", "wbPicker", "straighten", "remove". + /// Active on-canvas tool: "", "brush", "linear", "radial", "wbPicker", "straighten", "remove", + /// "lensBlurFocus" / "lensBlurBlur" (Lens Blur Brush Refinement, in the Edit panel). pub tool: String, /// Guided Upright: the selected guide (photo id + index) while the tool is open. A Delete / /// Backspace on it removes that guide alone; a click away or leaving the tool clears it. @@ -260,6 +261,9 @@ pub struct UiState { pub brush_auto_mask: bool, /// Brush Pen Pressure: a pen's pressure scales each dab's size and flow (a mouse paints at full pressure). pub brush_pressure: bool, + /// Lens Blur Brush Refinement: how far a stroke refines the focus, 1..100 (size, feather, + /// flow, Auto Mask and pressure are the brush's above). + pub lens_blur_brush_amount: f32, /// Remove tool brush: size (fraction of the long edge), feather and opacity (0..100). pub remove_size: f32, pub remove_feather: f32, @@ -484,6 +488,7 @@ impl Default for UiState { brush_erase: false, brush_auto_mask: false, brush_pressure: true, + lens_blur_brush_amount: 100.0, remove_size: 0.02, remove_feather: 50.0, remove_opacity: 100.0, diff --git a/crates/ui-egui/src/tests/compare.rs b/crates/ui-egui/src/tests/compare.rs index 4ce0341fb1..ee86f5322f 100644 --- a/crates/ui-egui/src/tests/compare.rs +++ b/crates/ui-egui/src/tests/compare.rs @@ -485,6 +485,110 @@ fn survey_command_click_takes_the_photo_out() { assert_eq!((sel(&h), active(&h)), (vec![a], Some(a)), "the last photo stays in the survey"); } +/// A photo taken out of the survey leaves the others to glide to their new cells, so it shows +/// which photo went where: a frame later a tile is between its old and new place, then it lands. +#[test] +fn survey_tiles_glide_to_their_new_cells() { + let mut h = demo(); + let [a, _, c] = survey_of_three(&mut h); + let tile = |h: &Headless| h.app.widgets.iter().find(|(w, _)| *w == format!("cull:{c}")).map(|(_, r)| *r).expect("the tile is laid out"); + let before = tile(&h); + h.app.run("library.select", json!({"ids": [a], "mode": "toggle"})).unwrap(); + h.step(); + h.step(); + let moving = tile(&h); + assert!(h.app.survey_motion.moving(h.time()), "the tiles are on their way"); + h.settle(SETTLE); + let after = tile(&h); + assert!(!h.app.survey_motion.moving(h.time())); + assert_ne!(before, after, "the photo has a new cell"); + assert!(moving != before && moving != after, "between {before:?} and {after:?}: {moving:?}"); +} + +/// A photo that joins the survey makes room: the tiles already there glide to their new cells too. +#[test] +fn survey_tiles_glide_when_a_photo_joins() { + let mut h = demo(); + let ids = survey_of_three(&mut h); + let joining = h.app.session.visible_cloned().iter().map(|p| p.0).find(|p| !ids.contains(p)).expect("a fourth photo"); + let tile = |h: &Headless, id: u64| h.app.widgets.iter().find(|(w, _)| *w == format!("cull:{id}")).map(|(_, r)| *r).expect("the tile is laid out"); + let before = ids.map(|id| tile(&h, id)); + h.app.run("library.select", json!({"ids": [joining], "mode": "toggle"})).unwrap(); + h.step(); + h.step(); + let moving = ids.map(|id| tile(&h, id)); + assert!(h.app.survey_motion.moving(h.time()), "the tiles are on their way"); + h.settle(SETTLE); + let after = ids.map(|id| tile(&h, id)); + let moved: Vec = (0..3).filter(|&i| before[i] != after[i]).collect(); + assert!(!moved.is_empty(), "a photo joining changes the grid: {before:?} → {after:?}"); + for i in moved { + assert!(moving[i] != before[i] && moving[i] != after[i], "tile {i} between {:?} and {:?}: {:?}", before[i], after[i], moving[i]); + } +} + +/// A photo that joins takes its cell at once, so it asks for its own render while the others are +/// still gliding (it doesn't wait on the thumbnail until they land). +#[test] +fn a_photo_that_joins_renders_while_the_others_glide() { + let mut h = demo(); + let ids = survey_of_three(&mut h); + let joining = h.app.session.visible_cloned().into_iter().find(|p| !ids.contains(&p.0)).expect("a fourth photo"); + h.app.run("library.select", json!({"ids": [joining.0], "mode": "toggle"})).unwrap(); + h.step(); + h.step(); + let now = h.time(); + assert!(h.app.survey_motion.moving(now), "the others are on their way"); + assert!(!h.app.survey_motion.gliding(joining, now), "the photo that joined stays put"); + let slot = h.app.survey_motion.slot(joining).expect("the photo that joined has a slot"); + assert!(h.app.renderer.wanted(crate::render::Slot::Compare(slot)).is_some(), "its render is asked for"); +} + +/// Photo ids are local to a library: opening another one forgets the survey's tiles, so a photo +/// there with the same id doesn't glide from a cell of the library left. +#[test] +fn opening_another_library_forgets_the_survey_tiles() { + let dir = std::env::temp_dir().join(format!("lc-ui-survey-switch-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut h = demo(); + let ids = survey_of_three(&mut h); + let tracked = |h: &Headless| ids.iter().filter(|id| h.app.survey_motion.tracks(lightcraft_catalog::PhotoId(**id))).count(); + assert_eq!(tracked(&h), 3); + let r = h.app.run("app.openLibrary", json!({"path": dir.join("second").to_string_lossy()})); + assert!(r.is_ok(), "{r:?}"); + assert_eq!(tracked(&h), 0, "nothing of the library left is remembered"); + drop(h); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Every surveyed photo gets its own render, and keeps it when another photo leaves the survey +/// (each photo keeps its render slot, so the tiles that move don't fall back to thumbnails). +#[test] +fn survey_tiles_keep_their_renders_when_a_photo_leaves() { + let mut h = demo(); + let [a, b, c] = survey_of_three(&mut h); + let rendered = |h: &Headless, ids: &[u64]| { + ids.iter().all(|id| h.app.renderer.textures.iter().any(|(s, t)| matches!(s, crate::render::Slot::Compare(_)) && t.photo.0 == *id)) + }; + assert!(h.step_until(SETTLE, |h| rendered(h, &[a, b, c])), "each tile shows its render"); + let slot_of = |h: &Headless, id: u64| { + h.app.renderer.textures.iter().find(|(s, t)| matches!(s, crate::render::Slot::Compare(_)) && t.photo.0 == id).map(|(s, _)| *s) + }; + let c_slot = slot_of(&h, c).expect("c is rendered"); + let c_tex = h.app.renderer.textures.get(&c_slot).map(|t| t.tex.id()).expect("c's texture"); + h.app.run("library.select", json!({"ids": [a], "mode": "toggle"})).unwrap(); + h.step(); + h.step(); + assert!(h.app.survey_motion.moving(h.time())); + let drawn = h.view.painted_shapes().iter().any(|s| match s { + egui::epaint::Shape::Rect(r) => r.fill_texture_id() == c_tex, + egui::epaint::Shape::Mesh(m) => m.texture_id == c_tex, + _ => false, + }); + assert!(drawn, "c's render is drawn while it moves, not its thumbnail"); + assert!(h.step_until(SETTLE, |h| rendered(h, &[b, c]))); +} + /// Hover photo `id`'s survey tile, as a person does, so its × appears; then click the × in its corner. fn click_x(h: &mut Headless, id: u64) { let name = format!("cull:{id}"); diff --git a/crates/ui-egui/src/tests/masking.rs b/crates/ui-egui/src/tests/masking.rs index f7fbc60536..6bf491c37d 100644 --- a/crates/ui-egui/src/tests/masking.rs +++ b/crates/ui-egui/src/tests/masking.rs @@ -2155,3 +2155,157 @@ fn effect_dropdown_applies_saves_and_shows_the_matching_effect() { assert_eq!((a.exposure, a.shadows, a.clarity, a.amount), (0.7, 25.0, 0.0, 50.0)); assert_eq!(exec(&mut h, "mask.effects", json!({}))["current"], "Lift"); } + +/// Lens Blur Brush Refinement: Focus / Blur pick a brush that paints on the photo from the Edit +/// panel (one `lensBlur.brushStroke` per drag, with the brush's settings); ⌥ erases; Reset clears. +#[test] +fn lens_blur_focus_and_blur_brushes_paint_on_the_photo() { + // (`panel.edit` toggles the panel, which a session opens on: set it instead) + let mut h = detail("panel.masking"); + // tall enough for the Lens Blur section under the closed sections + assert_eq!(h.request("ui.resize", json!({"width": 1200, "height": 1400}), T)["ok"], true); + let r = h.request("ui.set", json!({"right": "edit", "openSections": ["lensBlur"], "histogram": false}), T); + assert_eq!(r["ok"], true, "{r}"); + // off: the brushes don't paint + click(&mut h, "button:lensBlurFocus"); + assert_eq!(h.app.ui.tool, "", "no brush while the blur is off"); + click(&mut h, "check:lensBlur.enabled"); + assert!(develop(&h).lens_blur.enabled); + click(&mut h, "button:lensBlurFocus"); + assert_eq!(h.app.ui.tool, "lensBlurFocus"); + h.app.ui.lens_blur_brush_amount = 60.0; + pointer( + &mut h, + json!([{"kind": "down", "x": 0.3, "y": 0.5}, {"kind": "drag", "x": 0.4, "y": 0.5}, {"kind": "drag", "x": 0.5, "y": 0.5}, {"kind": "up", "x": 0.5, "y": 0.5}]), + ); + let b = develop(&h).lens_blur; + assert_eq!(b.focus_strokes.len(), 1, "{b:?}"); + assert!(b.focus_strokes[0].points.len() >= 2 && b.focus_strokes[0].density == 60.0 && b.blur_strokes.is_empty()); + assert!((b.focus_strokes[0].size - h.app.ui.brush_size as f64).abs() < 1e-6, "the shared brush's size"); + click(&mut h, "button:lensBlurBlur"); + assert_eq!(h.app.ui.tool, "lensBlurBlur"); + brush_at(&mut h, 0.6, 0.4); + let r = h.request("ui.pointer", json!({"events": [{"kind": "down", "x": 0.7, "y": 0.4}, {"kind": "up", "x": 0.7, "y": 0.4}], "alt": true}), T); + assert_eq!(r["ok"], true, "{r}"); + let b = develop(&h).lens_blur; + assert_eq!(b.blur_strokes.len(), 2); + assert!(!b.blur_strokes[0].erase && b.blur_strokes[1].erase, "⌥ erases"); + click(&mut h, "button:lensBlurBrushReset"); + let b = develop(&h).lens_blur; + assert!(b.focus_strokes.is_empty() && b.blur_strokes.is_empty()); + // switching the blur off puts the brush down + click(&mut h, "check:lensBlur.enabled"); + assert_eq!(h.app.ui.tool, ""); + h.settle(SETTLE); +} + +/// Lens Blur focus shape: without a focus mask a button per shape sets it; with one they're gone. +#[test] +fn lens_blur_shape_buttons_pick_the_focus_shape() { + use lightcraft_develop::FocusShape; + let mut h = detail("panel.masking"); + assert_eq!(h.request("ui.resize", json!({"width": 1200, "height": 1400}), T)["ok"], true); + let r = h.request("ui.set", json!({"right": "edit", "openSections": ["lensBlur"], "histogram": false}), T); + assert_eq!(r["ok"], true, "{r}"); + click(&mut h, "check:lensBlur.enabled"); + assert_eq!(develop(&h).lens_blur.shape, FocusShape::Auto); + click(&mut h, "lensBlurShape:wide"); + assert_eq!(develop(&h).lens_blur.shape, FocusShape::Wide); + click(&mut h, "lensBlurShape:tall"); + assert_eq!(develop(&h).lens_blur.shape, FocusShape::Tall); + click(&mut h, "lensBlurShape:auto"); + assert_eq!(develop(&h).lens_blur.shape, FocusShape::Auto); + // a focus mask: the shape is the mask's, no buttons + exec(&mut h, "mask.add", json!({"kind": "radial"})); + let id = develop(&h).masks[0].id; + exec(&mut h, "develop.merge", json!({"settings": {"lens_blur": {"focus_mask": id}}})); + let r = h.request("ui.set", json!({"right": "edit"}), T); + assert_eq!(r["ok"], true, "{r}"); + let r = h.request("ui.clickWidget", json!({"id": "lensBlurShape:round"}), T); + assert_eq!(r["ok"], false, "no shape buttons with a focus mask: {r}"); + h.settle(SETTLE); +} + +/// While Apply is off the focus controls don't respond; on, Move & Resize drags the fixed shape on +/// the photo (one undo step per drag) and a shape button puts it back in the middle. +#[test] +fn lens_blur_focus_controls_follow_apply_and_the_shape_moves() { + use lightcraft_develop::FocusShape; + let mut h = detail("panel.masking"); + assert_eq!(h.request("ui.resize", json!({"width": 1200, "height": 1400}), T)["ok"], true); + let r = h.request("ui.set", json!({"right": "edit", "openSections": ["lensBlur"], "histogram": false}), T); + assert_eq!(r["ok"], true, "{r}"); + // off: shape buttons, Find Subject and In Focus are inert + let before = develop(&h).lens_blur; + click(&mut h, "lensBlurShape:wide"); + click(&mut h, "button:lensBlurFindSubject"); + click(&mut h, "dropdown:lensBlurFocus"); + let r = h.request("ui.clickWidget", json!({"id": "lensBlurFocus:subject"}), T); + assert_eq!(r["ok"], false, "the In Focus menu doesn't open: {r}"); + assert_eq!(develop(&h).lens_blur, before, "nothing changes while Apply is off"); + // on: a round shape, then Move & Resize + click(&mut h, "check:lensBlur.enabled"); + click(&mut h, "lensBlurShape:round"); + assert_eq!(develop(&h).lens_blur.shape, FocusShape::Round); + click(&mut h, "button:lensBlurEditShape"); + assert_eq!(h.app.ui.tool, "lensBlurShape"); + // drag the middle of the photo (the shape's centre) to the right + pointer( + &mut h, + json!([{"kind": "down", "x": 0.5, "y": 0.5}, {"kind": "drag", "x": 0.55, "y": 0.5}, {"kind": "drag", "x": 0.6, "y": 0.5}, {"kind": "up", "x": 0.6, "y": 0.5}]), + ); + let a = develop(&h).lens_blur.area.expect("moved"); + assert!(a.center.x > 0.57 && (a.center.y - 0.5).abs() < 0.02, "{a:?}"); + assert!((a.rx - 0.22).abs() < 1e-9 && (a.ry - 0.22).abs() < 1e-9, "same size"); + // one drag, one undo step + exec(&mut h, "edit.undo", json!({})); + assert!(develop(&h).lens_blur.area.is_none(), "{:?}", develop(&h).lens_blur.area); + exec(&mut h, "edit.redo", json!({})); + assert!(develop(&h).lens_blur.area.is_some()); + // the preset button puts it back in the middle + click(&mut h, "lensBlurShape:round"); + assert!(develop(&h).lens_blur.area.is_none()); + // switching the blur off puts the tool down + click(&mut h, "check:lensBlur.enabled"); + assert_eq!(h.app.ui.tool, ""); + h.settle(SETTLE); +} + +/// A mask's Lens Blur is a block of its own under the mask's sliders: which side it blurs, its +/// sliders, an eye that switches it off (its controls then inert) and a header that folds it. +#[test] +fn a_masks_lens_blur_block_picks_the_side_and_switches_off() { + let mut h = detail("panel.masking"); + assert_eq!(h.request("ui.resize", json!({"width": 1200, "height": 3200}), T)["ok"], true); + exec(&mut h, "mask.add", json!({"kind": "linear", "start": [0.5, 0.2], "end": [0.5, 0.7]})); + h.settle(SETTLE); + let adjust = |h: &Headless| develop(h).masks[0].adjust; + // the block's own sliders, not one more in the list + assert!(h.app.widgets.iter().any(|(id, _)| id == "section:maskLensBlur")); + assert!(h.app.widgets.iter().any(|(id, _)| id == "slider:lens_blur_transition")); + // blurring the outside starts with a visible amount + click(&mut h, "button:maskLensBlurSide-outside"); + let a = adjust(&h); + assert!(a.lens_blur_outside && a.lens_blur == 50.0, "{a:?}"); + let r = h.request("ui.clickWidget", json!({"id": "slider:lens_blur_boost", "fx": 0.6}), T); + assert_eq!(r["ok"], true, "{r}"); + assert!(adjust(&h).lens_blur_boost > 30.0, "{:?}", adjust(&h)); + // the eye (shown over the header) switches it off and keeps the values + h.request("ui.hoverWidget", json!({"id": "section:maskLensBlur"}), T); + h.settle(SETTLE); + click(&mut h, "sectionEye:maskLensBlur"); + let off = adjust(&h); + assert!(off.lens_blur_off && off.lens_blur == 50.0 && off.lens_blur_outside, "{off:?}"); + // off: its controls don't respond + click(&mut h, "button:maskLensBlurSide-inside"); + assert_eq!(adjust(&h), off); + // on again + click(&mut h, "sectionEye:maskLensBlur"); + assert!(!adjust(&h).lens_blur_off); + // the header folds it + click(&mut h, "section:maskLensBlur"); + assert!(h.app.ui.section_folded("maskLensBlur")); + click(&mut h, "section:maskLensBlur"); + assert!(!h.app.ui.section_folded("maskLensBlur")); + h.settle(SETTLE); +} diff --git a/docs/ai-masks.md b/docs/ai-masks.md index 41873cb5a6..c24ea64cb3 100644 --- a/docs/ai-masks.md +++ b/docs/ai-masks.md @@ -6,8 +6,13 @@ through Metal on macOS, on the CPU elsewhere (for now). If the Mac's GPU can't r the CPU (see the worker below). **The model is optional.** It is not part of LightCraft, and nothing requires it: without it, -Object and Describe offer to download it, every other feature (and every existing mask, see -below) works, and no render, export or command ever waits for it. +Object, Describe and Lens Blur's **Find Subject** offer to download it, every other feature (and +every existing mask, see below) works, and no render, export or command ever waits for it. + +Lens Blur reuses this same optional SAM 3 model for **Find Subject**; it does not add or download a +separate model. The automatic subject estimate used before Find Subject finishes (or when **Auto** +is selected) uses existing person mattes when available, otherwise a local saliency heuristic, so +that fallback does not require SAM 3. ## Using them @@ -74,7 +79,9 @@ ssh -N -T -o ExitOnForwardFailure=yes -L 127.0.0.1:8793:127.0.0.1:8793 user@your LIGHTCRAFT_SAM3_REMOTE=127.0.0.1:8793 lightcraft ``` -Object clicks, Describe prompts, and detail refinement use the remote worker. Only the +Object clicks, Describe prompts, detail refinement and Lens Blur's Find Subject (people and animals, +from the camera's focus point when the file records it) use the remote worker; a worker older than the +app rejects a request it doesn't know with an error, so update both together. Only the rendered model input (long edge at most 1008 pixels) and prompts cross the tunnel. The worker caches the current photo; detail crops do not replace that cache. Returned masks stay in the local library, so later adjustments and exports work without the connection. @@ -96,9 +103,9 @@ not RAW development, denoising, or upscaling. The model licence below still appl ### In the app (recommended) -The first time you pick Object or Describe without the model, LightCraft asks: +The first time you pick Object, Describe or Lens Blur's Find Subject without the model, LightCraft asks: -> **Download the SAM 3 model?** Object and Describe masks use SAM 3, Meta's segmentation model. +> **Download the SAM 3 model?** Object, Describe and Lens Blur's Find Subject use SAM 3, Meta's segmentation model. > It isn't part of LightCraft, and everything else works without it. Download it once (about > 3.4 GB) · *folder*. Licence: SAM License (Meta) — Meta's terms, not LightCraft's. Downloading > it means accepting them. [Read the SAM License] — **Not Now** / **Download** diff --git a/docs/contributors.md b/docs/contributors.md index faf47dc716..e8b23d02f2 100644 --- a/docs/contributors.md +++ b/docs/contributors.md @@ -8,7 +8,8 @@ the AI models named in `Co-Authored-By` trailers. - Two files, both **compiled into the binary** by the UI crate's `build.rs` (nothing is read from disk or the network at run time; the web build has them too): - [`contributors/contributors.json`](../contributors/contributors.json): commit stats per GitHub - username. + username. Release builds regenerate it for the release commit + (`.github/workflows/release.yml`, `credits` job); the copy in the repository is not updated. - [`contributors/people.toml`](../contributors/people.toml): the names people chose for themselves. **Each contributor adds only their own entry**, in their own PR. - Each contributor gets one line: GitHub username (always), display name (opt-in, or their synced diff --git a/docs/gaps.md b/docs/gaps.md index 08cebce09d..72ff6d72f8 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -20,14 +20,14 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 3 B | **Render fidelity partial** (LR-BEHAV-RENDER-FIDELITY): calibrated camera-look Contrast and Blacks; other operators need measurement; from process V5 raw tone curves roll off into white in stops, so Exposure keeps recorded highlights (#1632) | process V3 reduces held-out response error from 0.136 to 0.038 stops for Contrast and 0.424 to 0.077 for Blacks on one Sony camera; Whites remains V2 pending a follow-up | imported Lightroom edits still differ, especially on uncalibrated operators and cameras | 30–60 | [calibrated Light operators](light-v3.md), [process versions](process-versions.md) | | 4 | ~~Original-pixel detail at 100%~~ (LR-VIEW-ZOOM): closed 2026-10-12, see Closed recently | checklist row ✅ | — | 0 | [ui-parity](ui-parity.md) | | 5 B | **AI masks: Subject, Sky, People, Background, Landscape** are heuristics; Object / Describe run SAM 3 but its download has no mirror configured | `crates/segment`; ai-masks.md; MASK rows 67% | masking is how most Lightroom users edit today | 40–70 + model decision | [target-app-parity](target-app-parity.md#ai) | -| 6 | ~~Compressed ORF~~ (every Olympus / OM body since ~2008): closed 2026-11-04, see Closed recently | checklist row 🟡 (LR-IMP-FORMATS remains 🟡: other raw formats open); bitstream entropy decoder in `crates/raw/src/vendor/orfc.rs`; OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) verified; 58 bodies newly unlocked (preview 187 → 129; 78 total across Olympus and OM) | — | 0 | [orf-compression](orf-compression.md) | +| 6 | **Compressed ORF** (support withdrawn) | #3775 decoder removed pending provenance review; uncompressed support remains | compressed files use embedded JPEG previews when available, not sensor data | pending review | [orf-compression](orf-compression.md) | | 7 | **Nikon High Efficiency NEF** (HE / HE★ on Z 8, Z 9, Z 6III, Z f, Z50II, Z5II when set to HE) | named and preview only (#193); needs a pure-Rust JPEG XS decoder | +1.1 points (only shots taken in HE; lossless works on the same bodies); low gain per hour (~0.04), so not a beta blocker | 20–40 | [raw-parity](raw-parity.md) | | 8 B | **Lens profiles: lensfun only, no picker, no own calibration** (LR-EDIT-OPTICS-PROFILE): the desktop app offers lensfun's database (CC BY-SA 3.0, pinned, never bundled) once on the first launch and downloads it on that click or from Settings, then looks every raw up by its lens ([lens-profiles.md](lens-profiles.md)), but those profiles are not validated against Lightroom, there is no profile picker (in the file / lens database / own calibration) and no calibration wizard; in-file corrections: DNG opcodes, RW2 in-file distortion, Sony ILCE-7RM4A, ILCE-7M3, full-frame ILCE-7CR distortion (Auto only) and ILCE-7RM6 and ILCE-6700 distortion (`docs/sony-ilce7rm6-lens-corrections.md`) and Nikon Z 6II / Z 8 / Z f distortion (`docs/nikon-lens-corrections.md`); tracked in #329 | Adobe ships 3,635 lens profiles; we never use them | distortion / vignetting correction is a default step for many | 40–80 + calibration shots | [raw-parity](raw-parity.md#lens-profiles) | | 9 B | **Tests don't run in CI on macOS, run on Windows only for Windows code, and no CI job runs the GPU equivalence tests**: the CI gate (`ci.yml`, #2667) runs `cargo xtask ci`, which includes `cargo test`, on Linux x64 for every push to `main` and every pull request; its Windows leg (`ci-windows.yml`) runs clippy and the tests of the crates with `cfg(windows)` code (wincolor, catalog, engine, ui-egui, lightcraft) on windows-latest when a pull request or a push to `main` changes that code, and on pull requests labelled `full-ci`; FreeBSD runs `cargo test` nightly, on pushes to `release` and on PRs that change its workflow or `packaging/freebsd/`; the macOS and Windows jobs build packages | `.github/workflows/` (ci, ci-windows, freebsd, packaging-lint, release, sonarcloud, windows-arm64); the gate's runner has Mesa software Vulkan drivers installed, but `Gpu::new` refuses software adapters (`crates/gpu/src/ctx.rs`), so the CPU ↔ GPU equivalence tests skip; the linux-riscv64 release job added in 0.6.0 (#844) runs only `lightcraft-cli --version` under QEMU; #1148 (open, not merged; #2667 names it superseded) has the macOS and Windows test legs and a `LIGHTCRAFT_GPU_ALLOW_SOFTWARE` opt-in that runs the GPU tests on lavapipe, Metal and WARP | a regression that only shows on macOS, on Windows in code outside the Windows leg's paths, or only on a GPU, reaches users; the full `cargo xtask ci` runs only on Linux in CI | 6–12 | [target-app-parity](target-app-parity.md#by-dimension) | | 10 B | **Per-model verification thin, plus cheap per-body decode fixes**: 557 of 1,446 Adobe models verified (39%), ~86% of photographers on a verified body; Nikon 5 bodies verified, Canon 34, Leica 14 (the Q3 by a recorded check of 38 private DNGs). Cheap fixes: Z 6II packed 14-bit NEF (#769, PR #671), Sony A100 regression (#702); F828 SRF now discovered and imported as preview-only, sensor decoding still missing, DSLR-A200…A390 / A850 12-bit ARW (#535) | measured: [raw/coverage.tsv](raw/coverage.tsv) | per-body bugs (levels, crops, WB) surface only from users | 25–45 | [raw-parity](raw-parity.md#by-maker-measured) | | 11 | **Enhance: Raw Details, Super Resolution; trained denoise weights and X-Trans** | ENH rows 0%; denoise Bayer only; the built-in denoiser is classical (block-matching collaborative filtering), RawNIND weights GPL and opt-in | Fujifilm users get no AI denoise; very noisy files gain less than from a trained model | 30–60 + model decision | [raw-parity](raw-parity.md#demosaic-levels-crops-and-lens-metadata) | | 12 | **Content-aware / generative remove, detect distractions, reflections removal** | REM rows 75%; patch synthesis missing | cleanup work goes back to Photoshop | 25–45 (+ generative model) | [target-app-parity](target-app-parity.md#ai) | -| 13 | **Lightroom catalog migration is one-way and approximate**: unsupported Adobe profiles / AI settings archived, history kept as data; main-file pages read on demand up to 16 GiB, with dense-table and WAL bounds retained (#798); offline record counts and destination are now shown in a lasting import result; catalog VIDEO records match the Videos filter, with older classification repaired on reimport; before an import the app asks whether the catalog merges into the open library or goes into a new library (opt-out in Settings, #2672) | lightroom-catalog-import.md | switching users lose some looks | 8–12 | [file-format-parity](file-format-parity.md) | +| 13 | **Lightroom catalog migration is one-way and approximate**: unsupported Adobe profiles / AI settings archived, history kept as data; main-file pages read on demand up to 16 GiB, with dense-table and WAL bounds retained (#798); offline record counts and destination are now shown in a lasting import result; catalog VIDEO records match the Videos filter, with older classification repaired on reimport; before an import the app asks whether the catalog merges into the open library or goes into a new library (opt-out in Settings, #2672); Lightroom's backup zips import directly (#2592) | lightroom-catalog-import.md | switching users lose some looks | 8–12 | [file-format-parity](file-format-parity.md) | | 14 | **HDR display** (EDR / Windows HDR); the headroom limit and SDR rendition from `crs` XMP (the HDR switch, `HDREditMode`, is read). HLG AVIF export done; the display's SDR/HDR decision is tested, blocked on eframe's 8-bit surface | HDR rows 70%; LR-VIEW-HDR-DISPLAY ⬜ | HDR editing works blind on HDR monitors | 12–25 | [hardware-parity](hardware-parity.md) | | 15 | **Print module**: identity plate / watermark / photo info overlays, Cut Guides for the packages, Custom Package Auto Layout, printer-driver Page Setup and direct printing, JPEG file output (the Print dialog writes a colour-managed PDF) | LRC-PRINT rows | Classic users who print | 15–25 | [target-app-parity](target-app-parity.md#features) | | 16 | **Map view, Book, Slideshow module, publish services** | LRC-MAP / BOOK / SS rows ⬜ | Classic users; publish services matter for Flickr / SmugMug workflows | 60–100 | [target-app-parity](target-app-parity.md#features) | @@ -61,8 +61,6 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w ## Closed recently (kept for calibration) -- 2026-11-04: Gap 6 closed: compressed Olympus ORF decodes from sensor data (`crates/raw/src/vendor/orfc.rs`); OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) verified; 58 bodies newly unlocked (78 total across Olympus and OM). - - 2026-10-29: the import review has a remembered 80–320 pt thumbnail-size slider, density-aware previews and bounded visible retention (#2237, part of #2056). Small sources do not reconstruct the same preview job every frame. The pre-import loupe and keyboard culling remain open in #2056; no ranked gap or headline feature count closes. - 2026-10-22: saving XMP preserves foreign namespaces even when they use `lc:` or `xmp:` prefixes; importing them no longer interprets their properties as native settings or ratings. Parser, merge and save-command regressions cover the correction; no ranked gap or readiness estimate changes. @@ -92,7 +90,9 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| -| 2026-11-04 | minor | Gap 6 closed: Compressed ORF decoded (`crates/raw/src/vendor/orfc.rs`), OM-D E-M1 and E-M10 Mark III verified; 58 bodies newly unlocked (78 total across Olympus and OM; OM / Olympus fully working 6% → 81%) | +| 2026-11-01 | minor | Gap 13: Lightroom catalog backup zips import directly, and a backup of an imported catalog adds no collection twice (#2592); the gap stays open | +| 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-04 | minor | Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. See [ORF status](orf-compression.md). | | 2026-11-05 | minor | Gap 3: process V5 rolls a raw's tone curve off into white in stops, so raising Exposure keeps the highlights the sensor recorded (#1632); the gap stays open (no Lightroom comparison) and hours are unchanged | | 2026-10-27 | minor | Gap 26: the loupe shows built previews (they were rendered again), photos ahead and the whole view are prepared in the background with settings per mode; gap not closed | | 2026-10-27 | minor | Gap 26: culling speed measured and improved (progressive Local browse, camera previews made ahead, a CR3's smallest covering JPEG, camera JPEG first at 100 %); what is left listed; gap not closed | @@ -177,7 +177,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-11 | minor | Reviewed against main after 0.6.0: CR3 entry names the CRX variants `crx.rs` still refuses and the R7 / R6 Mark II C-RAW state (decoding, not verified, so the measured numbers don't move); CI and Windows / Linux entries note the riscv64 release build (#844); R7 fix added to Closed recently. Panel docking (UI.9, #869) closes no listed gap | | 2026-10-11 | minor | Camera colour entry: raws with a black-and-white camera JPEG take its tone curve (#577); gap not closed | | 2026-10-11 | minor | Gap 4: Compare and Reference views get zoom windows per pane (1:1 was a 2,560 px render magnified); overlays and soft proofing remain, 8–15 h → 4–8 h | -| 2026-10-10 | minor | Compressed ORF entry links the two Olympus patents that describe the method | +| 2026-10-10 | minor | Compressed ORF patent references were added; these do not establish the provenance of the subsequently withdrawn #3775 decoder | | 2026-10-11 | minor | Gap 14: `crs:HDREditMode` is read from XMP (#663); the headroom limit and SDR rendition still aren't | | 2026-10-11 | minor | Gaps 2 and 10 shrink: EOS R5 Mark II CR3 decodes and is verified (fourth CR3 body, Canon 12 verified, 235 models, ~42% on a verified body); CR3 gain +6.5 → +6.2 points | | 2026-10-10 | minor | RAW gaps re-measured model by model (raw-parity.md): CR3, compressed ORF and verification entries carry measured shares; HE NEF no longer a beta blocker (+1.1 points for 20–40 h); verification entry absorbs the cheap per-body fixes (#769, #702, A200 series) | diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index 0e9816b7bb..2d68b51999 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -310,7 +310,7 @@ real failure still stops the whole process. Such a test asserts on its own rende `crates/gpu/tests/it/equivalence.rs` renders the same settings on both and compares 8-bit sRGB: bounds **mean |Δ| < 0.5 LSB and max |Δ| ≤ 3 LSB** per channel. Measured (Apple M4 Pro, Metal): **max 1 LSB, mean ≤ 0.0003 LSB** for every case — 26 settings cases (all tone/colour/effects tools, -3 vignette styles, grain, curves, grading, B&W, WB, NR, crop/straighten/flip, lens + perspective, +3 vignette styles, grain (value noise and crystal layers), curves, grading, B&W, WB, NR, crop/straighten/flip, lens + perspective, three mask sets incl. CPU-evaluated shapes, spots + defringe), all 8 orientations ± crop, embedded DNG lens data, display-referred sources, draft quality, full-size renders; the 24 MP export in `render_bench` also differs by max 1 LSB. Cached (slider-drag) GPU renders are bit-identical to diff --git a/docs/grain.md b/docs/grain.md new file mode 100644 index 0000000000..5e66405c6f --- /dev/null +++ b/docs/grain.md @@ -0,0 +1,147 @@ +# Film grain + +The Effects panel's Grain (`ctl:grain.amount`, `ctl:grain.size`, `ctl:grain.roughness`; XMP +`crs:GrainAmount`, `crs:GrainSize`, `crs:GrainFrequency`) draws grain from a simulated emulsion of +crystal layers: `crates/pipeline/src/crystal.rs` on the CPU, the same tables read by the GPU +kernel (`crates/gpu/src/wgsl/finish.wgsl`). + +This is the grain of **process V7** and later ([process-versions.md](process-versions.md)). Photos on +V1 to V6 keep the two-octave value noise they were edited with (`finish::ValueGrain`), so opening an +older catalog never changes a photo's grain; Update to Current Process moves a photo to the crystal +grain. The sliders, their ranges and their XMP names are unchanged. + +## Model + +After Aurélien Pierre, [*Stochastic photographic grain synthesis from crystallographic structure +simulation*](https://eng.aurelienpierre.com/2023/07/stochastic-photographic-grain-synthesis-from-crystallographic-structure-simulation/) +(2023). Implemented from the article's description of the method; no code was taken from it or from +any other implementation. + +- **Emulsion.** A stack of layers. Each layer has one crystal shape: a regular polygon of + `round(4.5 + z)` vertices (3–8), a random rotation, and a width (circumscribed diameter) drawn from a + log-normal distribution. The layers' widths are the quantiles of that distribution, dealt out in an + order the seed shuffles, so every seed has the same mix of sizes (the same grain strength and + width) in a different arrangement. +- **Crystals.** Each layer is a Boolean model: Poisson seeds grown into crystals, at the density + `λ = −ln(1 − F)/A` (crystal area `A`) that leaves a fraction `F = ½` of the layer covered. +- **Capture.** A point's grain is the number of layers covering it less the mean: many independent + layers of different crystal sizes add up to dense, soft, cloudy grain with no hard particle edges. +- **Print.** The light a crystal captures is proportional to the light falling on it, and a print + shows less grain towards paper white: the grain is `Y·(1 − Y)·g` in linear light (`Y` the pixel's + luminance), zero at black and at white. It is applied in the display-encoded domain, to first + order: each channel `v` moves by `k·lift(v)·(1 − Y)·g`, where `lift(v) = Y·dv/dY` of the sRGB curve. + In that domain the grain is symmetric, so it neither darkens shadows (the article's model in + linear light does, through the concave encoding) nor greys blown highlights, and it keeps hue. +- **Colour:** monochrome, as in Lightroom Classic. + +## Resolution independence + +The emulsion is drawn in frame coordinates at twice the resolution of a 6000 px export (a tile pixel +is half a reference pixel), on two periodic tiles (tori) of 640 and 567 reference pixels; layers +alternate between them. The tiles are stored as summed-area tables, so each output pixel takes the +**exact mean of the emulsion under its footprint** (16 table reads): a fit-to-window preview shows +the export's grain box-downscaled to its size, and an export larger than 6000 px (a 45 MP camera) +still shows crystals rather than enlarged pixels. The tori share no small factor: the two patterns +only line up again after 362,880 reference pixels, so the grain has no visible period. + +In a rotated frame (a straightened or rotated crop) the footprint is approximated: each pixel takes +the mean over an axis-aligned square of its size centred on it, not over the rotated pixel (summed +area tables only give axis-aligned boxes). The grain strength is the same; the exact match with a +box-downscaled export holds for unrotated frames in any orientation. + +Measured on the comparison renders (four photos, six regions each, 1500 px preview against the +6000 px export box-downscaled to 1500 px): preview / export grain strength **1.00–1.04** at the +default, finest and coarsest settings. `crystal::tests::small_render_is_the_downscaled_reference` +checks it exactly at 1/2, 1/4 and 1/8 size; `tests_grain::small_render_matches_the_downscaled_large_render` +through the whole pipeline. + +## Mapping and calibration + +Amount, Size and Roughness keep Lightroom Classic's meaning: strength and width at mid grey match its +exports (the measurements of open PR #1060, `docs/grain.md` on that branch). + +| Quantity | Value | +|---|---| +| strength (levels of 255 at mid grey, 6000 px) | `Amount/100 · exp(2.447 + 1.386·exp(−Size/19.88)) · (1 − 0.084d + 1.6384d²)`, `d = Roughness/100 − ½`: 8.55 at 50 / 25 / 50 | +| median crystal width (reference px) | by Size: 0.55, 1.39, 2.95, 5.17, 8.78, 12.38 at 0, 10, 25, 50, 75, 100; × 0.734 / 1 / 1.422 at Roughness 0 / 50 / 100 (`fit_widths`) | +| width spread (log std) | `hypot(0.1 + 0.6·Roughness/100, 0.45)` | +| layers | by Size: 16, 31, 54, 70 at 0, 25, 50, 100 | + +- **Amount only scales the strength**: the amplitude is measured from the drawn emulsion itself (its + variance at the reference resolution), so every setting and seed has exactly its target strength, + and dragging Amount draws nothing new. In the article the layer count sets the strength; here it + sets only how dense the texture is (coarser grain averages more layers, so it stays a soft clump + texture). +- **Texture.** The width spread was chosen so the anti-aliased crystals have the texture of the + first, whole-pixel prototype at every scale, not just its width: autocorrelation at 1–5 px and the + strength kept by box downscales of 2–16 match it within a few hundredths + (`texture_report`). +- **Size 0** is as fine as the model gets: crystals narrower than a pixel, uncorrelated pixels + (width 0.51 px; Lightroom Classic's 0.43 needs anti-correlated grain). + +Measured (chart, 6000 px, 8-bit, against the same build without grain): + +| Amount / Size / Roughness | Strength at grey 20 · 128 · 245 | Width | Lightroom Classic at 128 | +|---|---|---|---| +| 25 / 25 / 50 | 1.66 · 4.29 · 1.67 | 1.11 | 4.29, 1.13 | +| 50 / 25 / 50 | 3.27 · 8.57 · 3.30 | 1.12 | 8.55, 1.13 | +| 100 / 25 / 50 | 6.53 · 17.14 · 6.36 | 1.12 | 17.01, 1.14 | +| 50 / 0 / 50 | 8.80 · 23.10 · 8.55 | 0.53 | 23.08, 0.43 | +| 50 / 50 / 50 | 2.46 · 6.42 · 2.43 | 1.70 | — | +| 50 / 100 / 50 | 2.24 · 5.83 · 2.19 | 3.39 | 5.83, 3.38 | +| 50 / 25 / 0 | 4.73 · 12.44 · 4.67 | 0.85 | 12.42, 0.86 | +| 50 / 25 / 100 | 4.46 · 11.75 · 4.37 | 1.53 | 11.68, 1.54 | + +Unlike Lightroom Classic's, the grain fades towards black and white (the print model). Mean +brightness change on 24 photo regions: within ±0.1 level on every dark and mid-tone region at every +setting (#1060: up to +3.8 on dark fabric at 50 / 0 / 50); up to −0.55 on sunlit skin at the +strongest settings, where grain clips at white; blown highlights stay clean (−0.01 on a blown +curtain; #1060: −9.3). Fine detail under the grain is kept (detail gain +0.96–1.00). + +## Performance + +- **Drawing the emulsion** (per Size, Roughness and seed; cached, so Amount drags and re-renders + draw nothing): every crystal is stamped from a per-layer table of its rasterisation at 16 × 16 + sub-pixel phases, as one 64-bit mask per row (a fixed number of rows per layer, those outside a + band landing in scratch rows around it, so a crystal costs no branch per row), layers are counted + in bit-sliced counters, and the tiles are drawn in parallel bands. 7–15 ms on an M2 Max (12 + threads), 15–33 ms on a Ryzen 5 7545U (6 cores, 12 threads; 10–20 % less than before the row + masks) at any setting (`tile_timing_report`). +- **Drags.** A draft render (a slider drag) doesn't wait for a tile it hasn't got if one for the + photo's seed is cached: the last one drawn stands in while the new one is drawn in the background, + on a pool of half the cores so the drag's renders don't queue behind it, and the next render takes + it. With none cached for the seed there is nothing to stand in, so the draft waits for a draw + already running or draws the tile itself. The full-quality render when the drag ends waits for the + exact tile. A Size drag on the Ryzen with its + Radeon 740M (GPU, 2.5 MP preview): 13–14 ms a frame instead of 62–66 ms. (On wasm, without + threads, drafts wait.) +- **Drag benchmark** (`FRAMES=100 cargo run --release -p lightcraft-gpu --example grain_drag_bench`: GPU + draft renders of the 1936 × 1290 demo photo, median ms per frame of 100; the example has no + dependency on this model, so it can be copied unchanged into another branch). Ryzen 5 7545U / + Radeon 740M: + + | Build | No grain (Exposure drag) | Amount drag | Size drag | + |---|---|---|---| + | main (value noise) | 8–12 | 10–13 | 10–13 | + | #1060 (particles) | 8 | 11–14 | 151–179 (17–312) | + | this model | 8–11 | 14–15 | 13 | + + M2 Max (Metal), same benchmark, the medians of three runs: + + | Build | No grain (Exposure drag) | Amount drag | Size drag | + |---|---|---|---| + | main (value noise) | 3.2–3.4 | 2.9–3.0 | 2.9 | + | #1060 (particles) | 3.3 | 3.0–3.1 | 35.6–36.0 | + | this model | 3.2–3.3 | 3.4–3.5 | 5.9–6.0 | + +- **Per pixel:** two box sums, on the CPU and on the GPU. The tables (12 MB) stay on the GPU + between renders, for the last tile used (`Gpu::grain_tables`), and are copied after the finish + kernel's other tables in its `aux` buffer on the GPU: an Amount drag uploads nothing. On the + Radeon 740M an Amount drag frame (2.5 MP) went from 16.9 to 11–15 ms (no grain: 8 ms). +- **24 MP NEF → PNG** (`lightcraft-cli render`, M2 Max, median of three): no grain 1.06 s, grain + 50 / 25 / 50 1.05 s on the GPU; 1.28 s and 1.43 s CPU-only (the finish stage 0.26 → 0.42 s). + Grain costs main ≈ 0 on the GPU and +0.08 s CPU-only, #1060 +0.29 s and +1.71 s. +- **24 MP NEF → PNG on the Ryzen 5 7545U / Radeon 740M** (median of three): no grain 2.07 s, grain + 50 / 25 / 50 2.10 s on the GPU; 2.72 s and 2.88 s CPU-only. Grain costs main +0.03 s on the GPU + and +0.10 s CPU-only, #1060 +1.81 s and +3.54 s. diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index 80169dc859..d2316d17bc 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -42,6 +42,9 @@ being the choice the window opens with) or merges when the setting says so. A ca refused before a new library is made. The engine command `library.importLightroom` always imports into the library open now. +A Lightroom Classic catalog backup is imported the same way, as the `.zip` Lightroom writes +(`Backups/YYYY-MM-DD HHMM/.zip`; see *Catalog backups* below). + Equivalent commands: ```text @@ -164,6 +167,39 @@ photo and its virtual copies out of the library. To import originals on a share, from that share. A path that is not a path on this computer (a Windows drive path read on macOS or Linux) is not looked at either and stays catalogued as missing. +## Catalog backups + +Lightroom Classic backs a catalog up as `/Backups/YYYY-MM-DD HHMM/.zip`: one `.lrcat` (plus, +since Classic 12, a small `.lrcat-data/` folder the import does not need). Someone who has removed Lightroom +and its catalog may have nothing else, so `library.importLightroom` / `library.inspectLightroom` and File ▸ Import +Lightroom Catalog… take the zip directly (issue #2592, `crates/engine/src/lightroom_backup.rs`): + +- The `.lrcat` entry is inflated by streaming (stored or deflated, ZIP64 included) into a private folder, + `Interop/lc-lrbackup--